<commit_before>#![crate_name = "base64"]

/*
 * This file is part of the uutils coreutils package.
 *
 * (c) Jordy Dickinson <jordy.dickinson@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

#![feature(phase)]
#![feature(macro_rules)]

extern crate serialize;
extern crate getopts;
extern crate libc;
#[phase(plugin, link)] extern crate log;

use std::io::{println, File, stdout};
use std::io::stdio::stdin_raw;

use getopts::{
    getopts,
    optflag,
    optopt,
    usage
};
use serialize::base64;
use serialize::base64::{FromBase64, ToBase64};

#[path = "../common/util.rs"]
mod util;

static NAME: &'static str = "base64";

pub fn uumain(args: Vec<String>) -> int {
    let opts = [
        optflag("d", "decode", "decode data"),
        optflag("i", "ignore-garbage", "when decoding, ignore non-alphabetic characters"),
        optopt("w", "wrap",
            "wrap encoded lines after COLS character (default 76, 0 to disable wrapping)", "COLS"
        ),
        optflag("h", "help", "display this help text and exit"),
        optflag("V", "version", "output version information and exit")
    ];
    let matches = match getopts(args.tail(), opts) {
        Ok(m) => m,
        Err(e) => {
            error!("error: {}", e);
            fail!()
        }
    };

    let progname = args[0].clone();
    let usage = usage("Base64 encode or decode FILE, or standard input, to standard output.", opts);
    let mode = if matches.opt_present("help") {
        Help
    } else if matches.opt_present("version") {
        Version
    } else if matches.opt_present("decode") {
        Decode
    } else {
        Encode
    };
    let ignore_garbage = matches.opt_present("ignore-garbage");
    let line_wrap = match matches.opt_str("wrap") {
        Some(s) => match from_str(s.as_slice()) {
            Some(s) => s,
            None => {
                error!("error: {:s}", "Argument to option 'wrap' improperly formatted.");
                fail!()
            }
        },
        None => 76
    };
    let mut stdin_buf;
    let mut file_buf;
    let input = if matches.free.is_empty() || matches.free[0].as_slice() == "-" {
        stdin_buf = stdin_raw();
        &mut stdin_buf as &mut Reader
    } else {
        let path = Path::new(matches.free[0].as_slice());
        file_buf = File::open(&path);
        &mut file_buf as &mut Reader
    };

    match mode {
        Decode  => decode(input, ignore_garbage),
        Encode  => encode(input, line_wrap),
        Help    => help(progname.as_slice(), usage.as_slice()),
        Version => version()
    }

    0
}

fn decode(input: &mut Reader, ignore_garbage: bool) {
    let mut to_decode = match input.read_to_string() {
        Ok(m) => m,
        Err(f) => fail!(f)
    };

    let slice =
        if ignore_garbage {
            to_decode.as_slice()
                .trim_chars(|c: char| {
                    let num = match c.to_ascii_opt() {
                        Some(ascii) => ascii.to_byte(),
                        None => return false
                    };
                    !(num >= 'a' as u8 && num <= 'z' as u8 ||
                      num >= 'A' as u8 && num <= 'Z' as u8 ||
                      num >= '0' as u8 && num <= '9' as u8 ||
                      num == '+' as u8 || num == '/' as u8)
                })
        } else {
            to_decode = to_decode.as_slice().replace("\n", "");
            to_decode.as_slice()
        };

    match slice.from_base64() {
        Ok(bytes) => {
            let mut out = stdout();

            match out.write(bytes.as_slice()) {
                Ok(_) => {}
                Err(f) => { crash!(1, "{}", f); }
            }
            match out.flush() {
                Ok(_) => {}
                Err(f) => { crash!(1, "{}", f); }
            }
        }
        Err(s) => {
            error!("error: {}", s);
            fail!()
        }
    }
}

fn encode(input: &mut Reader, line_wrap: uint) {
    let b64_conf = base64::Config {
        char_set: base64::Standard,
        pad: true,
        line_length: match line_wrap {
            0 => None,
            _ => Some(line_wrap)
        }
    };
    let to_encode = match input.read_to_end() {
        Ok(m) => m,
        Err(err) => crash!(1, "{}", err)
    };
    let encoded = to_encode.as_slice().to_base64(b64_conf);

    // To my knowledge, RFC 3548 does not specify which line endings to use. It
    // seems that rust's base64 algorithm uses CRLF as prescribed by RFC 2045.
    // However, since GNU base64 outputs only LF (presumably because that is
    // the standard UNIX line ending), we strip CRs from the output to maintain
    // compatibility.
    let final = encoded.replace("\r", "");

    println(final.as_slice());
}

fn help(progname: &str, usage: &str) {
    println!("Usage: {:s} [OPTION]... [FILE]", progname);
    println!("");
    println(usage);

    let msg = "With no FILE, or when FILE is -, read standard input.\n\n\
        The data are encoded as described for the base64 alphabet in RFC \
        3548. When\ndecoding, the input may contain newlines in addition \
        to the bytes of the formal\nbase64 alphabet. Use --ignore-garbage \
        to attempt to recover from any other\nnon-alphabet bytes in the \
        encoded stream.";

    println(msg);
}

fn version() {
    println!("base64 1.0.0");
}

enum Mode {
    Decode,
    Encode,
    Help,
    Version
}
<commit_msg>'final' is a keyword now<commit_after>#![crate_name = "base64"]

/*
 * This file is part of the uutils coreutils package.
 *
 * (c) Jordy Dickinson <jordy.dickinson@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE file
 * that was distributed with this source code.
 */

#![feature(phase)]
#![feature(macro_rules)]

extern crate serialize;
extern crate getopts;
extern crate libc;
#[phase(plugin, link)] extern crate log;

use std::io::{println, File, stdout};
use std::io::stdio::stdin_raw;

use getopts::{
    getopts,
    optflag,
    optopt,
    usage
};
use serialize::base64;
use serialize::base64::{FromBase64, ToBase64};

#[path = "../common/util.rs"]
mod util;

static NAME: &'static str = "base64";

pub fn uumain(args: Vec<String>) -> int {
    let opts = [
        optflag("d", "decode", "decode data"),
        optflag("i", "ignore-garbage", "when decoding, ignore non-alphabetic characters"),
        optopt("w", "wrap",
            "wrap encoded lines after COLS character (default 76, 0 to disable wrapping)", "COLS"
        ),
        optflag("h", "help", "display this help text and exit"),
        optflag("V", "version", "output version information and exit")
    ];
    let matches = match getopts(args.tail(), opts) {
        Ok(m) => m,
        Err(e) => {
            error!("error: {}", e);
            fail!()
        }
    };

    let progname = args[0].clone();
    let usage = usage("Base64 encode or decode FILE, or standard input, to standard output.", opts);
    let mode = if matches.opt_present("help") {
        Help
    } else if matches.opt_present("version") {
        Version
    } else if matches.opt_present("decode") {
        Decode
    } else {
        Encode
    };
    let ignore_garbage = matches.opt_present("ignore-garbage");
    let line_wrap = match matches.opt_str("wrap") {
        Some(s) => match from_str(s.as_slice()) {
            Some(s) => s,
            None => {
                error!("error: {:s}", "Argument to option 'wrap' improperly formatted.");
                fail!()
            }
        },
        None => 76
    };
    let mut stdin_buf;
    let mut file_buf;
    let input = if matches.free.is_empty() || matches.free[0].as_slice() == "-" {
        stdin_buf = stdin_raw();
        &mut stdin_buf as &mut Reader
    } else {
        let path = Path::new(matches.free[0].as_slice());
        file_buf = File::open(&path);
        &mut file_buf as &mut Reader
    };

    match mode {
        Decode  => decode(input, ignore_garbage),
        Encode  => encode(input, line_wrap),
        Help    => help(progname.as_slice(), usage.as_slice()),
        Version => version()
    }

    0
}

fn decode(input: &mut Reader, ignore_garbage: bool) {
    let mut to_decode = match input.read_to_string() {
        Ok(m) => m,
        Err(f) => fail!(f)
    };

    let slice =
        if ignore_garbage {
            to_decode.as_slice()
                .trim_chars(|c: char| {
                    let num = match c.to_ascii_opt() {
                        Some(ascii) => ascii.to_byte(),
                        None => return false
                    };
                    !(num >= 'a' as u8 && num <= 'z' as u8 ||
                      num >= 'A' as u8 && num <= 'Z' as u8 ||
                      num >= '0' as u8 && num <= '9' as u8 ||
                      num == '+' as u8 || num == '/' as u8)
                })
        } else {
            to_decode = to_decode.as_slice().replace("\n", "");
            to_decode.as_slice()
        };

    match slice.from_base64() {
        Ok(bytes) => {
            let mut out = stdout();

            match out.write(bytes.as_slice()) {
                Ok(_) => {}
                Err(f) => { crash!(1, "{}", f); }
            }
            match out.flush() {
                Ok(_) => {}
                Err(f) => { crash!(1, "{}", f); }
            }
        }
        Err(s) => {
            error!("error: {}", s);
            fail!()
        }
    }
}

fn encode(input: &mut Reader, line_wrap: uint) {
    let b64_conf = base64::Config {
        char_set: base64::Standard,
        pad: true,
        line_length: match line_wrap {
            0 => None,
            _ => Some(line_wrap)
        }
    };
    let to_encode = match input.read_to_end() {
        Ok(m) => m,
        Err(err) => crash!(1, "{}", err)
    };
    let encoded = to_encode.as_slice().to_base64(b64_conf);

    // To my knowledge, RFC 3548 does not specify which line endings to use. It
    // seems that rust's base64 algorithm uses CRLF as prescribed by RFC 2045.
    // However, since GNU base64 outputs only LF (presumably because that is
    // the standard UNIX line ending), we strip CRs from the output to maintain
    // compatibility.
    let output = encoded.replace("\r", "");

    println(output.as_slice());
}

fn help(progname: &str, usage: &str) {
    println!("Usage: {:s} [OPTION]... [FILE]", progname);
    println!("");
    println(usage);

    let msg = "With no FILE, or when FILE is -, read standard input.\n\n\
        The data are encoded as described for the base64 alphabet in RFC \
        3548. When\ndecoding, the input may contain newlines in addition \
        to the bytes of the formal\nbase64 alphabet. Use --ignore-garbage \
        to attempt to recover from any other\nnon-alphabet bytes in the \
        encoded stream.";

    println(msg);
}

fn version() {
    println!("base64 1.0.0");
}

enum Mode {
    Decode,
    Encode,
    Help,
    Version
}
<|endoftext|>


<commit_before>
extern crate ndarray;
extern crate ndarray_odeint;
extern crate itertools;
extern crate simple_complex;
extern crate num_traits;

use ndarray::rcarr1;
use itertools::iterate;
use ndarray_odeint::prelude::*;
use simple_complex::c64;
use num_traits::Zero;

fn main() {
    let dt = 1e-5;
    let eom = GoyShell::default();
    let teo = semi_implicit::diag_rk4(eom, dt);
    let x0 = rcarr1(&vec![c64::zero(); 27]);
    let ts = iterate(x0, |y| teo.iterate(y.clone()));
    let end_time = 10000;
    for (_, v) in ts.take(end_time).enumerate() {
        println!("{:?}", v);
    }
}
<commit_msg>Output CSV<commit_after>
extern crate ndarray;
extern crate ndarray_odeint;
extern crate itertools;
extern crate simple_complex;
extern crate num_traits;

use ndarray::rcarr1;
use itertools::iterate;
use ndarray_odeint::prelude::*;
use simple_complex::c64;
use num_traits::Zero;

fn main() {
    let dt = 1e-5;
    let eom = GoyShell::default();
    let teo = semi_implicit::diag_rk4(eom, dt);
    let x0 = rcarr1(&vec![c64::zero(); 27]);
    let ts = iterate(x0, |y| teo.iterate(y.clone()));
    let end_time = 100;
    print!("r0,c0");
    for i in 1..27 {
        print!(",r{},c{}", i, i);
    }
    println!("");
    for (_, v) in ts.take(end_time).enumerate() {
        for (i, c) in v.iter().enumerate() {
            if i == 0 {
                print!("{},{}", c.re(), c.im());
            } else {
                print!(",{},{}", c.re(), c.im());
            }
        }
        println!("");
    }
}
<|endoftext|>


<commit_before>// Copyright © 2016, Canal TP and/or its affiliates. All rights reserved.
//
// This file is part of Navitia,
//     the software to build cool stuff with public transport.
//
// Hope you'll enjoy and contribute to this project,
//     powered by Canal TP (www.canaltp.fr).
// Help us simplify mobility and open public transport:
//     a non ending quest to the responsive locomotion way of traveling!
//
// LICENCE: This program is free software; you can redistribute it
// and/or modify it under the terms of the GNU Affero General Public
// License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//
// Stay tuned using
// twitter @navitia
// IRC #navitia on freenode
// https://groups.google.com/d/forum/navitia
// www.navitia.io

extern crate docopt;
#[macro_use]
extern crate log;
extern crate mimir;
extern crate mimirsbrunn;
extern crate rustc_serialize;

use mimir::rubber::Rubber;
use mimirsbrunn::osm_reader::admin::administrative_regions;
use mimirsbrunn::osm_reader::poi::{PoiTypes, pois, default_amenity_types,
                                              default_leisure_types,
                                              compute_poi_weight};
use mimirsbrunn::osm_reader::street::streets;
use mimirsbrunn::osm_reader::parse_osm_pbf;
use mimirsbrunn::admin_geofinder::AdminGeoFinder;

#[derive(RustcDecodable, Debug)]
struct Args {
    flag_input: String,
    flag_level: Vec<u32>,
    flag_city_level: u32,
    flag_connection_string: String,
    flag_import_way: bool,
    flag_import_admin: bool,
    flag_import_poi: bool,
    flag_dataset: String,
}

static USAGE: &'static str =
    "
Usage:
    osm2mimir --help
    osm2mimir --input=<file> \
     [--connection-string=<connection-string>] [--import-way] [--import-admin] [--import-poi] \
     [--dataset=<dataset>] [--city-level=<level>] --level=<level> ...

Options:
    -h, --help              \
     Show this message.
    -i, --input=<file>      OSM PBF file.
    -l, --level=<level>     \
     Admin levels to keep.
    -C, --city-level=<level>
                            City level to \
     calculate weight, [default: 8]
    -w, --import-way        Import ways
    -a, \
     --import-admin      Import admins
    -p, --import-poi        Import POIs
    -c, \
     --connection-string=<connection-string>
                            Elasticsearch \
     parameters, [default: http://localhost:9200/munin]
    -d, --dataset=<dataset>
                            \
     Name of the dataset, [default: fr]
";

fn main() {
    mimir::logger_init().unwrap();
    let args: Args = docopt::Docopt::new(USAGE)
        .and_then(|d| d.decode())
        .unwrap_or_else(|e| e.exit());

    let levels = args.flag_level.iter().cloned().collect();
    let city_level = args.flag_city_level;
    let mut parsed_pbf = parse_osm_pbf(&args.flag_input);
    debug!("creation of indexes");
    let mut rubber = Rubber::new(&args.flag_connection_string);

    info!("creating adminstrative regions");
    let admins = administrative_regions(&mut parsed_pbf, levels);
    let admins_geofinder = admins.iter().cloned().collect::<AdminGeoFinder>();
    {
        info!("Extracting streets from osm");
        let mut streets = streets(&mut parsed_pbf, &admins_geofinder, city_level);

        info!("computing city weight");
        compute_admin_weight(&mut streets);

        info!("computing street weight");
        compute_street_weight(&mut streets, city_level);

    if args.flag_import_way {
        info!("importing streets into Mimir");
        let nb_streets = rubber.index("way", &args.flag_dataset, streets.into_iter())
            .unwrap();
        info!("Nb of indexed street: {}", nb_streets);
    }

    let nb_admins = rubber.index("admin", &args.flag_dataset, admins.iter())
        .unwrap();
    info!("Nb of indexed admin: {}", nb_admins);

    if args.flag_import_poi {
        let mut poi_types = PoiTypes::new();
        poi_types.insert("amenity".to_string(), default_amenity_types());
        poi_types.insert("leisure".to_string(), default_leisure_types());

        info!("Extracting pois from osm");
        let mut pois = pois(&mut parsed_pbf, poi_types, &admins, city_level);

        info!("computing poi weight");
        compute_poi_weight(&mut pois, city_level);

        info!("Importing pois into Mimir");
        let nb_pois = rubber.index("poi", &args.flag_dataset, pois.iter())
            .unwrap();

        info!("Nb of indexed pois: {}", nb_pois);
    }
}
<commit_msg>rebase<commit_after>// Copyright © 2016, Canal TP and/or its affiliates. All rights reserved.
//
// This file is part of Navitia,
//     the software to build cool stuff with public transport.
//
// Hope you'll enjoy and contribute to this project,
//     powered by Canal TP (www.canaltp.fr).
// Help us simplify mobility and open public transport:
//     a non ending quest to the responsive locomotion way of traveling!
//
// LICENCE: This program is free software; you can redistribute it
// and/or modify it under the terms of the GNU Affero General Public
// License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see
// <http://www.gnu.org/licenses/>.
//
// Stay tuned using
// twitter @navitia
// IRC #navitia on freenode
// https://groups.google.com/d/forum/navitia
// www.navitia.io

extern crate docopt;
#[macro_use]
extern crate log;
extern crate mimir;
extern crate mimirsbrunn;
extern crate rustc_serialize;

use mimir::rubber::Rubber;
use mimirsbrunn::osm_reader::admin::{administrative_regions,compute_admin_weight};
use mimirsbrunn::osm_reader::poi::{PoiTypes, pois, default_amenity_types,
                                              default_leisure_types,
                                              compute_poi_weight};
use mimirsbrunn::osm_reader::street::{streets, compute_street_weight};
use mimirsbrunn::osm_reader::parse_osm_pbf;
use mimirsbrunn::admin_geofinder::AdminGeoFinder;

#[derive(RustcDecodable, Debug)]
struct Args {
    flag_input: String,
    flag_level: Vec<u32>,
    flag_city_level: u32,
    flag_connection_string: String,
    flag_import_way: bool,
    flag_import_admin: bool,
    flag_import_poi: bool,
    flag_dataset: String,
}

static USAGE: &'static str =
    "
Usage:
    osm2mimir --help
    osm2mimir --input=<file> \
     [--connection-string=<connection-string>] [--import-way] [--import-admin] [--import-poi] \
     [--dataset=<dataset>] [--city-level=<level>] --level=<level> ...

Options:
    -h, --help              \
     Show this message.
    -i, --input=<file>      OSM PBF file.
    -l, --level=<level>     \
     Admin levels to keep.
    -C, --city-level=<level>
                            City level to \
     calculate weight, [default: 8]
    -w, --import-way        Import ways
    -a, \
     --import-admin      Import admins
    -p, --import-poi        Import POIs
    -c, \
     --connection-string=<connection-string>
                            Elasticsearch \
     parameters, [default: http://localhost:9200/munin]
    -d, --dataset=<dataset>
                            \
     Name of the dataset, [default: fr]
";

fn main() {
    mimir::logger_init().unwrap();
    let args: Args = docopt::Docopt::new(USAGE)
        .and_then(|d| d.decode())
        .unwrap_or_else(|e| e.exit());

    let levels = args.flag_level.iter().cloned().collect();
    let city_level = args.flag_city_level;
    let mut parsed_pbf = parse_osm_pbf(&args.flag_input);
    debug!("creation of indexes");
    let mut rubber = Rubber::new(&args.flag_connection_string);

    info!("creating adminstrative regions");
    let admins = administrative_regions(&mut parsed_pbf, levels);
    let admins_geofinder = admins.iter().cloned().collect::<AdminGeoFinder>();
    {
        info!("Extracting streets from osm");
        let mut streets = streets(&mut parsed_pbf, &admins_geofinder, city_level);

        info!("computing city weight");
        compute_admin_weight(&mut streets);

        info!("computing street weight");
        compute_street_weight(&mut streets, city_level);

        if args.flag_import_way {
            info!("importing streets into Mimir");
            let nb_streets = rubber.index("way", &args.flag_dataset, streets.into_iter())
                .unwrap();
            info!("Nb of indexed street: {}", nb_streets);
        }
    }
    let nb_admins = rubber.index("admin", &args.flag_dataset, admins.iter())
        .unwrap();
    info!("Nb of indexed admin: {}", nb_admins);

    if args.flag_import_poi {
        let mut poi_types = PoiTypes::new();
        poi_types.insert("amenity".to_string(), default_amenity_types());
        poi_types.insert("leisure".to_string(), default_leisure_types());

        info!("Extracting pois from osm");
        let mut pois = pois(&mut parsed_pbf, poi_types, &admins_geofinder, city_level);

        info!("computing poi weight");
        compute_poi_weight(&mut pois, city_level);

        info!("Importing pois into Mimir");
        let nb_pois = rubber.index("poi", &args.flag_dataset, pois.iter())
            .unwrap();

        info!("Nb of indexed pois: {}", nb_pois);
    }
}
<|endoftext|>


<commit_before>mod advent_of_code;

use std::cmp::Ordering;

use std::collections::HashMap;

use std::io;
use std::io::BufRead;

const CHECKSUM_SIZE: usize = 5;

fn compare_counts(a: &(char, usize), b: &(char, usize))
    -> Ordering
{
    let mut cmp = b.1.cmp(&a.1);
    if cmp == Ordering::Equal
    {
        cmp = a.0.cmp(&b.0);
    }
    return cmp;
}

fn compute_checksum(name: &str)
    -> String
{
    let mut counts: HashMap<char, usize> = HashMap::new();

    for letter in name.chars()
    {
        if letter == '-'
        {
            continue;
        }

        let count = counts.entry(letter).or_insert(0);
        *count += 1;
    }

    let mut sorted_counts: Vec<(char, usize)> = counts.into_iter().collect();
    sorted_counts.sort_by(compare_counts);

    let mut checksum = String::with_capacity(CHECKSUM_SIZE);

    for pair in sorted_counts[..CHECKSUM_SIZE].iter()
    {
        let (letter, _) = *pair;
        checksum.push(letter);
    }

    return checksum;
}

fn rot_n(letter: char, n: i32)
    -> char
{
    let origin = 'a' as u8;
    let letter_value = letter as u8 - origin;
    let rotated_value = ((letter_value as i32 + n) % 26) as u8;
    let new_letter = (rotated_value + origin) as char;
    return new_letter;
}

fn shift(text: &str, n: i32)
    -> String
{
    let mut string = String::with_capacity(text.len());
    for letter in text.chars()
    {
        if letter == '-'
        {
            string.push(' ');
        }
        else
        {
            string.push(rot_n(letter, n));
        }
    }
    return string;
}

#[derive(PartialEq, Eq, Hash, Clone, Debug)]
struct Room<'a>
{
    checksum: &'a str,
    name: &'a str,
    sector_id: i32,
}

impl<'a> Room<'a>
{
    fn decode(text: &'a str)
        -> Room<'a>
    {
        let last_dash = text.rfind('-').unwrap();
        let checksum_outer_size = CHECKSUM_SIZE + 2;

        return Room {
            name: text[.. last_dash].as_ref(),
            sector_id: text[last_dash + 1 .. text.len() - checksum_outer_size].parse::<i32>().unwrap(),
            checksum: text[text.len() - 1 - CHECKSUM_SIZE .. text.len() - 1].as_ref(),
        };
    }
}

#[cfg(test)]
mod test
{
    use compute_checksum;
    use rot_n;
    use Room;
    use shift;

    #[test]
    fn test_decode_room()
    {
        let input = "aaaaa-bbb-z-y-x-123[abxyz]";
        let expected = Room {
            checksum: "abxyz",
            name: "aaaaa-bbb-z-y-x",
            sector_id: 123,
        };
        let actual = Room::decode(input);
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_checksum_1()
    {
        let input = "aaaaa-bbb-z-y-x";
        let expected = "abxyz";
        let actual = compute_checksum(input);
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_checksum_2()
    {
        let input = "a-b-c-d-e-f-g-h";
        let expected = "abcde";
        let actual = compute_checksum(input);
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_checksum_3()
    {
        let input = "not-a-real-room";
        let expected = "oarel";
        let actual = compute_checksum(input);
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_checksum_4()
    {
        let input = "totally-real-room";
        let expected = "loart";
        let actual = compute_checksum(input);
        assert_eq!(expected, actual);
    }

    fn assert_rot_n(input: char, n: i32, expected: char)
    {
        let actual = rot_n(input, n);
        assert_eq!(expected, actual);
    }

    fn assert_rot_26(input: char)
    {
        assert_rot_n(input, 26, input)
    }

    #[test]
    fn test_rot_2_a()
    {
        assert_rot_n('a', 2, 'c');
    }

    #[test]
    fn test_rot_2_q()
    {
        assert_rot_n('q', 2, 's');
    }

    #[test]
    fn test_rot_2_z()
    {
        assert_rot_n('z', 2, 'b');
    }

    #[test]
    fn test_rot_26_a()
    {
        assert_rot_26('a');
    }

    #[test]
    fn test_rot_26_q()
    {
        assert_rot_26('q');
    }

    #[test]
    fn test_rot_26_z()
    {
        assert_rot_26('z');
    }

    #[test]
    fn test_rot_32_a()
    {
        assert_rot_n('a', 32, 'g');
    }

    #[test]
    fn test_rot_32_q()
    {
        assert_rot_n('q', 32, 'w');
    }

    #[test]
    fn test_rot_32_z()
    {
        assert_rot_n('z', 32, 'f');
    }

    #[test]
    fn test_shift()
    {
        let expected = "de f";
        let actual = shift("ab-c", 3);
        assert_eq!(actual, expected);
    }
}

#[cfg(not(test))]
fn main()
{
    let stdin = io::stdin();
    let mut total_sector_id = 0;

    for wrapped_line in stdin.lock().lines()
    {
        let line = wrapped_line.unwrap();
        let room = Room::decode(&line);
        if room.checksum == compute_checksum(room.name)
        {
            total_sector_id += room.sector_id;
        }
    }

    println!("{}", total_sector_id);
}
<commit_msg>Add part 2 code<commit_after>mod advent_of_code;

use std::cmp::Ordering;

use std::collections::HashMap;

use std::io;
use std::io::BufRead;

const CHECKSUM_SIZE: usize = 5;

fn compare_counts(a: &(char, usize), b: &(char, usize))
    -> Ordering
{
    let mut cmp = b.1.cmp(&a.1);
    if cmp == Ordering::Equal
    {
        cmp = a.0.cmp(&b.0);
    }
    return cmp;
}

fn compute_checksum(name: &str)
    -> String
{
    let mut counts: HashMap<char, usize> = HashMap::new();

    for letter in name.chars()
    {
        if letter == '-'
        {
            continue;
        }

        let count = counts.entry(letter).or_insert(0);
        *count += 1;
    }

    let mut sorted_counts: Vec<(char, usize)> = counts.into_iter().collect();
    sorted_counts.sort_by(compare_counts);

    let mut checksum = String::with_capacity(CHECKSUM_SIZE);

    for pair in sorted_counts[..CHECKSUM_SIZE].iter()
    {
        let (letter, _) = *pair;
        checksum.push(letter);
    }

    return checksum;
}

fn rot_n(letter: char, n: i32)
    -> char
{
    let origin = 'a' as u8;
    let letter_value = letter as u8 - origin;
    let rotated_value = ((letter_value as i32 + n) % 26) as u8;
    let new_letter = (rotated_value + origin) as char;
    return new_letter;
}

fn shift(text: &str, n: i32)
    -> String
{
    let mut string = String::with_capacity(text.len());
    for letter in text.chars()
    {
        if letter == '-'
        {
            string.push(' ');
        }
        else
        {
            string.push(rot_n(letter, n));
        }
    }
    return string;
}

#[derive(PartialEq, Eq, Hash, Clone, Debug)]
struct Room<'a>
{
    checksum: &'a str,
    name: &'a str,
    sector_id: i32,
}

impl<'a> Room<'a>
{
    fn decode(text: &'a str)
        -> Room<'a>
    {
        let last_dash = text.rfind('-').unwrap();
        let checksum_outer_size = CHECKSUM_SIZE + 2;

        return Room {
            name: text[.. last_dash].as_ref(),
            sector_id: text[last_dash + 1 .. text.len() - checksum_outer_size].parse::<i32>().unwrap(),
            checksum: text[text.len() - 1 - CHECKSUM_SIZE .. text.len() - 1].as_ref(),
        };
    }
}

#[cfg(test)]
mod test
{
    use compute_checksum;
    use rot_n;
    use Room;
    use shift;

    #[test]
    fn test_decode_room()
    {
        let input = "aaaaa-bbb-z-y-x-123[abxyz]";
        let expected = Room {
            checksum: "abxyz",
            name: "aaaaa-bbb-z-y-x",
            sector_id: 123,
        };
        let actual = Room::decode(input);
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_checksum_1()
    {
        let input = "aaaaa-bbb-z-y-x";
        let expected = "abxyz";
        let actual = compute_checksum(input);
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_checksum_2()
    {
        let input = "a-b-c-d-e-f-g-h";
        let expected = "abcde";
        let actual = compute_checksum(input);
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_checksum_3()
    {
        let input = "not-a-real-room";
        let expected = "oarel";
        let actual = compute_checksum(input);
        assert_eq!(expected, actual);
    }

    #[test]
    fn test_checksum_4()
    {
        let input = "totally-real-room";
        let expected = "loart";
        let actual = compute_checksum(input);
        assert_eq!(expected, actual);
    }

    fn assert_rot_n(input: char, n: i32, expected: char)
    {
        let actual = rot_n(input, n);
        assert_eq!(expected, actual);
    }

    fn assert_rot_26(input: char)
    {
        assert_rot_n(input, 26, input)
    }

    #[test]
    fn test_rot_2_a()
    {
        assert_rot_n('a', 2, 'c');
    }

    #[test]
    fn test_rot_2_q()
    {
        assert_rot_n('q', 2, 's');
    }

    #[test]
    fn test_rot_2_z()
    {
        assert_rot_n('z', 2, 'b');
    }

    #[test]
    fn test_rot_26_a()
    {
        assert_rot_26('a');
    }

    #[test]
    fn test_rot_26_q()
    {
        assert_rot_26('q');
    }

    #[test]
    fn test_rot_26_z()
    {
        assert_rot_26('z');
    }

    #[test]
    fn test_rot_32_a()
    {
        assert_rot_n('a', 32, 'g');
    }

    #[test]
    fn test_rot_32_q()
    {
        assert_rot_n('q', 32, 'w');
    }

    #[test]
    fn test_rot_32_z()
    {
        assert_rot_n('z', 32, 'f');
    }

    #[test]
    fn test_shift()
    {
        let expected = "de f";
        let actual = shift("ab-c", 3);
        assert_eq!(actual, expected);
    }
}

#[cfg(not(test))]
fn main()
{
    let stdin = io::stdin();
    let mut total_sector_id = 0;

    for wrapped_line in stdin.lock().lines()
    {
        let line = wrapped_line.unwrap();
        let room = Room::decode(&line);
        if room.checksum == compute_checksum(room.name)
        {
            total_sector_id += room.sector_id;

            if false
            {
                // part 2
                let name = shift(room.name, room.sector_id);
                if name == "northpole object storage"
                {
                    println!("{}: {}", name, room.sector_id);
                }
            }
        }
    }

    println!("{}", total_sector_id);
}
<|endoftext|>


<commit_before>use std::path::Path;

use builder::context::Context;
use builder::distrib::{Unknown,Distribution};
use builder::error::{Error};
use builder::commands::{composer, gem, npm, pip};
use builder::packages;
use build_step::BuildStep;
use container::util::clean_dir;
use container::mount::{unmount, mount_system_dirs};
use file_util::{create_dir, copy};

pub struct Guard<'a> {
    pub ctx: Context<'a>,
    pub distro: Box<Distribution>,
}

impl<'a> Guard<'a> {
    pub fn build(ctx: Context) -> Result<(), Error> {
        Guard {
            ctx: ctx,
            distro: Box::new(Unknown),
        }.run_process()
    }

    fn run_process(&mut self) -> Result<(), Error> {
        try!(self.start());

        for b in self.ctx.container_config.setup.iter() {
            debug!("Building step: {:?}", b);
            try!(self.ctx.timelog.mark(format_args!("Step: {:?}", b))
                .map_err(|e| format!("Can't write timelog: {}", e)));
            try!(b.build(self, true)
                .map_err(|e| Error::Step(b.0.clone(), e)));
        }

        try!(self.finish());
        Ok(())
    }

    pub fn start(&mut self) -> Result<(), String> {
        try!(mount_system_dirs());
        try_msg!(create_dir("/vagga/root/etc", false),
             "Error creating /etc dir: {err}");
        try!(copy("/etc/resolv.conf", "/vagga/root/etc/resolv.conf")
            .map_err(|e| format!("Error copying /etc/resolv.conf: {}", e)));
        try!(self.ctx.timelog.mark(format_args!("Prepare"))
            .map_err(|e| format!("Can't write timelog: {}", e)));
        Ok(())
    }

    pub fn finish(&mut self) -> Result<(), String> {
        // Pip
        if self.ctx.featured_packages.contains(&packages::PipPy2) ||
           self.ctx.featured_packages.contains(&packages::PipPy3)
        {
            try!(pip::freeze(&mut self.ctx));
        }
        // Npm
        if self.ctx.featured_packages.contains(&packages::Npm) {
            try!(npm::list(&mut self.ctx));
        }
        // Composer
        if self.ctx.featured_packages.contains(&packages::Composer) {
            try!(composer::finish(&mut self.ctx));
        }
        // Gem
        if self.ctx.featured_packages.contains(&packages::Bundler) {
            try!(gem::list(&mut self.ctx));
        }

        try!(self.distro.finish(&mut self.ctx));

        let base = Path::new("/vagga/root");

        for path in self.ctx.mounted.iter().rev() {
            try!(unmount(path));
        }

        for dir in self.ctx.remove_dirs.iter() {
            try!(clean_dir(&base.join(dir), true)
                .map_err(|e| format!("Error removing dir: {}", e)));
        }

        for dir in self.ctx.empty_dirs.iter() {
            try!(clean_dir(&base.join(dir), false));
        }

        for dir in self.ctx.ensure_dirs.iter() {
            let fulldir = base.join(dir);
            try_msg!(create_dir(&fulldir, true),
                "Error creating dir: {err}");
        }

        try!(self.ctx.timelog.mark(format_args!("Finish"))
            .map_err(|e| format!("Can't write timelog: {}", e)));

        return Ok(());
    }
}
<commit_msg>fix /proc for build step commands<commit_after>use std::path::Path;

use builder::context::Context;
use builder::distrib::{Unknown,Distribution};
use builder::error::{Error};
use builder::commands::{composer, gem, npm, pip};
use builder::packages;
use build_step::BuildStep;
use container::util::clean_dir;
use container::mount::{unmount, mount_system_dirs, mount_proc};
use file_util::{create_dir, copy};

pub struct Guard<'a> {
    pub ctx: Context<'a>,
    pub distro: Box<Distribution>,
}

impl<'a> Guard<'a> {
    pub fn build(ctx: Context) -> Result<(), Error> {
        Guard {
            ctx: ctx,
            distro: Box::new(Unknown),
        }.run_process()
    }

    fn run_process(&mut self) -> Result<(), Error> {
        try!(self.start());

        for b in self.ctx.container_config.setup.iter() {
            debug!("Building step: {:?}", b);
            try!(self.ctx.timelog.mark(format_args!("Step: {:?}", b))
                .map_err(|e| format!("Can't write timelog: {}", e)));
            try!(b.build(self, true)
                .map_err(|e| Error::Step(b.0.clone(), e)));
        }

        try!(self.finish());
        Ok(())
    }

    pub fn start(&mut self) -> Result<(), String> {
        try!(mount_system_dirs());
        try!(mount_proc(&Path::new("/proc")));
        try_msg!(create_dir("/vagga/root/etc", false),
             "Error creating /etc dir: {err}");
        try!(copy("/etc/resolv.conf", "/vagga/root/etc/resolv.conf")
            .map_err(|e| format!("Error copying /etc/resolv.conf: {}", e)));
        try!(self.ctx.timelog.mark(format_args!("Prepare"))
            .map_err(|e| format!("Can't write timelog: {}", e)));
        Ok(())
    }

    pub fn finish(&mut self) -> Result<(), String> {
        // Pip
        if self.ctx.featured_packages.contains(&packages::PipPy2) ||
           self.ctx.featured_packages.contains(&packages::PipPy3)
        {
            try!(pip::freeze(&mut self.ctx));
        }
        // Npm
        if self.ctx.featured_packages.contains(&packages::Npm) {
            try!(npm::list(&mut self.ctx));
        }
        // Composer
        if self.ctx.featured_packages.contains(&packages::Composer) {
            try!(composer::finish(&mut self.ctx));
        }
        // Gem
        if self.ctx.featured_packages.contains(&packages::Bundler) {
            try!(gem::list(&mut self.ctx));
        }

        try!(self.distro.finish(&mut self.ctx));

        let base = Path::new("/vagga/root");

        for path in self.ctx.mounted.iter().rev() {
            try!(unmount(path));
        }

        for dir in self.ctx.remove_dirs.iter() {
            try!(clean_dir(&base.join(dir), true)
                .map_err(|e| format!("Error removing dir: {}", e)));
        }

        for dir in self.ctx.empty_dirs.iter() {
            try!(clean_dir(&base.join(dir), false));
        }

        for dir in self.ctx.ensure_dirs.iter() {
            let fulldir = base.join(dir);
            try_msg!(create_dir(&fulldir, true),
                "Error creating dir: {err}");
        }

        try!(self.ctx.timelog.mark(format_args!("Finish"))
            .map_err(|e| format!("Can't write timelog: {}", e)));

        return Ok(());
    }
}
<|endoftext|>


<commit_before>use crate::{cache::{
        GeneratorMask, LayerMask, Priority, PriorityCache, PriorityCacheEntry, SingularLayerType,
        TextureFormat, UnifiedPriorityCache,
    }, generate::ComputeShader, gpu_state::GpuState, terrain::quadtree::{QuadTree, VNode}};

pub(super) struct Entry {
    priority: Priority,
    node: VNode,
    pub(super) valid: bool,
    pub(super) generators: GeneratorMask,
}
impl Entry {
    fn new(node: VNode, priority: Priority) -> Self {
        Self { node, priority, valid: false, generators: GeneratorMask::empty() }
    }
}
impl PriorityCacheEntry for Entry {
    type Key = VNode;
    fn priority(&self) -> Priority {
        self.priority
    }
    fn key(&self) -> VNode {
        self.node
    }
}

#[repr(C)]
#[derive(Copy, Clone)]
pub(crate) struct SingularLayerGenerateUniforms {
    input_slot: u32,
    output_slot: u32,
}
unsafe impl bytemuck::Zeroable for SingularLayerGenerateUniforms {}
unsafe impl bytemuck::Pod for SingularLayerGenerateUniforms {}

pub(crate) struct SingularLayerDesc {
    pub generate: ComputeShader<SingularLayerGenerateUniforms>,
    pub cache_size: usize,
    pub dependency_mask: LayerMask,
    pub level: u8,
    pub ty: SingularLayerType,
    pub texture_resolution: u32,
    pub texture_format: TextureFormat,
}

pub(crate) struct SingularLayerCache {
    pub(super) inner: PriorityCache<Entry>,
    pub(super) desc: SingularLayerDesc,
}
impl SingularLayerCache {
    pub fn new(desc: SingularLayerDesc) -> Self {
        Self { inner: PriorityCache::new(desc.cache_size), desc }
    }

    pub fn update(&mut self, quadtree: &QuadTree) {
        // Update priorities
        for entry in self.inner.slots_mut() {
            entry.priority = quadtree.node_priority(entry.node);
        }
        let min_priority =
            self.inner.slots().iter().map(|s| s.priority).min().unwrap_or(Priority::none());

        // Find any tiles that may need to be added.
        let mut missing = Vec::new();
        VNode::breadth_first(|node| {
            let priority = quadtree.node_priority(node);
            if priority < Priority::cutoff() {
                return false;
            }
            if node.level() == self.desc.level
                && !self.inner.contains(&node)
                && (priority > min_priority || !self.inner.is_full())
            {
                missing.push(Entry::new(node, priority));
            }

            node.level() < self.desc.level
        });
        self.inner.insert(missing);
    }

    pub(super) fn generate_all(
        cache: &mut UnifiedPriorityCache,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        gpu_state: &GpuState,
    ) {
        let mut generated = Vec::new();
        let mut command_buffers = Vec::new();
        for layer_type in SingularLayerType::iter() {
            let m = &mut cache.textures[layer_type];

            let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some(&format!("{}.command_encoder", layer_type.name())),
            });

            for (index, entry) in m.inner.slots_mut().into_iter().enumerate() {
                if entry.valid || entry.priority < Priority::cutoff() {
                    continue;
                }
                if !cache.tiles.contains_all(entry.node, m.desc.dependency_mask) {
                    continue;
                }

                m.desc.generate.run(
                    device,
                    &mut encoder,
                    gpu_state,
                    ((m.desc.texture_resolution + 7) / 8, (m.desc.texture_resolution + 7) / 8, 1),
                    &SingularLayerGenerateUniforms {
                        input_slot: cache.tiles.get_slot(entry.node).unwrap() as u32,
                        output_slot: index as u32,
                    },
                );
                entry.valid = true;
                generated.push((layer_type, entry.node));
            }
            command_buffers.push(encoder.finish());
        }
        for (layer_type, node) in generated {
            cache.textures[layer_type].inner.entry_mut(&node).unwrap().generators =
                cache.generator_dependencies(node, cache.textures[layer_type].desc.dependency_mask);
        }

        queue.submit(command_buffers);
    }

    pub(super) fn make_cache_texture(&self, device: &wgpu::Device) -> (wgpu::Texture, wgpu::TextureView) {
        let texture = device.create_texture(&wgpu::TextureDescriptor {
            size: wgpu::Extent3d {
                width: self.desc.texture_resolution,
                height: self.desc.texture_resolution,
                depth_or_array_layers: self.desc.cache_size as u32,
            },
            format: self.desc.texture_format.to_wgpu(device.features()),
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            usage: wgpu::TextureUsage::COPY_SRC
                | wgpu::TextureUsage::COPY_DST
                | wgpu::TextureUsage::SAMPLED
                | if !self.desc.texture_format.is_compressed() {
                    wgpu::TextureUsage::STORAGE
                } else {
                    wgpu::TextureUsage::empty()
                },
            label: Some(&format!("texture.singular.{}", self.desc.ty.name())),
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor {
            label: Some(&format!("texture.singular.{}.view", self.desc.ty.name())),
            ..Default::default()
        });
        (texture, view)
    }
}
<commit_msg>Delete SingularTextureCache<commit_after><|endoftext|>


<commit_before>use redox::*;

// TODO: Structure using loops

use super::Mode;
use super::Mode::*;
use super::Editor;

pub fn exec(editor: &mut Editor, mode: &mut Mode, multiplier: &mut Option<u32>, last_change: &mut String, key_event: KeyEvent, window: &mut Window, swap: &mut usize, period: &mut String, is_recording: &mut bool) {
    match (*mode, key_event.scancode) {
        (Insert, K_ESC) => {
            *mode = Normal;
        },
        (Insert, K_BKSP) => editor.backspace(window),
        (Insert, K_DEL) => editor.delete(window),
        (_, K_F5) => editor.reload(window),
        (_, K_F6) => editor.save(window),
        (_, K_HOME) => editor.offset = 0,
        (_, K_UP) => editor.up(),
        (_, K_LEFT) => editor.left(),
        (_, K_RIGHT) => editor.right(),
        (_, K_END) => editor.offset = editor.string.len(),
        (_, K_DOWN) => editor.down(),
        (m, _) => {
            let (no_mult, mut times) = match *multiplier {
                Some(n) => (false, n),
                None => (true, 1),
            };
            let mut is_none = false;

            match (*mode, key_event.character) {
                (Normal, '0') if !no_mult => times *= 10,

                (Normal, '1') if no_mult => times = 1,
                (Normal, '1') => times = times * 10 + 1,

                (Normal, '2') if no_mult => times = 2,
                (Normal, '2') => times = times * 10 + 2,

                (Normal, '3') if no_mult => times = 3,
                (Normal, '3') => times = times * 10 + 3,

                (Normal, '4') if no_mult => times = 4,
                (Normal, '4') => times = times * 10 + 4,

                (Normal, '5') if no_mult => times = 5,
                (Normal, '5') => times = times * 10 + 5,

                (Normal, '6') if no_mult => times = 6,
                (Normal, '6') => times = times * 10 + 6,

                (Normal, '7') if no_mult => times = 7,
                (Normal, '7') => times = times * 10 + 7,

                (Normal, '8') if no_mult => times = 8,
                (Normal, '8') => times = times * 10 + 8,

                (Normal, '9') if no_mult => times = 9,
                (Normal, '9') => times = times * 10 + 9,
                (_, _) => {
                    if *is_recording {
                        if key_event.character == ',' {
                            *is_recording = false;
                        } else {
                            period.push(key_event.character);
                        }
                    } else {
                        for _ in 0 .. times {
                            match (m, key_event.character) {
                                (Normal, 'i') => {
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'h') => editor.left(),
                                (Normal, 'l') => editor.right(),
                                (Normal, 'k') => editor.up(),
                                (Normal, 'j') => editor.down(),
                                (Normal, 'K') => {
                                    for _ in 1..15 {
                                        editor.up();
                                    }
                                },
                                (Normal, 'J') => {
                                    for _ in 1..15 {
                                        editor.down();
                                    }
                                },
                                (Normal, 'g') => editor.offset = 0,
                                (Normal, 'G') => editor.offset = editor.string.len(),
                                (Normal, 'a') => {
                                    editor.right();
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'x') => editor.delete(window),
                                (Normal, 'X') => editor.backspace(window),
                                (Normal, 'u') => {
                                    editor.offset = 0;
                                    ::core::mem::swap(last_change, &mut editor.string);
                                },
                                (Normal, 'c') => {
                                    ::core::mem::swap(&mut editor.offset, swap);
                                },
                                (Normal, 's') => {
                                    editor.delete(window);
                                    *mode = Insert;
                                },
                                (Normal, 'o') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                    editor.insert('\n', window);
                                    *mode = Insert;
                                },
                                (Normal, 'O') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset >= 1 {
                                        editor.left();
                                    }
                                    editor.insert('\n', window);
                                    editor.left();
                                    *mode = Insert;
                                },
                                (Normal, '^') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset <= 0 {
                                        editor.left();
                                    }
                                    editor.right();
                                    while (editor.cur() == ' ' ||
                                          editor.cur() == '\t') &&
                                          editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                },
                                (Normal, '$') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                },
                                (Normal, '0') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset >= 1 {
                                        editor.left();
                                    }
                                    editor.right();
                                },
                                (Normal, 'd') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset < editor.string.len() {
                                        editor.delete(window);
                                    }
                                },
                                (Normal, 'w') => {
                                    editor.save(window);
                                },
                                (Normal, 'e') => {
                                    editor.right();
                                    while editor.cur() != '.' &&
                                          editor.cur() != '{' &&
                                          editor.cur() != ',' &&
                                          editor.cur() != ' ' &&
                                          editor.cur() != '}' &&
                                          editor.cur() != '(' &&
                                          editor.cur() != ')' &&
                                          editor.cur() != '[' &&
                                          editor.cur() != ']' &&
                                          editor.cur() != ';' &&
                                          editor.cur() != '"' &&
                                          editor.cur() != '\'' &&
                                          editor.cur() != '\n' &&
                                          editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                },
                                (Normal, 'b') => {
                                    editor.left();
                                    while editor.cur() != '.' &&
                                          editor.cur() != '{' &&
                                          editor.cur() != ',' &&
                                          editor.cur() != ' ' &&
                                          editor.cur() != '}' &&
                                          editor.cur() != '(' &&
                                          editor.cur() != ')' &&
                                          editor.cur() != '[' &&
                                          editor.cur() != ']' &&
                                          editor.cur() != ';' &&
                                          editor.cur() != '"' &&
                                          editor.cur() != '\'' &&
                                          editor.cur() != '\n' &&
                                          editor.offset < editor.string.len() {
                                        editor.left();
                                    }
                                },
                                (Normal, 'E') => {
                                    editor.right();
                                    while editor.cur() != ' ' && editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                },
                                (Normal, 'B') => {
                                    editor.left();
                                    while editor.cur() != ' ' && editor.offset < editor.string.len() {
                                        editor.left();
                                    }
                                },
                                (Normal, ',') => {
                                    *is_recording = true;
                                    *period = String::new();
                                },
                                (Normal, '%') => {
                                    match editor.cur() {
                                        '(' | '[' | '{' => {
                                            let mut i = 1;
                                            while i != 0 {
                                                editor.right();
                                                i += match editor.cur() {
                                                    '(' | '[' | '{' => 1,
                                                    ')' | ']' | '}' => -1,
                                                    _ => 0,
                                                };
                                                if editor.offset < editor.string.len() {
                                                    break;
                                                }
                                            }
                                        },
                                        ')' | ']' | '}' => {
                                            let mut i = 1;
                                            while i != 0 {
                                                editor.left();
                                                i += match editor.cur() {
                                                    '(' | '[' | '{' => -1,
                                                    ')' | ']' | '}' => 1,
                                                    _ => 0,
                                                };
                                                if editor.offset < editor.string.len() {
                                                    break;
                                                }
                                            }
                                        },
                                        _ => {},

                                    }
                                },
                                (Normal, '!') => {
                                    for c in period.clone().chars() {
                                        exec(editor, mode, multiplier, last_change, KeyEvent {
                                            character: c,
                                            scancode: 0,
                                            pressed: true,
                                        }, window, swap, period, is_recording);
                                    }
                                },
                                (Insert, '\0') => (),
                                (Insert, c) => {
                                    editor.insert(c, window);
                                },
                                _ => {},
                            }
                        }
                    }
                    is_none = true;
                }
            }

            if !is_none {
                *multiplier = Some(times);
            } else {
                *multiplier = None;
            }
        }
    }
}
<commit_msg>Fix while loops<commit_after>use redox::*;

// TODO: Structure using loops

use super::Mode;
use super::Mode::*;
use super::Editor;

pub fn exec(editor: &mut Editor, mode: &mut Mode, multiplier: &mut Option<u32>, last_change: &mut String, key_event: KeyEvent, window: &mut Window, swap: &mut usize, period: &mut String, is_recording: &mut bool) {
    match (*mode, key_event.scancode) {
        (Insert, K_ESC) => {
            *mode = Normal;
        },
        (Insert, K_BKSP) => editor.backspace(window),
        (Insert, K_DEL) => editor.delete(window),
        (_, K_F5) => editor.reload(window),
        (_, K_F6) => editor.save(window),
        (_, K_HOME) => editor.offset = 0,
        (_, K_UP) => editor.up(),
        (_, K_LEFT) => editor.left(),
        (_, K_RIGHT) => editor.right(),
        (_, K_END) => editor.offset = editor.string.len(),
        (_, K_DOWN) => editor.down(),
        (m, _) => {
            let (no_mult, mut times) = match *multiplier {
                Some(n) => (false, n),
                None => (true, 1),
            };
            let mut is_none = false;

            match (*mode, key_event.character) {
                (Normal, '0') if !no_mult => times *= 10,

                (Normal, '1') if no_mult => times = 1,
                (Normal, '1') => times = times * 10 + 1,

                (Normal, '2') if no_mult => times = 2,
                (Normal, '2') => times = times * 10 + 2,

                (Normal, '3') if no_mult => times = 3,
                (Normal, '3') => times = times * 10 + 3,

                (Normal, '4') if no_mult => times = 4,
                (Normal, '4') => times = times * 10 + 4,

                (Normal, '5') if no_mult => times = 5,
                (Normal, '5') => times = times * 10 + 5,

                (Normal, '6') if no_mult => times = 6,
                (Normal, '6') => times = times * 10 + 6,

                (Normal, '7') if no_mult => times = 7,
                (Normal, '7') => times = times * 10 + 7,

                (Normal, '8') if no_mult => times = 8,
                (Normal, '8') => times = times * 10 + 8,

                (Normal, '9') if no_mult => times = 9,
                (Normal, '9') => times = times * 10 + 9,
                (_, _) => {
                    if *is_recording {
                        if key_event.character == ',' {
                            *is_recording = false;
                        } else {
                            period.push(key_event.character);
                        }
                    } else {
                        for _ in 0 .. times {
                            match (m, key_event.character) {
                                (Normal, 'i') => {
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'h') => editor.left(),
                                (Normal, 'l') => editor.right(),
                                (Normal, 'k') => editor.up(),
                                (Normal, 'j') => editor.down(),
                                (Normal, 'K') => {
                                    for _ in 1..15 {
                                        editor.up();
                                    }
                                },
                                (Normal, 'J') => {
                                    for _ in 1..15 {
                                        editor.down();
                                    }
                                },
                                (Normal, 'g') => editor.offset = 0,
                                (Normal, 'G') => editor.offset = editor.string.len(),
                                (Normal, 'a') => {
                                    editor.right();
                                    *mode = Insert;
                                    *last_change = editor.string.clone();
                                },
                                (Normal, 'x') => editor.delete(window),
                                (Normal, 'X') => editor.backspace(window),
                                (Normal, 'u') => {
                                    editor.offset = 0;
                                    ::core::mem::swap(last_change, &mut editor.string);
                                },
                                (Normal, 'c') => {
                                    ::core::mem::swap(&mut editor.offset, swap);
                                },
                                (Normal, 's') => {
                                    editor.delete(window);
                                    *mode = Insert;
                                },
                                (Normal, 'o') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                    editor.insert('\n', window);
                                    *mode = Insert;
                                },
                                (Normal, 'O') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset >= 1 {
                                        editor.left();
                                    }
                                    editor.insert('\n', window);
                                    editor.left();
                                    *mode = Insert;
                                },
                                (Normal, '^') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset <= 0 {
                                        editor.left();
                                    }
                                    editor.right();
                                    while (editor.cur() == ' ' ||
                                          editor.cur() == '\t') &&
                                          editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                },
                                (Normal, '$') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                },
                                (Normal, '0') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset >= 1 {
                                        editor.left();
                                    }
                                    editor.right();
                                },
                                (Normal, 'd') => {
                                    while editor.cur() != '\n' &&
                                          editor.cur() != '\0' &&
                                          editor.offset < editor.string.len() {
                                        editor.delete(window);
                                    }
                                },
                                (Normal, 'w') => {
                                    editor.save(window);
                                },
                                (Normal, 'e') => {
                                    editor.right();
                                    while editor.cur() != '.' &&
                                          editor.cur() != '{' &&
                                          editor.cur() != ',' &&
                                          editor.cur() != ' ' &&
                                          editor.cur() != '}' &&
                                          editor.cur() != '(' &&
                                          editor.cur() != ')' &&
                                          editor.cur() != '[' &&
                                          editor.cur() != ']' &&
                                          editor.cur() != ';' &&
                                          editor.cur() != '"' &&
                                          editor.cur() != '\'' &&
                                          editor.cur() != '\n' &&
                                          editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                },
                                (Normal, 'b') => {
                                    editor.left();
                                    while editor.cur() != '.' &&
                                          editor.cur() != '{' &&
                                          editor.cur() != ',' &&
                                          editor.cur() != ' ' &&
                                          editor.cur() != '}' &&
                                          editor.cur() != '(' &&
                                          editor.cur() != ')' &&
                                          editor.cur() != '[' &&
                                          editor.cur() != ']' &&
                                          editor.cur() != ';' &&
                                          editor.cur() != '"' &&
                                          editor.cur() != '\'' &&
                                          editor.cur() != '\n' &&
                                          editor.offset >= 1 {
                                        editor.left();
                                    }
                                },
                                (Normal, 'E') => {
                                    editor.right();
                                    while editor.cur() != ' ' && editor.offset < editor.string.len() {
                                        editor.right();
                                    }
                                },
                                (Normal, 'B') => {
                                    editor.left();
                                    while editor.cur() != ' ' && editor.offset >= 1 {
                                        editor.left();
                                    }
                                },
                                (Normal, ',') => {
                                    *is_recording = true;
                                    *period = String::new();
                                },
                                (Normal, '%') => {
                                    match editor.cur() {
                                        '(' | '[' | '{' => {
                                            let mut i = 1;
                                            while i != 0 {
                                                editor.right();
                                                i += match editor.cur() {
                                                    '(' | '[' | '{' => 1,
                                                    ')' | ']' | '}' => -1,
                                                    _ => 0,
                                                };
                                                if editor.offset < editor.string.len() {
                                                    break;
                                                }
                                            }
                                        },
                                        ')' | ']' | '}' => {
                                            let mut i = 1;
                                            while i != 0 {
                                                editor.left();
                                                i += match editor.cur() {
                                                    '(' | '[' | '{' => -1,
                                                    ')' | ']' | '}' => 1,
                                                    _ => 0,
                                                };
                                                if editor.offset >= 0 {
                                                    break;
                                                }
                                            }
                                        },
                                        _ => {},

                                    }
                                },
                                (Normal, '!') => {
                                    for c in period.clone().chars() {
                                        exec(editor, mode, multiplier, last_change, KeyEvent {
                                            character: c,
                                            scancode: 0,
                                            pressed: true,
                                        }, window, swap, period, is_recording);
                                    }
                                },
                                (Insert, '\0') => (),
                                (Insert, c) => {
                                    editor.insert(c, window);
                                },
                                _ => {},
                            }
                        }
                    }
                    is_none = true;
                }
            }

            if !is_none {
                *multiplier = Some(times);
            } else {
                *multiplier = None;
            }
        }
    }
}
<|endoftext|>


<commit_before>enum DataType {
    Unknown = 0,
    Boolean,
    Byte,
    Int16,
    Uint16,
    Int32,
    Uint32,
    Int64,
    Uint64,
    String, // TODO: What to name this string type?
    ByteArray,
    Int16Array,
    Uint16Array,
    Int32Array,
    Uint32Array,
    Int64Array,
    Uint64Array,
    StringArray,
    Hrtime,
    Nvlist, // TODO: What to name this ?
    NvlistArray,
    BooleanValue,
    Int8,
    Uint8,
    BooleanArray,
    Int8Array,
    Uint8Array
}

struct NvPair {
    nvp_size:       i32, // size of this nvpair
    nvp_name_sz:    i16, // length of name string
    nvp_reserve:    i16, // not used
    nvp_value_elem: i32, // number of elements for array types
    nvp_type:       DataType, // type of value
    // name string
    // aligned ptr array for string arrays
    // aligned array of data for value
}

// nvlist header
struct NvList {
    nvl_version: i32
    nvl_nvflag:  u32 // persistent flags
    nvl_priv:    u64 // ptr to private data if not packed
    nvl_flag:    u32
    nvl_pad:     i32 // currently not used, for alignment
}

// nvp implementation version
const NV_VERSION: i32 = 0;

// nvlist pack encoding
const NV_ENCODE_NATIVE: u8 = 0;
const NV_ENCODE_XDR:    u8 = 1;

// nvlist persistent unique name flags, stored in nvl_nvflags
const NV_UNIQUE_NAME:      u32 = 0x1;
const NV_UNIQUE_NAME_TYPE: u32 = 0x2;

// nvlist lookup pairs related flags
const NV_FLAG_NOENTOK: isize = 0x1;

/* What to do about these macros?
// convenience macros
#define NV_ALIGN(x)     (((ulong_t)(x) + 7ul) & ~7ul)
#define NV_ALIGN4(x)        (((x) + 3) & ~3)

#define NVP_SIZE(nvp)       ((nvp)->nvp_size)
#define NVP_NAME(nvp)       ((char *)(nvp) + sizeof (nvpair_t))
#define NVP_TYPE(nvp)       ((nvp)->nvp_type)
#define NVP_NELEM(nvp)      ((nvp)->nvp_value_elem)
#define NVP_VALUE(nvp)      ((char *)(nvp) + NV_ALIGN(sizeof (nvpair_t) \
                + (nvp)->nvp_name_sz))

#define NVL_VERSION(nvl)    ((nvl)->nvl_version)
#define NVL_SIZE(nvl)       ((nvl)->nvl_size)
#define NVL_FLAG(nvl)       ((nvl)->nvl_flag)
*/

// NV allocator framework
struct NvAllocOps;

struct NvAlloc<> {
    nva_ops: &'static NvAllocOps,
    nva_arg: Any, // This was a void pointer type.
                  // Not sure if Any is the correct type.
}

struct NvAllocOps {
    int (*nv_ao_init)(nv_alloc_t *, __va_list);
    void (*nv_ao_fini)(nv_alloc_t *);
    void *(*nv_ao_alloc)(nv_alloc_t *, size_t);
    void (*nv_ao_free)(nv_alloc_t *, void *, size_t);
    void (*nv_ao_reset)(nv_alloc_t *);
}
<commit_msg>Forgot to comment out unrustified code<commit_after>enum DataType {
    Unknown = 0,
    Boolean,
    Byte,
    Int16,
    Uint16,
    Int32,
    Uint32,
    Int64,
    Uint64,
    String, // TODO: What to name this string type?
    ByteArray,
    Int16Array,
    Uint16Array,
    Int32Array,
    Uint32Array,
    Int64Array,
    Uint64Array,
    StringArray,
    Hrtime,
    Nvlist, // TODO: What to name this ?
    NvlistArray,
    BooleanValue,
    Int8,
    Uint8,
    BooleanArray,
    Int8Array,
    Uint8Array
}

struct NvPair {
    nvp_size:       i32, // size of this nvpair
    nvp_name_sz:    i16, // length of name string
    nvp_reserve:    i16, // not used
    nvp_value_elem: i32, // number of elements for array types
    nvp_type:       DataType, // type of value
    // name string
    // aligned ptr array for string arrays
    // aligned array of data for value
}

// nvlist header
struct NvList {
    nvl_version: i32
    nvl_nvflag:  u32 // persistent flags
    nvl_priv:    u64 // ptr to private data if not packed
    nvl_flag:    u32
    nvl_pad:     i32 // currently not used, for alignment
}

// nvp implementation version
const NV_VERSION: i32 = 0;

// nvlist pack encoding
const NV_ENCODE_NATIVE: u8 = 0;
const NV_ENCODE_XDR:    u8 = 1;

// nvlist persistent unique name flags, stored in nvl_nvflags
const NV_UNIQUE_NAME:      u32 = 0x1;
const NV_UNIQUE_NAME_TYPE: u32 = 0x2;

// nvlist lookup pairs related flags
const NV_FLAG_NOENTOK: isize = 0x1;

/* What to do about these macros?
// convenience macros
#define NV_ALIGN(x)     (((ulong_t)(x) + 7ul) & ~7ul)
#define NV_ALIGN4(x)        (((x) + 3) & ~3)

#define NVP_SIZE(nvp)       ((nvp)->nvp_size)
#define NVP_NAME(nvp)       ((char *)(nvp) + sizeof (nvpair_t))
#define NVP_TYPE(nvp)       ((nvp)->nvp_type)
#define NVP_NELEM(nvp)      ((nvp)->nvp_value_elem)
#define NVP_VALUE(nvp)      ((char *)(nvp) + NV_ALIGN(sizeof (nvpair_t) \
                + (nvp)->nvp_name_sz))

#define NVL_VERSION(nvl)    ((nvl)->nvl_version)
#define NVL_SIZE(nvl)       ((nvl)->nvl_size)
#define NVL_FLAG(nvl)       ((nvl)->nvl_flag)
*/

// NV allocator framework
struct NvAllocOps;

struct NvAlloc<> {
    nva_ops: &'static NvAllocOps,
    nva_arg: Any, // This was a void pointer type.
                  // Not sure if Any is the correct type.
}

/*
struct NvAllocOps {
    int (*nv_ao_init)(nv_alloc_t *, __va_list);
    void (*nv_ao_fini)(nv_alloc_t *);
    void *(*nv_ao_alloc)(nv_alloc_t *, size_t);
    void (*nv_ao_free)(nv_alloc_t *, void *, size_t);
    void (*nv_ao_reset)(nv_alloc_t *);
}
*/
<|endoftext|>


<commit_before>use cocoa::base::{id, nil};
use cocoa::foundation::NSString;
use std::borrow::Cow;
use std::convert::AsRef;
use std::error::Error;
use std::ffi::CStr;
use std::fmt::{self, Display, Formatter};
use std::marker::{Send, Sync};
use sys::MTLCommandQueue;
use {CommandBuffer, FromRaw, FromRawError};

pub struct CommandQueue(id);

unsafe impl Send for CommandQueue {}
unsafe impl Sync for CommandQueue {}

impl CommandQueue {
    pub fn command_buffer(&mut self) -> CommandBuffer {
        let cmd_buf = unsafe { self.0.commandBuffer() };
        FromRaw::from_raw(cmd_buf).unwrap()
    }

    pub fn command_buffer_with_unretained_references(&mut self) -> CommandBuffer {
        let cmd_buf = unsafe { self.0.commandBufferWithUnretainedReferences() };
        FromRaw::from_raw(cmd_buf).unwrap()
    }

    pub fn insert_debug_capture_boundary(&mut self) {
        unsafe {
            self.0.insertDebugCaptureBoundary();
        }
    }

    pub fn set_label<S: AsRef<str>>(&mut self, label: S) {
        unsafe { self.0.setLabel(NSString::alloc(nil).init_str(label.as_ref())) }
    }

    pub fn label(&self) -> Cow<str> {
        unsafe { CStr::from_ptr(self.0.label().UTF8String()).to_string_lossy() }
    }
}

impl_from_into_raw!(CommandQueue, of protocol "MTLCommandQueue");

#[derive(Clone, Debug)]
pub enum CommandQueueError {
    CouldNotCreate
}

impl Display for CommandQueueError {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let descr = match *self {
            CommandQueueError::CouldNotCreate => "DeviceError::CouldNotCreate",
        };
        write!(f, "{}", descr)
    }
}

impl Error for CommandQueueError {
    fn description(&self) -> &str {
        match *self {
            CommandQueueError::CouldNotCreate => "Could not create command queue.",
        }
    }
}

impl From<FromRawError> for CommandQueueError {
    fn from(_: FromRawError) -> Self {
        CommandQueueError::CouldNotCreate
    }
}
<commit_msg>Rename CommandQueue methods which create a CommandBuffer to prefix them with new<commit_after>use cocoa::base::{id, nil};
use cocoa::foundation::NSString;
use std::borrow::Cow;
use std::convert::AsRef;
use std::error::Error;
use std::ffi::CStr;
use std::fmt::{self, Display, Formatter};
use std::marker::{Send, Sync};
use sys::MTLCommandQueue;
use {CommandBuffer, FromRaw, FromRawError};

pub struct CommandQueue(id);

unsafe impl Send for CommandQueue {}
unsafe impl Sync for CommandQueue {}

impl CommandQueue {
    pub fn new_command_buffer(&mut self) -> CommandBuffer {
        let cmd_buf = unsafe { self.0.commandBuffer() };
        FromRaw::from_raw(cmd_buf).unwrap()
    }

    pub fn new_command_buffer_with_unretained_references(&mut self) -> CommandBuffer {
        let cmd_buf = unsafe { self.0.commandBufferWithUnretainedReferences() };
        FromRaw::from_raw(cmd_buf).unwrap()
    }

    pub fn insert_debug_capture_boundary(&mut self) {
        unsafe {
            self.0.insertDebugCaptureBoundary();
        }
    }

    pub fn set_label<S: AsRef<str>>(&mut self, label: S) {
        unsafe { self.0.setLabel(NSString::alloc(nil).init_str(label.as_ref())) }
    }

    pub fn label(&self) -> Cow<str> {
        unsafe { CStr::from_ptr(self.0.label().UTF8String()).to_string_lossy() }
    }
}

impl_from_into_raw!(CommandQueue, of protocol "MTLCommandQueue");

#[derive(Clone, Debug)]
pub enum CommandQueueError {
    CouldNotCreate
}

impl Display for CommandQueueError {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let descr = match *self {
            CommandQueueError::CouldNotCreate => "DeviceError::CouldNotCreate",
        };
        write!(f, "{}", descr)
    }
}

impl Error for CommandQueueError {
    fn description(&self) -> &str {
        match *self {
            CommandQueueError::CouldNotCreate => "Could not create command queue.",
        }
    }
}

impl From<FromRawError> for CommandQueueError {
    fn from(_: FromRawError) -> Self {
        CommandQueueError::CouldNotCreate
    }
}
<|endoftext|>