<commit_before>use crate::types::{get_value_from_input_event, Msg};
use web_sys::HtmlInputElement;
use yew::prelude::*;

pub struct CommandLine {
    valid_entries: Vec<Entry>,
    // Among valid (filtered) entries.
    selected_command_index: usize,
    value: String,
}

#[derive(PartialEq, Clone, Properties, Debug)]
pub struct CommandLineProperties {
    pub value: String,
    pub entries: Vec<Entry>,
    pub enabled: bool,
    pub input_node_ref: NodeRef,
    #[prop_or_default]
    pub oninput: Callback<String>,
    #[prop_or_default]
    pub onselect: Callback<Msg>,
    #[prop_or_default]
    pub onenter: Callback<()>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct Entry {
    pub label: String,
    pub description: String,
    pub action: Msg,
    pub valid_classes: Vec<String>,
}

#[derive(Debug)]
pub enum CommandLineMsg {
    Click,
    Key(KeyboardEvent),
    Input(String),
}

impl Component for CommandLine {
    type Message = CommandLineMsg;
    type Properties = CommandLineProperties;

    fn create(ctx: &Context<Self>) -> Self {
        Self {
            valid_entries: ctx.props().entries.clone(),
            selected_command_index: 0,
            value: ctx.props().value.clone(),
        }
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        let props = ctx.props();
        let value = &self.value;
        let enabled = props.enabled;
        let valid_entries = &self.valid_entries;
        let selected_entry = valid_entries.get(self.selected_command_index);
        let selected_entry_suffix = selected_entry
            .cloned()
            .map(|v| v.label.clone())
            .unwrap_or_default()
            .strip_prefix(value)
            .map(|v| v.to_string())
            .unwrap_or_default();
        let selected = true;
        // TODO: Fuzzy search.
        let entries: Vec<_> = if selected {
            valid_entries
                .iter()
                .enumerate()
                .map(|(i, v)| {
                    let value_string = v.label.clone();
                    let value_suffix = value_string.strip_prefix(value).unwrap_or_default();

                    // let node = v.to_node();
                    let action = v.action.clone();
                    let onselect = props.onselect.clone();
                    let onclick = Callback::from(move |_e: MouseEvent| {
                        onselect.emit(action.clone());
                    });
                    let mut classes_item = vec!["block", "border"];
                    if i == self.selected_command_index {
                        classes_item.push("selected");
                    }
                    // Avoid re-selecting the node, we want to move to next.
                    html! {

                          { value.clone() }
                          { value_suffix }

                    }
                })
                .collect()
        } else {
            vec![]
        };
        let classes_dropdown = vec!["absolute", "z-10", "bg-white"];
        // let id = view::command_input_id(&path);
        let style = if value.len() > 0 {
            format!("width: {}ch;", value.len())
        } else {
            "width: 0.1ch;".to_string()
        };
        let rows = value.split('\n').count();
        // XXX: Chrome inspector CSS color editor.
        let placeholder = "";
        let placeholder = if placeholder.is_empty() {
            None
        } else {
            Some(html! {

{ placeholder }

            })
        };
        let suffix = if selected {
            selected_entry_suffix
        } else {
            "".to_string()
        };
        let mut class = vec![
            "inline-flex",
            "w-full",
            "bg-transparent",
            "resize-none",
            "overflow-hidden",
        ];
        // let errors = vec![];
        // if !errors.is_empty() {
        //     class.push("error");
        // }

        // let editing = if model.mode == crate::types::Mode::Edit {
        let dropdown = if enabled && selected {
            html! {

                    { for entries }

            }
        } else {
            html! {}
        };
        let suffix = if enabled && selected {
            html! {
                { suffix }
            }
        } else {
            html! {}
        };
        let mut classes = if enabled && selected {
            match selected_entry {
                Some(entry) => entry.valid_classes.clone().join(" "),
                None => "".to_string(),
            }
        } else {
            "".to_string()
        };
        classes.push_str(" flex");

        let oninput = props.oninput.clone();
        let oninput = ctx.link().callback(move |e: InputEvent| {
            let v = get_value_from_input_event(e);
            oninput.emit(v.clone());
            CommandLineMsg::Input(v)
        });

        let onclick = ctx.link().callback(|_| CommandLineMsg::Click);
        let onfocus = ctx.link().callback(|_| CommandLineMsg::Click);
        let onkeydown = ctx
            .link()
            .callback(move |e: KeyboardEvent| CommandLineMsg::Key(e));

        html! {

                { for placeholder }

                        <textarea
                        rows={ format!("{}", rows) }
                        ref={ ctx.props().input_node_ref.clone() }
                        //   id={ id }
                        class={ class }
                        type="text"
                        oninput={ oninput }
                        onkeydown={ onkeydown }
                        //   onfocus={ onfocus }
                        value={ value.to_string() }
                        style={ style }
                        //   disabled={ model.mode != crate::types::Mode::Edit }
                        autocomplete="off"
                        >
                        </textarea>
                        { suffix }

                    { dropdown }

        }
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
            CommandLineMsg::Click => {
                let input_node = ctx.props().input_node_ref.clone();
                input_node
                    .cast::<HtmlInputElement>()
                    .unwrap()
                    .focus()
                    .unwrap();
                true
            }
            CommandLineMsg::Input(value) => {
                self.value = value.clone();
                self.valid_entries = ctx
                    .props()
                    .entries
                    .clone()
                    .into_iter()
                    .filter(|v| v.label.starts_with(&value))
                    .collect();
                true
            }
            CommandLineMsg::Key(e) => {
                let props = ctx.props();
                let entries = &self.valid_entries;
                let selected_command_index = self.selected_command_index;
                if e.shift_key() {
                    return false;
                }
                match e.key().as_ref() {
                    "ArrowUp" => {
                        if entries.len() > 0 {
                            self.selected_command_index = if selected_command_index > 0 {
                                selected_command_index - 1
                            } else {
                                entries.len() - 1
                            }
                        }
                    }
                    "ArrowDown" => {
                        if entries.len() > 0 {
                            self.selected_command_index =
                                if selected_command_index < entries.len() - 1 {
                                    selected_command_index + 1
                                } else {
                                    0
                                }
                        }
                    }
                    "Enter" => {
                        e.prevent_default();
                        let selected_entry = entries.get(selected_command_index).cloned();
                        if let Some(selected_entry) = selected_entry {
                            let action = selected_entry.action.clone();
                            props.onselect.emit(action);
                        } else {
                            props.onenter.emit(());
                        }
                    }
                    _ => {}
                };
                true
            }
        }
    }
}
<commit_msg>Fix command line bug<commit_after>use crate::types::{get_value_from_input_event, Msg};
use web_sys::HtmlInputElement;
use yew::prelude::*;

pub struct CommandLine {
    valid_entries: Vec<Entry>,
    // Among valid (filtered) entries.
    selected_command_index: usize,
    value: String,
}

#[derive(PartialEq, Clone, Properties, Debug)]
pub struct CommandLineProperties {
    pub value: String,
    pub entries: Vec<Entry>,
    pub enabled: bool,
    pub input_node_ref: NodeRef,
    #[prop_or_default]
    pub oninput: Callback<String>,
    #[prop_or_default]
    pub onselect: Callback<Msg>,
    #[prop_or_default]
    pub onenter: Callback<()>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct Entry {
    pub label: String,
    pub description: String,
    pub action: Msg,
    pub valid_classes: Vec<String>,
}

#[derive(Debug)]
pub enum CommandLineMsg {
    Click,
    Key(KeyboardEvent),
    Input(String),
}

impl Component for CommandLine {
    type Message = CommandLineMsg;
    type Properties = CommandLineProperties;

    fn create(ctx: &Context<Self>) -> Self {
        Self {
            valid_entries: ctx.props().entries.clone(),
            selected_command_index: 0,
            value: ctx.props().value.clone(),
        }
    }

    fn changed(&mut self, ctx: &Context<Self>) -> bool {
        self.valid_entries = ctx.props().entries.clone();
        self.value = ctx.props().value.clone();
        true
    }

    fn view(&self, ctx: &Context<Self>) -> Html {
        let props = ctx.props();
        let value = &self.value;
        let enabled = props.enabled;
        let valid_entries = &self.valid_entries;
        let selected_entry = valid_entries.get(self.selected_command_index);
        let selected_entry_suffix = selected_entry
            .cloned()
            .map(|v| v.label.clone())
            .unwrap_or_default()
            .strip_prefix(value)
            .map(|v| v.to_string())
            .unwrap_or_default();
        let selected = true;
        // TODO: Fuzzy search.
        let entries: Vec<_> = if selected {
            valid_entries
                .iter()
                .enumerate()
                .map(|(i, v)| {
                    let value_string = v.label.clone();
                    let value_suffix = value_string.strip_prefix(value).unwrap_or_default();

                    // let node = v.to_node();
                    let action = v.action.clone();
                    let onselect = props.onselect.clone();
                    let onclick = Callback::from(move |_e: MouseEvent| {
                        onselect.emit(action.clone());
                    });
                    let mut classes_item = vec!["block", "border"];
                    if i == self.selected_command_index {
                        classes_item.push("selected");
                    }
                    // Avoid re-selecting the node, we want to move to next.
                    html! {

                          { value.clone() }
                          { value_suffix }

                    }
                })
                .collect()
        } else {
            vec![]
        };
        let classes_dropdown = vec!["absolute", "z-10", "bg-white"];
        // let id = view::command_input_id(&path);
        let style = if value.len() > 0 {
            format!("width: {}ch;", value.len())
        } else {
            "width: 0.1ch;".to_string()
        };
        let rows = value.split('\n').count();
        // XXX: Chrome inspector CSS color editor.
        let placeholder = "";
        let placeholder = if placeholder.is_empty() {
            None
        } else {
            Some(html! {

{ placeholder }

            })
        };
        let suffix = if selected {
            selected_entry_suffix
        } else {
            "".to_string()
        };
        let mut class = vec![
            "inline-flex",
            "w-full",
            "bg-transparent",
            "resize-none",
            "overflow-hidden",
        ];
        // let errors = vec![];
        // if !errors.is_empty() {
        //     class.push("error");
        // }

        // let editing = if model.mode == crate::types::Mode::Edit {
        let dropdown = if enabled && selected {
            html! {

                    { for entries }

            }
        } else {
            html! {}
        };
        let suffix = if enabled && selected {
            html! {
                { suffix }
            }
        } else {
            html! {}
        };
        let mut classes = if enabled && selected {
            match selected_entry {
                Some(entry) => entry.valid_classes.clone().join(" "),
                None => "".to_string(),
            }
        } else {
            "".to_string()
        };
        classes.push_str(" flex");

        let oninput = props.oninput.clone();
        let oninput = ctx.link().callback(move |e: InputEvent| {
            let v = get_value_from_input_event(e);
            oninput.emit(v.clone());
            CommandLineMsg::Input(v)
        });

        let onclick = ctx.link().callback(|_| CommandLineMsg::Click);
        let onfocus = ctx.link().callback(|_| CommandLineMsg::Click);
        let onkeydown = ctx
            .link()
            .callback(move |e: KeyboardEvent| CommandLineMsg::Key(e));

        html! {

                { for placeholder }

                        <textarea
                        rows={ format!("{}", rows) }
                        ref={ ctx.props().input_node_ref.clone() }
                        //   id={ id }
                        class={ class }
                        type="text"
                        oninput={ oninput }
                        onkeydown={ onkeydown }
                        //   onfocus={ onfocus }
                        value={ value.to_string() }
                        style={ style }
                        //   disabled={ model.mode != crate::types::Mode::Edit }
                        autocomplete="off"
                        >
                        </textarea>
                        { suffix }

                    { dropdown }

        }
    }

    fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
        match msg {
            CommandLineMsg::Click => {
                let input_node = ctx.props().input_node_ref.clone();
                input_node
                    .cast::<HtmlInputElement>()
                    .unwrap()
                    .focus()
                    .unwrap();
                true
            }
            CommandLineMsg::Input(value) => {
                self.value = value.clone();
                self.valid_entries = ctx
                    .props()
                    .entries
                    .clone()
                    .into_iter()
                    .filter(|v| v.label.starts_with(&value))
                    .collect();
                true
            }
            CommandLineMsg::Key(e) => {
                let props = ctx.props();
                let entries = &self.valid_entries;
                let selected_command_index = self.selected_command_index;
                if e.shift_key() {
                    return false;
                }
                match e.key().as_ref() {
                    "ArrowUp" => {
                        if entries.len() > 0 {
                            self.selected_command_index = if selected_command_index > 0 {
                                selected_command_index - 1
                            } else {
                                entries.len() - 1
                            }
                        }
                    }
                    "ArrowDown" => {
                        if entries.len() > 0 {
                            self.selected_command_index =
                                if selected_command_index < entries.len() - 1 {
                                    selected_command_index + 1
                                } else {
                                    0
                                }
                        }
                    }
                    "Enter" => {
                        e.prevent_default();
                        let selected_entry = entries.get(selected_command_index).cloned();
                        if let Some(selected_entry) = selected_entry {
                            let action = selected_entry.action.clone();
                            props.onselect.emit(action);
                        } else {
                            props.onenter.emit(());
                        }
                    }
                    _ => {}
                };
                true
            }
        }
    }
}
<|endoftext|>


<commit_before>use std::collections::hash_map;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::default::Default;
use std::hash::Hash;
use std::hash::Hasher;
use std::slice;

use crate::clear::Clear;

use crate::reflect::ReflectValueRef;
use crate::rt;
use crate::wire_format;
use crate::zigzag::encode_zig_zag_32;
use crate::zigzag::encode_zig_zag_64;
use crate::CodedOutputStream;

/// Unknown value.
///
/// See [`UnknownFields`](crate::UnknownFields) for the explanations.
#[derive(Debug)]
pub enum UnknownValue {
    /// 32-bit unknown (e. g. `fixed32` or `float`)
    Fixed32(u32),
    /// 64-bit unknown (e. g. `fixed64` or `double`)
    Fixed64(u64),
    /// Varint unknown (e. g. `int32` or `bool`)
    Varint(u64),
    /// Length-delimited unknown (e. g. `message` or `string`)
    LengthDelimited(Vec<u8>),
}

impl UnknownValue {
    /// Wire type for this unknown
    pub fn wire_type(&self) -> wire_format::WireType {
        self.get_ref().wire_type()
    }

    /// As ref
    pub fn get_ref<'s>(&'s self) -> UnknownValueRef<'s> {
        match *self {
            UnknownValue::Fixed32(fixed32) => UnknownValueRef::Fixed32(fixed32),
            UnknownValue::Fixed64(fixed64) => UnknownValueRef::Fixed64(fixed64),
            UnknownValue::Varint(varint) => UnknownValueRef::Varint(varint),
            UnknownValue::LengthDelimited(ref bytes) => UnknownValueRef::LengthDelimited(&bytes),
        }
    }

    /// Construct unknown value from `int64` value.
    pub fn int32(i: i32) -> UnknownValue {
        UnknownValue::int64(i as i64)
    }

    /// Construct unknown value from `int64` value.
    pub fn int64(i: i64) -> UnknownValue {
        UnknownValue::Varint(i as u64)
    }

    /// Construct unknown value from `sint32` value.
    pub fn sint32(i: i32) -> UnknownValue {
        UnknownValue::Varint(encode_zig_zag_32(i) as u64)
    }

    /// Construct unknown value from `sint64` value.
    pub fn sint64(i: i64) -> UnknownValue {
        UnknownValue::Varint(encode_zig_zag_64(i))
    }

    /// Construct unknown value from `float` value.
    pub fn float(f: f32) -> UnknownValue {
        UnknownValue::Fixed32(f.to_bits())
    }

    /// Construct unknown value from `double` value.
    pub fn double(f: f64) -> UnknownValue {
        UnknownValue::Fixed64(f.to_bits())
    }

    /// Construct unknown value from `sfixed32` value.
    pub fn sfixed32(i: i32) -> UnknownValue {
        UnknownValue::Fixed32(i as u32)
    }

    /// Construct unknown value from `sfixed64` value.
    pub fn sfixed64(i: i64) -> UnknownValue {
        UnknownValue::Fixed64(i as u64)
    }
}

/// Reference to unknown value.
///
/// See [`UnknownFields`](crate::UnknownFields) for explanations.
pub enum UnknownValueRef<'o> {
    /// 32-bit unknown
    Fixed32(u32),
    /// 64-bit unknown
    Fixed64(u64),
    /// Varint unknown
    Varint(u64),
    /// Length-delimited unknown
    LengthDelimited(&'o [u8]),
}

impl<'o> UnknownValueRef<'o> {
    /// Wire-type to serialize this unknown
    pub fn wire_type(&self) -> wire_format::WireType {
        match *self {
            UnknownValueRef::Fixed32(_) => wire_format::WireTypeFixed32,
            UnknownValueRef::Fixed64(_) => wire_format::WireTypeFixed64,
            UnknownValueRef::Varint(_) => wire_format::WireTypeVarint,
            UnknownValueRef::LengthDelimited(_) => wire_format::WireTypeLengthDelimited,
        }
    }

    pub(crate) fn to_reflect_value_ref(&'o self) -> ReflectValueRef<'o> {
        match self {
            UnknownValueRef::Fixed32(v) => ReflectValueRef::U32(*v),
            UnknownValueRef::Fixed64(v) => ReflectValueRef::U64(*v),
            UnknownValueRef::Varint(v) => ReflectValueRef::U64(*v),
            UnknownValueRef::LengthDelimited(v) => ReflectValueRef::Bytes(v),
        }
    }
}

/// Field unknown values.
///
/// See [`UnknownFields`](crate::UnknownFields) for explanations.
#[derive(Clone, PartialEq, Eq, Debug, Default, Hash)]
pub struct UnknownValues {
    /// 32-bit unknowns
    pub fixed32: Vec<u32>,
    /// 64-bit unknowns
    pub fixed64: Vec<u64>,
    /// Varint unknowns
    pub varint: Vec<u64>,
    /// Length-delimited unknowns
    pub length_delimited: Vec<Vec<u8>>,
}

impl UnknownValues {
    /// Add unknown value
    pub fn add_value(&mut self, value: UnknownValue) {
        match value {
            UnknownValue::Fixed64(fixed64) => self.fixed64.push(fixed64),
            UnknownValue::Fixed32(fixed32) => self.fixed32.push(fixed32),
            UnknownValue::Varint(varint) => self.varint.push(varint),
            UnknownValue::LengthDelimited(length_delimited) => {
                self.length_delimited.push(length_delimited)
            }
        };
    }

    /// Iterate over unknown values
    pub fn iter<'s>(&'s self) -> UnknownValuesIter<'s> {
        UnknownValuesIter {
            fixed32: self.fixed32.iter(),
            fixed64: self.fixed64.iter(),
            varint: self.varint.iter(),
            length_delimited: self.length_delimited.iter(),
        }
    }
}

impl<'a> IntoIterator for &'a UnknownValues {
    type Item = UnknownValueRef<'a>;
    type IntoIter = UnknownValuesIter<'a>;

    fn into_iter(self) -> UnknownValuesIter<'a> {
        self.iter()
    }
}

/// Iterator over unknown values
pub struct UnknownValuesIter<'o> {
    fixed32: slice::Iter<'o, u32>,
    fixed64: slice::Iter<'o, u64>,
    varint: slice::Iter<'o, u64>,
    length_delimited: slice::Iter<'o, Vec<u8>>,
}

impl<'o> Iterator for UnknownValuesIter<'o> {
    type Item = UnknownValueRef<'o>;

    fn next(&mut self) -> Option<UnknownValueRef<'o>> {
        let fixed32 = self.fixed32.next();
        if fixed32.is_some() {
            return Some(UnknownValueRef::Fixed32(*fixed32.unwrap()));
        }
        let fixed64 = self.fixed64.next();
        if fixed64.is_some() {
            return Some(UnknownValueRef::Fixed64(*fixed64.unwrap()));
        }
        let varint = self.varint.next();
        if varint.is_some() {
            return Some(UnknownValueRef::Varint(*varint.unwrap()));
        }
        let length_delimited = self.length_delimited.next();
        if length_delimited.is_some() {
            return Some(UnknownValueRef::LengthDelimited(&length_delimited.unwrap()));
        }
        None
    }
}

/// Hold "unknown" fields in parsed message.
///
/// Field may be unknown if it they are added in newer version of `.proto`.
/// Unknown fields are stored in `UnknownFields` structure, so
/// protobuf message could process messages without losing data.
///
/// For example, in this operation: load from DB, modify, store to DB,
/// even when working with older `.proto` file, new fields won't be lost.
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub struct UnknownFields {
    /// The map.
    // option is needed, because HashMap constructor performs allocation,
    // and very expensive
    fields: Option<Box<HashMap<u32, UnknownValues>>>,
}

/// Very simple hash implementation of `Hash` for `UnknownFields`.
/// Since map is unordered, we cannot put entry hashes into hasher,
/// instead we summing hashes of entries.
impl Hash for UnknownFields {
    fn hash<H: Hasher>(&self, state: &mut H) {
        if let Some(ref map) = self.fields {
            if !map.is_empty() {
                let mut hash: u64 = 0;
                for (k, v) in &**map {
                    let mut entry_hasher = DefaultHasher::new();
                    Hash::hash(&(k, v), &mut entry_hasher);
                    hash = hash.wrapping_add(entry_hasher.finish());
                }
                Hash::hash(&map.len(), state);
                Hash::hash(&hash, state);
            }
        }
    }
}

impl UnknownFields {
    /// Empty unknown fields
    pub const fn new() -> UnknownFields {
        UnknownFields { fields: None }
    }

    fn init_map(&mut self) {
        if self.fields.is_none() {
            self.fields = Some(Default::default());
        }
    }

    fn find_field<'a>(&'a mut self, number: &'a u32) -> &'a mut UnknownValues {
        self.init_map();

        match self.fields.as_mut().unwrap().entry(*number) {
            hash_map::Entry::Occupied(e) => e.into_mut(),
            hash_map::Entry::Vacant(e) => e.insert(Default::default()),
        }
    }

    /// Add unknown fixed 32-bit
    pub fn add_fixed32(&mut self, number: u32, fixed32: u32) {
        self.find_field(&number).fixed32.push(fixed32);
    }

    /// Add unknown fixed 64-bit
    pub fn add_fixed64(&mut self, number: u32, fixed64: u64) {
        self.find_field(&number).fixed64.push(fixed64);
    }

    /// Add unknown varint
    pub fn add_varint(&mut self, number: u32, varint: u64) {
        self.find_field(&number).varint.push(varint);
    }

    /// Add unknown length delimited
    pub fn add_length_delimited(&mut self, number: u32, length_delimited: Vec<u8>) {
        self.find_field(&number)
            .length_delimited
            .push(length_delimited);
    }

    /// Add unknown value
    pub fn add_value(&mut self, number: u32, value: UnknownValue) {
        self.find_field(&number).add_value(value);
    }

    /// Remove unknown field by number
    pub fn remove(&mut self, field_number: u32) {
        if let Some(fields) = &mut self.fields {
            fields.remove(&field_number);
        }
    }

    /// Iterate over all unknowns
    pub fn iter<'s>(&'s self) -> UnknownFieldsIter<'s> {
        UnknownFieldsIter {
            entries: self.fields.as_ref().map(|m| m.iter()),
        }
    }

    /// Find unknown field by number
    pub fn get(&self, field_number: u32) -> Option<&UnknownValues> {
        match self.fields {
            Some(ref map) => map.get(&field_number),
            None => None,
        }
    }

    #[doc(hidden)]
    pub fn write_to_bytes(&self) -> Vec<u8> {
        let mut r = Vec::with_capacity(rt::unknown_fields_size(self) as usize);
        let mut stream = CodedOutputStream::vec(&mut r);
        // TODO: figure out how to make output stable
        stream.write_unknown_fields_sorted(self).unwrap();
        stream.flush().unwrap();
        drop(stream);
        r
    }
}

impl Clear for UnknownFields {
    fn clear(&mut self) {
        if let Some(ref mut fields) = self.fields {
            fields.clear();
        }
    }
}

impl<'a> IntoIterator for &'a UnknownFields {
    type Item = (u32, &'a UnknownValues);
    type IntoIter = UnknownFieldsIter<'a>;

    fn into_iter(self) -> UnknownFieldsIter<'a> {
        self.iter()
    }
}

/// Iterator over [`UnknownFields`](crate::UnknownFields)
pub struct UnknownFieldsIter<'s> {
    entries: Option<hash_map::Iter<'s, u32, UnknownValues>>,
}

impl<'s> Iterator for UnknownFieldsIter<'s> {
    type Item = (u32, &'s UnknownValues);

    fn next(&mut self) -> Option<(u32, &'s UnknownValues)> {
        match self.entries {
            Some(ref mut entries) => entries.next().map(|(&number, values)| (number, values)),
            None => None,
        }
    }
}

#[cfg(test)]
mod test {
    use super::UnknownFields;
    use std::collections::hash_map::DefaultHasher;
    use std::hash::Hash;
    use std::hash::Hasher;

    #[test]
    fn unknown_fields_hash() {
        let mut unknown_fields_1 = UnknownFields::new();
        let mut unknown_fields_2 = UnknownFields::new();

        // Check field order is not important

        unknown_fields_1.add_fixed32(10, 222);
        unknown_fields_1.add_fixed32(10, 223);
        unknown_fields_1.add_fixed64(14, 224);

        unknown_fields_2.add_fixed32(10, 222);
        unknown_fields_2.add_fixed64(14, 224);
        unknown_fields_2.add_fixed32(10, 223);

        fn hash(unknown_fields: &UnknownFields) -> u64 {
            let mut hasher = DefaultHasher::new();
            Hash::hash(unknown_fields, &mut hasher);
            hasher.finish()
        }

        assert_eq!(hash(&unknown_fields_1), hash(&unknown_fields_2));
    }
}
<commit_msg>Make protobuf codegen deterministic<commit_after>use std::collections::hash_map;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::default::Default;
use std::hash::BuildHasherDefault;
use std::hash::Hash;
use std::hash::Hasher;
use std::slice;

use crate::clear::Clear;

use crate::reflect::ReflectValueRef;
use crate::rt;
use crate::wire_format;
use crate::zigzag::encode_zig_zag_32;
use crate::zigzag::encode_zig_zag_64;
use crate::CodedOutputStream;

/// Unknown value.
///
/// See [`UnknownFields`](crate::UnknownFields) for the explanations.
#[derive(Debug)]
pub enum UnknownValue {
    /// 32-bit unknown (e. g. `fixed32` or `float`)
    Fixed32(u32),
    /// 64-bit unknown (e. g. `fixed64` or `double`)
    Fixed64(u64),
    /// Varint unknown (e. g. `int32` or `bool`)
    Varint(u64),
    /// Length-delimited unknown (e. g. `message` or `string`)
    LengthDelimited(Vec<u8>),
}

impl UnknownValue {
    /// Wire type for this unknown
    pub fn wire_type(&self) -> wire_format::WireType {
        self.get_ref().wire_type()
    }

    /// As ref
    pub fn get_ref<'s>(&'s self) -> UnknownValueRef<'s> {
        match *self {
            UnknownValue::Fixed32(fixed32) => UnknownValueRef::Fixed32(fixed32),
            UnknownValue::Fixed64(fixed64) => UnknownValueRef::Fixed64(fixed64),
            UnknownValue::Varint(varint) => UnknownValueRef::Varint(varint),
            UnknownValue::LengthDelimited(ref bytes) => UnknownValueRef::LengthDelimited(&bytes),
        }
    }

    /// Construct unknown value from `int64` value.
    pub fn int32(i: i32) -> UnknownValue {
        UnknownValue::int64(i as i64)
    }

    /// Construct unknown value from `int64` value.
    pub fn int64(i: i64) -> UnknownValue {
        UnknownValue::Varint(i as u64)
    }

    /// Construct unknown value from `sint32` value.
    pub fn sint32(i: i32) -> UnknownValue {
        UnknownValue::Varint(encode_zig_zag_32(i) as u64)
    }

    /// Construct unknown value from `sint64` value.
    pub fn sint64(i: i64) -> UnknownValue {
        UnknownValue::Varint(encode_zig_zag_64(i))
    }

    /// Construct unknown value from `float` value.
    pub fn float(f: f32) -> UnknownValue {
        UnknownValue::Fixed32(f.to_bits())
    }

    /// Construct unknown value from `double` value.
    pub fn double(f: f64) -> UnknownValue {
        UnknownValue::Fixed64(f.to_bits())
    }

    /// Construct unknown value from `sfixed32` value.
    pub fn sfixed32(i: i32) -> UnknownValue {
        UnknownValue::Fixed32(i as u32)
    }

    /// Construct unknown value from `sfixed64` value.
    pub fn sfixed64(i: i64) -> UnknownValue {
        UnknownValue::Fixed64(i as u64)
    }
}

/// Reference to unknown value.
///
/// See [`UnknownFields`](crate::UnknownFields) for explanations.
pub enum UnknownValueRef<'o> {
    /// 32-bit unknown
    Fixed32(u32),
    /// 64-bit unknown
    Fixed64(u64),
    /// Varint unknown
    Varint(u64),
    /// Length-delimited unknown
    LengthDelimited(&'o [u8]),
}

impl<'o> UnknownValueRef<'o> {
    /// Wire-type to serialize this unknown
    pub fn wire_type(&self) -> wire_format::WireType {
        match *self {
            UnknownValueRef::Fixed32(_) => wire_format::WireTypeFixed32,
            UnknownValueRef::Fixed64(_) => wire_format::WireTypeFixed64,
            UnknownValueRef::Varint(_) => wire_format::WireTypeVarint,
            UnknownValueRef::LengthDelimited(_) => wire_format::WireTypeLengthDelimited,
        }
    }

    pub(crate) fn to_reflect_value_ref(&'o self) -> ReflectValueRef<'o> {
        match self {
            UnknownValueRef::Fixed32(v) => ReflectValueRef::U32(*v),
            UnknownValueRef::Fixed64(v) => ReflectValueRef::U64(*v),
            UnknownValueRef::Varint(v) => ReflectValueRef::U64(*v),
            UnknownValueRef::LengthDelimited(v) => ReflectValueRef::Bytes(v),
        }
    }
}

/// Field unknown values.
///
/// See [`UnknownFields`](crate::UnknownFields) for explanations.
#[derive(Clone, PartialEq, Eq, Debug, Default, Hash)]
pub struct UnknownValues {
    /// 32-bit unknowns
    pub fixed32: Vec<u32>,
    /// 64-bit unknowns
    pub fixed64: Vec<u64>,
    /// Varint unknowns
    pub varint: Vec<u64>,
    /// Length-delimited unknowns
    pub length_delimited: Vec<Vec<u8>>,
}

impl UnknownValues {
    /// Add unknown value
    pub fn add_value(&mut self, value: UnknownValue) {
        match value {
            UnknownValue::Fixed64(fixed64) => self.fixed64.push(fixed64),
            UnknownValue::Fixed32(fixed32) => self.fixed32.push(fixed32),
            UnknownValue::Varint(varint) => self.varint.push(varint),
            UnknownValue::LengthDelimited(length_delimited) => {
                self.length_delimited.push(length_delimited)
            }
        };
    }

    /// Iterate over unknown values
    pub fn iter<'s>(&'s self) -> UnknownValuesIter<'s> {
        UnknownValuesIter {
            fixed32: self.fixed32.iter(),
            fixed64: self.fixed64.iter(),
            varint: self.varint.iter(),
            length_delimited: self.length_delimited.iter(),
        }
    }
}

impl<'a> IntoIterator for &'a UnknownValues {
    type Item = UnknownValueRef<'a>;
    type IntoIter = UnknownValuesIter<'a>;

    fn into_iter(self) -> UnknownValuesIter<'a> {
        self.iter()
    }
}

/// Iterator over unknown values
pub struct UnknownValuesIter<'o> {
    fixed32: slice::Iter<'o, u32>,
    fixed64: slice::Iter<'o, u64>,
    varint: slice::Iter<'o, u64>,
    length_delimited: slice::Iter<'o, Vec<u8>>,
}

impl<'o> Iterator for UnknownValuesIter<'o> {
    type Item = UnknownValueRef<'o>;

    fn next(&mut self) -> Option<UnknownValueRef<'o>> {
        let fixed32 = self.fixed32.next();
        if fixed32.is_some() {
            return Some(UnknownValueRef::Fixed32(*fixed32.unwrap()));
        }
        let fixed64 = self.fixed64.next();
        if fixed64.is_some() {
            return Some(UnknownValueRef::Fixed64(*fixed64.unwrap()));
        }
        let varint = self.varint.next();
        if varint.is_some() {
            return Some(UnknownValueRef::Varint(*varint.unwrap()));
        }
        let length_delimited = self.length_delimited.next();
        if length_delimited.is_some() {
            return Some(UnknownValueRef::LengthDelimited(&length_delimited.unwrap()));
        }
        None
    }
}

/// Hold "unknown" fields in parsed message.
///
/// Field may be unknown if it they are added in newer version of `.proto`.
/// Unknown fields are stored in `UnknownFields` structure, so
/// protobuf message could process messages without losing data.
///
/// For example, in this operation: load from DB, modify, store to DB,
/// even when working with older `.proto` file, new fields won't be lost.
#[derive(Clone, PartialEq, Eq, Debug, Default)]
pub struct UnknownFields {
    /// The map.
    //
    // `Option` is needed, because HashMap constructor performs allocation,
    // and very expensive.
    //
    // We use "default hasher" to make iteration order deterministic.
    // Which is used to make codegen output deterministic in presence of unknown fields
    // (e. g. file options are represented as unknown fields).
    // Using default hasher is suboptimal, because it makes unknown fields less safe.
    // Note, Google Protobuf C++ simply uses linear map (which can exploitable the same way),
    // and Google Protobuf Java uses tree map to store unknown fields
    // (which is more expensive than hashmap).
    fields: Option<Box<HashMap<u32, UnknownValues, BuildHasherDefault<DefaultHasher>>>>,
}

/// Very simple hash implementation of `Hash` for `UnknownFields`.
/// Since map is unordered, we cannot put entry hashes into hasher,
/// instead we summing hashes of entries.
impl Hash for UnknownFields {
    fn hash<H: Hasher>(&self, state: &mut H) {
        if let Some(ref map) = self.fields {
            if !map.is_empty() {
                let mut hash: u64 = 0;
                for (k, v) in &**map {
                    let mut entry_hasher = DefaultHasher::new();
                    Hash::hash(&(k, v), &mut entry_hasher);
                    hash = hash.wrapping_add(entry_hasher.finish());
                }
                Hash::hash(&map.len(), state);
                Hash::hash(&hash, state);
            }
        }
    }
}

impl UnknownFields {
    /// Empty unknown fields
    pub const fn new() -> UnknownFields {
        UnknownFields { fields: None }
    }

    fn init_map(&mut self) {
        if self.fields.is_none() {
            self.fields = Some(Default::default());
        }
    }

    fn find_field<'a>(&'a mut self, number: &'a u32) -> &'a mut UnknownValues {
        self.init_map();

        match self.fields.as_mut().unwrap().entry(*number) {
            hash_map::Entry::Occupied(e) => e.into_mut(),
            hash_map::Entry::Vacant(e) => e.insert(Default::default()),
        }
    }

    /// Add unknown fixed 32-bit
    pub fn add_fixed32(&mut self, number: u32, fixed32: u32) {
        self.find_field(&number).fixed32.push(fixed32);
    }

    /// Add unknown fixed 64-bit
    pub fn add_fixed64(&mut self, number: u32, fixed64: u64) {
        self.find_field(&number).fixed64.push(fixed64);
    }

    /// Add unknown varint
    pub fn add_varint(&mut self, number: u32, varint: u64) {
        self.find_field(&number).varint.push(varint);
    }

    /// Add unknown length delimited
    pub fn add_length_delimited(&mut self, number: u32, length_delimited: Vec<u8>) {
        self.find_field(&number)
            .length_delimited
            .push(length_delimited);
    }

    /// Add unknown value
    pub fn add_value(&mut self, number: u32, value: UnknownValue) {
        self.find_field(&number).add_value(value);
    }

    /// Remove unknown field by number
    pub fn remove(&mut self, field_number: u32) {
        if let Some(fields) = &mut self.fields {
            fields.remove(&field_number);
        }
    }

    /// Iterate over all unknowns
    pub fn iter<'s>(&'s self) -> UnknownFieldsIter<'s> {
        UnknownFieldsIter {
            entries: self.fields.as_ref().map(|m| m.iter()),
        }
    }

    /// Find unknown field by number
    pub fn get(&self, field_number: u32) -> Option<&UnknownValues> {
        match self.fields {
            Some(ref map) => map.get(&field_number),
            None => None,
        }
    }

    #[doc(hidden)]
    pub fn write_to_bytes(&self) -> Vec<u8> {
        let mut r = Vec::with_capacity(rt::unknown_fields_size(self) as usize);
        let mut stream = CodedOutputStream::vec(&mut r);
        // TODO: figure out how to make output stable
        stream.write_unknown_fields_sorted(self).unwrap();
        stream.flush().unwrap();
        drop(stream);
        r
    }
}

impl Clear for UnknownFields {
    fn clear(&mut self) {
        if let Some(ref mut fields) = self.fields {
            fields.clear();
        }
    }
}

impl<'a> IntoIterator for &'a UnknownFields {
    type Item = (u32, &'a UnknownValues);
    type IntoIter = UnknownFieldsIter<'a>;

    fn into_iter(self) -> UnknownFieldsIter<'a> {
        self.iter()
    }
}

/// Iterator over [`UnknownFields`](crate::UnknownFields)
pub struct UnknownFieldsIter<'s> {
    entries: Option<hash_map::Iter<'s, u32, UnknownValues>>,
}

impl<'s> Iterator for UnknownFieldsIter<'s> {
    type Item = (u32, &'s UnknownValues);

    fn next(&mut self) -> Option<(u32, &'s UnknownValues)> {
        match self.entries {
            Some(ref mut entries) => entries.next().map(|(&number, values)| (number, values)),
            None => None,
        }
    }
}

#[cfg(test)]
mod test {
    use super::UnknownFields;
    use std::collections::hash_map::DefaultHasher;
    use std::hash::Hash;
    use std::hash::Hasher;

    #[test]
    fn unknown_fields_hash() {
        let mut unknown_fields_1 = UnknownFields::new();
        let mut unknown_fields_2 = UnknownFields::new();

        // Check field order is not important

        unknown_fields_1.add_fixed32(10, 222);
        unknown_fields_1.add_fixed32(10, 223);
        unknown_fields_1.add_fixed64(14, 224);

        unknown_fields_2.add_fixed32(10, 222);
        unknown_fields_2.add_fixed64(14, 224);
        unknown_fields_2.add_fixed32(10, 223);

        fn hash(unknown_fields: &UnknownFields) -> u64 {
            let mut hasher = DefaultHasher::new();
            Hash::hash(unknown_fields, &mut hasher);
            hasher.finish()
        }

        assert_eq!(hash(&unknown_fields_1), hash(&unknown_fields_2));
    }

    #[test]
    fn unknown_fields_iteration_order_deterministic() {
        let mut u_1 = UnknownFields::new();
        let mut u_2 = UnknownFields::new();
        for u in [&mut u_1, &mut u_2] {
            u.add_fixed32(10, 20);
            u.add_varint(30, 40);
            u.add_fixed64(50, 60);
            u.add_length_delimited(70, Vec::new());
            u.add_varint(80, 90);
            u.add_fixed32(11, 22);
            u.add_fixed64(33, 44);
        }

        let items_1: Vec<_> = u_1.iter().collect();
        let items_2: Vec<_> = u_2.iter().collect();
        assert_eq!(items_1, items_2);
    }
}
<|endoftext|>


<commit_before>use super::rootservice::RootService;
use futures::{Future, Stream};
use hyper::{self, server::Http};
use num_cpus;
use proto::{ArcHandler, ArcService};
use routing::Router;
use std::io;
use std::net::{self, SocketAddr};
use std::sync::Arc;
use std::thread;
use tokio_core::net::TcpListener;
use tokio_core::reactor::Core;

/// The main server, the ArcReactor is where you mount your routes, middlewares
/// and initiate the server.
///
/// #Examples
///
/// ```rust,ignore
/// extern crate arc_reactor;
/// use arc_reactor::ArcReactor;
///
/// fn main() {
/// 	ArcReactor::new().routes(..).port(1234).initiate().unwrap()
/// 	}
/// ```
pub struct ArcReactor {
	port: i16,
	threads: usize,
	handler: Option<ArcHandler>,
}

impl ArcReactor {
	/// Creates an instance of the server.
	/// with a default port of `8080`
	/// and *No* routes. Note that calling `initiate` on an `ArcReactor` without
	/// routes will cause your program to panic.
	pub fn new() -> ArcReactor {
		ArcReactor {
			port: 8080,
			handler: None,
			threads: num_cpus::get()
		}
	}

	/// Sets the port for the server to listen on and returns the instance.
	pub fn port(mut self, port: i16) -> Self {
		self.port = port;

		self
	}

	/// set the number of threads, for Arc-Reactor
	/// to spawn reactors on.
	///
	/// Default is num_cpus::get()
	pub fn threads(mut self, num: usize) -> Self {
		self.threads = num;

		self
	}

	/// Mounts the Router on the ArcReactor.
	pub fn routes(mut self, routes: Router) -> Self {
		let routes = Arc::new(box routes as Box<ArcService>);
		if let Some(ref mut archandler) = self.handler {
			archandler.handler = routes;
		} else {
			self.handler = Some(ArcHandler {
				before: None,
				after: None,
				handler: routes,
			});
		}

		self
	}

	/// Binds the listener and blocks the main thread while listening for
	/// incoming connections.
	///
	/// # Panics
	///
	/// Calling this function will panic if: no routes are supplied, or it
	/// cannot start the main event loop.

	#[must_use]
	pub fn initiate(self) -> io::Result<()> {
		let addr = format!("0.0.0.0:{}", self.port).parse().unwrap();

		println!("[arc-reactor]: Binding to port {}", self.port);
		let listener = match net::TcpListener::bind(&addr) {
			Ok(listener) => listener,
			Err(e) => {
				eprintln!(
					"[arc-reactor]: Whoops! something else is running on port {}, {}",
					&self.port, e
				);
				return Err(e);
			}
		};

		println!("[arc-reactor]: Spawning threads!");

		let routes = Arc::new(self.handler.expect("This thing needs routes to work!"));

		for _ in 0..self.threads {
			let listener = listener.try_clone().expect("Could not clone listener!");
			let routes = routes.clone();

			thread::spawn(move || spawn(routes.clone(), listener, addr));
		}

		println!(
			"[arc-reactor]: Starting main event loop!\n[arc-reactor]: Spawned {} threads",
			self.threads + 1
		);

		spawn(routes, listener, addr);
		Ok(())
	}
}

fn spawn(routes: Arc<ArcHandler>, listener: net::TcpListener, addr: SocketAddr) {
	let mut core = Core::new().expect("Could not start event loop");
	let handle = core.handle();
	let http: Http<hyper::Chunk> = Http::new();
	let listener = TcpListener::from_listener(listener, &addr, &handle)
		.expect("Could not convert TCPListener to async");

	let future = listener.incoming().for_each(|(socket, remote_ip)| {
		let service = routes.clone();
		let connection_future = http.serve_connection(
			socket,
			RootService {
				service,
				remote_ip,
				handle: handle.clone(),
			},
		).then(|_| Ok(()));
		handle.spawn(connection_future);
		Ok(())
	});

	core.run(future).expect("Error running reactor core!");
}
<commit_msg>refactor http<commit_after>use super::rootservice::RootService;
use futures::{Future, Stream};
use hyper::{self, server::Http};
use num_cpus;
use proto::{ArcHandler, ArcService};
use routing::Router;
use std::io;
use std::net::{self, SocketAddr};
use std::sync::Arc;
use std::thread;
use tokio_core::net::TcpListener;
use tokio_core::reactor::Core;

/// The main server, the ArcReactor is where you mount your routes, middlewares
/// and initiate the server.
///
/// #Examples
///
/// ```rust,ignore
/// extern crate arc_reactor;
/// use arc_reactor::ArcReactor;
///
/// fn main() {
/// 	ArcReactor::new().routes(..).port(1234).initiate().unwrap()
/// 	}
/// ```
pub struct ArcReactor {
	port: i16,
	threads: usize,
	handler: Option<ArcHandler>,
}

impl ArcReactor {
	/// Creates an instance of the server.
	/// with a default port of `8080`
	/// and *No* routes. Note that calling `initiate` on an `ArcReactor` without
	/// routes will cause your program to panic.
	pub fn new() -> ArcReactor {
		ArcReactor {
			port: 8080,
			handler: None,
			threads: num_cpus::get()
		}
	}

	/// Sets the port for the server to listen on and returns the instance.
	pub fn port(mut self, port: i16) -> Self {
		self.port = port;

		self
	}

	/// set the number of threads, for Arc-Reactor
	/// to spawn reactors on.
	///
	/// Default is num_cpus::get()
	pub fn threads(mut self, num: usize) -> Self {
		self.threads = num;

		self
	}

	/// Mounts the Router on the ArcReactor.
	pub fn routes(mut self, routes: Router) -> Self {
		let routes = Arc::new(box routes as Box<ArcService>);
		if let Some(ref mut archandler) = self.handler {
			archandler.handler = routes;
		} else {
			self.handler = Some(ArcHandler {
				before: None,
				after: None,
				handler: routes,
			});
		}

		self
	}

	/// Binds the listener and blocks the main thread while listening for
	/// incoming connections.
	///
	/// # Panics
	///
	/// Calling this function will panic if: no routes are supplied, or it
	/// cannot start the main event loop.

	#[must_use]
	pub fn initiate(self) -> io::Result<()> {
		let addr = format!("0.0.0.0:{}", self.port).parse().unwrap();

		println!("[arc-reactor]: Binding to port {}", self.port);
		let listener = match net::TcpListener::bind(&addr) {
			Ok(listener) => listener,
			Err(e) => {
				eprintln!(
					"[arc-reactor]: Whoops! something else is running on port {}, {}",
					&self.port, e
				);
				return Err(e);
			}
		};

		println!("[arc-reactor]: Spawning threads!");

		let routes = Arc::new(self.handler.expect("This thing needs routes to work!"));
		let http = Http::new();

		for _ in 0..self.threads {
			let listener = listener.try_clone().expect("Could not clone listener!");
			let routes = routes.clone();
			let http = http.clone();

			thread::spawn(move || spawn(routes, listener, addr, http));
		}

		println!(
			"[arc-reactor]: Starting main event loop!\n[arc-reactor]: Spawned {} threads",
			self.threads + 1
		);

		spawn(routes, listener, addr, http);
		Ok(())
	}
}

fn spawn(routes: Arc<ArcHandler>, listener: net::TcpListener, addr: SocketAddr, http: Http<hyper::Chunk>) {
	let mut core = Core::new().expect("Could not start event loop");
	let handle = core.handle();
	let listener = TcpListener::from_listener(listener, &addr, &handle)
		.expect("Could not convert TCPListener to async");

	let future = listener.incoming().for_each(|(socket, remote_ip)| {
		let service = routes.clone();
		let connection_future = http.serve_connection(
			socket,
			RootService {
				service,
				remote_ip,
				handle: handle.clone(),
			},
		).then(|_| Ok(()));
		handle.spawn(connection_future);
		Ok(())
	});

	core.run(future).expect("Error running reactor core!");
}
<|endoftext|>


<commit_before>extern crate structopt;
#[macro_use]
extern crate structopt_derive;

use structopt::StructOpt;
use std::fs::File;
use std::io::Read;

#[derive(Debug, Clone)]
struct Coordinate {
    x: isize,
    y: isize,
    z: isize,
}

impl Coordinate {
    fn origin() -> Coordinate {
        Coordinate {x: 0, y: 0, z: 0}
    }
    fn travel(&self, dir: &Direction) -> Coordinate {
        use Direction::*;
        match *dir {
            N => Coordinate {x: self.x, y: self.y + 1, z: self.z - 1},
            Ne => Coordinate {x: self.x + 1, y: self.y, z: self.z - 1},
            Se => Coordinate {x: self.x + 1, y: self.y - 1, z: self.z},
            S => Coordinate {x: self.x, y: self.y - 1, z: self.z + 1},
            Sw => Coordinate {x: self.x - 1, y: self.y, z: self.z + 1},
            Nw => Coordinate {x: self.x - 1, y: self.y + 1, z: self.z},
        }
    }
    fn distance(&self, other: &Coordinate) -> isize {
        ((self.x - other.x).abs() + (self.y - other.y).abs() + (self.z - other.z).abs()) / 2
    }
}

#[derive(Debug)]
enum Direction {
    N,
    Ne,
    Se,
    S,
    Sw,
    Nw,
}

#[derive(Debug)]
struct DirectionParseError;

impl std::str::FromStr for Direction {
    type Err = DirectionParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use Direction::*;
        match s {
            "n" => Ok(N),
            "ne" => Ok(Ne),
            "se" => Ok(Se),
            "s" => Ok(S),
            "sw" => Ok(Sw),
            "nw" => Ok(Nw),
            _ => Err(DirectionParseError),
        }
    }
}

fn part1(input: &str) -> isize {
    let directions: Vec<_> = input
        .trim()
        .split(',')
        .map(|s| s
             .parse::<Direction>()
             .expect(&format!("could not parse direction \"{}\"", s))
        )
        .collect();
    let end = directions.iter().fold(Coordinate::origin(), |loc, dir| loc.travel(dir));
    Coordinate::origin().distance(&end)
}

fn part2(input: &str) -> isize {
    let directions: Vec<_> = input
        .trim()
        .split(',')
        .map(|s| s
             .parse::<Direction>()
             .expect(&format!("could not parse direction \"{}\"", s))
        )
        .collect();
    let mut loc = Coordinate::origin();
    let mut furthest = 0;
    for dir in directions {
        loc = loc.travel(&dir);
        let dist = loc.distance(&Coordinate::origin());
        if dist > furthest {
            furthest = dist;
        }
    }
    furthest
}

fn main() {
    let opt = Opt::from_args();
    let mut contents = String::new();
    if opt.input == "-" {
        std::io::stdin()
            .read_to_string(&mut contents)
            .expect("could not read stdin");
    } else {
        let mut file = File::open(&opt.input)
            .expect(&format!("file {} not found", opt.input));
        file.read_to_string(&mut contents)
            .expect(&format!("could not read file {}", opt.input));
    }
    println!("Part 1: {}", part1(&contents));
    println!("Part 2: {}", part2(&contents));
}

#[derive(StructOpt, Debug)]
#[structopt(name = "day10", about = "Advent of code 2017 day 10")]
struct Opt {
    #[structopt(help = "Input file")] input: String,
}

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

    #[test]
    fn part1_test() {
        assert_eq!(part1("ne,ne,ne"), 3);
        assert_eq!(part1("ne,ne,sw,sw"), 0);
        assert_eq!(part1("ne,ne,s,s"), 2);
        assert_eq!(part1("se,sw,se,sw,sw"), 3);
    }
}
<commit_msg>2017 day 11: combine parts 1 and 2<commit_after>extern crate structopt;
#[macro_use]
extern crate structopt_derive;

use structopt::StructOpt;
use std::fs::File;
use std::io::Read;

#[derive(Debug, Clone)]
struct Coordinate {
    x: isize,
    y: isize,
    z: isize,
}

impl Coordinate {
    fn origin() -> Coordinate {
        Coordinate { x: 0, y: 0, z: 0 }
    }
    fn travel(&self, dir: &Direction) -> Coordinate {
        use Direction::*;
        match *dir {
            N => Coordinate {
                x: self.x,
                y: self.y + 1,
                z: self.z - 1,
            },
            Ne => Coordinate {
                x: self.x + 1,
                y: self.y,
                z: self.z - 1,
            },
            Se => Coordinate {
                x: self.x + 1,
                y: self.y - 1,
                z: self.z,
            },
            S => Coordinate {
                x: self.x,
                y: self.y - 1,
                z: self.z + 1,
            },
            Sw => Coordinate {
                x: self.x - 1,
                y: self.y,
                z: self.z + 1,
            },
            Nw => Coordinate {
                x: self.x - 1,
                y: self.y + 1,
                z: self.z,
            },
        }
    }
    fn distance(&self, other: &Coordinate) -> isize {
        ((self.x - other.x).abs() + (self.y - other.y).abs()
            + (self.z - other.z).abs()) / 2
    }
}

#[derive(Debug)]
enum Direction {
    N,
    Ne,
    Se,
    S,
    Sw,
    Nw,
}

#[derive(Debug)]
struct DirectionParseError;

impl std::str::FromStr for Direction {
    type Err = DirectionParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use Direction::*;
        match s {
            "n" => Ok(N),
            "ne" => Ok(Ne),
            "se" => Ok(Se),
            "s" => Ok(S),
            "sw" => Ok(Sw),
            "nw" => Ok(Nw),
            _ => Err(DirectionParseError),
        }
    }
}

// solve parts 1 and 2
fn solve(input: &str) -> (isize, isize) {
    let (end, max_dist) = input
        .trim()
        .split(',')
        .map(|s| {
            s.parse::<Direction>()
                .expect(&format!("could not parse direction \"{}\"", s))
        })
        .fold((Coordinate::origin(), 0), |(loc, max_dist), dir| {
            let new_loc = loc.travel(&dir);
            let new_dist = new_loc.distance(&Coordinate::origin());
            (new_loc, max_dist.max(new_dist))
        });
    (end.distance(&Coordinate::origin()), max_dist)
}

fn main() {
    let opt = Opt::from_args();
    let mut contents = String::new();
    if opt.input == "-" {
        std::io::stdin()
            .read_to_string(&mut contents)
            .expect("could not read stdin");
    } else {
        let mut file = File::open(&opt.input)
            .expect(&format!("file {} not found", opt.input));
        file.read_to_string(&mut contents)
            .expect(&format!("could not read file {}", opt.input));
    }
    let solution = solve(&contents);
    println!("Part 1: {}", solution.0);
    println!("Part 2: {}", solution.1);
}

#[derive(StructOpt, Debug)]
#[structopt(name = "day10", about = "Advent of code 2017 day 10")]
struct Opt {
    #[structopt(help = "Input file")] input: String,
}

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

    #[test]
    fn part1_test() {
        assert_eq!(solve("ne,ne,ne").0, 3);
        assert_eq!(solve("ne,ne,sw,sw").0, 0);
        assert_eq!(solve("ne,ne,s,s").0, 2);
        assert_eq!(solve("se,sw,se,sw,sw").0, 3);
    }
}
<|endoftext|>


<commit_before>use std::path::PathBuf;
use structopt::StructOpt;

fn part1(input: &[isize]) -> isize {
    let mut input = input.to_vec();
    input[1] = 12;
    input[2] = 2;
    intcode::run_tape(&mut input);
    input[0]
}

fn part2(input: &[isize]) -> isize {
    for noun in 0..99 {
        for verb in 0..=noun {
            if intcode::compute(noun, verb, input.to_vec()) == 1969_0720 {
                return 100 * noun + verb;
            }
        }
    }
    panic!("No noun / verb pair found")
}

fn main() {
    let input: Vec<_> = std::fs::read_to_string(Opt::from_args().input)
        .expect("error reading file")
        .split(',')
        .map(|num| {
            num.trim()
                .parse::<isize>()
                .unwrap_or_else(|err| panic!("could not parse token \"{}\": {:?}", num, err))
        })
        .collect();
    println!("Part 1: {}", part1(&input));
    println!("Part 2: {}", part2(&input));
}

#[derive(StructOpt)]
struct Opt {
    #[structopt(parse(from_os_str))]
    input: PathBuf,
}
<commit_msg>Complete intcode refactor<commit_after>use std::path::PathBuf;
use structopt::StructOpt;

fn part1(input: &[isize]) -> isize {
    intcode::compute(12, 2, input.to_vec())
}

fn part2(input: &[isize]) -> isize {
    for noun in 0..99 {
        for verb in 0..=noun {
            if intcode::compute(noun, verb, input.to_vec()) == 1969_0720 {
                return 100 * noun + verb;
            }
        }
    }
    panic!("No noun / verb pair found")
}

fn main() {
    let input: Vec<_> = std::fs::read_to_string(Opt::from_args().input)
        .expect("error reading file")
        .split(',')
        .map(|num| {
            num.trim()
                .parse::<isize>()
                .unwrap_or_else(|err| panic!("could not parse token \"{}\": {:?}", num, err))
        })
        .collect();
    println!("Part 1: {}", part1(&input));
    println!("Part 2: {}", part2(&input));
}

#[derive(StructOpt)]
struct Opt {
    #[structopt(parse(from_os_str))]
    input: PathBuf,
}
<|endoftext|>


<commit_before>extern crate serde_json;
extern crate curl;
extern crate rand;

use std::collections::BTreeMap;

use serde_json::Value;
use serde_json::value::{ToJson, from_value};
use serde_json::ser::to_string_pretty;

use curl::easy::{Easy, List};
use rand::{thread_rng, Rng};

pub type ClientResult<T> = Result<T, curl::Error>;

#[derive(Debug, Clone)]
pub enum Space {
	DISCRETE{n: u64},
	BOX{shape: Vec<u64>, high: Vec<f64>, low: Vec<f64>},
	TUPLE{spaces: Vec<Box<Space>>}
}

impl Space {
	fn from_json(info: &Value) -> Space {
		match info.find("name").unwrap().as_str().unwrap() {
			"Discrete" => {
				let n = info.find("n").unwrap().as_u64().unwrap();
				Space::DISCRETE{n: n}
			},
			"Box" => {
				let mut shape = Vec::new();
				for val in info.find("shape").unwrap().as_array().unwrap() {
					shape.push(val.as_u64().unwrap());
				}
				let mut high = Vec::new();
				for val in info.find("high").unwrap().as_array().unwrap() {
					high.push(val.as_f64().unwrap());
				}
				let mut low = Vec::new();
				for val in info.find("low").unwrap().as_array().unwrap() {
					low.push(val.as_f64().unwrap());
				}
				Space::BOX{shape: shape, high: high, low: low}
			},
			"Tuple" => panic!("Parsing for Tuple spaces is not yet implemented"),
			e @ _ => panic!("Unrecognized space name: {}", e)
		}
	}
	pub fn sample(&self) -> Vec<f64> {
		let mut rng = thread_rng();
		match *self {
			Space::DISCRETE{n} => {
				vec![(rng.gen::<u64>()%n) as f64]
			},
			Space::BOX{ref shape, ref high, ref low} => {
				let mut ret = Vec::new();
				let mut index = 0;
				for &i in shape {
					for _ in 0..i {
						ret.push(rng.gen_range(low[index], high[index]));
						index += 1;
					}
				}
				ret
			},
			Space::TUPLE{ref spaces} => {
				let mut ret = Vec::new();
				for space in spaces {
					ret.extend(space.sample());
				}
				ret
			}
		}
	}
}

#[allow(dead_code)]
#[derive(Debug)]
pub struct State {
	pub observation:	Vec<f64>,
	pub reward:			f64,
	pub done:			bool,
	pub info:			Value
}

#[allow(dead_code)]
pub struct Environment {
	client:			Box<Client>,
	instance_id:	String,
	act_space:		Space,
	obs_space:		Space
}

impl Environment {
	pub fn action_space(&self) -> Space {
		self.act_space.clone()
	}
	pub fn observation_space(&self) -> Space {
		self.obs_space.clone()
	}
	pub fn reset(&mut self) -> ClientResult<Vec<f64>> {
		let observation = try!(self.client.post("/v1/envs/".to_string() + &self.instance_id + "/reset/",
										   		Value::Null));
		let mut ret = Vec::new();
		for val in observation.find("observation").unwrap().as_array().unwrap() {
			ret.push(val.as_f64().unwrap());
		}
		Ok(ret)
	}
	pub fn step(&mut self, action: Vec<f64>, render: bool) -> ClientResult<State> {
		let mut req = BTreeMap::new();
		req.insert("render", Value::Bool(render));
		match self.act_space {
			Space::DISCRETE{..} => {
				assert_eq!(action.len(), 1);
				req.insert("action", Value::U64(action[0] as u64));
			},
			Space::BOX{ref shape, ..} => {
				assert_eq!(action.len(), shape[0] as usize);
				req.insert("action", action.to_json());
			},
			Space::TUPLE{..} => panic!("Actions for Tuple spaces not implemented yet")
		}

		let state = try!(self.client.post("/v1/envs/".to_string() + &self.instance_id + "/step/",
									 	  req.to_json()));

		Ok(State {
			observation: from_value(state.find("observation").unwrap().clone()).unwrap(),
			reward: state.find("reward").unwrap().as_f64().unwrap(),
			done: state.find("done").unwrap().as_bool().unwrap(),
			info: state.find("info").unwrap().clone()
		})
	}
	pub fn monitor_start(&mut self, directory: String, force: bool, resume: bool) -> ClientResult<()> {
		let mut req = BTreeMap::new();
		req.insert("directory", Value::String(directory));
		req.insert("force", Value::Bool(force));
		req.insert("resume", Value::Bool(resume));
		try!(self.client.post("/v1/envs/".to_string() + &self.instance_id + "/monitor/start/",
						 	  req.to_json()));
		Ok(())
	}
	pub fn monitor_stop(&mut self) -> ClientResult<()> {
		try!(self.client.post("/v1/envs/".to_string() + &self.instance_id + "/monitor/close/",
						 	  Value::Null));
		Ok(())
	}
}

pub struct Client {
	address:	String,
	handle:		Easy
}

impl Client {
    pub fn new(addr: String) -> Client {
    	let mut headers = List::new();
    	headers.append("Content-Type: application/json").unwrap();

    	let mut handle = Easy::new();
    	handle.http_headers(headers).unwrap();

    	Client{address: addr, handle: handle}
    }
    pub fn make(mut self, env_id: &str) -> ClientResult<Environment> {
    	let mut req: BTreeMap<&str, &str> = BTreeMap::new();
    	req.insert("env_id", env_id);

    	let instance_id = try!(self.post("/v1/envs/".to_string(), req.to_json()));
    	let instance_id = match instance_id.find("instance_id") {
    		Some(id) => id.as_str().unwrap(),
    		None => panic!("Unrecognized environment id: {}", env_id)
    	};

    	let obs_space = try!(self.get("/v1/envs/".to_string() + instance_id + "/observation_space/"));
    	let act_space = try!(self.get("/v1/envs/".to_string() + instance_id + "/action_space/"));

    	Ok(Environment {
    		client: Box::new(self),
    		instance_id: instance_id.to_string(),
    		act_space: Space::from_json(act_space.find("info").unwrap()),
    		obs_space: Space::from_json(obs_space.find("info").unwrap())})
    }

    fn post(&mut self, route: String, request: Value) -> ClientResult<Value> {
    	let request = to_string_pretty(&request).unwrap();
    	let data = request.as_bytes();
    	let url = self.address.clone() + &route;

    	try!(self.handle.url(&url));
	    try!(self.handle.post(true));
	    try!(self.handle.post_field_size(data.len() as u64));
	    try!(self.handle.post_fields_copy(data));

	    let mut answer = Vec::new();
	    {
	    	let mut transfer = self.handle.transfer();
		    transfer.write_function(|data| {
		        answer.extend_from_slice(data);
		        Ok(data.len())
		    }).unwrap();
		    try!(transfer.perform());
	    }

	    Ok(serde_json::from_str(&String::from_utf8(answer).unwrap()).unwrap())
    }
    fn get(&mut self, route: String) -> ClientResult<Value> {
    	let url = self.address.clone() + &route;

    	try!(self.handle.url(&url));
    	try!(self.handle.post(false));

    	let mut answer = Vec::new();
	    {
	    	let mut transfer = self.handle.transfer();
		    transfer.write_function(|data| {
		        answer.extend_from_slice(data);
		        Ok(data.len())
		    }).unwrap();
		    transfer.perform().unwrap();
	    }

	    Ok(serde_json::from_str(&String::from_utf8(answer).unwrap()).unwrap())
    }
}<commit_msg>Added upload<commit_after>extern crate serde_json;
extern crate curl;
extern crate rand;

use std::collections::BTreeMap;

use serde_json::Value;
use serde_json::value::{ToJson, from_value};
use serde_json::ser::to_string_pretty;

use curl::easy::{Easy, List};
use rand::{thread_rng, Rng};

pub type ClientResult<T> = Result<T, curl::Error>;

#[derive(Debug, Clone)]
pub enum Space {
	DISCRETE{n: u64},
	BOX{shape: Vec<u64>, high: Vec<f64>, low: Vec<f64>},
	TUPLE{spaces: Vec<Box<Space>>}
}

impl Space {
	fn from_json(info: &Value) -> Space {
		match info.find("name").unwrap().as_str().unwrap() {
			"Discrete" => {
				let n = info.find("n").unwrap().as_u64().unwrap();
				Space::DISCRETE{n: n}
			},
			"Box" => {
				let mut shape = Vec::new();
				for val in info.find("shape").unwrap().as_array().unwrap() {
					shape.push(val.as_u64().unwrap());
				}
				let mut high = Vec::new();
				for val in info.find("high").unwrap().as_array().unwrap() {
					high.push(val.as_f64().unwrap());
				}
				let mut low = Vec::new();
				for val in info.find("low").unwrap().as_array().unwrap() {
					low.push(val.as_f64().unwrap());
				}
				Space::BOX{shape: shape, high: high, low: low}
			},
			"Tuple" => panic!("Parsing for Tuple spaces is not yet implemented"),
			e @ _ => panic!("Unrecognized space name: {}", e)
		}
	}
	pub fn sample(&self) -> Vec<f64> {
		let mut rng = thread_rng();
		match *self {
			Space::DISCRETE{n} => {
				vec![(rng.gen::<u64>()%n) as f64]
			},
			Space::BOX{ref shape, ref high, ref low} => {
				let mut ret = Vec::new();
				let mut index = 0;
				for &i in shape {
					for _ in 0..i {
						ret.push(rng.gen_range(low[index], high[index]));
						index += 1;
					}
				}
				ret
			},
			Space::TUPLE{ref spaces} => {
				let mut ret = Vec::new();
				for space in spaces {
					ret.extend(space.sample());
				}
				ret
			}
		}
	}
}

#[allow(dead_code)]
#[derive(Debug)]
pub struct State {
	pub observation:	Vec<f64>,
	pub reward:			f64,
	pub done:			bool,
	pub info:			Value
}

#[allow(dead_code)]
pub struct Environment {
	client:			Box<Client>,
	instance_id:	String,
	act_space:		Space,
	obs_space:		Space
}

impl Environment {
	pub fn action_space(&self) -> Space {
		self.act_space.clone()
	}
	pub fn observation_space(&self) -> Space {
		self.obs_space.clone()
	}
	pub fn reset(&mut self) -> ClientResult<Vec<f64>> {
		let observation = try!(self.client.post("/v1/envs/".to_string() + &self.instance_id + "/reset/",
										   		Value::Null));
		let mut ret = Vec::new();
		for val in observation.find("observation").unwrap().as_array().unwrap() {
			ret.push(val.as_f64().unwrap());
		}
		Ok(ret)
	}
	pub fn step(&mut self, action: Vec<f64>, render: bool) -> ClientResult<State> {
		let mut req = BTreeMap::new();
		req.insert("render", Value::Bool(render));
		match self.act_space {
			Space::DISCRETE{..} => {
				assert_eq!(action.len(), 1);
				req.insert("action", Value::U64(action[0] as u64));
			},
			Space::BOX{ref shape, ..} => {
				assert_eq!(action.len(), shape[0] as usize);
				req.insert("action", action.to_json());
			},
			Space::TUPLE{..} => panic!("Actions for Tuple spaces not implemented yet")
		}

		let state = try!(self.client.post("/v1/envs/".to_string() + &self.instance_id + "/step/",
									 	  req.to_json()));

		Ok(State {
			observation: from_value(state.find("observation").unwrap().clone()).unwrap(),
			reward: state.find("reward").unwrap().as_f64().unwrap(),
			done: state.find("done").unwrap().as_bool().unwrap(),
			info: state.find("info").unwrap().clone()
		})
	}
	pub fn monitor_start(&mut self, directory: String, force: bool, resume: bool) -> ClientResult<()> {
		let mut req = BTreeMap::new();
		req.insert("directory", Value::String(directory));
		req.insert("force", Value::Bool(force));
		req.insert("resume", Value::Bool(resume));
		try!(self.client.post("/v1/envs/".to_string() + &self.instance_id + "/monitor/start/",
						 	  req.to_json()));
		Ok(())
	}
	pub fn monitor_stop(&mut self) -> ClientResult<()> {
		try!(self.client.post("/v1/envs/".to_string() + &self.instance_id + "/monitor/close/",
						 	  Value::Null));
		Ok(())
	}
	pub fn upload(&mut self, training_dir: String, api_key: String, algorithm_id: String) -> ClientResult<()> {
		let mut req = BTreeMap::new();
		req.insert("training_dir", training_dir);
		req.insert("api_key", api_key);
		req.insert("algorithm_id", algorithm_id);

		try!(self.client.post("/v1/upload/".to_string(), req.to_json()));
		Ok(())
	}
}

pub struct Client {
	address:	String,
	handle:		Easy
}

impl Client {
    pub fn new(addr: String) -> Client {
    	let mut headers = List::new();
    	headers.append("Content-Type: application/json").unwrap();

    	let mut handle = Easy::new();
    	handle.http_headers(headers).unwrap();

    	Client{address: addr, handle: handle}
    }
    pub fn make(mut self, env_id: &str) -> ClientResult<Environment> {
    	let mut req: BTreeMap<&str, &str> = BTreeMap::new();
    	req.insert("env_id", env_id);

    	let instance_id = try!(self.post("/v1/envs/".to_string(), req.to_json()));
    	let instance_id = match instance_id.find("instance_id") {
    		Some(id) => id.as_str().unwrap(),
    		None => panic!("Unrecognized environment id: {}", env_id)
    	};

    	let obs_space = try!(self.get("/v1/envs/".to_string() + instance_id + "/observation_space/"));
    	let act_space = try!(self.get("/v1/envs/".to_string() + instance_id + "/action_space/"));

    	Ok(Environment {
    		client: Box::new(self),
    		instance_id: instance_id.to_string(),
    		act_space: Space::from_json(act_space.find("info").unwrap()),
    		obs_space: Space::from_json(obs_space.find("info").unwrap())})
    }

    fn post(&mut self, route: String, request: Value) -> ClientResult<Value> {
    	let request = to_string_pretty(&request).unwrap();
    	let data = request.as_bytes();
    	let url = self.address.clone() + &route;

    	try!(self.handle.url(&url));
	    try!(self.handle.post(true));
	    try!(self.handle.post_field_size(data.len() as u64));
	    try!(self.handle.post_fields_copy(data));

	    let mut answer = Vec::new();
	    {
	    	let mut transfer = self.handle.transfer();
		    transfer.write_function(|data| {
		        answer.extend_from_slice(data);
		        Ok(data.len())
		    }).unwrap();
		    try!(transfer.perform());
	    }

	    Ok(serde_json::from_str(&String::from_utf8(answer).unwrap()).unwrap())
    }
    fn get(&mut self, route: String) -> ClientResult<Value> {
    	let url = self.address.clone() + &route;

    	try!(self.handle.url(&url));
    	try!(self.handle.post(false));

    	let mut answer = Vec::new();
	    {
	    	let mut transfer = self.handle.transfer();
		    transfer.write_function(|data| {
		        answer.extend_from_slice(data);
		        Ok(data.len())
		    }).unwrap();
		    transfer.perform().unwrap();
	    }

	    Ok(serde_json::from_str(&String::from_utf8(answer).unwrap()).unwrap())
    }
}<|endoftext|>


<commit_before>extern crate serde_json;
extern crate hyper;
extern crate rand;

use std::collections::BTreeMap;
use std::io::Read;

use serde_json::Value;
use serde_json::value::{ToJson, from_value};

use hyper::client::Client;
use hyper::header::Headers;

use rand::{thread_rng, Rng};

pub type GymResult<T> = Result<T, hyper::Error>;

#[derive(Debug, Clone)]
pub enum Space {
	DISCRETE{n: u64},
	BOX{shape: Vec<u64>, high: Vec<f64>, low: Vec<f64>},
	TUPLE{spaces: Vec<Box<Space>>}
}

impl Space {
	fn from_json(info: &Value) -> Space {
		match info.find("name").unwrap().as_str().unwrap() {
			"Discrete" => {
				let n = info.find("n").unwrap().as_u64().unwrap();
				Space::DISCRETE{n: n}
			},
			"Box" => {
				let mut shape = Vec::new();
				for val in info.find("shape").unwrap().as_array().unwrap() {
					shape.push(val.as_u64().unwrap());
				}
				let mut high = Vec::new();
				for val in info.find("high").unwrap().as_array().unwrap() {
					high.push(val.as_f64().unwrap());
				}
				let mut low = Vec::new();
				for val in info.find("low").unwrap().as_array().unwrap() {
					low.push(val.as_f64().unwrap());
				}
				Space::BOX{shape: shape, high: high, low: low}
			},
			"Tuple" => panic!("Parsing for Tuple spaces is not yet implemented"),
			e @ _ => panic!("Unrecognized space name: {}", e)
		}
	}
	pub fn sample(&self) -> Vec<f64> {
		let mut rng = thread_rng();
		match *self {
			Space::DISCRETE{n} => {
				vec![(rng.gen::<u64>()%n) as f64]
			},
			Space::BOX{ref shape, ref high, ref low} => {
				let mut ret = Vec::new();
				let mut index = 0;
				for &i in shape {
					for _ in 0..i {
						ret.push(rng.gen_range(low[index], high[index]));
						index += 1;
					}
				}
				ret
			},
			Space::TUPLE{ref spaces} => {
				let mut ret = Vec::new();
				for space in spaces {
					ret.extend(space.sample());
				}
				ret
			}
		}
	}
}

#[allow(dead_code)]
#[derive(Debug)]
pub struct State {
	pub observation:	Vec<f64>,
	pub reward:			f64,
	pub done:			bool,
	pub info:			Value,
}

#[allow(dead_code)]
pub struct Environment {
	client:			GymClient,
	instance_id:	String,
	act_space:		Space,
	obs_space:		Space,
}

impl Environment {
	pub fn action_space(&self) -> Space {
		self.act_space.clone()
	}
	pub fn observation_space(&self) -> Space {
		self.obs_space.clone()
	}
	pub fn reset(&mut self) -> GymResult<Vec<f64>> {
		let observation = try!(self.client.post("/v1/envs/".to_string() + &self.instance_id + "/reset/",
										   		Value::Null));
		let mut ret = Vec::new();
		for val in observation.find("observation").unwrap().as_array().unwrap() {
			ret.push(val.as_f64().unwrap());
		}
		Ok(ret)
	}
	pub fn step(&mut self, action: Vec<f64>, render: bool) -> GymResult<State> {
		let mut req = BTreeMap::new();
		req.insert("render", Value::Bool(render));
		match self.act_space {
			Space::DISCRETE{..} => {
				assert_eq!(action.len(), 1);
				req.insert("action", Value::U64(action[0] as u64));
			},
			Space::BOX{ref shape, ..} => {
				assert_eq!(action.len(), shape[0] as usize);
				req.insert("action", action.to_json());
			},
			Space::TUPLE{..} => panic!("Actions for Tuple spaces not implemented yet")
		}

		let path = "/v1/envs/".to_string() + &self.instance_id + "/step/";
		let state = try!(self.client.post(path, req.to_json()));

		Ok(State {
			observation: from_value(state.find("observation").unwrap().clone()).unwrap(),
			reward: state.find("reward").unwrap().as_f64().unwrap(),
			done: state.find("done").unwrap().as_bool().unwrap(),
			info: state.find("info").unwrap().clone()
		})
	}
	pub fn monitor_start(&mut self, directory: String, force: bool, resume: bool) -> GymResult<()> {
		let mut req = BTreeMap::new();
		req.insert("directory", Value::String(directory));
		req.insert("force", Value::Bool(force));
		req.insert("resume", Value::Bool(resume));

		try!(self.client.post("/v1/envs/".to_string() + &self.instance_id + "/monitor/start/",
						 	  req.to_json()));
		Ok(())
	}
	pub fn monitor_stop(&mut self) -> GymResult<()> {
		try!(self.client.post("/v1/envs/".to_string() + &self.instance_id + "/monitor/close/",
						 	  Value::Null));
		Ok(())
	}
	pub fn upload(&mut self, training_dir: String, api_key: String, algorithm_id: String) -> GymResult<()> {
		let mut req = BTreeMap::new();
		req.insert("training_dir", training_dir);
		req.insert("api_key", api_key);
		req.insert("algorithm_id", algorithm_id);

		try!(self.client.post("/v1/upload/".to_string(), req.to_json()));
		Ok(())
	}
}

pub struct GymClient {
	address:	String,
	handle:		Client,
	headers:	Headers,
}

impl GymClient {
    pub fn new(addr: String) -> GymClient {
		let mut headers = Headers::new();
		headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);

    	GymClient {
    		address: addr,
    		handle: Client::new(),
    		headers: headers
    	}
    }
    pub fn make(mut self, env_id: &str) -> GymResult<Environment> {
    	let mut req: BTreeMap<&str, &str> = BTreeMap::new();
    	req.insert("env_id", env_id);

    	let instance_id = try!(self.post("/v1/envs/".to_string(), req.to_json()));
    	let instance_id = match instance_id.find("instance_id") {
    		Some(id) => id.as_str().unwrap(),
    		None => panic!("Unrecognized environment id: {}", env_id)
    	};

    	let obs_space = try!(self.get("/v1/envs/".to_string() + instance_id + "/observation_space/"));
    	let act_space = try!(self.get("/v1/envs/".to_string() + instance_id + "/action_space/"));

    	Ok(Environment {
    		client: self,
    		instance_id: instance_id.to_string(),
    		act_space: Space::from_json(act_space.find("info").unwrap()),
    		obs_space: Space::from_json(obs_space.find("info").unwrap())})
    }

    fn post(&mut self, route: String, request: Value) -> GymResult<Value> {
    	let url = self.address.clone() + &route;
    	let mut resp = try!(self.handle.post(&url)
    							  	   .body(&request.to_string())
    							  	   .headers(self.headers.clone())
    							  	   .send());

    	let mut json = String::new();
    	let _ = resp.read_to_string(&mut json);

	    Ok(serde_json::from_str(&json).unwrap_or(Value::Null))
    }
    fn get(&mut self, route: String) -> GymResult<Value> {
    	let url = self.address.clone() + &route;
    	let mut resp = try!(self.handle.get(&url)
    							  	   .send());
    	let mut json = String::new();
    	let _ = resp.read_to_string(&mut json);

		Ok(serde_json::from_str(&json).unwrap_or(Value::Null))
    }
}<commit_msg>Cleaned up some code<commit_after>extern crate serde_json;
extern crate hyper;
extern crate rand;

use std::collections::BTreeMap;
use std::io::Read;

use serde_json::Value;
use serde_json::value::{ToJson, from_value};

use hyper::client::Client;
use hyper::header::Headers;

use rand::{thread_rng, Rng};

pub type GymResult<T> = Result<T, hyper::Error>;

#[derive(Debug, Clone)]
pub enum Space {
	DISCRETE{n: u64},
	BOX{shape: Vec<u64>, high: Vec<f64>, low: Vec<f64>},
	TUPLE{spaces: Vec<Box<Space>>}
}

impl Space {
	fn from_json(info: &Value) -> Space {
		match info.find("name").unwrap().as_str().unwrap() {
			"Discrete" => {
				let n = info.find("n").unwrap().as_u64().unwrap();
				Space::DISCRETE{n: n}
			},
			"Box" => {
				let shape = info.find("shape").unwrap().as_array().unwrap()
								.into_iter().map(|x| x.as_u64().unwrap())
								.collect::<Vec<_>>();

				let high = info.find("high").unwrap().as_array().unwrap()
							   .into_iter().map(|x| x.as_f64().unwrap())
							   .collect::<Vec<_>>();

				let low = info.find("low").unwrap().as_array().unwrap()
							  .into_iter().map(|x| x.as_f64().unwrap())
							  .collect::<Vec<_>>();

				Space::BOX{shape: shape, high: high, low: low}
			},
			"Tuple" => panic!("Parsing for Tuple spaces is not yet implemented"),
			e @ _ => panic!("Unrecognized space name: {}", e)
		}
	}
	pub fn sample(&self) -> Vec<f64> {
		let mut rng = thread_rng();
		match *self {
			Space::DISCRETE{n} => {
				vec![(rng.gen::<u64>()%n) as f64]
			},
			Space::BOX{ref shape, ref high, ref low} => {
				let mut ret = Vec::with_capacity(shape.iter().map(|x| *x as usize).product());
				let mut index = 0;
				for &i in shape {
					for _ in 0..i {
						ret.push(rng.gen_range(low[index], high[index]));
						index += 1;
					}
				}
				ret
			},
			Space::TUPLE{ref spaces} => {
				let mut ret = Vec::new();
				for space in spaces {
					ret.extend(space.sample());
				}
				ret
			}
		}
	}
}

#[allow(dead_code)]
#[derive(Debug)]
pub struct State {
	pub observation:	Vec<f64>,
	pub reward:			f64,
	pub done:			bool,
	pub info:			Value,
}

#[allow(dead_code)]
pub struct Environment {
	client:			GymClient,
	instance_id:	String,
	act_space:		Space,
	obs_space:		Space,
}

impl Environment {
	pub fn action_space<'a>(&'a self) -> &'a Space {
		&self.act_space
	}
	pub fn observation_space<'a>(&'a self) -> &'a Space {
		&self.obs_space
	}
	pub fn reset(&mut self) -> GymResult<Vec<f64>> {
		let path = "/v1/envs/".to_string() + &self.instance_id + "/reset/";
		let observation = try!(self.client.post(path, Value::Null));

		let ret: Vec<_> = observation.find("observation").unwrap().as_array().unwrap()
									 .into_iter().map(|x| x.as_f64().unwrap())
									 .collect();
		Ok(ret)
	}
	pub fn step(&mut self, action: Vec<f64>, render: bool) -> GymResult<State> {
		let mut req = BTreeMap::new();
		req.insert("render", Value::Bool(render));
		match self.act_space {
			Space::DISCRETE{..} => {
				assert_eq!(action.len(), 1);
				req.insert("action", Value::U64(action[0] as u64));
			},
			Space::BOX{ref shape, ..} => {
				assert_eq!(action.len(), shape[0] as usize);
				req.insert("action", action.to_json());
			},
			Space::TUPLE{..} => panic!("Actions for Tuple spaces not implemented yet")
		}

		let path = "/v1/envs/".to_string() + &self.instance_id + "/step/";
		let state = try!(self.client.post(path, req.to_json()));

		Ok(State {
			observation: from_value(state.find("observation").unwrap().clone()).unwrap(),
			reward: state.find("reward").unwrap().as_f64().unwrap(),
			done: state.find("done").unwrap().as_bool().unwrap(),
			info: state.find("info").unwrap().clone()
		})
	}
	pub fn monitor_start(&mut self, directory: String, force: bool, resume: bool) -> GymResult<()> {
		let mut req = BTreeMap::new();
		req.insert("directory", Value::String(directory));
		req.insert("force", Value::Bool(force));
		req.insert("resume", Value::Bool(resume));

		let path = "/v1/envs/".to_string() + &self.instance_id + "/monitor/start/";
		try!(self.client.post(path, req.to_json()));
		Ok(())
	}
	pub fn monitor_stop(&mut self) -> GymResult<()> {
		let path = "/v1/envs/".to_string() + &self.instance_id + "/monitor/close/";
		try!(self.client.post(path, Value::Null));
		Ok(())
	}
	pub fn upload(&mut self, training_dir: String, api_key: String, algorithm_id: String) -> GymResult<()> {
		let mut req = BTreeMap::new();
		req.insert("training_dir", training_dir);
		req.insert("api_key", api_key);
		req.insert("algorithm_id", algorithm_id);

		try!(self.client.post("/v1/upload/".to_string(), req.to_json()));
		Ok(())
	}
}

pub struct GymClient {
	address:	String,
	handle:		Client,
	headers:	Headers,
}

impl GymClient {
    pub fn new(addr: String) -> GymClient {
		let mut headers = Headers::new();
		headers.set_raw("Content-Type", vec![b"application/json".to_vec()]);

    	GymClient {
    		address: addr,
    		handle: Client::new(),
    		headers: headers
    	}
    }
    pub fn make(mut self, env_id: &str) -> GymResult<Environment> {
    	let mut req: BTreeMap<&str, &str> = BTreeMap::new();
    	req.insert("env_id", env_id);

    	let instance_id = try!(self.post("/v1/envs/".to_string(), req.to_json()));
    	let instance_id = match instance_id.find("instance_id") {
    		Some(id) => id.as_str().unwrap(),
    		None => panic!("Unrecognized environment id: {}", env_id)
    	};

    	let obs_space = try!(self.get("/v1/envs/".to_string() + instance_id + "/observation_space/"));
    	let act_space = try!(self.get("/v1/envs/".to_string() + instance_id + "/action_space/"));

    	Ok(Environment {
    		client: self,
    		instance_id: instance_id.to_string(),
    		act_space: Space::from_json(act_space.find("info").unwrap()),
    		obs_space: Space::from_json(obs_space.find("info").unwrap())})
    }

    fn post(&mut self, route: String, request: Value) -> GymResult<Value> {
    	let url = self.address.clone() + &route;
    	let mut resp = try!(self.handle.post(&url)
    							  	   .body(&request.to_string())
    							  	   .headers(self.headers.clone())
    							  	   .send());

    	let mut json = String::new();
    	let _ = resp.read_to_string(&mut json);

	    Ok(serde_json::from_str(&json).unwrap_or(Value::Null))
    }
    fn get(&mut self, route: String) -> GymResult<Value> {
    	let url = self.address.clone() + &route;
    	let mut resp = try!(self.handle.get(&url)
    							  	   .send());
    	let mut json = String::new();
    	let _ = resp.read_to_string(&mut json);

		Ok(serde_json::from_str(&json).unwrap_or(Value::Null))
    }
}<|endoftext|>