<commit_before><commit_msg>implemented and tested Heaps<commit_after>use std::cmp::{Ord, Ordering};
use std::collections::BinaryHeap as RHeap;
use super::{ Cost, NodeId, INF, NEG_INF };

/// minimalistic heap trait restricted for `(NodeId, Cost)` tuples
pub trait Heap {
    /// Find the min element in `O(1)` time.
    fn find_min(&self) -> Option<NodeId>;
    /// Return the current number of elements in the heap.
    fn size(&self) -> usize;
    fn is_empty(&self) -> bool;
    fn insert(&mut self, node_id: NodeId, cost: Cost);
    /// Remove the current minimal element.
    fn delete_min(&mut self);
}

/// BinaryHeap, wraps the native Rust implementation.
/// Rust's BinaryHeap is a max heap, we need a min heap.
/// I solved that by adding the costs as negative in the `insert` function.
pub struct BinaryHeap {
    inner_heap: RHeap<HeapMember>
}
impl BinaryHeap {
    fn new() -> Self {
        BinaryHeap {
            inner_heap: RHeap::new()
        }
    }
    fn with_capacity(capacity: usize) -> Self {
        BinaryHeap {
            inner_heap: RHeap::with_capacity(capacity)
        }
    }
}

impl Heap for BinaryHeap {
    fn find_min(&self) -> Option<NodeId> {
        match self.inner_heap.peek() {
            Some(&member) => Some(member.key),
            None => None,
        }
    }
    fn size(&self) -> usize {
        self.inner_heap.len()
    }
    fn is_empty(&self) -> bool {
        self.inner_heap.is_empty()
    }
    fn insert(&mut self, node_id: NodeId, cost: Cost) {
        self.inner_heap.push(HeapMember { key: node_id, cost: -cost }) // rust heap is a max heap
    }
    fn delete_min(&mut self) {
        self.inner_heap.pop();
    }
}

struct FibElement {
    heap_member: HeapMember,
    rank: usize,
    children: Vec<FibElement>,
}

pub struct FibonacciHeap {
    min_elem: Option<FibElement>,
    root: Vec<FibElement>,
    size: usize,
}

impl FibonacciHeap {
    fn new() -> Self {
        FibonacciHeap {
            min_elem: None,
            root: Vec::new(),
            size: 0,
        }
    }
    fn remove_min(&mut self) {
        let min_elem = self.min_elem.take().unwrap();
        for child in min_elem.children {
            self.root.push(child);
        }
    }
    fn merge_roots(&mut self) {
        let root_degrees = &mut (vec![self.size; self.root.len()])[..]; // self.size is an invalid id
        while self.not_all_different() {
            for i in 0..self.root.len() {
                let rank = self.root.get(i).unwrap().rank;
                if root_degrees[rank] != self.size {
                    self.link(root_degrees[rank], i);
                    root_degrees[rank] = self.size;
                    break;
                } else {
                    root_degrees[rank] = i;
                }
            }
        }
    }
    fn update_min(&mut self) {
        let mut min_id = 0;
        let mut min_cost = INF;
        for i in 0..self.root.len() {
            let current_cost = self.root.get(i).unwrap().heap_member.cost;
            if current_cost < min_cost {
                min_cost = current_cost;
                min_id = i;
            }
        }
        self.min_elem = Some(self.root.remove(min_id))
    }
    fn link(&mut self, i: usize, j: usize) {
        let mut elem_i = self.root.remove(i);
        let mut elem_j = self.root.remove(j);
        if elem_i.heap_member < elem_j.heap_member {
            elem_i.children.push(elem_j);
            elem_i.rank += 1;
            self.root.push(elem_i);
        } else {
            elem_j.children.push(elem_i);
            elem_j.rank += 1;
            self.root.push(elem_j);
        }
    }
    fn not_all_different(&self) -> bool {
        let root_degrees = &mut (vec![self.size; self.root.len()])[..]; // self.size is an invalid id
        for i in 0..self.root.len() {
            let rank = self.root.get(i).unwrap().rank;
            if root_degrees[rank] != self.size {
                return true;
            } else {
                root_degrees[rank] = i;
            }
        }
        false
    }
}

impl Heap for FibonacciHeap {
    fn find_min(&self) -> Option<NodeId> {
        self.min_elem.as_ref().map(|elem| elem.heap_member.key)
    }
    fn size(&self) -> usize {
        self.size
    }
    fn is_empty(&self) -> bool {
        self.size == 0
    }
    fn insert(&mut self, node: NodeId, cost: Cost) {
        let new_elem = FibElement {
                heap_member: HeapMember{ key: node, cost: cost },
                rank: 0,
                children: Vec::new(),
            };

        if self.is_empty() {
            self.min_elem = Some(new_elem)
        } else if cost < self.min_elem.as_ref().unwrap().heap_member.cost {
            self.root.push(self.min_elem.take().unwrap());
            self.min_elem = Some(new_elem);
        } else {
            self.root.push(new_elem)
        }
        self.size += 1;
    }
    fn delete_min(&mut self) {
        if ! self.is_empty() {
            self.size -= 1;
            self.remove_min();
            self.merge_roots();
            self.update_min();
        }
    }
}

/// Heap element, wraps a tuple of node id and respective costs
#[derive(Copy, Clone, PartialEq)]
struct HeapMember {
    key: NodeId,
    cost: Cost,
}

impl Eq for HeapMember {}

/// Implementation of `PartialOrd` based on the cost to reach a node
impl PartialOrd for HeapMember {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        if self.cost.is_nan() || other.cost.is_nan() {
            return None;
        }
        if self.cost < other.cost {
            return Some(Ordering::Less);
        } else if self.cost > other.cost {
            return Some(Ordering::Greater);
        } else {
            return Some(Ordering::Equal);
        }
    }

    fn lt(&self, other: &Self) -> bool {
        self.cost < other.cost
    }
    fn le(&self, other: &Self) -> bool {
        self.cost <= other.cost
    }
    fn gt(&self, other: &Self) -> bool {
        self.cost > other.cost
    }
    fn ge(&self, other: &Self) -> bool {
        self.cost >= other.cost
    }
}

/// Implement a total ordering on elements of a heap based on costs
impl Ord for HeapMember {
    fn cmp(&self, other: &Self) -> Ordering {
        if self.cost < other.cost {
            return Ordering::Less;
        } else if self.cost > other.cost {
            return Ordering::Greater;
        } else {
            return Ordering::Equal;
        }
    }
}

#[test]
fn test_partial_ordering() {
    let mem1 = HeapMember{key: 0, cost: 0.0};
    let mem2 = HeapMember{key: 1, cost: 1.0};
    let mem3 = HeapMember{key: 2, cost: -1.0};

    assert!(mem1 < mem2);
    assert!(mem2 > mem1);
    assert!(mem3 < mem2);
    assert!(mem3 < mem1);
    assert!(mem1 == mem1);
}

#[test]
fn test_ordering() {
    let mem1 = HeapMember{key: 0, cost: 0.0};
    let mem2 = HeapMember{key: 1, cost: 1.0};
    let mem3 = HeapMember{key: 2, cost: -1.0};

    assert_eq!(Ordering::Less, mem1.cmp(&mem2));
    assert_eq!(Ordering::Greater, mem2.cmp(&mem1));
    assert_eq!(Ordering::Equal, mem1.cmp(&mem1));
    assert_eq!(Ordering::Less, mem3.cmp(&mem1));
}

#[test]
fn test_binary_heap() {
    let mut binary_heap = BinaryHeap::new();
    binary_heap.insert(0,0.0);
    assert_eq!(Some(0), binary_heap.find_min());
    binary_heap.insert(1,1.0);
    binary_heap.delete_min();
    binary_heap.insert(2,2.0);
    binary_heap.insert(3,3.0);
    assert_eq!(Some(1), binary_heap.find_min());
    assert_eq!(3, binary_heap.size());
    binary_heap.insert(4,4.0);
    binary_heap.insert(5,5.0);
    assert_eq!(5, binary_heap.size());
    assert_eq!(Some(1), binary_heap.find_min());
    binary_heap.insert(0,0.0);
    assert_eq!(Some(0), binary_heap.find_min());
}

#[test]
fn test_fibonacci_heap() {
    let mut fibonacci_heap = FibonacciHeap::new();
    fibonacci_heap.insert(0,0.0);
    assert_eq!(Some(0), fibonacci_heap.find_min());
    fibonacci_heap.insert(1,1.0);
    fibonacci_heap.delete_min();
    fibonacci_heap.insert(2,2.0);
    fibonacci_heap.insert(3,3.0);
    assert_eq!(Some(1), fibonacci_heap.find_min());
    assert_eq!(3, fibonacci_heap.size());
    fibonacci_heap.insert(4,4.0);
    fibonacci_heap.insert(5,5.0);
    assert_eq!(5, fibonacci_heap.size());
    assert_eq!(Some(1), fibonacci_heap.find_min());
    fibonacci_heap.insert(0,0.0);
    assert_eq!(Some(0), fibonacci_heap.find_min());
}
<|endoftext|>


<commit_before><commit_msg>file open err<commit_after><|endoftext|>


<commit_before><commit_msg>Fix: Use module path when getting mail instead of using plain MessageId object in String representation<commit_after><|endoftext|>


<commit_before><commit_msg>Added Node and Graphyll data structure -- needs testing<commit_after><|endoftext|>


<commit_before><commit_msg>Replace 'static' keyword with 'const' to be compilable in rust 0.12<commit_after><|endoftext|>


<commit_before><commit_msg>Rollup merge of #27147 - apasel422:issue-19404, r=alexcrichton<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![feature(reflect_marker)]

use std::any::TypeId;
use std::marker::Reflect;
use std::rc::Rc;

type Fp<T> = Rc<T>;

struct Engine;

trait Component: 'static + Reflect {}
impl Component for Engine {}

trait Env {
    fn get_component_type_id(&self, type_id: TypeId) -> Option<Fp<Component>>;
}

impl<'a> Env+'a {
    fn get_component<T: Component>(&self) -> Option<Fp<T>> {
        let x = self.get_component_type_id(TypeId::of::<T>());
        None
    }
}

trait Figment {
    fn init(&mut self, env: &Env);
}

struct MyFigment;

impl Figment for MyFigment {
    fn init(&mut self, env: &Env) {
        let engine = env.get_component::<Engine>();
    }
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>add AWS Config integration tests<commit_after>#![cfg(feature = "config")]

extern crate rusoto;

use rusoto::config::{ConfigServiceClient, DescribeConfigRulesRequest, DescribeDeliveryChannelsRequest};
use rusoto::{DefaultCredentialsProvider, Region};

#[test]
fn should_describe_config_rules() {
    let credentials = DefaultCredentialsProvider::new().unwrap();
    let client = ConfigServiceClient::new(credentials, Region::UsEast1);

    let request = DescribeConfigRulesRequest::default();

    match client.describe_config_rules(&request) {
        Ok(response) => {
            println!("{:#?}", response);
            assert!(true)
        },
        Err(err) => panic!("Expected OK response, got {:#?}", err)
    };
}

#[test]
fn should_describe_delivery_channels() {
    let credentials = DefaultCredentialsProvider::new().unwrap();
    let client = ConfigServiceClient::new(credentials, Region::UsEast1);

    let request = DescribeDeliveryChannelsRequest::default();

    match client.describe_delivery_channels(&request) {
        Ok(response) => {
            println!("{:#?}", response);
            assert!(true)
        },
        Err(err) => panic!("Expected OK response, got {:#?}", err)
    };
}
<|endoftext|>


<commit_before><commit_msg>traits documentation<commit_after><|endoftext|>


<commit_before><commit_msg>Fix broken pipe panics<commit_after><|endoftext|>


<commit_before><commit_msg>Fix for broken pipe errors<commit_after><|endoftext|>


<commit_before><commit_msg>Fix mod echo interface<commit_after><|endoftext|>


<commit_before>use std::string::FromUtf8Error;
use rustc_serialize::base64::FromBase64Error;
use rustc_serialize::json;

pub enum Error {
    Format,
    Base64,
    Decode,
    Json,
    Utf8,
}

macro_rules! error_wrap {
    ($f: ty, $e: expr) => {
    impl From<$f> for Error {
        fn from(_: $f) -> Error { $e }
    }
}
}

error_wrap!(FromBase64Error, Error::Base64);
error_wrap!(json::DecoderError, Error::Decode);
error_wrap!(json::ErrorCode, Error::Json);
error_wrap!(FromUtf8Error, Error::Utf8);
<commit_msg>Derive debug<commit_after>use std::string::FromUtf8Error;
use rustc_serialize::base64::FromBase64Error;
use rustc_serialize::json;

#[derive(Debug)]
pub enum Error {
    Format,
    Base64,
    Decode,
    Json,
    Utf8,
}

macro_rules! error_wrap {
    ($f: ty, $e: expr) => {
    impl From<$f> for Error {
        fn from(_: $f) -> Error { $e }
    }
}
}

error_wrap!(FromBase64Error, Error::Base64);
error_wrap!(json::DecoderError, Error::Decode);
error_wrap!(json::ErrorCode, Error::Json);
error_wrap!(FromUtf8Error, Error::Utf8);
<|endoftext|>


<commit_before><commit_msg>Simplify a match statement<commit_after><|endoftext|>


<commit_before><commit_msg>Rename parameter from X to This<commit_after><|endoftext|>


<commit_before>use std::uint;
use std::num;
use time::precise_time_ns;
use token::Token;
use util::Slab;

const EMPTY: Token = Token(uint::MAX);
const NS_PER_MS: u64 = 1_000_000;

// Implements coarse-grained timeouts using an algorithm based on hashed timing
// wheels by Varghese & Lauck.
//
// TODO:
// * Handle the case when the timer falls more than an entire wheel behind. There
//   is no point to loop multiple times around the wheel in one go.
// * New type for tick, now() -> Tick
pub struct Timer<T> {
    // Size of each tick in milliseconds
    tick_ms: u64,
    // Slab of timeout entries
    entries: Slab<Entry<T>>,
    // Timeout wheel. Each tick, the timer will look at the next slot for
    // timeouts that match the current tick.
    wheel: Vec<Token>,
    // Tick 0's time in milliseconds
    start: u64,
    // The current tick
    tick: u64,
    // The next entry to possibly timeout
    next: Token,
    // Masks the target tick to get the slot
    mask: u64,
}

pub struct Timeout {
    // Reference into the timer entry slab
    token: Token,
    // Tick that it should matchup with
    tick: u64,
}

impl<T> Timer<T> {
    pub fn new(tick_ms: u64, mut slots: uint, mut capacity: uint) -> Timer<T> {
        slots = num::next_power_of_two(slots);
        capacity = num::next_power_of_two(capacity);

        Timer {
            tick_ms: tick_ms,
            entries: Slab::new(capacity),
            wheel: Vec::from_fn(slots, |_| EMPTY),
            start: 0,
            tick: 0,
            next: EMPTY,
            mask: (slots as u64) - 1
        }
    }

    pub fn count(&self) -> uint {
        self.entries.count()
    }

    // Number of ms remaining until the next tick
    pub fn next_tick_in_ms(&self) -> u64 {
        let now = self.now_ms();
        let nxt = self.start + (self.tick + 1) * self.tick_ms;

        if nxt <= now {
            return 0;
        }

        nxt - now
    }

    /*
     *
     * ===== Initialization =====
     *
     */

    // Sets the starting time of the timer using the current system time
    pub fn setup(&mut self) {
        let now = self.now_ms();
        self.set_start_ms(now);
    }

    fn set_start_ms(&mut self, start: u64) {
        assert!(!self.is_initialized(), "the timer has already started");
        self.start = start;
    }

    /*
     *
     * ===== Timeout create / cancel =====
     *
     */

    pub fn timeout_ms(&mut self, token: T, delay: u64) -> TimerResult<Timeout> {
        let at = self.now_ms() + delay;
        self.timeout_at_ms(token, at)
    }

    pub fn timeout_at_ms(&mut self, token: T, mut at: u64) -> TimerResult<Timeout> {
        // Make relative to start
        at -= self.start;
        // Calculate tick
        let mut tick = (at + self.tick_ms - 1) / self.tick_ms;

        // Always target at least 1 tick in the future
        if tick <= self.tick {
            tick = self.tick + 1;
        }

        self.insert(token, tick)
    }

    pub fn clear(&mut self, timeout: Timeout) -> bool {
        let links = match self.entries.get(timeout.token) {
            Some(e) => e.links,
            None => return false
        };

        // Sanity check
        if links.tick != timeout.tick {
            return false;
        }

        self.unlink(&links, timeout.token);
        self.entries.remove(timeout.token);
        true
    }

    fn insert(&mut self, token: T, tick: u64) -> TimerResult<Timeout> {
        // Get the slot for the requested tick
        let slot = (tick & self.mask) as uint;
        let curr = self.wheel[slot];

        // Insert the new entry
        let token = try!(
            self.entries.insert(Entry::new(token, tick, curr))
            .map_err(|_| TimerError::overflow()));

        if curr != EMPTY {
            // If there was a previous entry, set its prev pointer to the new
            // entry
            self.entries[curr].links.prev = token;
        }

        // Update the head slot
        *self.wheel.get_mut(slot) = token;

        debug!("inserted timout; slot={}; token={}", slot, token);

        // Return the new timeout
        Ok(Timeout {
            token: token,
            tick: tick
        })
    }

    fn unlink(&mut self, links: &EntryLinks, token: Token) {
        debug!("unlinking timeout; slot={}; token={}",
               self.slot_for(links.tick), token);

        if links.prev == EMPTY {
            let slot = self.slot_for(links.tick);
            *self.wheel.get_mut(slot) = links.next;
        } else {
            self.entries[links.prev].links.next = links.next;
        }

        if links.next != EMPTY {
            self.entries[links.next].links.prev = links.prev;

            if token == self.next {
                self.next = links.next;
            }
        } else if token == self.next {
            self.next = EMPTY;
        }
    }

    /*
     *
     * ===== Advance time =====
     *
     */

    pub fn now(&self) -> u64 {
        self.ms_to_tick(self.now_ms())
    }

    pub fn tick_to(&mut self, now: u64) -> Option<T> {
        debug!("tick_to; now={}; tick={}", now, self.tick);

        while self.tick <= now {
            let curr = self.next;

            debug!("ticking; curr={}", curr);

            if curr == EMPTY {
                self.tick += 1;
                self.next = self.wheel[self.slot_for(self.tick)];
            } else {
                let links = self.entries[curr].links;

                if links.tick <= self.tick {
                    debug!("triggering; token={}", curr);

                    // Unlink will also advance self.next
                    self.unlink(&links, curr);

                    // Remove and return the token
                    return self.entries.remove(curr)
                        .map(|e| e.token);
                } else {
                    self.next = links.next;
                }
            }
        }

        None
    }

    /*
     *
     * ===== Misc =====
     *
     */

    // Timers are initialized when either the current time has been advanced or a timeout has been set
    #[inline]
    fn is_initialized(&self) -> bool {
        self.tick > 0 || !self.entries.is_empty()
    }

    #[inline]
    fn slot_for(&self, tick: u64) -> uint {
        (self.mask & tick) as uint
    }

    // Convert a ms duration into a number of ticks, rounds up
    #[inline]
    fn ms_to_tick(&self, ms: u64) -> u64 {
        (ms - self.start) / self.tick_ms
    }

    #[inline]
    fn now_ms(&self) -> u64 {
        precise_time_ns() / NS_PER_MS
    }
}

// Doubly linked list of timer entries. Allows for efficient insertion /
// removal of timeouts.
struct Entry<T> {
    token: T,
    links: EntryLinks,
}

impl<T> Entry<T> {
    fn new(token: T, tick: u64, next: Token) -> Entry<T> {
        Entry {
            token: token,
            links: EntryLinks {
                tick: tick,
                prev: EMPTY,
                next: next,
            },
        }
    }
}

struct EntryLinks {
    tick: u64,
    prev: Token,
    next: Token
}

pub type TimerResult<T> = Result<T, TimerError>;

#[deriving(Show)]
pub struct TimerError {
    kind: TimerErrorKind,
    desc: &'static str,
}

impl TimerError {
    fn overflow() -> TimerError {
        TimerError {
            kind: TimerOverflow,
            desc: "too many timer entries"
        }
    }
}

#[deriving(Show)]
pub enum TimerErrorKind {
    TimerOverflow,
}

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

    #[test]
    pub fn test_timeout_next_tick() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 100).unwrap();

        tick = t.ms_to_tick(50);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(100);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(150);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));

        assert_eq!(t.count(), 0);
    }

    #[test]
    pub fn test_clearing_timeout() {
        let mut t = timer();
        let mut tick;

        let to = t.timeout_at_ms("a", 100).unwrap();
        assert!(t.clear(to));

        tick = t.ms_to_tick(100);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));

        assert_eq!(t.count(), 0);
    }

    #[test]
    pub fn test_multiple_timeouts_same_tick() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 100).unwrap();
        t.timeout_at_ms("b", 100).unwrap();

        let mut rcv = vec![];

        tick = t.ms_to_tick(100);
        rcv.push(t.tick_to(tick).unwrap());
        rcv.push(t.tick_to(tick).unwrap());

        assert_eq!(None, t.tick_to(tick));

        rcv.sort();
        assert!(rcv.as_slice() == ["a", "b"], "actual={}", rcv.as_slice());

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));

        assert_eq!(t.count(), 0);
    }

    #[test]
    pub fn test_multiple_timeouts_diff_tick() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 110).unwrap();
        t.timeout_at_ms("b", 220).unwrap();
        t.timeout_at_ms("c", 230).unwrap();
        t.timeout_at_ms("d", 440).unwrap();

        tick = t.ms_to_tick(100);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(300);
        assert_eq!(Some("c"), t.tick_to(tick));
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(400);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(500);
        assert_eq!(Some("d"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(600);
        assert_eq!(None, t.tick_to(tick));
    }

    #[test]
    pub fn test_catching_up() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 110).unwrap();
        t.timeout_at_ms("b", 220).unwrap();
        t.timeout_at_ms("c", 230).unwrap();
        t.timeout_at_ms("d", 440).unwrap();

        tick = t.ms_to_tick(600);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(Some("c"), t.tick_to(tick));
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(Some("d"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));
    }

    #[test]
    pub fn test_timeout_hash_collision() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 100).unwrap();
        t.timeout_at_ms("b", 100 + TICK * SLOTS as u64).unwrap();

        tick = t.ms_to_tick(100);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(1, t.count());

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));
        assert_eq!(1, t.count());

        tick = t.ms_to_tick(100 + TICK * SLOTS as u64);
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(0, t.count());
    }

    #[test]
    pub fn test_clearing_timeout_between_triggers() {
        let mut t = timer();
        let mut tick;

        let a = t.timeout_at_ms("a", 100).unwrap();
        let _ = t.timeout_at_ms("b", 100).unwrap();
        let _ = t.timeout_at_ms("c", 200).unwrap();

        tick = t.ms_to_tick(100);
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(2, t.count());

        t.clear(a);
        assert_eq!(1, t.count());

        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(Some("c"), t.tick_to(tick));
        assert_eq!(0, t.count());
    }

    const TICK: u64 = 100;
    const SLOTS: uint = 16;

    fn timer() -> Timer<&'static str> {
        Timer::new(TICK, SLOTS, 32)
    }
}
<commit_msg>Use Vec []-operator instead of deprecated get_mut<commit_after>use std::uint;
use std::num;
use time::precise_time_ns;
use token::Token;
use util::Slab;

const EMPTY: Token = Token(uint::MAX);
const NS_PER_MS: u64 = 1_000_000;

// Implements coarse-grained timeouts using an algorithm based on hashed timing
// wheels by Varghese & Lauck.
//
// TODO:
// * Handle the case when the timer falls more than an entire wheel behind. There
//   is no point to loop multiple times around the wheel in one go.
// * New type for tick, now() -> Tick
pub struct Timer<T> {
    // Size of each tick in milliseconds
    tick_ms: u64,
    // Slab of timeout entries
    entries: Slab<Entry<T>>,
    // Timeout wheel. Each tick, the timer will look at the next slot for
    // timeouts that match the current tick.
    wheel: Vec<Token>,
    // Tick 0's time in milliseconds
    start: u64,
    // The current tick
    tick: u64,
    // The next entry to possibly timeout
    next: Token,
    // Masks the target tick to get the slot
    mask: u64,
}

pub struct Timeout {
    // Reference into the timer entry slab
    token: Token,
    // Tick that it should matchup with
    tick: u64,
}

impl<T> Timer<T> {
    pub fn new(tick_ms: u64, mut slots: uint, mut capacity: uint) -> Timer<T> {
        slots = num::next_power_of_two(slots);
        capacity = num::next_power_of_two(capacity);

        Timer {
            tick_ms: tick_ms,
            entries: Slab::new(capacity),
            wheel: Vec::from_fn(slots, |_| EMPTY),
            start: 0,
            tick: 0,
            next: EMPTY,
            mask: (slots as u64) - 1
        }
    }

    pub fn count(&self) -> uint {
        self.entries.count()
    }

    // Number of ms remaining until the next tick
    pub fn next_tick_in_ms(&self) -> u64 {
        let now = self.now_ms();
        let nxt = self.start + (self.tick + 1) * self.tick_ms;

        if nxt <= now {
            return 0;
        }

        nxt - now
    }

    /*
     *
     * ===== Initialization =====
     *
     */

    // Sets the starting time of the timer using the current system time
    pub fn setup(&mut self) {
        let now = self.now_ms();
        self.set_start_ms(now);
    }

    fn set_start_ms(&mut self, start: u64) {
        assert!(!self.is_initialized(), "the timer has already started");
        self.start = start;
    }

    /*
     *
     * ===== Timeout create / cancel =====
     *
     */

    pub fn timeout_ms(&mut self, token: T, delay: u64) -> TimerResult<Timeout> {
        let at = self.now_ms() + delay;
        self.timeout_at_ms(token, at)
    }

    pub fn timeout_at_ms(&mut self, token: T, mut at: u64) -> TimerResult<Timeout> {
        // Make relative to start
        at -= self.start;
        // Calculate tick
        let mut tick = (at + self.tick_ms - 1) / self.tick_ms;

        // Always target at least 1 tick in the future
        if tick <= self.tick {
            tick = self.tick + 1;
        }

        self.insert(token, tick)
    }

    pub fn clear(&mut self, timeout: Timeout) -> bool {
        let links = match self.entries.get(timeout.token) {
            Some(e) => e.links,
            None => return false
        };

        // Sanity check
        if links.tick != timeout.tick {
            return false;
        }

        self.unlink(&links, timeout.token);
        self.entries.remove(timeout.token);
        true
    }

    fn insert(&mut self, token: T, tick: u64) -> TimerResult<Timeout> {
        // Get the slot for the requested tick
        let slot = (tick & self.mask) as uint;
        let curr = self.wheel[slot];

        // Insert the new entry
        let token = try!(
            self.entries.insert(Entry::new(token, tick, curr))
            .map_err(|_| TimerError::overflow()));

        if curr != EMPTY {
            // If there was a previous entry, set its prev pointer to the new
            // entry
            self.entries[curr].links.prev = token;
        }

        // Update the head slot
        self.wheel[slot] = token;

        debug!("inserted timout; slot={}; token={}", slot, token);

        // Return the new timeout
        Ok(Timeout {
            token: token,
            tick: tick
        })
    }

    fn unlink(&mut self, links: &EntryLinks, token: Token) {
        debug!("unlinking timeout; slot={}; token={}",
               self.slot_for(links.tick), token);

        if links.prev == EMPTY {
            let slot = self.slot_for(links.tick);
            self.wheel[slot] = links.next;
        } else {
            self.entries[links.prev].links.next = links.next;
        }

        if links.next != EMPTY {
            self.entries[links.next].links.prev = links.prev;

            if token == self.next {
                self.next = links.next;
            }
        } else if token == self.next {
            self.next = EMPTY;
        }
    }

    /*
     *
     * ===== Advance time =====
     *
     */

    pub fn now(&self) -> u64 {
        self.ms_to_tick(self.now_ms())
    }

    pub fn tick_to(&mut self, now: u64) -> Option<T> {
        debug!("tick_to; now={}; tick={}", now, self.tick);

        while self.tick <= now {
            let curr = self.next;

            debug!("ticking; curr={}", curr);

            if curr == EMPTY {
                self.tick += 1;
                self.next = self.wheel[self.slot_for(self.tick)];
            } else {
                let links = self.entries[curr].links;

                if links.tick <= self.tick {
                    debug!("triggering; token={}", curr);

                    // Unlink will also advance self.next
                    self.unlink(&links, curr);

                    // Remove and return the token
                    return self.entries.remove(curr)
                        .map(|e| e.token);
                } else {
                    self.next = links.next;
                }
            }
        }

        None
    }

    /*
     *
     * ===== Misc =====
     *
     */

    // Timers are initialized when either the current time has been advanced or a timeout has been set
    #[inline]
    fn is_initialized(&self) -> bool {
        self.tick > 0 || !self.entries.is_empty()
    }

    #[inline]
    fn slot_for(&self, tick: u64) -> uint {
        (self.mask & tick) as uint
    }

    // Convert a ms duration into a number of ticks, rounds up
    #[inline]
    fn ms_to_tick(&self, ms: u64) -> u64 {
        (ms - self.start) / self.tick_ms
    }

    #[inline]
    fn now_ms(&self) -> u64 {
        precise_time_ns() / NS_PER_MS
    }
}

// Doubly linked list of timer entries. Allows for efficient insertion /
// removal of timeouts.
struct Entry<T> {
    token: T,
    links: EntryLinks,
}

impl<T> Entry<T> {
    fn new(token: T, tick: u64, next: Token) -> Entry<T> {
        Entry {
            token: token,
            links: EntryLinks {
                tick: tick,
                prev: EMPTY,
                next: next,
            },
        }
    }
}

struct EntryLinks {
    tick: u64,
    prev: Token,
    next: Token
}

pub type TimerResult<T> = Result<T, TimerError>;

#[deriving(Show)]
pub struct TimerError {
    kind: TimerErrorKind,
    desc: &'static str,
}

impl TimerError {
    fn overflow() -> TimerError {
        TimerError {
            kind: TimerOverflow,
            desc: "too many timer entries"
        }
    }
}

#[deriving(Show)]
pub enum TimerErrorKind {
    TimerOverflow,
}

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

    #[test]
    pub fn test_timeout_next_tick() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 100).unwrap();

        tick = t.ms_to_tick(50);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(100);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(150);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));

        assert_eq!(t.count(), 0);
    }

    #[test]
    pub fn test_clearing_timeout() {
        let mut t = timer();
        let mut tick;

        let to = t.timeout_at_ms("a", 100).unwrap();
        assert!(t.clear(to));

        tick = t.ms_to_tick(100);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));

        assert_eq!(t.count(), 0);
    }

    #[test]
    pub fn test_multiple_timeouts_same_tick() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 100).unwrap();
        t.timeout_at_ms("b", 100).unwrap();

        let mut rcv = vec![];

        tick = t.ms_to_tick(100);
        rcv.push(t.tick_to(tick).unwrap());
        rcv.push(t.tick_to(tick).unwrap());

        assert_eq!(None, t.tick_to(tick));

        rcv.sort();
        assert!(rcv.as_slice() == ["a", "b"], "actual={}", rcv.as_slice());

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));

        assert_eq!(t.count(), 0);
    }

    #[test]
    pub fn test_multiple_timeouts_diff_tick() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 110).unwrap();
        t.timeout_at_ms("b", 220).unwrap();
        t.timeout_at_ms("c", 230).unwrap();
        t.timeout_at_ms("d", 440).unwrap();

        tick = t.ms_to_tick(100);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(300);
        assert_eq!(Some("c"), t.tick_to(tick));
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(400);
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(500);
        assert_eq!(Some("d"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(600);
        assert_eq!(None, t.tick_to(tick));
    }

    #[test]
    pub fn test_catching_up() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 110).unwrap();
        t.timeout_at_ms("b", 220).unwrap();
        t.timeout_at_ms("c", 230).unwrap();
        t.timeout_at_ms("d", 440).unwrap();

        tick = t.ms_to_tick(600);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(Some("c"), t.tick_to(tick));
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(Some("d"), t.tick_to(tick));
        assert_eq!(None, t.tick_to(tick));
    }

    #[test]
    pub fn test_timeout_hash_collision() {
        let mut t = timer();
        let mut tick;

        t.timeout_at_ms("a", 100).unwrap();
        t.timeout_at_ms("b", 100 + TICK * SLOTS as u64).unwrap();

        tick = t.ms_to_tick(100);
        assert_eq!(Some("a"), t.tick_to(tick));
        assert_eq!(1, t.count());

        tick = t.ms_to_tick(200);
        assert_eq!(None, t.tick_to(tick));
        assert_eq!(1, t.count());

        tick = t.ms_to_tick(100 + TICK * SLOTS as u64);
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(0, t.count());
    }

    #[test]
    pub fn test_clearing_timeout_between_triggers() {
        let mut t = timer();
        let mut tick;

        let a = t.timeout_at_ms("a", 100).unwrap();
        let _ = t.timeout_at_ms("b", 100).unwrap();
        let _ = t.timeout_at_ms("c", 200).unwrap();

        tick = t.ms_to_tick(100);
        assert_eq!(Some("b"), t.tick_to(tick));
        assert_eq!(2, t.count());

        t.clear(a);
        assert_eq!(1, t.count());

        assert_eq!(None, t.tick_to(tick));

        tick = t.ms_to_tick(200);
        assert_eq!(Some("c"), t.tick_to(tick));
        assert_eq!(0, t.count());
    }

    const TICK: u64 = 100;
    const SLOTS: uint = 16;

    fn timer() -> Timer<&'static str> {
        Timer::new(TICK, SLOTS, 32)
    }
}
<|endoftext|>


<commit_before><commit_msg>Get started with importing the context scheme to userspace<commit_after>use redox::Box;
use redox::cell::UnsafeCell;
use redox::console::ConsoleWindow;
use redox::fs::file::File;
use redox::rc::Rc;
use redox::str;
use redox::string::*;
use redox::io::SeekFrom;

pub struct Scheme;

impl Scheme {
    fn scheme(&self) -> Box<Self> {
        box Scheme
    }

    fn open(&mut self, url: &URL) -> Option<Box<Resource>> {
        let i;
        let len;
        unsafe {
            /*
            let reenable = scheduler::start_no_ints();
            i = context_i;
            len = (*contexts_ptr).len();
            scheduler::end_no_ints(reenable);
            */
        }

        Some(box Resource::new(File::open("context://"), ("Current: ".to_string() + i + "\nTotal: " + len).to_utf8()))
    }
}
<|endoftext|>


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

/// Formatting of chained expressions, i.e. expressions which are chained by
/// dots: struct and enum field access and method calls.
///
/// Instead of walking these subexpressions one-by-one, as is our usual strategy
/// for expression formatting, we collect maximal sequences of these expressions
/// and handle them simultaneously.
///
/// Whenever possible, the entire chain is put on a single line. If that fails,
/// we put each subexpression on a separate, much like the (default) function
/// argument function argument strategy.
///
/// Depends on config options: `chain_base_indent` is the indent to use for
/// blocks in the parent/root/base of the chain.
/// E.g., `let foo = { aaaa; bbb; ccc }.bar.baz();`, we would layout for the
/// following values of `chain_base_indent`:
/// Visual:
/// ```
/// let foo = {
///               aaaa;
///               bbb;
///               ccc
///           }
///           .bar
///           .baz();
/// ```
/// Inherit:
/// ```
/// let foo = {
///     aaaa;
///     bbb;
///     ccc
/// }
/// .bar
/// .baz();
/// ```
/// Tabbed:
/// ```
/// let foo = {
///         aaaa;
///         bbb;
///         ccc
///     }
///     .bar
///     .baz();
/// ```
///
/// `chain_indent` dictates how the rest of the chain is aligned.
/// If the first item in the chain is a block expression, we align the dots with
/// the braces.
/// Visual:
/// ```
/// let a = foo.bar
///            .baz()
///            .qux
/// ```
/// Inherit:
/// ```
/// let a = foo.bar
/// .baz()
/// .qux
/// ```
/// Tabbed:
/// ```
/// let a = foo.bar
///     .baz()
///     .qux
/// ```
/// `chains_overflow_last` applies only to chains where the last item is a
/// method call. Usually, any line break in a chain sub-expression causes the
/// whole chain to be split with newlines at each `.`. With `chains_overflow_last`
/// true, then we allow the last method call to spill over multiple lines without
/// forcing the rest of the chain to be split.

use Indent;
use rewrite::{Rewrite, RewriteContext};
use utils::{wrap_str, first_line_width};
use expr::rewrite_call;
use config::BlockIndentStyle;

use syntax::{ast, ptr};
use syntax::codemap::{mk_sp, Span};

pub fn rewrite_chain(expr: &ast::Expr,
                     context: &RewriteContext,
                     width: usize,
                     offset: Indent)
                     -> Option<String> {
    let total_span = expr.span;
    let (parent, subexpr_list) = make_subexpr_list(expr);

    // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
    let parent_block_indent = chain_base_indent(context, offset);
    let parent_context = &RewriteContext { block_indent: parent_block_indent, ..*context };
    let parent_rewrite = try_opt!(parent.rewrite(parent_context, width, offset));

    // Decide how to layout the rest of the chain. `extend` is true if we can
    // put the first non-parent item on the same line as the parent.
    let (indent, extend) = if !parent_rewrite.contains('\n') && is_continuable(parent) ||
                              parent_rewrite.len() <= context.config.tab_spaces {
        // Try and put at least the first two items on the same line.
        (chain_indent(context, offset + Indent::new(0, parent_rewrite.len())), true)
    } else if is_block_expr(parent, &parent_rewrite) {
        // The parent is a block, so align the rest of the chain with the closing
        // brace.
        (parent_block_indent, false)
    } else if parent_rewrite.contains('\n') {
        (chain_indent(context, parent_block_indent.block_indent(context.config)), false)
    } else {
        (chain_indent_newline(context, offset + Indent::new(0, parent_rewrite.len())), false)
    };

    let max_width = try_opt!((width + offset.width()).checked_sub(indent.width()));
    let mut rewrites = try_opt!(subexpr_list.iter()
        .rev()
        .map(|e| rewrite_chain_subexpr(e, total_span, context, max_width, indent))
        .collect::<Option<Vec<_>>>());

    // Total of all items excluding the last.
    let almost_total = rewrites[..rewrites.len() - 1]
        .iter()
        .fold(0, |a, b| a + first_line_width(b)) + parent_rewrite.len();
    let total_width = almost_total + first_line_width(rewrites.last().unwrap());

    let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
        // Look at the source code. Unless all chain elements start on the same
        // line, we won't consider putting them on a single line either.
        let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
        let first_span = context.snippet(subexpr_list[1].span);
        let last_iter = last_span.chars().take_while(|c| c.is_whitespace());

        first_span.chars().chain(last_iter).any(|c| c == '\n')
    } else {
        false
    };

    let mut fits_single_line = !veto_single_line && total_width <= width;
    if fits_single_line {
        let len = rewrites.len();
        let (init, last) = rewrites.split_at_mut(len - 1);
        fits_single_line = init.iter().all(|s| !s.contains('\n'));

        if fits_single_line {
            fits_single_line = match expr.node {
                ref e @ ast::ExprKind::MethodCall(..) if context.config.chains_overflow_last => {
                    rewrite_method_call_with_overflow(e,
                                                      &mut last[0],
                                                      almost_total,
                                                      width,
                                                      total_span,
                                                      context,
                                                      offset)
                }
                _ => !last[0].contains('\n'),
            }
        }
    }

    let connector = if fits_single_line && !parent_rewrite.contains('\n') {
        // Yay, we can put everything on one line.
        String::new()
    } else {
        // Use new lines.
        format!("\n{}", indent.to_string(context.config))
    };

    let first_connector = if extend {
        ""
    } else {
        &connector
    };

    wrap_str(format!("{}{}{}",
                     parent_rewrite,
                     first_connector,
                     rewrites.join(&connector)),
             context.config.max_width,
             width,
             offset)
}

// States whether an expression's last line exclusively consists of closing
// parens, braces, and brackets in its idiomatic formatting.
fn is_block_expr(expr: &ast::Expr, repr: &str) -> bool {
    match expr.node {
        ast::ExprKind::Struct(..) |
        ast::ExprKind::While(..) |
        ast::ExprKind::WhileLet(..) |
        ast::ExprKind::If(..) |
        ast::ExprKind::IfLet(..) |
        ast::ExprKind::Block(..) |
        ast::ExprKind::Loop(..) |
        ast::ExprKind::ForLoop(..) |
        ast::ExprKind::Match(..) => repr.contains('\n'),
        ast::ExprKind::Paren(ref expr) |
        ast::ExprKind::Binary(_, _, ref expr) |
        ast::ExprKind::Index(_, ref expr) |
        ast::ExprKind::Unary(_, ref expr) => is_block_expr(expr, repr),
        _ => false,
    }
}

// Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
// E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
fn make_subexpr_list(mut expr: &ast::Expr) -> (&ast::Expr, Vec<&ast::Expr>) {
    fn pop_expr_chain(expr: &ast::Expr) -> Option<&ast::Expr> {
        match expr.node {
            ast::ExprKind::MethodCall(_, _, ref expressions) => Some(&expressions[0]),
            ast::ExprKind::TupField(ref subexpr, _) |
            ast::ExprKind::Field(ref subexpr, _) => Some(subexpr),
            _ => None,
        }
    }

    let mut subexpr_list = vec![expr];

    while let Some(subexpr) = pop_expr_chain(expr) {
        subexpr_list.push(subexpr);
        expr = subexpr;
    }

    let parent = subexpr_list.pop().unwrap();
    (parent, subexpr_list)
}

fn chain_base_indent(context: &RewriteContext, offset: Indent) -> Indent {
    match context.config.chain_base_indent {
        BlockIndentStyle::Visual => offset,
        BlockIndentStyle::Inherit => context.block_indent,
        BlockIndentStyle::Tabbed => context.block_indent.block_indent(context.config),
    }
}

fn chain_indent(context: &RewriteContext, offset: Indent) -> Indent {
    match context.config.chain_indent {
        BlockIndentStyle::Visual => offset,
        BlockIndentStyle::Inherit => context.block_indent,
        BlockIndentStyle::Tabbed => context.block_indent.block_indent(context.config),
    }
}

// Ignores visual indenting because this function should be called where it is
// not possible to use visual indentation because we are starting on a newline.
fn chain_indent_newline(context: &RewriteContext, _offset: Indent) -> Indent {
    match context.config.chain_indent {
        BlockIndentStyle::Inherit => context.block_indent,
        BlockIndentStyle::Visual | BlockIndentStyle::Tabbed => {
            context.block_indent.block_indent(context.config)
        }
    }
}

fn rewrite_method_call_with_overflow(expr_kind: &ast::ExprKind,
                                     last: &mut String,
                                     almost_total: usize,
                                     width: usize,
                                     total_span: Span,
                                     context: &RewriteContext,
                                     offset: Indent)
                                     -> bool {
    if let &ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) = expr_kind {
        let budget = match width.checked_sub(almost_total) {
            Some(b) => b,
            None => return false,
        };
        let mut last_rewrite = rewrite_method_call(method_name.node,
                                                   types,
                                                   expressions,
                                                   total_span,
                                                   context,
                                                   budget,
                                                   offset + almost_total);

        if let Some(ref mut s) = last_rewrite {
            ::std::mem::swap(s, last);
            true
        } else {
            false
        }
    } else {
        unreachable!();
    }
}

// Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
// `.c`.
fn rewrite_chain_subexpr(expr: &ast::Expr,
                         span: Span,
                         context: &RewriteContext,
                         width: usize,
                         offset: Indent)
                         -> Option<String> {
    match expr.node {
        ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) => {
            let inner = &RewriteContext { block_indent: offset, ..*context };
            rewrite_method_call(method_name.node,
                                types,
                                expressions,
                                span,
                                inner,
                                width,
                                offset)
        }
        ast::ExprKind::Field(_, ref field) => {
            let s = format!(".{}", field.node);
            if s.len() <= width {
                Some(s)
            } else {
                None
            }
        }
        ast::ExprKind::TupField(_, ref field) => {
            let s = format!(".{}", field.node);
            if s.len() <= width {
                Some(s)
            } else {
                None
            }
        }
        _ => unreachable!(),
    }
}

// Determines if we can continue formatting a given expression on the same line.
fn is_continuable(expr: &ast::Expr) -> bool {
    match expr.node {
        ast::ExprKind::Path(..) => true,
        _ => false,
    }
}

fn rewrite_method_call(method_name: ast::Ident,
                       types: &[ptr::P<ast::Ty>],
                       args: &[ptr::P<ast::Expr>],
                       span: Span,
                       context: &RewriteContext,
                       width: usize,
                       offset: Indent)
                       -> Option<String> {
    let (lo, type_str) = if types.is_empty() {
        (args[0].span.hi, String::new())
    } else {
        let type_list: Vec<_> = try_opt!(types.iter()
            .map(|ty| ty.rewrite(context, width, offset))
            .collect());

        (types.last().unwrap().span.hi, format!("::<{}>", type_list.join(", ")))
    };

    let callee_str = format!(".{}{}", method_name, type_str);
    let span = mk_sp(lo, span.hi);

    rewrite_call(context, &callee_str, &args[1..], span, width, offset)
}
<commit_msg>Fix for stable<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/// Formatting of chained expressions, i.e. expressions which are chained by
/// dots: struct and enum field access and method calls.
///
/// Instead of walking these subexpressions one-by-one, as is our usual strategy
/// for expression formatting, we collect maximal sequences of these expressions
/// and handle them simultaneously.
///
/// Whenever possible, the entire chain is put on a single line. If that fails,
/// we put each subexpression on a separate, much like the (default) function
/// argument function argument strategy.
///
/// Depends on config options: `chain_base_indent` is the indent to use for
/// blocks in the parent/root/base of the chain.
/// E.g., `let foo = { aaaa; bbb; ccc }.bar.baz();`, we would layout for the
/// following values of `chain_base_indent`:
/// Visual:
/// ```
/// let foo = {
///               aaaa;
///               bbb;
///               ccc
///           }
///           .bar
///           .baz();
/// ```
/// Inherit:
/// ```
/// let foo = {
///     aaaa;
///     bbb;
///     ccc
/// }
/// .bar
/// .baz();
/// ```
/// Tabbed:
/// ```
/// let foo = {
///         aaaa;
///         bbb;
///         ccc
///     }
///     .bar
///     .baz();
/// ```
///
/// `chain_indent` dictates how the rest of the chain is aligned.
/// If the first item in the chain is a block expression, we align the dots with
/// the braces.
/// Visual:
/// ```
/// let a = foo.bar
///            .baz()
///            .qux
/// ```
/// Inherit:
/// ```
/// let a = foo.bar
/// .baz()
/// .qux
/// ```
/// Tabbed:
/// ```
/// let a = foo.bar
///     .baz()
///     .qux
/// ```
/// `chains_overflow_last` applies only to chains where the last item is a
/// method call. Usually, any line break in a chain sub-expression causes the
/// whole chain to be split with newlines at each `.`. With `chains_overflow_last`
/// true, then we allow the last method call to spill over multiple lines without
/// forcing the rest of the chain to be split.

use Indent;
use rewrite::{Rewrite, RewriteContext};
use utils::{wrap_str, first_line_width};
use expr::rewrite_call;
use config::BlockIndentStyle;

use syntax::{ast, ptr};
use syntax::codemap::{mk_sp, Span};

pub fn rewrite_chain(expr: &ast::Expr,
                     context: &RewriteContext,
                     width: usize,
                     offset: Indent)
                     -> Option<String> {
    let total_span = expr.span;
    let (parent, subexpr_list) = make_subexpr_list(expr);

    // Parent is the first item in the chain, e.g., `foo` in `foo.bar.baz()`.
    let parent_block_indent = chain_base_indent(context, offset);
    let parent_context = &RewriteContext { block_indent: parent_block_indent, ..*context };
    let parent_rewrite = try_opt!(parent.rewrite(parent_context, width, offset));

    // Decide how to layout the rest of the chain. `extend` is true if we can
    // put the first non-parent item on the same line as the parent.
    let (indent, extend) = if !parent_rewrite.contains('\n') && is_continuable(parent) ||
                              parent_rewrite.len() <= context.config.tab_spaces {
        // Try and put at least the first two items on the same line.
        (chain_indent(context, offset + Indent::new(0, parent_rewrite.len())), true)
    } else if is_block_expr(parent, &parent_rewrite) {
        // The parent is a block, so align the rest of the chain with the closing
        // brace.
        (parent_block_indent, false)
    } else if parent_rewrite.contains('\n') {
        (chain_indent(context, parent_block_indent.block_indent(context.config)), false)
    } else {
        (chain_indent_newline(context, offset + Indent::new(0, parent_rewrite.len())), false)
    };

    let max_width = try_opt!((width + offset.width()).checked_sub(indent.width()));
    let mut rewrites = try_opt!(subexpr_list.iter()
        .rev()
        .map(|e| rewrite_chain_subexpr(e, total_span, context, max_width, indent))
        .collect::<Option<Vec<_>>>());

    // Total of all items excluding the last.
    let almost_total = rewrites[..rewrites.len() - 1]
        .iter()
        .fold(0, |a, b| a + first_line_width(b)) + parent_rewrite.len();
    let total_width = almost_total + first_line_width(rewrites.last().unwrap());

    let veto_single_line = if context.config.take_source_hints && subexpr_list.len() > 1 {
        // Look at the source code. Unless all chain elements start on the same
        // line, we won't consider putting them on a single line either.
        let last_span = context.snippet(mk_sp(subexpr_list[1].span.hi, total_span.hi));
        let first_span = context.snippet(subexpr_list[1].span);
        let last_iter = last_span.chars().take_while(|c| c.is_whitespace());

        first_span.chars().chain(last_iter).any(|c| c == '\n')
    } else {
        false
    };

    let mut fits_single_line = !veto_single_line && total_width <= width;
    if fits_single_line {
        let len = rewrites.len();
        let (init, last) = rewrites.split_at_mut(len - 1);
        fits_single_line = init.iter().all(|s| !s.contains('\n'));

        if fits_single_line {
            fits_single_line = match expr.node {
                ref e @ ast::ExprKind::MethodCall(..) if context.config.chains_overflow_last => {
                    rewrite_method_call_with_overflow(e,
                                                      &mut last[0],
                                                      almost_total,
                                                      width,
                                                      total_span,
                                                      context,
                                                      offset)
                }
                _ => !last[0].contains('\n'),
            }
        }
    }

    let connector = if fits_single_line && !parent_rewrite.contains('\n') {
        // Yay, we can put everything on one line.
        String::new()
    } else {
        // Use new lines.
        format!("\n{}", indent.to_string(context.config))
    };

    let first_connector = if extend {
        ""
    } else {
        &*connector
    };

    wrap_str(format!("{}{}{}",
                     parent_rewrite,
                     first_connector,
                     rewrites.join(&connector)),
             context.config.max_width,
             width,
             offset)
}

// States whether an expression's last line exclusively consists of closing
// parens, braces, and brackets in its idiomatic formatting.
fn is_block_expr(expr: &ast::Expr, repr: &str) -> bool {
    match expr.node {
        ast::ExprKind::Struct(..) |
        ast::ExprKind::While(..) |
        ast::ExprKind::WhileLet(..) |
        ast::ExprKind::If(..) |
        ast::ExprKind::IfLet(..) |
        ast::ExprKind::Block(..) |
        ast::ExprKind::Loop(..) |
        ast::ExprKind::ForLoop(..) |
        ast::ExprKind::Match(..) => repr.contains('\n'),
        ast::ExprKind::Paren(ref expr) |
        ast::ExprKind::Binary(_, _, ref expr) |
        ast::ExprKind::Index(_, ref expr) |
        ast::ExprKind::Unary(_, ref expr) => is_block_expr(expr, repr),
        _ => false,
    }
}

// Returns the root of the chain and a Vec of the prefixes of the rest of the chain.
// E.g., for input `a.b.c` we return (`a`, [`a.b.c`, `a.b`])
fn make_subexpr_list(mut expr: &ast::Expr) -> (&ast::Expr, Vec<&ast::Expr>) {
    fn pop_expr_chain(expr: &ast::Expr) -> Option<&ast::Expr> {
        match expr.node {
            ast::ExprKind::MethodCall(_, _, ref expressions) => Some(&expressions[0]),
            ast::ExprKind::TupField(ref subexpr, _) |
            ast::ExprKind::Field(ref subexpr, _) => Some(subexpr),
            _ => None,
        }
    }

    let mut subexpr_list = vec![expr];

    while let Some(subexpr) = pop_expr_chain(expr) {
        subexpr_list.push(subexpr);
        expr = subexpr;
    }

    let parent = subexpr_list.pop().unwrap();
    (parent, subexpr_list)
}

fn chain_base_indent(context: &RewriteContext, offset: Indent) -> Indent {
    match context.config.chain_base_indent {
        BlockIndentStyle::Visual => offset,
        BlockIndentStyle::Inherit => context.block_indent,
        BlockIndentStyle::Tabbed => context.block_indent.block_indent(context.config),
    }
}

fn chain_indent(context: &RewriteContext, offset: Indent) -> Indent {
    match context.config.chain_indent {
        BlockIndentStyle::Visual => offset,
        BlockIndentStyle::Inherit => context.block_indent,
        BlockIndentStyle::Tabbed => context.block_indent.block_indent(context.config),
    }
}

// Ignores visual indenting because this function should be called where it is
// not possible to use visual indentation because we are starting on a newline.
fn chain_indent_newline(context: &RewriteContext, _offset: Indent) -> Indent {
    match context.config.chain_indent {
        BlockIndentStyle::Inherit => context.block_indent,
        BlockIndentStyle::Visual | BlockIndentStyle::Tabbed => {
            context.block_indent.block_indent(context.config)
        }
    }
}

fn rewrite_method_call_with_overflow(expr_kind: &ast::ExprKind,
                                     last: &mut String,
                                     almost_total: usize,
                                     width: usize,
                                     total_span: Span,
                                     context: &RewriteContext,
                                     offset: Indent)
                                     -> bool {
    if let &ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) = expr_kind {
        let budget = match width.checked_sub(almost_total) {
            Some(b) => b,
            None => return false,
        };
        let mut last_rewrite = rewrite_method_call(method_name.node,
                                                   types,
                                                   expressions,
                                                   total_span,
                                                   context,
                                                   budget,
                                                   offset + almost_total);

        if let Some(ref mut s) = last_rewrite {
            ::std::mem::swap(s, last);
            true
        } else {
            false
        }
    } else {
        unreachable!();
    }
}

// Rewrite the last element in the chain `expr`. E.g., given `a.b.c` we rewrite
// `.c`.
fn rewrite_chain_subexpr(expr: &ast::Expr,
                         span: Span,
                         context: &RewriteContext,
                         width: usize,
                         offset: Indent)
                         -> Option<String> {
    match expr.node {
        ast::ExprKind::MethodCall(ref method_name, ref types, ref expressions) => {
            let inner = &RewriteContext { block_indent: offset, ..*context };
            rewrite_method_call(method_name.node,
                                types,
                                expressions,
                                span,
                                inner,
                                width,
                                offset)
        }
        ast::ExprKind::Field(_, ref field) => {
            let s = format!(".{}", field.node);
            if s.len() <= width {
                Some(s)
            } else {
                None
            }
        }
        ast::ExprKind::TupField(_, ref field) => {
            let s = format!(".{}", field.node);
            if s.len() <= width {
                Some(s)
            } else {
                None
            }
        }
        _ => unreachable!(),
    }
}

// Determines if we can continue formatting a given expression on the same line.
fn is_continuable(expr: &ast::Expr) -> bool {
    match expr.node {
        ast::ExprKind::Path(..) => true,
        _ => false,
    }
}

fn rewrite_method_call(method_name: ast::Ident,
                       types: &[ptr::P<ast::Ty>],
                       args: &[ptr::P<ast::Expr>],
                       span: Span,
                       context: &RewriteContext,
                       width: usize,
                       offset: Indent)
                       -> Option<String> {
    let (lo, type_str) = if types.is_empty() {
        (args[0].span.hi, String::new())
    } else {
        let type_list: Vec<_> = try_opt!(types.iter()
            .map(|ty| ty.rewrite(context, width, offset))
            .collect());

        (types.last().unwrap().span.hi, format!("::<{}>", type_list.join(", ")))
    };

    let callee_str = format!(".{}{}", method_name, type_str);
    let span = mk_sp(lo, span.hi);

    rewrite_call(context, &callee_str, &args[1..], span, width, offset)
}
<|endoftext|>


<commit_before><commit_msg>Add manual page to cp, -h and --help options<commit_after><|endoftext|>


<commit_before><commit_msg>Implemented Lights::search_new_lights()<commit_after><|endoftext|>


<commit_before><commit_msg>Adapt to new libimagstore::iter::Entries API<commit_after><|endoftext|>


<commit_before><commit_msg>Implement is_expired on config<commit_after><|endoftext|>


<commit_before><commit_msg>Add problem #30<commit_after>extern mod std;

use std::sort::{ quick_sort };

// 9^5     = 59049
// 9999    => 9^5 * 4 = 236196
// 99999   => 9^5 * 5 = 295245
// 999999  => 9^5 * 6 = 354294
// 9999999 => 9^5 * 7 = 413343

// 1-6 digits numbers meet conditions
fn main() {
    let pows = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map(|n| int::pow(*n, 5) as uint);
    let nums = [mut 0, 0, 0, 0, 0, 0, 0];
    let mut sum = 0;

    for uint::range(0, 10) |d0| {
        let p0 = pows[d0];
        let s0 = p0;
        for uint::range(d0, 10) |d1| {
            let p1 = pows[d1];
            let s1 = s0 + p1;
            for uint::range(d1, 10) |d2| {
                let p2 = pows[d2];
                let s2 = s1 + p2;
                for uint::range(d2, 10) |d3| {
                    let p3 = pows[d3];
                    let s3 = s2 + p3;
                    for uint::range(d3, 10) |d4| {
                        let p4 = pows[d4];
                        let s4 = s3 + p4;
                        for uint::range(d4, 10) |d5| {
                            let p5 = pows[d5];
                            let s5 = s4 + p5;
                            for uint::range(d5, 10) |d6| {
                                let p6 = pows[d6];
                                let s6 = s5 + p6;
                                let mut itr = s6;
                                for uint::range(0, nums.len()) |i| {
                                    nums[i] = itr % 10;
                                    itr /= 10;
                                }
                                quick_sort(|a, b| a < b, nums);
                                if nums[0] == d0 &&
                                    nums[1] == d1 &&
                                    nums[2] == d2 &&
                                    nums[3] == d3 &&
                                    nums[4] == d4 &&
                                    nums[5] == d5 &&
                                    nums[6] == d6 {
                                    io::println(fmt!("%u", s6));
                                    sum += s6;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    io::println(fmt!("answer: %u", sum - 1)); // remove 1
}
<|endoftext|>


<commit_before><commit_msg>Fix StringExpander::ttyname(): Return the actual name, not the full path.<commit_after><|endoftext|>


<commit_before>use std::io::net::ip::{Port, IpAddr};

use router::Router;
use middleware::{ MiddlewareStack, Middleware, Action };
use into_middleware::IntoMiddleware;
use into_error_handler::IntoErrorHandler;
use nickel_error::{ NickelError, ErrorWithStatusCode };
use server::Server;

use http::method::{ Method, Get, Post, Put, Delete };
use http::status::NotFound;
use request::Request;
use response::Response;

//pre defined middleware
use json_body_parser::JsonBodyParser;
use query_string::QueryStringParser;
use default_error_handler::DefaultErrorHandler;

/// Nickel is the application object. It's the surface that
/// holds all public APIs.

pub struct Nickel{
    middleware_stack: MiddlewareStack,
    server: Option<Server>,
}

impl Nickel {

    /// In order to use Nickels API one first has to create an instance.
    ///
    /// # Example
    /// ```{rust,ignore}
    /// let mut server = Nickel::new();
    /// ```
    pub fn new() -> Nickel {
        let mut middleware_stack = MiddlewareStack::new();

        // Hook up the default error handler by default. Users are
        // free to cancel it out from their custom error handler if
        // they don't like the default behaviour.
        middleware_stack.add_error_handler(DefaultErrorHandler);

        Nickel {
            middleware_stack: middleware_stack,
            server: None
        }
    }

    /// Registers a middleware handler which will be invoked among other middleware
    /// handlers before each request. Middleware can be stacked and is invoked in the
    /// same order it was registered.
    ///
    /// A middleware handler is nearly identical to a regular route handler with the only
    /// difference that it expects a return value of boolean. That is to indicate whether
    /// other middleware handler (if any) further down the stack should continue or if the
    /// middleware invocation should be stopped after the current handler.
    ///
    /// # Example
    ///
    /// ```{rust,ignore}
    /// fn logger (req: &Request, res: &mut Response) -> Result<Action, NickelError>{
    ///     println!("logging request: {}", req.origin.request_uri);
    ///     Ok(Continue)
    /// }
    /// ```
    pub fn utilize<T: Middleware>(&mut self, handler: T){
        self.middleware_stack.add_middleware(handler);
    }

    /// Registers a handler to be used for a specific GET request.
    /// Handlers are assigned to paths and paths are allowed to contain
    /// variables and wildcards.
    ///
    /// A handler added through this API will
    /// be attached to the default router. Consider creating the router
    /// middleware manually for advanced functionality.
    ///
    /// # Example
    ///
    /// ```{rust}
    /// use nickel::{Nickel, Request, Response};
    /// let mut server = Nickel::new();
    ///
    /// //  without variables or wildcards
    /// fn bare_handler(request: &Request, response: &mut Response) {
    ///     response.send("This matches /user");
    /// };
    /// server.get("/user", bare_handler);
    ///
    /// // with variables
    /// fn var_handler(request: &Request, response: &mut Response) {
    ///     let text = format!("This is user: {}", request.param("userid"));
    ///     response.send(text.as_slice());
    /// };
    /// server.get("/user/:userid", var_handler);
    ///
    /// // with simple wildcard
    /// fn wild_handler(request: &Request, response: &mut Response) {
    ///     response.send("This matches /user/list/4711 but not /user/extended/list/4711");
    /// };
    /// server.get("/user/*/:userid", wild_handler);
    ///
    /// // with double wildcard
    /// fn very_wild_handler(request: &Request, response: &mut Response) {
    ///     response.send("This matches /user/list/4711 and also /user/extended/list/4711");
    /// };
    /// server.get("/user/**/:userid", very_wild_handler);
    /// ```
    pub fn get(&mut self, uri: &str, handler: fn(request: &Request, response: &mut Response)){
        self.register_route_with_new_router(Get, uri, handler);
    }

    /// Registers a handler to be used for a specific POST request.
    /// A handler added through this API will be attached to the default router.
    /// Consider creating the router middleware manually for advanced functionality.
    ///
    /// Take a look at `get(...)` for a more detailed description.
    /// # Example
    ///
    /// ```{rust}
    /// use nickel::{Nickel, Request, Response};
    /// fn handler(request: &Request, response: &mut Response) {
    ///     response.send("This matches a POST request to /a/post/request");
    /// };
    ///
    /// let mut server = Nickel::new();
    /// server.post("/a/post/request", handler);
    /// ```
    pub fn post(&mut self, uri: &str, handler: fn(request: &Request, response: &mut Response)){
        self.register_route_with_new_router(Post, uri, handler);
    }

    /// Registers a handler to be used for a specific PUT request.
    /// A handler added through this API will be attached to the default router.
    /// Consider creating the router middleware manually for advanced functionality.
    ///
    /// Take a look at `get(...)` for a more detailed description.
    /// # Example
    ///
    /// ```{rust}
    /// use nickel::{Nickel, Request, Response};
    /// fn handler(request: &Request, response: &mut Response) {
    ///     response.send("This matches a POST request to /a/put/request");
    /// };
    ///
    /// let mut server = Nickel::new();
    /// server.put("/a/put/request", handler);
    /// ```
    pub fn put(&mut self, uri: &str, handler: fn(request: &Request, response: &mut Response)){
        self.register_route_with_new_router(Put, uri, handler);
    }

    /// Registers a handler to be used for a specific DELETE request.
    /// A handler added through this API will be attached to the default router.
    /// Consider creating the router middleware manually for advanced functionality.
    ///
    /// Take a look at `get(...)` for a more detailed description.
    /// # Example
    ///
    /// ```{rust}
    /// use nickel::{Nickel, Request, Response};
    /// fn handler(request: &Request, response: &mut Response) {
    ///     response.send("This matches a DELETE request to /a/delete/request");
    /// };
    ///
    /// let mut server = Nickel::new();
    /// server.delete("/a/delete/request", handler);
    /// ```
    pub fn delete(&mut self, uri: &str, handler: fn(request: &Request, response: &mut Response)){
        self.register_route_with_new_router(Delete, uri, handler);
    }

    fn register_route_with_new_router(&mut self, method: Method, uri: &str, handler: fn(request: &Request, response: &mut Response)) {
        let mut router = Router::new();
        router.add_route(method, String::from_str(uri), handler);
        self.utilize(router);
    }

    /// Registers an error handler which will be invoked among other error handler
    /// as soon as any regular handler returned an error
    ///
    /// A error handler is nearly identical to a regular middleware handler with the only
    /// difference that it takes an additional error parameter or type `NickelError.
    ///
    /// # Example
    ///
    /// ```{rust}
    /// # extern crate http;
    /// # extern crate nickel;
    /// # fn main() {
    /// use nickel::{Nickel, Request, Response, Action, Continue, Halt};
    /// use nickel::{NickelError, ErrorWithStatusCode, get_media_type};
    /// use http::status::NotFound;
    ///
    /// fn error_handler(err: &NickelError, req: &Request, response: &mut Response)
    ///                  -> Result<Action, NickelError>{
    ///    match err.kind {
    ///        ErrorWithStatusCode(NotFound) => {
    ///            response.origin.headers.content_type = get_media_type("html");
    ///            response.origin.status = NotFound;
    ///            response.send("<h1>Call the police!<h1>");
    ///            Ok(Halt)
    ///        },
    ///        _ => Ok(Continue)
    ///    }
    /// }
    ///
    /// let mut server = Nickel::new();
    /// server.handle_error(error_handler)
    /// # }
    /// ```
    pub fn handle_error(&mut self, handler: fn(err: &NickelError,
                                               req: &Request,
                                               res: &mut Response)
                                            -> Result<Action, NickelError>){
        let handler = IntoErrorHandler::from_fn(handler);
        self.middleware_stack.add_error_handler(handler);
    }

    /// Create a new middleware to serve as a router.
    ///
    ///
    /// # Example
    /// ```{rust}
    /// use nickel::{Nickel, Request, Response};
    ///
    /// let mut server = Nickel::new();
    /// let mut router = Nickel::router();
    ///
    /// fn foo_handler(request: &Request, response: &mut Response) {
    ///     response.send("Hi from /foo");
    /// };
    ///
    /// router.get("/foo", foo_handler);
    /// server.utilize(router);
    /// ```
    pub fn router() -> Router {
        Router::new()
    }

    /// Create a new middleware to parse JSON bodies.
    ///
    ///
    /// # Example
    /// ```{rust}
    /// # #![feature(phase)]
    /// # #[phase(plugin)] extern crate nickel_macros;
    /// # extern crate nickel;
    /// # extern crate serialize;
    /// # use nickel::{Nickel, Request, Response};
    /// use nickel::JsonBody;
    ///
    /// # fn main() {
    /// #[deriving(Decodable, Encodable)]
    /// struct Person {
    ///     first_name: String,
    ///     last_name:  String,
    /// }
    ///
    /// let router = router! {
    ///     post "/a/post/request" => |request, response| {
    ///         let person = request.json_as::<Person>().unwrap();
    ///         let text = format!("Hello {} {}", person.first_name, person.last_name);
    ///         response.send(text);
    ///     }
    /// };
    ///
    /// let mut server = Nickel::new();
    /// // It is currently a requirement that the json_body_parser middleware
    /// // is added before any routes that require it.
    /// server.utilize(Nickel::json_body_parser());
    /// server.utilize(router);
    /// # }
    /// ```
    pub fn json_body_parser() -> JsonBodyParser {
        JsonBodyParser
    }

    /// Create a new middleware to parse the query string.
    ///
    ///
    /// # Example
    /// ```{rust}
    /// # #![feature(phase)]
    /// # #[phase(plugin)] extern crate nickel_macros;
    /// # extern crate nickel;
    /// # use nickel::{Nickel, Request, Response};
    /// use nickel::QueryString;
    /// # fn main() {
    /// let router = router! {
    ///     get "/a/get/request" => |request, response| {
    ///         let foo = request.query("foo", "this is the default value, if foo is not present!");
    ///         response.send(foo[0].as_slice());
    ///     }
    /// };
    ///
    /// let mut server = Nickel::new();
    /// // It is currently a requirement that the query_string middleware
    /// // is added before any routes that require it.
    /// server.utilize(Nickel::query_string());
    /// server.utilize(router);
    /// # }
    /// ```
    pub fn query_string() -> QueryStringParser {
        QueryStringParser
    }

    /// Bind and listen for connections on the given host and port
    ///
    /// # Example
    /// ```{rust,ignore}
    /// let mut server = Nickel::new();
    /// server.listen(Ipv4Addr(127, 0, 0, 1), 6767);
    /// ```
    pub fn listen(mut self, ip: IpAddr, port: Port) {
        fn not_found_handler(_request: &Request, _response: &mut Response) -> Result<Action, NickelError> {
            Err(NickelError::new("File Not Found", ErrorWithStatusCode(NotFound)))
        }

        self.middleware_stack.add_middleware(IntoMiddleware::from_fn(not_found_handler));
        self.server = Some(Server::new(self.middleware_stack, ip, port));
        self.server.unwrap().serve();
    }
}
<commit_msg>docs(nickel): fix docs for utilize<commit_after>use std::io::net::ip::{Port, IpAddr};

use router::Router;
use middleware::{ MiddlewareStack, Middleware, Action };
use into_middleware::IntoMiddleware;
use into_error_handler::IntoErrorHandler;
use nickel_error::{ NickelError, ErrorWithStatusCode };
use server::Server;

use http::method::{ Method, Get, Post, Put, Delete };
use http::status::NotFound;
use request::Request;
use response::Response;

//pre defined middleware
use json_body_parser::JsonBodyParser;
use query_string::QueryStringParser;
use default_error_handler::DefaultErrorHandler;

/// Nickel is the application object. It's the surface that
/// holds all public APIs.

pub struct Nickel{
    middleware_stack: MiddlewareStack,
    server: Option<Server>,
}

impl Nickel {

    /// In order to use Nickels API one first has to create an instance.
    ///
    /// # Example
    /// ```{rust,ignore}
    /// let mut server = Nickel::new();
    /// ```
    pub fn new() -> Nickel {
        let mut middleware_stack = MiddlewareStack::new();

        // Hook up the default error handler by default. Users are
        // free to cancel it out from their custom error handler if
        // they don't like the default behaviour.
        middleware_stack.add_error_handler(DefaultErrorHandler);

        Nickel {
            middleware_stack: middleware_stack,
            server: None
        }
    }

    /// Registers a middleware handler which will be invoked among other middleware
    /// handlers before each request. Middleware can be stacked and is invoked in the
    /// same order it was registered.
    ///
    /// A middleware handler is nearly identical to a regular route handler with the only
    /// difference that it expects a result of either Action or NickelError.
    /// That is to indicate whether other middleware handlers (if any) further
    /// down the stack should continue or if the middleware invocation should
    /// be stopped after the current handler.
    ///
    /// # Example
    ///
    /// ```{rust}
    /// use nickel::IntoMiddleware; // This is *hopefully* temporary
    /// use nickel::{Nickel, Request, Response, Action, Continue, NickelError};
    /// fn logger(req: &Request, res: &mut Response) -> Result<Action, NickelError>{
    ///     println!("logging request: {}", req.origin.request_uri);
    ///     Ok(Continue)
    /// }
    ///
    /// let mut server = Nickel::new();
    /// server.utilize(IntoMiddleware::from_fn(logger));
    /// ```
    pub fn utilize<T: Middleware>(&mut self, handler: T){
        self.middleware_stack.add_middleware(handler);
    }

    /// Registers a handler to be used for a specific GET request.
    /// Handlers are assigned to paths and paths are allowed to contain
    /// variables and wildcards.
    ///
    /// A handler added through this API will
    /// be attached to the default router. Consider creating the router
    /// middleware manually for advanced functionality.
    ///
    /// # Example
    ///
    /// ```{rust}
    /// use nickel::{Nickel, Request, Response};
    /// let mut server = Nickel::new();
    ///
    /// //  without variables or wildcards
    /// fn bare_handler(request: &Request, response: &mut Response) {
    ///     response.send("This matches /user");
    /// };
    /// server.get("/user", bare_handler);
    ///
    /// // with variables
    /// fn var_handler(request: &Request, response: &mut Response) {
    ///     let text = format!("This is user: {}", request.param("userid"));
    ///     response.send(text.as_slice());
    /// };
    /// server.get("/user/:userid", var_handler);
    ///
    /// // with simple wildcard
    /// fn wild_handler(request: &Request, response: &mut Response) {
    ///     response.send("This matches /user/list/4711 but not /user/extended/list/4711");
    /// };
    /// server.get("/user/*/:userid", wild_handler);
    ///
    /// // with double wildcard
    /// fn very_wild_handler(request: &Request, response: &mut Response) {
    ///     response.send("This matches /user/list/4711 and also /user/extended/list/4711");
    /// };
    /// server.get("/user/**/:userid", very_wild_handler);
    /// ```
    pub fn get(&mut self, uri: &str, handler: fn(request: &Request, response: &mut Response)){
        self.register_route_with_new_router(Get, uri, handler);
    }

    /// Registers a handler to be used for a specific POST request.
    /// A handler added through this API will be attached to the default router.
    /// Consider creating the router middleware manually for advanced functionality.
    ///
    /// Take a look at `get(...)` for a more detailed description.
    /// # Example
    ///
    /// ```{rust}
    /// use nickel::{Nickel, Request, Response};
    /// fn handler(request: &Request, response: &mut Response) {
    ///     response.send("This matches a POST request to /a/post/request");
    /// };
    ///
    /// let mut server = Nickel::new();
    /// server.post("/a/post/request", handler);
    /// ```
    pub fn post(&mut self, uri: &str, handler: fn(request: &Request, response: &mut Response)){
        self.register_route_with_new_router(Post, uri, handler);
    }

    /// Registers a handler to be used for a specific PUT request.
    /// A handler added through this API will be attached to the default router.
    /// Consider creating the router middleware manually for advanced functionality.
    ///
    /// Take a look at `get(...)` for a more detailed description.
    /// # Example
    ///
    /// ```{rust}
    /// use nickel::{Nickel, Request, Response};
    /// fn handler(request: &Request, response: &mut Response) {
    ///     response.send("This matches a POST request to /a/put/request");
    /// };
    ///
    /// let mut server = Nickel::new();
    /// server.put("/a/put/request", handler);
    /// ```
    pub fn put(&mut self, uri: &str, handler: fn(request: &Request, response: &mut Response)){
        self.register_route_with_new_router(Put, uri, handler);
    }

    /// Registers a handler to be used for a specific DELETE request.
    /// A handler added through this API will be attached to the default router.
    /// Consider creating the router middleware manually for advanced functionality.
    ///
    /// Take a look at `get(...)` for a more detailed description.
    /// # Example
    ///
    /// ```{rust}
    /// use nickel::{Nickel, Request, Response};
    /// fn handler(request: &Request, response: &mut Response) {
    ///     response.send("This matches a DELETE request to /a/delete/request");
    /// };
    ///
    /// let mut server = Nickel::new();
    /// server.delete("/a/delete/request", handler);
    /// ```
    pub fn delete(&mut self, uri: &str, handler: fn(request: &Request, response: &mut Response)){
        self.register_route_with_new_router(Delete, uri, handler);
    }

    fn register_route_with_new_router(&mut self, method: Method, uri: &str, handler: fn(request: &Request, response: &mut Response)) {
        let mut router = Router::new();
        router.add_route(method, String::from_str(uri), handler);
        self.utilize(router);
    }

    /// Registers an error handler which will be invoked among other error handler
    /// as soon as any regular handler returned an error
    ///
    /// A error handler is nearly identical to a regular middleware handler with the only
    /// difference that it takes an additional error parameter or type `NickelError.
    ///
    /// # Example
    ///
    /// ```{rust}
    /// # extern crate http;
    /// # extern crate nickel;
    /// # fn main() {
    /// use nickel::{Nickel, Request, Response, Action, Continue, Halt};
    /// use nickel::{NickelError, ErrorWithStatusCode, get_media_type};
    /// use http::status::NotFound;
    ///
    /// fn error_handler(err: &NickelError, req: &Request, response: &mut Response)
    ///                  -> Result<Action, NickelError>{
    ///    match err.kind {
    ///        ErrorWithStatusCode(NotFound) => {
    ///            response.origin.headers.content_type = get_media_type("html");
    ///            response.origin.status = NotFound;
    ///            response.send("<h1>Call the police!<h1>");
    ///            Ok(Halt)
    ///        },
    ///        _ => Ok(Continue)
    ///    }
    /// }
    ///
    /// let mut server = Nickel::new();
    /// server.handle_error(error_handler)
    /// # }
    /// ```
    pub fn handle_error(&mut self, handler: fn(err: &NickelError,
                                               req: &Request,
                                               res: &mut Response)
                                            -> Result<Action, NickelError>){
        let handler = IntoErrorHandler::from_fn(handler);
        self.middleware_stack.add_error_handler(handler);
    }

    /// Create a new middleware to serve as a router.
    ///
    ///
    /// # Example
    /// ```{rust}
    /// use nickel::{Nickel, Request, Response};
    ///
    /// let mut server = Nickel::new();
    /// let mut router = Nickel::router();
    ///
    /// fn foo_handler(request: &Request, response: &mut Response) {
    ///     response.send("Hi from /foo");
    /// };
    ///
    /// router.get("/foo", foo_handler);
    /// server.utilize(router);
    /// ```
    pub fn router() -> Router {
        Router::new()
    }

    /// Create a new middleware to parse JSON bodies.
    ///
    ///
    /// # Example
    /// ```{rust}
    /// # #![feature(phase)]
    /// # #[phase(plugin)] extern crate nickel_macros;
    /// # extern crate nickel;
    /// # extern crate serialize;
    /// # use nickel::{Nickel, Request, Response};
    /// use nickel::JsonBody;
    ///
    /// # fn main() {
    /// #[deriving(Decodable, Encodable)]
    /// struct Person {
    ///     first_name: String,
    ///     last_name:  String,
    /// }
    ///
    /// let router = router! {
    ///     post "/a/post/request" => |request, response| {
    ///         let person = request.json_as::<Person>().unwrap();
    ///         let text = format!("Hello {} {}", person.first_name, person.last_name);
    ///         response.send(text);
    ///     }
    /// };
    ///
    /// let mut server = Nickel::new();
    /// // It is currently a requirement that the json_body_parser middleware
    /// // is added before any routes that require it.
    /// server.utilize(Nickel::json_body_parser());
    /// server.utilize(router);
    /// # }
    /// ```
    pub fn json_body_parser() -> JsonBodyParser {
        JsonBodyParser
    }

    /// Create a new middleware to parse the query string.
    ///
    ///
    /// # Example
    /// ```{rust}
    /// # #![feature(phase)]
    /// # #[phase(plugin)] extern crate nickel_macros;
    /// # extern crate nickel;
    /// # use nickel::{Nickel, Request, Response};
    /// use nickel::QueryString;
    /// # fn main() {
    /// let router = router! {
    ///     get "/a/get/request" => |request, response| {
    ///         let foo = request.query("foo", "this is the default value, if foo is not present!");
    ///         response.send(foo[0].as_slice());
    ///     }
    /// };
    ///
    /// let mut server = Nickel::new();
    /// // It is currently a requirement that the query_string middleware
    /// // is added before any routes that require it.
    /// server.utilize(Nickel::query_string());
    /// server.utilize(router);
    /// # }
    /// ```
    pub fn query_string() -> QueryStringParser {
        QueryStringParser
    }

    /// Bind and listen for connections on the given host and port
    ///
    /// # Example
    /// ```{rust,ignore}
    /// let mut server = Nickel::new();
    /// server.listen(Ipv4Addr(127, 0, 0, 1), 6767);
    /// ```
    pub fn listen(mut self, ip: IpAddr, port: Port) {
        fn not_found_handler(_request: &Request, _response: &mut Response) -> Result<Action, NickelError> {
            Err(NickelError::new("File Not Found", ErrorWithStatusCode(NotFound)))
        }

        self.middleware_stack.add_middleware(IntoMiddleware::from_fn(not_found_handler));
        self.server = Some(Server::new(self.middleware_stack, ip, port));
        self.server.unwrap().serve();
    }
}
<|endoftext|>


<commit_before><commit_msg>Revert "add inventory rendering"<commit_after><|endoftext|>


<commit_before><commit_msg>Add Rust solution for array_pair_sum<commit_after>use std::collections::HashSet;
type Pair = (i64, i64);

fn array_pair_sum(values: Vec<i64>, k: i64) -> HashSet<Pair> {
    let mut pairs: HashSet<Pair> = HashSet::new();
    let mut seen: HashSet<i64> = HashSet::new();

    for v1 in &values {
        let other = k - v1;
        if seen.contains(&other) {
            pairs.insert((*v1, other));
        }
        seen.insert(*v1);
    }
    pairs
}

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

    #[test]
    fn test_array_pair_sum() {
        let mut expected1: HashSet<Pair> = HashSet::new();
        expected1.insert((6, 4));
        expected1.insert((7, 3));
        assert_eq!(array_pair_sum(vec![3, 4, 5, 6, 7], 10), expected1);

        let mut expected2: HashSet<Pair> = HashSet::new();
        expected2.insert((5, 3));
        expected2.insert((4, 4));
        assert_eq!(array_pair_sum(vec![3, 4, 5, 4, 4], 8), expected2);

        assert!(array_pair_sum(vec![4], 8).is_empty());

        let mut expected3: HashSet<Pair> = HashSet::new();
        expected3.insert((-4, 4));
        assert_eq!(array_pair_sum(vec![4, -4], 0), expected3);
    }
}

<|endoftext|>