<commit_before>//To use this, please install zfs-fuse
use redox::*;

pub mod nvpair;
pub mod nvstream;
pub mod xdr;

#[repr(packed)]
pub struct VdevLabel {
    pub blank: [u8; 8 * 1024],
    pub boot_header: [u8; 8 * 1024],
    pub nv_pairs: [u8; 112 * 1024],
    pub uberblocks: [Uberblock; 128],
}

impl VdevLabel {
    pub fn from(data: &[u8]) -> Option<Self> {
        if data.len() >= mem::size_of::<VdevLabel>() {
            let vdev_label = unsafe { ptr::read(data.as_ptr() as *const VdevLabel) };
            Some(vdev_label)
        } else {
            Option::None
        }
    }
}

#[derive(Copy, Clone, Debug)]
#[repr(packed)]
pub struct Uberblock {
    pub magic: u64,
    pub version: u64,
    pub txg: u64,
    pub guid_sum: u64,
    pub timestamp: u64,
    pub rootbp: BlockPtr,
}

impl Uberblock {
    pub fn magic_little() -> u64 {
        return 0x0cb1ba00;
    }

    pub fn magic_big() -> u64 {
        return 0x00bab10c;
    }

    pub fn from(data: &Vec<u8>) -> Option<Self> {
        if data.len() >= mem::size_of::<Uberblock>() {
            let uberblock = unsafe { ptr::read(data.as_ptr() as *const Uberblock) };
            if uberblock.magic == Uberblock::magic_little() {
                return Option::Some(uberblock);
            } else if uberblock.magic == Uberblock::magic_big() {
                return Option::Some(uberblock);
            } else if uberblock.magic > 0 {
                println!("Unknown Magic: {:X}", uberblock.magic as usize);
            }
        }

        Option::None
    }
}

#[derive(Copy, Clone, Debug)]
#[repr(packed)]
pub struct DVAddr {
    pub vdev: u64,
    pub offset: u64,
}

impl DVAddr {
    /// Sector address is the offset plus two vdev labels and one boot block (4 MB, or 8192 sectors)
    pub fn sector(&self) -> u64 {
        self.offset() + 0x2000
    }

    pub fn offset(&self) -> u64 {
        self.offset & 0x7FFFFFFFFFFFFFFF
    }

    pub fn asize(&self) -> u64 {
        (self.vdev & 0xFFFFFF) + 1
    }
}

#[derive(Copy, Clone, Debug)]
#[repr(packed)]
pub struct BlockPtr {
    pub dvas: [DVAddr; 3],
    pub flags_size: u64,
    pub padding: [u64; 3],
    pub birth_txg: u64,
    pub fill_count: u64,
    pub checksum: [u64; 4],
}

impl BlockPtr {
    pub fn lsize(&self) -> u64 {
        (self.flags_size) & 0xFFFF + 1
    }

    pub fn psize(&self) -> u64 {
        ((self.flags_size) >> 16) & 0xFFFF + 1
    }
}

#[derive(Copy, Clone, Debug)]
#[repr(packed)]
pub struct Gang {
    pub bps: [BlockPtr; 3],
    pub padding: [u64; 14],
    pub magic: u64,
    pub checksum: u64,
}

impl Gang {
    pub fn magic() -> u64 {
        return 0x117a0cb17ada1002;
    }
}

#[repr(packed)]
pub struct DNodePhys {
    pub object_type: u8,
    pub indblkshift: u8, // ln2(indirect block size)
    pub nlevels: u8, // 1=blkptr->data blocks
    pub nblkptr: u8, // length of blkptr
    pub bonustype: u8, // type of data in bonus buffer
    pub checksum: u8, // ZIO_CHECKSUM type
    pub compress: u8, // ZIO_COMPRESS type
    pub flags: u8, // DNODE_FLAG_*
    pub datablkszsec: u16, // data block size in 512b sectors
    pub bonuslen: u16, // length of bonus
    pub pad2: [u8; 4],

    // accounting is protected by dirty_mtx
    pub maxblkid: u64, // largest allocated block ID
    pub used: u64, // bytes (or sectors) of disk space

    pub pad3: [u64; 4],

    blkptr_bonus: [u8; 448],
}

impl DNodePhys {
    pub fn from(data: &[u8]) -> Option<Self> {
        if data.len() >= mem::size_of::<DNodePhys>() {
            Some(unsafe { ptr::read(data.as_ptr() as *const DNodePhys) })
        } else {
            Option::None
        }
    }

    pub fn get_blkptr<'a>(&self, i: usize) -> &'a BlockPtr {
        unsafe { mem::transmute(&self.blkptr_bonus[i*128]) }
    }

    pub fn get_bonus(&self) -> &[u8] {
        &self.blkptr_bonus[(self.nblkptr as usize)*128..]
    }
}

impl fmt::Debug for DNodePhys {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "DNodePhys {{ object_type: {:X}, nlevels: {:X}, nblkptr: {},}}\n", self.object_type, self.nlevels, self.nblkptr));
        Ok(())
    }
}

#[repr(packed)]
pub struct ObjectSetPhys {
    meta_dnode: DNodePhys,
    zil_header: ZilHeader,
    os_type: u64,
    pad: [u8; 360],
}

impl ObjectSetPhys {
    pub fn from(data: &[u8]) -> Option<Self> {
        if data.len() >= mem::size_of::<ObjectSetPhys>() {
            Some(unsafe { ptr::read(data.as_ptr() as *const ObjectSetPhys) })
        } else {
            Option::None
        }
    }
}

pub struct ZilHeader {
    claim_txg: u64,
    replay_seq: u64,
    log: BlockPtr,
}

pub struct ZFS {
    disk: File,
}

impl ZFS {
    pub fn new(disk: File) -> Self {
        ZFS { disk: disk }
    }

    //TODO: Error handling
    pub fn read(&mut self, start: usize, length: usize) -> Vec<u8> {
        let mut ret: Vec<u8> = vec![0; length*512];

        self.disk.seek(Seek::Start(start * 512));
        self.disk.read(&mut ret);

        return ret;
    }

    pub fn write(&mut self, block: usize, data: &[u8; 512]) {
        self.disk.seek(Seek::Start(block * 512));
        self.disk.write(data);
    }

    pub fn uber(&mut self) -> Option<Uberblock> {
        let mut newest_uberblock: Option<Uberblock> = Option::None;
        for i in 0..128 {
            match Uberblock::from(&self.read(256 + i * 2, 2)) {
                Option::Some(uberblock) => {
                    let mut newest = false;
                    match newest_uberblock {
                        Option::Some(previous) => {
                            if uberblock.txg > previous.txg {
                                newest = true;
                            }
                        }
                        Option::None => newest = true,
                    }

                    if newest {
                        newest_uberblock = Option::Some(uberblock);
                    }
                }
                Option::None => (), //Invalid uberblock
            }
        }
        return newest_uberblock;
    }
}

//TODO: Find a way to remove all the to_string's
pub fn main() {
    console_title("ZFS");

    let red = [255, 127, 127, 255];
    let green = [127, 255, 127, 255];
    let blue = [127, 127, 255, 255];

    println!("Type open zfs.img to open the image file");

    let mut zfs_option: Option<ZFS> = Option::None;

    while let Option::Some(line) = readln!() {
        let mut args: Vec<String> = Vec::new();
        for arg in line.split(' ') {
            args.push(arg.to_string());
        }

        if let Option::Some(command) = args.get(0) {
            println!("# {}", line);

            let mut close = false;
            match zfs_option {
                Option::Some(ref mut zfs) => {
                    if *command == "uber".to_string() {
                        //128 KB of ubers after 128 KB of other stuff
                        match zfs.uber() {
                            Some(uberblock) => {
                                println_color!(green, "Newest Uberblock {:X}", uberblock.magic);
                                println!("Version {}", uberblock.version);
                                println!("TXG {}", uberblock.txg);
                                println!("GUID {:X}", uberblock.guid_sum);
                                println!("Timestamp {}", uberblock.timestamp);
                            }
                            None => println_color!(red, "No valid uberblock found!"),
                        }
                    } else if *command == "vdev_label".to_string() {
                        match VdevLabel::from(&zfs.read(0, 256 * 2)) {
                            Some(ref mut vdev_label) => {
                                let mut xdr = xdr::MemOps::new(&mut vdev_label.nv_pairs);
                                let nv_list = nvstream::decode_nv_list(&mut xdr);
                                println_color!(green, "Got nv_list:\n{:?}", nv_list);
                            },
                            None => { println_color!(red, "Couldn't read vdev_label"); },
                        }
                    } else if *command == "mos".to_string() {
                        match zfs.uber() {
                            Some(uberblock) => {
                                let mos_dva = uberblock.rootbp.dvas[0];
                                println_color!(green, "DVA: {:?}", mos_dva);
                                println!("Reading {} sectors starting at {}", mos_dva.asize(), mos_dva.sector());
                                println!("ObjectSetPhys size: {}", mem::size_of::<ObjectSetPhys>());
                                println!("DNodePhys size: {}", mem::size_of::<DNodePhys>());
                                let mut mos = zfs.read(mos_dva.sector() as usize, mos_dva.asize() as usize);
                                let obj_set = ObjectSetPhys::from(&mos[..]);
                                if let Some(ref obj_set) = obj_set {
                                    println!("{:?}", obj_set.meta_dnode);
                                }
                                /*let mut xdr = xdr::MemOps::new(&mut mos);
                                let nv_list = nvstream::decode_nv_list(&mut xdr);
                                println_color!(green, "Got nv_list:\n{:?}", nv_list);*/
                            },
                            None => println_color!(red, "No valid uberblock found!"),
                        }
                    } else if *command == "dump".to_string() {
                        match args.get(1) {
                            Some(arg) => {
                                let sector = arg.to_num();
                                println_color!(green, "Dump sector: {}", sector);

                                let data = zfs.read(sector, 1);
                                for i in 0..data.len() {
                                    if i % 32 == 0 {
                                        print!("\n{:X}:", i);
                                    }
                                    if let Option::Some(byte) = data.get(i) {
                                        print!(" {:X}", *byte);
                                    } else {
                                        println!(" !");
                                    }
                                }
                                print!("\n");
                            }
                            None => println_color!(red, "No sector specified!"),
                        }
                    } else if *command == "close".to_string() {
                        println_color!(red, "Closing");
                        close = true;
                    } else {
                        println_color!(blue, "Commands: uber vdev_label mos dump close");
                    }
                }
                Option::None => {
                    if *command == "open".to_string() {
                        match args.get(1) {
                            Option::Some(arg) => {
                                println_color!(green, "Open: {}", arg);
                                zfs_option = Option::Some(ZFS::new(File::open(arg)));
                            }
                            Option::None => println_color!(red, "No file specified!"),
                        }
                    } else {
                        println_color!(blue, "Commands: open");
                    }
                }
            }
            if close {
                zfs_option = Option::None;
            }
        }
    }
}
<commit_msg>Stuff<commit_after>//To use this, please install zfs-fuse
use redox::*;

pub mod nvpair;
pub mod nvstream;
pub mod xdr;

#[repr(packed)]
pub struct VdevLabel {
    pub blank: [u8; 8 * 1024],
    pub boot_header: [u8; 8 * 1024],
    pub nv_pairs: [u8; 112 * 1024],
    pub uberblocks: [Uberblock; 128],
}

impl VdevLabel {
    pub fn from(data: &[u8]) -> Option<Self> {
        if data.len() >= mem::size_of::<VdevLabel>() {
            let vdev_label = unsafe { ptr::read(data.as_ptr() as *const VdevLabel) };
            Some(vdev_label)
        } else {
            Option::None
        }
    }
}

#[derive(Copy, Clone, Debug)]
#[repr(packed)]
pub struct Uberblock {
    pub magic: u64,
    pub version: u64,
    pub txg: u64,
    pub guid_sum: u64,
    pub timestamp: u64,
    pub rootbp: BlockPtr,
}

impl Uberblock {
    pub fn magic_little() -> u64 {
        return 0x0cb1ba00;
    }

    pub fn magic_big() -> u64 {
        return 0x00bab10c;
    }

    pub fn from(data: &Vec<u8>) -> Option<Self> {
        if data.len() >= mem::size_of::<Uberblock>() {
            let uberblock = unsafe { ptr::read(data.as_ptr() as *const Uberblock) };
            if uberblock.magic == Uberblock::magic_little() {
                return Option::Some(uberblock);
            } else if uberblock.magic == Uberblock::magic_big() {
                return Option::Some(uberblock);
            } else if uberblock.magic > 0 {
                println!("Unknown Magic: {:X}", uberblock.magic as usize);
            }
        }

        Option::None
    }
}

#[derive(Copy, Clone, Debug)]
#[repr(packed)]
pub struct DVAddr {
    pub vdev: u64,
    pub offset: u64,
}

impl DVAddr {
    /// Sector address is the offset plus two vdev labels and one boot block (4 MB, or 8192 sectors)
    pub fn sector(&self) -> u64 {
        self.offset() + 0x2000
    }

    pub fn offset(&self) -> u64 {
        self.offset & 0x7FFFFFFFFFFFFFFF
    }

    pub fn asize(&self) -> u64 {
        (self.vdev & 0xFFFFFF) + 1
    }
}

#[derive(Copy, Clone, Debug)]
#[repr(packed)]
pub struct BlockPtr {
    pub dvas: [DVAddr; 3],
    pub flags_size: u64,
    pub padding: [u64; 3],
    pub birth_txg: u64,
    pub fill_count: u64,
    pub checksum: [u64; 4],
}

impl BlockPtr {
    pub fn lsize(&self) -> u64 {
        (self.flags_size) & 0xFFFF + 1
    }

    pub fn psize(&self) -> u64 {
        ((self.flags_size) >> 16) & 0xFFFF + 1
    }
}

#[derive(Copy, Clone, Debug)]
#[repr(packed)]
pub struct Gang {
    pub bps: [BlockPtr; 3],
    pub padding: [u64; 14],
    pub magic: u64,
    pub checksum: u64,
}

impl Gang {
    pub fn magic() -> u64 {
        return 0x117a0cb17ada1002;
    }
}

#[repr(packed)]
pub struct DNodePhys {
    pub object_type: u8,
    pub indblkshift: u8, // ln2(indirect block size)
    pub nlevels: u8, // 1=blkptr->data blocks
    pub nblkptr: u8, // length of blkptr
    pub bonustype: u8, // type of data in bonus buffer
    pub checksum: u8, // ZIO_CHECKSUM type
    pub compress: u8, // ZIO_COMPRESS type
    pub flags: u8, // DNODE_FLAG_*
    pub datablkszsec: u16, // data block size in 512b sectors
    pub bonuslen: u16, // length of bonus
    pub pad2: [u8; 4],

    // accounting is protected by dirty_mtx
    pub maxblkid: u64, // largest allocated block ID
    pub used: u64, // bytes (or sectors) of disk space

    pub pad3: [u64; 4],

    blkptr_bonus: [u8; 448],
}

impl DNodePhys {
    pub fn from(data: &[u8]) -> Option<Self> {
        if data.len() >= mem::size_of::<DNodePhys>() {
            Some(unsafe { ptr::read(data.as_ptr() as *const DNodePhys) })
        } else {
            Option::None
        }
    }

    pub fn get_blkptr<'a>(&self, i: usize) -> &'a BlockPtr {
        unsafe { mem::transmute(&self.blkptr_bonus[i*128]) }
    }

    pub fn get_bonus(&self) -> &[u8] {
        &self.blkptr_bonus[(self.nblkptr as usize)*128..]
    }
}

impl fmt::Debug for DNodePhys {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "DNodePhys {{ object_type: {:X}, nlevels: {:X}, nblkptr: {},}}\n", self.object_type, self.nlevels, self.nblkptr));
        Ok(())
    }
}

#[repr(packed)]
pub struct ObjectSetPhys {
    meta_dnode: DNodePhys,
    zil_header: ZilHeader,
    os_type: u64,
    pad: [u8; 360],
}

impl ObjectSetPhys {
    pub fn from(data: &[u8]) -> Option<Self> {
        if data.len() >= mem::size_of::<ObjectSetPhys>() {
            Some(unsafe { ptr::read(data.as_ptr() as *const ObjectSetPhys) })
        } else {
            Option::None
        }
    }
}

#[repr(packed)]
pub struct ZilHeader {
    claim_txg: u64,
    replay_seq: u64,
    log: BlockPtr,
}

pub struct ZFS {
    disk: File,
}

impl ZFS {
    pub fn new(disk: File) -> Self {
        ZFS { disk: disk }
    }

    //TODO: Error handling
    pub fn read(&mut self, start: usize, length: usize) -> Vec<u8> {
        let mut ret: Vec<u8> = vec![0; length*512];

        self.disk.seek(Seek::Start(start * 512));
        self.disk.read(&mut ret);

        return ret;
    }

    pub fn write(&mut self, block: usize, data: &[u8; 512]) {
        self.disk.seek(Seek::Start(block * 512));
        self.disk.write(data);
    }

    pub fn uber(&mut self) -> Option<Uberblock> {
        let mut newest_uberblock: Option<Uberblock> = Option::None;
        for i in 0..128 {
            match Uberblock::from(&self.read(256 + i * 2, 2)) {
                Option::Some(uberblock) => {
                    let mut newest = false;
                    match newest_uberblock {
                        Option::Some(previous) => {
                            if uberblock.txg > previous.txg {
                                newest = true;
                            }
                        }
                        Option::None => newest = true,
                    }

                    if newest {
                        newest_uberblock = Option::Some(uberblock);
                    }
                }
                Option::None => (), //Invalid uberblock
            }
        }
        return newest_uberblock;
    }
}

//TODO: Find a way to remove all the to_string's
pub fn main() {
    console_title("ZFS");

    let red = [255, 127, 127, 255];
    let green = [127, 255, 127, 255];
    let blue = [127, 127, 255, 255];

    println!("Type open zfs.img to open the image file");

    let mut zfs_option: Option<ZFS> = Option::None;

    while let Option::Some(line) = readln!() {
        let mut args: Vec<String> = Vec::new();
        for arg in line.split(' ') {
            args.push(arg.to_string());
        }

        if let Option::Some(command) = args.get(0) {
            println!("# {}", line);

            let mut close = false;
            match zfs_option {
                Option::Some(ref mut zfs) => {
                    if *command == "uber".to_string() {
                        //128 KB of ubers after 128 KB of other stuff
                        match zfs.uber() {
                            Some(uberblock) => {
                                println_color!(green, "Newest Uberblock {:X}", uberblock.magic);
                                println!("Version {}", uberblock.version);
                                println!("TXG {}", uberblock.txg);
                                println!("GUID {:X}", uberblock.guid_sum);
                                println!("Timestamp {}", uberblock.timestamp);
                            }
                            None => println_color!(red, "No valid uberblock found!"),
                        }
                    } else if *command == "vdev_label".to_string() {
                        match VdevLabel::from(&zfs.read(0, 256 * 2)) {
                            Some(ref mut vdev_label) => {
                                let mut xdr = xdr::MemOps::new(&mut vdev_label.nv_pairs);
                                let nv_list = nvstream::decode_nv_list(&mut xdr);
                                println_color!(green, "Got nv_list:\n{:?}", nv_list);
                            },
                            None => { println_color!(red, "Couldn't read vdev_label"); },
                        }
                    } else if *command == "mos".to_string() {
                        match zfs.uber() {
                            Some(uberblock) => {
                                let mos_dva = uberblock.rootbp.dvas[0];
                                println_color!(green, "DVA: {:?}", mos_dva);
                                println!("Reading {} sectors starting at {}", mos_dva.asize(), mos_dva.sector());
                                println!("ObjectSetPhys size: {}", mem::size_of::<ObjectSetPhys>());
                                println!("DNodePhys size: {}", mem::size_of::<DNodePhys>());
                                let mut mos = zfs.read(mos_dva.sector() as usize, mos_dva.asize() as usize);
                                let obj_set = ObjectSetPhys::from(&mos[..]);
                                if let Some(ref obj_set) = obj_set {
                                    println!("meta dnode: {:?}", obj_set.meta_dnode);
                                    println!("os_type: {:X}", obj_set.os_type);
                                }
                                /*let mut xdr = xdr::MemOps::new(&mut mos);
                                let nv_list = nvstream::decode_nv_list(&mut xdr);
                                println_color!(green, "Got nv_list:\n{:?}", nv_list);*/
                            },
                            None => println_color!(red, "No valid uberblock found!"),
                        }
                    } else if *command == "dump".to_string() {
                        match args.get(1) {
                            Some(arg) => {
                                let sector = arg.to_num();
                                println_color!(green, "Dump sector: {}", sector);

                                let data = zfs.read(sector, 1);
                                for i in 0..data.len() {
                                    if i % 32 == 0 {
                                        print!("\n{:X}:", i);
                                    }
                                    if let Option::Some(byte) = data.get(i) {
                                        print!(" {:X}", *byte);
                                    } else {
                                        println!(" !");
                                    }
                                }
                                print!("\n");
                            }
                            None => println_color!(red, "No sector specified!"),
                        }
                    } else if *command == "close".to_string() {
                        println_color!(red, "Closing");
                        close = true;
                    } else {
                        println_color!(blue, "Commands: uber vdev_label mos dump close");
                    }
                }
                Option::None => {
                    if *command == "open".to_string() {
                        match args.get(1) {
                            Option::Some(arg) => {
                                println_color!(green, "Open: {}", arg);
                                zfs_option = Option::Some(ZFS::new(File::open(arg)));
                            }
                            Option::None => println_color!(red, "No file specified!"),
                        }
                    } else {
                        println_color!(blue, "Commands: open");
                    }
                }
            }
            if close {
                zfs_option = Option::None;
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Rename to per_package<commit_after><|endoftext|>


<commit_before><commit_msg>problem: tests are failing solution: fix tests<commit_after><|endoftext|>


<commit_before><commit_msg>Add timestamp to screenshots, and output jpg files instead<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor(password daemon): change message for startup message, reduce default to 30 seconds<commit_after><|endoftext|>


<commit_before><commit_msg>Added all permissions to the users table.<commit_after><|endoftext|>


<commit_before>#[doc(
    brief = "The attribute parsing pass",
    desc =
    "Traverses the document tree, pulling relevant documention out of the \
     corresponding AST nodes. The information gathered here is the basis \
     of the natural-language documentation for a crate."
)];

import rustc::syntax::ast;
import rustc::middle::ast_map;

export mk_pass;

fn mk_pass() -> pass {
    run
}

fn run(
    srv: astsrv::srv,
    doc: doc::cratedoc
) -> doc::cratedoc {
    let fold = fold::fold({
        fold_crate: fold_crate,
        fold_mod: fold_mod,
        fold_fn: fold_fn,
        fold_const: fold_const
        with *fold::default_seq_fold(srv)
    });
    fold.fold_crate(fold, doc)
}

fn fold_crate(
    fold: fold::fold<astsrv::srv>,
    doc: doc::cratedoc
) -> doc::cratedoc {

    let srv = fold.ctxt;
    let doc = fold::default_seq_fold_crate(fold, doc);

    let attrs = astsrv::exec(srv) {|ctxt|
        let attrs = ctxt.ast.node.attrs;
        attr_parser::parse_crate(attrs)
    };

    ~{
        topmod: ~{
            name: option::from_maybe(doc.topmod.name, attrs.name)
            with *doc.topmod
        }
    }
}

#[test]
fn should_replace_top_module_name_with_crate_name() {
    let source = "#[link(name = \"bond\")];";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let fold = fold::default_seq_fold(srv);
    let doc = fold_crate(fold, doc);
    assert doc.topmod.name == "bond";
}

fn fold_mod(fold: fold::fold<astsrv::srv>, doc: doc::moddoc) -> doc::moddoc {
    let srv = fold.ctxt;
    let attrs = if doc.id == ast::crate_node_id {
        // This is the top-level mod, use the crate attributes
        astsrv::exec(srv) {|ctxt|
            attr_parser::parse_mod(ctxt.ast.node.attrs)
        }
    } else {
        astsrv::exec(srv) {|ctxt|
            let attrs = alt ctxt.map.get(doc.id) {
              ast_map::node_item(item) { item.attrs }
            };
            attr_parser::parse_mod(attrs)
        }
    };
    let doc = fold::default_seq_fold_mod(fold, doc);
    ret merge_mod_attrs(doc, attrs);

    fn merge_mod_attrs(
        doc: doc::moddoc,
        attrs: attr_parser::mod_attrs
    ) -> doc::moddoc {
        ~{
            brief: attrs.brief,
            desc: attrs.desc
            with *doc
        }
    }
}

#[test]
fn fold_mod_should_extract_mod_attributes() {
    let source = "#[doc = \"test\"] mod a { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let fold = fold::default_seq_fold(srv);
    let doc = fold_mod(fold, doc.topmod.mods[0]);
    assert doc.desc == some("test");
}

#[test]
fn fold_mod_should_extract_top_mod_attributes() {
    let source = "#[doc = \"test\"];";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let fold = fold::default_seq_fold(srv);
    let doc = fold_mod(fold, doc.topmod);
    assert doc.desc == some("test");
}

fn fold_fn(
    fold: fold::fold<astsrv::srv>,
    doc: doc::fndoc
) -> doc::fndoc {

    let srv = fold.ctxt;

    let attrs = astsrv::exec(srv) {|ctxt|
        let attrs = alt ctxt.map.get(doc.id) {
          ast_map::node_item(item) { item.attrs }
        };
        attr_parser::parse_fn(attrs)
    };
    ret merge_fn_attrs(doc, attrs);

    fn merge_fn_attrs(
        doc: doc::fndoc,
        attrs: attr_parser::fn_attrs
    ) -> doc::fndoc {
        ret ~{
            brief: attrs.brief,
            desc: attrs.desc,
            args: merge_arg_attrs(doc.args, attrs.args),
            return: merge_ret_attrs(doc.return, attrs.return)
            with *doc
        };
    }

    fn merge_arg_attrs(
        docs: [doc::argdoc],
        attrs: [attr_parser::arg_attrs]
    ) -> [doc::argdoc] {
        vec::map(docs) {|doc|
            alt vec::find(attrs) {|attr|
                attr.name == doc.name
            } {
                some(attr) {
                    ~{
                        desc: some(attr.desc)
                        with *doc
                    }
                }
                none { doc }
            }
        }
        // FIXME: Warning when documenting a non-existent arg
    }

    fn merge_ret_attrs(
        doc: doc::retdoc,
        attrs: option<str>
    ) -> doc::retdoc {
        {
            desc: attrs
            with doc
        }
    }
}

#[test]
fn fold_fn_should_extract_fn_attributes() {
    let source = "#[doc = \"test\"] fn a() -> int { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let fold = fold::default_seq_fold(srv);
    let doc = fold_fn(fold, doc.topmod.fns[0]);
    assert doc.desc == some("test");
}

#[test]
fn fold_fn_should_extract_arg_attributes() {
    let source = "#[doc(args(a = \"b\"))] fn c(a: bool) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let fold = fold::default_seq_fold(srv);
    let doc = fold_fn(fold, doc.topmod.fns[0]);
    assert doc.args[0].desc == some("b");
}

#[test]
fn fold_fn_should_extract_return_attributes() {
    let source = "#[doc(return = \"what\")] fn a() -> int { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = tystr_pass::mk_pass()(srv, doc);
    let fold = fold::default_seq_fold(srv);
    let doc = fold_fn(fold, doc.topmod.fns[0]);
    assert doc.return.desc == some("what");
}

#[test]
fn fold_fn_should_preserve_sig() {
    let source = "fn a() -> int { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = tystr_pass::mk_pass()(srv, doc);
    let fold = fold::default_seq_fold(srv);
    let doc = fold_fn(fold, doc.topmod.fns[0]);
    assert doc.sig == some("fn a() -> int");
}

fn fold_const(
    fold: fold::fold<astsrv::srv>,
    doc: doc::constdoc
) -> doc::constdoc {
    let srv = fold.ctxt;
    let attrs = astsrv::exec(srv) {|ctxt|
        let attrs = alt ctxt.map.get(doc.id) {
          ast_map::node_item(item) { item.attrs }
        };
        attr_parser::parse_mod(attrs)
    };

    ~{
        brief: attrs.brief,
        desc: attrs.desc
        with *doc
    }
}

#[test]
fn fold_const_should_extract_docs() {
    let source = "#[doc(brief = \"foo\", desc = \"bar\")]\
                  const a: bool = true;";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let fold = fold::default_seq_fold(srv);
    let doc = fold_const(fold, doc.topmod.consts[0]);
    assert doc.brief == some("foo");
    assert doc.desc == some("bar");
}
<commit_msg>rustdoc: Some refactoring in attr_pass<commit_after>#[doc(
    brief = "The attribute parsing pass",
    desc =
    "Traverses the document tree, pulling relevant documention out of the \
     corresponding AST nodes. The information gathered here is the basis \
     of the natural-language documentation for a crate."
)];

import rustc::syntax::ast;
import rustc::middle::ast_map;

export mk_pass;

fn mk_pass() -> pass {
    run
}

fn run(
    srv: astsrv::srv,
    doc: doc::cratedoc
) -> doc::cratedoc {
    let fold = fold::fold({
        fold_crate: fold_crate,
        fold_mod: fold_mod,
        fold_fn: fold_fn,
        fold_const: fold_const
        with *fold::default_seq_fold(srv)
    });
    fold.fold_crate(fold, doc)
}

fn fold_crate(
    fold: fold::fold<astsrv::srv>,
    doc: doc::cratedoc
) -> doc::cratedoc {

    let srv = fold.ctxt;
    let doc = fold::default_seq_fold_crate(fold, doc);

    let attrs = astsrv::exec(srv) {|ctxt|
        let attrs = ctxt.ast.node.attrs;
        attr_parser::parse_crate(attrs)
    };

    ~{
        topmod: ~{
            name: option::from_maybe(doc.topmod.name, attrs.name)
            with *doc.topmod
        }
    }
}

#[test]
fn should_replace_top_module_name_with_crate_name() {
    let source = "#[link(name = \"bond\")];";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let fold = fold::default_seq_fold(srv);
    let doc = fold_crate(fold, doc);
    assert doc.topmod.name == "bond";
}

fn parse_item_attrs<T>(
    srv: astsrv::srv,
    id: doc::ast_id,
    parse_attrs: fn~([ast::attribute]) -> T) -> T {
    astsrv::exec(srv) {|ctxt|
        let attrs = alt ctxt.map.get(id) {
          ast_map::node_item(item) { item.attrs }
        };
        parse_attrs(attrs)
    }
}

fn fold_mod(fold: fold::fold<astsrv::srv>, doc: doc::moddoc) -> doc::moddoc {
    let srv = fold.ctxt;
    let attrs = if doc.id == ast::crate_node_id {
        // This is the top-level mod, use the crate attributes
        astsrv::exec(srv) {|ctxt|
            attr_parser::parse_mod(ctxt.ast.node.attrs)
        }
    } else {
        parse_item_attrs(srv, doc.id, attr_parser::parse_mod)
    };
    let doc = fold::default_seq_fold_mod(fold, doc);
    ret merge_mod_attrs(doc, attrs);

    fn merge_mod_attrs(
        doc: doc::moddoc,
        attrs: attr_parser::mod_attrs
    ) -> doc::moddoc {
        ~{
            brief: attrs.brief,
            desc: attrs.desc
            with *doc
        }
    }
}

#[test]
fn fold_mod_should_extract_mod_attributes() {
    let source = "#[doc = \"test\"] mod a { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let fold = fold::default_seq_fold(srv);
    let doc = fold_mod(fold, doc.topmod.mods[0]);
    assert doc.desc == some("test");
}

#[test]
fn fold_mod_should_extract_top_mod_attributes() {
    let source = "#[doc = \"test\"];";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let fold = fold::default_seq_fold(srv);
    let doc = fold_mod(fold, doc.topmod);
    assert doc.desc == some("test");
}

fn fold_fn(
    fold: fold::fold<astsrv::srv>,
    doc: doc::fndoc
) -> doc::fndoc {

    let srv = fold.ctxt;

    let attrs = parse_item_attrs(srv, doc.id, attr_parser::parse_fn);
    ret merge_fn_attrs(doc, attrs);

    fn merge_fn_attrs(
        doc: doc::fndoc,
        attrs: attr_parser::fn_attrs
    ) -> doc::fndoc {
        ret ~{
            brief: attrs.brief,
            desc: attrs.desc,
            args: merge_arg_attrs(doc.args, attrs.args),
            return: merge_ret_attrs(doc.return, attrs.return)
            with *doc
        };
    }

    fn merge_arg_attrs(
        docs: [doc::argdoc],
        attrs: [attr_parser::arg_attrs]
    ) -> [doc::argdoc] {
        vec::map(docs) {|doc|
            alt vec::find(attrs) {|attr|
                attr.name == doc.name
            } {
                some(attr) {
                    ~{
                        desc: some(attr.desc)
                        with *doc
                    }
                }
                none { doc }
            }
        }
        // FIXME: Warning when documenting a non-existent arg
    }

    fn merge_ret_attrs(
        doc: doc::retdoc,
        attrs: option<str>
    ) -> doc::retdoc {
        {
            desc: attrs
            with doc
        }
    }
}

#[test]
fn fold_fn_should_extract_fn_attributes() {
    let source = "#[doc = \"test\"] fn a() -> int { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let fold = fold::default_seq_fold(srv);
    let doc = fold_fn(fold, doc.topmod.fns[0]);
    assert doc.desc == some("test");
}

#[test]
fn fold_fn_should_extract_arg_attributes() {
    let source = "#[doc(args(a = \"b\"))] fn c(a: bool) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let fold = fold::default_seq_fold(srv);
    let doc = fold_fn(fold, doc.topmod.fns[0]);
    assert doc.args[0].desc == some("b");
}

#[test]
fn fold_fn_should_extract_return_attributes() {
    let source = "#[doc(return = \"what\")] fn a() -> int { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = tystr_pass::mk_pass()(srv, doc);
    let fold = fold::default_seq_fold(srv);
    let doc = fold_fn(fold, doc.topmod.fns[0]);
    assert doc.return.desc == some("what");
}

#[test]
fn fold_fn_should_preserve_sig() {
    let source = "fn a() -> int { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = tystr_pass::mk_pass()(srv, doc);
    let fold = fold::default_seq_fold(srv);
    let doc = fold_fn(fold, doc.topmod.fns[0]);
    assert doc.sig == some("fn a() -> int");
}

fn fold_const(
    fold: fold::fold<astsrv::srv>,
    doc: doc::constdoc
) -> doc::constdoc {
    let srv = fold.ctxt;
    let attrs = parse_item_attrs(srv, doc.id, attr_parser::parse_mod);

    ~{
        brief: attrs.brief,
        desc: attrs.desc
        with *doc
    }
}

#[test]
fn fold_const_should_extract_docs() {
    let source = "#[doc(brief = \"foo\", desc = \"bar\")]\
                  const a: bool = true;";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let fold = fold::default_seq_fold(srv);
    let doc = fold_const(fold, doc.topmod.consts[0]);
    assert doc.brief == some("foo");
    assert doc.desc == some("bar");
}
<|endoftext|>


<commit_before><commit_msg>Initializer: i dont understand the git CLI<commit_after>use std::collections::HashMap;
use types::{LispToken, LispFunc};

macro_rules! lisp_func(
	(|$ee:ident, $args:ident| -> $fun:expr) => (LispFunc::new(box |$ee, args| -> LispToken {
		match args {
			&LispToken::List(ref $args) => $fun,
			_ => panic!("Invalid Argument Error")
		}
	}))
);

macro_rules! lisp_fold_func(
	(|$ee:ident, $args:ident| -> { $temp:ident = $start:expr + |$acc:ident, $elem:ident| -> $fun:expr; $wrap:expr } ) =>
		( lisp_func!(|$ee, $args| -> {
			let $temp = args.iter().fold( $start, |$acc, $elem| { $fun } );
			$wrap
		}) );
	(|$ee:ident, $args:ident| -> { $temp:ident = |$acc:ident, $elem:ident| -> $fun:expr; $wrap:expr } ) =>
		( lisp_func!(|$ee, $args| -> {
			let $temp = args.iter().skip(1).fold( $args[0], |$acc, $elem| { $fun } );
			$wrap
	} ) );
);

macro_rules! lisp_map_func(
	(|$ee:ident, $args:ident| -> |$arg:ident| -> $map:expr) =>
		( lisp_func!( |$ee, $args| -> LispToken::List(args.iter().map(|$arg| { $map }.collect()) ) ) )
);

macro_rules! lisp_filter_func(
	(|$ee:ident, $args:ident| -> |$arg:ident| -> $filter:expr) =>
		( lisp_func!( |$ee, $args| -> LispToken::List(args.iter().map(|$arg| { $filter }.collect()) ) ) )
);

macro_rules! check_arg!(
	($elem:ident, $arg:pat, $then:expr) => (match $elem {
		$arg => $then,
		_ => panic!("Invalid Argument Error")
	})
)

macro_rules! math_fold_funct(
	(|$a:ident, $n:ident| -> $fun:expr) => { lisp_func!( |ee, arg_list| -> match arg_list[0] {
				LispToken::Integer(i) => LispToken::Integer(arg_list.iter().skip(1).fold(i, |$a, elem| {
					match elem {
						&LispToken::Integer($n) => $fun,
						&LispToken::FloatingPoint(f) => {
							let $n = f as i32;
							$fun
						},
						_ => panic!("Invalid Argument Error")
					}
				})),
				LispToken::FloatingPoint(f) => LispToken::FloatingPoint(arg_list.iter().skip(1).fold(f, |$a, elem| {
					match elem {
						&LispToken::Integer(i) => {
							let $n = i as f64;
							$fun
						},
						&LispToken::FloatingPoint($n) => $fun,
						_ => panic!("Invalid Argument Error")
					}
				})),
				_ => panic!("Invalid Argument Error")
			})
	}
);

pub fn init_functs(functs: &mut HashMap<&str, LispFunc>) {
	functs.insert("+", math_fold_funct!(|a, n| -> a + n));
	functs.insert("*", math_fold_funct!(|a, n| -> a * n));
	functs.insert("-", math_fold_funct!(|a, n| -> a - n));
	functs.insert("/", math_fold_funct!(|a, n| -> a / n));
	functs.insert("concat", lisp_fold_func!(|ee, args| -> ));
}<|endoftext|>


<commit_before><commit_msg>Read config file and connect to Discord<commit_after><|endoftext|>


<commit_before><commit_msg>Cleaning up consume frame method.<commit_after><|endoftext|>


<commit_before><commit_msg>Redox is not ready for this kind of intelligence, File::metadata() is not in libstd<commit_after><|endoftext|>


<commit_before><commit_msg>found how to chain function calls by passing ownership<commit_after><|endoftext|>


<commit_before><commit_msg>Add common setup function<commit_after>pub fn setup() {
    // placeholder to reuse in different tests
}<|endoftext|>


<commit_before>use std;
import std::str;

native "c-stack-cdecl" mod libc = "" {
    fn atol(x: str::sbuf) -> int;
    fn atoll(x: str::sbuf) -> i64;
}

fn atol(s: str) -> int {
    ret str::as_buf(s, { |x| libc::atol(x) });
}

fn atoll(s: str) -> i64 {
    ret str::as_buf(s, { |x| libc::atoll(x) });
}

fn main() {
    assert atol("1024") * 10 == atol("10240");
    assert (atoll("11111111111111111") * 10i64) == atoll("111111111111111110");
}
<commit_msg>Fix long lines<commit_after>use std;
import std::str;

native "c-stack-cdecl" mod libc = "" {
    fn atol(x: str::sbuf) -> int;
    fn atoll(x: str::sbuf) -> i64;
}

fn atol(s: str) -> int {
    ret str::as_buf(s, { |x| libc::atol(x) });
}

fn atoll(s: str) -> i64 {
    ret str::as_buf(s, { |x| libc::atoll(x) });
}

fn main() {
    assert atol("1024") * 10 == atol("10240");
    assert (atoll("11111111111111111") * 10i64)
        == atoll("111111111111111110");
}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #72710 - jsgf:unused-deps-test, r=jsgf<commit_after>// Test-only use OK

// edition:2018
// check-pass
// aux-crate:bar=bar.rs
// compile-flags:--test

#![deny(unused_crate_dependencies)]

fn main() {}

#[test]
fn test_bar() {
    assert_eq!(bar::BAR, "bar");
}
<|endoftext|>


<commit_before><commit_msg>re-export the Address struct<commit_after><|endoftext|>


<commit_before><commit_msg>Renaming BMPCore to Core<commit_after><|endoftext|>


<commit_before><commit_msg>Remove some unnecessary boxing<commit_after><|endoftext|>


<commit_before><commit_msg>Bucket distribution iterator<commit_after><|endoftext|>


<commit_before><commit_msg>add_history_persist<commit_after><|endoftext|>


<commit_before><commit_msg>remove rand_string method<commit_after><|endoftext|>


<commit_before><commit_msg>add -> push<commit_after><|endoftext|>


<commit_before><commit_msg>Fix bug where non-HTTP API call can overwrite existing http-only cookie.<commit_after><|endoftext|>


<commit_before><commit_msg>Add "pub use" for Stats.<commit_after><|endoftext|>


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

extern crate env_logger;
extern crate getopts;
extern crate time;
extern crate glutin;
extern crate gfx;
extern crate gfx_device_gl;
#[cfg(target_os = "windows")]
extern crate gfx_device_dx11;
extern crate gfx_window_glutin;
//extern crate gfx_window_glfw;
#[cfg(target_os = "windows")]
extern crate gfx_window_dxgi;

pub mod shade;

pub type ColorFormat = gfx::format::Srgba8;
pub type DepthFormat = gfx::format::DepthStencil;

pub struct Init<R: gfx::Resources> {
    pub backend: shade::Backend,
    pub color: gfx::handle::RenderTargetView<R, ColorFormat>,
    pub depth: gfx::handle::DepthStencilView<R, DepthFormat>,
    pub aspect_ratio: f32,
}

pub enum Backend {
    OpenGL2,
    Direct3D11 {
        pix_mode: bool,
    },
}

pub struct Config {
    //pub backend: Backend,
    pub size: (u16, u16),
}

pub const DEFAULT_CONFIG: Config = Config {
    //backend: Backend::OpenGL2,
    size: (800, 520),
};

struct Harness {
    start: f64,
    num_frames: f64,
}

impl Harness {
    fn new() -> Harness {
        Harness {
            start: time::precise_time_s(),
            num_frames: 0.0,
        }
    }
    fn bump(&mut self) {
        self.num_frames += 1.0;
    }
}

impl Drop for Harness {
    fn drop(&mut self) {
        let time_end = time::precise_time_s();
        println!("Avg frame time: {} ms",
            (time_end - self.start) * 1000.0 / self.num_frames
        );
    }
}

pub trait ApplicationBase<R: gfx::Resources, C: gfx::CommandBuffer<R>> {
    fn new<F>(F, gfx::Encoder<R, C>, Init<R>) -> Self where
        F: gfx::Factory<R>;
    fn render<D>(&mut self, &mut D) where
        D: gfx::Device<Resources=R, CommandBuffer=C>;
}

pub trait Application<R: gfx::Resources>: Sized {
    fn new<F: gfx::Factory<R>>(F, Init<R>) -> Self;
    fn render<C: gfx::CommandBuffer<R>>(&mut self, &mut gfx::Encoder<R, C>);
    #[cfg(target_os = "windows")]
    fn launch_default(name: &str) where WrapD3D11<Self>: ApplicationD3D11 {
        WrapD3D11::<Self>::launch(name, DEFAULT_CONFIG);
    }
    #[cfg(not(target_os = "windows"))]
    fn launch_default(name: &str) where WrapGL2<Self>: ApplicationGL2 {
        WrapGL2::<Self>::launch(name, DEFAULT_CONFIG);
    }
}

pub struct Wrap<R: gfx::Resources, C: gfx::CommandBuffer<R>, A>{
    encoder: gfx::Encoder<R, C>,
    app: A,
}

#[cfg(target_os = "windows")]
pub type D3D11CommandBuffer = gfx_device_dx11::CommandBuffer<gfx_device_dx11::DeferredContext>;
#[cfg(target_os = "windows")]
pub type D3D11CommandBufferFake = gfx_device_dx11::CommandBuffer<gfx_device_dx11::CommandList>;
#[cfg(target_os = "windows")]
pub type WrapD3D11<A> = Wrap<gfx_device_dx11::Resources, D3D11CommandBuffer, A>;
pub type WrapGL2<A> = Wrap<gfx_device_gl::Resources, gfx_device_gl::CommandBuffer, A>;

impl<
    R: gfx::Resources,
    C: gfx::CommandBuffer<R>,
    A: Application<R>,
> ApplicationBase<R, C> for Wrap<R, C, A> {
    fn new<F>(factory: F, encoder: gfx::Encoder<R, C>, init: Init<R>) -> Self where
        F: gfx::Factory<R>
    {
        Wrap {
            encoder: encoder,
            app: A::new(factory, init),
        }
    }

    fn render<D>(&mut self, device: &mut D) where
        D: gfx::Device<Resources=R, CommandBuffer=C>
    {
        self.app.render(&mut self.encoder);
        self.encoder.flush(device);
    }
}

pub trait ApplicationGL2 {
    fn launch(&str, Config);
}

#[cfg(target_os = "windows")]
pub trait ApplicationD3D11 {
    fn launch(&str, Config);
}

impl<
    A: ApplicationBase<gfx_device_gl::Resources, gfx_device_gl::CommandBuffer>
> ApplicationGL2 for A {
    fn launch(title: &str, config: Config) {
        use gfx::traits::Device;

        env_logger::init().unwrap();
        let builder = glutin::WindowBuilder::new()
            .with_title(title.to_string())
            .with_dimensions(config.size.0 as u32, config.size.1 as u32)
            .with_vsync();
        let (window, mut device, mut factory, main_color, main_depth) =
            gfx_window_glutin::init::<ColorFormat, DepthFormat>(builder);
        let (width, height) = window.get_inner_size().unwrap();
        let combuf = factory.create_command_buffer();

        let mut app = Self::new(factory, combuf.into(), Init {
            backend: shade::Backend::Glsl(device.get_info().shading_language),
            color: main_color,
            depth: main_depth,
            aspect_ratio: width as f32 / height as f32,
        });

        let mut harness = Harness::new();
        'main: loop {
            // quit when Esc is pressed.
            for event in window.poll_events() {
                match event {
                    glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) |
                    glutin::Event::Closed => break 'main,
                    _ => {},
                }
            }
            // draw a frame
            app.render(&mut device);
            window.swap_buffers().unwrap();
            device.cleanup();
            harness.bump()
        }
    }
}

#[cfg(target_os = "windows")]
impl<
    A: ApplicationBase<gfx_device_dx11::Resources, D3D11CommandBuffer>
> ApplicationD3D11 for A {
    fn launch(title: &str, config: Config) {
        use gfx::traits::{Device, Factory};

        env_logger::init().unwrap();
        let (window, device, mut factory, main_color) =
            gfx_window_dxgi::init::<ColorFormat>(title, config.size.0, config.size.1)
            .unwrap();
        let main_depth = factory.create_depth_stencil_view_only(
            window.size.0, window.size.1).unwrap();

        //let combuf = factory.create_command_buffer();
        let combuf = factory.create_command_buffer_native();

        let mut app = Self::new(factory, combuf.into(), Init {
            backend: shade::Backend::Hlsl(device.get_shader_model()),
            color: main_color,
            depth: main_depth,
            aspect_ratio: window.size.0 as f32 / window.size.1 as f32,
        });

        let mut device: gfx_device_dx11::Deferred = device.into();

        let mut harness = Harness::new();
        while window.dispatch() {
            app.render(&mut device);
            window.swap_buffers(1);
            device.cleanup();
            harness.bump();
        }
    }
}
<commit_msg>gfx_app refactored a little to improve readability<commit_after>// Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

extern crate env_logger;
extern crate getopts;
extern crate time;
extern crate glutin;
extern crate gfx;
extern crate gfx_device_gl;
#[cfg(target_os = "windows")]
extern crate gfx_device_dx11;
extern crate gfx_window_glutin;
//extern crate gfx_window_glfw;
#[cfg(target_os = "windows")]
extern crate gfx_window_dxgi;

pub mod shade;

pub type ColorFormat = gfx::format::Srgba8;
pub type DepthFormat = gfx::format::DepthStencil;

pub struct Init<R: gfx::Resources> {
    pub backend: shade::Backend,
    pub color: gfx::handle::RenderTargetView<R, ColorFormat>,
    pub depth: gfx::handle::DepthStencilView<R, DepthFormat>,
    pub aspect_ratio: f32,
}

pub enum Backend {
    OpenGL2,
    Direct3D11 {
        pix_mode: bool,
    },
}

pub struct Config {
    //pub backend: Backend,
    pub size: (u16, u16),
}

pub const DEFAULT_CONFIG: Config = Config {
    //backend: Backend::OpenGL2,
    size: (800, 520),
};

struct Harness {
    start: f64,
    num_frames: f64,
}

impl Harness {
    fn new() -> Harness {
        Harness {
            start: time::precise_time_s(),
            num_frames: 0.0,
        }
    }
    fn bump(&mut self) {
        self.num_frames += 1.0;
    }
}

impl Drop for Harness {
    fn drop(&mut self) {
        let time_end = time::precise_time_s();
        println!("Avg frame time: {} ms",
            (time_end - self.start) * 1000.0 / self.num_frames
        );
    }
}

pub trait ApplicationBase<R: gfx::Resources, C: gfx::CommandBuffer<R>> {
    fn new<F>(F, gfx::Encoder<R, C>, Init<R>) -> Self where
        F: gfx::Factory<R>;
    fn render<D>(&mut self, &mut D) where
        D: gfx::Device<Resources=R, CommandBuffer=C>;
}

pub trait Application<R: gfx::Resources>: Sized {
    fn new<F: gfx::Factory<R>>(F, Init<R>) -> Self;
    fn render<C: gfx::CommandBuffer<R>>(&mut self, &mut gfx::Encoder<R, C>);
    #[cfg(target_os = "windows")]
    fn launch_default(name: &str) where WrapD3D11<Self>: ApplicationD3D11 {
        WrapD3D11::<Self>::launch(name, DEFAULT_CONFIG);
    }
    #[cfg(not(target_os = "windows"))]
    fn launch_default(name: &str) where WrapGL2<Self>: ApplicationGL2 {
        WrapGL2::<Self>::launch(name, DEFAULT_CONFIG);
    }
}

pub struct Wrap<R: gfx::Resources, C: gfx::CommandBuffer<R>, A>{
    encoder: gfx::Encoder<R, C>,
    app: A,
}

#[cfg(target_os = "windows")]
pub type D3D11CommandBuffer = gfx_device_dx11::CommandBuffer<gfx_device_dx11::DeferredContext>;
#[cfg(target_os = "windows")]
pub type D3D11CommandBufferFake = gfx_device_dx11::CommandBuffer<gfx_device_dx11::CommandList>;
#[cfg(target_os = "windows")]
pub type WrapD3D11<A> = Wrap<gfx_device_dx11::Resources, D3D11CommandBuffer, A>;
pub type WrapGL2<A> = Wrap<gfx_device_gl::Resources, gfx_device_gl::CommandBuffer, A>;

impl<R, C, A> ApplicationBase<R, C> for Wrap<R, C, A> where
    R: gfx::Resources,
    C: gfx::CommandBuffer<R>,
    A: Application<R>
{
    fn new<F>(factory: F, encoder: gfx::Encoder<R, C>, init: Init<R>) -> Self where
        F: gfx::Factory<R>
    {
        Wrap {
            encoder: encoder,
            app: A::new(factory, init),
        }
    }

    fn render<D>(&mut self, device: &mut D) where
        D: gfx::Device<Resources=R, CommandBuffer=C>
    {
        self.app.render(&mut self.encoder);
        self.encoder.flush(device);
    }
}

pub trait ApplicationGL2 {
    fn launch(&str, Config);
}

#[cfg(target_os = "windows")]
pub trait ApplicationD3D11 {
    fn launch(&str, Config);
}

impl<A> ApplicationGL2 for A where
    A: ApplicationBase<gfx_device_gl::Resources,
                       gfx_device_gl::CommandBuffer>
{
    fn launch(title: &str, config: Config) {
        use gfx::traits::Device;

        env_logger::init().unwrap();
        let builder = glutin::WindowBuilder::new()
            .with_title(title.to_string())
            .with_dimensions(config.size.0 as u32, config.size.1 as u32)
            .with_vsync();
        let (window, mut device, mut factory, main_color, main_depth) =
            gfx_window_glutin::init::<ColorFormat, DepthFormat>(builder);
        let (width, height) = window.get_inner_size().unwrap();
        let combuf = factory.create_command_buffer();

        let mut app = Self::new(factory, combuf.into(), Init {
            backend: shade::Backend::Glsl(device.get_info().shading_language),
            color: main_color,
            depth: main_depth,
            aspect_ratio: width as f32 / height as f32,
        });

        let mut harness = Harness::new();
        'main: loop {
            // quit when Esc is pressed.
            for event in window.poll_events() {
                match event {
                    glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) |
                    glutin::Event::Closed => break 'main,
                    _ => {},
                }
            }
            // draw a frame
            app.render(&mut device);
            window.swap_buffers().unwrap();
            device.cleanup();
            harness.bump()
        }
    }
}

#[cfg(target_os = "windows")]
impl<
    A: ApplicationBase<gfx_device_dx11::Resources, D3D11CommandBuffer>
> ApplicationD3D11 for A {
    fn launch(title: &str, config: Config) {
        use gfx::traits::{Device, Factory};

        env_logger::init().unwrap();
        let (window, device, mut factory, main_color) =
            gfx_window_dxgi::init::<ColorFormat>(title, config.size.0, config.size.1)
            .unwrap();
        let main_depth = factory.create_depth_stencil_view_only(
            window.size.0, window.size.1).unwrap();

        //let combuf = factory.create_command_buffer();
        let combuf = factory.create_command_buffer_native();

        let mut app = Self::new(factory, combuf.into(), Init {
            backend: shade::Backend::Hlsl(device.get_shader_model()),
            color: main_color,
            depth: main_depth,
            aspect_ratio: window.size.0 as f32 / window.size.1 as f32,
        });

        let mut device: gfx_device_dx11::Deferred = device.into();

        let mut harness = Harness::new();
        while window.dispatch() {
            app.render(&mut device);
            window.swap_buffers(1);
            device.cleanup();
            harness.bump();
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>added parsetools<commit_after>// ParseTools for reference to slice of char

pub trait ParseTools
{
	type Item;
	fn skip_while<F>(self, pred: F) -> Self where F: Fn(Self::Item) -> bool;
	fn take_while<F>(self, pred: F) -> (Self, Self) where F: Fn(Self::Item) -> bool;
	fn drop(self, count: usize) -> Self;
	fn clone_as_string(self) -> String;
}
impl<'a> ParseTools for &'a [char]
{
	type Item = char;
	fn skip_while<F>(self, pred: F) -> Self where F: Fn(char) -> bool
	{
		if !self.is_empty() && pred(self[0]) { Self::skip_while(&self[1..], pred) } else { self }
	}
	fn take_while<F>(self, pred: F) -> (Self, Self) where F: Fn(char) -> bool
	{
		fn _impl<F>(input: &[char], counter: usize, pred: F) -> usize where F: Fn(char) -> bool
		{
			if !input.is_empty() && pred(input[0]) { _impl(&input[1..], counter + 1, pred) } else { counter }
		}
		let len = _impl(self, 0, pred);
		(&self[..len], &self[len..])
	}
	fn drop(self, count: usize) -> Self { &self[count..] }
	fn clone_as_string(self) -> String { self.into_iter().cloned().collect() }
}
<|endoftext|>


<commit_before><commit_msg>Base SMP code<commit_after>use core::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};
use interrupts::apic::send_interrupt;
use collections::Vec;

extern {
    fn smp_init_vector();
}

#[allow(non_upper_case_globals)]
pub static processor_count: AtomicUsize = ATOMIC_USIZE_INIT;
<|endoftext|>


<commit_before><commit_msg>tap_parser -> TapParser<commit_after><|endoftext|>


<commit_before><commit_msg>solved 0004 with Rust<commit_after>use std::io::prelude::*;
use std::str::FromStr;

fn ans( i : Vec<f64> ) -> (f64,f64) {
    let a = i[0];
    let b = i[1];
    let c = i[2];
    let d = i[3];
    let e = i[4];
    let f = i[5];

    let x = ( (c*e - b*f) / (a*e - b*d) * 1000.0).round() / 1000.0;
    let y = ( (c*d - a*f) / (b*d - a*e) * 1000.0).round() / 1000.0;

    (x,y)
}

fn main() {
    let stdin = std::io::stdin();

    for line in stdin.lock().lines() {
        let d : Vec<f64> = line.unwrap().split_whitespace().map(|x| f64::from_str(x).unwrap()).collect();
        let (x,y) = ans(d);
        println!("{:.3} {:.3}",x,y);
    }
}
<|endoftext|>


<commit_before><commit_msg>Change At test to use assert_eq!<commit_after><|endoftext|>


<commit_before>
fn main() {
    let v = vec::from_fn(1024u) {|n| n};
    // this should trip a bounds check
    log(error, v[-1i8]);
}
<commit_msg>test: Add an error pattern to small-negative-indexing<commit_after>// error-pattern:bounds check
fn main() {
    let v = vec::from_fn(1024u) {|n| n};
    // this should trip a bounds check
    log(error, v[-1i8]);
}
<|endoftext|>


<commit_before><commit_msg>Basic tests for reopen logging<commit_after>//! Tests!
extern crate fern;
extern crate log;
extern crate tempdir;

use std::io::prelude::*;
use std::{fs, io};

use log::Level::*;

mod support;

use support::manual_log;

#[test]
fn test_basic_logging_reopen_logging() {
    // Create a temporary directory to put a log file into for testing
    let temp_log_dir = tempdir::TempDir::new("fern").expect("Failed to set up temporary directory");
    let log_file = temp_log_dir.path().join("test.log");

    {
        // Create a basic logger configuration
        let (_max_level, logger) = fern::Dispatch::new()
            .format(|out, msg, record| out.finish(format_args!("[{}] {}", record.level(), msg)))
            .level(log::LevelFilter::Info)
            .chain(io::stdout())
            .chain(fern::log_reopen(&log_file).expect("Failed to open log file"))
            .into_log();

        let l = &*logger;
        manual_log(l, Trace, "SHOULD NOT DISPLAY");
        manual_log(l, Debug, "SHOULD NOT DISPLAY");
        manual_log(l, Info, "Test information message");
        manual_log(l, Warn, "Test warning message");
        manual_log(l, Error, "Test error message");

        // ensure all File objects are dropped and OS buffers are flushed.
        log::logger().flush();

        {
            let result = {
                let mut log_read = fs::File::open(&temp_log_dir.path().join("test.log")).unwrap();
                let mut buf = String::new();
                log_read.read_to_string(&mut buf).unwrap();
                buf
            };
            assert!(
                !result.contains("SHOULD NOT DISPLAY"),
                "expected result not including \"SHOULD_NOT_DISPLAY\", found:\n```\n{}\n```\n",
                result
            );
            assert!(
                result.contains("[INFO] Test information message"),
                "expected result including \"[INFO] Test information message\", found:\n```\n{}\n```\n",
                result
            );
            assert!(
                result.contains("[WARN] Test warning message"),
                "expected result including \"[WARN] Test warning message\", found:\n```\n{}\n```\n",
                result
            );
            assert!(
                result.contains("[ERROR] Test error message"),
                "expected result to not include \"[ERROR] Test error message\", found:\n```\n{}\n```\n",
                result
            );
        }
    } // ensure logger is dropped before temp dir

    temp_log_dir
        .close()
        .expect("Failed to clean up temporary directory");
}

#[test]
fn test_custom_line_separators() {
    // Create a temporary directory to put a log file into for testing
    let temp_log_dir = tempdir::TempDir::new("fern").expect("Failed to set up temporary directory");
    let log_file = temp_log_dir.path().join("test_custom_line_sep.log");

    {
        // Create a basic logger configuration
        let (_max_level, logger) = fern::Dispatch::new()
            // default format is just the message if not specified
            // default log level is 'trace' if not specified (logs all messages)
            // output to the log file with the "\r\n" line separator.
            .chain(fern::Output::reopen(fern::log_reopen(&log_file).expect("Failed to open log file"), "\r\n"))
            .into_log();

        let l = &*logger;
        manual_log(l, Info, "message1");
        manual_log(l, Info, "message2");

        // ensure all File objects are dropped and OS buffers are flushed.
        logger.flush();

        {
            let result = {
                let mut log_read =
                    fs::File::open(&temp_log_dir.path().join("test_custom_line_sep.log")).unwrap();
                let mut buf = String::new();
                log_read.read_to_string(&mut buf).unwrap();
                buf
            };
            assert_eq!(&result, "message1\r\nmessage2\r\n");
        }
    } // ensure logger is dropped before temp dir

    temp_log_dir
        .close()
        .expect("Failed to clean up temporary directory");
}

<|endoftext|>


<commit_before><commit_msg>Adding Rust version<commit_after>fn main() {
    loop {
        print!("BEES ");
    }
}
<|endoftext|>


<commit_before><commit_msg>Update vec.rs<commit_after><|endoftext|>


<commit_before><commit_msg>with permissive-provenance set, we already treat ptr::invalid correctly<commit_after>// compile-flags: -Zmiri-permissive-provenance
#![feature(strict_provenance)]

// Ensure that a `ptr::invalid` ptr is truly invalid.
fn main() {
    let x = 42;
    let xptr = &x as *const i32;
    let xptr_invalid = std::ptr::invalid::<i32>(xptr.expose_addr());
    let _val = unsafe { *xptr_invalid }; //~ ERROR is not a valid pointer
}
<|endoftext|>


<commit_before><commit_msg>Add tests for Visibility parsing<commit_after>mod features;

use proc_macro2::TokenStream;
use syn::{Result, Visibility};
use syn::parse::{Parse, ParseStream};

#[derive(Debug)]
struct VisRest {
    vis: Visibility,
    rest: TokenStream,
}

impl Parse for VisRest {
    fn parse(input: ParseStream) -> Result<Self> {
        Ok(VisRest {
            vis: input.parse()?,
            rest: input.parse()?,
        })
    }
}

macro_rules! assert_vis_parse {
    ($input:expr, Ok($p:pat)) => {
        assert_vis_parse!($input, Ok($p) + "");
    };

    ($input:expr, Ok($p:pat) + $rest:expr) => {
        let expected = $rest.parse::<TokenStream>().unwrap();
        let parse: VisRest = syn::parse_str($input).unwrap();

        match parse.vis {
            $p => {}
            _ => panic!("Expected {}, got {:?}", stringify!($p), parse.vis),
        }

        // NOTE: Round-trips through `to_string` to avoid potential whitespace
        // diffs.
        assert_eq!(parse.rest.to_string(), expected.to_string());
    };

    ($input:expr, Err) => {
        syn::parse2::<VisRest>($input.parse().unwrap()).unwrap_err();
    };
}

#[test]
fn test_pub() {
    assert_vis_parse!("pub", Ok(Visibility::Public(_)));
}

#[test]
fn test_crate() {
    assert_vis_parse!("crate", Ok(Visibility::Crate(_)));
}

#[test]
fn test_inherited() {
    assert_vis_parse!("", Ok(Visibility::Inherited));
}

#[test]
fn test_in() {
    assert_vis_parse!("pub(in foo::bar)", Ok(Visibility::Restricted(_)));
}

#[test]
fn test_pub_crate() {
    assert_vis_parse!("pub(crate)", Ok(Visibility::Restricted(_)));
}

#[test]
fn test_pub_self() {
    assert_vis_parse!("pub(self)", Ok(Visibility::Restricted(_)));
}

#[test]
fn test_pub_super() {
    assert_vis_parse!("pub(super)", Ok(Visibility::Restricted(_)));
}

#[test]
fn test_missing_in() {
    assert_vis_parse!("pub(foo::bar)", Ok(Visibility::Public(_)) + "(foo::bar)");
}

#[test]
fn test_missing_in_path() {
    assert_vis_parse!("pub(in)", Err);
}

#[test]
fn test_crate_path() {
    assert_vis_parse!("pub(crate::A, crate::B)", Ok(Visibility::Public(_)) + "(crate::A, crate::B)");
}

#[test]
fn test_junk_after_in() {
    assert_vis_parse!("pub(in some::path @@garbage)", Err);
}
<|endoftext|>


<commit_before><commit_msg>Small fix for remove_entity<commit_after><|endoftext|>


<commit_before><commit_msg>Create a prototype for rewindable database<commit_after>use std::collections::BTreeMap;
use std::sync::{Arc, RwLock};

use exonum::storage::{Database, Patch, Change, Result as StorageResult, Snapshot};

/// Implementation of a `Database`, which allows to rollback commits introduced by the `merge()`
/// function.
///
/// **Note:** Intended for testing purposes only. Probably inefficient.
#[derive(Clone, Debug)]
pub struct CheckpointDb<T> {
    inner: T,
    journal: Arc<RwLock<Vec<Patch>>>,
}

impl<T: Database + Clone> CheckpointDb<T> {
    /// Creates a new checkpointed database that uses the specified `db` as the underlying
    /// data storage.
    pub fn new(db: T) -> Self {
        CheckpointDb {
            inner: db,
            journal: Arc::new(RwLock::new(Vec::new())),
        }
    }

    /// Rolls this database by udoing the latest `count` `merge()` operations.
    pub fn rollback(&mut self, count: usize) -> bool {
        let journal_len = self.journal
            .read()
            .expect("Cannot acquire read lock on journal")
            .len();
        assert!(
            journal_len >= count,
            "Cannot rollback {} changes; only {} checkpoints in the journal",
            count,
            journal_len
        );

        let mut journal = self.journal.write().expect(
            "Cannot acquire write lock on journal",
        );

        for _ in 0..count {
            if let Some(patch) = journal.pop() {
                self.inner.merge(patch).expect(
                    "Cannot merge roll-back patch",
                );
            } else {
                panic!("Cannot rollback the database, the journal is empty");
            }
        }

        journal_len < count
    }

    /// Returns a handler to the database. The handler could be used to roll the database back
    /// without having the ownership to it.
    pub fn handler(&self) -> CheckpointDbHandler<T> {
        CheckpointDbHandler(Clone::clone(self))
    }
}

impl<T: Database + Clone> Database for CheckpointDb<T> {
    fn clone(&self) -> Box<Database> {
        Box::new(Clone::clone(self))
    }

    fn snapshot(&self) -> Box<Snapshot> {
        self.inner.snapshot()
    }

    fn merge(&mut self, patch: Patch) -> StorageResult<()> {
        let snapshot = self.inner.snapshot();
        let mut rev_patch = Patch::new();

        for (name, kv_map) in &patch {
            let mut rev_kv_map = BTreeMap::new();
            for key in kv_map.keys() {
                match snapshot.get(name, key) {
                    Some(value) => {
                        rev_kv_map.insert(key.clone(), Change::Put(value));
                    }
                    None => {
                        rev_kv_map.insert(key.clone(), Change::Delete);
                    }
                }
            }
            rev_patch.insert(name.to_string(), rev_kv_map);
        }

        {
            let mut journal = self.journal.write().expect(
                "Cannot acquire write lock on journal",
            );
            journal.push(rev_patch);
        }
        self.inner.merge(patch)
    }
}

/// Handler to a checkpointed database.
#[derive(Clone, Debug)]
pub struct CheckpointDbHandler<T>(CheckpointDb<T>);

impl<T: Database + Clone> CheckpointDbHandler<T> {
    /// Rolls this database by udoing the latest `count` `merge()` operations.
    pub fn rollback(&mut self, count: usize) -> bool {
        self.0.rollback(count)
    }
}

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

    fn create_patch<'a, I>(from: I) -> Patch
    where
        I: IntoIterator<Item = (&'a str, Vec<u8>, Change)>,
    {
        let mut patch = Patch::new();

        for (name, key, value) in from.into_iter() {
            let name = name.to_string();
            let kv_map = patch.entry(name).or_insert_with(BTreeMap::new);
            if kv_map.insert(key, value).is_some() {
                panic!("Attempt to re-insert a key into patch");
            }
        }

        patch
    }

    #[test]
    fn test_checkpointdb_basics() {
        let mut db = CheckpointDb::new(MemoryDB::new());
        let mut fork = db.fork();
        fork.put("foo", vec![], vec![2]);
        db.merge(fork.into_patch()).unwrap();
        {
            let journal = db.journal.read().expect(
                "Cannot acquire read lock on journal",
            );
            assert_eq!(journal.len(), 1);
            assert_eq!(
                journal[0],
                create_patch(vec![("foo", vec![], Change::Delete)])
            );
        }

        let snapshot = db.snapshot();
        assert_eq!(snapshot.get("foo", &[]), Some(vec![2]));

        let mut fork = db.fork();
        fork.put("foo", vec![], vec![3]);
        fork.put("bar", vec![1], vec![4]);
        db.merge(fork.into_patch()).unwrap();
        {
            let journal = db.journal.read().expect(
                "Cannot acquire read lock on journal",
            );
            assert_eq!(journal.len(), 2);
            assert_eq!(
                journal[0],
                create_patch(vec![("foo", vec![], Change::Delete)])
            );
            assert_eq!(
                journal[1],
                create_patch(vec![
                    ("foo", vec![], Change::Put(vec![2])),
                    ("bar", vec![1], Change::Delete),
                ])
            );
        }

        // Check that the old snapshot still corresponds to the same DB state
        assert_eq!(snapshot.get("foo", &[]), Some(vec![2]));
        let snapshot = db.snapshot();
        assert_eq!(snapshot.get("foo", &[]), Some(vec![3]));
    }

    #[test]
    fn test_checkpointdb_rollback() {
        let mut db = CheckpointDb::new(MemoryDB::new());
        let mut fork = db.fork();
        fork.put("foo", vec![], vec![2]);
        db.merge(fork.into_patch()).unwrap();

        let mut fork = db.fork();
        fork.put("foo", vec![], vec![3]);
        fork.put("bar", vec![1], vec![4]);
        db.merge(fork.into_patch()).unwrap();
        {
            let journal = db.journal.read().expect(
                "Cannot acquire read lock on journal",
            );
            assert_eq!(journal.len(), 2);
        }

        let snapshot = db.snapshot();
        assert_eq!(snapshot.get("foo", &[]), Some(vec![3]));
        db.rollback(1);
        let snapshot = db.snapshot();
        assert_eq!(snapshot.get("foo", &[]), Some(vec![2]));
        assert_eq!(snapshot.get("bar", &[1]), None);
        {
            let journal = db.journal.read().expect(
                "Cannot acquire read lock on journal",
            );
            assert_eq!(journal.len(), 1);
        }

        // Check that DB continues working as usual after a rollback
        let mut fork = db.fork();
        fork.put("foo", vec![], vec![4]);
        fork.put("foo", vec![0, 0], vec![255]);
        db.merge(fork.into_patch()).unwrap();
        {
            let journal = db.journal.read().expect(
                "Cannot acquire read lock on journal",
            );
            assert_eq!(journal.len(), 2);
        }
        let snapshot = db.snapshot();
        assert_eq!(snapshot.get("foo", &[]), Some(vec![4]));
        assert_eq!(snapshot.get("foo", &[0, 0]), Some(vec![255]));

        let mut fork = db.fork();
        fork.put("bar", vec![1], vec![254]);
        db.merge(fork.into_patch()).unwrap();
        {
            let journal = db.journal.read().expect(
                "Cannot acquire read lock on journal",
            );
            assert_eq!(journal.len(), 3);
        }
        let new_snapshot = db.snapshot();
        assert_eq!(new_snapshot.get("foo", &[]), Some(vec![4]));
        assert_eq!(new_snapshot.get("foo", &[0, 0]), Some(vec![255]));
        assert_eq!(new_snapshot.get("bar", &[1]), Some(vec![254]));

        db.rollback(2);
        {
            let journal = db.journal.read().expect(
                "Cannot acquire read lock on journal",
            );
            assert_eq!(journal.len(), 1);
        }
        let snapshot = db.snapshot();
        assert_eq!(snapshot.get("foo", &[]), Some(vec![2]));
        assert_eq!(snapshot.get("foo", &[0, 0]), None);
        assert_eq!(snapshot.get("bar", &[1]), None);

        assert_eq!(new_snapshot.get("foo", &[]), Some(vec![4]));
        assert_eq!(new_snapshot.get("foo", &[0, 0]), Some(vec![255]));
        assert_eq!(new_snapshot.get("bar", &[1]), Some(vec![254]));
    }

    #[test]
    fn test_checkpointdb_clone() {
        let mut db = CheckpointDb::new(MemoryDB::new());
        let mut db_clone = Database::clone(&db);

        let mut fork = db.fork();
        fork.put("foo", vec![], vec![2]);
        db.merge(fork.into_patch()).unwrap();

        let snapshot = db_clone.snapshot();
        assert_eq!(snapshot.get("foo", &[]), Some(vec![2]));

        let mut fork = db_clone.fork();
        fork.put("foo", vec![], vec![3]);
        db_clone.merge(fork.into_patch()).unwrap();

        let snapshot = db.snapshot();
        assert_eq!(snapshot.get("foo", &[]), Some(vec![3]));

        // Check rollback on clones
        let mut db_clone = Clone::clone(&db);
        db_clone.rollback(1);
        let snapshot = db.snapshot();
        assert_eq!(snapshot.get("foo", &[]), Some(vec![2]));
        db.rollback(1);
        let snapshot = db_clone.snapshot();
        assert_eq!(snapshot.get("foo", &[]), None);
    }

    #[test]
    fn test_checkpointdb_handler() {
        let mut db = CheckpointDb::new(MemoryDB::new());
        let mut db_handler = db.handler();

        let mut fork = db.fork();
        fork.put("foo", vec![], vec![2]);
        db.merge(fork.into_patch()).unwrap();
        let snapshot = db.snapshot();
        assert_eq!(snapshot.get("foo", &[]), Some(vec![2]));

        db_handler.rollback(1);
        let snapshot = db.snapshot();
        assert_eq!(snapshot.get("foo", &[]), None);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add a rustdoc test for future rustc_deprecated attributes<commit_after>#![feature(staged_api)]

#![stable(feature = "rustc_deprecated-future-test", since = "1.0.0")]

// @has rustc_deprecated_future/index.html '//*[@class="stab deprecated"]' \
//      'Deprecation planned'
// @has rustc_deprecated_future/struct.S.html '//*[@class="stab deprecated"]' \
//      'Deprecating in 99.99.99: effectively never'
#[rustc_deprecated(since = "99.99.99", reason = "effectively never")]
#[stable(feature = "rustc_deprecated-future-test", since = "1.0.0")]
pub struct S;
<|endoftext|>


<commit_before><commit_msg>Add initialization benchmark<commit_after>extern crate glutin;
extern crate glium;
extern crate test;

use glium::DisplayBuild;

#[bench]
fn initialization(bencher: &mut test::Bencher) {
    bencher.bench_n(1, |bencher| {
        bencher.iter(|| {
            glutin::WindowBuilder::new().with_visibility(false).build_glium().unwrap()
        });
    });
}
<|endoftext|>


<commit_before><commit_msg>Problem 19<commit_after>fn rotate<T: Clone>(list: &[T], n: i32) -> ~[T] {
    let mut res = ~[];
    if n >= 0 {
        res.push_all(list.slice_from(n as uint));
        res.push_all(list.slice_to(n as uint));
        res
    } else {
        res.push_all(list.slice_from(list.len() + n as uint));
        res.push_all(list.slice_to(list.len() + n as uint));
        res
    }

}

fn main() {
    let list = ~['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];
    println!("{:?}", rotate(list, 3));
    println!("{:?}", rotate(list, -2));
}

<|endoftext|>


<commit_before><commit_msg>deleted: "tests/dir/ls\"alh.rs" for windows<commit_after><|endoftext|>


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

#![feature(plugin_registrar, quote)]

extern crate rustc;
extern crate syntax;

use std::gc::{Gc, GC};
use std::io::Command;
use std::mem;
use std::str;
use syntax::ast;
use syntax::codemap;
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use syntax::parse::token;
use syntax::parse::token::InternedString;

#[plugin_registrar]
pub fn registrar(reg: &mut rustc::plugin::Registry) {
    reg.register_syntax_extension(token::intern("link_glfw"),
                                  base::ItemModifier(expand));
}

enum Meta {
    MetaName(InternedString),
    MetaNameValue(InternedString, ast::Lit_),
    MetaList(InternedString, Vec<Meta>),
}

impl Meta {
    fn to_meta_item(self, context: &mut base::ExtCtxt, span: codemap::Span) -> Gc<ast::MetaItem> {
        match self {
            MetaName(name) => context.meta_word(span, name),
            MetaNameValue(name, value) => context.meta_name_value(span, name, value),
            MetaList(name, list) => {
                let meta_items = list.move_iter().map(|meta| {
                    meta.to_meta_item(context, span)
                }).collect();
                context.meta_list(span, name, meta_items)
            },
        }
    }

    fn to_attribute(self, context: &mut base::ExtCtxt, span: codemap::Span) -> ast::Attribute {
        let meta = self.to_meta_item(context, span);
        context.attribute(span, meta)
    }

    fn link(name: InternedString, kind: Option<InternedString>) -> Meta {
        let mut name_meta = MetaNameValue(InternedString::new("name"),
                                          ast::LitStr(name, ast::CookedStr));
        MetaList(InternedString::new("link"), match kind {
            Some(kind) => {
                let kind_meta = MetaNameValue(InternedString::new("kind"),
                                              ast::LitStr(kind, ast::CookedStr));
                vec![name_meta, kind_meta]
            },
            None => {
                vec![name_meta]
            },
        })
    }
}

pub fn expand(context: &mut base::ExtCtxt, span: codemap::Span, meta_item: Gc<ast::MetaItem>,
              item: Gc<ast::Item>) -> Gc<ast::Item> {
    let out = Command::new("pkg-config")
        .arg("--static")
        .arg("--libs-only-l")
        .arg("--libs-only-other")
        .arg("glfw3")
        .output();
    match out {
        Ok(out) => {
            if out.status.success() {
                let mut item = (*item).clone();
                str::from_utf8(out.output.as_slice()).map(|output| {
                    let mut expect_framework = false;
                    for word in output.words() {
                        if word.starts_with("-l") {
                            item.attrs.push(Meta::link(
                                token::intern_and_get_ident(word.slice_from(2)),
                                None,
                            ).to_attribute(context, span));
                        } else if expect_framework {
                            expect_framework = false;
                            item.attrs.push(Meta::link(
                                token::intern_and_get_ident(word),
                                Some(InternedString::new("framework")),
                            ).to_attribute(context, span));
                        } else if word.starts_with("-framework") {
                            expect_framework = true;
                        }
                    }
                });
                box (GC) item
            } else {
                context.span_err(span, format!("error returned by \
                    `pkg-config`: ({})", out.status).as_slice());
                item
            }
        },
        Err(e) => {
            context.span_err(span, format!("io error: {}", e).as_slice());
            item
        },
    }
}
<commit_msg>Simplify syntax extension implementation<commit_after>// Copyright 2014 The GLFW-RS Developers. For a full listing of the authors,
// refer to the AUTHORS file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![feature(plugin_registrar, quote)]

extern crate rustc;
extern crate syntax;

use std::gc::{Gc, GC};
use std::io::Command;
use std::mem;
use std::str;
use syntax::ast;
use syntax::codemap;
use syntax::ext::base;
use syntax::ext::build::AstBuilder;
use syntax::parse::token;
use intern_str = syntax::parse::token::intern_and_get_ident;

#[plugin_registrar]
pub fn registrar(reg: &mut rustc::plugin::Registry) {
    reg.register_syntax_extension(token::intern("link_glfw"),
                                  base::ItemModifier(expand));
}

fn lit_str(s: token::InternedString) -> ast::Lit_ {
    ast::LitStr(s, ast::CookedStr)
}

enum LinkKind {
    Unknown,
    Framework,
}

fn attr_link(context: &mut base::ExtCtxt, span: codemap::Span,
             name: token::InternedString, kind: LinkKind) -> ast::Attribute {
    let mut meta_items = vec![
        context.meta_name_value(span, intern_str("name"), lit_str(name)),
    ];
    match kind {
        Framework => {
            meta_items.push(context.meta_name_value(
                span, intern_str("kind"),
                lit_str(intern_str("framework"))
            ));
        },
        _ => {},
    }
    let meta_list = context.meta_list(span, intern_str("link"), meta_items);
    context.attribute(span, meta_list)
}

pub fn expand(context: &mut base::ExtCtxt, span: codemap::Span,
              meta_item: Gc<ast::MetaItem>, item: Gc<ast::Item>
              ) -> Gc<ast::Item> {
    let out = Command::new("pkg-config")
        .arg("--static")
        .arg("--libs-only-l")
        .arg("--libs-only-other")
        .arg("glfw3")
        .output();
    match out {
        Ok(out) => {
            if out.status.success() {
                let mut item = (*item).clone();
                str::from_utf8(out.output.as_slice()).map(|output| {
                    let mut expect_framework = false;
                    for word in output.words() {
                        if word.starts_with("-l") {
                            item.attrs.push(attr_link(
                                context, span,
                                intern_str(word.slice_from(2)),
                                Unknown,
                            ));
                        } else if expect_framework {
                            expect_framework = false;
                            item.attrs.push(attr_link(
                                context, span,
                                intern_str(word),
                                Framework,
                            ));
                        } else if word.starts_with("-framework") {
                            expect_framework = true;
                        }
                    }
                });
                box (GC) item
            } else {
                context.span_err(span, format!("error returned by \
                    `pkg-config`: ({})", out.status).as_slice());
                item
            }
        },
        Err(e) => {
            context.span_err(span, format!("io error: {}", e).as_slice());
            item
        },
    }
}
<|endoftext|>


<commit_before>use std::io::Read;
use std::fs::File;
use std::fmt;

/// Body type for a request.
#[derive(Debug)]
pub struct Body {
    reader: Kind,
}

impl Body {
    /// Instantiate a `Body` from a reader.
    pub fn new<R: Read + 'static>(reader: R) -> Body {
        Body {
            reader: Kind::Reader(Box::new(reader), None),
        }
    }

    /*
    pub fn sized(reader: (), len: u64) -> Body {
        unimplemented!()
    }

    pub fn chunked(reader: ()) -> Body {
        unimplemented!()
    }
    */
}

// useful for tests, but not publicly exposed
#[cfg(test)]
pub fn read_to_string(mut body: Body) -> ::std::io::Result<String> {
    let mut s = String::new();
    match body.reader {
        Kind::Reader(ref mut reader, _) => {
            reader.read_to_string(&mut s)
        }
        Kind::Bytes(ref mut bytes) => {
            (&**bytes).read_to_string(&mut s)
        }
    }.map(|_| s)
}

enum Kind {
    Reader(Box<Read>, Option<u64>),
    Bytes(Vec<u8>),
}

impl From<Vec<u8>> for Body {
    #[inline]
    fn from(v: Vec<u8>) -> Body {
        Body {
            reader: Kind::Bytes(v),
        }
    }
}

impl From<String> for Body {
    #[inline]
    fn from(s: String) -> Body {
        s.into_bytes().into()
    }
}

impl<'a> From<&'a [u8]> for Body {
    #[inline]
    fn from(s: &'a [u8]) -> Body {
        s.to_vec().into()
    }
}

impl<'a> From<&'a str> for Body {
    #[inline]
    fn from(s: &'a str) -> Body {
        s.as_bytes().into()
    }
}

impl From<File> for Body {
    #[inline]
    fn from(f: File) -> Body {
        let len = f.metadata().map(|m| m.len()).ok();
        Body {
            reader: Kind::Reader(Box::new(f), len),
        }
    }
}

impl fmt::Debug for Kind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &Kind::Reader(_, ref v) => f.debug_tuple("Kind::Reader").field(&"_").field(v).finish(),
            &Kind::Bytes(ref v) => f.debug_tuple("Kind::Bytes").field(v).finish(),
        }
    }
}

// Wraps a `std::io::Write`.
//pub struct Pipe(Kind);

pub fn as_hyper_body<'a>(body: &'a mut Body) -> ::hyper::client::Body<'a> {
    match body.reader {
        Kind::Bytes(ref bytes) => {
            let len = bytes.len();
            ::hyper::client::Body::BufBody(bytes, len)
        }
        Kind::Reader(ref mut reader, len_opt) => {
            match len_opt {
                Some(len) => ::hyper::client::Body::SizedBody(reader, len),
                None => ::hyper::client::Body::ChunkedBody(reader),
            }
        }
    }
}

pub fn can_reset(body: &Body) -> bool {
    match body.reader {
        Kind::Bytes(_) => true,
        Kind::Reader(..) => false,
    }
}
<commit_msg>add a note to  about redirects<commit_after>use std::io::Read;
use std::fs::File;
use std::fmt;

/// Body type for a request.
#[derive(Debug)]
pub struct Body {
    reader: Kind,
}

impl Body {
    /// Instantiate a `Body` from a reader.
    ///
    /// # Note
    ///
    /// While allowing for many types to be used, these bodies do not have
    /// a way to reset to the beginning and be reused. This means that when
    /// encountering a 307 or 308 status code, instead of repeating the
    /// request at the new location, the `Response` will be returned with
    /// the redirect status code set.
    ///
    /// A `Body` constructed from a set of bytes, like `String` or `Vec<u8>`,
    /// are stored differently and can be reused.
    pub fn new<R: Read + 'static>(reader: R) -> Body {
        Body {
            reader: Kind::Reader(Box::new(reader), None),
        }
    }

    /*
    pub fn sized(reader: (), len: u64) -> Body {
        unimplemented!()
    }

    pub fn chunked(reader: ()) -> Body {
        unimplemented!()
    }
    */
}

// useful for tests, but not publicly exposed
#[cfg(test)]
pub fn read_to_string(mut body: Body) -> ::std::io::Result<String> {
    let mut s = String::new();
    match body.reader {
        Kind::Reader(ref mut reader, _) => {
            reader.read_to_string(&mut s)
        }
        Kind::Bytes(ref mut bytes) => {
            (&**bytes).read_to_string(&mut s)
        }
    }.map(|_| s)
}

enum Kind {
    Reader(Box<Read>, Option<u64>),
    Bytes(Vec<u8>),
}

impl From<Vec<u8>> for Body {
    #[inline]
    fn from(v: Vec<u8>) -> Body {
        Body {
            reader: Kind::Bytes(v),
        }
    }
}

impl From<String> for Body {
    #[inline]
    fn from(s: String) -> Body {
        s.into_bytes().into()
    }
}

impl<'a> From<&'a [u8]> for Body {
    #[inline]
    fn from(s: &'a [u8]) -> Body {
        s.to_vec().into()
    }
}

impl<'a> From<&'a str> for Body {
    #[inline]
    fn from(s: &'a str) -> Body {
        s.as_bytes().into()
    }
}

impl From<File> for Body {
    #[inline]
    fn from(f: File) -> Body {
        let len = f.metadata().map(|m| m.len()).ok();
        Body {
            reader: Kind::Reader(Box::new(f), len),
        }
    }
}

impl fmt::Debug for Kind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &Kind::Reader(_, ref v) => f.debug_tuple("Kind::Reader").field(&"_").field(v).finish(),
            &Kind::Bytes(ref v) => f.debug_tuple("Kind::Bytes").field(v).finish(),
        }
    }
}

// Wraps a `std::io::Write`.
//pub struct Pipe(Kind);

pub fn as_hyper_body<'a>(body: &'a mut Body) -> ::hyper::client::Body<'a> {
    match body.reader {
        Kind::Bytes(ref bytes) => {
            let len = bytes.len();
            ::hyper::client::Body::BufBody(bytes, len)
        }
        Kind::Reader(ref mut reader, len_opt) => {
            match len_opt {
                Some(len) => ::hyper::client::Body::SizedBody(reader, len),
                None => ::hyper::client::Body::ChunkedBody(reader),
            }
        }
    }
}

pub fn can_reset(body: &Body) -> bool {
    match body.reader {
        Kind::Bytes(_) => true,
        Kind::Reader(..) => false,
    }
}
<|endoftext|>


<commit_before><commit_msg>rust: If you can't sleep, just count sheeps<commit_after><|endoftext|>