<commit_before>// Copyright 2015 The Delix Project Authors. See the AUTHORS file at the top level directory.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

use std::collections::{HashMap, hash_map};
use std::sync::{RwLock, mpsc};

use super::{Metric, metric};

pub struct Memory {
    entries: RwLock<HashMap<String, Entry>>,
    watches: RwLock<HashMap<String, mpsc::Sender<(String, Entry)>>>,
}

#[derive(Clone, Debug, PartialEq)]
enum Entry {
    Counter(usize),
    Gauge(isize),
}

impl Memory {
    pub fn new() -> Self {
        Memory {
            entries: RwLock::new(HashMap::new()),
            watches: RwLock::new(HashMap::new()),
        }
    }

    pub fn get_counter(&self, key: &str) -> usize {
        let entries = self.entries.read().unwrap();
        entries.get(key)
               .map(|entry| {
                   if let Entry::Counter(value) = *entry {
                       value
                   } else {
                       0
                   }
               })
               .unwrap_or(0)
    }

    pub fn get_gauge(&self, key: &str) -> isize {
        let entries = self.entries.read().unwrap();
        entries.get(key)
               .map(|entry| {
                   if let Entry::Gauge(value) = *entry {
                       value
                   } else {
                       0
                   }
               })
               .unwrap_or(0)
    }

    fn update_counter<F>(&self, key: &str, default: usize, f: F)
        where F: Fn(&mut usize)
    {
        self.update(key, Entry::Counter(default), |entry| {
            if let Entry::Counter(ref mut value) = *entry {
                f(value);
            }
        });
    }

    fn update_gauge<F>(&self, key: &str, default: isize, f: F)
        where F: Fn(&mut isize)
    {
        self.update(key, Entry::Gauge(default), |entry| {
            if let Entry::Gauge(ref mut value) = *entry {
                f(value);
            }
        });
    }

    fn update<F>(&self, key: &str, default: Entry, f: F)
        where F: Fn(&mut Entry)
    {
        let mut entries = self.entries.write().unwrap();
        let entry = match entries.entry(key.to_string()) {
            hash_map::Entry::Vacant(ve) => {
                ve.insert(default.clone());
                default
            }
            hash_map::Entry::Occupied(ref mut oe) => {
                f(oe.get_mut());
                oe.get().clone()
            }
        };

        let watches = self.watches.read().unwrap();
        if let Some(tx) = watches.get(key) {
            tx.send((key.to_string(), entry)).unwrap();
        }
    }

    pub fn watch_counter<F>(&self, pattern: &str, f: F)
        where F: Fn(&str, usize) -> bool
    {
        self.watch(pattern, |key, entry| {
            if let Entry::Counter(value) = *entry {
                return f(key, value);
            }
            false
        });
    }

    pub fn watch_gauge<F>(&self, pattern: &str, f: F)
        where F: Fn(&str, isize) -> bool
    {
        self.watch(pattern, |key, entry| {
            if let Entry::Gauge(value) = *entry {
                return f(key, value);
            }
            false
        });
    }

    fn watch<F>(&self, pattern: &str, f: F)
        where F: Fn(&str, &Entry) -> bool
    {
        let (tx, rx) = mpsc::channel();
        {
            let mut watches = self.watches.write().unwrap();
            if watches.contains_key(pattern) {
                panic!("entry exists");
            }
            watches.insert(pattern.to_string(), tx);
        }

        let (mut key, mut entry) = rx.recv().unwrap();
        while f(&key, &entry) {
            let tuple = rx.recv().unwrap();
            key = tuple.0;
            entry = tuple.1;
        }

        {
            let mut watches = self.watches.write().unwrap();
            watches.remove(pattern);
        }
    }
}

impl Metric for Memory {
    fn increment_counter(&self, key: &str) {
        self.update_counter(key, 1, |value| {
            *value += 1;
        });
    }

    fn change_gauge(&self, key: &str, change: metric::Change) {
        match change {
            metric::Change::Set(new_value) => {
                self.update_gauge(key, new_value, |value| *value = new_value);
            }
            metric::Change::Delta(delta_value) => {
                self.update_gauge(key, delta_value, |value| *value += delta_value);
            }
        }
    }
}

unsafe impl Send for Memory {}

unsafe impl Sync for Memory {}

#[cfg(test)]
mod tests {

    use std::sync::Arc;
    use std::thread;
    use super::super::{Metric, metric};
    use super::Memory;

    #[test]
    fn increment_counter() {
        let metric = Memory::new();
        assert_eq!(0, metric.get_counter("test"));
        metric.increment_counter("test");
        assert_eq!(1, metric.get_counter("test"));
        metric.increment_counter("test");
        assert_eq!(2, metric.get_counter("test"));
    }

    #[test]
    fn increment_counter_concurrently() {
        let metric = Arc::new(Memory::new());

        let metric_clone = metric.clone();
        let jh1 = thread::spawn(move || {
            for _ in 0..10 {
                metric_clone.increment_counter("test");
            }
        });

        let metric_clone = metric.clone();
        let jh2 = thread::spawn(move || {
            for _ in 0..10 {
                metric_clone.increment_counter("test");
            }
        });

        jh1.join().unwrap();
        jh2.join().unwrap();

        assert_eq!(20, metric.get_counter("test"));
    }

    #[test]
    fn watch_counter() {
        let metric = Arc::new(Memory::new());

        let metric_clone = metric.clone();
        thread::spawn(move || {
            for _ in 0..10 {
                metric_clone.increment_counter("test");
            }
        });

        metric.watch_counter("test", |_, value| value < 10);
    }

    #[test]
    fn change_gauge() {
        let metric = Memory::new();
        assert_eq!(0, metric.get_gauge("test"));
        metric.change_gauge("test", metric::Change::Set(10));
        assert_eq!(10, metric.get_gauge("test"));
        metric.change_gauge("test", metric::Change::Delta(-5));
        assert_eq!(5, metric.get_gauge("test"));
        metric.change_gauge("test", metric::Change::Delta(10));
        assert_eq!(15, metric.get_gauge("test"));
    }

    #[test]
    fn change_gauge_concurrently() {
        let metric = Arc::new(Memory::new());

        let metric_clone = metric.clone();
        let jh1 = thread::spawn(move || {
            for _ in 0..10 {
                metric_clone.change_gauge("test", metric::Change::Delta(5));
            }
        });

        let metric_clone = metric.clone();
        let jh2 = thread::spawn(move || {
            for _ in 0..10 {
                metric_clone.change_gauge("test", metric::Change::Delta(-10));
            }
        });

        jh1.join().unwrap();
        jh2.join().unwrap();

        assert_eq!(-50isize, metric.get_gauge("test"));
    }

    #[test]
    fn watch_gauge() {
        let metric = Arc::new(Memory::new());

        let metric_clone = metric.clone();
        thread::spawn(move || {
            for _ in 0..10 {
                metric_clone.change_gauge("test", metric::Change::Delta(-1isize));
            }
        });

        metric.watch_gauge("test", |_, value| value > -10);
    }

}
<commit_msg>fixed metric watch<commit_after>// Copyright 2015 The Delix Project Authors. See the AUTHORS file at the top level directory.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

use std::collections::{HashMap, hash_map};
use std::sync::{RwLock, mpsc};

use super::{Metric, metric};

pub struct Memory {
    entries: RwLock<HashMap<String, Entry>>,
    watches: RwLock<HashMap<String, mpsc::Sender<(String, Entry)>>>,
}

#[derive(Clone, Debug, PartialEq)]
enum Entry {
    Counter(usize),
    Gauge(isize),
}

impl Memory {
    pub fn new() -> Self {
        Memory {
            entries: RwLock::new(HashMap::new()),
            watches: RwLock::new(HashMap::new()),
        }
    }

    pub fn get_counter(&self, key: &str) -> usize {
        self.get(key)
            .map(|entry| {
                if let Entry::Counter(value) = entry {
                    value
                } else {
                    0
                }
            })
            .unwrap_or(0)
    }

    pub fn get_gauge(&self, key: &str) -> isize {
        self.get(key)
            .map(|entry| {
                if let Entry::Gauge(value) = entry {
                    value
                } else {
                    0
                }
            })
            .unwrap_or(0)
    }

    fn get(&self, key: &str) -> Option<Entry> {
        let entries = self.entries.read().unwrap();
        entries.get(key).map(|entry| entry.clone())
    }

    fn update_counter<F>(&self, key: &str, default: usize, f: F)
        where F: Fn(&mut usize)
    {
        self.update(key, Entry::Counter(default), |entry| {
            if let Entry::Counter(ref mut value) = *entry {
                f(value);
            }
        });
    }

    fn update_gauge<F>(&self, key: &str, default: isize, f: F)
        where F: Fn(&mut isize)
    {
        self.update(key, Entry::Gauge(default), |entry| {
            if let Entry::Gauge(ref mut value) = *entry {
                f(value);
            }
        });
    }

    fn update<F>(&self, key: &str, default: Entry, f: F)
        where F: Fn(&mut Entry)
    {
        let mut entries = self.entries.write().unwrap();
        let entry = match entries.entry(key.to_string()) {
            hash_map::Entry::Vacant(ve) => {
                ve.insert(default.clone());
                default
            }
            hash_map::Entry::Occupied(ref mut oe) => {
                f(oe.get_mut());
                oe.get().clone()
            }
        };

        let watches = self.watches.read().unwrap();
        if let Some(tx) = watches.get(key) {
            tx.send((key.to_string(), entry)).unwrap();
        }
    }

    pub fn watch_counter<F>(&self, pattern: &str, f: F)
        where F: Fn(&str, usize) -> bool
    {
        self.watch(pattern, |key, entry| {
            if let Entry::Counter(value) = *entry {
                return f(key, value);
            }
            false
        });
    }

    pub fn watch_gauge<F>(&self, pattern: &str, f: F)
        where F: Fn(&str, isize) -> bool
    {
        self.watch(pattern, |key, entry| {
            if let Entry::Gauge(value) = *entry {
                return f(key, value);
            }
            false
        });
    }

    fn watch<F>(&self, pattern: &str, f: F)
        where F: Fn(&str, &Entry) -> bool
    {
        let (tx, rx) = mpsc::channel();
        {
            let mut watches = self.watches.write().unwrap();

            if let Some(entry) = self.get(pattern) {
                if !f(pattern, &entry) {
                    return;
                }
            }

            if watches.contains_key(pattern) {
                panic!("entry exists");
            }
            watches.insert(pattern.to_string(), tx);
        }

        let (mut key, mut entry) = rx.recv().unwrap();
        while f(&key, &entry) {
            let tuple = rx.recv().unwrap();
            key = tuple.0;
            entry = tuple.1;
        }

        {
            let mut watches = self.watches.write().unwrap();
            watches.remove(pattern);
        }
    }
}

impl Metric for Memory {
    fn increment_counter(&self, key: &str) {
        self.update_counter(key, 1, |value| {
            *value += 1;
        });
    }

    fn change_gauge(&self, key: &str, change: metric::Change) {
        match change {
            metric::Change::Set(new_value) => {
                self.update_gauge(key, new_value, |value| *value = new_value);
            }
            metric::Change::Delta(delta_value) => {
                self.update_gauge(key, delta_value, |value| *value += delta_value);
            }
        }
    }
}

unsafe impl Send for Memory {}

unsafe impl Sync for Memory {}

#[cfg(test)]
mod tests {

    use std::sync::Arc;
    use std::thread;
    use super::super::{Metric, metric};
    use super::Memory;

    #[test]
    fn increment_counter() {
        let metric = Memory::new();
        assert_eq!(0, metric.get_counter("test"));
        metric.increment_counter("test");
        assert_eq!(1, metric.get_counter("test"));
        metric.increment_counter("test");
        assert_eq!(2, metric.get_counter("test"));
    }

    #[test]
    fn increment_counter_concurrently() {
        let metric = Arc::new(Memory::new());

        let metric_clone = metric.clone();
        let jh1 = thread::spawn(move || {
            for _ in 0..10 {
                metric_clone.increment_counter("test");
            }
        });

        let metric_clone = metric.clone();
        let jh2 = thread::spawn(move || {
            for _ in 0..10 {
                metric_clone.increment_counter("test");
            }
        });

        jh1.join().unwrap();
        jh2.join().unwrap();

        assert_eq!(20, metric.get_counter("test"));
    }

    #[test]
    fn watch_counter() {
        let metric = Arc::new(Memory::new());

        let metric_clone = metric.clone();
        thread::spawn(move || {
            for _ in 0..10 {
                metric_clone.increment_counter("test");
            }
        });

        metric.watch_counter("test", |_, value| value < 10);
    }

    #[test]
    fn watch_counter_without_trigger() {
        let metric = Memory::new();
        metric.increment_counter("test");
        metric.watch_counter("test", |_, value| value < 1);
    }

    #[test]
    fn change_gauge() {
        let metric = Memory::new();
        assert_eq!(0, metric.get_gauge("test"));
        metric.change_gauge("test", metric::Change::Set(10));
        assert_eq!(10, metric.get_gauge("test"));
        metric.change_gauge("test", metric::Change::Delta(-5));
        assert_eq!(5, metric.get_gauge("test"));
        metric.change_gauge("test", metric::Change::Delta(10));
        assert_eq!(15, metric.get_gauge("test"));
    }

    #[test]
    fn change_gauge_concurrently() {
        let metric = Arc::new(Memory::new());

        let metric_clone = metric.clone();
        let jh1 = thread::spawn(move || {
            for _ in 0..10 {
                metric_clone.change_gauge("test", metric::Change::Delta(5));
            }
        });

        let metric_clone = metric.clone();
        let jh2 = thread::spawn(move || {
            for _ in 0..10 {
                metric_clone.change_gauge("test", metric::Change::Delta(-10));
            }
        });

        jh1.join().unwrap();
        jh2.join().unwrap();

        assert_eq!(-50isize, metric.get_gauge("test"));
    }

    #[test]
    fn watch_gauge() {
        let metric = Arc::new(Memory::new());

        let metric_clone = metric.clone();
        thread::spawn(move || {
            for _ in 0..10 {
                metric_clone.change_gauge("test", metric::Change::Delta(-1isize));
            }
        });

        metric.watch_gauge("test", |_, value| value > -10);
    }

}
<|endoftext|>


<commit_before>mod terminal;

pub struct Interface {
    choices: Vec<String>
}

impl Interface {
    /// Creates a new Interface with the provided input choices.
    pub fn with_choices(choices: Vec<String>) -> Interface {
        Interface {
            choices: choices
        }
    }

    // Starts the interface
    pub fn run(&mut self) {
        println!("{} choices to search through", self.choices.len());
    }
}
<commit_msg>Add terminal to Interface, use for printing, events<commit_after>mod terminal;

use std::io::Write;
use self::terminal::{Terminal, Event, Key};

pub struct Interface {
    choices: Vec<String>,
    terminal: Terminal
}

impl Interface {
    /// Creates a new Interface with the provided input choices.
    pub fn with_choices(choices: Vec<String>) -> Interface {
        let mut term = Terminal::from("/dev/tty").unwrap();
        term.set_raw_mode().unwrap();

        Interface {
            choices: choices,
            terminal: term
        }
    }

    // Starts the interface
    pub fn run(&mut self) {
        let ref mut term = self.terminal;

        write!(term, "{} choices to search through\r\n", self.choices.len());

        for event in term.events().unwrap() {
            match event {
                Ok(Event::Key(Key::Ctrl('c'))) => {
                    return;
                },

                Ok(event) => write!(term, "{:?}\r\n", event),
                Err(err) => write!(term, "{:?}\r\n", err),
            };
        }
    }
}
<|endoftext|>


<commit_before>
use util;
use std;
use std::error::Error;

pub type Result<T> = std::result::Result<T,String>;

/// A list of symbols to be tokenized.
pub const SYMBOL_LIST: &'static [char] = &[
    ',', ':', '(', ')', '@', '%', '{', '}',
];

/// A token.
#[derive(Clone,Debug,PartialEq,Eq)]
pub enum Token
{
    /// A word.
    Word(String),
    /// A string literal.
    String(String),
    /// An integer literal.
    // TODO: use BigNum
    Integer(i64),
    /// A comment.
    ///
    /// If the comment is inline, it existed on the same line
    /// as the previous statement.
    ///
    /// For example
    ///
    /// ```
    /// add 2, 4 ; inline comment goes here
    /// ```
    Comment {
        inline: bool,
        text: String,
    },
    /// A symbol.
    Symbol(String),
    /// A new line.
    NewLine,
    /// End of file.
    /// Will always be yielded as the last
    /// token.
    EOF,
}

impl Token
{
    pub fn word<S>(word: S) -> Self
        where S: Into<String> {
        Token::Word(word.into())
    }

    pub fn string<S>(string: S) -> Self
        where S: Into<String> {
        Token::String(string.into())
    }

    pub fn integer<I>(integer: I) -> Self
        where I: Into<i64> {
        Token::Integer(integer.into())
    }

    pub fn comment<S>(text: S) -> Self
        where S: Into<String> {
        Token::Comment {
            inline: false,
            text: text.into(),
        }
    }

    pub fn inline_comment<S>(text: S) -> Self
        where S: Into<String> {
        Token::Comment {
            inline: true,
            text: text.into(),
        }
    }

    pub fn symbol<S>(symbol: S) -> Self
        where S: Into<String> {
        Token::Symbol(symbol.into())
    }

    pub fn new_line() -> Self {
        Token::NewLine
    }

    pub fn eof() -> Self {
        Token::EOF
    }
}

impl std::fmt::Display for Token
{
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            &Token::Word(ref w) => write!(fmt, "{}", w),
            &Token::String(ref s) => write!(fmt, "\"{}\"", s),
            &Token::Integer(ref i) => write!(fmt, "{}", i),
            &Token::Symbol(ref s) => write!(fmt, "{}", s),
            &Token::Comment { ref text, .. } => write!(fmt, " {}", text),
            &Token::NewLine => write!(fmt, "new line"),
            &Token::EOF => write!(fmt, "EOF"),
        }
    }
}

/// An iterator over a set of characters.
///
/// This type abstracts over another iterator of characters,
/// making sure that the yielded characters will have a specific
/// format.
///
/// * There will always be a new line (`\n`) before the end of file.
pub struct Characters<I: Iterator<Item=char>>
{
    it: std::iter::Peekable<I>,
    finished: bool,
    peek_buf: Option<char>,
}

impl<I> Characters<I>
    where I: Iterator<Item=char>
{
    pub fn new(it: I) -> Self {
        Characters {
            it: it.peekable(),
            finished: false,
            peek_buf: None,
        }
    }

    pub fn peek(&mut self) -> Option<char> {
        if self.peek_buf.is_none() {
            self.peek_buf = self.next();
        }

        self.peek_buf
    }

    pub fn eat(&mut self) {
        self.next();
    }

    pub fn eat_while<P>(&mut self, predicate: P)
        where P: FnMut(char) -> bool {
        self.consume_while(predicate);
    }

    pub fn consume_while<P>(&mut self, mut predicate: P)
        -> std::vec::IntoIter<char>
        where P: FnMut(char) -> bool {
        let mut result = Vec::new();

        loop {
            let c = match self.peek() {
                Some(c) => c,
                None => break,
            };

            if predicate(c) {
                result.push(self.next().unwrap());
            } else {
                break;
            }
        }

        result.into_iter()
    }
}

impl<I> Iterator for Characters<I>
    where I: Iterator<Item=char>
{
    type Item = char;

    fn next(&mut self) -> Option<char> {
        if self.peek_buf.is_some() {
            let c = self.peek_buf.unwrap();
            self.peek_buf = None;
            return Some(c);
        }

        match self.it.next() {
            Some(c) => Some(c),
            None => {
                if self.finished {
                    None
                } else { // When we first reach the EOF
                    self.finished = true;
                    Some('\n')
                }
            },
        }
    }
}

pub struct Tokenizer<I: Iterator<Item=char>>
{
    chars: Characters<I>,

    finished: bool,
    preserve_comments: bool,
}

impl<I> Tokenizer<I>
    where I: Iterator<Item=char>
{
    pub fn new(chars: I) -> Self {
        Tokenizer {
            chars: Characters::new(chars),
            finished: false,
            preserve_comments: false,
        }
    }

    /// Allows the tokenizer to preserve comments it tokenizes.
    pub fn preserve_comments(mut self) -> Self {
        self.preserve_comments = true;
        self
    }

    fn eat_whitespace(&mut self) {
        self.chars.eat_while(|c| c.is_whitespace() && c != '\n')
    }

    fn next_string(&mut self) -> Option<Result<Token>> {
        self.assert('"');
        let string = self.chars.consume_while(|c| c != '\"');
        self.assert('"');

        Some(Ok(Token::String(string.collect())))
    }

    fn next_integer(&mut self) -> Option<Result<Token>> {
        let string: String = self.chars.consume_while(|c| c.is_numeric()).collect();

        let int = match i64::from_str_radix(&string, 10) {
            Ok(int) => int,
            Err(e) => return Some(Err(format!("Could not parse integer: {}",
                                              e.description()))),
        };

        Some(Ok(Token::Integer(int)))
    }

    fn next_word(&mut self) -> Option<Result<Token>> {
        let word: String = self.chars.consume_while(internal::can_word_contain).collect();

        Some(Ok(Token::Word(word)))
    }

    fn next_symbol(&mut self) -> Option<Result<Token>> {
        match self.expect_one_of(SYMBOL_LIST) {
            Ok(sym) => Some(Ok(Token::symbol(format!("{}", sym)))),
            // TODO: this will give a shitty error message
            // if the end of stream is reached.
            Err(..) => Some(Err("unknown token".into())),
        }
    }

    fn next_comment(&mut self) -> Option<Result<Token>> {
        self.assert(';');
        let text: String = self.chars.consume_while(|c| c != '\n').collect();

        Some(Ok(Token::comment(text)))
    }

    fn eat_next_comment(&mut self) -> Option<Result<()>> {
        self.next_comment().map(|result| result.map(|_| ()))
    }

    fn assert(&mut self, expected: char) -> char {
        self.expect(expected).expect("unexpected character")
    }

    fn expect(&mut self, expected: char) -> Result<char> {
        // TODO: more specific error message
        self.expect_one_of(&[expected])
    }

    fn expect_one_of(&mut self, expected: &[char]) -> Result<char> {
        let expected_str = util::comma_separated_values(expected.iter());

        let next = match self.chars.next() {
            Some(c) => c,
            None => {
                return Err(format!("expected one of {} but got nothing", expected_str))
            },
        };

        if expected.iter().any(|&c| c == next) {
            Ok(next)
        } else {
            Err(format!("Expected one of {} but got {}", expected_str, next))
        }
    }
}

impl<I> Iterator for Tokenizer<I>
    where I: Iterator<Item=char>
{
    type Item = Result<Token>;

    fn next(&mut self) -> Option<Result<Token>> {
        self.eat_whitespace();

        let first_char = match self.chars.peek() {
            Some(c) => c,

            // If there are no tokens left, return EOF if
            // we haven't already, or None otherwise.
            None => {
                if self.finished {
                    return None;
                } else {
                    self.finished = true;
                    return Some(Ok(Token::eof()));
                }
            },
        };

        if first_char == '"' {
            self.next_string()
        } else if first_char == '\n' {
            self.chars.eat();
            Some(Ok(Token::new_line()))
        } else if first_char == ';' {
            if self.preserve_comments {
                self.next_comment()
            } else {

                // TODO: This could be nicer
                match self.eat_next_comment() {
                    Some(Ok(..)) => (),
                    Some(Err(e)) => return Some(Err(e)),
                    None => panic!("expected a comment to be parsed"),
                }

                // TODO: fix needless recursion
                self.next()
            }
        } else if first_char.is_numeric() {
            self.next_integer()
        } else if internal::can_word_start_with(first_char) {
            self.next_word()
        } else {
            // Try to parse the token as a symbol.
            // This is our final fallback.
            self.next_symbol()
        }
    }
}

mod internal
{
    pub fn can_word_start_with(c: char) -> bool {
        c.is_alphabetic() || c == '_'
    }

    pub fn can_word_contain(c: char) -> bool {
        can_word_start_with(c) || c.is_numeric()
    }
}

mod test
{
    use super::{Token,Tokenizer};

    /// Expects a mapping from a string of tokens into
    /// a list of tokens with the default tokenizer.
    macro_rules! expect_mapping {
        ($input:expr => $( $output:expr ),* ) => {
            expect_mapping_with!(Tokenizer::new($input.chars()) =>
                                 $( $output ),*);
        }
    }

    /// Expects a mapping from a string of tokens into
    /// a list of tokens, given a specific tokenizer.
    macro_rules! expect_mapping_with {
        // TODO: make the macro take several arguments
        // for several outputs
        ($tokenizer:expr => $( $output:expr ),* ) => {
            {
                let mut tokenizer = $tokenizer;

                $(
                    let token = tokenizer.next().unwrap().unwrap();
                    assert!($output == token,
                            format!("expected {} but got {}",
                                    $output, token));
                )*
            }
        }
    }

    #[test]
    fn test_string() {
        expect_mapping!("\"hello\"" =>  Token::string("hello"),
                                        Token::new_line(),
                                        Token::eof());

        expect_mapping!("\"hello abc\"" => Token::string("hello abc"),
                                           Token::new_line(),
                                           Token::eof());

        expect_mapping!("\"hello world\"  \"it is me\"" =>
                        Token::string("hello world"),
                        Token::string("it is me"),
                        Token::new_line(),
                        Token::eof());
    }

    #[test]
    fn test_integer() {
        expect_mapping!("123" => Token::integer(123),
                                 Token::new_line(),
                                 Token::eof());

        expect_mapping!("0982" => Token::integer(982),
                                  Token::new_line(),
                                  Token::eof());

        expect_mapping!("333 662" => Token::integer(333),
                                     Token::integer(662),
                                     Token::new_line(),
                                     Token::eof());

        expect_mapping!("1 2 3 4" => Token::integer(1),
                                     Token::integer(2),
                                     Token::integer(3),
                                     Token::integer(4),
                                     Token::new_line(),
                                     Token::eof());
    }

    #[test]
    fn test_word() {
        expect_mapping!("hello" => Token::word("hello"));

        expect_mapping!("ab cd" => Token::word("ab"),
                                   Token::word("cd"),
                                   Token::new_line(),
                                   Token::eof());

        expect_mapping!("a b c d" => Token::word("a"),
                                     Token::word("b"),
                                     Token::word("c"),
                                     Token::word("d"),
                                     Token::new_line(),
                                     Token::eof());
    }

    #[test]
    fn test_comments_not_preserved_by_default() {
        expect_mapping!("hello ; there" => Token::word("hello"),
                                           Token::new_line(),
                                           Token::eof());

        expect_mapping!(";why hello" => Token::new_line(),
                                        Token::eof());
    }

    #[test]
    fn test_comments() {
        expect_mapping_with!(Tokenizer::new("hello world ; this is me".chars())
                             .preserve_comments()
                             => Token::word("hello"),
                                Token::word("world"),
                                Token::comment(" this is me"),
                                Token::new_line(),
                                Token::eof());

        expect_mapping_with!(Tokenizer::new(";this is a test".chars())
                             .preserve_comments()
                             => Token::comment("this is a test"),
                                Token::new_line(),
                                Token::eof());
    }

    #[test]
    fn test_symbols() {
        expect_mapping!("(" => Token::symbol("("),
                               Token::new_line(),
                               Token::eof());

        expect_mapping!(")" => Token::symbol(")"));
        expect_mapping!("{ }" => Token::symbol("{"), Token::symbol("}"));
        expect_mapping!(":" => Token::symbol(":"));
        expect_mapping!("," => Token::symbol(","));
        expect_mapping!("@%" => Token::symbol("@"), Token::symbol("%"));
    }

    #[test]
    fn test_multiple() {
        expect_mapping!("12 bark \"earth\"" => Token::integer(12),
                                               Token::word("bark"),
                                               Token::string("earth"),
                                               Token::new_line(),
                                               Token::eof());

        expect_mapping!("a      23 gg \"a\"" => Token::word("a"),
                                                Token::integer(23),
                                                Token::word("gg"),
                                                Token::string("a"),
                                                Token::new_line(),
                                                Token::eof());

        expect_mapping!("4:3{2\n}" => Token::integer(4),
                                      Token::symbol(":"),
                                      Token::integer(3),
                                      Token::symbol("{"),
                                      Token::integer(2),
                                      Token::new_line(),
                                      Token::symbol("}"),
                                      Token::new_line(),
                                      Token::eof());
    }

    #[test]
    fn test_whitespace() {
        expect_mapping!("a\tb\t123\n\"qwer\"\n" => Token::word("a"),
                                                   Token::word("b"),
                                                   Token::integer(123),
                                                   Token::new_line(),
                                                   Token::string("qwer"),
                                                   Token::new_line(),
                                                   Token::new_line(),
                                                   Token::eof());
    }
}
<commit_msg>[IR] Added pretty symbol constructors to 'Token'<commit_after>
use util;
use std;
use std::error::Error;

pub type Result<T> = std::result::Result<T,String>;

/// A list of symbols to be tokenized.
pub const SYMBOL_LIST: &'static [char] = &[
    ',', ':', '(', ')', '@', '%', '{', '}',
];

/// A token.
#[derive(Clone,Debug,PartialEq,Eq)]
pub enum Token
{
    /// A word.
    Word(String),
    /// A string literal.
    String(String),
    /// An integer literal.
    // TODO: use BigNum
    Integer(i64),
    /// A comment.
    ///
    /// If the comment is inline, it existed on the same line
    /// as the previous statement.
    ///
    /// For example
    ///
    /// ```
    /// add 2, 4 ; inline comment goes here
    /// ```
    Comment {
        inline: bool,
        text: String,
    },
    /// A symbol.
    Symbol(String),
    /// A new line.
    NewLine,
    /// End of file.
    /// Will always be yielded as the last
    /// token.
    EOF,
}

impl Token
{
    pub fn comma() -> Self { Token::symbol(",") }
    pub fn colon() -> Self { Token::symbol(":") }
    pub fn left_parenthesis() -> Self { Token::symbol("(") }
    pub fn right_parenthesis() -> Self { Token::symbol(")") }
    pub fn at_sign() -> Self { Token::symbol("@") }
    pub fn percent_sign() -> Self { Token::symbol("%") }
    pub fn left_curly_brace() -> Self { Token::symbol("{") }
    pub fn right_curly_brace() -> Self { Token::symbol("}") }

    pub fn word<S>(word: S) -> Self
        where S: Into<String> {
        Token::Word(word.into())
    }

    pub fn string<S>(string: S) -> Self
        where S: Into<String> {
        Token::String(string.into())
    }

    pub fn integer<I>(integer: I) -> Self
        where I: Into<i64> {
        Token::Integer(integer.into())
    }

    pub fn comment<S>(text: S) -> Self
        where S: Into<String> {
        Token::Comment {
            inline: false,
            text: text.into(),
        }
    }

    pub fn inline_comment<S>(text: S) -> Self
        where S: Into<String> {
        Token::Comment {
            inline: true,
            text: text.into(),
        }
    }

    pub fn symbol<S>(symbol: S) -> Self
        where S: Into<String> {
        Token::Symbol(symbol.into())
    }

    pub fn new_line() -> Self {
        Token::NewLine
    }

    pub fn eof() -> Self {
        Token::EOF
    }
}

impl std::fmt::Display for Token
{
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            &Token::Word(ref w) => write!(fmt, "{}", w),
            &Token::String(ref s) => write!(fmt, "\"{}\"", s),
            &Token::Integer(ref i) => write!(fmt, "{}", i),
            &Token::Symbol(ref s) => write!(fmt, "{}", s),
            &Token::Comment { ref text, .. } => write!(fmt, " {}", text),
            &Token::NewLine => write!(fmt, "new line"),
            &Token::EOF => write!(fmt, "EOF"),
        }
    }
}

/// An iterator over a set of characters.
///
/// This type abstracts over another iterator of characters,
/// making sure that the yielded characters will have a specific
/// format.
///
/// * There will always be a new line (`\n`) before the end of file.
pub struct Characters<I: Iterator<Item=char>>
{
    it: std::iter::Peekable<I>,
    finished: bool,
    peek_buf: Option<char>,
}

impl<I> Characters<I>
    where I: Iterator<Item=char>
{
    pub fn new(it: I) -> Self {
        Characters {
            it: it.peekable(),
            finished: false,
            peek_buf: None,
        }
    }

    pub fn peek(&mut self) -> Option<char> {
        if self.peek_buf.is_none() {
            self.peek_buf = self.next();
        }

        self.peek_buf
    }

    pub fn eat(&mut self) {
        self.next();
    }

    pub fn eat_while<P>(&mut self, predicate: P)
        where P: FnMut(char) -> bool {
        self.consume_while(predicate);
    }

    pub fn consume_while<P>(&mut self, mut predicate: P)
        -> std::vec::IntoIter<char>
        where P: FnMut(char) -> bool {
        let mut result = Vec::new();

        loop {
            let c = match self.peek() {
                Some(c) => c,
                None => break,
            };

            if predicate(c) {
                result.push(self.next().unwrap());
            } else {
                break;
            }
        }

        result.into_iter()
    }
}

impl<I> Iterator for Characters<I>
    where I: Iterator<Item=char>
{
    type Item = char;

    fn next(&mut self) -> Option<char> {
        if self.peek_buf.is_some() {
            let c = self.peek_buf.unwrap();
            self.peek_buf = None;
            return Some(c);
        }

        match self.it.next() {
            Some(c) => Some(c),
            None => {
                if self.finished {
                    None
                } else { // When we first reach the EOF
                    self.finished = true;
                    Some('\n')
                }
            },
        }
    }
}

pub struct Tokenizer<I: Iterator<Item=char>>
{
    chars: Characters<I>,

    finished: bool,
    preserve_comments: bool,
}

impl<I> Tokenizer<I>
    where I: Iterator<Item=char>
{
    pub fn new(chars: I) -> Self {
        Tokenizer {
            chars: Characters::new(chars),
            finished: false,
            preserve_comments: false,
        }
    }

    /// Allows the tokenizer to preserve comments it tokenizes.
    pub fn preserve_comments(mut self) -> Self {
        self.preserve_comments = true;
        self
    }

    fn eat_whitespace(&mut self) {
        self.chars.eat_while(|c| c.is_whitespace() && c != '\n')
    }

    fn next_string(&mut self) -> Option<Result<Token>> {
        self.assert('"');
        let string = self.chars.consume_while(|c| c != '\"');
        self.assert('"');

        Some(Ok(Token::String(string.collect())))
    }

    fn next_integer(&mut self) -> Option<Result<Token>> {
        let string: String = self.chars.consume_while(|c| c.is_numeric()).collect();

        let int = match i64::from_str_radix(&string, 10) {
            Ok(int) => int,
            Err(e) => return Some(Err(format!("Could not parse integer: {}",
                                              e.description()))),
        };

        Some(Ok(Token::Integer(int)))
    }

    fn next_word(&mut self) -> Option<Result<Token>> {
        let word: String = self.chars.consume_while(internal::can_word_contain).collect();

        Some(Ok(Token::Word(word)))
    }

    fn next_symbol(&mut self) -> Option<Result<Token>> {
        match self.expect_one_of(SYMBOL_LIST) {
            Ok(sym) => Some(Ok(Token::symbol(format!("{}", sym)))),
            // TODO: this will give a shitty error message
            // if the end of stream is reached.
            Err(..) => Some(Err("unknown token".into())),
        }
    }

    fn next_comment(&mut self) -> Option<Result<Token>> {
        self.assert(';');
        let text: String = self.chars.consume_while(|c| c != '\n').collect();

        Some(Ok(Token::comment(text)))
    }

    fn eat_next_comment(&mut self) -> Option<Result<()>> {
        self.next_comment().map(|result| result.map(|_| ()))
    }

    fn assert(&mut self, expected: char) -> char {
        self.expect(expected).expect("unexpected character")
    }

    fn expect(&mut self, expected: char) -> Result<char> {
        // TODO: more specific error message
        self.expect_one_of(&[expected])
    }

    fn expect_one_of(&mut self, expected: &[char]) -> Result<char> {
        let expected_str = util::comma_separated_values(expected.iter());

        let next = match self.chars.next() {
            Some(c) => c,
            None => {
                return Err(format!("expected one of {} but got nothing", expected_str))
            },
        };

        if expected.iter().any(|&c| c == next) {
            Ok(next)
        } else {
            Err(format!("Expected one of {} but got {}", expected_str, next))
        }
    }
}

impl<I> Iterator for Tokenizer<I>
    where I: Iterator<Item=char>
{
    type Item = Result<Token>;

    fn next(&mut self) -> Option<Result<Token>> {
        self.eat_whitespace();

        let first_char = match self.chars.peek() {
            Some(c) => c,

            // If there are no tokens left, return EOF if
            // we haven't already, or None otherwise.
            None => {
                if self.finished {
                    return None;
                } else {
                    self.finished = true;
                    return Some(Ok(Token::eof()));
                }
            },
        };

        if first_char == '"' {
            self.next_string()
        } else if first_char == '\n' {
            self.chars.eat();
            Some(Ok(Token::new_line()))
        } else if first_char == ';' {
            if self.preserve_comments {
                self.next_comment()
            } else {

                // TODO: This could be nicer
                match self.eat_next_comment() {
                    Some(Ok(..)) => (),
                    Some(Err(e)) => return Some(Err(e)),
                    None => panic!("expected a comment to be parsed"),
                }

                // TODO: fix needless recursion
                self.next()
            }
        } else if first_char.is_numeric() {
            self.next_integer()
        } else if internal::can_word_start_with(first_char) {
            self.next_word()
        } else {
            // Try to parse the token as a symbol.
            // This is our final fallback.
            self.next_symbol()
        }
    }
}

mod internal
{
    pub fn can_word_start_with(c: char) -> bool {
        c.is_alphabetic() || c == '_'
    }

    pub fn can_word_contain(c: char) -> bool {
        can_word_start_with(c) || c.is_numeric()
    }
}

mod test
{
    use super::{Token,Tokenizer};

    /// Expects a mapping from a string of tokens into
    /// a list of tokens with the default tokenizer.
    macro_rules! expect_mapping {
        ($input:expr => $( $output:expr ),* ) => {
            expect_mapping_with!(Tokenizer::new($input.chars()) =>
                                 $( $output ),*);
        }
    }

    /// Expects a mapping from a string of tokens into
    /// a list of tokens, given a specific tokenizer.
    macro_rules! expect_mapping_with {
        // TODO: make the macro take several arguments
        // for several outputs
        ($tokenizer:expr => $( $output:expr ),* ) => {
            {
                let mut tokenizer = $tokenizer;

                $(
                    let token = tokenizer.next().unwrap().unwrap();
                    assert!($output == token,
                            format!("expected {} but got {}",
                                    $output, token));
                )*
            }
        }
    }

    #[test]
    fn test_string() {
        expect_mapping!("\"hello\"" =>  Token::string("hello"),
                                        Token::new_line(),
                                        Token::eof());

        expect_mapping!("\"hello abc\"" => Token::string("hello abc"),
                                           Token::new_line(),
                                           Token::eof());

        expect_mapping!("\"hello world\"  \"it is me\"" =>
                        Token::string("hello world"),
                        Token::string("it is me"),
                        Token::new_line(),
                        Token::eof());
    }

    #[test]
    fn test_integer() {
        expect_mapping!("123" => Token::integer(123),
                                 Token::new_line(),
                                 Token::eof());

        expect_mapping!("0982" => Token::integer(982),
                                  Token::new_line(),
                                  Token::eof());

        expect_mapping!("333 662" => Token::integer(333),
                                     Token::integer(662),
                                     Token::new_line(),
                                     Token::eof());

        expect_mapping!("1 2 3 4" => Token::integer(1),
                                     Token::integer(2),
                                     Token::integer(3),
                                     Token::integer(4),
                                     Token::new_line(),
                                     Token::eof());
    }

    #[test]
    fn test_word() {
        expect_mapping!("hello" => Token::word("hello"));

        expect_mapping!("ab cd" => Token::word("ab"),
                                   Token::word("cd"),
                                   Token::new_line(),
                                   Token::eof());

        expect_mapping!("a b c d" => Token::word("a"),
                                     Token::word("b"),
                                     Token::word("c"),
                                     Token::word("d"),
                                     Token::new_line(),
                                     Token::eof());
    }

    #[test]
    fn test_comments_not_preserved_by_default() {
        expect_mapping!("hello ; there" => Token::word("hello"),
                                           Token::new_line(),
                                           Token::eof());

        expect_mapping!(";why hello" => Token::new_line(),
                                        Token::eof());
    }

    #[test]
    fn test_comments() {
        expect_mapping_with!(Tokenizer::new("hello world ; this is me".chars())
                             .preserve_comments()
                             => Token::word("hello"),
                                Token::word("world"),
                                Token::comment(" this is me"),
                                Token::new_line(),
                                Token::eof());

        expect_mapping_with!(Tokenizer::new(";this is a test".chars())
                             .preserve_comments()
                             => Token::comment("this is a test"),
                                Token::new_line(),
                                Token::eof());
    }

    #[test]
    fn test_symbols() {
        expect_mapping!("(" => Token::symbol("("),
                               Token::new_line(),
                               Token::eof());

        expect_mapping!(")" => Token::symbol(")"));
        expect_mapping!("{ }" => Token::symbol("{"), Token::symbol("}"));
        expect_mapping!(":" => Token::symbol(":"));
        expect_mapping!("," => Token::symbol(","));
        expect_mapping!("@%" => Token::symbol("@"), Token::symbol("%"));
    }

    #[test]
    fn test_multiple() {
        expect_mapping!("12 bark \"earth\"" => Token::integer(12),
                                               Token::word("bark"),
                                               Token::string("earth"),
                                               Token::new_line(),
                                               Token::eof());

        expect_mapping!("a      23 gg \"a\"" => Token::word("a"),
                                                Token::integer(23),
                                                Token::word("gg"),
                                                Token::string("a"),
                                                Token::new_line(),
                                                Token::eof());

        expect_mapping!("4:3{2\n}" => Token::integer(4),
                                      Token::symbol(":"),
                                      Token::integer(3),
                                      Token::symbol("{"),
                                      Token::integer(2),
                                      Token::new_line(),
                                      Token::symbol("}"),
                                      Token::new_line(),
                                      Token::eof());
    }

    #[test]
    fn test_whitespace() {
        expect_mapping!("a\tb\t123\n\"qwer\"\n" => Token::word("a"),
                                                   Token::word("b"),
                                                   Token::integer(123),
                                                   Token::new_line(),
                                                   Token::string("qwer"),
                                                   Token::new_line(),
                                                   Token::new_line(),
                                                   Token::eof());
    }
}
<|endoftext|>


<commit_before>#[derive(Deserialize, Debug)]
pub struct Tweet {
    pub id: i64,
    pub text: String,
}

use std::fmt::{self, Display, Formatter};
impl Display for Tweet {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let mut txt = self.text.clone();
        if let Some(pos) = txt.find("http") {
            txt = txt[..pos].to_owned();
        }
        write!(f, "{}", txt)
    }
}
<commit_msg>Set tweet filter to include link<commit_after>#[derive(Deserialize, Debug)]
pub struct Tweet {
    pub id: i64,
    pub text: String,
}

use std::fmt::{self, Display, Formatter};
impl Display for Tweet {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let mut txt = self.text.clone();
        if let Some(pos) = txt.find("#") {
            txt = txt[..pos].to_owned();
        }
        write!(f, "{}", txt)
    }
}
<|endoftext|>


<commit_before>// rustfmt-indent_style: Block
// rustfmt-indent_style: Block
// rustfmt-indent_style: Block
// rustfmt-indent_style: Block

// #1357
impl<'a, Select, From, Distinct, Where, Order, Limit, Offset, Groupby, DB> InternalBoxedDsl<'a, DB>
    for SelectStatement<Select, From, Distinct, Where, Order, Limit, Offset, GroupBy>
where
    DB: Backend,
    Select: QueryFragment<DB> + SelectableExpression<From> + 'a,
    Distinct: QueryFragment<DB> + 'a,
    Where: Into<Option<Box<QueryFragment<DB> + 'a>>>,
    Order: QueryFragment<DB> + 'a,
    Limit: QueryFragment<DB> + 'a,
    Offset: QueryFragment<DB> + 'a,
{
    type Output = BoxedSelectStatement<'a, Select::SqlTypeForSelect, From, DB>;

    fn internal_into_boxed(self) -> Self::Output {
        BoxedSelectStatement::new(
            Box::new(self.select),
            self.from,
            Box::new(self.distinct),
            self.where_clause.into(),
            Box::new(self.order),
            Box::new(self.limit),
            Box::new(self.offset),
        )
    }
}

// #1369
impl<ExcessivelyLongGenericName, ExcessivelyLongGenericName, AnotherExcessivelyLongGenericName> Foo
    for Bar {
    fn foo() {}
}
impl Foo<ExcessivelyLongGenericName, ExcessivelyLongGenericName, AnotherExcessivelyLongGenericName>
    for Bar {
    fn foo() {}
}
impl<
    ExcessivelyLongGenericName,
    ExcessivelyLongGenericName,
    AnotherExcessivelyLongGenericName,
> Foo<ExcessivelyLongGenericName, ExcessivelyLongGenericName, AnotherExcessivelyLongGenericName>
    for Bar {
    fn foo() {}
}
impl<ExcessivelyLongGenericName, ExcessivelyLongGenericName, AnotherExcessivelyLongGenericName> Foo
    for Bar<
        ExcessivelyLongGenericName,
        ExcessivelyLongGenericName,
        AnotherExcessivelyLongGenericName,
    > {
    fn foo() {}
}
impl Foo<ExcessivelyLongGenericName, ExcessivelyLongGenericName, AnotherExcessivelyLongGenericName>
    for Bar<
        ExcessivelyLongGenericName,
        ExcessivelyLongGenericName,
        AnotherExcessivelyLongGenericName,
    > {
    fn foo() {}
}
impl<
    ExcessivelyLongGenericName,
    ExcessivelyLongGenericName,
    AnotherExcessivelyLongGenericName,
> Foo<ExcessivelyLongGenericName, ExcessivelyLongGenericName, AnotherExcessivelyLongGenericName>
    for Bar<
        ExcessivelyLongGenericName,
        ExcessivelyLongGenericName,
        AnotherExcessivelyLongGenericName,
    > {
    fn foo() {}
}

// #1689
impl<M, S, F, X> SubSelectDirect<M, S, F, X>
where
    M: select::Selector,
    S: event::Stream,
    F: for<'t> FnMut(transform::Api<'t, Stream<ContentStream<S>>>)
        -> transform::Api<'t, X>,
    X: event::Stream,
{
}
<commit_msg>Remove redundant options<commit_after>// rustfmt-indent_style: Block

// #1357
impl<'a, Select, From, Distinct, Where, Order, Limit, Offset, Groupby, DB> InternalBoxedDsl<'a, DB>
    for SelectStatement<Select, From, Distinct, Where, Order, Limit, Offset, GroupBy>
where
    DB: Backend,
    Select: QueryFragment<DB> + SelectableExpression<From> + 'a,
    Distinct: QueryFragment<DB> + 'a,
    Where: Into<Option<Box<QueryFragment<DB> + 'a>>>,
    Order: QueryFragment<DB> + 'a,
    Limit: QueryFragment<DB> + 'a,
    Offset: QueryFragment<DB> + 'a,
{
    type Output = BoxedSelectStatement<'a, Select::SqlTypeForSelect, From, DB>;

    fn internal_into_boxed(self) -> Self::Output {
        BoxedSelectStatement::new(
            Box::new(self.select),
            self.from,
            Box::new(self.distinct),
            self.where_clause.into(),
            Box::new(self.order),
            Box::new(self.limit),
            Box::new(self.offset),
        )
    }
}

// #1369
impl<ExcessivelyLongGenericName, ExcessivelyLongGenericName, AnotherExcessivelyLongGenericName> Foo
    for Bar {
    fn foo() {}
}
impl Foo<ExcessivelyLongGenericName, ExcessivelyLongGenericName, AnotherExcessivelyLongGenericName>
    for Bar {
    fn foo() {}
}
impl<
    ExcessivelyLongGenericName,
    ExcessivelyLongGenericName,
    AnotherExcessivelyLongGenericName,
> Foo<ExcessivelyLongGenericName, ExcessivelyLongGenericName, AnotherExcessivelyLongGenericName>
    for Bar {
    fn foo() {}
}
impl<ExcessivelyLongGenericName, ExcessivelyLongGenericName, AnotherExcessivelyLongGenericName> Foo
    for Bar<
        ExcessivelyLongGenericName,
        ExcessivelyLongGenericName,
        AnotherExcessivelyLongGenericName,
    > {
    fn foo() {}
}
impl Foo<ExcessivelyLongGenericName, ExcessivelyLongGenericName, AnotherExcessivelyLongGenericName>
    for Bar<
        ExcessivelyLongGenericName,
        ExcessivelyLongGenericName,
        AnotherExcessivelyLongGenericName,
    > {
    fn foo() {}
}
impl<
    ExcessivelyLongGenericName,
    ExcessivelyLongGenericName,
    AnotherExcessivelyLongGenericName,
> Foo<ExcessivelyLongGenericName, ExcessivelyLongGenericName, AnotherExcessivelyLongGenericName>
    for Bar<
        ExcessivelyLongGenericName,
        ExcessivelyLongGenericName,
        AnotherExcessivelyLongGenericName,
    > {
    fn foo() {}
}

// #1689
impl<M, S, F, X> SubSelectDirect<M, S, F, X>
where
    M: select::Selector,
    S: event::Stream,
    F: for<'t> FnMut(transform::Api<'t, Stream<ContentStream<S>>>)
        -> transform::Api<'t, X>,
    X: event::Stream,
{
}
<|endoftext|>


<commit_before>use backend::Backend;
use provider::error;
use provider::Provider;
use provider::Output;
use libc::uint32_t;

pub struct File<'a> {
    name: &'static str,
    backend: &'a Backend,
    provider: &'a Provider,
}

impl<'a> File<'a> {
    pub fn new(n: &'static str, b: &'a Backend, p: &'a Provider) -> File<'a> {
        File {
            name: n,
            backend: b,
            provider: p,
        }
    }

    pub fn mode(&self) -> Result<u32, error::Error> {
        self.backend
            .handle(self.provider.file.mode(self.name))
            .and_then(Output::to_u32)
    }

    pub fn size(&self) -> Result<i64, error::Error> {
        self.backend
            .handle(self.provider.file.size(self.name))
            .and_then(Output::to_i64)
    }

    pub fn is_file(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_file(self.name))
            .and_then(Output::to_bool)
    }

    pub fn exist(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.exist(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_directory(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_directory(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_block_device(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_block_device(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_character_device(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_character_device(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_pipe(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_pipe(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_socket(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_socket(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_symlink(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_symlink(self.name))
            .and_then(Output::to_bool)
    }

    pub fn contents(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.contents(self.name))
            .and_then(Output::to_string)
    }

    pub fn owner(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.owner(self.name))
            .and_then(Output::to_string)
    }

    pub fn group(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.group(self.name))
            .and_then(Output::to_string)
    }

    pub fn linked_to(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.linked_to(self.name))
            .and_then(Output::to_string)
    }

    pub fn is_readable(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_owner(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_owner(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_group(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_group(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_others(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_others(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_user(&self, user: &'static str) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_user(self.name, user))
            .and_then(Output::to_bool)
    }

    pub fn is_writable(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_owner(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_owner(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_group(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_group(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_others(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_others(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_user(&self, user: &'static str) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_user(self.name, user))
            .and_then(Output::to_bool)
    }

    pub fn md5sum(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.md5sum(self.name))
            .and_then(Output::to_string)
    }

    pub fn sha256sum(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.sha256sum(self.name))
            .and_then(Output::to_string)
    }
}

// Wrapper functions for FFI

#[no_mangle]
pub extern "C" fn resource_file_free(ptr: *mut File) {
    if ptr.is_null() {
        return;
    }
    unsafe {
        Box::from_raw(ptr);
    }
}

#[no_mangle]
pub extern "C" fn resource_file_mode(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    f.mode().unwrap()
}

#[no_mangle]
pub extern "C" fn resource_file_is_file(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_file().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_exist(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.exist().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_directory(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_directory().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_block_device(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_block_device().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_character_device(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_character_device().unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_pipe(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_pipe().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_socket(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_socket().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_symlink(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_symlink().unwrap() { 1 } else { 0 }
}
<commit_msg>Add wrapper function for file.contents()<commit_after>use backend::Backend;
use provider::error;
use provider::Provider;
use provider::Output;
use libc::{c_char, uint32_t};
use std::ffi::CString;

pub struct File<'a> {
    name: &'static str,
    backend: &'a Backend,
    provider: &'a Provider,
}

impl<'a> File<'a> {
    pub fn new(n: &'static str, b: &'a Backend, p: &'a Provider) -> File<'a> {
        File {
            name: n,
            backend: b,
            provider: p,
        }
    }

    pub fn mode(&self) -> Result<u32, error::Error> {
        self.backend
            .handle(self.provider.file.mode(self.name))
            .and_then(Output::to_u32)
    }

    pub fn size(&self) -> Result<i64, error::Error> {
        self.backend
            .handle(self.provider.file.size(self.name))
            .and_then(Output::to_i64)
    }

    pub fn is_file(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_file(self.name))
            .and_then(Output::to_bool)
    }

    pub fn exist(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.exist(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_directory(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_directory(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_block_device(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_block_device(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_character_device(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_character_device(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_pipe(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_pipe(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_socket(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_socket(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_symlink(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_symlink(self.name))
            .and_then(Output::to_bool)
    }

    pub fn contents(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.contents(self.name))
            .and_then(Output::to_string)
    }

    pub fn owner(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.owner(self.name))
            .and_then(Output::to_string)
    }

    pub fn group(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.group(self.name))
            .and_then(Output::to_string)
    }

    pub fn linked_to(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.linked_to(self.name))
            .and_then(Output::to_string)
    }

    pub fn is_readable(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_owner(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_owner(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_group(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_group(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_others(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_others(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_readable_by_user(&self, user: &'static str) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_readable_by_user(self.name, user))
            .and_then(Output::to_bool)
    }

    pub fn is_writable(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_owner(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_owner(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_group(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_group(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_others(&self) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_others(self.name))
            .and_then(Output::to_bool)
    }

    pub fn is_writable_by_user(&self, user: &'static str) -> Result<bool, error::Error> {
        self.backend
            .handle(self.provider.file.is_writable_by_user(self.name, user))
            .and_then(Output::to_bool)
    }

    pub fn md5sum(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.md5sum(self.name))
            .and_then(Output::to_string)
    }

    pub fn sha256sum(&self) -> Result<String, error::Error> {
        self.backend
            .handle(self.provider.file.sha256sum(self.name))
            .and_then(Output::to_string)
    }
}

// Wrapper functions for FFI

#[no_mangle]
pub extern "C" fn resource_file_free(ptr: *mut File) {
    if ptr.is_null() {
        return;
    }
    unsafe {
        Box::from_raw(ptr);
    }
}

#[no_mangle]
pub extern "C" fn resource_file_mode(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    f.mode().unwrap()
}

#[no_mangle]
pub extern "C" fn resource_file_is_file(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_file().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_exist(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.exist().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_directory(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_directory().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_block_device(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_block_device().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_character_device(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_character_device().unwrap() {
        1
    } else {
        0
    }
}

#[no_mangle]
pub extern "C" fn resource_file_is_pipe(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_pipe().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_socket(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_socket().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_is_symlink(ptr: *const File) -> uint32_t {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };

    if f.is_symlink().unwrap() { 1 } else { 0 }
}

#[no_mangle]
pub extern "C" fn resource_file_contents(ptr: *const File) -> *mut c_char {
    let f = unsafe {
        assert!(!ptr.is_null());
        &*ptr
    };
    let c = f.contents().unwrap();
    CString::new(c).unwrap().into_raw()
}
<|endoftext|>


<commit_before>use node_bucket::NodeBucket;
use address::{Address, Addressable, LENGTH};

pub struct RoutingTable<A: Addressable> {
    self_address: Address,
    buckets: Vec<NodeBucket<A>>
}

impl<A: Addressable> RoutingTable<A> {
    pub fn new(k: usize, self_address: Address) -> RoutingTable<A> {
        let bucket = NodeBucket::new(k);
        RoutingTable {
            self_address: self_address,
            buckets: vec![bucket]
        }
    }

    pub fn insert(&mut self, node: A) {
        self.bucket_for(&node.address(), {move |bucket|
            bucket.insert(node)
        });
    }

    fn bucket_for<F>(&mut self, address: &Address, func: F)
        where F : FnOnce(&mut NodeBucket<A>) -> () {
        let index: usize;
        let split: bool;
        let buckets_maxed = self.buckets_maxed();
        let self_address = self.self_address;
        {
            let (idx, mut bucket) = self.buckets
                .iter_mut()
                .enumerate()
                .find(|&(_, ref b)| b.covers(address))
                .unwrap();

            index = idx;
            split = !buckets_maxed && bucket.is_full() && bucket.covers(&self_address);
        }

        if split {
            let mut bucket = self.buckets.remove(index);
            let (a, b) = bucket.split();
            self.buckets.extend(vec![a, b]);
            self.bucket_for(address, func);
        } else {
            let ref mut bucket = self.buckets.get_mut(index).unwrap();
            func(bucket);
        }
    }

    fn buckets_maxed(&self) -> bool {
        self.buckets.len() >= LENGTH
    }
}

#[cfg(test)]
mod tests {
    use super::RoutingTable;
    use address::{Address, Addressable};

    #[derive(Clone,Copy,Debug,PartialEq,Eq)]
    struct TestNode {
        pub address: Address
    }

    impl TestNode {
        fn new(address: Address) -> TestNode {
            TestNode { address: address }
        }
    }

    impl Addressable for TestNode {
        fn address(&self) -> Address {
            self.address
        }
    }

    #[test]
    fn test_insert() {
        let self_node = Address::from_str("0000000000000000000000000000000000000000");
        let mut table: RoutingTable<TestNode> = RoutingTable::new(2, self_node);
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        table.insert(TestNode::new(Address::from_str("ffffffffffffffffffffffffffffffffffffffff")));
        assert_eq!(table.buckets.len(), 1);

        // Splits buckets upon adding a k+1th node in the same space as self node
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffe")));
        assert_eq!(table.buckets.len(), 2);
        table.insert(TestNode::new(Address::from_str("7fffffffffffffffffffffffffffffffffffffff")));
        table.insert(TestNode::new(Address::from_str("7ffffffffffffffffffffffffffffffffffffffe")));
        assert_eq!(table.buckets.len(), 3);

        // Replaces instead of duplicates existing nodes
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        assert_eq!(table.buckets.len(), 3);

        // Disregards new nodes for full, non-self space buckets
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffd")));
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffc")));
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffb")));
        assert_eq!(table.buckets.len(), 3);
    }
}
<commit_msg>Get rid of uneeded mutability<commit_after>use node_bucket::NodeBucket;
use address::{Address, Addressable, LENGTH};

pub struct RoutingTable<A: Addressable> {
    self_address: Address,
    buckets: Vec<NodeBucket<A>>
}

impl<A: Addressable> RoutingTable<A> {
    pub fn new(k: usize, self_address: Address) -> RoutingTable<A> {
        let bucket = NodeBucket::new(k);
        RoutingTable {
            self_address: self_address,
            buckets: vec![bucket]
        }
    }

    pub fn insert(&mut self, node: A) {
        self.bucket_for(&node.address(), {move |bucket|
            bucket.insert(node)
        });
    }

    fn bucket_for<F>(&mut self, address: &Address, func: F)
        where F : FnOnce(&mut NodeBucket<A>) -> () {
        let index: usize;
        let split: bool;
        let buckets_maxed = self.buckets_maxed();
        let self_address = self.self_address;
        {
            let (idx, bucket) = self.buckets
                .iter()
                .enumerate()
                .find(|&(_, ref b)| b.covers(address))
                .unwrap();

            index = idx;
            split = !buckets_maxed && bucket.is_full() && bucket.covers(&self_address);
        }

        if split {
            let mut bucket = self.buckets.remove(index);
            let (a, b) = bucket.split();
            self.buckets.extend(vec![a, b]);
            self.bucket_for(address, func);
        } else {
            let ref mut bucket = self.buckets.get_mut(index).unwrap();
            func(bucket);
        }
    }

    fn buckets_maxed(&self) -> bool {
        self.buckets.len() >= LENGTH
    }
}

#[cfg(test)]
mod tests {
    use super::RoutingTable;
    use address::{Address, Addressable};

    #[derive(Clone,Copy,Debug,PartialEq,Eq)]
    struct TestNode {
        pub address: Address
    }

    impl TestNode {
        fn new(address: Address) -> TestNode {
            TestNode { address: address }
        }
    }

    impl Addressable for TestNode {
        fn address(&self) -> Address {
            self.address
        }
    }

    #[test]
    fn test_insert() {
        let self_node = Address::from_str("0000000000000000000000000000000000000000");
        let mut table: RoutingTable<TestNode> = RoutingTable::new(2, self_node);
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        table.insert(TestNode::new(Address::from_str("ffffffffffffffffffffffffffffffffffffffff")));
        assert_eq!(table.buckets.len(), 1);

        // Splits buckets upon adding a k+1th node in the same space as self node
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffe")));
        assert_eq!(table.buckets.len(), 2);
        table.insert(TestNode::new(Address::from_str("7fffffffffffffffffffffffffffffffffffffff")));
        table.insert(TestNode::new(Address::from_str("7ffffffffffffffffffffffffffffffffffffffe")));
        assert_eq!(table.buckets.len(), 3);

        // Replaces instead of duplicates existing nodes
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        table.insert(TestNode::new(Address::from_str("0000000000000000000000000000000000000001")));
        assert_eq!(table.buckets.len(), 3);

        // Disregards new nodes for full, non-self space buckets
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffd")));
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffc")));
        table.insert(TestNode::new(Address::from_str("fffffffffffffffffffffffffffffffffffffffb")));
        assert_eq!(table.buckets.len(), 3);
    }
}
<|endoftext|>


<commit_before>use rustc_serialize::json::{ToJson, Json};
use std::collections::BTreeMap;
use super::Name;

impl ToJson for Name {

    /// Serializes a name into parsed components.
    ///
    /// ```
    /// # extern crate rustc_serialize;
    /// # extern crate human_name;
    /// #
    /// use human_name::Name;
    /// use rustc_serialize::json::ToJson;
    ///
    /// # fn main() {
    /// let name = Name::parse("JOHN ALLEN Q MACDONALD JR").unwrap();
    /// assert_eq!(
    ///   r#"{"first_initial":"J","given_name":"John","middle_initial":"AQ","middle_names":"Allen","suffix":"Jr.","surname":"MacDonald"}"#,
    ///   name.to_json().to_string()
    /// );
    /// # }
    /// ```
    fn to_json(&self) -> Json {
        let mut d = BTreeMap::new();
        d.insert("surname".to_string(), self.surname().to_json());
        d.insert("first_initial".to_string(),
                 format!("{}", self.first_initial()).to_json());
        if self.given_name().is_some() {
            d.insert("given_name".to_string(),
                     self.given_name().unwrap().to_json());
        }
        if self.middle_initials().is_some() {
            d.insert("middle_initial".to_string(),
                     self.middle_initials().unwrap().to_json());
        }
        if self.middle_names().is_some() {
            d.insert("middle_names".to_string(),
                     self.middle_name().unwrap().to_json());
        }
        if self.suffix().is_some() {
            d.insert("suffix".to_string(), self.suffix().unwrap().to_json());
        }
        Json::Object(d)
    }
}
<commit_msg>Typo fix in JSON serialization<commit_after>use rustc_serialize::json::{ToJson, Json};
use std::collections::BTreeMap;
use super::Name;

impl ToJson for Name {

    /// Serializes a name into parsed components.
    ///
    /// ```
    /// # extern crate rustc_serialize;
    /// # extern crate human_name;
    /// #
    /// use human_name::Name;
    /// use rustc_serialize::json::ToJson;
    ///
    /// # fn main() {
    /// let name = Name::parse("JOHN ALLEN Q MACDONALD JR").unwrap();
    /// assert_eq!(
    ///   r#"{"first_initial":"J","given_name":"John","middle_initials":"AQ","middle_names":"Allen","suffix":"Jr.","surname":"MacDonald"}"#,
    ///   name.to_json().to_string()
    /// );
    /// # }
    /// ```
    fn to_json(&self) -> Json {
        let mut d = BTreeMap::new();
        d.insert("surname".to_string(), self.surname().to_json());
        d.insert("first_initial".to_string(),
                 format!("{}", self.first_initial()).to_json());
        if self.given_name().is_some() {
            d.insert("given_name".to_string(),
                     self.given_name().unwrap().to_json());
        }
        if self.middle_initials().is_some() {
            d.insert("middle_initials".to_string(),
                     self.middle_initials().unwrap().to_json());
        }
        if self.middle_names().is_some() {
            d.insert("middle_names".to_string(),
                     self.middle_name().unwrap().to_json());
        }
        if self.suffix().is_some() {
            d.insert("suffix".to_string(), self.suffix().unwrap().to_json());
        }
        Json::Object(d)
    }
}
<|endoftext|>


<commit_before>extern crate crypto;

use std::env;
use std::process;
use std::str::FromStr;

fn main() {
    let args: Vec<_> = env::args().collect();
    if args.len() < 2 {
        println!("Warning: No key was input! Please input a key to run!");
        process::exit(1);
    }

    let key = args[1];
    let md5 = Md5::new();

    for i in (0..std::u64::MAX) {
        md5.input(&key);
        md5.input(i);

        let out: String = md5.result_str();

        let first_five = i32::from_str(out[..5]);
    }
}
<commit_msg>More progress on day 4<commit_after>extern crate crypto;

use std::env;
use std::process;
use std::str::FromStr;
use crypto::md5::Md5;
use crypto::digest::Digest;

fn main() {
    let args: Vec<_> = env::args().collect();
    if args.len() < 2 {
        println!("Warning: No key was input! Please input a key to run!");
        process::exit(1);
    }

    let key = args[1].clone();
    let mut md5 = Md5::new();

    for i in 0..std::u64::MAX {
        let temp_key: String = key + &i.to_string();
        md5.input(temp_key.as_bytes());

        let out: String = md5.result_str();

        let first_five = i32::from_str(&out[..5]);
    }
}
<|endoftext|>