<commit_before>use core::clone::Clone;
use core::mem::size_of;
use core::option::Option;

use common::memory::*;
use common::safeptr::*;
use common::string::*;
use common::vector::*;

use drivers::disk::*;

#[derive(Copy, Clone)]
pub struct Block {
    address: u64
}

#[derive(Copy, Clone)]
struct Extent{
    block: Block,
    length: u64
}

pub struct Header {
    pub signature: [u8; 4],
    pub version: u32,
    pub root_sector_list: Block,
    pub free_sector_list: Block,
    pub name: [u8; 256],
    reserved: [u8; 232]
}

struct Node {
    parent_collection: Block,
    data_sector_list: Block,
    data_size: u64,
    user_id: u64,
    group_id: u64,
    mode: u64,
    create_time: u64,
    modify_time: u64,
    access_time: u64,
    name: [u8; 256],
    reserved: [u8; 184]
}

struct SectorList {
    parent_node: Block,
    fragment_number: u64,
    last_fragment: Block,
    next_fragment: Block,
    extents: [Extent; 30]
}

pub struct UnFS {
    disk: Disk,
    pub header: &'static Header
}

impl UnFS {
    pub fn new() -> UnFS{
        unsafe{
            return UnFS::from_disk(Disk::new());
        }
    }

    pub unsafe fn from_disk(disk: Disk) -> UnFS{
        // TODO: Do not use header loaded in memory
        UnFS { disk:disk, header: &*(0x7E00 as *const Header) }
    }

    pub unsafe fn node(&self, filename: String) -> *const Node{
        let mut ret: *const Node = 0 as *const Node;
        let mut node_matches = false;

        let root_sector_list_ptr: SafePtr<SectorList> = SafePtr::new();
        match root_sector_list_ptr.get() {
            Option::Some(root_sector_list) => {
                let mut root_sector_list_address = self.header.root_sector_list.address;
                while root_sector_list_address > 0 {
                    self.disk.read(root_sector_list_address, 1, root_sector_list_ptr.unsafe_ptr() as usize);

                    for extent_i in 0..30 {
                        let extent = (*root_sector_list).extents[extent_i];
                        if extent.block.address > 0 {
                            for node_address in extent.block.address..extent.block.address + extent.length {
                                let node = alloc(size_of::<Node>()) as *const Node;
                                self.disk.read(node_address, 1, node as usize);

                                node_matches = true;
                                let mut i = 0;
                                for c in filename.chars()  {
                                    if !(i < 256 && (*node).name[i] == c as u8) {
                                        node_matches = false;
                                        break;
                                    }
                                    i += 1;
                                }
                                if !(i < 256 && (*node).name[i] == 0) {
                                    node_matches = false;
                                }

                                if node_matches {
                                    ret = node;
                                    break;
                                }else{
                                    unalloc(node as usize);
                                }
                            }
                        }

                        if node_matches {
                            break;
                        }
                    }

                    root_sector_list_address = (*root_sector_list).next_fragment.address;

                    if node_matches{
                        break;
                    }
                }
            },
            Option::None => ()
        }
        ret
    }

    pub fn list(&self, directory: String) -> Vector<String> {
        let mut ret = Vector::<String>::new();

        unsafe{
            let root_sector_list_ptr: SafePtr<SectorList> = SafePtr::new();
            match root_sector_list_ptr.get() {
                Option::Some(root_sector_list) => {
                    let mut root_sector_list_address = self.header.root_sector_list.address;
                    while root_sector_list_address > 0 {
                        self.disk.read(root_sector_list_address, 1, root_sector_list_ptr.unsafe_ptr() as usize);

                        for extent_i in 0..30 {
                            let extent = (*root_sector_list).extents[extent_i];
                            if extent.block.address > 0 {
                                for node_address in extent.block.address..extent.block.address + extent.length {
                                    let node = alloc(size_of::<Node>()) as *const Node;
                                    self.disk.read(node_address, 1, node as usize);

                                    let node_name = String::from_c_slice(&(*node).name);
                                    if node_name.starts_with(directory.clone()) {
                                        ret = ret + node_name;
                                    }

                                    unalloc(node as usize);
                                }
                            }
                        }

                        root_sector_list_address = (*root_sector_list).next_fragment.address;
                    }
                },
                Option::None => ()
            }
        }

        ret
    }

    pub unsafe fn load(&self, filename: String) -> usize{
        let mut destination = 0;

        let node = self.node(filename);

        if node as usize > 0{
            if (*node).data_sector_list.address > 0 {
                let sector_list_ptr: SafePtr<SectorList> = SafePtr::new();
                match sector_list_ptr.get() {
                    Option::Some(sector_list) => {
                        self.disk.read((*node).data_sector_list.address, 1, sector_list_ptr.unsafe_ptr() as usize);

                        //TODO: More than one extent, extent sector count > 64K
                        let mut size = 0;
                        for i in 0..1 {
                            if sector_list.extents[i].block.address > 0 && sector_list.extents[i].length > 0{
                                size += (*sector_list).extents[i].length * 512;
                            }
                        }

                        destination = alloc(size as usize);
                        if destination > 0 {
                            for i in 0..1 {
                                if sector_list.extents[i].block.address > 0 && sector_list.extents[i].length > 0{
                                    self.disk.read(sector_list.extents[i].block.address, sector_list.extents[i].length as u16, destination);
                                }
                            }
                        }
                    },
                    Option::None => ()
                }
            }

            unalloc(node as usize);
        }

        return destination;
    }

    // TODO: Support realloc of LBAs
    pub unsafe fn save(&self, filename: String, source: usize){
        let node = self.node(filename);

        if node as usize > 0{
            if (*node).data_sector_list.address > 0 {
                let sector_list_ptr: SafePtr<SectorList> = SafePtr::new();
                match sector_list_ptr.get() {
                    Option::Some(sector_list) => {
                        self.disk.read((*node).data_sector_list.address, 1, sector_list_ptr.unsafe_ptr() as usize);

                        if source > 0 {
                            for i in 0..1 {
                                if sector_list.extents[i].block.address > 0 && sector_list.extents[i].length > 0{
                                    self.disk.write(sector_list.extents[i].block.address, sector_list.extents[i].length as u16, source);
                                }
                            }
                        }
                    },
                    Option::None => ()
                }
            }

            unalloc(node as usize);
        }
    }
}
<commit_msg>Cleanup syntax where possible<commit_after>use core::clone::Clone;
use core::mem::size_of;
use core::option::Option;

use common::memory::*;
use common::safeptr::*;
use common::string::*;
use common::vector::*;

use drivers::disk::*;

#[derive(Copy, Clone)]
pub struct Block {
    address: u64
}

#[derive(Copy, Clone)]
struct Extent{
    block: Block,
    length: u64
}

pub struct Header {
    pub signature: [u8; 4],
    pub version: u32,
    pub root_sector_list: Block,
    pub free_sector_list: Block,
    pub name: [u8; 256],
    reserved: [u8; 232]
}

struct Node {
    parent_collection: Block,
    data_sector_list: Block,
    data_size: u64,
    user_id: u64,
    group_id: u64,
    mode: u64,
    create_time: u64,
    modify_time: u64,
    access_time: u64,
    name: [u8; 256],
    reserved: [u8; 184]
}

struct SectorList {
    parent_node: Block,
    fragment_number: u64,
    last_fragment: Block,
    next_fragment: Block,
    extents: [Extent; 30]
}

pub struct UnFS {
    disk: Disk,
    pub header: &'static Header
}

impl UnFS {
    pub fn new() -> UnFS{
        unsafe{
            return UnFS::from_disk(Disk::new());
        }
    }

    pub unsafe fn from_disk(disk: Disk) -> UnFS{
        // TODO: Do not use header loaded in memory
        UnFS { disk:disk, header: &*(0x7E00 as *const Header) }
    }

    pub unsafe fn node(&self, filename: String) -> *const Node{
        let mut ret: *const Node = 0 as *const Node;
        let mut node_matches = false;

        let root_sector_list_ptr: SafePtr<SectorList> = SafePtr::new();
        match root_sector_list_ptr.get() {
            Option::Some(root_sector_list) => {
                let mut root_sector_list_address = self.header.root_sector_list.address;
                while root_sector_list_address > 0 {
                    self.disk.read(root_sector_list_address, 1, root_sector_list_ptr.unsafe_ptr() as usize);

                    for extent_i in 0..30 {
                        let extent = root_sector_list.extents[extent_i];
                        if extent.block.address > 0 {
                            for node_address in extent.block.address..extent.block.address + extent.length {
                                let node = alloc(size_of::<Node>()) as *const Node;
                                self.disk.read(node_address, 1, node as usize);

                                node_matches = true;
                                let mut i = 0;
                                for c in filename.chars()  {
                                    if !(i < 256 && (*node).name[i] == c as u8) {
                                        node_matches = false;
                                        break;
                                    }
                                    i += 1;
                                }
                                if !(i < 256 && (*node).name[i] == 0) {
                                    node_matches = false;
                                }

                                if node_matches {
                                    ret = node;
                                    break;
                                }else{
                                    unalloc(node as usize);
                                }
                            }
                        }

                        if node_matches {
                            break;
                        }
                    }

                    root_sector_list_address = root_sector_list.next_fragment.address;

                    if node_matches{
                        break;
                    }
                }
            },
            Option::None => ()
        }
        ret
    }

    pub fn list(&self, directory: String) -> Vector<String> {
        let mut ret = Vector::<String>::new();

        unsafe{
            let root_sector_list_ptr: SafePtr<SectorList> = SafePtr::new();
            match root_sector_list_ptr.get() {
                Option::Some(root_sector_list) => {
                    let mut root_sector_list_address = self.header.root_sector_list.address;
                    while root_sector_list_address > 0 {
                        self.disk.read(root_sector_list_address, 1, root_sector_list_ptr.unsafe_ptr() as usize);

                        for extent_i in 0..30 {
                            let extent = root_sector_list.extents[extent_i];
                            if extent.block.address > 0 {
                                for node_address in extent.block.address..extent.block.address + extent.length {
                                    let node = alloc(size_of::<Node>()) as *const Node;
                                    self.disk.read(node_address, 1, node as usize);

                                    let node_name = String::from_c_slice(&(*node).name);
                                    if node_name.starts_with(directory.clone()) {
                                        ret = ret + node_name;
                                    }

                                    unalloc(node as usize);
                                }
                            }
                        }

                        root_sector_list_address = root_sector_list.next_fragment.address;
                    }
                },
                Option::None => ()
            }
        }

        ret
    }

    pub unsafe fn load(&self, filename: String) -> usize{
        let mut destination = 0;

        let node = self.node(filename);

        if node as usize > 0{
            if (*node).data_sector_list.address > 0 {
                let sector_list_ptr: SafePtr<SectorList> = SafePtr::new();
                match sector_list_ptr.get() {
                    Option::Some(sector_list) => {
                        self.disk.read((*node).data_sector_list.address, 1, sector_list_ptr.unsafe_ptr() as usize);

                        //TODO: More than one extent, extent sector count > 64K
                        let mut size = 0;
                        for i in 0..1 {
                            if sector_list.extents[i].block.address > 0 && sector_list.extents[i].length > 0{
                                size += sector_list.extents[i].length * 512;
                            }
                        }

                        destination = alloc(size as usize);
                        if destination > 0 {
                            for i in 0..1 {
                                if sector_list.extents[i].block.address > 0 && sector_list.extents[i].length > 0{
                                    self.disk.read(sector_list.extents[i].block.address, sector_list.extents[i].length as u16, destination);
                                }
                            }
                        }
                    },
                    Option::None => ()
                }
            }

            unalloc(node as usize);
        }

        return destination;
    }

    // TODO: Support realloc of LBAs
    pub unsafe fn save(&self, filename: String, source: usize){
        let node = self.node(filename);

        if node as usize > 0{
            if (*node).data_sector_list.address > 0 {
                let sector_list_ptr: SafePtr<SectorList> = SafePtr::new();
                match sector_list_ptr.get() {
                    Option::Some(sector_list) => {
                        self.disk.read((*node).data_sector_list.address, 1, sector_list_ptr.unsafe_ptr() as usize);

                        if source > 0 {
                            for i in 0..1 {
                                if sector_list.extents[i].block.address > 0 && sector_list.extents[i].length > 0{
                                    self.disk.write(sector_list.extents[i].block.address, sector_list.extents[i].length as u16, source);
                                }
                            }
                        }
                    },
                    Option::None => ()
                }
            }

            unalloc(node as usize);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix bug when parsing block comment in tokenizer. Add control symbol(`$` `#` `,` `;` `:` `.`) parsing. Add a test.<commit_after><|endoftext|>


<commit_before>// TODO:
//      - Simplify using instruction iterators
//      - Make movement mode
//      - Record modifiers

mod editor;
pub use self::editor::*;

mod mode;
pub use self::mode::*;

mod movement;
pub use self::movement::*;

mod cursor;
pub use self::cursor::*;

mod insert;
pub use self::insert::*;

mod exec;
pub use self::exec::*;

use redox::*;

pub fn main() {
    let mut window = Window::new((rand() % 400 + 50) as isize,
								 (rand() % 300 + 50) as isize,
								 576,
								 400,
								 &"Sodium").unwrap();

    let mut editor = Editor::new();

    let mut inp = window.event_iter().map(|x| {
        x.to_option()
    }).inst_iter(&editor.cursor().mode);

    for i in inp {
        editor.exec(i, &mut inp);
    }
    window.set([255, 255, 255, 255]);

}

pub fn redraw() {
    /*
                    // Redraw window
                    window.set([255, 255, 255, 255]);

                    for (y, row) in editor.text.iter().enumerate() {
                        for (x, c) in row.iter().enumerate() {
                            window.char(8 * (y - editor.scroll_y) as isize, 16 * (x - editor.scroll_x) as isize, *c, [128, 128, 128, 255]);
                            if editor.cursor().x == x && editor.cursor().y == y {
                                window.char(8 * (y - editor.scroll_y) as isize, 16 * (x - editor.scroll_x) as isize, '_', [128, 128, 128, 255]);
                            }
                        }
                    }
    */
}
<commit_msg>Convert tabs to spaces and remove some tailing spaces<commit_after>// TODO:
//      - Simplify using instruction iterators
//      - Make movement mode
//      - Record modifiers

mod editor;
pub use self::editor::*;

mod mode;
pub use self::mode::*;

mod movement;
pub use self::movement::*;

mod cursor;
pub use self::cursor::*;

mod insert;
pub use self::insert::*;

mod exec;
pub use self::exec::*;

use redox::*;

pub fn main() {
    let mut window = Window::new((rand() % 400 + 50) as isize,
                                 (rand() % 300 + 50) as isize,
                                 576,
                                 400,
                                 &"Sodium").unwrap();

    let mut editor = Editor::new();

    let mut inp = window.event_iter().map(|x| {
        x.to_option()
    }).inst_iter(&editor.cursor().mode);

    for i in inp {
        editor.exec(i, &mut inp);
    }
    window.set([255, 255, 255, 255]);

}

pub fn redraw() {
    /*
                    // Redraw window
                    window.set([255, 255, 255, 255]);

                    for (y, row) in editor.text.iter().enumerate() {
                        for (x, c) in row.iter().enumerate() {
                            window.char(8 * (y - editor.scroll_y) as isize, 16 * (x - editor.scroll_x) as isize, *c, [128, 128, 128, 255]);
                            if editor.cursor().x == x && editor.cursor().y == y {
                                window.char(8 * (y - editor.scroll_y) as isize, 16 * (x - editor.scroll_x) as isize, '_', [128, 128, 128, 255]);
                            }
                        }
                    }
    */
}
<|endoftext|>


<commit_before><commit_msg>Reduced test case for current backwarding bug.<commit_after>//xfail-stage0
//xfail-stage1
//xfail-stage2
//xfail-stage3
use std;

fn main() {

    obj a() {
        fn foo() -> int { ret 2; }
        fn bar() -> int { ret self.foo(); }
    }

    let my_a = a();

    let my_b = obj () {
        fn baz() -> int { ret self.foo(); }
        with my_a
    };

    // These should all be 2.
    log_err my_a.foo();
    log_err my_a.bar();
    log_err my_b.foo();

    // This works fine.  It sends us to foo on my_b, which forwards to
    // foo on my_a.
    log_err my_b.baz();

    // Currently segfaults.  It forwards us to bar on my_a, which
    // backwards us to foo on my_b, which forwards us to foo on my_a
    // -- or, at least, that's how it should work.
    log_err my_b.bar();

}
<|endoftext|>


<commit_before><commit_msg>Add some more tests<commit_after>extern crate session_types;

use std::thread::spawn;
use std::sync::mpsc::channel;

use session_types::*;

fn srv(c: Chan<(), Recv<u8, Eps>>) {
    let (c, x) = c.recv();
    c.close();
}

fn main() {
    let (c1, c2) = session_channel();
    let t1 = spawn(|| { srv(c1) });

    srv(c2);                    //~ ERROR
    c2.close();                 //~ ERROR
    c2.sel1();                  //~ ERROR
    c2.sel2();                  //~ ERROR
    c2.offer();                 //~ ERROR
    c2.enter();                 //~ ERROR
    c2.zero();                  //~ ERROR
    c2.succ();                  //~ ERROR
    c2.recv();                  //~ ERROR

    c2.send(42).close();

    t1.join().unwrap();
}
<|endoftext|>


<commit_before><commit_msg>imag-wiki: Move from error-chain to failure<commit_after><|endoftext|>


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

// This test exercises cases where cyclic structure is legal,
// including when the cycles go through data-structures such
// as `Vec` or `TypedArena`.
//
// The intent is to cover as many such cases as possible, ensuring
// that if the compiler did not complain circa Rust 1.x (1.2 as of
// this writing), then it will continue to not complain in the future.
//
// Note that while some of the tests are only exercising using the
// given collection as a "backing store" for a set of nodes that hold
// the actual cycle (and thus the cycle does not go through the
// collection itself in such cases), in general we *do* want to make
// sure to have at least one example exercising a cycle that goes
// through the collection, for every collection type that supports
// this.

#![feature(vecmap)]

use std::cell::Cell;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::collections::LinkedList;
use std::collections::VecDeque;
use std::collections::VecMap;
use std::collections::btree_map::BTreeMap;
use std::collections::btree_set::BTreeSet;
use std::hash::{Hash, Hasher};

const PRINT: bool = false;

pub fn main() {
    let c_orig = ContextData {
        curr_depth: 0,
        max_depth: 3,
        visited: 0,
        max_visits: 1000,
        skipped: 0,
        curr_mark: 0,
        saw_prev_marked: false,
    };

    // Cycle 1: { v[0] -> v[1], v[1] -> v[0] };
    // does not exercise `v` itself
    let v: Vec<S> = vec![Named::new("s0"),
                         Named::new("s1")];
    v[0].next.set(Some(&v[1]));
    v[1].next.set(Some(&v[0]));

    let mut c = c_orig.clone();
    c.curr_mark = 10;
    assert!(!c.saw_prev_marked);
    v[0].for_each_child(&mut c);
    assert!(c.saw_prev_marked);

    if PRINT { println!(""); }

    // Cycle 2: { v[0] -> v, v[1] -> v }
    let v: V = Named::new("v");
    v.contents[0].set(Some(&v));
    v.contents[1].set(Some(&v));

    let mut c = c_orig.clone();
    c.curr_mark = 20;
    assert!(!c.saw_prev_marked);
    v.for_each_child(&mut c);
    assert!(c.saw_prev_marked);

    if PRINT { println!(""); }

    // Cycle 3: { hk0 -> hv0, hv0 -> hk0, hk1 -> hv1, hv1 -> hk1 };
    // does not exercise `h` itself

    let mut h: HashMap<H,H> = HashMap::new();
    h.insert(Named::new("hk0"), Named::new("hv0"));
    h.insert(Named::new("hk1"), Named::new("hv1"));
    for (key, val) in h.iter() {
        val.next.set(Some(key));
        key.next.set(Some(val));
    }

    let mut c = c_orig.clone();
    c.curr_mark = 30;
    for (key, _) in h.iter() {
        c.curr_mark += 1;
        c.saw_prev_marked = false;
        key.for_each_child(&mut c);
        assert!(c.saw_prev_marked);
    }

    if PRINT { println!(""); }

    // Cycle 4: { h -> (hmk0,hmv0,hmk1,hmv1), {hmk0,hmv0,hmk1,hmv1} -> h }

    let mut h: HashMap<HM,HM> = HashMap::new();
    h.insert(Named::new("hmk0"), Named::new("hmv0"));
    h.insert(Named::new("hmk0"), Named::new("hmv0"));
    for (key, val) in h.iter() {
        val.contents.set(Some(&h));
        key.contents.set(Some(&h));
    }

    let mut c = c_orig.clone();
    c.max_depth = 2;
    c.curr_mark = 40;
    for (key, _) in h.iter() {
        c.curr_mark += 1;
        c.saw_prev_marked = false;
        key.for_each_child(&mut c);
        assert!(c.saw_prev_marked);
        // break;
    }

    if PRINT { println!(""); }

    // Cycle 5: { vd[0] -> vd[1], vd[1] -> vd[0] };
    // does not exercise vd itself
    let mut vd: VecDeque<S> = VecDeque::new();
    vd.push_back(Named::new("d0"));
    vd.push_back(Named::new("d1"));
    vd[0].next.set(Some(&vd[1]));
    vd[1].next.set(Some(&vd[0]));

    let mut c = c_orig.clone();
    c.curr_mark = 50;
    assert!(!c.saw_prev_marked);
    vd[0].for_each_child(&mut c);
    assert!(c.saw_prev_marked);

    if PRINT { println!(""); }

    // Cycle 6: { vd -> (vd0, vd1), {vd0, vd1} -> vd }
    let mut vd: VecDeque<VD> = VecDeque::new();
    vd.push_back(Named::new("vd0"));
    vd.push_back(Named::new("vd1"));
    vd[0].contents.set(Some(&vd));
    vd[1].contents.set(Some(&vd));

    let mut c = c_orig.clone();
    c.curr_mark = 60;
    assert!(!c.saw_prev_marked);
    vd[0].for_each_child(&mut c);
    assert!(c.saw_prev_marked);

    if PRINT { println!(""); }

    // Cycle 7: { vm -> (vm0, vm1), {vm0, vm1} -> vm }
    let mut vm: VecMap<VM> = VecMap::new();
    vm.insert(0, Named::new("vm0"));
    vm.insert(1, Named::new("vm1"));
    vm[0].contents.set(Some(&vm));
    vm[1].contents.set(Some(&vm));

    let mut c = c_orig.clone();
    c.curr_mark = 70;
    assert!(!c.saw_prev_marked);
    vm[0].for_each_child(&mut c);
    assert!(c.saw_prev_marked);

    if PRINT { println!(""); }

    // Cycle 8: { ll -> (ll0, ll1), {ll0, ll1} -> ll }
    let mut ll: LinkedList<LL> = LinkedList::new();
    ll.push_back(Named::new("ll0"));
    ll.push_back(Named::new("ll1"));
    for e in &ll {
        e.contents.set(Some(&ll));
    }

    let mut c = c_orig.clone();
    c.curr_mark = 80;
    for e in &ll {
        c.curr_mark += 1;
        c.saw_prev_marked = false;
        e.for_each_child(&mut c);
        assert!(c.saw_prev_marked);
        // break;
    }

    if PRINT { println!(""); }

    // Cycle 9: { bh -> (bh0, bh1), {bh0, bh1} -> bh }
    let mut bh: BinaryHeap<BH> = BinaryHeap::new();
    bh.push(Named::new("bh0"));
    bh.push(Named::new("bh1"));
    for b in bh.iter() {
        b.contents.set(Some(&bh));
    }

    let mut c = c_orig.clone();
    c.curr_mark = 90;
    for b in &bh {
        c.curr_mark += 1;
        c.saw_prev_marked = false;
        b.for_each_child(&mut c);
        assert!(c.saw_prev_marked);
        // break;
    }

    if PRINT { println!(""); }

    // Cycle 10: { btm -> (btk0, btv1), {bt0, bt1} -> btm }
    let mut btm: BTreeMap<BTM, BTM> = BTreeMap::new();
    btm.insert(Named::new("btk0"), Named::new("btv0"));
    btm.insert(Named::new("btk1"), Named::new("btv1"));
    for (k, v) in btm.iter() {
        k.contents.set(Some(&btm));
        v.contents.set(Some(&btm));
    }

    let mut c = c_orig.clone();
    c.curr_mark = 100;
    for (k, _) in &btm {
        c.curr_mark += 1;
        c.saw_prev_marked = false;
        k.for_each_child(&mut c);
        assert!(c.saw_prev_marked);
        // break;
    }

    if PRINT { println!(""); }

    // Cycle 10: { bts -> (bts0, bts1), {bts0, bts1} -> btm }
    let mut bts: BTreeSet<BTS> = BTreeSet::new();
    bts.insert(Named::new("bts0"));
    bts.insert(Named::new("bts1"));
    for v in bts.iter() {
        v.contents.set(Some(&bts));
    }

    let mut c = c_orig.clone();
    c.curr_mark = 100;
    for b in &bts {
        c.curr_mark += 1;
        c.saw_prev_marked = false;
        b.for_each_child(&mut c);
        assert!(c.saw_prev_marked);
        // break;
    }
}

trait Named {
    fn new(&'static str) -> Self;
    fn name(&self) -> &str;
}

trait Marked<M> {
    fn mark(&self) -> M;
    fn set_mark(&self, mark: M);
}

struct S<'a> {
    name: &'static str,
    mark: Cell<u32>,
    next: Cell<Option<&'a S<'a>>>,
}

impl<'a> Named for S<'a> {
    fn new<'b>(name: &'static str) -> S<'b> {
        S { name: name, mark: Cell::new(0), next: Cell::new(None) }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for S<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

struct V<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Vec<Cell<Option<&'a V<'a>>>>,
}

impl<'a> Named for V<'a> {
    fn new<'b>(name: &'static str) -> V<'b> {
        V { name: name,
            mark: Cell::new(0),
            contents: vec![Cell::new(None), Cell::new(None)]
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for V<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

#[derive(Eq)]
struct H<'a> {
    name: &'static str,
    mark: Cell<u32>,
    next: Cell<Option<&'a H<'a>>>,
}

impl<'a> Named for H<'a> {
    fn new<'b>(name: &'static str) -> H<'b> {
        H { name: name, mark: Cell::new(0), next: Cell::new(None) }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for H<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

impl<'a> PartialEq for H<'a> {
    fn eq(&self, rhs: &H<'a>) -> bool {
        self.name == rhs.name
    }
}

impl<'a> Hash for H<'a> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state)
    }
}

#[derive(Eq)]
struct HM<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Cell<Option<&'a HashMap<HM<'a>, HM<'a>>>>,
}

impl<'a> Named for HM<'a> {
    fn new<'b>(name: &'static str) -> HM<'b> {
        HM { name: name,
             mark: Cell::new(0),
             contents: Cell::new(None)
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for HM<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

impl<'a> PartialEq for HM<'a> {
    fn eq(&self, rhs: &HM<'a>) -> bool {
        self.name == rhs.name
    }
}

impl<'a> Hash for HM<'a> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.name.hash(state)
    }
}

struct VD<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Cell<Option<&'a VecDeque<VD<'a>>>>,
}

impl<'a> Named for VD<'a> {
    fn new<'b>(name: &'static str) -> VD<'b> {
        VD { name: name,
             mark: Cell::new(0),
             contents: Cell::new(None)
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for VD<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

struct VM<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Cell<Option<&'a VecMap<VM<'a>>>>,
}

impl<'a> Named for VM<'a> {
    fn new<'b>(name: &'static str) -> VM<'b> {
        VM { name: name,
             mark: Cell::new(0),
             contents: Cell::new(None)
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for VM<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

struct LL<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Cell<Option<&'a LinkedList<LL<'a>>>>,
}

impl<'a> Named for LL<'a> {
    fn new<'b>(name: &'static str) -> LL<'b> {
        LL { name: name,
             mark: Cell::new(0),
             contents: Cell::new(None)
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for LL<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

struct BH<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Cell<Option<&'a BinaryHeap<BH<'a>>>>,
}

impl<'a> Named for BH<'a> {
    fn new<'b>(name: &'static str) -> BH<'b> {
        BH { name: name,
             mark: Cell::new(0),
             contents: Cell::new(None)
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for BH<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

impl<'a> Eq for BH<'a> { }

impl<'a> PartialEq for BH<'a> {
    fn eq(&self, rhs: &BH<'a>) -> bool {
        self.name == rhs.name
    }
}

impl<'a> PartialOrd for BH<'a> {
    fn partial_cmp(&self, rhs: &BH<'a>) -> Option<Ordering> {
        Some(self.cmp(rhs))
    }
}

impl<'a> Ord for BH<'a> {
    fn cmp(&self, rhs: &BH<'a>) -> Ordering {
        self.name.cmp(rhs.name)
    }
}

struct BTM<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Cell<Option<&'a BTreeMap<BTM<'a>, BTM<'a>>>>,
}

impl<'a> Named for BTM<'a> {
    fn new<'b>(name: &'static str) -> BTM<'b> {
        BTM { name: name,
             mark: Cell::new(0),
             contents: Cell::new(None)
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for BTM<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

impl<'a> Eq for BTM<'a> { }

impl<'a> PartialEq for BTM<'a> {
    fn eq(&self, rhs: &BTM<'a>) -> bool {
        self.name == rhs.name
    }
}

impl<'a> PartialOrd for BTM<'a> {
    fn partial_cmp(&self, rhs: &BTM<'a>) -> Option<Ordering> {
        Some(self.cmp(rhs))
    }
}

impl<'a> Ord for BTM<'a> {
    fn cmp(&self, rhs: &BTM<'a>) -> Ordering {
        self.name.cmp(rhs.name)
    }
}

struct BTS<'a> {
    name: &'static str,
    mark: Cell<u32>,
    contents: Cell<Option<&'a BTreeSet<BTS<'a>>>>,
}

impl<'a> Named for BTS<'a> {
    fn new<'b>(name: &'static str) -> BTS<'b> {
        BTS { name: name,
             mark: Cell::new(0),
             contents: Cell::new(None)
        }
    }
    fn name(&self) -> &str { self.name }
}

impl<'a> Marked<u32> for BTS<'a> {
    fn mark(&self) -> u32 { self.mark.get() }
    fn set_mark(&self, mark: u32) { self.mark.set(mark); }
}

impl<'a> Eq for BTS<'a> { }

impl<'a> PartialEq for BTS<'a> {
    fn eq(&self, rhs: &BTS<'a>) -> bool {
        self.name == rhs.name
    }
}

impl<'a> PartialOrd for BTS<'a> {
    fn partial_cmp(&self, rhs: &BTS<'a>) -> Option<Ordering> {
        Some(self.cmp(rhs))
    }
}

impl<'a> Ord for BTS<'a> {
    fn cmp(&self, rhs: &BTS<'a>) -> Ordering {
        self.name.cmp(rhs.name)
    }
}

trait Context {
    fn should_act(&self) -> bool;
    fn increase_visited(&mut self);
    fn increase_skipped(&mut self);
    fn increase_depth(&mut self);
    fn decrease_depth(&mut self);
}

trait PrePost<T> {
    fn pre(&mut self, &T);
    fn post(&mut self, &T);
    fn hit_limit(&mut self, &T);
}

trait Children<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<Self>, Self: Sized;

    fn descend_into_self<C>(&self, context: &mut C)
        where C: Context + PrePost<Self>, Self: Sized
    {
        context.pre(self);
        if context.should_act() {
            context.increase_visited();
            context.increase_depth();
            self.for_each_child(context);
            context.decrease_depth();
        } else {
            context.hit_limit(self);
            context.increase_skipped();
        }
        context.post(self);
    }

    fn descend<'b, C>(&self, c: &Cell<Option<&'b Self>>, context: &mut C)
        where C: Context + PrePost<Self>, Self: Sized
    {
        if let Some(r) = c.get() {
            r.descend_into_self(context);
        }
    }
}

impl<'a> Children<'a> for S<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<S<'a>>
    {
        self.descend(&self.next, context);
    }
}

impl<'a> Children<'a> for V<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<V<'a>>
    {
        for r in &self.contents {
            self.descend(r, context);
        }
    }
}

impl<'a> Children<'a> for H<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<H<'a>>
    {
        self.descend(&self.next, context);
    }
}

impl<'a> Children<'a> for HM<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<HM<'a>>
    {
        if let Some(ref hm) = self.contents.get() {
            for (k, v) in hm.iter() {
                for r in &[k, v] {
                    r.descend_into_self(context);
                }
            }
        }
    }
}

impl<'a> Children<'a> for VD<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<VD<'a>>
    {
        if let Some(ref vd) = self.contents.get() {
            for r in vd.iter() {
                r.descend_into_self(context);
            }
        }
    }
}

impl<'a> Children<'a> for VM<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<VM<'a>>
    {
        if let Some(ref vd) = self.contents.get() {
            for (_idx, r) in vd.iter() {
                r.descend_into_self(context);
            }
        }
    }
}

impl<'a> Children<'a> for LL<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<LL<'a>>
    {
        if let Some(ref ll) = self.contents.get() {
            for r in ll.iter() {
                r.descend_into_self(context);
            }
        }
    }
}

impl<'a> Children<'a> for BH<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<BH<'a>>
    {
        if let Some(ref bh) = self.contents.get() {
            for r in bh.iter() {
                r.descend_into_self(context);
            }
        }
    }
}

impl<'a> Children<'a> for BTM<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<BTM<'a>>
    {
        if let Some(ref bh) = self.contents.get() {
            for (k, v) in bh.iter() {
                for r in &[k, v] {
                    r.descend_into_self(context);
                }
            }
        }
    }
}

impl<'a> Children<'a> for BTS<'a> {
    fn for_each_child<C>(&self, context: &mut C)
        where C: Context + PrePost<BTS<'a>>
    {
        if let Some(ref bh) = self.contents.get() {
            for r in bh.iter() {
                r.descend_into_self(context);
            }
        }
    }
}

#[derive(Copy, Clone)]
struct ContextData {
    curr_depth: usize,
    max_depth: usize,
    visited: usize,
    max_visits: usize,
    skipped: usize,
    curr_mark: u32,
    saw_prev_marked: bool,
}

impl Context for ContextData {
    fn should_act(&self) -> bool {
        self.curr_depth < self.max_depth && self.visited < self.max_visits
    }
    fn increase_visited(&mut self) { self.visited += 1; }
    fn increase_skipped(&mut self) { self.skipped += 1; }
    fn increase_depth(&mut self) {  self.curr_depth += 1; }
    fn decrease_depth(&mut self) {  self.curr_depth -= 1; }
}

impl<T:Named+Marked<u32>> PrePost<T> for ContextData {
    fn pre(&mut self, t: &T) {
        for _ in 0..self.curr_depth {
            if PRINT { print!(" "); }
        }
        if PRINT { println!("prev {}", t.name()); }
        if t.mark() == self.curr_mark {
            for _ in 0..self.curr_depth {
                if PRINT { print!(" "); }
            }
            if PRINT { println!("(probably previously marked)"); }
            self.saw_prev_marked = true;
        }
        t.set_mark(self.curr_mark);
    }
    fn post(&mut self, t: &T) {
        for _ in 0..self.curr_depth {
            if PRINT { print!(" "); }
        }
        if PRINT { println!("post {}", t.name()); }
    }
    fn hit_limit(&mut self, t: &T) {
        for _ in 0..self.curr_depth {
            if PRINT { print!(" "); }
        }
        if PRINT { println!("LIMIT {}", t.name()); }
    }
}
<|endoftext|>


<commit_before><commit_msg>run tidy check and added comments<commit_after><|endoftext|>


<commit_before><commit_msg>Start TAR loader<commit_after>// ba6ce90ac85fd41a3ff1d9b203f6de3e73a6b6da

/// Get the first file of the tar string (Header + Content)
pub fn get_file(s: &[u8]) -> File {

}

pub struct File<'a> {
    file: &'a [u8],
    header: TarHeader<'a>,
}

pub struct TarHeader<'a> {
    // I really need constant sized pointers here :(
    name: &'a [u8],
    mode: &'a [u8],
    group: &'a [u8],
    user: &'a [u8],
    size: &'a [u8],
    last_mod: &'a [u8],
    checksum: &'a [u8],
    link_ind: &u8,
    link: &[u8],
    ustar_header: UStarHeader,
}
<|endoftext|>


<commit_before><commit_msg>Fix test.<commit_after><|endoftext|>


<commit_before><commit_msg>fixed channel move issue, button uses correct signal<commit_after><|endoftext|>


<commit_before><commit_msg>Remove unnecessary warning suppression<commit_after><|endoftext|>


<commit_before><commit_msg>Moved inital setup of the value to request guard.<commit_after><|endoftext|>


<commit_before><commit_msg>add pihex program<commit_after>use std::env;

extern crate pihex;
use pihex::*;

fn main() {
    let place: u32 = env::args().nth(1).and_then(|x| x.parse().ok()).unwrap_or(0);
    print!("{}: ", place);
    for i in 0..8 {
        print!("{}", pihex(place + 4 * i as u32));
        if (i + 1) % 8 == 0 {
            print!("\n")
        } else {
            print!(" ")
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>problem: rustfmt is failing solution: fix it<commit_after><|endoftext|>


<commit_before>#![crate_name = "clog"]
#![comment = "A conventional changelog generator"]
#![license = "MIT"]
#![feature(macro_rules, phase)]

extern crate regex;
#[phase(plugin)]
extern crate regex_macros;
extern crate serialize;
#[phase(plugin)] extern crate docopt_macros;
extern crate docopt;
extern crate time;

use git::{ LogReaderConfig, get_commits, get_latest_tag };
use log_writer::{ LogWriter, LogWriterOptions };
use section_builder::build_sections;
use std::io::{File, Append, Write};
use docopt::FlagParser;

mod common;
mod git;
mod log_writer;
mod section_builder;

docopt!(Args, "clog

Usage:
  clog [--repository=<link> --setversion=<version> --subtitle=<subtitle>
        --from=<from> --to=<to> --from-latest-tag]

Options:
  -h --help               Show this screen.
  --version               Show version
  -r --repository=<link>  e.g https://github.com/thoughtram/clog
  --setversion=<version>  e.g. 0.1.0
  --subtitle=<subtitle>   e.g. crazy-release-name
  --from=<from>           e.g. 12a8546
  --to=<to>               e.g. 8057684
  --from-latest-tag       uses the latest tag as starting point. Ignores other --from parameter")

fn main () {

    let args: Args = FlagParser::parse().unwrap_or_else(|e| e.exit());

    let log_reader_config = LogReaderConfig {
        grep: "^feat|^fix|BREAKING'".to_string(),
        format: "%H%n%s%n%b%n==END==".to_string(),
        from: if args.flag_from_latest_tag { get_latest_tag() } else { args.flag_from },
        to: args.flag_to
    };

    let commits = get_commits(log_reader_config);

    let sections = build_sections(commits.clone());
    let mut file = File::open_mode(&Path::new("changelog.md"), Append, Write).ok().unwrap();
    let mut writer = LogWriter::new(&mut file, LogWriterOptions {
        repository_link: args.flag_repository,
        version: args.flag_setversion,
        subtitle: args.flag_subtitle
    });

    writer.write_header();
    writer.write_section("Bug Fixes", &sections.fixes);
    writer.write_section("Features", &sections.features);
}
<commit_msg>feat(main): print out notification<commit_after>#![crate_name = "clog"]
#![comment = "A conventional changelog generator"]
#![license = "MIT"]
#![feature(macro_rules, phase)]

extern crate regex;
#[phase(plugin)]
extern crate regex_macros;
extern crate serialize;
#[phase(plugin)] extern crate docopt_macros;
extern crate docopt;
extern crate time;

use git::{ LogReaderConfig, get_commits, get_latest_tag };
use log_writer::{ LogWriter, LogWriterOptions };
use section_builder::build_sections;
use std::io::{File, Append, Write};
use docopt::FlagParser;
use time::get_time;

mod common;
mod git;
mod log_writer;
mod section_builder;

docopt!(Args, "clog

Usage:
  clog [--repository=<link> --setversion=<version> --subtitle=<subtitle>
        --from=<from> --to=<to> --from-latest-tag]

Options:
  -h --help               Show this screen.
  --version               Show version
  -r --repository=<link>  e.g https://github.com/thoughtram/clog
  --setversion=<version>  e.g. 0.1.0
  --subtitle=<subtitle>   e.g. crazy-release-name
  --from=<from>           e.g. 12a8546
  --to=<to>               e.g. 8057684
  --from-latest-tag       uses the latest tag as starting point. Ignores other --from parameter")

fn main () {

    let start_nsec = get_time().nsec;
    let args: Args = FlagParser::parse().unwrap_or_else(|e| e.exit());

    let log_reader_config = LogReaderConfig {
        grep: "^feat|^fix|BREAKING'".to_string(),
        format: "%H%n%s%n%b%n==END==".to_string(),
        from: if args.flag_from_latest_tag { get_latest_tag() } else { args.flag_from },
        to: args.flag_to
    };

    let commits = get_commits(log_reader_config);

    let sections = build_sections(commits.clone());
    let mut file = File::open_mode(&Path::new("changelog.md"), Append, Write).ok().unwrap();
    let mut writer = LogWriter::new(&mut file, LogWriterOptions {
        repository_link: args.flag_repository,
        version: args.flag_setversion,
        subtitle: args.flag_subtitle
    });

    writer.write_header();
    writer.write_section("Bug Fixes", &sections.fixes);
    writer.write_section("Features", &sections.features);

    let end_nsec = get_time().nsec;
    let elapsed_mssec = (end_nsec - start_nsec) / 1000000;
    println!("changelog updated. (took {} ms)", elapsed_mssec);
}
<|endoftext|>


<commit_before><commit_msg>Hello world<commit_after><|endoftext|>


<commit_before><commit_msg>add tree-draw template<commit_after>use std;
use shader;
use glium::backend::glutin_backend::GlutinFacade;
use mesh::{VertexBase, Mesh};

pub struct Tree {
    pub model: Mesh<VertexBase>,
    pub shader: shader::Shader,
}

impl Tree {
    fn load_shaders(facade: &GlutinFacade) -> Result<shader::Shader, String> {
        let vertex_shader_src = r#"
    #version 140

    in vec3 pos;

    uniform mat4 proj;
    uniform mat4 view;
    uniform mat4 model;

    void main() {
        gl_Position = proj * (view * model) * vec4(pos, 1.0);
    }
"#;

        let fragment_shader_src = r#"
    #version 140

    out vec4 color;

    void main() {
        color = vec4(1.0, 1.0, 0.0, 1.0);
    }
"#;
        Ok(try!(shader::Shader::new(facade, vertex_shader_src, fragment_shader_src)))
    }

    pub fn new(facade: &GlutinFacade) -> Result<Tree, String>
    {
        let height = 2.0_f32;
        let radius = 0.5_f32;
        let cnt_vertex = 10;

        let mut vb = vec![VertexBase { pos: [0.0, height, 0.0] }];
        let mut ib = Vec::<u32>::new();

        let mut angle = 0.0_f32;
        let step = std::f32::consts::PI * 2.0_f32 / (cnt_vertex as f32);
        for i in 1 .. cnt_vertex + 1 {
            let sin = angle.sin();
            let cos = angle.cos();
            vb.push(VertexBase { pos: [radius * cos, 0.0_f32, radius * sin] });
            ib.push(i);
            ib.push(0);
            ib.push(if i == cnt_vertex {1} else {i + 1});

            angle += step;
		}

        let mesh = try!(Mesh::new(facade, &vb, &ib));
        let shader = try!(Tree::load_shaders(facade));

        Ok(Tree {
            model: mesh,
            shader: shader,
        })
    }

}
<|endoftext|>


<commit_before><commit_msg>Expression language is almost powerful enough to render v1<commit_after><|endoftext|>


<commit_before><commit_msg>Rearrange modules<commit_after><|endoftext|>


<commit_before><commit_msg>add missing u16 endian functions<commit_after><|endoftext|>


<commit_before><commit_msg>Origin offset fixes<commit_after><|endoftext|>


<commit_before>extern crate time;
extern crate sqlite3;

use time::Timespec;

use sqlite3::{DatabaseConnection, SqliteResult};
use sqlite3::{SQLITE_NULL, SQLITE_TEXT};

#[deriving(Show)]
struct Person {
    id: i32,
    name: String,
    time_created: Timespec,
    // TODO: data: Option<Vec<u8>>
}

pub fn main() {
    match io() {
        Ok(ppl) => println!("Found people: {}", ppl),
        Err(oops) => fail!(oops)
    }
}

fn io() -> SqliteResult<Vec<Person>> {
    let mut conn = try!(DatabaseConnection::new());

    try!(conn.exec("CREATE TABLE person (
                 id              SERIAL PRIMARY KEY,
                 name            VARCHAR NOT NULL,
                 time_created    TIMESTAMP NOT NULL
               )"));

    let me = Person {
        id: 0,
        name: "Dan".to_string(),
        time_created: time::get_time(),
    };
    {
        let mut tx = try!(conn.prepare("INSERT INTO person (name, time_created)
                           VALUES ($1, $2)"));
        let changes = try!(conn.update(&mut tx, [&me.name, &me.time_created]));
        assert_eq!(changes, 1);
    }

    let mut stmt = try!(conn.prepare("SELECT id, name, time_created FROM person"));

    let mut ppl = vec!();
    try!(stmt.query(
        [], |row| {
            ppl.push(Person {
                id: row.get(0u),
                name: row.get(1u),
                time_created: row.get(2u)
            });
            Ok(())
        }));
    Ok(ppl)
}
<commit_msg>oops... pruning assert_eq!()s leads to unused imports<commit_after>extern crate time;
extern crate sqlite3;

use time::Timespec;

use sqlite3::{DatabaseConnection, SqliteResult};

#[deriving(Show)]
struct Person {
    id: i32,
    name: String,
    time_created: Timespec,
    // TODO: data: Option<Vec<u8>>
}

pub fn main() {
    match io() {
        Ok(ppl) => println!("Found people: {}", ppl),
        Err(oops) => fail!(oops)
    }
}

fn io() -> SqliteResult<Vec<Person>> {
    let mut conn = try!(DatabaseConnection::new());

    try!(conn.exec("CREATE TABLE person (
                 id              SERIAL PRIMARY KEY,
                 name            VARCHAR NOT NULL,
                 time_created    TIMESTAMP NOT NULL
               )"));

    let me = Person {
        id: 0,
        name: "Dan".to_string(),
        time_created: time::get_time(),
    };
    {
        let mut tx = try!(conn.prepare("INSERT INTO person (name, time_created)
                           VALUES ($1, $2)"));
        let changes = try!(conn.update(&mut tx, [&me.name, &me.time_created]));
        assert_eq!(changes, 1);
    }

    let mut stmt = try!(conn.prepare("SELECT id, name, time_created FROM person"));

    let mut ppl = vec!();
    try!(stmt.query(
        [], |row| {
            ppl.push(Person {
                id: row.get(0u),
                name: row.get(1u),
                time_created: row.get(2u)
            });
            Ok(())
        }));
    Ok(ppl)
}
<|endoftext|>


<commit_before><commit_msg>stackpool...<commit_after><|endoftext|>


<commit_before><commit_msg>check button<commit_after><|endoftext|>


<commit_before><commit_msg>Add missing documentation<commit_after><|endoftext|>


<commit_before>use crate::command_prelude::*;

use cargo::ops;

pub fn cli() -> App {
    subcommand("uninstall")
        .about("Remove a Rust binary")
        .arg(opt("quiet", "No output printed to stdout").short("q"))
        .arg(Arg::with_name("spec").multiple(true))
        .arg_package_spec_simple("Package to uninstall")
        .arg(multi_opt("bin", "NAME", "Only uninstall the binary NAME"))
        .arg(opt("root", "Directory to uninstall packages from").value_name("DIR"))
        .after_help("Run `cargo help uninstall` for more detailed information.\n")
}

pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
    let root = args.value_of("root");
    let specs = args
        .values_of("spec")
        .unwrap_or_else(|| args.values_of("package").unwrap_or_default())
        .collect();
    ops::uninstall(root, specs, &values(args, "bin"), config)?;
    Ok(())
}
<commit_msg>feat: check cargo uninstall package opt with empty value<commit_after>use crate::command_prelude::*;

use cargo::ops;

pub fn cli() -> App {
    subcommand("uninstall")
        .about("Remove a Rust binary")
        .arg(opt("quiet", "No output printed to stdout").short("q"))
        .arg(Arg::with_name("spec").multiple(true))
        .arg_package_spec_simple("Package to uninstall")
        .arg(multi_opt("bin", "NAME", "Only uninstall the binary NAME"))
        .arg(opt("root", "Directory to uninstall packages from").value_name("DIR"))
        .after_help("Run `cargo help uninstall` for more detailed information.\n")
}

pub fn exec(config: &mut Config, args: &ArgMatches<'_>) -> CliResult {
    let root = args.value_of("root");

    if args.is_present_with_zero_values("package") {
        return Err(anyhow::anyhow!(
            "\"--package <SPEC>\" requires a SPEC format value.\n\
            Run `cargo help pkgid` for more information about SPEC format."
        ).into())
    }

    let specs = args
        .values_of("spec")
        .unwrap_or_else(|| args.values_of("package").unwrap_or_default())
        .collect();
    ops::uninstall(root, specs, &values(args, "bin"), config)?;
    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>Change colours, draw all cell states<commit_after><|endoftext|>


<commit_before><commit_msg>Add a regression test for #53457<commit_after>// run-pass

#![feature(existential_type)]

existential type X: Clone;

fn bar<F: Fn(&i32) + Clone>(f: F) -> F {
    f
}

fn foo() -> X {
    bar(|x| ())
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>fix(mod): support is and not keywords<commit_after><|endoftext|>


<commit_before><commit_msg>start new<commit_after>fn merge<T>(l1: Vec<T>, l2: Vec<T>) -> Vec<T> {}
<|endoftext|>


<commit_before><commit_msg>fix example<commit_after><|endoftext|>


<commit_before><commit_msg>Add regression test<commit_after>// check-pass
// Regression test for #78507.
fn foo() -> Option<fn() -> Option<bool>> {
    Some(|| Some(true))
}
fn main() {}
<|endoftext|>


<commit_before><commit_msg>A third tranche of rustdoc comments for renderervk.rs<commit_after><|endoftext|>


<commit_before><commit_msg>fix: unwrap to unwrap_or<commit_after><|endoftext|>


<commit_before><commit_msg>lex: fix invalid start of some tokens<commit_after><|endoftext|>


<commit_before><commit_msg>omfg forgot to commit free_vars.rs long ago...<commit_after>use lib::front::ast::*;

pub type Instantiations<'src> = BTreeSet<(Vec<Type<'src>>, Type<'src>)>;
pub type FreeVarInsts<'src> = BTreeMap<&'src str, Instantiations<'src>>;

/// Returns the unit set of the single element `x`
fn set_of<T: cmp::Ord>(x: T) -> BTreeSet<T> {
    once(x).collect()
}

/// Returns the map of `{k} -> {v}`
fn map_of<K: cmp::Ord, V>(k: K, v: V) -> BTreeMap<K, V> {
    once((k, v)).collect()
}

pub fn free_vars_in_exprs<'a, 'src: 'a, T>(es: T) -> FreeVarInsts<'src>
where
    T: IntoIterator<Item = &'a Expr<'src>>,
{
    let mut fvs = BTreeMap::new();
    for (k, v) in es.into_iter().flat_map(|e2| free_vars_in_expr(e2)) {
        fvs.entry(k).or_insert(BTreeSet::new()).extend(v)
    }
    fvs
}

/// Returns a map of the free variables in `e`, where each variable name is mapped to the
/// instantiations of the free variable in `e`
pub fn free_vars_in_expr<'src>(e: &Expr<'src>) -> FreeVarInsts<'src> {
    use self::ast::Expr::*;
    match *e {
        Nil(_) | NumLit(_) | StrLit(_) | Bool(_) => FreeVarInsts::new(),
        Variable(ref v) => {
            map_of(
                v.ident.s,
                set_of((
                    v.typ.get_inst_args().unwrap_or(&[]).to_vec(),
                    // Apply instantiation to type to remove wrapping `App`
                    v.typ.canonicalize(),
                )),
            )
        }
        App(box ref a) => free_vars_in_exprs([&a.func, &a.arg].iter().cloned()),
        If(ref i) => free_vars_in_exprs(
            [&i.predicate, &i.consequent, &i.alternative]
                .iter()
                .cloned(),
        ),
        Lambda(box ref l) => free_vars_in_lambda(l),
        Let(box ref l) => {
            let mut es = vec![&l.body];
            for binding in l.bindings.bindings() {
                if binding.typ.is_monomorphic() {
                    es.push(&binding.val)
                } else {
                    es.extend(binding.mono_insts.values())
                }
            }
            let mut fvs = free_vars_in_exprs(es.iter().cloned());
            for b in l.bindings.bindings() {
                fvs.remove(b.ident.s);
            }
            fvs
        }
        TypeAscript(_) => panic!("free_vars_in_expr encountered TypeAscript"),
        Cons(box ref c) => free_vars_in_exprs([&c.car, &c.cdr].iter().cloned()),
        Car(box ref c) => free_vars_in_expr(&c.expr),
        Cdr(box ref c) => free_vars_in_expr(&c.expr),
        Cast(ref c) => free_vars_in_expr(&c.expr),
        New(ref n) => free_vars_in_exprs(&n.members),
    }
}

/// Returns a map of the free variables in `e`, where each variable name is mapped to the
/// instantiations of the free variable in `e`
pub fn free_vars_in_lambda<'src>(lam: &Lambda<'src>) -> FreeVarInsts<'src> {
    let mut free_vars = free_vars_in_expr(&lam.body);
    free_vars.remove(lam.param_ident.s);
    free_vars
}

/// Generate a new variable for use in a binding, that does not occur in `not_in_expr`
pub fn new_variable<'s>(not_in_expr: &Expr<'s>) -> String {
    let frees = free_vars_in_expr(not_in_expr);
    (0..)
        .map(|i| format("_{}", i))
        .find(|s| !frees.contains_key(&s))
        .expect("ICE: Out of variable names in new_variable")
}
<|endoftext|>


<commit_before>// Suppress all warnings from casts which overflow.
#![allow(overflowing_literals)]

fn main() {
    let decimal = 65.4321_f32;

    // Error! No implicit conversion
    let integer: u8 = decimal;
    // FIXME ^ Comment out this line

    // Explicit conversion
    let integer = decimal as u8;
    let character = integer as char;

    println!("Casting: {} -> {} -> {}", decimal, integer, character);

    // when casting any value to an unsigned type, T,
    // std::T::MAX + 1 is added or subtracted until the value
    // fits into the new type

    // 1000 already fits in a u16
    println!("1000 as a u16 is: {}", 1000 as u16);

    // 1000 - 256 - 256 - 256 = 232
    // Under the hood, the first 8 bits from the least significant bit (LSB) are used,
    // while the rest towards the most significant bit (MSB) get truncated.
    println!("1000 as a u8 is : {}", 1000 as u8);
    // -1 + 256 = 255
    println!("  -1 as a u8 is : {}", (-1i8) as u8);

    // For positive numbers, this is the same as the modulus
    println!("1000 mod 256 is : {}", 1000 % 256);

    // When casting to a signed type, the result is the same as
    // first casting to the corresponding unsigned type then
    // taking the two's complement.

    // Unless it already fits, of course.
    println!(" 128 as a i16 is: {}", 128 as i16);
    // 128 as u8 -> 128, whose two's complement in eight bits is:
    println!(" 128 as a i8 is : {}", 128 as i8);

    // repeating the example above
    // 1000 as u8 -> 232
    println!("1000 as a i8 is : {}", 1000 as i8);
    // and the two's complement of 232 is -24
    println!(" 232 as a i8 is : {}", 232 as i8);

}
<commit_msg>cast/cast.rs: try to clear up two's complement #741<commit_after>// Suppress all warnings from casts which overflow.
#![allow(overflowing_literals)]

fn main() {
    let decimal = 65.4321_f32;

    // Error! No implicit conversion
    let integer: u8 = decimal;
    // FIXME ^ Comment out this line

    // Explicit conversion
    let integer = decimal as u8;
    let character = integer as char;

    println!("Casting: {} -> {} -> {}", decimal, integer, character);

    // when casting any value to an unsigned type, T,
    // std::T::MAX + 1 is added or subtracted until the value
    // fits into the new type

    // 1000 already fits in a u16
    println!("1000 as a u16 is: {}", 1000 as u16);

    // 1000 - 256 - 256 - 256 = 232
    // Under the hood, the first 8 least significant bits (LSB) are kept,
    // while the rest towards the most significant bit (MSB) get truncated.
    println!("1000 as a u8 is : {}", 1000 as u8);
    // -1 + 256 = 255
    println!("  -1 as a u8 is : {}", (-1i8) as u8);

    // For positive numbers, this is the same as the modulus
    println!("1000 mod 256 is : {}", 1000 % 256);

    // When casting to a signed type, the (bitwise) result is the same as
    // first casting to the corresponding unsigned type. If the most significant
    // bit of that value is 1, then the value is negative.

    // Unless it already fits, of course.
    println!(" 128 as a i16 is: {}", 128 as i16);
    // 128 as u8 -> 128, whose two's complement in eight bits is:
    println!(" 128 as a i8 is : {}", 128 as i8);

    // repeating the example above
    // 1000 as u8 -> 232
    println!("1000 as a i8 is : {}", 1000 as i8);
    // and the two's complement of 232 is -24
    println!(" 232 as a i8 is : {}", 232 as i8);

}
<|endoftext|>


<commit_before><commit_msg>Add an echo client<commit_after>extern crate janeiro;

#[macro_use]
extern crate log;
extern crate env_logger;

use std::str;
use std::io;

use janeiro::{Rio, Transport, Protocol, Reason};

struct EchoClientProtocol {
    running: bool
}

impl EchoClientProtocol {
    fn new() -> EchoClientProtocol {
        EchoClientProtocol{running: true}
    }
}

impl Protocol for EchoClientProtocol {

    fn connection_made(&mut self, _: &mut Transport) {
    }

    #[allow(unused_variables)]
    fn data_received(&mut self, data: &[u8], transport: &mut Transport) {
        let s_data = str::from_utf8(data).unwrap().trim();

        println!("{}", s_data);

        if !self.running {
            println!("I am done");
            return
        }

        let mut input = String::new();
        match io::stdin().read_line(&mut input) {
            Ok(n) => {
                println!("{} bytes read", n);
                println!("{}", input);
            }
            Err(error) => println!("error: {}", error),
        }

        let input_str = input.as_str();
        if input_str == "bye\n".to_string() {
            self.running = false;
        }
        println!("{:?}", self.running);
        transport.write(input_str.as_bytes());

    }

    fn connection_lost(&mut self, reason: Reason) {
        match reason {
            Reason::ConnectionLost => info!("Connection closed by peer"),
            Reason::HangUp => info!("Hang hup"),
            Reason::ConnectionError => println!("Connection error"),
        }

    }
}

fn main() {
    env_logger::init().unwrap();
    info!("Start the client");
    let mut rio = Rio::new();
    let protocol = EchoClientProtocol::new();
    let result = rio.connect("0.0.0.0:8888", Box::new(protocol));

    match result {
        Ok(token) => {
            info!("Start running the loop");
            rio.run_until(&|rio: &Rio| -> bool {
                rio.contains(token)
                });
        },

        Err(_) => {
            panic!("Cannot register client")
        }

    }
}
<|endoftext|>


<commit_before><commit_msg>Add example with the code in tutorial 01<commit_after>#[macro_use]
extern crate glium;
extern crate glutin;

fn main() {
    use glium::{DisplayBuild, Surface};
    let display = glutin::WindowBuilder::new().build_glium().unwrap();

    #[derive(Copy)]
    struct Vertex {
        position: [f32; 2],
    }

    implement_vertex!(Vertex, position);

    let vertex1 = Vertex { position: [-0.5, -0.5] };
    let vertex2 = Vertex { position: [ 0.0,  0.5] };
    let vertex3 = Vertex { position: [ 0.5, -0.25] };
    let shape = vec![vertex1, vertex2, vertex3];

    let vertex_buffer = glium::VertexBuffer::new(&display, shape);
    let indices = glium::index::NoIndices(glium::index::PrimitiveType::TrianglesList);

    let vertex_shader_src = r#"
        #version 110

        attribute vec2 position;

        void main() {
            gl_Position = vec4(position, 0.0, 1.0);
        }
    "#;

    let fragment_shader_src = r#"
        #version 110

        void main() {
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
        }
    "#;

    let program = glium::Program::from_source(&display, vertex_shader_src, fragment_shader_src, None).unwrap();

    loop {
        let mut target = display.draw();
        target.clear_color(0.0, 0.0, 1.0, 1.0);
        target.draw(&vertex_buffer, &indices, &program, &glium::uniforms::EmptyUniforms,
                    &std::default::Default::default()).unwrap();
        target.finish();

        if display.is_closed() {
            break;
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>test: Add a test case for linearize_ty_params() and shapes<commit_after>// xfail-test

// Tests that shapes respect linearize_ty_params().

tag option<T> {
    none;
    some(T);
}

type smallintmap<T> = @{mutable v: [mutable option<T>]};

fn mk<@T>() -> smallintmap<T> {
    let v: [mutable option<T>] = [mutable];
    ret @{mutable v: v};
}

fn f<@T,@U>() {
    let sim = mk::<U>();
    log_err sim;
}

fn main() {
    f::<int,int>();
}

<|endoftext|>


<commit_before><commit_msg>Nearly done with section 2<commit_after><|endoftext|>


<commit_before>use middleware::{Middleware, Continue, MiddlewareResult};
use hyper::uri::RequestUri::AbsolutePath;
use request::Request;
use response::Response;
use router::HttpRouter;
use hyper::method::Method;
use hyper::status::StatusCode;
use router::{Matcher, FORMAT_PARAM};

/// A Route is the basic data structure that stores both the path
/// and the handler that gets executed for the route.
/// The path can contain variable pattern such as `user/:userid/invoices`
pub struct Route {
    pub method: Method,
    pub handler: Box<Middleware + Send + Sync + 'static>,
    matcher: Matcher
}

/// A RouteResult is what the router returns when `match_route` is called.
/// It contains the matched `route` and also a `params` property holding
/// a HashMap with the keys being the variable names and the value being the
/// evaluated string
pub struct RouteResult<'a> {
    pub route: &'a Route,
    params: Vec<(String, String)>
}

impl<'a> RouteResult<'a> {
    pub fn param(&self, key: &str) -> &str {
        for &(ref k, ref v) in &self.params {
            if k == &key {
                return &v[..]
            }
        }

        // FIXME: should have a default format
        if key == FORMAT_PARAM { return "" }
        panic!("unknown param: {}", key)
    }
}

/// The Router's job is it to hold routes and to resolve them later against
/// concrete URLs. The router is also a regular middleware and needs to be
/// added to the middleware stack with `server.utilize(router)`.
pub struct Router {
    routes: Vec<Route>,
}

impl Router {
    pub fn new () -> Router {
        Router {
            routes: Vec::new()
        }
    }

    pub fn match_route<'a>(&'a self, method: &Method, path: &str) -> Option<RouteResult<'a>> {
        // Strip off the querystring when matching a route
        let path = path.splitn(1, '?').next().unwrap();

        self.routes
            .iter()
            .find(|item| item.method == *method && item.matcher.is_match(path))
            .map(|route|
                RouteResult {
                    params: extract_params(route, path),
                    route: route
                }
            )
    }
}

fn extract_params(route: &Route, path: &str) -> Vec<(String, String)> {
    match route.matcher.captures(path) {
        Some(captures) => {
            captures.iter_named()
                    .filter_map(|(name, subcap)| {
                        subcap.map(|cap| (name.to_string(), cap.to_string()))
                    })
                    .collect()
        }
        None => vec![]
    }
}

impl HttpRouter for Router {
    fn add_route<M: Into<Matcher>, H: Middleware>(&mut self, method: Method, matcher: M, handler: H) {
        let route = Route {
            matcher: matcher.into(),
            method: method,
            handler: Box::new(handler),
        };

        self.routes.push(route);
    }
}

impl Middleware for Router {
    fn invoke<'a, 'b>(&'a self, req: &mut Request<'b, 'a, 'b>, mut res: Response<'a>)
                        -> MiddlewareResult<'a> {
        debug!("Router::invoke for '{:?}'", req.origin.uri);
        let route_result = match req.origin.uri {
            AbsolutePath(ref url) => self.match_route(&req.origin.method, &**url),
            _ => None
        };
        debug!("route_result.route.path: {:?}", route_result.as_ref().map(|r| r.route.matcher.path()));

        match route_result {
            Some(route_result) => {
                res.set_status(StatusCode::Ok);
                let handler = &route_result.route.handler;
                req.route_result = Some(route_result);
                handler.invoke(req, res)
            },
            None => Ok(Continue(res))
        }
    }
}

#[test]
fn creates_regex_with_captures () {
    let matcher: Matcher = "foo/:uid/bar/:groupid".into();
    let caps = matcher.captures("foo/4711/bar/5490").unwrap();

    assert_eq!(matcher.path(), "foo/:uid/bar/:groupid(\\.:format)?");
    assert_eq!(caps.at(1).unwrap(), "4711");
    assert_eq!(caps.at(2).unwrap(), "5490");

    let matcher: Matcher = "foo/*/:uid/bar/:groupid".into();
    let caps = matcher.captures("foo/test/4711/bar/5490").unwrap();

    assert_eq!(matcher.path(), "foo/*/:uid/bar/:groupid(\\.:format)?");
    assert_eq!(caps.at(1).unwrap(), "4711");
    assert_eq!(caps.at(2).unwrap(), "5490");

    let matcher: Matcher = "foo/**/:uid/bar/:groupid".into();
    let caps = matcher.captures("foo/test/another/4711/bar/5490").unwrap();

    assert_eq!(matcher.path(), "foo/**/:uid/bar/:groupid(\\.:format)?");
    assert_eq!(caps.at(1).unwrap(), "4711");
    assert_eq!(caps.at(2).unwrap(), "5490");

    let matcher: Matcher = "foo/**/:format/bar/:groupid".into();
    let caps = matcher.captures("foo/test/another/4711/bar/5490").unwrap();

    assert_eq!(matcher.path(), "foo/**/:format/bar/:groupid");
    assert_eq!(caps.name("format").unwrap(), "4711");
    assert_eq!(caps.name("groupid").unwrap(), "5490");
}

#[test]
fn creates_valid_regex_for_routes () {
    let regex1: Matcher = "foo/:uid/bar/:groupid".into();
    let regex2: Matcher = "foo/*/bar".into();
    let regex3: Matcher = "foo/**/bar".into();

    assert_eq!(regex1.is_match("foo/4711/bar/5490"), true);
    assert_eq!(regex1.is_match("foo/4711/bar/5490?foo=true&bar=false"), true);
    assert_eq!(regex1.is_match("foo/4711/bar"), false);
    assert_eq!(regex1.is_match("foo/4711/bar?foo=true&bar=false"), false);
    assert_eq!(regex1.is_match("foo/4711/bar/test%20spacing"), true);
    assert_eq!(regex1.is_match("foo/4711/bar/5281?foo=test%20spacing&bar=false"), true);

    assert_eq!(regex2.is_match("foo/4711/bar"), true);
    assert_eq!(regex2.is_match("foo/4711/barr"), false);
    assert_eq!(regex2.is_match("foo/4711/bar?foo=true&bar=false"), true);
    assert_eq!(regex2.is_match("foo/4711/4712/bar"), false);
    assert_eq!(regex2.is_match("foo/4711/4712/bar?foo=true&bar=false"), false);

    assert_eq!(regex3.is_match("foo/4711/bar"), true);
    assert_eq!(regex3.is_match("foo/4711/bar?foo=true&bar=false"), true);
    assert_eq!(regex3.is_match("foo/4711/4712/bar"), true);
    assert_eq!(regex3.is_match("foo/4711/4712/bar?foo=true&bar=false"), true);

    //ensure that this works with commas too
    assert_eq!(regex1.is_match("foo/4711/bar/5490,1234"), true);
    assert_eq!(regex1.is_match("foo/4711/bar/5490,1234?foo=true&bar=false"), true);
    assert_eq!(regex1.is_match("foo/4711/bar"), false);
    assert_eq!(regex1.is_match("foo/4711/bar?foo=1,2,3&bar=false"), false);
}

#[test]
fn can_match_var_routes () {
    let route_store = &mut Router::new();
    let handler = middleware! { "hello from foo" };

    route_store.add_route(Method::Get, "/foo/:userid", handler);
    route_store.add_route(Method::Get, "/bar", handler);
    route_store.add_route(Method::Get, "/file/:format/:file", handler);

    let route_result = route_store.match_route(&Method::Get, "/foo/4711").unwrap();
    assert_eq!(route_result.param("userid"), "4711");

    let route_result = route_store.match_route(&Method::Get, "/bar/4711");
    assert!(route_result.is_none());

    let route_result = route_store.match_route(&Method::Get, "/foo");
    assert!(route_result.is_none());

    // ensure that this will work with commas too
    let route_result = route_store.match_route(&Method::Get, "/foo/123,456");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    assert_eq!(route_result.param("userid"), "123,456");

    // ensure that this will work with spacing too
    let route_result = route_store.match_route(&Method::Get, "/foo/John%20Doe");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    assert_eq!(route_result.param("userid"), "John%20Doe");

    // check for optional format param
    let route_result = route_store.match_route(&Method::Get, "/foo/John%20Doe.json");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    assert_eq!(route_result.param("userid"), "John%20Doe");
    assert_eq!(route_result.param("format"), "json");

    // ensure format works with queries
    let route_result = route_store.match_route(&Method::Get,
    "/foo/5490,1234.csv?foo=true&bar=false");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    // NOTE: `.param` doesn't cover query params currently
    assert_eq!(route_result.param("userid"), "5490,1234");
    assert_eq!(route_result.param("format"), "csv");

    // ensure format works with no format
    let route_result = route_store.match_route(&Method::Get,
                                               "/foo/5490,1234?foo=true&bar=false").unwrap();

    assert_eq!(route_result.param("format"), "");

    // ensure format works if defined by user
    let route_result = route_store.match_route(&Method::Get, "/file/markdown/something?foo=true");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    // NOTE: `.param` doesn't cover query params currently
    assert_eq!(route_result.param("file"), "something");
    assert_eq!(route_result.param("format"), "markdown");
}

#[test]
fn regex_path() {
    use regex::Regex;

    let route_store = &mut Router::new();
    let handler = middleware! { "hello from foo" };

    let regex = Regex::new("/(foo|bar)").unwrap();
    route_store.add_route(Method::Get, regex, handler);

    let route_result = route_store.match_route(&Method::Get, "/foo");
    assert!(route_result.is_some());

    let route_result = route_store.match_route(&Method::Get, "/bar");
    assert!(route_result.is_some());

    let route_result = route_store.match_route(&Method::Get, "/bar?foo");
    assert!(route_result.is_some());

    let route_result = route_store.match_route(&Method::Get, "/baz");
    assert!(route_result.is_none());
}

#[test]
fn regex_path_named() {
    use regex::Regex;

    let route_store = &mut Router::new();
    let handler = middleware! { "hello from foo" };

    let regex = Regex::new("/(?Pfoo|bar)/b").unwrap();
    route_store.add_route(Method::Get, regex, handler);

    let route_result = route_store.match_route(&Method::Get, "/foo/b");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    assert_eq!(route_result.param("a"), "foo");

    let route_result = route_store.match_route(&Method::Get, "/bar/b");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    assert_eq!(route_result.param("a"), "bar");

    let route_result = route_store.match_route(&Method::Get, "/baz/b");
    assert!(route_result.is_none());
}

#[test]
fn ignores_querystring() {
    use regex::Regex;

    let route_store = &mut Router::new();
    let handler = middleware! { "hello from foo" };

    let regex = Regex::new("/(?Pfoo|bar)/b").unwrap();
    route_store.add_route(Method::Get, regex, handler);
    route_store.add_route(Method::Get, "/:foo", handler);

    // Should ignore the querystring
    let route_result = route_store.match_route(&Method::Get, "/moo?foo");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    assert_eq!(route_result.param("foo"), "moo");

    let route_result = route_store.match_route(&Method::Get, "/bar/b?foo");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    assert_eq!(route_result.param("a"), "bar");
}
<commit_msg>fix(rustup): adjust for splitn change<commit_after>use middleware::{Middleware, Continue, MiddlewareResult};
use hyper::uri::RequestUri::AbsolutePath;
use request::Request;
use response::Response;
use router::HttpRouter;
use hyper::method::Method;
use hyper::status::StatusCode;
use router::{Matcher, FORMAT_PARAM};

/// A Route is the basic data structure that stores both the path
/// and the handler that gets executed for the route.
/// The path can contain variable pattern such as `user/:userid/invoices`
pub struct Route {
    pub method: Method,
    pub handler: Box<Middleware + Send + Sync + 'static>,
    matcher: Matcher
}

/// A RouteResult is what the router returns when `match_route` is called.
/// It contains the matched `route` and also a `params` property holding
/// a HashMap with the keys being the variable names and the value being the
/// evaluated string
pub struct RouteResult<'a> {
    pub route: &'a Route,
    params: Vec<(String, String)>
}

impl<'a> RouteResult<'a> {
    pub fn param(&self, key: &str) -> &str {
        for &(ref k, ref v) in &self.params {
            if k == &key {
                return &v[..]
            }
        }

        // FIXME: should have a default format
        if key == FORMAT_PARAM { return "" }
        panic!("unknown param: {}", key)
    }
}

/// The Router's job is it to hold routes and to resolve them later against
/// concrete URLs. The router is also a regular middleware and needs to be
/// added to the middleware stack with `server.utilize(router)`.
pub struct Router {
    routes: Vec<Route>,
}

impl Router {
    pub fn new () -> Router {
        Router {
            routes: Vec::new()
        }
    }

    pub fn match_route<'a>(&'a self, method: &Method, path: &str) -> Option<RouteResult<'a>> {
        // Strip off the querystring when matching a route
        let path = path.splitn(2, '?').next().unwrap();

        self.routes
            .iter()
            .find(|item| item.method == *method && item.matcher.is_match(path))
            .map(|route|
                RouteResult {
                    params: extract_params(route, path),
                    route: route
                }
            )
    }
}

fn extract_params(route: &Route, path: &str) -> Vec<(String, String)> {
    match route.matcher.captures(path) {
        Some(captures) => {
            captures.iter_named()
                    .filter_map(|(name, subcap)| {
                        subcap.map(|cap| (name.to_string(), cap.to_string()))
                    })
                    .collect()
        }
        None => vec![]
    }
}

impl HttpRouter for Router {
    fn add_route<M: Into<Matcher>, H: Middleware>(&mut self, method: Method, matcher: M, handler: H) {
        let route = Route {
            matcher: matcher.into(),
            method: method,
            handler: Box::new(handler),
        };

        self.routes.push(route);
    }
}

impl Middleware for Router {
    fn invoke<'a, 'b>(&'a self, req: &mut Request<'b, 'a, 'b>, mut res: Response<'a>)
                        -> MiddlewareResult<'a> {
        debug!("Router::invoke for '{:?}'", req.origin.uri);
        let route_result = match req.origin.uri {
            AbsolutePath(ref url) => self.match_route(&req.origin.method, &**url),
            _ => None
        };
        debug!("route_result.route.path: {:?}", route_result.as_ref().map(|r| r.route.matcher.path()));

        match route_result {
            Some(route_result) => {
                res.set_status(StatusCode::Ok);
                let handler = &route_result.route.handler;
                req.route_result = Some(route_result);
                handler.invoke(req, res)
            },
            None => Ok(Continue(res))
        }
    }
}

#[test]
fn creates_regex_with_captures () {
    let matcher: Matcher = "foo/:uid/bar/:groupid".into();
    let caps = matcher.captures("foo/4711/bar/5490").unwrap();

    assert_eq!(matcher.path(), "foo/:uid/bar/:groupid(\\.:format)?");
    assert_eq!(caps.at(1).unwrap(), "4711");
    assert_eq!(caps.at(2).unwrap(), "5490");

    let matcher: Matcher = "foo/*/:uid/bar/:groupid".into();
    let caps = matcher.captures("foo/test/4711/bar/5490").unwrap();

    assert_eq!(matcher.path(), "foo/*/:uid/bar/:groupid(\\.:format)?");
    assert_eq!(caps.at(1).unwrap(), "4711");
    assert_eq!(caps.at(2).unwrap(), "5490");

    let matcher: Matcher = "foo/**/:uid/bar/:groupid".into();
    let caps = matcher.captures("foo/test/another/4711/bar/5490").unwrap();

    assert_eq!(matcher.path(), "foo/**/:uid/bar/:groupid(\\.:format)?");
    assert_eq!(caps.at(1).unwrap(), "4711");
    assert_eq!(caps.at(2).unwrap(), "5490");

    let matcher: Matcher = "foo/**/:format/bar/:groupid".into();
    let caps = matcher.captures("foo/test/another/4711/bar/5490").unwrap();

    assert_eq!(matcher.path(), "foo/**/:format/bar/:groupid");
    assert_eq!(caps.name("format").unwrap(), "4711");
    assert_eq!(caps.name("groupid").unwrap(), "5490");
}

#[test]
fn creates_valid_regex_for_routes () {
    let regex1: Matcher = "foo/:uid/bar/:groupid".into();
    let regex2: Matcher = "foo/*/bar".into();
    let regex3: Matcher = "foo/**/bar".into();

    assert_eq!(regex1.is_match("foo/4711/bar/5490"), true);
    assert_eq!(regex1.is_match("foo/4711/bar/5490?foo=true&bar=false"), true);
    assert_eq!(regex1.is_match("foo/4711/bar"), false);
    assert_eq!(regex1.is_match("foo/4711/bar?foo=true&bar=false"), false);
    assert_eq!(regex1.is_match("foo/4711/bar/test%20spacing"), true);
    assert_eq!(regex1.is_match("foo/4711/bar/5281?foo=test%20spacing&bar=false"), true);

    assert_eq!(regex2.is_match("foo/4711/bar"), true);
    assert_eq!(regex2.is_match("foo/4711/barr"), false);
    assert_eq!(regex2.is_match("foo/4711/bar?foo=true&bar=false"), true);
    assert_eq!(regex2.is_match("foo/4711/4712/bar"), false);
    assert_eq!(regex2.is_match("foo/4711/4712/bar?foo=true&bar=false"), false);

    assert_eq!(regex3.is_match("foo/4711/bar"), true);
    assert_eq!(regex3.is_match("foo/4711/bar?foo=true&bar=false"), true);
    assert_eq!(regex3.is_match("foo/4711/4712/bar"), true);
    assert_eq!(regex3.is_match("foo/4711/4712/bar?foo=true&bar=false"), true);

    //ensure that this works with commas too
    assert_eq!(regex1.is_match("foo/4711/bar/5490,1234"), true);
    assert_eq!(regex1.is_match("foo/4711/bar/5490,1234?foo=true&bar=false"), true);
    assert_eq!(regex1.is_match("foo/4711/bar"), false);
    assert_eq!(regex1.is_match("foo/4711/bar?foo=1,2,3&bar=false"), false);
}

#[test]
fn can_match_var_routes () {
    let route_store = &mut Router::new();
    let handler = middleware! { "hello from foo" };

    route_store.add_route(Method::Get, "/foo/:userid", handler);
    route_store.add_route(Method::Get, "/bar", handler);
    route_store.add_route(Method::Get, "/file/:format/:file", handler);

    let route_result = route_store.match_route(&Method::Get, "/foo/4711").unwrap();
    assert_eq!(route_result.param("userid"), "4711");

    let route_result = route_store.match_route(&Method::Get, "/bar/4711");
    assert!(route_result.is_none());

    let route_result = route_store.match_route(&Method::Get, "/foo");
    assert!(route_result.is_none());

    // ensure that this will work with commas too
    let route_result = route_store.match_route(&Method::Get, "/foo/123,456");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    assert_eq!(route_result.param("userid"), "123,456");

    // ensure that this will work with spacing too
    let route_result = route_store.match_route(&Method::Get, "/foo/John%20Doe");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    assert_eq!(route_result.param("userid"), "John%20Doe");

    // check for optional format param
    let route_result = route_store.match_route(&Method::Get, "/foo/John%20Doe.json");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    assert_eq!(route_result.param("userid"), "John%20Doe");
    assert_eq!(route_result.param("format"), "json");

    // ensure format works with queries
    let route_result = route_store.match_route(&Method::Get,
    "/foo/5490,1234.csv?foo=true&bar=false");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    // NOTE: `.param` doesn't cover query params currently
    assert_eq!(route_result.param("userid"), "5490,1234");
    assert_eq!(route_result.param("format"), "csv");

    // ensure format works with no format
    let route_result = route_store.match_route(&Method::Get,
                                               "/foo/5490,1234?foo=true&bar=false").unwrap();

    assert_eq!(route_result.param("format"), "");

    // ensure format works if defined by user
    let route_result = route_store.match_route(&Method::Get, "/file/markdown/something?foo=true");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    // NOTE: `.param` doesn't cover query params currently
    assert_eq!(route_result.param("file"), "something");
    assert_eq!(route_result.param("format"), "markdown");
}

#[test]
fn regex_path() {
    use regex::Regex;

    let route_store = &mut Router::new();
    let handler = middleware! { "hello from foo" };

    let regex = Regex::new("/(foo|bar)").unwrap();
    route_store.add_route(Method::Get, regex, handler);

    let route_result = route_store.match_route(&Method::Get, "/foo");
    assert!(route_result.is_some());

    let route_result = route_store.match_route(&Method::Get, "/bar");
    assert!(route_result.is_some());

    let route_result = route_store.match_route(&Method::Get, "/bar?foo");
    assert!(route_result.is_some());

    let route_result = route_store.match_route(&Method::Get, "/baz");
    assert!(route_result.is_none());
}

#[test]
fn regex_path_named() {
    use regex::Regex;

    let route_store = &mut Router::new();
    let handler = middleware! { "hello from foo" };

    let regex = Regex::new("/(?Pfoo|bar)/b").unwrap();
    route_store.add_route(Method::Get, regex, handler);

    let route_result = route_store.match_route(&Method::Get, "/foo/b");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    assert_eq!(route_result.param("a"), "foo");

    let route_result = route_store.match_route(&Method::Get, "/bar/b");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    assert_eq!(route_result.param("a"), "bar");

    let route_result = route_store.match_route(&Method::Get, "/baz/b");
    assert!(route_result.is_none());
}

#[test]
fn ignores_querystring() {
    use regex::Regex;

    let route_store = &mut Router::new();
    let handler = middleware! { "hello from foo" };

    let regex = Regex::new("/(?Pfoo|bar)/b").unwrap();
    route_store.add_route(Method::Get, regex, handler);
    route_store.add_route(Method::Get, "/:foo", handler);

    // Should ignore the querystring
    let route_result = route_store.match_route(&Method::Get, "/moo?foo");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    assert_eq!(route_result.param("foo"), "moo");

    let route_result = route_store.match_route(&Method::Get, "/bar/b?foo");
    assert!(route_result.is_some());

    let route_result = route_result.unwrap();
    assert_eq!(route_result.param("a"), "bar");
}
<|endoftext|>


<commit_before><commit_msg>feat(scores): add PAM250 score matrix<commit_after>// Copyright 2014 M. Rizky Luthfianto.
// Licensed under the MIT license (http://opensource.org/licenses/MIT)
// This file may not be copied, modified, or distributed
// except according to those terms.

#[macro_use]
extern crate lazy_static;

extern crate nalgebra;

use nalgebra::DMat;

lazy_static! {

	// taken from https://github.com/seqan/seqan/blob/master/include%2Fseqan%2Fscore%2Fscore_matrix_data.h#L806
	static ref ARRAY: [i32;729]=[
		 2,  0, -2,  0,  0, -3,  1, -1, -1, -2, -1, -2, -1,  0,  0,  1,  0, -2,  1,  1,  0,  0, -6, -3,  0,  0, -8,
		 0,  3, -4,  3,  3, -4,  0,  1, -2, -3,  1, -3, -2,  2, -1, -1,  1, -1,  0,  0, -1, -2, -5, -3,  2, -1, -8,
		-2, -4, 12, -5, -5, -4, -3, -3, -2, -4, -5, -6, -5, -4, -3, -3, -5, -4,  0, -2, -3, -2, -8,  0, -5, -3, -8,
		 0,  3, -5,  4,  3, -6,  1,  1, -2, -3,  0, -4, -3,  2, -1, -1,  2, -1,  0,  0, -1, -2, -7, -4,  3, -1, -8,
		 0,  3, -5,  3,  4, -5,  0,  1, -2, -3,  0, -3, -2,  1, -1, -1,  2, -1,  0,  0, -1, -2, -7, -4,  3, -1, -8,
		-3, -4, -4, -6, -5,  9, -5, -2,  1,  2, -5,  2,  0, -3, -2, -5, -5, -4, -3, -3, -2, -1,  0,  7, -5, -2, -8,
		 1,  0, -3,  1,  0, -5,  5, -2, -3, -4, -2, -4, -3,  0, -1,  0, -1, -3,  1,  0, -1, -1, -7, -5,  0, -1, -8,
		-1,  1, -3,  1,  1, -2, -2,  6, -2, -2,  0, -2, -2,  2, -1,  0,  3,  2, -1, -1, -1, -2, -3,  0,  2, -1, -8,
		-1, -2, -2, -2, -2,  1, -3, -2,  5,  4, -2,  2,  2, -2, -1, -2, -2, -2, -1,  0, -1,  4, -5, -1, -2, -1, -8,
		-2, -3, -4, -3, -3,  2, -4, -2,  4,  4, -3,  4,  3, -3, -1, -3, -2, -3, -2, -1, -1,  3, -4, -1, -3, -1, -8,
		-1,  1, -5,  0,  0, -5, -2,  0, -2, -3,  5, -3,  0,  1, -1, -1,  1,  3,  0,  0, -1, -2, -3, -4,  0, -1, -8,
		-2, -3, -6, -4, -3,  2, -4, -2,  2,  4, -3,  6,  4, -3, -1, -3, -2, -3, -3, -2, -1,  2, -2, -1, -3, -1, -8,
		-1, -2, -5, -3, -2,  0, -3, -2,  2,  3,  0,  4,  6, -2, -1, -2, -1,  0, -2, -1, -1,  2, -4, -2, -2, -1, -8,
		 0,  2, -4,  2,  1, -3,  0,  2, -2, -3,  1, -3, -2,  2,  0,  0,  1,  0,  1,  0,  0, -2, -4, -2,  1,  0, -8,
		 0, -1, -3, -1, -1, -2, -1, -1, -1, -1, -1, -1, -1,  0, -1, -1, -1, -1,  0,  0, -1, -1, -4, -2, -1, -1, -8,
		 1, -1, -3, -1, -1, -5,  0,  0, -2, -3, -1, -3, -2,  0, -1,  6,  0,  0,  1,  0, -1, -1, -6, -5,  0, -1, -8,
		 0,  1, -5,  2,  2, -5, -1,  3, -2, -2,  1, -2, -1,  1, -1,  0,  4,  1, -1, -1, -1, -2, -5, -4,  3, -1, -8,
		-2, -1, -4, -1, -1, -4, -3,  2, -2, -3,  3, -3,  0,  0, -1,  0,  1,  6,  0, -1, -1, -2,  2, -4,  0, -1, -8,
		 1,  0,  0,  0,  0, -3,  1, -1, -1, -2,  0, -3, -2,  1,  0,  1, -1,  0,  2,  1,  0, -1, -2, -3,  0,  0, -8,
		 1,  0, -2,  0,  0, -3,  0, -1,  0, -1,  0, -2, -1,  0,  0,  0, -1, -1,  1,  3,  0,  0, -5, -3, -1,  0, -8,
		 0, -1, -3, -1, -1, -2, -1, -1, -1, -1, -1, -1, -1,  0, -1, -1, -1, -1,  0,  0, -1, -1, -4, -2, -1, -1, -8,
		 0, -2, -2, -2, -2, -1, -1, -2,  4,  3, -2,  2,  2, -2, -1, -1, -2, -2, -1,  0, -1,  4, -6, -2, -2, -1, -8,
		-6, -5, -8, -7, -7,  0, -7, -3, -5, -4, -3, -2, -4, -4, -4, -6, -5,  2, -2, -5, -4, -6, 17,  0, -6, -4, -8,
		-3, -3,  0, -4, -4,  7, -5,  0, -1, -1, -4, -1, -2, -2, -2, -5, -4, -4, -3, -3, -2, -2,  0, 10, -4, -2, -8,
		 0,  2, -5,  3,  3, -5,  0,  2, -2, -3,  0, -3, -2,  1, -1,  0,  3,  0,  0, -1, -1, -2, -6, -4,  3, -1, -8,
		 0, -1, -3, -1, -1, -2, -1, -1, -1, -1, -1, -1, -1,  0, -1, -1, -1, -1,  0,  0, -1, -1, -4, -2, -1, -1, -8,
		-8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8, -8,  1,
	];

	static ref MAT: DMat<i32> = DMat::from_col_vec(27, 27, &*ARRAY);
}

#[inline]
fn lookup(number: u8) -> usize {
	if      number==b'Y' { 23 as usize }
	else if number==b'Z' { 24 as usize }
	else if number==b'X' { 25 as usize }
	else if number==b'*' { 26 as usize }
	else { (number-65) as usize }
}

pub fn pam250(a: u8, b: u8) -> i32 {
	let a = lookup(a);
	let b = lookup(b);

	MAT[(a, b)]
}

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

	#[test]
	fn test_pam250() {
		let score1 = pam250(b'A',b'A');
		assert_eq!(score1, 2);
		let score2 = pam250(b'*',b'*');
		assert_eq!(score2, 1);
		let score3 = pam250(b'A',b'*');
		assert_eq!(score3, -8);
		let score4 = pam250(b'*',b'*');
		assert_eq!(score4, 1);
		let score5 = pam250(b'X',b'X');
		assert_eq!(score5, -1);
		let score6 = pam250(b'X',b'Z');
		assert_eq!(score6, -1);
	}
}
<|endoftext|>


<commit_before><commit_msg>util/graph/visit.rs: starting to stub out visitation traits...<commit_after>//! Visitation patterns for graphs.

use super::{Graph,NodeIndex,EdgeIndex,IndexType,Data};

/// Visitation-order selection helper.
pub trait Visitor<N: Data, E: Data, Ix: IndexType> {
    fn next(&mut self, g: &Graph<N, E, Ix>, n: NodeIndex<Ix>) -> Option<EdgeIndex<Ix>>;
}
<|endoftext|>


<commit_before><commit_msg>Enable vsync for window<commit_after><|endoftext|>


<commit_before><commit_msg>add Storage Gateway integration tests<commit_after>#![cfg(feature = "storagegateway")]

extern crate rusoto;

use rusoto::storagegateway::{StorageGatewayClient, ListGatewaysInput};
use rusoto::{DefaultCredentialsProvider, Region};

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

    let request = ListGatewaysInput::default();

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


<commit_before><commit_msg>fixup! Added tests<commit_after>extern crate syn;
use syn::*;

#[test]
fn test_meta_item_word() {
    run_test("#[foo]", MetaItem::Word)
}

#[test]
fn test_meta_item_name_value() {
    run_test("#[foo = 5]", MetaItem::NameValue(Lit::Int(5, IntTy::Unsuffixed)))
}

#[test]
fn test_meta_item_list_lit() {
    run_test("#[foo(5)]", MetaItem::List(vec![NestedMetaItem::Literal(Lit::Int(5, IntTy::Unsuffixed))]))
}

#[test]
fn test_meta_item_list_word() {
    run_test("#[foo(bar)]", MetaItem::List(vec![NestedMetaItem::MetaItem(Ident::from("bar"), MetaItem::Word)]))
}

#[test]
fn test_meta_item_list_name_value() {
    run_test("#[foo(bar = 5)]", MetaItem::List(vec![NestedMetaItem::MetaItem(Ident::from("bar"), MetaItem::NameValue(Lit::Int(5, IntTy::Unsuffixed)))]))
}

#[test]
fn test_meta_item_multiple() {
    run_test("#[foo(word, name = 5, list(name2 = 6), word2)]", MetaItem::List(vec![
        NestedMetaItem::MetaItem(Ident::from("word"), MetaItem::Word),
        NestedMetaItem::MetaItem(Ident::from("name"), MetaItem::NameValue(Lit::Int(5, IntTy::Unsuffixed))),
        NestedMetaItem::MetaItem(Ident::from("list"), MetaItem::List(vec![
            NestedMetaItem::MetaItem(Ident::from("name2"), MetaItem::NameValue(Lit::Int(6, IntTy::Unsuffixed)))
        ])),
        NestedMetaItem::MetaItem(Ident::from("word2"), MetaItem::Word),
    ]))
}

fn run_test(input: &str, expected: MetaItem) {
    let attr = parse_outer_attr(input).unwrap();
    assert_eq!(expected, attr.meta_item().unwrap());
}
<|endoftext|>


<commit_before><commit_msg>Test imag-mv<commit_after><|endoftext|>


<commit_before><commit_msg>Add rust code for isogram case<commit_after>#![feature(ascii_ctype)]

pub fn check(words: &str) -> bool {
    let mut mask = 0u32;

    for c in words.chars() {
        if c.is_ascii_alphabetic() {
            let index = c.to_ascii_lowercase() as usize - 'a' as usize;

            let v = 1u32 << index;
            if mask & v == v {
                return false;
            }

            mask |= v;
        }
    }

    true
}
<|endoftext|>