<commit_before>use collections::VecDeque;
// Temporary hack until libredox get hashmaps
use collections::btree_map::BTreeMap as HashMap;  //redox::HashMap;
use redox::*;

#[derive(Clone, Copy, Hash)]
pub enum InsertMode {
    Append,
    Insert,
    Replace,
}

#[derive(Clone, Copy, Hash)]
pub struct InsertOptions {
    mode: InsertMode,
}

/// A mode
#[derive(Clone, Copy, Hash)]
pub enum Mode {
    /// A primitive mode (no repeat, no delimiters, no preprocessing)
    Primitive(PrimitiveMode),
    /// Command mode
    Command(CommandMode),
}

/// A command mode
pub enum CommandMode {
//    Visual(VisualOptions),
    /// Normal mode
    Normal,
}

/// A primitive mode
pub enum PrimitiveMode {
    /// Insert mode
    Insert(InsertOptions),
}

#[derive(Clone, Hash)]
pub enum Unit {
    /// Single [repeated] instruction
    Inst(u16, char),
    /// Multiple instructions
    Block(u16, Vec<Unit>),
}

#[derive(Clone, Hash)]
/// The state of the editor
pub struct State {
    /// The current cursor
    pub current_cursor: u8,
    /// The cursors
    pub cursors: Vec<Cursor>,
    /// The text (document)
    pub text: VecDeque<VecDeque<char>>,
    /// The x coordinate of the scroll
    pub scroll_x: u32,
    /// The y coordinate of the scroll
    pub scroll_y: u32,
}

impl State {
    fn new() -> State {
        State {
            current_cursor: 0,
            cursors: Vec::new(),
            text: VecDeque::new(),
            scroll_x: 0,
            scroll_y: 0,
        }
    }
}

/// A command char
pub enum CommandChar {
    /// A char
    Char(char),
    /// A wildcard
    Wildcard,
}

#[derive(Clone, Hash)]
/// The editor
pub struct Editor<I: Iterator<Item = Unit>> {
    /// The state of the editor
    pub state: State,
    /// The commands
    pub commands: HashMap<Mode,
                          HashMap<CommandChar,
                                  FnMut<(u16, &mut State, &mut I, char)>>>,
}

impl<I: Iterator<Item = Unit>> Editor<I> {
    pub fn new() -> Self {
        let mut commands = HashMap::new();
        commands.insert(Mode::Primitive(PrimitiveMode::Insert), {
            let mut hm = HashMap::new();
            hm.insert(CommandChar::Wildcard, |_, state, iter, c| {
                state.insert(c);
            });
            hm
        });
        Editor {
            state: State::new(),
            commands: commands,
        }
    }

    pub fn exec(&mut self, cmd: &Unit) {
        let mut commands = self.commands.get(self.mode).unwrap();

        match *cmd {
            Unit::Single(n, c) => {
                commands.get(c).call((n, &mut self.state, self.cmd.iter(), c));
            },
            Unit::Block(n, units) => {
                for _ in 1..n {
                    for &i in units {
                        self.exec(i);
                    }
                }
            },
        }
    }
}

#[derive(Clone, Hash)]
/// A cursor
pub struct Cursor {
    /// The x coordinate of the cursor
    pub x: u32,
    /// The y coordinate of the cursor
    pub y: u32,
    /// The mode of the cursor
    pub mode: Mode,
    /// The history of the cursor
    pub history: Vec<Unit>,
}

#[derive(Clone, Hash)]
/// An iterator over units
pub struct UnitIterator<'a, I: Iterator<Item = char>> {
    /// The iterator over the chars
    char_iter: &'a mut I,
    /// The state
    state: &'a mut State,
}

impl<'a, I: Iterator<Item = char>> Iterator for UnitIterator<'a, I> {
    type Item = Unit;

    fn next(&mut self) -> Unit {
        match self.cursors[self.cursor as usize].mode {
            Mode::Primitive(_) => Unit::Single(1, self.char_iter.next().unwrap()),
            Mode::Command(_) => {
                let mut ch = self.first().unwrap_or('\0');
                let mut n = 1;

                let mut unset = true;
                for c in self.char_iter {
                    n = match c {
                        '0' if n != 0 => n * 10,
                        '1'           => n * 10 + 1,
                        '2'           => n * 10 + 2,
                        '3'           => n * 10 + 3,
                        '4'           => n * 10 + 4,
                        '5'           => n * 10 + 5,
                        '6'           => n * 10 + 6,
                        '7'           => n * 10 + 7,
                        '8'           => n * 10 + 8,
                        '9'           => n * 10 + 9,
                        _             => {
                            ch = c;
                            break;
                        },
                    };

                    if unset {
                        unset = false;
                        n     = 0;
                    }
                }

                if ch == '(' {
                    let mut level = 0;
                    *self = self.take_while(|c| {
                        level = match c {
                            '(' => level + 1,
                            ')' => level - 1,
                            ';' => 0,
                        }
                    }).skip(1).reverse().skip(1).reverse().unit_iter();
                    Unit::Block(n, self.collect())
                } else if let Some(ch) = self.char_iter.next() {
                    Unit::Inst(n, ch)
                }
            }
        }
    }
}

impl<I: Iterator<Item = char>> I {
    /// Create a iterator of the unit given by the chars
    pub fn unit_iter<'a>(&'a self, state: &'a mut State) -> UnitIterator<'a, I> {
        UnitIterator {
            char_iter: &mut *self,
            state: state,
        }
    }
}
<commit_msg>More work on sodium<commit_after>use collections::VecDeque;
// Temporary hack until libredox get hashmaps
use redox::*;

/// A temporary, very slow replacement for HashMaps, until redox::collections is finish.
pub struct HashMapTmp<K, V> {
    data: Vec<(K, V)>,
}
impl<K: PartialEq, V> HashMapTmp<K, V> {
    pub fn get(&self, key: &K) -> Option<&V> {
        match self.data.iter().find(|(k, _)| {
            k == *key
        }) {
            Some((k, ref v)) => Some(v),
            None => None
        }
    }
    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        match self.data.iter().find(|(k, _)| {
            k == *key
        }) {
            Some((k, ref mut v)) => Some(v),
            None => None
        }
    }
    pub fn insert(&mut self, key: K, value: V) -> Option<V> {
        let old = self.get_mut(&key);

        match old {
            Some(v) => {
                *v = value;
                Some(*v)
            },
            None => {
                self.data.push((key, value));
                None
            },
        }
    }
}

type Map<K, V> = HashMapTmp<K, V>;

#[derive(Clone, PartialEq, Copy, Hash)]
pub enum InsertMode {
    Append,
    Insert,
    Replace,
}

#[derive(Clone, PartialEq, Copy, Hash)]
pub struct InsertOptions {
    mode: InsertMode,
}

/// A mode
#[derive(Clone, PartialEq, Copy, Hash)]
pub enum Mode {
    /// A primitive mode (no repeat, no delimiters, no preprocessing)
    Primitive(PrimitiveMode),
    /// Command mode
    Command(CommandMode),
}

#[derive(Clone, PartialEq, Copy, Hash)]
/// A command mode
pub enum CommandMode {
//    Visual(VisualOptions),
    /// Normal mode
    Normal,
}

#[derive(Clone, PartialEq, Copy, Hash)]
/// A primitive mode
pub enum PrimitiveMode {
    /// Insert mode
    Insert(InsertOptions),
}

#[derive(Clone, PartialEq, Hash)]
pub enum Unit {
    /// Single [repeated] instruction
    Inst(u16, char),
    /// Multiple instructions
    Block(u16, Vec<Unit>),
}

#[derive(Clone, PartialEq, Hash)]
/// The state of the editor
pub struct State {
    /// The current cursor
    pub current_cursor: u8,
    /// The cursors
    pub cursors: Vec<Cursor>,
    /// The text (document)
    pub text: VecDeque<VecDeque<char>>,
    /// The x coordinate of the scroll
    pub scroll_x: u32,
    /// The y coordinate of the scroll
    pub scroll_y: u32,
}

impl State {
    fn new() -> State {
        State {
            current_cursor: 0,
            cursors: Vec::new(),
            text: VecDeque::new(),
            scroll_x: 0,
            scroll_y: 0,
        }
    }
}

/// A command char
#[derive(Clone, Copy, Hash, PartialEq)]
pub enum CommandChar {
    /// A char
    Char(char),
    /// A wildcard
    Wildcard,
}

#[derive(Clone, PartialEq, Hash)]
/// The editor
pub struct Editor<'a, I: Iterator<Item = Unit>> {
    /// The state of the editor
    pub state: State,
    /// The commands
    pub commands: Map<Mode,
                      Map<CommandChar,
                          Box<FnOnce(u16, &'a mut State, &'a mut I, char)>>>,
}

impl<'a, I: Iterator<Item = Unit>> Editor<'a, I> {
    pub fn new() -> Self {
        let mut commands = Map::new();
        commands.insert(Mode::Primitive(PrimitiveMode::Insert), {
            let mut hm = Map::new();
            hm.insert(CommandChar::Wildcard, |_, state, iter, c| {
                state.insert(c);
            });
            hm
        });
        Editor {
            state: State::new(),
            commands: commands,
        }
    }

    pub fn exec(&mut self, cmd: &Unit) {
        let mut commands = self.commands.get(&self.mode).unwrap();

        match *cmd {
            Unit::Inst(n, c) => {
                commands.get(&c).call((n, &mut self.state, self.cmd.iter(), c));
            },
            Unit::Block(n, units) => {
                for _ in 1..n {
                    for &i in units {
                        self.exec(i);
                    }
                }
            },
        }
    }
}

#[derive(Clone, PartialEq, Hash)]
/// A cursor
pub struct Cursor {
    /// The x coordinate of the cursor
    pub x: u32,
    /// The y coordinate of the cursor
    pub y: u32,
    /// The mode of the cursor
    pub mode: Mode,
    /// The history of the cursor
    pub history: Vec<Unit>,
}

#[derive(Clone, PartialEq, Hash)]
/// An iterator over units
pub struct UnitIterator<'a, I: Iterator<Item = char> + 'a> {
    /// The iterator over the chars
    char_iter: &'a mut I,
    /// The state
    state: &'a mut State,
}

impl<'a, I: Iterator<Item = char>> Iterator for UnitIterator<'a, I> {
    type Item = Unit;

    fn next(&mut self) -> Option<Unit> {
        match self.cursors[self.cursor as usize].mode {
            Mode::Primitive(_) => Unit::Inst(1, match self.char_iter.next() {
                Some(c) => c,
                None => return None,
            }),
            Mode::Command(_) => {
                let mut ch = self.first().unwrap_or('\0');
                let mut n = 1;

                let mut unset = true;
                for c in self.char_iter {
                    n = match c {
                        '0' if n != 0 => n * 10,
                        '1'           => n * 10 + 1,
                        '2'           => n * 10 + 2,
                        '3'           => n * 10 + 3,
                        '4'           => n * 10 + 4,
                        '5'           => n * 10 + 5,
                        '6'           => n * 10 + 6,
                        '7'           => n * 10 + 7,
                        '8'           => n * 10 + 8,
                        '9'           => n * 10 + 9,
                        _             => {
                            ch = c;
                            break;
                        },
                    };

                    if unset {
                        unset = false;
                        n     = 0;
                    }
                }

                if ch == '(' {
                    let mut level = 0;
                    *self = self.take_while(|c| {
                        level = match c {
                            '(' => level + 1,
                            ')' => level - 1,
                            ';' => 0,
                        }
                    }).skip(1).reverse().skip(1).reverse().unit_iter();
                    Some(Unit::Block(n, self.collect()))
                } else if let Some(ch) = self.char_iter.next() {
                    Some(Unit::Inst(n, ch))
                } else {
                    None
                }
            }
        }
    }
}

pub trait ToUnitIterator: Iterator<Item = char> {
    /// Create a iterator of the unit given by the chars
    fn unit_iter<'a>(&'a self, state: &'a mut State) -> UnitIterator<'a, Self>;
}

impl<I: Iterator<Item = char>> ToUnitIterator for I {
    fn unit_iter<'a>(&'a self, state: &'a mut State) -> UnitIterator<'a, I> {
        UnitIterator {
            char_iter: &mut *self,
            state: state,
        }
    }
}
<|endoftext|>


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

// Check that we correctly prevent users from making trait objects
// from traits with associated consts.

trait Bar {
    const X: usize;
}

fn make_bar<T:Bar>(t: &T) -> &Bar {
    //~^ ERROR E0038
    //~| NOTE the trait cannot contain associated consts like `X`
    //~| NOTE the trait `Bar` cannot be made into an object
    t
}

fn main() {
}
<commit_msg>Feature gate in 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.

// Check that we correctly prevent users from making trait objects
// from traits with associated consts.

#![feature(associated_consts)]

trait Bar {
    const X: usize;
}

fn make_bar<T:Bar>(t: &T) -> &Bar {
    //~^ ERROR E0038
    //~| NOTE the trait cannot contain associated consts like `X`
    //~| NOTE the trait `Bar` cannot be made into an object
    t
}

fn main() {
}
<|endoftext|>


<commit_before><commit_msg>add test for generics<commit_after>#[macro_use]
extern crate optional_struct;

#[derive(OptionalStruct)]
struct GenericConfig<T: std::fmt::Debug, V> {
    value_t: T,
    value_v: V,
}

#[test]
fn test_apply_options() {
    let mut config = GenericConfig {
        value_t: 3.0,
        value_v: "foo",
    };

    let opt_config = OptionalGenericConfig {
        value_t: None,
        value_v: Some("bar"),
    };

    config.apply_options(opt_config);

    assert_eq!(config.value_t, 3.0);
    assert_eq!(config.value_v, "bar");
}
<|endoftext|>


<commit_before><commit_msg>A frame module.<commit_after>use packets;
use std::iter;
use std::cmp;
use std::convert::From;
use std::borrow;

//This has to be small enough to leave room for the header.
const CHUNK_SIZE: usize = 500;

#[derive(Debug)]
pub struct FrameEncoder<'A, T: 'A> {
    channel: i16,
    sn: u64,
    last_reliable_frame: u64,
    reliable: bool,
    first: bool,
    iter: &'A mut T,
    workspace: Vec<u8>,
}

impl<'A, T, Q> FrameEncoder<'A, T>
where T: iter::ExactSizeIterator+iter::Iterator<Item=Q>,
Q: borrow::Borrow<u8>,
Vec<u8>: iter::Extend<Q> {
    pub fn new(iter: &'A mut T, channel: i16, starting_sequence_number: u64, last_reliable_frame: u64, reliable: bool)->FrameEncoder<'A, T> {
        FrameEncoder {
            channel: channel,
            sn: starting_sequence_number,
            last_reliable_frame: last_reliable_frame,
            reliable: reliable,
            first: true,
            iter: iter,
            workspace: Vec::with_capacity(CHUNK_SIZE),
        }
    }
}

impl<'A, T, Q> iter::Iterator for FrameEncoder<'A, T>
where T: iter::ExactSizeIterator+iter::Iterator<Item=Q>,
Q: borrow::Borrow<u8>,
Vec<u8>: iter::Extend<Q> {
    type Item = packets::Packet;

    fn next(&mut self)->Option<packets::Packet> {
        let mut header = None;
        if self.first {
            let length = packets::FRAME_HEADER_SIZE+self.iter.len();
            header = Some(packets::FrameHeader{last_reliable_frame: self.last_reliable_frame, length: length as u32});
        }
        //Get some bytes.
        self.workspace.clear();
        self.workspace.extend(self.iter.take(CHUNK_SIZE));
        if self.first == false && self.workspace.len() == 0 {return None;}
        let dp = packets::DataPacketBuilder::with_payload_and_header(self.sn, self.workspace.clone(), header)
        .set_reliable(self.reliable)
        .set_frame_start(self.first)
        .set_frame_end(self.iter.len() == 0)
        .build();
        self.first = false;
        self.sn += 1;
        return Some(packets::Packet::Data{chan: self.channel, packet: dp});
    }
}

#[test]
fn test_frames() {
    let test_data: Vec<u8> = vec![1u8; 1000];
    //channel 100, start at sn 3, last reliable is 1.
    let mut got_packets = FrameEncoder::new(&mut test_data.iter(), 100, 3, 1, false).collect::<Vec<_>>();
    let mut expected_packets = vec![
        packets::Packet::Data{chan: 100,
            packet: packets::DataPacketBuilder::with_payload_and_header(3, vec![1u8; 500], Some(packets::FrameHeader{length: 1012, last_reliable_frame: 1})).build()
        },
        packets::Packet::Data{chan: 100,
            packet: packets::DataPacketBuilder::with_payload(4, vec![1u8; 500]).set_frame_end(true).build()
        }
    ];
    assert_eq!(got_packets, expected_packets);
    got_packets = FrameEncoder::new(&mut test_data.iter(), 100, 3, 1, true).collect();
    expected_packets = vec![
        packets::Packet::Data{chan: 100,
            packet: packets::DataPacketBuilder::with_payload_and_header(3, vec![1u8; 500], Some(packets::FrameHeader{length: 1012, last_reliable_frame: 1})).set_reliable(true).build()
        },
        packets::Packet::Data{chan: 100,
            packet: packets::DataPacketBuilder::with_payload(4, vec![1u8; 500]).set_reliable(true).set_frame_end(true).build(),
        }
    ];
    assert_eq!(got_packets, expected_packets);
}
<|endoftext|>


<commit_before><commit_msg>Add scope tests<commit_after>#[macro_use]
pub mod compiler_test;

compiler_tests! {
    child_references_parent: "a = 1; { a + 2 }" => type(3),
    child_references_parent_too_early_error: "{ a + 2 }; a = 1" => error(NoSuchProperty@2) type(nothing),
    child_references_parent_container_error: "a = { a + 1 }" => error(NoSuchProperty@6) type(nothing),
    child_defines_value_early: "x = { a = 1; a+2 }; a = x + 3; a" => type(6),
    child_updates_parent: "a = 1; { a += 2 }; a + 3" => type(6),
    child_overwrites_parent: "a = 1; { a = 2 }; a + 3" => type(5),
    child_overwrites_and_references_parent: "a = 1; { a = 2; a + 3 } + a" => type(7),
    parent_references_child_error: "{ a = 0; a }; a" => error(NoSuchProperty@14) type(error),
}
<|endoftext|>


<commit_before><commit_msg>Added Huffman encoding program<commit_after>extern crate collections;
use collections::HashMap;
use collections::priority_queue::PriorityQueue;

// Implement data structures for a Huffman encoding tree

// Each HNode has a weight, representing the sum of the frequencies for all its
// children. It is either a leaf (containing a character), or a HTree
// (containing two children)
#[deriving(Show)]
struct HNode {
    weight: int,
    item: HTreeOrHLeaf,
}

#[deriving(Show)]
enum HTreeOrHLeaf {
    HTree(HTreeData),
    HLeaf(char),
}

#[deriving(Show)]
struct HTreeData {
    left: Box<HNode>,
    right: Box<HNode>,
}

// Implementing comparison traits (TotalOrd and all its dependencies) such that
// the HNode with the greatest weight is the smallest in a comparison. Basically
// reversing all the comparison operators.
impl TotalOrd for HNode {
    fn cmp(&self, other: &HNode) -> Ordering {
        match self.weight.cmp(&other.weight) {
            Less    => Greater,
            Equal   => Equal,
            Greater => Less,
        }
    }
}

impl TotalEq for HNode {}

impl Eq for HNode {
    fn eq(&self, other: &HNode) -> bool {
        self.weight == other.weight
    }
    fn ne(&self, other: &HNode) -> bool {
        ! self.eq(other)
    }
}

impl Ord for HNode {
    fn lt(&self, other: &HNode) -> bool {
        self.weight > other.weight
    }
    fn le(&self, other: &HNode) -> bool {
        self.weight >= other.weight
    }
    fn gt(&self, other: &HNode) -> bool {
        self.weight < other.weight
    }
    fn ge(&self, other: &HNode) -> bool {
        self.weight <= other.weight
    }
}

// Takes a non-empty string (function will fail if string is empty) and computes
// the Huffman encoding tree for that string.
fn huffmanTree(input: &str) -> HNode {
    // 1. Loop through all the characters in that string, adding them to a HashMap
    //    of character to frequency.
    let mut freq = HashMap::new();
    for ch in input.chars() {
        freq.insert_or_update_with(ch, 1, |_k, v: &mut int| {*v += 1;});
    }

    // 2. For each (character, frequency) pair in the HashMap, add a Leaf to a
    //    PriorityQueue
    let mut queue = PriorityQueue::<HNode>::new();
    for (ch, freq) in freq.iter() {
        let newNode = HNode{
            weight: *freq,
            item: HLeaf(*ch),
        };
        queue.push(newNode);
    }

    // 3. Pop two items with the least weight from the queue, combine them into
    //    a tree as children. The parent node's weight is the sum of the
    //    children's weight. Continue until one item is left on the queue, and
    //    return that item.
    while queue.len() > 1 {
        let item1 = queue.pop().unwrap();
        let item2 = queue.pop().unwrap();
        let newNode = HNode {
            weight: item1.weight + item2.weight,
            item: HTree(HTreeData{
                left: box item1,
                right: box item2,
            }),
        };
        queue.push(newNode);
    }
    queue.pop().unwrap()
}

// Takes a Huffman Tree, traverse it and build a table with each character and
// its encoding string.
fn buildEncodingTable(tree: &HNode,
                      table: &mut HashMap<char,String>,
                      startStr: &str) {
    match tree.item {
        HTree(ref data) => {
            buildEncodingTable(data.left, table,
                               String::from_str(startStr).append("0").as_slice());
            buildEncodingTable(data.right, table,
                               String::from_str(startStr).append("1").as_slice());
        },
        HLeaf(ch)   => {table.insert(ch, String::from_str(startStr));}
    };
}

// Attempts to construct a tree, and test that the construction is successful
//    7
//   ----
//  /    \
// 4:'4'  3
//      -----
//     /     \
//    2:'2'  1:'1'
#[test]
fn testTreeConstruction() {
    let to_encode = "4444221";
    let tree = huffmanTree(to_encode);
    assert!(tree.weight == 7);
    let children = match tree.item {
        HTree(data) => data,
        HLeaf(_)    => fail!("Tree Missing Children!"),
    };
    let left  = &children.left;
    let right = &children.right;
    assert!(right.weight == 4);
    assert!(left.weight == 3);
    let rightChar = match right.item {
        HTree(_)  => fail!("Node is not Leaf Node!"),
        HLeaf(ch) => ch,
    };
    assert!(rightChar == '4');
    let children = match left.item {
        HTree(ref data) => data,
        HLeaf(_)    => fail!("Tree Missing Children!"),
    };
    let left  = &children.left;
    let right = &children.right;
    let leftChar = match left.item {
        HTree(_)  => fail!("Node is not Leaf Node!"),
        HLeaf(ch) => ch,
    };
    let rightChar = match right.item {
        HTree(_)  => fail!("Node is not Leaf Node!"),
        HLeaf(ch) => ch,
    };
    match (left.weight, right.weight) {
        (1, 2) => {
            assert!(leftChar == '1');
            assert!(rightChar == '2');
        },
        (2, 1) => {
            assert!(leftChar == '2');
            assert!(rightChar == '1');
        },
        (_, _) => {
            fail!("Incorrect Leaf Nodes");
        }
    };
}

#[test]
// Constructs a table:
//  '4': 1
//  '2': 01 OR 00
//  '1': 00    01
// And tests that the table was correctly constructed
fn testTableConstruction() {
    let to_encode = "4444221";
    let tree = huffmanTree(to_encode);
    let mut table = HashMap::<char,String>::new();
    buildEncodingTable(&tree, &mut table, "");
    let one  = table.get(&'1').as_slice();
    let two  = table.get(&'2').as_slice();
    let four = table.get(&'4').as_slice();
    assert!(four == "1");
    assert!((one == "01" && two == "00") ||
            (one == "00" && two == "01"));
}

#[cfg(not(test))]
fn main() {
    let to_encode = "this is an example for huffman encoding";
    let tree = huffmanTree(to_encode);
    let mut table = HashMap::<char,String>::new();
    buildEncodingTable(&tree, &mut table, "");

    for (ch, encoding) in table.iter() {
        println!("{}: {}", *ch, encoding);
    }
}
<|endoftext|>


<commit_before><commit_msg>blank message<commit_after><|endoftext|>


<commit_before><commit_msg>Trying out tokio getting started<commit_after>extern crate futures;
extern crate tokio_core;
extern crate tokio_proto;
extern crate tokio_service;

use std::io;
use tokio_core::io::{Codec, EasyBuf};

pub struct LineCodec;   // Codecs may need a local state, potentially recording information about
                        // incomplete decoding/encoding

fn main() {

}
<|endoftext|>


<commit_before><commit_msg>all state encoded now<commit_after><|endoftext|>


<commit_before><commit_msg>still bad<commit_after>pub struct GraphQuery {
    pub blah: i64
}

pub struct GlobalQuery;

pub struct VertexQuery;
<|endoftext|>


<commit_before>#![crate_name = "wc"]

/*
 * This file is part of the uutils coreutils package.
 *
 * (c) Boden Garman <bpgarman@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#![feature(macro_rules)]

extern crate getopts;
extern crate libc;

use std::str::from_utf8;
use std::io::{print, File, BufferedReader};
use std::io::fs::PathExtensions;
use std::io::stdio::stdin_raw;
use std::result::Result as StdResult;
use getopts::Matches;

#[path = "../common/util.rs"]
mod util;

struct Result {
    filename: String,
    bytes: uint,
    chars: uint,
    lines: uint,
    words: uint,
    max_line_length: uint,
}

static NAME: &'static str = "wc";

pub fn uumain(args: Vec<String>) -> int {
    let program = args[0].clone();
    let opts = [
        getopts::optflag("c", "bytes", "print the byte counts"),
        getopts::optflag("m", "chars", "print the character counts"),
        getopts::optflag("l", "lines", "print the newline counts"),
        getopts::optflag("L", "max-line-length", "print the length of the longest line"),
        getopts::optflag("w", "words", "print the word counts"),
        getopts::optflag("h", "help", "display this help and exit"),
        getopts::optflag("V", "version", "output version information and exit"),
    ];

    let matches = match getopts::getopts(args.tail(), &opts) {
        Ok(m) => m,
        Err(f) => {
            crash!(1, "Invalid options\n{}", f)
        }
    };

    if matches.opt_present("help") {
        println!("Usage:");
        println!("  {0} [OPTION]... [FILE]...", program);
        println!("");
        print(getopts::usage("Print newline, word and byte counts for each FILE", &opts).as_slice());
        println!("");
        println!("With no FILE, or when FILE is -, read standard input.");
        return 0;
    }

    if matches.opt_present("version") {
        println!("wc 1.0.0");
        return 0;
    }

    let mut files = matches.free.clone();
    if files.is_empty() {
        files = vec!("-".to_string());
    }

    match wc(files, &matches) {
        Ok(()) => ( /* pass */ ),
        Err(e) => return e
    }

    0
}

static CR: u8 = '\r' as u8;
static LF: u8 = '\n' as u8;
static SPACE: u8 = ' ' as u8;
static TAB: u8 = '\t' as u8;
static SYN: u8 = 0x16 as u8;
static FF: u8 = 0x0C as u8;

#[inline(always)]
fn is_word_seperator(byte: u8) -> bool {
    byte == SPACE || byte == TAB || byte == CR || byte == SYN || byte == FF
}

pub fn wc(files: Vec<String>, matches: &Matches) -> StdResult<(), int> {
    let mut total_line_count: uint = 0;
    let mut total_word_count: uint = 0;
    let mut total_char_count: uint = 0;
    let mut total_byte_count: uint = 0;
    let mut total_longest_line_length: uint = 0;

    let mut results = vec!();
    let mut max_str_len: uint = 0;

    for path in files.iter() {
        let mut reader = match open(path.to_string()) {
            Ok(f) => f,
            Err(e) => { return Err(e); }
        };

        let mut line_count: uint = 0;
        let mut word_count: uint = 0;
        let mut byte_count: uint = 0;
        let mut char_count: uint = 0;
        let mut current_char_count: uint = 0;
        let mut longest_line_length: uint = 0;

        loop {
            // reading from a TTY seems to raise a condition on, rather than return Some(0) like a file.
            // hence the option wrapped in a result here
            match reader.read_until(LF) {
                Ok(raw_line) => {
                    // GNU 'wc' only counts lines that end in LF as lines
                    if raw_line.iter().last().unwrap() == &LF {
                        line_count += 1;
                    }

                    byte_count += raw_line.iter().len();

                    // try and convert the bytes to UTF-8 first
                    match from_utf8(raw_line.as_slice()) {
                        Some(line) => {
                            word_count += line.words().count();
                            current_char_count = line.chars().count();
                            char_count += current_char_count;
                        },
                        None => {
                            word_count += raw_line.as_slice().split(|&x| is_word_seperator(x)).count();
                            for byte in raw_line.iter() {
                                match byte.is_ascii() {
                                    true => {
                                        current_char_count += 1;
                                    }
                                    false => { }
                                }
                            }
                            char_count += current_char_count;
                        }
                    }

                    if current_char_count > longest_line_length {
                        // we subtract one here because `line.iter().len()` includes the LF
                        // matches GNU 'wc' behaviour
                        longest_line_length = current_char_count - 1;
                    }
                },
                _ => break
            }

        }

        results.push(Result {
            filename: path.to_string(),
            bytes: byte_count,
            chars: char_count,
            lines: line_count,
            words: word_count,
            max_line_length: longest_line_length,
        });

        total_line_count += line_count;
        total_word_count += word_count;
        total_char_count += char_count;
        total_byte_count += byte_count;

        if longest_line_length > total_longest_line_length {
            total_longest_line_length = longest_line_length;
        }

        // used for formatting
        max_str_len = total_byte_count.to_string().len();
    }

    for result in results.iter() {
        print_stats(result.filename.as_slice(), result.lines, result.words, result.chars, result.bytes, result.max_line_length, matches, max_str_len);
    }

    if files.len() > 1 {
        print_stats("total", total_line_count, total_word_count, total_char_count, total_byte_count, total_longest_line_length, matches, max_str_len);
    }

    Ok(())
}

fn print_stats(filename: &str, line_count: uint, word_count: uint, char_count: uint,
    byte_count: uint, longest_line_length: uint, matches: &Matches, max_str_len: uint) {
    if matches.opt_present("lines") {
        print!("{:1$}", line_count, max_str_len);
    }
    if matches.opt_present("words") {
        print!("{:1$}", word_count, max_str_len);
    }
    if matches.opt_present("bytes") {
        print!("{:1$}", byte_count, max_str_len);
    }
    if matches.opt_present("chars") {
        print!("{:1$}", char_count, max_str_len);
    }
    if matches.opt_present("max-line-length") {
        print!("{:1$}", longest_line_length, max_str_len);
    }

    // defaults
    if !matches.opt_present("bytes")
        && !matches.opt_present("chars")
        && !matches.opt_present("lines")
        && !matches.opt_present("words")
        && !matches.opt_present("max-line-length") {
        print!("{:1$}", line_count, max_str_len);
        print!("{:1$}", word_count, max_str_len + 1);
        print!("{:1$}", byte_count, max_str_len + 1);
    }

    if filename != "-" {
        println!(" {}", filename.as_slice());
    }
    else {
        println!("");
    }
}

fn open(path: String) -> StdResult<BufferedReader<Box<Reader+'static>>, int> {
    if "-" == path.as_slice() {
        let reader = box stdin_raw() as Box<Reader>;
        return Ok(BufferedReader::new(reader));
    }

    let fpath = Path::new(path.as_slice());
    if fpath.is_dir() {
        show_info!("{}: is a directory", path);
    }
    match File::open(&fpath) {
        Ok(fd) => {
            let reader = box fd as Box<Reader>;
            Ok(BufferedReader::new(reader))
        },
        Err(e) => {
            show_error!("wc: {}: {}", path, e);
            Err(1)
        }
    }
}
<commit_msg>wc: boost speed to be nearly as fast as GNU<commit_after>#![crate_name = "wc"]

/*
 * This file is part of the uutils coreutils package.
 *
 * (c) Boden Garman <bpgarman@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

#![feature(macro_rules)]

extern crate getopts;
extern crate libc;

use std::str::from_utf8;
use std::io::{print, File, BufferedReader};
use std::io::fs::PathExtensions;
use std::io::stdio::stdin_raw;
use std::result::Result as StdResult;
use getopts::Matches;

#[path = "../common/util.rs"]
mod util;

struct Result {
    filename: String,
    bytes: uint,
    chars: uint,
    lines: uint,
    words: uint,
    max_line_length: uint,
}

static NAME: &'static str = "wc";

pub fn uumain(args: Vec<String>) -> int {
    let program = args[0].clone();
    let opts = [
        getopts::optflag("c", "bytes", "print the byte counts"),
        getopts::optflag("m", "chars", "print the character counts"),
        getopts::optflag("l", "lines", "print the newline counts"),
        getopts::optflag("L", "max-line-length", "print the length of the longest line"),
        getopts::optflag("w", "words", "print the word counts"),
        getopts::optflag("h", "help", "display this help and exit"),
        getopts::optflag("V", "version", "output version information and exit"),
    ];

    let matches = match getopts::getopts(args.tail(), &opts) {
        Ok(m) => m,
        Err(f) => {
            crash!(1, "Invalid options\n{}", f)
        }
    };

    if matches.opt_present("help") {
        println!("Usage:");
        println!("  {0} [OPTION]... [FILE]...", program);
        println!("");
        print(getopts::usage("Print newline, word and byte counts for each FILE", &opts).as_slice());
        println!("");
        println!("With no FILE, or when FILE is -, read standard input.");
        return 0;
    }

    if matches.opt_present("version") {
        println!("wc 1.0.0");
        return 0;
    }

    let mut files = matches.free.clone();
    if files.is_empty() {
        files = vec!("-".to_string());
    }

    match wc(files, &matches) {
        Ok(()) => ( /* pass */ ),
        Err(e) => return e
    }

    0
}

const CR: u8 = '\r' as u8;
const LF: u8 = '\n' as u8;
const SPACE: u8 = ' ' as u8;
const TAB: u8 = '\t' as u8;
const SYN: u8 = 0x16 as u8;
const FF: u8 = 0x0C as u8;

#[inline(always)]
fn is_word_seperator(byte: u8) -> bool {
    byte == SPACE || byte == TAB || byte == CR || byte == SYN || byte == FF
}

pub fn wc(files: Vec<String>, matches: &Matches) -> StdResult<(), int> {
    let mut total_line_count: uint = 0;
    let mut total_word_count: uint = 0;
    let mut total_char_count: uint = 0;
    let mut total_byte_count: uint = 0;
    let mut total_longest_line_length: uint = 0;

    let mut results = vec!();
    let mut max_str_len: uint = 0;

    for path in files.iter() {
        let mut reader = try!(open(path.as_slice()));

        let mut line_count: uint = 0;
        let mut word_count: uint = 0;
        let mut byte_count: uint = 0;
        let mut char_count: uint = 0;
        let mut current_char_count: uint = 0;
        let mut longest_line_length: uint = 0;

        loop {
            // reading from a TTY seems to raise a condition on, rather than return Some(0) like a file.
            // hence the option wrapped in a result here
            match reader.read_until(LF) {
                Ok(raw_line) => {
                    // GNU 'wc' only counts lines that end in LF as lines
                    if *raw_line.last().unwrap() == LF {
                        line_count += 1;
                    }

                    byte_count += raw_line.len();

                    // try and convert the bytes to UTF-8 first
                    match from_utf8(raw_line.as_slice()) {
                        Some(line) => {
                            word_count += line.words().count();
                            current_char_count = line.char_len();
                            char_count += current_char_count;
                        },
                        None => {
                            word_count += raw_line.as_slice().split(|&x| is_word_seperator(x)).count();
                            for byte in raw_line.iter() {
                                match byte.is_ascii() {
                                    true => {
                                        current_char_count += 1;
                                    }
                                    false => { }
                                }
                            }
                            char_count += current_char_count;
                        }
                    }

                    if current_char_count > longest_line_length {
                        // we subtract one here because `line.len()` includes the LF
                        // matches GNU 'wc' behaviour
                        longest_line_length = current_char_count - 1;
                    }
                },
                _ => break
            }

        }

        results.push(Result {
            filename: path.to_string(),
            bytes: byte_count,
            chars: char_count,
            lines: line_count,
            words: word_count,
            max_line_length: longest_line_length,
        });

        total_line_count += line_count;
        total_word_count += word_count;
        total_char_count += char_count;
        total_byte_count += byte_count;

        if longest_line_length > total_longest_line_length {
            total_longest_line_length = longest_line_length;
        }

        // used for formatting
        max_str_len = total_byte_count.to_string().len();
    }

    for result in results.iter() {
        print_stats(result.filename.as_slice(), result.lines, result.words, result.chars, result.bytes, result.max_line_length, matches, max_str_len);
    }

    if files.len() > 1 {
        print_stats("total", total_line_count, total_word_count, total_char_count, total_byte_count, total_longest_line_length, matches, max_str_len);
    }

    Ok(())
}

fn print_stats(filename: &str, line_count: uint, word_count: uint, char_count: uint,
    byte_count: uint, longest_line_length: uint, matches: &Matches, max_str_len: uint) {
    if matches.opt_present("lines") {
        print!("{:1$}", line_count, max_str_len);
    }
    if matches.opt_present("words") {
        print!("{:1$}", word_count, max_str_len);
    }
    if matches.opt_present("bytes") {
        print!("{:1$}", byte_count, max_str_len);
    }
    if matches.opt_present("chars") {
        print!("{:1$}", char_count, max_str_len);
    }
    if matches.opt_present("max-line-length") {
        print!("{:1$}", longest_line_length, max_str_len);
    }

    // defaults
    if !matches.opt_present("bytes")
        && !matches.opt_present("chars")
        && !matches.opt_present("lines")
        && !matches.opt_present("words")
        && !matches.opt_present("max-line-length") {
        print!("{:1$}", line_count, max_str_len);
        print!("{:1$}", word_count, max_str_len + 1);
        print!("{:1$}", byte_count, max_str_len + 1);
    }

    if filename != "-" {
        println!(" {}", filename.as_slice());
    }
    else {
        println!("");
    }
}

fn open(path: &str) -> StdResult<BufferedReader<Box<Reader+'static>>, int> {
    if "-" == path {
        let reader = box stdin_raw() as Box<Reader>;
        return Ok(BufferedReader::new(reader));
    }

    let fpath = Path::new(path);
    if fpath.is_dir() {
        show_info!("{}: is a directory", path);
    }
    match File::open(&fpath) {
        Ok(fd) => {
            let reader = box fd as Box<Reader>;
            Ok(BufferedReader::new(reader))
        }
        Err(e) => {
            show_error!("wc: {}: {}", path, e);
            Err(1)
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Allow adding menu items after creation<commit_after><|endoftext|>


<commit_before><commit_msg>Rollup merge of #75910 - bugadani:testcase, r=oli-obk<commit_after>// compile-flags: -O
// min-llvm-version: 11.0

#![crate_type = "lib"]

// CHECK-LABEL: @trim_in_place
#[no_mangle]
pub fn trim_in_place(a: &mut &[u8]) {
    while a.first() == Some(&42) {
        // CHECK-NOT: slice_index_order_fail
        *a = &a[1..];
    }
}

// CHECK-LABEL: @trim_in_place2
#[no_mangle]
pub fn trim_in_place2(a: &mut &[u8]) {
    while let Some(&42) = a.first() {
        // CHECK-NOT: slice_index_order_fail
        *a = &a[2..];
    }
}
<|endoftext|>


<commit_before><commit_msg>Add test for source files feature<commit_after>// Copyright 2018 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.

#![crate_name = "foo"]

// @has source-files.js source-file.rs

pub struct Foo;
<|endoftext|>


<commit_before><commit_msg>concatenating two strings using string reference<commit_after><|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::codegen::Bindings::AttrBinding;
use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
use dom::bindings::codegen::InheritTypes::NodeCast;
use dom::bindings::global::Window;
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::trace::Traceable;
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::element::{Element, AttributeHandlers};
use dom::node::Node;
use dom::window::Window;
use dom::virtualmethods::vtable_for;
use servo_util::atom::Atom;
use servo_util::namespace;
use servo_util::namespace::Namespace;
use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS};
use std::cell::{Ref, RefCell};
use std::mem;

pub enum AttrSettingType {
    FirstSetAttr,
    ReplacedAttr,
}

#[deriving(PartialEq, Clone, Encodable)]
pub enum AttrValue {
    StringAttrValue(DOMString),
    TokenListAttrValue(DOMString, Vec<(uint, uint)>),
    UIntAttrValue(DOMString, u32),
    AtomAttrValue(Atom),
}

impl AttrValue {
    pub fn from_tokenlist(list: DOMString) -> AttrValue {
        let mut indexes = vec![];
        let mut last_index: uint = 0;
        for (index, ch) in list.as_slice().char_indices() {
            if HTML_SPACE_CHARACTERS.iter().any(|&space| space == ch) {
                indexes.push((last_index, index));
                last_index = index + 1;
            }
        }
        return TokenListAttrValue(list, indexes);
    }

    pub fn from_u32(string: DOMString, default: u32) -> AttrValue {
        let result: u32 = from_str(string.as_slice()).unwrap_or(default);
        UIntAttrValue(string, result)
    }

    pub fn from_atomic(string: DOMString) -> AttrValue {
        let value = Atom::from_slice(string.as_slice());
        AtomAttrValue(value)
    }

}

impl Str for AttrValue {
    fn as_slice<'a>(&'a self) -> &'a str {
        match *self {
            StringAttrValue(ref value) |
            TokenListAttrValue(ref value, _) |
            UIntAttrValue(ref value, _) => value.as_slice(),
            AtomAttrValue(ref value) => value.as_slice(),
        }
    }
}

#[deriving(Encodable)]
pub struct Attr {
    reflector_: Reflector,
    local_name: Atom,
    value: Traceable<RefCell<AttrValue>>,
    pub name: Atom,
    pub namespace: Namespace,
    pub prefix: Option<DOMString>,

    /// the element that owns this attribute.
    owner: JS<Element>,
}

impl Reflectable for Attr {
    fn reflector<'a>(&'a self) -> &'a Reflector {
        &self.reflector_
    }
}

impl Attr {
    fn new_inherited(local_name: Atom, value: AttrValue,
                     name: Atom, namespace: Namespace,
                     prefix: Option<DOMString>, owner: &JSRef<Element>) -> Attr {
        Attr {
            reflector_: Reflector::new(),
            local_name: local_name,
            value: Traceable::new(RefCell::new(value)),
            name: name,
            namespace: namespace,
            prefix: prefix,
            owner: JS::from_rooted(owner),
        }
    }

    pub fn new(window: &JSRef<Window>, local_name: Atom, value: AttrValue,
               name: Atom, namespace: Namespace,
               prefix: Option<DOMString>, owner: &JSRef<Element>) -> Temporary<Attr> {
        let attr = Attr::new_inherited(local_name, value, name, namespace, prefix, owner);
        reflect_dom_object(box attr, &Window(*window), AttrBinding::Wrap)
    }

    pub fn set_value(&self, set_type: AttrSettingType, value: AttrValue) {
        let owner = self.owner.root();
        let node: &JSRef<Node> = NodeCast::from_ref(&*owner);
        let namespace_is_null = self.namespace == namespace::Null;

        match set_type {
            ReplacedAttr => {
                if namespace_is_null {
                    vtable_for(node).before_remove_attr(
                        self.local_name(),
                        self.value().as_slice().to_string())
                }
            }
            FirstSetAttr => {}
        }

        *self.value.deref().borrow_mut() = value;

        if namespace_is_null {
            vtable_for(node).after_set_attr(
                self.local_name(),
                self.value().as_slice().to_string())
        }
    }

    pub fn value<'a>(&'a self) -> Ref<'a, AttrValue> {
        self.value.deref().borrow()
    }

    pub fn local_name<'a>(&'a self) -> &'a Atom {
        &self.local_name
    }
}

impl<'a> AttrMethods for JSRef<'a, Attr> {
    fn LocalName(&self) -> DOMString {
        self.local_name().as_slice().to_string()
    }

    fn Value(&self) -> DOMString {
        self.value().as_slice().to_string()
    }

    fn SetValue(&self, value: DOMString) {
        let owner = self.owner.root();
        let value = owner.deref().parse_attribute(
            &self.namespace, self.local_name(), value);
        self.set_value(ReplacedAttr, value);
    }

    fn Name(&self) -> DOMString {
        self.name.as_slice().to_string()
    }

    fn GetNamespaceURI(&self) -> Option<DOMString> {
        match self.namespace.to_str() {
            "" => None,
            url => Some(url.to_string()),
        }
    }

    fn GetPrefix(&self) -> Option<DOMString> {
        self.prefix.clone()
    }
}

pub trait AttrHelpersForLayout {
    unsafe fn value_ref_forever(&self) -> &'static str;
    unsafe fn value_atom_forever(&self) -> Option<Atom>;
}

impl AttrHelpersForLayout for Attr {
    unsafe fn value_ref_forever(&self) -> &'static str {
        // cast to point to T in RefCell<T> directly
        let value = mem::transmute::<&RefCell<AttrValue>, &AttrValue>(self.value.deref());
        value.as_slice()
    }

    unsafe fn value_atom_forever(&self) -> Option<Atom> {
        // cast to point to T in RefCell<T> directly
        let value = mem::transmute::<&RefCell<AttrValue>, &AttrValue>(self.value.deref());
        match *value {
            AtomAttrValue(ref val) => Some(val.clone()),
            _ => None,
        }
    }
}
<commit_msg>Fixed AttrValue::from_tokenlist indexes<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::codegen::Bindings::AttrBinding;
use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
use dom::bindings::codegen::InheritTypes::NodeCast;
use dom::bindings::global::Window;
use dom::bindings::js::{JS, JSRef, Temporary};
use dom::bindings::trace::Traceable;
use dom::bindings::utils::{Reflectable, Reflector, reflect_dom_object};
use dom::element::{Element, AttributeHandlers};
use dom::node::Node;
use dom::window::Window;
use dom::virtualmethods::vtable_for;
use servo_util::atom::Atom;
use servo_util::namespace;
use servo_util::namespace::Namespace;
use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS};
use std::cell::{Ref, RefCell};
use std::mem;

pub enum AttrSettingType {
    FirstSetAttr,
    ReplacedAttr,
}

#[deriving(PartialEq, Clone, Encodable)]
pub enum AttrValue {
    StringAttrValue(DOMString),
    TokenListAttrValue(DOMString, Vec<(uint, uint)>),
    UIntAttrValue(DOMString, u32),
    AtomAttrValue(Atom),
}

impl AttrValue {
    pub fn from_tokenlist(list: DOMString) -> AttrValue {
        let mut indexes = vec![];
        let mut last_index: uint = 0;
        let length = list.len() - 1;
        for (index, ch) in list.as_slice().char_indices() {
            if HTML_SPACE_CHARACTERS.iter().any(|&space| space == ch) {
                if last_index != index {
                    indexes.push((last_index, index));
                }
                last_index = index + 1;
            } else if index == length {
                indexes.push((last_index, index + 1));
            }
        }
        return TokenListAttrValue(list, indexes);
    }

    pub fn from_u32(string: DOMString, default: u32) -> AttrValue {
        let result: u32 = from_str(string.as_slice()).unwrap_or(default);
        UIntAttrValue(string, result)
    }

    pub fn from_atomic(string: DOMString) -> AttrValue {
        let value = Atom::from_slice(string.as_slice());
        AtomAttrValue(value)
    }

}

impl Str for AttrValue {
    fn as_slice<'a>(&'a self) -> &'a str {
        match *self {
            StringAttrValue(ref value) |
            TokenListAttrValue(ref value, _) |
            UIntAttrValue(ref value, _) => value.as_slice(),
            AtomAttrValue(ref value) => value.as_slice(),
        }
    }
}

#[deriving(Encodable)]
pub struct Attr {
    reflector_: Reflector,
    local_name: Atom,
    value: Traceable<RefCell<AttrValue>>,
    pub name: Atom,
    pub namespace: Namespace,
    pub prefix: Option<DOMString>,

    /// the element that owns this attribute.
    owner: JS<Element>,
}

impl Reflectable for Attr {
    fn reflector<'a>(&'a self) -> &'a Reflector {
        &self.reflector_
    }
}

impl Attr {
    fn new_inherited(local_name: Atom, value: AttrValue,
                     name: Atom, namespace: Namespace,
                     prefix: Option<DOMString>, owner: &JSRef<Element>) -> Attr {
        Attr {
            reflector_: Reflector::new(),
            local_name: local_name,
            value: Traceable::new(RefCell::new(value)),
            name: name,
            namespace: namespace,
            prefix: prefix,
            owner: JS::from_rooted(owner),
        }
    }

    pub fn new(window: &JSRef<Window>, local_name: Atom, value: AttrValue,
               name: Atom, namespace: Namespace,
               prefix: Option<DOMString>, owner: &JSRef<Element>) -> Temporary<Attr> {
        let attr = Attr::new_inherited(local_name, value, name, namespace, prefix, owner);
        reflect_dom_object(box attr, &Window(*window), AttrBinding::Wrap)
    }

    pub fn set_value(&self, set_type: AttrSettingType, value: AttrValue) {
        let owner = self.owner.root();
        let node: &JSRef<Node> = NodeCast::from_ref(&*owner);
        let namespace_is_null = self.namespace == namespace::Null;

        match set_type {
            ReplacedAttr => {
                if namespace_is_null {
                    vtable_for(node).before_remove_attr(
                        self.local_name(),
                        self.value().as_slice().to_string())
                }
            }
            FirstSetAttr => {}
        }

        *self.value.deref().borrow_mut() = value;

        if namespace_is_null {
            vtable_for(node).after_set_attr(
                self.local_name(),
                self.value().as_slice().to_string())
        }
    }

    pub fn value<'a>(&'a self) -> Ref<'a, AttrValue> {
        self.value.deref().borrow()
    }

    pub fn local_name<'a>(&'a self) -> &'a Atom {
        &self.local_name
    }
}

impl<'a> AttrMethods for JSRef<'a, Attr> {
    fn LocalName(&self) -> DOMString {
        self.local_name().as_slice().to_string()
    }

    fn Value(&self) -> DOMString {
        self.value().as_slice().to_string()
    }

    fn SetValue(&self, value: DOMString) {
        let owner = self.owner.root();
        let value = owner.deref().parse_attribute(
            &self.namespace, self.local_name(), value);
        self.set_value(ReplacedAttr, value);
    }

    fn Name(&self) -> DOMString {
        self.name.as_slice().to_string()
    }

    fn GetNamespaceURI(&self) -> Option<DOMString> {
        match self.namespace.to_str() {
            "" => None,
            url => Some(url.to_string()),
        }
    }

    fn GetPrefix(&self) -> Option<DOMString> {
        self.prefix.clone()
    }
}

pub trait AttrHelpersForLayout {
    unsafe fn value_ref_forever(&self) -> &'static str;
    unsafe fn value_atom_forever(&self) -> Option<Atom>;
}

impl AttrHelpersForLayout for Attr {
    unsafe fn value_ref_forever(&self) -> &'static str {
        // cast to point to T in RefCell<T> directly
        let value = mem::transmute::<&RefCell<AttrValue>, &AttrValue>(self.value.deref());
        value.as_slice()
    }

    unsafe fn value_atom_forever(&self) -> Option<Atom> {
        // cast to point to T in RefCell<T> directly
        let value = mem::transmute::<&RefCell<AttrValue>, &AttrValue>(self.value.deref());
        match *value {
            AtomAttrValue(ref val) => Some(val.clone()),
            _ => None,
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>build: shorten up `PackageBuild::from_file`<commit_after><|endoftext|>


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

// The crate store - a central repo for information collected about external
// crates and libraries

use metadata::decoder;
use metadata::loader;

use std::hashmap::HashMap;
use syntax::ast;
use syntax::parse::token::ident_interner;

// A map from external crate numbers (as decoded from some crate file) to
// local crate numbers (as generated during this session). Each external
// crate may refer to types in other external crates, and each has their
// own crate numbers.
pub type cnum_map = @mut HashMap<ast::CrateNum, ast::CrateNum>;

pub enum MetadataBlob {
    MetadataVec(~[u8]),
    MetadataArchive(loader::ArchiveMetadata),
}

pub struct crate_metadata {
    name: @str,
    data: MetadataBlob,
    cnum_map: cnum_map,
    cnum: ast::CrateNum
}

#[deriving(Eq)]
pub enum LinkagePreference {
    RequireDynamic,
    RequireStatic,
}

#[deriving(Eq, FromPrimitive)]
pub enum NativeLibaryKind {
    NativeStatic,    // native static library (.a archive)
    NativeFramework, // OSX-specific
    NativeUnknown,   // default way to specify a dynamic library
}

// Where a crate came from on the local filesystem. One of these two options
// must be non-None.
#[deriving(Eq)]
pub struct CrateSource {
    dylib: Option<Path>,
    rlib: Option<Path>,
    cnum: ast::CrateNum,
}

pub struct CStore {
    priv metas: HashMap <ast::CrateNum, @crate_metadata>,
    priv extern_mod_crate_map: extern_mod_crate_map,
    priv used_crate_sources: ~[CrateSource],
    priv used_libraries: ~[(~str, NativeLibaryKind)],
    priv used_link_args: ~[~str],
    intr: @ident_interner
}

// Map from NodeId's of local extern mod statements to crate numbers
type extern_mod_crate_map = HashMap<ast::NodeId, ast::CrateNum>;

impl CStore {
    pub fn new(intr: @ident_interner) -> CStore {
        CStore {
            metas: HashMap::new(),
            extern_mod_crate_map: HashMap::new(),
            used_crate_sources: ~[],
            used_libraries: ~[],
            used_link_args: ~[],
            intr: intr
        }
    }

    pub fn get_crate_data(&self, cnum: ast::CrateNum) -> @crate_metadata {
        *self.metas.get(&cnum)
    }

    pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> @str {
        let cdata = self.get_crate_data(cnum);
        decoder::get_crate_hash(cdata.data())
    }

    pub fn get_crate_vers(&self, cnum: ast::CrateNum) -> @str {
        let cdata = self.get_crate_data(cnum);
        decoder::get_crate_vers(cdata.data())
    }

    pub fn set_crate_data(&mut self, cnum: ast::CrateNum, data: @crate_metadata) {
        self.metas.insert(cnum, data);
    }

    pub fn have_crate_data(&self, cnum: ast::CrateNum) -> bool {
        self.metas.contains_key(&cnum)
    }

    pub fn iter_crate_data(&self, i: |ast::CrateNum, @crate_metadata|) {
        for (&k, &v) in self.metas.iter() {
            i(k, v);
        }
    }

    pub fn add_used_crate_source(&mut self, src: CrateSource) {
        if !self.used_crate_sources.contains(&src) {
            self.used_crate_sources.push(src);
        }
    }

    pub fn get_used_crate_sources<'a>(&'a self) -> &'a [CrateSource] {
        self.used_crate_sources.as_slice()
    }

    pub fn get_used_crates(&self, prefer: LinkagePreference)
                           -> ~[(ast::CrateNum, Option<Path>)] {
        self.used_crate_sources.iter()
            .map(|src| (src.cnum, match prefer {
                RequireDynamic => src.dylib.clone(),
                RequireStatic => src.rlib.clone(),
            }))
            .collect()
    }

    pub fn add_used_library(&mut self, lib: ~str, kind: NativeLibaryKind) -> bool {
        assert!(!lib.is_empty());
        if self.used_libraries.iter().any(|&(ref x, _)| x == &lib) {
            return false;
        }
        self.used_libraries.push((lib, kind));
        true
    }

    pub fn get_used_libraries<'a>(&'a self) -> &'a [(~str, NativeLibaryKind)] {
        self.used_libraries.as_slice()
    }

    pub fn add_used_link_args(&mut self, args: &str) {
        for s in args.split(' ') {
            self.used_link_args.push(s.to_owned());
        }
    }

    pub fn get_used_link_args<'a>(&'a self) -> &'a [~str] {
        self.used_link_args.as_slice()
    }

    pub fn add_extern_mod_stmt_cnum(&mut self,
                                    emod_id: ast::NodeId,
                                    cnum: ast::CrateNum) {
        self.extern_mod_crate_map.insert(emod_id, cnum);
    }

    pub fn find_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId)
                                     -> Option<ast::CrateNum> {
        self.extern_mod_crate_map.find(&emod_id).map(|x| *x)
    }

    // returns hashes of crates directly used by this crate. Hashes are sorted by
    // (crate name, crate version, crate hash) in lexicographic order (not semver)
    pub fn get_dep_hashes(&self) -> ~[@str] {
        let mut result = ~[];

        for (_, &cnum) in self.extern_mod_crate_map.iter() {
            let cdata = self.get_crate_data(cnum);
            let hash = decoder::get_crate_hash(cdata.data());
            let vers = decoder::get_crate_vers(cdata.data());
            debug!("Add hash[{}]: {} {}", cdata.name, vers, hash);
            result.push(crate_hash {
                name: cdata.name,
                vers: vers,
                hash: hash
            });
        }

        result.sort();

        debug!("sorted:");
        for x in result.iter() {
            debug!("  hash[{}]: {}", x.name, x.hash);
        }

        result.map(|ch| ch.hash)
    }
}

#[deriving(Clone, TotalEq, TotalOrd)]
struct crate_hash {
    name: @str,
    vers: @str,
    hash: @str,
}

impl crate_metadata {
    pub fn data<'a>(&'a self) -> &'a [u8] { self.data.as_slice() }
}

impl MetadataBlob {
    pub fn as_slice<'a>(&'a self) -> &'a [u8] {
        match *self {
            MetadataVec(ref vec) => vec.as_slice(),
            MetadataArchive(ref ar) => ar.as_slice(),
        }
    }
}
<commit_msg>librustc: De-`@mut` `CStore::metas`<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// The crate store - a central repo for information collected about external
// crates and libraries

use metadata::decoder;
use metadata::loader;

use std::cell::RefCell;
use std::hashmap::HashMap;
use syntax::ast;
use syntax::parse::token::ident_interner;

// A map from external crate numbers (as decoded from some crate file) to
// local crate numbers (as generated during this session). Each external
// crate may refer to types in other external crates, and each has their
// own crate numbers.
pub type cnum_map = @mut HashMap<ast::CrateNum, ast::CrateNum>;

pub enum MetadataBlob {
    MetadataVec(~[u8]),
    MetadataArchive(loader::ArchiveMetadata),
}

pub struct crate_metadata {
    name: @str,
    data: MetadataBlob,
    cnum_map: cnum_map,
    cnum: ast::CrateNum
}

#[deriving(Eq)]
pub enum LinkagePreference {
    RequireDynamic,
    RequireStatic,
}

#[deriving(Eq, FromPrimitive)]
pub enum NativeLibaryKind {
    NativeStatic,    // native static library (.a archive)
    NativeFramework, // OSX-specific
    NativeUnknown,   // default way to specify a dynamic library
}

// Where a crate came from on the local filesystem. One of these two options
// must be non-None.
#[deriving(Eq)]
pub struct CrateSource {
    dylib: Option<Path>,
    rlib: Option<Path>,
    cnum: ast::CrateNum,
}

pub struct CStore {
    priv metas: RefCell<HashMap<ast::CrateNum, @crate_metadata>>,
    priv extern_mod_crate_map: extern_mod_crate_map,
    priv used_crate_sources: ~[CrateSource],
    priv used_libraries: ~[(~str, NativeLibaryKind)],
    priv used_link_args: ~[~str],
    intr: @ident_interner
}

// Map from NodeId's of local extern mod statements to crate numbers
type extern_mod_crate_map = HashMap<ast::NodeId, ast::CrateNum>;

impl CStore {
    pub fn new(intr: @ident_interner) -> CStore {
        CStore {
            metas: RefCell::new(HashMap::new()),
            extern_mod_crate_map: HashMap::new(),
            used_crate_sources: ~[],
            used_libraries: ~[],
            used_link_args: ~[],
            intr: intr
        }
    }

    pub fn get_crate_data(&self, cnum: ast::CrateNum) -> @crate_metadata {
        let metas = self.metas.borrow();
        *metas.get().get(&cnum)
    }

    pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> @str {
        let cdata = self.get_crate_data(cnum);
        decoder::get_crate_hash(cdata.data())
    }

    pub fn get_crate_vers(&self, cnum: ast::CrateNum) -> @str {
        let cdata = self.get_crate_data(cnum);
        decoder::get_crate_vers(cdata.data())
    }

    pub fn set_crate_data(&mut self, cnum: ast::CrateNum, data: @crate_metadata) {
        let mut metas = self.metas.borrow_mut();
        metas.get().insert(cnum, data);
    }

    pub fn have_crate_data(&self, cnum: ast::CrateNum) -> bool {
        let metas = self.metas.borrow();
        metas.get().contains_key(&cnum)
    }

    pub fn iter_crate_data(&self, i: |ast::CrateNum, @crate_metadata|) {
        let metas = self.metas.borrow();
        for (&k, &v) in metas.get().iter() {
            i(k, v);
        }
    }

    pub fn add_used_crate_source(&mut self, src: CrateSource) {
        if !self.used_crate_sources.contains(&src) {
            self.used_crate_sources.push(src);
        }
    }

    pub fn get_used_crate_sources<'a>(&'a self) -> &'a [CrateSource] {
        self.used_crate_sources.as_slice()
    }

    pub fn get_used_crates(&self, prefer: LinkagePreference)
                           -> ~[(ast::CrateNum, Option<Path>)] {
        self.used_crate_sources.iter()
            .map(|src| (src.cnum, match prefer {
                RequireDynamic => src.dylib.clone(),
                RequireStatic => src.rlib.clone(),
            }))
            .collect()
    }

    pub fn add_used_library(&mut self, lib: ~str, kind: NativeLibaryKind) -> bool {
        assert!(!lib.is_empty());
        if self.used_libraries.iter().any(|&(ref x, _)| x == &lib) {
            return false;
        }
        self.used_libraries.push((lib, kind));
        true
    }

    pub fn get_used_libraries<'a>(&'a self) -> &'a [(~str, NativeLibaryKind)] {
        self.used_libraries.as_slice()
    }

    pub fn add_used_link_args(&mut self, args: &str) {
        for s in args.split(' ') {
            self.used_link_args.push(s.to_owned());
        }
    }

    pub fn get_used_link_args<'a>(&'a self) -> &'a [~str] {
        self.used_link_args.as_slice()
    }

    pub fn add_extern_mod_stmt_cnum(&mut self,
                                    emod_id: ast::NodeId,
                                    cnum: ast::CrateNum) {
        self.extern_mod_crate_map.insert(emod_id, cnum);
    }

    pub fn find_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId)
                                     -> Option<ast::CrateNum> {
        self.extern_mod_crate_map.find(&emod_id).map(|x| *x)
    }

    // returns hashes of crates directly used by this crate. Hashes are sorted by
    // (crate name, crate version, crate hash) in lexicographic order (not semver)
    pub fn get_dep_hashes(&self) -> ~[@str] {
        let mut result = ~[];

        for (_, &cnum) in self.extern_mod_crate_map.iter() {
            let cdata = self.get_crate_data(cnum);
            let hash = decoder::get_crate_hash(cdata.data());
            let vers = decoder::get_crate_vers(cdata.data());
            debug!("Add hash[{}]: {} {}", cdata.name, vers, hash);
            result.push(crate_hash {
                name: cdata.name,
                vers: vers,
                hash: hash
            });
        }

        result.sort();

        debug!("sorted:");
        for x in result.iter() {
            debug!("  hash[{}]: {}", x.name, x.hash);
        }

        result.map(|ch| ch.hash)
    }
}

#[deriving(Clone, TotalEq, TotalOrd)]
struct crate_hash {
    name: @str,
    vers: @str,
    hash: @str,
}

impl crate_metadata {
    pub fn data<'a>(&'a self) -> &'a [u8] { self.data.as_slice() }
}

impl MetadataBlob {
    pub fn as_slice<'a>(&'a self) -> &'a [u8] {
        match *self {
            MetadataVec(ref vec) => vec.as_slice(),
            MetadataArchive(ref ar) => ar.as_slice(),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>this is my first real commitment<commit_after>fn main() {
	println!("hello world!");
}
<|endoftext|>


<commit_before><commit_msg>ignore case to imei<commit_after><|endoftext|>


<commit_before>#[doc = "Prunes branches of the document tree that contain no documentation"];

export mk_pass;

fn mk_pass() -> pass {
    run
}

type ctxt = {
    mutable have_docs: bool
};

fn run(
    _srv: astsrv::srv,
    doc: doc::cratedoc
) -> doc::cratedoc {
    let ctxt = {
        mutable have_docs: true
    };
    let fold = fold::fold({
        fold_mod: fold_mod,
        fold_fn: fold_fn,
        fold_const: fold_const,
        fold_enum: fold_enum,
        fold_res: fold_res,
        fold_iface: fold_iface
        with *fold::default_seq_fold(ctxt)
    });
    fold.fold_crate(fold, doc)
}

fn fold_mod(
    fold: fold::fold<ctxt>,
    doc: doc::moddoc
) -> doc::moddoc {
    let doc = {
        items: ~vec::filter_map(*doc.items) {|itemtag|
            alt itemtag {
              doc::modtag(moddoc) {
                let doc = fold.fold_mod(fold, moddoc);
                if fold.ctxt.have_docs {
                    some(doc::modtag(doc))
                } else {
                    none
                }
              }
              doc::fntag(fndoc) {
                let doc = fold.fold_fn(fold, fndoc);
                if fold.ctxt.have_docs {
                    some(doc::fntag(doc))
                } else {
                    none
                }
              }
              doc::consttag(constdoc) {
                let doc = fold.fold_const(fold, constdoc);
                if fold.ctxt.have_docs {
                    some(doc::consttag(doc))
                } else {
                    none
                }
              }
              doc::enumtag(enumdoc) {
                let doc = fold.fold_enum(fold, enumdoc);
                if fold.ctxt.have_docs {
                    some(doc::enumtag(doc))
                } else {
                    none
                }
              }
              doc::restag(resdoc) {
                let doc = fold.fold_res(fold, resdoc);
                if fold.ctxt.have_docs {
                    some(doc::restag(doc))
                } else {
                    none
                }
              }
              doc::ifacetag(ifacedoc) {
                let doc = fold.fold_iface(fold, ifacedoc);
                if fold.ctxt.have_docs {
                    some(doc::ifacetag(doc))
                } else {
                    none
                }
              }
              _ { some(itemtag) }
            }
        }
        with fold::default_seq_fold_mod(fold, doc)
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(*doc.items);
    ret doc;
}

fn fold_fn(
    fold: fold::fold<ctxt>,
    doc: doc::fndoc
) -> doc::fndoc {
    let doc = {
        args: prune_args(doc.args),
        return: prune_return(doc.return)
        with doc
    };

    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(doc.args)
        || doc.return.desc != none
        || doc.failure != none;
    ret doc;
}

fn prune_args(docs: [doc::argdoc]) -> [doc::argdoc] {
    vec::filter_map(docs) {|doc|
        if option::is_some(doc.desc) {
            some(doc)
        } else {
            none
        }
    }
}

fn prune_return(doc: doc::retdoc) -> doc::retdoc {
    {
        ty: if option::is_some(doc.desc) {
            doc.ty
        } else {
            none
        }
        with doc
    }
}

#[test]
fn should_elide_undocumented_arguments() {
    let doc = test::mk_doc("#[doc = \"hey\"] fn a(b: int) { }");
    assert vec::is_empty(doc.topmod.fns()[0].args);
}

#[test]
fn should_not_elide_fns_with_documented_arguments() {
    let doc = test::mk_doc("#[doc(args(a = \"b\"))] fn a(a: int) { }");
    assert vec::is_not_empty(doc.topmod.fns());
}

#[test]
fn should_elide_undocumented_return_values() {
    let source = "#[doc = \"fonz\"] fn a() -> int { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = tystr_pass::mk_pass()(srv, doc);
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert doc.topmod.fns()[0].return.ty == none;
}

#[test]
fn should_not_elide_fns_with_documented_failure_conditions() {
    let doc = test::mk_doc("#[doc(failure = \"yup\")] fn a() { }");
    assert vec::is_not_empty(doc.topmod.fns());
}

#[test]
fn should_elide_undocumented_mods() {
    let doc = test::mk_doc("mod a { }");
    assert vec::is_empty(doc.topmod.mods());
}

#[test]
fn should_not_elide_undocument_mods_with_documented_mods() {
    let doc = test::mk_doc("mod a { #[doc = \"b\"] mod b { } }");
    assert vec::is_not_empty(doc.topmod.mods());
}

#[test]
fn should_not_elide_undocument_mods_with_documented_fns() {
    let doc = test::mk_doc("mod a { #[doc = \"b\"] fn b() { } }");
    assert vec::is_not_empty(doc.topmod.mods());
}

#[test]
fn should_elide_undocumented_fns() {
    let doc = test::mk_doc("fn a() { }");
    assert vec::is_empty(doc.topmod.fns());
}

fn fold_const(
    fold: fold::fold<ctxt>,
    doc: doc::constdoc
) -> doc::constdoc {
    let doc = fold::default_seq_fold_const(fold, doc);
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none;
    ret doc;
}

#[test]
fn should_elide_undocumented_consts() {
    let doc = test::mk_doc("const a: bool = true;");
    assert vec::is_empty(doc.topmod.consts());
}

fn fold_enum(fold: fold::fold<ctxt>, doc: doc::enumdoc) -> doc::enumdoc {
    let doc = {
        variants: vec::filter_map(doc.variants) {|variant|
            if variant.desc != none {
                some(variant)
            } else {
                none
            }
        }
        with fold::default_seq_fold_enum(fold, doc)
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(doc.variants);
    ret doc;
}

#[test]
fn should_elide_undocumented_enums() {
    let doc = test::mk_doc("enum a { b }");
    assert vec::is_empty(doc.topmod.enums());
}

#[test]
fn should_elide_undocumented_variants() {
    let doc = test::mk_doc("#[doc = \"a\"] enum a { b }");
    assert vec::is_empty(doc.topmod.enums()[0].variants);
}

#[test]
fn should_not_elide_enums_with_documented_variants() {
    let doc = test::mk_doc("enum a { #[doc = \"a\"] b }");
    assert vec::is_not_empty(doc.topmod.enums());
}

fn fold_res(fold: fold::fold<ctxt>, doc: doc::resdoc) -> doc::resdoc {
    let doc = {
        args: vec::filter_map(doc.args) {|arg|
            if arg.desc != none {
                some(arg)
            } else {
                none
            }
        }
        with fold::default_seq_fold_res(fold, doc)
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(doc.args);
    ret doc;
}

#[test]
fn should_elide_undocumented_resources() {
    let doc = test::mk_doc("resource r(a: bool) { }");
    assert vec::is_empty(doc.topmod.resources());
}

#[test]
fn should_elide_undocumented_resource_args() {
    let doc = test::mk_doc("#[doc = \"drunk\"]\
                            resource r(a: bool) { }");
    assert vec::is_empty(doc.topmod.resources()[0].args);
}

#[test]
fn should_not_elide_resources_with_documented_args() {
    let doc = test::mk_doc("#[doc(args(a = \"drunk\"))]\
                            resource r(a: bool) { }");
    assert vec::is_not_empty(doc.topmod.resources());
}

fn fold_iface(
    fold: fold::fold<ctxt>,
    doc: doc::ifacedoc
) -> doc::ifacedoc {
    let doc = fold::default_seq_fold_iface(fold, doc);
    let doc = {
        methods: vec::map(doc.methods) {|doc|
            {
                args: prune_args(doc.args),
                return: prune_return(doc.return)
                with doc
            }
        }
        with doc
    };
    let methods_have_docs = vec::foldl(false, doc.methods) {|accum, doc|
        accum
            || doc.brief != none
            || doc.desc != none
            || vec::is_not_empty(doc.args)
            || doc.return.desc != none
            || doc.failure != none
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || methods_have_docs;
    ret doc;
}

#[test]
fn should_elide_undocumented_ifaces() {
    let doc = test::mk_doc("iface i { fn a(); }");
    assert vec::is_empty(doc.topmod.ifaces());
}

#[test]
fn should_not_elide_documented_ifaces() {
    let doc = test::mk_doc("#[doc = \"hey\"] iface i { fn a(); }");
    assert vec::is_not_empty(doc.topmod.ifaces());
}

#[test]
fn should_not_elide_ifaces_with_documented_methods() {
    let doc = test::mk_doc("iface i { #[doc = \"hey\"] fn a(); }");
    assert vec::is_not_empty(doc.topmod.ifaces());
}

#[test]
fn should_not_elide_undocumented_methods() {
    let doc = test::mk_doc("#[doc = \"hey\"] iface i { fn a(); }");
    assert vec::is_not_empty(doc.topmod.ifaces()[0].methods);
}

#[test]
fn should_elide_undocumented_method_args() {
    let doc = test::mk_doc("#[doc = \"hey\"] iface i { fn a(); }");
    assert vec::is_empty(doc.topmod.ifaces()[0].methods[0].args);
}

#[test]
fn should_elide_undocumented_method_return_values() {
    let doc = test::mk_doc("#[doc = \"hey\"] iface i { fn a() -> int; }");
    assert doc.topmod.ifaces()[0].methods[0].return.ty == none;
}

#[cfg(test)]
mod test {
    fn mk_doc(source: str) -> doc::cratedoc {
        let srv = astsrv::mk_srv_from_str(source);
        let doc = extract::from_srv(srv, "");
        let doc = attr_pass::mk_pass()(srv, doc);
        run(srv, doc)
    }
}
<commit_msg>rustdoc: Prune undocumented impls<commit_after>#[doc = "Prunes branches of the document tree that contain no documentation"];

export mk_pass;

fn mk_pass() -> pass {
    run
}

type ctxt = {
    mutable have_docs: bool
};

fn run(
    _srv: astsrv::srv,
    doc: doc::cratedoc
) -> doc::cratedoc {
    let ctxt = {
        mutable have_docs: true
    };
    let fold = fold::fold({
        fold_mod: fold_mod,
        fold_fn: fold_fn,
        fold_const: fold_const,
        fold_enum: fold_enum,
        fold_res: fold_res,
        fold_iface: fold_iface,
        fold_impl: fold_impl
        with *fold::default_seq_fold(ctxt)
    });
    fold.fold_crate(fold, doc)
}

fn fold_mod(
    fold: fold::fold<ctxt>,
    doc: doc::moddoc
) -> doc::moddoc {
    let doc = {
        items: ~vec::filter_map(*doc.items) {|itemtag|
            alt itemtag {
              doc::modtag(moddoc) {
                let doc = fold.fold_mod(fold, moddoc);
                if fold.ctxt.have_docs {
                    some(doc::modtag(doc))
                } else {
                    none
                }
              }
              doc::fntag(fndoc) {
                let doc = fold.fold_fn(fold, fndoc);
                if fold.ctxt.have_docs {
                    some(doc::fntag(doc))
                } else {
                    none
                }
              }
              doc::consttag(constdoc) {
                let doc = fold.fold_const(fold, constdoc);
                if fold.ctxt.have_docs {
                    some(doc::consttag(doc))
                } else {
                    none
                }
              }
              doc::enumtag(enumdoc) {
                let doc = fold.fold_enum(fold, enumdoc);
                if fold.ctxt.have_docs {
                    some(doc::enumtag(doc))
                } else {
                    none
                }
              }
              doc::restag(resdoc) {
                let doc = fold.fold_res(fold, resdoc);
                if fold.ctxt.have_docs {
                    some(doc::restag(doc))
                } else {
                    none
                }
              }
              doc::ifacetag(ifacedoc) {
                let doc = fold.fold_iface(fold, ifacedoc);
                if fold.ctxt.have_docs {
                    some(doc::ifacetag(doc))
                } else {
                    none
                }
              }
              doc::impltag(impldoc) {
                let doc = fold.fold_impl(fold, impldoc);
                if fold.ctxt.have_docs {
                    some(doc::impltag(doc))
                } else {
                    none
                }
              }
              _ { some(itemtag) }
            }
        }
        with fold::default_seq_fold_mod(fold, doc)
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(*doc.items);
    ret doc;
}

fn fold_fn(
    fold: fold::fold<ctxt>,
    doc: doc::fndoc
) -> doc::fndoc {
    let doc = {
        args: prune_args(doc.args),
        return: prune_return(doc.return)
        with doc
    };

    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(doc.args)
        || doc.return.desc != none
        || doc.failure != none;
    ret doc;
}

fn prune_args(docs: [doc::argdoc]) -> [doc::argdoc] {
    vec::filter_map(docs) {|doc|
        if option::is_some(doc.desc) {
            some(doc)
        } else {
            none
        }
    }
}

fn prune_return(doc: doc::retdoc) -> doc::retdoc {
    {
        ty: if option::is_some(doc.desc) {
            doc.ty
        } else {
            none
        }
        with doc
    }
}

#[test]
fn should_elide_undocumented_arguments() {
    let doc = test::mk_doc("#[doc = \"hey\"] fn a(b: int) { }");
    assert vec::is_empty(doc.topmod.fns()[0].args);
}

#[test]
fn should_not_elide_fns_with_documented_arguments() {
    let doc = test::mk_doc("#[doc(args(a = \"b\"))] fn a(a: int) { }");
    assert vec::is_not_empty(doc.topmod.fns());
}

#[test]
fn should_elide_undocumented_return_values() {
    let source = "#[doc = \"fonz\"] fn a() -> int { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = tystr_pass::mk_pass()(srv, doc);
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert doc.topmod.fns()[0].return.ty == none;
}

#[test]
fn should_not_elide_fns_with_documented_failure_conditions() {
    let doc = test::mk_doc("#[doc(failure = \"yup\")] fn a() { }");
    assert vec::is_not_empty(doc.topmod.fns());
}

#[test]
fn should_elide_undocumented_mods() {
    let doc = test::mk_doc("mod a { }");
    assert vec::is_empty(doc.topmod.mods());
}

#[test]
fn should_not_elide_undocument_mods_with_documented_mods() {
    let doc = test::mk_doc("mod a { #[doc = \"b\"] mod b { } }");
    assert vec::is_not_empty(doc.topmod.mods());
}

#[test]
fn should_not_elide_undocument_mods_with_documented_fns() {
    let doc = test::mk_doc("mod a { #[doc = \"b\"] fn b() { } }");
    assert vec::is_not_empty(doc.topmod.mods());
}

#[test]
fn should_elide_undocumented_fns() {
    let doc = test::mk_doc("fn a() { }");
    assert vec::is_empty(doc.topmod.fns());
}

fn fold_const(
    fold: fold::fold<ctxt>,
    doc: doc::constdoc
) -> doc::constdoc {
    let doc = fold::default_seq_fold_const(fold, doc);
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none;
    ret doc;
}

#[test]
fn should_elide_undocumented_consts() {
    let doc = test::mk_doc("const a: bool = true;");
    assert vec::is_empty(doc.topmod.consts());
}

fn fold_enum(fold: fold::fold<ctxt>, doc: doc::enumdoc) -> doc::enumdoc {
    let doc = {
        variants: vec::filter_map(doc.variants) {|variant|
            if variant.desc != none {
                some(variant)
            } else {
                none
            }
        }
        with fold::default_seq_fold_enum(fold, doc)
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(doc.variants);
    ret doc;
}

#[test]
fn should_elide_undocumented_enums() {
    let doc = test::mk_doc("enum a { b }");
    assert vec::is_empty(doc.topmod.enums());
}

#[test]
fn should_elide_undocumented_variants() {
    let doc = test::mk_doc("#[doc = \"a\"] enum a { b }");
    assert vec::is_empty(doc.topmod.enums()[0].variants);
}

#[test]
fn should_not_elide_enums_with_documented_variants() {
    let doc = test::mk_doc("enum a { #[doc = \"a\"] b }");
    assert vec::is_not_empty(doc.topmod.enums());
}

fn fold_res(fold: fold::fold<ctxt>, doc: doc::resdoc) -> doc::resdoc {
    let doc = {
        args: vec::filter_map(doc.args) {|arg|
            if arg.desc != none {
                some(arg)
            } else {
                none
            }
        }
        with fold::default_seq_fold_res(fold, doc)
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(doc.args);
    ret doc;
}

#[test]
fn should_elide_undocumented_resources() {
    let doc = test::mk_doc("resource r(a: bool) { }");
    assert vec::is_empty(doc.topmod.resources());
}

#[test]
fn should_elide_undocumented_resource_args() {
    let doc = test::mk_doc("#[doc = \"drunk\"]\
                            resource r(a: bool) { }");
    assert vec::is_empty(doc.topmod.resources()[0].args);
}

#[test]
fn should_not_elide_resources_with_documented_args() {
    let doc = test::mk_doc("#[doc(args(a = \"drunk\"))]\
                            resource r(a: bool) { }");
    assert vec::is_not_empty(doc.topmod.resources());
}

fn fold_iface(
    fold: fold::fold<ctxt>,
    doc: doc::ifacedoc
) -> doc::ifacedoc {
    let doc = fold::default_seq_fold_iface(fold, doc);
    let doc = {
        methods: prune_methods(doc.methods)
        with doc
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || methods_have_docs(doc.methods);
    ret doc;
}

fn prune_methods(docs: [doc::methoddoc]) -> [doc::methoddoc] {
    vec::map(docs) {|doc|
        {
            args: prune_args(doc.args),
            return: prune_return(doc.return)
            with doc
        }
    }
}

fn methods_have_docs(docs: [doc::methoddoc]) -> bool {
    vec::foldl(false, docs) {|accum, doc|
        accum
            || doc.brief != none
            || doc.desc != none
            || vec::is_not_empty(doc.args)
            || doc.return.desc != none
            || doc.failure != none
    }
}

#[test]
fn should_elide_undocumented_ifaces() {
    let doc = test::mk_doc("iface i { fn a(); }");
    assert vec::is_empty(doc.topmod.ifaces());
}

#[test]
fn should_not_elide_documented_ifaces() {
    let doc = test::mk_doc("#[doc = \"hey\"] iface i { fn a(); }");
    assert vec::is_not_empty(doc.topmod.ifaces());
}

#[test]
fn should_not_elide_ifaces_with_documented_methods() {
    let doc = test::mk_doc("iface i { #[doc = \"hey\"] fn a(); }");
    assert vec::is_not_empty(doc.topmod.ifaces());
}

#[test]
fn should_not_elide_undocumented_iface_methods() {
    let doc = test::mk_doc("#[doc = \"hey\"] iface i { fn a(); }");
    assert vec::is_not_empty(doc.topmod.ifaces()[0].methods);
}

#[test]
fn should_elide_undocumented_iface_method_args() {
    let doc = test::mk_doc("#[doc = \"hey\"] iface i { fn a(); }");
    assert vec::is_empty(doc.topmod.ifaces()[0].methods[0].args);
}

#[test]
fn should_elide_undocumented_iface_method_return_values() {
    let doc = test::mk_doc("#[doc = \"hey\"] iface i { fn a() -> int; }");
    assert doc.topmod.ifaces()[0].methods[0].return.ty == none;
}

fn fold_impl(
    fold: fold::fold<ctxt>,
    doc: doc::impldoc
) -> doc::impldoc {
    let doc = fold::default_seq_fold_impl(fold, doc);
    let doc = {
        methods: prune_methods(doc.methods)
        with doc
    };
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || methods_have_docs(doc.methods);
    ret doc;
}

#[test]
fn should_elide_undocumented_impls() {
    let doc = test::mk_doc("impl i for int { fn a() { } }");
    assert vec::is_empty(doc.topmod.impls());
}

#[test]
fn should_not_elide_documented_impls() {
    let doc = test::mk_doc("#[doc = \"hey\"] impl i for int { fn a() { } }");
    assert vec::is_not_empty(doc.topmod.impls());
}

#[test]
fn should_not_elide_impls_with_documented_methods() {
    let doc = test::mk_doc("impl i for int { #[doc = \"hey\"] fn a() { } }");
    assert vec::is_not_empty(doc.topmod.impls());
}

#[test]
fn should_not_elide_undocumented_impl_methods() {
    let doc = test::mk_doc("#[doc = \"hey\"] impl i for int { fn a() { } }");
    assert vec::is_not_empty(doc.topmod.impls()[0].methods);
}

#[test]
fn should_elide_undocumented_impl_method_args() {
    let doc = test::mk_doc(
        "#[doc = \"hey\"] impl i for int { fn a(b: bool) { } }");
    assert vec::is_empty(doc.topmod.impls()[0].methods[0].args);
}

#[test]
fn should_elide_undocumented_impl_method_return_values() {
    let doc = test::mk_doc(
        "#[doc = \"hey\"] impl i for int { fn a() -> int { } }");
    assert doc.topmod.impls()[0].methods[0].return.ty == none;
}

#[cfg(test)]
mod test {
    fn mk_doc(source: str) -> doc::cratedoc {
        let srv = astsrv::mk_srv_from_str(source);
        let doc = extract::from_srv(srv, "");
        let doc = attr_pass::mk_pass()(srv, doc);
        run(srv, doc)
    }
}
<|endoftext|>


<commit_before><commit_msg>Old main included.<commit_after>extern crate mles_utils;

use std::thread;
use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc::channel;
use std::net::TcpStream;
use std::net::TcpListener;
use std::collections::HashMap;
use std::io::Write;
use std::time::Duration;
use std::option::Option;
use std::str;
use mles_utils::*;

fn process_channel(tx: Sender<Sender<TcpStream>>, removedtx: Sender<String>, this_channel: String ) {
    let mut cnt = 0;
    let (thr_tx, thr_rx): (Sender<TcpStream>, Receiver<TcpStream>) = channel();
    println!("Spawned: New channel created!");
    let mut users = HashMap::new();
    let mut messages: Vec<Vec<u8>> = Vec::new();
    tx.send(thr_tx.clone()).unwrap();
    loop {
        let mut removals = Vec::new();
        let mut newuser = true;
        while newuser {
            match thr_rx.try_recv() {
                Ok(val) => {
                    let mut thr: TcpStream = val;
                    cnt += 1;
                    println!("Adding user {}", cnt);
                    users.insert(cnt, thr.try_clone().unwrap());

                    /* If a new user, all push messages to her */
                    for buf in &messages {
                        thr.write(buf.as_slice()).unwrap();
                    }
                    newuser = true;
                },
                    Err(_) => { newuser = false; }
            }
        }
        for (user, thr_socket) in &users {
            let stream = thr_socket.try_clone().unwrap();
            let tuple = read_n(&stream, 4);
            let status = tuple.0;
            match status {
                Ok(0) => {
                    removals.push(user.clone());
                },
                    _ => {}
            }
            let mut buf = tuple.1;
            if 0 == buf.len() {
                continue;
            }
            if read_hdr_type(buf.as_slice()) != 'M' as u32 {
                continue;
            }
            let hdr_len = read_hdr_len(buf.as_slice()) as u64;
            if 0 == hdr_len {
                continue;
            }
            let tuple = read_n(&stream, hdr_len);
            let status = tuple.0;
            match status {
                Ok(0) => {
                    removals.push(user.clone());
                },
                    _ => {}
            }
            let payload = tuple.1;
            if payload.len() != (hdr_len as usize) {
                continue;
            }
            buf.extend(payload);
            for (another_user, mut thr_sock) in &users {
                if user != another_user {
                    thr_sock.write(buf.as_slice()).unwrap();
                }
            }
            /* Add to local db */
            messages.push(buf);
        }
        for removal in &removals {
            println!("Removing user {}", removal);
            users.remove(removal);
        }
        if cnt > 0 && users.is_empty() {
            removedtx.send(this_channel).unwrap();
            break;
        }
    }
}

fn main() {
    let address = "0.0.0.0:8081";
    let listener = TcpListener::bind(&address).unwrap();
    let mut spawned = HashMap::new();
    let option: Option<Duration> = Some(Duration::from_millis(50));

    let addr = listener.local_addr().unwrap();
    println!("Listening for connections on {}", addr);
    let (tx, rx) = channel();
    let (removedtx, removedrx) = channel();

    for socket in listener.incoming() {
        /* Check first has anybody removed channels */
        let mut remrx = true;
        while remrx {
            match removedrx.try_recv() {
                Ok(val) => {
                    let removed_channel: String = val;
                    println!("Removing unused channel {}", removed_channel.as_str());
                    spawned.remove(&removed_channel);
                    remrx = true;
                },
                Err(_) => { remrx = false; }
            }
        }
        /* 1. Read incoming msg channel
         * 2. If it does not exist, spawn new thread
         * 3. Send socket to thread
         */
        let socket = socket.unwrap();
        let stream = socket.try_clone().unwrap();
        let tuple = read_n(&stream, 4);
        let status = tuple.0;
        match status {
            Ok(0) => {
               continue;
            },
            Ok(_) => {},
            _ => {
               continue;
            },
        }
        let buf = tuple.1;
        if 0 == buf.len() {
            continue;
        }
        if read_hdr_type(buf.as_slice()) != 'M' as u32 {
            println!("Incorrect payload type");
            continue;
        }
        let tuple = read_n(&stream, read_hdr_len(buf.as_slice()) as u64);
        let status = tuple.0;
        match status {
            Ok(0) => {
               continue;
            },
            Ok(_) => {},
            _ => {
               continue;
            },
        }
        let buf = tuple.1;
        let decoded_msg = message_decode(buf.as_slice());
        if 0 == decoded_msg.channel.len() {
            continue;
        }
        socket.set_nodelay(true);
        socket.set_read_timeout(option);
        if !spawned.contains_key(decoded_msg.channel.as_str()) {
            let tx = tx.clone();
            let removedtx = removedtx.clone();
            let this_channel = decoded_msg.channel.clone();
            thread::spawn(move|| process_channel(tx, removedtx, this_channel));

            let thr_feed = rx.recv().unwrap();
            println!("Channel {}", decoded_msg.channel.as_str());
            spawned.insert(decoded_msg.channel.clone(), thr_feed);
        }
        let thr_socket = spawned.get_mut(&decoded_msg.channel).unwrap();
        thr_socket.send(socket).unwrap();
    }
}
<|endoftext|>


<commit_before><commit_msg>Add error when an ident was expected<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for issue 868<commit_after>fn f<T>(g: fn() -> T) -> T { g() }

fn main() {
  let _x = f( | | { 10 });
    // used to be: cannot determine a type for this expression
    f(| | { });
    // ditto
    f( | | { ()});
    // always worked
    let _: () = f(| | { });
    // empty block with no type info should compile too
    let _ = f(||{});
    let _ = (||{});
}

<|endoftext|>