<commit_before>#![allow(unused_imports, unused_variables, dead_code)]
use super::error::ConfigError;
use anyhow::{anyhow, Result};

use serde::de::{Deserializer, Error, MapAccess, SeqAccess, Visitor};
use serde::Deserialize;
use std::collections::HashMap;
use std::fmt;
use std::num::ParseIntError;
use std::path::PathBuf;
use std::vec::Vec;

type Tasks = HashMap<String, Task>;
type Params = HashMap<String, Param>;

#[derive(Debug, Clone, PartialEq)]
pub enum Nargs {
    One,
    Zero,
    OneOrZero,
    OneOrMore,
    ZeroOrMore,
    Range(usize, usize),
}

impl fmt::Display for Nargs {
    fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Nargs::One => write!(fmtr, "Nargs::One[1]"),
            Nargs::Zero => write!(fmtr, "Nargs::Zero[0]"),
            Nargs::OneOrZero => write!(fmtr, "Nargs::OneOrZero[?]"),
            Nargs::OneOrMore => write!(fmtr, "Nargs::OneOrMore[+]"),
            Nargs::ZeroOrMore => write!(fmtr, "Nargs::ZeroOrMore[*]"),
            Nargs::Range(min, max) => write!(fmtr, "Nargs::Range[{}, {}]", min + 1, max),
        }
    }
}

impl Default for Nargs {
    fn default() -> Self {
        Nargs::One
    }
}

impl<'de> Deserialize<'de> for Nargs {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        let result = match &s[..] {
            "1" => Nargs::One,
            "0" => Nargs::Zero,
            "?" => Nargs::OneOrZero,
            "+" => Nargs::OneOrMore,
            "*" => Nargs::ZeroOrMore,
            _ => {
                println!("s={}", s);
                if s.contains(':') {
                    let parts: Vec<&str> = s.split(':').collect();
                    let min = parts[0].parse::<usize>().map_err(Error::custom)?;
                    let max = parts[1].parse::<usize>().map_err(Error::custom)?;
                    Nargs::Range(min - 1, max)
                } else {
                    let num = s.parse::<usize>().map_err(Error::custom)?;
                    Nargs::Range(0, num)
                }
            }
        };
        Ok(result)
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Action {
    Script(String),
    File(PathBuf),
    //URL(Url),
}

#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    Item(String),
    List(Vec<String>),
    Dict(HashMap<String, String>),
    Empty,
}

impl fmt::Display for Value {
    fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::Item(s) => write!(fmtr, "Values::Item({})", s),
            Value::List(vs) => write!(fmtr, "Values::List([{}])", vs.join(", ")),
            Value::Dict(ds) => write!(fmtr, "Values::Dict[NOT IMPLEMENTED]"),
            Value::Empty => write!(fmtr, "Value::Empty(\"\")"),
        }
    }
}

impl Default for Value {
    fn default() -> Self {
        Value::Empty
    }
}

fn deserialize_value<'de, D>(deserializer: D) -> Result<Value, D::Error>
where
    D: Deserializer<'de>,
{
    struct ValueEnum;
    impl<'de> Visitor<'de> for ValueEnum {
        type Value = Value;

        fn expecting(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
            fmtr.write_str("string or list of strings")
        }
        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
        where
            E: Error,
        {
            Ok(Value::Item(value.to_owned()))
        }
        fn visit_seq<S>(self, mut visitor: S) -> Result<Self::Value, S::Error>
        where
            S: SeqAccess<'de>,
        {
            let mut vec: Vec<String> = vec![];
            while let Some(item) = visitor.next_element()? {
                vec.push(item);
            }
            Ok(Value::List(vec))
        }
    }
    deserializer.deserialize_any(ValueEnum)
}

fn default_otto() -> String {
    "otto".to_string()
}

fn default_verbosity() -> i32 {
    1
}

fn default_api() -> i32 {
    1
}

fn default_jobs() -> i32 {
    12
}
fn default_defaults() -> Defaults {
    Defaults {
        api: default_api(),
        verbosity: default_verbosity(),
        jobs: default_jobs(),
        tasks: vec![],
    }
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
pub struct Spec {
    #[serde(default = "default_defaults")]
    pub defaults: Defaults,

    pub otto: Otto,
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
pub struct Defaults {
    #[serde(default = "default_api")]
    pub api: i32,

    #[serde(default = "default_verbosity")]
    pub verbosity: i32,

    #[serde(default = "default_jobs")]
    pub jobs: i32,

    #[serde(default)]
    pub tasks: Vec<String>,
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
pub struct Otto {
    #[serde(skip_deserializing, default = "default_otto")]
    pub name: String,

    #[serde(default)]
    pub author: Option<String>,

    #[serde(default)]
    pub about: Option<String>,

    #[serde(default)]
    pub version: Option<String>,

    #[serde(default, deserialize_with = "deserialize_param_map")]
    pub params: Params,

    #[serde(default, deserialize_with = "deserialize_task_map")]
    pub tasks: Tasks,

    pub action: Option<String>,
}

impl Otto {
    fn get_param_key(&self, flag: &str) -> Result<&String, ConfigError> {
        for (key, param) in self.params.iter() {
            if param.flags.iter().any(|f| f == flag) {
                return Ok(key);
            }
        }
        Err(ConfigError::FlagLookupError(flag.to_string()))
    }
    pub fn get_param(&self, name: &str) -> Result<&Param, ConfigError> {
        self.params
            .get(name)
            .ok_or_else(|| ConfigError::NameLookupError(name.to_string()))
    }
    pub fn get_param_from_flag(&self, flag: &str) -> Result<&Param, ConfigError> {
        let key = self.get_param_key(flag)?;
        self.get_param(key)
    }
    pub fn set_param(&mut self, param: Param) -> Result<Param, ConfigError> {
        let name = param.name.to_owned();
        self.params
            .insert(name.to_owned(), param)
            .ok_or(ConfigError::NameLookupError(name))
    }
    pub fn get_task(&self, name: &str) -> Result<&Task, ConfigError> {
        self.tasks
            .get(name)
            .ok_or_else(|| ConfigError::NameLookupError(name.to_string()))
    }
    pub fn set_task(&mut self, task: Task) -> Result<Task, ConfigError> {
        let name = task.name.to_owned();
        self.tasks
            .insert(name.to_owned(), task)
            .ok_or(ConfigError::NameLookupError(name))
    }
    pub fn task_names(&self) -> Vec<&str> {
        self.tasks.keys().map(AsRef::as_ref).collect()
    }
}

pub enum ParamType {
    FLG,
    OPT,
    POS,
}

// FIXME: Flag, Named and Positional Args
#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
pub struct Param {
    #[serde(skip_deserializing)]
    pub name: String,

    #[serde(skip_deserializing)]
    pub flags: Vec<String>,

    #[serde(skip_deserializing)]
    pub value: Value,

    #[serde(default)]
    pub dest: Option<String>,

    #[serde(default)]
    pub metavar: Option<String>,

    #[serde(default)]
    pub default: Option<String>,

    #[serde(default, deserialize_with = "deserialize_value")]
    pub constant: Value,

    #[serde(default)]
    pub choices: Vec<String>,

    #[serde(default)]
    pub nargs: Nargs,

    #[serde(default)]
    pub help: Option<String>,
}

impl Param {
    pub fn param_type(&self) -> ParamType {
        match self.name.chars().next() {
            Some('-') => match self.default.as_deref() {
                Some("true") | Some("false") => ParamType::FLG,
                Some(_) | None => ParamType::OPT,
            },
            Some(_) | None => ParamType::POS,
        }
    }
}

fn deserialize_param_map<'de, D>(deserializer: D) -> Result<Params, D::Error>
where
    D: Deserializer<'de>,
{
    struct ParamMap;

    impl<'de> Visitor<'de> for ParamMap {
        type Value = Params;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a map of name to Param")
        }

        fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
        where
            M: MapAccess<'de>,
        {
            let mut params = Params::new();
            while let Some((name, mut param)) = map.next_entry::<String, Param>()? {
                if name.contains('-') {
                    param.flags = name.split('|').map(|f| f.to_string()).collect();
                    let short: Vec<String> = param
                        .flags
                        .iter()
                        .cloned()
                        .filter(|i| i.starts_with('-') && i.len() == 2)
                        .collect();
                    let long: Vec<String> = param
                        .flags
                        .iter()
                        .cloned()
                        .filter(|i| i.starts_with("--") && i.len() > 2)
                        .collect();
                    let name = match long.first() {
                        Some(long) => String::from(long.trim_matches('-')),
                        None => match short.first() {
                            Some(short) => String::from(short.trim_matches('-')),
                            None => param.name.to_owned(),
                        },
                    };
                }
                if param.dest.is_none() {
                    param.dest = Some(name.to_owned());
                }
                param.name = name.to_owned();
                params.insert(name.to_owned(), param);
            }
            Ok(params)
        }
    }
    deserializer.deserialize_map(ParamMap)
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
pub struct Task {
    #[serde(skip_deserializing)]
    pub name: String,

    #[serde(default)]
    pub help: Option<String>,

    #[serde(default)]
    pub after: Vec<String>,

    #[serde(default)]
    pub before: Vec<String>,

    #[serde(default, deserialize_with = "deserialize_param_map")]
    pub params: Params,

    pub action: Option<String>,

    #[serde(skip_deserializing)]
    pub selected: bool,
}

impl Task {
    pub fn new(
        name: String,
        help: Option<String>,
        after: Vec<String>,
        before: Vec<String>,
        params: Params,
        action: Option<String>,
        selected: bool,
    ) -> Self {
        Self {
            name,
            help,
            after,
            before,
            params,
            action,
            selected,
        }
    }
    fn get_param_key(&self, flag: &str) -> Result<&String, ConfigError> {
        for (key, param) in self.params.iter() {
            if param.flags.iter().any(|f| f == flag) {
                return Ok(key);
            }
        }
        Err(ConfigError::FlagLookupError(flag.to_string()))
    }
    pub fn get_param(&self, name: &str) -> Result<&Param> {
        self.params
            .get(name)
            .ok_or_else(|| anyhow!("get_param: failed to get name={}", name))
    }
    pub fn get_param_from_flag(&self, flag: &str) -> Result<&Param> {
        let key = self.get_param_key(flag)?;
        self.get_param(key)
    }
    pub fn set_param(&mut self, param: Param) -> Result<Param> {
        let name = param.name.to_owned();
        self.params
            .insert(name.to_owned(), param)
            .ok_or_else(|| anyhow!("set_param: failed to set param.name={}", name))
    }
}

fn deserialize_task_map<'de, D>(deserializer: D) -> Result<Tasks, D::Error>
where
    D: Deserializer<'de>,
{
    struct TaskMap;

    impl<'de> Visitor<'de> for TaskMap {
        type Value = Tasks;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a map of name to Task")
        }

        fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
        where
            M: MapAccess<'de>,
        {
            let mut tasks = Tasks::new();
            while let Some((name, mut task)) = map.next_entry::<String, Task>()? {
                task.name = name.to_owned();
                tasks.insert(name.to_owned(), task);
            }
            Ok(tasks)
        }
    }
    deserializer.deserialize_map(TaskMap)
}
<commit_msg>refactored to set short, long and name<commit_after>#![allow(unused_imports, unused_variables, dead_code)]
use super::error::ConfigError;
use anyhow::{anyhow, Result};

use serde::de::{Deserializer, Error, MapAccess, SeqAccess, Visitor};
use serde::Deserialize;
use std::collections::HashMap;
use std::fmt;
use std::num::ParseIntError;
use std::path::PathBuf;
use std::vec::Vec;

type Tasks = HashMap<String, Task>;
type Params = HashMap<String, Param>;

#[derive(Debug, Clone, PartialEq)]
pub enum Nargs {
    One,
    Zero,
    OneOrZero,
    OneOrMore,
    ZeroOrMore,
    Range(usize, usize),
}

impl fmt::Display for Nargs {
    fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Nargs::One => write!(fmtr, "Nargs::One[1]"),
            Nargs::Zero => write!(fmtr, "Nargs::Zero[0]"),
            Nargs::OneOrZero => write!(fmtr, "Nargs::OneOrZero[?]"),
            Nargs::OneOrMore => write!(fmtr, "Nargs::OneOrMore[+]"),
            Nargs::ZeroOrMore => write!(fmtr, "Nargs::ZeroOrMore[*]"),
            Nargs::Range(min, max) => write!(fmtr, "Nargs::Range[{}, {}]", min + 1, max),
        }
    }
}

impl Default for Nargs {
    fn default() -> Self {
        Nargs::One
    }
}

impl<'de> Deserialize<'de> for Nargs {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        let result = match &s[..] {
            "1" => Nargs::One,
            "0" => Nargs::Zero,
            "?" => Nargs::OneOrZero,
            "+" => Nargs::OneOrMore,
            "*" => Nargs::ZeroOrMore,
            _ => {
                println!("s={}", s);
                if s.contains(':') {
                    let parts: Vec<&str> = s.split(':').collect();
                    let min = parts[0].parse::<usize>().map_err(Error::custom)?;
                    let max = parts[1].parse::<usize>().map_err(Error::custom)?;
                    Nargs::Range(min - 1, max)
                } else {
                    let num = s.parse::<usize>().map_err(Error::custom)?;
                    Nargs::Range(0, num)
                }
            }
        };
        Ok(result)
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Action {
    Script(String),
    File(PathBuf),
    //URL(Url),
}

#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    Item(String),
    List(Vec<String>),
    Dict(HashMap<String, String>),
    Empty,
}

impl fmt::Display for Value {
    fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::Item(s) => write!(fmtr, "Values::Item({})", s),
            Value::List(vs) => write!(fmtr, "Values::List([{}])", vs.join(", ")),
            Value::Dict(ds) => write!(fmtr, "Values::Dict[NOT IMPLEMENTED]"),
            Value::Empty => write!(fmtr, "Value::Empty(\"\")"),
        }
    }
}

impl Default for Value {
    fn default() -> Self {
        Value::Empty
    }
}

fn deserialize_value<'de, D>(deserializer: D) -> Result<Value, D::Error>
where
    D: Deserializer<'de>,
{
    struct ValueEnum;
    impl<'de> Visitor<'de> for ValueEnum {
        type Value = Value;

        fn expecting(&self, fmtr: &mut fmt::Formatter) -> fmt::Result {
            fmtr.write_str("string or list of strings")
        }
        fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
        where
            E: Error,
        {
            Ok(Value::Item(value.to_owned()))
        }
        fn visit_seq<S>(self, mut visitor: S) -> Result<Self::Value, S::Error>
        where
            S: SeqAccess<'de>,
        {
            let mut vec: Vec<String> = vec![];
            while let Some(item) = visitor.next_element()? {
                vec.push(item);
            }
            Ok(Value::List(vec))
        }
    }
    deserializer.deserialize_any(ValueEnum)
}

fn default_otto() -> String {
    "otto".to_string()
}

fn default_verbosity() -> i32 {
    1
}

fn default_api() -> i32 {
    1
}

fn default_jobs() -> i32 {
    12
}
fn default_defaults() -> Defaults {
    Defaults {
        api: default_api(),
        verbosity: default_verbosity(),
        jobs: default_jobs(),
        tasks: vec![],
    }
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
pub struct Spec {
    #[serde(default = "default_defaults")]
    pub defaults: Defaults,

    pub otto: Otto,
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
pub struct Defaults {
    #[serde(default = "default_api")]
    pub api: i32,

    #[serde(default = "default_verbosity")]
    pub verbosity: i32,

    #[serde(default = "default_jobs")]
    pub jobs: i32,

    #[serde(default)]
    pub tasks: Vec<String>,
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
pub struct Otto {
    #[serde(skip_deserializing, default = "default_otto")]
    pub name: String,

    #[serde(default)]
    pub author: Option<String>,

    #[serde(default)]
    pub about: Option<String>,

    #[serde(default)]
    pub version: Option<String>,

    #[serde(default, deserialize_with = "deserialize_param_map")]
    pub params: Params,

    #[serde(default, deserialize_with = "deserialize_task_map")]
    pub tasks: Tasks,

    pub action: Option<String>,
}

impl Otto {
    fn get_param_key(&self, flag: &str) -> Result<&String, ConfigError> {
        for (key, param) in self.params.iter() {
            if param.flags.iter().any(|f| f == flag) {
                return Ok(key);
            }
        }
        Err(ConfigError::FlagLookupError(flag.to_string()))
    }
    pub fn get_param(&self, name: &str) -> Result<&Param, ConfigError> {
        self.params
            .get(name)
            .ok_or_else(|| ConfigError::NameLookupError(name.to_string()))
    }
    pub fn get_param_from_flag(&self, flag: &str) -> Result<&Param, ConfigError> {
        let key = self.get_param_key(flag)?;
        self.get_param(key)
    }
    pub fn set_param(&mut self, param: Param) -> Result<Param, ConfigError> {
        let name = param.name.to_owned();
        self.params
            .insert(name.to_owned(), param)
            .ok_or(ConfigError::NameLookupError(name))
    }
    pub fn get_task(&self, name: &str) -> Result<&Task, ConfigError> {
        self.tasks
            .get(name)
            .ok_or_else(|| ConfigError::NameLookupError(name.to_string()))
    }
    pub fn set_task(&mut self, task: Task) -> Result<Task, ConfigError> {
        let name = task.name.to_owned();
        self.tasks
            .insert(name.to_owned(), task)
            .ok_or(ConfigError::NameLookupError(name))
    }
    pub fn task_names(&self) -> Vec<&str> {
        self.tasks.keys().map(AsRef::as_ref).collect()
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum ParamType {
    FLG,
    OPT,
    POS,
}

impl Default for ParamType {
    fn default() -> Self {
        ParamType::FLG
    }
}

// FIXME: Flag, Named and Positional Args
#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
pub struct Param {
    #[serde(skip_deserializing)]
    pub name: String,

    #[serde(skip_deserializing)]
    pub short: Option<String>,

    #[serde(skip_deserializing)]
    pub long: Option<String>,

    #[serde(skip_deserializing)]
    pub flags: Vec<String>,

    #[serde(skip_deserializing, default)]
    pub param_type: ParamType,

    #[serde(default)]
    pub dest: Option<String>,

    #[serde(default)]
    pub metavar: Option<String>,

    #[serde(default)]
    pub default: Option<String>,

    #[serde(default, deserialize_with = "deserialize_value")]
    pub constant: Value,

    #[serde(default)]
    pub choices: Vec<String>,

    #[serde(default)]
    pub nargs: Nargs,

    #[serde(default)]
    pub help: Option<String>,
}

impl Param {
    pub fn param_type(&self) -> ParamType {
        match self.name.chars().next() {
            Some('-') => match self.default.as_deref() {
                Some("true") | Some("false") => ParamType::FLG,
                Some(_) | None => ParamType::OPT,
            },
            Some(_) | None => ParamType::POS,
        }
    }
}

fn divine(title: &str) -> (String, Option<String>, Option<String>) {
    let flags: Vec<String> = title.split('|').map(|f| f.to_string()).collect();
    let short = Some(String::from(
        flags
            .iter()
            .cloned()
            .filter(|i| i.starts_with('-') && i.len() == 2)
            .collect::<String>()
            .trim_matches('-'),
    ))
    .filter(|s| !s.is_empty());

    let long = Some(String::from(
        flags
            .iter()
            .cloned()
            .filter(|i| i.starts_with("--") && i.len() > 2)
            .collect::<String>()
            .trim_matches('-'),
    ))
    .filter(|s| !s.is_empty());
    let name = match long {
        Some(ref long) => long.to_owned(),
        None => match short {
            Some(ref short) => short.to_owned(),
            None => title.to_string(),
        },
    };
    (name, short, long)
}

fn deserialize_param_map<'de, D>(deserializer: D) -> Result<Params, D::Error>
where
    D: Deserializer<'de>,
{
    struct ParamMap;

    impl<'de> Visitor<'de> for ParamMap {
        type Value = Params;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a map of name to Param")
        }

        fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
        where
            M: MapAccess<'de>,
        {
            let mut params = Params::new();
            while let Some((title, mut param)) = map.next_entry::<String, Param>()? {
                (param.name, param.short, param.long) = divine(&title);
                params.insert(title.to_owned(), param);
            }
            Ok(params)
        }
    }
    deserializer.deserialize_map(ParamMap)
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
pub struct Task {
    #[serde(skip_deserializing)]
    pub name: String,

    #[serde(default)]
    pub help: Option<String>,

    #[serde(default)]
    pub after: Vec<String>,

    #[serde(default)]
    pub before: Vec<String>,

    #[serde(default, deserialize_with = "deserialize_param_map")]
    pub params: Params,

    pub action: Option<String>,

    #[serde(skip_deserializing)]
    pub selected: bool,
}

impl Task {
    pub fn new(
        name: String,
        help: Option<String>,
        after: Vec<String>,
        before: Vec<String>,
        params: Params,
        action: Option<String>,
        selected: bool,
    ) -> Self {
        Self {
            name,
            help,
            after,
            before,
            params,
            action,
            selected,
        }
    }
    fn get_param_key(&self, flag: &str) -> Result<&String, ConfigError> {
        for (key, param) in self.params.iter() {
            if param.flags.iter().any(|f| f == flag) {
                return Ok(key);
            }
        }
        Err(ConfigError::FlagLookupError(flag.to_string()))
    }
    pub fn get_param(&self, name: &str) -> Result<&Param> {
        self.params
            .get(name)
            .ok_or_else(|| anyhow!("get_param: failed to get name={}", name))
    }
    pub fn get_param_from_flag(&self, flag: &str) -> Result<&Param> {
        let key = self.get_param_key(flag)?;
        self.get_param(key)
    }
    pub fn set_param(&mut self, param: Param) -> Result<Param> {
        let name = param.name.to_owned();
        self.params
            .insert(name.to_owned(), param)
            .ok_or_else(|| anyhow!("set_param: failed to set param.name={}", name))
    }
}

fn deserialize_task_map<'de, D>(deserializer: D) -> Result<Tasks, D::Error>
where
    D: Deserializer<'de>,
{
    struct TaskMap;

    impl<'de> Visitor<'de> for TaskMap {
        type Value = Tasks;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("a map of name to Task")
        }

        fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
        where
            M: MapAccess<'de>,
        {
            let mut tasks = Tasks::new();
            while let Some((name, mut task)) = map.next_entry::<String, Task>()? {
                task.name = name.to_owned();
                tasks.insert(name.to_owned(), task);
            }
            Ok(tasks)
        }
    }
    deserializer.deserialize_map(TaskMap)
}
<|endoftext|>


<commit_before>// Implements http://rosettacode.org/wiki/File_size
// not_tested

fn main() {
    let path_wd = Path::new("input.txt");
    println!("{}", path_wd.stat().unwrap().size);

    let path_root = Path::new("/input.txt");
    println!("{}", path_root.stat().unwrap().size);
}
<commit_msg>Fix filesize<commit_after>// Implements http://rosettacode.org/wiki/File_size
// not_tested

use std::io::fs::PathExtensions;

fn main() {
    let path_wd = Path::new("input.txt");
    println!("{}", path_wd.stat().unwrap().size);

    let path_root = Path::new("/input.txt");
    println!("{}", path_root.stat().unwrap().size);
}
<|endoftext|>


<commit_before>#![allow(unused_imports)]
#![allow(non_snake_case)]

use procon::*;
use std::cmp::{max, min};
use std::collections::*;
use std::ops::*;
use std::*;

pub fn main() {
    return;
}

pub mod procon {
    use std;
    use std::cmp::*;
    use std::collections::*;
    use std::io;
    use std::mem;
    use std::str::FromStr;

    pub fn read_line() -> String {
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        buf.trim_right().to_owned()
    }

    pub fn read_words<T>() -> Vec<T>
    where
        T: std::str::FromStr,
        T::Err: std::fmt::Debug,
    {
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        buf.split_whitespace()
            .map(|word| T::from_str(word).unwrap())
            .collect()
    }

    pub fn read_vec(len: usize) -> Vec<String> {
        let mut vec = Vec::new();
        while vec.len() < len {
            let line = read_line();
            for word in line.split_whitespace() {
                vec.push(word.to_owned());
            }
        }
        assert!(vec.len() == len);
        vec
    }

    // Polyfill
    #[derive(PartialEq, Eq, Clone, Debug)]
    pub struct Rev<T>(pub T);

    impl<T: PartialOrd> PartialOrd for Rev<T> {
        fn partial_cmp(&self, other: &Rev<T>) -> Option<Ordering> {
            other.0.partial_cmp(&self.0)
        }
    }

    impl<T: Ord> Ord for Rev<T> {
        fn cmp(&self, other: &Rev<T>) -> Ordering {
            other.0.cmp(&self.0)
        }
    }
}

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

    #[test]
    pub fn test_ok() {
        assert_eq!(7, 1 + 2 * 3);
    }

    #[test]
    pub fn test_rev() {
        let mut v: Vec<Rev<i32>> = vec![3, 1, 4, 1, 5, 9, 2]
            .into_iter()
            .map(|x| Rev(x))
            .collect::<Vec<_>>();
        v.sort();
        let v = v.into_iter().map(|Rev(x)| x).collect::<Vec<_>>();
        assert_eq!(vec![9, 5, 4, 3, 2, 1, 1], v);
    }
}
<commit_msg>Remove tests<commit_after>#![allow(unused_imports)]
#![allow(non_snake_case)]

use procon::*;
use std::cmp::{max, min};
use std::collections::*;
use std::ops::*;
use std::*;

pub fn main() {
    return;
}

pub mod procon {
    use std;
    use std::cmp::*;
    use std::collections::*;
    use std::io;
    use std::mem;
    use std::str::FromStr;

    pub fn read_line() -> String {
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        buf.trim_right().to_owned()
    }

    pub fn read_words<T>() -> Vec<T>
    where
        T: std::str::FromStr,
        T::Err: std::fmt::Debug,
    {
        let mut buf = String::new();
        io::stdin().read_line(&mut buf).unwrap();
        buf.split_whitespace()
            .map(|word| T::from_str(word).unwrap())
            .collect()
    }

    pub fn read_vec(len: usize) -> Vec<String> {
        let mut vec = Vec::new();
        while vec.len() < len {
            let line = read_line();
            for word in line.split_whitespace() {
                vec.push(word.to_owned());
            }
        }
        assert!(vec.len() == len);
        vec
    }

    // Polyfill
    #[derive(PartialEq, Eq, Clone, Debug)]
    pub struct Rev<T>(pub T);

    impl<T: PartialOrd> PartialOrd for Rev<T> {
        fn partial_cmp(&self, other: &Rev<T>) -> Option<Ordering> {
            other.0.partial_cmp(&self.0)
        }
    }

    impl<T: Ord> Ord for Rev<T> {
        fn cmp(&self, other: &Rev<T>) -> Ordering {
            other.0.cmp(&self.0)
        }
    }
}

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

    #[test]
    pub fn test_ok() {
        assert_eq!(7, 1 + 2 * 3);
    }
}
<|endoftext|>


<commit_before>// -----------------------------------------------
// Framework <https://github.com/vain0x/procon>
//
// See the bottom of file for solution.
// -----------------------------------------------

#![allow(unused_imports)]
#![allow(non_snake_case)]

use std::cell::RefCell;
use std::cmp::{max, min, Ordering};
use std::collections::*;
use std::fmt::{Debug, Display, Formatter, Write as FmtWrite};
use std::io::{stderr, stdin, BufRead, Write};
use std::mem::{replace, swap};
use std::ops::*;
use std::rc::Rc;

/// Print values to standard error if debug mode.
#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), stderr());
            writeln!(err, "\x1B[33m{}\x1B[0m = {:?}", e, $e).unwrap()
        })*
    };
}

/// Read from standard input and parse each word.
/// - `read!(T, U, ..)` parses a line as a tuple of words.
/// - `read![[T]]` parses a line as an array of words.
/// - `read![..; N]` parses `N` lines, using `read!(..)` repeatedly.
#[allow(unused_macros)]
macro_rules! read {
    ([$t:ty] ; $n:expr) =>
        ((0..$n).map(|_| read!([$t])).collect::<Vec<_>>());
    ($($t:ty),+ ; $n:expr) =>
        ((0..$n).map(|_| read!($($t),+)).collect::<Vec<_>>());
    ([$t:ty]) =>
        (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::<Vec<$t>>());
    ($($t:ty),*) => {{
        let buf = rl();
        let mut w = buf.split_whitespace();
        ($(w.next().unwrap().parse::<$t>().unwrap()),*)
    }};
}

/// Read a line from standard input.
#[allow(dead_code)]
fn rl() -> String {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    buf.trim_right().to_owned()
}

// -----------------------------------------------
// Solution
// -----------------------------------------------

fn main() {
    println!("{}", 0)
}
<commit_msg>refactor: Use documentation comments<commit_after>//! ----------------------------------------------
//! Framework <https://github.com/vain0x/procon>
//!
//! See the bottom of file for solution.
//! ----------------------------------------------

#![allow(unused_imports)]
#![allow(non_snake_case)]

use std::cell::RefCell;
use std::cmp::{max, min, Ordering};
use std::collections::*;
use std::fmt::{Debug, Display, Formatter, Write as FmtWrite};
use std::io::{stderr, stdin, BufRead, Write};
use std::mem::{replace, swap};
use std::ops::*;
use std::rc::Rc;

/// Print values to standard error if debug mode.
#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), stderr());
            writeln!(err, "\x1B[33m{}\x1B[0m = {:?}", e, $e).unwrap()
        })*
    };
}

/// Read from standard input and parse each word.
/// - `read!(T, U, ..)` parses a line as a tuple of words.
/// - `read![[T]]` parses a line as an array of words.
/// - `read![..; N]` parses `N` lines, using `read!(..)` repeatedly.
#[allow(unused_macros)]
macro_rules! read {
    ([$t:ty] ; $n:expr) =>
        ((0..$n).map(|_| read!([$t])).collect::<Vec<_>>());
    ($($t:ty),+ ; $n:expr) =>
        ((0..$n).map(|_| read!($($t),+)).collect::<Vec<_>>());
    ([$t:ty]) =>
        (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::<Vec<$t>>());
    ($($t:ty),*) => {{
        let buf = rl();
        let mut w = buf.split_whitespace();
        ($(w.next().unwrap().parse::<$t>().unwrap()),*)
    }};
}

/// Read a line from standard input.
#[allow(dead_code)]
fn rl() -> String {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();
    buf.trim_right().to_owned()
}

// -----------------------------------------------
// Solution
// -----------------------------------------------

fn main() {
    println!("{}", 0)
}
<|endoftext|>


<commit_before>use cargo_helper::CargoInfo;
use Bytes;
use client::GetResponse;
use hyper::client::Client;
use hyper::error::Error;
use hyper::header::{ByteRangeSpec, Headers, Range};
use pbr::{MultiBar, Pipe, ProgressBar, Units};
use response::CheckResponseStatus;
use std::cmp::min;
use std::io::Read;
use std::thread;
use std::time::{Instant, Duration};
use write::{OutputFileWriter, OutputChunkWriter};

/// Constant to represent the length of the buffer to download
/// the remote content
const DOWNLOAD_BUFFER_BYTES: usize = 1024 * 64;

/// Constant to represent the refresh interval (in milliseconds)
/// for the CLI
const PROGRESS_UPDATE_INTERVAL_MILLIS: u64 = 500;

/// Represents a range between two Bytes types
#[derive(Debug, PartialEq)]
struct RangeBytes(Bytes, Bytes);

macro_rules! initbar {
    ($mp:ident,$mpb:ident,$length:expr,$index:expr) => {
        let mut $mp = $mpb.create_bar($length);
        $mp.tick_format("▏▎▍▌▋▊▉██▉▊▋▌▍▎▏");
        $mp.format("|#--|");
        $mp.show_tick = true;
        $mp.show_speed = true;
        $mp.show_percent = true;
        $mp.show_counter = false;
        $mp.show_time_left = true;
        $mp.set_units(Units::Bytes);
        $mp.message(&format!("Chunk {} ", $index));
    }
}

/// Function to get the current chunk length, based on the chunk index.
fn get_chunk_length(chunk_index: u64,
                    content_length: Bytes,
                    global_chunk_length: Bytes)
                    -> Option<RangeBytes> {

    if content_length == 0 || global_chunk_length == 0 {
        return None;
    }

    let b_range: Bytes = chunk_index * global_chunk_length;

    if b_range >= (content_length - 1) {
        return None;
    }

    let e_range: Bytes = min(content_length - 1,
                             ((chunk_index + 1) * global_chunk_length) - 1);

    Some(RangeBytes(b_range, e_range))

}

/// Function to get the HTTP header to send to the file server, for a chunk (specified by its index)
fn get_header_from_index(chunk_index: u64,
                         content_length: Bytes,
                         global_chunk_length: Bytes)
                         -> Option<(Headers, RangeBytes)> {

    get_chunk_length(chunk_index, content_length, global_chunk_length).map(|range| {
        let mut header = Headers::new();
        header.set(Range::Bytes(vec![ByteRangeSpec::FromTo(range.0, range.1)]));
        (header, RangeBytes(range.0, range.1 - range.0))
    })
}

/// Function to get from the server the content of a chunk.
/// This function returns a Result type - Bytes if the content of the header is accessible, an Error type otherwise.
fn download_a_chunk(http_client: &Client,
                    http_header: Headers,
                    mut chunk_writer: OutputChunkWriter,
                    url: &str,
                    mpb: &mut ProgressBar<Pipe>)
                    -> Result<Bytes, Error> {

    let mut body = http_client.get_http_response_using_headers(url, http_header).unwrap();
    if !body.check_partialcontent_status() {
        return Err(Error::Status);
    }
    let mut bytes_buffer = [0; DOWNLOAD_BUFFER_BYTES];
    let mut sum_bytes = 0;

    let progress_update_interval = Duration::from_millis(PROGRESS_UPDATE_INTERVAL_MILLIS);
    let mut last_progress_bytes = 0;
    let mut last_progress_time = Instant::now() - progress_update_interval;

    while let Ok(n) = body.read(&mut bytes_buffer) {
        if n == 0 {
            return Ok(sum_bytes);
        }

        chunk_writer.write(sum_bytes, &bytes_buffer[0..n]);

        sum_bytes += n as u64;

        // Update the CLI
        if Instant::now().duration_since(last_progress_time) > progress_update_interval {
            last_progress_time = Instant::now();
            let progress_bytes_delta = sum_bytes - last_progress_bytes;
            last_progress_bytes = sum_bytes;
            mpb.add(progress_bytes_delta);
        }
    }
    mpb.add(sum_bytes - last_progress_bytes);
    return Ok(0u64);
}

/// Function to download each chunk of a remote content (given by its URL).
/// This function takes as parameters:
/// * the remote content length,
/// * a mutable reference to share between threads, which contains each chunk,
/// * the number of chunks that contains the remote content,
/// * the URL of the remote content server,
/// * a custom authorization to access and download the remote content.
pub fn download_chunks(cargo_info: CargoInfo,
                       mut out_file: OutputFileWriter,
                       nb_chunks: u64,
                       url: &str) {
    let (content_length, auth_header_factory) =
        (cargo_info.content_length, cargo_info.auth_header);

    let global_chunk_length: u64 = (content_length / nb_chunks) + 1;
    let mut jobs = vec![];

    let mut mpb = MultiBar::new();
    mpb.println(&format!("Downloading {} chunks: ", nb_chunks));

    for chunk_index in 0..nb_chunks {

        let (mut http_header, RangeBytes(chunk_offset, chunk_length)) =
            get_header_from_index(chunk_index, content_length, global_chunk_length).unwrap();
        let hyper_client = Client::new();
        let url_clone = String::from(url);
        if let Some(auth_header_factory) = auth_header_factory.clone() {
            http_header.set(auth_header_factory.build_header());
        }

        // Initialize the progress bar for that chunk
        initbar!(mp, mpb, chunk_length, chunk_index);

        let chunk_writer = out_file.get_chunk_writer(chunk_offset);
        jobs.push(thread::spawn(move || match download_a_chunk(&hyper_client,
                                                                    http_header,
                                                                    chunk_writer,
                                                                    &url_clone,
                                                                    &mut mp) {
            Ok(bytes_written) => {
                mp.finish();
                if bytes_written == 0 {
                    panic!("The downloaded chunk {} is empty", chunk_index);
                }
            }
            Err(error) => {
                mp.finish();
                panic!("Cannot download the chunk {}, due to error {}",
                       chunk_index,
                       error);
            }
        }));
    }

    mpb.listen();

    for child in jobs {
        let _ = child.join();
    }

}

#[cfg(test)]
mod test_chunk_length {

    use super::get_chunk_length;
    use super::RangeBytes;

    #[test]
    fn wrong_content_length_parameter_should_return_none() {
        assert_eq!(None, get_chunk_length(0, 15, 0));
    }

    #[test]
    fn wrong_global_chunk_length_parameter_should_return_none() {
        assert_eq!(None, get_chunk_length(0, 0, 15));
    }

    #[test]
    fn wrong_length_parameters_should_return_none() {
        assert_eq!(None, get_chunk_length(0, 0, 0));
    }

    #[test]
    fn get_the_first_range_in_chunk() {
        assert_eq!(Some(RangeBytes(0, 249)), get_chunk_length(0, 1000, 250));
    }

    #[test]
    fn get_the_last_range_in_chunk() {
        assert_eq!(Some(RangeBytes(750, 999)), get_chunk_length(3, 1000, 250));
    }

    #[test]
    fn get_the_last_range_in_shorten_chunk() {
        assert_eq!(Some(RangeBytes(750, 997)), get_chunk_length(3, 998, 250));
    }

    #[test]
    fn wrong_index_parameter_should_return_none() {
        assert_eq!(None, get_chunk_length(4, 1000, 250));
    }

}

#[cfg(test)]
mod test_header {

    use super::{get_header_from_index, RangeBytes};
    use hyper::header::{ByteRangeSpec, Headers, Range};

    #[test]
    fn wrong_chunk_length_should_return_none() {
        assert_eq!(None, get_header_from_index(0, 0, 0));
    }

    #[test]
    fn good_chunk_length_should_return_a_good_header() {
        let mut test_header = Headers::new();
        test_header.set(Range::Bytes(vec![ByteRangeSpec::FromTo(750, 997)]));
        assert_eq!(Some((test_header, RangeBytes(750, 247))),
                   get_header_from_index(3, 998, 250));
    }

}
<commit_msg>Code style<commit_after>use cargo_helper::CargoInfo;
use Bytes;
use client::GetResponse;
use hyper::client::Client;
use hyper::error::Error;
use hyper::header::{ByteRangeSpec, Headers, Range};
use pbr::{MultiBar, Pipe, ProgressBar, Units};
use response::CheckResponseStatus;
use std::cmp::min;
use std::io::Read;
use std::thread;
use std::time::{Instant, Duration};
use write::{OutputFileWriter, OutputChunkWriter};

/// Constant to represent the length of the buffer to download
/// the remote content
const DOWNLOAD_BUFFER_BYTES: usize = 1024 * 64;

/// Constant to represent the refresh interval (in milliseconds)
/// for the CLI
const PROGRESS_UPDATE_INTERVAL_MILLIS: u64 = 500;

/// Represents a range between two Bytes types
#[derive(Debug, PartialEq)]
struct RangeBytes(Bytes, Bytes);

macro_rules! initbar {
    ($mp:ident,$mpb:ident,$length:expr,$index:expr) => {
        let mut $mp = $mpb.create_bar($length);
        $mp.tick_format("▏▎▍▌▋▊▉██▉▊▋▌▍▎▏");
        $mp.format("|#--|");
        $mp.show_tick = true;
        $mp.show_speed = true;
        $mp.show_percent = true;
        $mp.show_counter = false;
        $mp.show_time_left = true;
        $mp.set_units(Units::Bytes);
        $mp.message(&format!("Chunk {} ", $index));
    }
}

/// Function to get the current chunk length, based on the chunk index.
fn get_chunk_length(chunk_index: u64,
                    content_length: Bytes,
                    global_chunk_length: Bytes)
                    -> Option<RangeBytes> {

    if content_length == 0 || global_chunk_length == 0 {
        return None;
    }

    let b_range: Bytes = chunk_index * global_chunk_length;

    if b_range >= (content_length - 1) {
        return None;
    }

    let e_range: Bytes = min(content_length - 1,
                             ((chunk_index + 1) * global_chunk_length) - 1);

    Some(RangeBytes(b_range, e_range))

}

/// Function to get the HTTP header to send to the file server, for a chunk (specified by its index)
fn get_header_from_index(chunk_index: u64,
                         content_length: Bytes,
                         global_chunk_length: Bytes)
                         -> Option<(Headers, RangeBytes)> {

    get_chunk_length(chunk_index, content_length, global_chunk_length).map(|range| {
        let mut header = Headers::new();
        header.set(Range::Bytes(vec![ByteRangeSpec::FromTo(range.0, range.1)]));
        (header, RangeBytes(range.0, range.1 - range.0))
    })
}

/// Function to get from the server the content of a chunk.
/// This function returns a Result type - Bytes if the content of the header is accessible, an Error type otherwise.
fn download_a_chunk(http_client: &Client,
                    http_header: Headers,
                    mut chunk_writer: OutputChunkWriter,
                    url: &str,
                    mpb: &mut ProgressBar<Pipe>)
                    -> Result<Bytes, Error> {

    let mut body = http_client.get_http_response_using_headers(url, http_header).unwrap();
    if !body.check_partialcontent_status() {
        return Err(Error::Status);
    }
    let mut bytes_buffer = [0; DOWNLOAD_BUFFER_BYTES];
    let mut sum_bytes = 0;

    let progress_update_interval = Duration::from_millis(PROGRESS_UPDATE_INTERVAL_MILLIS);
    let mut last_progress_bytes = 0;
    let mut last_progress_time = Instant::now() - progress_update_interval;

    while let Ok(n) = body.read(&mut bytes_buffer) {
        if n == 0 {
            return Ok(sum_bytes);
        }

        chunk_writer.write(sum_bytes, &bytes_buffer[0..n]);

        sum_bytes += n as u64;

        // Update the CLI
        if Instant::now().duration_since(last_progress_time) > progress_update_interval {
            last_progress_time = Instant::now();
            let progress_bytes_delta = sum_bytes - last_progress_bytes;
            last_progress_bytes = sum_bytes;
            mpb.add(progress_bytes_delta);
        }
    }
    mpb.add(sum_bytes - last_progress_bytes);
    return Ok(0u64);
}

/// Function to download each chunk of a remote content (given by its URL).
/// This function takes as parameters:
/// * the remote content length,
/// * a mutable reference to share between threads, which contains each chunk,
/// * the number of chunks that contains the remote content,
/// * the URL of the remote content server,
/// * a custom authorization to access and download the remote content.
pub fn download_chunks(cargo_info: CargoInfo,
                       mut out_file: OutputFileWriter,
                       nb_chunks: u64,
                       url: &str) {
    let (content_length, auth_header_factory) = (cargo_info.content_length, cargo_info.auth_header);

    let global_chunk_length: u64 = (content_length / nb_chunks) + 1;
    let mut jobs = vec![];

    let mut mpb = MultiBar::new();
    mpb.println(&format!("Downloading {} chunks: ", nb_chunks));

    for chunk_index in 0..nb_chunks {

        let (mut http_header, RangeBytes(chunk_offset, chunk_length)) =
            get_header_from_index(chunk_index, content_length, global_chunk_length).unwrap();
        let hyper_client = Client::new();
        let url_clone = String::from(url);
        if let Some(auth_header_factory) = auth_header_factory.clone() {
            http_header.set(auth_header_factory.build_header());
        }

        // Initialize the progress bar for that chunk
        initbar!(mp, mpb, chunk_length, chunk_index);

        let chunk_writer = out_file.get_chunk_writer(chunk_offset);
        jobs.push(thread::spawn(move || match download_a_chunk(&hyper_client,
                                                       http_header,
                                                       chunk_writer,
                                                       &url_clone,
                                                       &mut mp) {
                                    Ok(bytes_written) => {
            mp.finish();
            if bytes_written == 0 {
                panic!("The downloaded chunk {} is empty", chunk_index);
            }
        }
                                    Err(error) => {
            mp.finish();
            panic!("Cannot download the chunk {}, due to error {}",
                   chunk_index,
                   error);
        }
                                }));
    }

    mpb.listen();

    for child in jobs {
        let _ = child.join();
    }

}

#[cfg(test)]
mod test_chunk_length {

    use super::get_chunk_length;
    use super::RangeBytes;

    #[test]
    fn wrong_content_length_parameter_should_return_none() {
        assert_eq!(None, get_chunk_length(0, 15, 0));
    }

    #[test]
    fn wrong_global_chunk_length_parameter_should_return_none() {
        assert_eq!(None, get_chunk_length(0, 0, 15));
    }

    #[test]
    fn wrong_length_parameters_should_return_none() {
        assert_eq!(None, get_chunk_length(0, 0, 0));
    }

    #[test]
    fn get_the_first_range_in_chunk() {
        assert_eq!(Some(RangeBytes(0, 249)), get_chunk_length(0, 1000, 250));
    }

    #[test]
    fn get_the_last_range_in_chunk() {
        assert_eq!(Some(RangeBytes(750, 999)), get_chunk_length(3, 1000, 250));
    }

    #[test]
    fn get_the_last_range_in_shorten_chunk() {
        assert_eq!(Some(RangeBytes(750, 997)), get_chunk_length(3, 998, 250));
    }

    #[test]
    fn wrong_index_parameter_should_return_none() {
        assert_eq!(None, get_chunk_length(4, 1000, 250));
    }

}

#[cfg(test)]
mod test_header {

    use super::{get_header_from_index, RangeBytes};
    use hyper::header::{ByteRangeSpec, Headers, Range};

    #[test]
    fn wrong_chunk_length_should_return_none() {
        assert_eq!(None, get_header_from_index(0, 0, 0));
    }

    #[test]
    fn good_chunk_length_should_return_a_good_header() {
        let mut test_header = Headers::new();
        test_header.set(Range::Bytes(vec![ByteRangeSpec::FromTo(750, 997)]));
        assert_eq!(Some((test_header, RangeBytes(750, 247))),
                   get_header_from_index(3, 998, 250));
    }

}
<|endoftext|>


<commit_before>use std::io;
use std::fs::File;
use std::ops::{Add, Sub};
use std::path::Path;

#[derive(Debug, Copy, Clone)]
pub struct Vec2D<T> {
    pub x: T,
    pub y: T
}

impl<T> Add<Vec2D<T>> for Vec2D<T> where T: Add<T, Output = T> {
    type Output = Vec2D<T>;

    fn add(self, other: Vec2D<T>) -> Vec2D<T> {
        Vec2D { x: self.x + other.x, y: self.y + other.y }
    }
}

impl<T> Sub<Vec2D<T>> for Vec2D<T> where T: Sub<T, Output = T> {
    type Output = Vec2D<T>;

    fn sub(self, other: Vec2D<T>) -> Vec2D<T> {
        Vec2D { x: self.x - other.x, y: self.y - other.y }
    }
}

#[derive(Debug, Copy, Clone)]
pub struct Vec3D<T> {
    pub x: T,
    pub y: T,
    pub z: T
}

impl<T> Add<Vec3D<T>> for Vec3D<T> where T: Add<T, Output = T> {
    type Output = Vec3D<T>;

    fn add(self, other: Vec3D<T>) -> Vec3D<T> {
        Vec3D { x: self.x + other.x, y: self.y + other.y, z: self.z + other.z }
    }
}

impl<T> Sub<Vec3D<T>> for Vec3D<T> where T: Sub<T, Output = T> {
    type Output = Vec3D<T>;

    fn sub(self, other: Vec3D<T>) -> Vec3D<T> {
        Vec3D { x: self.x - other.x, y: self.y - other.y, z: self.z - other.z }
    }
}

pub type Vec3Df = Vec3D<f64>;

#[derive(Debug)]
pub struct Model {
    pub verts: Vec<Vec3Df>,
    pub faces: Vec<Vec<u32>>
}

pub fn load_model_obj<P>(path: P) -> Result<Model, io::Error> where P: AsRef<Path> {
    let mut f = match File::open(&path) {
        Err(why)    => return Err(why),
        Ok(f)       => f,
    };

    Ok(Model { verts: Vec::new(), faces: Vec::new() })
}
<commit_msg>we can read files! wouhou!<commit_after>use std::io;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
use std::ops::{Add, Sub};
use std::path::Path;

#[derive(Debug, Copy, Clone)]
pub struct Vec2D<T> {
    pub x: T,
    pub y: T
}

impl<T> Add<Vec2D<T>> for Vec2D<T> where T: Add<T, Output = T> {
    type Output = Vec2D<T>;

    fn add(self, other: Vec2D<T>) -> Vec2D<T> {
        Vec2D { x: self.x + other.x, y: self.y + other.y }
    }
}

impl<T> Sub<Vec2D<T>> for Vec2D<T> where T: Sub<T, Output = T> {
    type Output = Vec2D<T>;

    fn sub(self, other: Vec2D<T>) -> Vec2D<T> {
        Vec2D { x: self.x - other.x, y: self.y - other.y }
    }
}

#[derive(Debug, Copy, Clone)]
pub struct Vec3D<T> {
    pub x: T,
    pub y: T,
    pub z: T
}

impl<T> Add<Vec3D<T>> for Vec3D<T> where T: Add<T, Output = T> {
    type Output = Vec3D<T>;

    fn add(self, other: Vec3D<T>) -> Vec3D<T> {
        Vec3D { x: self.x + other.x, y: self.y + other.y, z: self.z + other.z }
    }
}

impl<T> Sub<Vec3D<T>> for Vec3D<T> where T: Sub<T, Output = T> {
    type Output = Vec3D<T>;

    fn sub(self, other: Vec3D<T>) -> Vec3D<T> {
        Vec3D { x: self.x - other.x, y: self.y - other.y, z: self.z - other.z }
    }
}

pub type Vec3Df = Vec3D<f64>;

#[derive(Debug)]
pub struct Model {
    pub verts: Vec<Vec3Df>,
    pub faces: Vec<Vec<u32>>
}

pub fn load_model_obj<P>(path: P) -> Result<Model, io::Error> where P: AsRef<Path> {
    let mut f = match File::open(&path) {
        Err(why)    => return Err(why),
        Ok(f)       => f,
    };

    let mut reader = BufReader::new(&f);

    for line in reader.lines().filter_map(|res| res.ok()) {
        print!("{}", line);
    }

    Ok(Model { verts: Vec::new(), faces: Vec::new() })
}

<|endoftext|>


<commit_before>//! This module provides a bit reader

use std::io;

/// A bit reader.
///
/// Reads bits from a byte stream, LSB first.
pub struct BitReader<R> where R: Reader{
    r: R,
    bits: u8,
    buf: u64,
}

impl<R: Reader> BitReader<R> {
    /// Creates a new bit reader
    pub fn new(reader: R) -> BitReader<R> {
        BitReader {
            r: reader,
            bits: 0,
            buf: 0,
        }
    }

    fn fill_cache(&mut self, n: u8) -> io::IoResult<()> {
        if n > 64 {
            return Err(io::IoError {
                kind: io::InvalidInput,
                desc: "Cannot read more than 64 bits",
                detail: None
            })
        }
        // FIXME: 64bit won't work this way
        while self.bits < n {
            self.buf |= try!(self.r.read_byte()) as u64 << self.bits as uint;
            self.bits += 8;
        }
        Ok(())
    }

    /// Returns the next `n` bits without consuming them.
    pub fn peek_bits(&mut self, n: u8) -> io::IoResult<u64> {
        try!(self.fill_cache(n));
        let mask = (1 << n as uint) - 1;
        Ok(self.buf & mask)
    }

    fn consume(&mut self, n: u8) {
        self.buf >>= n as uint;
        self.bits -= n;
    }

    /// Returns the next `n` bits.
    pub fn read_bits(&mut self, n: u8) -> io::IoResult<u64> {
        let res = try!(self.peek_bits(n));
        self.consume(n);
        Ok(res)
    }

    /// Returns true if the reader is aligned to a byte of the underlying byte stream.
    #[inline(always)]
    fn is_aligned(&self) -> bool {
        self.bits == 0
    }
}

impl<R: Reader> Reader for BitReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
        if self.is_aligned() {
            self.r.read(buf)
        } else {
            let mut i = 0;
            for (j, byte) in buf.iter_mut().enumerate() {
                *byte = try!(self.read_bits(8)) as u8;
                i = j;
            }
            Ok(i)
        }
    }
}

/// A bit writer.
///
/// Reads bits from a byte stream, LSB first.
pub struct BitWriter<'a, W> where W: Writer + 'a {
    w: &'a mut W,
    bits: u8,
    buf: u8,
}

impl<'a, W> BitWriter<'a, W> where W: Writer + 'a {
    /// Creates a new bit reader
    pub fn new(writer: &'a mut W) -> BitWriter<'a, W> {
        BitWriter {
            w: writer,
            bits: 0,
            buf: 0,
        }
    }

    /// Returns the next `n` bits.
    pub fn write_bits(&mut self, mut v: u32, mut n: u8) -> io::IoResult<()> {
        while n > 0 {
            self.buf |= v as u8 << self.bits as uint;
            let missing = 8u8 - self.bits;
            if n >= missing {
                n -= missing;
                v >>= missing as uint;
                try!(self.w.write_u8(self.buf));
                self.bits = 0;
                self.buf = 0;
            } else {
                self.bits += n;
                break
            }
        }
        Ok(())
    }

    /// Flushes the internal accumulator fill missing bits with 0
    pub fn flush(&mut self) -> io::IoResult<()> {
        if self.bits > 0 {
            try!(self.w.write_u8(self.buf));
            self.bits = 0;
            self.buf = 0;
        }
        Ok(())
    }

    /// Returns true if the reader is aligned to a byte of the underlying byte stream.
    #[inline(always)]
    fn is_aligned(&self) -> bool {
        self.bits == 0
    }
}

#[cfg(test)]
mod test {
    #[test]
    fn reader_writer() {
        let data = [255, 20, 40, 120, 128];
        let mut expanded_data = Vec::new();
        let mut reader = super::BitReader::new(data.as_slice());
        while let Ok(b) = reader.read_bits(10) {
            expanded_data.push(b as u32)
        }
        let mut compressed_data = Vec::new();
        {
            let mut writer = super::BitWriter::new(&mut compressed_data);
            for &datum in expanded_data.iter() {
                let _  = writer.write_bits(datum, 10);
            }
        }
        assert_eq!(data.as_slice(), compressed_data.as_slice())
    }
}<commit_msg>suppress warnings<commit_after>//! This module provides a bit reader

use std::io;

/// A bit reader.
///
/// Reads bits from a byte stream, LSB first.
pub struct BitReader<R> where R: Reader{
    r: R,
    bits: u8,
    buf: u64,
}

impl<R: Reader> BitReader<R> {
    /// Creates a new bit reader
    pub fn new(reader: R) -> BitReader<R> {
        BitReader {
            r: reader,
            bits: 0,
            buf: 0,
        }
    }

    fn fill_cache(&mut self, n: u8) -> io::IoResult<()> {
        if n > 64 {
            return Err(io::IoError {
                kind: io::InvalidInput,
                desc: "Cannot read more than 64 bits",
                detail: None
            })
        }
        // FIXME: 64bit won't work this way
        while self.bits < n {
            self.buf |= try!(self.r.read_byte()) as u64 << self.bits as uint;
            self.bits += 8;
        }
        Ok(())
    }

    /// Returns the next `n` bits without consuming them.
    pub fn peek_bits(&mut self, n: u8) -> io::IoResult<u64> {
        try!(self.fill_cache(n));
        let mask = (1 << n as uint) - 1;
        Ok(self.buf & mask)
    }

    fn consume(&mut self, n: u8) {
        self.buf >>= n as uint;
        self.bits -= n;
    }

    /// Returns the next `n` bits.
    pub fn read_bits(&mut self, n: u8) -> io::IoResult<u64> {
        let res = try!(self.peek_bits(n));
        self.consume(n);
        Ok(res)
    }

    /// Returns true if the reader is aligned to a byte of the underlying byte stream.
    #[inline(always)]
    fn is_aligned(&self) -> bool {
        self.bits == 0
    }
}

impl<R: Reader> Reader for BitReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::IoResult<uint> {
        if self.is_aligned() {
            self.r.read(buf)
        } else {
            let mut i = 0;
            for (j, byte) in buf.iter_mut().enumerate() {
                *byte = try!(self.read_bits(8)) as u8;
                i = j;
            }
            Ok(i)
        }
    }
}

/// A bit writer.
///
/// Reads bits from a byte stream, LSB first.
#[allow(dead_code)]
pub struct BitWriter<'a, W> where W: Writer + 'a {
    w: &'a mut W,
    bits: u8,
    buf: u8,
}
#[allow(dead_code)]
impl<'a, W> BitWriter<'a, W> where W: Writer + 'a {
    /// Creates a new bit reader
    pub fn new(writer: &'a mut W) -> BitWriter<'a, W> {
        BitWriter {
            w: writer,
            bits: 0,
            buf: 0,
        }
    }

    /// Returns the next `n` bits.
    pub fn write_bits(&mut self, mut v: u32, mut n: u8) -> io::IoResult<()> {
        while n > 0 {
            self.buf |= v as u8 << self.bits as uint;
            let missing = 8u8 - self.bits;
            if n >= missing {
                n -= missing;
                v >>= missing as uint;
                try!(self.w.write_u8(self.buf));
                self.bits = 0;
                self.buf = 0;
            } else {
                self.bits += n;
                break
            }
        }
        Ok(())
    }

    /// Flushes the internal accumulator fill missing bits with 0
    pub fn flush(&mut self) -> io::IoResult<()> {
        if self.bits > 0 {
            try!(self.w.write_u8(self.buf));
            self.bits = 0;
            self.buf = 0;
        }
        Ok(())
    }
}

#[cfg(test)]
mod test {
    #[test]
    fn reader_writer() {
        let data = [255, 20, 40, 120, 128];
        let mut expanded_data = Vec::new();
        let mut reader = super::BitReader::new(data.as_slice());
        while let Ok(b) = reader.read_bits(10) {
            expanded_data.push(b as u32)
        }
        let mut compressed_data = Vec::new();
        {
            let mut writer = super::BitWriter::new(&mut compressed_data);
            for &datum in expanded_data.iter() {
                let _  = writer.write_bits(datum, 10);
            }
        }
        assert_eq!(data.as_slice(), compressed_data.as_slice())
    }
}<|endoftext|>


<commit_before>use crate::memory::{io::IoRegisters, palette::Palette};

pub const OBJ: usize = 4;

pub struct LineBuffer {
    // 240 pixels for each background (BG0-3 + OBJ)
    pixels: [[u16; 240]; 5],
    layer_metadata: [LayerMetadata; 5],
}

impl Default for LineBuffer {
    fn default() -> Self {
        LineBuffer {
            pixels: [[0; 240]; 5],
            layer_metadata: [LayerMetadata::default(); 5],
        }
    }
}

impl LineBuffer {
    pub(crate) fn put(&mut self, layer: usize, x: usize, pixel: u16) {
        self.pixels[layer][x] = pixel | 0x8000;
    }
    pub(crate) fn put_4bpp(&mut self, layer: usize, x: usize, palette: u8, entry: u8) {
        self.pixels[layer][x] = ((palette as u16) << 4) | (entry as u16);
    }

    pub(crate) fn put_8bpp(&mut self, layer: usize, x: usize, entry: u8) {
        self.pixels[layer][x] = entry as u16;
    }

    pub(crate) fn layer_metadata_mut(&mut self, layer: usize) -> &mut LayerMetadata {
        &mut self.layer_metadata[layer]
    }

    fn color(&self, layer: usize, x: usize, palette: &Palette) -> Option<u16> {
        let metadata = self.layer_metadata[layer];
        let entry = self.pixels[layer][x];

        if metadata.is_bitmap() {
            return Some(entry);
        }

        if metadata.is_4bpp() {
            let color_entry = entry & 0xF;
            if color_entry == 0 {
                return None;
            }
            let palette_index = entry >> 4;

            if layer == OBJ {
                Some(palette.get_obj16(palette_index as _, color_entry as _))
            } else {
                Some(palette.get_bg16(palette_index as _, color_entry as _))
            }
        } else if entry == 0 {
            None
        } else if layer == OBJ {
            Some(palette.get_obj256(entry as _))
        } else {
            Some(palette.get_bg256(entry as _))
        }
    }

    pub fn render(&self, output: &mut [u16], ioregs: &IoRegisters, palette: &Palette) {
        let backdrop = palette.get_bg256(0) | 0x8000;
        (0..240)
            .map(|x| (x, self.render_pixel(x, ioregs, backdrop, palette)))
            .for_each(|(x, p)| output[x] = p);
    }

    fn render_pixel(
        &self,
        x: usize,
        ioregs: &IoRegisters,
        backdrop: u16,
        palette: &Palette,
    ) -> u16 {
        let mut displayed_layers: usize = 0xFF;

        for priority in (0..4).rev() {
            for bg in 0usize..4 {
                if ioregs.dispcnt.display_bg(bg as _) && ioregs.bgcnt[bg].priority() == priority {
                    displayed_layers <<= 4;
                    displayed_layers |= bg as usize;
                }
            }
            // FIXME add OBJ pixel here :)
        }

        let layer = displayed_layers & 0xF;
        if layer > 4 {
            return backdrop;
        }

        self.color(layer, x, palette).unwrap_or(backdrop)
    }
}

#[derive(Clone, Copy, Default)]
pub(crate) struct LayerMetadata {
    value: u16,
}

impl LayerMetadata {
    const BITMAP_16BPP: u16 = 0x1;
    const PALETTE_4BPP: u16 = 0x2;

    pub fn is_bitmap(&self) -> bool {
        (self.value & Self::BITMAP_16BPP) != 0
    }

    pub fn is_4bpp(&self) -> bool {
        (self.value & Self::PALETTE_4BPP) != 0
    }

    pub fn is_8bpp(&self) -> bool {
        (self.value & (Self::BITMAP_16BPP | Self::PALETTE_4BPP)) == 0
    }

    pub fn set_bitmap(&mut self) {
        self.value |= Self::BITMAP_16BPP;
    }

    pub fn set_4bpp(&mut self) {
        self.value |= Self::PALETTE_4BPP;
    }

    pub fn set_8bpp(&mut self) {
        /* NOP */
    }
}

struct PixelMetadata {}
<commit_msg>Remove `is_8bpp`. `is_bitmap` and `is_4bpp` are enough.<commit_after>use crate::memory::{io::IoRegisters, palette::Palette};

pub const OBJ: usize = 4;

pub struct LineBuffer {
    // 240 pixels for each background (BG0-3 + OBJ)
    pixels: [[u16; 240]; 5],
    layer_metadata: [LayerMetadata; 5],
}

impl Default for LineBuffer {
    fn default() -> Self {
        LineBuffer {
            pixels: [[0; 240]; 5],
            layer_metadata: [LayerMetadata::default(); 5],
        }
    }
}

impl LineBuffer {
    pub(crate) fn put(&mut self, layer: usize, x: usize, pixel: u16) {
        self.pixels[layer][x] = pixel | 0x8000;
    }
    pub(crate) fn put_4bpp(&mut self, layer: usize, x: usize, palette: u8, entry: u8) {
        self.pixels[layer][x] = ((palette as u16) << 4) | (entry as u16);
    }

    pub(crate) fn put_8bpp(&mut self, layer: usize, x: usize, entry: u8) {
        self.pixels[layer][x] = entry as u16;
    }

    pub(crate) fn layer_metadata_mut(&mut self, layer: usize) -> &mut LayerMetadata {
        &mut self.layer_metadata[layer]
    }

    fn color(&self, layer: usize, x: usize, palette: &Palette) -> Option<u16> {
        let metadata = self.layer_metadata[layer];
        let entry = self.pixels[layer][x];

        if metadata.is_bitmap() {
            return Some(entry);
        }

        if metadata.is_4bpp() {
            let color_entry = entry & 0xF;
            if color_entry == 0 {
                return None;
            }
            let palette_index = entry >> 4;

            if layer == OBJ {
                Some(palette.get_obj16(palette_index as _, color_entry as _))
            } else {
                Some(palette.get_bg16(palette_index as _, color_entry as _))
            }
        } else if entry == 0 {
            None
        } else if layer == OBJ {
            Some(palette.get_obj256(entry as _))
        } else {
            Some(palette.get_bg256(entry as _))
        }
    }

    pub fn render(&self, output: &mut [u16], ioregs: &IoRegisters, palette: &Palette) {
        let backdrop = palette.get_bg256(0) | 0x8000;
        (0..240)
            .map(|x| (x, self.render_pixel(x, ioregs, backdrop, palette)))
            .for_each(|(x, p)| output[x] = p);
    }

    fn render_pixel(
        &self,
        x: usize,
        ioregs: &IoRegisters,
        backdrop: u16,
        palette: &Palette,
    ) -> u16 {
        let mut displayed_layers: usize = 0xFF;

        for priority in (0..4).rev() {
            for bg in 0usize..4 {
                if ioregs.dispcnt.display_bg(bg as _) && ioregs.bgcnt[bg].priority() == priority {
                    displayed_layers <<= 4;
                    displayed_layers |= bg as usize;
                }
            }
            // FIXME add OBJ pixel here :)
        }

        let layer = displayed_layers & 0xF;
        if layer > 4 {
            return backdrop;
        }

        self.color(layer, x, palette).unwrap_or(backdrop)
    }
}

#[derive(Clone, Copy, Default)]
pub(crate) struct LayerMetadata {
    value: u16,
}

impl LayerMetadata {
    const BITMAP_16BPP: u16 = 0x1;
    const PALETTE_4BPP: u16 = 0x2;

    pub fn is_bitmap(&self) -> bool {
        (self.value & Self::BITMAP_16BPP) != 0
    }

    pub fn is_4bpp(&self) -> bool {
        (self.value & Self::PALETTE_4BPP) != 0
    }

    pub fn set_bitmap(&mut self) {
        self.value |= Self::BITMAP_16BPP;
    }

    pub fn set_4bpp(&mut self) {
        self.value |= Self::PALETTE_4BPP;
    }

    pub fn set_8bpp(&mut self) {
        /* NOP */
    }
}

struct PixelMetadata {}
<|endoftext|>


<commit_before>//! Generates descriptors structure for unstable feature from Unstable Book
use std::path::{Path, PathBuf};

use quote::quote;
use walkdir::WalkDir;
use xshell::{cmd, read_file};

use crate::codegen::{project_root, reformat, update, Mode, Result};

pub fn generate_features(mode: Mode) -> Result<()> {
    if !Path::new("./target/rust").exists() {
        cmd!("git clone https://github.com/rust-lang/rust ./target/rust").run()?;
    }

    let contents = generate_descriptor("./target/rust/src/doc/unstable-book/src".into())?;

    let destination = project_root().join("crates/ide/src/completion/generated_features.rs");
    update(destination.as_path(), &contents, mode)?;

    Ok(())
}

fn generate_descriptor(src_dir: PathBuf) -> Result<String> {
    let definitions = ["language-features", "library-features"]
        .iter()
        .flat_map(|it| WalkDir::new(src_dir.join(it)))
        .filter_map(|e| e.ok())
        .filter(|entry| {
            // Get all `.md ` files
            entry.file_type().is_file() && entry.path().extension().unwrap_or_default() == "md"
        })
        .map(|entry| {
            let path = entry.path();
            let feature_ident = path.file_stem().unwrap().to_str().unwrap().replace("-", "_");
            let doc = read_file(path).unwrap();

            quote! { LintCompletion { label: #feature_ident, description: #doc } }
        });

    let ts = quote! {
        use crate::completion::complete_attribute::LintCompletion;

        pub(super) const FEATURES:  &[LintCompletion] = &[
            #(#definitions),*
        ];
    };
    reformat(&ts.to_string())
}
<commit_msg>Remove dead gen_features code<commit_after><|endoftext|>


<commit_before>// rustfmt-normalize_comments: true
// Closures

fn main() {
    let square = (|i: i32| i * i);

    let commented = |// first
                     a, // argument
                     // second
                     b: WithType, // argument
                     // ignored
                     _| {
        (
            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
            bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,
        )
    };

    let block_body = move |xxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
                           ref yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy| {
        xxxxxxxxxxxxxxxxxxxxxxxxxxxxx + yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
    };

    let loooooooooooooong_name = |field| {
        // format comments.
        if field.node.attrs.len() > 0 {
            field.node.attrs[0].span.lo()
        } else {
            field.span.lo()
        }
    };

    let unblock_me = |trivial| closure();

    let empty = |arg| {};

    let simple = |arg| {
        // comment formatting
        foo(arg)
    };

    let test = || {
        do_something();
        do_something_else();
    };

    let arg_test =
        |big_argument_name, test123| looooooooooooooooooong_function_naaaaaaaaaaaaaaaaame();

    let arg_test =
        |big_argument_name, test123| looooooooooooooooooong_function_naaaaaaaaaaaaaaaaame();

    let simple_closure = move || -> () {};

    let closure = |input: Ty| -> Option<String> { foo() };

    let closure_with_return_type =
        |aaaaaaaaaaaaaaaaaaaaaaarg1, aaaaaaaaaaaaaaaaaaaaaaarg2| -> Strong { "sup".to_owned() };

    |arg1, arg2, _, _, arg3, arg4| {
        let temp = arg4 + arg3;
        arg2 * arg1 - temp
    };

    let block_body_with_comment = args.iter().map(|a| {
        // Emitting only dep-info is possible only for final crate type, as
        // as others may emit required metadata for dependent crate types
        if a.starts_with("--emit") && is_final_crate_type && !self.workspace_mode {
            "--emit=dep-info"
        } else {
            a
        }
    });
}

fn issue311() {
    let func = |x| println!("{}", x);

    (func)(0.0);
}

fn issue863() {
    let closure = |x| match x {
        0 => true,
        _ => false,
    } == true;
}

fn issue934() {
    let hash: &Fn(&&Block) -> u64 = &|block| -> u64 {
        let mut h = SpanlessHash::new(cx);
        h.hash_block(block);
        h.finish()
    };

    let hash: &Fn(&&Block) -> u64 = &|block| -> u64 {
        let mut h = SpanlessHash::new(cx);
        h.hash_block(block);
        h.finish();
    };
}

impl<'a, 'tcx: 'a> SpanlessEq<'a, 'tcx> {
    pub fn eq_expr(&self, left: &Expr, right: &Expr) -> bool {
        match (&left.node, &right.node) {
            (&ExprBinary(l_op, ref ll, ref lr), &ExprBinary(r_op, ref rl, ref rr)) => {
                l_op.node == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
                    || swap_binop(l_op.node, ll, lr).map_or(false, |(l_op, ll, lr)| {
                        l_op == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
                    })
            }
        }
    }
}

fn foo() {
    lifetimes_iter___map(|lasdfasfd| {
        let hi = if l.bounds.is_empty() {
            l.lifetime.span.hi()
        };
    });
}

fn issue1405() {
    open_raw_fd(fd, b'r').and_then(|file| {
        Capture::new_raw(None, |_, err| unsafe { raw::pcap_fopen_offline(file, err) })
    });
}

fn issue1466() {
    let vertex_buffer = frame.scope(|ctx| {
        let buffer = ctx.create_host_visible_buffer::<VertexBuffer<Vertex>>(&vertices);
        ctx.create_device_local_buffer(buffer)
    });
}

fn issue470() {
    {
        {
            {
                let explicit_arg_decls = explicit_arguments.into_iter().enumerate().map(
                    |(index, (ty, pattern))| {
                        let lvalue = Lvalue::Arg(index as u32);
                        block = this.pattern(
                            block,
                            argument_extent,
                            hair::PatternRef::Hair(pattern),
                            &lvalue,
                        );
                        ArgDecl { ty: ty }
                    },
                );
            }
        }
    }
}

// #1509
impl Foo {
    pub fn bar(&self) {
        Some(SomeType {
            push_closure_out_to_100_chars: iter(otherwise_it_works_ok.into_iter().map(|f| Ok(f))),
        })
    }
}

fn issue1329() {
    aaaaaaaaaaaaaaaa
        .map(|x| {
            x += 1;
            x
        })
        .filter
}

fn issue325() {
    let f =
        || unsafe { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx };
}

fn issue1697() {
    Test.func_a(
        A_VERY_LONG_CONST_VARIABLE_NAME,
        move |arg1, arg2, arg3, arg4| arg1 + arg2 + arg3 + arg4,
    )
}

fn issue1694() {
    foooooo(
        |_referencefffffffff: _, _target_reference: _, _oid: _, _target_oid: _| {
            format!("refs/pull/{}/merge", pr_id)
        },
    )
}

fn issue1713() {
    rayon::join(
        || recurse(left, is_less, pred, limit),
        || recurse(right, is_less, Some(pivot), limit),
    );

    rayon::join(
        1,
        || recurse(left, is_less, pred, limit),
        2,
        || recurse(right, is_less, Some(pivot), limit),
    );
}

fn issue2063() {
    |ctx: Ctx<(String, String)>| -> io::Result<Response> {
        Ok(Response::new().with_body(ctx.params.0))
    }
}

fn issue1524() {
    let f = |x| x;
    let f = |x| x;
    let f = |x| x;
    let f = |x| x;
    let f = |x| x;
}

fn issue2171() {
    foo(|| unsafe {
        if PERIPHERALS {
            loop {}
        } else {
            PERIPHERALS = true;
        }
    })
}

fn issue2207() {
    a.map(|_| {
        unsafe { a_very_very_very_very_very_very_very_long_function_name_or_anything_else() }
            .to_string()
    })
}
<commit_msg>Update tests<commit_after>// rustfmt-normalize_comments: true
// Closures

fn main() {
    let square = (|i: i32| i * i);

    let commented = |// first
                     a, // argument
                     // second
                     b: WithType, // argument
                     // ignored
                     _| {
        (
            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
            bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,
        )
    };

    let block_body = move |xxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
                           ref yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy| {
        xxxxxxxxxxxxxxxxxxxxxxxxxxxxx + yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy
    };

    let loooooooooooooong_name = |field| {
        // format comments.
        if field.node.attrs.len() > 0 {
            field.node.attrs[0].span.lo()
        } else {
            field.span.lo()
        }
    };

    let unblock_me = |trivial| closure();

    let empty = |arg| {};

    let simple = |arg| {
        // comment formatting
        foo(arg)
    };

    let test = || {
        do_something();
        do_something_else();
    };

    let arg_test =
        |big_argument_name, test123| looooooooooooooooooong_function_naaaaaaaaaaaaaaaaame();

    let arg_test =
        |big_argument_name, test123| looooooooooooooooooong_function_naaaaaaaaaaaaaaaaame();

    let simple_closure = move || -> () {};

    let closure = |input: Ty| -> Option<String> { foo() };

    let closure_with_return_type =
        |aaaaaaaaaaaaaaaaaaaaaaarg1, aaaaaaaaaaaaaaaaaaaaaaarg2| -> Strong { "sup".to_owned() };

    |arg1, arg2, _, _, arg3, arg4| {
        let temp = arg4 + arg3;
        arg2 * arg1 - temp
    };

    let block_body_with_comment = args.iter().map(|a| {
        // Emitting only dep-info is possible only for final crate type, as
        // as others may emit required metadata for dependent crate types
        if a.starts_with("--emit") && is_final_crate_type && !self.workspace_mode {
            "--emit=dep-info"
        } else {
            a
        }
    });
}

fn issue311() {
    let func = |x| println!("{}", x);

    (func)(0.0);
}

fn issue863() {
    let closure = |x| match x {
        0 => true,
        _ => false,
    } == true;
}

fn issue934() {
    let hash: &Fn(&&Block) -> u64 = &|block| -> u64 {
        let mut h = SpanlessHash::new(cx);
        h.hash_block(block);
        h.finish()
    };

    let hash: &Fn(&&Block) -> u64 = &|block| -> u64 {
        let mut h = SpanlessHash::new(cx);
        h.hash_block(block);
        h.finish();
    };
}

impl<'a, 'tcx: 'a> SpanlessEq<'a, 'tcx> {
    pub fn eq_expr(&self, left: &Expr, right: &Expr) -> bool {
        match (&left.node, &right.node) {
            (&ExprBinary(l_op, ref ll, ref lr), &ExprBinary(r_op, ref rl, ref rr)) => {
                l_op.node == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
                    || swap_binop(l_op.node, ll, lr).map_or(false, |(l_op, ll, lr)| {
                        l_op == r_op.node && self.eq_expr(ll, rl) && self.eq_expr(lr, rr)
                    })
            }
        }
    }
}

fn foo() {
    lifetimes_iter___map(|lasdfasfd| {
        let hi = if l.bounds.is_empty() {
            l.lifetime.span.hi()
        };
    });
}

fn issue1405() {
    open_raw_fd(fd, b'r').and_then(|file| {
        Capture::new_raw(None, |_, err| unsafe {
            raw::pcap_fopen_offline(file, err)
        })
    });
}

fn issue1466() {
    let vertex_buffer = frame.scope(|ctx| {
        let buffer = ctx.create_host_visible_buffer::<VertexBuffer<Vertex>>(&vertices);
        ctx.create_device_local_buffer(buffer)
    });
}

fn issue470() {
    {
        {
            {
                let explicit_arg_decls = explicit_arguments.into_iter().enumerate().map(
                    |(index, (ty, pattern))| {
                        let lvalue = Lvalue::Arg(index as u32);
                        block = this.pattern(
                            block,
                            argument_extent,
                            hair::PatternRef::Hair(pattern),
                            &lvalue,
                        );
                        ArgDecl { ty: ty }
                    },
                );
            }
        }
    }
}

// #1509
impl Foo {
    pub fn bar(&self) {
        Some(SomeType {
            push_closure_out_to_100_chars: iter(otherwise_it_works_ok.into_iter().map(|f| Ok(f))),
        })
    }
}

fn issue1329() {
    aaaaaaaaaaaaaaaa
        .map(|x| {
            x += 1;
            x
        })
        .filter
}

fn issue325() {
    let f = || unsafe {
        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    };
}

fn issue1697() {
    Test.func_a(
        A_VERY_LONG_CONST_VARIABLE_NAME,
        move |arg1, arg2, arg3, arg4| arg1 + arg2 + arg3 + arg4,
    )
}

fn issue1694() {
    foooooo(
        |_referencefffffffff: _, _target_reference: _, _oid: _, _target_oid: _| {
            format!("refs/pull/{}/merge", pr_id)
        },
    )
}

fn issue1713() {
    rayon::join(
        || recurse(left, is_less, pred, limit),
        || recurse(right, is_less, Some(pivot), limit),
    );

    rayon::join(
        1,
        || recurse(left, is_less, pred, limit),
        2,
        || recurse(right, is_less, Some(pivot), limit),
    );
}

fn issue2063() {
    |ctx: Ctx<(String, String)>| -> io::Result<Response> {
        Ok(Response::new().with_body(ctx.params.0))
    }
}

fn issue1524() {
    let f = |x| x;
    let f = |x| x;
    let f = |x| x;
    let f = |x| x;
    let f = |x| x;
}

fn issue2171() {
    foo(|| unsafe {
        if PERIPHERALS {
            loop {}
        } else {
            PERIPHERALS = true;
        }
    })
}

fn issue2207() {
    a.map(|_| {
        unsafe { a_very_very_very_very_very_very_very_long_function_name_or_anything_else() }
            .to_string()
    })
}
<|endoftext|>


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

// spell-checker:ignore (ToDO) MAKEWORD addrs hashset

#[macro_use]
extern crate uucore;

use clap::{crate_version, App, Arg, ArgMatches};
use std::collections::hash_set::HashSet;
use std::net::ToSocketAddrs;
use std::str;

#[cfg(windows)]
use winapi::shared::minwindef::MAKEWORD;
#[cfg(windows)]
use winapi::um::winsock2::{WSACleanup, WSAStartup};

static ABOUT: &str = "Display or set the system's host name.";

static OPT_DOMAIN: &str = "domain";
static OPT_IP_ADDRESS: &str = "ip-address";
static OPT_FQDN: &str = "fqdn";
static OPT_SHORT: &str = "short";
static OPT_HOST: &str = "host";

pub fn uumain(args: impl uucore::Args) -> i32 {
    #![allow(clippy::let_and_return)]
    #[cfg(windows)]
    unsafe {
        #[allow(deprecated)]
        let mut data = std::mem::uninitialized();
        if WSAStartup(MAKEWORD(2, 2), &mut data as *mut _) != 0 {
            eprintln!("Failed to start Winsock 2.2");
            return 1;
        }
    }
    let result = execute(args);
    #[cfg(windows)]
    unsafe {
        WSACleanup();
    }
    result
}

fn get_usage() -> String {
    format!("{0} [OPTION]... [HOSTNAME]", executable!())
}
fn execute(args: impl uucore::Args) -> i32 {
    let usage = get_usage();
    let matches = uu_app().usage(&usage[..]).get_matches_from(args);

    match matches.value_of(OPT_HOST) {
        None => display_hostname(&matches),
        Some(host) => {
            if let Err(err) = hostname::set(host) {
                show_error!("{}", err);
                1
            } else {
                0
            }
        }
    }
}

pub fn uu_app() -> App<'static, 'static> {
    App::new(executable!())
        .version(crate_version!())
        .about(ABOUT)
        .arg(
            Arg::with_name(OPT_DOMAIN)
                .short("d")
                .long("domain")
                .help("Display the name of the DNS domain if possible"),
        )
        .arg(
            Arg::with_name(OPT_IP_ADDRESS)
                .short("i")
                .long("ip-address")
                .help("Display the network address(es) of the host"),
        )
        // TODO: support --long
        .arg(
            Arg::with_name(OPT_FQDN)
                .short("f")
                .long("fqdn")
                .help("Display the FQDN (Fully Qualified Domain Name) (default)"),
        )
        .arg(Arg::with_name(OPT_SHORT).short("s").long("short").help(
            "Display the short hostname (the portion before the first dot) if \
             possible",
        ))
        .arg(Arg::with_name(OPT_HOST))
}

fn display_hostname(matches: &ArgMatches) -> i32 {
    let hostname = hostname::get().unwrap().into_string().unwrap();

    if matches.is_present(OPT_IP_ADDRESS) {
        // XXX: to_socket_addrs needs hostname:port so append a dummy port and remove it later.
        // This was originally supposed to use std::net::lookup_host, but that seems to be
        // deprecated.  Perhaps we should use the dns-lookup crate?
        let hostname = hostname + ":1";
        match hostname.to_socket_addrs() {
            Ok(addresses) => {
                let mut hashset = HashSet::new();
                let mut output = String::new();
                for addr in addresses {
                    // XXX: not sure why this is necessary...
                    if !hashset.contains(&addr) {
                        let mut ip = format!("{}", addr);
                        if ip.ends_with(":1") {
                            let len = ip.len();
                            ip.truncate(len - 2);
                        }
                        output.push_str(&ip);
                        output.push(' ');
                        hashset.insert(addr);
                    }
                }
                let len = output.len();
                if len > 0 {
                    println!("{}", &output[0..len - 1]);
                }

                0
            }
            Err(f) => {
                show_error!("{}", f);

                1
            }
        }
    } else {
        if matches.is_present(OPT_SHORT) || matches.is_present(OPT_DOMAIN) {
            let mut it = hostname.char_indices().filter(|&ci| ci.1 == '.');
            if let Some(ci) = it.next() {
                if matches.is_present(OPT_SHORT) {
                    println!("{}", &hostname[0..ci.0]);
                } else {
                    println!("{}", &hostname[ci.0 + 1..]);
                }
                return 0;
            }
        }

        println!("{}", hostname);

        0
    }
}
<commit_msg>Added UResult for hostname<commit_after>//  * This file is part of the uutils coreutils package.
//  *
//  * (c) Alan Andrade <alan.andradec@gmail.com>
//  *
//  * For the full copyright and license information, please view the LICENSE
//  * file that was distributed with this source code.

// spell-checker:ignore (ToDO) MAKEWORD addrs hashset

#[macro_use]
extern crate uucore;

use clap::{crate_version, App, Arg, ArgMatches};
use std::collections::hash_set::HashSet;
use std::net::ToSocketAddrs;
use std::str;
use uucore::error::{UResult, USimpleError};

#[cfg(windows)]
use winapi::shared::minwindef::MAKEWORD;
#[cfg(windows)]
use winapi::um::winsock2::{WSACleanup, WSAStartup};

static ABOUT: &str = "Display or set the system's host name.";

static OPT_DOMAIN: &str = "domain";
static OPT_IP_ADDRESS: &str = "ip-address";
static OPT_FQDN: &str = "fqdn";
static OPT_SHORT: &str = "short";
static OPT_HOST: &str = "host";

#[uucore_procs::gen_uumain]
pub fn uumain(args: impl uucore::Args) -> UResult<()> {
    #![allow(clippy::let_and_return)]
    #[cfg(windows)]
    unsafe {
        #[allow(deprecated)]
        let mut data = std::mem::uninitialized();
        if WSAStartup(MAKEWORD(2, 2), &mut data as *mut _) != 0 {
            return Err(USimpleError::new(1, format!("Failed to start Winsock 2.2")));
        }
    }
    let result = execute(args);
    #[cfg(windows)]
    unsafe {
        WSACleanup();
    }
    result
}

fn get_usage() -> String {
    format!("{0} [OPTION]... [HOSTNAME]", executable!())
}
fn execute(args: impl uucore::Args) -> UResult<()> {
    let usage = get_usage();
    let matches = uu_app().usage(&usage[..]).get_matches_from(args);

    match matches.value_of(OPT_HOST) {
        None => display_hostname(&matches),
        Some(host) => {
            if let Err(err) = hostname::set(host) {
                return Err(USimpleError::new(1, format!("{}", err)));
            } else {
                Ok(())
            }
        }
    }
}

pub fn uu_app() -> App<'static, 'static> {
    App::new(executable!())
        .version(crate_version!())
        .about(ABOUT)
        .arg(
            Arg::with_name(OPT_DOMAIN)
                .short("d")
                .long("domain")
                .help("Display the name of the DNS domain if possible"),
        )
        .arg(
            Arg::with_name(OPT_IP_ADDRESS)
                .short("i")
                .long("ip-address")
                .help("Display the network address(es) of the host"),
        )
        // TODO: support --long
        .arg(
            Arg::with_name(OPT_FQDN)
                .short("f")
                .long("fqdn")
                .help("Display the FQDN (Fully Qualified Domain Name) (default)"),
        )
        .arg(Arg::with_name(OPT_SHORT).short("s").long("short").help(
            "Display the short hostname (the portion before the first dot) if \
             possible",
        ))
        .arg(Arg::with_name(OPT_HOST))
}

fn display_hostname(matches: &ArgMatches) -> UResult<()> {
    let hostname = hostname::get().unwrap().into_string().unwrap();

    if matches.is_present(OPT_IP_ADDRESS) {
        // XXX: to_socket_addrs needs hostname:port so append a dummy port and remove it later.
        // This was originally supposed to use std::net::lookup_host, but that seems to be
        // deprecated.  Perhaps we should use the dns-lookup crate?
        let hostname = hostname + ":1";
        match hostname.to_socket_addrs() {
            Ok(addresses) => {
                let mut hashset = HashSet::new();
                let mut output = String::new();
                for addr in addresses {
                    // XXX: not sure why this is necessary...
                    if !hashset.contains(&addr) {
                        let mut ip = format!("{}", addr);
                        if ip.ends_with(":1") {
                            let len = ip.len();
                            ip.truncate(len - 2);
                        }
                        output.push_str(&ip);
                        output.push(' ');
                        hashset.insert(addr);
                    }
                }
                let len = output.len();
                if len > 0 {
                    println!("{}", &output[0..len - 1]);
                }

                Ok(())
            }
            Err(f) => {
                return Err(USimpleError::new(1, format!("{}", f)));
            }
        }
    } else {
        if matches.is_present(OPT_SHORT) || matches.is_present(OPT_DOMAIN) {
            let mut it = hostname.char_indices().filter(|&ci| ci.1 == '.');
            if let Some(ci) = it.next() {
                if matches.is_present(OPT_SHORT) {
                    println!("{}", &hostname[0..ci.0]);
                } else {
                    println!("{}", &hostname[ci.0 + 1..]);
                }
                return Ok(());
            }
        }

        println!("{}", hostname);

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


<commit_before>//! Iota
//!
//! A highly customisable text editor built with modern hardware in mind.
//!
//! This module contains all you need to create an `iota` executable.

#![feature(unsafe_destructor)]
#![feature(collections)]
#![feature(unicode)]
#![feature(tempdir)]
#![feature(path)]
#![feature(fs)]
#![feature(io)]

#![warn(missing_docs)]

extern crate rustbox;
extern crate gapbuffer;

pub use editor::Editor;
pub use input::Input;
pub use frontends::RustboxFrontend;
pub use modes::{StandardMode, NormalMode, Mode};

mod input;
mod utils;
mod buffer;
mod editor;
mod keyboard;
mod keymap;
mod view;
mod uibuf;
mod log;
mod frontends;
mod modes;
mod overlay;
mod command;
mod textobject;
mod iterators;
<commit_msg>Remove unknown feature<commit_after>//! Iota
//!
//! A highly customisable text editor built with modern hardware in mind.
//!
//! This module contains all you need to create an `iota` executable.

#![feature(unsafe_destructor)]
#![feature(collections)]
#![feature(unicode)]
#![feature(tempdir)]
#![feature(path)]
#![feature(io)]

#![warn(missing_docs)]

extern crate rustbox;
extern crate gapbuffer;

pub use editor::Editor;
pub use input::Input;
pub use frontends::RustboxFrontend;
pub use modes::{StandardMode, NormalMode, Mode};

mod input;
mod utils;
mod buffer;
mod editor;
mod keyboard;
mod keymap;
mod view;
mod uibuf;
mod log;
mod frontends;
mod modes;
mod overlay;
mod command;
mod textobject;
mod iterators;
<|endoftext|>