<commit_before>#[link(name = "http",
       vers = "0.1-pre",
       uuid = "d2ad8df0-547a-4ce1-99c6-a9da3b98fb3e",
       url = "")];

#[comment = "Rust HTTP server"];
#[license = "MIT/ASL2"];
#[crate_type = "lib"];

#[deny(non_camel_case_types)];
//#[deny(missing_doc)];

#[macro_escape];

extern mod extra;

macro_rules! unreachable(() => (fail!("internal error: entered unreachable code")))

pub mod buffer;
pub mod client;
pub mod common;
pub mod server;
pub mod method;
pub mod headers;
pub mod rfc2616;
#[path = "generated/status.rs"]
pub mod status;  // Getting an error? It's generated; use ``make`` or see the ``Makefile``

/// TODO: submit upstream
pub mod memstream;
<commit_msg>Remove unreachable!() macro (upstream has it now).<commit_after>#[link(name = "http",
       vers = "0.1-pre",
       uuid = "d2ad8df0-547a-4ce1-99c6-a9da3b98fb3e",
       url = "")];

#[comment = "Rust HTTP server"];
#[license = "MIT/ASL2"];
#[crate_type = "lib"];

#[deny(non_camel_case_types)];
//#[deny(missing_doc)];

#[macro_escape];

extern mod extra;

pub mod buffer;
pub mod client;
pub mod common;
pub mod server;
pub mod method;
pub mod headers;
pub mod rfc2616;
#[path = "generated/status.rs"]
pub mod status;  // Getting an error? It's generated; use ``make`` or see the ``Makefile``

/// TODO: submit upstream
pub mod memstream;
<|endoftext|>


<commit_before>use instruction::{Definition, SrcKind, DestKind};
use instruction::Coding::*;
use instruction::OperationKind::*;
use fonts;

// Possible instruction set extensions to add:
//   http://www.mattmik.com/files/chip8/extensions/CHIP8ExtensionsReference.pdf
// Unlikely:
//   Chip-8C (limited info), Chip-8I (adds hardware IO), Chip-8 II (more hardware IO, for ASCII keyboard), Chip-8III (capability of Chip-8I&II but
//   maintains compatibility with original Chip8), Chip-8E (14 new instructions and hardware IO), Chip-8Y (hardware IO and compatibility)
// Might just be machine config changes
//   Chip-10 (Expanded resolution of 128x64)
//   Hi-Res Chip-8 (128x64 resolution, faster),
// Interesting:
//   MegaChip8 - Adds color
//   Chip-8X - Big update from RCA with color, sound, 2nd keypad
//   Chip-8M (Add morse code; http://www.mattmik.com/files/viper/Volume4Issue05.pdf)
// Already added:
//   Original Chip8, SuperChip, XOChip

const A1:usize = 1;
const A2:usize = 2;
const A3:usize = 4;
const A4:usize = 8;

pub const CHIP8: &'static [Definition] = &[
    Definition { pattern: [C(0x0), C(0x0),   C(0x0),   C(0x0)], op: NoOp },
    Definition { pattern: [C(0x0), C(0x0),   C(0xE),   C(0x0)], op: Cls },
    Definition { pattern: [C(0x0), C(0x0),   C(0xE),   C(0xE)], op: Ret },
    Definition { pattern: [C(0x1), A(A1),    A(A1),    A(A1)  ], op: Jump(SrcKind::Address12) },
    Definition { pattern: [C(0x2), A(A1),    A(A1),    A(A1)  ], op: Call(SrcKind::Address12) },
    Definition { pattern: [C(0x3), A(A1),    A(A2),    A(A2)  ], op: SkipEq(SrcKind::Register, SrcKind::Literal8) },
    Definition { pattern: [C(0x4), A(A1),    A(A2),    A(A3)  ], op: SkipNotEq(SrcKind::Register, SrcKind::Literal8) },
    Definition { pattern: [C(0x5), A(A1),    A(A2),    C(0x0)], op: SkipEq(SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x6), A(A1),    A(A2),    A(A2)  ], op: Load(DestKind::Register, SrcKind::Literal8) },
    Definition { pattern: [C(0x7), A(A1|A2), A(A3),    A(A3)  ], op: Add(DestKind::Register, SrcKind::Register, SrcKind::Literal8) },
    Definition { pattern: [C(0x8), A(A1),    A(A2),    C(0x0)], op: Load(DestKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1|A3), A(A3),    C(0x1)], op: Or(DestKind::Register, SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1|A3), A(A3),    C(0x2)], op: And(DestKind::Register, SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1|A3), A(A3),    C(0x3)], op: Xor(DestKind::Register, SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1|A3), A(A3),    C(0x4)], op: Add(DestKind::Register, SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1|A3), A(A3),    C(0x5)], op: Sub(DestKind::Register, SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1),    A(A2),    C(0x6)], op: Shr(DestKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1),    A(A2|A3), C(0x7)], op: Sub(DestKind::Register, SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1),    A(A2),    C(0xE)], op: Shl(DestKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x9), A(A1),    A(A2),    C(0x0)], op: SkipNotEq(SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0xA), A(A1),    A(A1),    A(A1)  ], op: Load(DestKind::I, SrcKind::Literal12 ) },
    Definition { pattern: [C(0xB), A(A1),    A(A1),    A(A1)  ], op: JumpV0(SrcKind::Literal12 ) },
    Definition { pattern: [C(0xC), A(A1),    A(A3),    A(A3)  ], op: Rand(DestKind::Register, SrcKind::Random, SrcKind::Literal8) },
    Definition { pattern: [C(0xD), A(A1),    A(A2),    A(A3)  ], op: Sprite(SrcKind::Register, SrcKind::Register, SrcKind::Literal4) },
    Definition { pattern: [C(0xE), A(A1),    C(0x9),   C(0xE)], op: SkipKey(SrcKind::Register) },
    Definition { pattern: [C(0xE), A(A1),    C(0xA),   C(0x1)], op: SkipNotKey(SrcKind::Register) },
    Definition { pattern: [C(0xF), A(A1),    C(0x0),   C(0x7)], op: Load(DestKind::Register, SrcKind::DelayTimer) },
    Definition { pattern: [C(0xF), A(A1),    C(0x0),   C(0xA)], op: WaitKey(DestKind::Register, SrcKind::Literal4) },
    Definition { pattern: [C(0xF), A(A2),    C(0x1),   C(0x5)], op: Load(DestKind::DelayTimer, SrcKind::Register) },
    Definition { pattern: [C(0xF), A(A2),    C(0x1),   C(0x8)], op: Load(DestKind::SoundTimer, SrcKind::Register) },
    Definition { pattern: [C(0xF), A(A3),    C(0x1),   C(0xE)], op: Add(DestKind::I, SrcKind::I, SrcKind::Register) },
    Definition { pattern: [C(0xF), A(A1),    C(0x2),   C(0x9)], op: Font(SrcKind::Register, SrcKind::Const(fonts::CODE_SMALL)) },
    Definition { pattern: [C(0xF), A(A1),    C(0x3),   C(0x3)], op: Bcd(SrcKind::Register) },
    Definition { pattern: [C(0xF), A(A2),    C(0x5),   C(0x5)], op: Stash(SrcKind::Const(0), SrcKind::Register) },
    Definition { pattern: [C(0xF), A(A2),    C(0x6),   C(0x5)], op: Fetch(SrcKind::Const(0), SrcKind::Register) },
];

pub const SUPERCHIP: &'static [Definition] = &[
    Definition { pattern: [C(0x0), C(0x0), C(0xC), A(A1)],   op: NoOp /*ScrollDown(SrcKind::Literal4)*/ },
    Definition { pattern: [C(0x0), C(0x0), C(0xF), C(0xB)], op: NoOp /*ScrollRight*/ },
    Definition { pattern: [C(0x0), C(0x0), C(0xF), C(0xC)], op: NoOp /*ScrollLeft*/ },
    Definition { pattern: [C(0x0), C(0x0), C(0xF), C(0xD)], op: NoOp /*Exit*/ },
    Definition { pattern: [C(0x0), C(0x0), C(0xF), C(0xE)], op: NoOp /*LowRes*/ },
    Definition { pattern: [C(0x0), C(0x0), C(0xF), C(0xF)], op: NoOp /*HighRes*/ },
    Definition { pattern: [C(0xD), A(A1),   C(0x3), C(0x0)], op: Font(SrcKind::Register, SrcKind::Const(fonts::CODE_BIG)) },
    Definition { pattern: [C(0xF), A(A1),   C(0x7), C(0x5)], op: NoOp /*SaveFlags(SrcKind::Register)*/},
    Definition { pattern: [C(0xF), A(A1),   C(0x8), C(0x5)], op: NoOp /*LoadFlags(SrcKind::Register)*/},
];

pub const XOCHIP: &'static [Definition] = &[
    Definition { pattern: [C(0x5), A(A1),   A(A2),   C(0x2)], op: Stash(SrcKind::Literal4, SrcKind::Literal4) },
    Definition { pattern: [C(0x5), A(A1),   A(A2),   C(0x3)], op: Fetch(SrcKind::Literal4, SrcKind::Literal4) },
    Definition { pattern: [C(0xF), C(0x0), C(0x0), C(0x0)], op: NoOp /*LoadI16*/ },
    Definition { pattern: [C(0xF), A(A1),   C(0x0), C(0x1)], op: NoOp /*SelectDrawPlane(SrcKind::Literal4)*/ },
    Definition { pattern: [C(0xF), A(A1),   C(0x0), C(0x2)], op: NoOp /*StoreAudio*/ },
    Definition { pattern: [C(0x0), C(0x0), C(0xD), A(A1)],   op: NoOp /*ScrollUp(SrcKind::Literal4)*/ },
];
<commit_msg>Formatting<commit_after>use instruction::{Definition, SrcKind, DestKind};
use instruction::Coding::*;
use instruction::OperationKind::*;
use fonts;

// Possible instruction set extensions to add:
//   http://www.mattmik.com/files/chip8/extensions/CHIP8ExtensionsReference.pdf
// Unlikely:
//   Chip-8C (limited info), Chip-8I (adds hardware IO), Chip-8 II (more hardware IO, for ASCII keyboard), Chip-8III (capability of Chip-8I&II but
//   maintains compatibility with original Chip8), Chip-8E (14 new instructions and hardware IO), Chip-8Y (hardware IO and compatibility)
// Might just be machine config changes
//   Chip-10 (Expanded resolution of 128x64)
//   Hi-Res Chip-8 (128x64 resolution, faster),
// Interesting:
//   MegaChip8 - Adds color
//   Chip-8X - Big update from RCA with color, sound, 2nd keypad
//   Chip-8M (Add morse code; http://www.mattmik.com/files/viper/Volume4Issue05.pdf)
// Already added:
//   Original Chip8, SuperChip, XOChip

const A1:usize = 1;
const A2:usize = 2;
const A3:usize = 4;

pub const CHIP8: &'static [Definition] = &[
    Definition { pattern: [C(0x0), C(0x0),   C(0x0),   C(0x0)], op: NoOp },
    Definition { pattern: [C(0x0), C(0x0),   C(0xE),   C(0x0)], op: Cls },
    Definition { pattern: [C(0x0), C(0x0),   C(0xE),   C(0xE)], op: Ret },
    Definition { pattern: [C(0x1), A(A1),    A(A1),    A(A1) ], op: Jump(SrcKind::Address12) },
    Definition { pattern: [C(0x2), A(A1),    A(A1),    A(A1) ], op: Call(SrcKind::Address12) },
    Definition { pattern: [C(0x3), A(A1),    A(A2),    A(A2) ], op: SkipEq(SrcKind::Register, SrcKind::Literal8) },
    Definition { pattern: [C(0x4), A(A1),    A(A2),    A(A3) ], op: SkipNotEq(SrcKind::Register, SrcKind::Literal8) },
    Definition { pattern: [C(0x5), A(A1),    A(A2),    C(0x0)], op: SkipEq(SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x6), A(A1),    A(A2),    A(A2) ], op: Load(DestKind::Register, SrcKind::Literal8) },
    Definition { pattern: [C(0x7), A(A1|A2), A(A3),    A(A3) ], op: Add(DestKind::Register, SrcKind::Register, SrcKind::Literal8) },
    Definition { pattern: [C(0x8), A(A1),    A(A2),    C(0x0)], op: Load(DestKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1|A3), A(A3),    C(0x1)], op: Or(DestKind::Register, SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1|A3), A(A3),    C(0x2)], op: And(DestKind::Register, SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1|A3), A(A3),    C(0x3)], op: Xor(DestKind::Register, SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1|A3), A(A3),    C(0x4)], op: Add(DestKind::Register, SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1|A3), A(A3),    C(0x5)], op: Sub(DestKind::Register, SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1),    A(A2),    C(0x6)], op: Shr(DestKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1),    A(A2|A3), C(0x7)], op: Sub(DestKind::Register, SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x8), A(A1),    A(A2),    C(0xE)], op: Shl(DestKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0x9), A(A1),    A(A2),    C(0x0)], op: SkipNotEq(SrcKind::Register, SrcKind::Register) },
    Definition { pattern: [C(0xA), A(A1),    A(A1),    A(A1) ], op: Load(DestKind::I, SrcKind::Literal12 ) },
    Definition { pattern: [C(0xB), A(A1),    A(A1),    A(A1) ], op: JumpV0(SrcKind::Literal12 ) },
    Definition { pattern: [C(0xC), A(A1),    A(A3),    A(A3) ], op: Rand(DestKind::Register, SrcKind::Random, SrcKind::Literal8) },
    Definition { pattern: [C(0xD), A(A1),    A(A2),    A(A3) ], op: Sprite(SrcKind::Register, SrcKind::Register, SrcKind::Literal4) },
    Definition { pattern: [C(0xE), A(A1),    C(0x9),   C(0xE)], op: SkipKey(SrcKind::Register) },
    Definition { pattern: [C(0xE), A(A1),    C(0xA),   C(0x1)], op: SkipNotKey(SrcKind::Register) },
    Definition { pattern: [C(0xF), A(A1),    C(0x0),   C(0x7)], op: Load(DestKind::Register, SrcKind::DelayTimer) },
    Definition { pattern: [C(0xF), A(A1),    C(0x0),   C(0xA)], op: WaitKey(DestKind::Register, SrcKind::Literal4) },
    Definition { pattern: [C(0xF), A(A2),    C(0x1),   C(0x5)], op: Load(DestKind::DelayTimer, SrcKind::Register) },
    Definition { pattern: [C(0xF), A(A2),    C(0x1),   C(0x8)], op: Load(DestKind::SoundTimer, SrcKind::Register) },
    Definition { pattern: [C(0xF), A(A3),    C(0x1),   C(0xE)], op: Add(DestKind::I, SrcKind::I, SrcKind::Register) },
    Definition { pattern: [C(0xF), A(A1),    C(0x2),   C(0x9)], op: Font(SrcKind::Register, SrcKind::Const(fonts::CODE_SMALL)) },
    Definition { pattern: [C(0xF), A(A1),    C(0x3),   C(0x3)], op: Bcd(SrcKind::Register) },
    Definition { pattern: [C(0xF), A(A2),    C(0x5),   C(0x5)], op: Stash(SrcKind::Const(0), SrcKind::Register) },
    Definition { pattern: [C(0xF), A(A2),    C(0x6),   C(0x5)], op: Fetch(SrcKind::Const(0), SrcKind::Register) },
];

pub const SUPERCHIP: &'static [Definition] = &[
    Definition { pattern: [C(0x0), C(0x0),   C(0xC),   A(A1)],  op: NoOp /*ScrollDown(SrcKind::Literal4)*/ },
    Definition { pattern: [C(0x0), C(0x0),   C(0xF),   C(0xB)], op: NoOp /*ScrollRight*/ },
    Definition { pattern: [C(0x0), C(0x0),   C(0xF),   C(0xC)], op: NoOp /*ScrollLeft*/ },
    Definition { pattern: [C(0x0), C(0x0),   C(0xF),   C(0xD)], op: NoOp /*Exit*/ },
    Definition { pattern: [C(0x0), C(0x0),   C(0xF),   C(0xE)], op: NoOp /*LowRes*/ },
    Definition { pattern: [C(0x0), C(0x0),   C(0xF),   C(0xF)], op: NoOp /*HighRes*/ },
    Definition { pattern: [C(0xD), A(A1),    C(0x3),   C(0x0)], op: Font(SrcKind::Register, SrcKind::Const(fonts::CODE_BIG)) },
    Definition { pattern: [C(0xF), A(A1),    C(0x7),   C(0x5)], op: NoOp /*SaveFlags(SrcKind::Register)*/},
    Definition { pattern: [C(0xF), A(A1),    C(0x8),   C(0x5)], op: NoOp /*LoadFlags(SrcKind::Register)*/},
];

pub const XOCHIP: &'static [Definition] = &[
    Definition { pattern: [C(0x5), A(A1),   A(A2),     C(0x2)], op: Stash(SrcKind::Literal4, SrcKind::Literal4) },
    Definition { pattern: [C(0x5), A(A1),   A(A2),     C(0x3)], op: Fetch(SrcKind::Literal4, SrcKind::Literal4) },
    Definition { pattern: [C(0xF), C(0x0),  C(0x0),    C(0x0)], op: NoOp /*LoadI16*/ },
    Definition { pattern: [C(0xF), A(A1),   C(0x0),    C(0x1)], op: NoOp /*SelectDrawPlane(SrcKind::Literal4)*/ },
    Definition { pattern: [C(0xF), A(A1),   C(0x0),    C(0x2)], op: NoOp /*StoreAudio*/ },
    Definition { pattern: [C(0x0), C(0x0),  C(0xD),    A(A1)],  op: NoOp /*ScrollUp(SrcKind::Literal4)*/ },
];
<|endoftext|>


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

#![allow(non_camel_case_types)]

use std::cell::RefCell;
use std::os;
use std::io::fs;
use collections::HashSet;

pub enum FileMatch { FileMatches, FileDoesntMatch }

// A module for searching for libraries
// FIXME (#2658): I'm not happy how this module turned out. Should
// probably just be folded into cstore.

/// Functions with type `pick` take a parent directory as well as
/// a file found in that directory.
pub type pick<'a> = 'a |path: &Path| -> FileMatch;

pub struct FileSearch<'a> {
    pub sysroot: &'a Path,
    pub addl_lib_search_paths: &'a RefCell<HashSet<Path>>,
    pub target_triple: &'a str
}

impl<'a> FileSearch<'a> {
    pub fn for_each_lib_search_path(&self, f: |&Path| -> FileMatch) {
        let mut visited_dirs = HashSet::new();
        let mut found = false;

        debug!("filesearch: searching additional lib search paths [{:?}]",
               self.addl_lib_search_paths.borrow().len());
        for path in self.addl_lib_search_paths.borrow().iter() {
            match f(path) {
                FileMatches => found = true,
                FileDoesntMatch => ()
            }
            visited_dirs.insert(path.as_vec().to_owned());
        }

        debug!("filesearch: searching target lib path");
        let tlib_path = make_target_lib_path(self.sysroot,
                                    self.target_triple);
        if !visited_dirs.contains_equiv(&tlib_path.as_vec()) {
            match f(&tlib_path) {
                FileMatches => found = true,
                FileDoesntMatch => ()
            }
        }
        visited_dirs.insert(tlib_path.as_vec().to_owned());
        // Try RUST_PATH
        if !found {
            let rustpath = rust_path();
            for path in rustpath.iter() {
                let tlib_path = make_rustpkg_target_lib_path(
                    self.sysroot, path, self.target_triple);
                debug!("is {} in visited_dirs? {:?}", tlib_path.display(),
                        visited_dirs.contains_equiv(&tlib_path.as_vec().to_owned()));

                if !visited_dirs.contains_equiv(&tlib_path.as_vec()) {
                    visited_dirs.insert(tlib_path.as_vec().to_owned());
                    // Don't keep searching the RUST_PATH if one match turns up --
                    // if we did, we'd get a "multiple matching crates" error
                    match f(&tlib_path) {
                       FileMatches => {
                           break;
                       }
                       FileDoesntMatch => ()
                    }
                }
            }
        }
    }

    pub fn get_target_lib_path(&self) -> Path {
        make_target_lib_path(self.sysroot, self.target_triple)
    }

    pub fn get_target_lib_file_path(&self, file: &Path) -> Path {
        let mut p = self.get_target_lib_path();
        p.push(file);
        p
    }

    pub fn search(&self, pick: pick) {
        self.for_each_lib_search_path(|lib_search_path| {
            debug!("searching {}", lib_search_path.display());
            match fs::readdir(lib_search_path) {
                Ok(files) => {
                    let mut rslt = FileDoesntMatch;
                    let is_rlib = |p: & &Path| {
                        p.extension_str() == Some("rlib")
                    };
                    // Reading metadata out of rlibs is faster, and if we find both
                    // an rlib and a dylib we only read one of the files of
                    // metadata, so in the name of speed, bring all rlib files to
                    // the front of the search list.
                    let files1 = files.iter().filter(|p| is_rlib(p));
                    let files2 = files.iter().filter(|p| !is_rlib(p));
                    for path in files1.chain(files2) {
                        debug!("testing {}", path.display());
                        let maybe_picked = pick(path);
                        match maybe_picked {
                            FileMatches => {
                                debug!("picked {}", path.display());
                                rslt = FileMatches;
                            }
                            FileDoesntMatch => {
                                debug!("rejected {}", path.display());
                            }
                        }
                    }
                    rslt
                }
                Err(..) => FileDoesntMatch,
            }
        });
    }

    pub fn new(sysroot: &'a Path,
               target_triple: &'a str,
               addl_lib_search_paths: &'a RefCell<HashSet<Path>>) -> FileSearch<'a> {
        debug!("using sysroot = {}", sysroot.display());
        FileSearch {
            sysroot: sysroot,
            addl_lib_search_paths: addl_lib_search_paths,
            target_triple: target_triple
        }
    }
}

pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path {
    let mut p = Path::new(find_libdir(sysroot));
    assert!(p.is_relative());
    p.push(rustlibdir());
    p.push(target_triple);
    p.push("lib");
    p
}

fn make_target_lib_path(sysroot: &Path,
                        target_triple: &str) -> Path {
    sysroot.join(&relative_target_lib_path(sysroot, target_triple))
}

fn make_rustpkg_target_lib_path(sysroot: &Path,
                                dir: &Path,
                                target_triple: &str) -> Path {
    let mut p = dir.join(find_libdir(sysroot));
    p.push(target_triple);
    p
}

pub fn get_or_default_sysroot() -> Path {
    // Follow symlinks.  If the resolved path is relative, make it absolute.
    fn canonicalize(path: Option<Path>) -> Option<Path> {
        path.and_then(|mut path|
            match fs::readlink(&path) {
                Ok(canon) => {
                    if canon.is_absolute() {
                        Some(canon)
                    } else {
                        path.pop();
                        Some(path.join(canon))
                    }
                },
                Err(..) => Some(path),
            })
    }

    match canonicalize(os::self_exe_name()) {
        Some(mut p) => { p.pop(); p.pop(); p }
        None => fail!("can't determine value for sysroot")
    }
}

#[cfg(windows)]
static PATH_ENTRY_SEPARATOR: &'static str = ";";
#[cfg(not(windows))]
static PATH_ENTRY_SEPARATOR: &'static str = ":";

/// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<~str> {
    os::getenv("RUST_PATH")
}

/// Returns the value of RUST_PATH, as a list
/// of Paths. Includes default entries for, if they exist:
/// $HOME/.rust
/// DIR/.rust for any DIR that's the current working directory
/// or an ancestor of it
pub fn rust_path() -> Vec<Path> {
    let mut env_rust_path: Vec<Path> = match get_rust_path() {
        Some(env_path) => {
            let env_path_components =
                env_path.split_str(PATH_ENTRY_SEPARATOR);
            env_path_components.map(|s| Path::new(s)).collect()
        }
        None => Vec::new()
    };
    let mut cwd = os::getcwd();
    // now add in default entries
    let cwd_dot_rust = cwd.join(".rust");
    if !env_rust_path.contains(&cwd_dot_rust) {
        env_rust_path.push(cwd_dot_rust);
    }
    if !env_rust_path.contains(&cwd) {
        env_rust_path.push(cwd.clone());
    }
    loop {
        if { let f = cwd.filename(); f.is_none() || f.unwrap() == bytes!("..") } {
            break
        }
        cwd.set_filename(".rust");
        if !env_rust_path.contains(&cwd) && cwd.exists() {
            env_rust_path.push(cwd.clone());
        }
        cwd.pop();
    }
    let h = os::homedir();
    for h in h.iter() {
        let p = h.join(".rust");
        if !env_rust_path.contains(&p) && p.exists() {
            env_rust_path.push(p);
        }
    }
    env_rust_path
}

// The name of the directory rustc expects libraries to be located.
// On Unix should be "lib", on windows "bin"
#[cfg(unix)]
fn find_libdir(sysroot: &Path) -> ~str {
    // FIXME: This is a quick hack to make the rustc binary able to locate
    // Rust libraries in Linux environments where libraries might be installed
    // to lib64/lib32. This would be more foolproof by basing the sysroot off
    // of the directory where librustc is located, rather than where the rustc
    // binary is.

    if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
        return primary_libdir_name();
    } else {
        return secondary_libdir_name();
    }

    #[cfg(target_word_size = "64")]
    fn primary_libdir_name() -> ~str { ~"lib64" }

    #[cfg(target_word_size = "32")]
    fn primary_libdir_name() -> ~str { ~"lib32" }

    fn secondary_libdir_name() -> ~str { ~"lib" }
}

#[cfg(windows)]
fn find_libdir(_sysroot: &Path) -> ~str {
    ~"bin"
}

// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
pub fn rustlibdir() -> ~str {
    ~"rustlib"
}
<commit_msg>metadata: filesearch: remove dead code<commit_after>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![allow(non_camel_case_types)]

use std::cell::RefCell;
use std::os;
use std::io::fs;
use collections::HashSet;

pub enum FileMatch { FileMatches, FileDoesntMatch }

// A module for searching for libraries
// FIXME (#2658): I'm not happy how this module turned out. Should
// probably just be folded into cstore.

/// Functions with type `pick` take a parent directory as well as
/// a file found in that directory.
pub type pick<'a> = 'a |path: &Path| -> FileMatch;

pub struct FileSearch<'a> {
    pub sysroot: &'a Path,
    pub addl_lib_search_paths: &'a RefCell<HashSet<Path>>,
    pub target_triple: &'a str
}

impl<'a> FileSearch<'a> {
    pub fn for_each_lib_search_path(&self, f: |&Path| -> FileMatch) {
        let mut visited_dirs = HashSet::new();
        let mut found = false;

        debug!("filesearch: searching additional lib search paths [{:?}]",
               self.addl_lib_search_paths.borrow().len());
        for path in self.addl_lib_search_paths.borrow().iter() {
            match f(path) {
                FileMatches => found = true,
                FileDoesntMatch => ()
            }
            visited_dirs.insert(path.as_vec().to_owned());
        }

        debug!("filesearch: searching target lib path");
        let tlib_path = make_target_lib_path(self.sysroot,
                                    self.target_triple);
        if !visited_dirs.contains_equiv(&tlib_path.as_vec()) {
            match f(&tlib_path) {
                FileMatches => found = true,
                FileDoesntMatch => ()
            }
        }
        visited_dirs.insert(tlib_path.as_vec().to_owned());
        // Try RUST_PATH
        if !found {
            let rustpath = rust_path();
            for path in rustpath.iter() {
                let tlib_path = make_rustpkg_target_lib_path(
                    self.sysroot, path, self.target_triple);
                debug!("is {} in visited_dirs? {:?}", tlib_path.display(),
                        visited_dirs.contains_equiv(&tlib_path.as_vec().to_owned()));

                if !visited_dirs.contains_equiv(&tlib_path.as_vec()) {
                    visited_dirs.insert(tlib_path.as_vec().to_owned());
                    // Don't keep searching the RUST_PATH if one match turns up --
                    // if we did, we'd get a "multiple matching crates" error
                    match f(&tlib_path) {
                       FileMatches => {
                           break;
                       }
                       FileDoesntMatch => ()
                    }
                }
            }
        }
    }

    pub fn get_target_lib_path(&self) -> Path {
        make_target_lib_path(self.sysroot, self.target_triple)
    }

    pub fn search(&self, pick: pick) {
        self.for_each_lib_search_path(|lib_search_path| {
            debug!("searching {}", lib_search_path.display());
            match fs::readdir(lib_search_path) {
                Ok(files) => {
                    let mut rslt = FileDoesntMatch;
                    let is_rlib = |p: & &Path| {
                        p.extension_str() == Some("rlib")
                    };
                    // Reading metadata out of rlibs is faster, and if we find both
                    // an rlib and a dylib we only read one of the files of
                    // metadata, so in the name of speed, bring all rlib files to
                    // the front of the search list.
                    let files1 = files.iter().filter(|p| is_rlib(p));
                    let files2 = files.iter().filter(|p| !is_rlib(p));
                    for path in files1.chain(files2) {
                        debug!("testing {}", path.display());
                        let maybe_picked = pick(path);
                        match maybe_picked {
                            FileMatches => {
                                debug!("picked {}", path.display());
                                rslt = FileMatches;
                            }
                            FileDoesntMatch => {
                                debug!("rejected {}", path.display());
                            }
                        }
                    }
                    rslt
                }
                Err(..) => FileDoesntMatch,
            }
        });
    }

    pub fn new(sysroot: &'a Path,
               target_triple: &'a str,
               addl_lib_search_paths: &'a RefCell<HashSet<Path>>) -> FileSearch<'a> {
        debug!("using sysroot = {}", sysroot.display());
        FileSearch {
            sysroot: sysroot,
            addl_lib_search_paths: addl_lib_search_paths,
            target_triple: target_triple
        }
    }
}

pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path {
    let mut p = Path::new(find_libdir(sysroot));
    assert!(p.is_relative());
    p.push(rustlibdir());
    p.push(target_triple);
    p.push("lib");
    p
}

fn make_target_lib_path(sysroot: &Path,
                        target_triple: &str) -> Path {
    sysroot.join(&relative_target_lib_path(sysroot, target_triple))
}

fn make_rustpkg_target_lib_path(sysroot: &Path,
                                dir: &Path,
                                target_triple: &str) -> Path {
    let mut p = dir.join(find_libdir(sysroot));
    p.push(target_triple);
    p
}

pub fn get_or_default_sysroot() -> Path {
    // Follow symlinks.  If the resolved path is relative, make it absolute.
    fn canonicalize(path: Option<Path>) -> Option<Path> {
        path.and_then(|mut path|
            match fs::readlink(&path) {
                Ok(canon) => {
                    if canon.is_absolute() {
                        Some(canon)
                    } else {
                        path.pop();
                        Some(path.join(canon))
                    }
                },
                Err(..) => Some(path),
            })
    }

    match canonicalize(os::self_exe_name()) {
        Some(mut p) => { p.pop(); p.pop(); p }
        None => fail!("can't determine value for sysroot")
    }
}

#[cfg(windows)]
static PATH_ENTRY_SEPARATOR: &'static str = ";";
#[cfg(not(windows))]
static PATH_ENTRY_SEPARATOR: &'static str = ":";

/// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<~str> {
    os::getenv("RUST_PATH")
}

/// Returns the value of RUST_PATH, as a list
/// of Paths. Includes default entries for, if they exist:
/// $HOME/.rust
/// DIR/.rust for any DIR that's the current working directory
/// or an ancestor of it
pub fn rust_path() -> Vec<Path> {
    let mut env_rust_path: Vec<Path> = match get_rust_path() {
        Some(env_path) => {
            let env_path_components =
                env_path.split_str(PATH_ENTRY_SEPARATOR);
            env_path_components.map(|s| Path::new(s)).collect()
        }
        None => Vec::new()
    };
    let mut cwd = os::getcwd();
    // now add in default entries
    let cwd_dot_rust = cwd.join(".rust");
    if !env_rust_path.contains(&cwd_dot_rust) {
        env_rust_path.push(cwd_dot_rust);
    }
    if !env_rust_path.contains(&cwd) {
        env_rust_path.push(cwd.clone());
    }
    loop {
        if { let f = cwd.filename(); f.is_none() || f.unwrap() == bytes!("..") } {
            break
        }
        cwd.set_filename(".rust");
        if !env_rust_path.contains(&cwd) && cwd.exists() {
            env_rust_path.push(cwd.clone());
        }
        cwd.pop();
    }
    let h = os::homedir();
    for h in h.iter() {
        let p = h.join(".rust");
        if !env_rust_path.contains(&p) && p.exists() {
            env_rust_path.push(p);
        }
    }
    env_rust_path
}

// The name of the directory rustc expects libraries to be located.
// On Unix should be "lib", on windows "bin"
#[cfg(unix)]
fn find_libdir(sysroot: &Path) -> ~str {
    // FIXME: This is a quick hack to make the rustc binary able to locate
    // Rust libraries in Linux environments where libraries might be installed
    // to lib64/lib32. This would be more foolproof by basing the sysroot off
    // of the directory where librustc is located, rather than where the rustc
    // binary is.

    if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
        return primary_libdir_name();
    } else {
        return secondary_libdir_name();
    }

    #[cfg(target_word_size = "64")]
    fn primary_libdir_name() -> ~str { ~"lib64" }

    #[cfg(target_word_size = "32")]
    fn primary_libdir_name() -> ~str { ~"lib32" }

    fn secondary_libdir_name() -> ~str { ~"lib" }
}

#[cfg(windows)]
fn find_libdir(_sysroot: &Path) -> ~str {
    ~"bin"
}

// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
pub fn rustlibdir() -> ~str {
    ~"rustlib"
}
<|endoftext|>


<commit_before>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::account_config::constants::CORE_CODE_ADDRESS;
use move_core_types::{
    identifier::{IdentStr, Identifier},
    language_storage::{ModuleId, StructTag},
};
use once_cell::sync::Lazy;

pub const ACCOUNT_MODULE_NAME: &str = "LibraAccount";

// Account
static ACCOUNT_MODULE_IDENTIFIER: Lazy<Identifier> =
    Lazy::new(|| Identifier::new("LibraAccount").unwrap());

/// The ModuleId for the Account module.
pub static ACCOUNT_MODULE: Lazy<ModuleId> =
    Lazy::new(|| ModuleId::new(CORE_CODE_ADDRESS, ACCOUNT_MODULE_IDENTIFIER.clone()));

// Payment Events
static SENT_EVENT_NAME: Lazy<Identifier> =
    Lazy::new(|| Identifier::new("SentPaymentEvent").unwrap());
static RECEIVED_EVENT_NAME: Lazy<Identifier> =
    Lazy::new(|| Identifier::new("ReceivedPaymentEvent").unwrap());

pub fn sent_event_name() -> &'static IdentStr {
    &*SENT_EVENT_NAME
}

pub fn received_event_name() -> &'static IdentStr {
    &*RECEIVED_EVENT_NAME
}

pub fn received_payment_tag() -> StructTag {
    StructTag {
        address: CORE_CODE_ADDRESS,
        module: ACCOUNT_MODULE_IDENTIFIER.clone(),
        name: received_event_name().to_owned(),
        type_params: vec![],
    }
}
<commit_msg>Removing received_payment_tag from types/src/account_config/constants/account.rs<commit_after>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::account_config::constants::CORE_CODE_ADDRESS;
use move_core_types::{
    identifier::{IdentStr, Identifier},
    language_storage::ModuleId,
};
use once_cell::sync::Lazy;

pub const ACCOUNT_MODULE_NAME: &str = "LibraAccount";

// Account
static ACCOUNT_MODULE_IDENTIFIER: Lazy<Identifier> =
    Lazy::new(|| Identifier::new("LibraAccount").unwrap());

/// The ModuleId for the Account module.
pub static ACCOUNT_MODULE: Lazy<ModuleId> =
    Lazy::new(|| ModuleId::new(CORE_CODE_ADDRESS, ACCOUNT_MODULE_IDENTIFIER.clone()));

// Payment Events
static SENT_EVENT_NAME: Lazy<Identifier> =
    Lazy::new(|| Identifier::new("SentPaymentEvent").unwrap());
static RECEIVED_EVENT_NAME: Lazy<Identifier> =
    Lazy::new(|| Identifier::new("ReceivedPaymentEvent").unwrap());

pub fn sent_event_name() -> &'static IdentStr {
    &*SENT_EVENT_NAME
}

pub fn received_event_name() -> &'static IdentStr {
    &*RECEIVED_EVENT_NAME
}
<|endoftext|>


<commit_before>use std::any::Any;
use std::mem;

use runtime::{Class, Imp, Object, Sel, Super};

/// Types that may be sent Objective-C messages.
/// For example: objects, classes, and blocks.
pub unsafe trait Message { }

unsafe impl Message for Object { }

unsafe impl Message for Class { }

mod verify;

#[cfg(target_arch = "x86")]
#[path = "x86.rs"]
mod platform;
#[cfg(target_arch = "x86_64")]
#[path = "x86_64.rs"]
mod platform;
#[cfg(target_arch = "arm")]
#[path = "arm.rs"]
mod platform;
#[cfg(all(target_arch = "aarch64", not(feature = "gnustep")))]
#[path = "arm64.rs"]
mod platform;

#[cfg(feature= "gnustep")]
mod gnustep;

#[cfg(not(feature = "gnustep"))]
use self::platform::{msg_send_fn, msg_send_super_fn};
#[cfg(feature = "gnustep")]
use self::gnustep::{msg_send_fn, msg_send_super_fn};

/// Types that may be used as the arguments of an Objective-C message.
pub trait MessageArguments: Sized {
    unsafe fn invoke<R>(imp: Imp, obj: *mut Object, sel: Sel, args: Self) -> R
            where R: Any;

    /// Sends a message to the given obj with the given selector and self as
    /// the arguments.
    ///
    /// The correct version of `objc_msgSend` will be chosen based on the
    /// return type. For more information, see Apple's documenation:
    /// https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/index.html#//apple_ref/doc/uid/TP40001418-CH1g-88778
    ///
    /// It is recommended to use the `msg_send!` macro rather than calling this
    /// method directly.
    unsafe fn send<T, R>(self, obj: *mut T, sel: Sel) -> R
            where T: Message, R: Any {
        send_unverified(obj, sel, self).unwrap()
    }

    /// Sends a message to the superclass of an instance of a class with self
    /// as the arguments.
    unsafe fn send_super<T, R>(self, obj: *mut T, superclass: &Class, sel: Sel) -> R
            where T: Message, R: Any {
        send_super_unverified(obj, superclass, sel, self).unwrap()
    }
}

macro_rules! message_args_impl {
    ($($a:ident : $t:ident),*) => (
        impl<$($t),*> MessageArguments for ($($t,)*) {
            unsafe fn invoke<R>(imp: Imp, obj: *mut Object, sel: Sel, ($($a,)*): Self) -> R
                    where R: Any {
                let imp: unsafe extern fn(*mut Object, Sel $(, $t)*) -> R =
                    mem::transmute(imp);
                imp(obj, sel $(, $a)*)
            }
        }
    );
}

message_args_impl!();
message_args_impl!(a: A);
message_args_impl!(a: A, b: B);
message_args_impl!(a: A, b: B, c: C);
message_args_impl!(a: A, b: B, c: C, d: D);
message_args_impl!(a: A, b: B, c: C, d: D, e: E);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K, l: L);

#[cfg(feature = "exception")]
macro_rules! objc_try {
    ($b:block) => (
        $crate::exception::try(|| $b).map_err(|exception| match exception {
            Some(exception) => format!("Uncaught exception {:?}", &*exception),
            None => "Uncaught exception nil".to_owned(),
        })
    )
}

#[cfg(not(feature = "exception"))]
macro_rules! objc_try {
    ($b:block) => (Ok($b))
}

#[inline(always)]
unsafe fn send_unverified<T, A, R>(obj: *const T, sel: Sel, args: A)
        -> Result<R, String> where T: Message, A: MessageArguments, R: Any {
    let (msg_send_fn, receiver) = msg_send_fn::<R>(obj as *mut T as *mut Object, sel);
    objc_try!({
        A::invoke(msg_send_fn, receiver, sel, args)
    })
}

#[doc(hidden)]
#[inline(always)]
#[cfg(not(feature = "verify_message"))]
pub unsafe fn send_message<T, A, R>(obj: *const T, sel: Sel, args: A)
        -> Result<R, String>
        where T: Message, A: MessageArguments, R: Any {
    send_unverified(obj, sel, args)
}

#[doc(hidden)]
#[inline(always)]
#[cfg(feature = "verify_message")]
pub unsafe fn send_message<T, A, R>(obj: *const T, sel: Sel, args: A)
        -> Result<R, String>
        where T: Message, A: MessageArguments + ::EncodeArguments,
        R: Any + ::Encode {
    use self::verify::verify_message_signature;

    let cls = if obj.is_null() {
        return Err(format!("Messaging {:?} to nil", sel));
    } else {
        (*(obj as *const Object)).class()
    };

    verify_message_signature::<A, R>(cls, sel).and_then(|_| {
        send_unverified(obj, sel, args)
    })
}

#[inline(always)]
unsafe fn send_super_unverified<T, A, R>(obj: *const T, superclass: &Class,
        sel: Sel, args: A) -> Result<R, String>
        where T: Message, A: MessageArguments, R: Any {
    let sup = Super { receiver: obj as *mut T as *mut Object, superclass: superclass };
    let (msg_send_fn, receiver) = msg_send_super_fn::<R>(&sup, sel);
    objc_try!({
        A::invoke(msg_send_fn, receiver, sel, args)
    })
}

#[doc(hidden)]
#[inline(always)]
#[cfg(not(feature = "verify_message"))]
pub unsafe fn send_super_message<T, A, R>(obj: *const T, superclass: &Class,
        sel: Sel, args: A) -> Result<R, String>
        where T: Message, A: MessageArguments, R: Any {
    send_super_unverified(obj, superclass, sel, args)
}

#[doc(hidden)]
#[inline(always)]
#[cfg(feature = "verify_message")]
pub unsafe fn send_super_message<T, A, R>(obj: *const T, superclass: &Class,
        sel: Sel, args: A) -> Result<R, String>
        where T: Message, A: MessageArguments + ::EncodeArguments,
        R: Any + ::Encode {
    use self::verify::verify_message_signature;

    if obj.is_null() {
        return Err(format!("Messaging {:?} to nil", sel));
    }

    verify_message_signature::<A, R>(superclass, sel).and_then(|_| {
        send_super_unverified(obj, superclass, sel, args)
    })
}

#[cfg(test)]
mod tests {
    use runtime::Object;
    use test_utils;

    #[test]
    fn test_send_message() {
        let obj = test_utils::custom_object();
        let result: u32 = unsafe {
            let _: () = msg_send![obj, setFoo:4u32];
            msg_send![obj, foo]
        };
        assert!(result == 4);
    }

    #[test]
    fn test_send_message_stret() {
        let obj = test_utils::custom_object();
        let result: test_utils::CustomStruct = unsafe {
            msg_send![obj, customStruct]
        };
        let expected = test_utils::CustomStruct { a: 1, b:2, c: 3, d: 4 };
        assert!(result == expected);
    }

    #[test]
    fn test_send_message_nil() {
        let nil: *mut Object = ::std::ptr::null_mut();
        let result: usize = unsafe {
            msg_send![nil, hash]
        };
        assert!(result == 0);

        let result: *mut Object = unsafe {
            msg_send![nil, description]
        };
        assert!(result.is_null());

        let result: f64 = unsafe {
            msg_send![nil, doubleValue]
        };
        assert!(result == 0.0);
    }

    #[test]
    fn test_send_message_super() {
        let obj = test_utils::custom_subclass_object();
        let superclass = test_utils::custom_class();
        unsafe {
            let _: () = msg_send![obj, setFoo:4u32];
            let foo: u32 = msg_send![super(obj, superclass), foo];
            assert!(foo == 4);

            // The subclass is overriden to return foo + 2
            let foo: u32 = msg_send![obj, foo];
            assert!(foo == 6);
        }
    }
}
<commit_msg>Moved definition of Message down the file.<commit_after>use std::any::Any;
use std::mem;

use runtime::{Class, Imp, Object, Sel, Super};

mod verify;

#[cfg(target_arch = "x86")]
#[path = "x86.rs"]
mod platform;
#[cfg(target_arch = "x86_64")]
#[path = "x86_64.rs"]
mod platform;
#[cfg(target_arch = "arm")]
#[path = "arm.rs"]
mod platform;
#[cfg(all(target_arch = "aarch64", not(feature = "gnustep")))]
#[path = "arm64.rs"]
mod platform;

#[cfg(feature= "gnustep")]
mod gnustep;

#[cfg(not(feature = "gnustep"))]
use self::platform::{msg_send_fn, msg_send_super_fn};
#[cfg(feature = "gnustep")]
use self::gnustep::{msg_send_fn, msg_send_super_fn};

/// Types that may be sent Objective-C messages.
/// For example: objects, classes, and blocks.
pub unsafe trait Message { }

unsafe impl Message for Object { }

unsafe impl Message for Class { }

/// Types that may be used as the arguments of an Objective-C message.
pub trait MessageArguments: Sized {
    unsafe fn invoke<R>(imp: Imp, obj: *mut Object, sel: Sel, args: Self) -> R
            where R: Any;

    /// Sends a message to the given obj with the given selector and self as
    /// the arguments.
    ///
    /// The correct version of `objc_msgSend` will be chosen based on the
    /// return type. For more information, see Apple's documenation:
    /// https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/index.html#//apple_ref/doc/uid/TP40001418-CH1g-88778
    ///
    /// It is recommended to use the `msg_send!` macro rather than calling this
    /// method directly.
    unsafe fn send<T, R>(self, obj: *mut T, sel: Sel) -> R
            where T: Message, R: Any {
        send_unverified(obj, sel, self).unwrap()
    }

    /// Sends a message to the superclass of an instance of a class with self
    /// as the arguments.
    unsafe fn send_super<T, R>(self, obj: *mut T, superclass: &Class, sel: Sel) -> R
            where T: Message, R: Any {
        send_super_unverified(obj, superclass, sel, self).unwrap()
    }
}

macro_rules! message_args_impl {
    ($($a:ident : $t:ident),*) => (
        impl<$($t),*> MessageArguments for ($($t,)*) {
            unsafe fn invoke<R>(imp: Imp, obj: *mut Object, sel: Sel, ($($a,)*): Self) -> R
                    where R: Any {
                let imp: unsafe extern fn(*mut Object, Sel $(, $t)*) -> R =
                    mem::transmute(imp);
                imp(obj, sel $(, $a)*)
            }
        }
    );
}

message_args_impl!();
message_args_impl!(a: A);
message_args_impl!(a: A, b: B);
message_args_impl!(a: A, b: B, c: C);
message_args_impl!(a: A, b: B, c: C, d: D);
message_args_impl!(a: A, b: B, c: C, d: D, e: E);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K);
message_args_impl!(a: A, b: B, c: C, d: D, e: E, f: F, g: G, h: H, i: I, j: J, k: K, l: L);

#[cfg(feature = "exception")]
macro_rules! objc_try {
    ($b:block) => (
        $crate::exception::try(|| $b).map_err(|exception| match exception {
            Some(exception) => format!("Uncaught exception {:?}", &*exception),
            None => "Uncaught exception nil".to_owned(),
        })
    )
}

#[cfg(not(feature = "exception"))]
macro_rules! objc_try {
    ($b:block) => (Ok($b))
}

#[inline(always)]
unsafe fn send_unverified<T, A, R>(obj: *const T, sel: Sel, args: A)
        -> Result<R, String> where T: Message, A: MessageArguments, R: Any {
    let (msg_send_fn, receiver) = msg_send_fn::<R>(obj as *mut T as *mut Object, sel);
    objc_try!({
        A::invoke(msg_send_fn, receiver, sel, args)
    })
}

#[doc(hidden)]
#[inline(always)]
#[cfg(not(feature = "verify_message"))]
pub unsafe fn send_message<T, A, R>(obj: *const T, sel: Sel, args: A)
        -> Result<R, String>
        where T: Message, A: MessageArguments, R: Any {
    send_unverified(obj, sel, args)
}

#[doc(hidden)]
#[inline(always)]
#[cfg(feature = "verify_message")]
pub unsafe fn send_message<T, A, R>(obj: *const T, sel: Sel, args: A)
        -> Result<R, String>
        where T: Message, A: MessageArguments + ::EncodeArguments,
        R: Any + ::Encode {
    use self::verify::verify_message_signature;

    let cls = if obj.is_null() {
        return Err(format!("Messaging {:?} to nil", sel));
    } else {
        (*(obj as *const Object)).class()
    };

    verify_message_signature::<A, R>(cls, sel).and_then(|_| {
        send_unverified(obj, sel, args)
    })
}

#[inline(always)]
unsafe fn send_super_unverified<T, A, R>(obj: *const T, superclass: &Class,
        sel: Sel, args: A) -> Result<R, String>
        where T: Message, A: MessageArguments, R: Any {
    let sup = Super { receiver: obj as *mut T as *mut Object, superclass: superclass };
    let (msg_send_fn, receiver) = msg_send_super_fn::<R>(&sup, sel);
    objc_try!({
        A::invoke(msg_send_fn, receiver, sel, args)
    })
}

#[doc(hidden)]
#[inline(always)]
#[cfg(not(feature = "verify_message"))]
pub unsafe fn send_super_message<T, A, R>(obj: *const T, superclass: &Class,
        sel: Sel, args: A) -> Result<R, String>
        where T: Message, A: MessageArguments, R: Any {
    send_super_unverified(obj, superclass, sel, args)
}

#[doc(hidden)]
#[inline(always)]
#[cfg(feature = "verify_message")]
pub unsafe fn send_super_message<T, A, R>(obj: *const T, superclass: &Class,
        sel: Sel, args: A) -> Result<R, String>
        where T: Message, A: MessageArguments + ::EncodeArguments,
        R: Any + ::Encode {
    use self::verify::verify_message_signature;

    if obj.is_null() {
        return Err(format!("Messaging {:?} to nil", sel));
    }

    verify_message_signature::<A, R>(superclass, sel).and_then(|_| {
        send_super_unverified(obj, superclass, sel, args)
    })
}

#[cfg(test)]
mod tests {
    use runtime::Object;
    use test_utils;

    #[test]
    fn test_send_message() {
        let obj = test_utils::custom_object();
        let result: u32 = unsafe {
            let _: () = msg_send![obj, setFoo:4u32];
            msg_send![obj, foo]
        };
        assert!(result == 4);
    }

    #[test]
    fn test_send_message_stret() {
        let obj = test_utils::custom_object();
        let result: test_utils::CustomStruct = unsafe {
            msg_send![obj, customStruct]
        };
        let expected = test_utils::CustomStruct { a: 1, b:2, c: 3, d: 4 };
        assert!(result == expected);
    }

    #[test]
    fn test_send_message_nil() {
        let nil: *mut Object = ::std::ptr::null_mut();
        let result: usize = unsafe {
            msg_send![nil, hash]
        };
        assert!(result == 0);

        let result: *mut Object = unsafe {
            msg_send![nil, description]
        };
        assert!(result.is_null());

        let result: f64 = unsafe {
            msg_send![nil, doubleValue]
        };
        assert!(result == 0.0);
    }

    #[test]
    fn test_send_message_super() {
        let obj = test_utils::custom_subclass_object();
        let superclass = test_utils::custom_class();
        unsafe {
            let _: () = msg_send![obj, setFoo:4u32];
            let foo: u32 = msg_send![super(obj, superclass), foo];
            assert!(foo == 4);

            // The subclass is overriden to return foo + 2
            let foo: u32 = msg_send![obj, foo];
            assert!(foo == 6);
        }
    }
}
<|endoftext|>


<commit_before>//! The server logic for the game.
//!
//! In order for the multiplayer to work, the server program listens for websocket connections.
//! This module implements that logic.

mod events;
mod gamestate;

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

use websocket;
use message;
use std::io;

use websocket::message::Type;
use websocket::{Server, Message, Receiver};
use websocket::server::Connection;
use websocket::stream::WebSocketStream;
use std::sync::mpsc;

use time;
use std::str::{self, FromStr};
use std::time::Duration;

pub use self::events::*;
pub use self::gamestate::GameState;

/// The main listening loop for the server.
pub fn listen(host: &str, port: u16, game_messages_sender: mpsc::Sender<WebSocketEvent>) {
    println!("Listening on {}:{}", host, port);
    let server = Server::bind((host, port)).unwrap();

    let mut next_client_id = 0;

    for connection in server {
        let temp = game_messages_sender.clone();
        let id = next_client_id;
        next_client_id += 1;
        // Spawn a new thread for each connection.
        let _ = thread::spawn(move || {
            if let Err(e) = handle_connection(id, connection, temp) {
                panic!("Connection {} quit with error {:?}", id, e)
            }
        });
    }
}

/// Spawns the main game loop in a separate thread. Non-blocking.
///
/// The general idea for the game loop is to update the game state every 16 milliseconds (60 FPS), processing messages along the way.
pub fn start_game_loop(game_messages: mpsc::Receiver<WebSocketEvent>) {
    static ITER_LENGTH: u64 = 16 * 1000000; // 16 milliseconds

    let _ = thread::spawn(move || {
        let mut game_state = GameState::new();

        let start_time = time::precise_time_ns();
        let mut iter: u64 = 1;
        loop {
            game_state.process_websocket_events(&game_messages);
            game_state.process_game_update();
            game_state.send_state_updates();

            // Sleep if needed to the next update
            let time_till_next = ((iter * ITER_LENGTH) as i64) -
                                 ((time::precise_time_ns() - start_time) as i64);
            iter += 1;
            if time_till_next > 0 {
                thread::sleep(Duration::new(0, time_till_next as u32));
            }
        }
    });
}

#[derive(Debug)]
enum ServerError {
    WebSocketError(websocket::result::WebSocketError),
    IoError(io::Error),
}

impl From<io::Error> for ServerError {
    fn from(error: io::Error) -> ServerError {
        ServerError::IoError(error)
    }
}

impl From<websocket::result::WebSocketError> for ServerError {
    fn from(error: websocket::result::WebSocketError) -> ServerError {
        ServerError::WebSocketError(error)
    }
}

/// Handle a given connection.
///
/// The basic idea is what we create two infinite loops:
/// One which forever reads from the game loop via a channel and sends stuff to the websocket when requested.
/// And one which forever reads from a websocket and sends the stuff to the game loop via a channel.
fn handle_connection(id: u32,
                     connection: io::Result<Connection<WebSocketStream, WebSocketStream>>,
                     game_messages_sender: mpsc::Sender<WebSocketEvent>)
                     -> Result<(), ServerError> {
    let request = try!(connection.unwrap().read_request()); // Get the request

    try!(request.validate()); // Validate the request
    let response = request.accept(); // Form a response
    let mut client = try!(response.send()); // Send the response

    let ip = client.get_mut_sender()
                   .get_mut()
                   .peer_addr()
                   .unwrap();

    println!("Connection from {}", id);

    let (sender, mut receiver) = client.split();

    // Create the channel which will allow the game loop to send messages to websockets.
    let (tx, rx) = channel();

    // Should never fail
    game_messages_sender.send(WebSocketEvent::ClientCreated { client: Client::new(id, tx) })
                        .unwrap();

    // Create the thread for sending websocket messages.
    let _ = thread::spawn(move || {
        if let Err(e) = websocket_send_loop(rx, sender) {
            panic!("Send loop had an error for client {} , {:?}", id, e)
        }
    });

    // Handle all incoming messages by forwarding them to the game loop.
    for message in receiver.incoming_messages() {
        let message: Message = try!(message);

        match message.opcode {
            Type::Close => {
                println!("Client {} disconnected", ip);

                // Should never fail
                game_messages_sender.send(WebSocketEvent::ClientClosed { client_id: id })
                                    .unwrap();
                return Ok(());
            }
            Type::Text => {
                let text = str::from_utf8(&message.payload).unwrap();

                // Should never fail
                game_messages_sender.send(WebSocketEvent::ClientMessage {
                                        client_id: id,
                                        message: message::Message::from_str(text).unwrap(),
                                    })
                                    .unwrap();
            }
            _ => {
                panic!("Unknown message type {:?}", message);
            }
        }
    }

    Ok(())
}

/// Constantly send messages over the websocket.
fn websocket_send_loop<S: websocket::Sender>(rx: mpsc::Receiver<Option<String>>,
                                             mut sender: S)
                                             -> Result<(), ServerError> {
    for message in rx {
        match message {
            Some(text) => {
                try!(sender.send_message(&Message::text(text)));
            }
            None => {
                try!(sender.send_message(&Message::close()));
                return Ok(());
            }
        }
    }

    Ok(())
}
<commit_msg>Remove unneeded unwrap.<commit_after>//! The server logic for the game.
//!
//! In order for the multiplayer to work, the server program listens for websocket connections.
//! This module implements that logic.

mod events;
mod gamestate;

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

use websocket;
use message;
use std::io;

use websocket::message::Type;
use websocket::{Server, Message, Receiver};
use websocket::server::Connection;
use websocket::stream::WebSocketStream;
use std::sync::mpsc;

use time;
use std::str::{self, FromStr};
use std::time::Duration;

pub use self::events::*;
pub use self::gamestate::GameState;

/// The main listening loop for the server.
pub fn listen(host: &str, port: u16, game_messages_sender: mpsc::Sender<WebSocketEvent>) {
    println!("Listening on {}:{}", host, port);
    let server = Server::bind((host, port)).unwrap();

    let mut next_client_id = 0;

    for connection in server {
        let temp = game_messages_sender.clone();
        let id = next_client_id;
        next_client_id += 1;
        // Spawn a new thread for each connection.
        let _ = thread::spawn(move || {
            if let Err(e) = handle_connection(id, connection, temp) {
                panic!("Connection {} quit with error {:?}", id, e)
            }
        });
    }
}

/// Spawns the main game loop in a separate thread. Non-blocking.
///
/// The general idea for the game loop is to update the game state every 16 milliseconds (60 FPS), processing messages along the way.
pub fn start_game_loop(game_messages: mpsc::Receiver<WebSocketEvent>) {
    static ITER_LENGTH: u64 = 16 * 1000000; // 16 milliseconds

    let _ = thread::spawn(move || {
        let mut game_state = GameState::new();

        let start_time = time::precise_time_ns();
        let mut iter: u64 = 1;
        loop {
            game_state.process_websocket_events(&game_messages);
            game_state.process_game_update();
            game_state.send_state_updates();

            // Sleep if needed to the next update
            let time_till_next = ((iter * ITER_LENGTH) as i64) -
                                 ((time::precise_time_ns() - start_time) as i64);
            iter += 1;
            if time_till_next > 0 {
                thread::sleep(Duration::new(0, time_till_next as u32));
            }
        }
    });
}

#[derive(Debug)]
enum ServerError {
    WebSocketError(websocket::result::WebSocketError),
    IoError(io::Error),
}

impl From<io::Error> for ServerError {
    fn from(error: io::Error) -> ServerError {
        ServerError::IoError(error)
    }
}

impl From<websocket::result::WebSocketError> for ServerError {
    fn from(error: websocket::result::WebSocketError) -> ServerError {
        ServerError::WebSocketError(error)
    }
}

/// Handle a given connection.
///
/// The basic idea is what we create two infinite loops:
/// One which forever reads from the game loop via a channel and sends stuff to the websocket when requested.
/// And one which forever reads from a websocket and sends the stuff to the game loop via a channel.
fn handle_connection(id: u32,
                     connection: io::Result<Connection<WebSocketStream, WebSocketStream>>,
                     game_messages_sender: mpsc::Sender<WebSocketEvent>)
                     -> Result<(), ServerError> {
    let request = try!(try!(connection).read_request()); // Get the request

    try!(request.validate()); // Validate the request
    let response = request.accept(); // Form a response
    let mut client = try!(response.send()); // Send the response

    let ip = try!(client.get_mut_sender()
                   .get_mut()
                   .peer_addr());

    println!("Connection from {}", id);

    let (sender, mut receiver) = client.split();

    // Create the channel which will allow the game loop to send messages to websockets.
    let (tx, rx) = channel();

    // Should never fail
    game_messages_sender.send(WebSocketEvent::ClientCreated { client: Client::new(id, tx) })
                        .unwrap();

    // Create the thread for sending websocket messages.
    let _ = thread::spawn(move || {
        if let Err(e) = websocket_send_loop(rx, sender) {
            panic!("Send loop had an error for client {} , {:?}", id, e)
        }
    });

    // Handle all incoming messages by forwarding them to the game loop.
    for message in receiver.incoming_messages() {
        let message: Message = try!(message);

        match message.opcode {
            Type::Close => {
                println!("Client {} disconnected", ip);

                // Should never fail
                game_messages_sender.send(WebSocketEvent::ClientClosed { client_id: id })
                                    .unwrap();
                return Ok(());
            }
            Type::Text => {
                let text = str::from_utf8(&message.payload).unwrap();

                // Should never fail
                game_messages_sender.send(WebSocketEvent::ClientMessage {
                                        client_id: id,
                                        message: message::Message::from_str(text).unwrap(),
                                    })
                                    .unwrap();
            }
            _ => {
                panic!("Unknown message type {:?}", message);
            }
        }
    }

    Ok(())
}

/// Constantly send messages over the websocket.
fn websocket_send_loop<S: websocket::Sender>(rx: mpsc::Receiver<Option<String>>,
                                             mut sender: S)
                                             -> Result<(), ServerError> {
    for message in rx {
        match message {
            Some(text) => {
                try!(sender.send_message(&Message::text(text)));
            }
            None => {
                try!(sender.send_message(&Message::close()));
                return Ok(());
            }
        }
    }

    Ok(())
}
<|endoftext|>


<commit_before>extern crate rustogram;
const HIGHEST_TRACKABLE_VALUE: i64 = 3600 * 1000 * 1000;
const NUMBER_OF_SIGNIFICANT_VALUE_DIGITS: i32 = 3;

#[test]
fn test_get_total_count() {
    let histogram = get_histogram();
    let raw_histogram = get_raw_histogram();
    assert_eq!(10_001, raw_histogram.get_total_count());
    assert_eq!(20_000, histogram.get_total_count());
}

#[test]
fn test_get_max_value() {
    let histogram = get_histogram();
    assert!(histogram.values_are_equivalent(100_000_000, histogram.get_max_value()));
}

#[test]
fn test_get_min_value() {
    let histogram = get_histogram();
    assert!(histogram.values_are_equivalent(1_000, histogram.get_min_value()));
}

#[test]
fn test_get_mean_value() {
    let mut histogram = get_histogram();
    let mut raw_histogram = get_raw_histogram();

    let expected_raw_mean = (10_000_000f64 + 100_000_000f64) / 10001f64;
    let expected_mean = (1_000f64 + 50_000_000f64) / 2f64;

    assert_float_eq(expected_raw_mean, raw_histogram.get_mean(), expected_raw_mean * 0.001);
    assert_float_eq(expected_mean, histogram.get_mean(), expected_mean * 0.001);
}

#[test]
fn test_get_value_at_percentile() {
    let histogram = get_histogram();
    let raw_histogram = get_raw_histogram();

    assert_eq!(1_000, raw_histogram.get_value_at_percentile(30f64));
}

#[test]
fn test_get_std_deviation() {
    let histogram = get_histogram();
    let raw_histogram = get_raw_histogram();

    let expected_raw_mean = (10_000_000f64 + 100_000_000f64) / 10001f64;
    let expected_raw_std_dev = (((10000.0 * (1000.0 - expected_raw_mean).powf(2f64)) +
                                (100000000.0 - expected_raw_mean).powf(2f64)) / 10001f64).sqrt();
    let expected_mean = (1_000f64 + 50_000_000f64) / 2f64;
    let mut expected_square_deviation_sum = 10_000f64 * (1_000f64 - expected_mean).powf(2f64);
    let mut value = 10_000;
    while value <= 100_000_000 {
        expected_square_deviation_sum += (value as f64 - expected_mean).powf(2f64);
        value += 10_000;
    }
    let expected_std_dev = (expected_square_deviation_sum as f64 / 20_000f64).sqrt();

    assert_float_eq(expected_raw_std_dev, raw_histogram.get_std_deviation(), expected_raw_std_dev * 0.001);
    assert_float_eq(expected_std_dev, histogram.get_std_deviation(), expected_std_dev * 0.001);
}

fn assert_float_eq(expected: f64, actual: f64, delta: f64) {
    // TODO improve error message
    assert!(actual > expected - delta && actual < expected + delta);
}

fn get_histogram() -> rustogram::Histogram {
    let mut h = rustogram::new_histogram(HIGHEST_TRACKABLE_VALUE, NUMBER_OF_SIGNIFICANT_VALUE_DIGITS);

    let mut i = 10_000;
    while i != 0 {
        h.record_value_with_expected_interval(1_000, 10_000);
        i -= 1;
    }
    h.record_value_with_expected_interval(100_000_000, 10_000);
    h
}

fn get_raw_histogram() -> rustogram::Histogram {
     let mut h = rustogram::new_histogram(HIGHEST_TRACKABLE_VALUE, NUMBER_OF_SIGNIFICANT_VALUE_DIGITS);

    let mut i = 10_000;
    while i != 0 {
        h.record_value(1_000);
        i -= 1;
    }
    h.record_value(100_000_000);
    h
}
<commit_msg>more get_value_at_percentile tests<commit_after>extern crate rustogram;
const HIGHEST_TRACKABLE_VALUE: i64 = 3600 * 1000 * 1000;
const NUMBER_OF_SIGNIFICANT_VALUE_DIGITS: i32 = 3;

#[test]
fn test_get_total_count() {
    let histogram = get_histogram();
    let raw_histogram = get_raw_histogram();
    assert_eq!(10_001, raw_histogram.get_total_count());
    assert_eq!(20_000, histogram.get_total_count());
}

#[test]
fn test_get_max_value() {
    let histogram = get_histogram();
    assert!(histogram.values_are_equivalent(100_000_000, histogram.get_max_value()));
}

#[test]
fn test_get_min_value() {
    let histogram = get_histogram();
    assert!(histogram.values_are_equivalent(1_000, histogram.get_min_value()));
}

#[test]
fn test_get_mean_value() {
    let mut histogram = get_histogram();
    let mut raw_histogram = get_raw_histogram();

    let expected_raw_mean = (10_000_000f64 + 100_000_000f64) / 10001f64;
    let expected_mean = (1_000f64 + 50_000_000f64) / 2f64;

    assert_float_eq(expected_raw_mean, raw_histogram.get_mean(), expected_raw_mean * 0.001);
    assert_float_eq(expected_mean, histogram.get_mean(), expected_mean * 0.001);
}

#[test]
fn test_get_std_deviation() {
    let histogram = get_histogram();
    let raw_histogram = get_raw_histogram();

    let expected_raw_mean = (10_000_000f64 + 100_000_000f64) / 10001f64;
    let expected_raw_std_dev = (((10000.0 * (1000.0 - expected_raw_mean).powf(2f64)) +
                                (100000000.0 - expected_raw_mean).powf(2f64)) / 10001f64).sqrt();
    let expected_mean = (1_000f64 + 50_000_000f64) / 2f64;
    let mut expected_square_deviation_sum = 10_000f64 * (1_000f64 - expected_mean).powf(2f64);
    let mut value = 10_000;
    while value <= 100_000_000 {
        expected_square_deviation_sum += (value as f64 - expected_mean).powf(2f64);
        value += 10_000;
    }
    let expected_std_dev = (expected_square_deviation_sum as f64 / 20_000f64).sqrt();

    assert_float_eq(expected_raw_std_dev, raw_histogram.get_std_deviation(), expected_raw_std_dev * 0.001);
    assert_float_eq(expected_std_dev, histogram.get_std_deviation(), expected_std_dev * 0.001);
}

#[test]
fn test_get_value_at_percentile() {
    let histogram = get_histogram();
    let raw_histogram = get_raw_histogram();

    assert_float_eq(1000.0, raw_histogram.get_value_at_percentile(30.0) as f64, 1000.0 * 0.001);
    assert_float_eq(1000.0, raw_histogram.get_value_at_percentile(99.0) as f64, 1000.0 * 0.001);
    assert_float_eq(1000.0, raw_histogram.get_value_at_percentile(99.99) as f64, 1000.0 * 0.001);
    assert_float_eq(100000000.0, raw_histogram.get_value_at_percentile(99.999) as f64, 100000000.0 * 0.001);
    assert_float_eq(100000000.0, raw_histogram.get_value_at_percentile(100.0) as f64, 100000000.0 * 0.001);

    assert_float_eq(1000.0, histogram.get_value_at_percentile(30.0) as f64, 1000.0 * 0.001);
    assert_float_eq(1000.0, histogram.get_value_at_percentile(50.0) as f64, 1000.0 * 0.001);
    assert_float_eq(50000000.0, histogram.get_value_at_percentile(75.0) as f64, 50000000.0 * 0.001);
    assert_float_eq(80000000.0, histogram.get_value_at_percentile(90.0) as f64, 80000000.0 * 0.001);
    assert_float_eq(98000000.0, histogram.get_value_at_percentile(99.0) as f64, 98000000.0 * 0.001);
    assert_float_eq(100000000.0, histogram.get_value_at_percentile(99.999) as f64, 100000000.0 * 0.001);
    assert_float_eq(100000000.0, histogram.get_value_at_percentile(100.0) as f64, 100000000.0 * 0.001);

}

fn assert_float_eq(expected: f64, actual: f64, delta: f64) {
    if !(actual > expected - delta && actual < expected + delta) {
        panic!(format!("Expected {} to be equal to {} +/-{}", actual, expected, delta));
    }
}

fn get_histogram() -> rustogram::Histogram {
    let mut h = rustogram::new_histogram(HIGHEST_TRACKABLE_VALUE, NUMBER_OF_SIGNIFICANT_VALUE_DIGITS);

    let mut i = 10_000;
    while i != 0 {
        h.record_value_with_expected_interval(1_000, 10_000);
        i -= 1;
    }
    h.record_value_with_expected_interval(100_000_000, 10_000);
    h
}

fn get_raw_histogram() -> rustogram::Histogram {
     let mut h = rustogram::new_histogram(HIGHEST_TRACKABLE_VALUE, NUMBER_OF_SIGNIFICANT_VALUE_DIGITS);

    let mut i = 10_000;
    while i != 0 {
        h.record_value(1_000);
        i -= 1;
    }
    h.record_value(100_000_000);
    h
}
<|endoftext|>


<commit_before>extern crate thoughtfuck;
mod common;

use common::FauxStdout;
use thoughtfuck::vm::*;
use thoughtfuck::program::*;
use thoughtfuck::parse::parse;

#[test]
fn hello_world () {
    const SOURCE: &str = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
    let commands = parse(SOURCE);

    let mut program = Program::new();
    program.append(&commands);

    let mut vm = VM::new(Some(Box::new(FauxStdout::new())));
    program.execute(&mut vm);
}
<commit_msg>Finalize hello_world integration test<commit_after>extern crate thoughtfuck;
mod common;

use common::FauxStdout;
use thoughtfuck::vm::*;
use thoughtfuck::program::*;
use thoughtfuck::parse::parse;

#[test]
fn hello_world () {
    const SOURCE: &str = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
    let commands = parse(SOURCE);

    let mut program = Program::new();
    program.append(&commands);

    let mut stdout = FauxStdout::new();
    {
        let mut vm = VM::new(&mut stdout);
        program.execute(&mut vm);
    }
    assert_eq!(stdout.buffer, "Hello World!\n");
}
<|endoftext|>


<commit_before>macro_rules! run_aggregate_test {
    ( $db:expr, $coll:expr, $pipeline:expr, $opt:expr, $out:expr, $outcome:expr ) => {{
        let mut cursor = $coll.aggregate($pipeline, $opt).unwrap();

        if !$out {
            let array = match $outcome.result {
                Bson::Array(ref arr) => arr.clone(),
                _ => panic!("Invalid `result` of aggregate test")
            };

            for bson in array {
                let b2 = &Bson::Document(cursor.next().unwrap().unwrap());
                assert!(eq::bson_eq(&bson, b2));
            }

            assert!(!cursor.has_next().ok().expect("Failed to execute 'has_next()' on cursor"));
        }

        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_count_test {
    ( $db:expr, $coll:expr, $filter:expr, $opt:expr, $outcome:expr ) => {{
        let n = $coll.count($filter, $opt).unwrap();
        assert!($outcome.result.int_eq(n));
        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_delete_test {
    ( $db:expr, $coll:expr, $filter:expr, $outcome:expr, $many:expr ) => {{
        let count = if $many {
                        $coll.delete_many($filter, None)
                    } else {
                        $coll.delete_one($filter, None)
                    };

        let expected = count.unwrap().deleted_count;

        let actual = match $outcome.result {
            Bson::Document(ref doc) => doc.get("deletedCount").unwrap(),
            _ => panic!("`delete` test result should be a document")
        };

        assert!(actual.int_eq(expected as i64));
        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_distinct_test {
    ( $db:expr, $coll:expr, $field_name:expr, $filter:expr, $outcome:expr ) => {{
        let actual = $coll.distinct(&$field_name, $filter, None).unwrap();

        let expected = match $outcome.result {
            Bson::Array(ref arr) => arr.clone(),
            _ => panic!("Invalid `result` of distinct test")
        };

        assert_eq!(actual.len(), expected.len());

        for i in 0..actual.len() {
            assert!(eq::bson_eq(&actual[i], &expected[i]));
        }

        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_find_one_and_delete_test {
    ( $db:expr, $coll:expr, $filter:expr, $opt:expr, $outcome:expr ) => {{
        let doc_opt = $coll.find_one_and_delete($filter, $opt).unwrap();

        let bson = match doc_opt {
            Some(ref doc) => Bson::Document(doc.clone()),
            None => Bson::Null
        };

        assert!(eq::bson_eq(&bson, &$outcome.result));
        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_find_one_and_replace_test {
    ( $db:expr, $coll:expr, $filter:expr, $replacement:expr, $opt:expr,
      $outcome:expr ) => {{
          let doc_opt = $coll.find_one_and_replace($filter, $replacement,
                                                   $opt).unwrap();

          let bson = match doc_opt {
              Some(ref doc) => Bson::Document(doc.clone()),
              None => Bson::Null
          };

          assert!(eq::bson_eq(&bson, &$outcome.result));
          check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_find_one_and_update_test {
    ( $db:expr, $coll:expr, $filter:expr, $update:expr, $opt:expr,
      $outcome:expr ) => {{
          let doc_opt = $coll.find_one_and_update($filter, $update, $opt).unwrap();

          let bson = match doc_opt {
              Some(ref doc) => Bson::Document(doc.clone()),
              None => Bson::Null
          };

          assert!(eq::bson_eq(&bson, &$outcome.result));
          check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_find_test {
    ( $db:expr, $coll:expr, $filter:expr, $opt:expr, $outcome:expr ) => {{
        let mut cursor = $coll.find($filter, $opt).unwrap();

        let array = match $outcome.result {
            Bson::Array(ref arr) => arr.clone(),
            _ => panic!("Invalid `result` of find test")
        };

        for bson in array {
            assert!(eq::bson_eq(&bson, &Bson::Document(cursor.next().unwrap().unwrap())));
        }

        assert!(!cursor.has_next().ok().expect("Failed to execute 'has_next()' on cursor"));
        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_insert_many_test {
    ( $db:expr, $coll:expr, $docs:expr, $outcome:expr ) => {{
        let inserted = $coll.insert_many($docs, true, None).unwrap().inserted_ids.unwrap();
        let ids_bson = match $outcome.result {
            Bson::Document(ref doc) => doc.get("insertedIds").unwrap(),
            _ => panic!("`insert_many` test result should be a document")
        };

        let ids = match ids_bson {
            &Bson::Array(ref arr) => arr.into_iter(),
            _ => panic!("`insertedIds` test result should be an array")
        };

        let mut actual_ids = inserted.values();

        for expected_id in ids {
            assert!(eq::bson_eq(&expected_id, actual_ids.next().unwrap()));
        }

        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_insert_one_test {
    ( $db:expr, $coll:expr, $doc:expr, $outcome:expr ) => {{
        let inserted = $coll.insert_one($doc, None).unwrap().inserted_id.unwrap();
        let id = match $outcome.result {
            Bson::Document(ref doc) => doc.get("insertedId").unwrap(),
            _ => panic!("`insert_one` test result should be a document")
        };

        assert!(eq::bson_eq(&id, &inserted));
        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_replace_one_test {
    ( $db:expr, $coll:expr, $filter:expr, $replacement:expr, $upsert:expr,
        $outcome:expr ) => {{
            let actual = $coll.replace_one($filter, $replacement, $upsert,
                                           None).unwrap();

            let (matched, modified, upserted) = match $outcome.result {
                Bson::Document(ref doc) => (
                    doc.get("matchedCount").unwrap(),
                    doc.get("modifiedCount").unwrap(),
                    doc.get("upsertedId"),
                    ),
                _ => panic!("`delete` test result should be a document")
            };

            assert!(matched.int_eq(actual.matched_count as i64));
            assert!(modified.int_eq(actual.modified_count as i64));

            let id = match actual.upserted_id {
                Some(Bson::Document(ref doc)) => doc.get("_id"),
                _ => None
            };

            match (upserted, id) {
                (None, None) => (),
                (Some(ref bson1), Some(ref bson2)) =>
                assert!(eq::bson_eq(&bson1, &bson2)),
                _ => panic!("Wrong `upsertedId` returned")
            };

            check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_update_test {
    ( $db:expr, $coll:expr, $filter:expr, $update:expr, $upsert:expr,
      $many:expr, $outcome:expr ) => {{
          let result = if $many {
                           $coll.update_many($filter, $update, $upsert, None)
                       } else {
                           $coll.update_one($filter, $update, $upsert, None)
                       };

          let actual = result.unwrap();

          let (matched, modified, upserted) = match $outcome.result {
              Bson::Document(ref doc) => (
                  doc.get("matchedCount").unwrap(),
                  doc.get("modifiedCount").unwrap(),
                  doc.get("upsertedId"),
              ),
              _ => panic!("`update` test result should be a document")
          };

          assert!(matched.int_eq(actual.matched_count as i64));
          assert!(modified.int_eq(actual.modified_count as i64));

          let id = match actual.upserted_id {
	          Some(Bson::Document(ref doc)) => doc.get("_id"),
              _ => None
          };

          match (upserted, id) {
              (None, None) => (),
              (Some(ref bson1), Some(ref bson2)) =>
                  assert!(eq::bson_eq(&bson1, &bson2)),
              _ => panic!("Wrong `upsertedId` returned")
          };

          check_coll!($db, $coll, $outcome.collection);
    }};
}

#[macro_export]
macro_rules! run_suite {
    ( $file:expr, $coll:expr ) => {{
        let json = Json::from_file($file).unwrap();
        let mut suite = json.get_suite().unwrap();
        let client =  Client::connect("localhost", 27017).unwrap();
        let db = client.db("test");
        let coll = db.collection($coll);

        suite.tests.remove(0);

        for test in suite.tests {
            coll.drop().unwrap();
            coll.insert_many(suite.data.clone(), true, None).unwrap();

            match test.operation {
                Arguments::Aggregate { pipeline, options, out } =>
                    run_aggregate_test!(db, coll, pipeline, Some(options), out,
                                        test.outcome),
                Arguments::Count { filter, options } =>
                    run_count_test!(db, coll, filter, Some(options), test.outcome),
                Arguments::Delete { filter, many } =>
                    run_delete_test!(db, coll, filter, test.outcome, many),
                Arguments::Distinct { field_name, filter } =>
                    run_distinct_test!(db, coll, field_name, filter, test.outcome),
                Arguments::Find { filter, options } =>
                    run_find_test!(db, coll, filter, Some(options), test.outcome),
                Arguments::FindOneAndDelete { filter, options } =>
                    run_find_one_and_delete_test!(db, coll, filter,
                                                  Some(options), test.outcome),
                Arguments::FindOneAndReplace { filter, replacement, options } =>
                    run_find_one_and_replace_test!(db, coll, filter, replacement,
                                                   Some(options), test.outcome),
                Arguments::FindOneAndUpdate { filter, update, options } =>
                    run_find_one_and_update_test!(db, coll, filter, update,
                                                  Some(options), test.outcome),
                Arguments::InsertMany { documents } =>
                    run_insert_many_test!(db, coll, documents, test.outcome),
                Arguments::InsertOne { document } =>
                    run_insert_one_test!(db, coll, document, test.outcome),
                Arguments::ReplaceOne { filter, replacement, upsert } =>
                    run_replace_one_test!(db, coll, filter, replacement, upsert,
                                          test.outcome),
                Arguments::Update { filter, update, upsert, many } =>
                    run_update_test!(db, coll, filter, update, upsert, many,
                                     test.outcome),
            };
        }
    }};
}

#[macro_export]
macro_rules! check_coll {
    ( $db:expr, $coll:expr, $coll_opt:expr ) => {{
        let outcome_coll = match $coll_opt {
            Some(ref coll) => coll.clone(),
            None => continue
        };

        let coll = match outcome_coll.name {
            Some(ref str) => $db.collection(&str),
            None => $db.collection(&$coll.name())
        };

        let mut cursor = coll.find(None, None).unwrap();

        for doc in outcome_coll.data.iter() {
            assert!(eq::bson_eq(&Bson::Document(doc.clone()),
                                &Bson::Document(cursor.next().unwrap().unwrap())));
        }

        assert!(!cursor.has_next().ok().expect("Failed to execute 'has_next()' on cursor"));

        $coll.drop().unwrap();
    }};
}
<commit_msg>changed it so first test in set isn't dropped<commit_after>macro_rules! run_aggregate_test {
    ( $db:expr, $coll:expr, $pipeline:expr, $opt:expr, $out:expr, $outcome:expr ) => {{
        let mut cursor = $coll.aggregate($pipeline, $opt).unwrap();

        if !$out {
            let array = match $outcome.result {
                Bson::Array(ref arr) => arr.clone(),
                _ => panic!("Invalid `result` of aggregate test")
            };

            for bson in array {
                let b2 = &Bson::Document(cursor.next().unwrap().unwrap());
                assert!(eq::bson_eq(&bson, b2));
            }

            assert!(!cursor.has_next().ok().expect("Failed to execute 'has_next()' on cursor"));
        }

        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_count_test {
    ( $db:expr, $coll:expr, $filter:expr, $opt:expr, $outcome:expr ) => {{
        let n = $coll.count($filter, $opt).unwrap();
        assert!($outcome.result.int_eq(n));
        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_delete_test {
    ( $db:expr, $coll:expr, $filter:expr, $outcome:expr, $many:expr ) => {{
        let count = if $many {
                        $coll.delete_many($filter, None)
                    } else {
                        $coll.delete_one($filter, None)
                    };

        let expected = count.unwrap().deleted_count;

        let actual = match $outcome.result {
            Bson::Document(ref doc) => doc.get("deletedCount").unwrap(),
            _ => panic!("`delete` test result should be a document")
        };

        assert!(actual.int_eq(expected as i64));
        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_distinct_test {
    ( $db:expr, $coll:expr, $field_name:expr, $filter:expr, $outcome:expr ) => {{
        let actual = $coll.distinct(&$field_name, $filter, None).unwrap();

        let expected = match $outcome.result {
            Bson::Array(ref arr) => arr.clone(),
            _ => panic!("Invalid `result` of distinct test")
        };

        assert_eq!(actual.len(), expected.len());

        for i in 0..actual.len() {
            assert!(eq::bson_eq(&actual[i], &expected[i]));
        }

        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_find_one_and_delete_test {
    ( $db:expr, $coll:expr, $filter:expr, $opt:expr, $outcome:expr ) => {{
        let doc_opt = $coll.find_one_and_delete($filter, $opt).unwrap();

        let bson = match doc_opt {
            Some(ref doc) => Bson::Document(doc.clone()),
            None => Bson::Null
        };

        assert!(eq::bson_eq(&bson, &$outcome.result));
        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_find_one_and_replace_test {
    ( $db:expr, $coll:expr, $filter:expr, $replacement:expr, $opt:expr,
      $outcome:expr ) => {{
          let doc_opt = $coll.find_one_and_replace($filter, $replacement,
                                                   $opt).unwrap();

          let bson = match doc_opt {
              Some(ref doc) => Bson::Document(doc.clone()),
              None => Bson::Null
          };

          assert!(eq::bson_eq(&bson, &$outcome.result));
          check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_find_one_and_update_test {
    ( $db:expr, $coll:expr, $filter:expr, $update:expr, $opt:expr,
      $outcome:expr ) => {{
          let doc_opt = $coll.find_one_and_update($filter, $update, $opt).unwrap();

          let bson = match doc_opt {
              Some(ref doc) => Bson::Document(doc.clone()),
              None => Bson::Null
          };

          assert!(eq::bson_eq(&bson, &$outcome.result));
          check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_find_test {
    ( $db:expr, $coll:expr, $filter:expr, $opt:expr, $outcome:expr ) => {{
        let mut cursor = $coll.find($filter, $opt).unwrap();

        let array = match $outcome.result {
            Bson::Array(ref arr) => arr.clone(),
            _ => panic!("Invalid `result` of find test")
        };

        for bson in array {
            assert!(eq::bson_eq(&bson, &Bson::Document(cursor.next().unwrap().unwrap())));
        }

        assert!(!cursor.has_next().ok().expect("Failed to execute 'has_next()' on cursor"));
        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_insert_many_test {
    ( $db:expr, $coll:expr, $docs:expr, $outcome:expr ) => {{
        let inserted = $coll.insert_many($docs, true, None).unwrap().inserted_ids.unwrap();
        let ids_bson = match $outcome.result {
            Bson::Document(ref doc) => doc.get("insertedIds").unwrap(),
            _ => panic!("`insert_many` test result should be a document")
        };

        let ids = match ids_bson {
            &Bson::Array(ref arr) => arr.into_iter(),
            _ => panic!("`insertedIds` test result should be an array")
        };

        let mut actual_ids = inserted.values();

        for expected_id in ids {
            assert!(eq::bson_eq(&expected_id, actual_ids.next().unwrap()));
        }

        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_insert_one_test {
    ( $db:expr, $coll:expr, $doc:expr, $outcome:expr ) => {{
        let inserted = $coll.insert_one($doc, None).unwrap().inserted_id.unwrap();
        let id = match $outcome.result {
            Bson::Document(ref doc) => doc.get("insertedId").unwrap(),
            _ => panic!("`insert_one` test result should be a document")
        };

        assert!(eq::bson_eq(&id, &inserted));
        check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_replace_one_test {
    ( $db:expr, $coll:expr, $filter:expr, $replacement:expr, $upsert:expr,
        $outcome:expr ) => {{
            let actual = $coll.replace_one($filter, $replacement, $upsert,
                                           None).unwrap();

            let (matched, modified, upserted) = match $outcome.result {
                Bson::Document(ref doc) => (
                    doc.get("matchedCount").unwrap(),
                    doc.get("modifiedCount").unwrap(),
                    doc.get("upsertedId"),
                    ),
                _ => panic!("`delete` test result should be a document")
            };

            assert!(matched.int_eq(actual.matched_count as i64));
            assert!(modified.int_eq(actual.modified_count as i64));

            let id = match actual.upserted_id {
                Some(Bson::Document(ref doc)) => doc.get("_id"),
                _ => None
            };

            match (upserted, id) {
                (None, None) => (),
                (Some(ref bson1), Some(ref bson2)) =>
                assert!(eq::bson_eq(&bson1, &bson2)),
                _ => panic!("Wrong `upsertedId` returned")
            };

            check_coll!($db, $coll, $outcome.collection);
    }};
}

macro_rules! run_update_test {
    ( $db:expr, $coll:expr, $filter:expr, $update:expr, $upsert:expr,
      $many:expr, $outcome:expr ) => {{
          let result = if $many {
                           $coll.update_many($filter, $update, $upsert, None)
                       } else {
                           $coll.update_one($filter, $update, $upsert, None)
                       };

          let actual = result.unwrap();

          let (matched, modified, upserted) = match $outcome.result {
              Bson::Document(ref doc) => (
                  doc.get("matchedCount").unwrap(),
                  doc.get("modifiedCount").unwrap(),
                  doc.get("upsertedId"),
              ),
              _ => panic!("`update` test result should be a document")
          };

          assert!(matched.int_eq(actual.matched_count as i64));
          assert!(modified.int_eq(actual.modified_count as i64));

          let id = match actual.upserted_id {
	          Some(Bson::Document(ref doc)) => doc.get("_id"),
              _ => None
          };

          match (upserted, id) {
              (None, None) => (),
              (Some(ref bson1), Some(ref bson2)) =>
                  assert!(eq::bson_eq(&bson1, &bson2)),
              _ => panic!("Wrong `upsertedId` returned")
          };

          check_coll!($db, $coll, $outcome.collection);
    }};
}

#[macro_export]
macro_rules! run_suite {
    ( $file:expr, $coll:expr ) => {{
        let json = Json::from_file($file).unwrap();
        let suite = json.get_suite().unwrap();
        let client =  Client::connect("localhost", 27017).unwrap();
        let db = client.db("test");
        let coll = db.collection($coll);

        for test in suite.tests {
            coll.drop().unwrap();
            coll.insert_many(suite.data.clone(), true, None).unwrap();

            match test.operation {
                Arguments::Aggregate { pipeline, options, out } =>
                    run_aggregate_test!(db, coll, pipeline, Some(options), out,
                                        test.outcome),
                Arguments::Count { filter, options } =>
                    run_count_test!(db, coll, filter, Some(options), test.outcome),
                Arguments::Delete { filter, many } =>
                    run_delete_test!(db, coll, filter, test.outcome, many),
                Arguments::Distinct { field_name, filter } =>
                    run_distinct_test!(db, coll, field_name, filter, test.outcome),
                Arguments::Find { filter, options } =>
                    run_find_test!(db, coll, filter, Some(options), test.outcome),
                Arguments::FindOneAndDelete { filter, options } =>
                    run_find_one_and_delete_test!(db, coll, filter,
                                                  Some(options), test.outcome),
                Arguments::FindOneAndReplace { filter, replacement, options } =>
                    run_find_one_and_replace_test!(db, coll, filter, replacement,
                                                   Some(options), test.outcome),
                Arguments::FindOneAndUpdate { filter, update, options } =>
                    run_find_one_and_update_test!(db, coll, filter, update,
                                                  Some(options), test.outcome),
                Arguments::InsertMany { documents } =>
                    run_insert_many_test!(db, coll, documents, test.outcome),
                Arguments::InsertOne { document } =>
                    run_insert_one_test!(db, coll, document, test.outcome),
                Arguments::ReplaceOne { filter, replacement, upsert } =>
                    run_replace_one_test!(db, coll, filter, replacement, upsert,
                                          test.outcome),
                Arguments::Update { filter, update, upsert, many } =>
                    run_update_test!(db, coll, filter, update, upsert, many,
                                     test.outcome),
            };
        }
    }};
}

#[macro_export]
macro_rules! check_coll {
    ( $db:expr, $coll:expr, $coll_opt:expr ) => {{
        let outcome_coll = match $coll_opt {
            Some(ref coll) => coll.clone(),
            None => continue
        };

        let coll = match outcome_coll.name {
            Some(ref str) => $db.collection(&str),
            None => $db.collection(&$coll.name())
        };

        let mut cursor = coll.find(None, None).unwrap();

        for doc in outcome_coll.data.iter() {
            assert!(eq::bson_eq(&Bson::Document(doc.clone()),
                                &Bson::Document(cursor.next().unwrap().unwrap())));
        }

        assert!(!cursor.has_next().ok().expect("Failed to execute 'has_next()' on cursor"));

        $coll.drop().unwrap();
    }};
}
<|endoftext|>


<commit_before>fn main() {
    // `print!` is like `println!` but it doesn't add a newline at the end
    print!("January has ");

    // `{}` are placeholders for arguments that will be stringified
    println!("{} days", 31);

    // The positional arguments can be reused along the template
    println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");

    // Named arguments can also be used
    println!("{subject} {verb} {predicate}",
             predicate="over the lazy dog",
             subject="the quick brown fox",
             verb="jumps");

    // Special formatting can be specified in the placeholder after a `:`
    println!("{} of {:t} people know binary, the other half don't", 1, 2);

    // Error! You are missing an argument
    println!("My name is {0}, {1} {0}", "Bond");
    // FIXME ^ Add the missing argument: "James"
}
<commit_msg>print: append type suffix to integer literals<commit_after>fn main() {
    // `print!` is like `println!` but it doesn't add a newline at the end
    print!("January has ");

    // `{}` are placeholders for arguments that will be stringified
    println!("{} days", 31i);

    // The positional arguments can be reused along the template
    println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");

    // Named arguments can also be used
    println!("{subject} {verb} {predicate}",
             predicate="over the lazy dog",
             subject="the quick brown fox",
             verb="jumps");

    // Special formatting can be specified in the placeholder after a `:`
    println!("{} of {:t} people know binary, the other half don't", 1i, 2i);

    // Error! You are missing an argument
    println!("My name is {0}, {1} {0}", "Bond");
    // FIXME ^ Add the missing argument: "James"
}
<|endoftext|>


<commit_before>fn main() {
    // `print!` is like `println!` but it doesn't add a newline at the end
    print!("January has ");

    // `{}` are placeholders for arguments that will be stringified
    println!("{} days", 31);
    // The `i` suffix indicates the compiler that this literal has type: signed
    // pointer size integer, see next chapter for more details

    // The positional arguments can be reused along the template
    println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");

    // Named arguments can also be used
    println!("{subject} {verb} {predicate}",
             predicate="over the lazy dog",
             subject="the quick brown fox",
             verb="jumps");

    // Special formatting can be specified in the placeholder after a `:`
    println!("{} of {:b} people know binary, the other half don't", 1i, 2i);

    // Error! You are missing an argument
    println!("My name is {0}, {1} {0}", "Bond");
    // FIXME ^ Add the missing argument: "James"
}
<commit_msg>the `i` suffix on integers is deprecated<commit_after>fn main() {
    // `print!` is like `println!` but it doesn't add a newline at the end
    print!("January has ");

    // `{}` are placeholders for arguments that will be stringified
    println!("{} days", 31);
    // The `i` suffix indicates the compiler that this literal has type: signed
    // pointer size integer, see next chapter for more details

    // The positional arguments can be reused along the template
    println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");

    // Named arguments can also be used
    println!("{subject} {verb} {predicate}",
             predicate="over the lazy dog",
             subject="the quick brown fox",
             verb="jumps");

    // Special formatting can be specified in the placeholder after a `:`
    println!("{} of {:b} people know binary, the other half don't", 1, 2);

    // Error! You are missing an argument
    println!("My name is {0}, {1} {0}", "Bond");
    // FIXME ^ Add the missing argument: "James"
}
<|endoftext|>