<commit_before><commit_msg>Add Rust solution for anagram detection<commit_after>use std::collections::HashMap;

// Split up a given string slice into all possible substrings of length n.
// Adapted from http://stackoverflow.com/a/30890221
fn offset_slices(s: &str, n: usize) -> Vec<&str> {
    if s.len() < n {
        return vec![s];
    }
    (0..s.len() - n + 1).map(|i| &s[i..i + n]).collect()
}

// Create a custom trait for hashing our data
trait Hash {
    fn hash(&self) -> u64;
}

// Hashing a character means mapping it to a prime number
impl Hash for char {
    fn hash(&self) -> u64 {
        match *self {
            'a' => 2,
            'b' => 3,
            'c' => 5,
            'd' => 7,
            'e' => 11,
            'f' => 13,
            'g' => 17,
            'h' => 19,
            'i' => 23,
            'j' => 29,
            'k' => 31,
            'l' => 37,
            'm' => 41,
            'n' => 43,
            'o' => 47,
            'p' => 53,
            'q' => 59,
            'r' => 61,
            's' => 67,
            't' => 71,
            'u' => 73,
            'v' => 79,
            'w' => 83,
            'x' => 89,
            'y' => 97,
            'z' => 101,
            'A' => 103,
            'B' => 107,
            'C' => 109,
            'D' => 113,
            'E' => 127,
            'F' => 131,
            'G' => 137,
            'H' => 139,
            'I' => 149,
            'J' => 151,
            'K' => 163,
            'L' => 167,
            'M' => 173,
            'N' => 179,
            'O' => 181,
            'P' => 191,
            'Q' => 193,
            'R' => 197,
            'S' => 199,
            'T' => 211,
            'U' => 223,
            'V' => 227,
            'W' => 229,
            'X' => 233,
            'Y' => 239,
            'Z' => 241,
            _ => panic!("ASCII only"),
        }
    }
}

// The hash of a String is the product of all character hashes
impl Hash for String {
    fn hash(&self) -> u64 {
        self.chars().fold(1, |mult, c| mult * c.hash())
    }
}

fn anagram_detection(parent: &str, child: &str) -> usize {
    let mut matches: Vec<String> = Vec::new();
    let child_hash = String::from(child).hash();

    for slice in offset_slices(parent, child.len()) {
        if String::from(slice).hash() == child_hash {
            matches.push(slice.into())
        }
    }

    return matches.len();
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_offset_slices() {
        assert_eq!(offset_slices("helloworld", 100), vec!["helloworld"]);
        assert_eq!(offset_slices("helloworld", 3),
                   vec!["hel", "ell", "llo", "low", "owo", "wor", "orl", "rld"]);
        assert_eq!(offset_slices("helloworld", 10), vec!["helloworld"]);
        assert_eq!(offset_slices("helloworld", 9),
                   vec!["helloworl", "elloworld"]);
    }

    #[test]
    fn test_anagram_detection() {
        assert_eq!(anagram_detection("AdnBndAndBdaBn", "dAn"), 4);
        assert_eq!(anagram_detection("AbrAcadAbRa", "cAda"), 2);
    }
}

<|endoftext|>


<commit_before><commit_msg>Added a benchmark for insert_or_update_document<commit_after>#![feature(test)]

#[macro_use]
extern crate maplit;
extern crate test;
extern crate kite;
extern crate kite_rocksdb;

use test::Bencher;
use std::fs::remove_dir_all;

use kite::term::Term;
use kite::token::Token;
use kite::schema::{FieldType, FIELD_INDEXED, FIELD_STORED};
use kite::document::{Document, FieldValue};

use kite_rocksdb::RocksDBIndexStore;

#[bench]
fn bench_insert_single_document(b: &mut Bencher) {
    remove_dir_all("test_indices/bench_insert_single_document");

    let mut store = RocksDBIndexStore::create("test_indices/bench_insert_single_document").unwrap();
    store.add_field("title".to_string(), FieldType::Text, FIELD_INDEXED).unwrap();
    store.add_field("body".to_string(), FieldType::Text, FIELD_INDEXED).unwrap();
    store.add_field("id".to_string(), FieldType::I64, FIELD_STORED).unwrap();

    let mut tokens = Vec::new();
    for t in 0..5000 {
        tokens.push(Token {
            term: Term::String(t.to_string()),
            position: t
        });
    }

    let mut i = 0;
    b.iter(|| {
        i += 1;

        store.insert_or_update_document(Document {
            key: i.to_string(),
            indexed_fields: hashmap! {
                "body".to_string() => tokens.clone(),
                "title".to_string() => vec![Token { term: Term::String(i.to_string()), position: 1}],
            },
            stored_fields: hashmap! {
                "id".to_string() => FieldValue::Integer(i),
            },
        });
    });
}
<|endoftext|>


<commit_before><commit_msg>handle commands in their own function<commit_after><|endoftext|>


<commit_before><commit_msg>stat: add main.rs<commit_after>extern crate uu_stat;

fn main() {
    std::process::exit(uu_stat::uumain(std::env::args().collect()));
}
<|endoftext|>


<commit_before><commit_msg>Add another prefix_has_suffix test case.<commit_after><|endoftext|>


<commit_before>// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[deny(missing_docs)]

extern crate gfx;
extern crate gfx_device_gl;
extern crate glutin;

use gfx::tex::Size;

/// A wrapper around the window that implements `Output`.
pub struct Output<R: gfx::Resources> {
    /// Glutin window in the open.
    pub window: glutin::Window,
    frame: gfx::FrameBufferHandle<R>,
    mask: gfx::Mask,
    supports_gamma_convertion: bool,
    gamma: gfx::Gamma,
}

impl<R: gfx::Resources> Output<R> {
    /// Try to set the gamma conversion.
    pub fn set_gamma(&mut self, gamma: gfx::Gamma) -> Result<(), ()> {
        if self.supports_gamma_convertion || gamma == gfx::Gamma::Original {
            self.gamma = gamma;
            Ok(())
        }else {
            Err(())
        }
    }
}

impl<R: gfx::Resources> gfx::Output<R> for Output<R> {
    fn get_handle(&self) -> Option<&gfx::FrameBufferHandle<R>> {
        Some(&self.frame)
    }

    fn get_size(&self) -> (Size, Size) {
        let factor = self.window.hidpi_factor();
        let (w, h) = self.window.get_inner_size().unwrap_or((0, 0));
        ((w as f32 * factor) as Size, (h as f32 * factor) as Size)
    }

    fn get_mask(&self) -> gfx::Mask {
        self.mask
    }

    fn get_gamma(&self) -> gfx::Gamma {
        self.gamma
    }
}

impl<R: gfx::Resources> gfx::Window<R> for Output<R> {
    fn swap_buffers(&mut self) {
        self.window.swap_buffers();
    }
}

/// Result of successful context initialization.
pub type Success = (
    Output<gfx_device_gl::Resources>,
    gfx_device_gl::Device,
    gfx_device_gl::Factory,
);

/// Initialize with a window.
pub fn init(window: glutin::Window) -> Success {
    unsafe { window.make_current() };
    let (device, factory) = gfx_device_gl::create(|s| window.get_proc_address(s));
    let format = window.get_pixel_format();
    let out = Output {
        window: window,
        frame: factory.get_main_frame_buffer(),
        mask: if format.color_bits != 0 { gfx::COLOR } else { gfx::Mask::empty() } |
            if format.depth_bits != 0 { gfx::DEPTH } else  { gfx::Mask::empty() } |
            if format.stencil_bits != 0 { gfx::STENCIL } else { gfx::Mask::empty() },
        supports_gamma_convertion: format.srgb,
        gamma: gfx::Gamma::Original,
    };
    (out, device, factory)
}
<commit_msg>Remove use of removed handle typedefs<commit_after>// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[deny(missing_docs)]

extern crate gfx;
extern crate gfx_device_gl;
extern crate glutin;

use gfx::tex::Size;

/// A wrapper around the window that implements `Output`.
pub struct Output<R: gfx::Resources> {
    /// Glutin window in the open.
    pub window: glutin::Window,
    frame: gfx::handle::FrameBuffer<R>,
    mask: gfx::Mask,
    supports_gamma_convertion: bool,
    gamma: gfx::Gamma,
}

impl<R: gfx::Resources> Output<R> {
    /// Try to set the gamma conversion.
    pub fn set_gamma(&mut self, gamma: gfx::Gamma) -> Result<(), ()> {
        if self.supports_gamma_convertion || gamma == gfx::Gamma::Original {
            self.gamma = gamma;
            Ok(())
        }else {
            Err(())
        }
    }
}

impl<R: gfx::Resources> gfx::Output<R> for Output<R> {
    fn get_handle(&self) -> Option<&gfx::handle::FrameBuffer<R>> {
        Some(&self.frame)
    }

    fn get_size(&self) -> (Size, Size) {
        let factor = self.window.hidpi_factor();
        let (w, h) = self.window.get_inner_size().unwrap_or((0, 0));
        ((w as f32 * factor) as Size, (h as f32 * factor) as Size)
    }

    fn get_mask(&self) -> gfx::Mask {
        self.mask
    }

    fn get_gamma(&self) -> gfx::Gamma {
        self.gamma
    }
}

impl<R: gfx::Resources> gfx::Window<R> for Output<R> {
    fn swap_buffers(&mut self) {
        self.window.swap_buffers();
    }
}

/// Result of successful context initialization.
pub type Success = (
    Output<gfx_device_gl::Resources>,
    gfx_device_gl::Device,
    gfx_device_gl::Factory,
);

/// Initialize with a window.
pub fn init(window: glutin::Window) -> Success {
    unsafe { window.make_current() };
    let (device, factory) = gfx_device_gl::create(|s| window.get_proc_address(s));
    let format = window.get_pixel_format();
    let out = Output {
        window: window,
        frame: factory.get_main_frame_buffer(),
        mask: if format.color_bits != 0 { gfx::COLOR } else { gfx::Mask::empty() } |
            if format.depth_bits != 0 { gfx::DEPTH } else  { gfx::Mask::empty() } |
            if format.stencil_bits != 0 { gfx::STENCIL } else { gfx::Mask::empty() },
        supports_gamma_convertion: format.srgb,
        gamma: gfx::Gamma::Original,
    };
    (out, device, factory)
}
<|endoftext|>


<commit_before><commit_msg>Remove indirection<commit_after><|endoftext|>


<commit_before><commit_msg>rust-rub work<commit_after><|endoftext|>


<commit_before><commit_msg>command refactor<commit_after><|endoftext|>


<commit_before><commit_msg>add test case for issue-61076<commit_after>// edition:2018

async fn foo() -> Result<(), ()> {
    Ok(())
}

async fn bar() -> Result<(), ()> {
    foo()?;
    Ok(())
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>make cargo "example" so we can profile the test code<commit_after>extern crate time_steward;
use time_steward::examples::handshakes;

fn main() {
  handshakes::testfunc();
}
<|endoftext|>


<commit_before><commit_msg>(doc) Added hitcounter example.<commit_after>#![allow(unused_mut)]
// Bug in the compiler with Arc/Mutex references.

extern crate iron;
extern crate http;
extern crate persistent;

use std::io::net::ip::Ipv4Addr;
use persistent::Persistent;
use http::status;
use iron::{Request, Response, Alloy, Iron, ServerT};
use iron::middleware::{Status, Continue};
use iron::mixin::Serve;

pub struct HitCounter;

fn hit_counter(_: &mut Request, _: &mut Response, alloy: &mut Alloy) -> Status {
    // Bug in the compiler
    let mut count = alloy.find::<Persistent<uint, HitCounter>>().unwrap().data.write();
    *count += 1;
    println!("{} hits!", *count);
    Continue
}

fn serve_hits(_: &mut Request, res: &mut Response, alloy: &mut Alloy) {
    let mut count = alloy.find::<Persistent<uint, HitCounter>>().unwrap().data.read();
    let _ = res.serve(status::Ok, format!("{} hits!", *count).as_slice());
}

fn main() {
    let mut server: ServerT = Iron::new();
    let counter: Persistent<uint, HitCounter> = Persistent::new(0u);
    server.link(counter);
    server.link(hit_counter);
    server.link(serve_hits);
    server.listen(Ipv4Addr(127, 0, 0, 1), 3001);
}

<|endoftext|>


<commit_before><commit_msg>First draft of streaming parser combinators.<commit_after>use std::mem;

// Borrowing encoding of paramaterized types from
// https://github.com/rust-lang/rfcs/blob/master/text/0195-associated-items.md#encoding-higher-kinded-types

pub trait RefType<'a> {
    type Ref;
}

pub type Ref<'a,T> where T: RefType<'a> = T::Ref;

#[derive(Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Debug)]
pub enum PushResult<T> {
    WillMatch,
    MightMatch,
    WontMatch,
    MatchedAll,
    MatchedSome(T),
}

pub trait Listener<T> where T: for<'a> RefType<'a> {
    fn push<'a,'b>(&'a mut self, value: Ref<'b,T>) -> PushResult<Ref<'b,T>>;
    fn done(&mut self);
}

pub struct StrRef;

impl<'a> RefType<'a> for StrRef {
    type Ref = &'a str;
}

enum WhitespaceParserState {
    Beginning,
    Middle(String),
    End,
}

struct WhitespaceParser<T> {
    downstream: T,
    state: WhitespaceParserState,
}

impl<T> From<T> for WhitespaceParser<T> {
    fn from(downstream: T) -> WhitespaceParser<T> {
        WhitespaceParser{ downstream: downstream, state: WhitespaceParserState::Beginning }
    }
}

impl<T> Listener<StrRef> for WhitespaceParser<T> where T: Listener<StrRef> {
    fn push<'a,'b>(&'a mut self, string: &'b str) -> PushResult<&'b str> {
        match mem::replace(&mut self.state, WhitespaceParserState::End) {
            WhitespaceParserState::Beginning => {
                match string.chars().next() {
                    None => {
                        self.state = WhitespaceParserState::Beginning;
                        PushResult::MightMatch
                    },
                    Some(ch) if ch.is_whitespace() => {
                        let len = ch.len_utf8();
                        match string[len..].find(|ch: char| !ch.is_whitespace()) {
                            None => {
                                self.state = WhitespaceParserState::Middle(String::from(string));
                                PushResult::WillMatch
                            },
                            Some(index) => {
                                self.downstream.push(&string[0..index+len]);
                                if string.len() == index+len {
                                    PushResult::MatchedAll
                                } else {
                                    PushResult::MatchedSome(&string[index+len..])
                                }
                            }
                        }
                    },
                    Some(_) => PushResult::WontMatch,
                }
            },
            WhitespaceParserState::Middle(mut buffer) => {
                match string.find(|ch: char| !ch.is_whitespace()) {
                    None => {
                        buffer.push_str(string);
                        self.state = WhitespaceParserState::Middle(buffer);
                        PushResult::WillMatch
                    },
                    Some(index) => {
                        buffer.push_str(&string[0..index]);
                        self.downstream.push(&*buffer);
                        if string.len() == index {
                            PushResult::MatchedAll
                        } else {
                            PushResult::MatchedSome(&string[index..])
                        }
                    }
                }
            },
            WhitespaceParserState::End => PushResult::MatchedSome(string),
        }
    }
    fn done(&mut self) {
        match mem::replace(&mut self.state, WhitespaceParserState::End) {
            WhitespaceParserState::Middle(buffer) => {
                self.downstream.push(&*buffer);
            },
            _              => (),
        }
        self.downstream.done();
    }
}

impl Listener<StrRef> for String {
    fn push<'a,'b>(&'a mut self, string: &'b str) -> PushResult<&'b str> {
        self.push_str(string);
        PushResult::MatchedAll
    }
    fn done(&mut self) {
    }
}

#[test]
fn test_whitespace() {
    let buffer = String::from("");
    let mut parser = WhitespaceParser::from(buffer);
    assert_eq!(parser.push(" \r\n\t"), PushResult::WillMatch);
    assert_eq!(parser.downstream, "");
    assert_eq!(parser.push(" stuff"), PushResult::MatchedSome("stuff"));
    assert_eq!(parser.downstream, " \r\n\t ");
}
<|endoftext|>


<commit_before>//! Details of the `#[ruma_api(...)]` attributes.

use syn::{
    parenthesized,
    parse::{Parse, ParseStream},
    Ident, Token,
};

/// Like syn::Meta, but only parses ruma_api attributes
pub enum Meta {
    /// A single word, like `query` in `#[ruma_api(query)]`
    Word(Ident),
    /// A name-value pair, like `header = CONTENT_TYPE` in `#[ruma_api(header = CONTENT_TYPE)]`
    NameValue(MetaNameValue),
}

impl Meta {
    pub fn from_attribute(attr: syn::Attribute) -> Result<Self, syn::Attribute> {
        match &attr.path {
            syn::Path {
                leading_colon: None,
                segments,
            } => {
                if segments.len() == 1 && segments[0].ident == "ruma_api" {
                    Ok(
                        syn::parse2(attr.tts)
                            .expect("ruma_api! could not parse request field attributes"),
                    )
                } else {
                    Err(attr)
                }
            }
            _ => Err(attr),
        }
    }
}

/// Like syn::MetaNameValue, but expects an identifier as the value. Also, we don't care about the
/// the span of the equals sign, so we don't have the `eq_token` field from syn::MetaNameValue.
pub struct MetaNameValue {
    /// The part left of the equals sign
    pub name: Ident,
    /// The part right of the equals sign
    pub value: Ident,
}

impl Parse for Meta {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let content;
        let _ = parenthesized!(content in input);
        let ident = content.parse()?;

        if content.peek(Token![=]) {
            let _ = content.parse::<Token![=]>();
            Ok(Meta::NameValue(MetaNameValue {
                name: ident,
                value: content.parse()?,
            }))
        } else {
            Ok(Meta::Word(ident))
        }
    }
}
<commit_msg>Re-run rustfmt<commit_after>//! Details of the `#[ruma_api(...)]` attributes.

use syn::{
    parenthesized,
    parse::{Parse, ParseStream},
    Ident, Token,
};

/// Like syn::Meta, but only parses ruma_api attributes
pub enum Meta {
    /// A single word, like `query` in `#[ruma_api(query)]`
    Word(Ident),
    /// A name-value pair, like `header = CONTENT_TYPE` in `#[ruma_api(header = CONTENT_TYPE)]`
    NameValue(MetaNameValue),
}

impl Meta {
    pub fn from_attribute(attr: syn::Attribute) -> Result<Self, syn::Attribute> {
        match &attr.path {
            syn::Path {
                leading_colon: None,
                segments,
            } => {
                if segments.len() == 1 && segments[0].ident == "ruma_api" {
                    Ok(syn::parse2(attr.tts)
                        .expect("ruma_api! could not parse request field attributes"))
                } else {
                    Err(attr)
                }
            }
            _ => Err(attr),
        }
    }
}

/// Like syn::MetaNameValue, but expects an identifier as the value. Also, we don't care about the
/// the span of the equals sign, so we don't have the `eq_token` field from syn::MetaNameValue.
pub struct MetaNameValue {
    /// The part left of the equals sign
    pub name: Ident,
    /// The part right of the equals sign
    pub value: Ident,
}

impl Parse for Meta {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let content;
        let _ = parenthesized!(content in input);
        let ident = content.parse()?;

        if content.peek(Token![=]) {
            let _ = content.parse::<Token![=]>();
            Ok(Meta::NameValue(MetaNameValue {
                name: ident,
                value: content.parse()?,
            }))
        } else {
            Ok(Meta::Word(ident))
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Suppress warnings from merge.<commit_after><|endoftext|>


<commit_before><commit_msg>+ start Mandelbrot calculations<commit_after>// mandelbrot.rs
// Calulate Mandelbrot sets in Rust
//
// vim: ft=rust sw=4 ts=4
//

use std::num::Complex;

pub fn pixel_value(x: f64, y: f64) -> u8 {

    let z0 = new Complex(x, y);
    let mut z = new Complex(0, 0);

    while () {
        // TODO
    }
    0
}

<|endoftext|>


<commit_before><commit_msg>Emit all error messages from Tera on init failure.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix missing documentation of PacketHandler<commit_after><|endoftext|>


<commit_before><commit_msg>linear algebra -> linear system errors<commit_after>// std imports
use std::fmt;

/// Errors in algorithms related to linear systems
pub enum LinearSystemError{

    /// There is no solution to the system of equations
    NoSolution,
    /// There are infinite solutions to the system of equations.
    InfiniteSolutions
}

impl LinearSystemError{

    /// Converts enum values to string representation
    pub fn to_string(&self) -> String {
        match *self{
            NoSolution => format!("No solution"),
            InfiniteSolutions => format!("Infinite solutions"),
        }
    }
}

impl fmt::Show for LinearSystemError {
    /// Formatting of enum values
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "{}", self.to_string()));
        Ok(())
    }
}
<|endoftext|>


<commit_before><commit_msg>Removes Scheduler outdates doc<commit_after><|endoftext|>


<commit_before><commit_msg>Add event body to send requests<commit_after><|endoftext|>


<commit_before>extern crate futures;

use futures::{done, Future};
use futures::stream::*;

mod support;
use support::*;

#[test]
fn sequence() {
    let (tx, mut rx) = channel();

    sassert_empty(&mut rx);
    sassert_empty(&mut rx);

    let amt = 20;
    send(amt, tx).forget();
    let mut rx = rx.wait();
    for i in (1..amt + 1).rev() {
        assert_eq!(rx.next(), Some(Ok(i)));
    }
    assert_eq!(rx.next(), None);

    fn send(n: u32, sender: Sender<u32, u32>)
            -> Box<Future<Item=(), Error=()> + Send> {
        if n == 0 {
            return done(Ok(())).boxed()
        }
        sender.send(Ok(n)).map_err(|_| ()).and_then(move |sender| {
            send(n - 1, sender)
        }).boxed()
    }
}

#[test]
fn drop_sender() {
    let (tx, mut rx) = channel::<u32, u32>();
    drop(tx);
    sassert_done(&mut rx);
}

#[test]
fn drop_rx() {
    let (tx, rx) = channel::<u32, u32>();
    let tx = tx.send(Ok(1)).wait().ok().unwrap();
    drop(rx);
    assert!(tx.send(Ok(1)).wait().is_err());
}
<commit_msg>Failing channel test<commit_after>extern crate futures;

use futures::{task, done, Future, Async};
use futures::stream::*;
use std::sync::Arc;

mod support;
use support::*;

#[test]
fn sequence() {
    let (tx, mut rx) = channel();

    sassert_empty(&mut rx);
    sassert_empty(&mut rx);

    let amt = 20;
    send(amt, tx).forget();
    let mut rx = rx.wait();
    for i in (1..amt + 1).rev() {
        assert_eq!(rx.next(), Some(Ok(i)));
    }
    assert_eq!(rx.next(), None);

    fn send(n: u32, sender: Sender<u32, u32>)
            -> Box<Future<Item=(), Error=()> + Send> {
        if n == 0 {
            return done(Ok(())).boxed()
        }
        sender.send(Ok(n)).map_err(|_| ()).and_then(move |sender| {
            send(n - 1, sender)
        }).boxed()
    }
}

#[test]
fn drop_sender() {
    let (tx, mut rx) = channel::<u32, u32>();
    drop(tx);
    sassert_done(&mut rx);
}

#[test]
fn drop_rx() {
    let (tx, rx) = channel::<u32, u32>();
    let tx = tx.send(Ok(1)).wait().ok().unwrap();
    drop(rx);
    assert!(tx.send(Ok(1)).wait().is_err());
}

struct Unpark;

impl task::Unpark for Unpark {
    fn unpark(&self) {
    }
}

#[test]
fn poll_future_then_drop() {
    let (tx, _) = channel::<u32, u32>();

    let tx = tx.send(Ok(1));
    let mut t = task::spawn(tx);

    // First poll succeeds
    let tx = match t.poll_future(Arc::new(Unpark)) {
        Ok(Async::Ready(tx)) => tx,
        _ => unreachable!(),
    };

    // Send another value
    let tx = tx.send(Ok(2));
    let mut t = task::spawn(tx);

    // Second poll doesn't
    match t.poll_future(Arc::new(Unpark)) {
        Ok(Async::NotReady) => {},
        _ => unreachable!(),
    };

    drop(t);
}
<|endoftext|>


<commit_before>use std::cell::RefCell;
use std::iter::Iterator;
use std::rc::Rc;
use std::ops::Deref;

use storage::file::File;

pub trait FilePrinter {

    fn new(verbose: bool, debug: bool) -> Self;

    /*
     * Print a single file
     */
    fn print_file(&self, Rc<RefCell<File>>);

    /*
     * Print a list of files
     */
    fn print_files<I: Iterator<Item = Rc<RefCell<File>>>>(&self, files: I) {
        for file in files {
            self.print_file(file);
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> String
    {
        info!("{}", f(file));
    }

    fn print_files_custom<F, I>(&self, files: I, f: &F)
        where I: Iterator<Item = Rc<RefCell<File>>>,
              F: Fn(Rc<RefCell<File>>) -> String
    {
        for file in files {
            self.print_file_custom(file, f);
        }
    }

}

struct DebugPrinter {
    debug: bool,
}

impl FilePrinter for DebugPrinter {

    fn new(_: bool, debug: bool) -> DebugPrinter {
        DebugPrinter {
            debug: debug,
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        if self.debug {
            debug!("[DebugPrinter] ->\n{:?}", f);
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> String
    {
        if self.debug {
            debug!("[DebugPrinter] ->\n{:?}", f(file));
        }
    }

}

struct SimplePrinter {
    verbose:    bool,
    debug:      bool,
}

impl FilePrinter for SimplePrinter {

    fn new(verbose: bool, debug: bool) -> SimplePrinter {
        SimplePrinter {
            debug:      debug,
            verbose:    verbose,
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        if self.debug {
            debug!("{:?}", f);
        } else if self.verbose {
            info!("{}", &*f.deref().borrow());
        } else {
            info!("[File]: {}", f.deref().borrow().id());
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> String
    {
        let s = f(file);
        if self.debug {
            debug!("{:?}", s);
        } else if self.verbose {
            info!("{}", s);
        } else {
            info!("[File]: {}", s);
        }
    }

}

pub struct TablePrinter {
    verbose:    bool,
    debug:      bool,
    sp:         SimplePrinter,
}

impl FilePrinter for TablePrinter {

    fn new(verbose: bool, debug: bool) -> TablePrinter {
        TablePrinter {
            debug:      debug,
            verbose:    verbose,
            sp:         SimplePrinter::new(verbose, debug),
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        self.sp.print_file(f);
    }

    fn print_files<I: Iterator<Item = Rc<RefCell<File>>>>(&self, files: I) {
        use prettytable::Table;
        use prettytable::row::Row;
        use prettytable::cell::Cell;

        let titles = row!["File#", "Owner", "ID"];

        let mut tab = Table::new();
        tab.set_titles(titles);

        let mut i = 0;
        for file in files {
            debug!("Printing file: {:?}", file);
            i += 1;
            let cell_i  = Cell::new(&format!("{}", i)[..]);
            let cell_o  = Cell::new(&format!("{}", file.deref().borrow().owner_name())[..]);

            let id : String = file.deref().borrow().id().clone().into();
            let cell_id = Cell::new(&id[..]);
            let row = Row::new(vec![cell_i, cell_o, cell_id]);
            tab.add_row(row);
        }

        if i != 0 {
            debug!("Printing {} table entries", i);
            tab.printstd();
        } else {
            debug!("Not printing table because there are zero entries");
        }
    }

    fn print_files_custom<F, I>(&self, files: I, f: &F)
        where I: Iterator<Item = Rc<RefCell<File>>>,
              F: Fn(Rc<RefCell<File>>) -> String
    {
        use prettytable::Table;
        use prettytable::row::Row;
        use prettytable::cell::Cell;

        let titles = row!["File#", "Owner", "ID", "..."];

        let mut tab = Table::new();
        tab.set_titles(titles);

        let mut i = 0;
        for file in files {
            debug!("Printing file: {:?}", file);
            i += 1;
            let cell_i  = Cell::new(&format!("{}", i)[..]);
            let cell_o  = Cell::new(&format!("{}", file.deref().borrow().owner_name())[..]);

            let id : String = file.deref().borrow().id().clone().into();
            let cell_id = Cell::new(&id[..]);

            let cell_extra = Cell::new(&f(file)[..]);

            let row = Row::new(vec![cell_i, cell_o, cell_id, cell_extra]);
            tab.add_row(row);
        }

        if i != 0 {
            debug!("Printing {} table entries", i);
            tab.printstd();
        } else {
            debug!("Not printing table because there are zero entries");
        }
    }

}
<commit_msg>Allow the custom function to return an Vec<String> in the FilePrinter trait<commit_after>use std::cell::RefCell;
use std::iter::Iterator;
use std::rc::Rc;
use std::ops::Deref;

use storage::file::File;

pub trait FilePrinter {

    fn new(verbose: bool, debug: bool) -> Self;

    /*
     * Print a single file
     */
    fn print_file(&self, Rc<RefCell<File>>);

    /*
     * Print a list of files
     */
    fn print_files<I: Iterator<Item = Rc<RefCell<File>>>>(&self, files: I) {
        for file in files {
            self.print_file(file);
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> Vec<String>
    {
        info!("{}", f(file).join(" "));
    }

    fn print_files_custom<F, I>(&self, files: I, f: &F)
        where I: Iterator<Item = Rc<RefCell<File>>>,
              F: Fn(Rc<RefCell<File>>) -> Vec<String>
    {
        for file in files {
            self.print_file_custom(file, f);
        }
    }

}

struct DebugPrinter {
    debug: bool,
}

impl FilePrinter for DebugPrinter {

    fn new(_: bool, debug: bool) -> DebugPrinter {
        DebugPrinter {
            debug: debug,
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        if self.debug {
            debug!("[DebugPrinter] ->\n{:?}", f);
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> Vec<String>
    {
        if self.debug {
            debug!("[DebugPrinter] ->\n{:?}", f(file).join(" "));
        }
    }

}

struct SimplePrinter {
    verbose:    bool,
    debug:      bool,
}

impl FilePrinter for SimplePrinter {

    fn new(verbose: bool, debug: bool) -> SimplePrinter {
        SimplePrinter {
            debug:      debug,
            verbose:    verbose,
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        if self.debug {
            debug!("{:?}", f);
        } else if self.verbose {
            info!("{}", &*f.deref().borrow());
        } else {
            info!("[File]: {}", f.deref().borrow().id());
        }
    }

    fn print_file_custom<F>(&self, file: Rc<RefCell<File>>, f: &F)
        where F: Fn(Rc<RefCell<File>>) -> Vec<String>
    {
        let s = f(file).join(" ");
        if self.debug {
            debug!("{:?}", s);
        } else if self.verbose {
            info!("{}", s);
        } else {
            info!("[File]: {}", s);
        }
    }

}

pub struct TablePrinter {
    verbose:    bool,
    debug:      bool,
    sp:         SimplePrinter,
}

impl FilePrinter for TablePrinter {

    fn new(verbose: bool, debug: bool) -> TablePrinter {
        TablePrinter {
            debug:      debug,
            verbose:    verbose,
            sp:         SimplePrinter::new(verbose, debug),
        }
    }

    fn print_file(&self, f: Rc<RefCell<File>>) {
        self.sp.print_file(f);
    }

    fn print_files<I: Iterator<Item = Rc<RefCell<File>>>>(&self, files: I) {
        use prettytable::Table;
        use prettytable::row::Row;
        use prettytable::cell::Cell;

        let titles = row!["File#", "Owner", "ID"];

        let mut tab = Table::new();
        tab.set_titles(titles);

        let mut i = 0;
        for file in files {
            debug!("Printing file: {:?}", file);
            i += 1;
            let cell_i  = Cell::new(&format!("{}", i)[..]);
            let cell_o  = Cell::new(&format!("{}", file.deref().borrow().owner_name())[..]);

            let id : String = file.deref().borrow().id().clone().into();
            let cell_id = Cell::new(&id[..]);
            let row = Row::new(vec![cell_i, cell_o, cell_id]);
            tab.add_row(row);
        }

        if i != 0 {
            debug!("Printing {} table entries", i);
            tab.printstd();
        } else {
            debug!("Not printing table because there are zero entries");
        }
    }

    fn print_files_custom<F, I>(&self, files: I, f: &F)
        where I: Iterator<Item = Rc<RefCell<File>>>,
              F: Fn(Rc<RefCell<File>>) -> Vec<String>
    {
        use prettytable::Table;
        use prettytable::row::Row;
        use prettytable::cell::Cell;

        let titles = row!["File#", "Owner", "ID", "..."];

        let mut tab = Table::new();
        tab.set_titles(titles);

        let mut i = 0;
        for file in files {
            debug!("Printing file: {:?}", file);
            i += 1;
            let cell_i  = Cell::new(&format!("{}", i)[..]);
            let cell_o  = Cell::new(&format!("{}", file.deref().borrow().owner_name())[..]);

            let id : String = file.deref().borrow().id().clone().into();
            let cell_id = Cell::new(&id[..]);

            let mut row = Row::new(vec![cell_i, cell_o, cell_id]);

            for cell in f(file).iter() {
                debug!("Adding custom cell: {:?}", cell);
                row.add_cell(Cell::new(&cell[..]))
            }

            tab.add_row(row);
        }

        if i != 0 {
            debug!("Printing {} table entries", i);
            tab.printstd();
        } else {
            debug!("Not printing table because there are zero entries");
        }
    }

}
<|endoftext|>


<commit_before><commit_msg>Comment out debug printing for interrupt pending reg reads<commit_after><|endoftext|>


<commit_before><commit_msg>Draw to column-major framebuffers<commit_after><|endoftext|>


<commit_before><commit_msg>Working on StrandReader.<commit_after><|endoftext|>


<commit_before><commit_msg>Started moving the low-level function calls into their own file, for clarity.<commit_after><|endoftext|>


<commit_before><commit_msg>style(tmux/pane): Use a slice instead of String<commit_after><|endoftext|>


<commit_before><commit_msg>string will coerce by reference<commit_after><|endoftext|>


<commit_before><commit_msg>Fix add_multi_exp_on.0<commit_after><|endoftext|>


<commit_before><commit_msg>implement data bags<commit_after>use api_client::{ApiClient, Error};
use serde_json;
use serde_json::Value;
use std::collections::HashMap;
use std::io;
use std::io::{Cursor, Read, ErrorKind};
use utils::decode_list;

chef_json_type!(DataBagJsonClass, "Chef::DataBag");
chef_json_type!(DataBagChefType, "data_bag");

#[derive(Debug,Clone,Serialize,Deserialize,Default)]
pub struct DataBag {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    chef_type: DataBagChefType,
    #[serde(default)]
    json_class: DataBagJsonClass,
    #[serde(default)]
    id: Option<usize>,
}

impl Read for DataBag {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if let Ok(data_bag) = serde_json::to_vec(self) {
            let mut data_bag = Cursor::new(data_bag.as_ref() as &[u8]);
            Read::read(&mut data_bag, buf)
        } else {
            Err(io::Error::new(ErrorKind::InvalidData,
                               "Failed to convert environment to JSON"))
        }
    }
}

impl DataBag {
    pub fn new<S>(name: S) -> DataBag
        where S: Into<String>
    {
        DataBag { name: Some(name.into()), ..Default::default() }
    }

    pub fn fetch<S: Into<String>>(client: &ApiClient, name: S) -> Result<DataBag, Error> {
        let org = &client.config.organization_path();
        let path = format!("{}/data/{}", org, name.into());
        client.get(path.as_ref()).and_then(|r| r.from_json::<DataBag>())
    }

    pub fn save(&self, client: &ApiClient) -> Result<DataBag, Error> {
        let org = &client.config.organization_path();
        let path = format!("{}/data", org);
        client.post(path.as_ref(), self).and_then(|r| r.from_json::<DataBag>())
    }

    pub fn from_json<R>(r: R) -> Result<DataBag, Error>
        where R: Read
    {
        serde_json::from_reader::<R, DataBag>(r).map_err(|e| Error::Json(e))
    }
}

#[cfg(test)]
mod tests {
    use super::DataBag;
    use std::fs::File;

}
<|endoftext|>


<commit_before>// xfail-test
use std;
use libc;
use zed(name = "std");
use bar(name = "std", vers = "0.1");

// FIXME: commented out since resolve doesn't know how to handle crates yet.
// import str;
// import x = str;
mod baz {
    // import str;
    // import x = str;

}

fn main() { }<commit_msg>test: Fix and un-xfail run-pass/use<commit_after>#[no_core];
use core;
use zed(name = "core");
use bar(name = "core", vers = "0.2");

import core::str;
import x = zed::str;
mod baz {
    import bar::str;
    import x = core::str;
}

fn main() { }<|endoftext|>


<commit_before><commit_msg>Day7_2 updates<commit_after><|endoftext|>


<commit_before><commit_msg>Add tests for wrapping integers<commit_after>extern crate config;

use config::*;

#[test]
fn wrapping_u16() {
    let c = Config::builder()
        .add_source(config::File::from_str(
            r#"
            [settings]
            port = 66000
            "#,
            config::FileFormat::Toml,
        ))
        .build()
        .unwrap();

    let port: u16 = c.get("settings.port").unwrap();
    assert_eq!(port, 464);
}

#[test]
fn nonwrapping_u32() {
    let c = Config::builder()
        .add_source(config::File::from_str(
            r#"
            [settings]
            port = 66000
            "#,
            config::FileFormat::Toml,
        ))
        .build()
        .unwrap();

    let port: u32 = c.get("settings.port").unwrap();
    assert_eq!(port, 66000);
}
<|endoftext|>


<commit_before><commit_msg>Add back client ackmode.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove cross borrowing from mut Box<T> to &mut T.<commit_after><|endoftext|>


<commit_before><commit_msg>Longer gc sanitization test<commit_after><|endoftext|>


<commit_before><commit_msg>Regression test for dropflag reinit issue.<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Check that when a `let`-binding occurs in a loop, its associated
// drop-flag is reinitialized (to indicate "needs-drop" at the end of
// the owning variable's scope).

struct A<'a>(&'a mut i32);

impl<'a> Drop for A<'a> {
    fn drop(&mut self) {
        *self.0 += 1;
    }
}

fn main() {
    let mut cnt = 0;
    for i in 0..2 {
        let a = A(&mut cnt);
        if i == 1 { // Note that
            break;  //  both this break
        }           //   and also
        drop(a);    //    this move of `a`
        // are necessary to expose the bug
    }
    assert_eq!(cnt, 2);
}
<|endoftext|>


<commit_before><commit_msg>rust heapsort<commit_after>// rust heapsort

pub fn heapsort(arr: &mut [i32]) {
	//heapify part
	//this procedure would build a valid max-heap (or min-heap for sorting descendantly)
	let end = arr.len();
	for start in (0..end / 2).rev() {
	    // Skip leaf nodes (end / 2).
	    sift_down(arr, start, end - 1);
	}

    //sorting part
	//iteratively sift down unsorted part (the heap).
	for end in (1..arr.len()).rev() {
	    arr.swap(end, 0);
	    sift_down(arr, 0, end - 1);
	}
}

//internal function for heap to fix itself to conform to heap definition.

//recondition: all elements below `start` are in heap order

//expect `start` itself.

fn sift_down(arr: &mut [i32], start: usize, end: usize) {
	let mut root = start;
	loop {
	    let mut child = root * 2 + 1; // Get the left child
	    if child > end {
	        break;
	    }
	    if child < end && arr[child] < arr[child + 1] {
	        //right child exists and is greater.
	        child += 1;
	    }

        if arr[root] < arr[child] {
	        //if child is greater than root, swap'em!
	        arr.swap(root, child);
	        root = child;
	    } else {
	        break;
	    }
	}
}

#[cfg(test)]

mod base {
	use super::*;
	base_cases!(heapsort);
}<|endoftext|>


<commit_before><commit_msg>Add synchronous Search example<commit_after>// Demonstrates:
//
// 1. Using a synchronous streaming Search.
// 2. A commented-out invalid use of LdapConn while
//    a derived EntryStream is active.
// 3. The technique for abandoning the search, with
//    directions for the ordering of steps to avoid
//    double-borrowing.

use ldap3::{LdapConn, Scope, SearchEntry};
use ldap3::result::Result;

fn main() -> Result<()> {
    let mut ldap = LdapConn::new("ldap://localhost:2389")?;
    let mut search = ldap
        .streaming_search(
            "ou=Places,dc=example,dc=org",
            Scope::Subtree,
            "(&(l=ma*)(objectClass=locality))",
            vec!["l"],
        )?;
    while let Some(entry) = search.next()? {
        let entry = SearchEntry::construct(entry);
        println!("{:?}", entry);
    }
    // The following two statements show how one would
    // Abandon a Search. The statements are commented out
    // because the ldap handle shouldn't be used before result()
    // is called on the streaming hanlde. To work, a) abandon()
    // should follow result(), b) there should be no error
    // handling of result(), because a prematurely finished
    // stream will always return an error.
    //
    //let msgid = search.last_id();
    //ldap.abandon(msgid)?;
    let _res = search.result().success()?;
    Ok(ldap.unbind()?)
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#![crate_name = "macros"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]

#![feature(macro_rules, plugin_registrar, quote)]

//! Exports macros for use in other Servo crates.

#[cfg(test)]
extern crate sync;

extern crate rustc;
extern crate syntax;

use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base;
use syntax::ext::base::{ExtCtxt, MacResult};
use syntax::parse::token;
use syntax::util::small_vector::SmallVector;
use rustc::plugin::Registry;
use std::gc::{Gc, GC};

#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
    reg.register_syntax_extension(
        token::intern("bit_struct"),
        base::IdentTT(box base::BasicIdentMacroExpander {
            expander: expand_bit_struct,
            span: None,
        }, None));
}

fn expand_bit_struct(cx: &mut ExtCtxt, sp: Span, name: ast::Ident, tts: Vec<ast::TokenTree>)
                     -> Box<base::MacResult> {
    let mut fields = Vec::new();
    for (i, e) in tts.iter().enumerate() {
        if i & 1 == 1 {
            match *e {
                ast::TTTok(_, token::COMMA) => (),
                _ => {
                    cx.span_err(sp, "bit_struct! expecting comma.");
                    return base::DummyResult::any(sp);
                }
            }
        } else {
            match *e {
                ast::TTTok(_, token::IDENT(ident, _)) => {
                    fields.push(ident)
                }
                _ => {
                    cx.span_err(sp, "bit_struct! requires ident args.");
                    return base::DummyResult::any(sp);
                }
            }
        }
    }
    let bits_per_word =
        if cfg!(target_word_size = "64") { 64 }
        else if cfg!(target_word_size = "32") { 32 }
        else { fail!("Unexpected target word size") };
    let nb_words = (fields.len() - 1 + bits_per_word) / bits_per_word;

    let struct_def = quote_item!(&*cx,
        pub struct $name {
            storage: [uint, ..$nb_words]
        }
    ).unwrap();
    let impl_def = quote_item!(&*cx,
        impl $name {
            #[inline]
            pub fn new() -> $name {
                $name { storage: [0, ..$nb_words] }
            }
        }
    ).unwrap();

    // Unwrap from Gc<T>, which does not implement DerefMut
    let mut impl_def = (*impl_def).clone();
    match impl_def.node {
        ast::ItemImpl(_, _, _, ref mut methods) => {
            for (i, field) in fields.iter().enumerate() {
                let setter_name = "set_".to_string() + field.as_str();
                let setter = token::str_to_ident(setter_name.as_slice());
                let word = i / bits_per_word;
                let bit = i % bits_per_word;
                let additional_impl = quote_item!(&*cx,
                    impl $name {
                        #[allow(non_snake_case_functions)]
                        pub fn $field(&self) -> bool {
                            (self.storage[$word] & (1 << $bit)) != 0
                        }
                        #[allow(non_snake_case_functions)]
                        pub fn $setter(&mut self, new_value: bool) {
                            if new_value {
                                self.storage[$word] |= 1 << $bit
                            } else {
                                self.storage[$word] &= !(1 << $bit)
                            }
                        }
                    }
                ).unwrap();
                match additional_impl.node {
                    ast::ItemImpl(_, _, _, ref additional_methods) => {
                        methods.push_all(additional_methods.as_slice());
                    }
                    _ => fail!()
                }
            }
        }
        _ => fail!()
    }
    // Re-wrap.
    let impl_def = box(GC) impl_def;

    struct MacItems {
        items: Vec<Gc<ast::Item>>
    }

    impl MacResult for MacItems {
        fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
            Some(SmallVector::many(self.items.clone()))
        }
    }

    box MacItems { items: vec![struct_def, impl_def] } as Box<MacResult>
}

#[macro_export]
macro_rules! bitfield(
    ($bitfieldname:ident, $getter:ident, $setter:ident, $value:expr) => (
        impl $bitfieldname {
            #[inline]
            pub fn $getter(self) -> bool {
                let $bitfieldname(this) = self;
                (this & $value) != 0
            }

            #[inline]
            pub fn $setter(&mut self, value: bool) {
                let $bitfieldname(this) = *self;
                *self = $bitfieldname((this & !$value) | (if value { $value } else { 0 }))
            }
        }
    )
)

#[macro_export]
macro_rules! lazy_init(
    ($(static ref $N:ident : $T:ty = $e:expr;)*) => (
        $(
            #[allow(non_camel_case_types)]
            struct $N {__unit__: ()}
            static $N: $N = $N {__unit__: ()};
            impl Deref<$T> for $N {
                fn deref<'a>(&'a self) -> &'a $T {
                    unsafe {
                        static mut s: *const $T = 0 as *const $T;
                        static mut ONCE: ::sync::one::Once = ::sync::one::ONCE_INIT;
                        ONCE.doit(|| {
                            s = ::std::mem::transmute::<Box<$T>, *const $T>(box () ($e));
                        });
                        &*s
                    }
                }
            }

        )*
    )
)

#[cfg(test)]
mod tests {
    use std::collections::hashmap::HashMap;
    lazy_init! {
        static ref NUMBER: uint = times_two(3);
        static ref VEC: [Box<uint>, ..3] = [box 1, box 2, box 3];
        static ref OWNED_STRING: String = "hello".to_string();
        static ref HASHMAP: HashMap<uint, &'static str> = {
            let mut m = HashMap::new();
            m.insert(0u, "abc");
            m.insert(1, "def");
            m.insert(2, "ghi");
            m
        };
    }

    fn times_two(n: uint) -> uint {
        n * 2
    }

    #[test]
    fn test_basic() {
        assert_eq!(*OWNED_STRING, "hello".to_string());
        assert_eq!(*NUMBER, 6);
        assert!(HASHMAP.find(&1).is_some());
        assert!(HASHMAP.find(&3).is_none());
        assert_eq!(VEC.as_slice(), &[box 1, box 2, box 3]);
    }

    #[test]
    fn test_repeat() {
        assert_eq!(*NUMBER, 6);
        assert_eq!(*NUMBER, 6);
        assert_eq!(*NUMBER, 6);
    }
}
<commit_msg>fixup! Move PropertyBitField to a syntax extension.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#![crate_name = "macros"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]

#![feature(macro_rules, plugin_registrar, quote)]

//! Exports macros for use in other Servo crates.

#[cfg(test)]
extern crate sync;

extern crate rustc;
extern crate syntax;

use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base;
use syntax::ext::base::{ExtCtxt, MacResult};
use syntax::parse::token;
use syntax::util::small_vector::SmallVector;
use rustc::plugin::Registry;
use std::gc::{Gc, GC};

#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
    reg.register_syntax_extension(
        token::intern("bit_struct"),
        base::IdentTT(box base::BasicIdentMacroExpander {
            expander: expand_bit_struct,
            span: None,
        }, None));
}

fn expand_bit_struct(cx: &mut ExtCtxt, sp: Span, name: ast::Ident, tts: Vec<ast::TokenTree>)
                     -> Box<base::MacResult> {
    let mut fields = Vec::new();
    for (i, e) in tts.iter().enumerate() {
        if i & 1 == 1 {
            match *e {
                ast::TTTok(_, token::COMMA) => (),
                _ => {
                    cx.span_err(sp, "bit_struct! expecting comma.");
                    return base::DummyResult::any(sp);
                }
            }
        } else {
            match *e {
                ast::TTTok(_, token::IDENT(ident, _)) => {
                    fields.push(ident)
                }
                _ => {
                    cx.span_err(sp, "bit_struct! requires ident args.");
                    return base::DummyResult::any(sp);
                }
            }
        }
    }
    let bits_per_word =
        if cfg!(target_word_size = "64") { 64 }
        else if cfg!(target_word_size = "32") { 32 }
        else { fail!("Unexpected target word size") };
    let nb_words = (fields.len() - 1 + bits_per_word) / bits_per_word;

    let struct_def = quote_item!(&*cx,
        pub struct $name {
            storage: [uint, ..$nb_words]
        }
    ).unwrap();
    let impl_def = quote_item!(&*cx,
        impl $name {
            #[inline]
            pub fn new() -> $name {
                $name { storage: [0, ..$nb_words] }
            }
        }
    ).unwrap();

    // Unwrap from Gc<T>, which does not implement DerefMut
    let mut impl_def = (*impl_def).clone();
    match impl_def.node {
        ast::ItemImpl(_, _, _, ref mut methods) => {
            for (i, field) in fields.iter().enumerate() {
                let setter_name = "set_".to_string() + field.as_str();
                let setter = token::str_to_ident(setter_name.as_slice());
                let word = i / bits_per_word;
                let bit = i % bits_per_word;
                let additional_impl = quote_item!(&*cx,
                    impl $name {
                        #[allow(non_snake_case_functions)]
                        #[inline]
                        pub fn $field(&self) -> bool {
                            (self.storage[$word] & (1 << $bit)) != 0
                        }
                        #[allow(non_snake_case_functions)]
                        #[inline]
                        pub fn $setter(&mut self, new_value: bool) {
                            if new_value {
                                self.storage[$word] |= 1 << $bit
                            } else {
                                self.storage[$word] &= !(1 << $bit)
                            }
                        }
                    }
                ).unwrap();
                match additional_impl.node {
                    ast::ItemImpl(_, _, _, ref additional_methods) => {
                        methods.push_all(additional_methods.as_slice());
                    }
                    _ => fail!()
                }
            }
        }
        _ => fail!()
    }
    // Re-wrap.
    let impl_def = box(GC) impl_def;

    // FIXME(SimonSapin) replace this with something from libsyntax
    // if/when https://github.com/rust-lang/rust/issues/16723 is fixed
    struct MacItems {
        items: Vec<Gc<ast::Item>>
    }

    impl MacResult for MacItems {
        fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
            Some(SmallVector::many(self.items.clone()))
        }
    }

    box MacItems { items: vec![struct_def, impl_def] } as Box<MacResult>
}

#[macro_export]
macro_rules! bitfield(
    ($bitfieldname:ident, $getter:ident, $setter:ident, $value:expr) => (
        impl $bitfieldname {
            #[inline]
            pub fn $getter(self) -> bool {
                let $bitfieldname(this) = self;
                (this & $value) != 0
            }

            #[inline]
            pub fn $setter(&mut self, value: bool) {
                let $bitfieldname(this) = *self;
                *self = $bitfieldname((this & !$value) | (if value { $value } else { 0 }))
            }
        }
    )
)

#[macro_export]
macro_rules! lazy_init(
    ($(static ref $N:ident : $T:ty = $e:expr;)*) => (
        $(
            #[allow(non_camel_case_types)]
            struct $N {__unit__: ()}
            static $N: $N = $N {__unit__: ()};
            impl Deref<$T> for $N {
                fn deref<'a>(&'a self) -> &'a $T {
                    unsafe {
                        static mut s: *const $T = 0 as *const $T;
                        static mut ONCE: ::sync::one::Once = ::sync::one::ONCE_INIT;
                        ONCE.doit(|| {
                            s = ::std::mem::transmute::<Box<$T>, *const $T>(box () ($e));
                        });
                        &*s
                    }
                }
            }

        )*
    )
)

#[cfg(test)]
mod tests {
    use std::collections::hashmap::HashMap;
    lazy_init! {
        static ref NUMBER: uint = times_two(3);
        static ref VEC: [Box<uint>, ..3] = [box 1, box 2, box 3];
        static ref OWNED_STRING: String = "hello".to_string();
        static ref HASHMAP: HashMap<uint, &'static str> = {
            let mut m = HashMap::new();
            m.insert(0u, "abc");
            m.insert(1, "def");
            m.insert(2, "ghi");
            m
        };
    }

    fn times_two(n: uint) -> uint {
        n * 2
    }

    #[test]
    fn test_basic() {
        assert_eq!(*OWNED_STRING, "hello".to_string());
        assert_eq!(*NUMBER, 6);
        assert!(HASHMAP.find(&1).is_some());
        assert!(HASHMAP.find(&3).is_none());
        assert_eq!(VEC.as_slice(), &[box 1, box 2, box 3]);
    }

    #[test]
    fn test_repeat() {
        assert_eq!(*NUMBER, 6);
        assert_eq!(*NUMBER, 6);
        assert_eq!(*NUMBER, 6);
    }
}
<|endoftext|>


<commit_before><commit_msg>Update<commit_after><|endoftext|>


<commit_before><commit_msg>Add clap matcher for get listen ip<commit_after><|endoftext|>


<commit_before><commit_msg> removed filter for testing<commit_after><|endoftext|>


<commit_before>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use std::fmt;

use rand::Rng;
use rand::ThreadRng;
use rand::thread_rng;

pub struct Randomizer {
    rng: ThreadRng,
    denominator: u32,
}

/// Implement Debug explicitly as ThreadRng does not derive it.
/// See: https://github.com/rust-lang-nursery/rand/issues/118
impl fmt::Debug for Randomizer {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{{Randomizer {:?}", self.denominator)
    }
}

impl Randomizer {
    pub fn new() -> Randomizer {
        Randomizer {
            rng: thread_rng(),
            denominator: 0u32,
        }
    }

    /// Throw a denominator sided die, returning true if 1 comes up
    /// If denominator is 0, return false
    pub fn throw_die(&mut self) -> bool {
        if self.denominator == 0 {
            false
        } else {
            self.rng.gen_weighted_bool(self.denominator)
        }
    }

    /// Set the probability of a failure.
    pub fn set_probability(&mut self, denominator: u32) -> &mut Self {
        self.denominator = denominator;
        self
    }

    /// Choose a bad item from a list of items.
    pub fn get_bad_item<'a, T>(&mut self, items: &'a [T]) -> Option<&'a T> {
        if self.throw_die() {
            self.rng.choose(items)
        } else {
            None
        }
    }
}
<commit_msg>Add a single quickcheck unit test for the randomization module.<commit_after>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use std::fmt;

use rand::Rng;
use rand::ThreadRng;
use rand::thread_rng;

pub struct Randomizer {
    rng: ThreadRng,
    denominator: u32,
}

/// Implement Debug explicitly as ThreadRng does not derive it.
/// See: https://github.com/rust-lang-nursery/rand/issues/118
impl fmt::Debug for Randomizer {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{{Randomizer {:?}", self.denominator)
    }
}

impl Randomizer {
    pub fn new() -> Randomizer {
        Randomizer {
            rng: thread_rng(),
            denominator: 0u32,
        }
    }

    /// Throw a denominator sided die, returning true if 1 comes up
    /// If denominator is 0, return false
    pub fn throw_die(&mut self) -> bool {
        if self.denominator == 0 {
            false
        } else {
            self.rng.gen_weighted_bool(self.denominator)
        }
    }

    /// Set the probability of a failure.
    pub fn set_probability(&mut self, denominator: u32) -> &mut Self {
        self.denominator = denominator;
        self
    }

    /// Choose a bad item from a list of items.
    pub fn get_bad_item<'a, T>(&mut self, items: &'a [T]) -> Option<&'a T> {
        if self.throw_die() {
            self.rng.choose(items)
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use quickcheck::QuickCheck;

    use super::*;

    #[test]
    fn prop_denominator_result() {

        /// Verify that if the denominator is 0 the result is always false,
        /// if 1, always true.
        fn denominator_result(denominator: u32) -> bool {
            let result = Randomizer::new().set_probability(denominator).throw_die();
            if denominator > 1 {
                true
            } else {
                if denominator == 0 {
                    result == false
                } else {
                    result == true
                }
            }
        }
        QuickCheck::new().tests(30).quickcheck(denominator_result as fn(u32) -> bool);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add run-fail test for #2061<commit_after>// error-pattern: ran out of stack
struct R {
    b: int,
    drop {
        let _y = R { b: self.b };
    }
}

fn main() {
    let _x = R { b: 0 };
}
<|endoftext|>


<commit_before>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// @has intra_links/index.html
// @has - '//a/@href' '../intra_links/struct.ThisType.html'
// @has - '//a/@href' '../intra_links/struct.ThisType.html#method.this_method'
// @has - '//a/@href' '../intra_links/enum.ThisEnum.html'
// @has - '//a/@href' '../intra_links/enum.ThisEnum.html#ThisVariant.v'
// @has - '//a/@href' '../intra_links/trait.ThisTrait.html'
// @has - '//a/@href' '../intra_links/trait.ThisTrait.html#tymethod.this_associated_method'
// @has - '//a/@href' '../intra_links/trait.ThisTrait.html#associatedtype.ThisAssociatedType'
// @has - '//a/@href' '../intra_links/trait.ThisTrait.html#associatedconstant.THIS_ASSOCIATED_CONST'
// @has - '//a/@href' '../intra_links/trait.ThisTrait.html'
// @has - '//a/@href' '../intra_links/type.ThisAlias.html'
// @has - '//a/@href' '../intra_links/union.ThisUnion.html'
// @has - '//a/@href' '../intra_links/fn.this_function.html'
// @has - '//a/@href' '../intra_links/constant.THIS_CONST.html'
// @has - '//a/@href' '../intra_links/static.THIS_STATIC.html'
// @has - '//a/@href' '../intra_links/macro.this_macro.html'
// @has - '//a/@href' '../intra_links/trait.SoAmbiguous.html'
// @has - '//a/@href' '../intra_links/fn.SoAmbiguous.html'
//! In this crate we would like to link to:
//!
//! * [`ThisType`](ThisType)
//! * [`ThisType::this_method`](ThisType::this_method)
//! * [`ThisEnum`](ThisEnum)
//! * [`ThisEnum::ThisVariant`](ThisEnum::ThisVariant)
//! * [`ThisTrait`](ThisTrait)
//! * [`ThisTrait::this_associated_method`](ThisTrait::this_associated_method)
//! * [`ThisTrait::ThisAssociatedType`](ThisTrait::ThisAssociatedType)
//! * [`ThisTrait::THIS_ASSOCIATED_CONST`](ThisTrait::THIS_ASSOCIATED_CONST)
//! * [`ThisAlias`](ThisAlias)
//! * [`ThisUnion`](ThisUnion)
//! * [`this_function`](this_function())
//! * [`THIS_CONST`](const@THIS_CONST)
//! * [`THIS_STATIC`](static@THIS_STATIC)
//! * [`this_macro`](this_macro!)
//!
//! In addition, there's some specifics we want to look at. There's [a trait called
//! SoAmbiguous][ambig-trait], but there's also [a function called SoAmbiguous][ambig-fn] too!
//! Whatever shall we do?
//!
//! [ambig-trait]: trait@SoAmbiguous
//! [ambig-fn]: SoAmbiguous()

#[macro_export]
macro_rules! this_macro {
    () => {};
}

pub struct ThisType;

impl ThisType {
    pub fn this_method() {}
}
pub enum ThisEnum { ThisVariant, }
pub trait ThisTrait {
    type ThisAssociatedType;
    const THIS_ASSOCIATED_CONST: u8;
    fn this_associated_method();
}
pub type ThisAlias = Result<(), ()>;
pub union ThisUnion { this_field: usize, }

pub fn this_function() {}
pub const THIS_CONST: usize = 5usize;
pub static THIS_STATIC: usize = 5usize;

pub trait SoAmbiguous {}

#[allow(bad_style)]
pub fn SoAmbiguous() {}
<commit_msg>Add test<commit_after>// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// @has intra_links/index.html
// @has - '//a/@href' '../intra_links/struct.ThisType.html'
// @has - '//a/@href' '../intra_links/struct.ThisType.html#method.this_method'
// @has - '//a/@href' '../intra_links/enum.ThisEnum.html'
// @has - '//a/@href' '../intra_links/enum.ThisEnum.html#ThisVariant.v'
// @has - '//a/@href' '../intra_links/trait.ThisTrait.html'
// @has - '//a/@href' '../intra_links/trait.ThisTrait.html#tymethod.this_associated_method'
// @has - '//a/@href' '../intra_links/trait.ThisTrait.html#associatedtype.ThisAssociatedType'
// @has - '//a/@href' '../intra_links/trait.ThisTrait.html#associatedconstant.THIS_ASSOCIATED_CONST'
// @has - '//a/@href' '../intra_links/trait.ThisTrait.html'
// @has - '//a/@href' '../intra_links/type.ThisAlias.html'
// @has - '//a/@href' '../intra_links/union.ThisUnion.html'
// @has - '//a/@href' '../intra_links/fn.this_function.html'
// @has - '//a/@href' '../intra_links/constant.THIS_CONST.html'
// @has - '//a/@href' '../intra_links/static.THIS_STATIC.html'
// @has - '//a/@href' '../intra_links/macro.this_macro.html'
// @has - '//a/@href' '../intra_links/trait.SoAmbiguous.html'
// @has - '//a/@href' '../intra_links/fn.SoAmbiguous.html'
//! In this crate we would like to link to:
//!
//! * [`ThisType`](ThisType)
//! * [`ThisType::this_method`](ThisType::this_method)
//! * [`ThisEnum`](ThisEnum)
//! * [`ThisEnum::ThisVariant`](ThisEnum::ThisVariant)
//! * [`ThisTrait`](ThisTrait)
//! * [`ThisTrait::this_associated_method`](ThisTrait::this_associated_method)
//! * [`ThisTrait::ThisAssociatedType`](ThisTrait::ThisAssociatedType)
//! * [`ThisTrait::THIS_ASSOCIATED_CONST`](ThisTrait::THIS_ASSOCIATED_CONST)
//! * [`ThisAlias`](ThisAlias)
//! * [`ThisUnion`](ThisUnion)
//! * [`this_function`](this_function())
//! * [`THIS_CONST`](const@THIS_CONST)
//! * [`THIS_STATIC`](static@THIS_STATIC)
//! * [`this_macro`](this_macro!)
//!
//! In addition, there's some specifics we want to look at. There's [a trait called
//! SoAmbiguous][ambig-trait], but there's also [a function called SoAmbiguous][ambig-fn] too!
//! Whatever shall we do?
//!
//! [ambig-trait]: trait@SoAmbiguous
//! [ambig-fn]: SoAmbiguous()

#[macro_export]
macro_rules! this_macro {
    () => {};
}

pub struct ThisType;

impl ThisType {
    pub fn this_method() {}
}
pub enum ThisEnum { ThisVariant, }
pub trait ThisTrait {
    type ThisAssociatedType;
    const THIS_ASSOCIATED_CONST: u8;
    fn this_associated_method();
}
pub type ThisAlias = Result<(), ()>;
pub union ThisUnion { this_field: usize, }

pub fn this_function() {}
pub const THIS_CONST: usize = 5usize;
pub static THIS_STATIC: usize = 5usize;

pub trait SoAmbiguous {}

#[allow(bad_style)]
pub fn SoAmbiguous() {}

// @has - '//a/@href' '../intra_links/struct.ThisType.html'
// @has - '//a/@href' '../intra_links/struct.ThisType.html#method.this_method'
// @has - '//a/@href' '../intra_links/enum.ThisEnum.html'
// @has - '//a/@href' '../intra_links/enum.ThisEnum.html#ThisVariant.v'
/// Shortcut links for:
/// * [`ThisType`]
/// * [`ThisType::this_method`]
/// * [ThisEnum]
/// * [ThisEnum::ThisVariant]
pub struct SomeOtherType;
<|endoftext|>


<commit_before><commit_msg>an empy message<commit_after><|endoftext|>


<commit_before><commit_msg>Fix custom emojis cutting off after first space<commit_after><|endoftext|>


<commit_before><commit_msg>feat: Implements Display for Arm7Tdmi<commit_after><|endoftext|>


<commit_before><commit_msg>test: Add a trivial test that trait composition parses<commit_after>trait Foo {
    fn foo();
}

trait Bar : Foo {
    fn bar();
}

fn main() {}

<|endoftext|>


<commit_before><commit_msg>Array_concatenation solution, initial checkin<commit_after>// http://rosettacode.org/wiki/Array_concatenation

fn main() {
    let a_vec: Vec<i32> = vec![1, 2, 3, 4, 5];
    let b_vec: Vec<i32> = vec![6; 5];

    let c_vec = concatenate_arrays::<i32>(a_vec.as_slice(), b_vec.as_slice());

    println!("{:?} ~ {:?} => {:?}", a_vec, b_vec, c_vec);
}

fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {
    let mut concat: Vec<T> = vec![x[0].clone(); x.len()];

    concat.clone_from_slice(x);
    concat.extend_from_slice(y);

    concat
}

#[cfg(test)]
mod tests {
    use super::concatenate_arrays;

    #[derive(Clone, Debug, PartialEq)]
    struct Dummy {
        a: f64,
        b: &'static str,
    }

    #[test]
    fn test_concatenation_int() {
        let a_vec: Vec<u64> = vec![0, 1, 2, 3, 4];
        let b_vec: Vec<u64> = vec![5; 5];
        let c_vec = concatenate_arrays::<u64>(a_vec.as_slice(), b_vec.as_slice());

        assert_eq!(c_vec, [0, 1, 2, 3, 4, 5, 5, 5, 5, 5]);
    }

    #[test]
    fn test_concatenation_str() {
        let a_vec: Vec<&str> = vec!["hay", "ye", "eye", "owe", "you"];
        let b_vec: Vec<&str> = vec!["why"];
        let c_vec = concatenate_arrays::<&str>(a_vec.as_slice(), b_vec.as_slice());

        assert_eq!(c_vec, ["hay", "ye", "eye", "owe", "you", "why"]);
    }

    #[test]
    fn test_concatenation_tuple() {
        let a_vec: Vec<(i32, &str)> = vec![(0, "hay"), (1, "ye"), (2, "eye")];
        let b_vec: Vec<(i32, &str)> = vec![(3, "owe"), (4, "you")];
        let c_vec = concatenate_arrays::<(i32, &str)>(a_vec.as_slice(), b_vec.as_slice());

        assert_eq!(c_vec,
                   [(0, "hay"), (1, "ye"), (2, "eye"), (3, "owe"), (4, "you")]);
    }

    #[test]
    fn test_concatenation_struct() {
        let a_vec: Vec<Dummy> = vec![Dummy { a: 0.0, b: "hay" },
                                     Dummy { a: 1.1, b: "ye" },
                                     Dummy { a: 2.2, b: "eye" }];
        let b_vec: Vec<Dummy> = vec![Dummy { a: 3.3, b: "owe" }, Dummy { a: 4.4, b: "you" }];

        let c_vec = concatenate_arrays::<Dummy>(a_vec.as_slice(), b_vec.as_slice());

        assert_eq!(c_vec,
                   [Dummy { a: 0.0, b: "hay" },
                    Dummy { a: 1.1, b: "ye" },
                    Dummy { a: 2.2, b: "eye" },
                    Dummy { a: 3.3, b: "owe" },
                    Dummy { a: 4.4, b: "you" }]);
    }
}
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2447<commit_after>// https://leetcode.com/problems/number-of-subarrays-with-gcd-equal-to-k/
pub fn subarray_gcd(nums: Vec<i32>, k: i32) -> i32 {
    todo!()
}

fn main() {
    println!("{}", subarray_gcd(vec![9, 3, 1, 2, 6, 3], 3)); // 4
    println!("{}", subarray_gcd(vec![4], 7)); // 0
}
<|endoftext|>


<commit_before><commit_msg>Added if let example<commit_after>fn main() {
    // All have type `Option<i32>`
    let number   = Some(7);
    let letter: Option<i32> = None;
    let emoticon: Option<i32> = None;

    // The `if let` construct reads: "if `let` destructures `number` into
    // `Some(i)`, evaluate the block (`{}`). Else do nothing.
    if let Some(i) = number {
        println!("Matched {:?}!", i);
    }

    // If you need to specify a failure, use an else:
    if let Some(i) = letter {
        println!("Matched {:?}!", i);
    } else {
        // Destructure failed. Change the failure case.
        println!("Didn't match a number. Let's go with a letter!");
    };

    // Provide an altered failing condition.
    let i_like_letters = false;

    if let Some(i) = emoticon {
        println!("Matched {:?}!", i);
    // Destructure failed. Evaluated the condition to see if this branch
    // should be taken.
    } else if i_like_letters {
        println!("Didn't match a number. Let's go with a letter!");
    // The condition evaluated false. This branch is the default.
    } else {
        println!("I don't like letters. Let's go with an emoticon :)!");
    };
}
<|endoftext|>