<commit_before>use common::debug::*;
use common::memory::*;
use common::string::*;

use drivers::disk::*;
use drivers::keyboard::*;
use drivers::mouse::*;

use filesystems::unfs::*;

use graphics::color::*;
use graphics::display::*;
use graphics::point::*;
use graphics::size::*;
use graphics::window::*;

use programs::program::*;

pub struct Editor {
    window: Window,
    filename: &'static str,
    string: String,
    offset: usize
}

impl Editor {
    pub unsafe fn new() -> Editor {
        Editor {
            window: Window{
                point: Point{ x:300, y:200 },
                size: Size { width:640, height:480 },
                title: "Press a function key to load a file",
                shaded: false,
                dragging: false,
                last_mouse_point: Point {
                    x: 0,
                    y: 0
                },
                last_mouse_event: MouseEvent {
                    x: 0,
                    y: 0,
                    left_button: false,
                    right_button: false,
                    middle_button: false,
                    valid: false
                }
            },
            filename: "",
            string: String::new(),
            offset: 0
        }
    }

    unsafe fn clear(&mut self){
        self.window.title = "Press a function key to load a file";
        self.filename = "";
        self.string = String::new();
        self.offset = 0;
    }

    unsafe fn load(&mut self, filename: &'static str){
        self.clear();
        let unfs = UnFS::new(Disk::new());
        let dest = unfs.load(filename);
        if dest > 0 {
            self.filename = filename;
            self.window.title = filename;
            self.string = String::from_c_str(dest as *const u8);
            self.offset = self.string.len();
            unalloc(dest);
        }else{
            d("Did not find '");
            d(filename);
            d("'\n");
        }
    }

    unsafe fn save(&self){
        let unfs = UnFS::new(Disk::new());
        let data = self.string.as_c_str() as usize;
        unfs.save(self.filename, data);
        unalloc(data);
        d("Saved\n");
    }
}

impl Program for Editor {
    unsafe fn draw(&self, display: &Display){
        self.window.draw(display);

		if ! self.window.shaded {
            let mut offset = 0;
            let mut row = 0;
            let mut col = 0;
            for c_ptr in self.string.as_slice() {
                if offset == self.offset && col < self.window.size.width / 8 && row < self.window.size.height / 16 {
                    display.char(Point::new(self.window.point.x + 8*col as i32, self.window.point.y + 16*row as i32), '_', Color::new(128, 128, 128));
                }

                let c = *c_ptr;
                if c == '\n' {
                    col = 0;
                    row += 1;
                }else if c == '\t' {
                    col += 8 - col % 8;
                }else{
                    if col < self.window.size.width / 8 && row < self.window.size.height / 16 {
                        let point = Point::new(self.window.point.x + 8*col as i32, self.window.point.y + 16*row as i32);
                        display.char(point, c, Color::new(255, 255, 255));
                        col += 1;
                    }
                }
                if col >= self.window.size.width / 8 {
                    col = 0;
                    row += 1;
                }

                offset += 1;
            }

            if offset == self.offset && col < self.window.size.width / 8 && row < self.window.size.height / 16 {
                display.char(Point::new(self.window.point.x + 8*col as i32, self.window.point.y + 16*row as i32), '_', Color::new(128, 128, 128));
            }
        }
    }

    unsafe fn on_key(&mut self, key_event: KeyEvent){
        if key_event.pressed {
            match key_event.scancode {
                0x3B => self.load("README.md"),
                0x3C => self.load("LICENSE.md"),
                0x40 => self.save(),
                0x47 => self.offset = 0,
                0x48 => for i in 1..self.offset {
                    match self.string.get(self.offset - i) {
                        '\0' => break,
                        '\n' => {
                            self.offset = self.offset - i;
                            break;
                        },
                        _ => ()
                    }
                },
                0x4B => if self.offset > 0 {
                            self.offset -= 1;
                        },
                0x4D => if self.offset < self.string.len() {
                            self.offset += 1;
                        },
                0x4F => self.offset = self.string.len(),
                0x50 => for i in self.offset + 1..self.string.len() {
                    match self.string.get(i) {
                        '\0' => break,
                        '\n' => {
                            self.offset = i;
                            break;
                        },
                        _ => ()
                    }
                },
                0x53 => if self.offset < self.string.len() {
                    self.string = self.string.substr(0, self.offset) + self.string.substr(self.offset + 1, self.string.len() - self.offset - 1);
                },
                _ => ()
            }

            match key_event.character {
                '\x00' => (),
                '\x08' => if self.offset > 0 {
                    self.string = self.string.substr(0, self.offset - 1) + self.string.substr(self.offset, self.string.len() - self.offset);
                    self.offset -= 1;
                },
                '\x1B' => self.clear(),
                _ => {
                    self.string = self.string.substr(0, self.offset) + key_event.character + self.string.substr(self.offset, self.string.len() - self.offset);
                    self.offset += 1;
                }
            }
        }
    }

    unsafe fn on_mouse(&mut self, mouse_point: Point, mouse_event: MouseEvent, allow_catch: bool) -> bool{
        return self.window.on_mouse(mouse_point, mouse_event, allow_catch);
    }
}<commit_msg>Repositioning of windows<commit_after>use common::debug::*;
use common::memory::*;
use common::string::*;

use drivers::disk::*;
use drivers::keyboard::*;
use drivers::mouse::*;

use filesystems::unfs::*;

use graphics::color::*;
use graphics::display::*;
use graphics::point::*;
use graphics::size::*;
use graphics::window::*;

use programs::program::*;

pub struct Editor {
    window: Window,
    filename: &'static str,
    string: String,
    offset: usize
}

impl Editor {
    pub unsafe fn new() -> Editor {
        Editor {
            window: Window{
                point: Point{ x:400, y:300 },
                size: Size { width:512, height:320 },
                title: "Press a function key to load a file",
                shaded: false,
                dragging: false,
                last_mouse_point: Point {
                    x: 0,
                    y: 0
                },
                last_mouse_event: MouseEvent {
                    x: 0,
                    y: 0,
                    left_button: false,
                    right_button: false,
                    middle_button: false,
                    valid: false
                }
            },
            filename: "",
            string: String::new(),
            offset: 0
        }
    }

    unsafe fn clear(&mut self){
        self.window.title = "Press a function key to load a file";
        self.filename = "";
        self.string = String::new();
        self.offset = 0;
    }

    unsafe fn load(&mut self, filename: &'static str){
        self.clear();
        let unfs = UnFS::new(Disk::new());
        let dest = unfs.load(filename);
        if dest > 0 {
            self.filename = filename;
            self.window.title = filename;
            self.string = String::from_c_str(dest as *const u8);
            self.offset = self.string.len();
            unalloc(dest);
        }else{
            d("Did not find '");
            d(filename);
            d("'\n");
        }
    }

    unsafe fn save(&self){
        let unfs = UnFS::new(Disk::new());
        let data = self.string.as_c_str() as usize;
        unfs.save(self.filename, data);
        unalloc(data);
        d("Saved\n");
    }
}

impl Program for Editor {
    unsafe fn draw(&self, display: &Display){
        self.window.draw(display);

		if ! self.window.shaded {
            let mut offset = 0;
            let mut row = 0;
            let mut col = 0;
            for c_ptr in self.string.as_slice() {
                if offset == self.offset && col < self.window.size.width / 8 && row < self.window.size.height / 16 {
                    display.char(Point::new(self.window.point.x + 8*col as i32, self.window.point.y + 16*row as i32), '_', Color::new(128, 128, 128));
                }

                let c = *c_ptr;
                if c == '\n' {
                    col = 0;
                    row += 1;
                }else if c == '\t' {
                    col += 8 - col % 8;
                }else{
                    if col < self.window.size.width / 8 && row < self.window.size.height / 16 {
                        let point = Point::new(self.window.point.x + 8*col as i32, self.window.point.y + 16*row as i32);
                        display.char(point, c, Color::new(255, 255, 255));
                        col += 1;
                    }
                }
                if col >= self.window.size.width / 8 {
                    col = 0;
                    row += 1;
                }

                offset += 1;
            }

            if offset == self.offset && col < self.window.size.width / 8 && row < self.window.size.height / 16 {
                display.char(Point::new(self.window.point.x + 8*col as i32, self.window.point.y + 16*row as i32), '_', Color::new(128, 128, 128));
            }
        }
    }

    unsafe fn on_key(&mut self, key_event: KeyEvent){
        if key_event.pressed {
            match key_event.scancode {
                0x3B => self.load("README.md"),
                0x3C => self.load("LICENSE.md"),
                0x40 => self.save(),
                0x47 => self.offset = 0,
                0x48 => for i in 1..self.offset {
                    match self.string.get(self.offset - i) {
                        '\0' => break,
                        '\n' => {
                            self.offset = self.offset - i;
                            break;
                        },
                        _ => ()
                    }
                },
                0x4B => if self.offset > 0 {
                            self.offset -= 1;
                        },
                0x4D => if self.offset < self.string.len() {
                            self.offset += 1;
                        },
                0x4F => self.offset = self.string.len(),
                0x50 => for i in self.offset + 1..self.string.len() {
                    match self.string.get(i) {
                        '\0' => break,
                        '\n' => {
                            self.offset = i;
                            break;
                        },
                        _ => ()
                    }
                },
                0x53 => if self.offset < self.string.len() {
                    self.string = self.string.substr(0, self.offset) + self.string.substr(self.offset + 1, self.string.len() - self.offset - 1);
                },
                _ => ()
            }

            match key_event.character {
                '\x00' => (),
                '\x08' => if self.offset > 0 {
                    self.string = self.string.substr(0, self.offset - 1) + self.string.substr(self.offset, self.string.len() - self.offset);
                    self.offset -= 1;
                },
                '\x1B' => self.clear(),
                _ => {
                    self.string = self.string.substr(0, self.offset) + key_event.character + self.string.substr(self.offset, self.string.len() - self.offset);
                    self.offset += 1;
                }
            }
        }
    }

    unsafe fn on_mouse(&mut self, mouse_point: Point, mouse_event: MouseEvent, allow_catch: bool) -> bool{
        return self.window.on_mouse(mouse_point, mouse_event, allow_catch);
    }
}<|endoftext|>


<commit_before>/* rustdoc: rust -> markdown translator
 * Copyright 2011 Google Inc.
 */

use std;
use rustc;

#[doc(
  brief = "Main function.",
  desc = "Command-line arguments:

*  argv[1]: crate file name",
  args(argv = "Command-line arguments.")
)]
fn main(argv: [str]) {

    if vec::len(argv) != 2u {
        std::io::println(#fmt("usage: %s <input>", argv[0]));
        ret;
    }

    let source_file = argv[1];
    let default_name = source_file;
    let crate = parse::from_file(source_file);
    let doc = extract::extract(crate, default_name);
    let doc = tystr_pass::run(doc, crate);
    gen::write_markdown(doc, std::io::stdout());
}
<commit_msg>rustdoc: Add a pass type and a run_passes function<commit_after>/* rustdoc: rust -> markdown translator
 * Copyright 2011 Google Inc.
 */

use std;
use rustc;

type pass = fn~(srv: astsrv::seq_srv, doc: doc::cratedoc) -> doc::cratedoc;

fn run_passes(
    srv: astsrv::seq_srv,
    doc: doc::cratedoc,
    passes: [pass]
) -> doc::cratedoc {
    vec::foldl(doc, passes) {|doc, pass|
        pass(srv, doc)
    }
}

#[test]
fn test_run_passes() {
    import astsrv::seq_srv;
    fn pass1(
        _srv: astsrv::seq_srv,
        doc: doc::cratedoc
    ) -> doc::cratedoc {
        ~{
            topmod: ~{
                name: doc.topmod.name + "two",
                mods: doc::modlist([]),
                fns: doc::fnlist([])
            }
        }
    }
    fn pass2(
        _srv: astsrv::seq_srv,
        doc: doc::cratedoc
    ) -> doc::cratedoc {
        ~{
            topmod: ~{
                name: doc.topmod.name + "three",
                mods: doc::modlist([]),
                fns: doc::fnlist([])
            }
        }
    }
    let source = "";
    let srv = astsrv::mk_seq_srv_from_str(source);
    let passes = [pass1, pass2];
    let doc = extract::from_srv(srv, "one");
    let doc = run_passes(srv, doc, passes);
    assert doc.topmod.name == "onetwothree";
}

#[doc(
  brief = "Main function.",
  desc = "Command-line arguments:

*  argv[1]: crate file name",
  args(argv = "Command-line arguments.")
)]
fn main(argv: [str]) {

    if vec::len(argv) != 2u {
        std::io::println(#fmt("usage: %s <input>", argv[0]));
        ret;
    }

    let source_file = argv[1];
    let default_name = source_file;
    let crate = parse::from_file(source_file);
    let doc = extract::extract(crate, default_name);
    let doc = tystr_pass::run(doc, crate);
    gen::write_markdown(doc, std::io::stdout());
}
<|endoftext|>


<commit_before><commit_msg>Add location to panic handler<commit_after><|endoftext|>


<commit_before><commit_msg>Remove extra read increment in glob branch (#334)<commit_after><|endoftext|>


<commit_before><commit_msg>video.editComment method<commit_after><|endoftext|>


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

trait Trait { }

fn function(t: &mut Trait) {
    t as *mut Trait
 //~^ ERROR: mismatched types:
 //~| expected `()`,
 //~|    found `*mut Trait`
 //~| (expected (),
 //~|    found *-ptr) [E0308]
}

fn main() { }
<|endoftext|>


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

fn main() {}

impl Type {
    undef!() //~ ERROR macro undefined: 'undef!'
}
<|endoftext|>


<commit_before>// error-pattern:get called on error result: "kitty"
fn main() {
  log(error, result::get(result::err::<int,str>("kitty")));
}<commit_msg>Fix a failing test.<commit_after>// error-pattern:get called on error result: ~"kitty"
fn main() {
  log(error, result::get(result::err::<int,str>("kitty")));
}
<|endoftext|>


<commit_before><commit_msg>2019: Add a simple debug logger.<commit_after>use std::fmt;
use std::time;

pub struct Debug {
    start_time: time::Instant,
}

impl Debug {
    pub fn new() -> Self {
        Debug {
            start_time: time::Instant::now(),
        }
    }

    pub fn log<T>(&self, name: &str, value: T) -> T
    where
        T: fmt::Debug,
    {
        println!(
            "[{}s] {} = {:?}",
            self.start_time.elapsed().as_secs(),
            name,
            value
        );
        value
    }
}
<|endoftext|>


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

use version::{try_getting_version, try_getting_local_version,
              Version, NoVersion, split_version};
use std::rt::io::Writer;
use std::hash::Streaming;
use std::hash;

/// Path-fragment identifier of a package such as
/// 'github.com/graydon/test'; path must be a relative
/// path with >=1 component.
#[deriving(Clone)]
pub struct PkgId {
    /// This is a path, on the local filesystem, referring to where the
    /// files for this package live. For example:
    /// github.com/mozilla/quux-whatever (it's assumed that if we're
    /// working with a package ID of this form, rustpkg has already cloned
    /// the sources into a local directory in the RUST_PATH).
    path: Path,
    /// Short name. This is the path's filestem, but we store it
    /// redundantly so as to not call get() everywhere (filestem() returns an
    /// option)
    /// The short name does not need to be a valid Rust identifier.
    /// Users can write: `extern mod foo = "...";` to get around the issue
    /// of package IDs whose short names aren't valid Rust identifiers.
    short_name: ~str,
    /// The requested package version.
    version: Version
}

impl Eq for PkgId {
    fn eq(&self, p: &PkgId) -> bool {
        p.path == self.path && p.version == self.version
    }
}

impl PkgId {
    pub fn new(s: &str) -> PkgId {
        use conditions::bad_pkg_id::cond;

        let mut given_version = None;

        // Did the user request a specific version?
        let s = match split_version(s) {
            Some((path, v)) => {
                debug!("s = %s, path = %s, v = %s", s, path, v.to_str());
                given_version = Some(v);
                path
            }
            None => {
                debug!("%s has no explicit version", s);
                s
            }
        };

        let path = Path(s);
        if path.is_absolute {
            return cond.raise((path, ~"absolute pkgid"));
        }
        if path.components.len() < 1 {
            return cond.raise((path, ~"0-length pkgid"));
        }
        let short_name = path.clone().filestem().expect(fmt!("Strange path! %s", s));

        let version = match given_version {
            Some(v) => v,
            None => match try_getting_local_version(&path) {
                Some(v) => v,
                None => match try_getting_version(&path) {
                    Some(v) => v,
                    None => NoVersion
                }
            }
        };

        debug!("path = %s", path.to_str());
        PkgId {
            path: path,
            short_name: short_name,
            version: version
        }
    }

    pub fn hash(&self) -> ~str {
        fmt!("%s-%s-%s", self.path.to_str(),
             hash(self.path.to_str() + self.version.to_str()),
             self.version.to_str())
    }

    pub fn short_name_with_version(&self) -> ~str {
        fmt!("%s%s", self.short_name, self.version.to_str())
    }

    /// True if the ID has multiple components
    pub fn is_complex(&self) -> bool {
        self.short_name != self.path.to_str()
     }
}

impl ToStr for PkgId {
    fn to_str(&self) -> ~str {
        // should probably use the filestem and not the whole path
        fmt!("%s-%s", self.path.to_str(), self.version.to_str())
    }
}

pub fn write<W: Writer>(writer: &mut W, string: &str) {
    writer.write(string.as_bytes());
}

pub fn hash(data: ~str) -> ~str {
    let hasher = &mut hash::default_state();
    write(hasher, data);
    hasher.result_str()
}
<commit_msg>made Eq for package_id use more standard parameter names<commit_after>// Copyright 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.

use version::{try_getting_version, try_getting_local_version,
              Version, NoVersion, split_version};
use std::rt::io::Writer;
use std::hash::Streaming;
use std::hash;

/// Path-fragment identifier of a package such as
/// 'github.com/graydon/test'; path must be a relative
/// path with >=1 component.
#[deriving(Clone)]
pub struct PkgId {
    /// This is a path, on the local filesystem, referring to where the
    /// files for this package live. For example:
    /// github.com/mozilla/quux-whatever (it's assumed that if we're
    /// working with a package ID of this form, rustpkg has already cloned
    /// the sources into a local directory in the RUST_PATH).
    path: Path,
    /// Short name. This is the path's filestem, but we store it
    /// redundantly so as to not call get() everywhere (filestem() returns an
    /// option)
    /// The short name does not need to be a valid Rust identifier.
    /// Users can write: `extern mod foo = "...";` to get around the issue
    /// of package IDs whose short names aren't valid Rust identifiers.
    short_name: ~str,
    /// The requested package version.
    version: Version
}

impl Eq for PkgId {
    fn eq(&self, other: &PkgId) -> bool {
        self.path == other.path && self.version == other.version
    }
}

impl PkgId {
    pub fn new(s: &str) -> PkgId {
        use conditions::bad_pkg_id::cond;

        let mut given_version = None;

        // Did the user request a specific version?
        let s = match split_version(s) {
            Some((path, v)) => {
                debug!("s = %s, path = %s, v = %s", s, path, v.to_str());
                given_version = Some(v);
                path
            }
            None => {
                debug!("%s has no explicit version", s);
                s
            }
        };

        let path = Path(s);
        if path.is_absolute {
            return cond.raise((path, ~"absolute pkgid"));
        }
        if path.components.len() < 1 {
            return cond.raise((path, ~"0-length pkgid"));
        }
        let short_name = path.clone().filestem().expect(fmt!("Strange path! %s", s));

        let version = match given_version {
            Some(v) => v,
            None => match try_getting_local_version(&path) {
                Some(v) => v,
                None => match try_getting_version(&path) {
                    Some(v) => v,
                    None => NoVersion
                }
            }
        };

        debug!("path = %s", path.to_str());
        PkgId {
            path: path,
            short_name: short_name,
            version: version
        }
    }

    pub fn hash(&self) -> ~str {
        fmt!("%s-%s-%s", self.path.to_str(),
             hash(self.path.to_str() + self.version.to_str()),
             self.version.to_str())
    }

    pub fn short_name_with_version(&self) -> ~str {
        fmt!("%s%s", self.short_name, self.version.to_str())
    }

    /// True if the ID has multiple components
    pub fn is_complex(&self) -> bool {
        self.short_name != self.path.to_str()
     }
}

impl ToStr for PkgId {
    fn to_str(&self) -> ~str {
        // should probably use the filestem and not the whole path
        fmt!("%s-%s", self.path.to_str(), self.version.to_str())
    }
}

pub fn write<W: Writer>(writer: &mut W, string: &str) {
    writer.write(string.as_bytes());
}

pub fn hash(data: ~str) -> ~str {
    let hasher = &mut hash::default_state();
    write(hasher, data);
    hasher.result_str()
}
<|endoftext|>


<commit_before>use quote::{ToTokens, Tokens};
use syn::synom::Synom;
use syn::{Expr, ExprStruct, Ident, Member};

pub struct Metadata {
    pub description: Expr,
    pub method: Expr,
    pub name: Expr,
    pub path: Expr,
    pub rate_limited: Expr,
    pub requires_authentication: Expr,
}

impl From<ExprStruct> for Metadata {
    fn from(expr: ExprStruct) -> Self {
        let mut description = None;
        let mut method = None;
        let mut name = None;
        let mut path = None;
        let mut rate_limited = None;
        let mut requires_authentication = None;

        for field in expr.fields {
            let Member::Named(identifier) = field.member;

            match identifier.as_ref() {
                "description" => description = Some(field.expr),
                "method" => method = Some(field.expr),
                "name" => name = Some(field.expr),
                "path" => path = Some(field.expr),
                "rate_limited" => rate_limited = Some(field.expr),
                "requires_authentication" => requires_authentication = Some(field.expr),
                _ => panic!("ruma_api! metadata included unexpected field"),
            }
        }

        Metadata {
            description: description.expect("ruma_api! `metadata` is missing `description`"),
            method: method.expect("ruma_api! `metadata` is missing `method`"),
            name: name.expect("ruma_api! `metadata` is missing `name`"),
            path: path.expect("ruma_api! `metadata` is missing `path`"),
            rate_limited: rate_limited.expect("ruma_api! `metadata` is missing `rate_limited`"),
            requires_authentication: requires_authentication
                .expect("ruma_api! `metadata` is missing `requires_authentication`"),
        }
    }
}
<commit_msg>Extract relevant types out of the metadata's fields.<commit_after>use quote::{ToTokens, Tokens};
use syn::punctuated::Pair;
use syn::synom::Synom;
use syn::{Expr, ExprStruct, Ident, Lit, Member};

pub struct Metadata {
    pub description: String,
    pub method: String,
    pub name: String,
    pub path: String,
    pub rate_limited: bool,
    pub requires_authentication: bool,
}

impl From<ExprStruct> for Metadata {
    fn from(expr: ExprStruct) -> Self {
        let mut description = None;
        let mut method = None;
        let mut name = None;
        let mut path = None;
        let mut rate_limited = None;
        let mut requires_authentication = None;

        for field in expr.fields {
            let Member::Named(identifier) = field.member;

            match identifier.as_ref() {
                "description" => {
                    let Expr::Lit(expr_lit) = field.expr;
                    let Lit::Str(lit_str) = expr_lit.lit;
                    description = Some(lit_str.value());
                }
                "method" => {
                    let Expr::Path(expr_path) = field.expr;
                    let path = expr_path.path;
                    let segments = path.segments;
                    if segments.len() != 1 {
                        panic!("ruma_api! expects a one component path for `metadata` `method`");
                    }
                    let pair = segments.first().unwrap(); // safe because we just checked
                    let Pair::End(method_name) = pair;
                    method = Some(method_name.ident.to_string());
                }
                "name" => {
                    let Expr::Lit(expr_lit) = field.expr;
                    let Lit::Str(lit_str) = expr_lit.lit;
                    name = Some(lit_str.value());
                }
                "path" => {
                    let Expr::Lit(expr_lit) = field.expr;
                    let Lit::Str(lit_str) = expr_lit.lit;
                    path = Some(lit_str.value());
                }
                "rate_limited" => {
                    let Expr::Lit(expr_lit) = field.expr;
                    let Lit::Bool(lit_bool) = expr_lit.lit;
                    rate_limited = Some(lit_bool.value)
                }
                "requires_authentication" => {
                    let Expr::Lit(expr_lit) = field.expr;
                    let Lit::Bool(lit_bool) = expr_lit.lit;
                    requires_authentication = Some(lit_bool.value)
                }
                _ => panic!("ruma_api! metadata included unexpected field"),
            }
        }

        Metadata {
            description: description.expect("ruma_api! `metadata` is missing `description`"),
            method: method.expect("ruma_api! `metadata` is missing `method`"),
            name: name.expect("ruma_api! `metadata` is missing `name`"),
            path: path.expect("ruma_api! `metadata` is missing `path`"),
            rate_limited: rate_limited.expect("ruma_api! `metadata` is missing `rate_limited`"),
            requires_authentication: requires_authentication
                .expect("ruma_api! `metadata` is missing `requires_authentication`"),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>feat(bench): describe benchmarks<commit_after><|endoftext|>


<commit_before><commit_msg>Improve description and give only a platform independent example for check_path<commit_after><|endoftext|>


<commit_before><commit_msg>switch grid y to height<commit_after><|endoftext|>


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

use std::borrow::Cow;
use std::fmt::Display;
use std::path::Path;
use std::vec::Vec;
use std::rc::Rc;
use std::cell::RefCell;

use dbus;
use dbus::Connection;
use dbus::BusType;
use dbus::Message;
use dbus::MessageItem;
use dbus::NameFlag;
use dbus::arg::Array;
use dbus::arg::IterAppend;
use dbus::tree::Access;
use dbus::tree::EmitsChangedSignal;
use dbus::tree::Factory;
use dbus::tree::MethodErr;
use dbus::tree::MTFn;
use dbus::tree::MethodResult;
use dbus::tree::MethodInfo;
use dbus::tree::PropInfo;
use dbus::tree::Tree;
use dbus::ConnectionItem;

use engine::{Engine, Redundancy};
use stratis::VERSION;

use super::filesystem::create_dbus_filesystem;
use super::blockdev::create_dbus_blockdev;
use super::pool::create_dbus_pool;
use super::types::{ActionQueue, DeferredAction, DbusContext, DbusErrorEnum, TData};
use super::util::STRATIS_BASE_PATH;
use super::util::STRATIS_BASE_SERVICE;
use super::util::code_to_message_items;
use super::util::default_object_path;
use super::util::engine_to_dbus_err;
use super::util::get_next_arg;
use super::util::ok_message_items;
use super::util::tuple_to_option;

fn create_pool(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    let message: &Message = m.msg;
    let mut iter = message.iter_init();

    let name: &str = get_next_arg(&mut iter, 0)?;
    let redundancy: (bool, u16) = get_next_arg(&mut iter, 1)?;
    let force: bool = get_next_arg(&mut iter, 2)?;
    let devs: Array<&str, _> = get_next_arg(&mut iter, 3)?;

    let blockdevs = devs.map(|x| Path::new(x)).collect::<Vec<&Path>>();

    let object_path = m.path.get_name();
    let dbus_context = m.tree.get_data();
    let mut engine = dbus_context.engine.borrow_mut();
    let result = engine.create_pool(name, &blockdevs, tuple_to_option(redundancy), force);

    let return_message = message.method_return();

    let msg = match result {
        Ok(pool_uuid) => {
            let pool_object_path: dbus::Path =
                create_dbus_pool(dbus_context, object_path.clone(), pool_uuid);
            let default_return =
                MessageItem::Struct(vec![MessageItem::ObjectPath(default_object_path()),
                                         MessageItem::Array(vec![], "o".into())]);
            let pool = get_mut_pool!(engine; pool_uuid; default_return; return_message);

            let bd_object_paths = pool.blockdevs()
                .iter()
                .map(|bd| {
                         MessageItem::ObjectPath(create_dbus_blockdev(dbus_context,
                                                                      pool_object_path.clone(),
                                                                      bd.uuid()))
                     })
                .collect::<Vec<_>>();

            let return_path = MessageItem::ObjectPath(pool_object_path);
            let return_list = MessageItem::Array(bd_object_paths, "o".into());
            let return_value = MessageItem::Struct(vec![return_path, return_list]);
            let (rc, rs) = ok_message_items();
            return_message.append3(return_value, rc, rs)
        }
        Err(x) => {
            let return_path = MessageItem::ObjectPath(default_object_path());
            let return_list = MessageItem::Array(vec![], "s".into());
            let return_value = MessageItem::Struct(vec![return_path, return_list]);
            let (rc, rs) = engine_to_dbus_err(&x);
            let (rc, rs) = code_to_message_items(rc, rs);
            return_message.append3(return_value, rc, rs)
        }
    };
    Ok(vec![msg])
}

fn destroy_pool(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {

    let message: &Message = m.msg;
    let mut iter = message.iter_init();

    let object_path: dbus::Path<'static> = get_next_arg(&mut iter, 0)?;

    let dbus_context = m.tree.get_data();

    let default_return = MessageItem::Bool(false);
    let return_message = message.method_return();

    let pool_uuid = match m.tree.get(&object_path) {
        Some(pool_path) => get_data!(pool_path; default_return; return_message).uuid,
        None => {
            let (rc, rs) = ok_message_items();
            return Ok(vec![return_message.append3(default_return, rc, rs)]);
        }
    };

    let msg = match dbus_context.engine.borrow_mut().destroy_pool(pool_uuid) {
        Ok(action) => {
            dbus_context
                .actions
                .borrow_mut()
                .push_remove(object_path);
            let (rc, rs) = ok_message_items();
            return_message.append3(MessageItem::Bool(action), rc, rs)
        }
        Err(err) => {
            let (rc, rs) = engine_to_dbus_err(&err);
            let (rc, rs) = code_to_message_items(rc, rs);
            return_message.append3(default_return, rc, rs)
        }
    };
    Ok(vec![msg])
}

fn get_list_items<T, I>(i: &mut IterAppend, iter: I) -> Result<(), MethodErr>
    where T: Display + Into<u16>,
          I: Iterator<Item = T>
{
    let msg_vec = iter.map(|item| {
                               MessageItem::Struct(vec![MessageItem::Str(format!("{}", item)),
                                                        MessageItem::UInt16(item.into())])
                           })
        .collect::<Vec<MessageItem>>();
    i.append(MessageItem::Array(msg_vec, Cow::Borrowed("(sq)")));
    Ok(())
}

fn get_error_values(i: &mut IterAppend,
                    _p: &PropInfo<MTFn<TData>, TData>)
                    -> Result<(), MethodErr> {
    get_list_items(i, DbusErrorEnum::iter_variants())
}

fn get_redundancy_values(i: &mut IterAppend,
                         _p: &PropInfo<MTFn<TData>, TData>)
                         -> Result<(), MethodErr> {
    get_list_items(i, Redundancy::iter_variants())
}

fn get_version(i: &mut IterAppend, _p: &PropInfo<MTFn<TData>, TData>) -> Result<(), MethodErr> {
    i.append(VERSION);
    Ok(())
}

fn configure_simulator(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    let message = m.msg;
    let mut iter = message.iter_init();

    let denominator: u32 = get_next_arg(&mut iter, 0)?;

    let dbus_context = m.tree.get_data();
    let result = dbus_context
        .engine
        .borrow_mut()
        .configure_simulator(denominator);

    let return_message = message.method_return();

    let msg = match result {
        Ok(_) => {
            let (rc, rs) = ok_message_items();
            return_message.append2(rc, rs)
        }
        Err(err) => {
            let (rc, rs) = engine_to_dbus_err(&err);
            let (rc, rs) = code_to_message_items(rc, rs);
            return_message.append2(rc, rs)
        }
    };
    Ok(vec![msg])
}

fn get_base_tree<'a>(dbus_context: DbusContext) -> (Tree<MTFn<TData>, TData>, dbus::Path<'a>) {

    let f = Factory::new_fn();

    let base_tree = f.tree(dbus_context);

    let create_pool_method = f.method("CreatePool", (), create_pool)
        .in_arg(("name", "s"))
        .in_arg(("redundancy", "(bq)"))
        .in_arg(("force", "b"))
        .in_arg(("devices", "as"))
        .out_arg(("result", "(oao)"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let destroy_pool_method = f.method("DestroyPool", (), destroy_pool)
        .in_arg(("pool", "o"))
        .out_arg(("action", "b"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let configure_simulator_method = f.method("ConfigureSimulator", (), configure_simulator)
        .in_arg(("denominator", "u"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let redundancy_values_property =
        f.property::<Array<(&str, u16), &Iterator<Item = (&str, u16)>>, _>("RedundancyValues", ())
            .access(Access::Read)
            .emits_changed(EmitsChangedSignal::Const)
            .on_get(get_redundancy_values);

    let error_values_property =
        f.property::<Array<(&str, u16), &Iterator<Item = (&str, u16)>>, _>("ErrorValues", ())
            .access(Access::Read)
            .emits_changed(EmitsChangedSignal::Const)
            .on_get(get_error_values);

    let version_property = f.property::<&str, _>("Version", ())
        .access(Access::Read)
        .emits_changed(EmitsChangedSignal::Const)
        .on_get(get_version);

    let interface_name = format!("{}.{}", STRATIS_BASE_SERVICE, "Manager");

    let obj_path = f.object_path(STRATIS_BASE_PATH, None)
        .introspectable()
        .object_manager()
        .add(f.interface(interface_name, ())
                 .add_m(create_pool_method)
                 .add_m(destroy_pool_method)
                 .add_m(configure_simulator_method)
                 .add_p(error_values_property)
                 .add_p(redundancy_values_property)
                 .add_p(version_property));

    let path = obj_path.get_name().to_owned();
    (base_tree.add(obj_path), path)
}

#[allow(type_complexity)]
pub fn connect(engine: Rc<RefCell<Engine>>)
               -> Result<(Connection, Tree<MTFn<TData>, TData>, DbusContext), dbus::Error> {
    let c = Connection::get_private(BusType::System)?;

    let local_engine = Rc::clone(&engine);

    let (mut tree, object_path) = get_base_tree(DbusContext::new(engine));
    let dbus_context = tree.get_data().clone();

    // This should never panic as create_dbus_pool(),
    // create_dbus_filesystem(), and create_dbus_blockdev() do not borrow the
    // engine.
    for pool in local_engine.borrow().pools() {
        let pool_path = create_dbus_pool(&dbus_context, object_path.clone(), pool.uuid());
        for fs_uuid in pool.filesystems().iter().map(|f| f.uuid()) {
            create_dbus_filesystem(&dbus_context, pool_path.clone(), fs_uuid);
        }
        for dev_uuid in pool.blockdevs().iter().map(|bd| bd.uuid()) {
            create_dbus_blockdev(&dbus_context, pool_path.clone(), dev_uuid);
        }
    }

    tree.set_registered(&c, true)?;

    c.register_name(STRATIS_BASE_SERVICE, NameFlag::ReplaceExisting as u32)?;

    process_deferred_actions(&c, &mut tree, &mut dbus_context.actions.borrow_mut())?;

    Ok((c, tree, dbus_context))
}

/// Update the dbus tree with deferred adds and removes.
fn process_deferred_actions(c: &Connection,
                            tree: &mut Tree<MTFn<TData>, TData>,
                            actions: &mut ActionQueue)
                            -> Result<(), dbus::Error> {
    for action in actions.drain() {
        match action {
            DeferredAction::Add(path) => {
                c.register_object_path(path.get_name())?;
                tree.insert(path);
            }
            DeferredAction::Remove(path) => {
                c.unregister_object_path(&path);
                tree.remove(&path);
            }
        }
    }
    Ok(())
}

pub fn handle(c: &Connection,
              item: &ConnectionItem,
              tree: &mut Tree<MTFn<TData>, TData>,
              dbus_context: &DbusContext)
              -> Result<(), dbus::Error> {
    if let ConnectionItem::MethodCall(ref msg) = *item {
        if let Some(v) = tree.handle(msg) {
            // Probably the wisest is to ignore any send errors here -
            // maybe the remote has disconnected during our processing.
            for m in v {
                let _ = c.send(m);
            }
        }

        process_deferred_actions(c, tree, &mut dbus_context.actions.borrow_mut())?;
    }

    Ok(())
}
<commit_msg>Remove obsoleted constants<commit_after>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use std::path::Path;
use std::vec::Vec;
use std::rc::Rc;
use std::cell::RefCell;

use dbus;
use dbus::Connection;
use dbus::BusType;
use dbus::Message;
use dbus::MessageItem;
use dbus::NameFlag;
use dbus::arg::Array;
use dbus::arg::IterAppend;
use dbus::tree::Access;
use dbus::tree::EmitsChangedSignal;
use dbus::tree::Factory;
use dbus::tree::MethodErr;
use dbus::tree::MTFn;
use dbus::tree::MethodResult;
use dbus::tree::MethodInfo;
use dbus::tree::PropInfo;
use dbus::tree::Tree;
use dbus::ConnectionItem;

use engine::Engine;
use stratis::VERSION;

use super::filesystem::create_dbus_filesystem;
use super::blockdev::create_dbus_blockdev;
use super::pool::create_dbus_pool;
use super::types::{ActionQueue, DeferredAction, DbusContext, DbusErrorEnum, TData};
use super::util::STRATIS_BASE_PATH;
use super::util::STRATIS_BASE_SERVICE;
use super::util::code_to_message_items;
use super::util::default_object_path;
use super::util::engine_to_dbus_err;
use super::util::get_next_arg;
use super::util::ok_message_items;
use super::util::tuple_to_option;

fn create_pool(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    let message: &Message = m.msg;
    let mut iter = message.iter_init();

    let name: &str = get_next_arg(&mut iter, 0)?;
    let redundancy: (bool, u16) = get_next_arg(&mut iter, 1)?;
    let force: bool = get_next_arg(&mut iter, 2)?;
    let devs: Array<&str, _> = get_next_arg(&mut iter, 3)?;

    let blockdevs = devs.map(|x| Path::new(x)).collect::<Vec<&Path>>();

    let object_path = m.path.get_name();
    let dbus_context = m.tree.get_data();
    let mut engine = dbus_context.engine.borrow_mut();
    let result = engine.create_pool(name, &blockdevs, tuple_to_option(redundancy), force);

    let return_message = message.method_return();

    let msg = match result {
        Ok(pool_uuid) => {
            let pool_object_path: dbus::Path =
                create_dbus_pool(dbus_context, object_path.clone(), pool_uuid);
            let default_return =
                MessageItem::Struct(vec![MessageItem::ObjectPath(default_object_path()),
                                         MessageItem::Array(vec![], "o".into())]);
            let pool = get_mut_pool!(engine; pool_uuid; default_return; return_message);

            let bd_object_paths = pool.blockdevs()
                .iter()
                .map(|bd| {
                         MessageItem::ObjectPath(create_dbus_blockdev(dbus_context,
                                                                      pool_object_path.clone(),
                                                                      bd.uuid()))
                     })
                .collect::<Vec<_>>();

            let return_path = MessageItem::ObjectPath(pool_object_path);
            let return_list = MessageItem::Array(bd_object_paths, "o".into());
            let return_value = MessageItem::Struct(vec![return_path, return_list]);
            let (rc, rs) = ok_message_items();
            return_message.append3(return_value, rc, rs)
        }
        Err(x) => {
            let return_path = MessageItem::ObjectPath(default_object_path());
            let return_list = MessageItem::Array(vec![], "s".into());
            let return_value = MessageItem::Struct(vec![return_path, return_list]);
            let (rc, rs) = engine_to_dbus_err(&x);
            let (rc, rs) = code_to_message_items(rc, rs);
            return_message.append3(return_value, rc, rs)
        }
    };
    Ok(vec![msg])
}

fn destroy_pool(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {

    let message: &Message = m.msg;
    let mut iter = message.iter_init();

    let object_path: dbus::Path<'static> = get_next_arg(&mut iter, 0)?;

    let dbus_context = m.tree.get_data();

    let default_return = MessageItem::Bool(false);
    let return_message = message.method_return();

    let pool_uuid = match m.tree.get(&object_path) {
        Some(pool_path) => get_data!(pool_path; default_return; return_message).uuid,
        None => {
            let (rc, rs) = ok_message_items();
            return Ok(vec![return_message.append3(default_return, rc, rs)]);
        }
    };

    let msg = match dbus_context.engine.borrow_mut().destroy_pool(pool_uuid) {
        Ok(action) => {
            dbus_context
                .actions
                .borrow_mut()
                .push_remove(object_path);
            let (rc, rs) = ok_message_items();
            return_message.append3(MessageItem::Bool(action), rc, rs)
        }
        Err(err) => {
            let (rc, rs) = engine_to_dbus_err(&err);
            let (rc, rs) = code_to_message_items(rc, rs);
            return_message.append3(default_return, rc, rs)
        }
    };
    Ok(vec![msg])
}

fn get_version(i: &mut IterAppend, _p: &PropInfo<MTFn<TData>, TData>) -> Result<(), MethodErr> {
    i.append(VERSION);
    Ok(())
}

fn configure_simulator(m: &MethodInfo<MTFn<TData>, TData>) -> MethodResult {
    let message = m.msg;
    let mut iter = message.iter_init();

    let denominator: u32 = get_next_arg(&mut iter, 0)?;

    let dbus_context = m.tree.get_data();
    let result = dbus_context
        .engine
        .borrow_mut()
        .configure_simulator(denominator);

    let return_message = message.method_return();

    let msg = match result {
        Ok(_) => {
            let (rc, rs) = ok_message_items();
            return_message.append2(rc, rs)
        }
        Err(err) => {
            let (rc, rs) = engine_to_dbus_err(&err);
            let (rc, rs) = code_to_message_items(rc, rs);
            return_message.append2(rc, rs)
        }
    };
    Ok(vec![msg])
}

fn get_base_tree<'a>(dbus_context: DbusContext) -> (Tree<MTFn<TData>, TData>, dbus::Path<'a>) {

    let f = Factory::new_fn();

    let base_tree = f.tree(dbus_context);

    let create_pool_method = f.method("CreatePool", (), create_pool)
        .in_arg(("name", "s"))
        .in_arg(("redundancy", "(bq)"))
        .in_arg(("force", "b"))
        .in_arg(("devices", "as"))
        .out_arg(("result", "(oao)"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let destroy_pool_method = f.method("DestroyPool", (), destroy_pool)
        .in_arg(("pool", "o"))
        .out_arg(("action", "b"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let configure_simulator_method = f.method("ConfigureSimulator", (), configure_simulator)
        .in_arg(("denominator", "u"))
        .out_arg(("return_code", "q"))
        .out_arg(("return_string", "s"));

    let version_property = f.property::<&str, _>("Version", ())
        .access(Access::Read)
        .emits_changed(EmitsChangedSignal::Const)
        .on_get(get_version);

    let interface_name = format!("{}.{}", STRATIS_BASE_SERVICE, "Manager");

    let obj_path = f.object_path(STRATIS_BASE_PATH, None)
        .introspectable()
        .object_manager()
        .add(f.interface(interface_name, ())
                 .add_m(create_pool_method)
                 .add_m(destroy_pool_method)
                 .add_m(configure_simulator_method)
                 .add_p(version_property));

    let path = obj_path.get_name().to_owned();
    (base_tree.add(obj_path), path)
}

#[allow(type_complexity)]
pub fn connect(engine: Rc<RefCell<Engine>>)
               -> Result<(Connection, Tree<MTFn<TData>, TData>, DbusContext), dbus::Error> {
    let c = Connection::get_private(BusType::System)?;

    let local_engine = Rc::clone(&engine);

    let (mut tree, object_path) = get_base_tree(DbusContext::new(engine));
    let dbus_context = tree.get_data().clone();

    // This should never panic as create_dbus_pool(),
    // create_dbus_filesystem(), and create_dbus_blockdev() do not borrow the
    // engine.
    for pool in local_engine.borrow().pools() {
        let pool_path = create_dbus_pool(&dbus_context, object_path.clone(), pool.uuid());
        for fs_uuid in pool.filesystems().iter().map(|f| f.uuid()) {
            create_dbus_filesystem(&dbus_context, pool_path.clone(), fs_uuid);
        }
        for dev_uuid in pool.blockdevs().iter().map(|bd| bd.uuid()) {
            create_dbus_blockdev(&dbus_context, pool_path.clone(), dev_uuid);
        }
    }

    tree.set_registered(&c, true)?;

    c.register_name(STRATIS_BASE_SERVICE, NameFlag::ReplaceExisting as u32)?;

    process_deferred_actions(&c, &mut tree, &mut dbus_context.actions.borrow_mut())?;

    Ok((c, tree, dbus_context))
}

/// Update the dbus tree with deferred adds and removes.
fn process_deferred_actions(c: &Connection,
                            tree: &mut Tree<MTFn<TData>, TData>,
                            actions: &mut ActionQueue)
                            -> Result<(), dbus::Error> {
    for action in actions.drain() {
        match action {
            DeferredAction::Add(path) => {
                c.register_object_path(path.get_name())?;
                tree.insert(path);
            }
            DeferredAction::Remove(path) => {
                c.unregister_object_path(&path);
                tree.remove(&path);
            }
        }
    }
    Ok(())
}

pub fn handle(c: &Connection,
              item: &ConnectionItem,
              tree: &mut Tree<MTFn<TData>, TData>,
              dbus_context: &DbusContext)
              -> Result<(), dbus::Error> {
    if let ConnectionItem::MethodCall(ref msg) = *item {
        if let Some(v) = tree.handle(msg) {
            // Probably the wisest is to ignore any send errors here -
            // maybe the remote has disconnected during our processing.
            for m in v {
                let _ = c.send(m);
            }
        }

        process_deferred_actions(c, tree, &mut dbus_context.actions.borrow_mut())?;
    }

    Ok(())
}
<|endoftext|>


<commit_before><commit_msg>(doc) This addresses issue 319 to describe the threading model used by the Hyper library.<commit_after><|endoftext|>


<commit_before><commit_msg>euler 6<commit_after>// The sum of the squares of the first ten natural numbers is 385
// The square of the sum of the first ten natural numbers is 3025
// Hence the difference between the sum of the squares of the first ten natural numbers and the
// square of the sum is 3025 − 385 = 2640.
// Find the difference between the sum of the squares of the first one hundred natural numbers and
// the square of the sum.

fn main() {
    println!("{}", (1u64..101).fold(0, |sum, acc| sum + acc).pow(2) - (1u64..101).map(|n| n.pow(2)).fold(0, |sum, acc| sum + acc));
}<|endoftext|>


<commit_before><commit_msg>Improve the shell output<commit_after><|endoftext|>


<commit_before><commit_msg>remove: unused import<commit_after><|endoftext|>


<commit_before>use std::collections::BTreeMap;
use std::string::String;
use std::vec::Vec;
use std::boxed::Box;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::env;
use std::process;

use self::to_num::ToNum;
use self::input_editor::readln;
use self::tokenizer::{Token, tokenize};
use self::expansion::expand_tokens;
use self::parser::{parse, Job};

pub mod builtin;
pub mod to_num;
pub mod input_editor;
pub mod tokenizer;
pub mod parser;
pub mod expansion;

/// Structure which represents a Terminal's command.
/// This command structure contains a name, and the code which run the
/// functionnality associated to this one, with zero, one or several argument(s).
/// # Example
/// ```
/// let my_command = Command {
///     name: "my_command",
///     help: "Describe what my_command does followed by a newline showing usage",
///     main: box|args: &Vec<String>| {
///         println!("Say 'hello' to my command! :-D");
///     }
/// }
/// ```
pub struct Command {
    pub name: &'static str,
    pub help: &'static str,
    pub main: Box<Fn(&Vec<String>, &mut BTreeMap<String, String>, &mut Vec<Mode>)>,
}

/// This struct will contain all of the data structures related to this
/// instance of the shell.
pub struct Shell<'a> {
    pub variables: &'a mut BTreeMap<String, String>,
    pub mode: &'a mut Vec<Mode>,
}

impl Command {
    /// Return the map from command names to commands
    pub fn map() -> BTreeMap<String, Self> {
        let mut commands: BTreeMap<String, Self> = BTreeMap::new();

        commands.insert("cat".to_string(),
                        Command {
                            name: "cat",
                            help: "To display a file in the output\n    cat <your_file>",
                            main: Box::new(|args: &Vec<String>,
                                            _: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {
                                builtin::cat(args);
                            }),
                        });

        commands.insert("cd".to_string(),
                        Command {
                            name: "cd",
                            help: "To change the current directory\n    cd <your_destination>",
                            main: Box::new(|args: &Vec<String>,
                                            _: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {
                                builtin::cd(args);
                            }),
                        });

        commands.insert("echo".to_string(),
                        Command {
                            name: "echo",
                            help: "To display some text in the output\n    echo Hello world!",
                            main: Box::new(|args: &Vec<String>,
                                            _: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {
                                builtin::echo(args);
                            }),
                        });

        commands.insert("exit".to_string(),
                        Command {
                            name: "exit",
                            help: "To exit the curent session",
                            main: Box::new(|_: &Vec<String>,
                                            _: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {}),
                        });

        commands.insert("free".to_string(),
                        Command {
                            name: "free",
                            help: "Show memory information\n    free",
                            main: Box::new(|_: &Vec<String>,
                                            _: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {
                                builtin::free();
                            }),
                        });

        commands.insert("ls".to_string(),
                        Command {
                            name: "ls",
                            help: "To list the content of the current directory\n    ls",
                            main: Box::new(|args: &Vec<String>,
                                            _: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {
                                builtin::ls(args);
                            }),
                        });

        commands.insert("mkdir".to_string(),
                        Command {
                            name: "mkdir",
                            help: "To create a directory in the current directory\n    mkdir \
                                   <my_new_directory>",
                            main: Box::new(|args: &Vec<String>,
                                            _: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {
                                builtin::mkdir(args);
                            }),
                        });

        commands.insert("poweroff".to_string(),
                        Command {
                            name: "poweroff",
                            help: "poweroff utility has the machine remove power, if \
                                   possible\n\tpoweroff",
                            main: Box::new(|_: &Vec<String>,
                                            _: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {
                                builtin::poweroff();
                            }),
                        });

        commands.insert("ps".to_string(),
                        Command {
                            name: "ps",
                            help: "Show process list\n    ps",
                            main: Box::new(|_: &Vec<String>,
                                            _: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {
                                builtin::ps();
                            }),
                        });

        commands.insert("pwd".to_string(),
                        Command {
                            name: "pwd",
                            help: "To output the path of the current directory\n    pwd",
                            main: Box::new(|_: &Vec<String>,
                                            _: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {
                                builtin::pwd();
                            }),
                        });

        commands.insert("read".to_string(),
                        Command {
                            name: "read",
                            help: "To read some variables\n    read <my_variable>",
                            main: Box::new(|args: &Vec<String>,
                                            variables: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {
                                builtin::read(args, variables);
                            }),
                        });

        commands.insert("rm".to_string(),
                        Command {
                            name: "rm",
                            help: "Remove a file\n    rm <file>",
                            main: Box::new(|args: &Vec<String>,
                                            _: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {
                                builtin::rm(args);
                            }),
                        });

        commands.insert("rmdir".to_string(),
                        Command {
                            name: "rmdir",
                            help: "Remove a directory\n    rmdir <directory>",
                            main: Box::new(|args: &Vec<String>,
                                            _: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {
                                builtin::rmdir(args);
                            }),
                        });

        commands.insert("run".to_string(),
                        Command {
                            name: "run",
                            help: "Run a script\n    run <script>",
                            main: Box::new(|args: &Vec<String>,
                                            variables: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {
                                builtin::run(args, variables);
                            }),
                        });

        commands.insert("sleep".to_string(),
                        Command {
                            name: "sleep",
                            help: "Make a sleep in the current session\n    sleep \
                                   <number_of_seconds>",
                            main: Box::new(|args: &Vec<String>,
                                            _: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {
                                builtin::sleep(args);
                            }),
                        });

        // Simple command to create a file, in the current directory
        // The file has got the name given as the first argument of the command
        // If the command have no arguments, the command don't create the file
        commands.insert("touch".to_string(),
                        Command {
                            name: "touch",
                            help: "To create a file, in the current directory\n    touch <my_file>",
                            main: Box::new(|args: &Vec<String>,
                                            _: &mut BTreeMap<String, String>,
                                            _: &mut Vec<Mode>| {
                                builtin::touch(args);
                            }),
                        });

        // TODO: Someone should implement FromIterator for HashMap before
        //       changing the type back to HashMap
        let command_helper: BTreeMap<String, String> = commands.iter()
                                                               .map(|(k, v)| {
                                                                   (k.to_string(),
                                                                    v.help.to_string())
                                                               })
                                                               .collect();

        commands.insert("help".to_string(),
                        Command {
                            name: "help",
                            help: "Display a little helper for a given command\n    help ls",
                            main: Box::new(move |args: &Vec<String>,
                                                 _: &mut BTreeMap<String, String>,
                                                 _: &mut Vec<Mode>| {
                                if let Some(command) = args.get(1) {
                                    if command_helper.contains_key(command) {
                                        match command_helper.get(command) {
                                            Some(help) => println!("{}", help),
                                            None => {
                                                println!("Command helper not found [run 'help']...")
                                            }
                                        }
                                    } else {
                                        println!("Command helper not found [run 'help']...");
                                    }
                                } else {
                                    for (command, _help) in command_helper.iter() {
                                        println!("{}", command);
                                    }
                                }
                            }),
                        });

        commands
    }
}

pub struct Mode {
    value: bool,
}

fn on_command(command_string: &str,
              commands: &BTreeMap<String, Command>,
              variables: &mut BTreeMap<String, String>,
              modes: &mut Vec<Mode>) {
    // Show variables
    if command_string == "$" {
        for (key, value) in variables.iter() {
            println!("{}={}", key, value);
        }
        return;
    }

    let mut tokens: Vec<Token> = expand_tokens(&mut tokenize(command_string), variables);
    let jobs: Vec<Job> = parse(&mut tokens);

    // Execute commands
    for job in jobs.iter() {
        if job.command == "if" {
            let mut value = false;

            if let Some(left) = job.args.get(0) {
                if let Some(cmp) = job.args.get(1) {
                    if let Some(right) = job.args.get(2) {
                        if cmp == "==" {
                            value = *left == *right;
                        } else if cmp == "!=" {
                            value = *left != *right;
                        } else if cmp == ">" {
                            value = left.to_num_signed() > right.to_num_signed();
                        } else if cmp == ">=" {
                            value = left.to_num_signed() >= right.to_num_signed();
                        } else if cmp == "<" {
                            value = left.to_num_signed() < right.to_num_signed();
                        } else if cmp == "<=" {
                            value = left.to_num_signed() <= right.to_num_signed();
                        } else {
                            println!("Unknown comparison: {}", cmp);
                        }
                    } else {
                        println!("No right hand side");
                    }
                } else {
                    println!("No comparison operator");
                }
            } else {
                println!("No left hand side");
            }

            modes.insert(0, Mode { value: value });
            continue;
        }

        if job.command == "else" {
            let mut syntax_error = false;
            match modes.get_mut(0) {
                Some(mode) => mode.value = !mode.value,
                None => syntax_error = true,
            }
            if syntax_error {
                println!("Syntax error: else found with no previous if");
            }
            continue;
        }

        if job.command == "fi" {
            let mut syntax_error = false;
            if !modes.is_empty() {
                modes.remove(0);
            } else {
                syntax_error = true;
            }
            if syntax_error {
                println!("Syntax error: fi found with no previous if");
            }
            continue;
        }

        let mut skipped: bool = false;
        for mode in modes.iter() {
            if !mode.value {
                skipped = true;
                break;
            }
        }
        if skipped {
            continue;
        }

        // Set variables
        if let Some(i) = job.command.find('=') {
            let name = job.command[0..i].trim();
            let mut value = job.command[i + 1..job.command.len()].trim().to_string();

            for i in 0..job.args.len() {
                if let Some(arg) = job.args.get(i) {
                    value = value + " " + &arg;
                }
            }

            set_var(variables, name, &value);
            continue;
        }

        // Commands
        let mut args = job.args.clone();
        args.insert(0, job.command.clone());
        if let Some(command) = commands.get(&job.command) {
            (*command.main)(&args, variables, modes);
        } else {
            run_external_commmand(args, variables);
        }
    }
}

pub fn set_var(variables: &mut BTreeMap<String, String>, name: &str, value: &str) {
    if name.is_empty() {
        return;
    }

    if value.is_empty() {
        variables.remove(&name.to_string());
    } else {
        variables.insert(name.to_string(), value.to_string());
    }
}

fn print_prompt(modes: &Vec<Mode>) {
    for mode in modes.iter().rev() {
        if mode.value {
            print!("+ ");
        } else {
            print!("- ");
        }
    }

    let cwd = match env::current_dir() {
        Ok(path) => {
            match path.to_str() {
                Some(path_str) => path_str.to_string(),
                None => "?".to_string(),
            }
        }
        Err(_) => "?".to_string(),
    };

    print!("ion:{}# ", cwd);
    if let Err(message) = stdout().flush() {
        println!("{}: failed to flush prompt to stdout", message);
    }
}

fn run_external_commmand(args: Vec<String>, variables: &mut BTreeMap<String, String>) {
    if let Some(path) = args.get(0) {
        let mut command = process::Command::new(path);
        for i in 1..args.len() {
            if let Some(arg) = args.get(i) {
                command.arg(arg);
            }
        }
        match command.spawn() {
            Ok(mut child) => {
                match child.wait() {
                    Ok(status) => {
                        if let Some(code) = status.code() {
                            set_var(variables, "?", &format!("{}", code));
                        } else {
                            println!("{}: No child exit code", path);
                        }
                    }
                    Err(err) => println!("{}: Failed to wait: {}", path, err),
                }
            }
            Err(err) => println!("{}: Failed to execute: {}", path, err),
        }
    }
}

fn main() {
    let commands = Command::map();
    let mut variables: BTreeMap<String, String> = BTreeMap::new();
    let mut modes: Vec<Mode> = vec![];

    for arg in env::args().skip(1) {
        let mut command_list = String::new();
        if let Ok(mut file) = File::open(&arg) {
            if let Err(message) = file.read_to_string(&mut command_list) {
                println!("{}: Failed to read {}", message, arg);
            }
        }
        on_command(&command_list, &commands, &mut variables, &mut modes);

        return;
    }

    loop {

        print_prompt(&modes);

        if let Some(command_original) = readln() {
            let command = command_original.trim();
            if command == "exit" {
                break;
            } else if !command.is_empty() {
                on_command(&command, &commands, &mut variables, &mut modes);
            }
        } else {
            break;
        }
    }
}
<commit_msg>Make builtins hashmap closures take shell as param<commit_after>use std::collections::BTreeMap;
use std::string::String;
use std::vec::Vec;
use std::boxed::Box;
use std::fs::File;
use std::io::{stdout, Read, Write};
use std::env;
use std::process;

use self::to_num::ToNum;
use self::input_editor::readln;
use self::tokenizer::{Token, tokenize};
use self::expansion::expand_tokens;
use self::parser::{parse, Job};

pub mod builtin;
pub mod to_num;
pub mod input_editor;
pub mod tokenizer;
pub mod parser;
pub mod expansion;

/// Structure which represents a Terminal's command.
/// This command structure contains a name, and the code which run the
/// functionnality associated to this one, with zero, one or several argument(s).
/// # Example
/// ```
/// let my_command = Command {
///     name: "my_command",
///     help: "Describe what my_command does followed by a newline showing usage",
///     main: box|args: &Vec<String>| {
///         println!("Say 'hello' to my command! :-D");
///     }
/// }
/// ```
pub struct Command {
    pub name: &'static str,
    pub help: &'static str,
    pub main: Box<Fn(&Vec<String>, &mut Shell)>,
}

/// This struct will contain all of the data structures related to this
/// instance of the shell.
pub struct Shell<'a> {
    pub variables: &'a mut BTreeMap<String, String>,
    pub modes: &'a mut Vec<Mode>,
}

impl Command {
    /// Return the map from command names to commands
    pub fn map() -> BTreeMap<String, Self> {
        let mut commands: BTreeMap<String, Self> = BTreeMap::new();

        commands.insert("cat".to_string(),
                        Command {
                            name: "cat",
                            help: "To display a file in the output\n    cat <your_file>",
                            main: Box::new(|args: &Vec<String>, _: &mut Shell| {
                                builtin::cat(args);
                            }),
                        });

        commands.insert("cd".to_string(),
                        Command {
                            name: "cd",
                            help: "To change the current directory\n    cd <your_destination>",
                            main: Box::new(|args: &Vec<String>, _: &mut Shell| {
                                builtin::cd(args);
                            }),
                        });

        commands.insert("echo".to_string(),
                        Command {
                            name: "echo",
                            help: "To display some text in the output\n    echo Hello world!",
                            main: Box::new(|args: &Vec<String>, _: &mut Shell| {
                                builtin::echo(args);
                            }),
                        });

        commands.insert("exit".to_string(),
                        Command {
                            name: "exit",
                            help: "To exit the curent session",
                            main: Box::new(|_: &Vec<String>, _: &mut Shell| {}),
                        });

        commands.insert("free".to_string(),
                        Command {
                            name: "free",
                            help: "Show memory information\n    free",
                            main: Box::new(|_: &Vec<String>, _: &mut Shell| {
                                builtin::free();
                            }),
                        });

        commands.insert("ls".to_string(),
                        Command {
                            name: "ls",
                            help: "To list the content of the current directory\n    ls",
                            main: Box::new(|args: &Vec<String>, _: &mut Shell| {
                                builtin::ls(args);
                            }),
                        });

        commands.insert("mkdir".to_string(),
                        Command {
                            name: "mkdir",
                            help: "To create a directory in the current directory\n    mkdir \
                                   <my_new_directory>",
                            main: Box::new(|args: &Vec<String>, _: &mut Shell| {
                                builtin::mkdir(args);
                            }),
                        });

        commands.insert("poweroff".to_string(),
                        Command {
                            name: "poweroff",
                            help: "poweroff utility has the machine remove power, if \
                                   possible\n\tpoweroff",
                            main: Box::new(|_: &Vec<String>, _: &mut Shell| {
                                builtin::poweroff();
                            }),
                        });

        commands.insert("ps".to_string(),
                        Command {
                            name: "ps",
                            help: "Show process list\n    ps",
                            main: Box::new(|_: &Vec<String>, _: &mut Shell| {
                                builtin::ps();
                            }),
                        });

        commands.insert("pwd".to_string(),
                        Command {
                            name: "pwd",
                            help: "To output the path of the current directory\n    pwd",
                            main: Box::new(|_: &Vec<String>, _: &mut Shell| {
                                builtin::pwd();
                            }),
                        });

        commands.insert("read".to_string(),
                        Command {
                            name: "read",
                            help: "To read some variables\n    read <my_variable>",
                            main: Box::new(|args: &Vec<String>, shell: &mut Shell| {
                                builtin::read(args, shell.variables);
                            }),
                        });

        commands.insert("rm".to_string(),
                        Command {
                            name: "rm",
                            help: "Remove a file\n    rm <file>",
                            main: Box::new(|args: &Vec<String>, _: &mut Shell| {
                                builtin::rm(args);
                            }),
                        });

        commands.insert("rmdir".to_string(),
                        Command {
                            name: "rmdir",
                            help: "Remove a directory\n    rmdir <directory>",
                            main: Box::new(|args: &Vec<String>, _: &mut Shell| {
                                builtin::rmdir(args);
                            }),
                        });

        commands.insert("run".to_string(),
                        Command {
                            name: "run",
                            help: "Run a script\n    run <script>",
                            main: Box::new(|args: &Vec<String>, shell: &mut Shell| {
                                builtin::run(args, shell.variables);
                            }),
                        });

        commands.insert("sleep".to_string(),
                        Command {
                            name: "sleep",
                            help: "Make a sleep in the current session\n    sleep \
                                   <number_of_seconds>",
                            main: Box::new(|args: &Vec<String>, _: &mut Shell| {
                                builtin::sleep(args);
                            }),
                        });

        // Simple command to create a file, in the current directory
        // The file has got the name given as the first argument of the command
        // If the command have no arguments, the command don't create the file
        commands.insert("touch".to_string(),
                        Command {
                            name: "touch",
                            help: "To create a file, in the current directory\n    touch <my_file>",
                            main: Box::new(|args: &Vec<String>, _: &mut Shell| {
                                builtin::touch(args);
                            }),
                        });

        // TODO: Someone should implement FromIterator for HashMap before
        //       changing the type back to HashMap
        let command_helper: BTreeMap<String, String> = commands.iter()
                                                               .map(|(k, v)| {
                                                                   (k.to_string(),
                                                                    v.help.to_string())
                                                               })
                                                               .collect();

        commands.insert("help".to_string(),
                        Command {
                            name: "help",
                            help: "Display a little helper for a given command\n    help ls",
                            main: Box::new(move |args: &Vec<String>, _: &mut Shell| {
                                if let Some(command) = args.get(1) {
                                    if command_helper.contains_key(command) {
                                        match command_helper.get(command) {
                                            Some(help) => println!("{}", help),
                                            None => {
                                                println!("Command helper not found [run 'help']...")
                                            }
                                        }
                                    } else {
                                        println!("Command helper not found [run 'help']...");
                                    }
                                } else {
                                    for (command, _help) in command_helper.iter() {
                                        println!("{}", command);
                                    }
                                }
                            }),
                        });

        commands
    }
}

pub struct Mode {
    value: bool,
}

fn on_command(command_string: &str, commands: &BTreeMap<String, Command>, shell: &mut Shell) {
    // Show variables
    if command_string == "$" {
        for (key, value) in shell.variables.iter() {
            println!("{}={}", key, value);
        }
        return;
    }

    let mut tokens: Vec<Token> = expand_tokens(&mut tokenize(command_string), shell.variables);
    let jobs: Vec<Job> = parse(&mut tokens);

    // Execute commands
    for job in jobs.iter() {
        if job.command == "if" {
            let mut value = false;

            if let Some(left) = job.args.get(0) {
                if let Some(cmp) = job.args.get(1) {
                    if let Some(right) = job.args.get(2) {
                        if cmp == "==" {
                            value = *left == *right;
                        } else if cmp == "!=" {
                            value = *left != *right;
                        } else if cmp == ">" {
                            value = left.to_num_signed() > right.to_num_signed();
                        } else if cmp == ">=" {
                            value = left.to_num_signed() >= right.to_num_signed();
                        } else if cmp == "<" {
                            value = left.to_num_signed() < right.to_num_signed();
                        } else if cmp == "<=" {
                            value = left.to_num_signed() <= right.to_num_signed();
                        } else {
                            println!("Unknown comparison: {}", cmp);
                        }
                    } else {
                        println!("No right hand side");
                    }
                } else {
                    println!("No comparison operator");
                }
            } else {
                println!("No left hand side");
            }

            shell.modes.insert(0, Mode { value: value });
            continue;
        }

        if job.command == "else" {
            let mut syntax_error = false;
            match shell.modes.get_mut(0) {
                Some(mode) => mode.value = !mode.value,
                None => syntax_error = true,
            }
            if syntax_error {
                println!("Syntax error: else found with no previous if");
            }
            continue;
        }

        if job.command == "fi" {
            let mut syntax_error = false;
            if !shell.modes.is_empty() {
                shell.modes.remove(0);
            } else {
                syntax_error = true;
            }
            if syntax_error {
                println!("Syntax error: fi found with no previous if");
            }
            continue;
        }

        let mut skipped: bool = false;
        for mode in shell.modes.iter() {
            if !mode.value {
                skipped = true;
                break;
            }
        }
        if skipped {
            continue;
        }

        // Set variables
        if let Some(i) = job.command.find('=') {
            let name = job.command[0..i].trim();
            let mut value = job.command[i + 1..job.command.len()].trim().to_string();

            for i in 0..job.args.len() {
                if let Some(arg) = job.args.get(i) {
                    value = value + " " + &arg;
                }
            }

            set_var(shell.variables, name, &value);
            continue;
        }

        // Commands
        let mut args = job.args.clone();
        args.insert(0, job.command.clone());
        if let Some(command) = commands.get(&job.command) {
            (*command.main)(&args, shell);
        } else {
            run_external_commmand(args, shell.variables);
        }
    }
}

pub fn set_var(variables: &mut BTreeMap<String, String>, name: &str, value: &str) {
    if name.is_empty() {
        return;
    }

    if value.is_empty() {
        variables.remove(&name.to_string());
    } else {
        variables.insert(name.to_string(), value.to_string());
    }
}

fn print_prompt(modes: &Vec<Mode>) {
    for mode in modes.iter().rev() {
        if mode.value {
            print!("+ ");
        } else {
            print!("- ");
        }
    }

    let cwd = match env::current_dir() {
        Ok(path) => {
            match path.to_str() {
                Some(path_str) => path_str.to_string(),
                None => "?".to_string(),
            }
        }
        Err(_) => "?".to_string(),
    };

    print!("ion:{}# ", cwd);
    if let Err(message) = stdout().flush() {
        println!("{}: failed to flush prompt to stdout", message);
    }
}

fn run_external_commmand(args: Vec<String>, variables: &mut BTreeMap<String, String>) {
    if let Some(path) = args.get(0) {
        let mut command = process::Command::new(path);
        for i in 1..args.len() {
            if let Some(arg) = args.get(i) {
                command.arg(arg);
            }
        }
        match command.spawn() {
            Ok(mut child) => {
                match child.wait() {
                    Ok(status) => {
                        if let Some(code) = status.code() {
                            set_var(variables, "?", &format!("{}", code));
                        } else {
                            println!("{}: No child exit code", path);
                        }
                    }
                    Err(err) => println!("{}: Failed to wait: {}", path, err),
                }
            }
            Err(err) => println!("{}: Failed to execute: {}", path, err),
        }
    }
}

fn main() {
    let commands = Command::map();
    let mut shell = Shell {
        variables: &mut BTreeMap::new(),
        modes: &mut vec![],
    };

    for arg in env::args().skip(1) {
        let mut command_list = String::new();
        if let Ok(mut file) = File::open(&arg) {
            if let Err(message) = file.read_to_string(&mut command_list) {
                println!("{}: Failed to read {}", message, arg);
            }
        }
        on_command(&command_list, &commands, &mut shell);

        return;
    }

    loop {

        print_prompt(&shell.modes);

        if let Some(command_original) = readln() {
            let command = command_original.trim();
            if command == "exit" {
                break;
            } else if !command.is_empty() {
                on_command(&command, &commands, &mut shell);
            }
        } else {
            break;
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>set_right_child()<commit_after><|endoftext|>


<commit_before><commit_msg>Simple time<commit_after><|endoftext|>


<commit_before><commit_msg>Add support for compiler flags in plugin<commit_after><|endoftext|>


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

#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "alloc_system"]
#![crate_type = "rlib"]
#![no_std]
#![cfg_attr(not(stage0), allocator)]
#![unstable(feature = "alloc_system",
            reason = "this library is unlikely to be stabilized in its current \
                      form or name",
            issue = "27783")]
#![feature(allocator)]
#![feature(asm)]
#![feature(staged_api)]

// The minimum alignment guaranteed by the architecture. This value is used to
// add fast paths for low alignment values. In practice, the alignment is a
// constant at the call site and the branch will be optimized out.
#[cfg(all(any(target_arch = "arm",
              target_arch = "mips",
              target_arch = "mipsel",
              target_arch = "powerpc")))]
const MIN_ALIGN: usize = 8;
#[cfg(all(any(target_arch = "x86",
              target_arch = "x86_64",
              target_arch = "aarch64")))]
const MIN_ALIGN: usize = 16;

extern "C" {
    fn memmove(dst: *mut u8, src: *const u8, size: usize);
    fn __rust_allocate(size: usize, align: usize) -> *mut u8;
    fn __rust_deallocate(ptr: *mut u8, old_size: usize, align: usize);
    fn __rust_reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8;
    fn __rust_reallocate_inplace(ptr: *mut u8,
                                 old_size: usize,
                                 size: usize,
                                 align: usize)
                                 -> usize;
    fn __rust_usable_size(size: usize, align: usize) -> usize;
}
<commit_msg>fix rustfmt on liballoc_system<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "alloc_system"]
#![crate_type = "rlib"]
#![no_std]
#![cfg_attr(not(stage0), allocator)]
#![unstable(feature = "alloc_system",
            reason = "this library is unlikely to be stabilized in its current \
                      form or name",
            issue = "27783")]
#![feature(allocator)]
#![feature(asm)]
#![feature(staged_api)]

// The minimum alignment guaranteed by the architecture. This value is used to
// add fast paths for low alignment values. In practice, the alignment is a
// constant at the call site and the branch will be optimized out.
#[cfg(all(any(target_arch = "arm",
              target_arch = "mips",
              target_arch = "mipsel",
              target_arch = "powerpc")))]
const MIN_ALIGN: usize = 8;
#[cfg(all(any(target_arch = "x86",
              target_arch = "x86_64",
              target_arch = "aarch64")))]
const MIN_ALIGN: usize = 16;

extern "C" {
    fn memmove(dst: *mut u8, src: *const u8, size: usize);
    fn __rust_allocate(size: usize, align: usize) -> *mut u8;
    fn __rust_deallocate(ptr: *mut u8, old_size: usize, align: usize);
    fn __rust_reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8;
    fn __rust_reallocate_inplace(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> usize;
    fn __rust_usable_size(size: usize, align: usize) -> usize;
}
<|endoftext|>


<commit_before>use std::collections::hashmap::HashMap;
use request::Request;
use middleware::{Action, Continue, Middleware};
use request;
use response;
use urlencoded;
use nickel_error::NickelError;
use http::server::request::{RequestUri, Star, AbsoluteUri, AbsolutePath, Authority};
use url::UrlParser;

type QueryStore = HashMap<String, Vec<String>>;

#[deriving(Clone)]
pub struct QueryStringParser;

impl QueryStringParser {
    fn parse(origin: &RequestUri) -> QueryStore {
        match *origin {
            AbsoluteUri(ref url) => {
                for query in url.query.iter() {
                    return urlencoded::parse(query.as_slice())
                }
            },
            AbsolutePath(ref s) => {
                match UrlParser::new().parse_path(s.as_slice()) {
                    Ok((_, Some(query), _)) => {
                        return urlencoded::parse(query.as_slice())
                    }
                    Ok(..) => {}
                    // FIXME: If this fails to parse, then it really shouldn't
                    // have reached here.
                    Err(..) => {}
                }
            },
            Star | Authority(..) => {}
        }

        HashMap::new()
    }
}

impl Middleware for QueryStringParser {
    fn invoke (&self, req: &mut request::Request, _res: &mut response::Response) -> Result<Action, NickelError> {
        let parsed = QueryStringParser::parse(&req.origin.request_uri);
        req.map.insert(parsed);
        Ok(Continue)
    }
}

pub trait QueryString {
    fn query(&self, key: &str, default: &str) -> Vec<String>;
}

impl<'a, 'b> QueryString for request::Request<'a, 'b> {
    fn query(&self, key: &str, default: &str) -> Vec<String> {
        self.map.find::<QueryStore>()
            .and_then(| store | {
                match store.find_copy(&key.to_string()) {
                    Some(result) => Some(result),
                    _ => Some(vec![default.to_string().clone()])
                }
            })
            .unwrap()
    }
}

#[test]
fn splits_and_parses_an_url() {
    use url::Url;
    let t = |url|{
        let store = QueryStringParser::parse(&url);
        assert_eq!(store["foo".to_string()], vec!["bar".to_string()]);
        assert_eq!(store["message".to_string()],
                        vec!["hello".to_string(), "world".to_string()]);
    };

    let raw = "http://www.foo.bar/query/test?foo=bar&message=hello&message=world";
    t(AbsoluteUri(Url::parse(raw).unwrap()));

    t(AbsolutePath("/query/test?foo=bar&message=hello&message=world".to_string()));

    assert_eq!(QueryStringParser::parse(&Star), HashMap::new());

    let store = QueryStringParser::parse(&Authority("host.com".to_string()));
    assert_eq!(store, HashMap::new());
}
<commit_msg>query_string: Style.<commit_after>use std::collections::hashmap::HashMap;
use request::Request;
use middleware::{Action, Continue, Middleware};
use request;
use response;
use urlencoded;
use nickel_error::NickelError;
use http::server::request::{RequestUri, Star, AbsoluteUri, AbsolutePath, Authority};
use url::UrlParser;

type QueryStore = HashMap<String, Vec<String>>;

#[deriving(Clone)]
pub struct QueryStringParser;

impl QueryStringParser {
    fn parse(origin: &RequestUri) -> QueryStore {
        match *origin {
            AbsoluteUri(ref url) => {
                for query in url.query.iter() {
                    return urlencoded::parse(query.as_slice())
                }
            },
            AbsolutePath(ref s) => {
                match UrlParser::new().parse_path(s.as_slice()) {
                    Ok((_, Some(query), _)) => {
                        return urlencoded::parse(query.as_slice())
                    }
                    Ok(..) => {}
                    // FIXME: If this fails to parse, then it really shouldn't
                    // have reached here.
                    Err(..) => {}
                }
            },
            Star | Authority(..) => {}
        }

        HashMap::new()
    }
}

impl Middleware for QueryStringParser {
    fn invoke (&self, req: &mut request::Request, _res: &mut response::Response) -> Result<Action, NickelError> {
        let parsed = QueryStringParser::parse(&req.origin.request_uri);
        req.map.insert(parsed);
        Ok(Continue)
    }
}

pub trait QueryString {
    fn query(&self, key: &str, default: &str) -> Vec<String>;
}

impl<'a, 'b> QueryString for request::Request<'a, 'b> {
    fn query(&self, key: &str, default: &str) -> Vec<String> {
        self.map.find::<QueryStore>().and_then(| store | {
            match store.find_copy(&key.to_string()) {
                Some(result) => Some(result),
                _ => Some(vec![default.to_string().clone()])
            }
        }).unwrap()
    }
}

#[test]
fn splits_and_parses_an_url() {
    use url::Url;
    let t = |url|{
        let store = QueryStringParser::parse(&url);
        assert_eq!(store["foo".to_string()], vec!["bar".to_string()]);
        assert_eq!(store["message".to_string()],
                        vec!["hello".to_string(), "world".to_string()]);
    };

    let raw = "http://www.foo.bar/query/test?foo=bar&message=hello&message=world";
    t(AbsoluteUri(Url::parse(raw).unwrap()));

    t(AbsolutePath("/query/test?foo=bar&message=hello&message=world".to_string()));

    assert_eq!(QueryStringParser::parse(&Star), HashMap::new());

    let store = QueryStringParser::parse(&Authority("host.com".to_string()));
    assert_eq!(store, HashMap::new());
}
<|endoftext|>


<commit_before><commit_msg>Refactor Enable Switch Button<commit_after><|endoftext|>


<commit_before><commit_msg>fetch/git: robustify git version detection<commit_after><|endoftext|>


<commit_before><commit_msg>Handle focus event<commit_after><|endoftext|>