<commit_before>/*!
    An example that shows how to handle custom clipboard operations

    Requires the following features: `cargo run --example clipboard --features "textbox listbox menu cursor clipboard"`
*/

extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;

use nwd::NwgUi;
use nwg::NativeUi;

#[derive(Default, NwgUi)]
pub struct ClipboardCustom {
    #[nwg_control(size: (400, 300), position: (300, 300), title: "Clipboard Handling")]
    #[nwg_events( OnWindowClose: [nwg::stop_thread_dispatch()] )]
    window: nwg::Window,

    grid: nwg::GridLayout,

    #[nwg_control(text:"Hello\r\nWorld\r\nClipboad\r\nExample", flags: "VISIBLE|AUTOVSCROLL|AUTOHSCROLL", focus: true,)]
    #[nwg_layout_item(layout: grid, row: 0, col: 0)]
    sample_text: nwg::TextBox,

    #[nwg_control]
    #[nwg_events(MousePressRightUp: [ClipboardCustom::show_menu])]
    #[nwg_layout_item(layout: grid, col: 1, row: 0)]
    listbox: nwg::ListBox<String>,

    #[nwg_control(popup: true)]
    listbox_menu: nwg::Menu,

    #[nwg_control(parent: listbox_menu, text: "Paste Items")]
    #[nwg_events(OnMenuItemSelected: [ClipboardCustom::paste_items])]
    listbox_menu_paste: nwg::MenuItem,

    #[nwg_control(parent: listbox_menu, text: "Copy Items")]
    #[nwg_events(OnMenuItemSelected: [ClipboardCustom::copy_items])]
    listbox_menu_copy: nwg::MenuItem,
}

impl ClipboardCustom {

    fn show_menu(&self) {
        let (x, y) = nwg::GlobalCursor::position();
        self.listbox_menu.popup(x, y)
    }

    fn paste_items(&self) {
        self.listbox.clear();

        if let Some(text) = nwg::Clipboard::data_text(&self.window) {
            for line in text.split("\r\n") {
                self.listbox.push(line.into());
            }
        }
    }

    fn copy_items(&self) {
        let mut copy_data = String::with_capacity(30);
        let col = self.listbox.collection();
        for item in col.iter() {
            copy_data.push_str(&item);
            copy_data.push_str("\r\n");
        }

        nwg::Clipboard::set_data_text(&self.window, &copy_data);
    }

}

fn main() {
    nwg::init().expect("Failed to init Native Windows GUI");
    nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font");
    let _app = ClipboardCustom::build_ui(Default::default()).expect("Failed to build UI");
    nwg::dispatch_thread_events();
}

<commit_msg>oops v3<commit_after>/*!
    An example that shows how to handle custom clipboard operations

    Requires the following features: `cargo run --example clipboard --features "textbox listbox menu cursor clipboard"`
*/

extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;

use nwd::NwgUi;
use nwg::NativeUi;

#[derive(Default, NwgUi)]
pub struct ClipboardCustom {
    #[nwg_control(size: (400, 300), position: (300, 300), title: "Clipboard Handling")]
    #[nwg_events( OnWindowClose: [nwg::stop_thread_dispatch()] )]
    window: nwg::Window,

    #[nwg_layout(parent: window)]
    grid: nwg::GridLayout,

    #[nwg_control(text:"Hello\r\nWorld\r\nClipboad\r\nExample", flags: "VISIBLE|AUTOVSCROLL|AUTOHSCROLL", focus: true,)]
    #[nwg_layout_item(layout: grid, row: 0, col: 0)]
    sample_text: nwg::TextBox,

    #[nwg_control]
    #[nwg_events(MousePressRightUp: [ClipboardCustom::show_menu])]
    #[nwg_layout_item(layout: grid, col: 1, row: 0)]
    listbox: nwg::ListBox<String>,

    #[nwg_control(popup: true)]
    listbox_menu: nwg::Menu,

    #[nwg_control(parent: listbox_menu, text: "Paste Items")]
    #[nwg_events(OnMenuItemSelected: [ClipboardCustom::paste_items])]
    listbox_menu_paste: nwg::MenuItem,

    #[nwg_control(parent: listbox_menu, text: "Copy Items")]
    #[nwg_events(OnMenuItemSelected: [ClipboardCustom::copy_items])]
    listbox_menu_copy: nwg::MenuItem,
}

impl ClipboardCustom {

    fn show_menu(&self) {
        let (x, y) = nwg::GlobalCursor::position();
        self.listbox_menu.popup(x, y)
    }

    fn paste_items(&self) {
        self.listbox.clear();

        if let Some(text) = nwg::Clipboard::data_text(&self.window) {
            for line in text.split("\r\n") {
                self.listbox.push(line.into());
            }
        }
    }

    fn copy_items(&self) {
        let mut copy_data = String::with_capacity(30);
        let col = self.listbox.collection();
        for item in col.iter() {
            copy_data.push_str(&item);
            copy_data.push_str("\r\n");
        }

        nwg::Clipboard::set_data_text(&self.window, &copy_data);
    }

}

fn main() {
    nwg::init().expect("Failed to init Native Windows GUI");
    nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font");
    let _app = ClipboardCustom::build_ui(Default::default()).expect("Failed to build UI");
    nwg::dispatch_thread_events();
}

<|endoftext|>


<commit_before>/* Copyright 2017 David Li.

 * This file is part of BigRedRPG.

 * BigRedRPG is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.

 * BigRedRPG is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU Affero General Public License
 * along with BigRedRPG.  If not, see <http://www.gnu.org/licenses/>.
 */

use std::collections::{BinaryHeap, HashMap, HashSet};

use student::{Student, StudentId};

pub struct Location {
    pub name: String,
    pub id: LocationId,

    pub students: Vec<Student>,
}

#[derive(Copy,Clone,Debug,Eq,Hash,PartialEq)]
pub struct LocationId(i32);

impl Location {
    pub fn new<S: Into<String>>(name: S, id: LocationId) -> Location {
        Location {
            name: name.into(),
            id: id,

            students: Vec::new(),
        }
    }

    pub fn add_student(&mut self, student: Student) {
        self.students.push(student);
    }

    pub fn remove_student_by_id(&mut self, id: StudentId) -> Student {
        let mut idx = None;
        for (index, student) in self.students.iter().enumerate() {
            if student.id == id {
                idx = Some(index);
            }
        }

        self.students.remove(idx.expect(&format!("Could not remove student {}", id)))
    }
}

pub struct LocationIdGenerator(i32);

impl LocationIdGenerator {
    pub fn new_from_index(index: i32) -> LocationIdGenerator {
        LocationIdGenerator(index)
    }

    pub fn new_id(&mut self) -> LocationId {
        let id = LocationId(self.0);
        self.0 += 1;

        id
    }
}

pub struct Map {
    locations: HashMap<LocationId, Location>,
    junctions: HashMap<LocationId, Vec<LocationId>>,
}

impl Map {
    pub fn new() -> Map {
        Map {
            locations: HashMap::new(),
            junctions: HashMap::new(),
        }
    }

    pub fn add(&mut self, location: Location) -> LocationId {
        let id = location.id;
        self.locations.insert(id, location);
        self.junctions.insert(id, Vec::new());

        id
    }

    pub fn add_junction(&mut self, location1: LocationId, location2: LocationId) {
        self.junctions.get_mut(&location1).unwrap().push(location2);
        self.junctions.get_mut(&location2).unwrap().push(location1);
    }

    pub fn get(&self, id: LocationId) -> Option<&Location> {
        self.locations.get(&id)
    }

    pub fn get_mut(&mut self, id: LocationId) -> Option<&mut Location> {
        self.locations.get_mut(&id)
    }

    pub fn iter(&self) -> ::std::collections::hash_map::Iter<LocationId, Location> {
        self.locations.iter()
    }

    pub fn iter_mut(&mut self) -> ::std::collections::hash_map::IterMut<LocationId, Location> {
        self.locations.iter_mut()
    }

    pub fn find_path(&self, start: LocationId, end: LocationId) -> Option<Vec<LocationId>> {
        // https://en.wikipedia.org/wiki/Dijkstra's_algorithm#Pseudocode
        use std::cmp::Ordering;

        #[derive(Clone,Copy,Eq,PartialEq)]
        struct State {
            location: LocationId,
            cost: usize,
        }

        impl PartialOrd for State {
            fn partial_cmp(&self, other: &State) -> Option<Ordering> {
                Some(self.cmp(other))
            }
        }

        impl Ord for State {
            fn cmp(&self, other: &State) -> Ordering {
                // Reverse the comparison order in order to use the
                // stdlib max-heap as a min-heap
                other.cost.cmp(&self.cost)
            }
        }

        let inf = self.locations.len() + 1;

        let mut dist = HashMap::new();
        let mut prev = HashMap::new();
        let mut seen = HashSet::new();
        dist.insert(start, inf);

        let mut heap = BinaryHeap::new();
        heap.push(State { location: start, cost: 0 });

        while let Some(State { location, cost }) = heap.pop() {
            if seen.contains(&location) {
                continue;
            }
            seen.insert(location);

            if location == end {
                let mut path = vec![location];
                let mut cur = location;
                while let Some(node) = prev.get(&cur) {
                    path.push(*node);
                    cur = *node;
                }
                return Some(path)
            }

            // If we've found a better way already, skip
            if cost > *dist.get(&location).unwrap_or(&inf) {
                continue;
            }

            for adjacent in self.junctions[&location].iter() {
                if seen.contains(adjacent) {
                    continue;
                }

                let next = State { location: *adjacent, cost: cost + 1 };

                if next.cost < *dist.get(&adjacent).unwrap_or(&inf) {
                    heap.push(next);
                    dist.insert(*adjacent, next.cost);
                    prev.insert(*adjacent, location);
                }
            }
        }

        None
    }
}
<commit_msg>feat(Location): fix pathfinding<commit_after>/* Copyright 2017 David Li.

 * This file is part of BigRedRPG.

 * BigRedRPG is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.

 * BigRedRPG is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU Affero General Public License
 * along with BigRedRPG.  If not, see <http://www.gnu.org/licenses/>.
 */

use std::collections::{BinaryHeap, HashMap, HashSet};

use student::{Student, StudentId};

pub struct Location {
    pub name: String,
    pub id: LocationId,

    pub students: Vec<Student>,
}

#[derive(Copy,Clone,Debug,Eq,Hash,PartialEq)]
pub struct LocationId(i32);

impl Location {
    pub fn new<S: Into<String>>(name: S, id: LocationId) -> Location {
        Location {
            name: name.into(),
            id: id,

            students: Vec::new(),
        }
    }

    pub fn add_student(&mut self, student: Student) {
        self.students.push(student);
    }

    pub fn remove_student_by_id(&mut self, id: StudentId) -> Student {
        let mut idx = None;
        for (index, student) in self.students.iter().enumerate() {
            if student.id == id {
                idx = Some(index);
            }
        }

        self.students.remove(idx.expect(&format!("Could not remove student {}", id)))
    }
}

pub struct LocationIdGenerator(i32);

impl LocationIdGenerator {
    pub fn new_from_index(index: i32) -> LocationIdGenerator {
        LocationIdGenerator(index)
    }

    pub fn new_id(&mut self) -> LocationId {
        let id = LocationId(self.0);
        self.0 += 1;

        id
    }
}

pub struct Map {
    locations: HashMap<LocationId, Location>,
    junctions: HashMap<LocationId, Vec<LocationId>>,
}

impl Map {
    pub fn new() -> Map {
        Map {
            locations: HashMap::new(),
            junctions: HashMap::new(),
        }
    }

    pub fn add(&mut self, location: Location) -> LocationId {
        let id = location.id;
        self.locations.insert(id, location);
        self.junctions.insert(id, Vec::new());

        id
    }

    pub fn add_junction(&mut self, location1: LocationId, location2: LocationId) {
        self.junctions.get_mut(&location1).unwrap().push(location2);
        self.junctions.get_mut(&location2).unwrap().push(location1);
    }

    pub fn get(&self, id: LocationId) -> Option<&Location> {
        self.locations.get(&id)
    }

    pub fn get_mut(&mut self, id: LocationId) -> Option<&mut Location> {
        self.locations.get_mut(&id)
    }

    pub fn iter(&self) -> ::std::collections::hash_map::Iter<LocationId, Location> {
        self.locations.iter()
    }

    pub fn iter_mut(&mut self) -> ::std::collections::hash_map::IterMut<LocationId, Location> {
        self.locations.iter_mut()
    }

    pub fn find_path(&self, start: LocationId, end: LocationId) -> Option<Vec<LocationId>> {
        // https://en.wikipedia.org/wiki/Dijkstra's_algorithm#Pseudocode
        use std::cmp::Ordering;

        #[derive(Clone,Copy,Eq,PartialEq)]
        struct State {
            location: LocationId,
            cost: usize,
        }

        impl PartialOrd for State {
            fn partial_cmp(&self, other: &State) -> Option<Ordering> {
                Some(self.cmp(other))
            }
        }

        impl Ord for State {
            fn cmp(&self, other: &State) -> Ordering {
                // Reverse the comparison order in order to use the
                // stdlib max-heap as a min-heap
                other.cost.cmp(&self.cost)
            }
        }

        let inf = self.locations.len() + 1;

        let mut dist = HashMap::new();
        let mut prev = HashMap::new();
        let mut seen = HashSet::new();
        dist.insert(start, inf);

        let mut heap = BinaryHeap::new();
        heap.push(State { location: start, cost: 0 });

        while let Some(State { location, cost }) = heap.pop() {
            if seen.contains(&location) {
                continue;
            }
            seen.insert(location);

            if location == end {
                let mut path = vec![location];
                let mut cur = location;
                while let Some(node) = prev.get(&cur) {
                    if *node != start {
                        path.push(*node);
                    }
                    cur = *node;
                }
                path.reverse();
                return Some(path)
            }

            // If we've found a better way already, skip
            if cost > *dist.get(&location).unwrap_or(&inf) {
                continue;
            }

            for adjacent in self.junctions[&location].iter() {
                if seen.contains(adjacent) {
                    continue;
                }

                let next = State { location: *adjacent, cost: cost + 1 };

                if next.cost < *dist.get(&adjacent).unwrap_or(&inf) {
                    heap.push(next);
                    dist.insert(*adjacent, next.cost);
                    prev.insert(*adjacent, location);
                }
            }
        }

        None
    }
}
<|endoftext|>


<commit_before>use std::iter::Iterator;

use self::SequenceItem::{Number, Range, Wildcard};

/// This represents an individual item in the list of requested message ids
/// passed by the client
/// The client can pass a number representing a single id, a wildcard
/// (represented by *) or a range which is made up of a start non-range sequence
/// item and an end non-range sequence item separated by a colon
/// A range represents all items with ids between its start and end, inclusive.
#[derive(Clone, PartialEq, Debug)]
pub enum SequenceItem {
    Number(usize),
    Range(Box<SequenceItem>, Box<SequenceItem>),
    Wildcard
}

fn parse_item(item: &str) -> Option<SequenceItem> {
    let intseq_opt = item.parse();
    match intseq_opt {
        Ok(intseq) => {
            // item is a valid number so return that
            Some(Number(intseq))
        }
        Err(_) => {
            // item is not a valid number
            // If it is the wildcard value return that
            // Otherwise, return no sequence item
            if item == "*" {
                Some(Wildcard)
            } else {
                None
            }
        }
    }
}

/// Given a string as passed in from the client, create a list of sequence items
/// If the string does not represent a valid list, return None
pub fn parse(sequence_string: &str) -> Option<Vec<SequenceItem>> {
    let sequences = sequence_string.split(',');
    let mut sequence_set = Vec::new();
    for sequence in sequences {
        let mut range = sequence.split(':');
        let start = match range.next() {
            None => return None,
            Some(seq) => {
                match parse_item(seq) {
                    None => return None,
                    Some(item) => item
                }
            }
        };
        let stop = match range.next() {
            None => {
                // Nothing after ':'
                // Add the number or wildcard and bail out
                sequence_set.push(start);
                continue;
            }
            Some(seq) => {
                match parse_item(seq) {
                    None => return None,
                    Some(item) => item
                }
            }
        };

        // A valid range only has one colon
        if range.next().is_some() {
            return None;
        }

        sequence_set.push(Range(Box::new(start), Box::new(stop)));
    }
    Some(sequence_set)
}

/// Create the list of unsigned integers representing valid ids from a list of
/// sequence items. Ideally this would handle wildcards in O(1) rather than O(n)
pub fn iterator(sequence_set: &[SequenceItem], max_id: usize) -> Vec<usize> {
    // If the number of possible messages is 0, we return an empty vec.
    if max_id == 0 { return Vec::new() }

    let stop = max_id + 1;

    let mut items = Vec::new();
    for item in sequence_set.iter() {
        match *item {
            // For a number we just need the value
            Number(num) => { items.push(num) },
            // For a range we need all the values inside it
            Range(ref a, ref b) => {
                // Grab the start of the range
                let a = match **a {
                    Number(num) => { num },
                    Wildcard => { max_id }
                    Range(_, _) => {
                        error!("A range of ranges is invalid.");
                        continue;
                    }
                };
                // Grab the end of the range
                let b = match **b {
                    Number(num) => { num },
                    Wildcard => { max_id }
                    Range(_, _) => {
                        error!("A range of ranges is invalid.");
                        continue;
                    }
                };
                // Figure out which way the range points
                let (mut min, mut max) = if a <= b {
                    (a, b)
                } else {
                    (b, a)
                };

                // Bounds checks
                if min > stop { min = stop; }
                if max > stop { max = stop; }

                // Generate the list of values between the min and max
                let seq_range: Vec<usize> = (min..max + 1).collect();
                items.extend(seq_range.iter());
            },
            Wildcard => {
                // If the sequence set contains the wildcard operator, it spans
                // the entire possible range of messages.
                return (1..stop).collect()
            }
        }
    }

    // Sort and remove duplicates.
    items.sort();
    items.dedup();
    // Remove all elements that are greater than the maximum.
    let items: Vec<usize> = items.into_iter().filter(|&x| x <= max_id).collect();
    items
}

pub fn uid_iterator(sequence_set: &[SequenceItem]) -> Vec<usize> {
    let mut items = Vec::new();
    for item in sequence_set.iter() {
        match *item {
            Number(num) => { items.push(num) },
            Range(ref a, ref b) => {
                let a = match **a {
                    Number(num) => { num },
                    Wildcard => { return Vec::new() }
                    Range(_, _) => {
                        error!("A range of ranges is invalid.");
                        continue;
                    }
                };
                let b = match **b {
                    Number(num) => { num },
                    Wildcard => { return Vec::new() }
                    Range(_, _) => {
                        error!("A range of ranges is invalid.");
                        continue;
                    }
                };
                let (min, max) = if a <= b {
                    (a, b)
                } else {
                    (b, a)
                };
                //if min > stop { min = stop; }
                //if max > stop { max = stop; }
                let seq_range: Vec<usize> = (min..max + 1).collect();
                items.extend(seq_range.iter());
            },
            Wildcard => {
                return Vec::new()
            }
        }
    }

    // Sort and remove duplicates.
    items.sort();
    items.dedup();
    // Remove all elements that are greater than the maximum.
    //let items: Vec<usize> = items.into_iter().filter(|&x| x <= max_id).collect();
    items
}

#[test]
fn test_sequence_num() {
    assert_eq!(iterator(&[Number(4324)], 5000), vec![4324]);
    assert_eq!(iterator(&[Number(23), Number(44)], 5000), vec![23, 44]);
    assert_eq!(iterator(&[Number(6), Number(6), Number(2)], 5000), vec![2, 6]);
}

#[test]
fn test_sequence_past_end() {
    assert_eq!(iterator(&[Number(4324)], 100), Vec::new());
    assert_eq!(iterator(&[Number(23), Number(44)], 30), vec![23]);
    assert_eq!(iterator(&[Number(6), Number(6), Number(2)], 4), vec![2]);
}

#[test]
fn test_sequence_range() {
    assert_eq!(iterator(&[Range(Box::new(Number(6)), Box::new(Wildcard))], 10), vec![6, 7, 8, 9, 10]);
    assert_eq!(iterator(&[Range(Box::new(Number(1)), Box::new(Number(10)))], 4), vec![1, 2, 3, 4]);
    assert_eq!(iterator(&[Range(Box::new(Wildcard), Box::new(Number(8))), Number(9), Number(2), Number(2)], 12), vec![2, 8, 9, 10, 11, 12]);
}

#[test]
fn test_sequence_wildcard() {
    assert_eq!(iterator(&[Range(Box::new(Number(10)), Box::new(Wildcard)), Wildcard], 6), vec![1, 2, 3, 4, 5, 6]);
    assert_eq!(iterator(&[Wildcard, Number(8)], 3), vec![1, 2, 3]);
}

#[test]
fn test_sequence_complex() {
    assert_eq!(iterator(
            &[Number(1), Number(3), Range(Box::new(Number(5)), Box::new(Number(7))), Number(9), Number(12), Range(Box::new(Number(15)), Box::new(Wildcard))], 13),
            vec![1, 3, 5, 6, 7, 9, 12, 13]);
}
<commit_msg>fix: add type inference help in test<commit_after>use std::iter::Iterator;

use self::SequenceItem::{Number, Range, Wildcard};

/// This represents an individual item in the list of requested message ids
/// passed by the client
/// The client can pass a number representing a single id, a wildcard
/// (represented by *) or a range which is made up of a start non-range sequence
/// item and an end non-range sequence item separated by a colon
/// A range represents all items with ids between its start and end, inclusive.
#[derive(Clone, PartialEq, Debug)]
pub enum SequenceItem {
    Number(usize),
    Range(Box<SequenceItem>, Box<SequenceItem>),
    Wildcard
}

fn parse_item(item: &str) -> Option<SequenceItem> {
    let intseq_opt = item.parse();
    match intseq_opt {
        Ok(intseq) => {
            // item is a valid number so return that
            Some(Number(intseq))
        }
        Err(_) => {
            // item is not a valid number
            // If it is the wildcard value return that
            // Otherwise, return no sequence item
            if item == "*" {
                Some(Wildcard)
            } else {
                None
            }
        }
    }
}

/// Given a string as passed in from the client, create a list of sequence items
/// If the string does not represent a valid list, return None
pub fn parse(sequence_string: &str) -> Option<Vec<SequenceItem>> {
    let sequences = sequence_string.split(',');
    let mut sequence_set = Vec::new();
    for sequence in sequences {
        let mut range = sequence.split(':');
        let start = match range.next() {
            None => return None,
            Some(seq) => {
                match parse_item(seq) {
                    None => return None,
                    Some(item) => item
                }
            }
        };
        let stop = match range.next() {
            None => {
                // Nothing after ':'
                // Add the number or wildcard and bail out
                sequence_set.push(start);
                continue;
            }
            Some(seq) => {
                match parse_item(seq) {
                    None => return None,
                    Some(item) => item
                }
            }
        };

        // A valid range only has one colon
        if range.next().is_some() {
            return None;
        }

        sequence_set.push(Range(Box::new(start), Box::new(stop)));
    }
    Some(sequence_set)
}

/// Create the list of unsigned integers representing valid ids from a list of
/// sequence items. Ideally this would handle wildcards in O(1) rather than O(n)
pub fn iterator(sequence_set: &[SequenceItem], max_id: usize) -> Vec<usize> {
    // If the number of possible messages is 0, we return an empty vec.
    if max_id == 0 { return Vec::new() }

    let stop = max_id + 1;

    let mut items = Vec::new();
    for item in sequence_set.iter() {
        match *item {
            // For a number we just need the value
            Number(num) => { items.push(num) },
            // For a range we need all the values inside it
            Range(ref a, ref b) => {
                // Grab the start of the range
                let a = match **a {
                    Number(num) => { num },
                    Wildcard => { max_id }
                    Range(_, _) => {
                        error!("A range of ranges is invalid.");
                        continue;
                    }
                };
                // Grab the end of the range
                let b = match **b {
                    Number(num) => { num },
                    Wildcard => { max_id }
                    Range(_, _) => {
                        error!("A range of ranges is invalid.");
                        continue;
                    }
                };
                // Figure out which way the range points
                let (mut min, mut max) = if a <= b {
                    (a, b)
                } else {
                    (b, a)
                };

                // Bounds checks
                if min > stop { min = stop; }
                if max > stop { max = stop; }

                // Generate the list of values between the min and max
                let seq_range: Vec<usize> = (min..max + 1).collect();
                items.extend(seq_range.iter());
            },
            Wildcard => {
                // If the sequence set contains the wildcard operator, it spans
                // the entire possible range of messages.
                return (1..stop).collect()
            }
        }
    }

    // Sort and remove duplicates.
    items.sort();
    items.dedup();
    // Remove all elements that are greater than the maximum.
    let items: Vec<usize> = items.into_iter().filter(|&x| x <= max_id).collect();
    items
}

pub fn uid_iterator(sequence_set: &[SequenceItem]) -> Vec<usize> {
    let mut items = Vec::new();
    for item in sequence_set.iter() {
        match *item {
            Number(num) => { items.push(num) },
            Range(ref a, ref b) => {
                let a = match **a {
                    Number(num) => { num },
                    Wildcard => { return Vec::new() }
                    Range(_, _) => {
                        error!("A range of ranges is invalid.");
                        continue;
                    }
                };
                let b = match **b {
                    Number(num) => { num },
                    Wildcard => { return Vec::new() }
                    Range(_, _) => {
                        error!("A range of ranges is invalid.");
                        continue;
                    }
                };
                let (min, max) = if a <= b {
                    (a, b)
                } else {
                    (b, a)
                };
                //if min > stop { min = stop; }
                //if max > stop { max = stop; }
                let seq_range: Vec<usize> = (min..max + 1).collect();
                items.extend(seq_range.iter());
            },
            Wildcard => {
                return Vec::new()
            }
        }
    }

    // Sort and remove duplicates.
    items.sort();
    items.dedup();
    // Remove all elements that are greater than the maximum.
    //let items: Vec<usize> = items.into_iter().filter(|&x| x <= max_id).collect();
    items
}

#[test]
fn test_sequence_num() {
    assert_eq!(iterator(&[Number(4324)], 5000), vec![4324]);
    assert_eq!(iterator(&[Number(23), Number(44)], 5000), vec![23, 44]);
    assert_eq!(iterator(&[Number(6), Number(6), Number(2)], 5000), vec![2, 6]);
}

#[test]
fn test_sequence_past_end() {
    // Needed to help rust infer the type for the empty vec.
    let empty_vec: Vec<usize> = Vec::new();

    assert_eq!(iterator(&[Number(4324)], 100), empty_vec);
    assert_eq!(iterator(&[Number(23), Number(44)], 30), vec![23]);
    assert_eq!(iterator(&[Number(6), Number(6), Number(2)], 4), vec![2]);
}

#[test]
fn test_sequence_range() {
    assert_eq!(iterator(&[Range(Box::new(Number(6)), Box::new(Wildcard))], 10), vec![6, 7, 8, 9, 10]);
    assert_eq!(iterator(&[Range(Box::new(Number(1)), Box::new(Number(10)))], 4), vec![1, 2, 3, 4]);
    assert_eq!(iterator(&[Range(Box::new(Wildcard), Box::new(Number(8))), Number(9), Number(2), Number(2)], 12), vec![2, 8, 9, 10, 11, 12]);
}

#[test]
fn test_sequence_wildcard() {
    assert_eq!(iterator(&[Range(Box::new(Number(10)), Box::new(Wildcard)), Wildcard], 6), vec![1, 2, 3, 4, 5, 6]);
    assert_eq!(iterator(&[Wildcard, Number(8)], 3), vec![1, 2, 3]);
}

#[test]
fn test_sequence_complex() {
    assert_eq!(iterator(
            &[Number(1), Number(3), Range(Box::new(Number(5)), Box::new(Number(7))), Number(9), Number(12), Range(Box::new(Number(15)), Box::new(Wildcard))], 13),
            vec![1, 3, 5, 6, 7, 9, 12, 13]);
}
<|endoftext|>


<commit_before>extern crate poke_a_mango;
extern crate cursive;

use std::io::stderr;
use std::process::exit;
use cursive::Cursive;

fn main() {
    let result = actual_main();
    exit(result);
}

fn actual_main() -> i32 {
    if let Err(err) = result_main() {
        err.print_error(&mut stderr());
        err.exit_value()
    } else {
        0
    }
}

fn result_main() -> Result<(), poke_a_mango::Error> {
    let opts = poke_a_mango::Options::parse();
    println!("{:?}", opts);

    let mut ui = Cursive::new();
    ui.set_fps(60);

    ui.add_global_callback('q', Cursive::quit);

    ui.run();

    Ok(())
}
<commit_msg>Basic UI framework<commit_after>extern crate poke_a_mango;
extern crate cursive;

use std::io::stderr;
use cursive::Cursive;
use std::process::exit;
use cursive::views::{LinearLayout, Button};

fn main() {
    let result = actual_main();
    exit(result);
}

fn actual_main() -> i32 {
    if let Err(err) = result_main() {
        err.print_error(&mut stderr());
        err.exit_value()
    } else {
        0
    }
}

fn result_main() -> Result<(), poke_a_mango::Error> {
    let opts = poke_a_mango::Options::parse();

    let mut ui = Cursive::new();
    ui.set_fps(60);

    let main_menu_screen = ui.add_screen();
    let choose_difficulty_screen = ui.add_screen();
    let highscores_screen = ui.add_screen();

    ui.set_screen(highscores_screen);
    // TODO: load the leaderboard
    ui.add_layer(LinearLayout::vertical().child(Button::new("Back", move |ui| ui.set_screen(main_menu_screen))));

    ui.set_screen(choose_difficulty_screen);
    // TODO: difficulty selection
    ui.add_layer(LinearLayout::vertical().child(Button::new("Back", move |ui| ui.set_screen(main_menu_screen))));

    ui.set_screen(main_menu_screen);
    ui.add_layer(LinearLayout::vertical()
        .child(Button::new("Start game", move |ui| ui.set_screen(choose_difficulty_screen)))
        .child(Button::new("Highscores", move |ui| ui.set_screen(highscores_screen)))
        .child(Button::new("Exit", Cursive::quit)));

    ui.run();

    Ok(())
}
<|endoftext|>


<commit_before>extern crate bencode;

use self::bencode::{FromBencode, Bencode, StringFromBencodeError};
use self::bencode::util::ByteString;
use std::fs::File;
use std::io::Read;
use std::io;

#[derive(PartialEq, Debug)]
struct Metainfo {
    announce: String,
    created_by: String,
}

#[derive(Debug)]
enum MyError {
    NotADict,
    DoesntContain(&'static str),
    ANotAString(StringFromBencodeError),
}

impl FromBencode for Metainfo {
    type Err = MyError;

    fn from_bencode(bencode: &bencode::Bencode) -> Result<Metainfo, MyError> {
        match bencode {
            &Bencode::Dict(ref m) => {
                let announce = try!(match m.get(&ByteString::from_str("announce")) {
                    Some(a) => FromBencode::from_bencode(a).map_err(MyError::ANotAString),
                    None => Err(MyError::DoesntContain("announce"))
                });

                let created_by = try!(match m.get(&ByteString::from_str("created by")) {
                    Some(a) => FromBencode::from_bencode(a).map_err(MyError::ANotAString),
                    None => Ok("".to_string())
                });

                Ok(Metainfo{ announce: announce, created_by: created_by })
            }
            _ => Err(MyError::NotADict)
        }
    }
}

pub fn run() {
    let result = parse_torrent_file("test_data/flagfromserver.torrent");
    match result {
        Ok(s)  => println!("Yay, it worked: {:?}", s),
        Err(e) => println!("Oops, it failed: {}", e)
    }
}

fn parse_torrent_file(filename: &str) -> Result<Metainfo, io::Error> {
    // read the torrent file into a byte vector
    let mut f = try!(File::open(filename));
    let mut v = Vec::new();
    try!(f.read_to_end(&mut v));

    // decode the byte vector into a struct
    let bencode = bencode::from_vec(v).unwrap();
    let result = FromBencode::from_bencode(&bencode).unwrap();

    Ok(result)
}
<commit_msg>Added auto-conversion from StringFromBencodeError to MetainfoError, to clean up the code.<commit_after>extern crate bencode;

use self::bencode::{FromBencode, Bencode, StringFromBencodeError};
use self::bencode::util::ByteString;
use std::fs::File;
use std::io::Read;
use std::{convert, io};

#[derive(PartialEq, Debug)]
struct Metainfo {
    announce: String,
    created_by: String,
}

#[derive(Debug)]
enum MetainfoError {
    NotADict,
    DoesntContain(&'static str),
    NotAString(StringFromBencodeError),
}

impl convert::From<StringFromBencodeError> for MetainfoError {
    fn from(err: StringFromBencodeError) -> MetainfoError {
        MetainfoError::NotAString(err)
    }
}

impl FromBencode for Metainfo {
    type Err = MetainfoError;

    fn from_bencode(bencode: &bencode::Bencode) -> Result<Metainfo, MetainfoError> {
        match bencode {
            &Bencode::Dict(ref m) => {
                let announce = match m.get(&ByteString::from_str("announce")) {
                    Some(a) => try!(FromBencode::from_bencode(a)),
                    None => return Err(MetainfoError::DoesntContain("announce"))
                };

                let created_by = match m.get(&ByteString::from_str("created by")) {
                    Some(a) => try!(FromBencode::from_bencode(a)),
                    None => "".to_string()
                };

                Ok(Metainfo{ announce: announce, created_by: created_by })
            }
            _ => Err(MetainfoError::NotADict)
        }
    }
}

pub fn run() {
    let result = parse_torrent_file("test_data/flagfromserver.torrent");
    match result {
        Ok(s)  => println!("Yay, it worked: {:?}", s),
        Err(e) => println!("Oops, it failed: {}", e)
    }
}

fn parse_torrent_file(filename: &str) -> Result<Metainfo, io::Error> {
    // read the torrent file into a byte vector
    let mut f = try!(File::open(filename));
    let mut v = Vec::new();
    try!(f.read_to_end(&mut v));

    // decode the byte vector into a struct
    let bencode = bencode::from_vec(v).unwrap();
    let result = FromBencode::from_bencode(&bencode).unwrap();

    Ok(result)
}
<|endoftext|>


<commit_before>#![feature(old_io, std_misc)]
#![deny(unused_mut)]
extern crate zookeeper;

use zookeeper::{Acl, CreateMode, Watcher, WatchedEvent, ZooKeeper};
use zookeeper::perms;

use std::old_io::{Buffer, BufferedReader, Command, Process};
use std::time::Duration;

struct LoggingWatcher;
impl Watcher for LoggingWatcher {
    fn handle(&self, e: &WatchedEvent) {
        println!("{:?}", e)
    }
}

fn start_zk() -> Process {
    match Command::new("java")
            .arg("-jar")
            .arg("zk-test-cluster/target/main.jar")
            .spawn() {
        Ok(p) => p,
        Err(e) => panic!("failed to execute process: {}", e),
    }
}

fn get_connect_string(server: &mut Process) -> String {
    let stdout = server.stdout.take().unwrap();
    let mut reader = BufferedReader::new(stdout);

    let mut connect_string = reader.read_line().unwrap();
    connect_string.pop(); // remove '\n'
    connect_string
}

#[test]
fn simple_integration_test() {

    // Create a test cluster and obtain its connection string
    let mut server = start_zk();
    let connect_string = get_connect_string(&mut server);

    // Connect to the test cluster
    let client = ZooKeeper::connect(connect_string.as_ref(), Duration::seconds(5), LoggingWatcher).unwrap();

    // Do the tests
    let acl1 = vec![Acl{perms: perms::ALL, scheme: "world".to_string(), id: "anyone".to_string()}];
    let create = client.create("/test", vec![8,8], acl1, CreateMode::Ephemeral);

    assert_eq!(create.ok(), Some("/test".to_string()));

    let exists = client.exists("/test", true);

    assert!(exists.is_ok());

    let children = client.get_children("/", true);

    assert!(children.is_ok());

    let mut sorted_children = children.unwrap();
    sorted_children.sort();

    assert_eq!(sorted_children, vec!["test".to_string(), "zookeeper".to_string()]);

    // After closing the client all operations return Err
    client.close();

    let exists = client.exists("/test", true);

    assert!(exists.is_err());

    // Close the server
    server.signal_exit().unwrap();
}
<commit_msg>process lib migrated<commit_after>#![feature(std_misc)]
#![deny(unused_mut)]
extern crate zookeeper;

use zookeeper::{Acl, CreateMode, Watcher, WatchedEvent, ZooKeeper};
use zookeeper::perms;

use std::io::{BufRead, BufReader};
use std::process::{Child, Command, Stdio};
use std::time::Duration;

struct LoggingWatcher;
impl Watcher for LoggingWatcher {
    fn handle(&self, e: &WatchedEvent) {
        println!("{:?}", e)
    }
}

fn start_zk() -> Child {
    match Command::new("java")
            .arg("-jar")
            .arg("zk-test-cluster/target/main.jar")
            .stdout(Stdio::piped())
            .spawn() {
        Ok(p) => p,
        Err(e) => panic!("failed to execute process: {}", e),
    }
}

fn get_connect_string(server: &mut Child) -> String {
    let mut reader = BufReader::new(server.stdout.as_mut().unwrap());

    let mut connect_string = String::new();
    if reader.read_line(&mut connect_string).is_err() {
        panic!("Couldn't read ZK connect_string")
    }
    connect_string.pop(); // remove '\n'
    connect_string
}

#[test]
fn simple_integration_test() {

    // Create a test cluster and obtain its connection string
    let mut server = start_zk();
    let connect_string = get_connect_string(&mut server);

    // Connect to the test cluster
    let client = ZooKeeper::connect(connect_string.as_ref(), Duration::seconds(5), LoggingWatcher).unwrap();

    // Do the tests
    let acl1 = vec![Acl{perms: perms::ALL, scheme: "world".to_string(), id: "anyone".to_string()}];
    let create = client.create("/test", vec![8,8], acl1, CreateMode::Ephemeral);

    assert_eq!(create.ok(), Some("/test".to_string()));

    let exists = client.exists("/test", true);

    assert!(exists.is_ok());

    let children = client.get_children("/", true);

    assert!(children.is_ok());

    let mut sorted_children = children.unwrap();
    sorted_children.sort();

    assert_eq!(sorted_children, vec!["test".to_string(), "zookeeper".to_string()]);

    // After closing the client all operations return Err
    client.close();

    let exists = client.exists("/test", true);

    assert!(exists.is_err());

    // Close the server
    server.kill().unwrap();
}
<|endoftext|>


<commit_before>#[link(name = "date", vers = "1.0", author = "eliovir")];
#[crate_type = "lib"];
#[license = "MIT"];
#[desc = "Library for simple date management" ];
#[comment = "Example of library: date management"];
/**
 * Date management
 *
 * Use "constructor", string manipulation
 * Tested with rust-0.8
 *
 * @author Eliovir <http://github.com/~eliovir>
 * @license MIT license <http://www.opensource.org/licenses/mit-license.php>
 * @since 2013-10-24
 */
use std::from_str::FromStr;

struct Date {
	day: int,
	month: int,
	year: int
}

impl Date {
	pub fn addDays(&mut self, days: int) {
		let mut day = self.day;
		let mut month = self.month;
		let mut year = self.year;
		day = day + days;
		if days > 0 {
			while (day > Date::monthLength(year, month)) {
				day = day - Date::monthLength(year, month);
				month = month + 1;
				if (month > 12) {
					year = year + 1;
					month = 1;
				}
			}
		}
		if day == 0 {
			month = month - 1;
			if (month < 1) {
				month = 12;
				year = year - 1;
			}
			day = Date::monthLength(year, month);
		}
		if days < 0 {
			while (day < 1) {
				month = month - 1;
				if (month < 1) {
					year = year - 1;
					month = 12;
				}
				day = day + Date::monthLength(year, month);
			}
		}
		self.day = day;
		self.month = month;
		self.year = year;
	}

	pub fn isValid(&self) -> bool {
		if self.month < 1 || self.month > 12 {
			false
		} else if self.day < 1 || self.day > Date::monthLength(self.year, self.month) {
			false
		} else {
			true
		}
	}

	/*
	 * Static methods
	 */
	pub fn isLeap(year: int) -> bool {
		(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
	}
	pub fn monthLength(year: int, month: int) -> int {
		match  month {
			1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
			2 => if Date::isLeap(year) { 29 } else { 28 },
			4 | 6 | 9 | 11 => 30,
			_ => fail!("Wrong month")
		}
	}
	pub fn new(year: int, month: int, day: int) -> Date {
		Date{day: day, month: month, year: year}
	}
	pub fn newFromString(string: &str) -> Date {
		if string.len() < 10 {
			fail!("Wrong format!");
		}
		let year = FromStr::from_str(string.slice_chars(0, 4)).unwrap();
		let month = FromStr::from_str(string.slice_chars(5, 7)).unwrap();
		let day = FromStr::from_str(string.slice_chars(8, 10)).unwrap();
		Date{day: day, month: month, year: year}
	}
}

/**
 * Operator overloading
 * @see http://maniagnosis.crsr.net/2013/04/operator-overloading-in-rust.html
 */
impl ToStr for Date {
	fn to_str(&self) -> ~str {
		format!("{:4d}-{:2d}-{:2d}", self.year, self.month, self.day)
	}
}

#[cfg(test)]
mod tests {
	#[test]
	fn addDays() {
		let mut date = ::Date::new(2013, 10, 24);
		let orig = date.to_str();
		let days = 2;
		date.addDays(days);
		let expected="2013-10-26";
		let found=date.to_str();
		assert!(expected==found, format!("Adding {:d} days to {} should return {}, not {}", days, orig, expected, found));
	}
	#[test]
	fn isLeap() {
		assert!(!::Date::isLeap(1900), "1900 is not a leap year");
		assert!(!::Date::isLeap(1901), "1901 is not a leap year");
		assert!(::Date::isLeap(2000), "2000 is leap year");
		assert!(::Date::isLeap(2004), "2004 is leap year");
	}
	#[test]
	fn isValid() {
		let mut date = ::Date::new(2013, 10, 24);
		assert!(date.isValid(), "2013-10-24 is a valid date");
		date = ::Date::new(2013, 02, 29);
		assert!(!date.isValid(), "2013-02-29 isn't a valid date");
		date = ::Date::new(2012, 02, 29);
		assert!(date.isValid(), "2012-02-29 isn't a valid date");
	}
	#[test]
	fn to_str() {
		let date = ::Date::new(2013, 10, 24);
		let expected = "2013-10-24";
		let found = date.to_str();
		assert!(expected == found, format!("{}!={}", expected, found));
	}
	/*
	 * Static methods
	 */
	#[test]
	fn monthLength() {
		assert!(::Date::monthLength(2000, 2) == 29, "February 2000 has 29 days");
		assert!(::Date::monthLength(2001, 2) == 28, "February 2001 has 28 days");
		assert!(::Date::monthLength(2013, 2) == 28, "February 2013 has 28 days");
		assert!(::Date::monthLength(2013, 9) == 30, "September 2013 has 30 days");
		assert!(::Date::monthLength(2013, 10) == 31, "October 2013 has 31 days");
	}
	#[test]
	fn new() {
		let date = ::Date::new(2013, 10, 24);
		let expected = "2013-10-24";
		let found = date.to_str();
		assert!(expected == found, format!("{}!={}", expected, found));
	}
	#[test]
	fn newFromString() {
		let date = ::Date::newFromString("2013-10-24 23:24:34");
		let expected = "2013-10-24";
		let found = date.to_str();
		assert!(expected == found, format!("{}!={}", expected, found));
	}
}
fn main() {
	println("This program must be build and run with --test");
}
<commit_msg>Changes to version 0.9-pre (6879c8b 2013-11-01 23:36:10 -0700)<commit_after>#[link(name = "date", vers = "1.0", author = "eliovir")];
#[crate_type = "lib"];
#[license = "MIT"];
#[desc = "Library for simple date management" ];
#[comment = "Example of library: date management"];
/**
 * Date management
 *
 * Use "constructor", string manipulation
 * Tested with rust-0.9-pre
 *
 * @author Eliovir <http://github.com/~eliovir>
 * @license MIT license <http://www.opensource.org/licenses/mit-license.php>
 * @since 2013-10-24
 */
use std::from_str::FromStr;

struct Date {
	day: int,
	month: int,
	year: int
}

impl Date {
	pub fn addDays(&mut self, days: int) {
		let mut day = self.day;
		let mut month = self.month;
		let mut year = self.year;
		day = day + days;
		if days > 0 {
			while (day > Date::monthLength(year, month)) {
				day = day - Date::monthLength(year, month);
				month = month + 1;
				if (month > 12) {
					year = year + 1;
					month = 1;
				}
			}
		}
		if day == 0 {
			month = month - 1;
			if (month < 1) {
				month = 12;
				year = year - 1;
			}
			day = Date::monthLength(year, month);
		}
		if days < 0 {
			while (day < 1) {
				month = month - 1;
				if (month < 1) {
					year = year - 1;
					month = 12;
				}
				day = day + Date::monthLength(year, month);
			}
		}
		self.day = day;
		self.month = month;
		self.year = year;
	}

	pub fn isValid(&self) -> bool {
		if self.month < 1 || self.month > 12 {
			false
		} else if self.day < 1 || self.day > Date::monthLength(self.year, self.month) {
			false
		} else {
			true
		}
	}

	/*
	 * Static methods
	 */
	pub fn isLeap(year: int) -> bool {
		(year % 4 == 0 && year % 100 != 0) || year % 400 == 0
	}
	pub fn monthLength(year: int, month: int) -> int {
		match  month {
			1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
			2 => if Date::isLeap(year) { 29 } else { 28 },
			4 | 6 | 9 | 11 => 30,
			_ => fail!("Wrong month")
		}
	}
	pub fn new(year: int, month: int, day: int) -> Date {
		Date{day: day, month: month, year: year}
	}
	pub fn newFromString(string: &str) -> Date {
		if string.len() < 10 {
			fail!("Wrong format!");
		}
		let year = FromStr::from_str(string.slice_chars(0, 4)).unwrap();
		let month = FromStr::from_str(string.slice_chars(5, 7)).unwrap();
		let day = FromStr::from_str(string.slice_chars(8, 10)).unwrap();
		Date{day: day, month: month, year: year}
	}
}

/**
 * Operator overloading
 * @see http://maniagnosis.crsr.net/2013/04/operator-overloading-in-rust.html
 */
impl ToStr for Date {
	fn to_str(&self) -> ~str {
		format!("{:4d}-{:2d}-{:2d}", self.year, self.month, self.day)
	}
}

#[cfg(test)]
mod tests {
	#[test]
	fn addDays() {
		let mut date = ::Date::new(2013, 10, 24);
		let orig = date.to_str();
		let days = 2;
		date.addDays(days);
		let expected="2013-10-26";
		let found=date.to_str();
		assert!(expected==found, format!("Adding {:d} days to {} should return {}, not {}", days, orig, expected, found));
	}
	#[test]
	fn isLeap() {
		assert!(!::Date::isLeap(1900), "1900 is not a leap year");
		assert!(!::Date::isLeap(1901), "1901 is not a leap year");
		assert!(::Date::isLeap(2000), "2000 is leap year");
		assert!(::Date::isLeap(2004), "2004 is leap year");
	}
	#[test]
	fn isValid() {
		let mut date = ::Date::new(2013, 10, 24);
		assert!(date.isValid(), "2013-10-24 is a valid date");
		date = ::Date::new(2013, 02, 29);
		assert!(!date.isValid(), "2013-02-29 isn't a valid date");
		date = ::Date::new(2012, 02, 29);
		assert!(date.isValid(), "2012-02-29 isn't a valid date");
	}
	#[test]
	fn to_str() {
		let date = ::Date::new(2013, 10, 24);
		let expected = "2013-10-24";
		let found = date.to_str();
		assert!(expected == found, format!("{}!={}", expected, found));
	}
	/*
	 * Static methods
	 */
	#[test]
	fn monthLength() {
		assert!(::Date::monthLength(2000, 2) == 29, "February 2000 has 29 days");
		assert!(::Date::monthLength(2001, 2) == 28, "February 2001 has 28 days");
		assert!(::Date::monthLength(2013, 2) == 28, "February 2013 has 28 days");
		assert!(::Date::monthLength(2013, 9) == 30, "September 2013 has 30 days");
		assert!(::Date::monthLength(2013, 10) == 31, "October 2013 has 31 days");
	}
	#[test]
	fn new() {
		let date = ::Date::new(2013, 10, 24);
		let expected = "2013-10-24";
		let found = date.to_str();
		assert!(expected == found, format!("{}!={}", expected, found));
	}
	#[test]
	fn newFromString() {
		let date = ::Date::newFromString("2013-10-24 23:24:34");
		let expected = "2013-10-24";
		let found = date.to_str();
		assert!(expected == found, format!("{}!={}", expected, found));
	}
}
fn main() {
	println("This program must be build and run with --test");
}
<|endoftext|>


<commit_before><commit_msg>Prevent panic on XML RPC client connection failure.<commit_after><|endoftext|>


<commit_before>// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// https://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! The Pareto distribution.

use Rng;
use distributions::{Distribution, OpenClosed01};

/// Samples floating-point numbers according to the Pareto distribution
///
/// # Example
/// ```
/// use rand::prelude::*;
/// use rand::distributions::Pareto;
///
/// let val: f64 = SmallRng::from_entropy().sample(Pareto::new(1., 2.));
/// println!("{}", val);
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Pareto {
    scale: f64,
    inv_neg_shape: f64,
}

impl Pareto {
    /// Construct a new Pareto distribution with given `scale` and `shape`.
    ///
    /// In the literature, `scale` is commonly written as xm or k and
    /// `shape` is often written as α.
    ///
    /// # Panics
    ///
    /// `scale` and `shape` have to be non-zero and positive.
    pub fn new(scale: f64, shape: f64) -> Pareto {
        assert!((scale > 0.) & (shape > 0.));
        Pareto { scale, inv_neg_shape: -1.0 / shape }
    }
}

impl Distribution<f64> for Pareto {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
        let u: f64 = rng.sample(OpenClosed01);
        self.scale * u.powf(self.inv_neg_shape)
    }
}

#[cfg(test)]
mod tests {
    use distributions::Distribution;
    use super::Pareto;

    #[test]
    #[should_panic]
    fn invalid() {
        Pareto::new(0., 0.);
    }

    #[test]
    fn sample() {
        let d = Pareto::new(1.0, 2.0);
        let mut rng = ::test::rng(1);
        for _ in 0..1000 {
            d.sample(&mut rng);
        }
    }
}
<commit_msg>Improve Pareto test<commit_after>// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// https://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! The Pareto distribution.

use Rng;
use distributions::{Distribution, OpenClosed01};

/// Samples floating-point numbers according to the Pareto distribution
///
/// # Example
/// ```
/// use rand::prelude::*;
/// use rand::distributions::Pareto;
///
/// let val: f64 = SmallRng::from_entropy().sample(Pareto::new(1., 2.));
/// println!("{}", val);
/// ```
#[derive(Clone, Copy, Debug)]
pub struct Pareto {
    scale: f64,
    inv_neg_shape: f64,
}

impl Pareto {
    /// Construct a new Pareto distribution with given `scale` and `shape`.
    ///
    /// In the literature, `scale` is commonly written as xm or k and
    /// `shape` is often written as α.
    ///
    /// # Panics
    ///
    /// `scale` and `shape` have to be non-zero and positive.
    pub fn new(scale: f64, shape: f64) -> Pareto {
        assert!((scale > 0.) & (shape > 0.));
        Pareto { scale, inv_neg_shape: -1.0 / shape }
    }
}

impl Distribution<f64> for Pareto {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> f64 {
        let u: f64 = rng.sample(OpenClosed01);
        self.scale * u.powf(self.inv_neg_shape)
    }
}

#[cfg(test)]
mod tests {
    use distributions::Distribution;
    use super::Pareto;

    #[test]
    #[should_panic]
    fn invalid() {
        Pareto::new(0., 0.);
    }

    #[test]
    fn sample() {
        let scale = 1.0;
        let shape = 2.0;
        let d = Pareto::new(scale, shape);
        let mut rng = ::test::rng(1);
        for _ in 0..1000 {
            let r = d.sample(&mut rng);
            assert!(r >= scale);
        }
    }
}
<|endoftext|>


<commit_before>use diffgeom::coordinates::{ConversionTo, CoordinateSystem, Point};
use diffgeom::metric::MetricSystem;
use diffgeom::tensors::Vector;
use generic_array::{ArrayLength, GenericArray};
use numeric::StateVector;
use numeric_algs::State;
use std::ops::Mul;
use typenum::consts::{U1, U2, U3};
use typenum::{Exp, Pow, Prod, Same, Unsigned};

pub struct Particle<C: CoordinateSystem>
where
    C::Dimension: Pow<U1>,
    Exp<C::Dimension, U1>: ArrayLength<f64>,
{
    x: Point<C>,
    v: Vector<C>,
}

impl<C: CoordinateSystem> Clone for Particle<C>
where
    C::Dimension: Pow<U1>,
    Exp<C::Dimension, U1>: ArrayLength<f64>,
{
    fn clone(&self) -> Self {
        Particle {
            x: self.x.clone(),
            v: self.v.clone(),
        }
    }
}

impl<C: CoordinateSystem> Particle<C>
where
    C::Dimension: Pow<U1>,
    Exp<C::Dimension, U1>: ArrayLength<f64>,
{
    pub fn new(x: Point<C>, v: Vector<C>) -> Self {
        Particle { x: x, v: v }
    }

    pub fn get_pos(&self) -> &Point<C> {
        &self.x
    }

    pub fn get_vel(&self) -> &Vector<C> {
        &self.v
    }
}

impl<C: CoordinateSystem> State for Particle<C>
where
    C::Dimension: Pow<U1> + Mul<U2> + Unsigned,
    Exp<C::Dimension, U1>: ArrayLength<f64>,
    Prod<C::Dimension, U2>: ArrayLength<f64>,
    <Prod<C::Dimension, U2> as ArrayLength<f64>>::ArrayType: Copy,
{
    type Derivative = StateVector<Prod<C::Dimension, U2>>;

    fn shift_in_place(&mut self, dir: &Self::Derivative, amount: f64) {
        let d = C::Dimension::to_usize();
        for i in 0..d {
            self.x[i] += dir.0[i] * amount;
            self.v[i] += dir.0[i + d] * amount;
            self.v.set_point(self.x.clone());
        }
    }
}

impl<C: CoordinateSystem> Particle<C>
where
    C::Dimension: Pow<U1> + Mul<U2> + Unsigned + Pow<U2> + Pow<U3>,
    Exp<C::Dimension, U1>: ArrayLength<f64>,
    Prod<C::Dimension, U2>: ArrayLength<f64>,
    <Prod<C::Dimension, U2> as ArrayLength<f64>>::ArrayType: Copy,
    C: MetricSystem,
    Exp<C::Dimension, U2>: ArrayLength<f64>,
    Exp<C::Dimension, U3>: ArrayLength<f64>,
{
    pub fn derivative(&self) -> StateVector<Prod<C::Dimension, U2>> {
        let christoffel = C::christoffel(&self.x);
        let temp = inner!(_, Vector<C>; U1, U3; christoffel, self.v.clone());
        let cov_der = inner!(_, Vector<C>; U1, U2; temp, self.v.clone());
        let mut result = GenericArray::default();
        let d = C::Dimension::to_usize();
        for i in 0..d {
            result[i] = self.v[i];
            result[i + d] = -cov_der[i];
        }
        StateVector(result)
    }
}

impl<C: CoordinateSystem> Particle<C>
where
    C::Dimension: Pow<U1>,
    Exp<C::Dimension, U1>: ArrayLength<f64>,
{
    pub fn convert<C2: CoordinateSystem + 'static>(&self) -> Particle<C2>
    where
        C: ConversionTo<C2>,
        C2::Dimension: Pow<U1> + Pow<U2>,
        Exp<C2::Dimension, U1>: ArrayLength<f64>,
        Exp<C2::Dimension, U2>: ArrayLength<f64>,
        C2::Dimension: Same<C::Dimension>,
    {
        let new_x: Point<C2> = C::convert_point(&self.x);
        let new_v: Vector<C2> = self.v.convert();
        Particle { x: new_x, v: new_v }
    }
}
<commit_msg>particle: add the PosAndVel trait<commit_after>use diffgeom::coordinates::{ConversionTo, CoordinateSystem, Point};
use diffgeom::metric::MetricSystem;
use diffgeom::tensors::Vector;
use generic_array::{ArrayLength, GenericArray};
use numeric::StateVector;
use numeric_algs::State;
use std::ops::Mul;
use typenum::consts::{U1, U2, U3};
use typenum::{Exp, Pow, Prod, Same, Unsigned};

pub struct Particle<C: CoordinateSystem>
where
    C::Dimension: Pow<U1>,
    Exp<C::Dimension, U1>: ArrayLength<f64>,
{
    x: Point<C>,
    v: Vector<C>,
}

impl<C: CoordinateSystem> Clone for Particle<C>
where
    C::Dimension: Pow<U1>,
    Exp<C::Dimension, U1>: ArrayLength<f64>,
{
    fn clone(&self) -> Self {
        Particle {
            x: self.x.clone(),
            v: self.v.clone(),
        }
    }
}

impl<C: CoordinateSystem> Particle<C>
where
    C::Dimension: Pow<U1>,
    Exp<C::Dimension, U1>: ArrayLength<f64>,
{
    pub fn new(x: Point<C>, v: Vector<C>) -> Self {
        Particle { x: x, v: v }
    }

    pub fn get_pos(&self) -> &Point<C> {
        &self.x
    }

    pub fn get_vel(&self) -> &Vector<C> {
        &self.v
    }
}

impl<C: CoordinateSystem> State for Particle<C>
where
    C::Dimension: Pow<U1> + Mul<U2> + Unsigned,
    Exp<C::Dimension, U1>: ArrayLength<f64>,
    Prod<C::Dimension, U2>: ArrayLength<f64>,
    <Prod<C::Dimension, U2> as ArrayLength<f64>>::ArrayType: Copy,
{
    type Derivative = StateVector<Prod<C::Dimension, U2>>;

    fn shift_in_place(&mut self, dir: &Self::Derivative, amount: f64) {
        let d = C::Dimension::to_usize();
        for i in 0..d {
            self.x[i] += dir.0[i] * amount;
            self.v[i] += dir.0[i + d] * amount;
            self.v.set_point(self.x.clone());
        }
    }
}

impl<C: CoordinateSystem> Particle<C>
where
    C::Dimension: Pow<U1> + Mul<U2> + Unsigned + Pow<U2> + Pow<U3>,
    Exp<C::Dimension, U1>: ArrayLength<f64>,
    Prod<C::Dimension, U2>: ArrayLength<f64>,
    <Prod<C::Dimension, U2> as ArrayLength<f64>>::ArrayType: Copy,
    C: MetricSystem,
    Exp<C::Dimension, U2>: ArrayLength<f64>,
    Exp<C::Dimension, U3>: ArrayLength<f64>,
{
    pub fn derivative(&self) -> StateVector<Prod<C::Dimension, U2>> {
        let christoffel = C::christoffel(&self.x);
        let temp = inner!(_, Vector<C>; U1, U3; christoffel, self.v.clone());
        let cov_der = inner!(_, Vector<C>; U1, U2; temp, self.v.clone());
        let mut result = GenericArray::default();
        let d = C::Dimension::to_usize();
        for i in 0..d {
            result[i] = self.v[i];
            result[i + d] = -cov_der[i];
        }
        StateVector(result)
    }
}

impl<C: CoordinateSystem> Particle<C>
where
    C::Dimension: Pow<U1>,
    Exp<C::Dimension, U1>: ArrayLength<f64>,
{
    pub fn convert<C2: CoordinateSystem + 'static>(&self) -> Particle<C2>
    where
        C: ConversionTo<C2>,
        C2::Dimension: Pow<U1> + Pow<U2>,
        Exp<C2::Dimension, U1>: ArrayLength<f64>,
        Exp<C2::Dimension, U2>: ArrayLength<f64>,
        C2::Dimension: Same<C::Dimension>,
    {
        let new_x: Point<C2> = C::convert_point(&self.x);
        let new_v: Vector<C2> = self.v.convert();
        Particle { x: new_x, v: new_v }
    }
}

pub trait PosAndVel<D: Unsigned + ArrayLength<f64> + Pow<U1>>
where
    Exp<D, U1>: ArrayLength<f64>,
{
    fn get_pos(&self) -> &GenericArray<f64, D>;
    fn get_vel(&self) -> &GenericArray<f64, Exp<D, U1>>;
}

impl<C: CoordinateSystem> PosAndVel<C::Dimension> for Particle<C>
where
    C::Dimension: Pow<U1>,
    Exp<C::Dimension, U1>: ArrayLength<f64>,
{
    fn get_pos(&self) -> &GenericArray<f64, C::Dimension> {
        self.x.coords_array()
    }

    fn get_vel(&self) -> &GenericArray<f64, Exp<C::Dimension, U1>> {
        self.v.coords_array()
    }
}
<|endoftext|>


<commit_before>/*!
This module is for platform-specific stuff.
*/

pub use self::inner::{current_time, file_last_modified, get_cache_dir_for};

#[cfg(unix)]
mod inner {
    extern crate time;

    use std::path::{Path, PathBuf};
    use std::{cmp, env, fs};
    use std::os::unix::fs::MetadataExt;
    use error::{MainError, Blame};

    /**
    Gets the last-modified time of a file, in milliseconds since the UNIX epoch.
    */
    pub fn file_last_modified(file: &fs::File) -> u64 {
        let mtime_s_1970_utc = file.metadata()
            .map(|md| md.as_raw().mtime())
            .unwrap_or(0);

        let mtime_s_1970_utc = cmp::max(0, mtime_s_1970_utc);
        mtime_s_1970_utc as u64 * 1000
    }

    /**
    Gets the current system time, in milliseconds since the UNIX epoch.
    */
    pub fn current_time() -> u64 {
        /*
        This is kinda dicey, since *ideally* both this function and `file_last_modified` would be using the same underlying APIs.  They are not, insofar as I know.
        */
        let now_1970_utc = time::now_utc().to_timespec();
        if now_1970_utc.sec < 0 || now_1970_utc.nsec < 0 {
            // Fuck it.
            return 0
        }
        let now_ms_1970_utc = (now_1970_utc.sec as u64 * 1000)
            + (now_1970_utc.nsec as u64 / 1_000_000);
        now_ms_1970_utc
    }

    pub fn get_cache_dir_for<P>(product: P) -> Result<PathBuf, MainError>
    where P: AsRef<Path> {
        let home = match env::var_os("HOME") {
            Some(val) => val,
            None => return Err((Blame::Human, "$HOME is not defined").into())
        };

        match product.as_ref().to_str() {
            Some(s) => {
                let folder = format!(".{}", s.to_lowercase());
                Ok(Path::new(&home).join(folder))
            },
            None => Err("product for `get_cache_dir_for` was not utf8".into())
        }
    }
}

#[cfg(windows)]
pub mod inner {
    #![allow(non_snake_case)]

    extern crate ole32;
    extern crate shell32;
    extern crate winapi;
    extern crate uuid;

    use std::ffi::OsString;
    use std::fmt;
    use std::fs;
    use std::path::{Path, PathBuf};
    use std::mem;
    use std::os::windows::ffi::OsStringExt;
    use self::uuid::FOLDERID_LocalAppData;
    use error::MainError;

    /**
    Gets the last-modified time of a file, in milliseconds since the UNIX epoch.
    */
    pub fn file_last_modified(file: &fs::File) -> u64 {
        use ::std::os::windows::fs::MetadataExt;

        const MS_BETWEEN_1601_1970: u64 = 11_644_473_600_000;

        let mtime_100ns_1601_utc = file.metadata()
            .map(|md| md.last_write_time())
            .unwrap_or(0);
        let mtime_ms_1601_utc = mtime_100ns_1601_utc / (1000*10);

        // This can obviously underflow... but since files created prior to 1970 are going to be *somewhat rare*, I'm just going to saturate to zero.
        let mtime_ms_1970_utc = mtime_ms_1601_utc.saturating_sub(MS_BETWEEN_1601_1970);
        mtime_ms_1970_utc
    }

    /**
    Gets the current system time, in milliseconds since the UNIX epoch.
    */
    pub fn current_time() -> u64 {
        extern crate time;

        /*
        This is kinda dicey, since *ideally* both this function and `file_last_modified` would be using the same underlying APIs.  They are not, insofar as I know.
        */
        let mut now_1970_utc = time::now_utc().to_timespec();
        if now_1970_utc.sec < 0 || now_1970_utc.nsec < 0 {
            // Fuck it.
            now_1970_utc = time::Timespec::new(0, 0);
        }
        let now_ms_1970_utc = (now_1970_utc.sec as u64 * 1000)
            + (now_1970_utc.nsec as u64 / 1_000_000);
        now_ms_1970_utc
    }

    /**
    Get a directory suitable for storing user- and machine-specific data which may or may not be persisted across sessions.

    On Windows, LocalAppData is where user- and machine- specific data should go, but it *might* be more appropriate to use whatever the official name for "Program Data" is, though.
    */
    pub fn get_cache_dir_for<P>(product: P) -> Result<PathBuf, MainError>
    where P: AsRef<Path> {
        let dir = try!(SHGetKnownFolderPath(&FOLDERID_LocalAppData, 0, ::std::ptr::null_mut())
            .map_err(|e| e.to_string()));
        Ok(Path::new(&dir).to_path_buf().join(product))
    }

    type WinResult<T> = Result<T, WinError>;

    struct WinError(winapi::HRESULT);

    impl fmt::Display for WinError {
        fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
            write!(fmt, "HRESULT({})", self.0)
        }
    }

    fn SHGetKnownFolderPath(rfid: &winapi::KNOWNFOLDERID, dwFlags: winapi::DWORD, hToken: winapi::HANDLE) -> WinResult<OsString> {
        use self::winapi::PWSTR;
        let mut psz_path: PWSTR = unsafe { mem::uninitialized() };
        let hresult = unsafe {
            shell32::SHGetKnownFolderPath(
                rfid,
                dwFlags,
                hToken,
                mem::transmute(&mut psz_path as &mut PWSTR as *mut PWSTR)
            )
        };

        if hresult == winapi::S_OK {
            let r = unsafe { pwstr_to_os_string(psz_path) };
            unsafe { ole32::CoTaskMemFree(psz_path as *mut _) };
            Ok(r)
        } else {
            Err(WinError(hresult))
        }
    }

    unsafe fn pwstr_to_os_string(ptr: winapi::PWSTR) -> OsString {
        OsStringExt::from_wide(::std::slice::from_raw_parts(ptr, pwstr_len(ptr)))
    }

    unsafe fn pwstr_len(mut ptr: winapi::PWSTR) -> usize {
        let mut len = 0;
        while *ptr != 0 {
            len += 1;
            ptr = ptr.offset(1);
        }
        len
    }
}
<commit_msg>Factored out the common `current_time` function.<commit_after>/*!
This module is for platform-specific stuff.
*/

pub use self::inner::{current_time, file_last_modified, get_cache_dir_for};

#[cfg(any(unix, windows))]
mod inner_unix_or_windows {
    extern crate time;

    /**
    Gets the current system time, in milliseconds since the UNIX epoch.
    */
    pub fn current_time() -> u64 {
        /*
        This is kinda dicey, since *ideally* both this function and `file_last_modified` would be using the same underlying APIs.  They are not, insofar as I know.

        At least, not when targetting Windows.

        That said, so long as everything is in the same units and uses the same epoch, it should be fine.
        */
        let now_1970_utc = time::now_utc().to_timespec();
        if now_1970_utc.sec < 0 || now_1970_utc.nsec < 0 {
            // Fuck it.
            return 0
        }
        let now_ms_1970_utc = (now_1970_utc.sec as u64 * 1000)
            + (now_1970_utc.nsec as u64 / 1_000_000);
        now_ms_1970_utc
    }
}

#[cfg(unix)]
mod inner {
    pub use super::inner_unix_or_windows::current_time;

    use std::path::{Path, PathBuf};
    use std::{cmp, env, fs};
    use std::os::unix::fs::MetadataExt;
    use error::{MainError, Blame};

    /**
    Gets the last-modified time of a file, in milliseconds since the UNIX epoch.
    */
    pub fn file_last_modified(file: &fs::File) -> u64 {
        let mtime_s_1970_utc = file.metadata()
            .map(|md| md.as_raw().mtime())
            .unwrap_or(0);

        let mtime_s_1970_utc = cmp::max(0, mtime_s_1970_utc);
        mtime_s_1970_utc as u64 * 1000
    }

    /**
    Get a directory suitable for storing user- and machine-specific data which may or may not be persisted across sessions.

    This is chosen to match the location where Cargo places its cache data.
    */
    pub fn get_cache_dir_for<P>(product: P) -> Result<PathBuf, MainError>
    where P: AsRef<Path> {
        let home = match env::var_os("HOME") {
            Some(val) => val,
            None => return Err((Blame::Human, "$HOME is not defined").into())
        };

        match product.as_ref().to_str() {
            Some(s) => {
                let folder = format!(".{}", s.to_lowercase());
                Ok(Path::new(&home).join(folder))
            },
            None => Err("product for `get_cache_dir_for` was not utf8".into())
        }
    }
}

#[cfg(windows)]
pub mod inner {
    #![allow(non_snake_case)]

    extern crate ole32;
    extern crate shell32;
    extern crate winapi;
    extern crate uuid;

    pub use super::inner_unix_or_windows::current_time;

    use std::ffi::OsString;
    use std::fmt;
    use std::fs;
    use std::path::{Path, PathBuf};
    use std::mem;
    use std::os::windows::ffi::OsStringExt;
    use self::uuid::FOLDERID_LocalAppData;
    use error::MainError;

    /**
    Gets the last-modified time of a file, in milliseconds since the UNIX epoch.
    */
    pub fn file_last_modified(file: &fs::File) -> u64 {
        use ::std::os::windows::fs::MetadataExt;

        const MS_BETWEEN_1601_1970: u64 = 11_644_473_600_000;

        let mtime_100ns_1601_utc = file.metadata()
            .map(|md| md.last_write_time())
            .unwrap_or(0);
        let mtime_ms_1601_utc = mtime_100ns_1601_utc / (1000*10);

        // This can obviously underflow... but since files created prior to 1970 are going to be *somewhat rare*, I'm just going to saturate to zero.
        let mtime_ms_1970_utc = mtime_ms_1601_utc.saturating_sub(MS_BETWEEN_1601_1970);
        mtime_ms_1970_utc
    }

    /**
    Get a directory suitable for storing user- and machine-specific data which may or may not be persisted across sessions.

    This is *not* chosen to match the location where Cargo places its cache data, because Cargo is *wrong*.  This is at least *less wrong*.

    On Windows, LocalAppData is where user- and machine- specific data should go, but it *might* be more appropriate to use whatever the official name for "Program Data" is, though.
    */
    pub fn get_cache_dir_for<P>(product: P) -> Result<PathBuf, MainError>
    where P: AsRef<Path> {
        let dir = try!(SHGetKnownFolderPath(&FOLDERID_LocalAppData, 0, ::std::ptr::null_mut())
            .map_err(|e| e.to_string()));
        Ok(Path::new(&dir).to_path_buf().join(product))
    }

    type WinResult<T> = Result<T, WinError>;

    struct WinError(winapi::HRESULT);

    impl fmt::Display for WinError {
        fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
            write!(fmt, "HRESULT({})", self.0)
        }
    }

    fn SHGetKnownFolderPath(rfid: &winapi::KNOWNFOLDERID, dwFlags: winapi::DWORD, hToken: winapi::HANDLE) -> WinResult<OsString> {
        use self::winapi::PWSTR;
        let mut psz_path: PWSTR = unsafe { mem::uninitialized() };
        let hresult = unsafe {
            shell32::SHGetKnownFolderPath(
                rfid,
                dwFlags,
                hToken,
                mem::transmute(&mut psz_path as &mut PWSTR as *mut PWSTR)
            )
        };

        if hresult == winapi::S_OK {
            let r = unsafe { pwstr_to_os_string(psz_path) };
            unsafe { ole32::CoTaskMemFree(psz_path as *mut _) };
            Ok(r)
        } else {
            Err(WinError(hresult))
        }
    }

    unsafe fn pwstr_to_os_string(ptr: winapi::PWSTR) -> OsString {
        OsStringExt::from_wide(::std::slice::from_raw_parts(ptr, pwstr_len(ptr)))
    }

    unsafe fn pwstr_len(mut ptr: winapi::PWSTR) -> usize {
        let mut len = 0;
        while *ptr != 0 {
            len += 1;
            ptr = ptr.offset(1);
        }
        len
    }
}
<|endoftext|>


<commit_before>extern {
    static dc_qlookup: [i16; 256];
    static ac_qlookup: [i16; 256];
}

pub fn dc_q(qindex: usize) -> i16 {
    unsafe {
        dc_qlookup[qindex]
    }
}

pub fn ac_q(qindex: usize) -> i16 {
    unsafe {
        ac_qlookup[qindex]
    }
}

pub fn quantize_in_place(qindex: usize, coeffs: &mut [i32]) {
    coeffs[0] /= dc_q(qindex) as i32;
    for c in coeffs[1..].iter_mut() {
        *c /= ac_q(qindex) as i32;
        *c = 0;
    }
    coeffs[15] = 0;
}

pub fn dequantize(qindex:usize, coeffs: &[i32], rcoeffs: &mut [i32]) {
    rcoeffs[0] = coeffs[0] * dc_q(qindex) as i32;
    for i in 1..16 {
        rcoeffs[i] = coeffs[i] * ac_q(qindex) as i32;
    }
}
<commit_msg>Fix #76: Admit non-zero coefficients<commit_after>extern {
    static dc_qlookup: [i16; 256];
    static ac_qlookup: [i16; 256];
}

pub fn dc_q(qindex: usize) -> i16 {
    unsafe {
        dc_qlookup[qindex]
    }
}

pub fn ac_q(qindex: usize) -> i16 {
    unsafe {
        ac_qlookup[qindex]
    }
}

pub fn quantize_in_place(qindex: usize, coeffs: &mut [i32]) {
    coeffs[0] /= dc_q(qindex) as i32;
    for c in coeffs[1..].iter_mut() {
        *c /= ac_q(qindex) as i32;
    }
    coeffs[15] = 0;
}

pub fn dequantize(qindex:usize, coeffs: &[i32], rcoeffs: &mut [i32]) {
    rcoeffs[0] = coeffs[0] * dc_q(qindex) as i32;
    for i in 1..16 {
        rcoeffs[i] = coeffs[i] * ac_q(qindex) as i32;
    }
}
<|endoftext|>


<commit_before>#![allow(dead_code)]
use raft::errors::{Result, Error};
use raft::Storage;
use protobuf::{self, RepeatedField};
use proto::raftpb::{HardState, Entry, EntryType, Message, Snapshot, MessageType, ConfChange,
                    ConfChangeType, ConfState};
use raft::raft::{Config, Raft, SoftState, INVALID_ID};
use raft::Status;
use std::sync::Arc;

#[derive(Debug, Default)]
pub struct Peer {
    pub id: u64,
    pub context: Option<Vec<u8>>,
}

#[derive(Debug, PartialEq, Copy, Clone)]
pub enum SnapshotStatus {
    SnapshotFinish,
    SnapshotFailure,
}

fn is_local_msg(m: &Message) -> bool {
    match m.get_msg_type() {
        MessageType::MsgHup |
        MessageType::MsgBeat |
        MessageType::MsgUnreachable |
        MessageType::MsgSnapStatus |
        MessageType::MsgCheckQuorum => true,
        _ => false,
    }
}

fn is_response_msg(m: &Message) -> bool {
    match m.get_msg_type() {
        MessageType::MsgAppendResponse |
        MessageType::MsgRequestVoteResponse |
        MessageType::MsgHeartbeatResponse |
        MessageType::MsgUnreachable => true,
        _ => false,
    }
}

pub fn is_empty_snap(s: &Snapshot) -> bool {
    s.get_metadata().get_index() == 0
}

// Ready encapsulates the entries and messages that are ready to read,
// be saved to stable storage, committed or sent to other peers.
// All fields in Ready are read-only.
#[derive(Default, Debug, PartialEq)]
pub struct Ready {
    // The current volatile state of a Node.
    // SoftState will be nil if there is no update.
    // It is not required to consume or store SoftState.
    pub ss: Option<SoftState>,

    // The current state of a Node to be saved to stable storage BEFORE
    // Messages are sent.
    // HardState will be equal to empty state if there is no update.
    pub hs: Option<HardState>,

    // Entries specifies entries to be saved to stable storage BEFORE
    // Messages are sent.
    pub entries: Vec<Entry>,

    // Snapshot specifies the snapshot to be saved to stable storage.
    pub snapshot: Snapshot,

    // CommittedEntries specifies entries to be committed to a
    // store/state-machine. These have previously been committed to stable
    // store.
    pub committed_entries: Vec<Entry>,

    // Messages specifies outbound messages to be sent AFTER Entries are
    // committed to stable storage.
    // If it contains a MsgSnap message, the application MUST report back to raft
    // when the snapshot has been received or has failed by calling ReportSnapshot.
    pub messages: Vec<Message>,
}

impl Ready {
    fn new<T: Storage>(raft: &mut Raft<T>, prev_ss: &SoftState, prev_hs: &HardState) -> Ready {
        let mut rd = Ready {
            entries: raft.raft_log.unstable_entries().unwrap_or(&[]).to_vec(),
            committed_entries: raft.raft_log.next_entries().unwrap_or_else(Vec::new),
            messages: raft.msgs.drain(..).collect(),
            ..Default::default()
        };
        let ss = raft.soft_state();
        if &ss != prev_ss {
            rd.ss = Some(ss);
        }
        let hs = raft.hard_state();
        if &hs != prev_hs {
            rd.hs = Some(hs);
        }
        if raft.raft_log.get_unstable().snapshot.is_some() {
            rd.snapshot = raft.raft_log.get_unstable().snapshot.clone().unwrap();
        }
        rd
    }
}

// RawNode is a thread-unsafe Node.
// The methods of this struct correspond to the methods of Node and are described
// more fully there.
pub struct RawNode<T: Storage> {
    pub raft: Raft<T>,
    prev_ss: SoftState,
    prev_hs: HardState,
}

impl<T: Storage> RawNode<T> {
    // NewRawNode returns a new RawNode given configuration and a list of raft peers.
    pub fn new(config: &Config, store: Arc<T>, peers: &[Peer]) -> Result<RawNode<T>> {
        assert!(config.id != 0, "config.id must not be zero");
        let r = Raft::new(config, store);
        let mut rn = RawNode {
            raft: r,
            prev_hs: Default::default(),
            prev_ss: Default::default(),
        };
        let last_index = rn.raft.get_store().last_index().expect("");
        if last_index == 0 {
            rn.raft.become_follower(1, INVALID_ID);
            let mut ents = Vec::with_capacity(peers.len());
            for (i, peer) in peers.iter().enumerate() {
                let mut cc = ConfChange::new();
                cc.set_change_type(ConfChangeType::ConfChangeAddNode);
                cc.set_node_id(peer.id);
                if peer.context.is_some() {
                    cc.set_context(peer.context.as_ref().unwrap().clone());
                }
                let data = protobuf::Message::write_to_bytes(&cc)
                               .expect("unexpected marshal error");
                let mut e = Entry::new();
                e.set_entry_type(EntryType::EntryConfChange);
                e.set_term(1);
                e.set_index(i as u64 + 1);
                e.set_data(data);
                ents.push(e);
            }
            rn.raft.raft_log.append(&ents);
            rn.raft.raft_log.committed = ents.len() as u64;
            for peer in peers {
                rn.raft.add_node(peer.id);
            }
        }
        rn.prev_ss = rn.raft.soft_state();
        rn.prev_hs = rn.raft.hard_state();
        Ok(rn)
    }

    fn commit_ready(&mut self, rd: Ready) {
        if rd.ss.is_some() {
            self.prev_ss = rd.ss.unwrap();
        }
        if let Some(e) = rd.hs {
            if e != HardState::new() {
                self.prev_hs = e;
            }
        }
        if self.prev_hs.get_commit() != 0 {
            // In most cases, prevHardSt and rd.HardState will be the same
            // because when there are new entries to apply we just sent a
            // HardState with an updated Commit value. However, on initial
            // startup the two are different because we don't send a HardState
            // until something changes, but we do send any un-applied but
            // committed entries (and previously-committed entries may be
            // incorporated into the snapshot, even if rd.CommittedEntries is
            // empty). Therefore we mark all committed entries as applied
            // whether they were included in rd.HardState or not.
            self.raft.raft_log.applied_to(self.prev_hs.get_commit());
        }
        if !rd.entries.is_empty() {
            let e = rd.entries.last().unwrap();
            self.raft.raft_log.stable_to(e.get_index(), e.get_term());
        }
        if rd.snapshot != Snapshot::new() {
            self.raft.raft_log.stable_snap_to(rd.snapshot.get_metadata().get_index());
        }
    }

    // Tick advances the internal logical clock by a single tick.
    pub fn tick(&mut self) {
        self.raft.tick();
    }

    // Campaign causes this RawNode to transition to candidate state.
    pub fn campaign(&mut self) -> Result<()> {
        let mut m = Message::new();
        m.set_msg_type(MessageType::MsgHup);
        self.raft.step(m)
    }

    // Propose proposes data be appended to the raft log.
    pub fn propose(&mut self, data: Vec<u8>) -> Result<()> {
        let mut m = Message::new();
        m.set_msg_type(MessageType::MsgPropose);
        m.set_from(self.raft.id);
        let mut e = Entry::new();
        e.set_data(data);
        m.set_entries(RepeatedField::from_vec(vec![e]));
        self.raft.step(m)
    }

    // ProposeConfChange proposes a config change.
    pub fn propose_conf_change(&mut self, cc: ConfChange) -> Result<()> {
        let data = try!(protobuf::Message::write_to_bytes(&cc));
        let mut m = Message::new();
        m.set_msg_type(MessageType::MsgPropose);
        let mut e = Entry::new();
        e.set_entry_type(EntryType::EntryConfChange);
        e.set_data(data);
        m.set_entries(RepeatedField::from_vec(vec![e]));
        self.raft.step(m)
    }

    pub fn apply_conf_change(&mut self, cc: ConfChange) -> ConfState {
        if cc.get_node_id() == INVALID_ID {
            self.raft.reset_pending_conf();
            let mut cs = ConfState::new();
            cs.set_nodes(self.raft.nodes());
            return cs;
        }
        let nid = cc.get_node_id();
        assert!(cc.has_change_type(), "unexpected conf type");
        match cc.get_change_type() {
            ConfChangeType::ConfChangeAddNode => self.raft.add_node(nid),
            ConfChangeType::ConfChangeRemoveNode => self.raft.remove_node(nid),
            ConfChangeType::ConfChangeUpdateNode => self.raft.reset_pending_conf(),
        }
        let mut cs = ConfState::new();
        cs.set_nodes(self.raft.nodes());
        cs
    }

    // Step advances the state machine using the given message.
    pub fn step(&mut self, m: Message) -> Result<()> {
        // ignore unexpected local messages receiving over network
        if is_local_msg(&m) {
            return Err(Error::StepLocalMsg);
        }
        if self.raft.prs.contains_key(&m.get_from()) || is_response_msg(&m) {
            return self.raft.step(m);
        }
        Err(Error::StepPeerNotFound)
    }

    // Ready returns the current point-in-time state of this RawNode.
    pub fn ready(&mut self) -> Ready {
        Ready::new(&mut self.raft, &self.prev_ss, &self.prev_hs)
    }

    // HasReady called when RawNode user need to check if any Ready pending.
    // Checking logic in this method should be consistent with Ready.containsUpdates().
    pub fn has_ready(&self) -> bool {
        let raft = &self.raft;
        if raft.soft_state() != self.prev_ss {
            return true;
        }
        let hs = raft.hard_state();
        if hs != HardState::new() && hs != self.prev_hs {
            return true;
        }
        if Some(true) == raft.raft_log.get_unstable().snapshot.as_ref().map(|s| !is_empty_snap(s)) {
            return true;
        }
        if !raft.msgs.is_empty() || raft.raft_log.unstable_entries().is_some() ||
           raft.raft_log.has_next_entries() {
            return true;
        }
        false
    }

    // Advance notifies the RawNode that the application has applied and saved progress in the
    // last Ready results.
    pub fn advance(&mut self, rd: Ready) {
        self.commit_ready(rd);
    }

    // Status returns the current status of the given group.
    pub fn status(&self) -> Status {
        Status::new(&self.raft)
    }

    // ReportUnreachable reports the given node is not reachable for the last send.
    pub fn report_unreachable(&mut self, id: u64) {
        let mut m = Message::new();
        m.set_msg_type(MessageType::MsgUnreachable);
        m.set_from(id);
        // we don't care if it is ok actually
        self.raft.step(m).is_ok();
    }

    // ReportSnapshot reports the status of the sent snapshot.
    pub fn report_snapshot(&mut self, id: u64, status: SnapshotStatus) {
        let rej = status == SnapshotStatus::SnapshotFailure;
        let mut m = Message::new();
        m.set_msg_type(MessageType::MsgSnapStatus);
        m.set_from(id);
        m.set_reject(rej);
        // we don't care if it is ok actually
        self.raft.step(m).is_ok();
    }
}
<commit_msg>raw_node: fix condition checking.<commit_after>#![allow(dead_code)]
use raft::errors::{Result, Error};
use raft::Storage;
use protobuf::{self, RepeatedField};
use proto::raftpb::{HardState, Entry, EntryType, Message, Snapshot, MessageType, ConfChange,
                    ConfChangeType, ConfState};
use raft::raft::{Config, Raft, SoftState, INVALID_ID};
use raft::Status;
use std::sync::Arc;

#[derive(Debug, Default)]
pub struct Peer {
    pub id: u64,
    pub context: Option<Vec<u8>>,
}

#[derive(Debug, PartialEq, Copy, Clone)]
pub enum SnapshotStatus {
    SnapshotFinish,
    SnapshotFailure,
}

fn is_local_msg(m: &Message) -> bool {
    match m.get_msg_type() {
        MessageType::MsgHup |
        MessageType::MsgBeat |
        MessageType::MsgUnreachable |
        MessageType::MsgSnapStatus |
        MessageType::MsgCheckQuorum => true,
        _ => false,
    }
}

fn is_response_msg(m: &Message) -> bool {
    match m.get_msg_type() {
        MessageType::MsgAppendResponse |
        MessageType::MsgRequestVoteResponse |
        MessageType::MsgHeartbeatResponse |
        MessageType::MsgUnreachable => true,
        _ => false,
    }
}

pub fn is_empty_snap(s: &Snapshot) -> bool {
    s.get_metadata().get_index() == 0
}

// Ready encapsulates the entries and messages that are ready to read,
// be saved to stable storage, committed or sent to other peers.
// All fields in Ready are read-only.
#[derive(Default, Debug, PartialEq)]
pub struct Ready {
    // The current volatile state of a Node.
    // SoftState will be nil if there is no update.
    // It is not required to consume or store SoftState.
    pub ss: Option<SoftState>,

    // The current state of a Node to be saved to stable storage BEFORE
    // Messages are sent.
    // HardState will be equal to empty state if there is no update.
    pub hs: Option<HardState>,

    // Entries specifies entries to be saved to stable storage BEFORE
    // Messages are sent.
    pub entries: Vec<Entry>,

    // Snapshot specifies the snapshot to be saved to stable storage.
    pub snapshot: Snapshot,

    // CommittedEntries specifies entries to be committed to a
    // store/state-machine. These have previously been committed to stable
    // store.
    pub committed_entries: Vec<Entry>,

    // Messages specifies outbound messages to be sent AFTER Entries are
    // committed to stable storage.
    // If it contains a MsgSnap message, the application MUST report back to raft
    // when the snapshot has been received or has failed by calling ReportSnapshot.
    pub messages: Vec<Message>,
}

impl Ready {
    fn new<T: Storage>(raft: &mut Raft<T>, prev_ss: &SoftState, prev_hs: &HardState) -> Ready {
        let mut rd = Ready {
            entries: raft.raft_log.unstable_entries().unwrap_or(&[]).to_vec(),
            committed_entries: raft.raft_log.next_entries().unwrap_or_else(Vec::new),
            messages: raft.msgs.drain(..).collect(),
            ..Default::default()
        };
        let ss = raft.soft_state();
        if &ss != prev_ss {
            rd.ss = Some(ss);
        }
        let hs = raft.hard_state();
        if &hs != prev_hs {
            rd.hs = Some(hs);
        }
        if raft.raft_log.get_unstable().snapshot.is_some() {
            rd.snapshot = raft.raft_log.get_unstable().snapshot.clone().unwrap();
        }
        rd
    }
}

// RawNode is a thread-unsafe Node.
// The methods of this struct correspond to the methods of Node and are described
// more fully there.
pub struct RawNode<T: Storage> {
    pub raft: Raft<T>,
    prev_ss: SoftState,
    prev_hs: HardState,
}

impl<T: Storage> RawNode<T> {
    // NewRawNode returns a new RawNode given configuration and a list of raft peers.
    pub fn new(config: &Config, store: Arc<T>, peers: &[Peer]) -> Result<RawNode<T>> {
        assert!(config.id != 0, "config.id must not be zero");
        let r = Raft::new(config, store);
        let mut rn = RawNode {
            raft: r,
            prev_hs: Default::default(),
            prev_ss: Default::default(),
        };
        let last_index = rn.raft.get_store().last_index().expect("");
        if last_index == 0 {
            rn.raft.become_follower(1, INVALID_ID);
            let mut ents = Vec::with_capacity(peers.len());
            for (i, peer) in peers.iter().enumerate() {
                let mut cc = ConfChange::new();
                cc.set_change_type(ConfChangeType::ConfChangeAddNode);
                cc.set_node_id(peer.id);
                if peer.context.is_some() {
                    cc.set_context(peer.context.as_ref().unwrap().clone());
                }
                let data = protobuf::Message::write_to_bytes(&cc)
                               .expect("unexpected marshal error");
                let mut e = Entry::new();
                e.set_entry_type(EntryType::EntryConfChange);
                e.set_term(1);
                e.set_index(i as u64 + 1);
                e.set_data(data);
                ents.push(e);
            }
            rn.raft.raft_log.append(&ents);
            rn.raft.raft_log.committed = ents.len() as u64;
            for peer in peers {
                rn.raft.add_node(peer.id);
            }
        }
        rn.prev_ss = rn.raft.soft_state();
        rn.prev_hs = rn.raft.hard_state();
        Ok(rn)
    }

    fn commit_ready(&mut self, rd: Ready) {
        if rd.ss.is_some() {
            self.prev_ss = rd.ss.unwrap();
        }
        if let Some(e) = rd.hs {
            if e != HardState::new() {
                self.prev_hs = e;
            }
        }
        if self.prev_hs.get_commit() != 0 {
            // In most cases, prevHardSt and rd.HardState will be the same
            // because when there are new entries to apply we just sent a
            // HardState with an updated Commit value. However, on initial
            // startup the two are different because we don't send a HardState
            // until something changes, but we do send any un-applied but
            // committed entries (and previously-committed entries may be
            // incorporated into the snapshot, even if rd.CommittedEntries is
            // empty). Therefore we mark all committed entries as applied
            // whether they were included in rd.HardState or not.
            self.raft.raft_log.applied_to(self.prev_hs.get_commit());
        }
        if !rd.entries.is_empty() {
            let e = rd.entries.last().unwrap();
            self.raft.raft_log.stable_to(e.get_index(), e.get_term());
        }
        if rd.snapshot != Snapshot::new() {
            self.raft.raft_log.stable_snap_to(rd.snapshot.get_metadata().get_index());
        }
    }

    // Tick advances the internal logical clock by a single tick.
    pub fn tick(&mut self) {
        self.raft.tick();
    }

    // Campaign causes this RawNode to transition to candidate state.
    pub fn campaign(&mut self) -> Result<()> {
        let mut m = Message::new();
        m.set_msg_type(MessageType::MsgHup);
        self.raft.step(m)
    }

    // Propose proposes data be appended to the raft log.
    pub fn propose(&mut self, data: Vec<u8>) -> Result<()> {
        let mut m = Message::new();
        m.set_msg_type(MessageType::MsgPropose);
        m.set_from(self.raft.id);
        let mut e = Entry::new();
        e.set_data(data);
        m.set_entries(RepeatedField::from_vec(vec![e]));
        self.raft.step(m)
    }

    // ProposeConfChange proposes a config change.
    pub fn propose_conf_change(&mut self, cc: ConfChange) -> Result<()> {
        let data = try!(protobuf::Message::write_to_bytes(&cc));
        let mut m = Message::new();
        m.set_msg_type(MessageType::MsgPropose);
        let mut e = Entry::new();
        e.set_entry_type(EntryType::EntryConfChange);
        e.set_data(data);
        m.set_entries(RepeatedField::from_vec(vec![e]));
        self.raft.step(m)
    }

    pub fn apply_conf_change(&mut self, cc: ConfChange) -> ConfState {
        if cc.get_node_id() == INVALID_ID {
            self.raft.reset_pending_conf();
            let mut cs = ConfState::new();
            cs.set_nodes(self.raft.nodes());
            return cs;
        }
        let nid = cc.get_node_id();
        assert!(cc.has_change_type(), "unexpected conf type");
        match cc.get_change_type() {
            ConfChangeType::ConfChangeAddNode => self.raft.add_node(nid),
            ConfChangeType::ConfChangeRemoveNode => self.raft.remove_node(nid),
            ConfChangeType::ConfChangeUpdateNode => self.raft.reset_pending_conf(),
        }
        let mut cs = ConfState::new();
        cs.set_nodes(self.raft.nodes());
        cs
    }

    // Step advances the state machine using the given message.
    pub fn step(&mut self, m: Message) -> Result<()> {
        // ignore unexpected local messages receiving over network
        if is_local_msg(&m) {
            return Err(Error::StepLocalMsg);
        }
        if self.raft.prs.contains_key(&m.get_from()) || !is_response_msg(&m) {
            return self.raft.step(m);
        }
        Err(Error::StepPeerNotFound)
    }

    // Ready returns the current point-in-time state of this RawNode.
    pub fn ready(&mut self) -> Ready {
        Ready::new(&mut self.raft, &self.prev_ss, &self.prev_hs)
    }

    // HasReady called when RawNode user need to check if any Ready pending.
    // Checking logic in this method should be consistent with Ready.containsUpdates().
    pub fn has_ready(&self) -> bool {
        let raft = &self.raft;
        if raft.soft_state() != self.prev_ss {
            return true;
        }
        let hs = raft.hard_state();
        if hs != HardState::new() && hs != self.prev_hs {
            return true;
        }
        if Some(true) == raft.raft_log.get_unstable().snapshot.as_ref().map(|s| !is_empty_snap(s)) {
            return true;
        }
        if !raft.msgs.is_empty() || raft.raft_log.unstable_entries().is_some() ||
           raft.raft_log.has_next_entries() {
            return true;
        }
        false
    }

    // Advance notifies the RawNode that the application has applied and saved progress in the
    // last Ready results.
    pub fn advance(&mut self, rd: Ready) {
        self.commit_ready(rd);
    }

    // Status returns the current status of the given group.
    pub fn status(&self) -> Status {
        Status::new(&self.raft)
    }

    // ReportUnreachable reports the given node is not reachable for the last send.
    pub fn report_unreachable(&mut self, id: u64) {
        let mut m = Message::new();
        m.set_msg_type(MessageType::MsgUnreachable);
        m.set_from(id);
        // we don't care if it is ok actually
        self.raft.step(m).is_ok();
    }

    // ReportSnapshot reports the status of the sent snapshot.
    pub fn report_snapshot(&mut self, id: u64, status: SnapshotStatus) {
        let rej = status == SnapshotStatus::SnapshotFailure;
        let mut m = Message::new();
        m.set_msg_type(MessageType::MsgSnapStatus);
        m.set_from(id);
        m.set_reject(rej);
        // we don't care if it is ok actually
        self.raft.step(m).is_ok();
    }
}
<|endoftext|>