<commit_before>#[macro_use]
extern crate clap;
extern crate regex;

use std::io::Write;
use std::str;

include!("../clap-test.rs");

use clap::{App, Arg};

static SCF2OP: &'static str = "flag present 2 times
option NOT present
positional NOT present
flag2 NOT present
option2 maybe present with value of: Nothing
positional2 maybe present with value of: Nothing
option3 NOT present
positional3 NOT present
option NOT present
positional NOT present
subcmd present
flag present 2 times
scoption present with value: some
An scoption: some
scpositional present with value: value
";

static SCFOP: &'static str = "flag present 1 times
option NOT present
positional NOT present
flag2 NOT present
option2 maybe present with value of: Nothing
positional2 maybe present with value of: Nothing
option3 NOT present
positional3 NOT present
option NOT present
positional NOT present
subcmd present
flag present 1 times
scoption present with value: some
An scoption: some
scpositional present with value: value
";

static O2P: &'static str = "flag NOT present
option present 2 times with value: some
An option: some
An option: other
positional present with value: value
flag2 NOT present
option2 maybe present with value of: Nothing
positional2 maybe present with value of: Nothing
option3 NOT present
positional3 NOT present
option present 2 times with value: some
An option: some
An option: other
positional present with value: value
subcmd NOT present
";

static F2OP: &'static str = "flag present 2 times
option present 1 times with value: some
An option: some
positional present with value: value
flag2 NOT present
option2 maybe present with value of: Nothing
positional2 maybe present with value of: Nothing
option3 NOT present
positional3 NOT present
option present 1 times with value: some
An option: some
positional present with value: value
subcmd NOT present
";

static FOP: &'static str = "flag present 1 times
option present 1 times with value: some
An option: some
positional present with value: value
flag2 NOT present
option2 maybe present with value of: Nothing
positional2 maybe present with value of: Nothing
option3 NOT present
positional3 NOT present
option present 1 times with value: some
An option: some
positional present with value: value
subcmd NOT present
";

pub fn check_complex_output(args: &str, out: &str) {
    let mut w = vec![];
    let matches = test::complex_app().get_matches_from(args.split(' ').collect::<Vec<_>>());
    if matches.is_present("flag") {
        writeln!(w, "flag present {} times", matches.occurrences_of("flag")).unwrap();
    } else {
        writeln!(w, "flag NOT present").unwrap();
    }

    if matches.is_present("option") {
        if let Some(v) = matches.value_of("option") {
            writeln!(w, "option present {} times with value: {}",matches.occurrences_of("option"), v).unwrap();
        }
        if let Some(ov) = matches.values_of("option") {
            for o in ov {
                writeln!(w, "An option: {}", o).unwrap();
            }
        }
    } else {
        writeln!(w, "option NOT present").unwrap();
    }

    if let Some(p) = matches.value_of("positional") {
        writeln!(w, "positional present with value: {}", p).unwrap();
    } else {
        writeln!(w, "positional NOT present").unwrap();
    }

    if matches.is_present("flag2") {
        writeln!(w, "flag2 present").unwrap();
        writeln!(w, "option2 present with value of: {}", matches.value_of("long-option-2").unwrap()).unwrap();
        writeln!(w, "positional2 present with value of: {}", matches.value_of("positional2").unwrap()).unwrap();
    } else {
        writeln!(w, "flag2 NOT present").unwrap();
        writeln!(w, "option2 maybe present with value of: {}", matches.value_of("long-option-2").unwrap_or("Nothing")).unwrap();
        writeln!(w, "positional2 maybe present with value of: {}", matches.value_of("positional2").unwrap_or("Nothing")).unwrap();
    }

    let _ = match matches.value_of("Option3").unwrap_or("") {
        "fast" => writeln!(w, "option3 present quickly"),
        "slow" => writeln!(w, "option3 present slowly"),
        _      => writeln!(w, "option3 NOT present")
    };

    let _ = match matches.value_of("positional3").unwrap_or("") {
        "vi" => writeln!(w, "positional3 present in vi mode"),
        "emacs" => writeln!(w, "positional3 present in emacs mode"),
        _      => writeln!(w, "positional3 NOT present")
    };

    if matches.is_present("option") {
        if let Some(v) = matches.value_of("option") {
            writeln!(w, "option present {} times with value: {}",matches.occurrences_of("option"), v).unwrap();
        }
        if let Some(ov) = matches.values_of("option") {
            for o in ov {
                writeln!(w, "An option: {}", o).unwrap();
            }
        }
    } else {
        writeln!(w, "option NOT present").unwrap();
    }

    if let Some(p) = matches.value_of("positional") {
        writeln!(w, "positional present with value: {}", p).unwrap();
    } else {
        writeln!(w, "positional NOT present").unwrap();
    }
    if matches.is_present("subcmd") {
        writeln!(w, "subcmd present").unwrap();
        if let Some(matches) = matches.subcommand_matches("subcmd") {
            if matches.is_present("flag") {
                writeln!(w, "flag present {} times", matches.occurrences_of("flag")).unwrap();
            } else {
                writeln!(w, "flag NOT present").unwrap();
            }

            if matches.is_present("option") {
                if let Some(v) = matches.value_of("option") {
                    writeln!(w, "scoption present with value: {}", v).unwrap();
                }
                if let Some(ov) = matches.values_of("option") {
                    for o in ov {
                        writeln!(w, "An scoption: {}", o).unwrap();
                    }
                }
            } else {
                writeln!(w, "scoption NOT present").unwrap();
            }

            if let Some(p) = matches.value_of("scpositional") {
                writeln!(w, "scpositional present with value: {}", p).unwrap();
            }
        }
    } else {
        writeln!(w, "subcmd NOT present").unwrap();
    }

    let res = str::from_utf8(&w).unwrap();
    assert_eq!(res, out);
}

arg_enum!{
    #[derive(Debug)]
    enum Val1 {
        ValOne,
        ValTwo
    }
}
arg_enum!{
    #[derive(Debug)]
    pub enum Val2 {
        ValOne,
        ValTwo
    }
}
arg_enum!{
    enum Val3 {
        ValOne,
        ValTwo
    }
}
arg_enum!{
    pub enum Val4 {
        ValOne,
        ValTwo
    }
}

#[test]
fn test_enums() {
    let v1_lower = "valone";
    let v1_camel = "ValOne";

    let v1_lp = v1_lower.parse::<Val1>().unwrap();
    let v1_cp = v1_camel.parse::<Val1>().unwrap();
    match v1_lp {
        Val1::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
    match v1_cp {
        Val1::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
    let v1_lp = v1_lower.parse::<Val2>().unwrap();
    let v1_cp = v1_camel.parse::<Val2>().unwrap();
    match v1_lp {
        Val2::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
    match v1_cp {
        Val2::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
    let v1_lp = v1_lower.parse::<Val3>().unwrap();
    let v1_cp = v1_camel.parse::<Val3>().unwrap();
    match v1_lp {
        Val3::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
    match v1_cp {
        Val3::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
    let v1_lp = v1_lower.parse::<Val4>().unwrap();
    let v1_cp = v1_camel.parse::<Val4>().unwrap();
    match v1_lp {
        Val4::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
    match v1_cp {
        Val4::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
}

#[test]
fn create_app() {
    let _ =
        App::new("test").version("1.0").author("kevin").about("does awesome things").get_matches_from(vec![""]);
}

#[test]
fn add_multiple_arg() {
    let _ = App::new("test")
                .args(&mut [
                    Arg::with_name("test").short("s"),
                    Arg::with_name("test2").short("l")])
                .get_matches_from(vec![""]);
}
#[test]
fn flag_x2_opt() {
    check_complex_output("clap-test value -f -f -o some",
"flag present 2 times
option present 1 times with value: some
An option: some
positional present with value: value
flag2 NOT present
option2 maybe present with value of: Nothing
positional2 maybe present with value of: Nothing
option3 NOT present
positional3 NOT present
option present 1 times with value: some
An option: some
positional present with value: value
subcmd NOT present
");
}

#[test]
fn long_opt_x2_pos() {
    check_complex_output("clap-test value --option some --option other", O2P);
}

#[test]
fn long_opt_eq_x2_pos() {
    check_complex_output("clap-test value --option=some --option=other", O2P);
}

#[test]
fn short_opt_x2_pos() {
    check_complex_output("clap-test value -o some -o other", O2P);
}

#[test]
fn short_opt_eq_x2_pos() {
    check_complex_output("clap-test value -o=some -o=other", O2P);
}

#[test]
fn short_flag_x2_comb_short_opt_pos() {
    check_complex_output("clap-test value -ff -o some", F2OP);
}

#[test]
fn short_flag_short_opt_pos() {
    check_complex_output("clap-test value -f -o some", FOP);
}

#[test]
fn long_flag_long_opt_pos() {
    check_complex_output("clap-test value --flag --option some", FOP);
}

#[test]
fn long_flag_long_opt_eq_pos() {
    check_complex_output("clap-test value --flag --option=some", FOP);
}

#[test]
fn sc_long_flag_long_opt() {
    check_complex_output("clap-test subcmd value --flag --option some", SCFOP);
}

#[test]
fn sc_long_flag_short_opt_pos() {
    check_complex_output("clap-test subcmd value --flag -o some", SCFOP);
}

#[test]
fn sc_long_flag_long_opt_eq_pos() {
    check_complex_output("clap-test subcmd value --flag --option=some", SCFOP);
}

#[test]
fn sc_short_flag_long_opt_pos() {
    check_complex_output("clap-test subcmd value -f --option some", SCFOP);
}

#[test]
fn sc_short_flag_short_opt_pos() {
    check_complex_output("clap-test subcmd value -f -o some", SCFOP);
}

#[test]
fn sc_short_flag_short_opt_eq_pos() {
    check_complex_output("clap-test subcmd value -f -o=some", SCFOP);
}

#[test]
fn sc_short_flag_long_opt_eq_pos() {
    check_complex_output("clap-test subcmd value -f --option=some", SCFOP);
}

#[test]
fn sc_short_flag_x2_comb_long_opt_pos() {
    check_complex_output("clap-test subcmd value -ff --option some", SCF2OP);
}

#[test]
fn sc_short_flag_x2_comb_short_opt_pos() {
    check_complex_output("clap-test subcmd value -ff -o some", SCF2OP);
}

#[test]
fn sc_short_flag_x2_comb_long_opt_eq_pos() {
    check_complex_output("clap-test subcmd value -ff --option=some", SCF2OP);
}

#[test]
fn sc_short_flag_x2_comb_short_opt_eq_pos() {
    check_complex_output("clap-test subcmd value -ff -o=some", SCF2OP);
}

#[test]
fn sc_long_flag_x2_long_opt_pos() {
    check_complex_output("clap-test subcmd value --flag --flag --option some", SCF2OP);
}

#[test]
fn sc_long_flag_x2_short_opt_pos() {
    check_complex_output("clap-test subcmd value --flag --flag -o some", SCF2OP);
}

#[test]
fn sc_long_flag_x2_short_opt_eq_pos() {
    check_complex_output("clap-test subcmd value --flag --flag -o=some", SCF2OP);
}

#[test]
fn sc_long_flag_x2_long_opt_eq_pos() {
    check_complex_output("clap-test subcmd value --flag --flag --option=some", SCF2OP);
}

#[test]
fn sc_short_flag_x2_long_opt_pos() {
    check_complex_output("clap-test subcmd value -f -f --option some", SCF2OP);
}

#[test]
fn sc_short_flag_x2_short_opt_pos() {
    check_complex_output("clap-test subcmd value -f -f -o some", SCF2OP);
}

#[test]
fn sc_short_flag_x2_short_opt_eq_pos() {
    check_complex_output("clap-test subcmd value -f -f -o=some", SCF2OP);
}

#[test]
fn sc_short_flag_x2_long_opt_eq_pos() {
    check_complex_output("clap-test subcmd value -f -f --option=some", SCF2OP);
}
<commit_msg>chore(clippy): Remove unnecessary mut in test.<commit_after>#[macro_use]
extern crate clap;
extern crate regex;

use std::io::Write;
use std::str;

include!("../clap-test.rs");

use clap::{App, Arg};

static SCF2OP: &'static str = "flag present 2 times
option NOT present
positional NOT present
flag2 NOT present
option2 maybe present with value of: Nothing
positional2 maybe present with value of: Nothing
option3 NOT present
positional3 NOT present
option NOT present
positional NOT present
subcmd present
flag present 2 times
scoption present with value: some
An scoption: some
scpositional present with value: value
";

static SCFOP: &'static str = "flag present 1 times
option NOT present
positional NOT present
flag2 NOT present
option2 maybe present with value of: Nothing
positional2 maybe present with value of: Nothing
option3 NOT present
positional3 NOT present
option NOT present
positional NOT present
subcmd present
flag present 1 times
scoption present with value: some
An scoption: some
scpositional present with value: value
";

static O2P: &'static str = "flag NOT present
option present 2 times with value: some
An option: some
An option: other
positional present with value: value
flag2 NOT present
option2 maybe present with value of: Nothing
positional2 maybe present with value of: Nothing
option3 NOT present
positional3 NOT present
option present 2 times with value: some
An option: some
An option: other
positional present with value: value
subcmd NOT present
";

static F2OP: &'static str = "flag present 2 times
option present 1 times with value: some
An option: some
positional present with value: value
flag2 NOT present
option2 maybe present with value of: Nothing
positional2 maybe present with value of: Nothing
option3 NOT present
positional3 NOT present
option present 1 times with value: some
An option: some
positional present with value: value
subcmd NOT present
";

static FOP: &'static str = "flag present 1 times
option present 1 times with value: some
An option: some
positional present with value: value
flag2 NOT present
option2 maybe present with value of: Nothing
positional2 maybe present with value of: Nothing
option3 NOT present
positional3 NOT present
option present 1 times with value: some
An option: some
positional present with value: value
subcmd NOT present
";

pub fn check_complex_output(args: &str, out: &str) {
    let mut w = vec![];
    let matches = test::complex_app().get_matches_from(args.split(' ').collect::<Vec<_>>());
    if matches.is_present("flag") {
        writeln!(w, "flag present {} times", matches.occurrences_of("flag")).unwrap();
    } else {
        writeln!(w, "flag NOT present").unwrap();
    }

    if matches.is_present("option") {
        if let Some(v) = matches.value_of("option") {
            writeln!(w, "option present {} times with value: {}",matches.occurrences_of("option"), v).unwrap();
        }
        if let Some(ov) = matches.values_of("option") {
            for o in ov {
                writeln!(w, "An option: {}", o).unwrap();
            }
        }
    } else {
        writeln!(w, "option NOT present").unwrap();
    }

    if let Some(p) = matches.value_of("positional") {
        writeln!(w, "positional present with value: {}", p).unwrap();
    } else {
        writeln!(w, "positional NOT present").unwrap();
    }

    if matches.is_present("flag2") {
        writeln!(w, "flag2 present").unwrap();
        writeln!(w, "option2 present with value of: {}", matches.value_of("long-option-2").unwrap()).unwrap();
        writeln!(w, "positional2 present with value of: {}", matches.value_of("positional2").unwrap()).unwrap();
    } else {
        writeln!(w, "flag2 NOT present").unwrap();
        writeln!(w, "option2 maybe present with value of: {}", matches.value_of("long-option-2").unwrap_or("Nothing")).unwrap();
        writeln!(w, "positional2 maybe present with value of: {}", matches.value_of("positional2").unwrap_or("Nothing")).unwrap();
    }

    let _ = match matches.value_of("Option3").unwrap_or("") {
        "fast" => writeln!(w, "option3 present quickly"),
        "slow" => writeln!(w, "option3 present slowly"),
        _      => writeln!(w, "option3 NOT present")
    };

    let _ = match matches.value_of("positional3").unwrap_or("") {
        "vi" => writeln!(w, "positional3 present in vi mode"),
        "emacs" => writeln!(w, "positional3 present in emacs mode"),
        _      => writeln!(w, "positional3 NOT present")
    };

    if matches.is_present("option") {
        if let Some(v) = matches.value_of("option") {
            writeln!(w, "option present {} times with value: {}",matches.occurrences_of("option"), v).unwrap();
        }
        if let Some(ov) = matches.values_of("option") {
            for o in ov {
                writeln!(w, "An option: {}", o).unwrap();
            }
        }
    } else {
        writeln!(w, "option NOT present").unwrap();
    }

    if let Some(p) = matches.value_of("positional") {
        writeln!(w, "positional present with value: {}", p).unwrap();
    } else {
        writeln!(w, "positional NOT present").unwrap();
    }
    if matches.is_present("subcmd") {
        writeln!(w, "subcmd present").unwrap();
        if let Some(matches) = matches.subcommand_matches("subcmd") {
            if matches.is_present("flag") {
                writeln!(w, "flag present {} times", matches.occurrences_of("flag")).unwrap();
            } else {
                writeln!(w, "flag NOT present").unwrap();
            }

            if matches.is_present("option") {
                if let Some(v) = matches.value_of("option") {
                    writeln!(w, "scoption present with value: {}", v).unwrap();
                }
                if let Some(ov) = matches.values_of("option") {
                    for o in ov {
                        writeln!(w, "An scoption: {}", o).unwrap();
                    }
                }
            } else {
                writeln!(w, "scoption NOT present").unwrap();
            }

            if let Some(p) = matches.value_of("scpositional") {
                writeln!(w, "scpositional present with value: {}", p).unwrap();
            }
        }
    } else {
        writeln!(w, "subcmd NOT present").unwrap();
    }

    let res = str::from_utf8(&w).unwrap();
    assert_eq!(res, out);
}

arg_enum!{
    #[derive(Debug)]
    enum Val1 {
        ValOne,
        ValTwo
    }
}
arg_enum!{
    #[derive(Debug)]
    pub enum Val2 {
        ValOne,
        ValTwo
    }
}
arg_enum!{
    enum Val3 {
        ValOne,
        ValTwo
    }
}
arg_enum!{
    pub enum Val4 {
        ValOne,
        ValTwo
    }
}

#[test]
fn test_enums() {
    let v1_lower = "valone";
    let v1_camel = "ValOne";

    let v1_lp = v1_lower.parse::<Val1>().unwrap();
    let v1_cp = v1_camel.parse::<Val1>().unwrap();
    match v1_lp {
        Val1::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
    match v1_cp {
        Val1::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
    let v1_lp = v1_lower.parse::<Val2>().unwrap();
    let v1_cp = v1_camel.parse::<Val2>().unwrap();
    match v1_lp {
        Val2::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
    match v1_cp {
        Val2::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
    let v1_lp = v1_lower.parse::<Val3>().unwrap();
    let v1_cp = v1_camel.parse::<Val3>().unwrap();
    match v1_lp {
        Val3::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
    match v1_cp {
        Val3::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
    let v1_lp = v1_lower.parse::<Val4>().unwrap();
    let v1_cp = v1_camel.parse::<Val4>().unwrap();
    match v1_lp {
        Val4::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
    match v1_cp {
        Val4::ValOne => (),
        _ => panic!("Val1 didn't parse correctly"),
    }
}

#[test]
fn create_app() {
    let _ =
        App::new("test").version("1.0").author("kevin").about("does awesome things").get_matches_from(vec![""]);
}

#[test]
fn add_multiple_arg() {
    let _ = App::new("test")
                .args(&[
                    Arg::with_name("test").short("s"),
                    Arg::with_name("test2").short("l")])
                .get_matches_from(vec![""]);
}
#[test]
fn flag_x2_opt() {
    check_complex_output("clap-test value -f -f -o some",
"flag present 2 times
option present 1 times with value: some
An option: some
positional present with value: value
flag2 NOT present
option2 maybe present with value of: Nothing
positional2 maybe present with value of: Nothing
option3 NOT present
positional3 NOT present
option present 1 times with value: some
An option: some
positional present with value: value
subcmd NOT present
");
}

#[test]
fn long_opt_x2_pos() {
    check_complex_output("clap-test value --option some --option other", O2P);
}

#[test]
fn long_opt_eq_x2_pos() {
    check_complex_output("clap-test value --option=some --option=other", O2P);
}

#[test]
fn short_opt_x2_pos() {
    check_complex_output("clap-test value -o some -o other", O2P);
}

#[test]
fn short_opt_eq_x2_pos() {
    check_complex_output("clap-test value -o=some -o=other", O2P);
}

#[test]
fn short_flag_x2_comb_short_opt_pos() {
    check_complex_output("clap-test value -ff -o some", F2OP);
}

#[test]
fn short_flag_short_opt_pos() {
    check_complex_output("clap-test value -f -o some", FOP);
}

#[test]
fn long_flag_long_opt_pos() {
    check_complex_output("clap-test value --flag --option some", FOP);
}

#[test]
fn long_flag_long_opt_eq_pos() {
    check_complex_output("clap-test value --flag --option=some", FOP);
}

#[test]
fn sc_long_flag_long_opt() {
    check_complex_output("clap-test subcmd value --flag --option some", SCFOP);
}

#[test]
fn sc_long_flag_short_opt_pos() {
    check_complex_output("clap-test subcmd value --flag -o some", SCFOP);
}

#[test]
fn sc_long_flag_long_opt_eq_pos() {
    check_complex_output("clap-test subcmd value --flag --option=some", SCFOP);
}

#[test]
fn sc_short_flag_long_opt_pos() {
    check_complex_output("clap-test subcmd value -f --option some", SCFOP);
}

#[test]
fn sc_short_flag_short_opt_pos() {
    check_complex_output("clap-test subcmd value -f -o some", SCFOP);
}

#[test]
fn sc_short_flag_short_opt_eq_pos() {
    check_complex_output("clap-test subcmd value -f -o=some", SCFOP);
}

#[test]
fn sc_short_flag_long_opt_eq_pos() {
    check_complex_output("clap-test subcmd value -f --option=some", SCFOP);
}

#[test]
fn sc_short_flag_x2_comb_long_opt_pos() {
    check_complex_output("clap-test subcmd value -ff --option some", SCF2OP);
}

#[test]
fn sc_short_flag_x2_comb_short_opt_pos() {
    check_complex_output("clap-test subcmd value -ff -o some", SCF2OP);
}

#[test]
fn sc_short_flag_x2_comb_long_opt_eq_pos() {
    check_complex_output("clap-test subcmd value -ff --option=some", SCF2OP);
}

#[test]
fn sc_short_flag_x2_comb_short_opt_eq_pos() {
    check_complex_output("clap-test subcmd value -ff -o=some", SCF2OP);
}

#[test]
fn sc_long_flag_x2_long_opt_pos() {
    check_complex_output("clap-test subcmd value --flag --flag --option some", SCF2OP);
}

#[test]
fn sc_long_flag_x2_short_opt_pos() {
    check_complex_output("clap-test subcmd value --flag --flag -o some", SCF2OP);
}

#[test]
fn sc_long_flag_x2_short_opt_eq_pos() {
    check_complex_output("clap-test subcmd value --flag --flag -o=some", SCF2OP);
}

#[test]
fn sc_long_flag_x2_long_opt_eq_pos() {
    check_complex_output("clap-test subcmd value --flag --flag --option=some", SCF2OP);
}

#[test]
fn sc_short_flag_x2_long_opt_pos() {
    check_complex_output("clap-test subcmd value -f -f --option some", SCF2OP);
}

#[test]
fn sc_short_flag_x2_short_opt_pos() {
    check_complex_output("clap-test subcmd value -f -f -o some", SCF2OP);
}

#[test]
fn sc_short_flag_x2_short_opt_eq_pos() {
    check_complex_output("clap-test subcmd value -f -f -o=some", SCF2OP);
}

#[test]
fn sc_short_flag_x2_long_opt_eq_pos() {
    check_complex_output("clap-test subcmd value -f -f --option=some", SCF2OP);
}
<|endoftext|>


<commit_before>#![feature(macro_rules)]

extern crate rand;
extern crate sdl2;
extern crate sdl2_gfx;

use rand::Rand;
use sdl2::event;
use sdl2::event::Event;
use sdl2::pixels;
use sdl2::keycode::KeyCode;

use sdl2_gfx::primitives::DrawRenderer;
use sdl2_gfx::framerate::FPSManager;

static SCREEN_WIDTH : int = 800;
static SCREEN_HEIGHT : int = 600;

// hadle the annoying Rect i32
macro_rules! rect(
    ($x:expr, $y:expr, $w:expr, $h:expr) => (
        sdl2::rect::Rect::new($x as i32, $y as i32, $w as i32, $h as i32)
    )
)

fn main() {
    match mainloop() {
        Ok(_) => (),
        Err(e) => println!("error while running mainloop: {}", e),
    }
}

fn mainloop() -> Result<(), String> {
    sdl2::init(sdl2::INIT_VIDEO);

    let window = try!(sdl2::video::Window::new(
        "rust-sdl2_gfx: draw line & FPSManager", sdl2::video::WindowPos::PosCentered,
        sdl2::video::WindowPos::PosCentered, SCREEN_WIDTH, SCREEN_HEIGHT,
        sdl2::video::OPENGL));

    let renderer = try!(sdl2::render::Renderer::from_window(
            window, sdl2::render::RenderDriverIndex::Auto, sdl2::render::ACCELERATED));

    try!(renderer.set_draw_color(pixels::Color::RGB(0, 0, 0)));

    try!(renderer.clear());

    renderer.present();

    let mut rng = rand::XorShiftRng::new_unseeded();
    let (mut lastx, mut lasty) = (0, 0);

    let mut fpsm = FPSManager::new();
    // default 30 is not good
    try!(fpsm.set_framerate(100));

    'main : loop {
        'event : loop {
            // this will avoid program to run 100% CPU
            fpsm.delay();

            match event::poll_event() {
                Event::Quit(_) => break 'main,
                Event::KeyDown(_, _, key, _, _, _) => {
                    if key == KeyCode::Escape {
                        break 'main
                    } else if key == KeyCode::Space {
                        for i in range(0u, 400) {
                            try!(renderer.pixel(i as i16, i as i16, 0xFF000FFu32));
                        }
                        renderer.present();

                    }
                }
                Event::MouseButtonDown(_, _, _, _, x, y) => {
                    let color : pixels::Color = Rand::rand(&mut rng);
                    // println!("color => {:}", color);
                    try!(renderer.line(lastx, lasty, x as i16, y as i16, color));
                    lastx = x as i16;
                    lasty = y as i16;
                    println!("mouse btn down at ({},{})", x, y);
                    renderer.present();
                }

                _ => {}
            }
        }
    }
    sdl2::quit();
    Ok(())
}
<commit_msg>Make demo work with newest sdl2 and rust nightly.<commit_after>#![feature(macro_rules)]

extern crate rand;
extern crate sdl2;
extern crate sdl2_gfx;

use rand::Rand;
use sdl2::event;
use sdl2::event::Event;
use sdl2::pixels;
use sdl2::keycode::KeyCode;

use sdl2_gfx::primitives::DrawRenderer;
use sdl2_gfx::framerate::FPSManager;

static SCREEN_WIDTH: i32 = 800;
static SCREEN_HEIGHT: i32 = 600;

// hadle the annoying Rect i32
macro_rules! rect(
    ($x:expr, $y:expr, $w:expr, $h:expr) => (
        sdl2::rect::Rect::new($x as i32, $y as i32, $w as i32, $h as i32)
    )
);

fn main() {

    let context = sdl2::init(sdl2::INIT_VIDEO).unwrap();

    let window = sdl2::video::Window::new(
        "rust-sdl2_gfx: draw line & FPSManager",
        sdl2::video::WindowPos::PosCentered,
        sdl2::video::WindowPos::PosCentered,
        SCREEN_WIDTH,
        SCREEN_HEIGHT,
        sdl2::video::OPENGL).unwrap();

    let renderer = sdl2::render::Renderer::from_window(
        window,
        sdl2::render::RenderDriverIndex::Auto,
        sdl2::render::ACCELERATED).unwrap();

    let mut drawer = renderer.drawer();
    drawer.set_draw_color(pixels::Color::RGB(0, 0, 0));
    drawer.clear();
    drawer.present();

    let mut rng = rand::XorShiftRng::new_unseeded();
    let (mut lastx, mut lasty) = (0, 0);

    let mut fpsm = FPSManager::new();

    fpsm.set_framerate(100); // Default 30 is not good.

    let mut events = context.event_pump();

    'main: loop {

        fpsm.delay(); // This will avoid program to run 100% CPU.

        for event in events.poll_iter() {

            match event {

                Event::Quit {..} => break 'main,

                Event::KeyDown {keycode: key, ..} => {
                    if key == KeyCode::Escape {
                        break 'main
                    } else if key == KeyCode::Space {
                        for i in 0..400 {
                            renderer.pixel(i as i16, i as i16, 0xFF000FFu32);
                        }
                        drawer.present();

                    }
                }

                Event::MouseButtonDown {x: x, y: y, ..} => {
                    let color = pixels::Color::RGB(
                        Rand::rand(&mut rng),
                        Rand::rand(&mut rng),
                        Rand::rand(&mut rng));
                    renderer.line(lastx, lasty, x as i16, y as i16, color);
                    lastx = x as i16;
                    lasty = y as i16;
                    println!("mouse btn down at ({},{})", x, y);
                    drawer.present();
                }

                _ => {}
            }
        }
    }
}
<|endoftext|>


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

//! Base64 binary-to-text encoding
use std::str;

/// Available encoding character sets
pub enum CharacterSet {
    /// The standard character set (uses `+` and `/`)
    Standard,
    /// The URL safe character set (uses `-` and `_`)
    UrlSafe
}

/// Contains configuration parameters for `to_base64`.
pub struct Config {
    /// Character set to use
    priv char_set: CharacterSet,
    /// True to pad output with `=` characters
    priv pad: bool,
    /// `Some(len)` to wrap lines at `len`, `None` to disable line wrapping
    priv line_length: Option<uint>
}

/// Configuration for RFC 4648 standard base64 encoding
pub static STANDARD: Config =
    Config {char_set: Standard, pad: true, line_length: None};

/// Configuration for RFC 4648 base64url encoding
pub static URL_SAFE: Config =
    Config {char_set: UrlSafe, pad: false, line_length: None};

/// Configuration for RFC 2045 MIME base64 encoding
pub static MIME: Config =
    Config {char_set: Standard, pad: true, line_length: Some(76)};

static STANDARD_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                                             "abcdefghijklmnopqrstuvwxyz",
                                             "0123456789+/");

static URLSAFE_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                                            "abcdefghijklmnopqrstuvwxyz",
                                            "0123456789-_");

/// A trait for converting a value to base64 encoding.
pub trait ToBase64 {
    /// Converts the value of `self` to a base64 value following the specified
    /// format configuration, returning the owned string.
    fn to_base64(&self, config: Config) -> ~str;
}

impl<'self> ToBase64 for &'self [u8] {
    /**
     * Turn a vector of `u8` bytes into a base64 string.
     *
     * # Example
     *
     * ```rust
     * extern mod extra;
     * use extra::base64::{ToBase64, STANDARD};
     *
     * fn main () {
     *     let str = [52,32].to_base64(STANDARD);
     *     println!("base 64 output: {}", str);
     * }
     * ```
     */
    fn to_base64(&self, config: Config) -> ~str {
        let bytes = match config.char_set {
            Standard => STANDARD_CHARS,
            UrlSafe => URLSAFE_CHARS
        };

        let mut v: ~[u8] = ~[];
        let mut i = 0;
        let mut cur_length = 0;
        let len = self.len();
        while i < len - (len % 3) {
            match config.line_length {
                Some(line_length) =>
                    if cur_length >= line_length {
                        v.push('\r' as u8);
                        v.push('\n' as u8);
                        cur_length = 0;
                    },
                None => ()
            }

            let n = (self[i] as u32) << 16 |
                    (self[i + 1] as u32) << 8 |
                    (self[i + 2] as u32);

            // This 24-bit number gets separated into four 6-bit numbers.
            v.push(bytes[(n >> 18) & 63]);
            v.push(bytes[(n >> 12) & 63]);
            v.push(bytes[(n >> 6 ) & 63]);
            v.push(bytes[n & 63]);

            cur_length += 4;
            i += 3;
        }

        if len % 3 != 0 {
            match config.line_length {
                Some(line_length) =>
                    if cur_length >= line_length {
                        v.push('\r' as u8);
                        v.push('\n' as u8);
                    },
                None => ()
            }
        }

        // Heh, would be cool if we knew this was exhaustive
        // (the dream of bounded integer types)
        match len % 3 {
            0 => (),
            1 => {
                let n = (self[i] as u32) << 16;
                v.push(bytes[(n >> 18) & 63]);
                v.push(bytes[(n >> 12) & 63]);
                if config.pad {
                    v.push('=' as u8);
                    v.push('=' as u8);
                }
            }
            2 => {
                let n = (self[i] as u32) << 16 |
                    (self[i + 1u] as u32) << 8;
                v.push(bytes[(n >> 18) & 63]);
                v.push(bytes[(n >> 12) & 63]);
                v.push(bytes[(n >> 6 ) & 63]);
                if config.pad {
                    v.push('=' as u8);
                }
            }
            _ => fail!("Algebra is broken, please alert the math police")
        }

        unsafe {
            str::raw::from_utf8_owned(v)
        }
    }
}

/// A trait for converting from base64 encoded values.
pub trait FromBase64 {
    /// Converts the value of `self`, interpreted as base64 encoded data, into
    /// an owned vector of bytes, returning the vector.
    fn from_base64(&self) -> Result<~[u8], ~str>;
}

impl<'self> FromBase64 for &'self str {
    /**
     * Convert any base64 encoded string (literal, `@`, `&`, or `~`)
     * to the byte values it encodes.
     *
     * You can use the `from_utf8` function in `std::str`
     * to turn a `[u8]` into a string with characters corresponding to those
     * values.
     *
     * # Example
     *
     * This converts a string literal to base64 and back.
     *
     * ```rust
     * extern mod extra;
     * use extra::base64::{ToBase64, FromBase64, STANDARD};
     * use std::str;
     *
     * fn main () {
     *     let hello_str = bytes!("Hello, World").to_base64(STANDARD);
     *     println!("base64 output: {}", hello_str);
     *     let res = hello_str.from_base64();
     *     if res.is_ok() {
     *       let optBytes = str::from_utf8_opt(res.unwrap());
     *       if optBytes.is_some() {
     *         println!("decoded from base64: {}", optBytes.unwrap());
     *       }
     *     }
     * }
     * ```
     */
    fn from_base64(&self) -> Result<~[u8], ~str> {
        let mut r = ~[];
        let mut buf: u32 = 0;
        let mut modulus = 0;

        let mut it = self.byte_iter().enumerate();
        for (idx, byte) in it {
            let val = byte as u32;

            match byte as char {
                'A'..'Z' => buf |= val - 0x41,
                'a'..'z' => buf |= val - 0x47,
                '0'..'9' => buf |= val + 0x04,
                '+'|'-' => buf |= 0x3E,
                '/'|'_' => buf |= 0x3F,
                '\r'|'\n' => continue,
                '=' => break,
                _ => return Err(format!("Invalid character '{}' at position {}",
                                     self.char_at(idx), idx))
            }

            buf <<= 6;
            modulus += 1;
            if modulus == 4 {
                modulus = 0;
                r.push((buf >> 22) as u8);
                r.push((buf >> 14) as u8);
                r.push((buf >> 6 ) as u8);
            }
        }

        for (idx, byte) in it {
            if (byte as char) != '=' {
                return Err(format!("Invalid character '{}' at position {}",
                                self.char_at(idx), idx));
            }
        }

        match modulus {
            2 => {
                r.push((buf >> 10) as u8);
            }
            3 => {
                r.push((buf >> 16) as u8);
                r.push((buf >> 8 ) as u8);
            }
            0 => (),
            _ => return Err(~"Invalid Base64 length")
        }

        Ok(r)
    }
}

#[cfg(test)]
mod test {
    use test::BenchHarness;
    use base64::*;

    #[test]
    fn test_to_base64_basic() {
        assert_eq!("".as_bytes().to_base64(STANDARD), ~"");
        assert_eq!("f".as_bytes().to_base64(STANDARD), ~"Zg==");
        assert_eq!("fo".as_bytes().to_base64(STANDARD), ~"Zm8=");
        assert_eq!("foo".as_bytes().to_base64(STANDARD), ~"Zm9v");
        assert_eq!("foob".as_bytes().to_base64(STANDARD), ~"Zm9vYg==");
        assert_eq!("fooba".as_bytes().to_base64(STANDARD), ~"Zm9vYmE=");
        assert_eq!("foobar".as_bytes().to_base64(STANDARD), ~"Zm9vYmFy");
    }

    #[test]
    fn test_to_base64_line_break() {
        assert!(![0u8, 1000].to_base64(Config {line_length: None, ..STANDARD})
                .contains("\r\n"));
        assert_eq!("foobar".as_bytes().to_base64(Config {line_length: Some(4),
                                                         ..STANDARD}),
                   ~"Zm9v\r\nYmFy");
    }

    #[test]
    fn test_to_base64_padding() {
        assert_eq!("f".as_bytes().to_base64(Config {pad: false, ..STANDARD}), ~"Zg");
        assert_eq!("fo".as_bytes().to_base64(Config {pad: false, ..STANDARD}), ~"Zm8");
    }

    #[test]
    fn test_to_base64_url_safe() {
        assert_eq!([251, 255].to_base64(URL_SAFE), ~"-_8");
        assert_eq!([251, 255].to_base64(STANDARD), ~"+/8=");
    }

    #[test]
    fn test_from_base64_basic() {
        assert_eq!("".from_base64().unwrap(), "".as_bytes().to_owned());
        assert_eq!("Zg==".from_base64().unwrap(), "f".as_bytes().to_owned());
        assert_eq!("Zm8=".from_base64().unwrap(), "fo".as_bytes().to_owned());
        assert_eq!("Zm9v".from_base64().unwrap(), "foo".as_bytes().to_owned());
        assert_eq!("Zm9vYg==".from_base64().unwrap(), "foob".as_bytes().to_owned());
        assert_eq!("Zm9vYmE=".from_base64().unwrap(), "fooba".as_bytes().to_owned());
        assert_eq!("Zm9vYmFy".from_base64().unwrap(), "foobar".as_bytes().to_owned());
    }

    #[test]
    fn test_from_base64_newlines() {
        assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap(),
                   "foobar".as_bytes().to_owned());
    }

    #[test]
    fn test_from_base64_urlsafe() {
        assert_eq!("-_8".from_base64().unwrap(), "+/8=".from_base64().unwrap());
    }

    #[test]
    fn test_from_base64_invalid_char() {
        assert!("Zm$=".from_base64().is_err())
        assert!("Zg==$".from_base64().is_err());
    }

    #[test]
    fn test_from_base64_invalid_padding() {
        assert!("Z===".from_base64().is_err());
    }

    #[test]
    fn test_base64_random() {
        use std::rand::{task_rng, random, Rng};
        use std::vec;

        do 1000.times {
            let times = task_rng().gen_range(1u, 100);
            let v = vec::from_fn(times, |_| random::<u8>());
            assert_eq!(v.to_base64(STANDARD).from_base64().unwrap(), v);
        }
    }

    #[bench]
    pub fn bench_to_base64(bh: & mut BenchHarness) {
        let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
                 ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
        do bh.iter {
            s.as_bytes().to_base64(STANDARD);
        }
        bh.bytes = s.len() as u64;
    }

    #[bench]
    pub fn bench_from_base64(bh: & mut BenchHarness) {
        let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
                 ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
        let b = s.as_bytes().to_base64(STANDARD);
        do bh.iter {
            b.from_base64();
        }
        bh.bytes = b.len() as u64;
    }

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

//! Base64 binary-to-text encoding
use std::str;

/// Available encoding character sets
pub enum CharacterSet {
    /// The standard character set (uses `+` and `/`)
    Standard,
    /// The URL safe character set (uses `-` and `_`)
    UrlSafe
}

/// Contains configuration parameters for `to_base64`.
pub struct Config {
    /// Character set to use
    priv char_set: CharacterSet,
    /// True to pad output with `=` characters
    priv pad: bool,
    /// `Some(len)` to wrap lines at `len`, `None` to disable line wrapping
    priv line_length: Option<uint>
}

/// Configuration for RFC 4648 standard base64 encoding
pub static STANDARD: Config =
    Config {char_set: Standard, pad: true, line_length: None};

/// Configuration for RFC 4648 base64url encoding
pub static URL_SAFE: Config =
    Config {char_set: UrlSafe, pad: false, line_length: None};

/// Configuration for RFC 2045 MIME base64 encoding
pub static MIME: Config =
    Config {char_set: Standard, pad: true, line_length: Some(76)};

static STANDARD_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                                             "abcdefghijklmnopqrstuvwxyz",
                                             "0123456789+/");

static URLSAFE_CHARS: &'static[u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                                            "abcdefghijklmnopqrstuvwxyz",
                                            "0123456789-_");

/// A trait for converting a value to base64 encoding.
pub trait ToBase64 {
    /// Converts the value of `self` to a base64 value following the specified
    /// format configuration, returning the owned string.
    fn to_base64(&self, config: Config) -> ~str;
}

impl<'self> ToBase64 for &'self [u8] {
    /**
     * Turn a vector of `u8` bytes into a base64 string.
     *
     * # Example
     *
     * ```rust
     * extern mod extra;
     * use extra::base64::{ToBase64, STANDARD};
     *
     * fn main () {
     *     let str = [52,32].to_base64(STANDARD);
     *     println!("base 64 output: {}", str);
     * }
     * ```
     */
    fn to_base64(&self, config: Config) -> ~str {
        let bytes = match config.char_set {
            Standard => STANDARD_CHARS,
            UrlSafe => URLSAFE_CHARS
        };

        let mut v: ~[u8] = ~[];
        let mut i = 0;
        let mut cur_length = 0;
        let len = self.len();
        while i < len - (len % 3) {
            match config.line_length {
                Some(line_length) =>
                    if cur_length >= line_length {
                        v.push('\r' as u8);
                        v.push('\n' as u8);
                        cur_length = 0;
                    },
                None => ()
            }

            let n = (self[i] as u32) << 16 |
                    (self[i + 1] as u32) << 8 |
                    (self[i + 2] as u32);

            // This 24-bit number gets separated into four 6-bit numbers.
            v.push(bytes[(n >> 18) & 63]);
            v.push(bytes[(n >> 12) & 63]);
            v.push(bytes[(n >> 6 ) & 63]);
            v.push(bytes[n & 63]);

            cur_length += 4;
            i += 3;
        }

        if len % 3 != 0 {
            match config.line_length {
                Some(line_length) =>
                    if cur_length >= line_length {
                        v.push('\r' as u8);
                        v.push('\n' as u8);
                    },
                None => ()
            }
        }

        // Heh, would be cool if we knew this was exhaustive
        // (the dream of bounded integer types)
        match len % 3 {
            0 => (),
            1 => {
                let n = (self[i] as u32) << 16;
                v.push(bytes[(n >> 18) & 63]);
                v.push(bytes[(n >> 12) & 63]);
                if config.pad {
                    v.push('=' as u8);
                    v.push('=' as u8);
                }
            }
            2 => {
                let n = (self[i] as u32) << 16 |
                    (self[i + 1u] as u32) << 8;
                v.push(bytes[(n >> 18) & 63]);
                v.push(bytes[(n >> 12) & 63]);
                v.push(bytes[(n >> 6 ) & 63]);
                if config.pad {
                    v.push('=' as u8);
                }
            }
            _ => fail!("Algebra is broken, please alert the math police")
        }

        unsafe {
            str::raw::from_utf8_owned(v)
        }
    }
}

/// A trait for converting from base64 encoded values.
pub trait FromBase64 {
    /// Converts the value of `self`, interpreted as base64 encoded data, into
    /// an owned vector of bytes, returning the vector.
    fn from_base64(&self) -> Result<~[u8], ~str>;
}

impl<'self> FromBase64 for &'self str {
    /**
     * Convert any base64 encoded string (literal, `@`, `&`, or `~`)
     * to the byte values it encodes.
     *
     * You can use the `from_utf8` function in `std::str`
     * to turn a `[u8]` into a string with characters corresponding to those
     * values.
     *
     * # Example
     *
     * This converts a string literal to base64 and back.
     *
     * ```rust
     * extern mod extra;
     * use extra::base64::{ToBase64, FromBase64, STANDARD};
     * use std::str;
     *
     * fn main () {
     *     let hello_str = bytes!("Hello, World").to_base64(STANDARD);
     *     println!("base64 output: {}", hello_str);
     *     let res = hello_str.from_base64();
     *     if res.is_ok() {
     *       let optBytes = str::from_utf8_opt(res.unwrap());
     *       if optBytes.is_some() {
     *         println!("decoded from base64: {}", optBytes.unwrap());
     *       }
     *     }
     * }
     * ```
     */
    fn from_base64(&self) -> Result<~[u8], ~str> {
        let mut r = ~[];
        let mut buf: u32 = 0;
        let mut modulus = 0;

        let mut it = self.byte_iter().enumerate();
        for (idx, byte) in it {
            let val = byte as u32;

            match byte as char {
                'A'..'Z' => buf |= val - 0x41,
                'a'..'z' => buf |= val - 0x47,
                '0'..'9' => buf |= val + 0x04,
                '+'|'-' => buf |= 0x3E,
                '/'|'_' => buf |= 0x3F,
                '\r'|'\n' => continue,
                '=' => break,
                _ => return Err(format!("Invalid character '{}' at position {}",
                                     self.char_at(idx), idx))
            }

            buf <<= 6;
            modulus += 1;
            if modulus == 4 {
                modulus = 0;
                r.push((buf >> 22) as u8);
                r.push((buf >> 14) as u8);
                r.push((buf >> 6 ) as u8);
            }
        }

        for (idx, byte) in it {
            if (byte as char) != '=' {
                return Err(format!("Invalid character '{}' at position {}",
                                self.char_at(idx), idx));
            }
        }

        match modulus {
            2 => {
                r.push((buf >> 10) as u8);
            }
            3 => {
                r.push((buf >> 16) as u8);
                r.push((buf >> 8 ) as u8);
            }
            0 => (),
            _ => return Err(~"Invalid Base64 length")
        }

        Ok(r)
    }
}

#[cfg(test)]
mod test {
    use test::BenchHarness;
    use base64::*;

    #[test]
    fn test_to_base64_basic() {
        assert_eq!("".as_bytes().to_base64(STANDARD), ~"");
        assert_eq!("f".as_bytes().to_base64(STANDARD), ~"Zg==");
        assert_eq!("fo".as_bytes().to_base64(STANDARD), ~"Zm8=");
        assert_eq!("foo".as_bytes().to_base64(STANDARD), ~"Zm9v");
        assert_eq!("foob".as_bytes().to_base64(STANDARD), ~"Zm9vYg==");
        assert_eq!("fooba".as_bytes().to_base64(STANDARD), ~"Zm9vYmE=");
        assert_eq!("foobar".as_bytes().to_base64(STANDARD), ~"Zm9vYmFy");
    }

    #[test]
    fn test_to_base64_line_break() {
        assert!(![0u8, ..1000].to_base64(Config {line_length: None, ..STANDARD})
                .contains("\r\n"));
        assert_eq!("foobar".as_bytes().to_base64(Config {line_length: Some(4),
                                                         ..STANDARD}),
                   ~"Zm9v\r\nYmFy");
    }

    #[test]
    fn test_to_base64_padding() {
        assert_eq!("f".as_bytes().to_base64(Config {pad: false, ..STANDARD}), ~"Zg");
        assert_eq!("fo".as_bytes().to_base64(Config {pad: false, ..STANDARD}), ~"Zm8");
    }

    #[test]
    fn test_to_base64_url_safe() {
        assert_eq!([251, 255].to_base64(URL_SAFE), ~"-_8");
        assert_eq!([251, 255].to_base64(STANDARD), ~"+/8=");
    }

    #[test]
    fn test_from_base64_basic() {
        assert_eq!("".from_base64().unwrap(), "".as_bytes().to_owned());
        assert_eq!("Zg==".from_base64().unwrap(), "f".as_bytes().to_owned());
        assert_eq!("Zm8=".from_base64().unwrap(), "fo".as_bytes().to_owned());
        assert_eq!("Zm9v".from_base64().unwrap(), "foo".as_bytes().to_owned());
        assert_eq!("Zm9vYg==".from_base64().unwrap(), "foob".as_bytes().to_owned());
        assert_eq!("Zm9vYmE=".from_base64().unwrap(), "fooba".as_bytes().to_owned());
        assert_eq!("Zm9vYmFy".from_base64().unwrap(), "foobar".as_bytes().to_owned());
    }

    #[test]
    fn test_from_base64_newlines() {
        assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap(),
                   "foobar".as_bytes().to_owned());
    }

    #[test]
    fn test_from_base64_urlsafe() {
        assert_eq!("-_8".from_base64().unwrap(), "+/8=".from_base64().unwrap());
    }

    #[test]
    fn test_from_base64_invalid_char() {
        assert!("Zm$=".from_base64().is_err())
        assert!("Zg==$".from_base64().is_err());
    }

    #[test]
    fn test_from_base64_invalid_padding() {
        assert!("Z===".from_base64().is_err());
    }

    #[test]
    fn test_base64_random() {
        use std::rand::{task_rng, random, Rng};
        use std::vec;

        do 1000.times {
            let times = task_rng().gen_range(1u, 100);
            let v = vec::from_fn(times, |_| random::<u8>());
            assert_eq!(v.to_base64(STANDARD).from_base64().unwrap(), v);
        }
    }

    #[bench]
    pub fn bench_to_base64(bh: & mut BenchHarness) {
        let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
                 ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
        do bh.iter {
            s.as_bytes().to_base64(STANDARD);
        }
        bh.bytes = s.len() as u64;
    }

    #[bench]
    pub fn bench_from_base64(bh: & mut BenchHarness) {
        let s = "イロハニホヘト チリヌルヲ ワカヨタレソ ツネナラム \
                 ウヰノオクヤマ ケフコエテ アサキユメミシ ヱヒモセスン";
        let b = s.as_bytes().to_base64(STANDARD);
        do bh.iter {
            b.from_base64();
        }
        bh.bytes = b.len() as u64;
    }

}
<|endoftext|>


<commit_before>//! Messages to and from the server.
#![stable]
use std::borrow::ToOwned;
use std::str::FromStr;

/// IRC Message data.
#[stable]
#[derive(Clone, PartialEq, Debug)]
pub struct Message {
    /// The message prefix (or source) as defined by [RFC 2812](http://tools.ietf.org/html/rfc2812).
    #[stable]
    pub prefix: Option<String>,
    /// The IRC command as defined by [RFC 2812](http://tools.ietf.org/html/rfc2812).
    #[stable]
    pub command: String,
    /// The command arguments.
    #[stable]
    pub args: Vec<String>,
    /// The message suffix as defined by [RFC 2812](http://tools.ietf.org/html/rfc2812).
    /// This is the only part of the message that is allowed to contain spaces.
    #[stable]
    pub suffix: Option<String>,
}

#[stable]
impl Message {
    /// Creates a new Message.
    #[stable]
    pub fn new(prefix: Option<&str>, command: &str, args: Option<Vec<&str>>, suffix: Option<&str>)
        -> Message {
        Message {
            prefix: prefix.map(|s| s.to_owned()),
            command: command.to_owned(),
            args: args.map_or(Vec::new(), |v| v.iter().map(|&s| s.to_owned()).collect()),
            suffix: suffix.map(|s| s.to_owned()),
        }
    }

    /// Gets the nickname of the message source, if it exists.
    #[stable]
    pub fn get_source_nickname(&self) -> Option<&str> {
        self.prefix.as_ref().and_then(|s| s.find('!').map(|i| &s[..i]))
    }

    /// Converts a Message into a String according to the IRC protocol.
    #[stable]
    pub fn into_string(&self) -> String {
        let mut ret = String::new();
        if let Some(ref prefix) = self.prefix {
            ret.push(':');
            ret.push_str(&prefix);
            ret.push(' ');
        }
        ret.push_str(&self.command);
        for arg in self.args.iter() {
            ret.push(' ');
            ret.push_str(&arg);
        }
        if let Some(ref suffix) = self.suffix {
            ret.push_str(" :");
            ret.push_str(&suffix);
        }
        ret.push_str("\r\n");
        ret
    }
}

impl ToMessage for Message {
    fn to_message(&self) -> Message {
        self.clone()
    }
}

impl FromStr for Message {
    type Err = &'static str;
    fn from_str(s: &str) -> Result<Message, &'static str> {
        let mut state = s.clone();
        if s.len() == 0 { return Err("Cannot parse an empty string as a message.") }
        let prefix = if state.starts_with(":") {
            let prefix = state.find(' ').map(|i| &state[1..i]);
            state = state.find(' ').map_or("", |i| &state[i+1..]);
            prefix
        } else {
            None
        };
        let suffix = if state.contains(":") {
            let suffix = state.find(':').map(|i| &state[i+1..state.len()-2]);
            state = state.find(':').map_or("", |i| &state[..i]);
            suffix
        } else {
            None
        };
        let command = match state.find(' ').map(|i| &state[..i]) {
            Some(cmd) => {
                state = state.find(' ').map_or("", |i| &state[i+1..]);
                cmd
            }
            _ => return Err("Cannot parse a message without a command.")
        };
        if suffix.is_none() { state = &state[..state.len() - 2] }
        let args: Vec<_> = state.splitn(14, ' ').filter(|s| s.len() != 0).collect();
        Ok(Message::new(prefix, command, if args.len() > 0 { Some(args) } else { None }, suffix))
    }
}

/// A trait representing the ability to be converted into a Message.
#[stable]
pub trait ToMessage {
    /// Converts this to a Message.
    fn to_message(&self) -> Message;
}

impl<'a> ToMessage for &'a str {
    fn to_message(&self) -> Message {
        self.parse().unwrap()
    }
}

#[cfg(test)]
mod test {
    use super::{Message, ToMessage};

    #[test]
    fn new() {
        let message = Message {
            prefix: None,
            command: format!("PRIVMSG"),
            args: vec![format!("test")],
            suffix: Some(format!("Testing!")),
        };
        assert_eq!(Message::new(None, "PRIVMSG", Some(vec!["test"]), Some("Testing!")), message);
    }

    #[test]
    fn get_source_nickname() {
        assert_eq!(Message::new(None, "PING", None, None).get_source_nickname(), None);
        assert_eq!(Message::new(
            Some("irc.test.net"), "PING", None, None
        ).get_source_nickname(), None);
        assert_eq!(Message::new(
            Some("test!test@test"), "PING", None, None
        ).get_source_nickname(), Some("test"));
    }

    #[test]
    fn into_string() {
        let message = Message {
            prefix: None,
            command: format!("PRIVMSG"),
            args: vec![format!("test")],
            suffix: Some(format!("Testing!")),
        };
        assert_eq!(&message.into_string()[..], "PRIVMSG test :Testing!\r\n");
        let message = Message {
            prefix: Some(format!("test!test@test")),
            command: format!("PRIVMSG"),
            args: vec![format!("test")],
            suffix: Some(format!("Still testing!")),
        };
        assert_eq!(&message.into_string()[..], ":test!test@test PRIVMSG test :Still testing!\r\n");
    }

    #[test]
    fn from_string() {
        let message = Message {
            prefix: None,
            command: format!("PRIVMSG"),
            args: vec![format!("test")],
            suffix: Some(format!("Testing!")),
        };
        assert_eq!("PRIVMSG test :Testing!\r\n".parse(), Ok(message));
        let message = Message {
            prefix: Some(format!("test!test@test")),
            command: format!("PRIVMSG"),
            args: vec![format!("test")],
            suffix: Some(format!("Still testing!")),
        };
        assert_eq!(":test!test@test PRIVMSG test :Still testing!\r\n".parse(), Ok(message));
    }

    #[test]
    fn to_message() {
        let message = Message {
            prefix: None,
            command: format!("PRIVMSG"),
            args: vec![format!("test")],
            suffix: Some(format!("Testing!")),
        };
        assert_eq!("PRIVMSG test :Testing!\r\n".to_message(), message);
        let message = Message {
            prefix: Some(format!("test!test@test")),
            command: format!("PRIVMSG"),
            args: vec![format!("test")],
            suffix: Some(format!("Still testing!")),
        };
        assert_eq!(":test!test@test PRIVMSG test :Still testing!\r\n".to_message(), message);
    }

    #[test]
    #[should_fail]
    fn to_message_invalid_format() {
        ":invalid :message".to_message();
    }
}
<commit_msg>Updated parsing to support colons within arguments.<commit_after>//! Messages to and from the server.
#![stable]
use std::borrow::ToOwned;
use std::str::FromStr;

/// IRC Message data.
#[stable]
#[derive(Clone, PartialEq, Debug)]
pub struct Message {
    /// The message prefix (or source) as defined by [RFC 2812](http://tools.ietf.org/html/rfc2812).
    #[stable]
    pub prefix: Option<String>,
    /// The IRC command as defined by [RFC 2812](http://tools.ietf.org/html/rfc2812).
    #[stable]
    pub command: String,
    /// The command arguments.
    #[stable]
    pub args: Vec<String>,
    /// The message suffix as defined by [RFC 2812](http://tools.ietf.org/html/rfc2812).
    /// This is the only part of the message that is allowed to contain spaces.
    #[stable]
    pub suffix: Option<String>,
}

#[stable]
impl Message {
    /// Creates a new Message.
    #[stable]
    pub fn new(prefix: Option<&str>, command: &str, args: Option<Vec<&str>>, suffix: Option<&str>)
        -> Message {
        Message {
            prefix: prefix.map(|s| s.to_owned()),
            command: command.to_owned(),
            args: args.map_or(Vec::new(), |v| v.iter().map(|&s| s.to_owned()).collect()),
            suffix: suffix.map(|s| s.to_owned()),
        }
    }

    /// Gets the nickname of the message source, if it exists.
    #[stable]
    pub fn get_source_nickname(&self) -> Option<&str> {
        self.prefix.as_ref().and_then(|s| s.find('!').map(|i| &s[..i]))
    }

    /// Converts a Message into a String according to the IRC protocol.
    #[stable]
    pub fn into_string(&self) -> String {
        let mut ret = String::new();
        if let Some(ref prefix) = self.prefix {
            ret.push(':');
            ret.push_str(&prefix);
            ret.push(' ');
        }
        ret.push_str(&self.command);
        for arg in self.args.iter() {
            ret.push(' ');
            ret.push_str(&arg);
        }
        if let Some(ref suffix) = self.suffix {
            ret.push_str(" :");
            ret.push_str(&suffix);
        }
        ret.push_str("\r\n");
        ret
    }
}

impl ToMessage for Message {
    fn to_message(&self) -> Message {
        self.clone()
    }
}

impl FromStr for Message {
    type Err = &'static str;
    fn from_str(s: &str) -> Result<Message, &'static str> {
        let mut state = s.clone();
        if s.len() == 0 { return Err("Cannot parse an empty string as a message.") }
        let prefix = if state.starts_with(":") {
            let prefix = state.find(' ').map(|i| &state[1..i]);
            state = state.find(' ').map_or("", |i| &state[i+1..]);
            prefix
        } else {
            None
        };
        let suffix = if state.contains(" :") {
            let suffix = state.find(" :").map(|i| &state[i+2..state.len()-2]);
            state = state.find(" :").map_or("", |i| &state[..i+1]);
            suffix
        } else {
            None
        };
        let command = match state.find(' ').map(|i| &state[..i]) {
            Some(cmd) => {
                state = state.find(' ').map_or("", |i| &state[i+1..]);
                cmd
            }
            _ => return Err("Cannot parse a message without a command.")
        };
        if suffix.is_none() { state = &state[..state.len() - 2] }
        let args: Vec<_> = state.splitn(14, ' ').filter(|s| s.len() != 0).collect();
        Ok(Message::new(prefix, command, if args.len() > 0 { Some(args) } else { None }, suffix))
    }
}

/// A trait representing the ability to be converted into a Message.
#[stable]
pub trait ToMessage {
    /// Converts this to a Message.
    fn to_message(&self) -> Message;
}

impl<'a> ToMessage for &'a str {
    fn to_message(&self) -> Message {
        self.parse().unwrap()
    }
}

#[cfg(test)]
mod test {
    use super::{Message, ToMessage};

    #[test]
    fn new() {
        let message = Message {
            prefix: None,
            command: format!("PRIVMSG"),
            args: vec![format!("test")],
            suffix: Some(format!("Testing!")),
        };
        assert_eq!(Message::new(None, "PRIVMSG", Some(vec!["test"]), Some("Testing!")), message);
    }

    #[test]
    fn get_source_nickname() {
        assert_eq!(Message::new(None, "PING", None, None).get_source_nickname(), None);
        assert_eq!(Message::new(
            Some("irc.test.net"), "PING", None, None
        ).get_source_nickname(), None);
        assert_eq!(Message::new(
            Some("test!test@test"), "PING", None, None
        ).get_source_nickname(), Some("test"));
    }

    #[test]
    fn into_string() {
        let message = Message {
            prefix: None,
            command: format!("PRIVMSG"),
            args: vec![format!("test")],
            suffix: Some(format!("Testing!")),
        };
        assert_eq!(&message.into_string()[..], "PRIVMSG test :Testing!\r\n");
        let message = Message {
            prefix: Some(format!("test!test@test")),
            command: format!("PRIVMSG"),
            args: vec![format!("test")],
            suffix: Some(format!("Still testing!")),
        };
        assert_eq!(&message.into_string()[..], ":test!test@test PRIVMSG test :Still testing!\r\n");
    }

    #[test]
    fn from_string() {
        let message = Message {
            prefix: None,
            command: format!("PRIVMSG"),
            args: vec![format!("test")],
            suffix: Some(format!("Testing!")),
        };
        assert_eq!("PRIVMSG test :Testing!\r\n".parse(), Ok(message));
        let message = Message {
            prefix: Some(format!("test!test@test")),
            command: format!("PRIVMSG"),
            args: vec![format!("test")],
            suffix: Some(format!("Still testing!")),
        };
        assert_eq!(":test!test@test PRIVMSG test :Still testing!\r\n".parse(), Ok(message));
    }

    #[test]
    fn to_message() {
        let message = Message {
            prefix: None,
            command: format!("PRIVMSG"),
            args: vec![format!("test")],
            suffix: Some(format!("Testing!")),
        };
        assert_eq!("PRIVMSG test :Testing!\r\n".to_message(), message);
        let message = Message {
            prefix: Some(format!("test!test@test")),
            command: format!("PRIVMSG"),
            args: vec![format!("test")],
            suffix: Some(format!("Still testing!")),
        };
        assert_eq!(":test!test@test PRIVMSG test :Still testing!\r\n".to_message(), message);
    }

    #[test]
    fn to_message_with_colon_in_arg() {
        // Apparently, UnrealIRCd (and perhaps some others) send some messages that include
        // colons within individual parameters. So, let's make sure it parses correctly.
        let message = Message {
            prefix: Some(format!("test!test@test")),
            command: format!("COMMAND"),
            args: vec![format!("ARG:test")],
            suffix: Some(format!("Still testing!")),
        };
        assert_eq!(":test!test@test COMMAND ARG:test :Still testing!\r\n".to_message(), message);
    }

    #[test]
    #[should_fail]
    fn to_message_invalid_format() {
        ":invalid :message".to_message();
    }
}
<|endoftext|>


<commit_before>//! Define semi-implicit schemes

use ndarray::*;
use ndarray_linalg::*;

use super::traits::*;
use super::diag::{Diagonal, diagonal};

pub struct DiagRK4<NLin, Lin>
    where Lin: TimeStep
{
    nlin: NLin,
    lin: Lin,
    dt: Lin::Time,
}

pub fn diag_rk4<A, D, EOM>(eom: EOM, dt: A::Real) -> DiagRK4<EOM, Diagonal<A, D>>
    where A: Scalar,
          D: Dimension,
          EOM: StiffDiagonal<Scalar = A, Dim = D>
{
    let diag = diagonal(&eom, dt / into_scalar(2.0));
    DiagRK4 {
        nlin: eom,
        lin: diag,
        dt: dt,
    }
}

impl<NLin, Lin> TimeStep for DiagRK4<NLin, Lin>
    where Lin: TimeStep
{
    type Time = Lin::Time;

    fn get_dt(&self) -> Self::Time {
        self.dt
    }

    fn set_dt(&mut self, dt: Self::Time) {
        self.lin.set_dt(dt / into_scalar(2.0));
    }
}

impl<D, NLin, Lin> ModelSpec for DiagRK4<NLin, Lin>
    where D: Dimension,
          NLin: ModelSpec<Dim = D>,
          Lin: ModelSpec<Dim = D> + TimeStep
{
    type Dim = D;

    fn model_size(&self) -> <Self::Dim as Dimension>::Pattern {
        self.nlin.model_size() // TODO check
    }
}

impl<NLin, Lin> BufferSpec for DiagRK4<NLin, Lin>
    where Lin: BufferSpec + TimeStep
{
    type Buffer = Lin::Buffer;

    fn new_buffer(&self) -> Self::Buffer {
        self.lin.new_buffer()
    }
}

impl<A, D, NLin, Lin> TimeEvolution for DiagRK4<NLin, Lin>
    where A: Scalar,
          D: Dimension,
          NLin: SemiImplicit<Scalar = A, Dim = D>,
          Lin: TimeEvolution<Scalar = A, Dim = D> + TimeStep<Time = A::Real>
{
    type Scalar = A;

    fn iterate<'a, S>(&self,
                      x: &'a mut ArrayBase<S, Self::Dim>,
                      mut buf: &mut Self::Buffer)
                      -> &'a mut ArrayBase<S, Self::Dim>
        where S: DataMut<Elem = A>
    {
        // constants
        let dt = self.dt;
        let dt_2 = self.dt / into_scalar(2.0);
        let dt_3 = self.dt / into_scalar(3.0);
        let dt_6 = self.dt / into_scalar(6.0);
        // operators
        let l = &self.lin;
        let f = &self.nlin;
        // calc
        let mut x_ = x.to_owned();
        let mut lx = x.to_owned();
        l.iterate(&mut lx, &mut buf);
        let mut k1 = f.nlin(x);
        let k1_ = k1.to_owned();
        Zip::from(&mut *k1)
            .and(&x_)
            .apply(|k1, &x_| { *k1 = x_ + k1.mul_real(dt_2); });
        let mut k2 = f.nlin(l.iterate(k1, &mut buf));
        let k2_ = k2.to_owned();
        Zip::from(&mut *k2)
            .and(&lx)
            .apply(|k2, &lx| { *k2 = lx + k2.mul_real(dt_2); });
        let mut k3 = f.nlin(k2);
        let k3_ = k3.to_owned();
        Zip::from(&mut *k3)
            .and(&lx)
            .apply(|k3, &lx| { *k3 = lx + k3.mul_real(dt); });
        let mut k4 = f.nlin(l.iterate(k3, &mut buf));
        azip!(mut x_, k1_ in { *x_ = *x_ + k1_.mul_real(dt_6) });
        l.iterate(&mut x_, &mut buf);
        azip!(mut x_, k2_, k3_ in { *x_ = *x_ + (k2_ + k3_).mul_real(dt_3) });
        l.iterate(&mut x_, &mut buf);
        Zip::from(&mut *k4)
            .and(&x_)
            .apply(|k4, &x_| { *k4 = x_ + k4.mul_real(dt_6); });
        k4
    }
}
<commit_msg>Support buffer for DiagRK4<commit_after>//! Define semi-implicit schemes

use ndarray::*;
use ndarray_linalg::*;

use super::traits::*;
use super::diag::{Diagonal, diagonal};

pub struct DiagRK4<NLin, Lin>
    where Lin: TimeStep
{
    nlin: NLin,
    lin: Lin,
    dt: Lin::Time,
}

pub fn diag_rk4<A, D, EOM>(eom: EOM, dt: A::Real) -> DiagRK4<EOM, Diagonal<A, D>>
    where A: Scalar,
          D: Dimension,
          EOM: StiffDiagonal<Scalar = A, Dim = D>
{
    let diag = diagonal(&eom, dt / into_scalar(2.0));
    DiagRK4 {
        nlin: eom,
        lin: diag,
        dt: dt,
    }
}

impl<NLin, Lin> TimeStep for DiagRK4<NLin, Lin>
    where Lin: TimeStep
{
    type Time = Lin::Time;

    fn get_dt(&self) -> Self::Time {
        self.dt
    }

    fn set_dt(&mut self, dt: Self::Time) {
        self.lin.set_dt(dt / into_scalar(2.0));
    }
}

impl<D, NLin, Lin> ModelSpec for DiagRK4<NLin, Lin>
    where D: Dimension,
          NLin: ModelSpec<Dim = D>,
          Lin: ModelSpec<Dim = D> + TimeStep
{
    type Dim = D;

    fn model_size(&self) -> <Self::Dim as Dimension>::Pattern {
        self.nlin.model_size() // TODO check
    }
}

pub struct DiagRK4Buffer<NLinBuf, LinBuf, Arr> {
    nlin: NLinBuf,
    lin: LinBuf,
    x: Arr,
    lx: Arr,
    k1: Arr,
    k2: Arr,
    k3: Arr,
}

impl<A, D, NLin, Lin> BufferSpec for DiagRK4<NLin, Lin>
    where A: Scalar,
          D: Dimension,
          NLin: SemiImplicitBuf<Scalar = A, Dim = D>,
          Lin: TimeEvolution<Scalar = A, Dim = D> + TimeStep
{
    type Buffer = DiagRK4Buffer<NLin::Buffer, Lin::Buffer, Array<A, D>>;

    fn new_buffer(&self) -> Self::Buffer {
        DiagRK4Buffer {
            nlin: self.nlin.new_buffer(),
            lin: self.lin.new_buffer(),
            x: Array::zeros(self.lin.model_size()),
            lx: Array::zeros(self.lin.model_size()),
            k1: Array::zeros(self.lin.model_size()),
            k2: Array::zeros(self.lin.model_size()),
            k3: Array::zeros(self.lin.model_size()),
        }
    }
}

impl<A, D, NLin, Lin> TimeEvolution for DiagRK4<NLin, Lin>
    where A: Scalar,
          D: Dimension,
          NLin: SemiImplicitBuf<Scalar = A, Dim = D>,
          Lin: TimeEvolution<Scalar = A, Dim = D> + TimeStep<Time = A::Real>
{
    type Scalar = A;

    fn iterate<'a, S>(&self,
                      x: &'a mut ArrayBase<S, Self::Dim>,
                      mut buf: &mut Self::Buffer)
                      -> &'a mut ArrayBase<S, Self::Dim>
        where S: DataMut<Elem = A>
    {
        // constants
        let dt = self.dt;
        let dt_2 = self.dt / into_scalar(2.0);
        let dt_3 = self.dt / into_scalar(3.0);
        let dt_6 = self.dt / into_scalar(6.0);
        // operators
        let l = &self.lin;
        let f = &self.nlin;
        // calc
        buf.x.zip_mut_with(x, |buf, x| *buf = *x);
        buf.lx.zip_mut_with(x, |buf, lx| *buf = *lx);
        l.iterate(&mut buf.lx, &mut buf.lin);
        let mut k1 = f.nlin(x, &mut buf.nlin);
        buf.k1.zip_mut_with(k1, |buf, k1| *buf = *k1);
        Zip::from(&mut *k1)
            .and(&buf.x)
            .apply(|k1, &x_| { *k1 = x_ + k1.mul_real(dt_2); });
        let mut k2 = f.nlin(l.iterate(k1, &mut buf.lin), &mut buf.nlin);
        buf.k2.zip_mut_with(k2, |buf, k| *buf = *k);
        Zip::from(&mut *k2)
            .and(&buf.lx)
            .apply(|k2, &lx| { *k2 = lx + k2.mul_real(dt_2); });
        let mut k3 = f.nlin(k2, &mut buf.nlin);
        buf.k3.zip_mut_with(k3, |buf, k| *buf = *k);
        Zip::from(&mut *k3)
            .and(&buf.lx)
            .apply(|k3, &lx| { *k3 = lx + k3.mul_real(dt); });
        let mut k4 = f.nlin(l.iterate(k3, &mut buf.lin), &mut buf.nlin);
        Zip::from(&mut buf.x)
            .and(&buf.k1)
            .apply(|x_, k1_| *x_ = *x_ + k1_.mul_real(dt_6));
        l.iterate(&mut buf.x, &mut buf.lin);
        Zip::from(&mut buf.x)
            .and(&buf.k2)
            .and(&buf.k3)
            .apply(|x_, &k2_, &k3_| *x_ = *x_ + (k2_ + k3_).mul_real(dt_3));
        l.iterate(&mut buf.x, &mut buf.lin);
        Zip::from(&mut *k4)
            .and(&buf.x)
            .apply(|k4, &x_| { *k4 = x_ + k4.mul_real(dt_6); });
        k4
    }
}
<|endoftext|>


<commit_before>use std::fmt;
use std::str;
use serde::de::{Deserialize, Deserializer, EnumAccess, Error, Unexpected, VariantAccess, Visitor};
use serde::ser::{Serialize, Serializer};
use crate::{IpNetwork, Ipv4Network, Ipv6Network};

impl Serialize for IpNetwork {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        if serializer.is_human_readable() {
            serializer.serialize_str(&self.to_string())
        } else {
            match *self {
                IpNetwork::V4(ref a) => {
                    serializer.serialize_newtype_variant("IpNetwork", 0, "V4", a)
                }
                IpNetwork::V6(ref a) => {
                    serializer.serialize_newtype_variant("IpNetwork", 1, "V6", a)
                }
            }
        }
    }
}

impl<'de> Deserialize<'de> for IpNetwork {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        if deserializer.is_human_readable() {
            struct IpNetworkVisitor;

            impl<'de> Visitor<'de> for IpNetworkVisitor {
                type Value = IpNetwork;

                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                    formatter.write_str("IP network")
                }

                fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
                where
                    E: Error,
                {
                    s.parse().map_err(serde::de::Error::custom)
                }
            }

            deserializer.deserialize_str(IpNetworkVisitor)
        } else {
            enum IpNetworkKind {
                V4,
                V6,
            }

            static VARIANTS: &[&str] = &["V4", "V6"];

            impl<'de> Deserialize<'de> for IpNetworkKind {
                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
                where
                    D: Deserializer<'de>,
                {
                    struct KindVisitor;
                    impl<'de> Visitor<'de> for KindVisitor {
                        type Value = IpNetworkKind;
                        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                            formatter.write_str("`V4` or `V6`")
                        }
                        fn visit_u32<E: Error>(self, value: u32) -> Result<Self::Value, E> {
                            match value {
                                0 => Ok(IpNetworkKind::V4),
                                1 => Ok(IpNetworkKind::V6),
                                _ => Err(Error::invalid_value(
                                    Unexpected::Unsigned(value as u64),
                                    &self,
                                )),
                            }
                        }
                        fn visit_str<E: Error>(self, value: &str) -> Result<Self::Value, E> {
                            match value {
                                "V4" => Ok(IpNetworkKind::V4),
                                "V6" => Ok(IpNetworkKind::V6),
                                _ => Err(Error::unknown_variant(value, VARIANTS)),
                            }
                        }
                        fn visit_bytes<E: Error>(self, value: &[u8]) -> Result<Self::Value, E> {
                            match value {
                                b"V4" => Ok(IpNetworkKind::V4),
                                b"V6" => Ok(IpNetworkKind::V6),
                                _ => match str::from_utf8(value) {
                                    Ok(value) => Err(Error::unknown_variant(value, VARIANTS)),
                                    Err(_) => {
                                        Err(Error::invalid_value(Unexpected::Bytes(value), &self))
                                    }
                                },
                            }
                        }
                    }
                    deserializer.deserialize_identifier(KindVisitor)
                }
            }

            struct EnumVisitor;

            impl<'de> Visitor<'de> for EnumVisitor {
                type Value = IpNetwork;

                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                    formatter.write_str("IP network")
                }

                fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
                where
                    A: EnumAccess<'de>,
                {
                    match data.variant()? {
                        (IpNetworkKind::V4, v) => v.newtype_variant().map(IpNetwork::V4),
                        (IpNetworkKind::V6, v) => v.newtype_variant().map(IpNetwork::V6),
                    }
                }
            }

            deserializer.deserialize_enum("IpNetwork", VARIANTS, EnumVisitor)
        }
    }
}

macro_rules! ser_de_impl {
    ($expecting:tt $ty:ty) => {
        impl Serialize for $ty {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                if serializer.is_human_readable() {
                    serializer.serialize_str(&self.to_string())
                } else {
                    (self.network_address(), self.netmask()).serialize(serializer)
                }
            }
        }

        impl<'de> Deserialize<'de> for $ty {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: Deserializer<'de>,
            {
                if deserializer.is_human_readable() {
                    struct IpNetworkVisitor;

                    impl<'de> Visitor<'de> for IpNetworkVisitor {
                        type Value = $ty;

                        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                            formatter.write_str($expecting)
                        }

                        fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
                        where
                            E: Error,
                        {
                            s.parse().map_err(serde::de::Error::custom)
                        }
                    }

                    deserializer.deserialize_str(IpNetworkVisitor)
                } else {
                    let (network_address, netmask) = <(_, u8)>::deserialize(deserializer)?;
                    Self::new(network_address, netmask).map_err(serde::de::Error::custom)
                }
            }
        }
    };
}

ser_de_impl!("IPv4 network" Ipv4Network);
ser_de_impl!("IPv6 network" Ipv6Network);

#[cfg(test)]
mod tests {
    use crate::{IpNetwork, Ipv4Network, Ipv6Network};
    use serde_test::{assert_tokens, Configure, Token};
    use std::net::{Ipv4Addr, Ipv6Addr};

    #[test]
    fn ip_network_serialize_readable() {
        let ip_network = IpNetwork::new(Ipv4Addr::new(1, 2, 3, 4), 32).unwrap();

        assert_tokens(&ip_network.readable(), &[Token::BorrowedStr("1.2.3.4/32")]);
    }

    #[test]
    fn ip_network_serialize_compact() {
        let ip_network = IpNetwork::new(Ipv4Addr::new(1, 2, 3, 4), 32).unwrap();

        assert_tokens(
            &ip_network.compact(),
            &[
                Token::NewtypeVariant {
                    name: "IpNetwork",
                    variant: "V4",
                },
                Token::Tuple { len: 2 },
                Token::Tuple { len: 4 },
                Token::U8(1),
                Token::U8(2),
                Token::U8(3),
                Token::U8(4),
                Token::TupleEnd,
                Token::U8(32),
                Token::TupleEnd,
            ],
        );
    }

    #[test]
    fn ipv4_network_serialize_readable() {
        let ip_network = Ipv4Network::new(Ipv4Addr::new(1, 2, 3, 4), 32).unwrap();

        assert_tokens(&ip_network.readable(), &[Token::BorrowedStr("1.2.3.4/32")]);
    }

    #[test]
    fn ipv4_network_serialize_compact() {
        let ip_network = Ipv4Network::new(Ipv4Addr::new(1, 2, 3, 4), 32).unwrap();

        assert_tokens(
            &ip_network.compact(),
            &[
                Token::Tuple { len: 2 },
                Token::Tuple { len: 4 },
                Token::U8(1),
                Token::U8(2),
                Token::U8(3),
                Token::U8(4),
                Token::TupleEnd,
                Token::U8(32),
                Token::TupleEnd,
            ],
        );
    }

    #[test]
    fn ipv6_network_serialize_readable() {
        let ip_network = Ipv6Network::new(Ipv6Addr::new(1, 2, 3, 4, 0, 0, 0, 0), 64).unwrap();

        assert_tokens(
            &ip_network.readable(),
            &[Token::BorrowedStr("1:2:3:4::/64")],
        );
    }

    #[test]
    fn ipv6_network_serialize_compact() {
        let ip_network = Ipv6Network::new(Ipv6Addr::new(1, 2, 3, 4, 0, 0, 0, 0), 64).unwrap();

        assert_tokens(
            &ip_network.compact(),
            &[
                Token::Tuple { len: 2 },
                Token::Tuple { len: 16 },
                Token::U8(0),
                Token::U8(1),
                Token::U8(0),
                Token::U8(2),
                Token::U8(0),
                Token::U8(3),
                Token::U8(0),
                Token::U8(4),
                Token::U8(0),
                Token::U8(0),
                Token::U8(0),
                Token::U8(0),
                Token::U8(0),
                Token::U8(0),
                Token::U8(0),
                Token::U8(0),
                Token::TupleEnd,
                Token::U8(64),
                Token::TupleEnd,
            ],
        );
    }
}
<commit_msg>Do not use full path in Serde for Error<commit_after>use std::fmt;
use std::str;
use serde::de::{Deserialize, Deserializer, EnumAccess, Error, Unexpected, VariantAccess, Visitor};
use serde::ser::{Serialize, Serializer};
use crate::{IpNetwork, Ipv4Network, Ipv6Network};

impl Serialize for IpNetwork {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        if serializer.is_human_readable() {
            serializer.serialize_str(&self.to_string())
        } else {
            match *self {
                IpNetwork::V4(ref a) => {
                    serializer.serialize_newtype_variant("IpNetwork", 0, "V4", a)
                }
                IpNetwork::V6(ref a) => {
                    serializer.serialize_newtype_variant("IpNetwork", 1, "V6", a)
                }
            }
        }
    }
}

impl<'de> Deserialize<'de> for IpNetwork {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        if deserializer.is_human_readable() {
            struct IpNetworkVisitor;

            impl<'de> Visitor<'de> for IpNetworkVisitor {
                type Value = IpNetwork;

                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                    formatter.write_str("IP network")
                }

                fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
                where
                    E: Error,
                {
                    s.parse().map_err(Error::custom)
                }
            }

            deserializer.deserialize_str(IpNetworkVisitor)
        } else {
            enum IpNetworkKind {
                V4,
                V6,
            }

            static VARIANTS: &[&str] = &["V4", "V6"];

            impl<'de> Deserialize<'de> for IpNetworkKind {
                fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
                where
                    D: Deserializer<'de>,
                {
                    struct KindVisitor;
                    impl<'de> Visitor<'de> for KindVisitor {
                        type Value = IpNetworkKind;
                        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                            formatter.write_str("`V4` or `V6`")
                        }
                        fn visit_u32<E: Error>(self, value: u32) -> Result<Self::Value, E> {
                            match value {
                                0 => Ok(IpNetworkKind::V4),
                                1 => Ok(IpNetworkKind::V6),
                                _ => Err(Error::invalid_value(
                                    Unexpected::Unsigned(value as u64),
                                    &self,
                                )),
                            }
                        }
                        fn visit_str<E: Error>(self, value: &str) -> Result<Self::Value, E> {
                            match value {
                                "V4" => Ok(IpNetworkKind::V4),
                                "V6" => Ok(IpNetworkKind::V6),
                                _ => Err(Error::unknown_variant(value, VARIANTS)),
                            }
                        }
                        fn visit_bytes<E: Error>(self, value: &[u8]) -> Result<Self::Value, E> {
                            match value {
                                b"V4" => Ok(IpNetworkKind::V4),
                                b"V6" => Ok(IpNetworkKind::V6),
                                _ => match str::from_utf8(value) {
                                    Ok(value) => Err(Error::unknown_variant(value, VARIANTS)),
                                    Err(_) => {
                                        Err(Error::invalid_value(Unexpected::Bytes(value), &self))
                                    }
                                },
                            }
                        }
                    }
                    deserializer.deserialize_identifier(KindVisitor)
                }
            }

            struct EnumVisitor;

            impl<'de> Visitor<'de> for EnumVisitor {
                type Value = IpNetwork;

                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                    formatter.write_str("IP network")
                }

                fn visit_enum<A>(self, data: A) -> Result<Self::Value, A::Error>
                where
                    A: EnumAccess<'de>,
                {
                    match data.variant()? {
                        (IpNetworkKind::V4, v) => v.newtype_variant().map(IpNetwork::V4),
                        (IpNetworkKind::V6, v) => v.newtype_variant().map(IpNetwork::V6),
                    }
                }
            }

            deserializer.deserialize_enum("IpNetwork", VARIANTS, EnumVisitor)
        }
    }
}

macro_rules! ser_de_impl {
    ($expecting:tt $ty:ty) => {
        impl Serialize for $ty {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: Serializer,
            {
                if serializer.is_human_readable() {
                    serializer.serialize_str(&self.to_string())
                } else {
                    (self.network_address(), self.netmask()).serialize(serializer)
                }
            }
        }

        impl<'de> Deserialize<'de> for $ty {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: Deserializer<'de>,
            {
                if deserializer.is_human_readable() {
                    struct IpNetworkVisitor;

                    impl<'de> Visitor<'de> for IpNetworkVisitor {
                        type Value = $ty;

                        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                            formatter.write_str($expecting)
                        }

                        fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
                        where
                            E: Error,
                        {
                            s.parse().map_err(Error::custom)
                        }
                    }

                    deserializer.deserialize_str(IpNetworkVisitor)
                } else {
                    let (network_address, netmask) = <(_, u8)>::deserialize(deserializer)?;
                    Self::new(network_address, netmask).map_err(Error::custom)
                }
            }
        }
    };
}

ser_de_impl!("IPv4 network" Ipv4Network);
ser_de_impl!("IPv6 network" Ipv6Network);

#[cfg(test)]
mod tests {
    use crate::{IpNetwork, Ipv4Network, Ipv6Network};
    use serde_test::{assert_tokens, Configure, Token};
    use std::net::{Ipv4Addr, Ipv6Addr};

    #[test]
    fn ip_network_serialize_readable() {
        let ip_network = IpNetwork::new(Ipv4Addr::new(1, 2, 3, 4), 32).unwrap();

        assert_tokens(&ip_network.readable(), &[Token::BorrowedStr("1.2.3.4/32")]);
    }

    #[test]
    fn ip_network_serialize_compact() {
        let ip_network = IpNetwork::new(Ipv4Addr::new(1, 2, 3, 4), 32).unwrap();

        assert_tokens(
            &ip_network.compact(),
            &[
                Token::NewtypeVariant {
                    name: "IpNetwork",
                    variant: "V4",
                },
                Token::Tuple { len: 2 },
                Token::Tuple { len: 4 },
                Token::U8(1),
                Token::U8(2),
                Token::U8(3),
                Token::U8(4),
                Token::TupleEnd,
                Token::U8(32),
                Token::TupleEnd,
            ],
        );
    }

    #[test]
    fn ipv4_network_serialize_readable() {
        let ip_network = Ipv4Network::new(Ipv4Addr::new(1, 2, 3, 4), 32).unwrap();

        assert_tokens(&ip_network.readable(), &[Token::BorrowedStr("1.2.3.4/32")]);
    }

    #[test]
    fn ipv4_network_serialize_compact() {
        let ip_network = Ipv4Network::new(Ipv4Addr::new(1, 2, 3, 4), 32).unwrap();

        assert_tokens(
            &ip_network.compact(),
            &[
                Token::Tuple { len: 2 },
                Token::Tuple { len: 4 },
                Token::U8(1),
                Token::U8(2),
                Token::U8(3),
                Token::U8(4),
                Token::TupleEnd,
                Token::U8(32),
                Token::TupleEnd,
            ],
        );
    }

    #[test]
    fn ipv6_network_serialize_readable() {
        let ip_network = Ipv6Network::new(Ipv6Addr::new(1, 2, 3, 4, 0, 0, 0, 0), 64).unwrap();

        assert_tokens(
            &ip_network.readable(),
            &[Token::BorrowedStr("1:2:3:4::/64")],
        );
    }

    #[test]
    fn ipv6_network_serialize_compact() {
        let ip_network = Ipv6Network::new(Ipv6Addr::new(1, 2, 3, 4, 0, 0, 0, 0), 64).unwrap();

        assert_tokens(
            &ip_network.compact(),
            &[
                Token::Tuple { len: 2 },
                Token::Tuple { len: 16 },
                Token::U8(0),
                Token::U8(1),
                Token::U8(0),
                Token::U8(2),
                Token::U8(0),
                Token::U8(3),
                Token::U8(0),
                Token::U8(4),
                Token::U8(0),
                Token::U8(0),
                Token::U8(0),
                Token::U8(0),
                Token::U8(0),
                Token::U8(0),
                Token::U8(0),
                Token::U8(0),
                Token::TupleEnd,
                Token::U8(64),
                Token::TupleEnd,
            ],
        );
    }
}
<|endoftext|>


<commit_before>#![feature(
    async_await,
    await_macro,
    futures_api,
    pin,
    arbitrary_self_types
)]

#[cfg(test)]
mod tests {
    use std::future::Future;
    use std::pin::{Pin, Unpin};
    use std::task::{LocalWaker, Poll};
    use std::time::{Duration, Instant};

    use futures::compat::Future01CompatExt;
    use futures::executor::{block_on, ThreadPoolBuilder};
    use futures::prelude::{FutureExt, TryFutureExt};
    use tokio::timer::Delay;

    use timer::{Guard, Timer};

    struct Myfuture {
        timer: Timer,
        guard: Option<Guard>,
    }

    impl Unpin for Myfuture {}

    impl Future for Myfuture {
        type Output = bool;

        fn poll(self: Pin<&mut Self>, lw: &LocalWaker) -> Poll<Self::Output> {
            if self.guard.is_some() {
                println!("\nMyfuture: I am ready");
                return Poll::Ready(true);
            } else {
                println!("\nMyfuture: I am not ready");
                let waker = lw.clone().into_waker();
                Pin::get_mut(self).guard = Some(self.timer.schedule_with_delay(
                    chrono::Duration::seconds(1),
                    move || {
                        waker.wake();
                    },
                ));
                return Poll::Pending;
            }
        }
    }

    #[test]
    fn executor_current_thread() {
        assert_eq!(
            true,
            block_on(async {
                await!(Myfuture {
                timer: Timer::new(),
                guard: None,
            })})
        );
    }

    #[test]
    fn executor_threadpool() {
        let mut pool = ThreadPoolBuilder::new().pool_size(1).create().unwrap();
        assert_eq!(
            true,
            pool.run(Myfuture {
                timer: Timer::new(),
                guard: None,
            })
        );
    }

    #[test]
    fn executor_eventloop() {
        tokio::run(
            Myfuture {
                timer: Timer::new(),
                guard: None,
            }
            .map(|x| {
                assert_eq!(true, x);
                ()
            })
            .unit_error()
            // convert futures 0.3 into 0.1 with TryFuture
            .compat(),
        );
    }

    #[test]
    #[should_panic]
    fn job_on_time() {
        let when = Instant::now() + Duration::from_millis(100);
        assert_eq!(
            1,
            // Tokio 0.1's Future doesn't work in Futures 0.3's executor now.
            block_on(Delay::new(when).compat().map(|x| {
                assert_eq!((), x.unwrap());
                1
            }))
        );
    }
}
//[cfg(test)]
<commit_msg>Pin API is stable<commit_after>#![feature(async_await, await_macro, futures_api, arbitrary_self_types)]

#[cfg(test)]
mod tests {
    use std::future::Future;
    use std::pin::Pin;
    use std::task::{LocalWaker, Poll};
    use std::time::{Duration, Instant};

    use futures::compat::Future01CompatExt;
    use futures::executor::{block_on, ThreadPoolBuilder};
    use futures::prelude::{FutureExt, TryFutureExt};
    use tokio::timer::Delay;

    use timer::{Guard, Timer};

    struct Myfuture {
        timer: Timer,
        guard: Option<Guard>,
    }

    impl Future for Myfuture {
        type Output = bool;

        fn poll(self: Pin<&mut Self>, lw: &LocalWaker) -> Poll<Self::Output> {
            if self.guard.is_some() {
                println!("\nMyfuture: I am ready");
                return Poll::Ready(true);
            } else {
                println!("\nMyfuture: I am not ready");
                let waker = lw.clone().into_waker();
                Pin::get_mut(self).guard = Some(self.timer.schedule_with_delay(
                    chrono::Duration::seconds(1),
                    move || {
                        waker.wake();
                    },
                ));
                return Poll::Pending;
            }
        }
    }

    #[test]
    fn executor_current_thread() {
        assert_eq!(
            true,
            block_on(
                async {
                    await!(Myfuture {
                        timer: Timer::new(),
                        guard: None,
                    })
                }
            )
        );
    }

    #[test]
    fn executor_threadpool() {
        let mut pool = ThreadPoolBuilder::new().pool_size(1).create().unwrap();
        assert_eq!(
            true,
            pool.run(Myfuture {
                timer: Timer::new(),
                guard: None,
            })
        );
    }

    #[test]
    fn executor_eventloop() {
        tokio::run(
            Myfuture {
                timer: Timer::new(),
                guard: None,
            }
            .map(|x| {
                assert_eq!(true, x);
                ()
            })
            .unit_error()
            // convert futures 0.3 into 0.1 with TryFuture
            .compat(),
        );
    }

    #[test]
    #[should_panic]
    fn job_on_time() {
        let when = Instant::now() + Duration::from_millis(100);
        assert_eq!(
            1,
            // Tokio 0.1's Future doesn't work in Futures 0.3's executor now.
            block_on(Delay::new(when).compat().map(|x| {
                assert_eq!((), x.unwrap());
                1
            }))
        );
    }
}
//[cfg(test)]
<|endoftext|>