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

#![feature(plugin)]
#![cfg_attr(feature = "dev", plugin(clippy))]

/// Inject failures to `TikV`.
///
/// TODO: Integrate into tikv-ctl.
///
/// # Examples
///
/// ```sh
/// ./tikv-fail -a 127.0.0.1:9090 inject\
//      tikv::raftstore::store::store::raft_between_save=panic
/// ```
///

extern crate tikv;
extern crate clap;
extern crate grpcio as grpc;
extern crate protobuf;
extern crate kvproto;

use std::fs;
use std::io::{BufRead, BufReader};
use std::str;
use std::time::Duration;
use std::sync::Arc;

use clap::{App, Arg, SubCommand};
use grpc::{CallOption, ChannelBuilder, EnvBuilder};
use kvproto::debugpb;
use kvproto::debugpb_grpc::DebugClient;

fn main() {
    let app = App::new("TiKV fail point")
        .author("PingCAP")
        .about("A tool for injecting failures to TiKV and recovery")
        .arg(
            Arg::with_name("addr")
                .short("a")
                .takes_value(true)
                .help("set tikv ip:port"),
        )
        .subcommand(
            SubCommand::with_name("inject")
                .about("Inject failures")
                .arg(
                    Arg::with_name("args")
                        .multiple(true)
                        .takes_value(true)
                        .help(
                            "Inject fail point and actions pairs.\
                             E.g. tikv-fail inject fail::a=off fail::b=panic",
                        ),
                )
                .arg(
                    Arg::with_name("file")
                        .short("f")
                        .takes_value(true)
                        .help("Read a file of fail points and actions to inject"),
                ),
        )
        .subcommand(
            SubCommand::with_name("recover")
                .about("Recover failures")
                .arg(
                    Arg::with_name("args")
                        .multiple(true)
                        .takes_value(true)
                        .help("Recover fail points. Eg. tikv-fail recover fail::a fail::b"),
                )
                .arg(
                    Arg::with_name("file")
                        .short("f")
                        .takes_value(true)
                        .help("Recover from a file of fail points"),
                ),
        )
        .subcommand(SubCommand::with_name("list").about("List all fail points"));
    let matches = app.clone().get_matches();
    let addr = matches.value_of("addr").unwrap();
    let addr = addr.trim_left_matches("http://");

    let env = Arc::new(EnvBuilder::new().name_prefix("tikv-fail").build());
    let channel = ChannelBuilder::new(env).connect(addr);
    let client = DebugClient::new(channel);

    if let Some(matches) = matches.subcommand_matches("inject") {
        let mut list = matches.value_of("file").map_or_else(Vec::new, read_file);
        if let Some(ps) = matches.values_of("args") {
            for pair in ps {
                let mut parts = pair.split('=');
                list.push((
                    parts.next().unwrap().to_owned(),
                    parts.next().unwrap_or("").to_owned(),
                ))
            }
        }

        for (name, actions) in list {
            if actions.is_empty() {
                println!("No action for fail point {}", name);
                continue;
            }
            let mut inject_req = debugpb::InjectFailPointRequest::new();
            inject_req.set_name(name);
            inject_req.set_actions(actions);

            let option = CallOption::default().timeout(Duration::from_secs(10));
            client.inject_fail_point_opt(inject_req, option).unwrap();
        }
    } else if let Some(matches) = matches.subcommand_matches("recover") {
        let mut list = matches.value_of("file").map_or_else(Vec::new, read_file);
        if let Some(fps) = matches.values_of("args") {
            for fp in fps {
                list.push((fp.to_owned(), "".to_owned()))
            }
        }

        for (name, _) in list {
            let mut recover_req = debugpb::RecoverFailPointRequest::new();
            recover_req.set_name(name);

            let option = CallOption::default().timeout(Duration::from_secs(10));
            client.recover_fail_point_opt(recover_req, option).unwrap();
        }
    } else if matches.is_present("list") {
        let list_req = debugpb::ListFailPointsRequest::new();
        let option = CallOption::default().timeout(Duration::from_secs(10));
        let resp = client.list_fail_points_opt(list_req, option).unwrap();
        println!("{:?}", resp.get_entries());
    }
}

fn read_file(path: &str) -> Vec<(String, String)> {
    let f = fs::File::open(path).unwrap();
    let f = BufReader::new(f);

    let mut list = vec![];
    for line in f.lines() {
        let line = line.unwrap();
        let mut parts = line.split('=');
        list.push((
            parts.next().unwrap().to_owned(),
            parts.next().unwrap_or("").to_owned(),
        ))
    }
    list
}
<commit_msg>tikv-fail: change addr arg to required (#2602)<commit_after>// Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.

#![feature(plugin)]
#![cfg_attr(feature = "dev", plugin(clippy))]

/// Inject failures to `TikV`.
///
/// TODO: Integrate into tikv-ctl.
///
/// # Examples
///
/// ```sh
/// ./tikv-fail -a 127.0.0.1:9090 inject\
//      tikv::raftstore::store::store::raft_between_save=panic
/// ```
///

extern crate tikv;
extern crate clap;
extern crate grpcio as grpc;
extern crate protobuf;
extern crate kvproto;

use std::fs;
use std::io::{BufRead, BufReader};
use std::str;
use std::time::Duration;
use std::sync::Arc;

use clap::{App, Arg, SubCommand};
use grpc::{CallOption, ChannelBuilder, EnvBuilder};
use kvproto::debugpb;
use kvproto::debugpb_grpc::DebugClient;

fn main() {
    let app = App::new("TiKV fail point")
        .author("PingCAP")
        .about("A tool for injecting failures to TiKV and recovery")
        .arg(
            Arg::with_name("addr")
                .required(true)
                .short("a")
                .takes_value(true)
                .help("set tikv ip:port"),
        )
        .subcommand(
            SubCommand::with_name("inject")
                .about("Inject failures")
                .arg(
                    Arg::with_name("args")
                        .multiple(true)
                        .takes_value(true)
                        .help(
                            "Inject fail point and actions pairs.\
                             E.g. tikv-fail inject fail::a=off fail::b=panic",
                        ),
                )
                .arg(
                    Arg::with_name("file")
                        .short("f")
                        .takes_value(true)
                        .help("Read a file of fail points and actions to inject"),
                ),
        )
        .subcommand(
            SubCommand::with_name("recover")
                .about("Recover failures")
                .arg(
                    Arg::with_name("args")
                        .multiple(true)
                        .takes_value(true)
                        .help("Recover fail points. Eg. tikv-fail recover fail::a fail::b"),
                )
                .arg(
                    Arg::with_name("file")
                        .short("f")
                        .takes_value(true)
                        .help("Recover from a file of fail points"),
                ),
        )
        .subcommand(SubCommand::with_name("list").about("List all fail points"));
    let matches = app.clone().get_matches();
    let addr = matches.value_of("addr").unwrap();
    let addr = addr.trim_left_matches("http://");

    let env = Arc::new(EnvBuilder::new().name_prefix("tikv-fail").build());
    let channel = ChannelBuilder::new(env).connect(addr);
    let client = DebugClient::new(channel);

    if let Some(matches) = matches.subcommand_matches("inject") {
        let mut list = matches.value_of("file").map_or_else(Vec::new, read_file);
        if let Some(ps) = matches.values_of("args") {
            for pair in ps {
                let mut parts = pair.split('=');
                list.push((
                    parts.next().unwrap().to_owned(),
                    parts.next().unwrap_or("").to_owned(),
                ))
            }
        }

        for (name, actions) in list {
            if actions.is_empty() {
                println!("No action for fail point {}", name);
                continue;
            }
            let mut inject_req = debugpb::InjectFailPointRequest::new();
            inject_req.set_name(name);
            inject_req.set_actions(actions);

            let option = CallOption::default().timeout(Duration::from_secs(10));
            client.inject_fail_point_opt(inject_req, option).unwrap();
        }
    } else if let Some(matches) = matches.subcommand_matches("recover") {
        let mut list = matches.value_of("file").map_or_else(Vec::new, read_file);
        if let Some(fps) = matches.values_of("args") {
            for fp in fps {
                list.push((fp.to_owned(), "".to_owned()))
            }
        }

        for (name, _) in list {
            let mut recover_req = debugpb::RecoverFailPointRequest::new();
            recover_req.set_name(name);

            let option = CallOption::default().timeout(Duration::from_secs(10));
            client.recover_fail_point_opt(recover_req, option).unwrap();
        }
    } else if matches.is_present("list") {
        let list_req = debugpb::ListFailPointsRequest::new();
        let option = CallOption::default().timeout(Duration::from_secs(10));
        let resp = client.list_fail_points_opt(list_req, option).unwrap();
        println!("{:?}", resp.get_entries());
    }
}

fn read_file(path: &str) -> Vec<(String, String)> {
    let f = fs::File::open(path).unwrap();
    let f = BufReader::new(f);

    let mut list = vec![];
    for line in f.lines() {
        let line = line.unwrap();
        let mut parts = line.split('=');
        list.push((
            parts.next().unwrap().to_owned(),
            parts.next().unwrap_or("").to_owned(),
        ))
    }
    list
}
<|endoftext|>


<commit_before>table! {
	repositories(name) {
		name -> Text,
		path -> Text,
	}
}
<commit_msg>Run rustfmt<commit_after>table! {
    repositories(name) {
        name -> Text,
        path -> Text,
    }
}
<|endoftext|>


<commit_before>use std::collections::HashMap;
use std::error;

use super::row::{Row, RowError};
use super::schema::{Schema, Type};
use super::value::Value;
pub use super::row_builder::RowBuilder;

#[derive(Debug)]
pub enum StreamError {
    ValidationError(String),
    FieldNotFound(String),
    MissingRowId
}

impl From<RowError> for StreamError {
    fn from(err: RowError) -> StreamError {
        StreamError::MissingRowId
    }

}

#[derive(Debug)]
pub struct Stream {
    inserts: u64, // total number of inserts this Stream has seen
    lowest_id: Option<u64>,  // lowest id we still have in the Stream
    ttl: Option<u64>,
    rows: HashMap<u64, Row>,
    schema: Schema,

}

/**
This is a weird DB.  There's no primary key, since everything is based off append only streaming

*/
impl Stream {
    pub fn new() -> Stream {
        let mut stream = Stream::new_empty();
        stream.schema.add_type("_id", Type::Int);
        stream.schema.add_type("_created", Type::Timestamp);
        stream
    }

    // used in temporary tables
    pub fn new_empty() -> Stream {
        let mut stream = Stream {
            inserts: 0,
            lowest_id: None,
            rows: HashMap::new(),
            schema: Schema::new(),
            ttl: None,
        };
        stream
    }

    /* we take a HashMap of String -> Field here
    * we're going to convert it to HashMap<u8, Field> for the Row struct
    */
    pub fn insert(&mut self, mut row_builder: RowBuilder) -> Result<u64, StreamError> {
        // validate the inserted data
        let mut row_map : HashMap<u8, Value> = HashMap::new();
        for (key, val) in row_builder.data.drain() {
            // get the field from the schema
            // TypeDef
            let tmp = try!(self.schema.get(&key)
                               .ok_or(StreamError::FieldNotFound(key.to_string())));
            row_map.insert(tmp.id, val);

        }
        let row_id = self.inserts;
        let row = try!(Row::new(row_map));
        self.rows.insert(self.inserts, row.clone());
        self.inserts += 1;
        Ok(row_id)
    }

    fn get(&self, position: u64) -> Option<&Row> {
        self.rows.get(&position)
    }

}

impl<'a> IntoIterator for &'a Stream {
    type Item = &'a Row;
    type IntoIter = StreamIterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        // TODO fix the position
        StreamIterator{position:0,
                       stream: self}
    }
}

pub struct StreamIterator<'a> {
    position: u64,
    stream: &'a Stream,
}

impl<'a> StreamIterator<'a> {
    fn offset(&'a mut self, num: u64) -> &'a mut StreamIterator {
        self.position = num;
        self
    }
}

impl<'a> Iterator for StreamIterator<'a> {
    type Item = &'a Row;
    fn next(&mut self) -> Option<&'a Row> {
        let tmp = self.stream.get(self.position);
        self.position = self.position + 1;
        tmp
    }
}

#[cfg(test)]
mod tests {
    use super::{Stream, RowBuilder};

    use db::schema::{Schema, Type};
    use db::value::Value;
    use std::collections::HashMap;

    fn get_stream() -> Stream {
        let mut s = Stream::new();
        s.schema.add_type("name", Type::String);
        s.schema.add_type("age", Type::Int);
        s.schema.add_type("created", Type::Timestamp);
        s
    }

    fn get_stream_with_data() -> Stream {
        let mut s = get_stream();
        for x in 0..10 {
            let mut row = RowBuilder::new();
            row.set_string("name", "test");
            row.set_int("age", x);
            let result = s.insert(row).unwrap();
        }
        s
    }

    #[test]
    fn test_insert_works_normal_case() {
        let mut s = Stream::new();
        let name_id = s.schema.add_type("name", Type::String);

        let mut row = RowBuilder::new();
        row.set_string("name", "test");
        let result = s.insert(row).unwrap();
        assert_eq!(result, 0);
        assert_eq!(s.inserts, 1);
        let row2 = s.get(result).unwrap();
        let name = row2.get(name_id).unwrap();
        // was the data inserted?
        assert_eq!(row2.get(name_id).unwrap().clone(),
                   Value::from("test"));

    }

    #[test]
    fn test_equality() {
        assert_eq!(Value::from("jon"), Value::from("jon"));
    }

    #[test]
    fn test_builder() {
        let mut s = get_stream();
        let mut row = RowBuilder::new();

        row.set_string("name", "value")
           .set_int("age", 10);
        s.insert(row);

        let mut c = 0;
        for r in s.into_iter() {
            c += 1;
        }
        assert_eq!(c, 1);
    }

    #[test]
    fn test_iterator_offset() {
        let mut s = get_stream_with_data();
        let mut i = 0;
        for row in s.into_iter().offset(9) {
            i = i + 1;
        }
        assert_eq!(i, 1);
    }
}<commit_msg>made data better<commit_after>use std::collections::HashMap;
use std::error;

use super::row::{Row, RowError};
use super::schema::{Schema, Type};
use super::value::Value;
pub use super::row_builder::RowBuilder;

#[derive(Debug)]
pub enum StreamError {
    ValidationError(String),
    FieldNotFound(String),
    MissingRowId
}

impl From<RowError> for StreamError {
    fn from(err: RowError) -> StreamError {
        StreamError::MissingRowId
    }

}

#[derive(Debug)]
pub struct Stream {
    inserts: u64, // total number of inserts this Stream has seen
    lowest_id: Option<u64>,  // lowest id we still have in the Stream
    ttl: Option<u64>,
    rows: HashMap<u64, Row>,
    schema: Schema,

}

/**
This is a weird DB.  There's no primary key, since everything is based off append only streaming

*/
impl Stream {
    pub fn new() -> Stream {
        let mut stream = Stream::new_empty();
        stream.schema.add_type("_id", Type::Int);
        stream.schema.add_type("_created", Type::Timestamp);
        stream
    }

    // used in temporary tables
    pub fn new_empty() -> Stream {
        let mut stream = Stream {
            inserts: 0,
            lowest_id: None,
            rows: HashMap::new(),
            schema: Schema::new(),
            ttl: None,
        };
        stream
    }

    /* we take a HashMap of String -> Field here
    * we're going to convert it to HashMap<u8, Field> for the Row struct
    */
    pub fn insert(&mut self, mut row_builder: RowBuilder) -> Result<u64, StreamError> {
        // validate the inserted data
        let mut row_map : HashMap<u8, Value> = HashMap::new();
        for (key, val) in row_builder.data.drain() {
            // get the field from the schema
            // TypeDef
            let tmp = try!(self.schema.get(&key)
                               .ok_or(StreamError::FieldNotFound(key.to_string())));
            row_map.insert(tmp.id, val);

        }
        let row_id = self.inserts;
        let row = try!(Row::new(row_map));
        self.rows.insert(self.inserts, row.clone());
        self.inserts += 1;
        Ok(row_id)
    }

    fn get(&self, position: u64) -> Option<&Row> {
        self.rows.get(&position)
    }

}

impl<'a> IntoIterator for &'a Stream {
    type Item = &'a Row;
    type IntoIter = StreamIterator<'a>;

    fn into_iter(self) -> Self::IntoIter {
        // TODO fix the position
        StreamIterator{position:0,
                       stream: self}
    }
}

pub struct StreamIterator<'a> {
    position: u64,
    stream: &'a Stream,
}

impl<'a> StreamIterator<'a> {
    fn offset(&'a mut self, num: u64) -> &'a mut StreamIterator {
        self.position = num;
        self
    }
}

impl<'a> Iterator for StreamIterator<'a> {
    type Item = &'a Row;
    fn next(&mut self) -> Option<&'a Row> {
        let tmp = self.stream.get(self.position);
        self.position = self.position + 1;
        tmp
    }
}

#[cfg(test)]
mod tests {
    use super::{Stream, RowBuilder};

    use db::schema::{Schema, Type};
    use db::value::Value;
    use std::collections::HashMap;

    fn get_stream() -> Stream {
        let mut s = Stream::new();
        s.schema.add_type("name", Type::String);
        s.schema.add_type("age", Type::Int);
        s.schema.add_type("created", Type::Timestamp);
        s
    }

    fn get_stream_with_data() -> Stream {
        let mut s = get_stream();

        let names = vec!["Jon", "Dani", "Pete", "Sammy", "Steph",
                         "Blake", "Mr. Robot", "Ted", "Rachel", "Gloria"];
        let ages = vec![35, 29, 45, 56, 100,
                        35, 78, 32, 32, 67];

        for x in 0..10 {
            let mut row = RowBuilder::new();
            row.set_string("name", names[x]);
            row.set_int("age", ages[x]);
            let result = s.insert(row).unwrap();
        }
        s
    }

    #[test]
    fn test_insert_works_normal_case() {
        let mut s = Stream::new();
        let name_id = s.schema.add_type("name", Type::String);

        let mut row = RowBuilder::new();
        row.set_string("name", "test");
        let result = s.insert(row).unwrap();
        assert_eq!(result, 0);
        assert_eq!(s.inserts, 1);
        let row2 = s.get(result).unwrap();
        let name = row2.get(name_id).unwrap();
        // was the data inserted?
        assert_eq!(row2.get(name_id).unwrap().clone(),
                   Value::from("test"));

    }

    #[test]
    fn test_equality() {
        assert_eq!(Value::from("jon"), Value::from("jon"));
    }

    #[test]
    fn test_builder_insertion() {
        let mut s = get_stream();
        let mut row = RowBuilder::new();

        row.set_string("name", "value")
           .set_int("age", 10);
        s.insert(row);

        let mut c = 0;
        for r in s.into_iter() {
            c += 1;
        }
        assert_eq!(c, 1);
    }

    #[test]
    fn test_iterator_offset() {
        let mut s = get_stream_with_data();
        let mut i = 0;
        for row in s.into_iter().offset(9) {
            i = i + 1;
        }
        assert_eq!(i, 1);
    }

    #[test]
    fn test_chaining() {

    }
}<|endoftext|>


<commit_before>use crate::{Desktop, DesktopKeyMap, Mobile, MobileKeyMap};
use serde::{Deserialize, Serialize};
use serde_yaml as yaml;
use std::collections::HashMap;
use strum_macros::{Display, EnumIter, EnumString};

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProjectDesc {
    pub name: String,
    pub description: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Project {
    pub locales: HashMap<String, ProjectDesc>,
    pub author: String,
    pub email: String,
    pub copyright: String,
    pub organisation: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LayoutStrings {
    pub space: String,

    #[serde(rename = "return")]
    pub return_: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeriveOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transforms: Option<bool>,
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[derive(EnumString, Display, EnumIter)]
#[derive(Serialize, Deserialize)]
pub enum IsoKey {
    E00,
    E01,
    E02,
    E03,
    E04,
    E05,
    E06,
    E07,
    E08,
    E09,
    E10,
    E11,
    E12,
    D01,
    D02,
    D03,
    D04,
    D05,
    D06,
    D07,
    D08,
    D09,
    D10,
    D11,
    D12,
    C01,
    C02,
    C03,
    C04,
    C05,
    C06,
    C07,
    C08,
    C09,
    C10,
    C11,
    C12,
    B00,
    B01,
    B02,
    B03,
    B04,
    B05,
    B06,
    B07,
    B08,
    B09,
    B10,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Serialize, Deserialize)]
pub struct Modes {
    win: Option<DesktopModes>,
    mac: Option<DesktopModes>,
    ios: Option<MobileModes>,
    android: Option<MobileModes>,
    chrome: Option<DesktopModes>,
    x11: Option<DesktopModes>,
    desktop: Option<DesktopModes>,
    mobile: Option<MobileModes>,
}

pub type MobileModes = Mobile<MobileKeyMap>;
pub type DesktopModes = Desktop<DesktopKeyMap>;

/// A layout is defined as a file by the name <locale>.yaml or <locale>.<target>.yaml, and lives in the
/// locales/ directory in the kbdgen project bundle.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Layout {
    /// The display names for the layout, keyed by locale.
    #[serde(rename = "displayNames")]
    pub display_names: HashMap<String, String>,

    /// The different modes.
    pub modes: Modes,

    /// The decimal key. Nominally a '.' or ','.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decimal: Option<String>,

    /// An override for space keys on some OSes. Keyed by target.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub space: Option<Desktop<char>>,

    /// Dead keys present, keyed by layer code.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "deadKeys")]
    pub dead_keys: Option<Desktop<Vec<char>>>,

    /// The items to be shown when a key is long-pressed. Values are space separated in one string.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub longpress: Option<HashMap<String, String>>,

    /// The chain of inputs necessary to provide an output after a deadkey is pressed. Keyed by each individual input.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transforms: Option<HashMap<String, HashMap<String, String>>>,

    /// Strings to be shown on some OSes
    #[serde(skip_serializing_if = "Option::is_none")]
    pub strings: Option<LayoutStrings>,

    /// Derives
    #[serde(skip_serializing_if = "Option::is_none")]
    pub derive: Option<DeriveOptions>,

    /// Targets...
    #[serde(skip_serializing_if = "Option::is_none")]
    pub targets: Option<HashMap<String, yaml::Value>>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LayoutTargetWindows {
    /// The actual locale within Windows, as per their broken ISO 639-3 scheme or secret hardcoded lists.
    pub locale: String,

    /// The language name to be cached, in order to try to mask the ugly ISO code name that often shows.
    #[serde(rename = "languageName")]
    pub language_name: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LayoutTargetAndroid {
    /// Minimum SDK can be specified for a specific layout
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "minimumSdk")]
    pub minimum_sdk: Option<u32>,

    /// Styles
    #[serde(skip_serializing_if = "Option::is_none")]
    pub style: Option<HashMap<String, yaml::Value>>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TargetAndroid {
    pub version: String,

    pub build: u32,

    #[serde(rename = "packageId")]
    pub package_id: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "sentryDsn")]
    pub sentry_dsn: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "showNumberHints")]
    pub show_number_hints: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "minimumSdk")]
    pub minimum_sdk: Option<u32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub chfst: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "keyStore")]
    pub key_store: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "keyAlias")]
    pub key_alias: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TargetIOS {
    pub version: String,

    pub build: u32,

    #[serde(rename = "packageId")]
    pub package_id: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,

    #[serde(rename = "bundleName")]
    pub bundle_name: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "teamId")]
    pub team_id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "codeSignId")]
    pub code_sign_id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "sentryDsn")]
    pub sentry_dsn: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "aboutDir")]
    pub about_dir: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub chfst: Option<bool>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TargetWindows {
    pub version: String,

    #[serde(rename = "appName")]
    pub app_name: String,

    pub url: String,

    pub uuid: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "codeSignPfx")]
    pub code_sign_pfx: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "customLocales")]
    pub custom_locales: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "licensePath")]
    pub license_path: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "readmePath")]
    pub readme_path: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TargetMacOS {
    pub version: String,

    pub build: u32,

    #[serde(rename = "packageId")]
    pub package_id: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,

    #[serde(rename = "bundleName")]
    pub bundle_name: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "teamId")]
    pub team_id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "codeSignId")]
    pub code_sign_id: Option<String>,
}
<commit_msg>Add layout target types<commit_after>use crate::{Desktop, DesktopKeyMap, Mobile, MobileKeyMap};
use serde::{Deserialize, Serialize};
use serde_yaml as yaml;
use std::collections::HashMap;
use strum_macros::{Display, EnumIter, EnumString};

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProjectDesc {
    pub name: String,
    pub description: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Project {
    pub locales: HashMap<String, ProjectDesc>,
    pub author: String,
    pub email: String,
    pub copyright: String,
    pub organisation: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LayoutStrings {
    pub space: String,

    #[serde(rename = "return")]
    pub return_: String,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DeriveOptions {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transforms: Option<bool>,
}

#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[derive(EnumString, Display, EnumIter)]
#[derive(Serialize, Deserialize)]
pub enum IsoKey {
    E00,
    E01,
    E02,
    E03,
    E04,
    E05,
    E06,
    E07,
    E08,
    E09,
    E10,
    E11,
    E12,
    D01,
    D02,
    D03,
    D04,
    D05,
    D06,
    D07,
    D08,
    D09,
    D10,
    D11,
    D12,
    C01,
    C02,
    C03,
    C04,
    C05,
    C06,
    C07,
    C08,
    C09,
    C10,
    C11,
    C12,
    B00,
    B01,
    B02,
    B03,
    B04,
    B05,
    B06,
    B07,
    B08,
    B09,
    B10,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Serialize, Deserialize)]
pub struct Modes {
    win: Option<DesktopModes>,
    mac: Option<DesktopModes>,
    ios: Option<MobileModes>,
    android: Option<MobileModes>,
    chrome: Option<DesktopModes>,
    x11: Option<DesktopModes>,
    desktop: Option<DesktopModes>,
    mobile: Option<MobileModes>,
}

pub type MobileModes = Mobile<MobileKeyMap>;
pub type DesktopModes = Desktop<DesktopKeyMap>;

/// A layout is defined as a file by the name <locale>.yaml or <locale>.<target>.yaml, and lives in the
/// locales/ directory in the kbdgen project bundle.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Layout {
    /// The display names for the layout, keyed by locale.
    #[serde(rename = "displayNames")]
    pub display_names: HashMap<String, String>,

    /// The different modes.
    pub modes: Modes,

    /// The decimal key. Nominally a '.' or ','.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decimal: Option<String>,

    /// An override for space keys on some OSes. Keyed by target.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub space: Option<Desktop<char>>,

    /// Dead keys present, keyed by layer code.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "deadKeys")]
    pub dead_keys: Option<Desktop<Vec<char>>>,

    /// The items to be shown when a key is long-pressed. Values are space separated in one string.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub longpress: Option<HashMap<String, String>>,

    /// The chain of inputs necessary to provide an output after a deadkey is pressed. Keyed by each individual input.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub transforms: Option<HashMap<String, HashMap<String, String>>>,

    /// Strings to be shown on some OSes
    #[serde(skip_serializing_if = "Option::is_none")]
    pub strings: Option<LayoutStrings>,

    /// Derives
    #[serde(skip_serializing_if = "Option::is_none")]
    pub derive: Option<DeriveOptions>,

    /// Targets...
    #[serde(skip_serializing_if = "Option::is_none")]
    pub targets: Option<LayoutTarget>,
}

#[derive(Debug, Clone, PartialEq)]
#[derive(Serialize, Deserialize)]
pub struct LayoutTarget {
    win: Option<LayoutTargetWindows>,
    mac: Option<yaml::Value>,
    ios: Option<LayoutTargetIOS>,
    android: Option<LayoutTargetAndroid>,
    chrome: Option<yaml::Value>,
    x11: Option<yaml::Value>,
    desktop: Option<yaml::Value>,
    mobile: Option<yaml::Value>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LayoutTargetWindows {
    /// The actual locale within Windows, as per their broken ISO 639-3 scheme or secret hardcoded lists.
    pub locale: String,

    /// The language name to be cached, in order to try to mask the ugly ISO code name that often shows.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "languageName")]
    pub language_name: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LayoutTargetIOS {
    /// Minimum SDK can be specified for a specific layout
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "legacyName")]
    pub legacy_name: Option<u32>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct LayoutTargetAndroid {
    /// Minimum SDK can be specified for a specific layout
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "minimumSdk")]
    pub minimum_sdk: Option<u32>,

    /// Styles
    #[serde(skip_serializing_if = "Option::is_none")]
    pub style: Option<HashMap<String, yaml::Value>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "legacyName")]
    pub legacy_name: Option<u32>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TargetAndroid {
    pub version: String,

    pub build: u32,

    #[serde(rename = "packageId")]
    pub package_id: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "sentryDsn")]
    pub sentry_dsn: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "showNumberHints")]
    pub show_number_hints: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "minimumSdk")]
    pub minimum_sdk: Option<u32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub chfst: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "keyStore")]
    pub key_store: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "keyAlias")]
    pub key_alias: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TargetIOS {
    pub version: String,

    pub build: u32,

    #[serde(rename = "packageId")]
    pub package_id: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,

    #[serde(rename = "bundleName")]
    pub bundle_name: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "teamId")]
    pub team_id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "codeSignId")]
    pub code_sign_id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "sentryDsn")]
    pub sentry_dsn: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "aboutDir")]
    pub about_dir: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub chfst: Option<bool>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TargetWindows {
    pub version: String,

    #[serde(rename = "appName")]
    pub app_name: String,

    pub url: String,

    pub uuid: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "codeSignPfx")]
    pub code_sign_pfx: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "customLocales")]
    pub custom_locales: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "licensePath")]
    pub license_path: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "readmePath")]
    pub readme_path: Option<String>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TargetMacOS {
    pub version: String,

    pub build: u32,

    #[serde(rename = "packageId")]
    pub package_id: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,

    #[serde(rename = "bundleName")]
    pub bundle_name: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "teamId")]
    pub team_id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "codeSignId")]
    pub code_sign_id: Option<String>,
}
<|endoftext|>


<commit_before>use boxdraw;

use SimpleSearch;

// EXERCISE 1: Can you make an undraw implementation that can handle
// the case below?

#[test]
fn three_by_three() {
    boxdraw::check_undraw(".............\n\
                           ..+--+--+--+.\n\
                           ..|aa|bb|cc|.\n\
                           ..|aa|bb|cc|.\n\
                           ..+--+--+--+.\n\
                           ..|dd|ee|ff|.\n\
                           ..|dd|ee|ff|.\n\
                           ..+--+--+--+.\n\
                           ..|gg|hh|ii|.\n\
                           ..|gg|hh|ii|.\n\
                           ..+--+--+--+.\n\
                           .............\n\
                          ",
                          &SimpleSearch).unwrap();

}

// EXERCISE 2: One might think that once you generate a working
// Script, there's no further way to improve upon it. However,
// consider a case like this:
//
//
//                  ....................
//                  ......+------+......
//                  ......|bbbbbb|......
//                  ......|bbbbbb|......
//                  .+----|bbbbbb|----+.
//                  .|aaaa|bbbbbb|aaaa|.
//                  .|aaaa|bbbbbb|aaaa|.
//                  .+----|bbbbbb|----+.
//                  ......|bbbbbb|......
//                  ......+------+......
//                  ....................
//
// There are two "obvious" relatively short scripts that generate the
// above picture: one that draws two 'a' rectangles and then the
// single 'b' rectangle (thus requiring three commands in the script).
//
//  ....................       ....................
//  ....................       ......+------+......
//  ....................       ......|bbbbbb|......
//  ....................       ......|bbbbbb|......
//  .+----+......+----+.       ......|bbbbbb|......
//  .|aaaa|......|aaaa|. then  ......|bbbbbb|......
//  .|aaaa|......|aaaa|.       ......|bbbbbb|......
//  .+----+......+----+.       ......|bbbbbb|......
//  ....................       ......|bbbbbb|......
//  ....................       ......+------+......
//  ....................       ....................
//
//
// But there is also this approach, which requires only two commands:
//
//  ....................       ....................
//  ....................       ......+------+......
//  ....................       ......|bbbbbb|......
//  ....................       ......|bbbbbb|......
//  .+----------------+.       ......|bbbbbb|......
//  .|aaaaaaaaaaaaaaaa|. then  ......|bbbbbb|......
//  .|aaaaaaaaaaaaaaaa|.       ......|bbbbbb|......
//  .+----------------+.       ......|bbbbbb|......
//  ....................       ......|bbbbbb|......
//  ....................       ......+------+......
//  ....................       ....................
//
// The undraw strategy of the code above will tend to generate the
// three-command script. What ideas do you have to try to make it
// generate "optimal" scripts (where "optimal" here means "minimal
// number of commands."

// EXERCISE 3: Up until now, we have assumed that all boxes are at
// least width and height >= 2.  So for example `test::narrow_lines()`
// shows boxes of width == 2, so narrow that they have no interior.
//
// BUT: The boxdraw-rs library supports boxes of width or height == 1
// as well, and it has *very* different behavior for them. Find out
// what that behavior is (perhaps by looking at the tests in the
// boxdraw library).
//
// Consider what a box with both width and height equal to 1 would
// look like. What implications does this have? For example, what kind
// of pictures can you make with just boxes of *both* width and height 1?
//
// Try to solve the undraw problem even for such cases.
//
// Note 1: to do this, you may want to start from scratch; or maybe
// some of the code here could be of use.
//
// Note 2: You may want to play around first with approaches that are
// not anywhere close to optimal.

// EXERCISE 4: Like exercise 2 above: Again, solve the generalized
// undraw problem (that is, including boxes of width and/or height 1),
// but this time, try to generate relatively small scripts.
//
// Note that you can make short scripts that first draw large boxes
// (which will then have borders) and then write over the borders with
// boxes of width or height 1, like so:
//
//  ....................       ....................   ....................
//  ....................       ....................   ....................
//  ....................       ....................   ....................
//  ....................       ....................   ....................
//  .+----------------+.       .aaaaaaaaaaaaaaaaaa.   .a................a.
//  .|aaaaaaaaaaaaaaaa|. then  .................... ; .a................a.
//  .|aaaaaaaaaaaaaaaa|.       ....................   .a................a.
//  .+----------------+.       .aaaaaaaaaaaaaaaaaa.   .a................a.
//  ....................       ....................   ....................
//  ....................       ....................   ....................
//  ....................       ....................   ....................
//
// and this generates a picture with a borderless box:
//
//  ....................
//  ....................
//  ....................
//  ....................
//  .aaaaaaaaaaaaaaaaaa.
//  .aaaaaaaaaaaaaaaaaa.
//  .aaaaaaaaaaaaaaaaaa.
//  .aaaaaaaaaaaaaaaaaa.
//  ....................
//  ....................
//  ....................
//
// but does it with only five commands.
<commit_msg>Finalizing the exercises.<commit_after>use boxdraw;

use SimpleSearch;

// NOTE: There is not a strict ordering of the exercises below, You
// can try them in order [1,2,3,4,5], or you can jump around, i.e. try
// exercise 4 first, then come back to exercises 1 or 2.  (The only
// exception to the above note is that exercise 5 is a harder version
// of exercise 4.)

// EXERCISE 1: Can you make an undraw implementation that can handle
// the case below?

#[test]
fn three_by_three() {
    boxdraw::check_undraw(".............\n\
                           ..+--+--+--+.\n\
                           ..|aa|bb|cc|.\n\
                           ..|aa|bb|cc|.\n\
                           ..+--+--+--+.\n\
                           ..|dd|ee|ff|.\n\
                           ..|dd|ee|ff|.\n\
                           ..+--+--+--+.\n\
                           ..|gg|hh|ii|.\n\
                           ..|gg|hh|ii|.\n\
                           ..+--+--+--+.\n\
                           .............\n\
                          ",
                          &SimpleSearch).unwrap();

}

// EXERCISE 2: The code for naive-undraw was not written with very
// much efficiency in mind. There are places where the code will
// redundantly rescan the same areas to check that they are sound,
// namely when dealing with `PartialMatch'es`.
//
// 2a.) Can you make benchmarks (via Rust's `#[bench]` form) to
//      illustrate how relatively badly this can get (i.e. by
//      comparing the running time for picture with a single small box
//      to one with a single big box.
//
// 2b.) What sorts of improvements are possible to avoid such scans?
//      Try to implement them; make sure to record how the benchmarks
//      performed with and without your changes.

// EXERCISE 3: One might think that once you generate a working
// Script, there's no further way to improve upon it. However,
// consider a case like this:
//
//
//                  ....................
//                  ......+------+......
//                  ......|bbbbbb|......
//                  ......|bbbbbb|......
//                  .+----|bbbbbb|----+.
//                  .|aaaa|bbbbbb|aaaa|.
//                  .|aaaa|bbbbbb|aaaa|.
//                  .+----|bbbbbb|----+.
//                  ......|bbbbbb|......
//                  ......+------+......
//                  ....................
//
// There are two "obvious" relatively short scripts that generate the
// above picture: one that draws two 'a' rectangles and then the
// single 'b' rectangle (thus requiring three commands in the script).
//
//  ....................       ....................
//  ....................       ......+------+......
//  ....................       ......|bbbbbb|......
//  ....................       ......|bbbbbb|......
//  .+----+......+----+.       ......|bbbbbb|......
//  .|aaaa|......|aaaa|. then  ......|bbbbbb|......
//  .|aaaa|......|aaaa|.       ......|bbbbbb|......
//  .+----+......+----+.       ......|bbbbbb|......
//  ....................       ......|bbbbbb|......
//  ....................       ......+------+......
//  ....................       ....................
//
//
// But there is also this approach, which requires only two commands:
//
//  ....................       ....................
//  ....................       ......+------+......
//  ....................       ......|bbbbbb|......
//  ....................       ......|bbbbbb|......
//  .+----------------+.       ......|bbbbbb|......
//  .|aaaaaaaaaaaaaaaa|. then  ......|bbbbbb|......
//  .|aaaaaaaaaaaaaaaa|.       ......|bbbbbb|......
//  .+----------------+.       ......|bbbbbb|......
//  ....................       ......|bbbbbb|......
//  ....................       ......+------+......
//  ....................       ....................
//
// The undraw strategy of the code above will tend to generate the
// three-command script. What ideas do you have to try to make it
// generate "optimal" scripts (where "optimal" here means "minimal
// number of commands."

// EXERCISE 4: Up until now, we have assumed that all boxes are at
// least width and height >= 2.  So for example `test::narrow_lines()`
// shows boxes of width == 2, so narrow that they have no interior.
//
// BUT: The boxdraw-rs library supports boxes of width or height == 1
// as well, and it has *very* different behavior for them. Find out
// what that behavior is (perhaps by looking at the tests in the
// boxdraw library).
//
// Consider what a box with both width and height equal to 1 would
// look like. What implications does this have? For example, what kind
// of pictures can you make with just boxes of *both* width and height 1?
//
// Try to solve the undraw problem even for such cases.
//
// Note 1: to do this, you may want to start from scratch; or maybe
// some of the code here could be of use.
//
// Note 2: You may want to play around first with approaches that are
// not anywhere close to optimal.

// EXERCISE 5: Like exercise 3 above: Again, solve the generalized
// undraw problem (that is, including boxes of width and/or height 1),
// but this time, try to generate relatively small scripts.
//
// Note that you can make short scripts that first draw large boxes
// (which will then have borders) and then write over the borders with
// boxes of width or height 1, like so:
//
//  ....................       ....................   ....................
//  ....................       ....................   ....................
//  ....................       ....................   ....................
//  ....................       ....................   ....................
//  .+----------------+.       .aaaaaaaaaaaaaaaaaa.   .a................a.
//  .|aaaaaaaaaaaaaaaa|. then  .................... ; .a................a.
//  .|aaaaaaaaaaaaaaaa|.       ....................   .a................a.
//  .+----------------+.       .aaaaaaaaaaaaaaaaaa.   .a................a.
//  ....................       ....................   ....................
//  ....................       ....................   ....................
//  ....................       ....................   ....................
//
// and this generates a picture with a borderless box:
//
//  ....................
//  ....................
//  ....................
//  ....................
//  .aaaaaaaaaaaaaaaaaa.
//  .aaaaaaaaaaaaaaaaaa.
//  .aaaaaaaaaaaaaaaaaa.
//  .aaaaaaaaaaaaaaaaaa.
//  ....................
//  ....................
//  ....................
//
// but does it with only five commands.
<|endoftext|>


<commit_before>use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::collections::HashMap;

pub fn rudolph_meds_1(file: &str) -> i32 {
    process(file)
}

pub fn rudolph_meds_2(file: &str) -> i32 {
    process(file)
}

fn process(file: &str) -> i32 {
    let input = File::open(file).expect("File open fail.");
    let reader = BufReader::new(input);

    let lines = reader.lines()
        .filter_map(Result::ok)
        .collect::<Vec<String>>();

    let mut replacements = HashMap::new();
    let mut med_molecule = "";
    for line in lines.iter() {
        let mut words = line.split_whitespace();
        loop {
            if let Some(element) = words.next() {
                if let Some(replacement_elem) = words.nth(1) {
                    replacements.insert(element, replacement_elem);
                } else {
                    med_molecule = element;
                }
            } else {
                break
            }
        }
    }
    println!("{:?}", replacements);
    println!("{:?}", med_molecule);

    let mut med_molecule_elements = Vec::new();
    let mut med_molecule_iter = med_molecule.chars();
    loop {
        let mut other = Vec::new();
        if let Some(c) = med_molecule_iter.next() {
            let mut elem = format!("{}", c);
            if replacements.keys().any(|&k| k == elem) {
                med_molecule_elements.append(&mut other);
                med_molecule_elements.push(elem);
            } else if let Some(b) = med_molecule_iter.next() {
                elem.push(b);
                if replacements.keys().any(|&k| k == elem) {
                    med_molecule_elements.append(&mut other);
                    med_molecule_elements.push(elem);
                } else {
                    other.push(elem);
                }
            } else {
                other.push(elem);
            }
        } else {
            break
        }
    }
    println!("{:?}", med_molecule_elements);

    42
}
<commit_msg>Update to count combinations.<commit_after>use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::collections::HashMap;

pub fn rudolph_meds_1(file: &str) -> i32 {
    process(file)
}

pub fn rudolph_meds_2(file: &str) -> i32 {
    process(file)
}

fn process(file: &str) -> i32 {
    let input = File::open(file).expect("File open fail.");
    let reader = BufReader::new(input);

    let lines = reader.lines()
        .filter_map(Result::ok)
        .collect::<Vec<String>>();

    let mut replacements = HashMap::new();
    let mut med_molecule = "";
    for line in lines.iter() {
        let mut words = line.split_whitespace();
        loop {
            if let Some(element) = words.next() {
                if let Some(replacement_elem) = words.nth(1) {
                    let replacement_list
                        = replacements.entry(element).or_insert(Vec::new());
                    replacement_list.push(replacement_elem);
                } else {
                    med_molecule = element;
                }
            } else {
                break
            }
        }
    }
    println!("{:?}", replacements);
    println!("{:?}", med_molecule);

    let mut med_molecule_elements = Vec::new();
    let mut med_molecule_iter = med_molecule.chars();
    let mut other = String::new();
    loop {
        if let Some(c) = med_molecule_iter.next() {
            let mut elem = format!("{}", c);
            if replacements.keys().any(|&k| k == elem) {
                if other.len() > 0 {
                    med_molecule_elements.push(other);
                    other = String::new();
                }
                med_molecule_elements.push(elem);
            } else if let Some(b) = med_molecule_iter.next() {
                elem.push(b);
                if replacements.keys().any(|&k| k == elem) {
                    if other.len() > 0 {
                        med_molecule_elements.push(other);
                        other = String::new();
                    }
                    med_molecule_elements.push(elem);
                } else {
                    other.push_str(&*elem);
                }
            } else {
                other.push_str(&*elem);
            }
        } else {
            break
        }
    }
    println!("{:?}", med_molecule_elements);

    let mut count = 1;
    for elem in med_molecule_elements {
        let  mut combinations = 1;
        if let Some(replacement_list) = replacements.get(&*elem) {
            combinations = replacement_list.len();
        }
        count *= combinations;
    }

    count as i32
}
<|endoftext|>


<commit_before>use std::fmt;

use style::Style;

/// Styles have a special `Debug` implementation that only shows the fields that
/// are set. Fields that haven’t been touched aren’t included in the output.
///
/// This behaviour gets bypassed when using the alternate formatting mode
/// `format!("{:#?}")`.
///
///     use ansi_term::Colour::{Red, Blue};
///     assert_eq!("Style { fg(Red), on(Blue), bold, italic }",
///                format!("{:?}", Red.on(Blue).bold().italic()));
impl fmt::Debug for Style {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        if fmt.alternate() {
            fmt.debug_struct("Style")
               .field("foreground",    &self.foreground)
               .field("background",    &self.background)
               .field("blink",         &self.is_blink)
               .field("bold",          &self.is_bold)
               .field("dimmed",        &self.is_dimmed)
               .field("hidden",        &self.is_hidden)
               .field("italic",        &self.is_italic)
               .field("reverse",       &self.is_reverse)
               .field("strikethrough", &self.is_strikethrough)
               .field("underline",     &self.is_underline)
               .finish()
        }
        else if self.is_plain() {
            fmt.write_str("Style {}")
        }
        else {
            fmt.write_str("Style { ")?;

            let mut written_anything = false;

            if let Some(fg) = self.foreground {
                if written_anything { fmt.write_str(", ")? }
                written_anything = true;
                write!(fmt, "fg({:?})", fg)?
            }

            if let Some(bg) = self.background {
                if written_anything { fmt.write_str(", ")? }
                written_anything = true;
                write!(fmt, "on({:?})", bg)?
            }

            {
                let mut write_flag = |name| {
                    if written_anything { fmt.write_str(", ")? }
                    written_anything = true;
                    fmt.write_str(name)
                };

                if self.is_blink          { write_flag("blink")? }
                if self.is_bold           { write_flag("bold")? }
                if self.is_dimmed         { write_flag("dimmed")? }
                if self.is_hidden         { write_flag("hidden")? }
                if self.is_italic         { write_flag("italic")? }
                if self.is_reverse        { write_flag("reverse")? }
                if self.is_strikethrough  { write_flag("strikethrough")? }
                if self.is_underline      { write_flag("underline")? }
            }

            write!(fmt, " }}")
        }
    }
}

#[cfg(test)]
mod test {
    use style::Colour::*;
    use style::Style;

    fn style() -> Style {
        Style::new()
    }

    macro_rules! test {
        ($name: ident: $obj: expr => $result: expr) => {
            #[test]
            fn $name() {
                assert_eq!($result, format!("{:?}", $obj));
            }
        };
    }

    test!(empty:   style()                  => "Style {}");
    test!(bold:    style().bold()           => "Style { bold }");
    test!(italic:  style().italic()         => "Style { italic }");
    test!(both:    style().bold().italic()  => "Style { bold, italic }");

    test!(red:     Red.normal()                     => "Style { fg(Red) }");
    test!(redblue: Red.normal().on(RGB(3, 2, 4))    => "Style { fg(Red), on(RGB(3, 2, 4)) }");

    test!(everything:
            Red.on(Blue).blink().bold().dimmed().hidden().italic().reverse().strikethrough().underline() =>
            "Style { fg(Red), on(Blue), blink, bold, dimmed, hidden, italic, reverse, strikethrough, underline }");

    #[test]
    fn long_and_detailed() {
        let debug = r##"Style {
    foreground: Some(
        Blue
    ),
    background: None,
    blink: false,
    bold: true,
    dimmed: false,
    hidden: false,
    italic: false,
    reverse: false,
    strikethrough: false,
    underline: false
}"##;
        assert_eq!(debug, format!("{:#?}", Blue.bold()));
    }
}
<commit_msg>Fix failing test<commit_after>use std::fmt;

use style::Style;

/// Styles have a special `Debug` implementation that only shows the fields that
/// are set. Fields that haven’t been touched aren’t included in the output.
///
/// This behaviour gets bypassed when using the alternate formatting mode
/// `format!("{:#?}")`.
///
///     use ansi_term::Colour::{Red, Blue};
///     assert_eq!("Style { fg(Red), on(Blue), bold, italic }",
///                format!("{:?}", Red.on(Blue).bold().italic()));
impl fmt::Debug for Style {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        if fmt.alternate() {
            fmt.debug_struct("Style")
               .field("foreground",    &self.foreground)
               .field("background",    &self.background)
               .field("blink",         &self.is_blink)
               .field("bold",          &self.is_bold)
               .field("dimmed",        &self.is_dimmed)
               .field("hidden",        &self.is_hidden)
               .field("italic",        &self.is_italic)
               .field("reverse",       &self.is_reverse)
               .field("strikethrough", &self.is_strikethrough)
               .field("underline",     &self.is_underline)
               .finish()
        }
        else if self.is_plain() {
            fmt.write_str("Style {}")
        }
        else {
            fmt.write_str("Style { ")?;

            let mut written_anything = false;

            if let Some(fg) = self.foreground {
                if written_anything { fmt.write_str(", ")? }
                written_anything = true;
                write!(fmt, "fg({:?})", fg)?
            }

            if let Some(bg) = self.background {
                if written_anything { fmt.write_str(", ")? }
                written_anything = true;
                write!(fmt, "on({:?})", bg)?
            }

            {
                let mut write_flag = |name| {
                    if written_anything { fmt.write_str(", ")? }
                    written_anything = true;
                    fmt.write_str(name)
                };

                if self.is_blink          { write_flag("blink")? }
                if self.is_bold           { write_flag("bold")? }
                if self.is_dimmed         { write_flag("dimmed")? }
                if self.is_hidden         { write_flag("hidden")? }
                if self.is_italic         { write_flag("italic")? }
                if self.is_reverse        { write_flag("reverse")? }
                if self.is_strikethrough  { write_flag("strikethrough")? }
                if self.is_underline      { write_flag("underline")? }
            }

            write!(fmt, " }}")
        }
    }
}

#[cfg(test)]
mod test {
    use style::Colour::*;
    use style::Style;

    fn style() -> Style {
        Style::new()
    }

    macro_rules! test {
        ($name: ident: $obj: expr => $result: expr) => {
            #[test]
            fn $name() {
                assert_eq!($result, format!("{:?}", $obj));
            }
        };
    }

    test!(empty:   style()                  => "Style {}");
    test!(bold:    style().bold()           => "Style { bold }");
    test!(italic:  style().italic()         => "Style { italic }");
    test!(both:    style().bold().italic()  => "Style { bold, italic }");

    test!(red:     Red.normal()                     => "Style { fg(Red) }");
    test!(redblue: Red.normal().on(RGB(3, 2, 4))    => "Style { fg(Red), on(RGB(3, 2, 4)) }");

    test!(everything:
            Red.on(Blue).blink().bold().dimmed().hidden().italic().reverse().strikethrough().underline() =>
            "Style { fg(Red), on(Blue), blink, bold, dimmed, hidden, italic, reverse, strikethrough, underline }");

    #[test]
    fn long_and_detailed() {
        let debug = r##"Style {
    foreground: Some(
        Blue,
    ),
    background: None,
    blink: false,
    bold: true,
    dimmed: false,
    hidden: false,
    italic: false,
    reverse: false,
    strikethrough: false,
    underline: false,
}"##;
        assert_eq!(debug, format!("{:#?}", Blue.bold()));
    }
}
<|endoftext|>


<commit_before>/// Utilities for writing messages to the Janus log.
extern crate chrono;
extern crate colored;

use self::chrono::{DateTime, Local};
use self::colored::{Color, Colorize};
use super::ffi;
use std::ffi::CString;
use std::fmt::Write;

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
/// A Janus log level. Lower is more severe.
pub enum LogLevel {
    Fatal = 1,
    Err = 2,
    Warn = 3,
    Info = 4,
    Verb = 5,
    Huge = 6,
    Dbg = 7,
}

impl LogLevel {
    /// The color associated with each log level's label (if colors are enabled.)
    fn color(&self) -> Option<Color> {
        match *self {
            LogLevel::Fatal => Some(Color::Magenta),
            LogLevel::Err => Some(Color::Red),
            LogLevel::Warn => Some(Color::Yellow),
            _ => None,
        }
    }
}

#[derive(Debug, Clone)]
pub struct LogParameters {
    pub max_log_level: i32,
    pub log_timestamps: bool,
    pub log_colors: bool,
    pub clock: fn() -> DateTime<Local>,
}

impl Default for LogParameters {
    fn default() -> Self {
        unsafe {
            Self {
                max_log_level: ffi::janus_log_level,
                log_timestamps: ffi::janus_log_timestamps == 1,
                log_colors: ffi::janus_log_colors == 1,
                clock: Local::now,
            }
        }
    }
}

/// Writes a message at the given log level to the Janus log, using the provided parameters to control
/// how the log message is formatted.
pub fn write_log(level: LogLevel, message: &str, params: LogParameters) {
    if level as i32 <= params.max_log_level {
        let output = CString::new(print_log(level, message, params)).expect("Null character in log message :(");
        unsafe { ffi::janus_vprintf(output.as_ptr()) }
    }
}

/// Prints a message at the given log level into an owned string, using the provided parameters to control
/// how the log message is formatted.
pub fn print_log(level: LogLevel, message: &str, params: LogParameters) -> String {
    let mut output = String::with_capacity(message.len() + 40);
    if params.log_timestamps {
        write!(output, "{} ", (params.clock)().format("[%a %b %e %T %Y]")).unwrap();
    }
    if level <= LogLevel::Warn {
        let name = format!("[{:?}] ", level).to_uppercase();
        match (params.log_colors, level.color()) {
            (true, Some(c)) => output.push_str(&name.color(c)),
            _ => output.push_str(&name),
        }
    }
    output.push_str(message);
    output.push('\n');
    output
}

/// Writes a message at the given log level to the Janus log.
pub fn log(level: LogLevel, message: &str) {
    write_log(level, message, LogParameters::default());
}

#[cfg(test)]
mod tests {

    use super::*;
    use super::chrono::TimeZone;

    fn fixed_clock(year: i32, month: u32, day: u32, hour: u32, min: u32, sec: u32) -> DateTime<Local> {
        Local.ymd(year, month, day).and_hms(hour, min, sec)
    }

    #[test]
    fn log_format_correctness() {
        assert_eq!(
            "[Tue Oct 10 01:37:46 2017] [WARN] Test message.\n",
            print_log(
                LogLevel::Warn,
                "Test message.",
                LogParameters {
                    max_log_level: 6,
                    log_timestamps: true,
                    log_colors: false,
                    clock: || fixed_clock(2017, 10, 10, 1, 37, 46),
                }
            )
        )
    }
}
<commit_msg>Use match guard in print_log<commit_after>/// Utilities for writing messages to the Janus log.
extern crate chrono;
extern crate colored;

use self::chrono::{DateTime, Local};
use self::colored::{Color, Colorize};
use super::ffi;
use std::ffi::CString;
use std::fmt::Write;

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
/// A Janus log level. Lower is more severe.
pub enum LogLevel {
    Fatal = 1,
    Err = 2,
    Warn = 3,
    Info = 4,
    Verb = 5,
    Huge = 6,
    Dbg = 7,
}

impl LogLevel {
    /// The color associated with each log level's label (if colors are enabled.)
    fn color(&self) -> Option<Color> {
        match *self {
            LogLevel::Fatal => Some(Color::Magenta),
            LogLevel::Err => Some(Color::Red),
            LogLevel::Warn => Some(Color::Yellow),
            _ => None,
        }
    }
}

#[derive(Debug, Clone)]
pub struct LogParameters {
    pub max_log_level: i32,
    pub log_timestamps: bool,
    pub log_colors: bool,
    pub clock: fn() -> DateTime<Local>,
}

impl Default for LogParameters {
    fn default() -> Self {
        unsafe {
            Self {
                max_log_level: ffi::janus_log_level,
                log_timestamps: ffi::janus_log_timestamps == 1,
                log_colors: ffi::janus_log_colors == 1,
                clock: Local::now,
            }
        }
    }
}

/// Writes a message at the given log level to the Janus log, using the provided parameters to control
/// how the log message is formatted.
pub fn write_log(level: LogLevel, message: &str, params: LogParameters) {
    if level as i32 <= params.max_log_level {
        let output = CString::new(print_log(level, message, params)).expect("Null character in log message :(");
        unsafe { ffi::janus_vprintf(output.as_ptr()) }
    }
}

/// Prints a message at the given log level into an owned string, using the provided parameters to control
/// how the log message is formatted.
pub fn print_log(level: LogLevel, message: &str, params: LogParameters) -> String {
    let mut output = String::with_capacity(message.len() + 40);
    if params.log_timestamps {
        write!(output, "{} ", (params.clock)().format("[%a %b %e %T %Y]")).unwrap();
    }
    if level <= LogLevel::Warn {
        let name = format!("[{:?}] ", level).to_uppercase();
        match level.color() {
            Some(c) if params.log_colors => output.push_str(&name.color(c)),
            _ => output.push_str(&name),
        }
    }
    output.push_str(message);
    output.push('\n');
    output
}

/// Writes a message at the given log level to the Janus log.
pub fn log(level: LogLevel, message: &str) {
    write_log(level, message, LogParameters::default());
}

#[cfg(test)]
mod tests {

    use super::*;
    use super::chrono::TimeZone;

    fn fixed_clock(year: i32, month: u32, day: u32, hour: u32, min: u32, sec: u32) -> DateTime<Local> {
        Local.ymd(year, month, day).and_hms(hour, min, sec)
    }

    #[test]
    fn log_format_correctness() {
        assert_eq!(
            "[Tue Oct 10 01:37:46 2017] [WARN] Test message.\n",
            print_log(
                LogLevel::Warn,
                "Test message.",
                LogParameters {
                    max_log_level: 6,
                    log_timestamps: true,
                    log_colors: false,
                    clock: || fixed_clock(2017, 10, 10, 1, 37, 46),
                }
            )
        )
    }
}
<|endoftext|>


<commit_before>#![feature(test)]

extern crate bit_field;

use bit_field::*;

pub trait BitOper {
    const BIT_LEN: usize;
    fn get_b(&self, idx: usize) -> bool;
    fn set_b(&mut self, idx: usize, val: bool);
    fn toggle(&mut self, idx: usize);
}

pub trait BitArrayOper<T: BitOper> {
    fn get_blen(&self)->usize;
    fn get_b(&self, idx: usize) -> bool;
    fn set_b(&mut self, idx: usize, val: bool);
    fn toggle(&mut self, idx: usize);
}

impl BitOper for u8 {
    const BIT_LEN: usize = std::mem::size_of::<Self>() as usize * 8;

    fn set_b(&mut self, idx: usize, val: bool) {
        assert!(idx < Self::BIT_LEN);
        if val {
            *self |= 1 << idx;
        } else {
            *self &= !(1 << idx);
        }
    }

    fn get_b(&self, idx: usize) -> bool {
        assert!(idx < Self::BIT_LEN);
        (self & 1 << idx) != 0
    }

    fn toggle(&mut self, idx: usize) {
        assert!(idx <  Self::BIT_LEN);
        *self ^= 1 << idx;
    }
}

impl BitOper for u32 {
  const BIT_LEN: usize = std::mem::size_of::<Self>() as usize * 8;
    fn set_b(&mut self, idx: usize, val: bool) {
        assert!(idx < Self::BIT_LEN);
        if val {
            *self |= 1 << idx;
        } else {
            *self &= !(1 << idx);
        }
    }

    fn get_b(&self, idx: usize) -> bool {
        assert!(idx < Self::BIT_LEN);
        (self & 1 << idx) != 0
    }

    fn toggle(&mut self, idx: usize) {
        assert!(idx <  Self::BIT_LEN);
        *self ^= 1 << idx;
    }
}

impl BitOper for u64 {
  const BIT_LEN: usize = std::mem::size_of::<Self>() as usize * 8;
    fn set_b(&mut self, idx: usize, val: bool) {
        assert!(idx < Self::BIT_LEN);
        if val {
            *self |= 1 << idx;
        } else {
            *self &= !(1 << idx);
        }
    }

    fn get_b(&self, idx: usize) -> bool {
        assert!(idx < Self::BIT_LEN);
        (self & 1 << idx) != 0
    }

    fn toggle(&mut self, idx: usize) {
        assert!(idx <  Self::BIT_LEN);
        *self ^= 1 << idx;
    }
}

impl <T:BitOper> BitArrayOper<T> for [T] {
    fn get_blen(&self) -> usize {
        self.len() * T::BIT_LEN
    }

    fn get_b(&self, idx: usize) -> bool {
        self[idx / T::BIT_LEN].get_b(idx % T::BIT_LEN)
    }

    fn set_b(&mut self, idx: usize, val: bool) {
        self[idx / T::BIT_LEN].set_b(idx % T::BIT_LEN, val);
    }

    fn toggle(&mut self, idx: usize) {
        self[idx / T::BIT_LEN].toggle(idx % T::BIT_LEN);
    }
}

extern crate test;

use test::Bencher;

const len: usize = 256;

fn set_bitfield<T:BitField>(v: &mut Vec<T>) {
        for i in 0..v.len() * T::BIT_LENGTH {
            v.as_mut_slice().set_bit(i, true);;
        }
 }

fn get_bitfield<T:BitField>(v: &Vec<T>) {
        for i in 0..v.len() * T::BIT_LENGTH {
            let _b = v.as_slice().get_bit(i);
        }
 }

 fn set_trivial<T:BitOper>(v: &mut Vec<T>) {
        for i in 0..v.len() * T::BIT_LEN {
            v.set_b(i, true);
        }
}

 fn toggle<T:BitOper>(v: &mut Vec<T>) {
        for i in 0..v.len() * T::BIT_LEN {
            v.toggle(i);
        }
}

 fn get_trivial<T:BitOper>(v: &Vec<T>) {
        for i in 0..v.len() * T::BIT_LEN {
            let _b = v.get_b(i);
        }
}

#[bench]
fn u8_set_bitfield(b: &mut Bencher) {
    let mut v = vec![0u8; len];
    b.iter(|| {
        set_bitfield(&mut v);
    });
}

#[bench]
fn u8_set_trivial(b: &mut Bencher) {
    let mut v = vec![0u8; len];

    b.iter(|| {
       set_trivial(&mut v);
    });
}

#[bench]
fn u8_get_bitfield(b: &mut Bencher) {
    let v = vec![1u8; len];
    b.iter(|| {
       get_bitfield(&v);
    });
}

#[bench]
fn u8_get_trivial(b: &mut Bencher) {
    let v = vec![1u8; len];
    b.iter(|| {
        get_trivial(&v);
    });
}

#[bench]
fn u32_set_bitfield(b: &mut Bencher) {
    let mut v = vec![0u32; len];
    b.iter(|| {
        set_bitfield(&mut v);
    });
}

#[bench]
fn u32_set_trivial(b: &mut Bencher) {
    let mut v = vec![0u32; len];

    b.iter(|| {
       set_trivial(&mut v);
    });
}

#[bench]
fn u32_get_bitfield(b: &mut Bencher) {
    let v = vec![1u32; len];
    b.iter(|| {
       get_bitfield(&v);
    });
}

#[bench]
fn u32_get_trivial(b: &mut Bencher) {
    let v = vec![1u32; len];
    b.iter(|| {
        get_trivial(&v);
    });
}

/*

#[bench]
fn u64_set_bitfield(b: &mut Bencher) {
    let mut v = vec![0u64; len];
    b.iter(|| {
        set_bitfield(&mut v);
    });
}

#[bench]
fn u64_set_trivial(b: &mut Bencher) {
    let mut v = vec![0u64; len];

    b.iter(|| {
       set_trivial(&mut v);
    });
}

#[bench]
fn u64_get_bitfield(b: &mut Bencher) {
    let v = vec![1u64; len];
    b.iter(|| {
       get_bitfield(&v);
    });
}

#[bench]
fn u64_get_trivial(b: &mut Bencher) {
    let v = vec![1u64; len];
    b.iter(|| {
        get_trivial(&v);
    });
}
*/
<commit_msg>Comment in u64 benches<commit_after>#![feature(test)]

extern crate bit_field;

use bit_field::*;

pub trait BitOper {
    const BIT_LEN: usize;
    fn get_b(&self, idx: usize) -> bool;
    fn set_b(&mut self, idx: usize, val: bool);
    fn toggle(&mut self, idx: usize);
}

pub trait BitArrayOper<T: BitOper> {
    fn get_blen(&self)->usize;
    fn get_b(&self, idx: usize) -> bool;
    fn set_b(&mut self, idx: usize, val: bool);
    fn toggle(&mut self, idx: usize);
}

impl BitOper for u8 {
    const BIT_LEN: usize = std::mem::size_of::<Self>() as usize * 8;

    fn set_b(&mut self, idx: usize, val: bool) {
        assert!(idx < Self::BIT_LEN);
        if val {
            *self |= 1 << idx;
        } else {
            *self &= !(1 << idx);
        }
    }

    fn get_b(&self, idx: usize) -> bool {
        assert!(idx < Self::BIT_LEN);
        (self & 1 << idx) != 0
    }

    fn toggle(&mut self, idx: usize) {
        assert!(idx <  Self::BIT_LEN);
        *self ^= 1 << idx;
    }
}

impl BitOper for u32 {
  const BIT_LEN: usize = std::mem::size_of::<Self>() as usize * 8;
    fn set_b(&mut self, idx: usize, val: bool) {
        assert!(idx < Self::BIT_LEN);
        if val {
            *self |= 1 << idx;
        } else {
            *self &= !(1 << idx);
        }
    }

    fn get_b(&self, idx: usize) -> bool {
        assert!(idx < Self::BIT_LEN);
        (self & 1 << idx) != 0
    }

    fn toggle(&mut self, idx: usize) {
        assert!(idx <  Self::BIT_LEN);
        *self ^= 1 << idx;
    }
}

impl BitOper for u64 {
  const BIT_LEN: usize = std::mem::size_of::<Self>() as usize * 8;
    fn set_b(&mut self, idx: usize, val: bool) {
        assert!(idx < Self::BIT_LEN);
        if val {
            *self |= 1 << idx;
        } else {
            *self &= !(1 << idx);
        }
    }

    fn get_b(&self, idx: usize) -> bool {
        assert!(idx < Self::BIT_LEN);
        (self & 1 << idx) != 0
    }

    fn toggle(&mut self, idx: usize) {
        assert!(idx <  Self::BIT_LEN);
        *self ^= 1 << idx;
    }
}

impl <T:BitOper> BitArrayOper<T> for [T] {
    fn get_blen(&self) -> usize {
        self.len() * T::BIT_LEN
    }

    fn get_b(&self, idx: usize) -> bool {
        self[idx / T::BIT_LEN].get_b(idx % T::BIT_LEN)
    }

    fn set_b(&mut self, idx: usize, val: bool) {
        self[idx / T::BIT_LEN].set_b(idx % T::BIT_LEN, val);
    }

    fn toggle(&mut self, idx: usize) {
        self[idx / T::BIT_LEN].toggle(idx % T::BIT_LEN);
    }
}

extern crate test;

use test::Bencher;

const len: usize = 256;

fn set_bitfield<T:BitField>(v: &mut Vec<T>) {
        for i in 0..v.len() * T::BIT_LENGTH {
            v.as_mut_slice().set_bit(i, true);;
        }
 }

fn get_bitfield<T:BitField>(v: &Vec<T>) {
        for i in 0..v.len() * T::BIT_LENGTH {
            let _b = v.as_slice().get_bit(i);
        }
 }

 fn set_trivial<T:BitOper>(v: &mut Vec<T>) {
        for i in 0..v.len() * T::BIT_LEN {
            v.set_b(i, true);
        }
}

 fn toggle<T:BitOper>(v: &mut Vec<T>) {
        for i in 0..v.len() * T::BIT_LEN {
            v.toggle(i);
        }
}

 fn get_trivial<T:BitOper>(v: &Vec<T>) {
        for i in 0..v.len() * T::BIT_LEN {
            let _b = v.get_b(i);
        }
}

#[bench]
fn u8_set_bitfield(b: &mut Bencher) {
    let mut v = vec![0u8; len];
    b.iter(|| {
        set_bitfield(&mut v);
    });
}

#[bench]
fn u8_set_trivial(b: &mut Bencher) {
    let mut v = vec![0u8; len];

    b.iter(|| {
       set_trivial(&mut v);
    });
}

#[bench]
fn u8_get_bitfield(b: &mut Bencher) {
    let v = vec![1u8; len];
    b.iter(|| {
       get_bitfield(&v);
    });
}

#[bench]
fn u8_get_trivial(b: &mut Bencher) {
    let v = vec![1u8; len];
    b.iter(|| {
        get_trivial(&v);
    });
}

#[bench]
fn u32_set_bitfield(b: &mut Bencher) {
    let mut v = vec![0u32; len];
    b.iter(|| {
        set_bitfield(&mut v);
    });
}

#[bench]
fn u32_set_trivial(b: &mut Bencher) {
    let mut v = vec![0u32; len];

    b.iter(|| {
       set_trivial(&mut v);
    });
}

#[bench]
fn u32_get_bitfield(b: &mut Bencher) {
    let v = vec![1u32; len];
    b.iter(|| {
       get_bitfield(&v);
    });
}

#[bench]
fn u32_get_trivial(b: &mut Bencher) {
    let v = vec![1u32; len];
    b.iter(|| {
        get_trivial(&v);
    });
}

#[bench]
fn u64_set_bitfield(b: &mut Bencher) {
    let mut v = vec![0u64; len];
    b.iter(|| {
        set_bitfield(&mut v);
    });
}

#[bench]
fn u64_set_trivial(b: &mut Bencher) {
    let mut v = vec![0u64; len];

    b.iter(|| {
       set_trivial(&mut v);
    });
}

#[bench]
fn u64_get_bitfield(b: &mut Bencher) {
    let v = vec![1u64; len];
    b.iter(|| {
       get_bitfield(&v);
    });
}

#[bench]
fn u64_get_trivial(b: &mut Bencher) {
    let v = vec![1u64; len];
    b.iter(|| {
        get_trivial(&v);
    });
}
<|endoftext|>


<commit_before>use Bitmap;
use Treemap;

use std::io::{Cursor, Result, Seek, SeekFrom};
use byteorder::{NativeEndian, BigEndian, ReadBytesExt, WriteBytesExt};

pub trait Serializer {}

/// croaring::Treemap serializer that is compatible with C++ version found in
/// CRoaring at https://github.com/RoaringBitmap/CRoaring/blob/master/cpp/roaring64map.hh
pub trait NativeSerializer: Serializer {
    type Item;

    fn serialize(&self) -> Result<Vec<u8>>;
    fn deserialize(buffer: &[u8]) -> Result<Self::Item>;
}

impl Serializer for Treemap {}

impl NativeSerializer for Treemap {
    type Item = Treemap;

    fn serialize(&self) -> Result<Vec<u8>> {
        let mut buffer = vec![];
        buffer.write_u64::<NativeEndian>(self.map.len() as u64)?;

        for (index, bitmap) in &self.map {
            buffer.write_u32::<NativeEndian>(*index)?;
            let bitmap_buffer = bitmap.serialize();
            buffer.extend(bitmap_buffer);
        }

        Ok(buffer)
    }

    fn deserialize(buffer: &[u8]) -> Result<Self> {
        let mut cursor = Cursor::new(&buffer);
        let mut treemap = Treemap::create();
        let bitmap_count = cursor.read_u64::<NativeEndian>()?;

        for _ in 0..bitmap_count {
            let index = cursor.read_u32::<NativeEndian>()?;
            let bitmap = Bitmap::deserialize(
                &buffer[cursor.position() as usize..]
            );
            cursor.seek(
                SeekFrom::Current(bitmap.get_serialized_size_in_bytes() as i64)
            )?;
            treemap.map.insert(index, bitmap);
        }

        Ok(treemap)
    }
}

/// croaring::Treemap serializer that is compatible with JVM version of Treemap
/// found in RoaringBitmap Java implementation at:
/// https://github.com/RoaringBitmap/RoaringBitmap/blob/master/roaringbitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java
pub trait JvmSerializer: Serializer {
    type Item;

    fn serialize(&self) -> Result<Vec<u8>>;
    fn deserialize(buffer: &[u8]) -> Result<Self::Item>;
}

impl JvmSerializer for Treemap {
    type Item = Treemap;

    fn serialize(&self) -> Result<Vec<u8>> {
        let mut buffer = vec![];
        buffer.write_u8(0)?;
        buffer.write_u32::<BigEndian>(self.map.len() as u32)?;

        for (index, bitmap) in &self.map {
            buffer.write_u32::<BigEndian>(*index)?;
            let bitmap_buffer = bitmap.serialize();
            buffer.extend(bitmap_buffer);
        }

        Ok(buffer)
    }

    fn deserialize(buffer: &[u8]) -> Result<Self::Item> {
        let mut cursor = Cursor::new(&buffer);
        cursor.read_u8()?; // read and discard boolean indicator

        let mut treemap = Treemap::create();
        let bitmap_count = cursor.read_u32::<BigEndian>()?;

        for _ in 0..bitmap_count {
            let index = cursor.read_u32::<BigEndian>()?;
            let bitmap = Bitmap::deserialize(
                &buffer[cursor.position() as usize..]
            );
            cursor.seek(
                SeekFrom::Current(bitmap.get_serialized_size_in_bytes() as i64)
            )?;
            treemap.map.insert(index, bitmap);
        }

        Ok(treemap)
    }
}
<commit_msg>Add Treemap::get_serialized_size_in_bytes<commit_after>use Bitmap;
use Treemap;

use std::io::{Cursor, Result, Seek, SeekFrom};
use std::mem::size_of;
use byteorder::{NativeEndian, BigEndian, ReadBytesExt, WriteBytesExt};

pub trait Serializer {}

/// croaring::Treemap serializer that is compatible with C++ version found in
/// CRoaring at https://github.com/RoaringBitmap/CRoaring/blob/master/cpp/roaring64map.hh
pub trait NativeSerializer: Serializer {
    type Item;

    fn serialize(&self) -> Result<Vec<u8>>;
    fn deserialize(buffer: &[u8]) -> Result<Self::Item>;
    fn get_serialized_size_in_bytes(&self) -> usize;
}

impl Serializer for Treemap {}

impl NativeSerializer for Treemap {
    type Item = Treemap;

    fn serialize(&self) -> Result<Vec<u8>> {
        let mut buffer = vec![];
        buffer.write_u64::<NativeEndian>(self.map.len() as u64)?;

        for (index, bitmap) in &self.map {
            buffer.write_u32::<NativeEndian>(*index)?;
            let bitmap_buffer = bitmap.serialize();
            buffer.extend(bitmap_buffer);
        }

        Ok(buffer)
    }

    fn deserialize(buffer: &[u8]) -> Result<Self> {
        let mut cursor = Cursor::new(&buffer);
        let mut treemap = Treemap::create();
        let bitmap_count = cursor.read_u64::<NativeEndian>()?;

        for _ in 0..bitmap_count {
            let index = cursor.read_u32::<NativeEndian>()?;
            let bitmap = Bitmap::deserialize(
                &buffer[cursor.position() as usize..]
            );
            cursor.seek(
                SeekFrom::Current(bitmap.get_serialized_size_in_bytes() as i64)
            )?;
            treemap.map.insert(index, bitmap);
        }

        Ok(treemap)
    }

    /// How many bytes are required to serialize this bitmap with
    /// NativeSerializer
    ///
    /// # Examples
    ///
    /// ```
    /// use croaring::Treemap;
    /// use croaring::treemap::NativeSerializer;
    ///
    /// let mut treemap = Treemap::create();
    ///
    /// for i in 100..1000 {
    ///   treemap.add(i);
    /// }
    ///
    /// treemap.add(std::u32::MAX as u64);
    /// treemap.add(std::u64::MAX);
    ///
    /// assert_eq!(treemap.get_serialized_size_in_bytes(), 1860);
    /// ```
    fn get_serialized_size_in_bytes(&self) -> usize {
        self.map.iter().fold(
            size_of::<u64>() + self.map.len() * size_of::<u32>(),
            |sum, (_, bitmap)| sum + bitmap.get_serialized_size_in_bytes()
        )
    }
}

/// croaring::Treemap serializer that is compatible with JVM version of Treemap
/// found in RoaringBitmap Java implementation at:
/// https://github.com/RoaringBitmap/RoaringBitmap/blob/master/roaringbitmap/src/main/java/org/roaringbitmap/longlong/Roaring64NavigableMap.java
pub trait JvmSerializer: Serializer {
    type Item;

    fn serialize(&self) -> Result<Vec<u8>>;
    fn deserialize(buffer: &[u8]) -> Result<Self::Item>;
    fn get_serialized_size_in_bytes(&self) -> usize;
}

impl JvmSerializer for Treemap {
    type Item = Treemap;

    fn serialize(&self) -> Result<Vec<u8>> {
        let mut buffer = vec![];
        buffer.write_u8(0)?;
        buffer.write_u32::<BigEndian>(self.map.len() as u32)?;

        for (index, bitmap) in &self.map {
            buffer.write_u32::<BigEndian>(*index)?;
            let bitmap_buffer = bitmap.serialize();
            buffer.extend(bitmap_buffer);
        }

        Ok(buffer)
    }

    fn deserialize(buffer: &[u8]) -> Result<Self::Item> {
        let mut cursor = Cursor::new(&buffer);
        cursor.read_u8()?; // read and discard boolean indicator

        let mut treemap = Treemap::create();
        let bitmap_count = cursor.read_u32::<BigEndian>()?;

        for _ in 0..bitmap_count {
            let index = cursor.read_u32::<BigEndian>()?;
            let bitmap = Bitmap::deserialize(
                &buffer[cursor.position() as usize..]
            );
            cursor.seek(
                SeekFrom::Current(bitmap.get_serialized_size_in_bytes() as i64)
            )?;
            treemap.map.insert(index, bitmap);
        }

        Ok(treemap)
    }

    /// How many bytes are required to serialize this bitmap with
    /// JvmSerializer
    ///
    /// # Examples
    ///
    /// ```
    /// use croaring::Treemap;
    /// use croaring::treemap::JvmSerializer;
    ///
    /// let mut treemap = Treemap::create();
    ///
    /// for i in 100..1000 {
    ///   treemap.add(i);
    /// }
    ///
    /// treemap.add(std::u32::MAX as u64);
    /// treemap.add(std::u64::MAX);
    ///
    /// assert_eq!(treemap.get_serialized_size_in_bytes(), 1857);
    /// ```
    fn get_serialized_size_in_bytes(&self) -> usize {
        self.map.iter().fold(
            size_of::<u8>() + size_of::<u32>() + self.map.len() * size_of::<u32>(),
            |sum, (_, bitmap)| sum + bitmap.get_serialized_size_in_bytes()
        )
    }
}
<|endoftext|>


<commit_before>use std::{convert::TryFrom, env, process::exit};

use ruma_client::{
    self,
    api::r0,
    events::{
        room::message::{MessageEventContent, TextMessageEventContent},
        EventType,
    },
    identifiers::RoomAliasId,
    Client,
};
use url::Url;

async fn hello_world(homeserver_url: Url, room: String) -> anyhow::Result<()> {
    let client = Client::new(homeserver_url, None);

    client.register_guest().await?;
    let response = client
        .request(r0::alias::get_alias::Request {
            room_alias: RoomAliasId::try_from(&room[..]).unwrap(),
        })
        .await?;

    let room_id = response.room_id;

    client
        .request(r0::membership::join_room_by_id::Request {
            room_id: room_id.clone(),
            third_party_signed: None,
        })
        .await?;

    client
        .request(r0::message::create_message_event::Request {
            room_id,
            event_type: EventType::RoomMessage,
            txn_id: "1".to_owned(),
            data: MessageEventContent::Text(TextMessageEventContent {
                body: "Hello World!".to_owned(),
                format: None,
                formatted_body: None,
                relates_to: None,
            })
            .into(),
        })
        .await?;

    Ok(())
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let (homeserver_url, room) = match (env::args().nth(1), env::args().nth(2)) {
        (Some(a), Some(b)) => (a, b),
        _ => {
            eprintln!(
                "Usage: {} <homeserver_url> <room>",
                env::args().next().unwrap()
            );
            exit(1)
        }
    };

    hello_world(homeserver_url.parse().unwrap(), room).await
}
<commit_msg>Fix hello_world example<commit_after>use std::{convert::TryFrom, env, process::exit};

use ruma_client::{
    self,
    api::r0,
    events::{
        room::message::{MessageEventContent, TextMessageEventContent},
        EventType,
    },
    identifiers::RoomAliasId,
    Client,
};
use serde_json::value::to_raw_value as to_raw_json_value;
use url::Url;

async fn hello_world(homeserver_url: Url, room: String) -> anyhow::Result<()> {
    let client = Client::new(homeserver_url, None);

    client.register_guest().await?;
    let response = client
        .request(r0::alias::get_alias::Request {
            room_alias: RoomAliasId::try_from(&room[..]).unwrap(),
        })
        .await?;

    let room_id = response.room_id;

    client
        .request(r0::membership::join_room_by_id::Request {
            room_id: room_id.clone(),
            third_party_signed: None,
        })
        .await?;

    client
        .request(r0::message::create_message_event::Request {
            room_id,
            event_type: EventType::RoomMessage,
            txn_id: "1".to_owned(),
            data: to_raw_json_value(&MessageEventContent::Text(TextMessageEventContent {
                body: "Hello World!".to_owned(),
                format: None,
                formatted_body: None,
                relates_to: None,
            }))?,
        })
        .await?;

    Ok(())
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let (homeserver_url, room) = match (env::args().nth(1), env::args().nth(2)) {
        (Some(a), Some(b)) => (a, b),
        _ => {
            eprintln!(
                "Usage: {} <homeserver_url> <room>",
                env::args().next().unwrap()
            );
            exit(1)
        }
    };

    hello_world(homeserver_url.parse().unwrap(), room).await
}
<|endoftext|>


<commit_before>// Copyright (C) 2019 Guillaume Desmottes <guillaume.desmottes@collabora.com>
//
// 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.

#![crate_type = "cdylib"]

#[macro_use]
extern crate glib;
#[macro_use]
extern crate gstreamer as gst;

mod cdgdec;

fn plugin_init(plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
    cdgdec::register(plugin)
}

gst_plugin_define!(
    cdg,
    "CDG Plugin",
    plugin_init,
    "1.0",
    "MIT/X11",
    "cdg",
    "cdg",
    "https://gitlab.freedesktop.org/gstreamer/gst-plugin-rs",
    "2019-05-01"
);
<commit_msg>cdg: fix plugin name<commit_after>// Copyright (C) 2019 Guillaume Desmottes <guillaume.desmottes@collabora.com>
//
// 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.

#![crate_type = "cdylib"]

#[macro_use]
extern crate glib;
#[macro_use]
extern crate gstreamer as gst;

mod cdgdec;

fn plugin_init(plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
    cdgdec::register(plugin)
}

gst_plugin_define!(
    rscdg,
    "CDG Plugin",
    plugin_init,
    "1.0",
    "MIT/X11",
    "cdg",
    "cdg",
    "https://gitlab.freedesktop.org/gstreamer/gst-plugin-rs",
    "2019-05-01"
);
<|endoftext|>


<commit_before>// Copyright (c) Aptos
// SPDX-License-Identifier: Apache-2.0

use crate::generate_traffic;
use forge::system_metrics::{MetricsThreshold, SystemMetricsThreshold};
use forge::{NetworkContext, NetworkTest, Result, Test};
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::runtime::Runtime;

pub struct PerformanceBenchmarkWithFN;

impl Test for PerformanceBenchmarkWithFN {
    fn name(&self) -> &'static str {
        "performance benchmark with full nodes"
    }
}

impl NetworkTest for PerformanceBenchmarkWithFN {
    fn run<'t>(&self, ctx: &mut NetworkContext<'t>) -> Result<()> {
        let duration = ctx.global_job.duration;

        let all_fullnodes = ctx
            .swarm()
            .full_nodes()
            .map(|v| v.peer_id())
            .collect::<Vec<_>>();

        // Generate some traffic
        let start_timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards")
            .as_secs();
        let txn_stat = generate_traffic(ctx, &all_fullnodes, duration, 1)?;
        ctx.report
            .report_txn_stats(self.name().to_string(), &txn_stat, duration);
        // ensure we meet the success criteria
        ctx.check_for_success(&txn_stat, &duration)?;
        let end_timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards")
            .as_secs();

        let runtime = Runtime::new().unwrap();

        runtime.block_on(ctx.swarm().ensure_no_validator_restart())?;
        runtime.block_on(ctx.swarm().ensure_no_fullnode_restart())?;

        // Threshold of more than 12 CPU cores for 30% of the time
        let cpu_threshold = MetricsThreshold::new(12, 30);
        // Threshold of more than 3 GB of memory for 30% of the time
        let memory_threshold = MetricsThreshold::new(3 * 1024 * 1024 * 1024, 30);
        runtime.block_on(ctx.swarm().ensure_healthy_system_metrics(
            start_timestamp as i64,
            end_timestamp as i64,
            SystemMetricsThreshold::new(cpu_threshold, memory_threshold),
        ))?;

        Ok(())
    }
}
<commit_msg>[Forge] Disable system metrics check (#3137)<commit_after>// Copyright (c) Aptos
// SPDX-License-Identifier: Apache-2.0

use crate::generate_traffic;
use forge::{NetworkContext, NetworkTest, Result, Test};
use tokio::runtime::Runtime;

pub struct PerformanceBenchmarkWithFN;

impl Test for PerformanceBenchmarkWithFN {
    fn name(&self) -> &'static str {
        "performance benchmark with full nodes"
    }
}

impl NetworkTest for PerformanceBenchmarkWithFN {
    fn run<'t>(&self, ctx: &mut NetworkContext<'t>) -> Result<()> {
        let duration = ctx.global_job.duration;

        let all_fullnodes = ctx
            .swarm()
            .full_nodes()
            .map(|v| v.peer_id())
            .collect::<Vec<_>>();

        // Generate some traffic
        let txn_stat = generate_traffic(ctx, &all_fullnodes, duration, 1)?;
        ctx.report
            .report_txn_stats(self.name().to_string(), &txn_stat, duration);
        // ensure we meet the success criteria
        ctx.check_for_success(&txn_stat, &duration)?;
        let runtime = Runtime::new().unwrap();

        runtime.block_on(ctx.swarm().ensure_no_validator_restart())?;
        runtime.block_on(ctx.swarm().ensure_no_fullnode_restart())?;

        // TODO(skedia) enable them after resolving failure in
        // https://github.com/aptos-labs/aptos-core/runs/7904217460?check_suite_focus=true
        // Threshold of more than 12 CPU cores for 30% of the time
        // let cpu_threshold = MetricsThreshold::new(12, 30);
        // Threshold of more than 3 GB of memory for 30% of the time
        // let memory_threshold = MetricsThreshold::new(3 * 1024 * 1024 * 1024, 30);
        // runtime.block_on(ctx.swarm().ensure_healthy_system_metrics(
        //     start_timestamp as i64,
        //     end_timestamp as i64,
        //     SystemMetricsThreshold::new(cpu_threshold, memory_threshold),
        // ))?;
        Ok(())
    }
}
<|endoftext|>