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

fn part1_next(n: u32, d: char) -> u32 {
    match d {
        'U' if n > 3 => n - 3,
        'D' if n < 7 => n + 3,
        'L' if n % 3 != 1 => n - 1,
        'R' if n % 3 != 0 => n + 1,
        _ => n,
    }
}

// i feel dirty
fn part2_next(n: char, d: char) -> char {
    match d {
        'U' => match n {
            '3' => '1',
            '6' | '7' | '8' => char::from_digit(n.to_digit(10).unwrap() - 4, 10).unwrap(),
            'A' => '6',
            'B' => '7',
            'C' => '8',
            'D' => 'B',
            _ => n
         },
        'D' => match n {
            '1' => '3',
            '2' | '3' | '4' => char::from_digit(n.to_digit(10).unwrap() + 4, 10).unwrap(),
            '6' => 'A',
            '7' => 'B',
            '8' => 'C',
            'B' => 'D',
            _ => n,
        },
        'L' => match n {
            '3' | '4' | '6' | '7' | '8' | '9' => char::from_digit(n.to_digit(10).unwrap() - 1, 10).unwrap(),
            'B' => 'A',
            'C' => 'B',
            _ => n
        },
        'R' => match n {
            '2' | '3' | '5' | '6' | '7' | '8' => char::from_digit(n.to_digit(10).unwrap() + 1, 10).unwrap(),
            'A' => 'B',
            'B' => 'C',
            _ => n,
        },
        _ => panic!("invalid input"),
    }
}

fn main() {
    let mut part1 = String::new();
    let mut part2 = String::new();
    let mut p1 = 5;
    let mut p2 = '5';

    let stdin = io::stdin();
    let stdin = stdin.lock().lines();

    for line in stdin {
        let line = line.unwrap();
        for c in line.chars() {
            p1 = part1_next(p1, c);
            p2 = part2_next(p2, c);
        }
        part1.push(char::from_digit(p1, 10).unwrap());
        part2.push(p2);
    }

    println!("part1: {}", part1);
    println!("part2: {}", part2);
}
<commit_msg>cargo fmt<commit_after>use std::io;
use std::io::prelude::*;
use std::char;

fn part1_next(n: u32, d: char) -> u32 {
    match d {
        'U' if n > 3 => n - 3,
        'D' if n < 7 => n + 3,
        'L' if n % 3 != 1 => n - 1,
        'R' if n % 3 != 0 => n + 1,
        _ => n,
    }
}

// i feel dirty
fn part2_next(n: char, d: char) -> char {
    match d {
        'U' => {
            match n {
                '3' => '1',
                '6' | '7' | '8' => char::from_digit(n.to_digit(10).unwrap() - 4, 10).unwrap(),
                'A' => '6',
                'B' => '7',
                'C' => '8',
                'D' => 'B',
                _ => n,
            }
        }
        'D' => {
            match n {
                '1' => '3',
                '2' | '3' | '4' => char::from_digit(n.to_digit(10).unwrap() + 4, 10).unwrap(),
                '6' => 'A',
                '7' => 'B',
                '8' => 'C',
                'B' => 'D',
                _ => n,
            }
        }
        'L' => {
            match n {
                '3' | '4' | '6' | '7' | '8' | '9' => {
                    char::from_digit(n.to_digit(10).unwrap() - 1, 10).unwrap()
                }
                'B' => 'A',
                'C' => 'B',
                _ => n,
            }
        }
        'R' => {
            match n {
                '2' | '3' | '5' | '6' | '7' | '8' => {
                    char::from_digit(n.to_digit(10).unwrap() + 1, 10).unwrap()
                }
                'A' => 'B',
                'B' => 'C',
                _ => n,
            }
        }
        _ => panic!("invalid input"),
    }
}

fn main() {
    let mut part1 = String::new();
    let mut part2 = String::new();
    let mut p1 = 5;
    let mut p2 = '5';

    let stdin = io::stdin();
    let stdin = stdin.lock().lines();

    for line in stdin {
        let line = line.unwrap();
        for c in line.chars() {
            p1 = part1_next(p1, c);
            p2 = part2_next(p2, c);
        }
        part1.push(char::from_digit(p1, 10).unwrap());
        part2.push(p2);
    }

    println!("part1: {}", part1);
    println!("part2: {}", part2);
}
<|endoftext|>


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

fn main() {
    let mut counts = Vec::<HashMap<char, u32>>::new();
    for _ in 0..8 {
        counts.push(HashMap::new());
    }

    let stdin = io::stdin();
    let stdin = stdin.lock().lines();
    for line in stdin {
        let line = line.unwrap();
        for (i, c) in line.chars().enumerate() {
            *counts[i].entry(c).or_insert(0) += 1;
        }
    }
    let part1: String = counts.iter()
        .map(|hm| {
            hm.into_iter().fold(('_', 0), |(c1, max), (&c2, &count)| if count > max {
                (c2, count)
            } else {
                (c1, max)
            })

        })
        .map(|(c, _)| c)
        .collect();

    let part2: String = counts.iter()
        .map(|hm| {
            hm.into_iter().fold(('_', std::u32::MAX),
                                |(c1, min), (&c2, &count)| if count < min {
                                    (c2, count)
                                } else {
                                    (c1, min)
                                })

        })
        .map(|(c, _)| c)
        .collect();
    println!("{:?}", part1);
    println!("{:?}", part2);
}
<commit_msg>do not reimplement max_by_key with fold<commit_after>use std::io;
use std::io::prelude::*;
use std::collections::HashMap;

fn main() {
    let mut counts = Vec::<HashMap<char, u32>>::new();
    for _ in 0..8 {
        counts.push(HashMap::new());
    }

    let stdin = io::stdin();
    let stdin = stdin.lock().lines();
    for line in stdin {
        let line = line.unwrap();
        for (i, c) in line.chars().enumerate() {
            *counts[i].entry(c).or_insert(0) += 1;
        }
    }
    let part1: String = counts.iter()
        .map(|hm| *hm.into_iter().max_by_key(|&(_, n)| n).unwrap().0)
        .collect();
    let part2: String = counts.iter()
        .map(|hm| *hm.into_iter().min_by_key(|&(_, n)| n).unwrap().0)
        .collect();
    println!("{:?}", part1);
    println!("{:?}", part2);
}
<|endoftext|>


<commit_before>use std::str::FromStr;

use eyre::{bail, Result};
use graph_triples::ResourceInfo;
use serde::Serialize;
use strum::AsRefStr;

/// An execution plan for a document
#[derive(Debug, Default, Serialize)]
pub struct Plan {
    /// The options used to generate the plan
    pub options: PlanOptions,

    /// The stages to be executed
    pub stages: Vec<Stage>,
}

impl Plan {
    pub fn to_markdown(&self) -> String {
        let options = self.options.to_markdown();
        let stages = self
            .stages
            .iter()
            .enumerate()
            .map(|(index, stage)| format!("## Stage {}\n\n{}", index + 1, stage.to_markdown()))
            .collect::<Vec<String>>()
            .join("\n\n");
        format!("{}\n\n{}", options, stages)
    }
}

/// Options for generating a plan
#[derive(Debug, Clone, Serialize)]
pub struct PlanOptions {
    /// The ordering of nodes used when generating the plan
    pub ordering: PlanOrdering,

    /// The maximum step concurrency
    ///
    /// Limits the number of [`Step`]s that can be grouped together in a [`Stage`].
    /// Defaults to the number of logical CPU cores on the current machine.
    pub max_concurrency: usize,
}

impl PlanOptions {
    pub fn default_ordering() -> PlanOrdering {
        PlanOrdering::Topological
    }

    pub fn default_max_concurrency() -> usize {
        num_cpus::get()
    }

    pub fn to_markdown(&self) -> String {
        format!(
            r"## Options

- Ordering: {}
- Maximum concurrency: {}",
            self.ordering.as_ref(),
            self.max_concurrency
        )
    }
}

impl Default for PlanOptions {
    fn default() -> Self {
        Self {
            ordering: Self::default_ordering(),
            max_concurrency: Self::default_max_concurrency(),
        }
    }
}

/// The ordering of nodes used when generating a plan
#[derive(Debug, Clone, Serialize, AsRefStr)]
pub enum PlanOrdering {
    /// Nodes are executed in the order that they appear in the
    /// document, top to bottom, left to right.
    Appearance,

    /// Nodes are executed in the order that ensures
    /// that the dependencies of a node are executed before it is
    Topological,
}

impl FromStr for PlanOrdering {
    type Err = eyre::Report;

    fn from_str(str: &str) -> Result<PlanOrdering> {
        Ok(match str.to_lowercase().as_str() {
            "a" | "ap" | "app" | "appear" | "appearance" => PlanOrdering::Appearance,
            "t" | "to" | "top" | "topo" | "topological" => PlanOrdering::Topological,
            _ => bail!("Unrecognized plan ordering: {}", str),
        })
    }
}

/// A stage in an execution plan
///
/// A stage represents a group of [`Step`]s that can be executed concurrently
/// (e.g. because they can be executed in different kernels or a kernel fork)
#[derive(Debug, Default, Serialize)]
pub struct Stage {
    /// The steps to be executed
    pub steps: Vec<Step>,
}

impl Stage {
    pub fn to_markdown(&self) -> String {
        self.steps
            .iter()
            .map(|step| ["- ", &step.to_markdown()].concat())
            .collect::<Vec<String>>()
            .join("\n")
    }
}

/// A step in an execution plan
///
/// A step is the smallest unit in an execution plan and corresponds to a kernel [`Task`]
/// (but to avoid confusion we use a different name here).
#[derive(Debug, Serialize)]
pub struct Step {
    /// Information on the resource to be executed
    ///
    /// Passed to kernel for `symbols_used` etc
    pub resource_info: ResourceInfo,

    /// The name of the kernel that the code will be executed in
    ///
    /// If this is `None` it indicates that no kernel capable of executing
    /// the node is available on the machine
    pub kernel_name: Option<String>,

    /// The code will be executed in a fork of the kernel
    ///
    /// Code that has no side effects or who's side effects should be
    /// ignored (i.e. is "@pure") are executed in a fork of the kernel.
    pub is_fork: bool,
}

impl Step {
    pub fn to_markdown(&self) -> String {
        let node_type = self.resource_info.resource.node_type().unwrap_or("?");
        let node_id = self.resource_info.resource.node_id().unwrap_or("?");
        let kernel_name = self.kernel_name.as_deref().unwrap_or("?");
        let fork = if self.is_fork { "**fork**" } else { "" };

        format!(
            "Run `{}` *#{}* in *{}* kernel {}",
            node_type, node_id, kernel_name, fork,
        )
    }
}
<commit_msg>fix(Execution plan): Remove unessary # prefix for id<commit_after>use std::str::FromStr;

use eyre::{bail, Result};
use graph_triples::ResourceInfo;
use serde::Serialize;
use strum::AsRefStr;

/// An execution plan for a document
#[derive(Debug, Default, Serialize)]
pub struct Plan {
    /// The options used to generate the plan
    pub options: PlanOptions,

    /// The stages to be executed
    pub stages: Vec<Stage>,
}

impl Plan {
    pub fn to_markdown(&self) -> String {
        let options = self.options.to_markdown();
        let stages = self
            .stages
            .iter()
            .enumerate()
            .map(|(index, stage)| format!("## Stage {}\n\n{}", index + 1, stage.to_markdown()))
            .collect::<Vec<String>>()
            .join("\n\n");
        format!("{}\n\n{}", options, stages)
    }
}

/// Options for generating a plan
#[derive(Debug, Clone, Serialize)]
pub struct PlanOptions {
    /// The ordering of nodes used when generating the plan
    pub ordering: PlanOrdering,

    /// The maximum step concurrency
    ///
    /// Limits the number of [`Step`]s that can be grouped together in a [`Stage`].
    /// Defaults to the number of logical CPU cores on the current machine.
    pub max_concurrency: usize,
}

impl PlanOptions {
    pub fn default_ordering() -> PlanOrdering {
        PlanOrdering::Topological
    }

    pub fn default_max_concurrency() -> usize {
        num_cpus::get()
    }

    pub fn to_markdown(&self) -> String {
        format!(
            r"## Options

- Ordering: {}
- Maximum concurrency: {}",
            self.ordering.as_ref(),
            self.max_concurrency
        )
    }
}

impl Default for PlanOptions {
    fn default() -> Self {
        Self {
            ordering: Self::default_ordering(),
            max_concurrency: Self::default_max_concurrency(),
        }
    }
}

/// The ordering of nodes used when generating a plan
#[derive(Debug, Clone, Serialize, AsRefStr)]
pub enum PlanOrdering {
    /// Nodes are executed in the order that they appear in the
    /// document, top to bottom, left to right.
    Appearance,

    /// Nodes are executed in the order that ensures
    /// that the dependencies of a node are executed before it is
    Topological,
}

impl FromStr for PlanOrdering {
    type Err = eyre::Report;

    fn from_str(str: &str) -> Result<PlanOrdering> {
        Ok(match str.to_lowercase().as_str() {
            "a" | "ap" | "app" | "appear" | "appearance" => PlanOrdering::Appearance,
            "t" | "to" | "top" | "topo" | "topological" => PlanOrdering::Topological,
            _ => bail!("Unrecognized plan ordering: {}", str),
        })
    }
}

/// A stage in an execution plan
///
/// A stage represents a group of [`Step`]s that can be executed concurrently
/// (e.g. because they can be executed in different kernels or a kernel fork)
#[derive(Debug, Default, Serialize)]
pub struct Stage {
    /// The steps to be executed
    pub steps: Vec<Step>,
}

impl Stage {
    pub fn to_markdown(&self) -> String {
        self.steps
            .iter()
            .map(|step| ["- ", &step.to_markdown()].concat())
            .collect::<Vec<String>>()
            .join("\n")
    }
}

/// A step in an execution plan
///
/// A step is the smallest unit in an execution plan and corresponds to a kernel [`Task`]
/// (but to avoid confusion we use a different name here).
#[derive(Debug, Serialize)]
pub struct Step {
    /// Information on the resource to be executed
    ///
    /// Passed to kernel for `symbols_used` etc
    pub resource_info: ResourceInfo,

    /// The name of the kernel that the code will be executed in
    ///
    /// If this is `None` it indicates that no kernel capable of executing
    /// the node is available on the machine
    pub kernel_name: Option<String>,

    /// The code will be executed in a fork of the kernel
    ///
    /// Code that has no side effects or who's side effects should be
    /// ignored (i.e. is "@pure") are executed in a fork of the kernel.
    pub is_fork: bool,
}

impl Step {
    pub fn to_markdown(&self) -> String {
        let node_type = self.resource_info.resource.node_type().unwrap_or("?");
        let node_id = self.resource_info.resource.node_id().unwrap_or("?");
        let kernel_name = self.kernel_name.as_deref().unwrap_or("?");
        let fork = if self.is_fork { "**fork**" } else { "" };

        format!(
            "Run `{}` *{}* in *{}* kernel {}",
            node_type, node_id, kernel_name, fork,
        )
    }
}
<|endoftext|>


<commit_before>use crate::util;
use anyhow::{bail, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use validator::Validate;

#[derive(Debug, PartialEq, Deserialize, Serialize, Validate)]
pub struct Config {
    #[serde(default)]
    #[validate]
    pub serve: crate::serve::config::Config,

    #[serde(default)]
    #[validate]
    pub plugins: crate::plugins::config::Config,

    #[serde(default)]
    #[validate]
    pub upgrade: crate::upgrade::config::Config,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            serve: Default::default(),
            plugins: Default::default(),
            upgrade: Default::default(),
        }
    }
}

const CONFIG_FILE: &str = "config.toml";

/// Get the path of the configuration file
fn path() -> Result<PathBuf> {
    #[cfg(not(test))]
    return Ok(util::dirs::config(true)?.join(CONFIG_FILE));

    // When running tests, avoid messing with users existing config
    #[cfg(test)]
    {
        let path = std::env::temp_dir()
            .join("stencila")
            .join("test")
            .join(CONFIG_FILE);
        fs::create_dir_all(path.parent().unwrap())?;
        return Ok(path);
    }
}

/// Read the config from the configuration file
fn read() -> Result<Config> {
    let config_file = path()?;
    let content = fs::read_to_string(config_file).unwrap_or_else(|_| "".to_string());
    let config = toml::from_str(content.as_str())?;
    Ok(config)
}

/// Write the config to the configuration file
fn write(config: Config) -> Result<()> {
    let config_file = path()?;
    let mut file = fs::File::create(config_file)?;
    file.write_all(toml::to_string(&config)?.as_bytes())?;
    file.sync_data()?;
    Ok(())
}

/// Validate the config
pub fn validate(config: &Config) -> Result<()> {
    if let Err(error) = config.validate() {
        bail!(
            "Invalid configuration; use `config set`, `config reset` or edit {} to fix.\n\n{:#?}",
            path()?.display(),
            error
        )
    }
    Ok(())
}

/// Read and validate the config
pub fn get() -> Result<Config> {
    let config = read()?;
    validate(&config)?;
    Ok(config)
}

/// Ensure that a string is a valid JSON pointer
///
/// Replaces dots (`.`) with slashes (`/`) and ensures a
/// leading slash.
pub fn json_pointer(pointer: &str) -> String {
    let pointer = pointer.replace(".", "/");
    if pointer.starts_with('/') {
        pointer
    } else {
        format!("/{}", pointer)
    }
}

/// Display a config property
pub fn display(pointer: Option<String>) -> Result<String> {
    let config = get()?;
    match pointer {
        None => Ok(toml::to_string(&config)?),
        Some(pointer) => {
            let config = serde_json::to_value(config)?;
            if let Some(part) = config.pointer(json_pointer(&pointer).as_str()) {
                let json = serde_json::to_string(part)?;
                let part: toml::Value = serde_json::from_str(&json)?;
                let toml = toml::to_string(&part)?;
                Ok(toml)
            } else {
                bail!("No configuration value at pointer: {}", pointer)
            }
        }
    }
}

/// Set a config property
pub fn set(pointer: String, value: String) -> Result<()> {
    // Use `read` to avoid validation (user may fix any errors and we
    // validate below anyway).
    let config = read()?;

    let mut config = serde_json::to_value(config)?;
    if let Some(property) = config.pointer_mut(json_pointer(&pointer).as_str()) {
        let value = match serde_json::from_str(&value) {
            Ok(value) => value,
            Err(_) => serde_json::Value::String(value),
        };
        *property = value;
    } else {
        bail!("No configuration value at pointer: {}", pointer)
    };

    let config: Config = serde_json::from_value(config)?;
    validate(&config)?;

    write(config)
}

/// Reset a config property
pub fn reset(property: String) -> Result<()> {
    let config = get()?;

    let config: Config = match property.as_str() {
        "all" => Default::default(),
        "serve" => Config {
            serve: Default::default(),
            ..config
        },
        "upgrade" => Config {
            upgrade: Default::default(),
            ..config
        },
        _ => bail!("No configuration property named: {}", property),
    };

    write(config)
}

/// CLI options for the `config` command
#[cfg(feature = "cli")]
pub mod cli {
    use super::*;
    use structopt::StructOpt;

    #[derive(Debug, StructOpt)]
    #[structopt(
        about = "Manage configuration options",
        setting = structopt::clap::AppSettings::DeriveDisplayOrder
    )]
    pub struct Args {
        #[structopt(subcommand)]
        pub action: Action,
    }

    #[derive(Debug, StructOpt)]
    #[structopt(
        setting = structopt::clap::AppSettings::DeriveDisplayOrder
    )]
    pub enum Action {
        Get(Get),
        Set(Set),
        Reset(Reset),

        #[structopt(about = "Get the directories used for config, cache etc")]
        Dirs,
    }

    #[derive(Debug, StructOpt)]
    #[structopt(about = "Get configuration properties")]
    pub struct Get {
        /// A pointer to a config property e.g. `upgrade.auto`
        pub pointer: Option<String>,
    }

    #[derive(Debug, StructOpt)]
    #[structopt(
        about = "Set configuration properties",
        setting = structopt::clap::AppSettings::TrailingVarArg,
        setting = structopt::clap::AppSettings::AllowLeadingHyphen
    )]
    pub struct Set {
        /// A pointer to a config property e.g. `upgrade.auto`
        pub pointer: String,

        /// The value to set the property to
        pub value: String,
    }

    #[derive(Debug, StructOpt)]
    #[structopt(about = "Reset configuration properties to their defaults")]
    pub struct Reset {
        /// The config property to reset. Use 'all' to reset the entire config.
        pub property: String,
    }

    pub fn config(args: Args) -> Result<()> {
        let Args { action } = args;
        match action {
            Action::Get(action) => {
                let Get { pointer } = action;
                let config = super::display(pointer)?;
                println!("{}", config)
            }
            Action::Set(action) => {
                let Set { pointer, value } = action;
                super::set(pointer, value)?;
            }
            Action::Reset(action) => {
                let Reset { property } = action;
                super::reset(property)?;
            }
            Action::Dirs => {
                let config = util::dirs::config(false)?.display().to_string();
                let plugins = util::dirs::plugins(false)?.display().to_string();
                println!("config: {}\nplugins: {}", config, plugins);
            }
        };
        Ok(())
    }
}

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

    #[test]
    fn test_path() -> Result<()> {
        let path = path()?;
        assert!(path.starts_with(std::env::temp_dir()));
        Ok(())
    }

    #[test]
    fn test_json_pointer() {
        assert_eq!(json_pointer("a"), "/a");
        assert_eq!(json_pointer("a/b"), "/a/b");
        assert_eq!(json_pointer("/a.b"), "/a/b");
        assert_eq!(json_pointer("a.b.c"), "/a/b/c");
    }

    #[test]
    fn test_display() -> Result<()> {
        let all = display(None)?;
        assert!(all.contains("[serve]\n"));
        assert!(all.contains("[upgrade]\n"));

        let serve = display(Some("serve".to_string()))?;
        assert!(!serve.contains("[serve]\n"));
        assert!(serve.contains("url = "));

        let upgrade = display(Some("upgrade".to_string()))?;
        assert!(!upgrade.contains("[upgrade]\n"));
        assert!(upgrade.contains("auto = "));

        assert_eq!(
            display(Some("foo.bar".to_string()))
                .unwrap_err()
                .to_string(),
            "No configuration value at pointer: foo.bar"
        );

        Ok(())
    }

    #[test]
    fn test_get_set_reset() -> Result<()> {
        // Do all this in one test to avoid individual tests
        // clobbering each other

        let default = Config {
            ..Default::default()
        };

        reset("all".to_string())?;
        assert_eq!(get()?, default);

        set("upgrade.auto".to_string(), "off".to_string())?;
        assert_eq!(get()?.upgrade.auto, "off");

        set("upgrade.verbose".to_string(), "true".to_string())?;
        assert_eq!(get()?.upgrade.verbose, true);

        assert_eq!(
            set("foo.bar".to_string(), "baz".to_string())
                .unwrap_err()
                .to_string(),
            "No configuration value at pointer: foo.bar"
        );

        reset("upgrade".to_string())?;
        let upgrade = get()?.upgrade;
        assert_eq!(upgrade.auto, default.upgrade.auto);
        assert_eq!(upgrade.verbose, default.upgrade.verbose);

        reset("serve".to_string())?;

        assert_eq!(
            reset("foo".to_string()).unwrap_err().to_string(),
            "No configuration property named: foo"
        );

        use super::cli::*;

        config(Args {
            action: Action::Get(Get { pointer: None }),
        })?;

        config(Args {
            action: Action::Set(Set {
                pointer: "upgrade.confirm".to_string(),
                value: "true".to_string(),
            }),
        })?;

        config(Args {
            action: Action::Reset(Reset {
                property: "upgrade".to_string(),
            }),
        })?;

        config(Args {
            action: Action::Dirs,
        })?;

        Ok(())
    }
}
<commit_msg>chore(clippy): Remove unnecessary return<commit_after>use crate::util;
use anyhow::{bail, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use validator::Validate;

#[derive(Debug, PartialEq, Deserialize, Serialize, Validate)]
pub struct Config {
    #[serde(default)]
    #[validate]
    pub serve: crate::serve::config::Config,

    #[serde(default)]
    #[validate]
    pub plugins: crate::plugins::config::Config,

    #[serde(default)]
    #[validate]
    pub upgrade: crate::upgrade::config::Config,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            serve: Default::default(),
            plugins: Default::default(),
            upgrade: Default::default(),
        }
    }
}

const CONFIG_FILE: &str = "config.toml";

/// Get the path of the configuration file
fn path() -> Result<PathBuf> {
    #[cfg(not(test))]
    return Ok(util::dirs::config(true)?.join(CONFIG_FILE));

    // When running tests, avoid messing with users existing config
    #[cfg(test)]
    {
        let path = std::env::temp_dir()
            .join("stencila")
            .join("test")
            .join(CONFIG_FILE);
        fs::create_dir_all(path.parent().unwrap())?;
        Ok(path)
    }
}

/// Read the config from the configuration file
fn read() -> Result<Config> {
    let config_file = path()?;
    let content = fs::read_to_string(config_file).unwrap_or_else(|_| "".to_string());
    let config = toml::from_str(content.as_str())?;
    Ok(config)
}

/// Write the config to the configuration file
fn write(config: Config) -> Result<()> {
    let config_file = path()?;
    let mut file = fs::File::create(config_file)?;
    file.write_all(toml::to_string(&config)?.as_bytes())?;
    file.sync_data()?;
    Ok(())
}

/// Validate the config
pub fn validate(config: &Config) -> Result<()> {
    if let Err(error) = config.validate() {
        bail!(
            "Invalid configuration; use `config set`, `config reset` or edit {} to fix.\n\n{:#?}",
            path()?.display(),
            error
        )
    }
    Ok(())
}

/// Read and validate the config
pub fn get() -> Result<Config> {
    let config = read()?;
    validate(&config)?;
    Ok(config)
}

/// Ensure that a string is a valid JSON pointer
///
/// Replaces dots (`.`) with slashes (`/`) and ensures a
/// leading slash.
pub fn json_pointer(pointer: &str) -> String {
    let pointer = pointer.replace(".", "/");
    if pointer.starts_with('/') {
        pointer
    } else {
        format!("/{}", pointer)
    }
}

/// Display a config property
pub fn display(pointer: Option<String>) -> Result<String> {
    let config = get()?;
    match pointer {
        None => Ok(toml::to_string(&config)?),
        Some(pointer) => {
            let config = serde_json::to_value(config)?;
            if let Some(part) = config.pointer(json_pointer(&pointer).as_str()) {
                let json = serde_json::to_string(part)?;
                let part: toml::Value = serde_json::from_str(&json)?;
                let toml = toml::to_string(&part)?;
                Ok(toml)
            } else {
                bail!("No configuration value at pointer: {}", pointer)
            }
        }
    }
}

/// Set a config property
pub fn set(pointer: String, value: String) -> Result<()> {
    // Use `read` to avoid validation (user may fix any errors and we
    // validate below anyway).
    let config = read()?;

    let mut config = serde_json::to_value(config)?;
    if let Some(property) = config.pointer_mut(json_pointer(&pointer).as_str()) {
        let value = match serde_json::from_str(&value) {
            Ok(value) => value,
            Err(_) => serde_json::Value::String(value),
        };
        *property = value;
    } else {
        bail!("No configuration value at pointer: {}", pointer)
    };

    let config: Config = serde_json::from_value(config)?;
    validate(&config)?;

    write(config)
}

/// Reset a config property
pub fn reset(property: String) -> Result<()> {
    let config = get()?;

    let config: Config = match property.as_str() {
        "all" => Default::default(),
        "serve" => Config {
            serve: Default::default(),
            ..config
        },
        "upgrade" => Config {
            upgrade: Default::default(),
            ..config
        },
        _ => bail!("No configuration property named: {}", property),
    };

    write(config)
}

/// CLI options for the `config` command
#[cfg(feature = "cli")]
pub mod cli {
    use super::*;
    use structopt::StructOpt;

    #[derive(Debug, StructOpt)]
    #[structopt(
        about = "Manage configuration options",
        setting = structopt::clap::AppSettings::DeriveDisplayOrder
    )]
    pub struct Args {
        #[structopt(subcommand)]
        pub action: Action,
    }

    #[derive(Debug, StructOpt)]
    #[structopt(
        setting = structopt::clap::AppSettings::DeriveDisplayOrder
    )]
    pub enum Action {
        Get(Get),
        Set(Set),
        Reset(Reset),

        #[structopt(about = "Get the directories used for config, cache etc")]
        Dirs,
    }

    #[derive(Debug, StructOpt)]
    #[structopt(about = "Get configuration properties")]
    pub struct Get {
        /// A pointer to a config property e.g. `upgrade.auto`
        pub pointer: Option<String>,
    }

    #[derive(Debug, StructOpt)]
    #[structopt(
        about = "Set configuration properties",
        setting = structopt::clap::AppSettings::TrailingVarArg,
        setting = structopt::clap::AppSettings::AllowLeadingHyphen
    )]
    pub struct Set {
        /// A pointer to a config property e.g. `upgrade.auto`
        pub pointer: String,

        /// The value to set the property to
        pub value: String,
    }

    #[derive(Debug, StructOpt)]
    #[structopt(about = "Reset configuration properties to their defaults")]
    pub struct Reset {
        /// The config property to reset. Use 'all' to reset the entire config.
        pub property: String,
    }

    pub fn config(args: Args) -> Result<()> {
        let Args { action } = args;
        match action {
            Action::Get(action) => {
                let Get { pointer } = action;
                let config = super::display(pointer)?;
                println!("{}", config)
            }
            Action::Set(action) => {
                let Set { pointer, value } = action;
                super::set(pointer, value)?;
            }
            Action::Reset(action) => {
                let Reset { property } = action;
                super::reset(property)?;
            }
            Action::Dirs => {
                let config = util::dirs::config(false)?.display().to_string();
                let plugins = util::dirs::plugins(false)?.display().to_string();
                println!("config: {}\nplugins: {}", config, plugins);
            }
        };
        Ok(())
    }
}

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

    #[test]
    fn test_path() -> Result<()> {
        let path = path()?;
        assert!(path.starts_with(std::env::temp_dir()));
        Ok(())
    }

    #[test]
    fn test_json_pointer() {
        assert_eq!(json_pointer("a"), "/a");
        assert_eq!(json_pointer("a/b"), "/a/b");
        assert_eq!(json_pointer("/a.b"), "/a/b");
        assert_eq!(json_pointer("a.b.c"), "/a/b/c");
    }

    #[test]
    fn test_display() -> Result<()> {
        let all = display(None)?;
        assert!(all.contains("[serve]\n"));
        assert!(all.contains("[upgrade]\n"));

        let serve = display(Some("serve".to_string()))?;
        assert!(!serve.contains("[serve]\n"));
        assert!(serve.contains("url = "));

        let upgrade = display(Some("upgrade".to_string()))?;
        assert!(!upgrade.contains("[upgrade]\n"));
        assert!(upgrade.contains("auto = "));

        assert_eq!(
            display(Some("foo.bar".to_string()))
                .unwrap_err()
                .to_string(),
            "No configuration value at pointer: foo.bar"
        );

        Ok(())
    }

    #[test]
    fn test_get_set_reset() -> Result<()> {
        // Do all this in one test to avoid individual tests
        // clobbering each other

        let default = Config {
            ..Default::default()
        };

        reset("all".to_string())?;
        assert_eq!(get()?, default);

        set("upgrade.auto".to_string(), "off".to_string())?;
        assert_eq!(get()?.upgrade.auto, "off");

        set("upgrade.verbose".to_string(), "true".to_string())?;
        assert_eq!(get()?.upgrade.verbose, true);

        assert_eq!(
            set("foo.bar".to_string(), "baz".to_string())
                .unwrap_err()
                .to_string(),
            "No configuration value at pointer: foo.bar"
        );

        reset("upgrade".to_string())?;
        let upgrade = get()?.upgrade;
        assert_eq!(upgrade.auto, default.upgrade.auto);
        assert_eq!(upgrade.verbose, default.upgrade.verbose);

        reset("serve".to_string())?;

        assert_eq!(
            reset("foo".to_string()).unwrap_err().to_string(),
            "No configuration property named: foo"
        );

        use super::cli::*;

        config(Args {
            action: Action::Get(Get { pointer: None }),
        })?;

        config(Args {
            action: Action::Set(Set {
                pointer: "upgrade.confirm".to_string(),
                value: "true".to_string(),
            }),
        })?;

        config(Args {
            action: Action::Reset(Reset {
                property: "upgrade".to_string(),
            }),
        })?;

        config(Args {
            action: Action::Dirs,
        })?;

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


<commit_before>use super::*;
use crate::crypto::{double_sha256, Digest, PublicKey};
use crate::script::Script;

pub const SCRIPT_HASH_BUF_PREFIX: u8 = 0x03;

#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ScriptHash(pub Digest);

impl ScriptHash {
    #[inline]
    pub fn from_slice(slice: &[u8]) -> Option<ScriptHash> {
        let digest = Digest::from_slice(slice)?;
        Some(ScriptHash(digest))
    }
}

impl Wif<ScriptHash, Box<str>> for ScriptHash {
    fn from_wif(s: &str) -> Result<ScriptHash, WifError> {
        if s.len() < 3 || &s[0..3] != PUB_ADDRESS_PREFIX {
            return Err(WifError::new(WifErrorKind::InvalidPrefix));
        }
        let raw = match bs58::decode(&s[3..]).into_vec() {
            Ok(bytes) => bytes,
            Err(_) => {
                return Err(WifError::new(WifErrorKind::InvalidBs58Encoding));
            }
        };
        if raw.len() != 37 {
            return Err(WifError::new(WifErrorKind::InvalidLen));
        } else if raw[0] != SCRIPT_HASH_BUF_PREFIX {
            return Err(WifError::new(WifErrorKind::InvalidPrefix));
        }

        let prefixed_key = &raw[0..raw.len() - 4];
        {
            let checksum_a = &raw[raw.len() - 4..raw.len()];
            let checksum_b = &double_sha256(prefixed_key)[0..4];
            if checksum_a != checksum_b {
                return Err(WifError::new(WifErrorKind::InvalidChecksum));
            }
        }

        let key = &prefixed_key[1..prefixed_key.len()];
        Ok(ScriptHash::from_slice(key).unwrap())
    }

    fn to_wif(&self) -> Box<str> {
        let mut buf: Vec<u8> = Vec::<u8>::with_capacity(37);
        buf.push(SCRIPT_HASH_BUF_PREFIX);
        buf.extend_from_slice(self.0.as_ref());

        let checksum = &double_sha256(&buf)[0..4];
        buf.extend_from_slice(checksum);

        let mut s = bs58::encode(buf).into_string();
        s.insert_str(0, PUB_ADDRESS_PREFIX);
        s.into_boxed_str()
    }
}

impl From<&Script> for ScriptHash {
    fn from(script: &Script) -> ScriptHash {
        let hash = double_sha256(script);
        ScriptHash(hash)
    }
}

impl From<Script> for ScriptHash {
    fn from(script: Script) -> ScriptHash {
        (&script).into()
    }
}

impl From<PublicKey> for ScriptHash {
    fn from(key: PublicKey) -> ScriptHash {
        let script: Script = key.into();
        script.into()
    }
}

impl From<&PublicKey> for ScriptHash {
    fn from(key: &PublicKey) -> ScriptHash {
        let script: Script = key.clone().into();
        script.into()
    }
}

impl AsRef<[u8]> for ScriptHash {
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}
<commit_msg>Add P2SH WIF test<commit_after>use super::*;
use crate::crypto::{double_sha256, Digest, PublicKey};
use crate::script::Script;

pub const SCRIPT_HASH_BUF_PREFIX: u8 = 0x03;

#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ScriptHash(pub Digest);

impl ScriptHash {
    #[inline]
    pub fn from_slice(slice: &[u8]) -> Option<ScriptHash> {
        let digest = Digest::from_slice(slice)?;
        Some(ScriptHash(digest))
    }
}

impl Wif<ScriptHash, Box<str>> for ScriptHash {
    fn from_wif(s: &str) -> Result<ScriptHash, WifError> {
        if s.len() < 3 || &s[0..3] != PUB_ADDRESS_PREFIX {
            return Err(WifError::new(WifErrorKind::InvalidPrefix));
        }
        let raw = match bs58::decode(&s[3..]).into_vec() {
            Ok(bytes) => bytes,
            Err(_) => {
                return Err(WifError::new(WifErrorKind::InvalidBs58Encoding));
            }
        };
        if raw.len() != 37 {
            return Err(WifError::new(WifErrorKind::InvalidLen));
        } else if raw[0] != SCRIPT_HASH_BUF_PREFIX {
            return Err(WifError::new(WifErrorKind::InvalidPrefix));
        }

        let prefixed_key = &raw[0..raw.len() - 4];
        {
            let checksum_a = &raw[raw.len() - 4..raw.len()];
            let checksum_b = &double_sha256(prefixed_key)[0..4];
            if checksum_a != checksum_b {
                return Err(WifError::new(WifErrorKind::InvalidChecksum));
            }
        }

        let key = &prefixed_key[1..prefixed_key.len()];
        Ok(ScriptHash::from_slice(key).unwrap())
    }

    fn to_wif(&self) -> Box<str> {
        let mut buf: Vec<u8> = Vec::<u8>::with_capacity(37);
        buf.push(SCRIPT_HASH_BUF_PREFIX);
        buf.extend_from_slice(self.0.as_ref());

        let checksum = &double_sha256(&buf)[0..4];
        buf.extend_from_slice(checksum);

        let mut s = bs58::encode(buf).into_string();
        s.insert_str(0, PUB_ADDRESS_PREFIX);
        s.into_boxed_str()
    }
}

impl From<&Script> for ScriptHash {
    fn from(script: &Script) -> ScriptHash {
        let hash = double_sha256(script);
        ScriptHash(hash)
    }
}

impl From<Script> for ScriptHash {
    fn from(script: Script) -> ScriptHash {
        (&script).into()
    }
}

impl From<PublicKey> for ScriptHash {
    fn from(key: PublicKey) -> ScriptHash {
        let script: Script = key.into();
        script.into()
    }
}

impl From<&PublicKey> for ScriptHash {
    fn from(key: &PublicKey) -> ScriptHash {
        let script: Script = key.clone().into();
        script.into()
    }
}

impl AsRef<[u8]> for ScriptHash {
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}

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

    #[test]
    fn import_p2sh_from_wif() {
        let kp =
            PrivateKey::from_wif("3GAD3otqozDorfu1iDpMQJ1gzWp8PRFEjVHZivZdedKW3i3KtM").unwrap();

        let wif = "GOD78WVbdCHAwEVajuPKprZ6je6t1zvTieLEsEcKiYVtTjbpfjqLR";
        let hash = ScriptHash::from_wif(&wif).unwrap();
        assert_eq!(hash.to_wif().as_ref(), wif);
        assert_eq!(ScriptHash::from(Script::from(kp.0.clone())), hash);
    }
}
<|endoftext|>


<commit_before>use ws;
use time;
use std::fmt;
use uuid::Uuid;
use std::sync::{Arc,Mutex};
use std::collections::{HashMap,HashSet};

#[derive(PartialEq, Eq, Hash, Debug, Clone)]
pub enum Item {
    Potatoes,
    Berries,
    TreeSap,
}

trait ParseFrom<T, Out = Self> {
    fn parse (from: T) -> Result<Out, String>;
}

impl ParseFrom<i32> for Item {
    fn parse (i: i32) -> Result<Self, String> {
        match i {
            0 => Ok(Item::Potatoes),
            1 => Ok(Item::Berries),
            2 => Ok(Item::TreeSap),
            _ => Err(format!("Item.parse<i32> failure: unrecognized Item {}", i)),
        }
    }
}

#[derive(Debug)]
#[allow(non_camel_case_types)]
pub enum Action {
    addItemToInventory(Item),
}

#[derive(Debug, Clone)]
pub struct PlayerState {
    inventory: HashSet<Item>,
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub enum Player {
    AnonymousPlayer {
        state : PlayerState,
    },
    RegisteredPlayer {
        id    : i32,
        name  : String,
        state : PlayerState,
    }
}

#[allow(non_snake_case)]
mod AnonymousPlayer {
    use super::*;
    pub fn new () -> Player {
        let mut new_player_inventory = HashSet::new();
        new_player_inventory.insert(Item::Potatoes);

        Player::AnonymousPlayer {
            state: PlayerState {
                inventory: new_player_inventory
            }
        }
    }
}

#[allow(non_snake_case,dead_code)]
mod RegisteredPlayer {
    use super::*;
    pub fn new (id: i32, name: String) -> Player {
        let mut new_player_inventory = HashSet::new();
        new_player_inventory.insert(Item::Potatoes);

        Player::RegisteredPlayer {
            id: id,
            name: name,
            state: PlayerState {
                inventory: new_player_inventory
            }
        }
    }
}

#[derive(Debug, Clone)]
pub struct Connection {
    uuid   : Uuid,
    player : Player,
}

impl Connection {
    fn new(u: Uuid, p: Player) -> Connection {
        Connection {
            uuid  : u,
            player: p
        }
    }
}

impl fmt::Display for Connection {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "conn{{{}}}", self.uuid)
    }
}

fn parse_cookies (req: &ws::Request) -> HashMap<String, String> {
    req.header("cookie")
        .and_then(|cookies_bytes| String::from_utf8(cookies_bytes.to_vec()).ok())
        .unwrap_or(String::from(""))
        .rsplit(";")
        .filter_map(|cookie_string| {
            let mut cookie_pair = cookie_string.split("=");
            match (cookie_pair.next(), cookie_pair.next()) {
                (Some(name), Some(value)) => {
                    Some((String::from(name.trim()), String::from(value.trim())))
                },
                _ => None
            }
        })
        .collect()
}

fn put_cookie (name: String, value: String, resp: &mut ws::Response) {
    let headers = resp.headers_mut();
    let cookie_bytes = format!("{}={}", name, value).as_bytes().to_vec();
    headers.push((String::from("Set-Cookie"), cookie_bytes));
}

fn authorize_ticket_dumb (ticket: Uuid, msg_type: Vec<String>, conn_map: ConnectionMap) -> Result<Vec<String>, String> {
   if conn_map.lock().unwrap().contains_key(&ticket) {
        Ok(msg_type)
   } else {
        Err(String::from("authorize_ticket_dumb authorization failed"))
   }
}

type ConnectionMap = Arc<Mutex<HashMap<Uuid, Connection>>>;

struct WSServer {
    out: ws::Sender,
    connections: ConnectionMap,
}

fn parse_message (msg: ws::Message) -> Result<(Uuid, Vec<String>), String> {
    fn parse_error_msg (reason: &str) -> String {
        format!("parse_message failure: {}", reason)
    }

    msg.into_text()
        .or(Err(parse_error_msg("cannot get text from Message")))
        .and_then(|message_blob: String| {
            let mut message_parts = message_blob.split(":");

            let msg_ticket   = message_parts.next();
            let msg_contents = message_parts.map(|p| p.to_string()).collect();

            msg_ticket
                .ok_or(parse_error_msg("no ticket"))
                .and_then(|uuid_string| {
                    Uuid::parse_str(uuid_string)
                        .or(Err(parse_error_msg("ticket is invalid uuidv4")))
                })
                .map(|uuid| (uuid, msg_contents))
        })
}

impl ws::Handler for WSServer {
    fn on_request(&mut self, req: &ws::Request) -> ws::Result<ws::Response> {
        let mut resp = ws::Response::from_request(req).unwrap();

        let mut conn_map = self.connections.lock().unwrap();

        println!("ws:req[{}]", time::precise_time_ns());

        let cookies : HashMap<String, String> = parse_cookies(req);

        let mut cookie_existed = true;
        let ticket = cookies.get("bzwf_anon_wstx")
            .and_then(|uuid_string| Uuid::parse_str(uuid_string.as_str()).ok())
            .unwrap_or_else(|| {
                println!("ws:req[{}]: no bzwf_anon_wstx cookie found", time::precise_time_ns());
                cookie_existed = false;
                Uuid::new_v4()
            });

        let users_count = conn_map.len();

        if conn_map.contains_key(&ticket) {
            println!("ws:req[{}]: reconnect: uuid {}", time::precise_time_ns(), ticket);
            println!("{} connected users", users_count);
        } else {
            println!("ws:req[{}]: new connection with uuid {}", time::precise_time_ns(), ticket);

            let cookie_op_str = if cookie_existed {
                "replacing persistence cookie"
            } else {
                "creating persistence cookie"
            };

            println!("ws:req[{}]: {}: bzwf_anon_wstx={}", time::precise_time_ns(), cookie_op_str, ticket);
            println!("{} connected users", users_count + 1);
            put_cookie(String::from("bzwf_anon_wstx"), ticket.to_string(), &mut resp);
            conn_map.insert(ticket, Connection::new(ticket, AnonymousPlayer::new()));
        }

        Ok(resp)
    }

    fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> {
        println!("ws:rcv[{}]: user with uuid {} sent ws msg {}",
                 time::precise_time_ns(),
                 "[[[ we don't have uuids in ws yet ]]]",
                 msg);

        parse_message(msg)
            .and_then(|(msg_ticket, msg_contents)| {
                println!("authorizing ticket {}", msg_ticket);
                authorize_ticket_dumb(msg_ticket, msg_contents, self.connections.clone())
            })
            .and_then(|msg_contents| {
                // FIXME possible out of bounds error
                let ref msg_type  = msg_contents[0];
                let ref msg_param = msg_contents[1];

                println!("trying to read message contents of {}({})", msg_type, msg_param);

                match (msg_type.as_str(), msg_param) {
                    ("addItemToInventory", item) => {
                        if let Ok(item_num) = item.parse::<i32>() {
                            Item::parse(item_num)
                                .map(|item| Action::addItemToInventory(item))
                        } else {
                            Err(String::from("parse_message failure: addItemToInventory: invalid item code"))
                        }
                    },
                    _ => Err(String::from("parse_message failure: unrecognized message type"))
                }
            })
            .map(|action| {
                self.out.send(format!("gotcha, you want to {:?}", action))
            })
            .unwrap_or_else(|err| {
                println!("{}", err);
                self.out.send("got your message, but not sure what it meant")
            });

        Ok(())
    }

    fn on_open(&mut self, _: ws::Handshake) -> ws::Result<()> {
        // TODO
        println!("ws:opn[{}]: user with uuid {} opened ws cxn",
                 time::precise_time_ns(),
                 "[[[ we don't have uuids in ws yet ]]]");
        Ok(())
    }

    fn on_close(&mut self, code: ws::CloseCode, reason: &str) {
        println!("ws:cls[{}]: user with uuid {} closed ws cxn\n\tCode [{:?}] reason: {}",
                 time::precise_time_ns(),
                 "[[[ we don't have uuids in ws yet ]]]",
                 code,
                 reason);
        // TODO
    }

    fn on_error(&mut self, err: ws::Error) {
        println!("ws:err[{}]: user with uuid {} got error {}",
                 time::precise_time_ns(),
                 "[[[ we don't have uuids in ws yet ]]]",
                 err);
        // TODO
    }
}

pub fn server (domain: String, port: i32) -> () {
    let connections : ConnectionMap = Arc::new(Mutex::new(HashMap::new()));
    let addr = format!("{}:{}", domain, port);
    println!("WebSockets server listening on {}", addr);
    ws::listen(addr, |out| WSServer {
        out: out,
        connections: connections.clone(),
    }).unwrap();
}
<commit_msg>Refactor: simplified, type-annontated parse_message<commit_after>use ws;
use time;
use std::fmt;
use uuid::Uuid;
use std::sync::{Arc,Mutex};
use std::collections::{HashMap,HashSet};

#[derive(PartialEq, Eq, Hash, Debug, Clone)]
pub enum Item {
    Potatoes,
    Berries,
    TreeSap,
}

trait ParseFrom<T, Out = Self> {
    fn parse (from: T) -> Result<Out, String>;
}

impl ParseFrom<i32> for Item {
    fn parse (i: i32) -> Result<Self, String> {
        match i {
            0 => Ok(Item::Potatoes),
            1 => Ok(Item::Berries),
            2 => Ok(Item::TreeSap),
            _ => Err(format!("Item.parse<i32> failure: unrecognized Item {}", i)),
        }
    }
}

#[derive(Debug)]
#[allow(non_camel_case_types)]
pub enum Action {
    addItemToInventory(Item),
}

#[derive(Debug, Clone)]
pub struct PlayerState {
    inventory: HashSet<Item>,
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub enum Player {
    AnonymousPlayer {
        state : PlayerState,
    },
    RegisteredPlayer {
        id    : i32,
        name  : String,
        state : PlayerState,
    }
}

#[allow(non_snake_case)]
mod AnonymousPlayer {
    use super::*;
    pub fn new () -> Player {
        let mut new_player_inventory = HashSet::new();
        new_player_inventory.insert(Item::Potatoes);

        Player::AnonymousPlayer {
            state: PlayerState {
                inventory: new_player_inventory
            }
        }
    }
}

#[allow(non_snake_case,dead_code)]
mod RegisteredPlayer {
    use super::*;
    pub fn new (id: i32, name: String) -> Player {
        let mut new_player_inventory = HashSet::new();
        new_player_inventory.insert(Item::Potatoes);

        Player::RegisteredPlayer {
            id: id,
            name: name,
            state: PlayerState {
                inventory: new_player_inventory
            }
        }
    }
}

#[derive(Debug, Clone)]
pub struct Connection {
    uuid   : Uuid,
    player : Player,
}

impl Connection {
    fn new(u: Uuid, p: Player) -> Connection {
        Connection {
            uuid  : u,
            player: p
        }
    }
}

impl fmt::Display for Connection {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "conn{{{}}}", self.uuid)
    }
}

fn parse_cookies (req: &ws::Request) -> HashMap<String, String> {
    req.header("cookie")
        .and_then(|cookies_bytes| String::from_utf8(cookies_bytes.to_vec()).ok())
        .unwrap_or(String::from(""))
        .rsplit(";")
        .filter_map(|cookie_string| {
            let mut cookie_pair = cookie_string.split("=");
            match (cookie_pair.next(), cookie_pair.next()) {
                (Some(name), Some(value)) => {
                    Some((String::from(name.trim()), String::from(value.trim())))
                },
                _ => None
            }
        })
        .collect()
}

fn put_cookie (name: String, value: String, resp: &mut ws::Response) {
    let headers = resp.headers_mut();
    let cookie_bytes = format!("{}={}", name, value).as_bytes().to_vec();
    headers.push((String::from("Set-Cookie"), cookie_bytes));
}

fn authorize_ticket_dumb (ticket: Uuid, msg_type: Vec<String>, conn_map: ConnectionMap) -> Result<Vec<String>, String> {
   if conn_map.lock().unwrap().contains_key(&ticket) {
        Ok(msg_type)
   } else {
        Err(String::from("authorize_ticket_dumb authorization failed"))
   }
}

type ConnectionMap = Arc<Mutex<HashMap<Uuid, Connection>>>;

struct WSServer {
    out: ws::Sender,
    connections: ConnectionMap,
}

fn parse_message (msg: ws::Message) -> Result<(Uuid, Vec<String>), String> {
    fn parse_error_msg (reason: &str) -> String {
        format!("parse_message failure: {}", reason)
    }

    msg.into_text()
        .or(Err(parse_error_msg("cannot get text from Message; is it a binary Message?")))
        // NOTE(jordan): feels... wrong. But I hate the nesting! There's no unwrap_or_err()...
        .and_then(|msg| msg                  // Result<String, Err> -> String, or propagate Err
        .split(":")                          // String -> Split<'_, &str>
        .map(|p| p.to_string())              // Split<'_, &str> -> &[String]
        .collect::<Vec<String>>()            // &[String] -> Vec<String>
        .split_first()                       // Vec<String> -> Option<(String, Vec<String>)>
        .ok_or(parse_error_msg("no ticket")) // Option -> Result<(String, &[String]), String>
        .and_then(|(uuid_string, rest)| {    // Result<(String, &[String]), String>
            Uuid::parse_str(uuid_string)     //   |-> Result<(Uuid, Vec<String>), String>
                .or(Err(parse_error_msg("ticket is invalid uuidv4")))
                .map(|uuid| (uuid, Vec::from(rest)))
        }))
}

impl ws::Handler for WSServer {
    fn on_request(&mut self, req: &ws::Request) -> ws::Result<ws::Response> {
        let mut resp = ws::Response::from_request(req).unwrap();

        let mut conn_map = self.connections.lock().unwrap();

        println!("ws:req[{}]", time::precise_time_ns());

        let cookies : HashMap<String, String> = parse_cookies(req);

        let mut cookie_existed = true;
        let ticket = cookies.get("bzwf_anon_wstx")
            .and_then(|uuid_string| Uuid::parse_str(uuid_string.as_str()).ok())
            .unwrap_or_else(|| {
                println!("ws:req[{}]: no bzwf_anon_wstx cookie found", time::precise_time_ns());
                cookie_existed = false;
                Uuid::new_v4()
            });

        let users_count = conn_map.len();

        if conn_map.contains_key(&ticket) {
            println!("ws:req[{}]: reconnect: uuid {}", time::precise_time_ns(), ticket);
            println!("{} connected users", users_count);
        } else {
            println!("ws:req[{}]: new connection with uuid {}", time::precise_time_ns(), ticket);

            let cookie_op_str = if cookie_existed {
                "replacing persistence cookie"
            } else {
                "creating persistence cookie"
            };

            println!("ws:req[{}]: {}: bzwf_anon_wstx={}", time::precise_time_ns(), cookie_op_str, ticket);
            println!("{} connected users", users_count + 1);
            put_cookie(String::from("bzwf_anon_wstx"), ticket.to_string(), &mut resp);
            conn_map.insert(ticket, Connection::new(ticket, AnonymousPlayer::new()));
        }

        Ok(resp)
    }

    fn on_message(&mut self, msg: ws::Message) -> ws::Result<()> {
        println!("ws:rcv[{}]: user with uuid {} sent ws msg {}",
                 time::precise_time_ns(),
                 "[[[ we don't have uuids in ws yet ]]]",
                 msg);

        parse_message(msg)
            .and_then(|(msg_ticket, msg_contents)| {
                println!("authorizing ticket {}", msg_ticket);
                authorize_ticket_dumb(msg_ticket, msg_contents, self.connections.clone())
            })
            .and_then(|msg_contents| {
                // FIXME possible out of bounds error
                let ref msg_type  = msg_contents[0];
                let ref msg_param = msg_contents[1];

                println!("trying to read message contents of {}({})", msg_type, msg_param);

                match (msg_type.as_str(), msg_param) {
                    ("addItemToInventory", item) => {
                        if let Ok(item_num) = item.parse::<i32>() {
                            Item::parse(item_num)
                                .map(|item| Action::addItemToInventory(item))
                        } else {
                            Err(String::from("parse_message failure: addItemToInventory: invalid item code"))
                        }
                    },
                    _ => Err(String::from("parse_message failure: unrecognized message type"))
                }
            })
            .map(|action| {
                self.out.send(format!("gotcha, you want to {:?}", action))
            })
            .unwrap_or_else(|err| {
                println!("{}", err);
                self.out.send("got your message, but not sure what it meant")
            });

        Ok(())
    }

    fn on_open(&mut self, _: ws::Handshake) -> ws::Result<()> {
        // TODO
        println!("ws:opn[{}]: user with uuid {} opened ws cxn",
                 time::precise_time_ns(),
                 "[[[ we don't have uuids in ws yet ]]]");
        Ok(())
    }

    fn on_close(&mut self, code: ws::CloseCode, reason: &str) {
        println!("ws:cls[{}]: user with uuid {} closed ws cxn\n\tCode [{:?}] reason: {}",
                 time::precise_time_ns(),
                 "[[[ we don't have uuids in ws yet ]]]",
                 code,
                 reason);
        // TODO
    }

    fn on_error(&mut self, err: ws::Error) {
        println!("ws:err[{}]: user with uuid {} got error {}",
                 time::precise_time_ns(),
                 "[[[ we don't have uuids in ws yet ]]]",
                 err);
        // TODO
    }
}

pub fn server (domain: String, port: i32) -> () {
    let connections : ConnectionMap = Arc::new(Mutex::new(HashMap::new()));
    let addr = format!("{}:{}", domain, port);
    println!("WebSockets server listening on {}", addr);
    ws::listen(addr, |out| WSServer {
        out: out,
        connections: connections.clone(),
    }).unwrap();
}
<|endoftext|>


<commit_before>extern crate libsqlite3_sys as ffi;

mod functions;
#[doc(hidden)]
pub mod raw;
mod serialized_value;
mod stmt;
mod statement_iterator;
mod sqlite_value;

pub use self::sqlite_value::SqliteValue;

use std::os::raw as libc;

use connection::*;
use deserialize::{Queryable, QueryableByName};
use query_builder::*;
use query_builder::bind_collector::RawBytesBindCollector;
use result::*;
use self::raw::RawConnection;
use self::statement_iterator::*;
use self::stmt::{Statement, StatementUse};
use serialize::ToSql;
use sql_types::HasSqlType;
use sqlite::Sqlite;

/// Connections for the SQLite backend. Unlike other backends, "connection URLs"
/// for SQLite are file paths or special identifiers like `:memory`.
#[allow(missing_debug_implementations)]
pub struct SqliteConnection {
    statement_cache: StatementCache<Sqlite, Statement>,
    raw_connection: RawConnection,
    transaction_manager: AnsiTransactionManager,
}

// This relies on the invariant that RawConnection or Statement are never
// leaked. If a reference to one of those was held on a different thread, this
// would not be thread safe.
unsafe impl Send for SqliteConnection {}

impl SimpleConnection for SqliteConnection {
    fn batch_execute(&self, query: &str) -> QueryResult<()> {
        self.raw_connection.exec(query)
    }
}

impl Connection for SqliteConnection {
    type Backend = Sqlite;
    type TransactionManager = AnsiTransactionManager;

    fn establish(database_url: &str) -> ConnectionResult<Self> {
        RawConnection::establish(database_url).map(|conn| SqliteConnection {
            statement_cache: StatementCache::new(),
            raw_connection: conn,
            transaction_manager: AnsiTransactionManager::new(),
        })
    }

    #[doc(hidden)]
    fn execute(&self, query: &str) -> QueryResult<usize> {
        try!(self.batch_execute(query));
        Ok(self.raw_connection.rows_affected_by_last_query())
    }

    #[doc(hidden)]
    fn query_by_index<T, U>(&self, source: T) -> QueryResult<Vec<U>>
    where
        T: AsQuery,
        T::Query: QueryFragment<Self::Backend> + QueryId,
        Self::Backend: HasSqlType<T::SqlType>,
        U: Queryable<T::SqlType, Self::Backend>,
    {
        let mut statement = try!(self.prepare_query(&source.as_query()));
        let statement_use = StatementUse::new(&mut statement);
        let iter = StatementIterator::new(statement_use);
        iter.collect()
    }

    #[doc(hidden)]
    fn query_by_name<T, U>(&self, source: &T) -> QueryResult<Vec<U>>
    where
        T: QueryFragment<Self::Backend> + QueryId,
        U: QueryableByName<Self::Backend>,
    {
        let mut statement = self.prepare_query(source)?;
        let statement_use = StatementUse::new(&mut statement);
        let iter = NamedStatementIterator::new(statement_use)?;
        iter.collect()
    }

    #[doc(hidden)]
    fn execute_returning_count<T>(&self, source: &T) -> QueryResult<usize>
    where
        T: QueryFragment<Self::Backend> + QueryId,
    {
        let mut statement = try!(self.prepare_query(source));
        let mut statement_use = StatementUse::new(&mut statement);
        try!(statement_use.run());
        Ok(self.raw_connection.rows_affected_by_last_query())
    }

    #[doc(hidden)]
    fn transaction_manager(&self) -> &Self::TransactionManager {
        &self.transaction_manager
    }
}

impl SqliteConnection {
    /// Run a transaction with `BEGIN IMMEDIATE`
    ///
    /// This method will return an error if a transaction is already open.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate diesel;
    /// # include!("../../doctest_setup.rs");
    /// #
    /// # fn main() {
    /// #     run_test().unwrap();
    /// # }
    /// #
    /// # fn run_test() -> QueryResult<()> {
    /// #     let conn = SqliteConnection::establish(":memory:").unwrap();
    /// conn.immediate_transaction(|| {
    ///     // Do stuff in a transaction
    ///     Ok(())
    /// })
    /// # }
    /// ```
    pub fn immediate_transaction<T, E, F>(&self, f: F) -> Result<T, E>
    where
        F: FnOnce() -> Result<T, E>,
        E: From<Error>,
    {
        self.transaction_sql(f, "BEGIN IMMEDIATE")
    }

    /// Run a transaction with `BEGIN EXCLUSIVE`
    ///
    /// This method will return an error if a transaction is already open.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate diesel;
    /// # include!("../../doctest_setup.rs");
    /// #
    /// # fn main() {
    /// #     run_test().unwrap();
    /// # }
    /// #
    /// # fn run_test() -> QueryResult<()> {
    /// #     let conn = SqliteConnection::establish(":memory:").unwrap();
    /// conn.exclusive_transaction(|| {
    ///     // Do stuff in a transaction
    ///     Ok(())
    /// })
    /// # }
    /// ```
    pub fn exclusive_transaction<T, E, F>(&self, f: F) -> Result<T, E>
    where
        F: FnOnce() -> Result<T, E>,
        E: From<Error>,
    {
        self.transaction_sql(f, "BEGIN EXCLUSIVE")
    }

    fn transaction_sql<T, E, F>(&self, f: F, sql: &str) -> Result<T, E>
    where
        F: FnOnce() -> Result<T, E>,
        E: From<Error>,
    {
        let transaction_manager = self.transaction_manager();

        transaction_manager.begin_transaction_sql(self, sql)?;
        match f() {
            Ok(value) => {
                transaction_manager.commit_transaction(self)?;
                Ok(value)
            }
            Err(e) => {
                transaction_manager.rollback_transaction(self)?;
                Err(e)
            }
        }
    }

    fn prepare_query<T: QueryFragment<Sqlite> + QueryId>(
        &self,
        source: &T,
    ) -> QueryResult<MaybeCached<Statement>> {
        let mut statement = try!(self.cached_prepared_statement(source));

        let mut bind_collector = RawBytesBindCollector::<Sqlite>::new();
        try!(source.collect_binds(&mut bind_collector, &()));
        let metadata = bind_collector.metadata;
        let binds = bind_collector.binds;
        for (tpe, value) in metadata.into_iter().zip(binds) {
            try!(statement.bind(tpe, value));
        }

        Ok(statement)
    }

    fn cached_prepared_statement<T: QueryFragment<Sqlite> + QueryId>(
        &self,
        source: &T,
    ) -> QueryResult<MaybeCached<Statement>> {
        self.statement_cache.cached_statement(source, &[], |sql| {
            Statement::prepare(&self.raw_connection, sql)
        })
    }

    #[doc(hidden)]
    pub fn register_sql_function<ArgsSqlType, RetSqlType, Args, Ret, F>(
        &self,
        fn_name: &str,
        deterministic: bool,
        f: F,
    ) -> QueryResult<()>
    where
        F: FnMut(Args) -> Ret + Send + 'static,
        Args: Queryable<ArgsSqlType, Sqlite>,
        Ret: ToSql<RetSqlType, Sqlite>,
        Sqlite: HasSqlType<RetSqlType>,
    {
        functions::register(&self.raw_connection, fn_name, deterministic, f)
    }
}

fn error_message(err_code: libc::c_int) -> &'static str {
    ffi::code_to_str(err_code)
}

#[cfg(test)]
mod tests {
    use dsl::sql;
    use prelude::*;
    use super::*;
    use sql_types::Integer;

    #[test]
    fn prepared_statements_are_cached_when_run() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        let query = ::select(1.into_sql::<Integer>());

        assert_eq!(Ok(1), query.get_result(&connection));
        assert_eq!(Ok(1), query.get_result(&connection));
        assert_eq!(1, connection.statement_cache.len());
    }

    #[test]
    fn sql_literal_nodes_are_not_cached() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        let query = ::select(sql::<Integer>("1"));

        assert_eq!(Ok(1), query.get_result(&connection));
        assert_eq!(0, connection.statement_cache.len());
    }

    #[test]
    fn queries_containing_sql_literal_nodes_are_not_cached() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        let one_as_expr = 1.into_sql::<Integer>();
        let query = ::select(one_as_expr.eq(sql::<Integer>("1")));

        assert_eq!(Ok(true), query.get_result(&connection));
        assert_eq!(0, connection.statement_cache.len());
    }

    #[test]
    fn queries_containing_in_with_vec_are_not_cached() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        let one_as_expr = 1.into_sql::<Integer>();
        let query = ::select(one_as_expr.eq_any(vec![1, 2, 3]));

        assert_eq!(Ok(true), query.get_result(&connection));
        assert_eq!(0, connection.statement_cache.len());
    }

    #[test]
    fn queries_containing_in_with_subselect_are_cached() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        let one_as_expr = 1.into_sql::<Integer>();
        let query = ::select(one_as_expr.eq_any(::select(one_as_expr)));

        assert_eq!(Ok(true), query.get_result(&connection));
        assert_eq!(1, connection.statement_cache.len());
    }

    use sql_types::Text;
    sql_function!(fn fun_case(x: Text) -> Text);

    #[test]
    fn register_custom_function() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        fun_case::register_impl(&connection, |x: String| {
            x.chars()
                .enumerate()
                .map(|(i, c)| {
                    if i % 2 == 0 {
                        c.to_lowercase().to_string()
                    } else {
                        c.to_uppercase().to_string()
                    }
                })
                .collect::<String>()
        }).unwrap();

        let mapped_string = ::select(fun_case("foobar"))
            .get_result::<String>(&connection)
            .unwrap();
        assert_eq!("fOoBaR", mapped_string);
    }

    sql_function!(fn my_add(x: Integer, y: Integer) -> Integer);

    #[test]
    fn register_multiarg_function() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        my_add::register_impl(&connection, |x: i32, y: i32| {
            x + y
        }).unwrap();

        let added = ::select(my_add(1, 2))
            .get_result::<i32>(&connection);
        assert_eq!(Ok(3), added);
    }

    sql_function!(fn add_counter(x: Integer) -> Integer);

    #[test]
    fn register_nondeterministic_function() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        let mut y = 0;
        add_counter::register_nondeterministic_impl(&connection, move |x: i32| {
            y += 1;
            x + y
        }).unwrap();

        let added = ::select((add_counter(1), add_counter(1), add_counter(1)))
            .get_result::<(i32, i32, i32)>(&connection);
        assert_eq!(Ok((2, 3, 4)), added);
    }
}
<commit_msg>rustfmt<commit_after>extern crate libsqlite3_sys as ffi;

mod functions;
#[doc(hidden)]
pub mod raw;
mod serialized_value;
mod stmt;
mod statement_iterator;
mod sqlite_value;

pub use self::sqlite_value::SqliteValue;

use std::os::raw as libc;

use connection::*;
use deserialize::{Queryable, QueryableByName};
use query_builder::*;
use query_builder::bind_collector::RawBytesBindCollector;
use result::*;
use self::raw::RawConnection;
use self::statement_iterator::*;
use self::stmt::{Statement, StatementUse};
use serialize::ToSql;
use sql_types::HasSqlType;
use sqlite::Sqlite;

/// Connections for the SQLite backend. Unlike other backends, "connection URLs"
/// for SQLite are file paths or special identifiers like `:memory`.
#[allow(missing_debug_implementations)]
pub struct SqliteConnection {
    statement_cache: StatementCache<Sqlite, Statement>,
    raw_connection: RawConnection,
    transaction_manager: AnsiTransactionManager,
}

// This relies on the invariant that RawConnection or Statement are never
// leaked. If a reference to one of those was held on a different thread, this
// would not be thread safe.
unsafe impl Send for SqliteConnection {}

impl SimpleConnection for SqliteConnection {
    fn batch_execute(&self, query: &str) -> QueryResult<()> {
        self.raw_connection.exec(query)
    }
}

impl Connection for SqliteConnection {
    type Backend = Sqlite;
    type TransactionManager = AnsiTransactionManager;

    fn establish(database_url: &str) -> ConnectionResult<Self> {
        RawConnection::establish(database_url).map(|conn| SqliteConnection {
            statement_cache: StatementCache::new(),
            raw_connection: conn,
            transaction_manager: AnsiTransactionManager::new(),
        })
    }

    #[doc(hidden)]
    fn execute(&self, query: &str) -> QueryResult<usize> {
        try!(self.batch_execute(query));
        Ok(self.raw_connection.rows_affected_by_last_query())
    }

    #[doc(hidden)]
    fn query_by_index<T, U>(&self, source: T) -> QueryResult<Vec<U>>
    where
        T: AsQuery,
        T::Query: QueryFragment<Self::Backend> + QueryId,
        Self::Backend: HasSqlType<T::SqlType>,
        U: Queryable<T::SqlType, Self::Backend>,
    {
        let mut statement = try!(self.prepare_query(&source.as_query()));
        let statement_use = StatementUse::new(&mut statement);
        let iter = StatementIterator::new(statement_use);
        iter.collect()
    }

    #[doc(hidden)]
    fn query_by_name<T, U>(&self, source: &T) -> QueryResult<Vec<U>>
    where
        T: QueryFragment<Self::Backend> + QueryId,
        U: QueryableByName<Self::Backend>,
    {
        let mut statement = self.prepare_query(source)?;
        let statement_use = StatementUse::new(&mut statement);
        let iter = NamedStatementIterator::new(statement_use)?;
        iter.collect()
    }

    #[doc(hidden)]
    fn execute_returning_count<T>(&self, source: &T) -> QueryResult<usize>
    where
        T: QueryFragment<Self::Backend> + QueryId,
    {
        let mut statement = try!(self.prepare_query(source));
        let mut statement_use = StatementUse::new(&mut statement);
        try!(statement_use.run());
        Ok(self.raw_connection.rows_affected_by_last_query())
    }

    #[doc(hidden)]
    fn transaction_manager(&self) -> &Self::TransactionManager {
        &self.transaction_manager
    }
}

impl SqliteConnection {
    /// Run a transaction with `BEGIN IMMEDIATE`
    ///
    /// This method will return an error if a transaction is already open.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate diesel;
    /// # include!("../../doctest_setup.rs");
    /// #
    /// # fn main() {
    /// #     run_test().unwrap();
    /// # }
    /// #
    /// # fn run_test() -> QueryResult<()> {
    /// #     let conn = SqliteConnection::establish(":memory:").unwrap();
    /// conn.immediate_transaction(|| {
    ///     // Do stuff in a transaction
    ///     Ok(())
    /// })
    /// # }
    /// ```
    pub fn immediate_transaction<T, E, F>(&self, f: F) -> Result<T, E>
    where
        F: FnOnce() -> Result<T, E>,
        E: From<Error>,
    {
        self.transaction_sql(f, "BEGIN IMMEDIATE")
    }

    /// Run a transaction with `BEGIN EXCLUSIVE`
    ///
    /// This method will return an error if a transaction is already open.
    ///
    /// # Example
    ///
    /// ```rust
    /// # #[macro_use] extern crate diesel;
    /// # include!("../../doctest_setup.rs");
    /// #
    /// # fn main() {
    /// #     run_test().unwrap();
    /// # }
    /// #
    /// # fn run_test() -> QueryResult<()> {
    /// #     let conn = SqliteConnection::establish(":memory:").unwrap();
    /// conn.exclusive_transaction(|| {
    ///     // Do stuff in a transaction
    ///     Ok(())
    /// })
    /// # }
    /// ```
    pub fn exclusive_transaction<T, E, F>(&self, f: F) -> Result<T, E>
    where
        F: FnOnce() -> Result<T, E>,
        E: From<Error>,
    {
        self.transaction_sql(f, "BEGIN EXCLUSIVE")
    }

    fn transaction_sql<T, E, F>(&self, f: F, sql: &str) -> Result<T, E>
    where
        F: FnOnce() -> Result<T, E>,
        E: From<Error>,
    {
        let transaction_manager = self.transaction_manager();

        transaction_manager.begin_transaction_sql(self, sql)?;
        match f() {
            Ok(value) => {
                transaction_manager.commit_transaction(self)?;
                Ok(value)
            }
            Err(e) => {
                transaction_manager.rollback_transaction(self)?;
                Err(e)
            }
        }
    }

    fn prepare_query<T: QueryFragment<Sqlite> + QueryId>(
        &self,
        source: &T,
    ) -> QueryResult<MaybeCached<Statement>> {
        let mut statement = try!(self.cached_prepared_statement(source));

        let mut bind_collector = RawBytesBindCollector::<Sqlite>::new();
        try!(source.collect_binds(&mut bind_collector, &()));
        let metadata = bind_collector.metadata;
        let binds = bind_collector.binds;
        for (tpe, value) in metadata.into_iter().zip(binds) {
            try!(statement.bind(tpe, value));
        }

        Ok(statement)
    }

    fn cached_prepared_statement<T: QueryFragment<Sqlite> + QueryId>(
        &self,
        source: &T,
    ) -> QueryResult<MaybeCached<Statement>> {
        self.statement_cache.cached_statement(source, &[], |sql| {
            Statement::prepare(&self.raw_connection, sql)
        })
    }

    #[doc(hidden)]
    pub fn register_sql_function<ArgsSqlType, RetSqlType, Args, Ret, F>(
        &self,
        fn_name: &str,
        deterministic: bool,
        f: F,
    ) -> QueryResult<()>
    where
        F: FnMut(Args) -> Ret + Send + 'static,
        Args: Queryable<ArgsSqlType, Sqlite>,
        Ret: ToSql<RetSqlType, Sqlite>,
        Sqlite: HasSqlType<RetSqlType>,
    {
        functions::register(&self.raw_connection, fn_name, deterministic, f)
    }
}

fn error_message(err_code: libc::c_int) -> &'static str {
    ffi::code_to_str(err_code)
}

#[cfg(test)]
mod tests {
    use dsl::sql;
    use prelude::*;
    use super::*;
    use sql_types::Integer;

    #[test]
    fn prepared_statements_are_cached_when_run() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        let query = ::select(1.into_sql::<Integer>());

        assert_eq!(Ok(1), query.get_result(&connection));
        assert_eq!(Ok(1), query.get_result(&connection));
        assert_eq!(1, connection.statement_cache.len());
    }

    #[test]
    fn sql_literal_nodes_are_not_cached() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        let query = ::select(sql::<Integer>("1"));

        assert_eq!(Ok(1), query.get_result(&connection));
        assert_eq!(0, connection.statement_cache.len());
    }

    #[test]
    fn queries_containing_sql_literal_nodes_are_not_cached() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        let one_as_expr = 1.into_sql::<Integer>();
        let query = ::select(one_as_expr.eq(sql::<Integer>("1")));

        assert_eq!(Ok(true), query.get_result(&connection));
        assert_eq!(0, connection.statement_cache.len());
    }

    #[test]
    fn queries_containing_in_with_vec_are_not_cached() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        let one_as_expr = 1.into_sql::<Integer>();
        let query = ::select(one_as_expr.eq_any(vec![1, 2, 3]));

        assert_eq!(Ok(true), query.get_result(&connection));
        assert_eq!(0, connection.statement_cache.len());
    }

    #[test]
    fn queries_containing_in_with_subselect_are_cached() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        let one_as_expr = 1.into_sql::<Integer>();
        let query = ::select(one_as_expr.eq_any(::select(one_as_expr)));

        assert_eq!(Ok(true), query.get_result(&connection));
        assert_eq!(1, connection.statement_cache.len());
    }

    use sql_types::Text;
    sql_function!(fn fun_case(x: Text) -> Text);

    #[test]
    fn register_custom_function() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        fun_case::register_impl(&connection, |x: String| {
            x.chars()
                .enumerate()
                .map(|(i, c)| {
                    if i % 2 == 0 {
                        c.to_lowercase().to_string()
                    } else {
                        c.to_uppercase().to_string()
                    }
                })
                .collect::<String>()
        }).unwrap();

        let mapped_string = ::select(fun_case("foobar"))
            .get_result::<String>(&connection)
            .unwrap();
        assert_eq!("fOoBaR", mapped_string);
    }

    sql_function!(fn my_add(x: Integer, y: Integer) -> Integer);

    #[test]
    fn register_multiarg_function() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        my_add::register_impl(&connection, |x: i32, y: i32| x + y).unwrap();

        let added = ::select(my_add(1, 2)).get_result::<i32>(&connection);
        assert_eq!(Ok(3), added);
    }

    sql_function!(fn add_counter(x: Integer) -> Integer);

    #[test]
    fn register_nondeterministic_function() {
        let connection = SqliteConnection::establish(":memory:").unwrap();
        let mut y = 0;
        add_counter::register_nondeterministic_impl(&connection, move |x: i32| {
            y += 1;
            x + y
        }).unwrap();

        let added = ::select((add_counter(1), add_counter(1), add_counter(1)))
            .get_result::<(i32, i32, i32)>(&connection);
        assert_eq!(Ok((2, 3, 4)), added);
    }
}
<|endoftext|>


<commit_before>#[test]
fn dogfood() {
    if option_env!("RUSTC_TEST_SUITE").is_some() {
        return;
    }
    let root_dir = std::env::current_dir().unwrap();
    for d in &[".", "clippy_lints"] {
        std::env::set_current_dir(root_dir.join(d)).unwrap();
        let output = std::process::Command::new("cargo")
            .arg("run")
            .arg("--bin").arg("cargo-clippy")
            .arg("--manifest-path").arg(root_dir.join("Cargo.toml"))
            .output().unwrap();
        println!("status: {}", output.status);
        println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
        println!("stderr: {}", String::from_utf8_lossy(&output.stderr));

        assert!(output.status.success());
    }
}
<commit_msg>Don't run dogfood on windows or in the rustc test suite<commit_after>#[test]
fn dogfood() {
    if option_env!("RUSTC_TEST_SUITE").is_some() {
        return;
    }
    if cfg!(windows) {
        return;
    }
    let root_dir = std::env::current_dir().unwrap();
    for d in &[".", "clippy_lints"] {
        std::env::set_current_dir(root_dir.join(d)).unwrap();
        let output = std::process::Command::new("cargo")
            .arg("run")
            .arg("--bin").arg("cargo-clippy")
            .arg("--manifest-path").arg(root_dir.join("Cargo.toml"))
            .output().unwrap();
        println!("status: {}", output.status);
        println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
        println!("stderr: {}", String::from_utf8_lossy(&output.stderr));

        assert!(output.status.success());
    }
}
<|endoftext|>


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

extern crate quilkin;

#[cfg(test)]
mod tests {
    use std::net::{IpAddr, Ipv4Addr, SocketAddr};

    use slog::info;

    use quilkin::config::{Config, ConnectionConfig, EndPoint, Filter, Local};
    use quilkin::extensions::default_registry;
    use quilkin::test_utils::{
        echo_server, logger, recv_multiple_packets, run_proxy, TestFilterFactory,
    };

    #[tokio::test]
    async fn test_filter() {
        let base_logger = logger();

        // create two echo servers as endpoints
        let echo = echo_server().await;

        // create server configuration
        let server_port = 12346;
        let server_config = Config {
            local: Local { port: server_port },
            filters: vec![Filter {
                name: "TestFilter".to_string(),
                config: serde_yaml::Value::Null,
            }],
            connections: ConnectionConfig::Server {
                endpoints: vec![EndPoint {
                    name: "server".to_string(),
                    address: echo,
                    connection_ids: vec![],
                }],
            },
        };
        assert_eq!(Ok(()), server_config.validate());

        let mut registry = default_registry(&base_logger);
        registry.insert(TestFilterFactory {});
        let close_server = run_proxy(&base_logger, registry, server_config);

        // create a local client
        let client_port = 12347;
        let client_config = Config {
            local: Local { port: client_port },
            filters: vec![Filter {
                name: "TestFilter".to_string(),
                config: serde_yaml::Value::Null,
            }],
            connections: ConnectionConfig::Client {
                addresses: vec![SocketAddr::new(
                    IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
                    server_port,
                )],
                connection_id: String::from(""),
                lb_policy: None,
            },
        };
        assert_eq!(Ok(()), client_config.validate());

        let mut registry = default_registry(&base_logger);
        registry.insert(TestFilterFactory {});
        let close_client = run_proxy(&base_logger, registry, client_config);

        // let's send the packet
        let (mut recv_chan, mut send) = recv_multiple_packets(&base_logger).await;

        // game_client
        let local_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), client_port);
        info!(base_logger, "Sending hello"; "addr" => local_addr);
        send.send_to("hello".as_bytes(), &local_addr).await.unwrap();

        let result = recv_chan.recv().await.unwrap();
        // since we don't know the ephemeral ip addresses in use, we'll search for
        // substrings for the results we expect that the TestFilter will inject in
        // the round-tripped packets.
        assert_eq!(
            2,
            result.matches("lrf").count(),
            "Should be 2 local_receive_filter calls in {}",
            result
        );
        assert_eq!(
            2,
            result.matches("lsf").count(),
            "Should be 2 local_send_filter calls in {}",
            result
        );
        assert_eq!(
            2,
            result.matches("esf").count(),
            "Should be 2 endpoint_send_filter calls in {}",
            result
        );
        assert_eq!(
            2,
            result.matches("erf").count(),
            "Should be 2 endpoint_receive_filter calls in {}",
            result
        );

        close_server();
        close_client();
    }
}
<commit_msg>Integration test for DebugFilter (#78)<commit_after>/*
 * Copyright 2020 Google LLC All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

extern crate quilkin;

#[cfg(test)]
mod tests {
    use std::net::{IpAddr, Ipv4Addr, SocketAddr};

    use serde_yaml::{Mapping, Value};
    use slog::info;

    use quilkin::config::{Config, ConnectionConfig, EndPoint, Filter, Local};
    use quilkin::extensions::filters::DebugFilterFactory;
    use quilkin::extensions::{default_registry, FilterFactory};
    use quilkin::test_utils::{
        echo_server, logger, recv_multiple_packets, run_proxy, TestFilterFactory,
    };

    #[tokio::test]
    async fn test_filter() {
        let base_logger = logger();

        // create two echo servers as endpoints
        let echo = echo_server().await;

        // create server configuration
        let server_port = 12346;
        let server_config = Config {
            local: Local { port: server_port },
            filters: vec![Filter {
                name: "TestFilter".to_string(),
                config: serde_yaml::Value::Null,
            }],
            connections: ConnectionConfig::Server {
                endpoints: vec![EndPoint {
                    name: "server".to_string(),
                    address: echo,
                    connection_ids: vec![],
                }],
            },
        };
        assert_eq!(Ok(()), server_config.validate());

        let mut registry = default_registry(&base_logger);
        registry.insert(TestFilterFactory {});
        let close_server = run_proxy(&base_logger, registry, server_config);

        // create a local client
        let client_port = 12347;
        let client_config = Config {
            local: Local { port: client_port },
            filters: vec![Filter {
                name: "TestFilter".to_string(),
                config: serde_yaml::Value::Null,
            }],
            connections: ConnectionConfig::Client {
                addresses: vec![SocketAddr::new(
                    IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
                    server_port,
                )],
                connection_id: String::from(""),
                lb_policy: None,
            },
        };
        assert_eq!(Ok(()), client_config.validate());

        let mut registry = default_registry(&base_logger);
        registry.insert(TestFilterFactory {});
        let close_client = run_proxy(&base_logger, registry, client_config);

        // let's send the packet
        let (mut recv_chan, mut send) = recv_multiple_packets(&base_logger).await;

        // game_client
        let local_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), client_port);
        info!(base_logger, "Sending hello"; "addr" => local_addr);
        send.send_to("hello".as_bytes(), &local_addr).await.unwrap();

        let result = recv_chan.recv().await.unwrap();
        // since we don't know the ephemeral ip addresses in use, we'll search for
        // substrings for the results we expect that the TestFilter will inject in
        // the round-tripped packets.
        assert_eq!(
            2,
            result.matches("lrf").count(),
            "Should be 2 local_receive_filter calls in {}",
            result
        );
        assert_eq!(
            2,
            result.matches("lsf").count(),
            "Should be 2 local_send_filter calls in {}",
            result
        );
        assert_eq!(
            2,
            result.matches("esf").count(),
            "Should be 2 endpoint_send_filter calls in {}",
            result
        );
        assert_eq!(
            2,
            result.matches("erf").count(),
            "Should be 2 endpoint_receive_filter calls in {}",
            result
        );

        close_server();
        close_client();
    }

    #[tokio::test]
    async fn debug_filter() {
        let base_logger = logger();
        // handy for grabbing the configuration name
        let factory = DebugFilterFactory::new(&base_logger);

        // create two echo servers as endpoints
        let echo = echo_server().await;

        // filter config
        let mut map = Mapping::new();
        map.insert(Value::from("id"), Value::from("server"));
        // create server configuration
        let server_port = 12247;
        let server_config = Config {
            local: Local { port: server_port },
            filters: vec![Filter {
                name: factory.name(),
                config: serde_yaml::Value::Mapping(map),
            }],
            connections: ConnectionConfig::Server {
                endpoints: vec![EndPoint {
                    name: "server".to_string(),
                    address: echo,
                    connection_ids: vec![],
                }],
            },
        };
        let close_server = run_proxy(&base_logger, default_registry(&base_logger), server_config);

        let mut map = Mapping::new();
        map.insert(Value::from("id"), Value::from("client"));
        // create a local client
        let client_port = 12248;
        let client_config = Config {
            local: Local { port: client_port },
            filters: vec![Filter {
                name: factory.name(),
                config: serde_yaml::Value::Mapping(map),
            }],
            connections: ConnectionConfig::Client {
                addresses: vec![SocketAddr::new(
                    IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
                    server_port,
                )],
                connection_id: String::from(""),
                lb_policy: None,
            },
        };
        let close_client = run_proxy(&base_logger, default_registry(&base_logger), client_config);

        // let's send the packet
        let (mut recv_chan, mut send) = recv_multiple_packets(&base_logger).await;

        // game client
        let local_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), client_port);
        info!(base_logger, "Sending hello"; "addr" => local_addr);
        send.send_to("hello".as_bytes(), &local_addr).await.unwrap();

        // since the debug filter doesn't change the data, it should be exactly the same
        assert_eq!("hello", recv_chan.recv().await.unwrap());

        close_server();
        close_client();
    }
}
<|endoftext|>