<commit_before>// Copyright 2013 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 radix trie for storing integers in sorted order

use prelude::*;

// FIXME: #3469: need to manually update TrieNode when SHIFT changes
// FIXME: #5244: need to manually update the TrieNode constructor
const SHIFT: uint = 4;
const SIZE: uint = 1 << SHIFT;
const MASK: uint = SIZE - 1;

enum Child<T> {
    Internal(~TrieNode<T>),
    External(uint, T),
    Nothing
}

pub struct TrieMap<T> {
    priv root: TrieNode<T>,
    priv length: uint
}

impl<T> BaseIter<(uint, &'self T)> for TrieMap<T> {
    /// Visit all key-value pairs in order
    #[inline(always)]
    pure fn each(&self, f: &fn(&(uint, &self/T)) -> bool) {
        self.root.each(f);
    }
    #[inline(always)]
    pure fn size_hint(&self) -> Option<uint> { Some(self.len()) }
}

impl<T> ReverseIter<(uint, &'self T)> for TrieMap<T> {
    /// Visit all key-value pairs in reverse order
    #[inline(always)]
    pure fn each_reverse(&self, f: &fn(&(uint, &self/T)) -> bool) {
        self.root.each_reverse(f);
    }
}

impl<T> Container for TrieMap<T> {
    /// Return the number of elements in the map
    #[inline(always)]
    pure fn len(&self) -> uint { self.length }

    /// Return true if the map contains no elements
    #[inline(always)]
    pure fn is_empty(&self) -> bool { self.len() == 0 }
}

impl<T> Mutable for TrieMap<T> {
    /// Clear the map, removing all values.
    #[inline(always)]
    fn clear(&mut self) {
        self.root = TrieNode::new();
        self.length = 0;
    }
}

impl<T> Map<uint, T> for TrieMap<T> {
    /// Return true if the map contains a value for the specified key
    #[inline(always)]
    pure fn contains_key(&self, key: &uint) -> bool {
        self.find(key).is_some()
    }

    /// Visit all keys in order
    #[inline(always)]
    pure fn each_key(&self, f: &fn(&uint) -> bool) {
        self.each(|&(k, _)| f(&k))
    }

    /// Visit all values in order
    #[inline(always)]
    pure fn each_value(&self, f: &fn(&T) -> bool) {
        self.each(|&(_, v)| f(v))
    }

    /// Iterate over the map and mutate the contained values
    #[inline(always)]
    fn mutate_values(&mut self, f: &fn(&uint, &mut T) -> bool) {
        self.root.mutate_values(f);
    }

    /// Return the value corresponding to the key in the map
    #[inline(hint)]
    pure fn find(&self, key: &uint) -> Option<&self/T> {
        let mut node: &self/TrieNode<T> = &self.root;
        let mut idx = 0;
        loop {
            match node.children[chunk(*key, idx)] {
              Internal(ref x) => node = &**x,
              External(stored, ref value) => {
                if stored == *key {
                    return Some(value)
                } else {
                    return None
                }
              }
              Nothing => return None
            }
            idx += 1;
        }
    }

    /// Insert a key-value pair into the map. An existing value for a
    /// key is replaced by the new value. Return true if the key did
    /// not already exist in the map.
    #[inline(always)]
    fn insert(&mut self, key: uint, value: T) -> bool {
        let ret = insert(&mut self.root.count,
                         &mut self.root.children[chunk(key, 0)],
                         key, value, 1);
        if ret { self.length += 1 }
        ret
    }

    /// Remove a key-value pair from the map. Return true if the key
    /// was present in the map, otherwise false.
    #[inline(always)]
    fn remove(&mut self, key: &uint) -> bool {
        let ret = remove(&mut self.root.count,
                         &mut self.root.children[chunk(*key, 0)],
                         *key, 1);
        if ret { self.length -= 1 }
        ret
    }
}

impl<T> TrieMap<T> {
    #[inline(always)]
    static pure fn new() -> TrieMap<T> {
        TrieMap{root: TrieNode::new(), length: 0}
    }
}

impl<T> TrieMap<T> {
    /// Visit all keys in reverse order
    #[inline(always)]
    pure fn each_key_reverse(&self, f: &fn(&uint) -> bool) {
        self.each_reverse(|&(k, _)| f(&k))
    }

    /// Visit all values in reverse order
    #[inline(always)]
    pure fn each_value_reverse(&self, f: &fn(&T) -> bool) {
        self.each_reverse(|&(_, v)| f(v))
    }
}

pub struct TrieSet {
    priv map: TrieMap<()>
}

impl BaseIter<uint> for TrieSet {
    /// Visit all values in order
    pure fn each(&self, f: &fn(&uint) -> bool) { self.map.each_key(f) }
    pure fn size_hint(&self) -> Option<uint> { Some(self.len()) }
}

impl ReverseIter<uint> for TrieSet {
    /// Visit all values in reverse order
    pure fn each_reverse(&self, f: &fn(&uint) -> bool) {
        self.map.each_key_reverse(f)
    }
}

impl Container for TrieSet {
    /// Return the number of elements in the set
    #[inline(always)]
    pure fn len(&self) -> uint { self.map.len() }

    /// Return true if the set contains no elements
    #[inline(always)]
    pure fn is_empty(&self) -> bool { self.map.is_empty() }
}

impl Mutable for TrieSet {
    /// Clear the set, removing all values.
    #[inline(always)]
    fn clear(&mut self) { self.map.clear() }
}

impl TrieSet {
    /// Return true if the set contains a value
    #[inline(always)]
    pure fn contains(&self, value: &uint) -> bool {
        self.map.contains_key(value)
    }

    /// Add a value to the set. Return true if the value was not already
    /// present in the set.
    #[inline(always)]
    fn insert(&mut self, value: uint) -> bool { self.map.insert(value, ()) }

    /// Remove a value from the set. Return true if the value was
    /// present in the set.
    #[inline(always)]
    fn remove(&mut self, value: &uint) -> bool { self.map.remove(value) }
}

struct TrieNode<T> {
    count: uint,
    children: [Child<T> * 16] // FIXME: #3469: can't use the SIZE constant yet
}

impl<T> TrieNode<T> {
    #[inline(always)]
    static pure fn new() -> TrieNode<T> {
        // FIXME: #5244: [Nothing, ..SIZE] should be possible without Copy
        TrieNode{count: 0,
                 children: [Nothing, Nothing, Nothing, Nothing,
                            Nothing, Nothing, Nothing, Nothing,
                            Nothing, Nothing, Nothing, Nothing,
                            Nothing, Nothing, Nothing, Nothing]}
    }
}

impl<T> TrieNode<T> {
    pure fn each(&self, f: &fn(&(uint, &self/T)) -> bool) -> bool {
        for uint::range(0, self.children.len()) |idx| {
            match self.children[idx] {
                Internal(ref x) => if !x.each(f) { return false },
                External(k, ref v) => if !f(&(k, v)) { return false },
                Nothing => ()
            }
        }
        true
    }

    pure fn each_reverse(&self, f: &fn(&(uint, &self/T)) -> bool) -> bool {
        for uint::range_rev(self.children.len(), 0) |idx| {
            match self.children[idx - 1] {
                Internal(ref x) => if !x.each_reverse(f) { return false },
                External(k, ref v) => if !f(&(k, v)) { return false },
                Nothing => ()
            }
        }
        true
    }

    fn mutate_values(&mut self, f: &fn(&uint, &mut T) -> bool) -> bool {
        for vec::each_mut(self.children) |child| {
            match *child {
                Internal(ref mut x) => if !x.mutate_values(f) {
                    return false
                },
                External(k, ref mut v) => if !f(&k, v) { return false },
                Nothing => ()
            }
        }
        true
    }
}

// if this was done via a trait, the key could be generic
#[inline(always)]
pure fn chunk(n: uint, idx: uint) -> uint {
    let real_idx = uint::bytes - 1 - idx;
    (n >> (SHIFT * real_idx)) & MASK
}

fn insert<T>(count: &mut uint, child: &mut Child<T>, key: uint, value: T,
             idx: uint) -> bool {
    let mut tmp = Nothing;
    tmp <-> *child;
    let mut added = false;

    *child = match tmp {
      External(stored_key, stored_value) => {
          if stored_key == key {
              External(stored_key, value)
          } else {
              // conflict - split the node
              let mut new = ~TrieNode::new();
              insert(&mut new.count,
                     &mut new.children[chunk(stored_key, idx)],
                     stored_key, stored_value, idx + 1);
              insert(&mut new.count, &mut new.children[chunk(key, idx)], key,
                     value, idx + 1);
              added = true;
              Internal(new)
          }
      }
      Internal(x) => {
        let mut x = x;
        added = insert(&mut x.count, &mut x.children[chunk(key, idx)], key,
                       value, idx + 1);
        Internal(x)

      }
      Nothing => {
        *count += 1;
        added = true;
        External(key, value)
      }
    };
    added
}

fn remove<T>(count: &mut uint, child: &mut Child<T>, key: uint,
             idx: uint) -> bool {
    let (ret, this) = match *child {
      External(stored, _) => {
          if stored == key { (true, true) } else { (false, false) }
      }
      Internal(ref mut x) => {
          let ret = remove(&mut x.count, &mut x.children[chunk(key, idx)],
                           key, idx + 1);
          (ret, x.count == 0)
      }
      Nothing => (false, false)
    };

    if this {
        *child = Nothing;
        *count -= 1;
    }
    ret
}

#[cfg(test)]
pub fn check_integrity<T>(trie: &TrieNode<T>) {
    fail_unless!(trie.count != 0);

    let mut sum = 0;

    for trie.children.each |x| {
        match *x {
          Nothing => (),
          Internal(ref y) => {
              check_integrity(&**y);
              sum += 1
          }
          External(_, _) => { sum += 1 }
        }
    }

    fail_unless!(sum == trie.count);
}

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

    #[test]
    fn test_step() {
        let mut trie = TrieMap::new();
        let n = 300;

        for uint::range_step(1, n, 2) |x| {
            fail_unless!(trie.insert(x, x + 1));
            fail_unless!(trie.contains_key(&x));
            check_integrity(&trie.root);
        }

        for uint::range_step(0, n, 2) |x| {
            fail_unless!(!trie.contains_key(&x));
            fail_unless!(trie.insert(x, x + 1));
            check_integrity(&trie.root);
        }

        for uint::range(0, n) |x| {
            fail_unless!(trie.contains_key(&x));
            fail_unless!(!trie.insert(x, x + 1));
            check_integrity(&trie.root);
        }

        for uint::range_step(1, n, 2) |x| {
            fail_unless!(trie.remove(&x));
            fail_unless!(!trie.contains_key(&x));
            check_integrity(&trie.root);
        }

        for uint::range_step(0, n, 2) |x| {
            fail_unless!(trie.contains_key(&x));
            fail_unless!(!trie.insert(x, x + 1));
            check_integrity(&trie.root);
        }
    }

    #[test]
    fn test_each() {
        let mut m = TrieMap::new();

        fail_unless!(m.insert(3, 6));
        fail_unless!(m.insert(0, 0));
        fail_unless!(m.insert(4, 8));
        fail_unless!(m.insert(2, 4));
        fail_unless!(m.insert(1, 2));

        let mut n = 0;
        for m.each |&(k, v)| {
            fail_unless!(k == n);
            fail_unless!(*v == n * 2);
            n += 1;
        }
    }

    #[test]
    fn test_each_break() {
        let mut m = TrieMap::new();

        for uint::range_rev(uint::max_value, uint::max_value - 10000) |x| {
            m.insert(x, x / 2);
        }

        let mut n = uint::max_value - 9999;
        for m.each |&(k, v)| {
            if n == uint::max_value - 5000 { break }
            fail_unless!(n < uint::max_value - 5000);

            fail_unless!(k == n);
            fail_unless!(*v == n / 2);
            n += 1;
        }
    }

    #[test]
    fn test_each_reverse() {
        let mut m = TrieMap::new();

        fail_unless!(m.insert(3, 6));
        fail_unless!(m.insert(0, 0));
        fail_unless!(m.insert(4, 8));
        fail_unless!(m.insert(2, 4));
        fail_unless!(m.insert(1, 2));

        let mut n = 4;
        for m.each_reverse |&(k, v)| {
            fail_unless!(k == n);
            fail_unless!(*v == n * 2);
            n -= 1;
        }
    }

    #[test]
    fn test_each_reverse_break() {
        let mut m = TrieMap::new();

        for uint::range_rev(uint::max_value, uint::max_value - 10000) |x| {
            m.insert(x, x / 2);
        }

        let mut n = uint::max_value;
        for m.each_reverse |&(k, v)| {
            if n == uint::max_value - 5000 { break }
            fail_unless!(n > uint::max_value - 5000);

            fail_unless!(k == n);
            fail_unless!(*v == n / 2);
            n -= 1;
        }
    }
}
<commit_msg>auto merge of #5408 : thestinger/rust/trie, r=pcwalton<commit_after>// Copyright 2013 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 radix trie for storing integers in sorted order

use prelude::*;

// FIXME: #3469: need to manually update TrieNode when SHIFT changes
// FIXME: #5244: need to manually update the TrieNode constructor
const SHIFT: uint = 4;
const SIZE: uint = 1 << SHIFT;
const MASK: uint = SIZE - 1;

enum Child<T> {
    Internal(~TrieNode<T>),
    External(uint, T),
    Nothing
}

pub struct TrieMap<T> {
    priv root: TrieNode<T>,
    priv length: uint
}

impl<T> BaseIter<(uint, &'self T)> for TrieMap<T> {
    /// Visit all key-value pairs in order
    #[inline(always)]
    pure fn each(&self, f: &fn(&(uint, &self/T)) -> bool) {
        self.root.each(f);
    }
    #[inline(always)]
    pure fn size_hint(&self) -> Option<uint> { Some(self.len()) }
}

impl<T> ReverseIter<(uint, &'self T)> for TrieMap<T> {
    /// Visit all key-value pairs in reverse order
    #[inline(always)]
    pure fn each_reverse(&self, f: &fn(&(uint, &self/T)) -> bool) {
        self.root.each_reverse(f);
    }
}

impl<T> Container for TrieMap<T> {
    /// Return the number of elements in the map
    #[inline(always)]
    pure fn len(&self) -> uint { self.length }

    /// Return true if the map contains no elements
    #[inline(always)]
    pure fn is_empty(&self) -> bool { self.len() == 0 }
}

impl<T> Mutable for TrieMap<T> {
    /// Clear the map, removing all values.
    #[inline(always)]
    fn clear(&mut self) {
        self.root = TrieNode::new();
        self.length = 0;
    }
}

impl<T> Map<uint, T> for TrieMap<T> {
    /// Return true if the map contains a value for the specified key
    #[inline(always)]
    pure fn contains_key(&self, key: &uint) -> bool {
        self.find(key).is_some()
    }

    /// Visit all keys in order
    #[inline(always)]
    pure fn each_key(&self, f: &fn(&uint) -> bool) {
        self.each(|&(k, _)| f(&k))
    }

    /// Visit all values in order
    #[inline(always)]
    pure fn each_value(&self, f: &fn(&T) -> bool) {
        self.each(|&(_, v)| f(v))
    }

    /// Iterate over the map and mutate the contained values
    #[inline(always)]
    fn mutate_values(&mut self, f: &fn(&uint, &mut T) -> bool) {
        self.root.mutate_values(f);
    }

    /// Return the value corresponding to the key in the map
    #[inline(hint)]
    pure fn find(&self, key: &uint) -> Option<&self/T> {
        let mut node: &self/TrieNode<T> = &self.root;
        let mut idx = 0;
        loop {
            match node.children[chunk(*key, idx)] {
              Internal(ref x) => node = &**x,
              External(stored, ref value) => {
                if stored == *key {
                    return Some(value)
                } else {
                    return None
                }
              }
              Nothing => return None
            }
            idx += 1;
        }
    }

    /// Insert a key-value pair into the map. An existing value for a
    /// key is replaced by the new value. Return true if the key did
    /// not already exist in the map.
    #[inline(always)]
    fn insert(&mut self, key: uint, value: T) -> bool {
        let ret = insert(&mut self.root.count,
                         &mut self.root.children[chunk(key, 0)],
                         key, value, 1);
        if ret { self.length += 1 }
        ret
    }

    /// Remove a key-value pair from the map. Return true if the key
    /// was present in the map, otherwise false.
    #[inline(always)]
    fn remove(&mut self, key: &uint) -> bool {
        let ret = remove(&mut self.root.count,
                         &mut self.root.children[chunk(*key, 0)],
                         *key, 1);
        if ret { self.length -= 1 }
        ret
    }
}

impl<T> TrieMap<T> {
    /// Create an empty TrieMap
    #[inline(always)]
    static pure fn new() -> TrieMap<T> {
        TrieMap{root: TrieNode::new(), length: 0}
    }
}

impl<T> TrieMap<T> {
    /// Visit all keys in reverse order
    #[inline(always)]
    pure fn each_key_reverse(&self, f: &fn(&uint) -> bool) {
        self.each_reverse(|&(k, _)| f(&k))
    }

    /// Visit all values in reverse order
    #[inline(always)]
    pure fn each_value_reverse(&self, f: &fn(&T) -> bool) {
        self.each_reverse(|&(_, v)| f(v))
    }
}

pub struct TrieSet {
    priv map: TrieMap<()>
}

impl BaseIter<uint> for TrieSet {
    /// Visit all values in order
    pure fn each(&self, f: &fn(&uint) -> bool) { self.map.each_key(f) }
    pure fn size_hint(&self) -> Option<uint> { Some(self.len()) }
}

impl ReverseIter<uint> for TrieSet {
    /// Visit all values in reverse order
    pure fn each_reverse(&self, f: &fn(&uint) -> bool) {
        self.map.each_key_reverse(f)
    }
}

impl Container for TrieSet {
    /// Return the number of elements in the set
    #[inline(always)]
    pure fn len(&self) -> uint { self.map.len() }

    /// Return true if the set contains no elements
    #[inline(always)]
    pure fn is_empty(&self) -> bool { self.map.is_empty() }
}

impl Mutable for TrieSet {
    /// Clear the set, removing all values.
    #[inline(always)]
    fn clear(&mut self) { self.map.clear() }
}

impl TrieSet {
    /// Create an empty TrieSet
    #[inline(always)]
    static pure fn new() -> TrieSet {
        TrieSet{map: TrieMap::new()}
    }

    /// Return true if the set contains a value
    #[inline(always)]
    pure fn contains(&self, value: &uint) -> bool {
        self.map.contains_key(value)
    }

    /// Add a value to the set. Return true if the value was not already
    /// present in the set.
    #[inline(always)]
    fn insert(&mut self, value: uint) -> bool { self.map.insert(value, ()) }

    /// Remove a value from the set. Return true if the value was
    /// present in the set.
    #[inline(always)]
    fn remove(&mut self, value: &uint) -> bool { self.map.remove(value) }
}

struct TrieNode<T> {
    count: uint,
    children: [Child<T> * 16] // FIXME: #3469: can't use the SIZE constant yet
}

impl<T> TrieNode<T> {
    #[inline(always)]
    static pure fn new() -> TrieNode<T> {
        // FIXME: #5244: [Nothing, ..SIZE] should be possible without Copy
        TrieNode{count: 0,
                 children: [Nothing, Nothing, Nothing, Nothing,
                            Nothing, Nothing, Nothing, Nothing,
                            Nothing, Nothing, Nothing, Nothing,
                            Nothing, Nothing, Nothing, Nothing]}
    }
}

impl<T> TrieNode<T> {
    pure fn each(&self, f: &fn(&(uint, &self/T)) -> bool) -> bool {
        for uint::range(0, self.children.len()) |idx| {
            match self.children[idx] {
                Internal(ref x) => if !x.each(f) { return false },
                External(k, ref v) => if !f(&(k, v)) { return false },
                Nothing => ()
            }
        }
        true
    }

    pure fn each_reverse(&self, f: &fn(&(uint, &self/T)) -> bool) -> bool {
        for uint::range_rev(self.children.len(), 0) |idx| {
            match self.children[idx - 1] {
                Internal(ref x) => if !x.each_reverse(f) { return false },
                External(k, ref v) => if !f(&(k, v)) { return false },
                Nothing => ()
            }
        }
        true
    }

    fn mutate_values(&mut self, f: &fn(&uint, &mut T) -> bool) -> bool {
        for vec::each_mut(self.children) |child| {
            match *child {
                Internal(ref mut x) => if !x.mutate_values(f) {
                    return false
                },
                External(k, ref mut v) => if !f(&k, v) { return false },
                Nothing => ()
            }
        }
        true
    }
}

// if this was done via a trait, the key could be generic
#[inline(always)]
pure fn chunk(n: uint, idx: uint) -> uint {
    let sh = uint::bits - (SHIFT * (idx + 1));
    (n >> sh) & MASK
}

fn insert<T>(count: &mut uint, child: &mut Child<T>, key: uint, value: T,
             idx: uint) -> bool {
    let mut tmp = Nothing;
    tmp <-> *child;
    let mut added = false;

    *child = match tmp {
      External(stored_key, stored_value) => {
          if stored_key == key {
              External(stored_key, value)
          } else {
              // conflict - split the node
              let mut new = ~TrieNode::new();
              insert(&mut new.count,
                     &mut new.children[chunk(stored_key, idx)],
                     stored_key, stored_value, idx + 1);
              insert(&mut new.count, &mut new.children[chunk(key, idx)], key,
                     value, idx + 1);
              added = true;
              Internal(new)
          }
      }
      Internal(x) => {
        let mut x = x;
        added = insert(&mut x.count, &mut x.children[chunk(key, idx)], key,
                       value, idx + 1);
        Internal(x)

      }
      Nothing => {
        *count += 1;
        added = true;
        External(key, value)
      }
    };
    added
}

fn remove<T>(count: &mut uint, child: &mut Child<T>, key: uint,
             idx: uint) -> bool {
    let (ret, this) = match *child {
      External(stored, _) => {
          if stored == key { (true, true) } else { (false, false) }
      }
      Internal(ref mut x) => {
          let ret = remove(&mut x.count, &mut x.children[chunk(key, idx)],
                           key, idx + 1);
          (ret, x.count == 0)
      }
      Nothing => (false, false)
    };

    if this {
        *child = Nothing;
        *count -= 1;
    }
    ret
}

#[cfg(test)]
pub fn check_integrity<T>(trie: &TrieNode<T>) {
    fail_unless!(trie.count != 0);

    let mut sum = 0;

    for trie.children.each |x| {
        match *x {
          Nothing => (),
          Internal(ref y) => {
              check_integrity(&**y);
              sum += 1
          }
          External(_, _) => { sum += 1 }
        }
    }

    fail_unless!(sum == trie.count);
}

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

    #[test]
    fn test_step() {
        let mut trie = TrieMap::new();
        let n = 300;

        for uint::range_step(1, n, 2) |x| {
            fail_unless!(trie.insert(x, x + 1));
            fail_unless!(trie.contains_key(&x));
            check_integrity(&trie.root);
        }

        for uint::range_step(0, n, 2) |x| {
            fail_unless!(!trie.contains_key(&x));
            fail_unless!(trie.insert(x, x + 1));
            check_integrity(&trie.root);
        }

        for uint::range(0, n) |x| {
            fail_unless!(trie.contains_key(&x));
            fail_unless!(!trie.insert(x, x + 1));
            check_integrity(&trie.root);
        }

        for uint::range_step(1, n, 2) |x| {
            fail_unless!(trie.remove(&x));
            fail_unless!(!trie.contains_key(&x));
            check_integrity(&trie.root);
        }

        for uint::range_step(0, n, 2) |x| {
            fail_unless!(trie.contains_key(&x));
            fail_unless!(!trie.insert(x, x + 1));
            check_integrity(&trie.root);
        }
    }

    #[test]
    fn test_each() {
        let mut m = TrieMap::new();

        fail_unless!(m.insert(3, 6));
        fail_unless!(m.insert(0, 0));
        fail_unless!(m.insert(4, 8));
        fail_unless!(m.insert(2, 4));
        fail_unless!(m.insert(1, 2));

        let mut n = 0;
        for m.each |&(k, v)| {
            fail_unless!(k == n);
            fail_unless!(*v == n * 2);
            n += 1;
        }
    }

    #[test]
    fn test_each_break() {
        let mut m = TrieMap::new();

        for uint::range_rev(uint::max_value, uint::max_value - 10000) |x| {
            m.insert(x, x / 2);
        }

        let mut n = uint::max_value - 9999;
        for m.each |&(k, v)| {
            if n == uint::max_value - 5000 { break }
            fail_unless!(n < uint::max_value - 5000);

            fail_unless!(k == n);
            fail_unless!(*v == n / 2);
            n += 1;
        }
    }

    #[test]
    fn test_each_reverse() {
        let mut m = TrieMap::new();

        fail_unless!(m.insert(3, 6));
        fail_unless!(m.insert(0, 0));
        fail_unless!(m.insert(4, 8));
        fail_unless!(m.insert(2, 4));
        fail_unless!(m.insert(1, 2));

        let mut n = 4;
        for m.each_reverse |&(k, v)| {
            fail_unless!(k == n);
            fail_unless!(*v == n * 2);
            n -= 1;
        }
    }

    #[test]
    fn test_each_reverse_break() {
        let mut m = TrieMap::new();

        for uint::range_rev(uint::max_value, uint::max_value - 10000) |x| {
            m.insert(x, x / 2);
        }

        let mut n = uint::max_value;
        for m.each_reverse |&(k, v)| {
            if n == uint::max_value - 5000 { break }
            fail_unless!(n > uint::max_value - 5000);

            fail_unless!(k == n);
            fail_unless!(*v == n / 2);
            n -= 1;
        }
    }

    #[test]
    fn test_sane_chunk() {
        let x = 1;
        let y = 1 << (uint::bits - 1);

        let mut trie = TrieSet::new();

        fail_unless!(trie.insert(x));
        fail_unless!(trie.insert(y));

        fail_unless!(trie.len() == 2);

        let expected = [x, y];

        let mut i = 0;

        for trie.each |x| {
            fail_unless!(expected[i] == *x);
            i += 1;
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Implement 24-bit True Color Support<commit_after><|endoftext|>


<commit_before><commit_msg>Add Indirect State<commit_after><|endoftext|>


<commit_before><commit_msg>lib: move fn's, add PkgInfo<commit_after><|endoftext|>


<commit_before><commit_msg>Separate kind and position of LexicalError.<commit_after><|endoftext|>


<commit_before><commit_msg>05 - literals<commit_after>fn main() {
    // Suffixed literals, their types are known at initialization
    let x = 1u8;
    let y = 2u;
    let z = 3f32;

    // Unsuffixed literal, their types depend on how they are used
    let i = 1;
    let f = 1.0;

    // `size_of_val` returns the size of a variable in bytes
    println!("size of `x` in bytes: {}", std::mem::size_of_val(&x));
    println!("size of `y` in bytes: {}", std::mem::size_of_val(&y));
    println!("size of `z` in bytes: {}", std::mem::size_of_val(&z));
    println!("size of `i` in bytes: {}", std::mem::size_of_val(&i));
    println!("size of `f` in bytes: {}", std::mem::size_of_val(&f));

    // Constraints (summands must have the same type) for `i` and `f`
    let _constraint_i = x + i;
    let _constraint_f = z + f;
    // Commenting out these two lines we have a compile time error
}
<|endoftext|>


<commit_before><commit_msg>Add @weiznich's regression test<commit_after>// check-pass
// compile-flags: --emit=mir,link
// Regression test for issue #68264
// Checks that we don't encounter overflow
// when running const-prop on functions with
// complicated bounds
pub trait Query {}

pub trait AsQuery {
    type Query: Query;
}
pub trait Table: AsQuery + Sized {}

pub trait LimitDsl {
    type Output;
}

pub(crate) trait LoadQuery<Conn, U>: RunQueryDsl<Conn> {}

impl<T: Query> AsQuery for T {
    type Query = Self;
}

impl<T> LimitDsl for T
where
    T: Table,
    T::Query: LimitDsl,
{
    type Output = <T::Query as LimitDsl>::Output;
}

pub(crate) trait RunQueryDsl<Conn>: Sized {
    fn first<U>(self, _conn: &Conn) -> U
    where
        Self: LimitDsl,
        Self::Output: LoadQuery<Conn, U>,
    {
        // Overflow is caused by this function body
        unimplemented!()
    }
}

fn main() {}
<|endoftext|>


<commit_before>#[doc = "A library for handling colors and parsing css color declarations."]

// TODO: handle #rrggbb color declarations, handle rgb(r%,g%,b%),
// sanitize input / crop it to correct ranges, predefine other 130
// css-defined colors

import float::round;
import libc::types::os::arch::c95::c_double;
import css_colors::*;
import cmp::eq;

enum Color = {red : u8, green : u8, blue : u8, alpha : float};

impl Color of eq for Color {
    fn eq(&&other: Color) -> bool {
        ret self.red == other.red && self.green == other.green && self.blue == other.blue &&
            self.alpha == other.alpha;
    }
}

fn rgba(r : u8, g : u8, b : u8, a : float) -> Color {
    Color({red : r, green : g, blue : b, alpha : a})
}

fn rgb(r : u8, g : u8, b : u8) -> Color {
    ret rgba(r, g, b, 1.0);
}

fn hsla(h : float, s : float, l : float, a : float) -> Color {
    // Algorithm for converting hsl to rbg taken from
    // http://www.w3.org/TR/2003/CR-css3-color-20030514/#hsl-color
    let m2 = if l <= 0.5 { l*(s + 1.0) } else { l + s - l*s };
    let m1 = l*2.0 - m2;
    let h = h / 360.0;

    fn hue_to_rgb(m1 : float, m2 : float, h : float) -> float {
        let h = if h < 0.0 { h + 1.0 } else if h > 1.0 { h - 1.0 } else { h };

        alt h {
          0.0 to 1.0/6.0     { ret m1 + (m2 - m1)*h*6.0; }
          1.0/6.0 to 1.0/2.0 { ret m2; }
          1.0/2.0 to 2.0/3.0 { ret m1 + (m2 - m1)*(4.0 - 6.0*h); }
          2.0/3.0 to 1.0     { ret m1; }
          _                  { fail "unexpected hue value"; }
        }
    }

    let r = round(255.0*hue_to_rgb(m1, m2, h + 1.0/3.0) as c_double);;
    let g = round(255.0*hue_to_rgb(m1, m2, h) as c_double);
    let b = round(255.0*hue_to_rgb(m1, m2, h - 1.0/3.0) as c_double);

    ret rgba(r as u8, g as u8, b as u8, a);
}

fn hsl(h : float, s : float, l : float) -> Color {
    ret hsla(h, s, l, 1.0);
}

impl methods for Color {
    fn print() -> str {
        #fmt["rgba(%u,%u,%u,%f)", self.red as uint, self.green as uint,
             self.blue as uint, self.alpha]
    }
}

mod parsing {
    export parse_color;

    // TODO, fail by ignoring the rule instead of setting the
    // color to black
    fn fail_unrecognized(col : str) -> Color {
        #warn["Unrecognized color %s", col];
        ret  black();
    }

    #[doc="Match an exact color keyword."]
    fn parse_by_name(color : str) -> Color {
        alt color.to_lower() {
          "black"   { black()   }
          "silver"  { silver()  }
          "gray"    { gray()    }
          "grey"    { gray()    }
          "white"   { white()   }
          "maroon"  { maroon()  }
          "red"     { red()     }
          "purple"  { purple()  }
          "fuschia" { fuschia() }
          "green"   { green()   }
          "lime"    { lime()    }
          "olive"   { olive()   }
          "yellow"  { yellow()  }
          "navy"    { navy()    }
          "blue"    { blue()    }
          "teal"    { teal()    }
          "aqua"    { aqua()    }
          _         { fail_unrecognized(color) }
        }
    }

    #[doc="Parses a color specification in the form rgb(foo,bar,baz)"]
    fn parse_rgb(color : str) -> Color {
        // Shave off the rgb( and the )
        let only_colors = color.substr(4u, color.len() - 5u);

        // split up r, g, and b
        let cols = only_colors.split_char(',');
        if cols.len() != 3u { ret fail_unrecognized(color); }

        alt (u8::from_str(cols[0]), u8::from_str(cols[1]),
             u8::from_str(cols[2])) {
          (some(r), some(g), some(b)) { rgb(r, g, b) }
          _               { fail_unrecognized(color) }
        }
    }

    #[doc="Parses a color specification in the form rgba(foo,bar,baz,qux)"]
    fn parse_rgba(color : str) -> Color {
        // Shave off the rgba( and the )
        let only_vals = color.substr(5u, color.len() - 6u);

        // split up r, g, and b
        let cols = only_vals.split_char(',');
        if cols.len() != 4u { ret fail_unrecognized(color); }

        alt (u8::from_str(cols[0]), u8::from_str(cols[1]),
             u8::from_str(cols[2]), float::from_str(cols[3])) {
          (some(r), some(g), some(b), some(a)) { rgba(r, g, b, a) }
          _ { fail_unrecognized(color) }
        }
    }

    #[doc="Parses a color specification in the form hsl(foo,bar,baz)"]
    fn parse_hsl(color : str) -> Color {
        // Shave off the hsl( and the )
        let only_vals = color.substr(4u, color.len() - 5u);

        // split up h, s, and l
        let vals = only_vals.split_char(',');
        if vals.len() != 3u { ret fail_unrecognized(color); }

        alt (float::from_str(vals[0]), float::from_str(vals[1]),
             float::from_str(vals[2])) {
          (some(h), some(s), some(l)) { hsl(h, s, l) }
          _               { fail_unrecognized(color) }
        }
    }

    #[doc="Parses a color specification in the form hsla(foo,bar,baz,qux)"]
    fn parse_hsla(color : str) -> Color {
        // Shave off the hsla( and the )
        let only_vals = color.substr(5u, color.len() - 6u);

        let vals = only_vals.split_char(',');
        if vals.len() != 4u { ret fail_unrecognized(color); }

        alt (float::from_str(vals[0]), float::from_str(vals[1]),
             float::from_str(vals[2]), float::from_str(vals[3])) {
          (some(h), some(s), some(l), some(a)) { hsla(h, s, l, a) }
          _ { fail_unrecognized(color) }
        }
    }

    // Currently colors are supported in rgb(a,b,c) form and also by
    // keywords for several common colors.
    // TODO: extend this
    fn parse_color(color : str) -> Color {
        alt color {
          c if c.starts_with("rgb(")  { parse_rgb(c) }
          c if c.starts_with("rgba(") { parse_rgba(c) }
          c if c.starts_with("hsl(")  { parse_hsl(c) }
          c if c.starts_with("hsla(") { parse_hsla(c) }
          c                           { parse_by_name(c) }
        }
    }
}

mod test {
    import css_colors::*;
    import parsing::parse_color;

    #[test]
    fn test_parse_by_name() {
        assert red().eq(parse_color("red"));
        assert lime().eq(parse_color("Lime"));
        assert blue().eq(parse_color("BLUE"));
        assert green().eq(parse_color("GreEN"));
        assert white().eq(parse_color("white"));
        assert black().eq(parse_color("Black"));
        assert gray().eq(parse_color("Gray"));
        assert silver().eq(parse_color("SiLvEr"));
        assert maroon().eq(parse_color("maroon"));
        assert purple().eq(parse_color("PURPLE"));
        assert fuschia().eq(parse_color("FUSCHIA"));
        assert olive().eq(parse_color("oLiVe"));
        assert yellow().eq(parse_color("yellow"));
        assert navy().eq(parse_color("NAVY"));
        assert teal().eq(parse_color("Teal"));
        assert aqua().eq(parse_color("Aqua"));
    }

    #[test]
    fn test_parsing_rgb() {
        assert red().eq(parse_color("rgb(255,0,0)"));
        assert red().eq(parse_color("rgba(255,0,0,1.0)"));
        assert red().eq(parse_color("rgba(255,0,0,1)"));
        assert lime().eq(parse_color("rgba(0,255,0,1.00)"));
        assert rgb(1u8,2u8,3u8).eq(parse_color("rgb(1,2,03)"));
        assert rgba(15u8,250u8,3u8,0.5).eq(parse_color("rgba(15,250,3,.5)"));
        assert rgba(15u8,250u8,3u8,0.5).eq(parse_color("rgba(15,250,3,0.5)"));
    }

    #[test]
    fn test_parsing_hsl() {
        assert red().eq(parse_color("hsl(0,1,.5)"));
        assert lime().eq(parse_color("hsl(120.0,1.0,.5)"));
        assert blue().eq(parse_color("hsl(240.0,1.0,.5)"));
        assert green().eq(parse_color("hsl(120.0,1.0,.25)"));
        assert white().eq(parse_color("hsl(1.0,1.,1.0)"));
        assert white().eq(parse_color("hsl(129.0,0.3,1.0)"));
        assert black().eq(parse_color("hsl(231.2,0.75,0.0)"));
        assert black().eq(parse_color("hsl(11.2,0.0,0.0)"));
        assert gray().eq(parse_color("hsl(0.0,0.0,0.5)"));
        assert maroon().eq(parse_color("hsl(0.0,1.0,0.25)"));
        assert purple().eq(parse_color("hsl(300.0,1.0,0.25)"));
        assert fuschia().eq(parse_color("hsl(300,1.0,0.5)"));
        assert olive().eq(parse_color("hsl(60.,1.0,0.25)"));
        assert yellow().eq(parse_color("hsl(60.,1.0,0.5)"));
        assert navy().eq(parse_color("hsl(240.0,1.0,.25)"));
        assert teal().eq(parse_color("hsl(180.0,1.0,.25)"));
        assert aqua().eq(parse_color("hsl(180.0,1.0,.5)"));
    }
}

#[doc="Define the colors specified by css"]
mod css_colors {
    // The 16 basic css colors
    fn black() -> Color {
        Color({red : 0u8, green : 0u8, blue : 0u8, alpha : 1.0})
    }
    fn silver() -> Color {
        Color({red : 192u8, green : 192u8, blue : 192u8, alpha : 1.0})
    }
    fn gray() -> Color {
        Color({red : 128u8, green : 128u8, blue : 128u8, alpha : 1.0})
    }
    fn white() -> Color {
        Color({red : 255u8, green : 255u8, blue : 255u8, alpha : 1.0})
    }
    fn maroon() -> Color {
        Color({red : 128u8, green : 0u8, blue : 0u8, alpha : 1.0})
    }
    fn red() -> Color {
        Color({red : 255u8, green : 0u8, blue : 0u8, alpha : 1.0})
    }
    fn purple() -> Color {
        Color({red : 128u8, green : 0u8, blue : 128u8, alpha : 1.0})
    }
    fn fuschia() -> Color {
        Color({red : 255u8, green : 0u8, blue : 255u8, alpha : 1.0})
    }
    fn green() -> Color {
        Color({red : 0u8, green : 128u8, blue : 0u8, alpha : 1.0})
    }
    fn lime() -> Color {
        Color({red : 0u8, green : 255u8, blue : 0u8, alpha : 1.0})
    }
    fn olive() -> Color {
        Color({red : 128u8, green : 128u8, blue : 0u8, alpha : 1.0})
    }
    fn yellow() -> Color {
        Color({red : 255u8, green : 255u8, blue : 0u8, alpha : 1.0})
    }
    fn navy() -> Color {
        Color({red : 0u8, green : 0u8, blue : 128u8, alpha : 1.0})
    }
    fn blue() -> Color {
        Color({red : 0u8, green : 0u8, blue : 255u8, alpha : 1.0})
    }
    fn teal() -> Color {
        Color({red : 0u8, green : 128u8, blue : 128u8, alpha : 1.0})
    }
    fn aqua() -> Color {
        Color({red : 0u8, green : 255u8, blue : 255u8, alpha : 1.0})
    }

    // The other 130 css colors
    // TODO
}
<commit_msg>Correct spelling of "fuchsia"<commit_after>#[doc = "A library for handling colors and parsing css color declarations."]

// TODO: handle #rrggbb color declarations, handle rgb(r%,g%,b%),
// sanitize input / crop it to correct ranges, predefine other 130
// css-defined colors

import float::round;
import libc::types::os::arch::c95::c_double;
import css_colors::*;
import cmp::eq;

enum Color = {red : u8, green : u8, blue : u8, alpha : float};

impl Color of eq for Color {
    fn eq(&&other: Color) -> bool {
        ret self.red == other.red && self.green == other.green && self.blue == other.blue &&
            self.alpha == other.alpha;
    }
}

fn rgba(r : u8, g : u8, b : u8, a : float) -> Color {
    Color({red : r, green : g, blue : b, alpha : a})
}

fn rgb(r : u8, g : u8, b : u8) -> Color {
    ret rgba(r, g, b, 1.0);
}

fn hsla(h : float, s : float, l : float, a : float) -> Color {
    // Algorithm for converting hsl to rbg taken from
    // http://www.w3.org/TR/2003/CR-css3-color-20030514/#hsl-color
    let m2 = if l <= 0.5 { l*(s + 1.0) } else { l + s - l*s };
    let m1 = l*2.0 - m2;
    let h = h / 360.0;

    fn hue_to_rgb(m1 : float, m2 : float, h : float) -> float {
        let h = if h < 0.0 { h + 1.0 } else if h > 1.0 { h - 1.0 } else { h };

        alt h {
          0.0 to 1.0/6.0     { ret m1 + (m2 - m1)*h*6.0; }
          1.0/6.0 to 1.0/2.0 { ret m2; }
          1.0/2.0 to 2.0/3.0 { ret m1 + (m2 - m1)*(4.0 - 6.0*h); }
          2.0/3.0 to 1.0     { ret m1; }
          _                  { fail "unexpected hue value"; }
        }
    }

    let r = round(255.0*hue_to_rgb(m1, m2, h + 1.0/3.0) as c_double);;
    let g = round(255.0*hue_to_rgb(m1, m2, h) as c_double);
    let b = round(255.0*hue_to_rgb(m1, m2, h - 1.0/3.0) as c_double);

    ret rgba(r as u8, g as u8, b as u8, a);
}

fn hsl(h : float, s : float, l : float) -> Color {
    ret hsla(h, s, l, 1.0);
}

impl methods for Color {
    fn print() -> str {
        #fmt["rgba(%u,%u,%u,%f)", self.red as uint, self.green as uint,
             self.blue as uint, self.alpha]
    }
}

mod parsing {
    export parse_color;

    // TODO, fail by ignoring the rule instead of setting the
    // color to black
    fn fail_unrecognized(col : str) -> Color {
        #warn["Unrecognized color %s", col];
        ret  black();
    }

    #[doc="Match an exact color keyword."]
    fn parse_by_name(color : str) -> Color {
        alt color.to_lower() {
          "black"   { black()   }
          "silver"  { silver()  }
          "gray"    { gray()    }
          "grey"    { gray()    }
          "white"   { white()   }
          "maroon"  { maroon()  }
          "red"     { red()     }
          "purple"  { purple()  }
          "fuchsia" { fuchsia() }
          "green"   { green()   }
          "lime"    { lime()    }
          "olive"   { olive()   }
          "yellow"  { yellow()  }
          "navy"    { navy()    }
          "blue"    { blue()    }
          "teal"    { teal()    }
          "aqua"    { aqua()    }
          _         { fail_unrecognized(color) }
        }
    }

    #[doc="Parses a color specification in the form rgb(foo,bar,baz)"]
    fn parse_rgb(color : str) -> Color {
        // Shave off the rgb( and the )
        let only_colors = color.substr(4u, color.len() - 5u);

        // split up r, g, and b
        let cols = only_colors.split_char(',');
        if cols.len() != 3u { ret fail_unrecognized(color); }

        alt (u8::from_str(cols[0]), u8::from_str(cols[1]),
             u8::from_str(cols[2])) {
          (some(r), some(g), some(b)) { rgb(r, g, b) }
          _               { fail_unrecognized(color) }
        }
    }

    #[doc="Parses a color specification in the form rgba(foo,bar,baz,qux)"]
    fn parse_rgba(color : str) -> Color {
        // Shave off the rgba( and the )
        let only_vals = color.substr(5u, color.len() - 6u);

        // split up r, g, and b
        let cols = only_vals.split_char(',');
        if cols.len() != 4u { ret fail_unrecognized(color); }

        alt (u8::from_str(cols[0]), u8::from_str(cols[1]),
             u8::from_str(cols[2]), float::from_str(cols[3])) {
          (some(r), some(g), some(b), some(a)) { rgba(r, g, b, a) }
          _ { fail_unrecognized(color) }
        }
    }

    #[doc="Parses a color specification in the form hsl(foo,bar,baz)"]
    fn parse_hsl(color : str) -> Color {
        // Shave off the hsl( and the )
        let only_vals = color.substr(4u, color.len() - 5u);

        // split up h, s, and l
        let vals = only_vals.split_char(',');
        if vals.len() != 3u { ret fail_unrecognized(color); }

        alt (float::from_str(vals[0]), float::from_str(vals[1]),
             float::from_str(vals[2])) {
          (some(h), some(s), some(l)) { hsl(h, s, l) }
          _               { fail_unrecognized(color) }
        }
    }

    #[doc="Parses a color specification in the form hsla(foo,bar,baz,qux)"]
    fn parse_hsla(color : str) -> Color {
        // Shave off the hsla( and the )
        let only_vals = color.substr(5u, color.len() - 6u);

        let vals = only_vals.split_char(',');
        if vals.len() != 4u { ret fail_unrecognized(color); }

        alt (float::from_str(vals[0]), float::from_str(vals[1]),
             float::from_str(vals[2]), float::from_str(vals[3])) {
          (some(h), some(s), some(l), some(a)) { hsla(h, s, l, a) }
          _ { fail_unrecognized(color) }
        }
    }

    // Currently colors are supported in rgb(a,b,c) form and also by
    // keywords for several common colors.
    // TODO: extend this
    fn parse_color(color : str) -> Color {
        alt color {
          c if c.starts_with("rgb(")  { parse_rgb(c) }
          c if c.starts_with("rgba(") { parse_rgba(c) }
          c if c.starts_with("hsl(")  { parse_hsl(c) }
          c if c.starts_with("hsla(") { parse_hsla(c) }
          c                           { parse_by_name(c) }
        }
    }
}

mod test {
    import css_colors::*;
    import parsing::parse_color;

    #[test]
    fn test_parse_by_name() {
        assert red().eq(parse_color("red"));
        assert lime().eq(parse_color("Lime"));
        assert blue().eq(parse_color("BLUE"));
        assert green().eq(parse_color("GreEN"));
        assert white().eq(parse_color("white"));
        assert black().eq(parse_color("Black"));
        assert gray().eq(parse_color("Gray"));
        assert silver().eq(parse_color("SiLvEr"));
        assert maroon().eq(parse_color("maroon"));
        assert purple().eq(parse_color("PURPLE"));
        assert fuchsia().eq(parse_color("FUCHSIA"));
        assert olive().eq(parse_color("oLiVe"));
        assert yellow().eq(parse_color("yellow"));
        assert navy().eq(parse_color("NAVY"));
        assert teal().eq(parse_color("Teal"));
        assert aqua().eq(parse_color("Aqua"));
    }

    #[test]
    fn test_parsing_rgb() {
        assert red().eq(parse_color("rgb(255,0,0)"));
        assert red().eq(parse_color("rgba(255,0,0,1.0)"));
        assert red().eq(parse_color("rgba(255,0,0,1)"));
        assert lime().eq(parse_color("rgba(0,255,0,1.00)"));
        assert rgb(1u8,2u8,3u8).eq(parse_color("rgb(1,2,03)"));
        assert rgba(15u8,250u8,3u8,0.5).eq(parse_color("rgba(15,250,3,.5)"));
        assert rgba(15u8,250u8,3u8,0.5).eq(parse_color("rgba(15,250,3,0.5)"));
    }

    #[test]
    fn test_parsing_hsl() {
        assert red().eq(parse_color("hsl(0,1,.5)"));
        assert lime().eq(parse_color("hsl(120.0,1.0,.5)"));
        assert blue().eq(parse_color("hsl(240.0,1.0,.5)"));
        assert green().eq(parse_color("hsl(120.0,1.0,.25)"));
        assert white().eq(parse_color("hsl(1.0,1.,1.0)"));
        assert white().eq(parse_color("hsl(129.0,0.3,1.0)"));
        assert black().eq(parse_color("hsl(231.2,0.75,0.0)"));
        assert black().eq(parse_color("hsl(11.2,0.0,0.0)"));
        assert gray().eq(parse_color("hsl(0.0,0.0,0.5)"));
        assert maroon().eq(parse_color("hsl(0.0,1.0,0.25)"));
        assert purple().eq(parse_color("hsl(300.0,1.0,0.25)"));
        assert fuchsia().eq(parse_color("hsl(300,1.0,0.5)"));
        assert olive().eq(parse_color("hsl(60.,1.0,0.25)"));
        assert yellow().eq(parse_color("hsl(60.,1.0,0.5)"));
        assert navy().eq(parse_color("hsl(240.0,1.0,.25)"));
        assert teal().eq(parse_color("hsl(180.0,1.0,.25)"));
        assert aqua().eq(parse_color("hsl(180.0,1.0,.5)"));
    }
}

#[doc="Define the colors specified by css"]
mod css_colors {
    // The 16 basic css colors
    fn black() -> Color {
        Color({red : 0u8, green : 0u8, blue : 0u8, alpha : 1.0})
    }
    fn silver() -> Color {
        Color({red : 192u8, green : 192u8, blue : 192u8, alpha : 1.0})
    }
    fn gray() -> Color {
        Color({red : 128u8, green : 128u8, blue : 128u8, alpha : 1.0})
    }
    fn white() -> Color {
        Color({red : 255u8, green : 255u8, blue : 255u8, alpha : 1.0})
    }
    fn maroon() -> Color {
        Color({red : 128u8, green : 0u8, blue : 0u8, alpha : 1.0})
    }
    fn red() -> Color {
        Color({red : 255u8, green : 0u8, blue : 0u8, alpha : 1.0})
    }
    fn purple() -> Color {
        Color({red : 128u8, green : 0u8, blue : 128u8, alpha : 1.0})
    }
    fn fuchsia() -> Color {
        Color({red : 255u8, green : 0u8, blue : 255u8, alpha : 1.0})
    }
    fn green() -> Color {
        Color({red : 0u8, green : 128u8, blue : 0u8, alpha : 1.0})
    }
    fn lime() -> Color {
        Color({red : 0u8, green : 255u8, blue : 0u8, alpha : 1.0})
    }
    fn olive() -> Color {
        Color({red : 128u8, green : 128u8, blue : 0u8, alpha : 1.0})
    }
    fn yellow() -> Color {
        Color({red : 255u8, green : 255u8, blue : 0u8, alpha : 1.0})
    }
    fn navy() -> Color {
        Color({red : 0u8, green : 0u8, blue : 128u8, alpha : 1.0})
    }
    fn blue() -> Color {
        Color({red : 0u8, green : 0u8, blue : 255u8, alpha : 1.0})
    }
    fn teal() -> Color {
        Color({red : 0u8, green : 128u8, blue : 128u8, alpha : 1.0})
    }
    fn aqua() -> Color {
        Color({red : 0u8, green : 255u8, blue : 255u8, alpha : 1.0})
    }

    // The other 130 css colors
    // TODO
}
<|endoftext|>


<commit_before><commit_msg>Silence warning about 'go' being potentially unused<commit_after><|endoftext|>


<commit_before><commit_msg>Add tests for Ident::new and Ident::parse<commit_after>// Copyright 2018 Syn Developers
//
// 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.

extern crate proc_macro2;
extern crate syn;

use std::str::FromStr;
use proc_macro2::{TokenStream, Span};
use syn::Ident;
use syn::synom::ParseError;

fn parse(s: &str) -> Result<Ident, ParseError> {
    syn::parse2(TokenStream::from_str(s).unwrap())
}

fn new(s: &str) -> Ident {
    Ident::new(s, Span::call_site())
}

#[test]
fn ident_parse() {
    parse("String").unwrap();
}

#[test]
fn ident_parse_keyword() {
    parse("abstract").unwrap_err();
}

#[test]
fn ident_parse_empty() {
    parse("").unwrap_err();
}

#[test]
fn ident_parse_lifetime() {
    parse("'static").unwrap_err();
}

#[test]
fn ident_parse_underscore() {
    parse("_").unwrap_err();
}

#[test]
fn ident_parse_number() {
    parse("255").unwrap_err();
}

#[test]
fn ident_parse_invalid() {
    parse("a#").unwrap_err();
}

#[test]
fn ident_new() {
    new("String");
}

#[test]
fn ident_new_keyword() {
    new("abstract");
}

#[test]
#[should_panic(expected = "ident is not allowed to be empty; use Option<Ident>")]
fn ident_new_empty() {
    new("");
}

#[test]
#[should_panic(expected = "ident is not allowed to be a lifetime; use syn::Lifetime")]
fn ident_new_lifetime() {
    new("'static");
}

#[test]
#[should_panic(expected = "`_` is not a valid ident; use syn::token::Underscore")]
fn ident_new_underscore() {
    new("_");
}

#[test]
#[should_panic(expected = "ident cannot be a number, use syn::Index instead")]
fn ident_new_number() {
    new("255");
}

#[test]
#[should_panic(expected = "\"a#\" is not a valid ident")]
fn ident_new_invalid() {
    new("a#");
}
<|endoftext|>


<commit_before><commit_msg>Add rust code for armstrong-numbers<commit_after>pub fn is_armstrong_number(num: u32) -> bool {
    let mut result = num;
    let mut numbers = Vec::new();

    while result > 0 {
        numbers.push(result % 10);
        result /= 10;
    }

    let width = numbers.len() as u32;

    num == numbers.iter().fold(0, |acc, x| acc + x.pow(width))
}
<|endoftext|>


<commit_before><commit_msg>Add a test for #2759<commit_after>// rustfmt-wrap_comments: true
// rustfmt-max_width: 89

// Code block in doc comments that will exceed max width.
/// ```rust
/// extern crate actix_web;
/// use actix_web::{actix, server, App, HttpResponse};
///
/// fn main() {
///     // Run actix system, this method actually starts all async processes
///     actix::System::run(|| {
///         server::new(|| App::new().resource("/", |r| r.h(|_| HttpResponse::Ok())))
///             .bind("127.0.0.1:0")
///             .expect("Can not bind to 127.0.0.1:0")
///             .start();
/// #           actix::Arbiter::system().do_send(actix::msgs::SystemExit(0));
///     });
/// }
/// ```
fn foo() {}

// Code block in doc comments without the closing '```'.
/// ```rust
/// # extern crate actix_web;
/// use actix_web::{App, HttpResponse, http};
///
/// fn main() {
///     let app = App::new()
///         .resource(
///             "/", |r| r.method(http::Method::GET).f(|r| HttpResponse::Ok()))
///         .finish();
/// }
fn bar() {}

// `#` with indent.
/// ```rust
/// # use std::thread;
/// # extern crate actix_web;
/// use actix_web::{server, App, HttpResponse};
///
/// struct State1;
///
/// struct State2;
///
/// fn main() {
///     # thread::spawn(|| {
///     server::new(|| {
///         vec![
///             App::with_state(State1)
///                 .prefix("/app1")
///                 .resource("/", |r| r.f(|r| HttpResponse::Ok()))
///                 .boxed(),
///             App::with_state(State2)
///                 .prefix("/app2")
///                 .resource("/", |r| r.f(|r| HttpResponse::Ok()))
///                 .boxed(),
///         ]
///     }).bind("127.0.0.1:8080")
///         .unwrap()
///         .run()
///     # });
/// }
/// ```
fn foobar() {}
<|endoftext|>


<commit_before><commit_msg>Add wildcard test for const_if_match<commit_after>// check-pass

#![feature(const_if_match)]

enum E {
    A,
    B,
    C
}

const fn f(e: E) -> usize {
    match e {
        _ => 0
    }
}

fn main() {
    assert_eq!(f(E::A), 0);
}
<|endoftext|>


<commit_before><commit_msg>Add auto trait leakage TAIT test<commit_after>// check-pass

#![feature(type_alias_impl_trait)]
#![allow(dead_code)]

mod m {
    type Foo = impl std::fmt::Debug;

    pub fn foo() -> Foo {
        22_u32
    }
}

fn is_send<T: Send>(_: T) {}

fn main() {
    is_send(m::foo());
}
<|endoftext|>


<commit_before><commit_msg>Add a method marking all tiles as having changed contents<commit_after><|endoftext|>


<commit_before><commit_msg>playground/operationsystems/rust-os/autobuild/src/lib.rs<commit_after><|endoftext|>


<commit_before><commit_msg>add regression test for #73730<commit_after>// check-pass
#![feature(const_generics)]
#![allow(incomplete_features)]

trait Foo<'a, A>: Iterator<Item=A> {
    fn bar<const N: usize>(&mut self) -> *const [A; N];
}

impl<'a, A, I: ?Sized> Foo<'a, A> for I where I: Iterator<Item=A>  {
    fn bar<const N: usize>(&mut self) -> *const [A; N] {
        std::ptr::null()
    }
}

fn main() {
    (0_u8 .. 10).bar::<10_usize>();
}
<|endoftext|>


<commit_before><commit_msg>Guessing game now reads from stdin<commit_after><|endoftext|>


<commit_before><commit_msg>Do not print stats when listing files with matches<commit_after><|endoftext|>


<commit_before>extern crate libc;

use std::collections::BTreeMap;
use std::collections::HashMap;
use std::env;

use ArgMatches;
use Arg;
use args::OptArg;
use args::FlagArg;
use args::PosArg;

pub struct App {
	pub name: &'static str,
	pub author: Option<&'static str>,
	pub version: Option<&'static str>,
	pub about: Option<&'static str>,
	flags: HashMap<&'static str, FlagArg>,
	opts: HashMap<&'static str, OptArg>,
	positionals_idx: BTreeMap<u8, PosArg>,
	positionals_name: HashMap<&'static str, PosArg>,
	needs_long_help: bool,
	needs_long_version: bool,
	needs_short_help: bool,
	needs_short_version: bool,
}

impl App {
	pub fn new(n: &'static str) -> App {
		App {
			name: n,
			author: None,
			about: None,
			version: None,
			flags: HashMap::new(),
			opts: HashMap::new(),
			positionals_idx: BTreeMap::new(),
			positionals_name: HashMap::new(),
			needs_long_version: true,
			needs_long_help: true,
			needs_short_help: true,
			needs_short_version: true,
		}
	}

	pub fn author(&mut self, a: &'static str) -> &mut App {
		self.author = Some(a);
		self
	}

	pub fn about(&mut self, a: &'static str) -> &mut App {
		self.about = Some(a);
		self
	}

	pub fn version(&mut self, v: &'static str)-> &mut App  {
		self.version = Some(v);
		self
	}

	pub fn arg(&mut self, a: &Arg) -> &mut App {
		if let Some(i) = a.index {
			self.positionals_name.insert(a.name, PosArg {
				name: a.name,
				index: i,
				required: a.required,
				help: a.help,
				value: None
			});
			self.positionals_idx.insert(i, PosArg {
				name: a.name,
				index: i,
				required: a.required,
				help: a.help,
				value: None
			});
		} else if a.takes_value {
			self.opts.insert(a.name, OptArg {
				name: a.name,
				short: a.short,
				long: a.long,
				help: a.help,
				required: a.required,
				value: None
			});
		} else {
			if let Some(ref l) = a.long {
				if *l == "help" {
					self.needs_long_help = false;
				} else if *l == "version" {
					self.needs_long_version = false;
				}
			}
			if let Some(ref s) = a.short {
				if *s == 'h' {
					self.needs_short_help = false;
				} else if *s == 'v' {
					self.needs_short_version = false;
				}
			}
			self.flags.insert(a.name, FlagArg{
				name: a.name,
				short: a.short,
				long: a.long,
				help: a.help,
				multiple: a.multiple,
				occurrences: 1
			});
		}
		self
	}

	fn exit(&self) {
		unsafe { libc::exit(0); }
	}

	fn report_error(&self, msg: &String, help: bool, quit: bool) {
		println!("{}", msg);
		if help { self.print_help(); }
		if quit {self.exit(); }
	}

	fn print_help(&self) {
		self.print_version(false);
		let mut flags = false;
		let mut pos = false;
		let mut opts = false;

		if let Some(ref author) = self.author {
			println!("{}", author);
		}
		if let Some(ref about) = self.about {
			println!("{}", about);
		}
		print!("USAGE {} {} {} {}", self.name,
			if ! self.flags.is_empty() {flags = true; "[FLAGS]"} else {""},
			if ! self.opts.is_empty() {opts = true; "[OPTIONS]"} else {""},
			if ! self.positionals_name.is_empty() {pos = true; "[POSITIONAL]"} else {""});
		if flags || opts || pos {
			println!("");
			println!("Where...");
		}
		if flags {
			println!("");
			println!("FLAGS:");
			for (_, v) in self.flags.iter() {
				println!("{}{}\t\t{}",
						if let Some(ref s) = v.short{format!("-{}",s)}else{format!("   ")},
						if let Some(ref l) = v.long {format!(",--{}",l)}else {format!("   ")},
						if let Some(ref h) = v.help {*h} else {"   "} );
			}
		}
		if opts {
			println!("");
			println!("OPTIONS:");
			for (_, v) in self.opts.iter() {
				println!("{}{}\t\t{}",
						if let Some(ref s) = v.short{format!("-{}",s)}else{format!("   ")},
						if let Some(ref l) = v.long {format!(",--{}",l)}else {format!("   ")},
						if let Some(ref h) = v.help {*h} else {"   "} );
			}
		}
		if pos {
			println!("");
			println!("POSITIONAL ARGUMENTS:");
			for (_, v) in self.positionals_idx.iter() {
				println!("{}\t\t\t{}", v.name,
						if let Some(ref h) = v.help {*h} else {"   "} );
			}
		}

		self.exit();
	}

	fn print_version(&self, quit: bool) {
		println!("{} {}", self.name, if let Some(ref v) = self.version {*v} else {""} );
		if quit { self.exit(); }
	}

	fn parse_single_short_flag(&mut self, matches: &mut ArgMatches, arg: char) -> bool {
		for (k, v) in self.flags.iter() {
			if let Some(s) = v.short {
				if s != arg { continue; }

				if !matches.flags.contains_key(k) {
					matches.flags.insert(k, v.clone());
				} else if matches.flags.get(k).unwrap().multiple {
					matches.flags.get_mut(k).unwrap().occurrences += 1
				}

				return true;
			}
		}
		false
	}

	fn parse_long_arg(&mut self, matches: &mut ArgMatches ,full_arg: &String) -> Option<&'static str> {
		let mut arg = full_arg.as_slice().trim_left_matches(|c| c == '-');
		let mut found = false;

		if arg == "help" && self.needs_long_help {
			self.print_help();
		} else if arg == "version" && self.needs_long_version {
			self.print_version(true);
		}

		let mut arg_val: Option<String> = None;

		if arg.contains("=") {
			let arg_vec: Vec<&str> = arg.split_str("=").collect();
			arg = arg_vec[0];
			arg_val = Some(arg_vec[1].to_string());
		}

		for (k, v) in self.opts.iter() {
			if let Some(ref l) = v.long {
				if *l == arg {
					matches.opts.insert(k, OptArg{
						name: v.name,
					    short: v.short,
					    long: v.long,
					    help: v.help,
					    required: v.required,
					    value: arg_val.clone()
					});
					match arg_val {
						None => { return Some(v.name); },
						_ => { return None; }
					}
				}
			}
		}

		for (k, v) in self.flags.iter() {
			if let Some(ref l) = v.long {
				if *l != arg { continue; }
				found = true;
				let mut multi = false;
				if let Some(ref mut f) = matches.flags.get_mut(k) {
					f.occurrences = if f.multiple { f.occurrences + 1 } else { 1 };
					multi = true;
				}
				// Cannot borrow mutable twice at same time
				// so the 'if let' must finish it's scope first
				// before calling .insert()
				if ! multi {
					matches.flags.insert(k, v.clone());
				}
				break;
			}
		}

		if ! found {
			self.report_error(
				&format!("Argument --{} isn't valid", arg),
				false, true);
		}
		None
	}

	fn check_for_help_and_version(&self, arg: char) {
		if arg == 'h' && self.needs_short_help {
			self.print_help();
		} else if arg == 'v' && self.needs_short_version {
			self.print_version(true);
		}
	}

	fn parse_short_arg(&mut self, matches: &mut ArgMatches ,full_arg: &String) -> Option<&'static str> {
		let arg = full_arg.as_slice().trim_left_matches(|c| c == '-');
		if arg.len() > 1 {
			// Multiple flags using short i.e. -bgHlS
			for c in arg.chars() {
				self.check_for_help_and_version(c);
				if ! self.parse_single_short_flag(matches, c) {
					self.report_error(
						&format!("Argument -{} isn't valid",c),
						false, true);
				}
			}
		} else {
			// Short flag or opt
			let arg_c = arg.char_at(0);
			self.check_for_help_and_version(arg_c);

			if ! self.parse_single_short_flag(matches, arg_c) {
				for (k, v) in self.opts.iter() {
					if let Some(s) = v.short {
						if s == arg_c {
							return Some(k)
						}
					}
				}

				self.report_error(
					&format!("Argument -{} isn't valid",arg_c),
					false, true);
			}

		}
		None
	}

	pub fn get_matches(&mut self) -> ArgMatches {
		let mut matches = ArgMatches::new(self);

		// let mut needs_val = false;
		let mut needs_val_of: Option<&'static str> = None;
		let mut pos_counter = 1;
		for arg in env::args().collect::<Vec<String>>().tail() {
			let arg_slice = arg.as_slice();
			let mut skip = false;
			if let Some(ref nvo) = needs_val_of {
				if let Some(ref opt) = self.opts.get(nvo) {
					matches.opts.insert(nvo, OptArg{
						name: opt.name,
					    short: opt.short,
					    long: opt.long,
					    help: opt.help,
					    required: opt.required,
					    value: Some(arg.clone())
					});
					skip = true;
				}
			}
			if skip {
				needs_val_of = None;
				continue;
			}
			if arg_slice.starts_with("--") {
				// Single flag, or option long version
				needs_val_of = self.parse_long_arg(&mut matches, &arg);

			} else if arg_slice.starts_with("-") {
				needs_val_of = self.parse_short_arg(&mut matches, &arg);
			} else {
				// Positional

				if self.positionals_idx.is_empty() || self.positionals_name.is_empty() {
					self.report_error(
						&format!("Found positional argument {}, but {} doesn't accept any", arg, self.name),
						false, true);
				}
				if let Some(ref p) = self.positionals_idx.get(&pos_counter) {
					matches.positionals.insert(p.name, PosArg{
						name: p.name,
						help: p.help,
						required: p.required,
						value: Some(arg.clone()),
						index: pos_counter
					});
					pos_counter += 1;
				}
			}
		}

		match needs_val_of {
			Some(ref a) => {
				self.report_error(
					&format!("Argument {} requires a value but none was supplied", a),
					false, true);
			}
			_ => {}
		}
		matches
	}
}<commit_msg>v0.0.5.3<commit_after>extern crate libc;

use std::collections::BTreeMap;
use std::collections::HashMap;
use std::env;

use ArgMatches;
use Arg;
use args::OptArg;
use args::FlagArg;
use args::PosArg;

pub struct App {
	pub name: &'static str,
	pub author: Option<&'static str>,
	pub version: Option<&'static str>,
	pub about: Option<&'static str>,
	flags: HashMap<&'static str, FlagArg>,
	opts: HashMap<&'static str, OptArg>,
	positionals_idx: BTreeMap<u8, PosArg>,
	positionals_name: HashMap<&'static str, PosArg>,
	needs_long_help: bool,
	needs_long_version: bool,
	needs_short_help: bool,
	needs_short_version: bool,
}

impl App {
	pub fn new(n: &'static str) -> App {
		App {
			name: n,
			author: None,
			about: None,
			version: None,
			flags: HashMap::new(),
			opts: HashMap::new(),
			positionals_idx: BTreeMap::new(),
			positionals_name: HashMap::new(),
			needs_long_version: true,
			needs_long_help: true,
			needs_short_help: true,
			needs_short_version: true,
		}
	}

	pub fn author(&mut self, a: &'static str) -> &mut App {
		self.author = Some(a);
		self
	}

	pub fn about(&mut self, a: &'static str) -> &mut App {
		self.about = Some(a);
		self
	}

	pub fn version(&mut self, v: &'static str)-> &mut App  {
		self.version = Some(v);
		self
	}

	pub fn arg(&mut self, a: &Arg) -> &mut App {
		if let Some(i) = a.index {
			self.positionals_name.insert(a.name, PosArg {
				name: a.name,
				index: i,
				required: a.required,
				help: a.help,
				value: None
			});
			self.positionals_idx.insert(i, PosArg {
				name: a.name,
				index: i,
				required: a.required,
				help: a.help,
				value: None
			});
		} else if a.takes_value {
			self.opts.insert(a.name, OptArg {
				name: a.name,
				short: a.short,
				long: a.long,
				help: a.help,
				required: a.required,
				value: None
			});
		} else {
			if let Some(ref l) = a.long {
				if *l == "help" {
					self.needs_long_help = false;
				} else if *l == "version" {
					self.needs_long_version = false;
				}
			}
			if let Some(ref s) = a.short {
				if *s == 'h' {
					self.needs_short_help = false;
				} else if *s == 'v' {
					self.needs_short_version = false;
				}
			}
			self.flags.insert(a.name, FlagArg{
				name: a.name,
				short: a.short,
				long: a.long,
				help: a.help,
				multiple: a.multiple,
				occurrences: 1
			});
		}
		self
	}

	fn exit(&self) {
		unsafe { libc::exit(0); }
	}

	fn report_error(&self, msg: &String, help: bool, quit: bool) {
		println!("{}", msg);
		if help { self.print_help(); }
		if quit {self.exit(); }
	}

	fn print_help(&self) {
		self.print_version(false);
		let mut flags = false;
		let mut pos = false;
		let mut opts = false;

		if let Some(ref author) = self.author {
			println!("{}", author);
		}
		if let Some(ref about) = self.about {
			println!("{}", about);
		}
		print!("USAGE: {} {} {} {}", self.name,
			if ! self.flags.is_empty() {flags = true; "[FLAGS]"} else {""},
			if ! self.opts.is_empty() {opts = true; "[OPTIONS]"} else {""},
			if ! self.positionals_name.is_empty() {pos = true; "[POSITIONAL]"} else {""});
		if flags || opts || pos {
			println!("");
			println!("Where...");
		}
		if flags {
			println!("");
			println!("FLAGS:");
			for (_, v) in self.flags.iter() {
				println!("{}{}\t\t{}",
						if let Some(ref s) = v.short{format!("-{}",s)}else{format!("   ")},
						if let Some(ref l) = v.long {format!(",--{}",l)}else {format!("   ")},
						if let Some(ref h) = v.help {*h} else {"   "} );
			}
		}
		if opts {
			println!("");
			println!("OPTIONS:");
			for (_, v) in self.opts.iter() {
				println!("{}{}\t\t{}",
						if let Some(ref s) = v.short{format!("-{}",s)}else{format!("   ")},
						if let Some(ref l) = v.long {format!(",--{}",l)}else {format!("   ")},
						if let Some(ref h) = v.help {*h} else {"   "} );
			}
		}
		if pos {
			println!("");
			println!("POSITIONAL ARGUMENTS:");
			for (_, v) in self.positionals_idx.iter() {
				println!("{}\t\t\t{}", v.name,
						if let Some(ref h) = v.help {*h} else {"   "} );
			}
		}

		self.exit();
	}

	fn print_version(&self, quit: bool) {
		println!("{} {}", self.name, if let Some(ref v) = self.version {*v} else {""} );
		if quit { self.exit(); }
	}

	fn parse_single_short_flag(&mut self, matches: &mut ArgMatches, arg: char) -> bool {
		for (k, v) in self.flags.iter() {
			if let Some(s) = v.short {
				if s != arg { continue; }

				if !matches.flags.contains_key(k) {
					matches.flags.insert(k, v.clone());
				} else if matches.flags.get(k).unwrap().multiple {
					matches.flags.get_mut(k).unwrap().occurrences += 1
				}

				return true;
			}
		}
		false
	}

	fn parse_long_arg(&mut self, matches: &mut ArgMatches ,full_arg: &String) -> Option<&'static str> {
		let mut arg = full_arg.as_slice().trim_left_matches(|c| c == '-');
		let mut found = false;

		if arg == "help" && self.needs_long_help {
			self.print_help();
		} else if arg == "version" && self.needs_long_version {
			self.print_version(true);
		}

		let mut arg_val: Option<String> = None;

		if arg.contains("=") {
			let arg_vec: Vec<&str> = arg.split_str("=").collect();
			arg = arg_vec[0];
			arg_val = Some(arg_vec[1].to_string());
		}

		for (k, v) in self.opts.iter() {
			if let Some(ref l) = v.long {
				if *l == arg {
					matches.opts.insert(k, OptArg{
						name: v.name,
					    short: v.short,
					    long: v.long,
					    help: v.help,
					    required: v.required,
					    value: arg_val.clone()
					});
					match arg_val {
						None => { return Some(v.name); },
						_ => { return None; }
					}
				}
			}
		}

		for (k, v) in self.flags.iter() {
			if let Some(ref l) = v.long {
				if *l != arg { continue; }
				found = true;
				let mut multi = false;
				if let Some(ref mut f) = matches.flags.get_mut(k) {
					f.occurrences = if f.multiple { f.occurrences + 1 } else { 1 };
					multi = true;
				}
				// Cannot borrow mutable twice at same time
				// so the 'if let' must finish it's scope first
				// before calling .insert()
				if ! multi {
					matches.flags.insert(k, v.clone());
				}
				break;
			}
		}

		if ! found {
			self.report_error(
				&format!("Argument --{} isn't valid", arg),
				false, true);
		}
		None
	}

	fn check_for_help_and_version(&self, arg: char) {
		if arg == 'h' && self.needs_short_help {
			self.print_help();
		} else if arg == 'v' && self.needs_short_version {
			self.print_version(true);
		}
	}

	fn parse_short_arg(&mut self, matches: &mut ArgMatches ,full_arg: &String) -> Option<&'static str> {
		let arg = full_arg.as_slice().trim_left_matches(|c| c == '-');
		if arg.len() > 1 {
			// Multiple flags using short i.e. -bgHlS
			for c in arg.chars() {
				self.check_for_help_and_version(c);
				if ! self.parse_single_short_flag(matches, c) {
					self.report_error(
						&format!("Argument -{} isn't valid",c),
						false, true);
				}
			}
		} else {
			// Short flag or opt
			let arg_c = arg.char_at(0);
			self.check_for_help_and_version(arg_c);

			if ! self.parse_single_short_flag(matches, arg_c) {
				for (k, v) in self.opts.iter() {
					if let Some(s) = v.short {
						if s == arg_c {
							return Some(k)
						}
					}
				}

				self.report_error(
					&format!("Argument -{} isn't valid",arg_c),
					false, true);
			}

		}
		None
	}

	pub fn get_matches(&mut self) -> ArgMatches {
		let mut matches = ArgMatches::new(self);

		// let mut needs_val = false;
		let mut needs_val_of: Option<&'static str> = None;
		let mut pos_counter = 1;
		for arg in env::args().collect::<Vec<String>>().tail() {
			let arg_slice = arg.as_slice();
			let mut skip = false;
			if let Some(ref nvo) = needs_val_of {
				if let Some(ref opt) = self.opts.get(nvo) {
					matches.opts.insert(nvo, OptArg{
						name: opt.name,
					    short: opt.short,
					    long: opt.long,
					    help: opt.help,
					    required: opt.required,
					    value: Some(arg.clone())
					});
					skip = true;
				}
			}
			if skip {
				needs_val_of = None;
				continue;
			}
			if arg_slice.starts_with("--") {
				// Single flag, or option long version
				needs_val_of = self.parse_long_arg(&mut matches, &arg);

			} else if arg_slice.starts_with("-") {
				needs_val_of = self.parse_short_arg(&mut matches, &arg);
			} else {
				// Positional

				if self.positionals_idx.is_empty() || self.positionals_name.is_empty() {
					self.report_error(
						&format!("Found positional argument {}, but {} doesn't accept any", arg, self.name),
						false, true);
				}
				if let Some(ref p) = self.positionals_idx.get(&pos_counter) {
					matches.positionals.insert(p.name, PosArg{
						name: p.name,
						help: p.help,
						required: p.required,
						value: Some(arg.clone()),
						index: pos_counter
					});
					pos_counter += 1;
				}
			}
		}

		match needs_val_of {
			Some(ref a) => {
				self.report_error(
					&format!("Argument {} requires a value but none was supplied", a),
					false, true);
			}
			_ => {}
		}
		matches
	}
}<|endoftext|>


<commit_before><commit_msg>Per core CPU stuff<commit_after>use vmx;
use collections::vec::Vec;
use core::sync::atomic::{ATOMIC_U16_INIT, AtomicU16, Ordering};

static CPU_COUNT: AtomicU16 = ATOMIC_U16_INIT;
static CPU_ASSIGNMENT: AtomicU16 = ATOMIC_U16_INIT;

pub fn init(count: u16) {
    CPU_COUNT.store(count, Ordering::Relaxed);
}

pub fn bring_core_online() {
    let cpu_num = CPU_ASSIGNMENT.fetch_add(1, Ordering::Relaxed);
    set_number(cpu_num);
}

fn set_number(num: u16) {
    vmx::write_gs(num);
}

pub fn get_number() -> u16 {
    vmx::read_gs()
}

#[derive(Default)]
pub struct PerCoreVariable<T> {
    vars: Vec<T>,
}

impl<T> PerCoreVariable<T> {
    pub fn get(&self) -> &T {
        &self.vars[get_number() as usize]
    }
}
<|endoftext|>


<commit_before><commit_msg>depot_tools work<commit_after><|endoftext|>


<commit_before><commit_msg>Wrong transaction sign order<commit_after><|endoftext|>


<commit_before>//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event
//! notification, and other useful utilities for building high performance IO
//! apps.
//!
//! # Goals
//!
//! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...)
//! * Zero allocations
//! * A scalable readiness-based API, similar to epoll on Linux
//! * Design to allow for stack allocated buffers when possible (avoid double buffering).
//! * Provide utilities such as a timers, a notification channel, buffer abstractions, and a slab.
//!
//! # Usage
//!
//! Using mio starts by creating an [EventLoop](struct.EventLoop.html), which
//! handles receiving events from the OS and dispatching them to a supplied
//! [Handler](handler/trait.Handler.html).
//!
//! # Example
//!
//! ```
//! use mio::{event, EventLoop, IoAcceptor, Handler, Token};
//! use mio::net::{SockAddr};
//! use mio::net::tcp::{TcpSocket, TcpAcceptor};
//!
//! // Setup some tokens to allow us to identify which event is
//! // for which socket.
//! const SERVER: Token = Token(0);
//! const CLIENT: Token = Token(1);
//!
//! let addr = SockAddr::parse("127.0.0.1:13265")
//!     .expect("could not parse InetAddr");
//!
//! // Setup the server socket
//! let server = TcpSocket::v4().unwrap()
//!     .bind(&addr).unwrap()
//!     .listen(256u).unwrap();
//!
//! // Create an event loop
//! let mut event_loop = EventLoop::<(), ()>::new().unwrap();
//!
//! // Start listening for incoming connections
//! event_loop.register(&server, SERVER).unwrap();
//!
//! // Setup the client socket
//! let sock = TcpSocket::v4().unwrap();
//!
//! // Connect to the server
//! sock.connect(&addr).unwrap();
//!
//! // Register the socket
//! event_loop.register(&sock, CLIENT).unwrap();
//!
//! // Define a handler to process the events
//! struct MyHandler(TcpAcceptor);
//!
//! impl Handler<(), ()> for MyHandler {
//!     fn readable(&mut self, event_loop: &mut EventLoop<(), ()>, token: Token, _: event::ReadHint) {
//!         match token {
//!             SERVER => {
//!                 let MyHandler(ref mut server) = *self;
//!                 // Accept and drop the socket immediately, this will close
//!                 // the socket and notify the client of the EOF.
//!                 let _ = server.accept();
//!             }
//!             CLIENT => {
//!                 // The server just shuts down the socket, let's just
//!                 // shutdown the event loop
//!                 event_loop.shutdown();
//!             }
//!             _ => panic!("unexpected token"),
//!         }
//!     }
//! }
//!
//! // Start handling events
//! let _ = event_loop.run(MyHandler(server));
//!
//! ```

#![crate_name = "mio"]

// mio is still in rapid development
#![unstable]

// Enable extra features
#![feature(globs)]
#![feature(phase)]
#![feature(unsafe_destructor)]

// Disable dead code warnings
#![allow(dead_code)]

extern crate alloc;
extern crate nix;
extern crate time;

#[phase(plugin, link)]
extern crate log;

pub use buf::{
    Buf,
    MutBuf,
};
pub use error::{
    MioResult,
    MioError,
    MioErrorKind
};
pub use handler::{
    Handler,
};
pub use io::{
    pipe,
    NonBlock,
    IoReader,
    IoWriter,
    IoAcceptor,
    PipeReader,
    PipeWriter,
};
pub use poll::{
    Poll
};
pub use event_loop::{
    EventLoop,
    EventLoopConfig,
    EventLoopResult,
    EventLoopSender,
    EventLoopError
};
pub use timer::{
    Timeout,
};
pub use os::token::{
    Token,
};

pub use os::event;

pub mod buf;
pub mod net;
pub mod util;

mod error;
mod event_loop;
mod handler;
mod io;
mod notify;
mod os;
mod poll;
mod timer;
<commit_msg>Re-export IoHandle.<commit_after>//! A fast, low-level IO library for Rust focusing on non-blocking APIs, event
//! notification, and other useful utilities for building high performance IO
//! apps.
//!
//! # Goals
//!
//! * Fast - minimal overhead over the equivalent OS facilities (epoll, kqueue, etc...)
//! * Zero allocations
//! * A scalable readiness-based API, similar to epoll on Linux
//! * Design to allow for stack allocated buffers when possible (avoid double buffering).
//! * Provide utilities such as a timers, a notification channel, buffer abstractions, and a slab.
//!
//! # Usage
//!
//! Using mio starts by creating an [EventLoop](struct.EventLoop.html), which
//! handles receiving events from the OS and dispatching them to a supplied
//! [Handler](handler/trait.Handler.html).
//!
//! # Example
//!
//! ```
//! use mio::{event, EventLoop, IoAcceptor, Handler, Token};
//! use mio::net::{SockAddr};
//! use mio::net::tcp::{TcpSocket, TcpAcceptor};
//!
//! // Setup some tokens to allow us to identify which event is
//! // for which socket.
//! const SERVER: Token = Token(0);
//! const CLIENT: Token = Token(1);
//!
//! let addr = SockAddr::parse("127.0.0.1:13265")
//!     .expect("could not parse InetAddr");
//!
//! // Setup the server socket
//! let server = TcpSocket::v4().unwrap()
//!     .bind(&addr).unwrap()
//!     .listen(256u).unwrap();
//!
//! // Create an event loop
//! let mut event_loop = EventLoop::<(), ()>::new().unwrap();
//!
//! // Start listening for incoming connections
//! event_loop.register(&server, SERVER).unwrap();
//!
//! // Setup the client socket
//! let sock = TcpSocket::v4().unwrap();
//!
//! // Connect to the server
//! sock.connect(&addr).unwrap();
//!
//! // Register the socket
//! event_loop.register(&sock, CLIENT).unwrap();
//!
//! // Define a handler to process the events
//! struct MyHandler(TcpAcceptor);
//!
//! impl Handler<(), ()> for MyHandler {
//!     fn readable(&mut self, event_loop: &mut EventLoop<(), ()>, token: Token, _: event::ReadHint) {
//!         match token {
//!             SERVER => {
//!                 let MyHandler(ref mut server) = *self;
//!                 // Accept and drop the socket immediately, this will close
//!                 // the socket and notify the client of the EOF.
//!                 let _ = server.accept();
//!             }
//!             CLIENT => {
//!                 // The server just shuts down the socket, let's just
//!                 // shutdown the event loop
//!                 event_loop.shutdown();
//!             }
//!             _ => panic!("unexpected token"),
//!         }
//!     }
//! }
//!
//! // Start handling events
//! let _ = event_loop.run(MyHandler(server));
//!
//! ```

#![crate_name = "mio"]

// mio is still in rapid development
#![unstable]

// Enable extra features
#![feature(globs)]
#![feature(phase)]
#![feature(unsafe_destructor)]

// Disable dead code warnings
#![allow(dead_code)]

extern crate alloc;
extern crate nix;
extern crate time;

#[phase(plugin, link)]
extern crate log;

pub use buf::{
    Buf,
    MutBuf,
};
pub use error::{
    MioResult,
    MioError,
    MioErrorKind
};
pub use handler::{
    Handler,
};
pub use io::{
    pipe,
    NonBlock,
    IoReader,
    IoWriter,
    IoAcceptor,
    IoHandle,
    PipeReader,
    PipeWriter,
};
pub use poll::{
    Poll
};
pub use event_loop::{
    EventLoop,
    EventLoopConfig,
    EventLoopResult,
    EventLoopSender,
    EventLoopError
};
pub use timer::{
    Timeout,
};
pub use os::token::{
    Token,
};

pub use os::event;

pub mod buf;
pub mod net;
pub mod util;

mod error;
mod event_loop;
mod handler;
mod io;
mod notify;
mod os;
mod poll;
mod timer;
<|endoftext|>


<commit_before><commit_msg>Add doc examples for `Url::host`.<commit_after><|endoftext|>


<commit_before><commit_msg>Add a TODO to optimize cookie storage.<commit_after><|endoftext|>


<commit_before><commit_msg>start new<commit_after>/*fn replace_words<'a>(words: &'a Vec<&'a str>, sentence: &'a str) -> Vec<String> {
    let temp = sentence.split(' ').collect();
    let mut result: Vec<String>;
    for w in temp {}
}*/

fn match_head_of_str(a: &str, b: &str) -> bool {
    let len1 = a.chars().count();
    let len2 = b.chars().count();

    if len1 >= len2 {
        return a.starts_with(b);
    } else {
        return b.starts_with(a);
    }
}

fn main() {
    let words = vec!["cat", "bat", "rat"];
    let sentence = "the cattle was rattled by the battery";
    //println!("{:?}", replace_words(&words, &sentence));
    println!("{:?}", match_head_of_str("aa", "aaab"));
}
<|endoftext|>


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

// ignore-test
// error-pattern: thread '<main>' has overflowed its stack

struct R {
    b: isize,
}

impl Drop for R {
    fn drop(&mut self) {
        let _y = R { b: self.b };
    }
}

fn main() {
    let _x = R { b: 0 };
}
<commit_msg>Auto merge of #26248 - steveklabnik:remove_2061, r=alexcrichton<commit_after><|endoftext|>


<commit_before><commit_msg>Rename phase clock -> frequency clock etc<commit_after><|endoftext|>


<commit_before><commit_msg>Use new std::io module in example application<commit_after><|endoftext|>


<commit_before><commit_msg>Remove `HeadSymbol` and remain ambig `>` separated.<commit_after><|endoftext|>


<commit_before><commit_msg>(feat) Added alloy to ingot signatures.<commit_after><|endoftext|>


<commit_before>// This file is part of the uutils coreutils package.
//
// (c) Derek Chiang <derekchiang93@gmail.com>
// (c) Christopher Brown <ccbrown112@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

#[macro_use]
extern crate uucore;

use clap::{App, Arg};
use std::io::{self, Write};
use std::iter::Peekable;
use std::str::Chars;

static VERSION: &str = env!("CARGO_PKG_VERSION");
const NAME: &str = "echo";
const SYNTAX: &str = "[OPTIONS]... [STRING]...";
const SUMMARY: &str = "display a line of text";
const HELP: &str = r#"
 Echo the STRING(s) to standard output.
 If -e is in effect, the following sequences are recognized:

 \\\\      backslash
 \\a      alert (BEL)
 \\b      backspace
 \\c      produce no further output
 \\e      escape
 \\f      form feed
 \\n      new line
 \\r      carriage return
 \\t      horizontal tab
 \\v      vertical tab
 \\0NNN   byte with octal value NNN (1 to 3 digits)
 \\xHH    byte with hexadecimal value HH (1 to 2 digits)
"#;

mod options {
    pub const STRING: &str = "string";
    pub const NEWLINE: &str = "n";
    pub const ENABLE_ESCAPE: &str = "e";
    pub const DISABLE_ESCAPE: &str = "E";
}

fn parse_code(
    input: &mut Peekable<Chars>,
    base: u32,
    max_digits: u32,
    bits_per_digit: u32,
) -> Option<char> {
    let mut ret = 0x8000_0000;
    for _ in 0..max_digits {
        match input.peek().and_then(|c| c.to_digit(base)) {
            Some(n) => ret = (ret << bits_per_digit) | n,
            None => break,
        }
        input.next();
    }
    std::char::from_u32(ret)
}

fn print_escaped(input: &str, mut output: impl Write) -> io::Result<bool> {
    let mut should_stop = false;

    let mut buffer = ['\\'; 2];

    let mut iter = input.chars().peekable();
    while let Some(mut c) = iter.next() {
        let mut start = 1;

        if c == '\\' {
            if let Some(next) = iter.next() {
                c = match next {
                    '\\' => '\\',
                    'a' => '\x07',
                    'b' => '\x08',
                    'c' => {
                        should_stop = true;
                        break;
                    }
                    'e' => '\x1b',
                    'f' => '\x0c',
                    'n' => '\n',
                    'r' => '\r',
                    't' => '\t',
                    'v' => '\x0b',
                    'x' => parse_code(&mut iter, 16, 2, 4).unwrap_or_else(|| {
                        start = 0;
                        next
                    }),
                    '0' => parse_code(&mut iter, 8, 3, 3).unwrap_or_else(|| {
                        start = 0;
                        next
                    }),
                    _ => {
                        start = 0;
                        next
                    }
                };
            }
        }

        buffer[1] = c;

        // because printing char slices is apparently not available in the standard library
        for ch in &buffer[start..] {
            write!(output, "{}", ch)?;
        }
    }

    Ok(should_stop)
}

pub fn uumain(args: impl uucore::Args) -> i32 {
    let args = args.collect_str();

    let matches = App::new(executable!())
        .name(NAME)
        // TrailingVarArg specifies the final positional argument is a VarArg
        // and it doesn't attempts the parse any further args.
        // Final argument must have multiple(true) or the usage string equivalent.
        .setting(clap::AppSettings::TrailingVarArg)
        .setting(clap::AppSettings::AllowLeadingHyphen)
        .version(VERSION)
        .usage(SYNTAX)
        .about(SUMMARY)
        .help(HELP)
        .arg(Arg::with_name(options::STRING).hidden(true).multiple(true))
        .arg(
            Arg::with_name(options::NEWLINE)
                .short("n")
                .help("do not output the trailing newline"),
        )
        .arg(
            Arg::with_name(options::ENABLE_ESCAPE)
                .short("e")
                .help("enable interpretation of backslash escapes"),
        )
        .arg(
            Arg::with_name(options::DISABLE_ESCAPE)
                .short("E")
                .help("disable interpretation of backslash escapes (default)"),
        )
        .get_matches_from(args);

    let no_newline = matches.is_present("n");
    let escaped = matches.is_present("e");
    let values: Vec<String> = match matches.values_of(options::STRING) {
        Some(v) => v.map(|v| v.to_string()).collect(),
        None => vec!["".to_string()],
    };

    match execute(no_newline, escaped, values) {
        Ok(_) => 0,
        Err(f) => {
            show_error!("{}", f);
            1
        }
    }
}

fn execute(no_newline: bool, escaped: bool, free: Vec<String>) -> io::Result<()> {
    let stdout = io::stdout();
    let mut output = stdout.lock();

    for (i, input) in free.iter().enumerate() {
        if i > 0 {
            write!(output, " ")?;
        }
        if escaped {
            let should_stop = print_escaped(&input, &mut output)?;
            if should_stop {
                break;
            }
        } else {
            write!(output, "{}", input)?;
        }
    }

    if !no_newline {
        writeln!(output)?;
    }

    Ok(())
}
<commit_msg>echo: Refactored help message. (#1886)<commit_after>// This file is part of the uutils coreutils package.
//
// (c) Derek Chiang <derekchiang93@gmail.com>
// (c) Christopher Brown <ccbrown112@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.

#[macro_use]
extern crate uucore;

use clap::{crate_version, App, Arg};
use std::io::{self, Write};
use std::iter::Peekable;
use std::str::Chars;

static NAME: &str = "echo";
static USAGE: &str = "[OPTIONS]... [STRING]...";
static SUMMARY: &str = "display a line of text";
static AFTER_HELP: &str = r#"
 Echo the STRING(s) to standard output.

 If -e is in effect, the following sequences are recognized:

 \\\\      backslash
 \\a      alert (BEL)
 \\b      backspace
 \\c      produce no further output
 \\e      escape
 \\f      form feed
 \\n      new line
 \\r      carriage return
 \\t      horizontal tab
 \\v      vertical tab
 \\0NNN   byte with octal value NNN (1 to 3 digits)
 \\xHH    byte with hexadecimal value HH (1 to 2 digits)
"#;

mod options {
    pub static STRING: &str = "STRING";
    pub static NO_NEWLINE: &str = "no_newline";
    pub static ENABLE_BACKSLASH_ESCAPE: &str = "enable_backslash_escape";
    pub static DISABLE_BACKSLASH_ESCAPE: &str = "disable_backslash_escape";
}

fn parse_code(
    input: &mut Peekable<Chars>,
    base: u32,
    max_digits: u32,
    bits_per_digit: u32,
) -> Option<char> {
    let mut ret = 0x8000_0000;
    for _ in 0..max_digits {
        match input.peek().and_then(|c| c.to_digit(base)) {
            Some(n) => ret = (ret << bits_per_digit) | n,
            None => break,
        }
        input.next();
    }
    std::char::from_u32(ret)
}

fn print_escaped(input: &str, mut output: impl Write) -> io::Result<bool> {
    let mut should_stop = false;

    let mut buffer = ['\\'; 2];

    let mut iter = input.chars().peekable();
    while let Some(mut c) = iter.next() {
        let mut start = 1;

        if c == '\\' {
            if let Some(next) = iter.next() {
                c = match next {
                    '\\' => '\\',
                    'a' => '\x07',
                    'b' => '\x08',
                    'c' => {
                        should_stop = true;
                        break;
                    }
                    'e' => '\x1b',
                    'f' => '\x0c',
                    'n' => '\n',
                    'r' => '\r',
                    't' => '\t',
                    'v' => '\x0b',
                    'x' => parse_code(&mut iter, 16, 2, 4).unwrap_or_else(|| {
                        start = 0;
                        next
                    }),
                    '0' => parse_code(&mut iter, 8, 3, 3).unwrap_or_else(|| {
                        start = 0;
                        next
                    }),
                    _ => {
                        start = 0;
                        next
                    }
                };
            }
        }

        buffer[1] = c;

        // because printing char slices is apparently not available in the standard library
        for ch in &buffer[start..] {
            write!(output, "{}", ch)?;
        }
    }

    Ok(should_stop)
}

pub fn uumain(args: impl uucore::Args) -> i32 {
    let args = args.collect_str();

    let matches = App::new(executable!())
        .name(NAME)
        // TrailingVarArg specifies the final positional argument is a VarArg
        // and it doesn't attempts the parse any further args.
        // Final argument must have multiple(true) or the usage string equivalent.
        .setting(clap::AppSettings::TrailingVarArg)
        .setting(clap::AppSettings::AllowLeadingHyphen)
        .version(crate_version!())
        .usage(USAGE)
        .about(SUMMARY)
        .after_help(AFTER_HELP)
        .arg(
            Arg::with_name(options::NO_NEWLINE)
                .short("n")
                .help("do not output the trailing newline")
                .takes_value(false)
                .display_order(1),
        )
        .arg(
            Arg::with_name(options::ENABLE_BACKSLASH_ESCAPE)
                .short("e")
                .help("enable interpretation of backslash escapes")
                .takes_value(false)
                .display_order(2),
        )
        .arg(
            Arg::with_name(options::DISABLE_BACKSLASH_ESCAPE)
                .short("E")
                .help("disable interpretation of backslash escapes (default)")
                .takes_value(false)
                .display_order(3),
        )
        .arg(
            Arg::with_name(options::STRING)
                .hidden(true)
                .multiple(true)
                .allow_hyphen_values(true),
        )
        .get_matches_from(args);

    let no_newline = matches.is_present(options::NO_NEWLINE);
    let escaped = matches.is_present(options::ENABLE_BACKSLASH_ESCAPE);
    let values: Vec<String> = match matches.values_of(options::STRING) {
        Some(s) => s.map(|s| s.to_string()).collect(),
        None => vec!["".to_string()],
    };

    match execute(no_newline, escaped, values) {
        Ok(_) => 0,
        Err(f) => {
            show_error!("{}", f);
            1
        }
    }
}

fn execute(no_newline: bool, escaped: bool, free: Vec<String>) -> io::Result<()> {
    let stdout = io::stdout();
    let mut output = stdout.lock();

    for (i, input) in free.iter().enumerate() {
        if i > 0 {
            write!(output, " ")?;
        }
        if escaped {
            let should_stop = print_escaped(&input, &mut output)?;
            if should_stop {
                break;
            }
        } else {
            write!(output, "{}", input)?;
        }
    }

    if !no_newline {
        writeln!(output)?;
    }

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Add test for Location::caller in a macro.<commit_after>// run-pass

#![feature(track_caller)]

macro_rules! caller_location_from_macro {
    () => (core::panic::Location::caller());
}

fn main() {
    let loc = core::panic::Location::caller();
    assert_eq!(loc.file(), file!());
    assert_eq!(loc.line(), 10);
    assert_eq!(loc.column(), 15);

    // `Location::caller()` in a macro should behave similarly to `file!` and `line!`,
    // i.e. point to where the macro was invoked, instead of the macro itself.
    let loc2 = caller_location_from_macro!();
    assert_eq!(loc2.file(), file!());
    assert_eq!(loc2.line(), 17);
    assert_eq!(loc2.column(), 16);
}
<|endoftext|>


<commit_before><commit_msg>add notes<commit_after><|endoftext|>


<commit_before><commit_msg>test: Add test for #979<commit_after>resource r(b: @mutable int) {
    *b += 1;
}

fn main() {
    let b = @mutable 0;
    {
        let p = some(r(b));
    }

    assert *b == 1;
}<|endoftext|>


<commit_before><commit_msg>Use only one contact point per collision pair<commit_after><|endoftext|>


<commit_before><commit_msg>New formulation for an error message<commit_after><|endoftext|>


<commit_before>// Copyright 2013 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()
{
    unsafe {
        libc::exit(0);
    }
    error!("ack");
}
<commit_msg>test: XFAIL test issue-4120 due to Valgrind complaints.<commit_after>// xfail-test

// XFAIL'd due to Valgrind complaining about TLS loss.

// Copyright 2013 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()
{
    unsafe {
        libc::exit(0);
    }
    error!("ack");
}
<|endoftext|>


<commit_before><commit_msg>Go back to log calculation of digits<commit_after><|endoftext|>


<commit_before><commit_msg>Remove all expect<commit_after><|endoftext|>


<commit_before><commit_msg>Regression test.<commit_after>// Copyright 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.

// Issue #12856: a lifetime formal binding introduced by a generic fn
// should not upset the variance inference for actual occurrences of
// that lifetime in type expressions.

trait HasLife<'a> { }

trait UseLife01 {
    fn refs<'a, H: HasLife<'a>>(&'a self) -> H;
}

trait UseLife02 {
    fn refs<'a, T, H: HasType<&'a T>>(&'a self) -> H;
}

trait HasType<T> { }

trait UseLife03<T> {
    fn refs<'a, H: HasType<&'a T>>(&'a self) -> H;
}

// (The functions below were not actually a problem observed during
// fixing of #12856; they just seem like natural tests to put in to
// cover a couple more points in the testing space)

pub fn top_refs_1<'a, H: HasLife<'a>>(_s: &'a ()) -> H {
    unimplemented!()
}

pub fn top_refs_2<'a, T, H: HasType<&'a T>>(_s: &'a ()) -> H {
    unimplemented!()
}

pub fn main() {}
<|endoftext|>