<commit_before>//! This is a script for validating the platform support page in the rustc book.
//!
//! The script takes two arguments, the path to the Platform Support source
//! page, and the second argument is the path to `rustc`.

use std::collections::HashSet;

fn main() {
    let mut args = std::env::args().skip(1);
    let src = args.next().expect("expected source file as first argument");
    let filename = std::path::Path::new(&src).file_name().unwrap().to_str().unwrap();
    let rustc = args.next().expect("expected rustc as second argument");
    let output = std::process::Command::new(rustc)
        .arg("--print=target-list")
        .output()
        .expect("rustc should run");
    if !output.status.success() {
        eprintln!("rustc failed to run");
        std::process::exit(0);
    }
    let stdout = std::str::from_utf8(&output.stdout).expect("utf8");
    let target_list: HashSet<_> = stdout.lines().collect();

    let doc_targets_md = std::fs::read_to_string(&src).expect("failed to read input source");
    let doc_targets: HashSet<_> = doc_targets_md
        .lines()
        .filter(|line| line.starts_with('`') && line.contains('|'))
        .map(|line| line.split('`').skip(1).next().expect("expected target code span"))
        .collect();

    let missing: Vec<_> = target_list.difference(&doc_targets).collect();
    let extra: Vec<_> = doc_targets.difference(&target_list).collect();
    for target in &missing {
        eprintln!(
            "error: target `{}` is missing from {}\n\
            If this is a new target, please add it to {}.",
            target, filename, src
        );
    }
    for target in &extra {
        eprintln!(
            "error: target `{}` is in {}, but does not appear in the rustc target list\n\
            If the target has been removed, please edit {} and remove the target.",
            target, filename, src
        );
    }
    if !missing.is_empty() || !extra.is_empty() {
        std::process::exit(1);
    }
}
<commit_msg>tier-check: Check for lines with '[' such as those containing links<commit_after>//! This is a script for validating the platform support page in the rustc book.
//!
//! The script takes two arguments, the path to the Platform Support source
//! page, and the second argument is the path to `rustc`.

use std::collections::HashSet;

fn main() {
    let mut args = std::env::args().skip(1);
    let src = args.next().expect("expected source file as first argument");
    let filename = std::path::Path::new(&src).file_name().unwrap().to_str().unwrap();
    let rustc = args.next().expect("expected rustc as second argument");
    let output = std::process::Command::new(rustc)
        .arg("--print=target-list")
        .output()
        .expect("rustc should run");
    if !output.status.success() {
        eprintln!("rustc failed to run");
        std::process::exit(0);
    }
    let stdout = std::str::from_utf8(&output.stdout).expect("utf8");
    let target_list: HashSet<_> = stdout.lines().collect();

    let doc_targets_md = std::fs::read_to_string(&src).expect("failed to read input source");
    let doc_targets: HashSet<_> = doc_targets_md
        .lines()
        .filter(|line| line.starts_with(&['`', '['][..]) && line.contains('|'))
        .map(|line| line.split('`').skip(1).next().expect("expected target code span"))
        .collect();

    let missing: Vec<_> = target_list.difference(&doc_targets).collect();
    let extra: Vec<_> = doc_targets.difference(&target_list).collect();
    for target in &missing {
        eprintln!(
            "error: target `{}` is missing from {}\n\
            If this is a new target, please add it to {}.",
            target, filename, src
        );
    }
    for target in &extra {
        eprintln!(
            "error: target `{}` is in {}, but does not appear in the rustc target list\n\
            If the target has been removed, please edit {} and remove the target.",
            target, filename, src
        );
    }
    if !missing.is_empty() || !extra.is_empty() {
        std::process::exit(1);
    }
}
<|endoftext|>


<commit_before>use super::ssz::{decode_ssz_list, Decodable, DecodeError, Encodable, SszStream};
use super::{AggregatePublicKey, Signature};
use bls_aggregates::AggregateSignature as RawAggregateSignature;

/// A BLS aggregate signature.
///
/// This struct is a wrapper upon a base type and provides helper functions (e.g., SSZ
/// serialization).
#[derive(Debug, PartialEq, Clone)]
pub struct AggregateSignature(RawAggregateSignature);

impl AggregateSignature {
    /// Instantiate a new AggregateSignature.
    pub fn new() -> Self {
        AggregateSignature(RawAggregateSignature::new())
    }

    /// Add (aggregate) a signature to the `AggregateSignature`.
    pub fn add(&mut self, signature: &Signature) {
        self.0.add(signature.as_raw())
    }

    /// Verify the `AggregateSignature` against an `AggregatePublicKey`.
    ///
    /// Only returns `true` if the set of keys in the `AggregatePublicKey` match the set of keys
    /// that signed the `AggregateSignature`.
    pub fn verify(&mut self, msg: &[u8], avk: &AggregatePublicKey) -> bool {
        self.0.verify(msg, avk)
    }
}

impl Default for AggregateSignature {
    /// A "default" signature is a signature across an empty message by a secret key of 48 zeros.
    fn default() -> Self {
        AggregateSignature::new()
    }
}

impl Encodable for AggregateSignature {
    fn ssz_append(&self, s: &mut SszStream) {
        s.append_vec(&self.0.as_bytes());
    }
}

impl Decodable for AggregateSignature {
    fn ssz_decode(bytes: &[u8], i: usize) -> Result<(Self, usize), DecodeError> {
        let (sig_bytes, i) = decode_ssz_list(bytes, i)?;
        let raw_sig =
            RawAggregateSignature::from_bytes(&sig_bytes).map_err(|_| DecodeError::TooShort)?;
        Ok((AggregateSignature(raw_sig), i))
    }
}

#[cfg(test)]
mod tests {
    use super::super::ssz::ssz_encode;
    use super::super::{Keypair, Signature};
    use super::*;

    #[test]
    pub fn test_ssz_round_trip() {
        let keypair = Keypair::random();

        let mut original = AggregateSignature::new();
        original.add(&Signature::new(&[42, 42], &keypair.sk));

        let bytes = ssz_encode(&original);
        let (decoded, _) = AggregateSignature::ssz_decode(&bytes, 0).unwrap();

        assert_eq!(original, decoded);
    }
}
<commit_msg>Fix error in agg sig newtype<commit_after>use super::ssz::{decode_ssz_list, Decodable, DecodeError, Encodable, SszStream};
use super::{AggregatePublicKey, Signature};
use bls_aggregates::AggregateSignature as RawAggregateSignature;

/// A BLS aggregate signature.
///
/// This struct is a wrapper upon a base type and provides helper functions (e.g., SSZ
/// serialization).
#[derive(Debug, PartialEq, Clone)]
pub struct AggregateSignature(RawAggregateSignature);

impl AggregateSignature {
    /// Instantiate a new AggregateSignature.
    pub fn new() -> Self {
        AggregateSignature(RawAggregateSignature::new())
    }

    /// Add (aggregate) a signature to the `AggregateSignature`.
    pub fn add(&mut self, signature: &Signature) {
        self.0.add(signature.as_raw())
    }

    /// Verify the `AggregateSignature` against an `AggregatePublicKey`.
    ///
    /// Only returns `true` if the set of keys in the `AggregatePublicKey` match the set of keys
    /// that signed the `AggregateSignature`.
    pub fn verify(&self, msg: &[u8], avk: &AggregatePublicKey) -> bool {
        self.0.verify(msg, avk)
    }
}

impl Default for AggregateSignature {
    /// A "default" signature is a signature across an empty message by a secret key of 48 zeros.
    fn default() -> Self {
        AggregateSignature::new()
    }
}

impl Encodable for AggregateSignature {
    fn ssz_append(&self, s: &mut SszStream) {
        s.append_vec(&self.0.as_bytes());
    }
}

impl Decodable for AggregateSignature {
    fn ssz_decode(bytes: &[u8], i: usize) -> Result<(Self, usize), DecodeError> {
        let (sig_bytes, i) = decode_ssz_list(bytes, i)?;
        let raw_sig =
            RawAggregateSignature::from_bytes(&sig_bytes).map_err(|_| DecodeError::TooShort)?;
        Ok((AggregateSignature(raw_sig), i))
    }
}

#[cfg(test)]
mod tests {
    use super::super::ssz::ssz_encode;
    use super::super::{Keypair, Signature};
    use super::*;

    #[test]
    pub fn test_ssz_round_trip() {
        let keypair = Keypair::random();

        let mut original = AggregateSignature::new();
        original.add(&Signature::new(&[42, 42], &keypair.sk));

        let bytes = ssz_encode(&original);
        let (decoded, _) = AggregateSignature::ssz_decode(&bytes, 0).unwrap();

        assert_eq!(original, decoded);
    }
}
<|endoftext|>


<commit_before>#![feature(globs)]
#![feature(phase)]
#![feature(slicing_syntax)]

extern crate mpc;
extern crate phf;

#[phase(plugin)]
extern crate phf_mac;

#[cfg(test)]
extern crate test;

use cell::{Cell, CurriedBuiltinSpec, LambdaSpec};
use environment::Environment;
use parser::Parser;

#[cfg(test)]
use self::test::Bencher;

mod types;
mod cell;
mod globals;
mod environment;
mod builtin;
mod parser;

pub struct Rlisp<'a> {
    parser: Parser,
    environment: Environment,
}

impl<'a> Rlisp<'a> {
    pub fn new() -> Rlisp<'a> {
        Rlisp {
            parser: Parser::new(),
            environment: Environment::new(),
        }
    }

    pub fn execute(&mut self, input: &str) -> String {
        format!("{}", eval(self.environment.clone(), &self.parser.parse(input)))
    }
}

fn apply(env: Environment, procedure: &Cell, args: &[Cell]) -> Cell {
    if let Some(e) = first_error(args) {
         return e.clone();
    }

    let evaled_args = args.iter().map(|a| eval(env.clone(), a)).collect::<Vec<Cell>>();

    if let Some(e) = first_error(evaled_args[]) {
         return e.clone();
    }

    match procedure {
        &Cell::Lambda(box ref lambda) => {
            let sub_env = lambda.environment.make_sub_environment();

            let mut found_elipsis = false;

            for (i, arg) in evaled_args.iter().enumerate() {
                if let Some(&Cell::Symbol(ref s)) = lambda.arguments.get(i) {
                    match (s[] == "...", i == lambda.arguments.len() - 1) {
                        (true, true)  => { sub_env.insert(s, &Cell::Qexpr(evaled_args[i..].to_vec())); found_elipsis = true; break; },
                        (true, false) => return Cell::Error("Lambda can only have ... as it's last argument".to_string()),
                        (false, _)    => sub_env.insert(s, arg),
                    }
                }
            }

            if evaled_args.len() == lambda.arguments.len() || found_elipsis {
                eval(sub_env.clone(), &Cell::Sexpr(lambda.body.clone()))
            } else if evaled_args.len() < lambda.arguments.len() {
                if evaled_args.len() == 0 {
                    Cell::Error(format!("{} got no arguments", procedure))
                } else {
                    Cell::Lambda(box LambdaSpec {
                        arguments:   lambda.arguments[evaled_args.len()..].to_vec(),
                        body:        lambda.body.clone(),
                        environment: sub_env.clone(),
                    })
                }
            } else {
                Cell::Error(format!("{} got to many arguments expected {} got {}",
                                    procedure, lambda.arguments.len(), evaled_args.len()))
            }
        },
        &Cell::Builtin(builtin) => {
            let arity = types::get_arity(builtin.argument_types);

            if evaled_args.len() as i32 >= arity.requierd {
                if let Some(e) = types::validate(builtin, evaled_args[]) {
                    return Cell::Error(e);
                }

                (builtin.func)(env, evaled_args[])
            } else {
                Cell::CurriedBuiltin(box CurriedBuiltinSpec {
                    builtin: builtin,
                    bound_args: evaled_args,
                })
            }
        },
        &Cell::CurriedBuiltin(box ref cb) => {
            let arity = types::get_arity(cb.builtin.argument_types);
            let mut evaled_and_bound_args = Vec::new();
            evaled_and_bound_args.push_all(cb.bound_args[]);
            evaled_and_bound_args.push_all(evaled_args[]);

            if evaled_and_bound_args.len() as i32 >= arity.requierd {
                if let Some(e) = types::validate(cb.builtin, evaled_and_bound_args[]) {
                    return Cell::Error(e);
                }

                (cb.builtin.func)(env, evaled_and_bound_args[])
            } else {
                Cell::CurriedBuiltin(box CurriedBuiltinSpec {
                    builtin: cb.builtin,
                    bound_args: evaled_and_bound_args,
                })
            }
        },
        _ => Cell::Error(format!("{} is not a procedure, is {}", *procedure, procedure.get_type().to_string())),
    }
}

fn eval(env: Environment, c: &Cell) -> Cell {
    match c {
        &Cell::Sexpr(ref v) => match v[] {
            [ref procedure, args..] => {
                let evaled_procedure = eval(env.clone(), procedure);

                if let Cell::Error(_) = evaled_procedure {
                    return evaled_procedure.clone();
                }

                apply(env.clone(), &evaled_procedure, args)
            },
            _ => c.clone(),
        },
        &Cell::Symbol(ref s) => env.lookup(s),
        _ => c.clone(),
    }
}

fn first_error(c: &[Cell]) -> Option<&Cell> {
    for e in c.iter() {
        if let &Cell::Error(_) = e {
            return Some(e);
        }
    }
    None
}

#[test]
fn test_rlisp() {
    let mut rlisp = Rlisp::new();

    assert_eq!(rlisp.execute("(def {a} 12)"), "()".to_string());

    assert_eq!(rlisp.execute("(+ a a)"), "24".to_string());

    assert_eq!(rlisp.execute("(- a 4)"), "8".to_string());

    assert_eq!(rlisp.execute("(eval (head {(+ 1 2) (+ 10 20)}))"), "3".to_string());

    assert_eq!(rlisp.execute("((lambda {a} {+ a 1}) 2)"), "3".to_string());

    assert_eq!(rlisp.execute("((lambda {a} {+ a 1}) a)"), "13".to_string());

    assert_eq!(rlisp.execute("(def {addgen} (lambda {a} {lambda {} {+ a 1}}))"), "()".to_string());
    assert_eq!(rlisp.execute("(def {adder} (addgen 1))"), "()".to_string());
    assert_eq!(rlisp.execute("(adder)"), "2".to_string());

    assert_eq!(rlisp.execute("(def {defgen} (lambda {a} {lambda {} {def {o} a}}))"), "()".to_string());
    assert_eq!(rlisp.execute("(def {defer} (defgen 10))"), "()".to_string());
    assert_eq!(rlisp.execute("(defer)"), "()".to_string());
    assert_eq!(rlisp.execute("o"), "10".to_string());

    assert_eq!(rlisp.execute("((lambda {x y} {+ x y}) 10 20)"), "30".to_string());

    assert_eq!(rlisp.execute("(def {add-mul} (lambda {x y} {+ x (* x y)}))"), "()".to_string());
    assert_eq!(rlisp.execute("(add-mul 10 20)"), "210".to_string());

    assert_eq!(rlisp.execute("(def {add-mul-10} (add-mul 10))"), "()".to_string());
    assert_eq!(rlisp.execute("(add-mul-10 50)"), "510".to_string());

    assert_eq!(rlisp.execute("(def {f x y} {+ x (/ (+ x x) y)})"), "()".to_string());
    assert_eq!(rlisp.execute("(f 10 20)"), "11".to_string());

    assert_eq!(rlisp.execute("(def {hof f} {f 12 12})"), "()".to_string());
    assert_eq!(rlisp.execute("(hof +)"), "24".to_string());
    assert_eq!(rlisp.execute("(hof (lambda {a b} {+ a (/ b 2)}))"), "18".to_string());

    assert_eq!(rlisp.execute("(def {elipse ...} {head (list ...)})"), "()".to_string());
    assert_eq!(rlisp.execute("(elipse 1 2 3)"), "{1 2 3}".to_string());
    assert_eq!(rlisp.execute("(elipse 1 2 3 4 5)"), "{1 2 3 4 5}".to_string());
 }

 #[test]
fn test_curried_builtin() {
    let mut rlisp = Rlisp::new();

    assert_eq!(rlisp.execute("(def {a} (* 5))"), "()".to_string());

    assert_eq!(rlisp.execute("(a 10)"), "50".to_string());
}

 #[bench]
fn bench_rlisp_add(b: &mut Bencher) {
    let mut rlisp = Rlisp::new();

    b.iter(|| {
        test::black_box(rlisp.execute("(+ 1 1)"));
    });
}

#[bench]
fn bench_rlisp_lookup(b: &mut Bencher) {
    let mut rlisp = Rlisp::new();

    rlisp.execute("(def {a} 12)");

    b.iter(|| {
        test::black_box(rlisp.execute("a"));
    });
}

#[bench]
fn bench_rlisp_add_lookup(b: &mut Bencher) {
    let mut rlisp = Rlisp::new();

    rlisp.execute("(def {a} 12)");

    b.iter(|| {
        test::black_box(rlisp.execute("(+ a a)"));
    });
}<commit_msg>Fixed elipsis is zero or more arguments<commit_after>#![feature(globs)]
#![feature(phase)]
#![feature(slicing_syntax)]

extern crate mpc;
extern crate phf;

#[phase(plugin)]
extern crate phf_mac;

#[cfg(test)]
extern crate test;

use cell::{Cell, CurriedBuiltinSpec, LambdaSpec};
use environment::Environment;
use parser::Parser;

#[cfg(test)]
use self::test::Bencher;

mod types;
mod cell;
mod globals;
mod environment;
mod builtin;
mod parser;

pub struct Rlisp<'a> {
    parser: Parser,
    environment: Environment,
}

impl<'a> Rlisp<'a> {
    pub fn new() -> Rlisp<'a> {
        Rlisp {
            parser: Parser::new(),
            environment: Environment::new(),
        }
    }

    pub fn execute(&mut self, input: &str) -> String {
        format!("{}", eval(self.environment.clone(), &self.parser.parse(input)))
    }
}

fn apply(env: Environment, procedure: &Cell, args: &[Cell]) -> Cell {
    if let Some(e) = first_error(args) {
         return e.clone();
    }

    let evaled_args = args.iter().map(|a| eval(env.clone(), a)).collect::<Vec<Cell>>();

    if let Some(e) = first_error(evaled_args[]) {
         return e.clone();
    }

    match procedure {
        &Cell::Lambda(box ref lambda) => {
            let sub_env = lambda.environment.make_sub_environment();

            let mut found_elipsis = false;

            for (i, arg) in evaled_args.iter().enumerate() {
                if let Some(&Cell::Symbol(ref s)) = lambda.arguments.get(i) {
                    match (s[] == "...", i == lambda.arguments.len() - 1) {
                        (true, true)  => { sub_env.insert(s, &Cell::Qexpr(evaled_args[i..].to_vec())); found_elipsis = true; break; },
                        (true, false) => return Cell::Error("Lambda can only have ... as it's last argument".to_string()),
                        (false, _)    => sub_env.insert(s, arg),
                    }
                }
            }

            if evaled_args.len() == 0 {
                if let Some(&Cell::Symbol(ref s)) = lambda.arguments.get(0) {
                    if s[] == "..." {
                        sub_env.insert(s, &Cell::Qexpr(Vec::new()));
                        found_elipsis = true;
                    }
                }
            }

            if evaled_args.len() == lambda.arguments.len() || found_elipsis {
                eval(sub_env.clone(), &Cell::Sexpr(lambda.body.clone()))
            } else if evaled_args.len() < lambda.arguments.len() {
                if evaled_args.len() == 0 {
                    Cell::Error(format!("{} got no arguments", procedure))
                } else {
                    Cell::Lambda(box LambdaSpec {
                        arguments:   lambda.arguments[evaled_args.len()..].to_vec(),
                        body:        lambda.body.clone(),
                        environment: sub_env.clone(),
                    })
                }
            } else {
                Cell::Error(format!("{} got to many arguments expected {} got {}",
                                    procedure, lambda.arguments.len(), evaled_args.len()))
            }
        },
        &Cell::Builtin(builtin) => {
            let arity = types::get_arity(builtin.argument_types);

            if evaled_args.len() as i32 >= arity.requierd {
                if let Some(e) = types::validate(builtin, evaled_args[]) {
                    return Cell::Error(e);
                }

                (builtin.func)(env, evaled_args[])
            } else {
                Cell::CurriedBuiltin(box CurriedBuiltinSpec {
                    builtin: builtin,
                    bound_args: evaled_args,
                })
            }
        },
        &Cell::CurriedBuiltin(box ref cb) => {
            let arity = types::get_arity(cb.builtin.argument_types);
            let mut evaled_and_bound_args = Vec::new();
            evaled_and_bound_args.push_all(cb.bound_args[]);
            evaled_and_bound_args.push_all(evaled_args[]);

            if evaled_and_bound_args.len() as i32 >= arity.requierd {
                if let Some(e) = types::validate(cb.builtin, evaled_and_bound_args[]) {
                    return Cell::Error(e);
                }

                (cb.builtin.func)(env, evaled_and_bound_args[])
            } else {
                Cell::CurriedBuiltin(box CurriedBuiltinSpec {
                    builtin: cb.builtin,
                    bound_args: evaled_and_bound_args,
                })
            }
        },
        _ => Cell::Error(format!("{} is not a procedure, is {}", *procedure, procedure.get_type().to_string())),
    }
}

fn eval(env: Environment, c: &Cell) -> Cell {
    match c {
        &Cell::Sexpr(ref v) => match v[] {
            [ref procedure, args..] => {
                let evaled_procedure = eval(env.clone(), procedure);

                if let Cell::Error(_) = evaled_procedure {
                    return evaled_procedure.clone();
                }

                apply(env.clone(), &evaled_procedure, args)
            },
            _ => c.clone(),
        },
        &Cell::Symbol(ref s) => env.lookup(s),
        _ => c.clone(),
    }
}

fn first_error(c: &[Cell]) -> Option<&Cell> {
    for e in c.iter() {
        if let &Cell::Error(_) = e {
            return Some(e);
        }
    }
    None
}

#[test]
fn test_rlisp() {
    let mut rlisp = Rlisp::new();

    assert_eq!(rlisp.execute("(def {a} 12)"), "()".to_string());

    assert_eq!(rlisp.execute("(+ a a)"), "24".to_string());

    assert_eq!(rlisp.execute("(- a 4)"), "8".to_string());

    assert_eq!(rlisp.execute("(eval (head {(+ 1 2) (+ 10 20)}))"), "3".to_string());

    assert_eq!(rlisp.execute("((lambda {a} {+ a 1}) 2)"), "3".to_string());

    assert_eq!(rlisp.execute("((lambda {a} {+ a 1}) a)"), "13".to_string());

    assert_eq!(rlisp.execute("(def {addgen} (lambda {a} {lambda {} {+ a 1}}))"), "()".to_string());
    assert_eq!(rlisp.execute("(def {adder} (addgen 1))"), "()".to_string());
    assert_eq!(rlisp.execute("(adder)"), "2".to_string());

    assert_eq!(rlisp.execute("(def {defgen} (lambda {a} {lambda {} {def {o} a}}))"), "()".to_string());
    assert_eq!(rlisp.execute("(def {defer} (defgen 10))"), "()".to_string());
    assert_eq!(rlisp.execute("(defer)"), "()".to_string());
    assert_eq!(rlisp.execute("o"), "10".to_string());

    assert_eq!(rlisp.execute("((lambda {x y} {+ x y}) 10 20)"), "30".to_string());

    assert_eq!(rlisp.execute("(def {add-mul} (lambda {x y} {+ x (* x y)}))"), "()".to_string());
    assert_eq!(rlisp.execute("(add-mul 10 20)"), "210".to_string());

    assert_eq!(rlisp.execute("(def {add-mul-10} (add-mul 10))"), "()".to_string());
    assert_eq!(rlisp.execute("(add-mul-10 50)"), "510".to_string());

    assert_eq!(rlisp.execute("(def {f x y} {+ x (/ (+ x x) y)})"), "()".to_string());
    assert_eq!(rlisp.execute("(f 10 20)"), "11".to_string());

    assert_eq!(rlisp.execute("(def {hof f} {f 12 12})"), "()".to_string());
    assert_eq!(rlisp.execute("(hof +)"), "24".to_string());
    assert_eq!(rlisp.execute("(hof (lambda {a b} {+ a (/ b 2)}))"), "18".to_string());

    assert_eq!(rlisp.execute("(def {elipse ...} {head (list ...)})"), "()".to_string());
    assert_eq!(rlisp.execute("(elipse 1 2 3)"), "{1 2 3}".to_string());
    assert_eq!(rlisp.execute("(elipse 1 2 3 4 5)"), "{1 2 3 4 5}".to_string());
 }

#[test]
fn test_elipsis_emty_arg_list() {
    let mut rlisp = Rlisp::new();

    assert_eq!(rlisp.execute("(def {a ...} {head (list ...)})"), "()".to_string());

    assert_eq!(rlisp.execute("(a)"), "{}".to_string());
}

#[test]
fn test_curried_builtin() {
    let mut rlisp = Rlisp::new();

    assert_eq!(rlisp.execute("(def {a} (* 5))"), "()".to_string());

    assert_eq!(rlisp.execute("(a 10)"), "50".to_string());
}

 #[bench]
fn bench_rlisp_add(b: &mut Bencher) {
    let mut rlisp = Rlisp::new();

    b.iter(|| {
        test::black_box(rlisp.execute("(+ 1 1)"));
    });
}

#[bench]
fn bench_rlisp_lookup(b: &mut Bencher) {
    let mut rlisp = Rlisp::new();

    rlisp.execute("(def {a} 12)");

    b.iter(|| {
        test::black_box(rlisp.execute("a"));
    });
}

#[bench]
fn bench_rlisp_add_lookup(b: &mut Bencher) {
    let mut rlisp = Rlisp::new();

    rlisp.execute("(def {a} 12)");

    b.iter(|| {
        test::black_box(rlisp.execute("(+ a a)"));
    });
}<|endoftext|>


<commit_before>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use libra_crypto::ed25519::Ed25519PublicKey;
use libra_management::{
    config::ConfigPath,
    error::Error,
    secure_backend::{SecureBackend, SharedBackend},
};
use std::path::PathBuf;
use structopt::StructOpt;

libra_management::secure_backend!(
    ValidatorBackend,
    validator_backend,
    "validator configuration",
    "path-to-key"
);

#[derive(Debug, StructOpt)]
struct Key {
    #[structopt(flatten)]
    config: ConfigPath,
    #[structopt(flatten)]
    shared_backend: SharedBackend,
    #[structopt(flatten)]
    validator_backend: ValidatorBackend,
    #[structopt(long, help = "ed25519 public key in lcs or hex format")]
    path_to_key: Option<PathBuf>,
}

impl Key {
    fn submit_key(
        &self,
        key_name: &'static str,
        account_name: Option<&'static str>,
    ) -> Result<Ed25519PublicKey, Error> {
        let config = self
            .config
            .load()?
            .override_shared_backend(&self.shared_backend.shared_backend)?
            .override_validator_backend(&self.validator_backend.validator_backend)?;

        let key = if let Some(path_to_key) = &self.path_to_key {
            libra_management::read_key_from_file(path_to_key)
                .map_err(|e| Error::UnableToReadFile(format!("{:?}", path_to_key), e))?
        } else {
            let mut validator_storage = config.validator_backend();
            let key = validator_storage.ed25519_public_from_private(key_name)?;

            if let Some(account_name) = account_name {
                let peer_id = libra_types::account_address::from_public_key(&key);
                validator_storage.set(account_name, peer_id)?;
            }
            key
        };

        let mut shared_storage = config.shared_backend();
        shared_storage.set(key_name, key.clone())?;

        Ok(key)
    }
}

#[derive(Debug, StructOpt)]
pub struct LibraRootKey {
    #[structopt(flatten)]
    key: Key,
}

impl LibraRootKey {
    pub fn execute(self) -> Result<Ed25519PublicKey, Error> {
        self.key
            .submit_key(libra_global_constants::LIBRA_ROOT_KEY, None)
    }
}

#[derive(Debug, StructOpt)]
pub struct OperatorKey {
    #[structopt(flatten)]
    key: Key,
}

impl OperatorKey {
    pub fn execute(self) -> Result<Ed25519PublicKey, Error> {
        self.key.submit_key(
            libra_global_constants::OPERATOR_KEY,
            Some(libra_global_constants::OPERATOR_ACCOUNT),
        )
    }
}

#[derive(Debug, StructOpt)]
pub struct OwnerKey {
    #[structopt(flatten)]
    key: Key,
}

impl OwnerKey {
    pub fn execute(self) -> Result<Ed25519PublicKey, Error> {
        self.key.submit_key(
            libra_global_constants::OWNER_KEY,
            Some(libra_global_constants::OWNER_ACCOUNT),
        )
    }
}

#[derive(Debug, StructOpt)]
pub struct TreasuryComplianceKey {
    #[structopt(flatten)]
    key: Key,
}

impl TreasuryComplianceKey {
    pub fn execute(self) -> Result<Ed25519PublicKey, Error> {
        self.key
            .submit_key(libra_global_constants::TREASURY_COMPLIANCE_KEY, None)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage_helper::StorageHelper;
    use libra_secure_storage::{CryptoStorage, KVStorage};

    #[test]
    fn test_owner_key() {
        test_key(libra_global_constants::OWNER_KEY, StorageHelper::owner_key);
    }

    #[test]
    fn test_operator_key() {
        test_key(
            libra_global_constants::OPERATOR_KEY,
            StorageHelper::operator_key,
        );
    }

    fn test_key(
        key_name: &str,
        op: fn(&StorageHelper, &str, &str) -> Result<Ed25519PublicKey, Error>,
    ) {
        let helper = StorageHelper::new();
        let local_ns = format!("local_{}_key", key_name);
        let remote_ns = format!("remote_{}_key", key_name);

        op(&helper, &local_ns, &remote_ns).unwrap_err();

        helper.initialize_by_idx(local_ns.clone(), 0);
        let local = helper.storage(local_ns.clone());
        let local_key = local.get_public_key(key_name).unwrap().public_key;

        let output_key = op(&helper, &local_ns, &remote_ns).unwrap();
        let remote = helper.storage(remote_ns);
        let remote_key = remote.get::<Ed25519PublicKey>(key_name).unwrap().value;

        assert_eq!(local_key, output_key);
        assert_eq!(local_key, remote_key);
    }
}
<commit_msg>[genesis] prevent race condition in setting owner account<commit_after>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use libra_crypto::ed25519::Ed25519PublicKey;
use libra_management::{
    config::ConfigPath,
    error::Error,
    secure_backend::{SecureBackend, SharedBackend},
};
use std::path::PathBuf;
use structopt::StructOpt;

libra_management::secure_backend!(
    ValidatorBackend,
    validator_backend,
    "validator configuration",
    "path-to-key"
);

#[derive(Debug, StructOpt)]
struct Key {
    #[structopt(flatten)]
    config: ConfigPath,
    #[structopt(flatten)]
    shared_backend: SharedBackend,
    #[structopt(flatten)]
    validator_backend: ValidatorBackend,
    #[structopt(long, help = "ed25519 public key in lcs or hex format")]
    path_to_key: Option<PathBuf>,
}

impl Key {
    fn submit_key(
        &self,
        key_name: &'static str,
        account_name: Option<&'static str>,
    ) -> Result<Ed25519PublicKey, Error> {
        let config = self
            .config
            .load()?
            .override_shared_backend(&self.shared_backend.shared_backend)?
            .override_validator_backend(&self.validator_backend.validator_backend)?;

        let key = if let Some(path_to_key) = &self.path_to_key {
            libra_management::read_key_from_file(path_to_key)
                .map_err(|e| Error::UnableToReadFile(format!("{:?}", path_to_key), e))?
        } else {
            let mut validator_storage = config.validator_backend();
            let key = validator_storage.ed25519_public_from_private(key_name)?;

            if let Some(account_name) = account_name {
                let peer_id = libra_types::account_address::from_public_key(&key);
                validator_storage.set(account_name, peer_id)?;
            }
            key
        };

        let mut shared_storage = config.shared_backend();
        shared_storage.set(key_name, key.clone())?;

        Ok(key)
    }
}

#[derive(Debug, StructOpt)]
pub struct LibraRootKey {
    #[structopt(flatten)]
    key: Key,
}

impl LibraRootKey {
    pub fn execute(self) -> Result<Ed25519PublicKey, Error> {
        self.key
            .submit_key(libra_global_constants::LIBRA_ROOT_KEY, None)
    }
}

#[derive(Debug, StructOpt)]
pub struct OperatorKey {
    #[structopt(flatten)]
    key: Key,
}

impl OperatorKey {
    pub fn execute(self) -> Result<Ed25519PublicKey, Error> {
        self.key.submit_key(
            libra_global_constants::OPERATOR_KEY,
            Some(libra_global_constants::OPERATOR_ACCOUNT),
        )
    }
}

#[derive(Debug, StructOpt)]
pub struct OwnerKey {
    #[structopt(flatten)]
    key: Key,
}

impl OwnerKey {
    pub fn execute(self) -> Result<Ed25519PublicKey, Error> {
        self.key.submit_key(libra_global_constants::OWNER_KEY, None)
    }
}

#[derive(Debug, StructOpt)]
pub struct TreasuryComplianceKey {
    #[structopt(flatten)]
    key: Key,
}

impl TreasuryComplianceKey {
    pub fn execute(self) -> Result<Ed25519PublicKey, Error> {
        self.key
            .submit_key(libra_global_constants::TREASURY_COMPLIANCE_KEY, None)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage_helper::StorageHelper;
    use libra_secure_storage::{CryptoStorage, KVStorage};

    #[test]
    fn test_owner_key() {
        test_key(libra_global_constants::OWNER_KEY, StorageHelper::owner_key);
    }

    #[test]
    fn test_operator_key() {
        test_key(
            libra_global_constants::OPERATOR_KEY,
            StorageHelper::operator_key,
        );
    }

    fn test_key(
        key_name: &str,
        op: fn(&StorageHelper, &str, &str) -> Result<Ed25519PublicKey, Error>,
    ) {
        let helper = StorageHelper::new();
        let local_ns = format!("local_{}_key", key_name);
        let remote_ns = format!("remote_{}_key", key_name);

        op(&helper, &local_ns, &remote_ns).unwrap_err();

        helper.initialize_by_idx(local_ns.clone(), 0);
        let local = helper.storage(local_ns.clone());
        let local_key = local.get_public_key(key_name).unwrap().public_key;

        let output_key = op(&helper, &local_ns, &remote_ns).unwrap();
        let remote = helper.storage(remote_ns);
        let remote_key = remote.get::<Ed25519PublicKey>(key_name).unwrap().value;

        assert_eq!(local_key, output_key);
        assert_eq!(local_key, remote_key);
    }
}
<|endoftext|>


<commit_before>use std::io;
use std::io::prelude::*;

enum State {
    Normal,
    Backslash,
    Hex(u8),
}

pub fn main() {
    let stdin = io::stdin();
    let mut chr = 0;
    let mut len = 0;
    for line in stdin.lock().lines() {
        let line = line.unwrap();
        len += line.len();
        let mut state = State::Normal;
        for c in line.chars() {
            state = match state {
                State::Normal => {
                    chr += 1;
                    if c == '\\' {
                        State::Backslash
                    } else {
                        State::Normal
                    }
                }
                State::Backslash => {
                    if c == 'x' {
                        State::Hex(1)
                    } else {
                        State::Normal
                    }
                }
                State::Hex(x) => {
                    if x == 0 {
                        State::Normal
                    } else {
                        State::Hex(x - 1)
                    }
                }
            }
        }
        chr -= 2; // substract the open and close quotes
    }
    println!("{}", len - chr);
}
<commit_msg>day 8 part 2 rust solution<commit_after>use std::io;
use std::io::prelude::*;

enum State {
    Normal,
    Backslash,
    Hex(u8),
}

pub fn main() {
    let stdin = io::stdin();
    let mut chr = 0;
    let mut len = 0;
    let mut escaped = 0;
    for line in stdin.lock().lines() {
        let line = line.unwrap();
        len += line.len();
        escaped += 2;
        let mut state = State::Normal;
        for c in line.chars() {
            if c == '"' || c == '\\' {
                escaped += 1
            };
            state = match state {
                State::Normal => {
                    chr += 1;
                    if c == '\\' {
                        State::Backslash
                    } else {
                        State::Normal
                    }
                }
                State::Backslash => {
                    if c == 'x' {
                        State::Hex(1)
                    } else {
                        State::Normal
                    }
                }
                State::Hex(x) => {
                    if x == 0 {
                        State::Normal
                    } else {
                        State::Hex(x - 1)
                    }
                }
            }
        }
        chr -= 2; // substract the open and close quotes
    }
    println!("Part 1: {}", len - chr);
    println!("Part 2: {}", escaped);
}
<|endoftext|>


<commit_before>#![cfg(all(not(target_os = "fuchsia"), not(target_os = "android"), not(target_os = "windows")))]

extern crate libc;
extern crate pagecache;
extern crate rand;
extern crate sled;
extern crate tests;

use std::fs;
use std::mem::size_of;
use std::path::Path;
use std::thread;
use std::time::Duration;

use rand::Rng;

use pagecache::{Config, ConfigBuilder};

const CYCLE: usize = 16; // 65536;

/// Verifies that the keys in the tree are correctly recovered.
/// Panics if they are incorrect.
/// Returns the key that should be resumed at, and the current cycle value.
fn verify(tree: &sled::Tree) -> (u32, u32) {
    // key 0 should always be the highest value, as that's where we increment
    // at some point, it might go down by one
    // it should never return, or go down again after that
    let mut iter = tree.iter();
    let highest = match iter.next() {
        Some(Ok((_k, v))) => slice_to_u32(&*v),
        Some(Err(e)) => panic!("{:?}", e),
        None => return (0, 0),
    };

    let highest_vec = u32_to_vec(highest);

    // find how far we got
    let mut contiguous: u32 = 0;
    let mut lowest = 0;
    for res in iter {
        let (mut k, v) = res.unwrap();
        if &v[..4] == &highest_vec[..4] {
            contiguous += 1;
        } else {
            k.reverse();
            let expected = if highest == 0 {
                CYCLE as u32 - 1
            } else {
                (highest - 1) % CYCLE as u32
            };
            let actual = slice_to_u32(&*v);
            assert_eq!(expected, actual);
            lowest = actual;
            break;
        }
    }

    let lowest_vec = u32_to_vec(lowest);

    // ensure nothing changes after this point
    let low_beginning = u32_to_vec(contiguous + 1);

    for res in tree.scan(&*low_beginning) {
        let (mut k, v) = res.unwrap();
        if v != lowest_vec {
            k.reverse();
        }
        assert_eq!(
            v,
            lowest_vec,
            "expected key {} to have value {}, instead it had value {}",
            slice_to_u32(&*k),
            lowest,
            slice_to_u32(&*v)
        );
    }

    (contiguous, highest)
}

fn u32_to_vec(u: u32) -> Vec<u8> {
    let buf: [u8; size_of::<u32>()] =
        unsafe { std::mem::transmute(u) };
    buf.to_vec()
}

fn slice_to_u32(b: &[u8]) -> u32 {
    let mut buf = [0u8; size_of::<u32>()];
    buf.copy_from_slice(&b[..size_of::<u32>()]);

    unsafe { std::mem::transmute(buf) }
}

fn run(config: Config) {
    // tests::setup_logger();
    let tree = sled::Tree::start(config).unwrap();

    // flush to ensure the initial root is stable.
    // TODO is this necessary or voodoo?
    tree.flush().unwrap();

    thread::spawn(|| {
        let runtime = rand::thread_rng().gen_range(0, 200);
        thread::sleep(Duration::from_millis(runtime));
        unsafe {
            libc::raise(9);
        }
    });

    let (key, highest) = verify(&tree);

    let mut hu = ((highest as usize) * CYCLE) + key as usize;
    assert_eq!(hu % CYCLE, key as usize);
    assert_eq!(hu / CYCLE, highest as usize);

    loop {
        hu += 1;

        if hu / CYCLE >= CYCLE {
            hu = 0;
        }

        let mut key = u32_to_vec((hu % CYCLE) as u32);
        key.reverse();

        let mut value = u32_to_vec((hu / CYCLE) as u32);
        let additional_len = rand::thread_rng().gen_range(0, 100_000);
        value.append(&mut vec![0u8; additional_len]);

        tree.set(key, value).unwrap();
    }
}

fn run_without_snapshot() {
    let config = ConfigBuilder::new()
        .io_bufs(2)
        .blink_fanout(15)
        .page_consolidation_threshold(10)
        .cache_bits(6)
        .cache_capacity(128 * 1024 * 1024)
        .flush_every_ms(Some(100))
        // drop io_buf_size to 1<<16, then 1<<17 to tease out
        // low hanging fruit more quickly
        .io_buf_size(100_000) // 1<<16 is 65k but might cause stalling
        .path("test_crashes".to_string())
        .snapshot_after_ops(1 << 56)
        .build();

    match thread::spawn(|| run(config)).join() {
        Err(e) => {
            println!("worker thread failed: {:?}", e);
            std::process::exit(15);
        }
        _ => {}
    }
}

fn run_with_snapshot() {
    let config = ConfigBuilder::new()
        .io_bufs(2)
        .blink_fanout(15)
        .page_consolidation_threshold(10)
        .cache_bits(6)
        .cache_capacity(128 * 1024 * 1024)
        .flush_every_ms(Some(100))
        // drop io_buf_size to 1<<16, then 1<<17 to tease out
        // low hanging fruit more quickly
        .io_buf_size(100_000) // 1<<16 is 65k but might cause stalling
        .path("test_crashes_with_snapshot".to_string())
        .snapshot_after_ops(1 << 10)
        .build();

    match thread::spawn(|| run(config)).join() {
        Err(e) => {
            println!("worker thread failed: {:?}", e);
            std::process::exit(15);
        }
        _ => {}
    }
}

#[test]
fn test_crash_recovery_with_runtime_snapshot() {
    cleanup_with_snapshots();
    for _ in 0..100 {
        let child = unsafe { libc::fork() };
        if child == 0 {
            run_with_snapshot()
        } else {
            let mut status = 0;
            unsafe {
                libc::waitpid(
                    child,
                    &mut status as *mut libc::c_int,
                    0,
                );
            }
            if status != 9 {
                cleanup();
                panic!("child exited abnormally");
            }
        }
    }
    cleanup_with_snapshots();
}

#[test]
fn test_crash_recovery_no_runtime_snapshot() {
    cleanup();
    for _ in 0..100 {
        let child = unsafe { libc::fork() };
        if child == 0 {
            run_without_snapshot()
        } else {
            let mut status = 0;
            unsafe {
                libc::waitpid(
                    child,
                    &mut status as *mut libc::c_int,
                    0,
                );
            }
            if status != 9 {
                cleanup();
                panic!("child exited abnormally");
            }
        }
    }
    cleanup();
}

fn cleanup_with_snapshots() {
    let dir = Path::new("test_crashes_with_snapshot");
    if dir.exists() {
        fs::remove_dir_all(dir).unwrap();
    }
}

fn cleanup() {
    let dir = Path::new("test_crashes");
    if dir.exists() {
        fs::remove_dir_all(dir).unwrap();
    }
}
<commit_msg>Write more pages during crash testing<commit_after>#![cfg(all(
    not(target_os = "fuchsia"),
    not(target_os = "android"),
    not(target_os = "windows")
))]

extern crate libc;
extern crate pagecache;
extern crate rand;
extern crate sled;
extern crate tests;

use std::fs;
use std::mem::size_of;
use std::path::Path;
use std::thread;
use std::time::Duration;

use rand::Rng;

use pagecache::{Config, ConfigBuilder};

const CYCLE: usize = 256;

/// Verifies that the keys in the tree are correctly recovered.
/// Panics if they are incorrect.
/// Returns the key that should be resumed at, and the current cycle value.
fn verify(tree: &sled::Tree) -> (u32, u32) {
    // key 0 should always be the highest value, as that's where we increment
    // at some point, it might go down by one
    // it should never return, or go down again after that
    let mut iter = tree.iter();
    let highest = match iter.next() {
        Some(Ok((_k, v))) => slice_to_u32(&*v),
        Some(Err(e)) => panic!("{:?}", e),
        None => return (0, 0),
    };

    let highest_vec = u32_to_vec(highest);

    // find how far we got
    let mut contiguous: u32 = 0;
    let mut lowest = 0;
    for res in iter {
        let (mut k, v) = res.unwrap();
        if &v[..4] == &highest_vec[..4] {
            contiguous += 1;
        } else {
            k.reverse();
            let expected = if highest == 0 {
                CYCLE as u32 - 1
            } else {
                (highest - 1) % CYCLE as u32
            };
            let actual = slice_to_u32(&*v);
            assert_eq!(expected, actual);
            lowest = actual;
            break;
        }
    }

    let lowest_vec = u32_to_vec(lowest);

    // ensure nothing changes after this point
    let low_beginning = u32_to_vec(contiguous + 1);

    for res in tree.scan(&*low_beginning) {
        let (mut k, v) = res.unwrap();
        if v != lowest_vec {
            k.reverse();
        }
        assert_eq!(
            v,
            lowest_vec,
            "expected key {} to have value {}, instead it had value {}",
            slice_to_u32(&*k),
            lowest,
            slice_to_u32(&*v)
        );
    }

    (contiguous, highest)
}

fn u32_to_vec(u: u32) -> Vec<u8> {
    let buf: [u8; size_of::<u32>()] =
        unsafe { std::mem::transmute(u) };
    buf.to_vec()
}

fn slice_to_u32(b: &[u8]) -> u32 {
    let mut buf = [0u8; size_of::<u32>()];
    buf.copy_from_slice(&b[..size_of::<u32>()]);

    unsafe { std::mem::transmute(buf) }
}

fn run(config: Config) {
    // tests::setup_logger();
    let tree = sled::Tree::start(config).unwrap();

    // flush to ensure the initial root is stable.
    // TODO is this necessary or voodoo?
    tree.flush().unwrap();

    thread::spawn(|| {
        let runtime = rand::thread_rng().gen_range(0, 200);
        thread::sleep(Duration::from_millis(runtime));
        unsafe {
            libc::raise(9);
        }
    });

    let (key, highest) = verify(&tree);

    let mut hu = ((highest as usize) * CYCLE) + key as usize;
    assert_eq!(hu % CYCLE, key as usize);
    assert_eq!(hu / CYCLE, highest as usize);

    loop {
        hu += 1;

        if hu / CYCLE >= CYCLE {
            hu = 0;
        }

        let mut key = u32_to_vec((hu % CYCLE) as u32);
        key.reverse();

        let mut value = u32_to_vec((hu / CYCLE) as u32);
        let additional_len = rand::thread_rng().gen_range(0, 100_000);
        value.append(&mut vec![0u8; additional_len]);

        tree.set(key, value).unwrap();
    }
}

fn run_without_snapshot() {
    let config = ConfigBuilder::new()
        .io_bufs(2)
        .blink_fanout(15)
        .page_consolidation_threshold(10)
        .cache_bits(6)
        .cache_capacity(128 * 1024 * 1024)
        .flush_every_ms(Some(100))
        // drop io_buf_size to 1<<16, then 1<<17 to tease out
        // low hanging fruit more quickly
        .io_buf_size(100_000) // 1<<16 is 65k but might cause stalling
        .path("test_crashes".to_string())
        .snapshot_after_ops(1 << 56)
        .build();

    match thread::spawn(|| run(config)).join() {
        Err(e) => {
            println!("worker thread failed: {:?}", e);
            std::process::exit(15);
        }
        _ => {}
    }
}

fn run_with_snapshot() {
    let config = ConfigBuilder::new()
        .io_bufs(2)
        .blink_fanout(15)
        .page_consolidation_threshold(10)
        .cache_bits(6)
        .cache_capacity(128 * 1024 * 1024)
        .flush_every_ms(Some(100))
        // drop io_buf_size to 1<<16, then 1<<17 to tease out
        // low hanging fruit more quickly
        .io_buf_size(100_000) // 1<<16 is 65k but might cause stalling
        .path("test_crashes_with_snapshot".to_string())
        .snapshot_after_ops(1 << 10)
        .build();

    match thread::spawn(|| run(config)).join() {
        Err(e) => {
            println!("worker thread failed: {:?}", e);
            std::process::exit(15);
        }
        _ => {}
    }
}

#[test]
fn test_crash_recovery_with_runtime_snapshot() {
    cleanup_with_snapshots();
    for _ in 0..100 {
        let child = unsafe { libc::fork() };
        if child == 0 {
            run_with_snapshot()
        } else {
            let mut status = 0;
            unsafe {
                libc::waitpid(
                    child,
                    &mut status as *mut libc::c_int,
                    0,
                );
            }
            if status != 9 {
                cleanup();
                panic!("child exited abnormally");
            }
        }
    }
    cleanup_with_snapshots();
}

#[test]
fn test_crash_recovery_no_runtime_snapshot() {
    cleanup();
    for _ in 0..100 {
        let child = unsafe { libc::fork() };
        if child == 0 {
            run_without_snapshot()
        } else {
            let mut status = 0;
            unsafe {
                libc::waitpid(
                    child,
                    &mut status as *mut libc::c_int,
                    0,
                );
            }
            if status != 9 {
                cleanup();
                panic!("child exited abnormally");
            }
        }
    }
    cleanup();
}

fn cleanup_with_snapshots() {
    let dir = Path::new("test_crashes_with_snapshot");
    if dir.exists() {
        fs::remove_dir_all(dir).unwrap();
    }
}

fn cleanup() {
    let dir = Path::new("test_crashes");
    if dir.exists() {
        fs::remove_dir_all(dir).unwrap();
    }
}
<|endoftext|>


<commit_before>#[warn(clippy::many_single_char_names)]

fn bla() {
    let a: i32;
    let (b, c, d): (i32, i64, i16);
    {
        {
            let cdefg: i32;
            let blar: i32;
        }
        {
            let e: i32;
        }
        {
            let e: i32;
            let f: i32;
        }
        match 5 {
            1 => println!(),
            e => panic!(),
        }
        match 5 {
            1 => println!(),
            _ => panic!(),
        }
    }
}

fn bindings(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32, g: i32, h: i32) {}

fn bindings2() {
    let (a, b, c, d, e, f, g, h) = unimplemented!();
}

fn shadowing() {
    let a = 0i32;
    let a = 0i32;
    let a = 0i32;
    let a = 0i32;
    let a = 0i32;
    let a = 0i32;
    {
        let a = 0i32;
    }
}

fn patterns() {
    enum Z {
        A(i32),
        B(i32),
        C(i32),
        D(i32),
        E(i32),
        F(i32),
    }

    // These should not trigger a warning, since the pattern bindings are a new scope.
    match Z::A(0) {
        Z::A(a) => {},
        Z::B(b) => {},
        Z::C(c) => {},
        Z::D(d) => {},
        Z::E(e) => {},
        Z::F(f) => {},
    }
}

fn main() {}
<commit_msg>Add test for #3198<commit_after>#[warn(clippy::many_single_char_names)]

fn bla() {
    let a: i32;
    let (b, c, d): (i32, i64, i16);
    {
        {
            let cdefg: i32;
            let blar: i32;
        }
        {
            let e: i32;
        }
        {
            let e: i32;
            let f: i32;
        }
        match 5 {
            1 => println!(),
            e => panic!(),
        }
        match 5 {
            1 => println!(),
            _ => panic!(),
        }
    }
}

fn bindings(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32, g: i32, h: i32) {}

fn bindings2() {
    let (a, b, c, d, e, f, g, h) = unimplemented!();
}

fn shadowing() {
    let a = 0i32;
    let a = 0i32;
    let a = 0i32;
    let a = 0i32;
    let a = 0i32;
    let a = 0i32;
    {
        let a = 0i32;
    }
}

fn patterns() {
    enum Z {
        A(i32),
        B(i32),
        C(i32),
        D(i32),
        E(i32),
        F(i32),
    }

    // These should not trigger a warning, since the pattern bindings are a new scope.
    match Z::A(0) {
        Z::A(a) => {},
        Z::B(b) => {},
        Z::C(c) => {},
        Z::D(d) => {},
        Z::E(e) => {},
        Z::F(f) => {},
    }
}

#[allow(clippy::many_single_char_names)]
fn issue_3198_allow_works() {
    let (a, b, c, d, e) = (0, 0, 0, 0, 0);
}

fn main() {}
<|endoftext|>


<commit_before>use crate::utils::{in_macro, snippet, snippet_with_applicability, span_lint_and_sugg};
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir::{
    def::{DefKind, Res},
    Item, ItemKind, PathSegment, UseKind,
};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::BytePos;

declare_clippy_lint! {
    /// **What it does:** Checks for `use Enum::*`.
    ///
    /// **Why is this bad?** It is usually better style to use the prefixed name of
    /// an enumeration variant, rather than importing variants.
    ///
    /// **Known problems:** Old-style enumerations that prefix the variants are
    /// still around.
    ///
    /// **Example:**
    /// ```rust
    /// use std::cmp::Ordering::*;
    /// ```
    pub ENUM_GLOB_USE,
    pedantic,
    "use items that import all variants of an enum"
}

declare_clippy_lint! {
    /// **What it does:** Checks for wildcard imports `use _::*`.
    ///
    /// **Why is this bad?** wildcard imports can polute the namespace. This is especially bad if
    /// you try to import something through a wildcard, that already has been imported by name from
    /// a different source:
    ///
    /// ```rust,ignore
    /// use crate1::foo; // Imports a function named foo
    /// use crate2::*; // Has a function named foo
    ///
    /// foo(); // Calls crate1::foo
    /// ```
    ///
    /// This can lead to confusing error messages at best and to unexpected behavior at worst.
    ///
    /// Note that this will not warn about wildcard imports from modules named `prelude`; many
    /// crates (including the standard library) provide modules named "prelude" specifically
    /// designed for wildcard import.
    ///
    /// **Known problems:** If macros are imported through the wildcard, this macro is not included
    /// by the suggestion and has to be added by hand.
    ///
    /// Applying the suggestion when explicit imports of the things imported with a glob import
    /// exist, may result in `unused_imports` warnings.
    ///
    /// **Example:**
    ///
    /// Bad:
    /// ```rust,ignore
    /// use crate1::*;
    ///
    /// foo();
    /// ```
    ///
    /// Good:
    /// ```rust,ignore
    /// use crate1::foo;
    ///
    /// foo();
    /// ```
    pub WILDCARD_IMPORTS,
    pedantic,
    "lint `use _::*` statements"
}

declare_lint_pass!(WildcardImports => [ENUM_GLOB_USE, WILDCARD_IMPORTS]);

impl LateLintPass<'_, '_> for WildcardImports {
    fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &Item<'_>) {
        if item.vis.node.is_pub() || item.vis.node.is_pub_restricted() {
            return;
        }
        if_chain! {
            if !in_macro(item.span);
            if let ItemKind::Use(use_path, UseKind::Glob) = &item.kind;
            if !is_prelude_import(use_path.segments);
            if !is_super_only_import_in_test(use_path.segments);
            let used_imports = cx.tcx.names_imported_by_glob_use(item.hir_id.owner);
            if !used_imports.is_empty(); // Already handled by `unused_imports`
            then {
                let mut applicability = Applicability::MachineApplicable;
                let import_source_snippet = snippet_with_applicability(cx, use_path.span, "..", &mut applicability);
                let (span, braced_glob) = if import_source_snippet.is_empty() {
                    // This is a `_::{_, *}` import
                    // In this case `use_path.span` is empty and ends directly in front of the `*`,
                    // so we need to extend it by one byte.
                    (
                        use_path.span.with_hi(use_path.span.hi() + BytePos(1)),
                        true,
                    )
                } else {
                    // In this case, the `use_path.span` ends right before the `::*`, so we need to
                    // extend it up to the `*`. Since it is hard to find the `*` in weird
                    // formattings like `use _ ::  *;`, we extend it up to, but not including the
                    // `;`. In nested imports, like `use _::{inner::*, _}` there is no `;` and we
                    // can just use the end of the item span
                    let mut span = use_path.span.with_hi(item.span.hi());
                    if snippet(cx, span, "").ends_with(';') {
                        span = use_path.span.with_hi(item.span.hi() - BytePos(1));
                    }
                    (
                        span,
                        false,
                    )
                };

                let imports_string = if used_imports.len() == 1 {
                    used_imports.iter().next().unwrap().to_string()
                } else {
                    let mut imports = used_imports
                        .iter()
                        .map(ToString::to_string)
                        .collect::<Vec<_>>();
                    imports.sort();
                    if braced_glob {
                        imports.join(", ")
                    } else {
                        format!("{{{}}}", imports.join(", "))
                    }
                };

                let sugg = if braced_glob {
                    imports_string
                } else {
                    format!("{}::{}", import_source_snippet, imports_string)
                };

                let (lint, message) = if let Res::Def(DefKind::Enum, _) = use_path.res {
                    (ENUM_GLOB_USE, "usage of wildcard import for enum variants")
                } else {
                    (WILDCARD_IMPORTS, "usage of wildcard import")
                };

                span_lint_and_sugg(
                    cx,
                    lint,
                    span,
                    message,
                    "try",
                    sugg,
                    applicability,
                );
            }
        }
    }
}

// Allow "...prelude::*" imports.
// Many crates have a prelude, and it is imported as a glob by design.
fn is_prelude_import(segments: &[PathSegment<'_>]) -> bool {
    segments.iter().last().map_or(false, |ps| ps.ident.as_str() == "prelude")
}

// Allow "super::*" imports.
// This is intended primarily to ease the process of writing unit tests.
fn is_super_only_import_in_test(segments: &[PathSegment<'_>]) -> bool {
    segments.iter().len() == 1 &&
        segments.first().map_or(false, |ps| ps.ident.as_str() == "super")
}
<commit_msg>Run `cargo dev fmt`<commit_after>use crate::utils::{in_macro, snippet, snippet_with_applicability, span_lint_and_sugg};
use if_chain::if_chain;
use rustc_errors::Applicability;
use rustc_hir::{
    def::{DefKind, Res},
    Item, ItemKind, PathSegment, UseKind,
};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::BytePos;

declare_clippy_lint! {
    /// **What it does:** Checks for `use Enum::*`.
    ///
    /// **Why is this bad?** It is usually better style to use the prefixed name of
    /// an enumeration variant, rather than importing variants.
    ///
    /// **Known problems:** Old-style enumerations that prefix the variants are
    /// still around.
    ///
    /// **Example:**
    /// ```rust
    /// use std::cmp::Ordering::*;
    /// ```
    pub ENUM_GLOB_USE,
    pedantic,
    "use items that import all variants of an enum"
}

declare_clippy_lint! {
    /// **What it does:** Checks for wildcard imports `use _::*`.
    ///
    /// **Why is this bad?** wildcard imports can polute the namespace. This is especially bad if
    /// you try to import something through a wildcard, that already has been imported by name from
    /// a different source:
    ///
    /// ```rust,ignore
    /// use crate1::foo; // Imports a function named foo
    /// use crate2::*; // Has a function named foo
    ///
    /// foo(); // Calls crate1::foo
    /// ```
    ///
    /// This can lead to confusing error messages at best and to unexpected behavior at worst.
    ///
    /// Note that this will not warn about wildcard imports from modules named `prelude`; many
    /// crates (including the standard library) provide modules named "prelude" specifically
    /// designed for wildcard import.
    ///
    /// **Known problems:** If macros are imported through the wildcard, this macro is not included
    /// by the suggestion and has to be added by hand.
    ///
    /// Applying the suggestion when explicit imports of the things imported with a glob import
    /// exist, may result in `unused_imports` warnings.
    ///
    /// **Example:**
    ///
    /// Bad:
    /// ```rust,ignore
    /// use crate1::*;
    ///
    /// foo();
    /// ```
    ///
    /// Good:
    /// ```rust,ignore
    /// use crate1::foo;
    ///
    /// foo();
    /// ```
    pub WILDCARD_IMPORTS,
    pedantic,
    "lint `use _::*` statements"
}

declare_lint_pass!(WildcardImports => [ENUM_GLOB_USE, WILDCARD_IMPORTS]);

impl LateLintPass<'_, '_> for WildcardImports {
    fn check_item(&mut self, cx: &LateContext<'_, '_>, item: &Item<'_>) {
        if item.vis.node.is_pub() || item.vis.node.is_pub_restricted() {
            return;
        }
        if_chain! {
            if !in_macro(item.span);
            if let ItemKind::Use(use_path, UseKind::Glob) = &item.kind;
            if !is_prelude_import(use_path.segments);
            if !is_super_only_import_in_test(use_path.segments);
            let used_imports = cx.tcx.names_imported_by_glob_use(item.hir_id.owner);
            if !used_imports.is_empty(); // Already handled by `unused_imports`
            then {
                let mut applicability = Applicability::MachineApplicable;
                let import_source_snippet = snippet_with_applicability(cx, use_path.span, "..", &mut applicability);
                let (span, braced_glob) = if import_source_snippet.is_empty() {
                    // This is a `_::{_, *}` import
                    // In this case `use_path.span` is empty and ends directly in front of the `*`,
                    // so we need to extend it by one byte.
                    (
                        use_path.span.with_hi(use_path.span.hi() + BytePos(1)),
                        true,
                    )
                } else {
                    // In this case, the `use_path.span` ends right before the `::*`, so we need to
                    // extend it up to the `*`. Since it is hard to find the `*` in weird
                    // formattings like `use _ ::  *;`, we extend it up to, but not including the
                    // `;`. In nested imports, like `use _::{inner::*, _}` there is no `;` and we
                    // can just use the end of the item span
                    let mut span = use_path.span.with_hi(item.span.hi());
                    if snippet(cx, span, "").ends_with(';') {
                        span = use_path.span.with_hi(item.span.hi() - BytePos(1));
                    }
                    (
                        span,
                        false,
                    )
                };

                let imports_string = if used_imports.len() == 1 {
                    used_imports.iter().next().unwrap().to_string()
                } else {
                    let mut imports = used_imports
                        .iter()
                        .map(ToString::to_string)
                        .collect::<Vec<_>>();
                    imports.sort();
                    if braced_glob {
                        imports.join(", ")
                    } else {
                        format!("{{{}}}", imports.join(", "))
                    }
                };

                let sugg = if braced_glob {
                    imports_string
                } else {
                    format!("{}::{}", import_source_snippet, imports_string)
                };

                let (lint, message) = if let Res::Def(DefKind::Enum, _) = use_path.res {
                    (ENUM_GLOB_USE, "usage of wildcard import for enum variants")
                } else {
                    (WILDCARD_IMPORTS, "usage of wildcard import")
                };

                span_lint_and_sugg(
                    cx,
                    lint,
                    span,
                    message,
                    "try",
                    sugg,
                    applicability,
                );
            }
        }
    }
}

// Allow "...prelude::*" imports.
// Many crates have a prelude, and it is imported as a glob by design.
fn is_prelude_import(segments: &[PathSegment<'_>]) -> bool {
    segments
        .iter()
        .last()
        .map_or(false, |ps| ps.ident.as_str() == "prelude")
}

// Allow "super::*" imports.
// This is intended primarily to ease the process of writing unit tests.
fn is_super_only_import_in_test(segments: &[PathSegment<'_>]) -> bool {
    segments.iter().len() == 1 && segments.first().map_or(false, |ps| ps.ident.as_str() == "super")
}
<|endoftext|>


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

use hcore::os::users;
use hcore::package::PackageInstall;

use error::{Result, Error};

static LOGKEY: &'static str = "UR";

/// This function checks to see if a user and group and if:
///     a) we are root
///     b) we are the specified user:group
///     c) fail otherwise
pub fn assert_pkg_user_and_group(user: &str, group: &str) -> Result<()> {
    if let None = users::get_uid_by_name(user) {
        return Err(sup_error!(Error::Permissions(format!(
            "Package requires user {} to exist, but it doesn't",
            user
        ))));
    }
    if let None = users::get_gid_by_name(&group) {
        return Err(sup_error!(Error::Permissions(format!(
            "Package requires group {} to exist, but it doesn't",
            group
        ))));
    }

    let current_user = users::get_current_username();
    let current_group = users::get_current_groupname();

    if let None = current_user {
        return Err(sup_error!(Error::Permissions(
            "Can't determine current user".to_string(),
        )));
    }

    if let None = current_group {
        return Err(sup_error!(Error::Permissions(
            "Can't determine current group".to_string(),
        )));
    }

    let current_user = current_user.unwrap();
    let current_group = current_group.unwrap();

    if current_user == users::root_level_account() {
        Ok(())
    } else {
        if current_user == user && current_group == group {
            // ok, sup is running as svc_user/svc_group already
            Ok(())
        } else {
            let msg = format!("Package must run as {}:{} or root", user, &group);
            return Err(sup_error!(Error::Permissions(msg)));
        }
    }
}
<commit_msg>Remove unused import<commit_after>// Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use hcore::os::users;

use error::{Result, Error};

static LOGKEY: &'static str = "UR";

/// This function checks to see if a user and group and if:
///     a) we are root
///     b) we are the specified user:group
///     c) fail otherwise
pub fn assert_pkg_user_and_group(user: &str, group: &str) -> Result<()> {
    if let None = users::get_uid_by_name(user) {
        return Err(sup_error!(Error::Permissions(format!(
            "Package requires user {} to exist, but it doesn't",
            user
        ))));
    }
    if let None = users::get_gid_by_name(&group) {
        return Err(sup_error!(Error::Permissions(format!(
            "Package requires group {} to exist, but it doesn't",
            group
        ))));
    }

    let current_user = users::get_current_username();
    let current_group = users::get_current_groupname();

    if let None = current_user {
        return Err(sup_error!(Error::Permissions(
            "Can't determine current user".to_string(),
        )));
    }

    if let None = current_group {
        return Err(sup_error!(Error::Permissions(
            "Can't determine current group".to_string(),
        )));
    }

    let current_user = current_user.unwrap();
    let current_group = current_group.unwrap();

    if current_user == users::root_level_account() {
        Ok(())
    } else {
        if current_user == user && current_group == group {
            // ok, sup is running as svc_user/svc_group already
            Ok(())
        } else {
            let msg = format!("Package must run as {}:{} or root", user, &group);
            return Err(sup_error!(Error::Permissions(msg)));
        }
    }
}
<|endoftext|>


<commit_before>//! An example of how to play with various graphics modes settings,
//! resize windows, etc.
//!
//! Prints instructions to the console.

use ggez::conf;
use ggez::event::{self, KeyCode, KeyMods};
use ggez::graphics::{self, Color, DrawMode};
use ggez::timer;
use ggez::{Context, GameResult};

use argh::FromArgs;

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

type Point2 = glam::Vec2;

struct WindowSettings {
    toggle_fullscreen: bool,
    is_fullscreen: bool,
    resize_projection: bool,
}

struct MainState {
    angle: f32, // in radians
    zoom: f32,
    image: graphics::Image,
    window_settings: WindowSettings,
}

impl MainState {
    fn new(ctx: &mut Context) -> GameResult<MainState> {
        let s = MainState {
            angle: 0.0,
            zoom: 1.0,
            image: graphics::Image::new(ctx, "/tile.png")?,
            window_settings: WindowSettings {
                toggle_fullscreen: false,
                is_fullscreen: false,
                resize_projection: false,
            },
        };
        Ok(s)
    }
}

impl event::EventHandler for MainState {
    fn update(&mut self, ctx: &mut Context) -> GameResult {
        const DESIRED_FPS: u32 = 60;
        while timer::check_update_time(ctx, DESIRED_FPS) {
            self.angle += 0.01;

            if self.window_settings.toggle_fullscreen {
                let fullscreen_type = if self.window_settings.is_fullscreen {
                    conf::FullscreenType::Desktop
                } else {
                    conf::FullscreenType::Windowed
                };
                ggez::graphics::set_fullscreen(ctx, fullscreen_type)?;
                self.window_settings.toggle_fullscreen = false;
            }
        }
        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        graphics::clear(ctx, Color::BLACK);
        let rotation = timer::ticks(ctx) % 1000;
        let circle = graphics::Mesh::new_circle(
            ctx,
            DrawMode::stroke(3.0),
            Point2::new(0.0, 0.0),
            100.0,
            4.0,
            Color::WHITE,
        )?;
        graphics::draw(
            ctx,
            &self.image,
            (Point2::new(400.0, 300.0), 0.0, Color::WHITE),
        )?;
        graphics::draw(
            ctx,
            &circle,
            (Point2::new(400.0, 300.0), rotation as f32, Color::WHITE),
        )?;

        // Let's draw a grid so we can see where the window bounds are.
        const COUNT: i32 = 10;
        let mut mb = graphics::MeshBuilder::new();
        for x in -COUNT..COUNT {
            for y in -COUNT..COUNT {
                const SPACING: i32 = 100;
                let fx = (x * SPACING) as f32;
                let fy = (y * SPACING) as f32;
                // println!("POS: {},{}", fx, fy);
                let r = (x as f32) / (COUNT as f32);
                let b = (y as f32) / (COUNT as f32);
                // println!("R: {}", r);
                let color = graphics::Color::new(r, 0.0, b, 1.0);
                // graphics::rectangle(
                //     ctx,
                //     color,
                //     graphics::DrawMode::fill(),
                //     graphics::Rect::new(fx, fy, 5.0, 5.0),
                // )?
                mb.rectangle(
                    DrawMode::fill(),
                    graphics::Rect::new(fx, fy, 5.0, 5.0),
                    color,
                )?;
            }
        }
        let mesh = mb.build(ctx)?;
        graphics::draw(ctx, &mesh, (ggez::mint::Point2 { x: 0.0, y: 0.0 },))?;
        graphics::present(ctx)?;
        Ok(())
    }

    fn mouse_button_down_event(
        &mut self,
        _ctx: &mut Context,
        _btn: event::MouseButton,
        x: f32,
        y: f32,
    ) {
        println!("Button clicked at: {} {}", x, y);
    }

    fn key_up_event(&mut self, ctx: &mut Context, keycode: KeyCode, _keymod: KeyMods) {
        match keycode {
            KeyCode::F => {
                self.window_settings.toggle_fullscreen = true;
                self.window_settings.is_fullscreen = !self.window_settings.is_fullscreen;
            }
            KeyCode::Up => {
                self.zoom += 0.1;
                println!("Zoom is now {}", self.zoom);
                let (w, h) = graphics::size(ctx);
                let new_rect =
                    graphics::Rect::new(0.0, 0.0, w as f32 * self.zoom, h as f32 * self.zoom);
                graphics::set_screen_coordinates(ctx, new_rect).unwrap();
            }
            KeyCode::Down => {
                self.zoom -= 0.1;
                println!("Zoom is now {}", self.zoom);
                let (w, h) = graphics::size(ctx);
                let new_rect =
                    graphics::Rect::new(0.0, 0.0, w as f32 * self.zoom, h as f32 * self.zoom);
                graphics::set_screen_coordinates(ctx, new_rect).unwrap();
            }
            KeyCode::Space => {
                self.window_settings.resize_projection = !self.window_settings.resize_projection;
                println!(
                    "Resizing the projection on window resize is now: {}",
                    self.window_settings.resize_projection
                );
            }
            _ => {}
        }
    }

    fn resize_event(&mut self, ctx: &mut Context, width: f32, height: f32) {
        println!("Resized screen to {}, {}", width, height);
        if self.window_settings.resize_projection {
            let new_rect = graphics::Rect::new(
                0.0,
                0.0,
                width as f32 * self.zoom,
                height as f32 * self.zoom,
            );
            graphics::set_screen_coordinates(ctx, new_rect).unwrap();
        }
    }
}

fn print_help() {
    println!("GRAPHICS SETTING EXAMPLE:");
    println!("    F: toggle fullscreen");
    println!("    Up/Down: Zoom in/out");
    println!(
        "    Spacebar: Toggle whether or not to resize the projection when the window is resized"
    );
    println!("    ");
    println!("    To see command-line options, run with `cargo run --example graphics_settings -- --help`");
    println!("    ");
}

/// Print out graphics settings.
#[derive(FromArgs, Debug)]
struct Opt {
    /// what level of MSAA to try to use (1, 2, 4, 8)
    #[argh(option, short = 'm', long = "msaa", default = "1")]
    msaa: u32,
    /// try to use OpenGL ES 3.0 instead of regular OpenGL.
    #[argh(switch, long = "es")]
    es: bool,
}

pub fn main() -> GameResult {
    let opt: Opt = argh::from_env();

    let resource_dir = if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
        let mut path = path::PathBuf::from(manifest_dir);
        path.push("resources");
        path
    } else {
        path::PathBuf::from("./resources")
    };

    let mut backend = conf::Backend::default();
    if opt.es {
        backend = backend.gles().version(3, 0);
    }

    let cb = ggez::ContextBuilder::new("graphics_settings", "ggez")
        .window_mode(
            conf::WindowMode::default()
                .fullscreen_type(conf::FullscreenType::Windowed)
                .resizable(true),
        )
        .window_setup(
            conf::WindowSetup::default().samples(
                conf::NumSamples::from_u32(opt.msaa)
                    .expect("Option msaa needs to be 1, 2, 4, 8 or 16!"),
            ),
        )
        .backend(backend)
        .add_resource_path(resource_dir);

    let (mut ctx, events_loop) = cb.build()?;

    println!("Renderer: {}", graphics::renderer_info(&ctx).unwrap());

    print_help();
    let state = MainState::new(&mut ctx)?;
    event::run(ctx, events_loop, state)
}
<commit_msg>Update graphics_settings example<commit_after>//! An example of how to play with various graphics modes settings,
//! resize windows, etc.
//!
//! Prints instructions to the console.
use std::convert::TryFrom;

use ggez::conf;
use ggez::event::{self, KeyCode, KeyMods};
use ggez::graphics::{self, Color, DrawMode};
use ggez::timer;
use ggez::{Context, GameResult};

use argh::FromArgs;

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

type Point2 = glam::Vec2;

struct WindowSettings {
    toggle_fullscreen: bool,
    is_fullscreen: bool,
    resize_projection: bool,
}

struct MainState {
    angle: f32, // in radians
    zoom: f32,
    image: graphics::Image,
    window_settings: WindowSettings,
}

impl MainState {
    fn new(ctx: &mut Context) -> GameResult<MainState> {
        let s = MainState {
            angle: 0.0,
            zoom: 1.0,
            image: graphics::Image::new(ctx, "/tile.png")?,
            window_settings: WindowSettings {
                toggle_fullscreen: false,
                is_fullscreen: false,
                resize_projection: false,
            },
        };
        Ok(s)
    }
}

impl event::EventHandler for MainState {
    fn update(&mut self, ctx: &mut Context) -> GameResult {
        const DESIRED_FPS: u32 = 60;
        while timer::check_update_time(ctx, DESIRED_FPS) {
            self.angle += 0.01;

            if self.window_settings.toggle_fullscreen {
                let fullscreen_type = if self.window_settings.is_fullscreen {
                    conf::FullscreenType::Desktop
                } else {
                    conf::FullscreenType::Windowed
                };
                ggez::graphics::set_fullscreen(ctx, fullscreen_type)?;
                self.window_settings.toggle_fullscreen = false;
            }
        }
        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        graphics::clear(ctx, Color::BLACK);
        let rotation = timer::ticks(ctx) % 1000;
        let circle = graphics::Mesh::new_circle(
            ctx,
            DrawMode::stroke(3.0),
            Point2::new(0.0, 0.0),
            100.0,
            4.0,
            Color::WHITE,
        )?;
        graphics::draw(
            ctx,
            &self.image,
            (Point2::new(400.0, 300.0), 0.0, Color::WHITE),
        )?;
        graphics::draw(
            ctx,
            &circle,
            (Point2::new(400.0, 300.0), rotation as f32, Color::WHITE),
        )?;

        // Let's draw a grid so we can see where the window bounds are.
        const COUNT: i32 = 10;
        let mut mb = graphics::MeshBuilder::new();
        for x in -COUNT..COUNT {
            for y in -COUNT..COUNT {
                const SPACING: i32 = 100;
                let fx = (x * SPACING) as f32;
                let fy = (y * SPACING) as f32;
                // println!("POS: {},{}", fx, fy);
                let r = (x as f32) / (COUNT as f32);
                let b = (y as f32) / (COUNT as f32);
                // println!("R: {}", r);
                let color = graphics::Color::new(r, 0.0, b, 1.0);
                // graphics::rectangle(
                //     ctx,
                //     color,
                //     graphics::DrawMode::fill(),
                //     graphics::Rect::new(fx, fy, 5.0, 5.0),
                // )?
                mb.rectangle(
                    DrawMode::fill(),
                    graphics::Rect::new(fx, fy, 5.0, 5.0),
                    color,
                )?;
            }
        }
        let mesh = mb.build(ctx)?;
        graphics::draw(ctx, &mesh, (ggez::mint::Point2 { x: 0.0, y: 0.0 },))?;
        graphics::present(ctx)?;
        Ok(())
    }

    fn mouse_button_down_event(
        &mut self,
        _ctx: &mut Context,
        _btn: event::MouseButton,
        x: f32,
        y: f32,
    ) {
        println!("Button clicked at: {} {}", x, y);
    }

    fn key_up_event(&mut self, ctx: &mut Context, keycode: KeyCode, _keymod: KeyMods) {
        match keycode {
            KeyCode::F => {
                self.window_settings.toggle_fullscreen = true;
                self.window_settings.is_fullscreen = !self.window_settings.is_fullscreen;
            }
            KeyCode::Up => {
                self.zoom += 0.1;
                println!("Zoom is now {}", self.zoom);
                let (w, h) = graphics::size(ctx);
                let new_rect =
                    graphics::Rect::new(0.0, 0.0, w as f32 * self.zoom, h as f32 * self.zoom);
                graphics::set_screen_coordinates(ctx, new_rect).unwrap();
            }
            KeyCode::Down => {
                self.zoom -= 0.1;
                println!("Zoom is now {}", self.zoom);
                let (w, h) = graphics::size(ctx);
                let new_rect =
                    graphics::Rect::new(0.0, 0.0, w as f32 * self.zoom, h as f32 * self.zoom);
                graphics::set_screen_coordinates(ctx, new_rect).unwrap();
            }
            KeyCode::Space => {
                self.window_settings.resize_projection = !self.window_settings.resize_projection;
                println!(
                    "Resizing the projection on window resize is now: {}",
                    self.window_settings.resize_projection
                );
            }
            _ => {}
        }
    }

    fn resize_event(&mut self, ctx: &mut Context, width: f32, height: f32) {
        println!("Resized screen to {}, {}", width, height);
        if self.window_settings.resize_projection {
            let new_rect = graphics::Rect::new(
                0.0,
                0.0,
                width as f32 * self.zoom,
                height as f32 * self.zoom,
            );
            graphics::set_screen_coordinates(ctx, new_rect).unwrap();
        }
    }
}

fn print_help() {
    println!("GRAPHICS SETTING EXAMPLE:");
    println!("    F: toggle fullscreen");
    println!("    Up/Down: Zoom in/out");
    println!(
        "    Spacebar: Toggle whether or not to resize the projection when the window is resized"
    );
    println!("    ");
    println!("    To see command-line options, run with `cargo run --example graphics_settings -- --help`");
    println!("    ");
}

/// Print out graphics settings.
#[derive(FromArgs, Debug)]
struct Opt {
    /// what level of MSAA to try to use (1, 2, 4, 8)
    #[argh(option, short = 'm', long = "msaa", default = "1")]
    msaa: u8,
    /// try to use OpenGL ES 3.0 instead of regular OpenGL.
    #[argh(switch, long = "es")]
    es: bool,
}

pub fn main() -> GameResult {
    let opt: Opt = argh::from_env();

    let resource_dir = if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
        let mut path = path::PathBuf::from(manifest_dir);
        path.push("resources");
        path
    } else {
        path::PathBuf::from("./resources")
    };

    let mut backend = conf::Backend::default();
    if opt.es {
        backend = backend.gles().version(3, 0);
    }

    let cb = ggez::ContextBuilder::new("graphics_settings", "ggez")
        .window_mode(
            conf::WindowMode::default()
                .fullscreen_type(conf::FullscreenType::Windowed)
                .resizable(true),
        )
        .window_setup(
            conf::WindowSetup::default().samples(
                conf::NumSamples::try_from(opt.msaa)
                    .expect("Option msaa needs to be 1, 2, 4, 8 or 16!"),
            ),
        )
        .backend(backend)
        .add_resource_path(resource_dir);

    let (mut ctx, events_loop) = cb.build()?;

    println!("Renderer: {}", graphics::renderer_info(&ctx).unwrap());

    print_help();
    let state = MainState::new(&mut ctx)?;
    event::run(ctx, events_loop, state)
}
<|endoftext|>


<commit_before>//! Handling of neuron activation functions.

use num_traits::Float;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Represents which activation function to use when evaluating neurons.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum Activation {
    /// Identity function. Outputs `x`.
    Linear,
    /// Heaviside or unit step function. Outputs `1` for `x > 0`, or `0` otherwise.
    UnitStep,
    /// Sign function. Outputs `1` for `x > 0`, `0` for `x = 0`, or `-1` otherwise.
    Sign,
    /// Logistic function. Outputs `1 / (1 + exp(-x))`.
    Sigmoid,
    /// Hyperbolic tangent function. Outputs `tanh(x)`.
    Tanh,
    /// Softsign function. Outputs `x / (1 + abs(x))`.
    SoftSign,
    /// Bent identity function. Outputs `(sqrt(x^2 + 1) - 1) / 2 + x`.
    BentIdentity,
    /// Rectified linear unit. Outputs `max(x, 0)`.
    Relu,
}

impl Activation {
    /// Applies the activation function to the input.
    pub fn apply<T: Float>(&self, x: T) -> T {
        match self {
            Activation::Linear => linear(x),
            Activation::UnitStep => unit_step(x),
            Activation::Sign => sign(x),
            Activation::Sigmoid => sigmoid(x),
            Activation::Tanh => tanh(x),
            Activation::SoftSign => soft_sign(x),
            Activation::BentIdentity => bent_identity(x),
            Activation::Relu => relu(x),
        }
    }

    /// Returns the corresponding function to the `Activation`.
    pub fn get_function<T: Float>(&self) -> fn(T) -> T {
        match self {
            Activation::Linear => linear,
            Activation::UnitStep => unit_step,
            Activation::Sign => sign,
            Activation::Sigmoid => sigmoid,
            Activation::Tanh => tanh,
            Activation::SoftSign => soft_sign,
            Activation::BentIdentity => bent_identity,
            Activation::Relu => relu,
        }
    }
}

/// Outputs `x`.
pub fn linear<T>(x: T) -> T {
    x
}

/// Heaviside/unit step function. Outputs `1` for `x > 0`, or `0` otherwise.
pub fn unit_step<T: Float>(x: T) -> T {
    if x > T::zero() {
        T::one()
    } else {
        T::zero()
    }
}

/// Outputs `1` for `x > 0`, `0` for `x = 0`, or `-1` otherwise.
pub fn sign<T: Float>(x: T) -> T {
    if x > T::zero() {
        T::one()
    } else if x == T::zero() {
        T::zero()
    } else {
        -T::one()
    }
}

/// Logistic function. Outputs `1 / (1 + exp(-x))`.
pub fn sigmoid<T: Float>(x: T) -> T {
    T::one() / (T::one() + (-x).exp())
}

/// Outputs `tanh(x)`.
pub fn tanh<T: Float>(x: T) -> T {
    x.tanh()
}

/// Outputs `x / (1 + abs(x))`.
pub fn soft_sign<T: Float>(x: T) -> T {
    x / (T::one() + x.abs())
}

/// Outputs `(sqrt(x^2 + 1) - 1) / 2 + x`.
pub fn bent_identity<T: Float>(x: T) -> T {
    (((x.powi(2) + T::one()).sqrt() - T::one()) / (T::one() + T::one())) + x
}

/// Rectified linear unit. Outputs `max(0, x)`.
pub fn relu<T: Float>(x: T) -> T {
    x.max(T::zero())
}

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

    use super::*;

    #[test]
    fn test_activation() {
        assert_approx_eq!(5.0, Activation::Linear.apply(5.0));
        assert_approx_eq!(0.0, Activation::UnitStep.apply(-5.0));
        assert_approx_eq!(-1.0, Activation::Sign.apply(-5.0));
        assert_approx_eq!(0.8807970779778823, Activation::Sigmoid.apply(2.0));
        assert_approx_eq!(0.9640275800758169, Activation::Tanh.apply(2.0));
        assert_approx_eq!(0.8333333333333334, Activation::SoftSign.apply(5.0));
        assert_approx_eq!(7.049509756796392, Activation::BentIdentity.apply(5.0));
        assert_approx_eq!(5.0, Activation::Relu.apply(5.0));
        assert_approx_eq!(0.0, Activation::Relu.apply(-5.0));
    }
}
<commit_msg>Make activation functions accessible directly through `Activation`<commit_after>//! Handling of neuron activation functions.

use num_traits::Float;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Represents which activation function to use when evaluating neurons.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum Activation {
    /// Identity function. Outputs `x`.
    Linear,
    /// Heaviside or unit step function. Outputs `1` for `x > 0`, or `0` otherwise.
    UnitStep,
    /// Sign function. Outputs `1` for `x > 0`, `0` for `x = 0`, or `-1` otherwise.
    Sign,
    /// Logistic function. Outputs `1 / (1 + exp(-x))`.
    Sigmoid,
    /// Hyperbolic tangent function. Outputs `tanh(x)`.
    Tanh,
    /// Softsign function. Outputs `x / (1 + abs(x))`.
    SoftSign,
    /// Bent identity function. Outputs `(sqrt(x^2 + 1) - 1) / 2 + x`.
    BentIdentity,
    /// Rectified linear unit. Outputs `max(x, 0)`.
    Relu,
}

impl Activation {
    /// Applies the activation function to the input.
    pub fn apply<T: Float>(&self, x: T) -> T {
        match self {
            Activation::Linear => Self::linear(x),
            Activation::UnitStep => Self::unit_step(x),
            Activation::Sign => Self::sign(x),
            Activation::Sigmoid => Self::sigmoid(x),
            Activation::Tanh => Self::tanh(x),
            Activation::SoftSign => Self::soft_sign(x),
            Activation::BentIdentity => Self::bent_identity(x),
            Activation::Relu => Self::relu(x),
        }
    }

    /// Returns the corresponding function to the `Activation`.
    pub fn get_function<T: Float>(&self) -> fn(T) -> T {
        match self {
            Activation::Linear => Self::linear,
            Activation::UnitStep => Self::unit_step,
            Activation::Sign => Self::sign,
            Activation::Sigmoid => Self::sigmoid,
            Activation::Tanh => Self::tanh,
            Activation::SoftSign => Self::soft_sign,
            Activation::BentIdentity => Self::bent_identity,
            Activation::Relu => Self::relu,
        }
    }

    /// Outputs `x`.
    pub fn linear<T: Float>(x: T) -> T {
        x
    }

    /// Heaviside/unit step function. Outputs `1` for `x > 0`, or `0` otherwise.
    pub fn unit_step<T: Float>(x: T) -> T {
        if x > T::zero() {
            T::one()
        } else {
            T::zero()
        }
    }

    /// Outputs `1` for `x > 0`, `0` for `x = 0`, or `-1` otherwise.
    pub fn sign<T: Float>(x: T) -> T {
        if x > T::zero() {
            T::one()
        } else if x == T::zero() {
            T::zero()
        } else {
            -T::one()
        }
    }

    /// Logistic function. Outputs `1 / (1 + exp(-x))`.
    pub fn sigmoid<T: Float>(x: T) -> T {
        T::one() / (T::one() + (-x).exp())
    }

    /// Outputs `tanh(x)`.
    pub fn tanh<T: Float>(x: T) -> T {
        x.tanh()
    }

    /// Outputs `x / (1 + abs(x))`.
    pub fn soft_sign<T: Float>(x: T) -> T {
        x / (T::one() + x.abs())
    }

    /// Outputs `(sqrt(x^2 + 1) - 1) / 2 + x`.
    pub fn bent_identity<T: Float>(x: T) -> T {
        (((x.powi(2) + T::one()).sqrt() - T::one()) / (T::one() + T::one())) + x
    }

    /// Rectified linear unit. Outputs `max(0, x)`.
    pub fn relu<T: Float>(x: T) -> T {
        x.max(T::zero())
    }
}

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

    use super::*;

    #[test]
    fn test_activation() {
        assert_approx_eq!(5.0, Activation::Linear.apply(5.0));
        assert_approx_eq!(0.0, Activation::UnitStep.apply(-5.0));
        assert_approx_eq!(-1.0, Activation::Sign.apply(-5.0));
        assert_approx_eq!(0.8807970779778823, Activation::Sigmoid.apply(2.0));
        assert_approx_eq!(0.9640275800758169, Activation::Tanh.apply(2.0));
        assert_approx_eq!(0.8333333333333334, Activation::SoftSign.apply(5.0));
        assert_approx_eq!(7.049509756796392, Activation::BentIdentity.apply(5.0));
        assert_approx_eq!(5.0, Activation::Relu.apply(5.0));
        assert_approx_eq!(0.0, Activation::Relu.apply(-5.0));
    }
}
<|endoftext|>