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

export mk_pass;

fn mk_pass() -> pass {
    run
}

type ctxt = {
    mutable have_docs: bool
};

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

fn fold_mod(
    fold: fold::fold<ctxt>,
    doc: doc::moddoc
) -> doc::moddoc {
    let doc = fold::default_seq_fold_mod(fold, doc);
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(*doc.mods)
        || vec::is_not_empty(*doc.fns);
    ret doc;
}

fn fold_fn(
    fold: fold::fold<ctxt>,
    doc: doc::fndoc
) -> doc::fndoc {
    let have_arg_docs = false;
    let doc = ~{
        args: vec::filter_map(doc.args) {|doc|
            if option::is_some(doc.desc) {
                have_arg_docs = true;
                some(doc)
            } else {
                none
            }
        },
        return: {
            ty: if option::is_some(doc.return.desc) {
                doc.return.ty
            } else {
                none
            }
            with doc.return
        }
        with *doc
    };

    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || have_arg_docs
        || doc.return.desc != none;
    ret doc;
}

#[test]
fn should_elide_undocumented_arguments() {
    let source = "#[doc = \"hey\"] fn a(b: int) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.fns[0].args);
}

#[test]
fn should_not_elide_fns_with_documented_arguments() {
    let source = "#[doc(args(a = \"b\"))] fn a(a: int) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(*doc.topmod.fns);
}

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

fn fold_modlist(
    fold: fold::fold<ctxt>,
    list: doc::modlist
) -> doc::modlist {
    doc::modlist(vec::filter_map(*list) {|doc|
        let doc = fold.fold_mod(fold, doc);
        if fold.ctxt.have_docs {
            some(doc)
        } else {
            none
        }
    })
}

#[test]
fn should_elide_undocumented_mods() {
    let source = "mod a { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(*doc.topmod.mods);
}

#[test]
fn should_not_elide_undocument_mods_with_documented_mods() {
    let source = "mod a { #[doc = \"b\"] mod b { } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(*doc.topmod.mods);
}

#[test]
fn should_not_elide_undocument_mods_with_documented_fns() {
    let source = "mod a { #[doc = \"b\"] fn b() { } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(*doc.topmod.mods);
}

fn fold_fnlist(
    fold: fold::fold<ctxt>,
    list: doc::fnlist
) -> doc::fnlist {
    doc::fnlist(vec::filter_map(*list) {|doc|
        let doc = fold.fold_fn(fold, doc);
        if fold.ctxt.have_docs {
            some(doc)
        } else {
            none
        }
    })
}

#[test]
fn should_elide_undocumented_fns() {
    let source = "fn a() { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(*doc.topmod.fns);
}

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

fn fold_constlist(
    fold: fold::fold<ctxt>,
    list: doc::constlist
) -> doc::constlist {
    doc::constlist(vec::filter_map(*list) {|doc|
        let doc = fold.fold_const(fold, doc);
        if fold.ctxt.have_docs {
            some(doc)
        } else {
            none
        }
    })
}

#[test]
fn should_elide_undocumented_consts() {
    let source = "const a: bool = true;";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(*doc.topmod.consts);
}
<commit_msg>rustdoc: Don't prune functions with documented failure conditions<commit_after>#[doc = "Prunes branches of the document tree that contain no documentation"];

export mk_pass;

fn mk_pass() -> pass {
    run
}

type ctxt = {
    mutable have_docs: bool
};

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

fn fold_mod(
    fold: fold::fold<ctxt>,
    doc: doc::moddoc
) -> doc::moddoc {
    let doc = fold::default_seq_fold_mod(fold, doc);
    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || vec::is_not_empty(*doc.mods)
        || vec::is_not_empty(*doc.fns);
    ret doc;
}

fn fold_fn(
    fold: fold::fold<ctxt>,
    doc: doc::fndoc
) -> doc::fndoc {
    let have_arg_docs = false;
    let doc = ~{
        args: vec::filter_map(doc.args) {|doc|
            if option::is_some(doc.desc) {
                have_arg_docs = true;
                some(doc)
            } else {
                none
            }
        },
        return: {
            ty: if option::is_some(doc.return.desc) {
                doc.return.ty
            } else {
                none
            }
            with doc.return
        }
        with *doc
    };

    fold.ctxt.have_docs =
        doc.brief != none
        || doc.desc != none
        || have_arg_docs
        || doc.return.desc != none
        || doc.failure != none;
    ret doc;
}

#[test]
fn should_elide_undocumented_arguments() {
    let source = "#[doc = \"hey\"] fn a(b: int) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_empty(doc.topmod.fns[0].args);
}

#[test]
fn should_not_elide_fns_with_documented_arguments() {
    let source = "#[doc(args(a = \"b\"))] fn a(a: int) { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(*doc.topmod.fns);
}

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

#[test]
fn should_not_elide_fns_with_documented_failure_conditions() {
    let source = "#[doc(failure = \"yup\")] fn a() { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(*doc.topmod.fns);
}

fn fold_modlist(
    fold: fold::fold<ctxt>,
    list: doc::modlist
) -> doc::modlist {
    doc::modlist(vec::filter_map(*list) {|doc|
        let doc = fold.fold_mod(fold, doc);
        if fold.ctxt.have_docs {
            some(doc)
        } else {
            none
        }
    })
}

#[test]
fn should_elide_undocumented_mods() {
    let source = "mod a { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(*doc.topmod.mods);
}

#[test]
fn should_not_elide_undocument_mods_with_documented_mods() {
    let source = "mod a { #[doc = \"b\"] mod b { } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(*doc.topmod.mods);
}

#[test]
fn should_not_elide_undocument_mods_with_documented_fns() {
    let source = "mod a { #[doc = \"b\"] fn b() { } }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = attr_pass::mk_pass()(srv, doc);
    let doc = run(srv, doc);
    assert vec::is_not_empty(*doc.topmod.mods);
}

fn fold_fnlist(
    fold: fold::fold<ctxt>,
    list: doc::fnlist
) -> doc::fnlist {
    doc::fnlist(vec::filter_map(*list) {|doc|
        let doc = fold.fold_fn(fold, doc);
        if fold.ctxt.have_docs {
            some(doc)
        } else {
            none
        }
    })
}

#[test]
fn should_elide_undocumented_fns() {
    let source = "fn a() { }";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(*doc.topmod.fns);
}

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

fn fold_constlist(
    fold: fold::fold<ctxt>,
    list: doc::constlist
) -> doc::constlist {
    doc::constlist(vec::filter_map(*list) {|doc|
        let doc = fold.fold_const(fold, doc);
        if fold.ctxt.have_docs {
            some(doc)
        } else {
            none
        }
    })
}

#[test]
fn should_elide_undocumented_consts() {
    let source = "const a: bool = true;";
    let srv = astsrv::mk_srv_from_str(source);
    let doc = extract::from_srv(srv, "");
    let doc = run(srv, doc);
    assert vec::is_empty(*doc.topmod.consts);
}
<|endoftext|>


<commit_before>use alloc::arc::Arc;

use collections::string::{String, ToString};
use collections::vec::Vec;

use core::cell::UnsafeCell;
use core::ops::DerefMut;
use core::{mem, ptr};

use common::elf::Elf;
use common::memory;

use scheduler;
use scheduler::context::{CONTEXT_STACK_SIZE, CONTEXT_STACK_ADDR, context_switch,
context_userspace, Context, ContextMemory};

use schemes::Url;

/// Excecute an excecutable
pub fn execute(url: Url, mut args: Vec<String>) {
    unsafe {

        if let Some(current) = Context::current_mut() {

            let reenable = scheduler::start_no_ints();
            let cptr = current.deref_mut();
            scheduler::end_no_ints(reenable);

            Context::spawn("kexec ".to_string() + &url.string, box move || {
                if let Some(mut resource) = url.open() {
                    let mut vec: Vec<u8> = Vec::new();
                    resource.read_to_end(&mut vec);

                    let executable = Elf::from_data(vec.as_ptr() as usize);
                    let entry = executable.entry();
                    let mut memory = Vec::new();
                    for segment in executable.load_segment().iter() {
                        let virtual_address = segment.vaddr as usize;
                        let virtual_size = segment.mem_len as usize;
                        let physical_address = memory::alloc(virtual_size);

                        if physical_address > 0 {
                            // Copy progbits
                            ::memcpy(physical_address as *mut u8,
                                     (executable.data + segment.off as usize) as *const u8,
                                     segment.file_len as usize);
                            // Zero bss
                            ::memset((physical_address + segment.file_len as usize) as *mut u8,
                            0,
                            segment.mem_len as usize - segment.file_len as usize);

                            memory.push(ContextMemory {
                                physical_address: physical_address,
                                virtual_address: virtual_address,
                                virtual_size: virtual_size,
                                writeable: segment.flags & 2 == 2
                            });
                        }
                    }

                    if entry > 0 && ! memory.is_empty() {
                        args.insert(0, url.to_string());

                        let mut context_args: Vec<usize> = Vec::new();
                        context_args.push(0); // ENVP
                        context_args.push(0); // ARGV NULL
                        let mut argc = 0;
                        for i in 0..args.len() {
                            if let Some(arg) = args.get(args.len() - i - 1) {
                                context_args.push(arg.as_ptr() as usize);
                                argc += 1;
                            }
                        }
                        context_args.push(argc);

                        let reenable = scheduler::start_no_ints();

                        let context = cptr;

                        context.name = url.to_string();

                        context.sp = context.kernel_stack + CONTEXT_STACK_SIZE - 128;

                        context.stack = Some(ContextMemory {
                            physical_address: memory::alloc(CONTEXT_STACK_SIZE),
                            virtual_address: CONTEXT_STACK_ADDR,
                            virtual_size: CONTEXT_STACK_SIZE,
                            writeable: true
                        });

                        context.args = Arc::new(UnsafeCell::new(args));
                        context.cwd = Arc::new(UnsafeCell::new((*context.cwd.get()).clone()));
                        context.memory = Arc::new(UnsafeCell::new(memory));

                        let user_sp = if let Some(ref stack) = context.stack {
                            let mut sp = stack.physical_address + stack.virtual_size - 128;
                            for arg in context_args.iter() {
                                sp -= mem::size_of::<usize>();
                                ptr::write(sp as *mut usize, *arg);
                            }
                            sp - stack.physical_address + stack.virtual_address
                        } else {
                            0
                        };

                        context.push(0x20 | 3);
                        context.push(user_sp);
                        context.push(1 << 9);
                        context.push(0x18 | 3);
                        context.push(entry);
                        context.push(context_userspace as usize);

                        scheduler::end_no_ints(reenable);
                    } else {
                        debug!("{}: Invalid memory or entry\n", url.string);
                    }
                } else {
                    debug!("{}: Failed to open\n", url.string);
                }
            });

            loop {
                context_switch(false);
            }
        }
    }
}
<commit_msg>Fix a typo<commit_after>use alloc::arc::Arc;

use collections::string::{String, ToString};
use collections::vec::Vec;

use core::cell::UnsafeCell;
use core::ops::DerefMut;
use core::{mem, ptr};

use common::elf::Elf;
use common::memory;

use scheduler;
use scheduler::context::{CONTEXT_STACK_SIZE, CONTEXT_STACK_ADDR, context_switch,
context_userspace, Context, ContextMemory};

use schemes::Url;

/// Execute an executable
pub fn execute(url: Url, mut args: Vec<String>) {
    unsafe {

        if let Some(current) = Context::current_mut() {

            let reenable = scheduler::start_no_ints();
            let cptr = current.deref_mut();
            scheduler::end_no_ints(reenable);

            Context::spawn("kexec ".to_string() + &url.string, box move || {
                if let Some(mut resource) = url.open() {
                    let mut vec: Vec<u8> = Vec::new();
                    resource.read_to_end(&mut vec);

                    let executable = Elf::from_data(vec.as_ptr() as usize);
                    let entry = executable.entry();
                    let mut memory = Vec::new();
                    for segment in executable.load_segment().iter() {
                        let virtual_address = segment.vaddr as usize;
                        let virtual_size = segment.mem_len as usize;
                        let physical_address = memory::alloc(virtual_size);

                        if physical_address > 0 {
                            // Copy progbits
                            ::memcpy(physical_address as *mut u8,
                                     (executable.data + segment.off as usize) as *const u8,
                                     segment.file_len as usize);
                            // Zero bss
                            ::memset((physical_address + segment.file_len as usize) as *mut u8,
                            0,
                            segment.mem_len as usize - segment.file_len as usize);

                            memory.push(ContextMemory {
                                physical_address: physical_address,
                                virtual_address: virtual_address,
                                virtual_size: virtual_size,
                                writeable: segment.flags & 2 == 2
                            });
                        }
                    }

                    if entry > 0 && ! memory.is_empty() {
                        args.insert(0, url.to_string());

                        let mut context_args: Vec<usize> = Vec::new();
                        context_args.push(0); // ENVP
                        context_args.push(0); // ARGV NULL
                        let mut argc = 0;
                        for i in 0..args.len() {
                            if let Some(arg) = args.get(args.len() - i - 1) {
                                context_args.push(arg.as_ptr() as usize);
                                argc += 1;
                            }
                        }
                        context_args.push(argc);

                        let reenable = scheduler::start_no_ints();

                        let context = cptr;

                        context.name = url.to_string();

                        context.sp = context.kernel_stack + CONTEXT_STACK_SIZE - 128;

                        context.stack = Some(ContextMemory {
                            physical_address: memory::alloc(CONTEXT_STACK_SIZE),
                            virtual_address: CONTEXT_STACK_ADDR,
                            virtual_size: CONTEXT_STACK_SIZE,
                            writeable: true
                        });

                        context.args = Arc::new(UnsafeCell::new(args));
                        context.cwd = Arc::new(UnsafeCell::new((*context.cwd.get()).clone()));
                        context.memory = Arc::new(UnsafeCell::new(memory));

                        let user_sp = if let Some(ref stack) = context.stack {
                            let mut sp = stack.physical_address + stack.virtual_size - 128;
                            for arg in context_args.iter() {
                                sp -= mem::size_of::<usize>();
                                ptr::write(sp as *mut usize, *arg);
                            }
                            sp - stack.physical_address + stack.virtual_address
                        } else {
                            0
                        };

                        context.push(0x20 | 3);
                        context.push(user_sp);
                        context.push(1 << 9);
                        context.push(0x18 | 3);
                        context.push(entry);
                        context.push(context_userspace as usize);

                        scheduler::end_no_ints(reenable);
                    } else {
                        debug!("{}: Invalid memory or entry\n", url.string);
                    }
                } else {
                    debug!("{}: Failed to open\n", url.string);
                }
            });

            loop {
                context_switch(false);
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>[add] currency converter<commit_after>use std::collections::HashMap;

struct Converter {
    val: HashMap<String, f64>
}

impl Converter {
    fn init() -> Converter {
        Converter {
            val: HashMap::new()
        }
    }

    fn add_new<U: Into<String>, T: Into<f64>>(&mut self, fname: U, fvalue: T) {
        self.val.insert(fname.into(), fvalue.into());
    }

    fn convert<U: Into<String>, T: Into<f64>>(&self, fvalue: T, fname: U, tname: U) -> Option<f64> {
        let p1 = match self.val.get(&fname.into()) {
            Some(value) => value,
            None => return None
        };
        let p2 = match self.val.get(&tname.into()) {
            Some(value) => value,
            None => return None
        };
        Some(fvalue.into() * p1 / p2)
    }
}

fn main() {
    let mut converter = Converter::init();
    converter.add_new("rub", 1);
    converter.add_new("eur", 68);
    converter.add_new("usd", 59);
    converter.add_new("btc", 155763);
    let from_v = 391.30882352941177;
    let r = converter.convert(from_v, "eur", "usd").unwrap();
    println!("{} eur -> {} usd", from_v, r);
    let from_v = 110882.13559322034;
    let r = converter.convert(from_v, "usd", "btc").unwrap();
    println!("{} usd -> {} btc", from_v, r);
}<|endoftext|>


<commit_before><commit_msg>Still working on word2vec<commit_after><|endoftext|>


<commit_before><commit_msg>add a scary test case<commit_after>fn main() {
    // If we are careful, we can exploit data layout...
    let raw = unsafe {
        std::mem::transmute::<&[u8], [usize; 2]>(&[42])
    };
    let ptr = raw[0] + raw[1];
    let ptr = ptr as *const u8;
    // The pointer is one-past-the end, but we decrement it into bounds before using it
    assert_eq!(unsafe { *ptr.offset(-1) }, 42);
}
<|endoftext|>


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

/*!

The `Ord` and `Eq` comparison traits

This module contains the definition of both `Ord` and `Eq` which define
the common interfaces for doing comparison. Both are language items
that the compiler uses to implement the comparison operators. Rust code
may implement `Ord` to overload the `<`, `<=`, `>`, and `>=` operators,
and `Eq` to overload the `==` and `!=` operators.

*/

#[allow(missing_doc)];

/**
* Trait for values that can be compared for equality and inequality.
*
* This trait allows partial equality, where types can be unordered instead of strictly equal or
* unequal. For example, with the built-in floating-point types `a == b` and `a != b` will both
* evaluate to false if either `a` or `b` is NaN (cf. IEEE 754-2008 section 5.11).
*
* Eq only requires the `eq` method to be implemented; `ne` is its negation by default.
*
* Eventually, this will be implemented by default for types that implement `TotalEq`.
*/
#[lang="eq"]
pub trait Eq {
    fn eq(&self, other: &Self) -> bool;

    #[inline]
    fn ne(&self, other: &Self) -> bool { !self.eq(other) }
}

/// Trait for equality comparisons where `a == b` and `a != b` are strict inverses.
pub trait TotalEq: Eq {
    /// This method must return the same value as `eq`. It exists to prevent
    /// deriving `TotalEq` from fields not implementing the `TotalEq` trait.
    fn equals(&self, other: &Self) -> bool {
        self.eq(other)
    }
}

macro_rules! totaleq_impl(
    ($t:ty) => {
        impl TotalEq for $t {
            #[inline]
            fn equals(&self, other: &$t) -> bool { *self == *other }
        }
    }
)

totaleq_impl!(bool)

totaleq_impl!(u8)
totaleq_impl!(u16)
totaleq_impl!(u32)
totaleq_impl!(u64)

totaleq_impl!(i8)
totaleq_impl!(i16)
totaleq_impl!(i32)
totaleq_impl!(i64)

totaleq_impl!(int)
totaleq_impl!(uint)

totaleq_impl!(char)

#[deriving(Clone, Eq, Show)]
pub enum Ordering { Less = -1, Equal = 0, Greater = 1 }

/// Trait for types that form a total order
pub trait TotalOrd: TotalEq + Ord {
    fn cmp(&self, other: &Self) -> Ordering;
}

impl TotalEq for Ordering {
    #[inline]
    fn equals(&self, other: &Ordering) -> bool {
        *self == *other
    }
}
impl TotalOrd for Ordering {
    #[inline]
    fn cmp(&self, other: &Ordering) -> Ordering {
        (*self as int).cmp(&(*other as int))
    }
}

impl Ord for Ordering {
    #[inline]
    fn lt(&self, other: &Ordering) -> bool { (*self as int) < (*other as int) }
}

macro_rules! totalord_impl(
    ($t:ty) => {
        impl TotalOrd for $t {
            #[inline]
            fn cmp(&self, other: &$t) -> Ordering {
                if *self < *other { Less }
                else if *self > *other { Greater }
                else { Equal }
            }
        }
    }
)

totalord_impl!(u8)
totalord_impl!(u16)
totalord_impl!(u32)
totalord_impl!(u64)

totalord_impl!(i8)
totalord_impl!(i16)
totalord_impl!(i32)
totalord_impl!(i64)

totalord_impl!(int)
totalord_impl!(uint)

totalord_impl!(char)

/// Compares (a1, b1) against (a2, b2), where the a values are more significant.
pub fn cmp2<A:TotalOrd,B:TotalOrd>(
    a1: &A, b1: &B,
    a2: &A, b2: &B) -> Ordering
{
    match a1.cmp(a2) {
        Less => Less,
        Greater => Greater,
        Equal => b1.cmp(b2)
    }
}

/**
Return `o1` if it is not `Equal`, otherwise `o2`. Simulates the
lexical ordering on a type `(int, int)`.
*/
#[inline]
pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering {
    match o1 {
        Equal => o2,
        _ => o1
    }
}

/**
* Trait for values that can be compared for a sort-order.
*
* Ord only requires implementation of the `lt` method,
* with the others generated from default implementations.
*
* However it remains possible to implement the others separately,
* for compatibility with floating-point NaN semantics
* (cf. IEEE 754-2008 section 5.11).
*/
#[lang="ord"]
pub trait Ord: Eq {
    fn lt(&self, other: &Self) -> bool;
    #[inline]
    fn le(&self, other: &Self) -> bool { !other.lt(self) }
    #[inline]
    fn gt(&self, other: &Self) -> bool {  other.lt(self) }
    #[inline]
    fn ge(&self, other: &Self) -> bool { !self.lt(other) }
}

/// The equivalence relation. Two values may be equivalent even if they are
/// of different types. The most common use case for this relation is
/// container types; e.g. it is often desirable to be able to use `&str`
/// values to look up entries in a container with `~str` keys.
pub trait Equiv<T> {
    fn equiv(&self, other: &T) -> bool;
}

#[inline]
pub fn min<T: TotalOrd>(v1: T, v2: T) -> T {
    if v1 < v2 { v1 } else { v2 }
}

#[inline]
pub fn max<T: TotalOrd>(v1: T, v2: T) -> T {
    if v1 > v2 { v1 } else { v2 }
}

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

    #[test]
    fn test_int_totalord() {
        assert_eq!(5.cmp(&10), Less);
        assert_eq!(10.cmp(&5), Greater);
        assert_eq!(5.cmp(&5), Equal);
        assert_eq!((-5).cmp(&12), Less);
        assert_eq!(12.cmp(-5), Greater);
    }

    #[test]
    fn test_cmp2() {
        assert_eq!(cmp2(1, 2, 3, 4), Less);
        assert_eq!(cmp2(3, 2, 3, 4), Less);
        assert_eq!(cmp2(5, 2, 3, 4), Greater);
        assert_eq!(cmp2(5, 5, 5, 4), Greater);
    }

    #[test]
    fn test_int_totaleq() {
        assert!(5.equals(&5));
        assert!(!2.equals(&17));
    }

    #[test]
    fn test_ordering_order() {
        assert!(Less < Equal);
        assert_eq!(Greater.cmp(&Less), Greater);
    }

    #[test]
    fn test_lexical_ordering() {
        fn t(o1: Ordering, o2: Ordering, e: Ordering) {
            assert_eq!(lexical_ordering(o1, o2), e);
        }

        let xs = [Less, Equal, Greater];
        for &o in xs.iter() {
            t(Less, o, Less);
            t(Equal, o, o);
            t(Greater, o, Greater);
         }
    }
}
<commit_msg>Remove std::cmp::cmp2.<commit_after>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/*!

The `Ord` and `Eq` comparison traits

This module contains the definition of both `Ord` and `Eq` which define
the common interfaces for doing comparison. Both are language items
that the compiler uses to implement the comparison operators. Rust code
may implement `Ord` to overload the `<`, `<=`, `>`, and `>=` operators,
and `Eq` to overload the `==` and `!=` operators.

*/

#[allow(missing_doc)];

/**
* Trait for values that can be compared for equality and inequality.
*
* This trait allows partial equality, where types can be unordered instead of strictly equal or
* unequal. For example, with the built-in floating-point types `a == b` and `a != b` will both
* evaluate to false if either `a` or `b` is NaN (cf. IEEE 754-2008 section 5.11).
*
* Eq only requires the `eq` method to be implemented; `ne` is its negation by default.
*
* Eventually, this will be implemented by default for types that implement `TotalEq`.
*/
#[lang="eq"]
pub trait Eq {
    fn eq(&self, other: &Self) -> bool;

    #[inline]
    fn ne(&self, other: &Self) -> bool { !self.eq(other) }
}

/// Trait for equality comparisons where `a == b` and `a != b` are strict inverses.
pub trait TotalEq: Eq {
    /// This method must return the same value as `eq`. It exists to prevent
    /// deriving `TotalEq` from fields not implementing the `TotalEq` trait.
    fn equals(&self, other: &Self) -> bool {
        self.eq(other)
    }
}

macro_rules! totaleq_impl(
    ($t:ty) => {
        impl TotalEq for $t {
            #[inline]
            fn equals(&self, other: &$t) -> bool { *self == *other }
        }
    }
)

totaleq_impl!(bool)

totaleq_impl!(u8)
totaleq_impl!(u16)
totaleq_impl!(u32)
totaleq_impl!(u64)

totaleq_impl!(i8)
totaleq_impl!(i16)
totaleq_impl!(i32)
totaleq_impl!(i64)

totaleq_impl!(int)
totaleq_impl!(uint)

totaleq_impl!(char)

#[deriving(Clone, Eq, Show)]
pub enum Ordering { Less = -1, Equal = 0, Greater = 1 }

/// Trait for types that form a total order
pub trait TotalOrd: TotalEq + Ord {
    fn cmp(&self, other: &Self) -> Ordering;
}

impl TotalEq for Ordering {
    #[inline]
    fn equals(&self, other: &Ordering) -> bool {
        *self == *other
    }
}
impl TotalOrd for Ordering {
    #[inline]
    fn cmp(&self, other: &Ordering) -> Ordering {
        (*self as int).cmp(&(*other as int))
    }
}

impl Ord for Ordering {
    #[inline]
    fn lt(&self, other: &Ordering) -> bool { (*self as int) < (*other as int) }
}

macro_rules! totalord_impl(
    ($t:ty) => {
        impl TotalOrd for $t {
            #[inline]
            fn cmp(&self, other: &$t) -> Ordering {
                if *self < *other { Less }
                else if *self > *other { Greater }
                else { Equal }
            }
        }
    }
)

totalord_impl!(u8)
totalord_impl!(u16)
totalord_impl!(u32)
totalord_impl!(u64)

totalord_impl!(i8)
totalord_impl!(i16)
totalord_impl!(i32)
totalord_impl!(i64)

totalord_impl!(int)
totalord_impl!(uint)

totalord_impl!(char)

/**
Return `o1` if it is not `Equal`, otherwise `o2`. Simulates the
lexical ordering on a type `(int, int)`.
*/
#[inline]
pub fn lexical_ordering(o1: Ordering, o2: Ordering) -> Ordering {
    match o1 {
        Equal => o2,
        _ => o1
    }
}

/**
* Trait for values that can be compared for a sort-order.
*
* Ord only requires implementation of the `lt` method,
* with the others generated from default implementations.
*
* However it remains possible to implement the others separately,
* for compatibility with floating-point NaN semantics
* (cf. IEEE 754-2008 section 5.11).
*/
#[lang="ord"]
pub trait Ord: Eq {
    fn lt(&self, other: &Self) -> bool;
    #[inline]
    fn le(&self, other: &Self) -> bool { !other.lt(self) }
    #[inline]
    fn gt(&self, other: &Self) -> bool {  other.lt(self) }
    #[inline]
    fn ge(&self, other: &Self) -> bool { !self.lt(other) }
}

/// The equivalence relation. Two values may be equivalent even if they are
/// of different types. The most common use case for this relation is
/// container types; e.g. it is often desirable to be able to use `&str`
/// values to look up entries in a container with `~str` keys.
pub trait Equiv<T> {
    fn equiv(&self, other: &T) -> bool;
}

#[inline]
pub fn min<T: TotalOrd>(v1: T, v2: T) -> T {
    if v1 < v2 { v1 } else { v2 }
}

#[inline]
pub fn max<T: TotalOrd>(v1: T, v2: T) -> T {
    if v1 > v2 { v1 } else { v2 }
}

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

    #[test]
    fn test_int_totalord() {
        assert_eq!(5.cmp(&10), Less);
        assert_eq!(10.cmp(&5), Greater);
        assert_eq!(5.cmp(&5), Equal);
        assert_eq!((-5).cmp(&12), Less);
        assert_eq!(12.cmp(-5), Greater);
    }

    #[test]
    fn test_int_totaleq() {
        assert!(5.equals(&5));
        assert!(!2.equals(&17));
    }

    #[test]
    fn test_ordering_order() {
        assert!(Less < Equal);
        assert_eq!(Greater.cmp(&Less), Greater);
    }

    #[test]
    fn test_lexical_ordering() {
        fn t(o1: Ordering, o2: Ordering, e: Ordering) {
            assert_eq!(lexical_ordering(o1, o2), e);
        }

        let xs = [Less, Equal, Greater];
        for &o in xs.iter() {
            t(Less, o, Less);
            t(Equal, o, o);
            t(Greater, o, Greater);
         }
    }
}
<|endoftext|>


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

#![crate_type = "dylib"]

#![doc(html_root_url = "http://ogeon.github.io/rustful/doc/")]

#![feature(plugin_registrar, quote)]

#![allow(unstable)]

//!This crate provides some helpful macros for rustful, including `insert_routes!` and `content_type!`.
//!
//!#`insert_routes!`
//!The `insert_routes!` macro generates routes from the provided handlers and routing tree and
//!adds them to the provided router. The router is then returned.
//!
//!This can be useful to lower the risk of typing errors, among other things.
//!
//!##Example 1
//!
//!```rust ignore
//!#![feature(plugin)]
//!#[plugin]
//!#[no_link]
//!extern crate rustful_macros;
//!
//!extern crate rustful;
//!
//!...
//!
//!let router = insert_routes!{
//!    TreeRouter::new(): {
//!        "/about" => Get: about_us,
//!        "/user/:user" => Get: show_user,
//!        "/product/:name" => Get: show_product,
//!        "/*" => Get: show_error,
//!        "/" => Get: show_welcome
//!    }
//!};
//!```
//!
//!##Example 2
//!
//!```rust ignore
//!#![feature(plugin)]
//!#[plugin]
//!#[no_link]
//!extern crate rustful_macros;
//!
//!extern crate rustful;
//!
//!...
//!
//!let mut router = TreeRouter::new();
//!insert_routes!{
//!    &mut router: {
//!        "/" => Get: show_home,
//!        "home" => Get: show_home,
//!        "user/:username" => {Get: show_user, Post: save_user},
//!        "product" => {
//!            Get: show_all_products,
//!
//!            "json" => Get: send_all_product_data
//!            ":id" => {
//!                Get: show_product,
//!                Post | Delete: edit_product,
//!
//!                "json" => Get: send_product_data
//!            }
//!        }
//!    }
//!};
//!```

extern crate syntax;
extern crate rustc;

use std::path::BytesContainer;

use syntax::{ast, codemap};
use syntax::ext::base::{
    ExtCtxt, MacResult, MacExpr,
    NormalTT, TTMacroExpander
};
use syntax::ext::build::AstBuilder;
use syntax::ext::quote::rt::ExtParseUtils;
use syntax::parse;
use syntax::parse::token;
use syntax::parse::parser;
use syntax::parse::parser::Parser;
use syntax::ptr::P;
//use syntax::print::pprust;

use rustc::plugin::Registry;

#[plugin_registrar]
#[doc(hidden)]
pub fn macro_registrar(reg: &mut Registry) {
    let expander = Box::new(expand_routes) as Box<TTMacroExpander>;
    reg.register_syntax_extension(token::intern("insert_routes"), NormalTT(expander, None));
}

fn expand_routes<'cx>(cx: &'cx mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult + 'cx> {
    let insert_method = cx.ident_of("insert");
    let router_ident = cx.ident_of("router");
    let router_var = cx.expr_ident(sp, router_ident);
    let router_trait_path = cx.path_global(sp, vec![cx.ident_of("rustful"), cx.ident_of("Router")]);
    let router_trait_use = cx.view_use_simple(sp, ast::Inherited, router_trait_path);

    let mut parser = parse::new_parser_from_tts(
        cx.parse_sess(), cx.cfg(), tts.to_vec()
    );

    let mut calls = vec![cx.stmt_let(sp, true, router_ident, parser.parse_expr())];
    parser.expect(&token::Colon);

    for (path, method, handler) in parse_routes(cx, &mut parser).into_iter() {
        let path_expr = cx.parse_expr(format!("\"{}\"", path));
        let method_expr = cx.expr_path(method);
        calls.push(cx.stmt_expr(cx.expr_method_call(sp, router_var.clone(), insert_method, vec![method_expr, path_expr, handler])));
    }

    let block = cx.expr_block(cx.block_all(sp, vec![router_trait_use], calls, Some(router_var)));

    MacExpr::new(block)
}

fn parse_routes(cx: &mut ExtCtxt, parser: &mut Parser) -> Vec<(String, ast::Path, P<ast::Expr>)> {
    parse_subroutes("", cx, parser)
}

fn parse_subroutes(base: &str, cx: &mut ExtCtxt, parser: &mut Parser) -> Vec<(String, ast::Path, P<ast::Expr>)> {
    let mut routes = Vec::new();

    parser.eat(&token::OpenDelim(token::Brace));

    while !parser.eat(&token::Eof) {
        match parser.parse_optional_str() {
            Some((ref s, _, _)) => {
                if !parser.eat(&token::FatArrow) {
                    parser.expect(&token::FatArrow);
                    break;
                }

                let mut new_base = base.to_string();
                match s.container_as_str() {
                    Some(s) => {
                        new_base.push_str(s.trim_matches('/'));
                        new_base.push_str("/");
                    },
                    None => cx.span_err(parser.span, "invalid path")
                }

                if parser.eat(&token::Eof) {
                    cx.span_err(parser.span, "unexpected end of routing tree");
                }

                if parser.eat(&token::OpenDelim(token::Brace)) {
                    let subroutes = parse_subroutes(new_base.as_slice(), cx, parser);
                    routes.push_all(subroutes.as_slice());

                    if parser.eat(&token::CloseDelim(token::Brace)) {
                        if !parser.eat(&token::Comma) {
                            break;
                        }
                    } else {
                        parser.expect_one_of(&[token::Comma, token::CloseDelim(token::Brace)], &[]);
                    }
                } else {
                    for (method, handler) in parse_handler(parser).into_iter() {
                        routes.push((new_base.clone(), method, handler))
                    }

                    if !parser.eat(&token::Comma) {
                        break;
                    }
                }
            },
            None => {
                for (method, handler) in parse_handler(parser).into_iter() {
                    routes.push((base.to_string(), method, handler))
                }

                if !parser.eat(&token::Comma) {
                    break;
                }
            }
        }
    }

    routes
}

fn parse_handler(parser: &mut Parser) -> Vec<(ast::Path, P<ast::Expr>)> {
    let mut methods = Vec::new();

    loop {
        methods.push(parser.parse_path(parser::NoTypesAllowed));

        if parser.eat(&token::Colon) {
            break;
        }

        if !parser.eat(&token::BinOp(token::Or)) {
            parser.expect_one_of(&[token::Colon, token::BinOp(token::Or)], &[]);
        }
    }

    let handler = parser.parse_expr();

    methods.into_iter().map(|m| (m, handler.clone())).collect()
}

/**
A macro for assigning content types.

It takes a main type, a sub type and a parameter list. Instead of this:

```
response.headers.content_type = Some(MediaType {
    type_: String::from_str("text"),
    subtype: String::from_str("html"),
    parameters: vec!((String::from_str("charset"), String::from_str("UTF-8")))
});
```

it can be written like this:

```
response.headers.content_type = content_type!("text", "html", "charset": "UTF-8");
```

The `"charset": "UTF-8"` part defines the parameter list for the content type.
It may contain more than one parameter, or be omitted:

```
response.headers.content_type = content_type!("application", "octet-stream", "type": "image/gif", "padding": "4");
```

```
response.headers.content_type = content_type!("image", "png");
```
**/
#[macro_export]
macro_rules! content_type {
    ($main_type:expr, $sub_type:expr) => ({
        ::rustful::mime::Mime (
            std::str::FromStr::from_str($main_type).unwrap(),
            std::str::FromStr::from_str($sub_type).unwrap(),
            Vec::new()
        )
    });

    ($main_type:expr, $sub_type:expr, $(($param:expr, $value:expr)),+) => ({
        ::rustful::mime::Mime (
            std::str::FromStr::from_str($main_type).unwrap(),
            std::str::FromStr::from_str($sub_type).unwrap(),
            vec!( $( (std::str::FromStr::from_str($param).unwrap(), std::str::FromStr::from_str($value).unwrap()) ),+ )
        )
    });
}

/**
A macro for callig `send` in response and aborting the handle function if it fails.

This macro will print an error to `stdout`.
**/
#[macro_export]
macro_rules! try_send {
    ($writer:expr, $content:expr) => (
        match $writer.send($content) {
            Ok(v) => v,
            Err(::rustful::ResponseError::IoError(e)) => {
                println!("IO error: {}", e);
                return;
            },
            Err(::rustful::ResponseError::PluginError(e)) => {
                println!("plugin error: {}", e);
                return;
            }
        }
    );

    ($writer:expr, $content:expr, $what:expr) => (
        match $writer.send($content) {
            Ok(v) => v,
            Err(::rustful::ResponseError::IoError(e)) => {
                println!("IO error while {}: {}", $what, e);
                return;
            },
            Err(::rustful::ResponseError::PluginError(e)) => {
                println!("plugin error while {}: {}", $what, e);
                return;
            }
        }
    )
}<commit_msg>Update for libsyntax changes<commit_after>#![crate_name = "rustful_macros"]

#![crate_type = "dylib"]

#![doc(html_root_url = "http://ogeon.github.io/rustful/doc/")]

#![feature(plugin_registrar, quote)]

#![allow(unstable)]

//!This crate provides some helpful macros for rustful, including `insert_routes!` and `content_type!`.
//!
//!#`insert_routes!`
//!The `insert_routes!` macro generates routes from the provided handlers and routing tree and
//!adds them to the provided router. The router is then returned.
//!
//!This can be useful to lower the risk of typing errors, among other things.
//!
//!##Example 1
//!
//!```rust ignore
//!#![feature(plugin)]
//!#[plugin]
//!#[no_link]
//!extern crate rustful_macros;
//!
//!extern crate rustful;
//!
//!...
//!
//!let router = insert_routes!{
//!    TreeRouter::new(): {
//!        "/about" => Get: about_us,
//!        "/user/:user" => Get: show_user,
//!        "/product/:name" => Get: show_product,
//!        "/*" => Get: show_error,
//!        "/" => Get: show_welcome
//!    }
//!};
//!```
//!
//!##Example 2
//!
//!```rust ignore
//!#![feature(plugin)]
//!#[plugin]
//!#[no_link]
//!extern crate rustful_macros;
//!
//!extern crate rustful;
//!
//!...
//!
//!let mut router = TreeRouter::new();
//!insert_routes!{
//!    &mut router: {
//!        "/" => Get: show_home,
//!        "home" => Get: show_home,
//!        "user/:username" => {Get: show_user, Post: save_user},
//!        "product" => {
//!            Get: show_all_products,
//!
//!            "json" => Get: send_all_product_data
//!            ":id" => {
//!                Get: show_product,
//!                Post | Delete: edit_product,
//!
//!                "json" => Get: send_product_data
//!            }
//!        }
//!    }
//!};
//!```

extern crate syntax;
extern crate rustc;

use std::path::BytesContainer;

use syntax::{ast, codemap};
use syntax::ext::base::{
    ExtCtxt, MacResult, MacExpr,
    NormalTT, TTMacroExpander
};
use syntax::ext::build::AstBuilder;
use syntax::ext::quote::rt::ExtParseUtils;
use syntax::parse;
use syntax::parse::token;
use syntax::parse::parser;
use syntax::parse::parser::Parser;
use syntax::ptr::P;
//use syntax::print::pprust;

use rustc::plugin::Registry;

#[plugin_registrar]
#[doc(hidden)]
pub fn macro_registrar(reg: &mut Registry) {
    let expander = Box::new(expand_routes) as Box<TTMacroExpander>;
    reg.register_syntax_extension(token::intern("insert_routes"), NormalTT(expander, None));
}

fn expand_routes<'cx>(cx: &'cx mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> Box<MacResult + 'cx> {
    let insert_method = cx.ident_of("insert");
    let router_ident = cx.ident_of("router");
    let router_var = cx.expr_ident(sp, router_ident);
    let router_trait_path = cx.path_global(sp, vec![cx.ident_of("rustful"), cx.ident_of("Router")]);
    let router_trait_use = cx.item_use_simple(sp, ast::Inherited, router_trait_path);

    let mut parser = parse::new_parser_from_tts(
        cx.parse_sess(), cx.cfg(), tts.to_vec()
    );

    let mut calls = vec![cx.stmt_item(sp, router_trait_use), cx.stmt_let(sp, true, router_ident, parser.parse_expr())];
    parser.expect(&token::Colon);

    for (path, method, handler) in parse_routes(cx, &mut parser).into_iter() {
        let path_expr = cx.parse_expr(format!("\"{}\"", path));
        let method_expr = cx.expr_path(method);
        calls.push(cx.stmt_expr(cx.expr_method_call(sp, router_var.clone(), insert_method, vec![method_expr, path_expr, handler])));
    }

    let block = cx.expr_block(cx.block_all(sp, calls, Some(router_var)));

    MacExpr::new(block)
}

fn parse_routes(cx: &mut ExtCtxt, parser: &mut Parser) -> Vec<(String, ast::Path, P<ast::Expr>)> {
    parse_subroutes("", cx, parser)
}

fn parse_subroutes(base: &str, cx: &mut ExtCtxt, parser: &mut Parser) -> Vec<(String, ast::Path, P<ast::Expr>)> {
    let mut routes = Vec::new();

    parser.eat(&token::OpenDelim(token::Brace));

    while !parser.eat(&token::Eof) {
        match parser.parse_optional_str() {
            Some((ref s, _, _)) => {
                if !parser.eat(&token::FatArrow) {
                    parser.expect(&token::FatArrow);
                    break;
                }

                let mut new_base = base.to_string();
                match s.container_as_str() {
                    Some(s) => {
                        new_base.push_str(s.trim_matches('/'));
                        new_base.push_str("/");
                    },
                    None => cx.span_err(parser.span, "invalid path")
                }

                if parser.eat(&token::Eof) {
                    cx.span_err(parser.span, "unexpected end of routing tree");
                }

                if parser.eat(&token::OpenDelim(token::Brace)) {
                    let subroutes = parse_subroutes(new_base.as_slice(), cx, parser);
                    routes.push_all(subroutes.as_slice());

                    if parser.eat(&token::CloseDelim(token::Brace)) {
                        if !parser.eat(&token::Comma) {
                            break;
                        }
                    } else {
                        parser.expect_one_of(&[token::Comma, token::CloseDelim(token::Brace)], &[]);
                    }
                } else {
                    for (method, handler) in parse_handler(parser).into_iter() {
                        routes.push((new_base.clone(), method, handler))
                    }

                    if !parser.eat(&token::Comma) {
                        break;
                    }
                }
            },
            None => {
                for (method, handler) in parse_handler(parser).into_iter() {
                    routes.push((base.to_string(), method, handler))
                }

                if !parser.eat(&token::Comma) {
                    break;
                }
            }
        }
    }

    routes
}

fn parse_handler(parser: &mut Parser) -> Vec<(ast::Path, P<ast::Expr>)> {
    let mut methods = Vec::new();

    loop {
        methods.push(parser.parse_path(parser::NoTypesAllowed));

        if parser.eat(&token::Colon) {
            break;
        }

        if !parser.eat(&token::BinOp(token::Or)) {
            parser.expect_one_of(&[token::Colon, token::BinOp(token::Or)], &[]);
        }
    }

    let handler = parser.parse_expr();

    methods.into_iter().map(|m| (m, handler.clone())).collect()
}

/**
A macro for assigning content types.

It takes a main type, a sub type and a parameter list. Instead of this:

```
response.headers.content_type = Some(MediaType {
    type_: String::from_str("text"),
    subtype: String::from_str("html"),
    parameters: vec!((String::from_str("charset"), String::from_str("UTF-8")))
});
```

it can be written like this:

```
response.headers.content_type = content_type!("text", "html", "charset": "UTF-8");
```

The `"charset": "UTF-8"` part defines the parameter list for the content type.
It may contain more than one parameter, or be omitted:

```
response.headers.content_type = content_type!("application", "octet-stream", "type": "image/gif", "padding": "4");
```

```
response.headers.content_type = content_type!("image", "png");
```
**/
#[macro_export]
macro_rules! content_type {
    ($main_type:expr, $sub_type:expr) => ({
        ::rustful::mime::Mime (
            std::str::FromStr::from_str($main_type).unwrap(),
            std::str::FromStr::from_str($sub_type).unwrap(),
            Vec::new()
        )
    });

    ($main_type:expr, $sub_type:expr, $(($param:expr, $value:expr)),+) => ({
        ::rustful::mime::Mime (
            std::str::FromStr::from_str($main_type).unwrap(),
            std::str::FromStr::from_str($sub_type).unwrap(),
            vec!( $( (std::str::FromStr::from_str($param).unwrap(), std::str::FromStr::from_str($value).unwrap()) ),+ )
        )
    });
}

/**
A macro for callig `send` in response and aborting the handle function if it fails.

This macro will print an error to `stdout`.
**/
#[macro_export]
macro_rules! try_send {
    ($writer:expr, $content:expr) => (
        match $writer.send($content) {
            Ok(v) => v,
            Err(::rustful::ResponseError::IoError(e)) => {
                println!("IO error: {}", e);
                return;
            },
            Err(::rustful::ResponseError::PluginError(e)) => {
                println!("plugin error: {}", e);
                return;
            }
        }
    );

    ($writer:expr, $content:expr, $what:expr) => (
        match $writer.send($content) {
            Ok(v) => v,
            Err(::rustful::ResponseError::IoError(e)) => {
                println!("IO error while {}: {}", $what, e);
                return;
            },
            Err(::rustful::ResponseError::PluginError(e)) => {
                println!("plugin error while {}: {}", $what, e);
                return;
            }
        }
    )
}<|endoftext|>


<commit_before><commit_msg>add basic slice functions<commit_after><|endoftext|>


<commit_before><commit_msg>ups. add evaluate_expression.rs<commit_after>//! The `evaluate_expressions` module...

use backend::zcode::zfile::{ZOP, Operand, Variable, Constant, LargeConstant};
use frontend::ast::{ASTNode};
use frontend::codegen;
use frontend::codegen::{CodeGenManager};
use frontend::lexer::Token::{TokNumOp, TokCompOp, TokLogOp, TokInt, TokBoolean, TokVariable, TokFunction};

pub fn evaluate_expression<'a>(node: &'a ASTNode, code: &mut Vec<ZOP>, mut manager: &mut CodeGenManager<'a>) -> Operand {
    let mut temp_ids = CodeGenManager::new_temp_var_vec();
    evaluate_expression_internal(node, code, &mut temp_ids, manager)
}

/// Evaluates an expression node to zCode.
fn evaluate_expression_internal<'a>(node: &'a ASTNode, code: &mut Vec<ZOP>,
        temp_ids: &mut Vec<u8>, mut manager: &mut CodeGenManager<'a>) -> Operand {
    let n = node.as_default();

    match n.category {
        TokNumOp { ref op_name, .. } => {
            if n.childs.len() != 2 {
                panic!("Numeric operators need two arguments!")
            }
            let eval0 = evaluate_expression_internal(&n.childs[0], code, temp_ids, manager);
            let eval1 = evaluate_expression_internal(&n.childs[1], code, temp_ids, manager);
            eval_num_op(&eval0, &eval1, &**op_name, code, temp_ids)
        },
        TokCompOp { ref op_name, .. } => {
            if n.childs.len() != 2 {
                panic!("Numeric operators need two arguments!")
            }
            let eval0 = evaluate_expression_internal(&n.childs[0], code, temp_ids, manager);
            let eval1 = evaluate_expression_internal(&n.childs[1], code, temp_ids, manager);
            eval_comp_op(&eval0, &eval1, &**op_name, code, temp_ids, manager)
        },
        TokLogOp { ref op_name, .. } => {
            let eval0 = evaluate_expression_internal(&n.childs[0], code, temp_ids, manager);

            match &**op_name {
                "and" | "or" => {
                    let eval1 = evaluate_expression_internal(&n.childs[1], code, temp_ids, manager);
                    eval_and_or(&eval0, &eval1, &**op_name, code, temp_ids)
                },
                "not" => {
                    eval_not(&eval0, code, temp_ids, manager)
                },
                _ => panic!("unhandled op")
            }
        }
        TokInt { ref value, .. } => {
            Operand::new_large_const(*value as i16)
        },
        TokBoolean { ref value, .. } => {
            boolstr_to_const(&**value)
        },
        TokVariable { ref name, .. } => {
            Operand::Var(manager.symbol_table.get_symbol_id(name))
        },
        TokFunction { ref name, .. } => {
            match &**name {
                "random" => {
                    let args = &node.as_default().childs;
                    if args.len() != 2 {
                        panic!("Function random only supports 2 args");
                    }

                    if args[0].as_default().childs.len() != 1 || args[1].as_default().childs.len() != 1 {
                        panic!("Unsupported Expression");
                    }

                    let from = &args[0].as_default().childs[0];
                    let to = &args[1].as_default().childs[0];

                    let from_value = evaluate_expression_internal(from, code, temp_ids, manager);
                    let to_value = evaluate_expression_internal(to, code, temp_ids, manager);
                    codegen::function_random(&from_value, &to_value, code, temp_ids)
                },
                _ => { panic!("Unsupported function: {}", name)}
            }
        },
        _ => panic!("unhandled token {:?}", n.category)
    }
}

fn eval_num_op<'a>(eval0: &Operand, eval1: &Operand, op_name: &str, code: &mut Vec<ZOP>, temp_ids: &mut Vec<u8>) -> Operand {
    if count_constants(eval0, eval1) == 2 {
        return direct_eval_num_op(eval0, eval1, op_name);
    }
    let save_var = determine_save_var(eval0, eval1, temp_ids);
    match op_name {
        "+" => {
            code.push(ZOP::Add{operand1: eval0.clone(), operand2: eval1.clone(), save_variable: save_var.clone()});
        },
        "-" => {
            code.push(ZOP::Sub{operand1: eval0.clone(), operand2: eval1.clone(), save_variable: save_var.clone()});
        },
        "*" => {

        },
        "/" => {

        },
        "%" => {

        },
        _ => panic!("unhandled op")
    };

    free_var_if_both_temp(eval0, eval1, temp_ids);

    Operand::Var(save_var)
}

fn direct_eval_num_op(eval0: &Operand, eval1: &Operand, op_name: &str) -> Operand {
    let mut out_large = false;
    let val0 = eval0.const_value();
    let val1 = eval1.const_value();
    match eval0 { &Operand::LargeConst(_) => {out_large = true; }, _ => {} };
    match eval1 { &Operand::LargeConst(_) => {out_large = true; }, _ => {} };
    let result = match op_name {
        "+" => {
            val0 + val1
        },
        "-" => {
            val0 - val1
        },
        "*" => {
            val0 * val1
        },
        "/" => {
            val0 / val1
        },
        "%" => {
            val0 % val1
        },
        _ => panic!("unhandled op")
    };
    if out_large {
        Operand::LargeConst(LargeConstant { value: result })
    } else {
        Operand::Const(Constant { value: result as u8 })
    }
}

fn eval_comp_op<'a>(eval0: &Operand, eval1: &Operand, op_name: &str, code: &mut Vec<ZOP>,
        temp_ids: &mut Vec<u8>, mut manager: &mut CodeGenManager<'a>) -> Operand {
    if count_constants(eval0, eval1) == 2 {
        return direct_eval_comp_op(eval0, eval1, op_name);
    }
    let save_var = Variable { id: temp_ids.pop().unwrap() };
    let label = format!("expr_{}", manager.ids_expr.start_next());
    let const_true = Operand::new_const(1);
    let const_false = Operand::new_const(0);
    match op_name {
        "is" | "==" | "eq" => {
            code.push(ZOP::StoreVariable{ variable: save_var.clone(), value: const_true});
            code.push(ZOP::JE{operand1: eval0.clone(), operand2: eval1.clone(), jump_to_label: label.to_string()});
            code.push(ZOP::StoreVariable{ variable: save_var.clone(), value: const_false});
        },
        "neq" => {
            code.push(ZOP::StoreVariable{ variable: save_var.clone(), value: const_false});
            code.push(ZOP::JE{operand1: eval0.clone(), operand2: eval1.clone(), jump_to_label: label.to_string()});
            code.push(ZOP::StoreVariable{ variable: save_var.clone(), value: const_true});
        },
        "<" | "lt" =>  {
            code.push(ZOP::StoreVariable{ variable: save_var.clone(), value: const_true });
            code.push(ZOP::JL{operand1: eval0.clone(), operand2: eval1.clone(), jump_to_label: label.to_string()});
            code.push(ZOP::StoreVariable{ variable: save_var.clone(), value: const_false});
        },
        "<=" | "lte" => {
            code.push(ZOP::StoreVariable{ variable: save_var.clone(), value: const_false});
            code.push(ZOP::JG{operand1: eval0.clone(), operand2: eval1.clone(), jump_to_label: label.to_string()});
            code.push(ZOP::StoreVariable{ variable: save_var.clone(), value: const_true});
        },
        ">=" | "gte" => {
            code.push(ZOP::StoreVariable{ variable: save_var.clone(), value: const_false});
            code.push(ZOP::JL{operand1: eval0.clone(), operand2: eval1.clone(), jump_to_label: label.to_string()});
            code.push(ZOP::StoreVariable{ variable: save_var.clone(), value: const_true});
        },
        ">" | "gt" => {
            code.push(ZOP::StoreVariable{ variable: save_var.clone(), value: const_true});
            code.push(ZOP::JG{operand1: eval0.clone(), operand2: eval1.clone(), jump_to_label: label.to_string()});
            code.push(ZOP::StoreVariable{ variable: save_var.clone(), value: const_false});
        },
        _ => panic!("unhandled op")
    };
    code.push(ZOP::Label {name: label.to_string()});
    free_var_if_temp(eval0, temp_ids);
    free_var_if_temp(eval1, temp_ids);
    Operand::Var(save_var)
}

/// Directly evaluates the given compare operation.
/// Both operands must be constants.
fn direct_eval_comp_op(eval0: &Operand, eval1: &Operand, op_name: &str) -> Operand {
    let val0 = eval0.const_value();
    let val1 = eval1.const_value();
    let result = match op_name {
        "is" | "==" | "eq" => { val0 == val1 },
        "neq" => { val0 != val1 },
        "<" | "lt" =>  { val0 < val1 },
        "<=" | "lte" => { val0 <= val1 },
        ">=" | "gte" => { val0 >= val1 },
        ">" | "gt" => { val0 > val1 },
        _ => panic!("unhandled op")
    };
    if result {
        Operand::Const(Constant {value: 1})
    } else {
        Operand::Const(Constant {value: 0})
    }
}

fn eval_and_or(eval0: &Operand, eval1: &Operand, op_name: &str, code: &mut Vec<ZOP>,
        temp_ids: &mut Vec<u8>) -> Operand {
    if count_constants(&eval0, &eval1) == 2 {
        let mut out_large = false;
        let val0 = eval0.const_value();
        let val1 = eval1.const_value();
        match eval0 { &Operand::LargeConst(_) => {out_large = true; }, _ => {} };
        match eval1 { &Operand::LargeConst(_) => {out_large = true; }, _ => {} };
        let result = if op_name == "or" {
                val0 | val1
            } else {
                val0 & val1
            };
        if out_large {
            return Operand::LargeConst(LargeConstant { value: result })
        } else {
            return Operand::Const(Constant { value: result as u8 })
        }
    }

    let save_var = determine_save_var(eval0, eval1, temp_ids);
    if op_name == "or" {
        code.push(ZOP::Or{operand1: eval0.clone(), operand2: eval1.clone(), save_variable: save_var.clone()});
    } else {
        code.push(ZOP::And{operand1: eval0.clone(), operand2: eval1.clone(), save_variable: save_var.clone()});
    }
    free_var_if_both_temp(eval0, eval1, temp_ids);
    Operand::Var(save_var)
}

fn eval_not<'a>(eval: &Operand, code: &mut Vec<ZOP>,
        temp_ids: &mut Vec<u8>, mut manager: &mut CodeGenManager<'a>) -> Operand {
    if eval.is_const() {
        let val = eval.const_value();
        let result: u8 = if val > 0 { 0 } else { 1 };
        return Operand::Const(Constant { value: result });
    }
    let save_var = Variable { id: temp_ids.pop().unwrap() };
    let label = format!("expr_{}", manager.ids_expr.start_next());
    code.push(ZOP::StoreVariable{ variable: save_var.clone(), value: Operand::new_const(0)});
    code.push(ZOP::JG{operand1: eval.clone(), operand2: Operand::new_const(0), jump_to_label: label.to_string()});
    code.push(ZOP::StoreVariable{ variable: save_var.clone(), value: Operand::new_const(1)});
    code.push(ZOP::Label {name: label.to_string()});
    free_var_if_temp(eval, temp_ids);
    Operand::Var(save_var)
}

fn free_var_if_both_temp (eval0: &Operand, eval1: &Operand, temp_ids: &mut Vec<u8>) {
    match eval0 {
        &Operand::Var(ref var1) => {
            if CodeGenManager::is_temp_var(var1) {
                match eval1 {
                    &Operand::Var(ref var2)=> {
                        if CodeGenManager::is_temp_var(var2) {
                            temp_ids.push(var2.id);
                        }
                    }, _ => {}
                }
            }
        }, _ => {}
    };
}

fn free_var_if_temp (operand: &Operand, temp_ids: &mut Vec<u8>) {
    match operand {
        &Operand::Var(ref var) => {
            if CodeGenManager::is_temp_var(var){
                temp_ids.push(var.id);
            }
        }, _ => {}
    }
}

fn determine_save_var(operand1: &Operand, operand2: &Operand, temp_ids: &mut Vec<u8>) -> Variable {
    match operand1 {
        &Operand::Var(ref var) => {
            if CodeGenManager::is_temp_var(var) {
                return var.clone();
            }
        }, _ => {}
    };
    match operand2 {
        &Operand::Var(ref var) => {
            if CodeGenManager::is_temp_var(var) {
                return var.clone();
            }
        }, _ => {}
    };
    return Variable { id: temp_ids.pop().unwrap() };
}

fn count_constants(operand1: &Operand, operand2: &Operand) -> u8 {
    let mut const_count: u8 = 0;
    if operand1.is_const() {
        const_count += 1;
    }
    if operand2.is_const() {
        const_count += 1;
    }
    const_count
}

fn boolstr_to_const(string: &str) -> Operand {
    match string {
        "true" => Operand::Const(Constant { value: 1 }),
        _ => Operand::Const(Constant { value: 0 })
    }
}<|endoftext|>


<commit_before><commit_msg>[algo] fizzbuzz solution with one trick<commit_after>// Mathematical approach for the fizzbuzz
//
// http://philcrissman.net/posts/eulers-fizzbuzz/
fn main() {
    (0..100).for_each(|number: i32| {
        let value = match number.pow(4) % 15 {
            0 => "FizzBuzz".to_string(),
            6 => "Fizz".to_string(),
            10 => "Buzz".to_string(),
            _ => number.to_string(),
        };

        println!("For {} Value is {}", number, value);
    })
}
<|endoftext|>


<commit_before><commit_msg>Add missing `simple.rs`<commit_after>// parng/lib.rs
//
// Copyright (c) 2016 Mozilla Foundation

//! A simple API that allocates an in-memory buffer and decodes into it.

use PngError;
use imageloader::{self, DataProvider, ImageLoader, InterlacingInfo, LevelOfDetail, LoadProgress};
use imageloader::{ScanlinesForPrediction, ScanlinesForRgbaConversion, UninitializedExtension};
use metadata::ColorType;
use std::io::{Read, Seek};
use std::mem;
use std::sync::mpsc::{self, Receiver, Sender};

struct MemoryDataProvider {
    rgba_pixels: Vec<u8>,
    indexed_pixels: Vec<u8>,
    rgba_aligned_stride: usize,
    indexed_aligned_stride: usize,
    data_sender: Sender<Vec<u8>>,
}

impl MemoryDataProvider {
    #[inline(never)]
    pub fn new(width: u32, height: u32, indexed: bool) -> (MemoryDataProvider, Receiver<Vec<u8>>) {
        let rgba_aligned_stride = imageloader::align(width as usize * 4);
        let indexed_aligned_stride = imageloader::align(width as usize * 4);
        let (data_sender, data_receiver) = mpsc::channel();

        // We make room for eight pixels past the end in case the final scanline consists of a
        // level of detail with a nonzero offset. Tricky!
        let rgba_length = rgba_aligned_stride * (height as usize) + 8 * 4;
        let indexed_length = if indexed {
            indexed_aligned_stride * (height as usize) + 8 + 1
        } else {
            0
        };

        let (mut rgba_pixels, mut indexed_pixels) = (vec![], vec![]);
        unsafe {
            rgba_pixels.extend_with_uninitialized(rgba_length);
            indexed_pixels.extend_with_uninitialized(indexed_length)
        }

        let data_provider = MemoryDataProvider {
            rgba_pixels: rgba_pixels,
            indexed_pixels: indexed_pixels,
            rgba_aligned_stride: rgba_aligned_stride,
            indexed_aligned_stride: indexed_aligned_stride,
            data_sender: data_sender,
        };
        (data_provider, data_receiver)
    }
}

impl DataProvider for MemoryDataProvider {
    fn fetch_scanlines_for_prediction<'a>(&'a mut self,
                                          reference_scanline: Option<u32>,
                                          current_scanline: u32,
                                          lod: LevelOfDetail,
                                          indexed: bool)
                                          -> ScanlinesForPrediction {
        let buffer_color_depth = buffer_color_depth(indexed);
        let reference_scanline = reference_scanline.map(|reference_scanline| {
            InterlacingInfo::new(reference_scanline, buffer_color_depth, lod)
        });
        let current_scanline = InterlacingInfo::new(current_scanline, buffer_color_depth, lod);

        let aligned_stride = if indexed {
            self.indexed_aligned_stride
        } else {
            self.rgba_aligned_stride
        };

        let split_point = aligned_stride * (current_scanline.y as usize);
        let dest_pixels = if indexed {
            &mut self.indexed_pixels
        } else {
            &mut self.rgba_pixels
        };
        let (head, tail) = dest_pixels.split_at_mut(split_point);
        let head_length = head.len();
        let reference_scanline_data = match reference_scanline {
            None => None,
            Some(reference_scanline) => {
                debug_assert!(current_scanline.stride == reference_scanline.stride);
                let start = (reference_scanline.y as usize) * aligned_stride +
                    (reference_scanline.offset as usize);
                let end = start + aligned_stride;
                let slice = &mut head[start..end];
                Some(slice)
            }
        };
        let start = (current_scanline.y as usize) * aligned_stride +
            (current_scanline.offset as usize) - head_length;
        let end = start + aligned_stride;
        let current_scanline_data = &mut tail[start..end];
        ScanlinesForPrediction {
            reference_scanline: reference_scanline_data,
            current_scanline: current_scanline_data,
            stride: current_scanline.stride,
        }
    }

    fn prediction_complete_for_scanline(&mut self, _: u32, _: LevelOfDetail) {}

    fn fetch_scanlines_for_rgba_conversion<'a>(&'a mut self,
                                               scanline: u32,
                                               lod: LevelOfDetail,
                                               indexed: bool)
                                               -> ScanlinesForRgbaConversion<'a> {
        let rgba_scanline = InterlacingInfo::new(scanline, 32, lod);
        let indexed_scanline = if indexed {
            Some(InterlacingInfo::new(scanline, 8, lod))
        } else {
            None
        };
        let rgba_aligned_stride = self.rgba_aligned_stride;
        let indexed_aligned_stride = self.indexed_aligned_stride;
        ScanlinesForRgbaConversion {
            rgba_scanline: &mut self.rgba_pixels[(rgba_aligned_stride * scanline as usize)..],
            indexed_scanline: if indexed_scanline.is_some() {
                Some(&self.indexed_pixels[(indexed_aligned_stride * scanline as usize)..])
            } else {
                None
            },
            rgba_stride: rgba_scanline.stride,
            indexed_stride: indexed_scanline.map(|indexed_scanline| indexed_scanline.stride),
        }
    }

    fn rgba_conversion_complete_for_scanline(&mut self, _: u32, _: LevelOfDetail) {}

    fn finished(&mut self) {
        self.data_sender.send(mem::replace(&mut self.rgba_pixels, vec![])).unwrap()
    }
}

/// An in-memory decoded image in big-endian RGBA format, 32 bits per pixel.
pub struct Image {
    /// The width of the image, in pixels.
    pub width: u32,
    /// The height of the image, in pixels.
    pub height: u32,
    /// The number of bytes between successive scanlines. This may be any value greater than or
    /// equal to `4 * width`.
    ///
    /// Because of SIMD alignment restrictions, `parng` may well choose a value greater than `4 *
    /// width` here.
    pub stride: usize,
    /// The actual pixels.
    pub pixels: Vec<u8>,
}

impl Image {
    /// Allocates space for and loads a PNG image stream from a reader into memory.
    ///
    /// The returned image is big-endian, 32 bits per pixel RGBA.
    ///
    /// This method does not return until the image is fully loaded. If you need a different
    /// in-memory representation, or you need to display the image before it's fully loaded,
    /// consider using the `imageloader::ImageLoader` API instead.
    pub fn load<I>(input: &mut I) -> Result<Image, PngError> where I: Read + Seek {
        let mut image = ImageLoader::new();
        loop {
            match try!(image.add_data(input)) {
                LoadProgress::NeedDataProviderAndMoreData => break,
                LoadProgress::NeedMoreData => {}
                LoadProgress::Finished => panic!("Image ended before metadata was read!"),
            }
        }

        let (dimensions, indexed) = {
            let metadata = image.metadata().as_ref().unwrap();
            (metadata.dimensions, metadata.color_type == ColorType::Indexed)
        };
        let (data_provider, data_receiver) = MemoryDataProvider::new(dimensions.width,
                                                                     dimensions.height,
                                                                     indexed);
        let aligned_stride = data_provider.rgba_aligned_stride;
        image.set_data_provider(Box::new(data_provider));

        while let LoadProgress::NeedMoreData = try!(image.add_data(input)) {}
        try!(image.wait_until_finished());

        let pixels = data_receiver.recv().unwrap();
        Ok(Image {
            width: dimensions.width,
            height: dimensions.height,
            stride: aligned_stride,
            pixels: pixels,
        })
    }
}

fn buffer_color_depth(indexed: bool) -> u8 {
    if indexed {
        8
    } else {
        32
    }
}

<|endoftext|>


<commit_before><commit_msg>Added Pi file and numbers folder<commit_after>use std::f32::to_str_digits;
use std::num::atan;

fn get_pi(num :uint) ->~str {
    to_str_digits(16f32*atan(1f32/5f32)-4f32*atan(1f32/239f32), num)
}

#[test]
fn get_pi_test() {
    assert!(get_pi(12) == to_str_digits(3.1415927410125732421875f32, 12), "{} {}", get_pi(12), 3.141592741013);
}

#[test]
fn get_pi_test2() {
    assert!(get_pi(0) == to_str_digits(3.1415927410125732421875f32, 0), "{} {}", get_pi(0), 3);
}

fn main() {
    let pi = get_pi(12);
    println!("{}", pi);
}<|endoftext|>


<commit_before><commit_msg>stop considering `Rc` cycles (leaks) as unsafe<commit_after><|endoftext|>


<commit_before><commit_msg>Got it working!!!<commit_after><|endoftext|>


<commit_before>// EBML enum definitions and utils shared by the encoder and decoder

const tag_paths: uint = 0x01u;

const tag_items: uint = 0x02u;

const tag_paths_data: uint = 0x03u;

const tag_paths_data_name: uint = 0x04u;

const tag_paths_data_item: uint = 0x05u;

const tag_paths_data_mod: uint = 0x06u;

const tag_def_id: uint = 0x07u;

const tag_items_data: uint = 0x08u;

const tag_items_data_item: uint = 0x09u;

const tag_items_data_item_family: uint = 0x0au;

const tag_items_data_item_ty_param_bounds: uint = 0x0bu;

const tag_items_data_item_type: uint = 0x0cu;

const tag_items_data_item_symbol: uint = 0x0du;

const tag_items_data_item_variant: uint = 0x0eu;

const tag_items_data_parent_item: uint = 0x0fu;

const tag_index: uint = 0x11u;

const tag_index_buckets: uint = 0x12u;

const tag_index_buckets_bucket: uint = 0x13u;

const tag_index_buckets_bucket_elt: uint = 0x14u;

const tag_index_table: uint = 0x15u;

const tag_meta_item_name_value: uint = 0x18u;

const tag_meta_item_name: uint = 0x19u;

const tag_meta_item_value: uint = 0x20u;

const tag_attributes: uint = 0x21u;

const tag_attribute: uint = 0x22u;

const tag_meta_item_word: uint = 0x23u;

const tag_meta_item_list: uint = 0x24u;

// The list of crates that this crate depends on
const tag_crate_deps: uint = 0x25u;

// A single crate dependency
const tag_crate_dep: uint = 0x26u;

const tag_crate_hash: uint = 0x28u;

const tag_parent_item: uint = 0x29u;

const tag_crate_dep_name: uint = 0x2au;
const tag_crate_dep_hash: uint = 0x2bu;
const tag_crate_dep_vers: uint = 0x2cu;

const tag_mod_impl: uint = 0x30u;

const tag_item_trait_method: uint = 0x31u;
const tag_impl_trait: uint = 0x32u;

// discriminator value for variants
const tag_disr_val: uint = 0x34u;

// used to encode ast_map::path and ast_map::path_elt
const tag_path: uint = 0x40u;
const tag_path_len: uint = 0x41u;
const tag_path_elt_mod: uint = 0x42u;
const tag_path_elt_name: uint = 0x43u;
const tag_item_field: uint = 0x44u;
const tag_class_mut: uint = 0x45u;

const tag_region_param: uint = 0x46u;
const tag_mod_impl_trait: uint = 0x47u;
/*
  trait items contain tag_item_trait_method elements,
  impl items contain tag_item_impl_method elements, and classes
  have both. That's because some code treats classes like traits,
  and other code treats them like impls. Because classes can contain
  both, tag_item_trait_method and tag_item_impl_method have to be two
  different tags.
 */
const tag_item_impl_method: uint = 0x48u;
const tag_item_dtor: uint = 0x49u;
const tag_paths_foreign_path: uint = 0x4a;
const tag_item_trait_method_self_ty: uint = 0x4b;
const tag_item_trait_method_self_ty_region: uint = 0x4c;

// Reexports are found within module tags. Each reexport contains def_ids
// and names.
const tag_items_data_item_reexport: uint = 0x4d;
const tag_items_data_item_reexport_def_id: uint = 0x4e;
const tag_items_data_item_reexport_name: uint = 0x4f;

// used to encode crate_ctxt side tables
enum astencode_tag { // Reserves 0x50 -- 0x6f
    tag_ast = 0x50,

    tag_tree = 0x51,

    tag_id_range = 0x52,

    tag_table = 0x53,
    tag_table_id = 0x54,
    tag_table_val = 0x55,
    tag_table_def = 0x56,
    tag_table_node_type = 0x57,
    tag_table_node_type_subst = 0x58,
    tag_table_freevars = 0x59,
    tag_table_tcache = 0x5a,
    tag_table_param_bounds = 0x5b,
    tag_table_inferred_modes = 0x5c,
    tag_table_mutbl = 0x5d,
    tag_table_last_use = 0x5e,
    tag_table_spill = 0x5f,
    tag_table_method_map = 0x60,
    tag_table_vtable_map = 0x61,
    tag_table_borrowings = 0x62
}

// djb's cdb hashes.
fn hash_node_id(&&node_id: int) -> uint {
    return 177573u ^ (node_id as uint);
}

fn hash_path(&&s: ~str) -> uint {
    let mut h = 5381u;
    for str::each(s) |ch| { h = (h << 5u) + h ^ (ch as uint); }
    return h;
}

type link_meta = {name: @~str, vers: @~str, extras_hash: ~str};

<commit_msg>rustc: Remove a bunch of unused metadata tags from common<commit_after>// EBML enum definitions and utils shared by the encoder and decoder

const tag_items: uint = 0x02u;

const tag_paths_data_name: uint = 0x04u;

const tag_def_id: uint = 0x07u;

const tag_items_data: uint = 0x08u;

const tag_items_data_item: uint = 0x09u;

const tag_items_data_item_family: uint = 0x0au;

const tag_items_data_item_ty_param_bounds: uint = 0x0bu;

const tag_items_data_item_type: uint = 0x0cu;

const tag_items_data_item_symbol: uint = 0x0du;

const tag_items_data_item_variant: uint = 0x0eu;

const tag_items_data_parent_item: uint = 0x0fu;

const tag_index: uint = 0x11u;

const tag_index_buckets: uint = 0x12u;

const tag_index_buckets_bucket: uint = 0x13u;

const tag_index_buckets_bucket_elt: uint = 0x14u;

const tag_index_table: uint = 0x15u;

const tag_meta_item_name_value: uint = 0x18u;

const tag_meta_item_name: uint = 0x19u;

const tag_meta_item_value: uint = 0x20u;

const tag_attributes: uint = 0x21u;

const tag_attribute: uint = 0x22u;

const tag_meta_item_word: uint = 0x23u;

const tag_meta_item_list: uint = 0x24u;

// The list of crates that this crate depends on
const tag_crate_deps: uint = 0x25u;

// A single crate dependency
const tag_crate_dep: uint = 0x26u;

const tag_crate_hash: uint = 0x28u;

const tag_parent_item: uint = 0x29u;

const tag_crate_dep_name: uint = 0x2au;
const tag_crate_dep_hash: uint = 0x2bu;
const tag_crate_dep_vers: uint = 0x2cu;

const tag_mod_impl: uint = 0x30u;

const tag_item_trait_method: uint = 0x31u;
const tag_impl_trait: uint = 0x32u;

// discriminator value for variants
const tag_disr_val: uint = 0x34u;

// used to encode ast_map::path and ast_map::path_elt
const tag_path: uint = 0x40u;
const tag_path_len: uint = 0x41u;
const tag_path_elt_mod: uint = 0x42u;
const tag_path_elt_name: uint = 0x43u;
const tag_item_field: uint = 0x44u;
const tag_class_mut: uint = 0x45u;

const tag_region_param: uint = 0x46u;
const tag_mod_impl_trait: uint = 0x47u;
/*
  trait items contain tag_item_trait_method elements,
  impl items contain tag_item_impl_method elements, and classes
  have both. That's because some code treats classes like traits,
  and other code treats them like impls. Because classes can contain
  both, tag_item_trait_method and tag_item_impl_method have to be two
  different tags.
 */
const tag_item_impl_method: uint = 0x48u;
const tag_item_dtor: uint = 0x49u;
const tag_item_trait_method_self_ty: uint = 0x4b;
const tag_item_trait_method_self_ty_region: uint = 0x4c;

// Reexports are found within module tags. Each reexport contains def_ids
// and names.
const tag_items_data_item_reexport: uint = 0x4d;
const tag_items_data_item_reexport_def_id: uint = 0x4e;
const tag_items_data_item_reexport_name: uint = 0x4f;

// used to encode crate_ctxt side tables
enum astencode_tag { // Reserves 0x50 -- 0x6f
    tag_ast = 0x50,

    tag_tree = 0x51,

    tag_id_range = 0x52,

    tag_table = 0x53,
    tag_table_id = 0x54,
    tag_table_val = 0x55,
    tag_table_def = 0x56,
    tag_table_node_type = 0x57,
    tag_table_node_type_subst = 0x58,
    tag_table_freevars = 0x59,
    tag_table_tcache = 0x5a,
    tag_table_param_bounds = 0x5b,
    tag_table_inferred_modes = 0x5c,
    tag_table_mutbl = 0x5d,
    tag_table_last_use = 0x5e,
    tag_table_spill = 0x5f,
    tag_table_method_map = 0x60,
    tag_table_vtable_map = 0x61,
    tag_table_borrowings = 0x62
}

// djb's cdb hashes.
fn hash_node_id(&&node_id: int) -> uint {
    return 177573u ^ (node_id as uint);
}

fn hash_path(&&s: ~str) -> uint {
    let mut h = 5381u;
    for str::each(s) |ch| { h = (h << 5u) + h ^ (ch as uint); }
    return h;
}

type link_meta = {name: @~str, vers: @~str, extras_hash: ~str};

<|endoftext|>


<commit_before><commit_msg>Set all dictionary names to lowercase, as querying won't work otherwise.<commit_after><|endoftext|>


<commit_before><commit_msg>Remove the `Datum::Json` variant<commit_after><|endoftext|>


<commit_before>use std::url::Url;
use std::{cmp, mem, ptr};
use std::get_slice::GetSlice;
use std::io::*;
use std::process::Command;
use std::ops::DerefMut;
use std::syscall::SysError;
use std::syscall::ENOENT;
use std::to_num::ToNum;

use orbital::event::Event;
use orbital::Point;
use orbital::Size;

use self::display::Display;
use self::session::Session;
use self::window::Window;

pub mod display;
pub mod package;
pub mod session;
pub mod window;

pub static mut session_ptr: *mut Session = 0 as *mut Session;

/// A window resource
pub struct Resource {
    /// The window
    pub window: Box<Window>,
    /// Seek point
    pub seek: usize,
}

impl Resource {
    pub fn dup(&self) -> Result<Box<Resource>> {
        Ok(box Resource {
            window: Window::new(self.window.point,
                                self.window.size,
                                self.window.title.clone()),
            seek: self.seek,
        })
    }

    /// Return the url of this resource
    pub fn path(&self) -> Result<String> {
        Ok(format!("orbital:///{}/{}/{}/{}/{}",
                   self.window.point.x,
                   self.window.point.y,
                   self.window.size.width,
                   self.window.size.height,
                   self.window.title))
    }

    /// Read data to buffer
    pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        // Read events from window
        let mut i = 0;
        while buf.len() - i >= mem::size_of::<Event>() {
            match self.window.poll() {
                Some(event) => {
                    unsafe { ptr::write(buf.as_ptr().offset(i as isize) as *mut Event, event) };
                    i += mem::size_of::<Event>();
                }
                None => break,
            }
        }

        Ok(i)
    }

    /// Write to resource
    pub fn write(&mut self, buf: &[u8]) -> Result<usize> {
        let content = &mut self.window.content;

        let size = cmp::min(content.size - self.seek, buf.len());
        unsafe {
            Display::copy_run(buf.as_ptr() as usize, content.offscreen + self.seek, size);
        }
        self.seek += size;

        Ok(size)
    }

    /// Seek
    pub fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
        let end = self.window.content.size;

        self.seek = match pos {
            SeekFrom::Start(offset) => cmp::min(end as u64, cmp::max(0, offset)) as usize,
            SeekFrom::Current(offset) =>
                cmp::min(end as i64, cmp::max(0, self.seek as i64 + offset)) as usize,
            SeekFrom::End(offset) =>
                cmp::min(end as i64, cmp::max(0, end as i64 + offset)) as usize,
        };

        Ok(self.seek as u64)
    }

    /// Sync the resource, should flip
    pub fn sync(&mut self) -> Result<()> {
        self.window.redraw();
        Ok(())
    }
}

/// A window scheme
pub struct Scheme {
    pub session: Box<Session>,
    pub next_x: isize,
    pub next_y: isize,
}

impl Scheme {
    pub fn new() -> Box<Scheme> {
        println!("- Starting Orbital");
        println!("    Console: Press F1");
        println!("    Desktop: Press F2");
        let mut ret = box Scheme {
            session: Session::new(),
            next_x: 0,
            next_y: 0,
        };
        unsafe { session_ptr = ret.session.deref_mut() };
        ret
    }

    pub fn open(&mut self, url_str: &str, _: usize) -> Result<Box<Resource>> {
        // window://host/path/path/path is the path type we're working with.
        let url = Url::from_str(url_str);

        let host = url.host();
        if host.is_empty() {
            let path = url.path_parts();
            let mut pointx = match path.get(0) {
                Some(x) => x.to_num_signed(),
                None => 0,
            };
            let mut pointy = match path.get(1) {
                Some(y) => y.to_num_signed(),
                None => 0,
            };
            let size_width = match path.get(2) {
                Some(w) => w.to_num(),
                None => 100,
            };
            let size_height = match path.get(3) {
                Some(h) => h.to_num(),
                None => 100,
            };

            let mut title = match path.get(4) {
                Some(t) => t.clone(),
                None => String::new(),
            };
            for i in 5..path.len() {
                if let Some(t) = path.get(i) {
                    title = title + "/" + t;
                }
            }

            if pointx <= 0 || pointy <= 0 {
                if self.next_x > self.session.display.width as isize - size_width as isize {
                    self.next_x = 0;
                }
                self.next_x += 32;
                pointx = self.next_x as i32;

                if self.next_y > self.session.display.height as isize - size_height as isize {
                    self.next_y = 0;
                }
                self.next_y += 32;
                pointy = self.next_y as i32;
            }

            Ok(box Resource {
                window: Window::new(Point::new(pointx, pointy),
                                    Size::new(size_width, size_height),
                                    title),
                seek: 0,
            })
        } else if host == "launch" {
            let path = url.path();

            for package in self.session.packages.iter() {
                let mut accepted = false;
                for accept in package.accepts.iter() {
                    if (accept.starts_with('*') &&
                        path.ends_with(&accept.get_slice(Some(1), None))) ||
                       (accept.ends_with('*') &&
                        path.starts_with(&accept.get_slice(None, Some(accept.len() - 1)))) {
                        accepted = true;
                        break;
                    }
                }
                if accepted {
                    if Command::new(&package.binary).arg(&path).spawn_scheme().is_none() {
                        println!("{}: Failed to launch", package.binary);
                    }
                    break;
                }
            }

            Err(SysError::new(ENOENT))
        } else {
            Err(SysError::new(ENOENT))
        }
    }

    pub fn event(&mut self, event: &Event) {
        self.session.event(event);

        unsafe { self.session.redraw() };
    }
}

// TODO: This is a hack and it will go away
#[cold]
#[inline(never)]
#[no_mangle]
pub unsafe extern "C" fn _event(scheme: *mut Scheme, event: *const Event) {
    (*scheme).event(&*event);
}
<commit_msg>Fixes #439 - Launch binaries from file manager if they end in .bin<commit_after>use std::url::Url;
use std::{cmp, mem, ptr};
use std::get_slice::GetSlice;
use std::io::*;
use std::process::Command;
use std::ops::DerefMut;
use std::syscall::SysError;
use std::syscall::ENOENT;
use std::to_num::ToNum;

use orbital::event::Event;
use orbital::Point;
use orbital::Size;

use self::display::Display;
use self::session::Session;
use self::window::Window;

pub mod display;
pub mod package;
pub mod session;
pub mod window;

pub static mut session_ptr: *mut Session = 0 as *mut Session;

/// A window resource
pub struct Resource {
    /// The window
    pub window: Box<Window>,
    /// Seek point
    pub seek: usize,
}

impl Resource {
    pub fn dup(&self) -> Result<Box<Resource>> {
        Ok(box Resource {
            window: Window::new(self.window.point,
                                self.window.size,
                                self.window.title.clone()),
            seek: self.seek,
        })
    }

    /// Return the url of this resource
    pub fn path(&self) -> Result<String> {
        Ok(format!("orbital:///{}/{}/{}/{}/{}",
                   self.window.point.x,
                   self.window.point.y,
                   self.window.size.width,
                   self.window.size.height,
                   self.window.title))
    }

    /// Read data to buffer
    pub fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        // Read events from window
        let mut i = 0;
        while buf.len() - i >= mem::size_of::<Event>() {
            match self.window.poll() {
                Some(event) => {
                    unsafe { ptr::write(buf.as_ptr().offset(i as isize) as *mut Event, event) };
                    i += mem::size_of::<Event>();
                }
                None => break,
            }
        }

        Ok(i)
    }

    /// Write to resource
    pub fn write(&mut self, buf: &[u8]) -> Result<usize> {
        let content = &mut self.window.content;

        let size = cmp::min(content.size - self.seek, buf.len());
        unsafe {
            Display::copy_run(buf.as_ptr() as usize, content.offscreen + self.seek, size);
        }
        self.seek += size;

        Ok(size)
    }

    /// Seek
    pub fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
        let end = self.window.content.size;

        self.seek = match pos {
            SeekFrom::Start(offset) => cmp::min(end as u64, cmp::max(0, offset)) as usize,
            SeekFrom::Current(offset) =>
                cmp::min(end as i64, cmp::max(0, self.seek as i64 + offset)) as usize,
            SeekFrom::End(offset) =>
                cmp::min(end as i64, cmp::max(0, end as i64 + offset)) as usize,
        };

        Ok(self.seek as u64)
    }

    /// Sync the resource, should flip
    pub fn sync(&mut self) -> Result<()> {
        self.window.redraw();
        Ok(())
    }
}

/// A window scheme
pub struct Scheme {
    pub session: Box<Session>,
    pub next_x: isize,
    pub next_y: isize,
}

impl Scheme {
    pub fn new() -> Box<Scheme> {
        println!("- Starting Orbital");
        println!("    Console: Press F1");
        println!("    Desktop: Press F2");
        let mut ret = box Scheme {
            session: Session::new(),
            next_x: 0,
            next_y: 0,
        };
        unsafe { session_ptr = ret.session.deref_mut() };
        ret
    }

    pub fn open(&mut self, url_str: &str, _: usize) -> Result<Box<Resource>> {
        // window://host/path/path/path is the path type we're working with.
        let url = Url::from_str(url_str);

        let host = url.host();
        if host.is_empty() {
            let path = url.path_parts();
            let mut pointx = match path.get(0) {
                Some(x) => x.to_num_signed(),
                None => 0,
            };
            let mut pointy = match path.get(1) {
                Some(y) => y.to_num_signed(),
                None => 0,
            };
            let size_width = match path.get(2) {
                Some(w) => w.to_num(),
                None => 100,
            };
            let size_height = match path.get(3) {
                Some(h) => h.to_num(),
                None => 100,
            };

            let mut title = match path.get(4) {
                Some(t) => t.clone(),
                None => String::new(),
            };
            for i in 5..path.len() {
                if let Some(t) = path.get(i) {
                    title = title + "/" + t;
                }
            }

            if pointx <= 0 || pointy <= 0 {
                if self.next_x > self.session.display.width as isize - size_width as isize {
                    self.next_x = 0;
                }
                self.next_x += 32;
                pointx = self.next_x as i32;

                if self.next_y > self.session.display.height as isize - size_height as isize {
                    self.next_y = 0;
                }
                self.next_y += 32;
                pointy = self.next_y as i32;
            }

            Ok(box Resource {
                window: Window::new(Point::new(pointx, pointy),
                                    Size::new(size_width, size_height),
                                    title),
                seek: 0,
            })
        } else if host == "launch" {
            let path = url.path();

            if path.ends_with(".bin") {
                if Command::new(&path).spawn_scheme().is_none() {
                    println!("{}: Failed to launch", path);
                }
            } else {
                for package in self.session.packages.iter() {
                    let mut accepted = false;
                    for accept in package.accepts.iter() {
                        if (accept.starts_with('*') &&
                            path.ends_with(&accept.get_slice(Some(1), None))) ||
                           (accept.ends_with('*') &&
                            path.starts_with(&accept.get_slice(None, Some(accept.len() - 1)))) {
                            accepted = true;
                            break;
                        }
                    }
                    if accepted {
                        if Command::new(&package.binary).arg(&path).spawn_scheme().is_none() {
                            println!("{}: Failed to launch", package.binary);
                        }
                        break;
                    }
                }
            }

            Err(SysError::new(ENOENT))
        } else {
            Err(SysError::new(ENOENT))
        }
    }

    pub fn event(&mut self, event: &Event) {
        self.session.event(event);

        unsafe { self.session.redraw() };
    }
}

// TODO: This is a hack and it will go away
#[cold]
#[inline(never)]
#[no_mangle]
pub unsafe extern "C" fn _event(scheme: *mut Scheme, event: *const Event) {
    (*scheme).event(&*event);
}
<|endoftext|>


<commit_before><commit_msg>an empy message<commit_after><|endoftext|>


<commit_before><commit_msg>Remove a few warnings from the Vulkan validation layers installation method<commit_after><|endoftext|>


<commit_before><commit_msg>Add rust code for ocr-numbers.<commit_after>#![feature(str_checked_slicing)]

const DIGITS: [&str; 10] = [
    " _ | ||_|   ", // 0
    "     |  |   ", // 1
    " _  _||_    ", // 2
    " _  _| _|   ", // 3
    "   |_|  |   ", // 4
    " _ |_  _|   ", // 5
    " _ |_ |_|   ", // 6
    " _   |  |   ", // 7
    " _ |_||_|   ", // 8
    " _ |_| _|   ", // 9
];

const DIGITS_ROWS: usize = 3;
const DIGITS_LINES: usize = 4;

pub fn convert(input: &str) -> Result<String, String> {
    let v = input.split(|x| x == '\n').collect::<Vec<_>>();

    let lines = v.len();
    if lines == 0 || lines % DIGITS_LINES != 0 {
        return Err("Invalid lines".to_string());
    }

    let rows = v[0].len();
    if rows == 0 || rows % DIGITS_ROWS != 0 {
        return Err(format!("Invalid {} row at line 1", rows));
    }
    if v.iter().any(|x| x.len() != rows) {
        return Err("Invalid rows".to_string());
    }

    let mut result = String::new();
    for i in 0..lines / DIGITS_LINES {
        for j in 0..rows / DIGITS_ROWS {
            let row = j * DIGITS_ROWS;
            let line = i * DIGITS_LINES;

            let number = format!(
                "{}{}{}{}",
                v[line].get(row..row + DIGITS_ROWS).unwrap(),
                v[line + 1].get(row..row + DIGITS_ROWS).unwrap(),
                v[line + 2].get(row..row + DIGITS_ROWS).unwrap(),
                v[line + 3].get(row..row + DIGITS_ROWS).unwrap()
            );

            let index: u8 = DIGITS
                .iter()
                .position(|&x| x == number)
                .map_or_else(|| b'?', |v| v as u8 + b'0');

            result.push(index as char);
        }

        result.push(',');
    }

    result.pop();

    Ok(result)
}
<|endoftext|>