<commit_before>#![deny(warnings)]

extern crate orbtk;

use orbtk::{Button, Point, Rect, TextBox, Window};
use orbtk::callback::{Click, Enter};
use orbtk::place::Place;

#[derive(Debug, Clone)]
pub enum Token {
    Plus,
    Minus,
    Divide,
    Multiply,
    Exponent,
    OpenParen,
    CloseParen,
    Number(String),
}

impl Token {
    pub fn to_str(&self) -> &'static str {
        match self {
            &Token::Plus       => "Plus",
            &Token::Minus      => "Minus",
            &Token::Divide     => "Divide",
            &Token::Multiply   => "Multiply",
            &Token::Exponent   => "Exponent",
            &Token::OpenParen  => "OpenParen",
            &Token::CloseParen => "CloseParen",
            &Token::Number(_)  => "Number",
        }
    }

    pub fn to_string(&self) -> String {
        self.to_str().to_owned()
    }
}

#[derive(Debug,  Clone)]
pub enum ParseError {
    InvalidNumber(String),
    UnrecognizedToken(String),
    UnexpectedToken(String, &'static str),
    UnexpectedEndOfInput,
    OtherError(String),
}

#[derive(Clone,Debug)]
pub struct IntermediateResult {
    value: f64,
    tokens_read: usize,
}

impl IntermediateResult {
    fn new(value: f64, tokens_read: usize) -> Self {
        IntermediateResult {
            value: value,
            tokens_read: tokens_read,
        }
    }
}

pub trait OperatorFunctions {
    fn is_operator(self) -> bool;
    fn operator_type(self) -> Token;
}

impl OperatorFunctions for char {
    fn is_operator(self) -> bool {
        self == '+' ||
        self == '-' ||
        self == '*' ||
        self == '/' ||
        self == '^' ||
        self == '(' ||
        self == ')'
    }

    fn operator_type(self) -> Token {
        match self {
            '+' => Token::Plus,
            '-' => Token::Minus,
            '/' => Token::Divide,
            '*' => Token::Multiply,
            '^' => Token::Exponent,
            '(' => Token::OpenParen,
            ')' => Token::CloseParen,
            _   => panic!("Invalid operator")
        }
    }
}

pub fn tokenize(input: &str) -> Result<Vec<Token>, ParseError> {
    // CONSIDER: input.len() too generous?
    let mut tokens = Vec::with_capacity(input.len());

    // TODO: Not this. Modify to use iterator
    let chars: Vec<char> = input.chars().collect();

    let input_length = chars.len();
    let mut current_pos = 0;
    while current_pos < input_length {
        let c = chars[current_pos];
        if c.is_digit(10) {
            let token_string = consume_number(&chars[current_pos..]);
            current_pos += token_string.len();
            tokens.push(Token::Number(token_string));
        } else if c.is_operator() {
            tokens.push(c.operator_type());
            current_pos += 1;
        } else if c.is_whitespace() {
            current_pos += 1;
        } else {
            let token_string = consume_until_new_token(&chars[current_pos..]);
            return Err(ParseError::UnrecognizedToken(token_string));
        }
    }
    Ok(tokens)
}

fn consume_number(input: &[char]) -> String {
    // CONSIDER: input.len seems a bit generous
    let mut number = String::with_capacity(input.len());
    let mut has_decimal_point = false;
    for &c in input {
        if c == '.' {
            if has_decimal_point {
                break;
            } else {
                number.push(c);
                has_decimal_point = true;
            }
        } else if c.is_digit(10) {
            number.push(c);
        } else {
            break;
        }
    }
    number
}

fn consume_until_new_token(input: &[char]) -> String {
    input.iter()
         .take_while(|c| !(c.is_whitespace() || c.is_operator() || c.is_digit(10)))
         .map(|&c| c)
         .collect()
}

// Addition and subtraction
pub fn e_expr(token_list: &[Token]) -> Result<IntermediateResult, ParseError> {
    let mut t1 = try!(t_expr(token_list));
    let mut index = t1.tokens_read;

    while index < token_list.len() {
        match token_list[index] {
            Token::Plus => {
                let t2 = try!(t_expr(&token_list[index+1..]));
                t1.value += t2.value;
                t1.tokens_read += t2.tokens_read + 1;
            }
            Token::Minus => {
                let t2 = try!(t_expr(&token_list[index+1..]));
                t1.value -= t2.value;
                t1.tokens_read += t2.tokens_read + 1;
            }
            Token::Number(ref n) => return Err(ParseError::UnexpectedToken(n.clone(),"operator")),
            _ => break,
        };
        index = t1.tokens_read;
    }
    Ok(t1)
}

// Multiplication and division
pub fn t_expr(token_list: &[Token]) -> Result<IntermediateResult, ParseError> {
    let mut f1 = try!(f_expr(token_list));
    let mut index = f1.tokens_read;

    while index < token_list.len() {
        match token_list[index] {
            Token::Multiply => {
                let f2 = try!(f_expr(&token_list[index+1..]));
                f1.value *= f2.value;
                f1.tokens_read += f2.tokens_read + 1;
            }
            Token::Divide => {
                let f2 = try!(f_expr(&token_list[index+1..]));
                if f2.value == 0.0 {
                    return Err(ParseError::OtherError("Divide by zero error".to_owned()));
                } else {
                    f1.value /= f2.value;
                    f1.tokens_read += f2.tokens_read + 1;
                }
            }
            Token::Number(ref n) => return Err(ParseError::UnexpectedToken(n.clone(),"operator")),
            _ => break,
        }
        index = f1.tokens_read;
    }
    Ok(f1)
}

// Exponentiation
pub fn f_expr(token_list: &[Token]) -> Result<IntermediateResult, ParseError> {
    let mut g1 = try!(g_expr(token_list));
    let mut index = g1.tokens_read;
    let token_len = token_list.len();
    while index < token_len {
        match token_list[index] {
            Token::Exponent => {
                let f = try!(f_expr(&token_list[index+1..]));
                g1.value = g1.value.powf(f.value);
                g1.tokens_read += f.tokens_read + 1;
            }
            Token::Number(ref n) => return Err(ParseError::UnexpectedToken(n.clone(),"operator")),
            _ => break,
        }
        index = g1.tokens_read;
    }
    Ok(g1)
}

// Numbers and parenthesized expressions
pub fn g_expr(token_list: &[Token]) -> Result<IntermediateResult, ParseError> {
    if !token_list.is_empty() {
        match token_list[0] {
            Token::Number(ref n) => {
                n.parse::<f64>()
                 .map_err(|_| ParseError::InvalidNumber(n.clone()))
                 .and_then(|num| Ok(IntermediateResult::new(num, 1)))
            }
            Token::Minus => {
                if token_list.len() > 1 {
                    if let Token::Number(ref n) = token_list[1] {
                        n.parse::<f64>()
                         .map_err(|_| ParseError::InvalidNumber(n.clone()))
                         .and_then(|num| Ok(IntermediateResult::new(-1.0 * num, 2)))
                    } else {
                        Err(ParseError::UnexpectedToken(token_list[1].to_string(), "number"))
                    }
                } else {
                    Err(ParseError::UnexpectedEndOfInput)
                }
            }
            Token::OpenParen => {
                let expr = e_expr(&token_list[1..]);
                match expr {
                    Ok(ir) => {
                        let close_paren = ir.tokens_read + 1;
                        if close_paren < token_list.len() {
                            match token_list[close_paren] {
                                Token::CloseParen => Ok(IntermediateResult::new(ir.value, close_paren+1)),
                                _ => Err(ParseError::UnexpectedToken(token_list[close_paren].to_string(), ")")),
                            }
                        } else {
                            Err(ParseError::OtherError("no matching close parenthesis found.".to_owned()))
                        }
                    }
                    Err(e) => Err(e),
                }
            }
            _ => Err(ParseError::UnexpectedToken(token_list[0].to_string(), "number"))
        }
    } else {
        Err(ParseError::UnexpectedEndOfInput)
    }
}

pub fn parse(tokens: Vec<Token>) -> Result<String, ParseError> {
    e_expr(&tokens).map(|answer| answer.value.to_string())
}

fn eval(input: &str) -> String {
    match tokenize(input).and_then(parse) {
        Ok(s) => s,
        Err(_e) => "Syntax Error".to_string()
    }
}

fn main(){
    let mut window = Window::new(Rect::new(100, 100, 148, 200), "Calculator");

    {
        let text_box = TextBox::new()
            .position(0, 0)
            .size(300, 16)
            .on_enter(move |text_box: &TextBox| {
                let input = text_box.text.get();
                let result = eval(&input);
                text_box.text_i.set(result.len());
                text_box.text.set(result);
            })
            .place(&mut window);

        let mut col = 0;
        let mut row = 0;

        {
            let mut btn = |name| {
                let text_box_clone = text_box.clone();
                Button::new()
                    .position(col * 36 + 4, row * 36 + 20)
                    .size(32, 32)
                    .text(name)
                    .text_offset(12, 8)
                    .on_click(move |_button: &Button, _point: Point| {
                        let text_i = text_box_clone.text_i.get();

                        let text = text_box_clone.text.get();

                        let mut new_text = String::new();
                        new_text.push_str(&text[.. text_i]);
                        new_text.push_str(name);
                        new_text.push_str(&text[text_i ..]);

                        text_box_clone.text.set(new_text);

                        text_box_clone.text_i.set(text_i + name.len());
                    })
                    .place(&mut window);
                col += 1;
                if col >= 4 {
                    col = 0;
                    row += 1;
                }
            };

            btn("("); btn(")"); btn("^"); btn("/");
            btn("7"); btn("8"); btn("9"); btn("*");
            btn("4"); btn("5"); btn("6"); btn("-");
            btn("1"); btn("2"); btn("3"); btn("+");
            btn("0"); btn("0"); btn(".");
        }

        {
            let text_box_clone = text_box.clone();
            Button::new()
                .position(col * 36 + 4, row * 36 + 20)
                .size(32, 32)
                .text("=")
                .text_offset(12, 8)
                .on_click(move |_button: &Button, _point: Point| {
                    text_box_clone.emit_enter();
                })
                .place(&mut window);
        }
    }

    window.exec();
}
<commit_msg>Fix calculator<commit_after>#![deny(warnings)]

extern crate orbtk;

use orbtk::{Button, Point, Rect, TextBox, Window, WidgetPlace};
use orbtk::callback::{Click, Enter};
use orbtk::place::Place;

#[derive(Debug, Clone)]
pub enum Token {
    Plus,
    Minus,
    Divide,
    Multiply,
    Exponent,
    OpenParen,
    CloseParen,
    Number(String),
}

impl Token {
    pub fn to_str(&self) -> &'static str {
        match self {
            &Token::Plus       => "Plus",
            &Token::Minus      => "Minus",
            &Token::Divide     => "Divide",
            &Token::Multiply   => "Multiply",
            &Token::Exponent   => "Exponent",
            &Token::OpenParen  => "OpenParen",
            &Token::CloseParen => "CloseParen",
            &Token::Number(_)  => "Number",
        }
    }

    pub fn to_string(&self) -> String {
        self.to_str().to_owned()
    }
}

#[derive(Debug,  Clone)]
pub enum ParseError {
    InvalidNumber(String),
    UnrecognizedToken(String),
    UnexpectedToken(String, &'static str),
    UnexpectedEndOfInput,
    OtherError(String),
}

#[derive(Clone,Debug)]
pub struct IntermediateResult {
    value: f64,
    tokens_read: usize,
}

impl IntermediateResult {
    fn new(value: f64, tokens_read: usize) -> Self {
        IntermediateResult {
            value: value,
            tokens_read: tokens_read,
        }
    }
}

pub trait OperatorFunctions {
    fn is_operator(self) -> bool;
    fn operator_type(self) -> Token;
}

impl OperatorFunctions for char {
    fn is_operator(self) -> bool {
        self == '+' ||
        self == '-' ||
        self == '*' ||
        self == '/' ||
        self == '^' ||
        self == '(' ||
        self == ')'
    }

    fn operator_type(self) -> Token {
        match self {
            '+' => Token::Plus,
            '-' => Token::Minus,
            '/' => Token::Divide,
            '*' => Token::Multiply,
            '^' => Token::Exponent,
            '(' => Token::OpenParen,
            ')' => Token::CloseParen,
            _   => panic!("Invalid operator")
        }
    }
}

pub fn tokenize(input: &str) -> Result<Vec<Token>, ParseError> {
    // CONSIDER: input.len() too generous?
    let mut tokens = Vec::with_capacity(input.len());

    // TODO: Not this. Modify to use iterator
    let chars: Vec<char> = input.chars().collect();

    let input_length = chars.len();
    let mut current_pos = 0;
    while current_pos < input_length {
        let c = chars[current_pos];
        if c.is_digit(10) {
            let token_string = consume_number(&chars[current_pos..]);
            current_pos += token_string.len();
            tokens.push(Token::Number(token_string));
        } else if c.is_operator() {
            tokens.push(c.operator_type());
            current_pos += 1;
        } else if c.is_whitespace() {
            current_pos += 1;
        } else {
            let token_string = consume_until_new_token(&chars[current_pos..]);
            return Err(ParseError::UnrecognizedToken(token_string));
        }
    }
    Ok(tokens)
}

fn consume_number(input: &[char]) -> String {
    // CONSIDER: input.len seems a bit generous
    let mut number = String::with_capacity(input.len());
    let mut has_decimal_point = false;
    for &c in input {
        if c == '.' {
            if has_decimal_point {
                break;
            } else {
                number.push(c);
                has_decimal_point = true;
            }
        } else if c.is_digit(10) {
            number.push(c);
        } else {
            break;
        }
    }
    number
}

fn consume_until_new_token(input: &[char]) -> String {
    input.iter()
         .take_while(|c| !(c.is_whitespace() || c.is_operator() || c.is_digit(10)))
         .map(|&c| c)
         .collect()
}

// Addition and subtraction
pub fn e_expr(token_list: &[Token]) -> Result<IntermediateResult, ParseError> {
    let mut t1 = try!(t_expr(token_list));
    let mut index = t1.tokens_read;

    while index < token_list.len() {
        match token_list[index] {
            Token::Plus => {
                let t2 = try!(t_expr(&token_list[index+1..]));
                t1.value += t2.value;
                t1.tokens_read += t2.tokens_read + 1;
            }
            Token::Minus => {
                let t2 = try!(t_expr(&token_list[index+1..]));
                t1.value -= t2.value;
                t1.tokens_read += t2.tokens_read + 1;
            }
            Token::Number(ref n) => return Err(ParseError::UnexpectedToken(n.clone(),"operator")),
            _ => break,
        };
        index = t1.tokens_read;
    }
    Ok(t1)
}

// Multiplication and division
pub fn t_expr(token_list: &[Token]) -> Result<IntermediateResult, ParseError> {
    let mut f1 = try!(f_expr(token_list));
    let mut index = f1.tokens_read;

    while index < token_list.len() {
        match token_list[index] {
            Token::Multiply => {
                let f2 = try!(f_expr(&token_list[index+1..]));
                f1.value *= f2.value;
                f1.tokens_read += f2.tokens_read + 1;
            }
            Token::Divide => {
                let f2 = try!(f_expr(&token_list[index+1..]));
                if f2.value == 0.0 {
                    return Err(ParseError::OtherError("Divide by zero error".to_owned()));
                } else {
                    f1.value /= f2.value;
                    f1.tokens_read += f2.tokens_read + 1;
                }
            }
            Token::Number(ref n) => return Err(ParseError::UnexpectedToken(n.clone(),"operator")),
            _ => break,
        }
        index = f1.tokens_read;
    }
    Ok(f1)
}

// Exponentiation
pub fn f_expr(token_list: &[Token]) -> Result<IntermediateResult, ParseError> {
    let mut g1 = try!(g_expr(token_list));
    let mut index = g1.tokens_read;
    let token_len = token_list.len();
    while index < token_len {
        match token_list[index] {
            Token::Exponent => {
                let f = try!(f_expr(&token_list[index+1..]));
                g1.value = g1.value.powf(f.value);
                g1.tokens_read += f.tokens_read + 1;
            }
            Token::Number(ref n) => return Err(ParseError::UnexpectedToken(n.clone(),"operator")),
            _ => break,
        }
        index = g1.tokens_read;
    }
    Ok(g1)
}

// Numbers and parenthesized expressions
pub fn g_expr(token_list: &[Token]) -> Result<IntermediateResult, ParseError> {
    if !token_list.is_empty() {
        match token_list[0] {
            Token::Number(ref n) => {
                n.parse::<f64>()
                 .map_err(|_| ParseError::InvalidNumber(n.clone()))
                 .and_then(|num| Ok(IntermediateResult::new(num, 1)))
            }
            Token::Minus => {
                if token_list.len() > 1 {
                    if let Token::Number(ref n) = token_list[1] {
                        n.parse::<f64>()
                         .map_err(|_| ParseError::InvalidNumber(n.clone()))
                         .and_then(|num| Ok(IntermediateResult::new(-1.0 * num, 2)))
                    } else {
                        Err(ParseError::UnexpectedToken(token_list[1].to_string(), "number"))
                    }
                } else {
                    Err(ParseError::UnexpectedEndOfInput)
                }
            }
            Token::OpenParen => {
                let expr = e_expr(&token_list[1..]);
                match expr {
                    Ok(ir) => {
                        let close_paren = ir.tokens_read + 1;
                        if close_paren < token_list.len() {
                            match token_list[close_paren] {
                                Token::CloseParen => Ok(IntermediateResult::new(ir.value, close_paren+1)),
                                _ => Err(ParseError::UnexpectedToken(token_list[close_paren].to_string(), ")")),
                            }
                        } else {
                            Err(ParseError::OtherError("no matching close parenthesis found.".to_owned()))
                        }
                    }
                    Err(e) => Err(e),
                }
            }
            _ => Err(ParseError::UnexpectedToken(token_list[0].to_string(), "number"))
        }
    } else {
        Err(ParseError::UnexpectedEndOfInput)
    }
}

pub fn parse(tokens: Vec<Token>) -> Result<String, ParseError> {
    e_expr(&tokens).map(|answer| answer.value.to_string())
}

fn eval(input: &str) -> String {
    match tokenize(input).and_then(parse) {
        Ok(s) => s,
        Err(_e) => "Syntax Error".to_string()
    }
}

fn main(){
    let window = Window::new(Rect::new(100, 100, 148, 200), "Calculator");

    {
        let text_box = TextBox::new()
            .position(0, 0)
            .size(300, 16)
            .on_enter(move |text_box: &TextBox| {
                let input = text_box.text.get();
                let result = eval(&input);
                text_box.text_i.set(result.len());
                text_box.text.set(result);
            })
            .place(&window);

        let mut col = 0;
        let mut row = 0;

        {
            let mut btn = |name| {
                let text_box_clone = text_box.clone();
                Button::new()
                    .position(col * 36 + 4, row * 36 + 20)
                    .size(32, 32)
                    .text(name)
                    .text_offset(12, 8)
                    .on_click(move |_button: &Button, _point: Point| {
                        let text_i = text_box_clone.text_i.get();

                        let text = text_box_clone.text.get();

                        let mut new_text = String::new();
                        new_text.push_str(&text[.. text_i]);
                        new_text.push_str(name);
                        new_text.push_str(&text[text_i ..]);

                        text_box_clone.text.set(new_text);

                        text_box_clone.text_i.set(text_i + name.len());
                    })
                    .place(&window);
                col += 1;
                if col >= 4 {
                    col = 0;
                    row += 1;
                }
            };

            btn("("); btn(")"); btn("^"); btn("/");
            btn("7"); btn("8"); btn("9"); btn("*");
            btn("4"); btn("5"); btn("6"); btn("-");
            btn("1"); btn("2"); btn("3"); btn("+");
            btn("0"); btn("0"); btn(".");
        }

        {
            let text_box_clone = text_box.clone();
            Button::new()
                .position(col * 36 + 4, row * 36 + 20)
                .size(32, 32)
                .text("=")
                .text_offset(12, 8)
                .on_click(move |_button: &Button, _point: Point| {
                    text_box_clone.emit_enter();
                })
                .place(&window);
        }
    }

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


<commit_before>use rustc::lint::*;
use rustc::middle::ty::TypeVariants;
use rustc_front::hir::*;
use syntax::codemap::Span;
use syntax::ptr::P;
use utils::{BOX_NEW_PATH, VEC_FROM_ELEM_PATH};
use utils::{is_expn_of, match_path, snippet, span_lint_and_then};

/// **What it does:** This lint warns about using `&vec![..]` when using `&[..]` would be possible.
/// It is `Warn` by default.
///
/// **Why is this bad?** This is less efficient.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust, ignore
/// foo(&vec![1, 2])
/// ```
declare_lint! {
    pub USELESS_VEC,
    Warn,
    "useless `vec!`"
}

#[derive(Copy, Clone, Debug)]
pub struct UselessVec;

impl LintPass for UselessVec {
    fn get_lints(&self) -> LintArray {
        lint_array!(USELESS_VEC)
    }
}

impl LateLintPass for UselessVec {
    fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
        unexpand_vec(cx, expr);

        // search for `&!vec[_]` expressions where the adjusted type is `&[_]`
        if_let_chain!{[
            let TypeVariants::TyRef(_, ref ty) = cx.tcx.expr_ty_adjusted(expr).sty,
            let TypeVariants::TySlice(..) = ty.ty.sty,
            let ExprAddrOf(_, ref addressee) = expr.node,
            let Some(vec_args) = unexpand_vec(cx, addressee)
        ], {
            let snippet = match vec_args {
                VecArgs::Repeat(elem, len) => {
                    format!("&[{}; {}]", snippet(cx, elem.span, "elem"), snippet(cx, len.span, "len")).into()
                }
                VecArgs::Vec(args) => {
                    if let Some(last) = args.iter().last() {
                        let span = Span {
                            lo: args[0].span.lo,
                            hi: last.span.hi,
                            expn_id: args[0].span.expn_id,
                        };

                        format!("&[{}]", snippet(cx, span, "..")).into()
                    }
                    else {
                        "&[]".into()
                    }
                }
            };

            span_lint_and_then(cx, USELESS_VEC, expr.span, "useless use of `vec!`", |db| {
                db.span_suggestion(expr.span, "you can use a slice directly", snippet);
            });
        }}
    }
}

/// Represent the pre-expansion arguments of a `vec!` invocation.
pub enum VecArgs<'a> {
    /// `vec![elem, len]`
    Repeat(&'a P<Expr>, &'a P<Expr>),
    /// `vec![a, b, c]`
    Vec(&'a [P<Expr>]),
}

/// Returns the arguments of the `vec!` macro if this expression was expanded from `vec!`.
pub fn unexpand_vec<'e>(cx: &LateContext, expr: &'e Expr) -> Option<VecArgs<'e>> {
    if_let_chain!{[
        let ExprCall(ref fun, ref args) = expr.node,
        let ExprPath(_, ref path) = fun.node,
        is_expn_of(cx, fun.span, "vec").is_some()
    ], {
        return if match_path(path, &VEC_FROM_ELEM_PATH) && args.len() == 2 {
            // `vec![elem; size]` case
            Some(VecArgs::Repeat(&args[0], &args[1]))
        }
        else if match_path(path, &["into_vec"]) && args.len() == 1 {
            // `vec![a, b, c]` case
            if_let_chain!{[
                let ExprCall(ref fun, ref args) = args[0].node,
                let ExprPath(_, ref path) = fun.node,
                match_path(path, &BOX_NEW_PATH) && args.len() == 1,
                let ExprVec(ref args) = args[0].node
            ], {
                return Some(VecArgs::Vec(&*args));
            }}

            None
        }
        else {
            None
        };
    }}

    None
}
<commit_msg>Fix formatting on wiki<commit_after>use rustc::lint::*;
use rustc::middle::ty::TypeVariants;
use rustc_front::hir::*;
use syntax::codemap::Span;
use syntax::ptr::P;
use utils::{BOX_NEW_PATH, VEC_FROM_ELEM_PATH};
use utils::{is_expn_of, match_path, snippet, span_lint_and_then};

/// **What it does:** This lint warns about using `&vec![..]` when using `&[..]` would be possible.
/// It is `Warn` by default.
///
/// **Why is this bad?** This is less efficient.
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rust,ignore
/// foo(&vec![1, 2])
/// ```
declare_lint! {
    pub USELESS_VEC,
    Warn,
    "useless `vec!`"
}

#[derive(Copy, Clone, Debug)]
pub struct UselessVec;

impl LintPass for UselessVec {
    fn get_lints(&self) -> LintArray {
        lint_array!(USELESS_VEC)
    }
}

impl LateLintPass for UselessVec {
    fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
        unexpand_vec(cx, expr);

        // search for `&!vec[_]` expressions where the adjusted type is `&[_]`
        if_let_chain!{[
            let TypeVariants::TyRef(_, ref ty) = cx.tcx.expr_ty_adjusted(expr).sty,
            let TypeVariants::TySlice(..) = ty.ty.sty,
            let ExprAddrOf(_, ref addressee) = expr.node,
            let Some(vec_args) = unexpand_vec(cx, addressee)
        ], {
            let snippet = match vec_args {
                VecArgs::Repeat(elem, len) => {
                    format!("&[{}; {}]", snippet(cx, elem.span, "elem"), snippet(cx, len.span, "len")).into()
                }
                VecArgs::Vec(args) => {
                    if let Some(last) = args.iter().last() {
                        let span = Span {
                            lo: args[0].span.lo,
                            hi: last.span.hi,
                            expn_id: args[0].span.expn_id,
                        };

                        format!("&[{}]", snippet(cx, span, "..")).into()
                    }
                    else {
                        "&[]".into()
                    }
                }
            };

            span_lint_and_then(cx, USELESS_VEC, expr.span, "useless use of `vec!`", |db| {
                db.span_suggestion(expr.span, "you can use a slice directly", snippet);
            });
        }}
    }
}

/// Represent the pre-expansion arguments of a `vec!` invocation.
pub enum VecArgs<'a> {
    /// `vec![elem, len]`
    Repeat(&'a P<Expr>, &'a P<Expr>),
    /// `vec![a, b, c]`
    Vec(&'a [P<Expr>]),
}

/// Returns the arguments of the `vec!` macro if this expression was expanded from `vec!`.
pub fn unexpand_vec<'e>(cx: &LateContext, expr: &'e Expr) -> Option<VecArgs<'e>> {
    if_let_chain!{[
        let ExprCall(ref fun, ref args) = expr.node,
        let ExprPath(_, ref path) = fun.node,
        is_expn_of(cx, fun.span, "vec").is_some()
    ], {
        return if match_path(path, &VEC_FROM_ELEM_PATH) && args.len() == 2 {
            // `vec![elem; size]` case
            Some(VecArgs::Repeat(&args[0], &args[1]))
        }
        else if match_path(path, &["into_vec"]) && args.len() == 1 {
            // `vec![a, b, c]` case
            if_let_chain!{[
                let ExprCall(ref fun, ref args) = args[0].node,
                let ExprPath(_, ref path) = fun.node,
                match_path(path, &BOX_NEW_PATH) && args.len() == 1,
                let ExprVec(ref args) = args[0].node
            ], {
                return Some(VecArgs::Vec(&*args));
            }}

            None
        }
        else {
            None
        };
    }}

    None
}
<|endoftext|>


<commit_before>/* chips::sam4l::ast -- Implementation of a single hardware timer.
 *
 * Author: Amit Levy <levya@cs.stanford.edu>
 * Author: Philip Levis <pal@cs.stanford.edu>
 * Date: 7/16/15
 */

use core::cell::Cell;
use core::intrinsics;
use nvic;
use hil::alarm::{Alarm, AlarmClient, Freq16Khz};
use hil::Controller;
use chip;
use pm::{self, PBDClock};

#[repr(C, packed)]
#[allow(missing_copy_implementations)]
struct AstRegisters {
    cr: u32,
    cv: u32,
    sr: u32,
    scr: u32,
    ier: u32,
    idr: u32,
    imr: u32,
    wer: u32,
    //0x20
    ar0: u32,
    ar1: u32,
    reserved0: [u32; 2],
    pir0: u32,
    pir1: u32,
    reserved1: [u32; 2],
    //0x40
    clock: u32,
    dtr: u32,
    eve: u32,
    evd: u32,
    evm: u32,
    calv: u32
    //we leave out parameter and version
}

pub const AST_BASE: isize = 0x400F0800;

#[allow(missing_copy_implementations)]
pub struct Ast {
    regs: *mut AstRegisters,
    callback: Cell<Option<&'static AlarmClient>>
}

pub static mut AST : Ast = Ast {
    regs: AST_BASE as *mut AstRegisters,
    callback: Cell::new(None)
};

impl Controller for Ast {
    type Config = &'static AlarmClient;

    fn configure(&self, client: &'static AlarmClient) {
        self.callback.set(Some(client));

        unsafe {
            pm::enable_clock(pm::Clock::PBD(PBDClock::AST));
        }
        self.select_clock(Clock::ClockOsc32);
        self.set_prescalar(0); // 32Khz / (2^(0 + 1)) = 16Khz
        self.enable_alarm_wake();
        self.clear_alarm();

        self.enable();
    }
}

#[repr(usize)]
pub enum Clock {
    ClockRCSys = 0,
    ClockOsc32 = 1,
    ClockAPB = 2,
    ClockGclk2 = 3,
    Clock1K = 4
}

impl Ast {
    pub fn clock_busy(&self) -> bool {
        unsafe {
            intrinsics::volatile_load(&(*self.regs).sr) & (1 << 28) != 0
        }
    }

    pub fn busy(&self) -> bool {
        unsafe {
            intrinsics::volatile_load(&(*self.regs).sr) & (1 << 24) != 0
        }
    }

    // Clears the alarm bit in the status register (indicating the alarm value
    // has been reached).
    pub fn clear_alarm(&self) {
        while self.busy() {}
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).scr, 1 << 8);
            nvic::clear_pending(nvic::NvicIdx::ASTALARM);
        }
    }

    // Clears the per0 bit in the status register (indicating the alarm value
    // has been reached).
    pub fn clear_periodic(&mut self) {
        while self.busy() {}
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).scr, 1 << 16);
        }
    }

    pub fn select_clock(&self, clock: Clock) {
        unsafe {
          // Disable clock by setting first bit to zero
          while self.clock_busy() {}
          let enb = intrinsics::volatile_load(&(*self.regs).clock) & !1;
          intrinsics::volatile_store(&mut (*self.regs).clock, enb);
          while self.clock_busy() {}

          // Select clock
          intrinsics::volatile_store(&mut (*self.regs).clock, (clock as u32) << 8);
          while self.clock_busy() {}

          // Re-enable clock
          let enb = intrinsics::volatile_load(&(*self.regs).clock) | 1;
          intrinsics::volatile_store(&mut (*self.regs).clock, enb);
        }
    }

    pub fn enable(&self) {
        while self.busy() {}
        unsafe {
            let cr = intrinsics::volatile_load(&(*self.regs).cr) | 1;
            intrinsics::volatile_store(&mut (*self.regs).cr, cr);
        }
    }

    pub fn disable(&self) {
        while self.busy() {}
        unsafe {
            let cr = intrinsics::volatile_load(&(*self.regs).cr) & !1;
            intrinsics::volatile_store(&mut (*self.regs).cr, cr);
        }
    }

    pub fn set_prescalar(&self, val: u8) {
        while self.busy() {}
        unsafe {
            let cr = intrinsics::volatile_load(&(*self.regs).cr) | (val as u32) << 16;
            intrinsics::volatile_store(&mut (*self.regs).cr, cr);
        }
    }

    pub fn enable_alarm_irq(&self) {
        unsafe {
            nvic::enable(nvic::NvicIdx::ASTALARM);
            intrinsics::volatile_store(&mut (*self.regs).ier, 1 << 8);
        }
    }

    pub fn disable_alarm_irq(&self) {
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).idr, 1 << 8);
        }
    }

    pub fn enable_ovf_irq(&mut self) {
        unsafe {
            nvic::enable(nvic::NvicIdx::ASTOVF);
            intrinsics::volatile_store(&mut (*self.regs).ier, 1);
        }
    }

    pub fn disable_ovf_irq(&mut self) {
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).idr, 1);
        }
    }

    pub fn enable_periodic_irq(&mut self) {
        unsafe {
            nvic::enable(nvic::NvicIdx::ASTPER);
            intrinsics::volatile_store(&mut (*self.regs).ier, 1 << 16);
        }
    }

    pub fn disable_periodic_irq(&mut self) {
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).idr, 1 << 16);
        }
    }

    pub fn enable_alarm_wake(&self) {
        while self.busy() {}
        unsafe {
            let wer = intrinsics::volatile_load(&mut (*self.regs).wer) | 1 << 8;
            intrinsics::volatile_store(&mut (*self.regs).wer, wer);
        }
    }

    pub fn set_periodic_interval(&mut self, interval: u32) {
        while self.busy() {}
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).pir0, interval);
        }
    }

    pub fn get_counter(&self) -> u32 {
        while self.busy() {}
        unsafe {
            intrinsics::volatile_load(&(*self.regs).cv)
        }
    }

    pub fn set_counter(&self, value: u32) {
        while self.busy() {}
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).cv, value);
        }
    }

    pub fn handle_interrupt(&mut self) {
        self.clear_alarm();
        self.callback.get().map(|cb| {
            cb.fired();
        });
    }

}

impl Alarm for Ast {

    type Frequency = Freq16Khz;

    fn now(&self) -> u32 {
        unsafe {
            intrinsics::volatile_load(&(*self.regs).cv)
        }
    }

    fn disable_alarm(&self) {
        self.disable_alarm_irq();
    }

    fn set_alarm(&self, tics: u32) {
        self.disable();
        while self.busy() {}
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).ar0, tics);
        }
        self.clear_alarm();
        self.enable_alarm_irq();
        self.enable();
    }

    fn get_alarm(&self) -> u32 {
        unsafe {
            intrinsics::volatile_load(&(*self.regs).ar0)
        }
    }
}

#[no_mangle]
#[allow(non_snake_case)]
pub unsafe extern fn AST_ALARM_Handler() {
    use common::Queue;

    nvic::disable(nvic::NvicIdx::ASTALARM);
    chip::INTERRUPT_QUEUE.as_mut().unwrap().enqueue(nvic::NvicIdx::ASTALARM);
}

<commit_msg>SAM4L: Wait on AST busy bit before reading regs<commit_after>/* chips::sam4l::ast -- Implementation of a single hardware timer.
 *
 * Author: Amit Levy <levya@cs.stanford.edu>
 * Author: Philip Levis <pal@cs.stanford.edu>
 * Date: 7/16/15
 */

use core::cell::Cell;
use core::intrinsics;
use nvic;
use hil::alarm::{Alarm, AlarmClient, Freq16Khz};
use hil::Controller;
use chip;
use pm::{self, PBDClock};

#[repr(C, packed)]
#[allow(missing_copy_implementations)]
struct AstRegisters {
    cr: u32,
    cv: u32,
    sr: u32,
    scr: u32,
    ier: u32,
    idr: u32,
    imr: u32,
    wer: u32,
    //0x20
    ar0: u32,
    ar1: u32,
    reserved0: [u32; 2],
    pir0: u32,
    pir1: u32,
    reserved1: [u32; 2],
    //0x40
    clock: u32,
    dtr: u32,
    eve: u32,
    evd: u32,
    evm: u32,
    calv: u32
    //we leave out parameter and version
}

pub const AST_BASE: isize = 0x400F0800;

#[allow(missing_copy_implementations)]
pub struct Ast {
    regs: *mut AstRegisters,
    callback: Cell<Option<&'static AlarmClient>>
}

pub static mut AST : Ast = Ast {
    regs: AST_BASE as *mut AstRegisters,
    callback: Cell::new(None)
};

impl Controller for Ast {
    type Config = &'static AlarmClient;

    fn configure(&self, client: &'static AlarmClient) {
        self.callback.set(Some(client));

        unsafe {
            pm::enable_clock(pm::Clock::PBD(PBDClock::AST));
        }
        self.select_clock(Clock::ClockOsc32);
        self.set_prescalar(0); // 32Khz / (2^(0 + 1)) = 16Khz
        self.enable_alarm_wake();
        self.clear_alarm();

        self.enable();
    }
}

#[repr(usize)]
pub enum Clock {
    ClockRCSys = 0,
    ClockOsc32 = 1,
    ClockAPB = 2,
    ClockGclk2 = 3,
    Clock1K = 4
}

impl Ast {
    pub fn clock_busy(&self) -> bool {
        unsafe {
            intrinsics::volatile_load(&(*self.regs).sr) & (1 << 28) != 0
        }
    }

    pub fn busy(&self) -> bool {
        unsafe {
            intrinsics::volatile_load(&(*self.regs).sr) & (1 << 24) != 0
        }
    }

    // Clears the alarm bit in the status register (indicating the alarm value
    // has been reached).
    pub fn clear_alarm(&self) {
        while self.busy() {}
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).scr, 1 << 8);
            nvic::clear_pending(nvic::NvicIdx::ASTALARM);
        }
    }

    // Clears the per0 bit in the status register (indicating the alarm value
    // has been reached).
    pub fn clear_periodic(&mut self) {
        while self.busy() {}
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).scr, 1 << 16);
        }
    }

    pub fn select_clock(&self, clock: Clock) {
        unsafe {
          // Disable clock by setting first bit to zero
          while self.clock_busy() {}
          let enb = intrinsics::volatile_load(&(*self.regs).clock) & !1;
          intrinsics::volatile_store(&mut (*self.regs).clock, enb);
          while self.clock_busy() {}

          // Select clock
          intrinsics::volatile_store(&mut (*self.regs).clock, (clock as u32) << 8);
          while self.clock_busy() {}

          // Re-enable clock
          let enb = intrinsics::volatile_load(&(*self.regs).clock) | 1;
          intrinsics::volatile_store(&mut (*self.regs).clock, enb);
        }
    }

    pub fn enable(&self) {
        while self.busy() {}
        unsafe {
            let cr = intrinsics::volatile_load(&(*self.regs).cr) | 1;
            intrinsics::volatile_store(&mut (*self.regs).cr, cr);
        }
    }

    pub fn disable(&self) {
        while self.busy() {}
        unsafe {
            let cr = intrinsics::volatile_load(&(*self.regs).cr) & !1;
            intrinsics::volatile_store(&mut (*self.regs).cr, cr);
        }
    }

    pub fn set_prescalar(&self, val: u8) {
        while self.busy() {}
        unsafe {
            let cr = intrinsics::volatile_load(&(*self.regs).cr) | (val as u32) << 16;
            intrinsics::volatile_store(&mut (*self.regs).cr, cr);
        }
    }

    pub fn enable_alarm_irq(&self) {
        unsafe {
            nvic::enable(nvic::NvicIdx::ASTALARM);
            intrinsics::volatile_store(&mut (*self.regs).ier, 1 << 8);
        }
    }

    pub fn disable_alarm_irq(&self) {
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).idr, 1 << 8);
        }
    }

    pub fn enable_ovf_irq(&mut self) {
        unsafe {
            nvic::enable(nvic::NvicIdx::ASTOVF);
            intrinsics::volatile_store(&mut (*self.regs).ier, 1);
        }
    }

    pub fn disable_ovf_irq(&mut self) {
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).idr, 1);
        }
    }

    pub fn enable_periodic_irq(&mut self) {
        unsafe {
            nvic::enable(nvic::NvicIdx::ASTPER);
            intrinsics::volatile_store(&mut (*self.regs).ier, 1 << 16);
        }
    }

    pub fn disable_periodic_irq(&mut self) {
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).idr, 1 << 16);
        }
    }

    pub fn enable_alarm_wake(&self) {
        while self.busy() {}
        unsafe {
            let wer = intrinsics::volatile_load(&mut (*self.regs).wer) | 1 << 8;
            intrinsics::volatile_store(&mut (*self.regs).wer, wer);
        }
    }

    pub fn set_periodic_interval(&mut self, interval: u32) {
        while self.busy() {}
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).pir0, interval);
        }
    }

    pub fn get_counter(&self) -> u32 {
        while self.busy() {}
        unsafe {
            intrinsics::volatile_load(&(*self.regs).cv)
        }
    }

    pub fn set_counter(&self, value: u32) {
        while self.busy() {}
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).cv, value);
        }
    }

    pub fn handle_interrupt(&mut self) {
        self.clear_alarm();
        self.callback.get().map(|cb| {
            cb.fired();
        });
    }

}

impl Alarm for Ast {

    type Frequency = Freq16Khz;

    fn now(&self) -> u32 {
        while self.busy() {}
        unsafe {
            intrinsics::volatile_load(&(*self.regs).cv)
        }
    }

    fn disable_alarm(&self) {
        self.disable_alarm_irq();
    }

    fn set_alarm(&self, tics: u32) {
        self.disable();
        while self.busy() {}
        unsafe {
            intrinsics::volatile_store(&mut (*self.regs).ar0, tics);
        }
        self.clear_alarm();
        self.enable_alarm_irq();
        self.enable();
    }

    fn get_alarm(&self) -> u32 {
        while self.busy() {}
        unsafe {
            intrinsics::volatile_load(&(*self.regs).ar0)
        }
    }
}

#[no_mangle]
#[allow(non_snake_case)]
pub unsafe extern fn AST_ALARM_Handler() {
    use common::Queue;

    nvic::disable(nvic::NvicIdx::ASTALARM);
    chip::INTERRUPT_QUEUE.as_mut().unwrap().enqueue(nvic::NvicIdx::ASTALARM);
}

<|endoftext|>


<commit_before>pub fn _collections() {
    println!("*** Collections ***");

    iterators();
    entries();

    binary_heap();
    btree_map();
    btree_set();

    println!("");
}

fn iterators() {
    let mut vec = vec![1, 2, 3, 4];

    for x in vec.iter() {
        print!("{} ", x);
    }
    println!("");

    for x in vec.iter_mut() {
        *x += 1;
        print!("{} ", x);
    }
    println!("");

    let vec2 = vec![10, 20, 30, 40];
    vec.extend(vec2);

    use std::collections::VecDeque;
    let buf: VecDeque<_> = vec.into_iter().collect();
}

fn entries() {
    use std::collections::btree_map::BTreeMap;

    let mut count = BTreeMap::new();
    let message = "sea shells by the shore";

    for c in message.chars() {
        *count.entry(c).or_insert(0) += 1;
    }

    assert_eq!(Some(&4), count.get(&'s'));

    for (ch, count) in &count {
        print!("{}: {}, ", ch, count);
    }
    println!("");
}

fn binary_heap() {
    // BinaryHeap struct
    {
        use std::collections::BinaryHeap;

        let mut heap = BinaryHeap::new();

        // nothing there yet
        assert_eq!(None, heap.peek());

        // pushing onto the heap
        heap.push(1);
        heap.push(5);
        heap.push(2);

        // peek what's "on top"
        assert_eq!(Some(&5), heap.peek());

        // number of items in the heap
        assert_eq!(3, heap.len());

        // in "random" order
        for x in &heap {
            print!("{} ", x);
        }
        println!("");

        // popping is in correct order
        assert_eq!(Some(5), heap.pop());
        assert_eq!(Some(2), heap.pop());
        assert_eq!(Some(1), heap.pop());
        assert_eq!(None, heap.pop());

        // clear anything that remains
        heap.clear();

        // not heap is empty
        assert!(heap.is_empty());

        // creating with preallocated capacity
        let mut heap = BinaryHeap::with_capacity(10);
        assert!(heap.capacity() >= 10);
        heap.push(4);

        *heap.peek_mut().unwrap() += 1;
        assert_eq!(Some(&5), heap.peek());

        heap.reserve_exact(8);
        heap.reserve(8);
        heap.shrink_to_fit();

        heap.push(3);
        heap.push(7);
        heap.push(4);

        // println!("Heap into vec: {:?}", heap.into_vec());
        println!("Heap into sorted vec: {:?}", heap.into_sorted_vec());

        let mut heap = BinaryHeap::new();
        heap.push(3);
        heap.push(7);
        heap.push(4);

        for x in heap.drain() {
            print!("{} ", x);
        }
        println!("");

        assert!(heap.is_empty());

        let v = vec![-4, 8, 3, 6, -3];
        let mut a = BinaryHeap::from(v);

        let v = vec![-20, 5, 43];
        let mut b = BinaryHeap::from(v);

        a.append(&mut b);

        println!("{:?}", a.into_sorted_vec());

        assert!(b.is_empty());
    }
}

fn btree_map() {
    // general example
    {
        use std::collections::BTreeMap;

        let mut movie_reviews = BTreeMap::new();

        // review some movies
        movie_reviews.insert("Pulp Fiction", "Masterpiece");
        movie_reviews.insert("The Godfather", "Very enjoyable");
        movie_reviews.insert("The Blues Brothers", "Eye lyked it alot");

        // check for a specific one
        if !movie_reviews.contains_key("Les Misérables") {
            println!("We've got {} reviews, but Les Misérables ain't one.",
                     movie_reviews.len());
        }

        // this one has spelling mistakes
        movie_reviews.remove("The Blues Brothers");

        // look up the values associated with some keys
        let to_find = ["Up!", "The Godfather"];

        for book in &to_find {
            match movie_reviews.get(book) {
                Some(review) => println!("{}: {}", book, review),
                None => println!("{} is unreviewed.", book),
            }
        }

        // iterate over everything
        for (movie, review) in &movie_reviews {
            println!("{}: \"{}\"", movie, review);

        }
    }

    // entry api
    {
        use std::collections::BTreeMap;

        let mut player_stats = BTreeMap::new();

        fn random_stat_buff() -> u8 {
            42
        }

        // insert a key only if it doesn't exist
        player_stats.entry("health").or_insert(100);

        // same, just using a function
        player_stats.entry("defence").or_insert_with(random_stat_buff);

        // update a key guarding against it possibly not being set
        let stat = player_stats.entry("attack").or_insert(100);
        *stat += random_stat_buff();
    }

    // methods on a BTreeMap
    {
        use std::collections::BTreeMap;

        let mut map = BTreeMap::new();

        map.insert(1, "a");

        if let Some(x) = map.get_mut(&1) {
            *x = "b";
        }

        assert_eq!(map.entry(1).key(), &1);

        map.clear();
        assert!(map.is_empty());

        // methods on entry struct
    }
}

fn btree_set() {
    // general example
    {
        use std::collections::BTreeSet;

        let mut books = BTreeSet::new();

        books.insert("A Dance with Dragons");
        books.insert("To Kill a Mockingbird");
        books.insert("The Odyssey");
        books.insert("The Great Gatsby");

        // check for a specific one
        if !books.contains("The Winds of Winter") {
            println!("We have {} books, but The Winds of Winter ain't one.",
                     books.len());
        }

        books.remove("The Odyssey");

        for book in &books {
            println!("{}, ", book);
        }
        println!("");
    }

    // methods
    {
        use std::collections::BTreeSet;

        let mut a = BTreeSet::new();
        a.insert(1);
        a.insert(2);

        let mut b = BTreeSet::new();
        b.insert(2);
        b.insert(3);

        println!("Diff: {:?}", a.difference(&b).cloned().collect::<Vec<i32>>());
        println!("Sym diff: {:?}",
                 a.symmetric_difference(&b).cloned().collect::<Vec<i32>>());
        println!("Inter: {:?}", a.intersection(&b).cloned().collect::<Vec<i32>>());
        println!("Union: {:?}", a.union(&b).cloned().collect::<Vec<i32>>());

        if let Some(x) = a.get(&2) {
            println!("Got {} from set!", x);
        }

        assert!(a.contains(&2), true);

        b.remove(&2);
        assert!(a.is_disjoint(&b));

        a.insert(3);
        assert!(a.is_superset(&b));
        assert!(b.is_subset(&a));

        assert_eq!(Some(3), a.replace(3));
        assert_eq!(None, a.replace(8));

        assert_eq!(Some(3), a.take(&3));
        assert!(!a.contains(&3));

        // append sets
        // split_off

        // sub, bitor, bitxor, bitand operators
        // into_iter (moves out)

        a.clear();
        assert!(a.is_empty());
    }
}
<commit_msg>[Rust] STD Library - Modules - collections - hash_map<commit_after>pub fn _collections() {
    println!("*** Collections ***");

    iterators();
    entries();

    binary_heap();
    btree_map();
    btree_set();

    hash_map();
    // hash set looks the same as btree_set..

    println!("");
}

fn iterators() {
    let mut vec = vec![1, 2, 3, 4];

    for x in vec.iter() {
        print!("{} ", x);
    }
    println!("");

    for x in vec.iter_mut() {
        *x += 1;
        print!("{} ", x);
    }
    println!("");

    let vec2 = vec![10, 20, 30, 40];
    vec.extend(vec2);

    use std::collections::VecDeque;
    let buf: VecDeque<_> = vec.into_iter().collect();
}

fn entries() {
    use std::collections::btree_map::BTreeMap;

    let mut count = BTreeMap::new();
    let message = "sea shells by the shore";

    for c in message.chars() {
        *count.entry(c).or_insert(0) += 1;
    }

    assert_eq!(Some(&4), count.get(&'s'));

    for (ch, count) in &count {
        print!("{}: {}, ", ch, count);
    }
    println!("");
}

fn binary_heap() {
    // BinaryHeap struct
    {
        use std::collections::BinaryHeap;

        let mut heap = BinaryHeap::new();

        // nothing there yet
        assert_eq!(None, heap.peek());

        // pushing onto the heap
        heap.push(1);
        heap.push(5);
        heap.push(2);

        // peek what's "on top"
        assert_eq!(Some(&5), heap.peek());

        // number of items in the heap
        assert_eq!(3, heap.len());

        // in "random" order
        for x in &heap {
            print!("{} ", x);
        }
        println!("");

        // popping is in correct order
        assert_eq!(Some(5), heap.pop());
        assert_eq!(Some(2), heap.pop());
        assert_eq!(Some(1), heap.pop());
        assert_eq!(None, heap.pop());

        // clear anything that remains
        heap.clear();

        // not heap is empty
        assert!(heap.is_empty());

        // creating with preallocated capacity
        let mut heap = BinaryHeap::with_capacity(10);
        assert!(heap.capacity() >= 10);
        heap.push(4);

        *heap.peek_mut().unwrap() += 1;
        assert_eq!(Some(&5), heap.peek());

        heap.reserve_exact(8);
        heap.reserve(8);
        heap.shrink_to_fit();

        heap.push(3);
        heap.push(7);
        heap.push(4);

        // println!("Heap into vec: {:?}", heap.into_vec());
        println!("Heap into sorted vec: {:?}", heap.into_sorted_vec());

        let mut heap = BinaryHeap::new();
        heap.push(3);
        heap.push(7);
        heap.push(4);

        for x in heap.drain() {
            print!("{} ", x);
        }
        println!("");

        assert!(heap.is_empty());

        let v = vec![-4, 8, 3, 6, -3];
        let mut a = BinaryHeap::from(v);

        let v = vec![-20, 5, 43];
        let mut b = BinaryHeap::from(v);

        a.append(&mut b);

        println!("{:?}", a.into_sorted_vec());

        assert!(b.is_empty());
    }
}

fn btree_map() {
    // general example
    {
        use std::collections::BTreeMap;

        let mut movie_reviews = BTreeMap::new();

        // review some movies
        movie_reviews.insert("Pulp Fiction", "Masterpiece");
        movie_reviews.insert("The Godfather", "Very enjoyable");
        movie_reviews.insert("The Blues Brothers", "Eye lyked it alot");

        // check for a specific one
        if !movie_reviews.contains_key("Les Misérables") {
            println!("We've got {} reviews, but Les Misérables ain't one.",
                     movie_reviews.len());
        }

        // this one has spelling mistakes
        movie_reviews.remove("The Blues Brothers");

        // look up the values associated with some keys
        let to_find = ["Up!", "The Godfather"];

        for book in &to_find {
            match movie_reviews.get(book) {
                Some(review) => println!("{}: {}", book, review),
                None => println!("{} is unreviewed.", book),
            }
        }

        // iterate over everything
        for (movie, review) in &movie_reviews {
            println!("{}: \"{}\"", movie, review);

        }
    }

    // entry api
    {
        use std::collections::BTreeMap;

        let mut player_stats = BTreeMap::new();

        fn random_stat_buff() -> u8 {
            42
        }

        // insert a key only if it doesn't exist
        player_stats.entry("health").or_insert(100);

        // same, just using a function
        player_stats.entry("defence").or_insert_with(random_stat_buff);

        // update a key guarding against it possibly not being set
        let stat = player_stats.entry("attack").or_insert(100);
        *stat += random_stat_buff();
    }

    // methods on a BTreeMap
    {
        use std::collections::BTreeMap;

        let mut map = BTreeMap::new();

        map.insert(1, "a");

        if let Some(x) = map.get_mut(&1) {
            *x = "b";
        }

        assert_eq!(map.entry(1).key(), &1);

        map.clear();
        assert!(map.is_empty());

        // methods on entry struct
    }
}

fn btree_set() {
    // general example
    {
        use std::collections::BTreeSet;

        let mut books = BTreeSet::new();

        books.insert("A Dance with Dragons");
        books.insert("To Kill a Mockingbird");
        books.insert("The Odyssey");
        books.insert("The Great Gatsby");

        // check for a specific one
        if !books.contains("The Winds of Winter") {
            println!("We have {} books, but The Winds of Winter ain't one.",
                     books.len());
        }

        books.remove("The Odyssey");

        for book in &books {
            println!("{}, ", book);
        }
        println!("");
    }

    // methods
    {
        use std::collections::BTreeSet;

        let mut a = BTreeSet::new();
        a.insert(1);
        a.insert(2);

        let mut b = BTreeSet::new();
        b.insert(2);
        b.insert(3);

        println!("Diff: {:?}", a.difference(&b).cloned().collect::<Vec<i32>>());
        println!("Sym diff: {:?}",
                 a.symmetric_difference(&b).cloned().collect::<Vec<i32>>());
        println!("Inter: {:?}", a.intersection(&b).cloned().collect::<Vec<i32>>());
        println!("Union: {:?}", a.union(&b).cloned().collect::<Vec<i32>>());

        if let Some(x) = a.get(&2) {
            println!("Got {} from set!", x);
        }

        assert!(a.contains(&2), true);

        b.remove(&2);
        assert!(a.is_disjoint(&b));

        a.insert(3);
        assert!(a.is_superset(&b));
        assert!(b.is_subset(&a));

        assert_eq!(Some(3), a.replace(3));
        assert_eq!(None, a.replace(8));

        assert_eq!(Some(3), a.take(&3));
        assert!(!a.contains(&3));

        // append sets
        // split_off

        // sub, bitor, bitxor, bitand operators
        // into_iter (moves out)

        a.clear();
        assert!(a.is_empty());
    }
}

fn hash_map() {
    use std::collections::HashMap;

    let mut book_reviews = HashMap::new();

    book_reviews.insert("Grimm's Fairy Tales", "Masterpiece.");
    book_reviews.insert("A Game of Thrones", "Exceptional.");
    book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot.");

    if !book_reviews.contains_key("Les Misérables") {
        println!("We've got {} reviews, but Les Misérables ain't one.",
                 book_reviews.len());
    }

    book_reviews.remove("The Adventures of Sherlock Holmes");

    let to_find = ["A Game of Thrones", "Harry Potter"];
    for book in &to_find {
        match book_reviews.get(book) {
            Some(review) => println!("{}: {}", book, review),
            None => println!("{} is unreviewed.", book),
        }
    }

    for (book, review) in &book_reviews {
        println!("{}: {}", book, review);
    }

    // hash_map implements the entry api

    // to use types in a HashMap, derive Eq, PartialEq & Hash

    let timber_resources: HashMap<&str, i32> =
        [("Norway", 100), ("Denmark", 50), ("Iceland", 10)]
        .iter().cloned().collect();
}
<|endoftext|>


<commit_before>use mli::{Backward, Forward, Train};
use ndarray::{azip, Array, Array2};
use itertools::izip;

#[derive(Clone, Debug)]
pub struct Map2Many<G>(pub Array2<G>);

impl<G, Input> Forward<Array2<Input>> for Map2Many<G>
where
    G: Forward<Input>,
{
    type Internal = Array2<G::Internal>;
    type Output = Array2<G::Output>;

    fn forward(&self, input: &Array2<Input>) -> (Self::Internal, Self::Output) {
        assert_eq!(input.shape(), self.0.shape());
        let both_vec: Vec<(G::Internal, G::Output)> = input
            .iter()
            .zip(self.0.iter())
            .map(|(input, op)| op.forward(input))
            .collect();
        let (internal_vec, output_vec) = both_vec.into_iter().fold(
            (vec![], vec![]),
            |(mut internal_vec, mut output_vec), (internal, output)| {
                internal_vec.push(internal);
                output_vec.push(output);
                (internal_vec, output_vec)
            },
        );
        let internal_array = Array::from_shape_vec(input.raw_dim(), internal_vec).unwrap();
        let output_array = Array::from_shape_vec(input.raw_dim(), output_vec).unwrap();
        (internal_array, output_array)
    }
}

impl<G, Input, OutputDelta> Backward<Array2<Input>, Array2<OutputDelta>> for Map2Many<G>
where
    G: Backward<Input, OutputDelta>,
{
    type InputDelta = Array2<G::InputDelta>;
    type TrainDelta = Array2<G::TrainDelta>;

    fn backward(
        &self,
        input: &Array2<Input>,
        internal: &Self::Internal,
        output_delta: &Array2<OutputDelta>,
    ) -> (Self::InputDelta, Self::TrainDelta) {
        assert_eq!(input.shape(), self.0.shape());
        let both_vec: Vec<(G::InputDelta, G::TrainDelta)> = izip!(input.iter(), internal.iter(), output_delta.iter(), self.0.iter())
            .map(|(input, internal, output_delta, op)| op.backward(input, internal, output_delta))
            .collect();
        let (input_delta_vec, train_delta_vec) = both_vec.into_iter().fold(
            (vec![], vec![]),
            |(mut input_delta_vec, mut train_delta_vec), (input_delta, train_delta)| {
                input_delta_vec.push(input_delta);
                train_delta_vec.push(train_delta);
                (input_delta_vec, train_delta_vec)
            },
        );
        let input_delta_array = Array::from_shape_vec(input.raw_dim(), input_delta_vec).unwrap();
        let train_delta_array = Array::from_shape_vec(input.raw_dim(), train_delta_vec).unwrap();
        (input_delta_array, train_delta_array)
    }
}
<commit_msg>impl Train for Map2Many<commit_after>use mli::{Backward, Forward, Train};
use ndarray::{azip, Array, Array2};
use itertools::izip;

#[derive(Clone, Debug)]
pub struct Map2Many<G>(pub Array2<G>);

impl<G, Input> Forward<Array2<Input>> for Map2Many<G>
where
    G: Forward<Input>,
{
    type Internal = Array2<G::Internal>;
    type Output = Array2<G::Output>;

    fn forward(&self, input: &Array2<Input>) -> (Self::Internal, Self::Output) {
        assert_eq!(input.shape(), self.0.shape());
        let both_vec: Vec<(G::Internal, G::Output)> = input
            .iter()
            .zip(self.0.iter())
            .map(|(input, op)| op.forward(input))
            .collect();
        let (internal_vec, output_vec) = both_vec.into_iter().fold(
            (vec![], vec![]),
            |(mut internal_vec, mut output_vec), (internal, output)| {
                internal_vec.push(internal);
                output_vec.push(output);
                (internal_vec, output_vec)
            },
        );
        let internal_array = Array::from_shape_vec(input.raw_dim(), internal_vec).unwrap();
        let output_array = Array::from_shape_vec(input.raw_dim(), output_vec).unwrap();
        (internal_array, output_array)
    }
}

impl<G, Input, OutputDelta> Backward<Array2<Input>, Array2<OutputDelta>> for Map2Many<G>
where
    G: Backward<Input, OutputDelta>,
{
    type InputDelta = Array2<G::InputDelta>;
    type TrainDelta = Array2<G::TrainDelta>;

    fn backward(
        &self,
        input: &Array2<Input>,
        internal: &Self::Internal,
        output_delta: &Array2<OutputDelta>,
    ) -> (Self::InputDelta, Self::TrainDelta) {
        assert_eq!(input.shape(), self.0.shape());
        let both_vec: Vec<(G::InputDelta, G::TrainDelta)> = izip!(input.iter(), internal.iter(), output_delta.iter(), self.0.iter())
            .map(|(input, internal, output_delta, op)| op.backward(input, internal, output_delta))
            .collect();
        let (input_delta_vec, train_delta_vec) = both_vec.into_iter().fold(
            (vec![], vec![]),
            |(mut input_delta_vec, mut train_delta_vec), (input_delta, train_delta)| {
                input_delta_vec.push(input_delta);
                train_delta_vec.push(train_delta);
                (input_delta_vec, train_delta_vec)
            },
        );
        let input_delta_array = Array::from_shape_vec(input.raw_dim(), input_delta_vec).unwrap();
        let train_delta_array = Array::from_shape_vec(input.raw_dim(), train_delta_vec).unwrap();
        (input_delta_array, train_delta_array)
    }
}

impl<G, Input, OutputDelta> Train<Array2<Input>, Array2<OutputDelta>> for Map2Many<G>
where
    G: Train<Input, OutputDelta>,
{
    fn train(&mut self, train_delta: &Self::TrainDelta) {
        let mut ops = self.0.view_mut();
        let train_delta = train_delta.view();
        azip!(mut ops, ref train_delta in {
            ops.train(train_delta);
        });
    }
}
<|endoftext|>


<commit_before>
use na::{Rotation};
use ecs::{DataHelper, EntityIter, System};
use ecs::system::entity::{EntityProcess};
use protobuf::repeated::RepeatedField;

use contracts::actions::{Active};
use contracts::ship::{PhysicsState, Ship}; // TODO move out for this reason
use contracts::world::{Snapshot};

use sim::{JmpComponents, JmpServices};

// I guess move this out too... TODO
pub struct SnapshotProcess;

impl System for SnapshotProcess { type Components = JmpComponents; type Services = JmpServices; }

impl EntityProcess for SnapshotProcess {
    fn process(&mut self, entities: EntityIter<JmpComponents>, data: &mut DataHelper<JmpComponents, JmpServices>) {
        let mut snapshot = Snapshot::new();
        let mut ships: Vec<Ship> = Vec::new();
        for e in entities {
            let mut ship = Ship::new();
            ship.set_entityId(e.id());
            let structure = data.structure[e].contract();
            ship.set_structure(structure);
            let ref body = data.physics_handle[e].handle.borrow();
            let mut physics_state = PhysicsState::new();
            physics_state.set_x(body.position().translation.x);
            physics_state.set_y(body.position().translation.y);
            physics_state.set_theta(body.position().rotation.rotation().x);
            physics_state.set_vx(body.lin_vel().x);
            physics_state.set_vy(body.lin_vel().y);
            physics_state.set_omega(body.ang_vel().x);
            ship.set_physicsState(physics_state);
            let mut active = Active::new();
            active.set_groups(data.active_thrusters[e].clone());
            ship.set_active(active);
            ships.push(ship);
        }
        println!("Serializing {} structures in snapshot", ships.len());
        snapshot.set_ships(RepeatedField::from_vec(ships));
        data.services.snapshot = Some(snapshot);
    }
}<commit_msg>moved it!<commit_after>
use na::{Rotation};
use ecs::{DataHelper, EntityIter, System};
use ecs::system::entity::{EntityProcess};
use protobuf::repeated::RepeatedField;

use contracts::actions::{Active};
use contracts::ship::{PhysicsState, Ship}; // TODO move out for this reason
use contracts::world::{Snapshot};

use sim::{JmpComponents, JmpServices};

pub struct SnapshotProcess;

impl System for SnapshotProcess { type Components = JmpComponents; type Services = JmpServices; }

impl EntityProcess for SnapshotProcess {
    fn process(&mut self, entities: EntityIter<JmpComponents>, data: &mut DataHelper<JmpComponents, JmpServices>) {
        let mut snapshot = Snapshot::new();
        let mut ships: Vec<Ship> = Vec::new();
        for e in entities {
            let mut ship = Ship::new();
            ship.set_entityId(e.id());
            let structure = data.structure[e].contract();
            ship.set_structure(structure);
            let ref body = data.physics_handle[e].handle.borrow();
            let mut physics_state = PhysicsState::new();
            physics_state.set_x(body.position().translation.x);
            physics_state.set_y(body.position().translation.y);
            physics_state.set_theta(body.position().rotation.rotation().x);
            physics_state.set_vx(body.lin_vel().x);
            physics_state.set_vy(body.lin_vel().y);
            physics_state.set_omega(body.ang_vel().x);
            ship.set_physicsState(physics_state);
            let mut active = Active::new();
            active.set_groups(data.active_thrusters[e].clone());
            ship.set_active(active);
            ships.push(ship);
        }
        println!("Serializing {} structures in snapshot", ships.len());
        snapshot.set_ships(RepeatedField::from_vec(ships));
        data.services.snapshot = Some(snapshot);
    }
}<|endoftext|>


<commit_before>//! Contains traits responsible for the actual construction of SQL statements
//!
//! The types in this module are part of Diesel's public API, but are generally
//! only useful for implementing Diesel plugins. Applications should generally
//! not need to care about the types inside of this module.

#[macro_use]
mod query_id;
#[macro_use]
mod clause_macro;

mod ast_pass;
pub mod bind_collector;
mod debug_query;
mod delete_statement;
#[doc(hidden)]
pub mod functions;
#[doc(hidden)]
pub mod nodes;
mod distinct_clause;
mod group_by_clause;
mod limit_clause;
mod offset_clause;
mod order_clause;
mod returning_clause;
mod select_clause;
mod select_statement;
pub mod where_clause;
pub mod insert_statement;
pub mod update_statement;

pub use self::ast_pass::AstPass;
pub use self::bind_collector::BindCollector;
pub use self::debug_query::DebugQuery;
pub use self::query_id::QueryId;
#[doc(hidden)]
pub use self::select_statement::{BoxedSelectStatement, SelectStatement};
#[doc(inline)]
pub use self::update_statement::{AsChangeset, Changeset, IncompleteUpdateStatement,
                                 IntoUpdateTarget, UpdateStatement, UpdateTarget};
#[doc(inline)]
pub use self::insert_statement::{IncompleteDefaultInsertStatement, IncompleteInsertStatement};

use std::error::Error;

use backend::Backend;
use result::QueryResult;

#[doc(hidden)]
pub type Binds = Vec<Option<Vec<u8>>>;
pub type BuildQueryResult = Result<(), Box<Error + Send + Sync>>;

/// Apps should not need to concern themselves with this trait.
///
/// This is the trait used to actually construct a SQL query. You will take one
/// of these as an argument if you're implementing
/// [`QueryFragment`](trait.QueryFragment.html) manually.
pub trait QueryBuilder<DB: Backend> {
    fn push_sql(&mut self, sql: &str);
    fn push_identifier(&mut self, identifier: &str) -> QueryResult<()>;
    fn push_bind_param(&mut self);
    fn finish(self) -> String;
}

/// A complete SQL query with a return type. This can be a select statement, or
/// a command such as `update` or `insert` with a `RETURNING` clause. Unlike
/// [`Expression`](../expression/trait.Expression.html), types implementing this
/// trait are guaranteed to be executable on their own.
pub trait Query {
    type SqlType;
}

impl<'a, T: Query> Query for &'a T {
    type SqlType = T::SqlType;
}

/// An untyped fragment of SQL. This may be a complete SQL command (such as
/// an update statement without a `RETURNING` clause), or a subsection (such as
/// our internal types used to represent a `WHERE` clause). All methods on
/// [`Connection`](../connection/trait.Connection.html) that execute a query require this
/// trait to be implemented.
pub trait QueryFragment<DB: Backend> {
    fn walk_ast(&self, pass: AstPass<DB>) -> QueryResult<()>;

    fn to_sql(&self, out: &mut DB::QueryBuilder) -> QueryResult<()> {
        self.walk_ast(AstPass::to_sql(out))
    }

    fn collect_binds(
        &self,
        out: &mut DB::BindCollector,
        metadata_lookup: &DB::MetadataLookup,
    ) -> QueryResult<()> {
        self.walk_ast(AstPass::collect_binds(out, metadata_lookup))
    }

    fn is_safe_to_cache_prepared(&self) -> QueryResult<bool> {
        let mut result = true;
        self.walk_ast(AstPass::is_safe_to_cache_prepared(&mut result))?;
        Ok(result)
    }
}

impl<T: ?Sized, DB> QueryFragment<DB> for Box<T>
where
    DB: Backend,
    T: QueryFragment<DB>,
{
    fn walk_ast(&self, pass: AstPass<DB>) -> QueryResult<()> {
        QueryFragment::walk_ast(&**self, pass)
    }
}

impl<'a, T: ?Sized, DB> QueryFragment<DB> for &'a T
where
    DB: Backend,
    T: QueryFragment<DB>,
{
    fn walk_ast(&self, pass: AstPass<DB>) -> QueryResult<()> {
        QueryFragment::walk_ast(&**self, pass)
    }
}

impl<DB: Backend> QueryFragment<DB> for () {
    fn walk_ast(&self, _: AstPass<DB>) -> QueryResult<()> {
        Ok(())
    }
}

/// Types that can be converted into a complete, typed SQL query. This is used
/// internally to automatically add the right select clause when none is
/// specified, or to automatically add `RETURNING *` in certain contexts
pub trait AsQuery {
    type SqlType;
    type Query: Query<SqlType = Self::SqlType>;

    fn as_query(self) -> Self::Query;
}

impl<T: Query> AsQuery for T {
    type SqlType = <Self as Query>::SqlType;
    type Query = Self;

    fn as_query(self) -> Self::Query {
        self
    }
}

/// Takes a query `QueryFragment` expression as an argument and returns a type
/// that implements `fmt::Display` and `fmt::Debug` to show the query.
///
/// The `Display` implementation will show the exact query being sent to the
/// server, with a comment showing the values of the bind parameters. The
/// `Debug` implementation will include the same information in a more
/// structured form, and respects pretty printing.
///
/// # Example
///
/// ### Returning SQL from a count statement:
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// #
/// # #[macro_use] extern crate diesel;
/// # use diesel::*;
/// # use schema::*;
/// #
/// # fn main() {
/// #   use schema::users::dsl::*;
/// let sql = debug_query::<DB, _>(&users.count()).to_string();
/// # if cfg!(feature = "postgres") {
/// #     assert_eq!(sql, r#"SELECT COUNT(*) FROM "users" -- binds: []"#);
/// # } else {
/// assert_eq!(sql, "SELECT COUNT(*) FROM `users` -- binds: []");
/// # }
///
/// let query = users.find(1);
/// let debug = debug_query::<DB, _>(&query);
/// # if cfg!(feature = "postgres") {
/// #     assert_eq!(debug.to_string(), "SELECT \"users\".\"id\", \"users\".\"name\" \
/// #         FROM \"users\" WHERE \"users\".\"id\" = $1 -- binds: [1]");
/// # } else {
/// assert_eq!(debug.to_string(), "SELECT `users`.`id`, `users`.`name` FROM `users` \
///     WHERE `users`.`id` = ? -- binds: [1]");
/// # }
///
/// let debug = format!("{:?}", debug);
/// # if !cfg!(feature = "postgres") { // Escaping that string is a pain
/// let expected = "Query { \
///     sql: \"SELECT `users`.`id`, `users`.`name` FROM `users` WHERE \
///         `users`.`id` = ?\", \
///     binds: [1] \
/// }";
/// assert_eq!(debug, expected);
/// # }
/// # }
/// ```
pub fn debug_query<DB, T>(query: &T) -> DebugQuery<T, DB> {
    DebugQuery::new(query)
}

#[doc(hidden)]
#[cfg(all(feature = "with-deprecated", feature = "postgres"))]
pub fn deprecated_debug_sql<T>(query: &T) -> String
where
    T: QueryFragment<::pg::Pg>,
{
    debug_query(query).to_string()
}

#[doc(hidden)]
#[cfg(all(feature = "with-deprecated", feature = "mysql", not(feature = "postgres")))]
pub fn deprecated_debug_sql<T>(query: &T) -> String
where
    T: QueryFragment<::mysql::Mysql>,
{
    debug_query(query).to_string()
}

#[doc(hidden)]
#[cfg(all(feature = "with-deprecated", feature = "sqlite",
            not(any(feature = "postgres", feature = "mysql"))))]
pub fn deprecated_debug_sql<T>(query: &T) -> String
where
    T: QueryFragment<::sqlite::Sqlite>,
{
    debug_query(query).to_string()
}

#[doc(hidden)]
#[cfg(all(feature = "with-deprecated",
            not(any(feature = "postgres", feature = "mysql", feature = "sqlite"))))]
pub fn deprecated_debug_sql<T>(_query: &T) -> String {
    String::from(
        "At least one backend must be enabled to generated debug SQL",
    )
}
<commit_msg>Document the items on `AsQuery` [ci skip]<commit_after>//! Contains traits responsible for the actual construction of SQL statements
//!
//! The types in this module are part of Diesel's public API, but are generally
//! only useful for implementing Diesel plugins. Applications should generally
//! not need to care about the types inside of this module.

#[macro_use]
mod query_id;
#[macro_use]
mod clause_macro;

mod ast_pass;
pub mod bind_collector;
mod debug_query;
mod delete_statement;
#[doc(hidden)]
pub mod functions;
#[doc(hidden)]
pub mod nodes;
mod distinct_clause;
mod group_by_clause;
mod limit_clause;
mod offset_clause;
mod order_clause;
mod returning_clause;
mod select_clause;
mod select_statement;
pub mod where_clause;
pub mod insert_statement;
pub mod update_statement;

pub use self::ast_pass::AstPass;
pub use self::bind_collector::BindCollector;
pub use self::debug_query::DebugQuery;
pub use self::query_id::QueryId;
#[doc(hidden)]
pub use self::select_statement::{BoxedSelectStatement, SelectStatement};
#[doc(inline)]
pub use self::update_statement::{AsChangeset, Changeset, IncompleteUpdateStatement,
                                 IntoUpdateTarget, UpdateStatement, UpdateTarget};
#[doc(inline)]
pub use self::insert_statement::{IncompleteDefaultInsertStatement, IncompleteInsertStatement};

use std::error::Error;

use backend::Backend;
use result::QueryResult;

#[doc(hidden)]
pub type Binds = Vec<Option<Vec<u8>>>;
pub type BuildQueryResult = Result<(), Box<Error + Send + Sync>>;

/// Apps should not need to concern themselves with this trait.
///
/// This is the trait used to actually construct a SQL query. You will take one
/// of these as an argument if you're implementing
/// [`QueryFragment`](trait.QueryFragment.html) manually.
pub trait QueryBuilder<DB: Backend> {
    fn push_sql(&mut self, sql: &str);
    fn push_identifier(&mut self, identifier: &str) -> QueryResult<()>;
    fn push_bind_param(&mut self);
    fn finish(self) -> String;
}

/// A complete SQL query with a return type. This can be a select statement, or
/// a command such as `update` or `insert` with a `RETURNING` clause. Unlike
/// [`Expression`](../expression/trait.Expression.html), types implementing this
/// trait are guaranteed to be executable on their own.
pub trait Query {
    type SqlType;
}

impl<'a, T: Query> Query for &'a T {
    type SqlType = T::SqlType;
}

/// An untyped fragment of SQL. This may be a complete SQL command (such as
/// an update statement without a `RETURNING` clause), or a subsection (such as
/// our internal types used to represent a `WHERE` clause). All methods on
/// [`Connection`](../connection/trait.Connection.html) that execute a query require this
/// trait to be implemented.
pub trait QueryFragment<DB: Backend> {
    fn walk_ast(&self, pass: AstPass<DB>) -> QueryResult<()>;

    fn to_sql(&self, out: &mut DB::QueryBuilder) -> QueryResult<()> {
        self.walk_ast(AstPass::to_sql(out))
    }

    fn collect_binds(
        &self,
        out: &mut DB::BindCollector,
        metadata_lookup: &DB::MetadataLookup,
    ) -> QueryResult<()> {
        self.walk_ast(AstPass::collect_binds(out, metadata_lookup))
    }

    fn is_safe_to_cache_prepared(&self) -> QueryResult<bool> {
        let mut result = true;
        self.walk_ast(AstPass::is_safe_to_cache_prepared(&mut result))?;
        Ok(result)
    }
}

impl<T: ?Sized, DB> QueryFragment<DB> for Box<T>
where
    DB: Backend,
    T: QueryFragment<DB>,
{
    fn walk_ast(&self, pass: AstPass<DB>) -> QueryResult<()> {
        QueryFragment::walk_ast(&**self, pass)
    }
}

impl<'a, T: ?Sized, DB> QueryFragment<DB> for &'a T
where
    DB: Backend,
    T: QueryFragment<DB>,
{
    fn walk_ast(&self, pass: AstPass<DB>) -> QueryResult<()> {
        QueryFragment::walk_ast(&**self, pass)
    }
}

impl<DB: Backend> QueryFragment<DB> for () {
    fn walk_ast(&self, _: AstPass<DB>) -> QueryResult<()> {
        Ok(())
    }
}

/// Types that can be converted into a complete, typed SQL query. This is used
/// internally to automatically add the right select clause when none is
/// specified, or to automatically add `RETURNING *` in certain contexts
pub trait AsQuery {
    /// The SQL type of `Self::Query`
    type SqlType;

    /// What kind of query does this type represent?
    type Query: Query<SqlType = Self::SqlType>;

    /// Converts a type which semantically represents a SQL query into the
    /// actual query being executed. See the trait level docs for more.
    fn as_query(self) -> Self::Query;
}

impl<T: Query> AsQuery for T {
    type SqlType = <Self as Query>::SqlType;
    type Query = Self;

    fn as_query(self) -> Self::Query {
        self
    }
}

/// Takes a query `QueryFragment` expression as an argument and returns a type
/// that implements `fmt::Display` and `fmt::Debug` to show the query.
///
/// The `Display` implementation will show the exact query being sent to the
/// server, with a comment showing the values of the bind parameters. The
/// `Debug` implementation will include the same information in a more
/// structured form, and respects pretty printing.
///
/// # Example
///
/// ### Returning SQL from a count statement:
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// #
/// # #[macro_use] extern crate diesel;
/// # use diesel::*;
/// # use schema::*;
/// #
/// # fn main() {
/// #   use schema::users::dsl::*;
/// let sql = debug_query::<DB, _>(&users.count()).to_string();
/// # if cfg!(feature = "postgres") {
/// #     assert_eq!(sql, r#"SELECT COUNT(*) FROM "users" -- binds: []"#);
/// # } else {
/// assert_eq!(sql, "SELECT COUNT(*) FROM `users` -- binds: []");
/// # }
///
/// let query = users.find(1);
/// let debug = debug_query::<DB, _>(&query);
/// # if cfg!(feature = "postgres") {
/// #     assert_eq!(debug.to_string(), "SELECT \"users\".\"id\", \"users\".\"name\" \
/// #         FROM \"users\" WHERE \"users\".\"id\" = $1 -- binds: [1]");
/// # } else {
/// assert_eq!(debug.to_string(), "SELECT `users`.`id`, `users`.`name` FROM `users` \
///     WHERE `users`.`id` = ? -- binds: [1]");
/// # }
///
/// let debug = format!("{:?}", debug);
/// # if !cfg!(feature = "postgres") { // Escaping that string is a pain
/// let expected = "Query { \
///     sql: \"SELECT `users`.`id`, `users`.`name` FROM `users` WHERE \
///         `users`.`id` = ?\", \
///     binds: [1] \
/// }";
/// assert_eq!(debug, expected);
/// # }
/// # }
/// ```
pub fn debug_query<DB, T>(query: &T) -> DebugQuery<T, DB> {
    DebugQuery::new(query)
}

#[doc(hidden)]
#[cfg(all(feature = "with-deprecated", feature = "postgres"))]
pub fn deprecated_debug_sql<T>(query: &T) -> String
where
    T: QueryFragment<::pg::Pg>,
{
    debug_query(query).to_string()
}

#[doc(hidden)]
#[cfg(all(feature = "with-deprecated", feature = "mysql", not(feature = "postgres")))]
pub fn deprecated_debug_sql<T>(query: &T) -> String
where
    T: QueryFragment<::mysql::Mysql>,
{
    debug_query(query).to_string()
}

#[doc(hidden)]
#[cfg(all(feature = "with-deprecated", feature = "sqlite",
            not(any(feature = "postgres", feature = "mysql"))))]
pub fn deprecated_debug_sql<T>(query: &T) -> String
where
    T: QueryFragment<::sqlite::Sqlite>,
{
    debug_query(query).to_string()
}

#[doc(hidden)]
#[cfg(all(feature = "with-deprecated",
            not(any(feature = "postgres", feature = "mysql", feature = "sqlite"))))]
pub fn deprecated_debug_sql<T>(_query: &T) -> String {
    String::from(
        "At least one backend must be enabled to generated debug SQL",
    )
}
<|endoftext|>


<commit_before>use game_map::RoomId;
use sized_enum::SizedEnum;
use direction::Direction;
use game_state::{GameState, GameMode};
use command::{CommandProcessor, HelpInfo};
use items::Item;
use platform;
use util;

use self::PrimaryCommand::*;

const MIN_STRENGTH_WARNING: i32 = 10;

#[derive(Debug)]
pub enum PrimaryCommand {
  Go(Direction),
  Inventory,
  Look,
  EatFood,
  MagicAmulet,
  Quit,
}

impl CommandProcessor<PrimaryCommand> for PrimaryCommand {
  fn get_help() -> Vec<HelpInfo> {
    HelpInfo::list(vec![
      ('n', "go north"),
      ('s', "go south"),
      ('e', "go east"),
      ('w', "go west"),
      ('u', "go up"),
      ('d', "go down"),
      ('c', "consume food"),
      ('m', "use magic amulet (if equipped)"),
      ('i', "inventory/buy provisions"),
      ('l', "look around"),
      ('q', "quit"),
    ])
  }

  fn from_char(c: char) -> Option<PrimaryCommand> {
    match c {
      'n' => Some(Go(Direction::North)),
      's' => Some(Go(Direction::South)),
      'e' => Some(Go(Direction::East)),
      'w' => Some(Go(Direction::West)),
      'u' => Some(Go(Direction::Up)),
      'd' => Some(Go(Direction::Down)),
      'c' => Some(EatFood),
      'm' => Some(MagicAmulet),
      'i' => Some(Inventory),
      'l' => Some(Look),
      'q' => Some(Quit),
      _ => None,
    }
  }
}

impl<'a> GameState<'a> {
  fn print_status_report(&self) {
    if self.strength <= MIN_STRENGTH_WARNING {
      println!("Warning, {}! Your strength is running low.\n",
               self.player_name);
    }
    println!("{}, your strength is {}.", self.player_name, self.strength);
    self.print_wealth();
    if self.food > 0 { self.print_food(); }
    if self.suit {
      println!("You are wearing armor.");
    }
    let item_names = self.get_item_names();
    if item_names.len() > 0 {
      println!("You are carrying {}.",
               util::friendly_join(self.get_item_names()));
    }
  }

  fn get_item_names(&self) -> Vec<&str> {
    let mut items = Vec::new();
    if self.axe { items.push(Item::Axe.as_str()) }
    if self.sword { items.push(Item::Sword.as_str()) }
    if self.amulet { items.push(Item::Amulet.as_str()) }
    items
  }

  fn use_amulet(&mut self) {
    if self.amulet {
      platform::writeln_with_wrapping(
        "You invoke the magic amulet and are whisked \
         away to somewhere else..."
      );
      self.pause();
      loop {
        let room_id = RoomId::random();
        if room_id != self.curr_room {
          self.curr_room = room_id;
          self.show_desc = true;
          self.process_move();
          break;
        }
      }
    } else {
      println!("You don't have the amulet, {}.", self.player_name);
    }
  }

  pub fn tick_primary_mode(&mut self) {
    if self.show_desc {
      match self.curr_room {
        RoomId::Lift => {
          println!("You have entered the lift...");
          self.pause();
          println!("It slowly descends...");
          self.pause();
          self.curr_room = RoomId::RearVestibule;
          return;
        },
        RoomId::Exit => {
          println!("\nYou've done it!!");
          self.pause();
          println!("That was the exit from the castle.");
          self.pause();
          println!("\nYou have succeeded, {}!", self.player_name);
          println!("\nYou managed to get out of the castle.");
          self.pause();
          println!("\nWell done!");
          self.pause();
          self.finish_game();
          return;
        },
        _ => {
          platform::clear_screen();
          self.print_status_report();
          println!("");
          if self.curr_room != RoomId::Entrance && !self.light {
            println!("It is too dark to see anything.");
          } else {
            platform::writeln_with_wrapping(
              self.map.room(self.curr_room).description
            );
          }
          println!("");
        }
      }
      self.show_desc = false;
    }

    if let Some(cmd) = PrimaryCommand::get() {
      match cmd {
        Go(dir) => {
          if let Some(room) = self.map.room(self.curr_room).get_exit(dir) {
            self.curr_room = room;
            self.show_desc = true;
            self.process_move();
          } else {
            println!("You can't go that way.");
          }
        },
        Inventory => { self.set_mode(GameMode::Inventory) },
        Look => { self.show_desc = true },
        EatFood => {
          if self.food == 0 {
            println!("You have no food!");
          } else {
            self.set_mode(GameMode::EatFood);
          }
        },
        MagicAmulet => { self.use_amulet() },
        Quit => { self.finish_game() }
      }
    };
  }
}
<commit_msg>Display treasure/terror in room description.<commit_after>use game_map::RoomId;
use sized_enum::SizedEnum;
use direction::Direction;
use game_state::{GameState, GameMode};
use game_map::RoomContents;
use command::{CommandProcessor, HelpInfo};
use items::Item;
use platform;
use util;

use self::PrimaryCommand::*;

const MIN_STRENGTH_WARNING: i32 = 10;

#[derive(Debug)]
pub enum PrimaryCommand {
  Go(Direction),
  Inventory,
  Look,
  EatFood,
  MagicAmulet,
  Quit,
}

impl CommandProcessor<PrimaryCommand> for PrimaryCommand {
  fn get_help() -> Vec<HelpInfo> {
    HelpInfo::list(vec![
      ('n', "go north"),
      ('s', "go south"),
      ('e', "go east"),
      ('w', "go west"),
      ('u', "go up"),
      ('d', "go down"),
      ('c', "consume food"),
      ('m', "use magic amulet (if equipped)"),
      ('i', "inventory/buy provisions"),
      ('l', "look around"),
      ('q', "quit"),
    ])
  }

  fn from_char(c: char) -> Option<PrimaryCommand> {
    match c {
      'n' => Some(Go(Direction::North)),
      's' => Some(Go(Direction::South)),
      'e' => Some(Go(Direction::East)),
      'w' => Some(Go(Direction::West)),
      'u' => Some(Go(Direction::Up)),
      'd' => Some(Go(Direction::Down)),
      'c' => Some(EatFood),
      'm' => Some(MagicAmulet),
      'i' => Some(Inventory),
      'l' => Some(Look),
      'q' => Some(Quit),
      _ => None,
    }
  }
}

impl<'a> GameState<'a> {
  fn print_status_report(&self) {
    if self.strength <= MIN_STRENGTH_WARNING {
      println!("Warning, {}! Your strength is running low.\n",
               self.player_name);
    }
    println!("{}, your strength is {}.", self.player_name, self.strength);
    self.print_wealth();
    if self.food > 0 { self.print_food(); }
    if self.suit {
      println!("You are wearing armor.");
    }
    let item_names = self.get_item_names();
    if item_names.len() > 0 {
      println!("You are carrying {}.",
               util::friendly_join(self.get_item_names()));
    }
  }

  fn get_item_names(&self) -> Vec<&str> {
    let mut items = Vec::new();
    if self.axe { items.push(Item::Axe.as_str()) }
    if self.sword { items.push(Item::Sword.as_str()) }
    if self.amulet { items.push(Item::Amulet.as_str()) }
    items
  }

  fn use_amulet(&mut self) {
    if self.amulet {
      platform::writeln_with_wrapping(
        "You invoke the magic amulet and are whisked \
         away to somewhere else..."
      );
      self.pause();
      loop {
        let room_id = RoomId::random();
        if room_id != self.curr_room {
          self.curr_room = room_id;
          self.show_desc = true;
          self.process_move();
          break;
        }
      }
    } else {
      println!("You don't have the amulet, {}.", self.player_name);
    }
  }

  pub fn tick_primary_mode(&mut self) {
    if self.show_desc {
      match self.curr_room {
        RoomId::Lift => {
          println!("You have entered the lift...");
          self.pause();
          println!("It slowly descends...");
          self.pause();
          self.curr_room = RoomId::RearVestibule;
          return;
        },
        RoomId::Exit => {
          println!("\nYou've done it!!");
          self.pause();
          println!("That was the exit from the castle.");
          self.pause();
          println!("\nYou have succeeded, {}!", self.player_name);
          println!("\nYou managed to get out of the castle.");
          self.pause();
          println!("\nWell done!");
          self.pause();
          self.finish_game();
          return;
        },
        _ => {
          platform::clear_screen();
          self.print_status_report();
          println!("");
          if self.curr_room != RoomId::Entrance && !self.light {
            println!("It is too dark to see anything.");
          } else {
            let room = self.map.room(self.curr_room);
            platform::writeln_with_wrapping(room.description);
            room.contents.map(|c| match c {
              RoomContents::Treasure(amount) => {
                println!("\nThere is treasure here worth ${}.", amount);
              },
              RoomContents::Terror(monster_id) => {
                println!("\nDanger... There is a monster here....");
                // TODO: Finish this.
              },
            });
          }
          println!("");
        }
      }
      self.show_desc = false;
    }

    if let Some(cmd) = PrimaryCommand::get() {
      match cmd {
        Go(dir) => {
          if let Some(room) = self.map.room(self.curr_room).get_exit(dir) {
            self.curr_room = room;
            self.show_desc = true;
            self.process_move();
          } else {
            println!("You can't go that way.");
          }
        },
        Inventory => { self.set_mode(GameMode::Inventory) },
        Look => { self.show_desc = true },
        EatFood => {
          if self.food == 0 {
            println!("You have no food!");
          } else {
            self.set_mode(GameMode::EatFood);
          }
        },
        MagicAmulet => { self.use_amulet() },
        Quit => { self.finish_game() }
      }
    };
  }
}
<|endoftext|>


<commit_before>use jit::buffer::Buffer;

pub fn nop(buf: &mut Buffer) {
    buf.emit_u32(0);
}<commit_msg>aarch64: added fits_u5 and fits_i12<commit_after>use jit::buffer::Buffer;

pub fn nop(buf: &mut Buffer) {
    buf.emit_u32(0);
}

// pub fn add(rd: Reg, rn: Reg, imm: i32) {
//     assert!(fits_i12(imm));
// }

// fn class_addsub(rd: i32, rn: i32, imm: i32) -> u32 {
//     assert!(fits_i5(rd));
//     assert!(fits_i5(rn));
//     assert!(fits_i12(imm));
// }

fn fits_u5(imm: i32) -> bool {
    0 <= imm && imm < 32
}

fn fits_i12(imm: i32) -> bool {
    -2048 <= imm && imm < 2048
}

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

    #[test]
    fn test_fits_u5() {
        assert!(fits_u5(0));
        assert!(fits_u5(31));
        assert!(!fits_u5(32));
        assert!(!fits_u5(-1));
    }

    #[test]
    fn test_fits_i12() {
        assert!(fits_i12(0));
        assert!(fits_i12(-2048));
        assert!(fits_i12(2047));
        assert!(!fits_i12(-2049));
        assert!(!fits_i12(2048));
    }
}<|endoftext|>


<commit_before>use iron::prelude::*;
use iron::Handler;
use iron::response::modifiers::{Status, Body};
use iron::status;

// Re-export Logger and Router so you can use redstart::Router instead of redstart::router::Router.
pub use self::logger::Logger;
pub use self::urlparser::URLParser;
pub use self::permission::PermCheck;

mod logger;
mod urlparser;
mod permission;
// End Re-export

pub struct RedStart;

pub enum Controller
{
    Reservation,
    Administration,
    User,
}

impl Handler for RedStart
{
    fn call(&self, _: &mut Request) -> IronResult<Response>
    {
        Ok(Response::new().set(Status(status::Ok)).set(Body("Hello world!\n")))
    }

    fn catch(&self, _: &mut Request, err: IronError) -> (Response, IronResult<()>)
    {
        // Its definetely *not* pretty. But it works.
        match err.name()
        {
            "NotLoggedIn" => { (Response::new().set(Status(status::Unauthorized)), Ok(())) },
            "InsufficientPermissions" => { (Response::new().set(Status(status::Forbidden)), Ok(())) },
            "NoRoute" => { (Response::new().set(Status(status::NotFound)), Ok(())) },
            "MalformedRequest" => { (Response::new().set(Status(status::BadRequest)), Ok(())) },
            _ => { (Response::new().set(Status(status::InternalServerError)), Ok(())) },
        }
    }
}
<commit_msg>End of segment commit. Nothing is working as far as I can tell. :P<commit_after>use iron::prelude::*;
use iron::Handler;
use iron::response::modifiers::{Status, Body};
use iron::status;

use self::

// Re-export Logger and Router so you can use redstart::Router instead of redstart::router::Router.
pub use self::logger::Logger;
pub use self::urlparser::URLParser;
pub use self::permission::PermCheck;

mod logger;
mod urlparser;
mod permission;
// End Re-export

pub struct RedStart;

pub enum Controller
{
    Reservation,
    Administration,
    User,
}

impl Handler for RedStart
{
    fn call(&self, _: &mut Request) -> IronResult<Response>
    {
        // Define some arbitrary variables. ToDo: These should be set by URLParser later on
        let controller = Controller::Reservation;

        match controller
        {
            User => {},
            Reservation => {},
            Administration => {},
        }

        Ok(Response::new().set(Status(status::Ok)).set(Body("Hello world!\n")))
    }

    fn catch(&self, _: &mut Request, err: IronError) -> (Response, IronResult<()>)
    {
        // Its definetely *not* pretty. But it works.
        match err.name()
        {
            "NotLoggedIn" => { (Response::new().set(Status(status::Unauthorized)), Ok(())) },
            "InsufficientPermissions" => { (Response::new().set(Status(status::Forbidden)), Ok(())) },
            "NoRoute" => { (Response::new().set(Status(status::NotFound)), Ok(())) },
            "MalformedRequest" => { (Response::new().set(Status(status::BadRequest)), Ok(())) },
            _ => { (Response::new().set(Status(status::InternalServerError)), Ok(())) },
        }
    }
}
<|endoftext|>