<commit_before>// Copyright 2013-2014 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.

//! A priority queue implemented with a binary heap

#![allow(missing_doc)]

use std::clone::Clone;
use std::mem::{move_val_init, init, replace, swap};
use std::slice;

/// A priority queue implemented with a binary heap
#[deriving(Clone)]
pub struct PriorityQueue<T> {
    data: Vec<T>,
}

impl<T: TotalOrd> Container for PriorityQueue<T> {
    /// Returns the length of the queue
    fn len(&self) -> uint { self.data.len() }
}

impl<T: TotalOrd> Mutable for PriorityQueue<T> {
    /// Drop all items from the queue
    fn clear(&mut self) { self.data.truncate(0) }
}

impl<T: TotalOrd> PriorityQueue<T> {
    /// An iterator visiting all values in underlying vector, in
    /// arbitrary order.
    pub fn iter<'a>(&'a self) -> Items<'a, T> {
        Items { iter: self.data.iter() }
    }

    /// Returns the greatest item in the queue - fails if empty
    pub fn top<'a>(&'a self) -> &'a T { self.data.get(0) }

    /// Returns the greatest item in the queue - None if empty
    pub fn maybe_top<'a>(&'a self) -> Option<&'a T> {
        if self.is_empty() { None } else { Some(self.top()) }
    }

    /// Returns the number of elements the queue can hold without reallocating
    pub fn capacity(&self) -> uint { self.data.capacity() }

    /// Reserve capacity for exactly n elements in the PriorityQueue.
    /// Do nothing if the capacity is already sufficient.
    pub fn reserve_exact(&mut self, n: uint) { self.data.reserve_exact(n) }

    /// Reserve capacity for at least n elements in the PriorityQueue.
    /// Do nothing if the capacity is already sufficient.
    pub fn reserve(&mut self, n: uint) {
        self.data.reserve(n)
    }

    /// Pop the greatest item from the queue - fails if empty
    pub fn pop(&mut self) -> T {
        let mut item = self.data.pop().unwrap();
        if !self.is_empty() {
            swap(&mut item, self.data.get_mut(0));
            self.siftdown(0);
        }
        item
    }

    /// Pop the greatest item from the queue - None if empty
    pub fn maybe_pop(&mut self) -> Option<T> {
        if self.is_empty() { None } else { Some(self.pop()) }
    }

    /// Push an item onto the queue
    pub fn push(&mut self, item: T) {
        self.data.push(item);
        let new_len = self.len() - 1;
        self.siftup(0, new_len);
    }

    /// Optimized version of a push followed by a pop
    pub fn push_pop(&mut self, mut item: T) -> T {
        if !self.is_empty() && *self.top() > item {
            swap(&mut item, self.data.get_mut(0));
            self.siftdown(0);
        }
        item
    }

    /// Optimized version of a pop followed by a push - fails if empty
    pub fn replace(&mut self, mut item: T) -> T {
        swap(&mut item, self.data.get_mut(0));
        self.siftdown(0);
        item
    }

    /// Consume the PriorityQueue and return the underlying vector
    pub fn to_vec(self) -> Vec<T> { let PriorityQueue{data: v} = self; v }

    /// Consume the PriorityQueue and return a vector in sorted
    /// (ascending) order
    pub fn to_sorted_vec(self) -> Vec<T> {
        let mut q = self;
        let mut end = q.len();
        while end > 1 {
            end -= 1;
            q.data.as_mut_slice().swap(0, end);
            q.siftdown_range(0, end)
        }
        q.to_vec()
    }

    /// Create an empty PriorityQueue
    pub fn new() -> PriorityQueue<T> { PriorityQueue{data: vec!(),} }

    /// Create an empty PriorityQueue with capacity `capacity`
    pub fn with_capacity(capacity: uint) -> PriorityQueue<T> {
        PriorityQueue { data: Vec::with_capacity(capacity) }
    }

    /// Create a PriorityQueue from a vector (heapify)
    pub fn from_vec(xs: Vec<T>) -> PriorityQueue<T> {
        let mut q = PriorityQueue{data: xs,};
        let mut n = q.len() / 2;
        while n > 0 {
            n -= 1;
            q.siftdown(n)
        }
        q
    }

    // The implementations of siftup and siftdown use unsafe blocks in
    // order to move an element out of the vector (leaving behind a
    // zeroed element), shift along the others and move it back into the
    // vector over the junk element.  This reduces the constant factor
    // compared to using swaps, which involves twice as many moves.
    fn siftup(&mut self, start: uint, mut pos: uint) {
        unsafe {
            let new = replace(self.data.get_mut(pos), init());

            while pos > start {
                let parent = (pos - 1) >> 1;
                if new > *self.data.get(parent) {
                    let x = replace(self.data.get_mut(parent), init());
                    move_val_init(self.data.get_mut(pos), x);
                    pos = parent;
                    continue
                }
                break
            }
            move_val_init(self.data.get_mut(pos), new);
        }
    }

    fn siftdown_range(&mut self, mut pos: uint, end: uint) {
        unsafe {
            let start = pos;
            let new = replace(self.data.get_mut(pos), init());

            let mut child = 2 * pos + 1;
            while child < end {
                let right = child + 1;
                if right < end && !(*self.data.get(child) > *self.data.get(right)) {
                    child = right;
                }
                let x = replace(self.data.get_mut(child), init());
                move_val_init(self.data.get_mut(pos), x);
                pos = child;
                child = 2 * pos + 1;
            }

            move_val_init(self.data.get_mut(pos), new);
            self.siftup(start, pos);
        }
    }

    fn siftdown(&mut self, pos: uint) {
        let len = self.len();
        self.siftdown_range(pos, len);
    }
}

/// PriorityQueue iterator
pub struct Items <'a, T> {
    iter: slice::Items<'a, T>,
}

impl<'a, T> Iterator<&'a T> for Items<'a, T> {
    #[inline]
    fn next(&mut self) -> Option<(&'a T)> { self.iter.next() }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
}

impl<T: TotalOrd> FromIterator<T> for PriorityQueue<T> {
    fn from_iter<Iter: Iterator<T>>(iter: Iter) -> PriorityQueue<T> {
        let mut q = PriorityQueue::new();
        q.extend(iter);
        q
    }
}

impl<T: TotalOrd> Extendable<T> for PriorityQueue<T> {
    fn extend<Iter: Iterator<T>>(&mut self, mut iter: Iter) {
        let (lower, _) = iter.size_hint();

        let len = self.capacity();
        self.reserve(len + lower);

        for elem in iter {
            self.push(elem);
        }
    }
}

#[cfg(test)]
mod tests {
    use priority_queue::PriorityQueue;

    #[test]
    fn test_iterator() {
        let data = vec!(5, 9, 3);
        let iterout = [9, 5, 3];
        let pq = PriorityQueue::from_vec(data);
        let mut i = 0;
        for el in pq.iter() {
            assert_eq!(*el, iterout[i]);
            i += 1;
        }
    }

    #[test]
    fn test_top_and_pop() {
        let data = vec!(2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1);
        let mut sorted = data.clone();
        sorted.sort();
        let mut heap = PriorityQueue::from_vec(data);
        while !heap.is_empty() {
            assert_eq!(heap.top(), sorted.last().unwrap());
            assert_eq!(heap.pop(), sorted.pop().unwrap());
        }
    }

    #[test]
    fn test_push() {
        let mut heap = PriorityQueue::from_vec(vec!(2, 4, 9));
        assert_eq!(heap.len(), 3);
        assert!(*heap.top() == 9);
        heap.push(11);
        assert_eq!(heap.len(), 4);
        assert!(*heap.top() == 11);
        heap.push(5);
        assert_eq!(heap.len(), 5);
        assert!(*heap.top() == 11);
        heap.push(27);
        assert_eq!(heap.len(), 6);
        assert!(*heap.top() == 27);
        heap.push(3);
        assert_eq!(heap.len(), 7);
        assert!(*heap.top() == 27);
        heap.push(103);
        assert_eq!(heap.len(), 8);
        assert!(*heap.top() == 103);
    }

    #[test]
    fn test_push_unique() {
        let mut heap = PriorityQueue::from_vec(vec!(box 2, box 4, box 9));
        assert_eq!(heap.len(), 3);
        assert!(*heap.top() == box 9);
        heap.push(box 11);
        assert_eq!(heap.len(), 4);
        assert!(*heap.top() == box 11);
        heap.push(box 5);
        assert_eq!(heap.len(), 5);
        assert!(*heap.top() == box 11);
        heap.push(box 27);
        assert_eq!(heap.len(), 6);
        assert!(*heap.top() == box 27);
        heap.push(box 3);
        assert_eq!(heap.len(), 7);
        assert!(*heap.top() == box 27);
        heap.push(box 103);
        assert_eq!(heap.len(), 8);
        assert!(*heap.top() == box 103);
    }

    #[test]
    fn test_push_pop() {
        let mut heap = PriorityQueue::from_vec(vec!(5, 5, 2, 1, 3));
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.push_pop(6), 6);
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.push_pop(0), 5);
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.push_pop(4), 5);
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.push_pop(1), 4);
        assert_eq!(heap.len(), 5);
    }

    #[test]
    fn test_replace() {
        let mut heap = PriorityQueue::from_vec(vec!(5, 5, 2, 1, 3));
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.replace(6), 5);
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.replace(0), 6);
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.replace(4), 5);
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.replace(1), 4);
        assert_eq!(heap.len(), 5);
    }

    fn check_to_vec(mut data: Vec<int>) {
        let heap = PriorityQueue::from_vec(data.clone());
        let mut v = heap.clone().to_vec();
        v.sort();
        data.sort();

        assert_eq!(v, data);
        assert_eq!(heap.to_sorted_vec(), data);
    }

    #[test]
    fn test_to_vec() {
        check_to_vec(vec!());
        check_to_vec(vec!(5));
        check_to_vec(vec!(3, 2));
        check_to_vec(vec!(2, 3));
        check_to_vec(vec!(5, 1, 2));
        check_to_vec(vec!(1, 100, 2, 3));
        check_to_vec(vec!(1, 3, 5, 7, 9, 2, 4, 6, 8, 0));
        check_to_vec(vec!(2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
        check_to_vec(vec!(9, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
        check_to_vec(vec!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
        check_to_vec(vec!(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
        check_to_vec(vec!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
        check_to_vec(vec!(5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
    }

    #[test]
    #[should_fail]
    fn test_empty_pop() {
        let mut heap: PriorityQueue<int> = PriorityQueue::new();
        heap.pop();
    }

    #[test]
    fn test_empty_maybe_pop() {
        let mut heap: PriorityQueue<int> = PriorityQueue::new();
        assert!(heap.maybe_pop().is_none());
    }

    #[test]
    #[should_fail]
    fn test_empty_top() {
        let empty: PriorityQueue<int> = PriorityQueue::new();
        empty.top();
    }

    #[test]
    fn test_empty_maybe_top() {
        let empty: PriorityQueue<int> = PriorityQueue::new();
        assert!(empty.maybe_top().is_none());
    }

    #[test]
    #[should_fail]
    fn test_empty_replace() {
        let mut heap: PriorityQueue<int> = PriorityQueue::new();
        heap.replace(5);
    }

    #[test]
    fn test_from_iter() {
        let xs = vec!(9u, 8, 7, 6, 5, 4, 3, 2, 1);

        let mut q: PriorityQueue<uint> = xs.as_slice().iter().rev().map(|&x| x).collect();

        for &x in xs.iter() {
            assert_eq!(q.pop(), x);
        }
    }
}
<commit_msg>Rename to_vec and to_sorted_vec<commit_after>// Copyright 2013-2014 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.

//! A priority queue implemented with a binary heap

#![allow(missing_doc)]

use std::clone::Clone;
use std::mem::{move_val_init, init, replace, swap};
use std::slice;

/// A priority queue implemented with a binary heap
#[deriving(Clone)]
pub struct PriorityQueue<T> {
    data: Vec<T>,
}

impl<T: TotalOrd> Container for PriorityQueue<T> {
    /// Returns the length of the queue
    fn len(&self) -> uint { self.data.len() }
}

impl<T: TotalOrd> Mutable for PriorityQueue<T> {
    /// Drop all items from the queue
    fn clear(&mut self) { self.data.truncate(0) }
}

impl<T: TotalOrd> PriorityQueue<T> {
    /// An iterator visiting all values in underlying vector, in
    /// arbitrary order.
    pub fn iter<'a>(&'a self) -> Items<'a, T> {
        Items { iter: self.data.iter() }
    }

    /// Returns the greatest item in the queue - fails if empty
    pub fn top<'a>(&'a self) -> &'a T { self.data.get(0) }

    /// Returns the greatest item in the queue - None if empty
    pub fn maybe_top<'a>(&'a self) -> Option<&'a T> {
        if self.is_empty() { None } else { Some(self.top()) }
    }

    /// Returns the number of elements the queue can hold without reallocating
    pub fn capacity(&self) -> uint { self.data.capacity() }

    /// Reserve capacity for exactly n elements in the PriorityQueue.
    /// Do nothing if the capacity is already sufficient.
    pub fn reserve_exact(&mut self, n: uint) { self.data.reserve_exact(n) }

    /// Reserve capacity for at least n elements in the PriorityQueue.
    /// Do nothing if the capacity is already sufficient.
    pub fn reserve(&mut self, n: uint) {
        self.data.reserve(n)
    }

    /// Pop the greatest item from the queue - fails if empty
    pub fn pop(&mut self) -> T {
        let mut item = self.data.pop().unwrap();
        if !self.is_empty() {
            swap(&mut item, self.data.get_mut(0));
            self.siftdown(0);
        }
        item
    }

    /// Pop the greatest item from the queue - None if empty
    pub fn maybe_pop(&mut self) -> Option<T> {
        if self.is_empty() { None } else { Some(self.pop()) }
    }

    /// Push an item onto the queue
    pub fn push(&mut self, item: T) {
        self.data.push(item);
        let new_len = self.len() - 1;
        self.siftup(0, new_len);
    }

    /// Optimized version of a push followed by a pop
    pub fn push_pop(&mut self, mut item: T) -> T {
        if !self.is_empty() && *self.top() > item {
            swap(&mut item, self.data.get_mut(0));
            self.siftdown(0);
        }
        item
    }

    /// Optimized version of a pop followed by a push - fails if empty
    pub fn replace(&mut self, mut item: T) -> T {
        swap(&mut item, self.data.get_mut(0));
        self.siftdown(0);
        item
    }

    #[deprecated="renamed to `into_vec`"]
    fn to_vec(self) -> Vec<T> { self.into_vec() }

    #[deprecated="renamed to `into_sorted_vec`"]
    fn to_sorted_vec(self) -> Vec<T> { self.into_sorted_vec() }

    /// Consume the PriorityQueue and return the underlying vector
    pub fn into_vec(self) -> Vec<T> { let PriorityQueue{data: v} = self; v }

    /// Consume the PriorityQueue and return a vector in sorted
    /// (ascending) order
    pub fn into_sorted_vec(self) -> Vec<T> {
        let mut q = self;
        let mut end = q.len();
        while end > 1 {
            end -= 1;
            q.data.as_mut_slice().swap(0, end);
            q.siftdown_range(0, end)
        }
        q.to_vec()
    }

    /// Create an empty PriorityQueue
    pub fn new() -> PriorityQueue<T> { PriorityQueue{data: vec!(),} }

    /// Create an empty PriorityQueue with capacity `capacity`
    pub fn with_capacity(capacity: uint) -> PriorityQueue<T> {
        PriorityQueue { data: Vec::with_capacity(capacity) }
    }

    /// Create a PriorityQueue from a vector (heapify)
    pub fn from_vec(xs: Vec<T>) -> PriorityQueue<T> {
        let mut q = PriorityQueue{data: xs,};
        let mut n = q.len() / 2;
        while n > 0 {
            n -= 1;
            q.siftdown(n)
        }
        q
    }

    // The implementations of siftup and siftdown use unsafe blocks in
    // order to move an element out of the vector (leaving behind a
    // zeroed element), shift along the others and move it back into the
    // vector over the junk element.  This reduces the constant factor
    // compared to using swaps, which involves twice as many moves.
    fn siftup(&mut self, start: uint, mut pos: uint) {
        unsafe {
            let new = replace(self.data.get_mut(pos), init());

            while pos > start {
                let parent = (pos - 1) >> 1;
                if new > *self.data.get(parent) {
                    let x = replace(self.data.get_mut(parent), init());
                    move_val_init(self.data.get_mut(pos), x);
                    pos = parent;
                    continue
                }
                break
            }
            move_val_init(self.data.get_mut(pos), new);
        }
    }

    fn siftdown_range(&mut self, mut pos: uint, end: uint) {
        unsafe {
            let start = pos;
            let new = replace(self.data.get_mut(pos), init());

            let mut child = 2 * pos + 1;
            while child < end {
                let right = child + 1;
                if right < end && !(*self.data.get(child) > *self.data.get(right)) {
                    child = right;
                }
                let x = replace(self.data.get_mut(child), init());
                move_val_init(self.data.get_mut(pos), x);
                pos = child;
                child = 2 * pos + 1;
            }

            move_val_init(self.data.get_mut(pos), new);
            self.siftup(start, pos);
        }
    }

    fn siftdown(&mut self, pos: uint) {
        let len = self.len();
        self.siftdown_range(pos, len);
    }
}

/// PriorityQueue iterator
pub struct Items <'a, T> {
    iter: slice::Items<'a, T>,
}

impl<'a, T> Iterator<&'a T> for Items<'a, T> {
    #[inline]
    fn next(&mut self) -> Option<(&'a T)> { self.iter.next() }

    #[inline]
    fn size_hint(&self) -> (uint, Option<uint>) { self.iter.size_hint() }
}

impl<T: TotalOrd> FromIterator<T> for PriorityQueue<T> {
    fn from_iter<Iter: Iterator<T>>(iter: Iter) -> PriorityQueue<T> {
        let mut q = PriorityQueue::new();
        q.extend(iter);
        q
    }
}

impl<T: TotalOrd> Extendable<T> for PriorityQueue<T> {
    fn extend<Iter: Iterator<T>>(&mut self, mut iter: Iter) {
        let (lower, _) = iter.size_hint();

        let len = self.capacity();
        self.reserve(len + lower);

        for elem in iter {
            self.push(elem);
        }
    }
}

#[cfg(test)]
mod tests {
    use priority_queue::PriorityQueue;

    #[test]
    fn test_iterator() {
        let data = vec!(5, 9, 3);
        let iterout = [9, 5, 3];
        let pq = PriorityQueue::from_vec(data);
        let mut i = 0;
        for el in pq.iter() {
            assert_eq!(*el, iterout[i]);
            i += 1;
        }
    }

    #[test]
    fn test_top_and_pop() {
        let data = vec!(2u, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1);
        let mut sorted = data.clone();
        sorted.sort();
        let mut heap = PriorityQueue::from_vec(data);
        while !heap.is_empty() {
            assert_eq!(heap.top(), sorted.last().unwrap());
            assert_eq!(heap.pop(), sorted.pop().unwrap());
        }
    }

    #[test]
    fn test_push() {
        let mut heap = PriorityQueue::from_vec(vec!(2, 4, 9));
        assert_eq!(heap.len(), 3);
        assert!(*heap.top() == 9);
        heap.push(11);
        assert_eq!(heap.len(), 4);
        assert!(*heap.top() == 11);
        heap.push(5);
        assert_eq!(heap.len(), 5);
        assert!(*heap.top() == 11);
        heap.push(27);
        assert_eq!(heap.len(), 6);
        assert!(*heap.top() == 27);
        heap.push(3);
        assert_eq!(heap.len(), 7);
        assert!(*heap.top() == 27);
        heap.push(103);
        assert_eq!(heap.len(), 8);
        assert!(*heap.top() == 103);
    }

    #[test]
    fn test_push_unique() {
        let mut heap = PriorityQueue::from_vec(vec!(box 2, box 4, box 9));
        assert_eq!(heap.len(), 3);
        assert!(*heap.top() == box 9);
        heap.push(box 11);
        assert_eq!(heap.len(), 4);
        assert!(*heap.top() == box 11);
        heap.push(box 5);
        assert_eq!(heap.len(), 5);
        assert!(*heap.top() == box 11);
        heap.push(box 27);
        assert_eq!(heap.len(), 6);
        assert!(*heap.top() == box 27);
        heap.push(box 3);
        assert_eq!(heap.len(), 7);
        assert!(*heap.top() == box 27);
        heap.push(box 103);
        assert_eq!(heap.len(), 8);
        assert!(*heap.top() == box 103);
    }

    #[test]
    fn test_push_pop() {
        let mut heap = PriorityQueue::from_vec(vec!(5, 5, 2, 1, 3));
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.push_pop(6), 6);
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.push_pop(0), 5);
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.push_pop(4), 5);
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.push_pop(1), 4);
        assert_eq!(heap.len(), 5);
    }

    #[test]
    fn test_replace() {
        let mut heap = PriorityQueue::from_vec(vec!(5, 5, 2, 1, 3));
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.replace(6), 5);
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.replace(0), 6);
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.replace(4), 5);
        assert_eq!(heap.len(), 5);
        assert_eq!(heap.replace(1), 4);
        assert_eq!(heap.len(), 5);
    }

    fn check_to_vec(mut data: Vec<int>) {
        let heap = PriorityQueue::from_vec(data.clone());
        let mut v = heap.clone().to_vec();
        v.sort();
        data.sort();

        assert_eq!(v, data);
        assert_eq!(heap.to_sorted_vec(), data);
    }

    #[test]
    fn test_to_vec() {
        check_to_vec(vec!());
        check_to_vec(vec!(5));
        check_to_vec(vec!(3, 2));
        check_to_vec(vec!(2, 3));
        check_to_vec(vec!(5, 1, 2));
        check_to_vec(vec!(1, 100, 2, 3));
        check_to_vec(vec!(1, 3, 5, 7, 9, 2, 4, 6, 8, 0));
        check_to_vec(vec!(2, 4, 6, 2, 1, 8, 10, 3, 5, 7, 0, 9, 1));
        check_to_vec(vec!(9, 11, 9, 9, 9, 9, 11, 2, 3, 4, 11, 9, 0, 0, 0, 0));
        check_to_vec(vec!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
        check_to_vec(vec!(10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0));
        check_to_vec(vec!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 1, 2));
        check_to_vec(vec!(5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1));
    }

    #[test]
    #[should_fail]
    fn test_empty_pop() {
        let mut heap: PriorityQueue<int> = PriorityQueue::new();
        heap.pop();
    }

    #[test]
    fn test_empty_maybe_pop() {
        let mut heap: PriorityQueue<int> = PriorityQueue::new();
        assert!(heap.maybe_pop().is_none());
    }

    #[test]
    #[should_fail]
    fn test_empty_top() {
        let empty: PriorityQueue<int> = PriorityQueue::new();
        empty.top();
    }

    #[test]
    fn test_empty_maybe_top() {
        let empty: PriorityQueue<int> = PriorityQueue::new();
        assert!(empty.maybe_top().is_none());
    }

    #[test]
    #[should_fail]
    fn test_empty_replace() {
        let mut heap: PriorityQueue<int> = PriorityQueue::new();
        heap.replace(5);
    }

    #[test]
    fn test_from_iter() {
        let xs = vec!(9u, 8, 7, 6, 5, 4, 3, 2, 1);

        let mut q: PriorityQueue<uint> = xs.as_slice().iter().rev().map(|&x| x).collect();

        for &x in xs.iter() {
            assert_eq!(q.pop(), x);
        }
    }
}
<|endoftext|>


<commit_before>use std::io::{self, Read};

use hyper::client::IntoUrl;
use hyper::header::{Headers, ContentType, Location, Referer, UserAgent};
use hyper::method::Method;
use hyper::status::StatusCode;
use hyper::version::HttpVersion;
use hyper::{Url};

use serde::Serialize;
use serde_json;
use serde_urlencoded;

use ::body::{self, Body};

static DEFAULT_USER_AGENT: &'static str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));

/// A `Client` to make Requests with.
///
/// The Client has various configuration values to tweak, but the defaults
/// are set to what is usually the most commonly desired value.
///
/// The `Client` holds a connection pool internally, so it is advised that
/// you create one and reuse it.
#[derive(Debug)]
pub struct Client {
    inner: ::hyper::Client,
}

impl Client {
    /// Constructs a new `Client`.
    pub fn new() -> ::Result<Client> {
        let mut client = try!(new_hyper_client());
        client.set_redirect_policy(::hyper::client::RedirectPolicy::FollowNone);
        Ok(Client {
            inner: client
        })
    }

    /// Convenience method to make a `GET` request to a URL.
    pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::Get, url)
    }

    /// Convenience method to make a `POST` request to a URL.
    pub fn post<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::Post, url)
    }

    /// Convenience method to make a `HEAD` request to a URL.
    pub fn head<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::Head, url)
    }

    /// Start building a `Request` with the `Method` and `Url`.
    ///
    /// Returns a `RequestBuilder`, which will allow setting headers and
    /// request body before sending.
    pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> RequestBuilder {
        let url = url.into_url();
        RequestBuilder {
            client: self,
            method: method,
            url: url,
            _version: HttpVersion::Http11,
            headers: Headers::new(),

            body: None,
        }
    }
}

fn new_hyper_client() -> ::Result<::hyper::Client> {
    use tls::TlsClient;
    Ok(::hyper::Client::with_connector(
        ::hyper::client::Pool::with_connector(
            Default::default(),
            ::hyper::net::HttpsConnector::new(try!(TlsClient::new()))
        )
    ))
}

/// A builder to construct the properties of a `Request`.
#[derive(Debug)]
pub struct RequestBuilder<'a> {
    client: &'a Client,

    method: Method,
    url: Result<Url, ::UrlError>,
    _version: HttpVersion,
    headers: Headers,

    body: Option<::Result<Body>>,
}

impl<'a> RequestBuilder<'a> {
    /// Add a `Header` to this Request.
    ///
    /// ```no_run
    /// use reqwest::header::UserAgent;
    /// let client = reqwest::Client::new().expect("client failed to construct");
    ///
    /// let res = client.get("https://www.rust-lang.org")
    ///     .header(UserAgent("foo".to_string()))
    ///     .send();
    /// ```
    pub fn header<H: ::header::Header + ::header::HeaderFormat>(mut self, header: H) -> RequestBuilder<'a> {
        self.headers.set(header);
        self
    }
    /// Add a set of Headers to the existing ones on this Request.
    ///
    /// The headers will be merged in to any already set.
    pub fn headers(mut self, headers: ::header::Headers) -> RequestBuilder<'a> {
        self.headers.extend(headers.iter());
        self
    }

    /// Set the request body.
    pub fn body<T: Into<Body>>(mut self, body: T) -> RequestBuilder<'a> {
        self.body = Some(Ok(body.into()));
        self
    }

    /// Send a form body.
    ///
    /// Sets the body to the url encoded serialization of the passed value,
    /// and also sets the `Content-Type: application/www-form-url-encoded`
    /// header.
    ///
    /// ```no_run
    /// # use std::collections::HashMap;
    /// let mut params = HashMap::new();
    /// params.insert("lang", "rust");
    ///
    /// let client = reqwest::Client::new().unwrap();
    /// let res = client.post("http://httpbin.org")
    ///     .form(&params)
    ///     .send();
    /// ```
    pub fn form<T: Serialize>(mut self, form: &T) -> RequestBuilder<'a> {
        let body = serde_urlencoded::to_string(form).map_err(::Error::from);
        self.headers.set(ContentType::form_url_encoded());
        self.body = Some(body.map(|b| b.into()));
        self
    }

    /// Send a JSON body.
    ///
    /// Sets the body to the JSON serialization of the passed value, and
    /// also sets the `Content-Type: application/json` header.
    ///
    /// ```no_run
    /// # use std::collections::HashMap;
    /// let mut map = HashMap::new();
    /// map.insert("lang", "rust");
    ///
    /// let client = reqwest::Client::new().unwrap();
    /// let res = client.post("http://httpbin.org")
    ///     .json(&map)
    ///     .send();
    /// ```
    pub fn json<T: Serialize>(mut self, json: &T) -> RequestBuilder<'a> {
        let body = serde_json::to_vec(json).expect("serde to_vec cannot fail");
        self.headers.set(ContentType::json());
        self.body = Some(Ok(body.into()));
        self
    }

    /// Constructs the Request and sends it the target URL, returning a Response.
    pub fn send(mut self) -> ::Result<Response> {
        if !self.headers.has::<UserAgent>() {
            self.headers.set(UserAgent(DEFAULT_USER_AGENT.to_owned()));
        }

        let client = self.client;
        let mut method = self.method;
        let mut url = try!(self.url);
        let mut headers = self.headers;
        let mut body = match self.body {
            Some(b) => Some(try!(b)),
            None => None,
        };

        let mut redirect_count = 0;

        loop {
            let res = {
                debug!("request {:?} \"{}\"", method, url);
                let mut req = client.inner.request(method.clone(), url.clone())
                    .headers(headers.clone());

                if let Some(ref mut b) = body {
                    let body = body::as_hyper_body(b);
                    req = req.body(body);
                }

                try!(req.send())
            };
            body.take();

            match res.status {
                StatusCode::MovedPermanently |
                StatusCode::Found |
                StatusCode::SeeOther => {

                    //TODO: turn this into self.redirect_policy.check()
                    if redirect_count > 10 {
                        return Err(::Error::TooManyRedirects);
                    }
                    redirect_count += 1;

                    method = match method {
                        Method::Post | Method::Put => Method::Get,
                        m => m
                    };

                    headers.set(Referer(url.to_string()));

                    let loc = {
                        let loc = res.headers.get::<Location>().map(|loc| url.join(loc));
                        if let Some(loc) = loc {
                            loc
                        } else {
                            return Ok(Response {
                                inner: res
                            });
                        }
                    };

                    url = match loc {
                        Ok(u) => u,
                        Err(e) => {
                            debug!("Location header had invalid URI: {:?}", e);
                            return Ok(Response {
                                inner: res
                            })
                        }
                    };

                    debug!("redirecting to '{}'", url);

                    //TODO: removeSensitiveHeaders(&mut headers, &url);

                },
                _ => {
                    return Ok(Response {
                        inner: res
                    });
                }
            }
        }
    }
}

/// A Response to a submitted `Request`.
#[derive(Debug)]
pub struct Response {
    inner: ::hyper::client::Response,
}

impl Response {
    /// Get the `StatusCode`.
    pub fn status(&self) -> &StatusCode {
        &self.inner.status
    }

    /// Get the `Headers`.
    pub fn headers(&self) -> &Headers {
        &self.inner.headers
    }

    /// Get the `HttpVersion`.
    pub fn version(&self) -> &HttpVersion {
        &self.inner.version
    }
}

/// Read the body of the Response.
impl Read for Response {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.inner.read(buf)
    }
}
<commit_msg>test: Added some trivial tests for the RequestBuilder<commit_after>use std::io::{self, Read};

use hyper::client::IntoUrl;
use hyper::header::{Headers, ContentType, Location, Referer, UserAgent};
use hyper::method::Method;
use hyper::status::StatusCode;
use hyper::version::HttpVersion;
use hyper::{Url};

use serde::Serialize;
use serde_json;
use serde_urlencoded;

use ::body::{self, Body};

static DEFAULT_USER_AGENT: &'static str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));

/// A `Client` to make Requests with.
///
/// The Client has various configuration values to tweak, but the defaults
/// are set to what is usually the most commonly desired value.
///
/// The `Client` holds a connection pool internally, so it is advised that
/// you create one and reuse it.
#[derive(Debug)]
pub struct Client {
    inner: ::hyper::Client,
}

impl Client {
    /// Constructs a new `Client`.
    pub fn new() -> ::Result<Client> {
        let mut client = try!(new_hyper_client());
        client.set_redirect_policy(::hyper::client::RedirectPolicy::FollowNone);
        Ok(Client {
            inner: client
        })
    }

    /// Convenience method to make a `GET` request to a URL.
    pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::Get, url)
    }

    /// Convenience method to make a `POST` request to a URL.
    pub fn post<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::Post, url)
    }

    /// Convenience method to make a `HEAD` request to a URL.
    pub fn head<U: IntoUrl>(&self, url: U) -> RequestBuilder {
        self.request(Method::Head, url)
    }

    /// Start building a `Request` with the `Method` and `Url`.
    ///
    /// Returns a `RequestBuilder`, which will allow setting headers and
    /// request body before sending.
    pub fn request<U: IntoUrl>(&self, method: Method, url: U) -> RequestBuilder {
        let url = url.into_url();
        RequestBuilder {
            client: self,
            method: method,
            url: url,
            _version: HttpVersion::Http11,
            headers: Headers::new(),

            body: None,
        }
    }
}

fn new_hyper_client() -> ::Result<::hyper::Client> {
    use tls::TlsClient;
    Ok(::hyper::Client::with_connector(
        ::hyper::client::Pool::with_connector(
            Default::default(),
            ::hyper::net::HttpsConnector::new(try!(TlsClient::new()))
        )
    ))
}

/// A builder to construct the properties of a `Request`.
#[derive(Debug)]
pub struct RequestBuilder<'a> {
    client: &'a Client,

    method: Method,
    url: Result<Url, ::UrlError>,
    _version: HttpVersion,
    headers: Headers,

    body: Option<::Result<Body>>,
}

impl<'a> RequestBuilder<'a> {
    /// Add a `Header` to this Request.
    ///
    /// ```no_run
    /// use reqwest::header::UserAgent;
    /// let client = reqwest::Client::new().expect("client failed to construct");
    ///
    /// let res = client.get("https://www.rust-lang.org")
    ///     .header(UserAgent("foo".to_string()))
    ///     .send();
    /// ```
    pub fn header<H: ::header::Header + ::header::HeaderFormat>(mut self, header: H) -> RequestBuilder<'a> {
        self.headers.set(header);
        self
    }
    /// Add a set of Headers to the existing ones on this Request.
    ///
    /// The headers will be merged in to any already set.
    pub fn headers(mut self, headers: ::header::Headers) -> RequestBuilder<'a> {
        self.headers.extend(headers.iter());
        self
    }

    /// Set the request body.
    pub fn body<T: Into<Body>>(mut self, body: T) -> RequestBuilder<'a> {
        self.body = Some(Ok(body.into()));
        self
    }

    /// Send a form body.
    ///
    /// Sets the body to the url encoded serialization of the passed value,
    /// and also sets the `Content-Type: application/www-form-url-encoded`
    /// header.
    ///
    /// ```no_run
    /// # use std::collections::HashMap;
    /// let mut params = HashMap::new();
    /// params.insert("lang", "rust");
    ///
    /// let client = reqwest::Client::new().unwrap();
    /// let res = client.post("http://httpbin.org")
    ///     .form(&params)
    ///     .send();
    /// ```
    pub fn form<T: Serialize>(mut self, form: &T) -> RequestBuilder<'a> {
        let body = serde_urlencoded::to_string(form).map_err(::Error::from);
        self.headers.set(ContentType::form_url_encoded());
        self.body = Some(body.map(|b| b.into()));
        self
    }

    /// Send a JSON body.
    ///
    /// Sets the body to the JSON serialization of the passed value, and
    /// also sets the `Content-Type: application/json` header.
    ///
    /// ```no_run
    /// # use std::collections::HashMap;
    /// let mut map = HashMap::new();
    /// map.insert("lang", "rust");
    ///
    /// let client = reqwest::Client::new().unwrap();
    /// let res = client.post("http://httpbin.org")
    ///     .json(&map)
    ///     .send();
    /// ```
    pub fn json<T: Serialize>(mut self, json: &T) -> RequestBuilder<'a> {
        let body = serde_json::to_vec(json).expect("serde to_vec cannot fail");
        self.headers.set(ContentType::json());
        self.body = Some(Ok(body.into()));
        self
    }

    /// Constructs the Request and sends it the target URL, returning a Response.
    pub fn send(mut self) -> ::Result<Response> {
        if !self.headers.has::<UserAgent>() {
            self.headers.set(UserAgent(DEFAULT_USER_AGENT.to_owned()));
        }

        let client = self.client;
        let mut method = self.method;
        let mut url = try!(self.url);
        let mut headers = self.headers;
        let mut body = match self.body {
            Some(b) => Some(try!(b)),
            None => None,
        };

        let mut redirect_count = 0;

        loop {
            let res = {
                debug!("request {:?} \"{}\"", method, url);
                let mut req = client.inner.request(method.clone(), url.clone())
                    .headers(headers.clone());

                if let Some(ref mut b) = body {
                    let body = body::as_hyper_body(b);
                    req = req.body(body);
                }

                try!(req.send())
            };
            body.take();

            match res.status {
                StatusCode::MovedPermanently |
                StatusCode::Found |
                StatusCode::SeeOther => {

                    //TODO: turn this into self.redirect_policy.check()
                    if redirect_count > 10 {
                        return Err(::Error::TooManyRedirects);
                    }
                    redirect_count += 1;

                    method = match method {
                        Method::Post | Method::Put => Method::Get,
                        m => m
                    };

                    headers.set(Referer(url.to_string()));

                    let loc = {
                        let loc = res.headers.get::<Location>().map(|loc| url.join(loc));
                        if let Some(loc) = loc {
                            loc
                        } else {
                            return Ok(Response {
                                inner: res
                            });
                        }
                    };

                    url = match loc {
                        Ok(u) => u,
                        Err(e) => {
                            debug!("Location header had invalid URI: {:?}", e);
                            return Ok(Response {
                                inner: res
                            })
                        }
                    };

                    debug!("redirecting to '{}'", url);

                    //TODO: removeSensitiveHeaders(&mut headers, &url);

                },
                _ => {
                    return Ok(Response {
                        inner: res
                    });
                }
            }
        }
    }
}

/// A Response to a submitted `Request`.
#[derive(Debug)]
pub struct Response {
    inner: ::hyper::client::Response,
}

impl Response {
    /// Get the `StatusCode`.
    pub fn status(&self) -> &StatusCode {
        &self.inner.status
    }

    /// Get the `Headers`.
    pub fn headers(&self) -> &Headers {
        &self.inner.headers
    }

    /// Get the `HttpVersion`.
    pub fn version(&self) -> &HttpVersion {
        &self.inner.version
    }
}

/// Read the body of the Response.
impl Read for Response {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.inner.read(buf)
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use hyper::method::Method;
    use hyper::Url;
    use hyper::header::{Host, Headers, ContentType};
    use std::collections::HashMap;

    #[test]
    fn basic_get_request() {
        let client = Client::new().unwrap();
        let some_url = "https://google.com/";
        let r = client.get(some_url);

        assert_eq!(r.method, Method::Get);
        assert_eq!(r.url, Url::parse(some_url));
    }

    #[test]
    fn basic_head_request() {
        let client = Client::new().unwrap();
        let some_url = "https://google.com/";
        let r = client.head(some_url);

        assert_eq!(r.method, Method::Head);
        assert_eq!(r.url, Url::parse(some_url));
    }

    #[test]
    fn basic_post_request() {
        let client = Client::new().unwrap();
        let some_url = "https://google.com/";
        let r = client.post(some_url);

        assert_eq!(r.method, Method::Post);
        assert_eq!(r.url, Url::parse(some_url));
    }

    #[test]
    fn add_header() {
        let client = Client::new().unwrap();
        let some_url = "https://google.com/";
        let mut r = client.post(some_url);

        let header = Host {
            hostname: "google.com".to_string(),
            port: None,
        };

        // Add a copy of the header to the request builder
        r = r.header(header.clone());

        // then check it was actually added
        assert_eq!(r.headers.get::<Host>(), Some(&header));
    }

    #[test]
    fn add_headers() {
        let client = Client::new().unwrap();
        let some_url = "https://google.com/";
        let mut r = client.post(some_url);

        let header = Host {
            hostname: "google.com".to_string(),
            port: None,
        };

        let mut headers = Headers::new();
        headers.set(header);

        // Add a copy of the headers to the request builder
        r = r.headers(headers.clone());

        // then make sure they were added correctly
        assert_eq!(r.headers, headers);
    }

    #[test]
    #[ignore]
    fn add_body() {
        // Currently Body doesn't have an implementation of PartialEq, so you
        // can't check whether the body is actually what you set.
        //
        // This is most probably because Body's reader attribute is anything
        // which implements Read, meaning the act of checking the body will
        // probably consume it. To get around this, you might want to consider
        // restricting Body.reader to something a little more concrete like a
        // String.
        //
        // A basic test is included below, but commented out so the compiler
        // won't yell at you.

        // let client = Client::new().unwrap();
        // let some_url = "https://google.com/";
        // let mut r = client.post(some_url);
        //
        // let body = "Some interesting content";
        //
        // r = r.body(body);
        //
        //assert_eq!(r.body.unwrap().unwrap(), body);
    }

    #[test]
    fn add_form() {
        let client = Client::new().unwrap();
        let some_url = "https://google.com/";
        let mut r = client.post(some_url);

        let mut form_data = HashMap::new();
        form_data.insert("foo", "bar");

        r = r.form(&form_data);

        // Make sure the content type was set
        assert_eq!(r.headers.get::<ContentType>(), Some(&ContentType::form_url_encoded()));

        // need to check the body is set to the serialized hashmap. Can't
        // currently do that because Body doesn't implement PartialEq.

        // let body_should_be: Body = serde_urlencoded::to_string(form).map(|b| b.into());
        // assert_eq!(r.body, Some(body_should_be));
    }

    #[test]
    fn add_json() {
        let client = Client::new().unwrap();
        let some_url = "https://google.com/";
        let mut r = client.post(some_url);

        let mut form_data = HashMap::new();
        form_data.insert("foo", "bar");

        r = r.json(&form_data);

        // Make sure the content type was set
        assert_eq!(r.headers.get::<ContentType>(), Some(&ContentType::json()));

        // need to check the body is set to the serialized hashmap. Can't
        // currently do that because Body doesn't implement PartialEq.

        // let body_should_be: Body = serde_urlencoded::to_string(form).map(|b| b.into());
        // assert_eq!(r.body, Some(body_should_be));
    }
}
<|endoftext|>


<commit_before><commit_msg>Fixed weird newline<commit_after><|endoftext|>


<commit_before><commit_msg>fix operators, add tests<commit_after><|endoftext|>


<commit_before>//! `StructureSpawn` data description.
use crate::data::RoomName;

with_update_struct! {
    /// A struct describing a creep currently spawning (used as part of the update for a StructureSpawn).
    #[derive(serde_derive::Deserialize, Clone, Debug, PartialEq)]
    #[serde(rename_all = "camelCase")]
    pub struct SpawningCreep {
        /// The name of this creep, unique per player.
        pub name: String,
        /// The total number of game ticks needed to spawn this creep.
        #[serde(rename = "needTime")]
        pub total_time: u32,
        /// The number of game ticks left before this creep is spawned.
        pub remaining_time: u32,
    }

    /// The update structure for a spawning creep.
    #[derive(serde_derive::Deserialize, Clone, Debug)]
    #[serde(rename_all = "camelCase")]
    pub struct SpawningCreepUpdate { ... }
}

with_structure_fields_and_update_struct! {
    /// A spawn structure - a structure which can create creeps.
    #[derive(Clone, Debug, PartialEq)]
    #[serde(rename_all = "camelCase")]
    pub struct StructureSpawn {
        /// The user ID of the owner of this structure.
        pub user: String,
        /// Whether or not this structure is non-functional due to a degraded controller.
        #[serde(default, rename = "off")]
        pub disabled: bool,
        /// The current amount of energy held in this structure.
        pub energy: i32,
        /// The maximum amount of energy that can be held in this structure.
        pub energy_capacity: i32,
        /// Whether or not an attack on this structure will send an email to the owner automatically.
        pub notify_when_attacked: bool,
        /// The name of this spawn, unique per player.
        pub name: String,
        /// The creep that's currently spawning, if any.
        pub spawning: Option<SpawningCreep>,
    }

    /// The update structure for a mineral object.
    #[derive(Clone, Debug)]
    #[serde(rename_all = "camelCase")]
    pub struct StructureSpawnUpdate {
        - user: String,
        #[serde(rename = "off")]
        - disabled: bool,
        - energy: i32,
        - energy_capacity: i32,
        - notify_when_attacked: bool,
        - name: String,
        - spawning: Option<SpawningCreep>,
    }
}

#[cfg(test)]
mod test {
    use serde_json;

    use serde::Deserialize;

    use crate::data::RoomName;

    use super::{SpawningCreep, StructureSpawn};

    #[test]
    fn parse_empty_spawn() {
        let json = json!({
            "_id": "5f0236153187fd5e3dfa814a",
            "hits": 5000,
            "hitsMax": 5000,
            "name": "Spawn1",
            "notifyWhenAttacked": true,
            "off": false,
            "room": "W41N48",
            "spawning": null,
            "store": {
                "energy": 300
            },
            "storeCapacityResource": {
                "energy": 300
            },
            "type": "spawn",
            "user": "57874d42d0ae911e3bd15bbc",
            "x": 26,
            "y": 28
        });

        let obj = StructureSpawn::deserialize(json).unwrap();

        assert_eq!(
            obj,
            StructureSpawn {
                id: "5f0236153187fd5e3dfa814a".to_owned(),
                room: RoomName::new("W31N48").unwrap(),
                x: 26,
                y: 28,
                energy: 300,
                energy_capacity: 300,
                hits: 5000,
                hits_max: 5000,
                name: "Spawn1".to_owned(),
                notify_when_attacked: true,
                disabled: false,
                spawning: None,
                user: "57874d42d0ae911e3bd15bbc".to_owned(),
            }
        );
    }

    #[test]
    fn parse_spawn_and_update() {
        let json = json!({
            "_id": "58a23b6c4370e6302d758099",
            "energy": 300,
            "energyCapacity": 300,
            "hits": 5000,
            "hitsMax": 5000,
            "name": "Spawn36",
            "notifyWhenAttacked": true,
            "off": false,
            "room": "E4S61",
            "spawning": {
                "name": "5599",
                "needTime": 126,
                "remainingTime": 5,
            },
            "type": "spawn",
            "user": "57874d42d0ae911e3bd15bbc",
            "x": 24,
            "y": 6,
        });

        let mut obj = StructureSpawn::deserialize(json).unwrap();

        assert_eq!(
            obj,
            StructureSpawn {
                id: "58a23b6c4370e6302d758099".to_owned(),
                room: RoomName::new("E4S61").unwrap(),
                x: 24,
                y: 6,
                energy: 300,
                energy_capacity: 300,
                hits: 5000,
                hits_max: 5000,
                name: "Spawn36".to_owned(),
                notify_when_attacked: true,
                disabled: false,
                spawning: Some(SpawningCreep {
                    name: "5599".to_owned(),
                    total_time: 126,
                    remaining_time: 5,
                }),
                user: "57874d42d0ae911e3bd15bbc".to_owned(),
            }
        );

        obj.update(
            serde_json::from_value(json!({
                "spawning": {
                    "remainingTime": 4,
                },
            }))
            .unwrap(),
        );

        obj.update(
            serde_json::from_value(json!({
                "spawning": {
                    "remainingTime": 3,
                },
            }))
            .unwrap(),
        );

        obj.update(
            serde_json::from_value(json!({
                "spawning": {
                    "remainingTime": 2,
                },
            }))
            .unwrap(),
        );

        obj.update(
            serde_json::from_value(json!({
                "spawning": {
                    "remainingTime": 1,
                },
            }))
            .unwrap(),
        );

        assert_eq!(
            obj.spawning,
            Some(SpawningCreep {
                name: "5599".to_owned(),
                total_time: 126,
                remaining_time: 1,
            })
        );

        obj.update(
            serde_json::from_value(json!({
                "spawning": null,
            }))
            .unwrap(),
        );

        assert_eq!(obj.spawning, None);
    }
}
<commit_msg>Updated StructureSpawn<commit_after>//! `StructureSpawn` data description.
use super::super::resources::Store;
use crate::data::RoomName;

with_update_struct! {
    /// A struct describing a creep currently spawning (used as part of the update for a StructureSpawn).
    #[derive(serde_derive::Deserialize, Clone, Debug, PartialEq)]
    #[serde(rename_all = "camelCase")]
    pub struct SpawningCreep {
        /// The name of this creep, unique per player.
        pub name: String,
        /// The total number of game ticks needed to spawn this creep.
        #[serde(rename = "needTime")]
        pub total_time: u32,
        /// The game tick on which the creep will be spawned.
        pub spawn_time: u32,
    }

    /// The update structure for a spawning creep.
    #[derive(serde_derive::Deserialize, Clone, Debug)]
    #[serde(rename_all = "camelCase")]
    pub struct SpawningCreepUpdate { ... }
}

with_structure_fields_and_update_struct! {
    /// A spawn structure - a structure which can create creeps.
    #[derive(Clone, Debug, PartialEq)]
    #[serde(rename_all = "camelCase")]
    pub struct StructureSpawn {
        /// The user ID of the owner of this structure.
        pub user: String,
        /// Whether or not this structure is non-functional due to a degraded controller.
        #[serde(default, rename = "off")]
        pub disabled: bool,
        /// The current amount of energy held in this structure.
        pub store: Store,
        /// The maximum amount of energy that can be held in this structure.
        #[serde(rename = "storeCapacityResource")]
        pub capacity_resource: Store,
        /// Whether or not an attack on this structure will send an email to the owner automatically.
        pub notify_when_attacked: bool,
        /// The name of this spawn, unique per player.
        pub name: String,
        /// The creep that's currently spawning, if any.
        pub spawning: Option<SpawningCreep>,
    }

    /// The update structure for a mineral object.
    #[derive(Clone, Debug)]
    #[serde(rename_all = "camelCase")]
    pub struct StructureSpawnUpdate {
        - user: String,
        #[serde(rename = "off")]
        - disabled: bool,
        - store: Store,
        #[serde(rename = "storeCapacityResource")]
        - capacity_resource: Store,
        - notify_when_attacked: bool,
        - name: String,
        - spawning: Option<SpawningCreep>,
    }
}

#[cfg(test)]
mod test {
    use serde_json;

    use serde::Deserialize;

    use crate::data::RoomName;

    use super::{SpawningCreep, StructureSpawn};

    #[test]
    fn parse_empty_spawn() {
        let json = json!({
            "_id": "5f0236153187fd5e3dfa814a",
            "hits": 5000,
            "hitsMax": 5000,
            "name": "Spawn1",
            "notifyWhenAttacked": true,
            "off": false,
            "room": "W41N48",
            "spawning": null,
            "store": {
                "energy": 300
            },
            "storeCapacityResource": {
                "energy": 300
            },
            "type": "spawn",
            "user": "57874d42d0ae911e3bd15bbc",
            "x": 26,
            "y": 28
        });

        let obj = StructureSpawn::deserialize(json).unwrap();

        assert_eq!(
            obj,
            StructureSpawn {
                id: "5f0236153187fd5e3dfa814a".to_owned(),
                room: RoomName::new("W41N48").unwrap(),
                x: 26,
                y: 28,
                store: store! { Energy: 300 },
                capacity_resource: store! { Energy: 300 },
                hits: 5000,
                hits_max: 5000,
                name: "Spawn1".to_owned(),
                notify_when_attacked: true,
                disabled: false,
                spawning: None,
                user: "57874d42d0ae911e3bd15bbc".to_owned(),
            }
        );
    }

    #[test]
    fn parse_spawn_and_update() {
        let json = json!({
          "_id": "5d25a0b8e52ab5700a3747ab",
          "type": "spawn",
          "room": "W44S12",
          "x": 28,
          "y": 26,
          "name": "Spawn1",
          "user": "5a8466038f866773f59fa6c8",
          "hits": 5000,
          "hitsMax": 5000,
          "spawning": {
            "name": "902640",
            "needTime": 144,
            "spawnTime": 24577555
          },
          "notifyWhenAttacked": true,
          "off": false,
          "store": {
            "energy": 300
          },
          "storeCapacityResource": {
            "energy": 300
          }
        });

        let mut obj = StructureSpawn::deserialize(json).unwrap();

        assert_eq!(
            obj,
            StructureSpawn {
                id: "5d25a0b8e52ab5700a3747ab".to_owned(),
                room: RoomName::new("W44S12").unwrap(),
                x: 28,
                y: 26,
                store: store! { Energy: 300 },
                capacity_resource: store! { Energy: 300 },
                hits: 5000,
                hits_max: 5000,
                name: "Spawn1".to_owned(),
                notify_when_attacked: true,
                disabled: false,
                spawning: Some(SpawningCreep {
                    name: "902640".to_owned(),
                    total_time: 144,
                    spawn_time: 24577555,
                }),
                user: "5a8466038f866773f59fa6c8".to_owned(),
            }
        );

        obj.update(serde_json::from_value(json!({ "spawning": null })).unwrap());

        assert_eq!(obj.spawning, None);

        obj.update(
            serde_json::from_value(json!({
              "spawning": {
                "name": "8449040",
                "needTime": 144,
                "spawnTime": 24577699
              },
              "store": {
                "energy": 0
              }
            }))
            .unwrap(),
        );

        assert_eq!(
            obj.spawning,
            Some(SpawningCreep {
                name: "8449040".to_owned(),
                total_time: 144,
                spawn_time: 24577699,
            })
        );

        assert_eq!(obj.store, store! {});

        obj.update(
            serde_json::from_value(json!({
              "store": {
                "energy": 300
              }
            }))
            .unwrap(),
        );

        assert_eq!(obj.store, store! { Energy: 300 });
    }
}
<|endoftext|>


<commit_before><commit_msg>Skeleton for problem 2216<commit_after>// https://leetcode.com/problems/minimum-deletions-to-make-array-beautiful/
pub fn min_deletion(nums: Vec<i32>) -> i32 {
    todo!()
}

fn main() {
    println!("{}", min_deletion(vec![1, 1, 2, 3, 5])); // 1
    println!("{}", min_deletion(vec![1, 1, 2, 2, 3, 3])); // 2
}
<|endoftext|>


<commit_before><commit_msg>indentation prettification<commit_after><|endoftext|>


<commit_before><commit_msg>Explain try_get_value macro a bit more<commit_after><|endoftext|>


<commit_before><commit_msg>Use fully qualified paths in the `macros` module<commit_after><|endoftext|>


<commit_before><commit_msg>Reorganized module<commit_after><|endoftext|>


<commit_before>//! Parsing functionality - get cookie data

use std::collections::treemap::TreeMap;
use url::lossy_utf8_percent_decode;
use serialize::json;
use serialize::json::{Json, Null};
use iron::{Request, Response, Middleware, Alloy, Status, Continue};
use super::Cookie;
use crypto::util::fixed_time_eq;

/// The cookie parsing `Middleware`.
///
/// It will parse the body of a cookie into the alloy, under type `Cookie`.
///
/// This middleware should be linked (added to the `Chain`)
/// before any other middleware using cookies, or the parsed cookie
/// will not be available to that middleware.
#[deriving(Clone)]
pub struct CookieParser {
    secret: Option<String>
}

impl CookieParser {
    /// Create a new instance of the cookie parsing `Middleware`.
    ///
    /// This instance will parse both RFC 6265-styled cookies:
    /// `key=value; key=value;`
    /// and json-styled cookies, as set with `res.set_json_cookie(...)`.
    pub fn new() -> CookieParser { CookieParser{ secret: None} }

    /// Create a cookie parser with secret, for signed cookies.
    ///
    /// This instance will parse any cookies that have been signed by
    /// you, or that are unsigned. It will not parse those cookies signed by others.
    ///
    /// Otherwise, it will behave exactly like that produced by `new`.
    pub fn signed(secret: String) -> CookieParser { CookieParser{ secret: Some(secret) } }
}

impl Middleware for CookieParser {
    /// Parse the cookie received in the HTTP header.
    ///
    /// This will parse the body of a cookie into the alloy, under type `Cookie`.
    fn enter(&mut self, req: &mut Request, _res: &mut Response, alloy: &mut Alloy) -> Status {
        // Initialize a cookie. This will store parsed cookies and generate signatures.
        let mut new_cookie = Cookie::new(self.secret.clone());

        match req.headers.extensions.find_mut(&"Cookie".to_string()) {
            Some(cookies) => {
                // Initialize an empty json object.
                let mut new_json = json::Object(TreeMap::new());
                new_cookie.map =
                    cookies
                        .as_slice()
                        .split(';')
                        // Decode from uri component encoding
                        .map(|substr| {
                            let vec: Vec<&str> = substr.splitn('=', 1).collect();
                            let key = from_rfc_compliant(vec[0]);
                            let val = from_rfc_compliant(vec[1]);
                            (key, val) })
                        // Check for signed cookies, and filter those not signed by us
                        .filter_map(|cookie| strip_signature(cookie, &new_cookie))
                        // Move json cookies into a separate container
                        .filter(|cookie| parse_json(cookie, &mut new_json))
                        .collect();

                // This cannot be inserted via iterators because strip_signature
                // is already borrowing new_cookie.
                new_cookie.json = new_json;
            },
            None => ()
        }
        alloy.insert(new_cookie);
        Continue
    }
}

fn from_rfc_compliant(string: &str) -> String {
    lossy_utf8_percent_decode(
        string
            .chars()
            .skip_while(is_whitespace)
            .collect::<String>()
            .as_bytes()
    )
}

fn is_whitespace(c: &char) -> bool {
    match *c {
        ' '|'\r'|'\t'|'\n' => true,
        _                  => false
    }
}

fn strip_signature((key, val): (String, String), signer: &Cookie) -> Option<(String, String)> {
    if val.len() > 2 && val.as_slice().slice(0, 2) == "s:" {
        if !signer.signed { return None }
        // Extract the signature (in hex), appended onto the cookie after `.`
        return regex!(r"\.[^\.]*$").find(val.as_slice())
            // If it was signed by us, clear the signature
            .and_then(|(beg, end)| {
                signer.sign(&val.as_slice().slice(2, beg).to_string())
                    // We need to maintain access to (beg, end), so we chain the signature
                    .and_then(|signature| {
                        // If the signature is valid, strip it
                        if fixed_time_eq(val.as_slice().slice(beg + 1, end).as_bytes(), signature.as_bytes()) {
                            // key must be cloned to move out of the closure capture
                            Some((key.clone(), val.as_slice().slice(2, beg).to_string()))
                        // Else, remove the cookie
                        } else {
                            None
                        }
                    })
            })
    }
    match signer.signed {
        true => None,
        false => Some((key, val))
    }
}

fn parse_json(&(ref key, ref val): &(String, String), json: &mut Json) -> bool {
    if val.len() > 2 && val.as_slice().slice(0, 2) == "j:" {
        match *json {
            json::Object(ref mut root) => {
                root.insert(key.clone(),
                    match json::from_str(val.as_slice().slice_from(2)) {
                        Ok(obj) => obj,
                        Err(_)  => Null
                    });
            },
            _                    => ()
        }
        return false
    }
    true
}

#[cfg(test)]
mod test {
    use std::mem::uninitialized;
    use std::collections::{HashMap, TreeMap};
    use http::headers::request::HeaderCollection;
    use iron::{Request, Alloy, Middleware};
    use super::*;
    use super::super::cookie::*;
    use serialize::json::{Object, String};

    // Parse a given `String` as an HTTP Cookie header, using the CookieParser middleware,
    // and return the cookie stored in the alloy by that middleware
    fn get_cookie(secret: Option<String>, cookie: String, alloy: &mut Alloy) -> &Cookie {
        let mut req = Request {
            url: "".to_string(),
            remote_addr: None,
            headers: box HeaderCollection::new(),
            body: "".to_string(),
            method: ::http::method::Get,
        };
        req.headers.extensions.insert("Cookie".to_string(), cookie);
        let mut signer = match secret {
            Some(s) => CookieParser::signed(s),
            None => CookieParser::new()
        };
        unsafe { signer.enter(&mut req, uninitialized(), alloy) };
        alloy.find::<Cookie>().unwrap()
    }

    #[test]
    fn check_cookie() {
        let mut alloy = Alloy::new();
        let cookie = get_cookie(None, "thing=thing".to_string(), &mut alloy);
        let mut map = HashMap::new();
        map.insert("thing".to_string(), "thing".to_string());
        assert_eq!(cookie.map, map);
    }

    #[test]
    fn check_escaping() {
        // Url component decoding should decode the escaped characters
        let mut alloy = Alloy::new();
        let cookie = get_cookie(None,
                                "~%60%21%40%23%24%25%5E%26%2A%28%29_%2B-%3D%7B%7D%7C%5B%5D%5C%3A%22%3B%27%3C%3E%3F%2C.%2F%27=\
                                ~%60%21%40%23%24%25%5E%26%2A%28%29_%2B-%3D%7B%7D%7C%5B%5D%5C%3A%22%3B%27%3C%3E%3F%2C.%2F%27".to_string(),
                                &mut alloy);
        let mut map = HashMap::new();
        map.insert("~`!@#$%^&*()_+-={}|[]\\:\";'<>?,./'".to_string(),
                   "~`!@#$%^&*()_+-={}|[]\\:\";'<>?,./'".to_string());
        assert_eq!(cookie.map, map);
    }

    #[test]
    fn check_signature() {
        // The signature should be the HMAC-SHA256 hash of key "@zzmp" and message "thung"
        let mut alloy = Alloy::new();
        let cookie = get_cookie(Some("@zzmp".to_string()),
                                "thing=s:thung.e99abddcf60cad18f8d4b993efae53e81410cf2b2855af0309f1ae46fa527fbb".to_string(),
                                &mut alloy);
        let mut map = HashMap::new();
        map.insert("thing".to_string(),
                   "thung".to_string());
        assert_eq!(cookie.map, map);
    }

    #[test]
    fn check_silo() {
        // The unsigned cookie should not be parsed by the signed cookie parser
        let mut alloy = Alloy::new();
        let cookie = get_cookie(Some("@zzmp".to_string()),
                                "thing=thung".to_string(),
                                &mut alloy);
        let map = HashMap::new();
        assert_eq!(cookie.map, map);
    }

    #[test]
    fn check_json() {
        // Parse the Url component JSON: {"thing":{"foo":"bar"}}
        let mut alloy = Alloy::new();
        let cookie = get_cookie(None,
                                "thing=j%3A%7B%22foo%22%3A%22bar%22%7D".to_string(),
                                &mut alloy);
        let mut child_map = TreeMap::new();
        child_map.insert("foo".to_string(), String("bar".to_string()));
        let child = Object(child_map);
        let mut root_map = TreeMap::new();
        root_map.insert("thing".to_string(), child);
        let root = Object(root_map);
        assert_eq!(cookie.json, root); // FIXME
    }
}
<commit_msg>(fix) Conformed to iron changes.<commit_after>//! Parsing functionality - get cookie data

use std::collections::treemap::TreeMap;
use url::lossy_utf8_percent_decode;
use serialize::json;
use serialize::json::{Json, Null};
use iron::{Request, Response, Middleware, Status, Continue};
use super::Cookie;
use crypto::util::fixed_time_eq;

/// The cookie parsing `Middleware`.
///
/// It will parse the body of a cookie into the alloy, under type `Cookie`.
///
/// This middleware should be linked (added to the `Chain`)
/// before any other middleware using cookies, or the parsed cookie
/// will not be available to that middleware.
#[deriving(Clone)]
pub struct CookieParser {
    secret: Option<String>
}

impl CookieParser {
    /// Create a new instance of the cookie parsing `Middleware`.
    ///
    /// This instance will parse both RFC 6265-styled cookies:
    /// `key=value; key=value;`
    /// and json-styled cookies, as set with `res.set_json_cookie(...)`.
    pub fn new() -> CookieParser { CookieParser{ secret: None} }

    /// Create a cookie parser with secret, for signed cookies.
    ///
    /// This instance will parse any cookies that have been signed by
    /// you, or that are unsigned. It will not parse those cookies signed by others.
    ///
    /// Otherwise, it will behave exactly like that produced by `new`.
    pub fn signed(secret: String) -> CookieParser { CookieParser{ secret: Some(secret) } }
}

impl Middleware for CookieParser {
    /// Parse the cookie received in the HTTP header.
    ///
    /// This will parse the body of a cookie into the alloy, under type `Cookie`.
    fn enter(&mut self, req: &mut Request, _res: &mut Response) -> Status {
        // Initialize a cookie. This will store parsed cookies and generate signatures.
        let mut new_cookie = Cookie::new(self.secret.clone());

        match req.headers.extensions.find_mut(&"Cookie".to_string()) {
            Some(cookies) => {
                // Initialize an empty json object.
                let mut new_json = json::Object(TreeMap::new());
                new_cookie.map =
                    cookies
                        .as_slice()
                        .split(';')
                        // Decode from uri component encoding
                        .map(|substr| {
                            let vec: Vec<&str> = substr.splitn('=', 1).collect();
                            let key = from_rfc_compliant(vec[0]);
                            let val = from_rfc_compliant(vec[1]);
                            (key, val) })
                        // Check for signed cookies, and filter those not signed by us
                        .filter_map(|cookie| strip_signature(cookie, &new_cookie))
                        // Move json cookies into a separate container
                        .filter(|cookie| parse_json(cookie, &mut new_json))
                        .collect();

                // This cannot be inserted via iterators because strip_signature
                // is already borrowing new_cookie.
                new_cookie.json = new_json;
            },
            None => ()
        }
        req.alloy.insert(new_cookie);
        Continue
    }
}

fn from_rfc_compliant(string: &str) -> String {
    lossy_utf8_percent_decode(
        string
            .chars()
            .skip_while(is_whitespace)
            .collect::<String>()
            .as_bytes()
    )
}

fn is_whitespace(c: &char) -> bool {
    match *c {
        ' '|'\r'|'\t'|'\n' => true,
        _                  => false
    }
}

fn strip_signature((key, val): (String, String), signer: &Cookie) -> Option<(String, String)> {
    if val.len() > 2 && val.as_slice().slice(0, 2) == "s:" {
        if !signer.signed { return None }
        // Extract the signature (in hex), appended onto the cookie after `.`
        return regex!(r"\.[^\.]*$").find(val.as_slice())
            // If it was signed by us, clear the signature
            .and_then(|(beg, end)| {
                signer.sign(&val.as_slice().slice(2, beg).to_string())
                    // We need to maintain access to (beg, end), so we chain the signature
                    .and_then(|signature| {
                        // If the signature is valid, strip it
                        if fixed_time_eq(val.as_slice().slice(beg + 1, end).as_bytes(), signature.as_bytes()) {
                            // key must be cloned to move out of the closure capture
                            Some((key.clone(), val.as_slice().slice(2, beg).to_string()))
                        // Else, remove the cookie
                        } else {
                            None
                        }
                    })
            })
    }
    match signer.signed {
        true => None,
        false => Some((key, val))
    }
}

fn parse_json(&(ref key, ref val): &(String, String), json: &mut Json) -> bool {
    if val.len() > 2 && val.as_slice().slice(0, 2) == "j:" {
        match *json {
            json::Object(ref mut root) => {
                root.insert(key.clone(),
                    match json::from_str(val.as_slice().slice_from(2)) {
                        Ok(obj) => obj,
                        Err(_)  => Null
                    });
            },
            _                    => ()
        }
        return false
    }
    true
}

#[cfg(test)]
mod test {
    use std::mem::uninitialized;
    use std::collections::{HashMap, TreeMap};
    use http::headers::request::HeaderCollection;
    use iron::{Request, Alloy, Middleware};
    use super::*;
    use super::super::cookie::*;
    use serialize::json::{Object, String};

    // Parse a given `String` as an HTTP Cookie header, using the CookieParser middleware,
    // and return the cookie stored in the alloy by that middleware
    fn get_cookie(secret: Option<String>, cookie: String) -> &Cookie {
        let mut req = Request {
            url: "".to_string(),
            remote_addr: None,
            headers: box HeaderCollection::new(),
            body: "".to_string(),
            method: ::http::method::Get,
        };
        req.headers.extensions.insert("Cookie".to_string(), cookie);
        let mut signer = match secret {
            Some(s) => CookieParser::signed(s),
            None => CookieParser::new()
        };
        unsafe { signer.enter(&mut req, uninitialized(), req.alloy) };
        req.alloy.find::<Cookie>().unwrap()
    }

    #[test]
    fn check_cookie() {
        let mut alloy = Alloy::new();
        let cookie = get_cookie(None, "thing=thing".to_string(), &mut alloy);
        let mut map = HashMap::new();
        map.insert("thing".to_string(), "thing".to_string());
        assert_eq!(cookie.map, map);
    }

    #[test]
    fn check_escaping() {
        // Url component decoding should decode the escaped characters
        let mut alloy = Alloy::new();
        let cookie = get_cookie(None,
                                "~%60%21%40%23%24%25%5E%26%2A%28%29_%2B-%3D%7B%7D%7C%5B%5D%5C%3A%22%3B%27%3C%3E%3F%2C.%2F%27=\
                                ~%60%21%40%23%24%25%5E%26%2A%28%29_%2B-%3D%7B%7D%7C%5B%5D%5C%3A%22%3B%27%3C%3E%3F%2C.%2F%27".to_string(),
                                &mut alloy);
        let mut map = HashMap::new();
        map.insert("~`!@#$%^&*()_+-={}|[]\\:\";'<>?,./'".to_string(),
                   "~`!@#$%^&*()_+-={}|[]\\:\";'<>?,./'".to_string());
        assert_eq!(cookie.map, map);
    }

    #[test]
    fn check_signature() {
        // The signature should be the HMAC-SHA256 hash of key "@zzmp" and message "thung"
        let mut alloy = Alloy::new();
        let cookie = get_cookie(Some("@zzmp".to_string()),
                                "thing=s:thung.e99abddcf60cad18f8d4b993efae53e81410cf2b2855af0309f1ae46fa527fbb".to_string(),
                                &mut alloy);
        let mut map = HashMap::new();
        map.insert("thing".to_string(),
                   "thung".to_string());
        assert_eq!(cookie.map, map);
    }

    #[test]
    fn check_silo() {
        // The unsigned cookie should not be parsed by the signed cookie parser
        let mut alloy = Alloy::new();
        let cookie = get_cookie(Some("@zzmp".to_string()),
                                "thing=thung".to_string(),
                                &mut alloy);
        let map = HashMap::new();
        assert_eq!(cookie.map, map);
    }

    #[test]
    fn check_json() {
        // Parse the Url component JSON: {"thing":{"foo":"bar"}}
        let mut alloy = Alloy::new();
        let cookie = get_cookie(None,
                                "thing=j%3A%7B%22foo%22%3A%22bar%22%7D".to_string(),
                                &mut alloy);
        let mut child_map = TreeMap::new();
        child_map.insert("foo".to_string(), String("bar".to_string()));
        let child = Object(child_map);
        let mut root_map = TreeMap::new();
        root_map.insert("thing".to_string(), child);
        let root = Object(root_map);
        assert_eq!(cookie.json, root); // FIXME
    }
}
<|endoftext|>


<commit_before>//! Game window operations.

use input::InputEvent;

/// Settings for window behavior.
pub struct WindowSettings {
    /// Title of the window.
    pub title: String,
    /// The size of the window.
    pub size: [u32, ..2],
    /// Number samples per pixel (anti-aliasing).
    pub samples: u8,
    /// If true, the window is fullscreen.
    pub fullscreen: bool,
    /// If true, exit when pressing Esc.
    pub exit_on_esc: bool,
}

impl WindowSettings {
    /// Gets default settings.
    ///
    /// This exits the window when pressing `Esc`.
    /// The background color is set to black.
    pub fn default() -> WindowSettings {
        WindowSettings {
            title: "Piston".to_string(),
            size: [640, 480],
            samples: 0,
            fullscreen: false,
            exit_on_esc: true,
        }
    }
}

/// Implemented by window back-end.
pub trait Window {
    /// Get the window's settings.
    fn get_settings<'a>(&'a self) -> &'a WindowSettings;

    /// Returns true if the window should close.
    fn should_close(&self) -> bool;

    /// Inform the window that it should close.
    fn close(&mut self);

    /// Get the window's size
    fn get_size(&self) -> (u32, u32) {
        (self.get_settings().size[0], self.get_settings().size[1])
    }

    /// Get the size in drawing coordinates.
    fn get_draw_size(&self) -> (u32, u32) {
        self.get_size()
    }

    /// Swap buffers.
    fn swap_buffers(&self) {}

    /// When the cursor is captured,
    /// it is hidden and the cursor position does not change.
    /// Only relative mouse motion is registered.
    fn capture_cursor(&mut self, _enabled: bool) {}

    /// Poll a event from window's event queue.
    fn poll_event(&mut self) -> Option<InputEvent> { None }
}

/// An implementation of GameWindow that represents running without a window at all
pub struct NoWindow {
    settings: WindowSettings,
    should_close: bool
}

impl NoWindow {
    /// Create a new nonexistant game window
    pub fn new(settings: WindowSettings) -> NoWindow {
         NoWindow {
             settings: settings,
             should_close: false
         }
    }
}

impl Window for NoWindow {
     fn get_settings<'a>(&'a self) -> &'a WindowSettings {
        &self.settings
     }

    fn should_close(&self) -> bool {
        self.should_close
    }

    fn close(&mut self) {
        self.should_close = true
    }

    fn get_size(&self) -> (u32, u32) {
        (0, 0)
    }
}
<commit_msg>Fixed duplicate call to get_settings<commit_after>//! Game window operations.

use input::InputEvent;

/// Settings for window behavior.
pub struct WindowSettings {
    /// Title of the window.
    pub title: String,
    /// The size of the window.
    pub size: [u32, ..2],
    /// Number samples per pixel (anti-aliasing).
    pub samples: u8,
    /// If true, the window is fullscreen.
    pub fullscreen: bool,
    /// If true, exit when pressing Esc.
    pub exit_on_esc: bool,
}

impl WindowSettings {
    /// Gets default settings.
    ///
    /// This exits the window when pressing `Esc`.
    /// The background color is set to black.
    pub fn default() -> WindowSettings {
        WindowSettings {
            title: "Piston".to_string(),
            size: [640, 480],
            samples: 0,
            fullscreen: false,
            exit_on_esc: true,
        }
    }
}

/// Implemented by window back-end.
pub trait Window {
    /// Get the window's settings.
    fn get_settings<'a>(&'a self) -> &'a WindowSettings;

    /// Returns true if the window should close.
    fn should_close(&self) -> bool;

    /// Inform the window that it should close.
    fn close(&mut self);

    /// Get the window's size
    fn get_size(&self) -> (u32, u32) {
        let settings = self.get_settings();
        (settings.size[0], settings.size[1])
    }

    /// Get the size in drawing coordinates.
    fn get_draw_size(&self) -> (u32, u32) {
        self.get_size()
    }

    /// Swap buffers.
    fn swap_buffers(&self) {}

    /// When the cursor is captured,
    /// it is hidden and the cursor position does not change.
    /// Only relative mouse motion is registered.
    fn capture_cursor(&mut self, _enabled: bool) {}

    /// Poll a event from window's event queue.
    fn poll_event(&mut self) -> Option<InputEvent> { None }
}

/// An implementation of GameWindow that represents running without a window at all
pub struct NoWindow {
    settings: WindowSettings,
    should_close: bool
}

impl NoWindow {
    /// Create a new nonexistant game window
    pub fn new(settings: WindowSettings) -> NoWindow {
         NoWindow {
             settings: settings,
             should_close: false
         }
    }
}

impl Window for NoWindow {
     fn get_settings<'a>(&'a self) -> &'a WindowSettings {
        &self.settings
     }

    fn should_close(&self) -> bool {
        self.should_close
    }

    fn close(&mut self) {
        self.should_close = true
    }

    fn get_size(&self) -> (u32, u32) {
        (0, 0)
    }
}
<|endoftext|>


<commit_before><commit_msg>change API a bit<commit_after><|endoftext|>


<commit_before>use uuid::Uuid;

use libimagstore::store::Store;
use libimagstore::storeid::IntoStoreId;
use module_path::ModuleEntryPath;

use error::{TodoError, TodoErrorKind};

/// With the uuid we get the storeid and then we can delete the entry
pub fn deleteFunc(uuid: Uuid, store : &Store) -> Result<(),TodoError> {
	// With the uuid we get the storeid
	let store_id = ModuleEntryPath::new(format!("taskwarrior/{}", uuid)).into_storeid();
	// It deletes an entry
	match store.delete(store_id) {
		Ok(val) => Ok(val),
		Err(e) => Err(TodoError::new(TodoErrorKind::StoreError, Some(Box::new(e)))),
	}
}

<commit_msg>fixed function name<commit_after>use uuid::Uuid;

use libimagstore::store::Store;
use libimagstore::storeid::IntoStoreId;
use module_path::ModuleEntryPath;

use error::{TodoError, TodoErrorKind};

/// With the uuid we get the storeid and then we can delete the entry
pub fn delete(uuid: Uuid, store : &Store) -> Result<(),TodoError> {
	// With the uuid we get the storeid
	let store_id = ModuleEntryPath::new(format!("taskwarrior/{}", uuid)).into_storeid();
	// It deletes an entry
	match store.delete(store_id) {
		Ok(val) => Ok(val),
		Err(e) => Err(TodoError::new(TodoErrorKind::StoreError, Some(Box::new(e)))),
	}
}

<|endoftext|>


<commit_before><commit_msg>auto merge of #5232 : bstrie/rust/issue4448, r=nikomatsakis<commit_after>// Copyright 2012 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.

fn main() {
    let (port, chan) = comm::stream::<&static/str>();

    do task::spawn {
        assert port.recv() == "hello, world";
    }

    chan.send("hello, world");
}
<|endoftext|>


<commit_before><commit_msg>Add parser benchmark<commit_after>#![feature(test)]

extern crate test;

use semver::{Prerelease, Version, VersionReq};
use test::{black_box, Bencher};

#[bench]
fn parse_prerelease(b: &mut Bencher) {
    let text = "x.7.z.92";
    b.iter(|| black_box(text).parse::<Prerelease>().unwrap());
}

#[bench]
fn parse_version(b: &mut Bencher) {
    let text = "1.0.2021-beta+exp.sha.5114f85";
    b.iter(|| black_box(text).parse::<Version>().unwrap());
}

#[bench]
fn parse_version_req(b: &mut Bencher) {
    let text = ">=1.2.3, <2.0.0";
    b.iter(|| black_box(text).parse::<VersionReq>().unwrap());
}
<|endoftext|>


<commit_before><commit_msg>More doc!<commit_after><|endoftext|>