<commit_before>// Copyright 2012-2014 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.

use rustc::session::Session;

use generated_code;

use std::cell::Cell;
use std::env;

use syntax::parse::lexer::{self, StringReader};
use syntax::parse::token::{self, Token};
use syntax::symbol::keywords;
use syntax_pos::*;

#[derive(Clone)]
pub struct SpanUtils<'a> {
    pub sess: &'a Session,
    // FIXME given that we clone SpanUtils all over the place, this err_count is
    // probably useless and any logic relying on it is bogus.
    pub err_count: Cell<isize>,
}

impl<'a> SpanUtils<'a> {
    pub fn new(sess: &'a Session) -> SpanUtils<'a> {
        SpanUtils {
            sess,
            err_count: Cell::new(0),
        }
    }

    pub fn make_path_string(path: &FileName) -> String {
        match *path {
            FileName::Real(ref path) if !path.is_absolute() =>
                env::current_dir()
                    .unwrap()
                    .join(&path)
                    .display()
                    .to_string(),
            _ => path.to_string(),
        }
    }

    pub fn snippet(&self, span: Span) -> String {
        match self.sess.codemap().span_to_snippet(span) {
            Ok(s) => s,
            Err(_) => String::new(),
        }
    }

    pub fn retokenise_span(&self, span: Span) -> StringReader<'a> {
        lexer::StringReader::retokenize(&self.sess.parse_sess, span)
    }

    // Re-parses a path and returns the span for the last identifier in the path
    pub fn span_for_last_ident(&self, span: Span) -> Option<Span> {
        let mut result = None;

        let mut toks = self.retokenise_span(span);
        let mut bracket_count = 0;
        loop {
            let ts = toks.real_token();
            if ts.tok == token::Eof {
                return result;
            }
            if bracket_count == 0 && (ts.tok.is_ident() || ts.tok.is_keyword(keywords::SelfValue)) {
                result = Some(ts.sp);
            }

            bracket_count += match ts.tok {
                token::Lt => 1,
                token::Gt => -1,
                token::BinOp(token::Shr) => -2,
                _ => 0,
            }
        }
    }

    // Return the span for the first identifier in the path.
    pub fn span_for_first_ident(&self, span: Span) -> Option<Span> {
        let mut toks = self.retokenise_span(span);
        let mut bracket_count = 0;
        loop {
            let ts = toks.real_token();
            if ts.tok == token::Eof {
                return None;
            }
            if bracket_count == 0 && (ts.tok.is_ident() || ts.tok.is_keyword(keywords::SelfValue)) {
                return Some(ts.sp);
            }

            bracket_count += match ts.tok {
                token::Lt => 1,
                token::Gt => -1,
                token::BinOp(token::Shr) => -2,
                _ => 0,
            }
        }
    }

    // Return the span for the last ident before a `<` and outside any
    // angle brackets, or the last span.
    pub fn sub_span_for_type_name(&self, span: Span) -> Option<Span> {
        let mut toks = self.retokenise_span(span);
        let mut prev = toks.real_token();
        let mut result = None;

        // We keep track of the following two counts - the depth of nesting of
        // angle brackets, and the depth of nesting of square brackets. For the
        // angle bracket count, we only count tokens which occur outside of any
        // square brackets (i.e. bracket_count == 0). The intutition here is
        // that we want to count angle brackets in the type, but not any which
        // could be in expression context (because these could mean 'less than',
        // etc.).
        let mut angle_count = 0;
        let mut bracket_count = 0;
        loop {
            let next = toks.real_token();

            if (next.tok == token::Lt || next.tok == token::Colon) && angle_count == 0
                && bracket_count == 0 && prev.tok.is_ident()
            {
                result = Some(prev.sp);
            }

            if bracket_count == 0 {
                angle_count += match prev.tok {
                    token::Lt => 1,
                    token::Gt => -1,
                    token::BinOp(token::Shl) => 2,
                    token::BinOp(token::Shr) => -2,
                    _ => 0,
                };
            }

            bracket_count += match prev.tok {
                token::OpenDelim(token::Bracket) => 1,
                token::CloseDelim(token::Bracket) => -1,
                _ => 0,
            };

            if next.tok == token::Eof {
                break;
            }
            prev = next;
        }
        if angle_count != 0 || bracket_count != 0 {
            let loc = self.sess.codemap().lookup_char_pos(span.lo());
            span_bug!(
                span,
                "Mis-counted brackets when breaking path? Parsing '{}' \
                 in {}, line {}",
                self.snippet(span),
                loc.file.name,
                loc.line
            );
        }
        if result.is_none() && prev.tok.is_ident() && angle_count == 0 {
            return Some(prev.sp);
        }
        result
    }

    pub fn sub_span_before_token(&self, span: Span, tok: Token) -> Option<Span> {
        let mut toks = self.retokenise_span(span);
        let mut prev = toks.real_token();
        loop {
            if prev.tok == token::Eof {
                return None;
            }
            let next = toks.real_token();
            if next.tok == tok {
                return Some(prev.sp);
            }
            prev = next;
        }
    }

    pub fn sub_span_of_token(&self, span: Span, tok: Token) -> Option<Span> {
        let mut toks = self.retokenise_span(span);
        loop {
            let next = toks.real_token();
            if next.tok == token::Eof {
                return None;
            }
            if next.tok == tok {
                return Some(next.sp);
            }
        }
    }

    pub fn sub_span_after_keyword(&self, span: Span, keyword: keywords::Keyword) -> Option<Span> {
        self.sub_span_after(span, |t| t.is_keyword(keyword))
    }

    pub fn sub_span_after_token(&self, span: Span, tok: Token) -> Option<Span> {
        self.sub_span_after(span, |t| t == tok)
    }

    fn sub_span_after<F: Fn(Token) -> bool>(&self, span: Span, f: F) -> Option<Span> {
        let mut toks = self.retokenise_span(span);
        loop {
            let ts = toks.real_token();
            if ts.tok == token::Eof {
                return None;
            }
            if f(ts.tok) {
                let ts = toks.real_token();
                if ts.tok == token::Eof {
                    return None;
                } else {
                    return Some(ts.sp);
                }
            }
        }
    }

    // // Return the name for a macro definition (identifier after first `!`)
    // pub fn span_for_macro_def_name(&self, span: Span) -> Option<Span> {
    //     let mut toks = self.retokenise_span(span);
    //     loop {
    //         let ts = toks.real_token();
    //         if ts.tok == token::Eof {
    //             return None;
    //         }
    //         if ts.tok == token::Not {
    //             let ts = toks.real_token();
    //             if ts.tok.is_ident() {
    //                 return Some(ts.sp);
    //             } else {
    //                 return None;
    //             }
    //         }
    //     }
    // }

    // // Return the name for a macro use (identifier before first `!`).
    // pub fn span_for_macro_use_name(&self, span:Span) -> Option<Span> {
    //     let mut toks = self.retokenise_span(span);
    //     let mut prev = toks.real_token();
    //     loop {
    //         if prev.tok == token::Eof {
    //             return None;
    //         }
    //         let ts = toks.real_token();
    //         if ts.tok == token::Not {
    //             if prev.tok.is_ident() {
    //                 return Some(prev.sp);
    //             } else {
    //                 return None;
    //             }
    //         }
    //         prev = ts;
    //     }
    // }

    /// Return true if the span is generated code, and
    /// it is not a subspan of the root callsite.
    ///
    /// Used to filter out spans of minimal value,
    /// such as references to macro internal variables.
    pub fn filter_generated(&self, sub_span: Option<Span>, parent: Span) -> bool {
        if !generated_code(parent) {
            if sub_span.is_none() {
                // Edge case - this occurs on generated code with incorrect expansion info.
                return true;
            }
            return false;
        }
        // If sub_span is none, filter out generated code.
        let sub_span = match sub_span {
            Some(ss) => ss,
            None => return true,
        };

        //If the span comes from a fake filemap, filter it.
        if !self.sess
            .codemap()
            .lookup_char_pos(parent.lo())
            .file
            .is_real_file()
        {
            return true;
        }

        // Otherwise, a generated span is deemed invalid if it is not a sub-span of the root
        // callsite. This filters out macro internal variables and most malformed spans.
        !parent.source_callsite().contains(sub_span)
    }
}

macro_rules! filter {
    ($util: expr, $span: expr, $parent: expr, None) => {
        if $util.filter_generated($span, $parent) {
            return None;
        }
    };
    ($util: expr, $span: ident, $parent: expr) => {
        if $util.filter_generated($span, $parent) {
            return;
        }
    };
}
<commit_msg>save-analysis: power through bracket mis-counts<commit_after>// Copyright 2012-2014 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.

use rustc::session::Session;

use generated_code;

use std::cell::Cell;
use std::env;

use syntax::parse::lexer::{self, StringReader};
use syntax::parse::token::{self, Token};
use syntax::symbol::keywords;
use syntax_pos::*;

#[derive(Clone)]
pub struct SpanUtils<'a> {
    pub sess: &'a Session,
    // FIXME given that we clone SpanUtils all over the place, this err_count is
    // probably useless and any logic relying on it is bogus.
    pub err_count: Cell<isize>,
}

impl<'a> SpanUtils<'a> {
    pub fn new(sess: &'a Session) -> SpanUtils<'a> {
        SpanUtils {
            sess,
            err_count: Cell::new(0),
        }
    }

    pub fn make_path_string(path: &FileName) -> String {
        match *path {
            FileName::Real(ref path) if !path.is_absolute() =>
                env::current_dir()
                    .unwrap()
                    .join(&path)
                    .display()
                    .to_string(),
            _ => path.to_string(),
        }
    }

    pub fn snippet(&self, span: Span) -> String {
        match self.sess.codemap().span_to_snippet(span) {
            Ok(s) => s,
            Err(_) => String::new(),
        }
    }

    pub fn retokenise_span(&self, span: Span) -> StringReader<'a> {
        lexer::StringReader::retokenize(&self.sess.parse_sess, span)
    }

    // Re-parses a path and returns the span for the last identifier in the path
    pub fn span_for_last_ident(&self, span: Span) -> Option<Span> {
        let mut result = None;

        let mut toks = self.retokenise_span(span);
        let mut bracket_count = 0;
        loop {
            let ts = toks.real_token();
            if ts.tok == token::Eof {
                return result;
            }
            if bracket_count == 0 && (ts.tok.is_ident() || ts.tok.is_keyword(keywords::SelfValue)) {
                result = Some(ts.sp);
            }

            bracket_count += match ts.tok {
                token::Lt => 1,
                token::Gt => -1,
                token::BinOp(token::Shr) => -2,
                _ => 0,
            }
        }
    }

    // Return the span for the first identifier in the path.
    pub fn span_for_first_ident(&self, span: Span) -> Option<Span> {
        let mut toks = self.retokenise_span(span);
        let mut bracket_count = 0;
        loop {
            let ts = toks.real_token();
            if ts.tok == token::Eof {
                return None;
            }
            if bracket_count == 0 && (ts.tok.is_ident() || ts.tok.is_keyword(keywords::SelfValue)) {
                return Some(ts.sp);
            }

            bracket_count += match ts.tok {
                token::Lt => 1,
                token::Gt => -1,
                token::BinOp(token::Shr) => -2,
                _ => 0,
            }
        }
    }

    // Return the span for the last ident before a `<` and outside any
    // angle brackets, or the last span.
    pub fn sub_span_for_type_name(&self, span: Span) -> Option<Span> {
        let mut toks = self.retokenise_span(span);
        let mut prev = toks.real_token();
        let mut result = None;

        // We keep track of the following two counts - the depth of nesting of
        // angle brackets, and the depth of nesting of square brackets. For the
        // angle bracket count, we only count tokens which occur outside of any
        // square brackets (i.e. bracket_count == 0). The intuition here is
        // that we want to count angle brackets in the type, but not any which
        // could be in expression context (because these could mean 'less than',
        // etc.).
        let mut angle_count = 0;
        let mut bracket_count = 0;
        loop {
            let next = toks.real_token();

            if (next.tok == token::Lt || next.tok == token::Colon) && angle_count == 0
                && bracket_count == 0 && prev.tok.is_ident()
            {
                result = Some(prev.sp);
            }

            if bracket_count == 0 {
                angle_count += match prev.tok {
                    token::Lt => 1,
                    token::Gt => -1,
                    token::BinOp(token::Shl) => 2,
                    token::BinOp(token::Shr) => -2,
                    _ => 0,
                };
            }

            bracket_count += match prev.tok {
                token::OpenDelim(token::Bracket) => 1,
                token::CloseDelim(token::Bracket) => -1,
                _ => 0,
            };

            if next.tok == token::Eof {
                break;
            }
            prev = next;
        }
        #[cfg(debug_assertions)] {
            if angle_count != 0 || bracket_count != 0 {
                let loc = self.sess.codemap().lookup_char_pos(span.lo());
                span_bug!(
                    span,
                    "Mis-counted brackets when breaking path? Parsing '{}' \
                     in {}, line {}",
                    self.snippet(span),
                    loc.file.name,
                    loc.line
                );
            }
        }
        if result.is_none() && prev.tok.is_ident() {
            return Some(prev.sp);
        }
        result
    }

    pub fn sub_span_before_token(&self, span: Span, tok: Token) -> Option<Span> {
        let mut toks = self.retokenise_span(span);
        let mut prev = toks.real_token();
        loop {
            if prev.tok == token::Eof {
                return None;
            }
            let next = toks.real_token();
            if next.tok == tok {
                return Some(prev.sp);
            }
            prev = next;
        }
    }

    pub fn sub_span_of_token(&self, span: Span, tok: Token) -> Option<Span> {
        let mut toks = self.retokenise_span(span);
        loop {
            let next = toks.real_token();
            if next.tok == token::Eof {
                return None;
            }
            if next.tok == tok {
                return Some(next.sp);
            }
        }
    }

    pub fn sub_span_after_keyword(&self, span: Span, keyword: keywords::Keyword) -> Option<Span> {
        self.sub_span_after(span, |t| t.is_keyword(keyword))
    }

    pub fn sub_span_after_token(&self, span: Span, tok: Token) -> Option<Span> {
        self.sub_span_after(span, |t| t == tok)
    }

    fn sub_span_after<F: Fn(Token) -> bool>(&self, span: Span, f: F) -> Option<Span> {
        let mut toks = self.retokenise_span(span);
        loop {
            let ts = toks.real_token();
            if ts.tok == token::Eof {
                return None;
            }
            if f(ts.tok) {
                let ts = toks.real_token();
                if ts.tok == token::Eof {
                    return None;
                } else {
                    return Some(ts.sp);
                }
            }
        }
    }

    // // Return the name for a macro definition (identifier after first `!`)
    // pub fn span_for_macro_def_name(&self, span: Span) -> Option<Span> {
    //     let mut toks = self.retokenise_span(span);
    //     loop {
    //         let ts = toks.real_token();
    //         if ts.tok == token::Eof {
    //             return None;
    //         }
    //         if ts.tok == token::Not {
    //             let ts = toks.real_token();
    //             if ts.tok.is_ident() {
    //                 return Some(ts.sp);
    //             } else {
    //                 return None;
    //             }
    //         }
    //     }
    // }

    // // Return the name for a macro use (identifier before first `!`).
    // pub fn span_for_macro_use_name(&self, span:Span) -> Option<Span> {
    //     let mut toks = self.retokenise_span(span);
    //     let mut prev = toks.real_token();
    //     loop {
    //         if prev.tok == token::Eof {
    //             return None;
    //         }
    //         let ts = toks.real_token();
    //         if ts.tok == token::Not {
    //             if prev.tok.is_ident() {
    //                 return Some(prev.sp);
    //             } else {
    //                 return None;
    //             }
    //         }
    //         prev = ts;
    //     }
    // }

    /// Return true if the span is generated code, and
    /// it is not a subspan of the root callsite.
    ///
    /// Used to filter out spans of minimal value,
    /// such as references to macro internal variables.
    pub fn filter_generated(&self, sub_span: Option<Span>, parent: Span) -> bool {
        if !generated_code(parent) {
            if sub_span.is_none() {
                // Edge case - this occurs on generated code with incorrect expansion info.
                return true;
            }
            return false;
        }
        // If sub_span is none, filter out generated code.
        let sub_span = match sub_span {
            Some(ss) => ss,
            None => return true,
        };

        //If the span comes from a fake filemap, filter it.
        if !self.sess
            .codemap()
            .lookup_char_pos(parent.lo())
            .file
            .is_real_file()
        {
            return true;
        }

        // Otherwise, a generated span is deemed invalid if it is not a sub-span of the root
        // callsite. This filters out macro internal variables and most malformed spans.
        !parent.source_callsite().contains(sub_span)
    }
}

macro_rules! filter {
    ($util: expr, $span: expr, $parent: expr, None) => {
        if $util.filter_generated($span, $parent) {
            return None;
        }
    };
    ($util: expr, $span: ident, $parent: expr) => {
        if $util.filter_generated($span, $parent) {
            return;
        }
    };
}
<|endoftext|>


<commit_before>//! # TreeView Sample
//!
//! This sample demonstrates how to create a TreeView with either a ListStore or TreeStore.

#![feature(globs)]
#![crate_type = "bin"]

extern crate rgtk;

use rgtk::*;
use rgtk::gtk::signals;

fn append_text_column(tree: &mut gtk::TreeView) {
    let column = gtk::TreeViewColumn::new().unwrap();
    let cell = gtk::CellRendererText::new().unwrap();
    column.pack_start(&cell, true);
    column.add_attribute(&cell, "text", 0);
    tree.append_column(&column);
}

fn main() {
    gtk::init();

    let mut window = gtk::Window::new(gtk::window_type::TopLevel).unwrap();
    window.set_title("TreeView Sample");
    window.set_window_position(gtk::window_position::Center);

    window.connect(signals::DeleteEvent::new(|_| {
        gtk::main_quit();
        true
    }));

    // left pane

    let mut left_tree = gtk::TreeView::new().unwrap();
    let column_types = [glib::ffi::g_type_string];
    let left_store = gtk::ListStore::new(column_types).unwrap();
    let left_model = left_store.get_model().unwrap();
    left_tree.set_model(&left_model);
    left_tree.set_headers_visible(false);
    append_text_column(&mut left_tree);

    for _ in range(0i, 10i) {
        let iter = gtk::TreeIter::new().unwrap();
        left_store.append(&iter);
        left_store.set_string(&iter, 0, "I'm in a list");
    }

    // right pane

    let mut right_tree = gtk::TreeView::new().unwrap();
    let column_types = [glib::ffi::g_type_string];
    let right_store = gtk::TreeStore::new(column_types).unwrap();
    let right_model = right_store.get_model().unwrap();
    right_tree.set_model(&right_model);
    right_tree.set_headers_visible(false);
    append_text_column(&mut right_tree);

    for _ in range(0i, 10i) {
        let iter = gtk::TreeIter::new().unwrap();
        right_store.append(&iter, None);
        right_store.set_string(&iter, 0, "I'm in a tree");

        let mut child_raw = gtk::ffi::C_GtkTreeIter;
        let child = gtk::TreeIter::wrap_pointer(&mut child_raw);
        right_store.append(&child, Some(&iter));
        right_store.set_string(&child, 0, "I'm a child node");
    }

    // display the panes

    let mut split_pane = gtk::Box::new(gtk::orientation::Horizontal, 10).unwrap();
    split_pane.set_size_request(-1, -1);
    split_pane.add(&left_tree);
    split_pane.add(&right_tree);

    window.add(&split_pane);
    window.show_all();
    gtk::main();
}
<commit_msg>Fix iter in example<commit_after>//! # TreeView Sample
//!
//! This sample demonstrates how to create a TreeView with either a ListStore or TreeStore.

#![feature(globs)]
#![crate_type = "bin"]

extern crate rgtk;

use rgtk::*;
use rgtk::gtk::signals;

fn append_text_column(tree: &mut gtk::TreeView) {
    let column = gtk::TreeViewColumn::new().unwrap();
    let cell = gtk::CellRendererText::new().unwrap();
    column.pack_start(&cell, true);
    column.add_attribute(&cell, "text", 0);
    tree.append_column(&column);
}

fn main() {
    gtk::init();

    let mut window = gtk::Window::new(gtk::window_type::TopLevel).unwrap();
    window.set_title("TreeView Sample");
    window.set_window_position(gtk::window_position::Center);

    window.connect(signals::DeleteEvent::new(|_| {
        gtk::main_quit();
        true
    }));

    // left pane

    let mut left_tree = gtk::TreeView::new().unwrap();
    let column_types = [glib::ffi::g_type_string];
    let left_store = gtk::ListStore::new(column_types).unwrap();
    let left_model = left_store.get_model().unwrap();
    left_tree.set_model(&left_model);
    left_tree.set_headers_visible(false);
    append_text_column(&mut left_tree);

    for _ in range(0i, 10i) {
        let iter = gtk::TreeIter::new().unwrap();
        left_store.append(&iter);
        left_store.set_string(&iter, 0, "I'm in a list");
    }

    // right pane

    let mut right_tree = gtk::TreeView::new().unwrap();
    let column_types = [glib::ffi::g_type_string];
    let right_store = gtk::TreeStore::new(column_types).unwrap();
    let right_model = right_store.get_model().unwrap();
    right_tree.set_model(&right_model);
    right_tree.set_headers_visible(false);
    append_text_column(&mut right_tree);

    for _ in range(0i, 10i) {
        let iter = gtk::TreeIter::new().unwrap();
        right_store.append(&iter, None);
        right_store.set_string(&iter, 0, "I'm in a tree");

        let child_iter = gtk::TreeIter::new().unwrap();
        right_store.append(&child_iter, Some(&iter));
        right_store.set_string(&child_iter, 0, "I'm a child node");
    }

    // display the panes

    let mut split_pane = gtk::Box::new(gtk::orientation::Horizontal, 10).unwrap();
    split_pane.set_size_request(-1, -1);
    split_pane.add(&left_tree);
    split_pane.add(&right_tree);

    window.add(&split_pane);
    window.show_all();
    gtk::main();
}
<|endoftext|>


<commit_before><commit_msg>Set 1 challenge 5<commit_after>use super::challenge2::xor_bytes;

pub fn encode(data: &Vec<u8>, key: &Vec<u8>) -> Vec<u8> {
    xor_bytes(data, &key.iter().cloned().cycle().take(data.len()).collect())
}

#[cfg(test)]
mod test {
    use super::super::shared::bytes_to_hex_string;
    use super::encode;

    #[test]
    fn test_encode() {
        let input = b"Burning 'em, if you ain't quick and nimble
I go crazy when I hear a cymbal";
        let output = String::from("0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f");
        assert_eq!(bytes_to_hex_string(&encode(&input.to_vec(), &b"ICE".to_vec())), output);
    }
}
<|endoftext|>


<commit_before><commit_msg>Make does_not_register_rw test use Poll API (#650)<commit_after><|endoftext|>


<commit_before><commit_msg>--amend<commit_after><|endoftext|>


<commit_before><commit_msg>Improve documentation<commit_after><|endoftext|>


<commit_before><commit_msg>things<commit_after>
use std::os;
use std::io::File;

fn main() {
    let args: ~[~str] = os::args();
    if args.len() != 3 {
        println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]);
    } else {
        let share1_file = &args[1];
        let share2_file = &args[2];
        let path1 = Path::new(share1_file.clone());
        let path2 = Path::new(share2_file.clone());
        let msg_file1 = File::open(&path1);
        let msg_file2 = File::open(&path2);

        match (msg_file1, msg_file2) {
            (Some(mut share1), Some(mut share2)) => {
                let msg_bytes1: ~[u8] = share1.read_to_end();
                let msg_bytes2: ~[u8] = share2.read_to_end();
                print!("{:s}", std::str::from_utf8_owned(
                    xor(msg_bytes1, msg_bytes2)));
            } ,
            (_,_) => fail!("Error opening message files")
        }
    }
}

fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
    let mut ret = ~[];
    for i in range(0, a.len()) {
	   ret.push(a[i] ^ b[i]);
    }
    ret
}
<|endoftext|>


<commit_before><commit_msg>Broken code format<commit_after><|endoftext|>


<commit_before>extern crate rusoto_codegen;

use std::env;
use std::path::Path;

use rusoto_codegen::{Service, generate};

/*
gamelift/2015-10-01/service-2.json:    "protocol":"json"
support/2013-04-15/service-2.json:    "protocol":"json"
*/

// expand to use cfg!() so codegen only gets run for services
// in the features list
macro_rules! services {
    ( $( [$name:expr, $date:expr] ),* ) => {
        {
            let mut services = Vec::new();
            $(
                if cfg!(feature = $name) {
                    services.push(Service::new($name, $date));
                }
            )*
            services
        }
    }
}

fn main() {
    let out_dir = env::var_os("OUT_DIR").expect("OUT_DIR not specified");
    let out_path = Path::new(&out_dir);

    let services = services! {
        ["acm", "2015-12-08"],
        ["cloudhsm", "2014-05-30"],
        ["cloudtrail", "2013-11-01"],
        ["codecommit", "2015-04-13"],
        ["codedeploy", "2014-10-06"],
        ["codepipeline", "2015-07-09"],
        ["cognito-identity", "2014-06-30"],
        ["config", "2014-11-12"],
        ["datapipeline", "2012-10-29"],
        ["devicefarm", "2015-06-23"],
        ["directconnect", "2012-10-25"],
        ["ds", "2015-04-16"],
        ["dynamodb", "2012-08-10"],
        ["dynamodbstreams", "2012-08-10"],
        ["ec2", "2015-10-01"],
        ["ecr", "2015-09-21"],
        ["ecs", "2014-11-13"],
        ["elastictranscoder", "2012-09-25"],
        ["emr", "2009-03-31"],
        ["events", "2014-02-03"],
        ["firehose", "2015-08-04"],
        ["inspector", "2016-02-16"],
        ["kinesis", "2013-12-02"],
        ["kms", "2014-11-01"],
        ["logs", "2014-03-28"],
        ["machinelearning", "2014-12-12"],
        ["marketplacecommerceanalytics", "2015-07-01"],
        ["opsworks", "2013-02-18"],
        ["route53domains", "2014-05-15"],
        ["sqs", "2012-11-05"],
        ["ssm", "2014-11-06"],
        ["storagegateway", "2013-06-30"],
        ["swf", "2012-01-25"],
        ["waf", "2015-08-24"],
        ["workspaces", "2015-04-08"]
    };

    for service in services {
        generate(service, out_path);
    }

    println!("cargo:rerun-if-changed=codegen");
}
<commit_msg>don't output the rerun-if-changed condition from the build script if the codegen directory doesn't exist (i.e., if rusoto is packaged as a crates.io dependency)<commit_after>extern crate rusoto_codegen;

use std::env;
use std::path::Path;

use rusoto_codegen::{Service, generate};

/*
gamelift/2015-10-01/service-2.json:    "protocol":"json"
support/2013-04-15/service-2.json:    "protocol":"json"
*/

// expand to use cfg!() so codegen only gets run for services
// in the features list
macro_rules! services {
    ( $( [$name:expr, $date:expr] ),* ) => {
        {
            let mut services = Vec::new();
            $(
                if cfg!(feature = $name) {
                    services.push(Service::new($name, $date));
                }
            )*
            services
        }
    }
}

fn main() {
    let out_dir = env::var_os("OUT_DIR").expect("OUT_DIR not specified");
    let out_path = Path::new(&out_dir);

    let services = services! {
        ["acm", "2015-12-08"],
        ["cloudhsm", "2014-05-30"],
        ["cloudtrail", "2013-11-01"],
        ["codecommit", "2015-04-13"],
        ["codedeploy", "2014-10-06"],
        ["codepipeline", "2015-07-09"],
        ["cognito-identity", "2014-06-30"],
        ["config", "2014-11-12"],
        ["datapipeline", "2012-10-29"],
        ["devicefarm", "2015-06-23"],
        ["directconnect", "2012-10-25"],
        ["ds", "2015-04-16"],
        ["dynamodb", "2012-08-10"],
        ["dynamodbstreams", "2012-08-10"],
        ["ec2", "2015-10-01"],
        ["ecr", "2015-09-21"],
        ["ecs", "2014-11-13"],
        ["elastictranscoder", "2012-09-25"],
        ["emr", "2009-03-31"],
        ["events", "2014-02-03"],
        ["firehose", "2015-08-04"],
        ["inspector", "2016-02-16"],
        ["kinesis", "2013-12-02"],
        ["kms", "2014-11-01"],
        ["logs", "2014-03-28"],
        ["machinelearning", "2014-12-12"],
        ["marketplacecommerceanalytics", "2015-07-01"],
        ["opsworks", "2013-02-18"],
        ["route53domains", "2014-05-15"],
        ["sqs", "2012-11-05"],
        ["ssm", "2014-11-06"],
        ["storagegateway", "2013-06-30"],
        ["swf", "2012-01-25"],
        ["waf", "2015-08-24"],
        ["workspaces", "2015-04-08"]
    };

    for service in services {
        generate(service, out_path);
    }

    let codegen_dir = Path::new("codegen");

    // avoid unnecessary recompiles when used as a crates.io dependency
    if codegen_dir.exists() {
        println!("cargo:rerun-if-changed=codegen");
    }
}
<|endoftext|>


<commit_before><commit_msg>Fixed some documentation in macros.rs<commit_after><|endoftext|>


<commit_before><commit_msg>auto merge of #14788 : Sawyer47/rust/issue-13214, r=huonw<commit_after>// Copyright 2014 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.

// defining static with struct that contains enum
// with &'static str variant used to cause ICE

pub enum Foo {
    Bar,
    Baz(&'static str),
}

pub static TEST: Test = Test {
    foo: Bar,
    c: 'a'
};

pub struct Test {
    foo: Foo,
    c: char,
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Normalize derive order in room_key_requests<commit_after><|endoftext|>


<commit_before><commit_msg>Minor correction to opcode docs<commit_after><|endoftext|>


<commit_before><commit_msg>Fix cd command (#181)<commit_after><|endoftext|>


<commit_before>use std::collections::VecDeque;
use std::env::{set_current_dir, current_dir};
use std::path::PathBuf;
use super::status::{SUCCESS, FAILURE};

pub struct DirectoryStack {
    dirs: VecDeque<PathBuf>, // The top is always the current directory
    max_size: usize,
}

impl DirectoryStack {
    pub fn new() -> Result<DirectoryStack, &'static str> {
        let mut dirs: VecDeque<PathBuf> = VecDeque::new();
        if let Ok(curr_dir) = current_dir() {
            dirs.push_front(curr_dir);
            Ok(DirectoryStack {
                dirs: dirs,
                max_size: 1000, // TODO don't hardcode this size, make it configurable
            })
        } else {
            Err("Failed to get current directory when building directory stack")
        }
    }

    pub fn popd<I: IntoIterator>(&mut self, _: I) -> i32
        where I::Item: AsRef<str>
    {
        if self.dirs.len() < 2 {
            println!("Directory stack is empty");
            return FAILURE;
        }
        if let Some(dir) = self.dirs.get(self.dirs.len() - 2) {
            if let Err(err) = set_current_dir(dir) {
                println!("{}: Failed to switch to directory {}", err, dir.display());
                return FAILURE;
            }
        }
        self.dirs.pop_back();
        self.print_dirs();
        SUCCESS
    }

    pub fn pushd<I: IntoIterator>(&mut self, args: I) -> i32
        where I::Item: AsRef<str>
    {
        self.change_and_push_dir(args);
        self.print_dirs();
        SUCCESS  // TODO determine success from result of change_and_push_dir
                 // I am not doing this at the moment because it will just create
                 // a nasty merge conflict
    }

    pub fn cd<I: IntoIterator>(&mut self, args: I) -> i32
        where I::Item: AsRef<str>
    {
        self.change_and_push_dir(args);
        SUCCESS  // TODO determine success from result of change_and_push_dir
    }

    // TODO the signature for this function doesn't make a lot of sense I did
    // it this way to for ease of use where it is used, however, it should take
    // just one dir instead of args once we add features like `cd -`.
    pub fn change_and_push_dir<I: IntoIterator>(&mut self, args: I)
        where I::Item: AsRef<str>
    {
        if let Some(dir) = args.into_iter().skip(1).next() {
            match (set_current_dir(dir.as_ref()), current_dir()) {
                (Ok(()), Ok(cur_dir)) => {
                    self.push_dir(cur_dir);
                }
                (Err(err), _) => {
                    println!("Failed to set current dir to {}: {}", dir.as_ref(), err);
                    return;
                }
                (_, _) => (),
            }
        } else {
            println!("No directory provided");
            return;
        }
    }

    fn push_dir(&mut self, path: PathBuf) {
        self.dirs.push_front(path);
        self.dirs.truncate(self.max_size);
    }

    pub fn dirs<I: IntoIterator>(&self, _: I) -> i32
        where I::Item: AsRef<str>
    {
        self.print_dirs();
        SUCCESS
    }

    fn print_dirs(&self) {
        let dir = self.dirs.iter().fold(String::new(), |acc, dir| {
            acc + " " + dir.to_str().unwrap_or("No directory found")
        });
        println!("{}", dir.trim_left());
    }
}
<commit_msg>Switch to home directory is not provided<commit_after>use std::collections::VecDeque;
use std::env::{set_current_dir, current_dir, home_dir};
use std::path::PathBuf;
use super::status::{SUCCESS, FAILURE};

pub struct DirectoryStack {
    dirs: VecDeque<PathBuf>, // The top is always the current directory
    max_size: usize,
}

impl DirectoryStack {
    pub fn new() -> Result<DirectoryStack, &'static str> {
        let mut dirs: VecDeque<PathBuf> = VecDeque::new();
        if let Ok(curr_dir) = current_dir() {
            dirs.push_front(curr_dir);
            Ok(DirectoryStack {
                dirs: dirs,
                max_size: 1000, // TODO don't hardcode this size, make it configurable
            })
        } else {
            Err("Failed to get current directory when building directory stack")
        }
    }

    pub fn popd<I: IntoIterator>(&mut self, _: I) -> i32
        where I::Item: AsRef<str>
    {
        if self.dirs.len() < 2 {
            println!("Directory stack is empty");
            return FAILURE;
        }
        if let Some(dir) = self.dirs.get(self.dirs.len() - 2) {
            if let Err(err) = set_current_dir(dir) {
                println!("{}: Failed to switch to directory {}", err, dir.display());
                return FAILURE;
            }
        }
        self.dirs.pop_back();
        self.print_dirs();
        SUCCESS
    }

    pub fn pushd<I: IntoIterator>(&mut self, args: I) -> i32
        where I::Item: AsRef<str>
    {
        if let Some(dir) = args.into_iter().nth(1) {
            let result = self.change_and_push_dir(dir.as_ref());
            self.print_dirs();
            result
        } else {
            println!("No directory provided");
            FAILURE
        }
    }

    pub fn cd<I: IntoIterator>(&mut self, args: I) -> i32
        where I::Item: AsRef<str>
    {
        if let Some(dir) = args.into_iter().nth(1) {
            let dir = dir.as_ref();
            self.change_and_push_dir(dir)
        } else {
            if let Some(home) = home_dir() {
                if let Some(home) = home.to_str() {
                    self.change_and_push_dir(home)
                } else {
                    println!("Failed to convert home directory to str");
                    FAILURE
                }
            } else {
                println!("Failed to get home directory");
                FAILURE
            }
        }
    }

    pub fn change_and_push_dir(&mut self, dir: &str) -> i32
    {
        match (set_current_dir(dir), current_dir()) {
            (Ok(()), Ok(cur_dir)) => {
                self.push_dir(cur_dir);
                SUCCESS
            }
            (Err(err), _) => {
                println!("Failed to set current dir to {}: {}", dir, err);
                FAILURE
            }
            (_, _) => FAILURE // This should not happen
        }
    }

    fn push_dir(&mut self, path: PathBuf) {
        self.dirs.push_front(path);
        self.dirs.truncate(self.max_size);
    }

    pub fn dirs<I: IntoIterator>(&self, _: I) -> i32
        where I::Item: AsRef<str>
    {
        self.print_dirs();
        SUCCESS
    }

    fn print_dirs(&self) {
        let dir = self.dirs.iter().fold(String::new(), |acc, dir| {
            acc + " " + dir.to_str().unwrap_or("No directory found")
        });
        println!("{}", dir.trim_left());
    }
}
<|endoftext|>


<commit_before><commit_msg>Use resiter::IterInnerOkOrElse instead of libimagerror version<commit_after><|endoftext|>


<commit_before>// Copyright 2013 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.

//! Useful synchronization primitives
//!
//! This modules contains useful safe and unsafe synchronization primitives.
//! Most of the primitives in this module do not provide any sort of locking
//! and/or blocking at all, but rather provide the necessary tools to build
//! other types of concurrent primitives.

#![experimental]

#[stable]
pub use core_sync::atomic;

pub use core_sync::{deque, mpmc_bounded_queue, mpsc_queue, spsc_queue};
pub use core_sync::{Arc, Weak, Mutex, MutexGuard, Condvar, Barrier};
pub use core_sync::{RWLock, RWLockReadGuard, RWLockWriteGuard};
pub use core_sync::{Semaphore, SemaphoreGuard};
pub use core_sync::one::{Once, ONCE_INIT};

#[deprecated = "use atomic instead"]
pub use atomics = core_sync::atomic;

pub use self::future::Future;
pub use self::task_pool::TaskPool;

mod future;
mod task_pool;
<commit_msg>auto merge of #16327 : mdinger/rust/typo, r=steveklabnik<commit_after>// Copyright 2013 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.

//! Useful synchronization primitives
//!
//! This module contains useful safe and unsafe synchronization primitives.
//! Most of the primitives in this module do not provide any sort of locking
//! and/or blocking at all, but rather provide the necessary tools to build
//! other types of concurrent primitives.

#![experimental]

#[stable]
pub use core_sync::atomic;

pub use core_sync::{deque, mpmc_bounded_queue, mpsc_queue, spsc_queue};
pub use core_sync::{Arc, Weak, Mutex, MutexGuard, Condvar, Barrier};
pub use core_sync::{RWLock, RWLockReadGuard, RWLockWriteGuard};
pub use core_sync::{Semaphore, SemaphoreGuard};
pub use core_sync::one::{Once, ONCE_INIT};

#[deprecated = "use atomic instead"]
pub use atomics = core_sync::atomic;

pub use self::future::Future;
pub use self::task_pool::TaskPool;

mod future;
mod task_pool;
<|endoftext|>


<commit_before><commit_msg>regression test for #38821<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.

pub struct Nullable<T: NotNull>(T);

pub trait NotNull {}

pub trait IntoNullable {
    type Nullable;
}

impl<T: NotNull> IntoNullable for T {
    type Nullable = Nullable<T>;
}

impl<T: NotNull> IntoNullable for Nullable<T> {
    type Nullable = Nullable<T>;
}

pub trait Expression {
    type SqlType;
}

pub trait Column: Expression {}

#[derive(Debug, Copy, Clone)]
//~^ ERROR the trait bound `<Col as Expression>::SqlType: NotNull` is not satisfied
pub enum ColumnInsertValue<Col, Expr> where
    Col: Column,
    Expr: Expression<SqlType=<Col::SqlType as IntoNullable>::Nullable>,
{
    Expression(Col, Expr),
    Default(Col),
}

fn main() {}
<|endoftext|>


<commit_before>// Copyright 2012-2016 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.

// compile-flags: -Z emit-end-regions -Z borrowck-mir

fn guard() -> bool {
    false
}

fn guard2(_:i32) -> bool {
    true
}

fn full_tested_match() {
    let _ = match Some(42) {
        Some(x) if guard() => 1 + x,
        Some(y) => 2 + y,
        None => 3,
    };
}

fn full_tested_match2() {
    let _ = match Some(42) {
        Some(x) if guard() => 1 + x,
        None => 3,
        Some(y) => 2 + y,
    };
}

fn main() {
    let _ = match Some(1) {
        Some(_w) if guard() => 1,
        _x => 2,
        Some(y) if guard2(y) => 3,
        _z => 4,
    };
}

// END RUST SOURCE
//
// START rustc.node17.NLL.before.mir
//  bb0: {
//      ...
//      _2 = std::option::Option<i32>::Some(const 42i32,);
//      _5 = discriminant(_2);
//      switchInt(_5) -> [0isize: bb5, otherwise: bb3];
//  }
//  bb1: { // arm1
//      StorageLive(_7);
//      _7 = _3;
//      _1 = Add(const 1i32, _7);
//      ...
//      goto -> bb11;
//  }
//  bb2: { // binding3(empty) and arm3
//      _1 = const 3i32;
//      goto -> bb11;
//  }
//  bb3: {
//      falseEdges -> [real: bb7, imaginary: bb4]; //pre_binding1
//  }
//  bb4: {
//      falseEdges -> [real: bb10, imaginary: bb5]; //pre_binding2
//  }
//  bb5: {
//      falseEdges -> [real: bb2, imaginary: bb6]; //pre_binding3
//  }
//  bb6: {
//      unreachable;
//  }
//  bb7: { // binding1 and guard
//      StorageLive(_3);
//      _3 = ((_2 as Some).0: i32);
//      StorageLive(_6);
//      _6 = const guard() -> bb8;
//  }
//  bb8: { // end of guard
//      switchInt(_6) -> [0u8: bb9, otherwise: bb1];
//  }
//  bb9: { // to pre_binding2
//      falseEdges -> [real: bb4, imaginary: bb4];
//  }
//  bb10: { // binding2 and arm2
//      StorageLive(_4);
//      _4 = ((_2 as Some).0: i32);
//      StorageLive(_8);
//      _8 = _4;
//      _1 = Add(const 2i32, _8);
//      StorageDead(_8);
//      goto -> bb11;
//  }
//  bb11: {
//      ...
//      return;
//  }
// END rustc.node17.NLL.before.mir
//
// START rustc.node40.NLL.before.mir
//  bb0: {
//      ...
//      _2 = std::option::Option<i32>::Some(const 42i32,);
//      _5 = discriminant(_2);
//      switchInt(_5) -> [0isize: bb4, otherwise: bb3];
//  }
//  bb1: { // arm1
//      StorageLive(_7);
//      _7 = _3;
//      _1 = Add(const 1i32, _7);
//      ...
//      goto -> bb11;
//  }
//  bb2: { // binding3(empty) and arm3
//      _1 = const 3i32;
//      goto -> bb11;
//  }
//  bb3: {
//      falseEdges -> [real: bb7, imaginary: bb4]; //pre_binding1
//  }
//  bb4: {
//      falseEdges -> [real: bb2, imaginary: bb5]; //pre_binding2
//  }
//  bb5: {
//      falseEdges -> [real: bb10, imaginary: bb6]; //pre_binding3
//  }
//  bb6: {
//      unreachable;
//  }
//  bb7: { // binding1 and guard
//      StorageLive(_3);
//      _3 = ((_2 as Some).0: i32);
//      StorageLive(_6);
//      _6 = const guard() -> bb8;
//  }
//  bb8: { // end of guard
//      switchInt(_6) -> [0u8: bb9, otherwise: bb1];
//  }
//  bb9: { // to pre_binding2
//      falseEdges -> [real: bb5, imaginary: bb4];
//  }
//  bb10: { // binding2 and arm2
//      StorageLive(_4);
//      _4 = ((_2 as Some).0: i32);
//      StorageLive(_8);
//      _8 = _4;
//      _1 = Add(const 2i32, _8);
//      StorageDead(_8);
//      goto -> bb11;
//  }
//  bb11: {
//      ...
//      return;
//  }
// END rustc.node40.NLL.before.mir
//
// START rustc.node63.NLL.before.mir
// bb0: {
//     ...
//     _2 = std::option::Option<i32>::Some(const 1i32,);
//     _7 = discriminant(_2);
//     switchInt(_7) -> [1isize: bb3, otherwise: bb4];
// }
// bb1: { // arm1
//      _1 = const 1i32;
//      goto -> bb16;
// }
// bb2: { // arm3
//     _1 = const 3i32;
//      goto -> bb16;
// }
//
//  bb3: {
//      falseEdges -> [real: bb8, imaginary: bb4]; //pre_binding1
//  }
//  bb4: {
//      falseEdges -> [real: bb11, imaginary: bb5]; //pre_binding2
//  }
//  bb5: {
//      falseEdges -> [real: bb12, imaginary: bb6]; //pre_binding3
//  }
//  bb6: {
//      falseEdges -> [real: bb15, imaginary: bb7]; //pre_binding4
//  }
//  bb7: {
//      unreachable;
//  }
//  bb8: { // binding1: Some(w) if guard()
//      StorageLive(_3);
//      _3 = ((_2 as Some).0: i32);
//      StorageLive(_8);
//      _8 = const guard() -> bb9;
//  }
//  bb9: { //end of guard
//      switchInt(_8) -> [0u8: bb10, otherwise: bb1];
//  }
//  bb10: { // to pre_binding2
//      falseEdges -> [real: bb4, imaginary: bb4];
//  }
//  bb11: { // binding2 & arm2
//      StorageLive(_4);
//      _4 = _2;
//      _1 = const 2i32;
//      goto -> bb16;
//  }
//  bb12: { // binding3: Some(y) if guard2(y)
//      StorageLive(_5);
//      _5 = ((_2 as Some).0: i32);
//      StorageLive(_10);
//      StorageLive(_11);
//      _11 = _5;
//      _10 = const guard2(_11) -> bb13;
//  }
//  bb13: { // end of guard2
//      StorageDead(_11);
//      switchInt(_10) -> [0u8: bb14, otherwise: bb2];
//  }
//  bb14: { // to pre_binding4
//      falseEdges -> [real: bb6, imaginary: bb6];
//  }
//  bb15: { // binding4 & arm4
//      StorageLive(_6);
//      _6 = _2;
//      _1 = const 4i32;
//      goto -> bb16;
//  }
// bb16: {
//     ...
//     return;
// }
// END rustc.node63.NLL.before.mir
<commit_msg>change mir stage in test<commit_after>// Copyright 2012-2016 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.

// compile-flags: -Z emit-end-regions -Z borrowck-mir

fn guard() -> bool {
    false
}

fn guard2(_:i32) -> bool {
    true
}

fn full_tested_match() {
    let _ = match Some(42) {
        Some(x) if guard() => 1 + x,
        Some(y) => 2 + y,
        None => 3,
    };
}

fn full_tested_match2() {
    let _ = match Some(42) {
        Some(x) if guard() => 1 + x,
        None => 3,
        Some(y) => 2 + y,
    };
}

fn main() {
    let _ = match Some(1) {
        Some(_w) if guard() => 1,
        _x => 2,
        Some(y) if guard2(y) => 3,
        _z => 4,
    };
}

// END RUST SOURCE
//
// START rustc.node17.SimplifyBranches-initial.before.mir
//  bb0: {
//      ...
//      _2 = std::option::Option<i32>::Some(const 42i32,);
//      _5 = discriminant(_2);
//      switchInt(_5) -> [0isize: bb5, otherwise: bb3];
//  }
//  bb1: { // arm1
//      StorageLive(_7);
//      _7 = _3;
//      _1 = Add(const 1i32, _7);
//      ...
//      goto -> bb11;
//  }
//  bb2: { // binding3(empty) and arm3
//      _1 = const 3i32;
//      goto -> bb11;
//  }
//  bb3: {
//      falseEdges -> [real: bb7, imaginary: bb4]; //pre_binding1
//  }
//  bb4: {
//      falseEdges -> [real: bb10, imaginary: bb5]; //pre_binding2
//  }
//  bb5: {
//      falseEdges -> [real: bb2, imaginary: bb6]; //pre_binding3
//  }
//  bb6: {
//      unreachable;
//  }
//  bb7: { // binding1 and guard
//      StorageLive(_3);
//      _3 = ((_2 as Some).0: i32);
//      StorageLive(_6);
//      _6 = const guard() -> bb8;
//  }
//  bb8: { // end of guard
//      switchInt(_6) -> [0u8: bb9, otherwise: bb1];
//  }
//  bb9: { // to pre_binding2
//      falseEdges -> [real: bb4, imaginary: bb4];
//  }
//  bb10: { // bindingNoLandingPads.before.mir2 and arm2
//      StorageLive(_4);
//      _4 = ((_2 as Some).0: i32);
//      StorageLive(_8);
//      _8 = _4;
//      _1 = Add(const 2i32, _8);
//      StorageDead(_8);
//      goto -> bb11;
//  }
//  bb11: {
//      ...
//      return;
//  }
// END rustc.node17.SimplifyBranches-initial.before.mir
//
// START rustc.node40.SimplifyBranches-initial.before.mir
//  bb0: {
//      ...
//      _2 = std::option::Option<i32>::Some(const 42i32,);
//      _5 = discriminant(_2);
//      switchInt(_5) -> [0isize: bb4, otherwise: bb3];
//  }
//  bb1: { // arm1
//      StorageLive(_7);
//      _7 = _3;
//      _1 = Add(const 1i32, _7);
//      ...
//      goto -> bb11;
//  }
//  bb2: { // binding3(empty) and arm3
//      _1 = const 3i32;
//      goto -> bb11;
//  }
//  bb3: {
//      falseEdges -> [real: bb7, imaginary: bb4]; //pre_binding1
//  }
//  bb4: {
//      falseEdges -> [real: bb2, imaginary: bb5]; //pre_binding2
//  }
//  bb5: {
//      falseEdges -> [real: bb10, imaginary: bb6]; //pre_binding3
//  }
//  bb6: {
//      unreachable;
//  }
//  bb7: { // binding1 and guard
//      StorageLive(_3);
//      _3 = ((_2 as Some).0: i32);
//      StorageLive(_6);
//      _6 = const guard() -> bb8;
//  }
//  bb8: { // end of guard
//      switchInt(_6) -> [0u8: bb9, otherwise: bb1];
//  }
//  bb9: { // to pre_binding2
//      falseEdges -> [real: bb5, imaginary: bb4];
//  }
//  bb10: { // binding2 and arm2
//      StorageLive(_4);
//      _4 = ((_2 as Some).0: i32);
//      StorageLive(_8);
//      _8 = _4;
//      _1 = Add(const 2i32, _8);
//      StorageDead(_8);
//      goto -> bb11;
//  }
//  bb11: {
//      ...
//      return;
//  }
// END rustc.node40.SimplifyBranches-initial.before.mir
//
// START rustc.node63.SimplifyBranches-initial.before.mir
// bb0: {
//     ...
//     _2 = std::option::Option<i32>::Some(const 1i32,);
//     _7 = discriminant(_2);
//     switchInt(_7) -> [1isize: bb3, otherwise: bb4];
// }
// bb1: { // arm1
//      _1 = const 1i32;
//      goto -> bb16;
// }
// bb2: { // arm3
//     _1 = const 3i32;
//      goto -> bb16;
// }
//
//  bb3: {
//      falseEdges -> [real: bb8, imaginary: bb4]; //pre_binding1
//  }
//  bb4: {
//      falseEdges -> [real: bb11, imaginary: bb5]; //pre_binding2
//  }
//  bb5: {
//      falseEdges -> [real: bb12, imaginary: bb6]; //pre_binding3
//  }
//  bb6: {
//      falseEdges -> [real: bb15, imaginary: bb7]; //pre_binding4
//  }
//  bb7: {
//      unreachable;
//  }
//  bb8: { // binding1: Some(w) if guard()
//      StorageLive(_3);
//      _3 = ((_2 as Some).0: i32);
//      StorageLive(_8);
//      _8 = const guard() -> bb9;
//  }
//  bb9: { //end of guard
//      switchInt(_8) -> [0u8: bb10, otherwise: bb1];
//  }
//  bb10: { // to pre_binding2
//      falseEdges -> [real: bb4, imaginary: bb4];
//  }
//  bb11: { // binding2 & arm2
//      StorageLive(_4);
//      _4 = _2;
//      _1 = const 2i32;
//      goto -> bb16;
//  }
//  bb12: { // binding3: Some(y) if guard2(y)
//      StorageLive(_5);
//      _5 = ((_2 as Some).0: i32);
//      StorageLive(_10);
//      StorageLive(_11);
//      _11 = _5;
//      _10 = const guard2(_11) -> bb13;
//  }
//  bb13: { // end of guard2
//      StorageDead(_11);
//      switchInt(_10) -> [0u8: bb14, otherwise: bb2];
//  }
//  bb14: { // to pre_binding4
//      falseEdges -> [real: bb6, imaginary: bb6];
//  }
//  bb15: { // binding4 & arm4
//      StorageLive(_6);
//      _6 = _2;
//      _1 = const 4i32;
//      goto -> bb16;
//  }
// bb16: {
//     ...
//     return;
// }
// END rustc.node63.SimplifyBranches-initial.before.mir
<|endoftext|>


<commit_before><commit_msg>Add code for short-fibonacci<commit_after>/// Create an empty vector
pub fn create_empty() -> Vec<u8> {
    vec![]
}

/// Create a buffer of `count` zeroes.
///
/// Applications often use buffers when serializing data to send over the network.
pub fn create_buffer(count: usize) -> Vec<u8> {
    vec![0; count]
}

/// Create a vector containing the first five elements of the Fibonacci sequence.
///
/// Fibonacci's sequence is the list of numbers where the next number is a sum of the previous two.
/// Its first five elements are `1, 1, 2, 3, 5`.
pub fn fibonacci() -> Vec<u8> {
    vec![1, 1, 2, 3, 5]
}
<|endoftext|>


<commit_before>use std::io::stdout;
use std::io::Write;

use lister::Lister;
use result::Result;

use libimagstore::store::FileLockEntry;
use libimagutil::iter::FoldResult;

pub struct PathLister {
    absolute: bool,
}

impl PathLister {

    pub fn new(absolute: bool) -> PathLister {
        PathLister {
            absolute: absolute,
        }
    }

}

impl Lister for PathLister {

    fn list<'a, I: Iterator<Item = FileLockEntry<'a>>>(&self, entries: I) -> Result<()> {
        use error::ListError as LE;
        use error::ListErrorKind as LEK;
        use std::path::PathBuf;

        entries.fold_defresult(|entry| {
            Ok(entry.get_location().clone())
                .and_then(|pb| {
                    let pb : PathBuf = pb.into();
                    if self.absolute {
                        pb.canonicalize().map_err(|e| LE::new(LEK::FormatError, Some(Box::new(e))))
                    } else {
                        Ok(pb.into())
                    }
                })
                .and_then(|pb| {
                    write!(stdout(), "{:?}\n", pb)
                        .map_err(|e| LE::new(LEK::FormatError, Some(Box::new(e))))
                })
                .map_err(|e| {
                    if e.err_type() == LEK::FormatError {
                        e
                    } else {
                        LE::new(LEK::FormatError, Some(Box::new(e)))
                    }
                })
            })
    }

}

<commit_msg>Use StoreId::into_pathbuf() rather than ::into()<commit_after>use std::io::stdout;
use std::io::Write;

use lister::Lister;
use result::Result;
use error::MapErrInto;

use libimagstore::store::FileLockEntry;
use libimagutil::iter::FoldResult;

pub struct PathLister {
    absolute: bool,
}

impl PathLister {

    pub fn new(absolute: bool) -> PathLister {
        PathLister {
            absolute: absolute,
        }
    }

}

impl Lister for PathLister {

    fn list<'a, I: Iterator<Item = FileLockEntry<'a>>>(&self, entries: I) -> Result<()> {
        use error::ListError as LE;
        use error::ListErrorKind as LEK;

        entries.fold_defresult(|entry| {
            Ok(entry.get_location().clone())
                .and_then(|pb| pb.into_pathbuf().map_err_into(LEK::FormatError))
                .and_then(|pb| {
                    if self.absolute {
                        pb.canonicalize().map_err(|e| LE::new(LEK::FormatError, Some(Box::new(e))))
                    } else {
                        Ok(pb.into())
                    }
                })
                .and_then(|pb| {
                    write!(stdout(), "{:?}\n", pb)
                        .map_err(|e| LE::new(LEK::FormatError, Some(Box::new(e))))
                })
                .map_err(|e| {
                    if e.err_type() == LEK::FormatError {
                        e
                    } else {
                        LE::new(LEK::FormatError, Some(Box::new(e)))
                    }
                })
            })
    }

}

<|endoftext|>


<commit_before><commit_msg>day 15, part 1<commit_after>#![feature(iter_arith)]
trait Ingredient {
    fn capacity() -> i64;
    fn durability() -> i64;
    fn flavor() -> i64;
    fn texture() -> i64;
    fn calories() -> i64;
}

struct Sprinkles;
struct PeanutButter;
struct Frosting;
struct Sugar;

// just gonna hard code this stuff
impl Ingredient for Sprinkles {
    fn capacity() -> i64 { 5 }
    fn durability() -> i64 { -1 }
    fn flavor() -> i64 { 0 }
    fn texture() -> i64 { 0 }
    fn calories() -> i64 { 5 }
}
impl Ingredient for PeanutButter {
    fn capacity() -> i64 { -1 }
    fn durability() -> i64 { 3 }
    fn flavor() -> i64 { 0 }
    fn texture() -> i64 { 0 }
    fn calories() -> i64 { 1 }
}
impl Ingredient for Frosting {
    fn capacity() -> i64 { 0 }
    fn durability() -> i64 { -1 }
    fn flavor() -> i64 { 4 }
    fn texture() -> i64 { 0 }
    fn calories() -> i64 { 6 }
}
impl Ingredient for Sugar {
    fn capacity() -> i64 { -1 }
    fn durability() -> i64 { 0 }
    fn flavor() -> i64 { 0 }
    fn texture() -> i64 { 2 }
    fn calories() -> i64 { 8 }
}

fn capacity(sprinkles: i64, peanut_butter: i64, frosting: i64, sugar: i64) -> i64 {
    Sprinkles::capacity() * sprinkles +
        PeanutButter::capacity() * peanut_butter +
        Frosting::capacity() * frosting +
        Sugar::capacity() * sugar
}
fn durability(sprinkles: i64, peanut_butter: i64, frosting: i64, sugar: i64) -> i64 {
    Sprinkles::durability() * sprinkles +
        PeanutButter::durability() * peanut_butter +
        Frosting::durability() * frosting +
        Sugar::durability() * sugar
}
fn flavor(sprinkles: i64, peanut_butter: i64, frosting: i64, sugar: i64) -> i64 {
    Sprinkles::flavor() * sprinkles +
        PeanutButter::flavor() * peanut_butter +
        Frosting::flavor() * frosting +
        Sugar::flavor() * sugar
}
fn texture(sprinkles: i64, peanut_butter: i64, frosting: i64, sugar: i64) -> i64 {
    Sprinkles::texture() * sprinkles +
        PeanutButter::texture() * peanut_butter +
        Frosting::texture() * frosting +
        Sugar::texture() * sugar
}
fn calories(sprinkles: i64, peanut_butter: i64, frosting: i64, sugar: i64) -> i64 {
    Sprinkles::calories() * sprinkles +
        PeanutButter::calories() * peanut_butter +
        Frosting::calories() * frosting +
        Sugar::calories() * sugar
}

fn score(sprinkles: i64, peanut_butter: i64, frosting: i64, sugar: i64) -> i64 {
    let amounts = vec![
        capacity(sprinkles, peanut_butter, frosting, sugar),
        durability(sprinkles, peanut_butter, frosting, sugar),
        flavor(sprinkles, peanut_butter, frosting, sugar),
        texture(sprinkles, peanut_butter, frosting, sugar),
    ];
    if amounts.iter().any(|v| *v < 0) {
        0
    } else {
        amounts.iter().product()
    }
}

fn main() {
    let mut bs = None;
    let mut best = (25, 25, 25, 25);
    for sprinkles in (0..101) {
        for pb in (0..101) {
            for frosting in (0..101) {
                for sugar in (0..101) {
                    if sprinkles + pb + frosting + sugar == 100 {
                        let this_score = score(sprinkles, pb, frosting, sugar);
                        if bs.is_none() || bs.unwrap() < this_score {
                            bs = Some(this_score);
                            best = (sprinkles, pb, frosting, sugar);
                        }
                    }
                }
            }
        }
    }
    println!("({}, {}, {}, {}): {}",
        best.0, best.1, best.2, best.3, bs.unwrap());
}
<|endoftext|>


<commit_before><commit_msg>Disallow watch after multi<commit_after><|endoftext|>


<commit_before><commit_msg>Add example for multiple simultaneous examples<commit_after>extern crate init = "gl-init-rs";
extern crate libc;
extern crate gl;

fn main() {
    let window1 = init::Window::new().unwrap();
    let window2 = init::Window::new().unwrap();

    spawn(proc() {
        run(window1, (0.0, 1.0, 0.0, 1.0));
    });

    spawn(proc() {
        run(window2, (0.0, 0.0, 1.0, 1.0));
    });
}

fn run(window: init::Window, color: (f32, f32, f32, f32)) {
    unsafe { window.make_current() };

    gl::load_with(|symbol| window.get_proc_address(symbol) as *const libc::c_void);

    gl::ClearColor(color.val0(), color.val1(), color.val2(), color.val3());

    while !window.is_closed() {
       window.wait_events().collect::<Vec<init::Event>>();

        gl::Clear(gl::COLOR_BUFFER_BIT);

        window.swap_buffers();
    }
}
<|endoftext|>


<commit_before><commit_msg>[WIP]<commit_after>//! ```cargo
//! [dependencies]
//! ar = "0.6.2"
//! ```

use std::io::Read;

// 64 gives Invalid file size field in entry header
// 32 gives unexpected EOF in the middle of archive entry header
const METADATA_LEN: usize = 64;

fn main() {
    let mut builder = ar::Builder::new(std::fs::File::create("test.a").expect("create"));

    // Remove this append and there is no problem.
    let header = ar::Header::new(b"core-fc675.rcgu.o".to_vec(), 0);
    // Remove any of the characters in the filename and ! from will show up in the error message.
    // Making it shorter than 17 chars will fix the problem though.

    builder.append(&header, &mut (&[] as &[u8])).expect("add rcgu");

    let mut buf: Vec<u8> = vec!['!' as u8; 28];
    buf.extend(b"hello worl");
    buf.extend(&['*' as u8; 26] as &[u8]);
    assert!(buf.len() >= METADATA_LEN);

    let header = ar::Header::new(b"rust.metadata.bin".to_vec(), METADATA_LEN as u64);
    builder.append(&header, &mut (&buf[0..METADATA_LEN])).expect("add meta");

    std::mem::drop(builder);

    // Remove this ranlib invocation and there is no problem.
    /*assert!(
        std::process::Command::new("ranlib")
            .arg("test.a")
            .status()
            .expect("Couldn't run ranlib")
            .success()
    );*/

    let mut archive = ar::Archive::new(std::fs::File::open("test.a").expect("open"));
    while let Some(entry) = archive.next_entry() {
        entry.unwrap();
    }
}
<|endoftext|>


<commit_before><commit_msg>Add a simple main expression parser<commit_after>// Such imports are used to allow for the expr_literal macro to work
use parser::number::numeric_literal;
use parser::identifier::identifier_literal;
use ast::Expression;

// Temp do bad stuff
named!(pub expr_literal<Expression>,
    alt!(numeric_literal | identifier_literal)
);<|endoftext|>