<commit_before>#![feature(libc)]
#![feature(std_misc)]
#![feature(optin_builtin_traits)]

extern crate gag;
extern crate libc;
extern crate num;
#[macro_use] extern crate enum_primitive;
extern crate termbox_sys as termbox;
#[macro_use] extern crate bitflags;

pub use self::style::{Style, RB_BOLD, RB_UNDERLINE, RB_REVERSE, RB_NORMAL};

use std::error::Error;
use std::fmt;
use std::io;
use std::char;
use std::time::duration::Duration;
use std::default::Default;

use num::FromPrimitive;
use termbox::RawEvent;
use libc::c_int;
use gag::Hold;

pub mod keyboard;
pub mod mouse;

pub use keyboard::Key;
pub use mouse::Mouse;

#[derive(Clone, Copy)]
pub enum Event {
    KeyEventRaw(u8, u16, u32),
    KeyEvent(Option<Key>),
    ResizeEvent(i32, i32),
    MouseEvent(Mouse, i32, i32),
    NoEvent
}

#[derive(Clone, Copy, Debug)]
pub enum InputMode {
    Current = 0x00,

    /// When ESC sequence is in the buffer and it doesn't match any known
    /// ESC sequence => ESC means TB_KEY_ESC
    Esc     = 0x01,
    /// When ESC sequence is in the buffer and it doesn't match any known
    /// sequence => ESC enables TB_MOD_ALT modifier for the next keyboard event.
    Alt     = 0x02,
}

#[derive(Clone, Copy, PartialEq)]
#[repr(C,u16)]
pub enum Color {
    Default =  0x00,
    Black =    0x01,
    Red =      0x02,
    Green =    0x03,
    Yellow =   0x04,
    Blue =     0x05,
    Magenta =  0x06,
    Cyan =     0x07,
    White =    0x08,
}

mod style {
    bitflags! {
        #[repr(C)]
        flags Style: u16 {
            const TB_NORMAL_COLOR = 0x000F,
            const RB_BOLD = 0x0100,
            const RB_UNDERLINE = 0x0200,
            const RB_REVERSE = 0x0400,
            const RB_NORMAL = 0x0000,
            const TB_ATTRIB = RB_BOLD.bits | RB_UNDERLINE.bits | RB_REVERSE.bits,
        }
    }

    impl Style {
        pub fn from_color(color: super::Color) -> Style {
            Style { bits: color as u16 & TB_NORMAL_COLOR.bits }
        }
    }
}

const NIL_RAW_EVENT: RawEvent = RawEvent { etype: 0, emod: 0, key: 0, ch: 0, w: 0, h: 0, x: 0, y: 0 };

// FIXME: Rust doesn't support this enum representation.
// #[derive(Copy,FromPrimitive,Debug)]
// #[repr(C,int)]
// pub enum EventErrorKind {
//     Error = -1,
// }
// pub type EventError = Option<EventErrorKind>;
#[allow(non_snake_case)]
pub mod EventErrorKind {
    #[derive(Clone, Copy,Debug)]
    pub struct Error;
}

pub type EventError = Option<EventErrorKind::Error>;

pub type EventResult<T> = Result<T, EventError>;

/// Unpack a RawEvent to an Event
///
/// if the `raw` parameter is true, then the Event variant will be the raw
/// representation of the event.
///     for instance KeyEventRaw instead of KeyEvent
///
/// This is useful if you want to interpret the raw event data yourself, rather
/// than having rustbox translate it to its own representation.
fn unpack_event(ev_type: c_int, ev: &RawEvent, raw: bool) -> EventResult<Event> {
    match ev_type {
        0 => Ok(Event::NoEvent),
        1 => Ok(
            if raw {
                Event::KeyEventRaw(ev.emod, ev.key, ev.ch)
            } else {
                let k = match ev.key {
                    0 => char::from_u32(ev.ch).map(|c| Key::Char(c)),
                    a => Key::from_code(a),
                };
                Event::KeyEvent(k)
            }),
        2 => Ok(Event::ResizeEvent(ev.w, ev.h)),
        3 => {
            let mouse = Mouse::from_code(ev.key).unwrap_or(Mouse::Left);
            Ok(Event::MouseEvent(mouse, ev.x, ev.y))
        }
        // FIXME: Rust doesn't support this error representation
        // res => FromPrimitive::from_int(res as isize),
        -1 => Err(Some(EventErrorKind::Error)),
        _ => Err(None)
    }
}

enum_from_primitive! {
#[derive(Clone, Copy, Debug)]
#[repr(C,isize)]
pub enum InitErrorKind {
    UnsupportedTerminal = -1,
    FailedToOpenTty = -2,
    PipeTrapError = -3,
}
}

#[derive(Debug)]
pub enum InitError {
    BufferStderrFailed(io::Error),
    AlreadyOpen,
    TermBox(Option<InitErrorKind>),
}

impl fmt::Display for InitError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}", self.description())
    }
}

impl Error for InitError {
    fn description(&self) -> &str {
        match *self {
            InitError::BufferStderrFailed(_) => "Could not redirect stderr",
            InitError::AlreadyOpen => "RustBox is already open",
            InitError::TermBox(e) => e.map_or("Unexpected TermBox return code", |e| match e {
                InitErrorKind::UnsupportedTerminal => "Unsupported terminal",
                InitErrorKind::FailedToOpenTty => "Failed to open TTY",
                InitErrorKind::PipeTrapError => "Pipe trap error",
            }),
        }
    }

    fn cause(&self) -> Option<&Error> {
        match *self {
            InitError::BufferStderrFailed(ref e) => Some(e),
            _ => None
        }
    }
}

#[allow(missing_copy_implementations)]
pub struct RustBox {
   // We only bother to redirect stderr for the moment, since it's used for panic!
   _stderr: Option<Hold>,
}

// Termbox is not thread safe
impl !Send for RustBox {}

#[derive(Clone, Copy,Debug)]
pub struct InitOptions {
    /// Use this option to initialize with a specific input mode
    ///
    /// See InputMode enum for details on the variants.
    pub input_mode: InputMode,

    /// Use this option to automatically buffer stderr while RustBox is running.  It will be
    /// written when RustBox exits.
    ///
    /// This option uses a nonblocking OS pipe to buffer stderr output.  This means that if the
    /// pipe fills up, subsequent writes will fail until RustBox exits.  If this is a concern for
    /// your program, don't use RustBox's default pipe-based redirection; instead, redirect stderr
    /// to a log file or another process that is capable of handling it better.
    pub buffer_stderr: bool,
}

impl Default for InitOptions {
    fn default() -> Self {
        InitOptions {
            input_mode: InputMode::Current,
            buffer_stderr: false,
        }
    }
}

impl RustBox {
    /// Initialize rustbox.
    ///
    /// For the default options, you can use:
    ///
    /// ```
    /// use rustbox::RustBox;
    /// use std::default::Default;
    /// let rb = RustBox::init(Default::default());
    /// ```
    ///
    /// Otherwise, you can specify:
    ///
    /// ```
    /// use rustbox::{RustBox, InitOptions};
    /// use std::default::Default;
    /// let rb = RustBox::init(InitOptions { input_mode: rustbox::InputMode::Esc, ..Default::default() });
    /// ```
    pub fn init(opts: InitOptions) -> Result<RustBox, InitError> {
        let stderr = if opts.buffer_stderr {
            Some(try!(Hold::stderr().map_err(|e| InitError::BufferStderrFailed(e))))
        } else {
            None
        };

        // Create the RustBox.
        let rb = unsafe { match termbox::tb_init() {
            0 => RustBox {
                _stderr: stderr,
            },
            res => {
                return Err(InitError::TermBox(FromPrimitive::from_isize(res as isize)))
            }
        }};
        match opts.input_mode {
            InputMode::Current => (),
            _ => rb.set_input_mode(opts.input_mode),
        }
        Ok(rb)
    }

    pub fn width(&self) -> usize {
        unsafe { termbox::tb_width() as usize }
    }

    pub fn height(&self) -> usize {
        unsafe { termbox::tb_height() as usize }
    }

    pub fn clear(&self) {
        unsafe { termbox::tb_clear() }
    }

    pub fn present(&self) {
        unsafe { termbox::tb_present() }
    }

    pub fn set_cursor(&self, x: isize, y: isize) {
        unsafe { termbox::tb_set_cursor(x as c_int, y as c_int) }
    }

    pub unsafe fn change_cell(&self, x: usize, y: usize, ch: u32, fg: u16, bg: u16) {
        termbox::tb_change_cell(x as c_int, y as c_int, ch, fg, bg)
    }

    pub fn print(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, s: &str) {
        let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB);
        let bg = Style::from_color(bg);
        for (i, ch) in s.chars().enumerate() {
            unsafe {
                self.change_cell(x+i, y, ch as u32, fg.bits(), bg.bits());
            }
        }
    }

    pub fn print_char(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, ch: char) {
        let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB);
        let bg = Style::from_color(bg);
        unsafe {
            self.change_cell(x, y, ch as u32, fg.bits(), bg.bits());
        }
    }

    pub fn poll_event(&self, raw: bool) -> EventResult<Event> {
        let ev = NIL_RAW_EVENT;
        let rc = unsafe {
            termbox::tb_poll_event(&ev as *const RawEvent)
        };
        unpack_event(rc, &ev, raw)
    }

    pub fn peek_event(&self, timeout: Duration, raw: bool) -> EventResult<Event> {
        let ev = NIL_RAW_EVENT;
        let rc = unsafe {
            termbox::tb_peek_event(&ev as *const RawEvent, timeout.num_milliseconds() as c_int)
        };
        unpack_event(rc, &ev, raw)
    }

    pub fn set_input_mode(&self, mode: InputMode) {
        unsafe {
            termbox::tb_select_input_mode(mode as c_int);
        }
    }
}

impl Drop for RustBox {
    fn drop(&mut self) {
        // Since only one instance of the RustBox is ever accessible, we should not
        // need to do this atomically.
        // Note: we should definitely have RUSTBOX_RUNNING = true here.
        unsafe {
            termbox::tb_shutdown();
        }
    }
}
<commit_msg>Add mouse input modes<commit_after>#![feature(libc)]
#![feature(std_misc)]
#![feature(optin_builtin_traits)]

extern crate gag;
extern crate libc;
extern crate num;
#[macro_use] extern crate enum_primitive;
extern crate termbox_sys as termbox;
#[macro_use] extern crate bitflags;

pub use self::style::{Style, RB_BOLD, RB_UNDERLINE, RB_REVERSE, RB_NORMAL};

use std::error::Error;
use std::fmt;
use std::io;
use std::char;
use std::time::duration::Duration;
use std::default::Default;

use num::FromPrimitive;
use termbox::RawEvent;
use libc::c_int;
use gag::Hold;

pub mod keyboard;
pub mod mouse;

pub use keyboard::Key;
pub use mouse::Mouse;

#[derive(Clone, Copy)]
pub enum Event {
    KeyEventRaw(u8, u16, u32),
    KeyEvent(Option<Key>),
    ResizeEvent(i32, i32),
    MouseEvent(Mouse, i32, i32),
    NoEvent
}

#[derive(Clone, Copy, Debug)]
pub enum InputMode {
    Current = 0x00,

    /// When ESC sequence is in the buffer and it doesn't match any known
    /// ESC sequence => ESC means TB_KEY_ESC
    Esc     = 0x01,
    /// When ESC sequence is in the buffer and it doesn't match any known
    /// sequence => ESC enables TB_MOD_ALT modifier for the next keyboard event.
    Alt     = 0x02,
    /// Same as `Esc` but enables mouse events
    EscMouse = 0x05,
    /// Same as `Alt` but enables mouse events
    AltMouse = 0x06
}

#[derive(Clone, Copy, PartialEq)]
#[repr(C,u16)]
pub enum Color {
    Default =  0x00,
    Black =    0x01,
    Red =      0x02,
    Green =    0x03,
    Yellow =   0x04,
    Blue =     0x05,
    Magenta =  0x06,
    Cyan =     0x07,
    White =    0x08,
}

mod style {
    bitflags! {
        #[repr(C)]
        flags Style: u16 {
            const TB_NORMAL_COLOR = 0x000F,
            const RB_BOLD = 0x0100,
            const RB_UNDERLINE = 0x0200,
            const RB_REVERSE = 0x0400,
            const RB_NORMAL = 0x0000,
            const TB_ATTRIB = RB_BOLD.bits | RB_UNDERLINE.bits | RB_REVERSE.bits,
        }
    }

    impl Style {
        pub fn from_color(color: super::Color) -> Style {
            Style { bits: color as u16 & TB_NORMAL_COLOR.bits }
        }
    }
}

const NIL_RAW_EVENT: RawEvent = RawEvent { etype: 0, emod: 0, key: 0, ch: 0, w: 0, h: 0, x: 0, y: 0 };

// FIXME: Rust doesn't support this enum representation.
// #[derive(Copy,FromPrimitive,Debug)]
// #[repr(C,int)]
// pub enum EventErrorKind {
//     Error = -1,
// }
// pub type EventError = Option<EventErrorKind>;
#[allow(non_snake_case)]
pub mod EventErrorKind {
    #[derive(Clone, Copy,Debug)]
    pub struct Error;
}

pub type EventError = Option<EventErrorKind::Error>;

pub type EventResult<T> = Result<T, EventError>;

/// Unpack a RawEvent to an Event
///
/// if the `raw` parameter is true, then the Event variant will be the raw
/// representation of the event.
///     for instance KeyEventRaw instead of KeyEvent
///
/// This is useful if you want to interpret the raw event data yourself, rather
/// than having rustbox translate it to its own representation.
fn unpack_event(ev_type: c_int, ev: &RawEvent, raw: bool) -> EventResult<Event> {
    match ev_type {
        0 => Ok(Event::NoEvent),
        1 => Ok(
            if raw {
                Event::KeyEventRaw(ev.emod, ev.key, ev.ch)
            } else {
                let k = match ev.key {
                    0 => char::from_u32(ev.ch).map(|c| Key::Char(c)),
                    a => Key::from_code(a),
                };
                Event::KeyEvent(k)
            }),
        2 => Ok(Event::ResizeEvent(ev.w, ev.h)),
        3 => {
            let mouse = Mouse::from_code(ev.key).unwrap_or(Mouse::Left);
            Ok(Event::MouseEvent(mouse, ev.x, ev.y))
        }
        // FIXME: Rust doesn't support this error representation
        // res => FromPrimitive::from_int(res as isize),
        -1 => Err(Some(EventErrorKind::Error)),
        _ => Err(None)
    }
}

enum_from_primitive! {
#[derive(Clone, Copy, Debug)]
#[repr(C,isize)]
pub enum InitErrorKind {
    UnsupportedTerminal = -1,
    FailedToOpenTty = -2,
    PipeTrapError = -3,
}
}

#[derive(Debug)]
pub enum InitError {
    BufferStderrFailed(io::Error),
    AlreadyOpen,
    TermBox(Option<InitErrorKind>),
}

impl fmt::Display for InitError {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}", self.description())
    }
}

impl Error for InitError {
    fn description(&self) -> &str {
        match *self {
            InitError::BufferStderrFailed(_) => "Could not redirect stderr",
            InitError::AlreadyOpen => "RustBox is already open",
            InitError::TermBox(e) => e.map_or("Unexpected TermBox return code", |e| match e {
                InitErrorKind::UnsupportedTerminal => "Unsupported terminal",
                InitErrorKind::FailedToOpenTty => "Failed to open TTY",
                InitErrorKind::PipeTrapError => "Pipe trap error",
            }),
        }
    }

    fn cause(&self) -> Option<&Error> {
        match *self {
            InitError::BufferStderrFailed(ref e) => Some(e),
            _ => None
        }
    }
}

#[allow(missing_copy_implementations)]
pub struct RustBox {
   // We only bother to redirect stderr for the moment, since it's used for panic!
   _stderr: Option<Hold>,
}

// Termbox is not thread safe
impl !Send for RustBox {}

#[derive(Clone, Copy,Debug)]
pub struct InitOptions {
    /// Use this option to initialize with a specific input mode
    ///
    /// See InputMode enum for details on the variants.
    pub input_mode: InputMode,

    /// Use this option to automatically buffer stderr while RustBox is running.  It will be
    /// written when RustBox exits.
    ///
    /// This option uses a nonblocking OS pipe to buffer stderr output.  This means that if the
    /// pipe fills up, subsequent writes will fail until RustBox exits.  If this is a concern for
    /// your program, don't use RustBox's default pipe-based redirection; instead, redirect stderr
    /// to a log file or another process that is capable of handling it better.
    pub buffer_stderr: bool,
}

impl Default for InitOptions {
    fn default() -> Self {
        InitOptions {
            input_mode: InputMode::Current,
            buffer_stderr: false,
        }
    }
}

impl RustBox {
    /// Initialize rustbox.
    ///
    /// For the default options, you can use:
    ///
    /// ```
    /// use rustbox::RustBox;
    /// use std::default::Default;
    /// let rb = RustBox::init(Default::default());
    /// ```
    ///
    /// Otherwise, you can specify:
    ///
    /// ```
    /// use rustbox::{RustBox, InitOptions};
    /// use std::default::Default;
    /// let rb = RustBox::init(InitOptions { input_mode: rustbox::InputMode::Esc, ..Default::default() });
    /// ```
    pub fn init(opts: InitOptions) -> Result<RustBox, InitError> {
        let stderr = if opts.buffer_stderr {
            Some(try!(Hold::stderr().map_err(|e| InitError::BufferStderrFailed(e))))
        } else {
            None
        };

        // Create the RustBox.
        let rb = unsafe { match termbox::tb_init() {
            0 => RustBox {
                _stderr: stderr,
            },
            res => {
                return Err(InitError::TermBox(FromPrimitive::from_isize(res as isize)))
            }
        }};
        match opts.input_mode {
            InputMode::Current => (),
            _ => rb.set_input_mode(opts.input_mode),
        }
        Ok(rb)
    }

    pub fn width(&self) -> usize {
        unsafe { termbox::tb_width() as usize }
    }

    pub fn height(&self) -> usize {
        unsafe { termbox::tb_height() as usize }
    }

    pub fn clear(&self) {
        unsafe { termbox::tb_clear() }
    }

    pub fn present(&self) {
        unsafe { termbox::tb_present() }
    }

    pub fn set_cursor(&self, x: isize, y: isize) {
        unsafe { termbox::tb_set_cursor(x as c_int, y as c_int) }
    }

    pub unsafe fn change_cell(&self, x: usize, y: usize, ch: u32, fg: u16, bg: u16) {
        termbox::tb_change_cell(x as c_int, y as c_int, ch, fg, bg)
    }

    pub fn print(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, s: &str) {
        let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB);
        let bg = Style::from_color(bg);
        for (i, ch) in s.chars().enumerate() {
            unsafe {
                self.change_cell(x+i, y, ch as u32, fg.bits(), bg.bits());
            }
        }
    }

    pub fn print_char(&self, x: usize, y: usize, sty: Style, fg: Color, bg: Color, ch: char) {
        let fg = Style::from_color(fg) | (sty & style::TB_ATTRIB);
        let bg = Style::from_color(bg);
        unsafe {
            self.change_cell(x, y, ch as u32, fg.bits(), bg.bits());
        }
    }

    pub fn poll_event(&self, raw: bool) -> EventResult<Event> {
        let ev = NIL_RAW_EVENT;
        let rc = unsafe {
            termbox::tb_poll_event(&ev as *const RawEvent)
        };
        unpack_event(rc, &ev, raw)
    }

    pub fn peek_event(&self, timeout: Duration, raw: bool) -> EventResult<Event> {
        let ev = NIL_RAW_EVENT;
        let rc = unsafe {
            termbox::tb_peek_event(&ev as *const RawEvent, timeout.num_milliseconds() as c_int)
        };
        unpack_event(rc, &ev, raw)
    }

    pub fn set_input_mode(&self, mode: InputMode) {
        unsafe {
            termbox::tb_select_input_mode(mode as c_int);
        }
    }
}

impl Drop for RustBox {
    fn drop(&mut self) {
        // Since only one instance of the RustBox is ever accessible, we should not
        // need to do this atomically.
        // Note: we should definitely have RUSTBOX_RUNNING = true here.
        unsafe {
            termbox::tb_shutdown();
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Respect sigterm<commit_after><|endoftext|>


<commit_before><commit_msg>Add Day 17 solution<commit_after>// advent17.rs
// eggnog perfect bin packing

use std::io;

fn main() {
    let mut containers: Vec<u32> = Vec::new();
    loop {
        let mut input = String::new();
        let result = io::stdin().read_line(&mut input);
        match result {
            Ok(byte_count) => if byte_count == 0 { break; },
            Err(_) => {
                println!("error reading from stdin");
                break;
            }
        }

        // Parse container sizes from input
        if let Ok(x) = input.trim().parse::<u32>() {
            containers.push(x);
        }
    }

    println!("exact fits: {}", count_exact_fits(&containers, 150));
    println!("min exact fits: {}", count_min_exact_fits(&containers, 150));

}

// check if we can exactly get target size from combination of bins
fn is_exact_fit(bins: &[u32], bit_mask: u32, target: u32) -> bool {
    let total = bins.iter().enumerate()
        .fold(0, |sum, (i, bin)|
              if bit_mask & (1 << i) == 0 {
                  sum
              } else {
                  sum + bin
              });
    total == target
}

fn count_exact_fits(bins: &[u32], target: u32) -> usize {
    // because I'm storing a bit mask in a u32
    assert!(bins.len() <= 32);

    (1u32..(1 << bins.len())).filter(|x| is_exact_fit(bins, *x, target)).count()
}

#[test]
fn test_is_exact_fit() {
    let bins = [20, 15, 10, 5, 5];
    assert!(is_exact_fit(&bins, 0b0_0110, 25));
    assert!(!is_exact_fit(&bins, 0b1_0110, 25));
}

#[test]
fn test_count_exact_fits() {
    let bins = [20, 15, 10, 5, 5];

    assert_eq!(4, count_exact_fits(&bins, 25));
}

// part 2
fn find_exact_fits(bins: &[u32], target: u32) -> Vec<u32> {
    // because I'm storing a bit mask in a u32
    assert!(bins.len() <= 32);

    (1u32..(1 << bins.len())).filter(|x| is_exact_fit(bins, *x, target)).collect()
}

fn count_bits(x: u32) -> u32 {
    let mut total = 0;
    let mut val = x;

    while val > 0 {
        if (val & 1) != 0 {
            total += 1;
        }
        val >>= 1;
    }

    total
}

fn count_min_exact_fits(bins: &[u32], target: u32) -> usize {
    let fit_bits: Vec<u32> = find_exact_fits(bins, target).iter().map(|x| count_bits(*x)).collect();
    let min_bits = fit_bits.iter().min().unwrap();

    fit_bits.iter().filter(|x| *x == min_bits).count()
}

#[test]
fn test_find_exact_fits() {
    let bins = [20, 15, 10, 5, 5];
    let expected_result: Vec<u32> = vec![0b0_0110, 0b0_1001, 0b1_0001, 0b1_1010];

    assert_eq!(expected_result, find_exact_fits(&bins, 25));
}

#[test]
fn test_count_min_exact_fits() {
    let bins = [20, 15, 10, 5, 5];

    assert_eq!(3, count_min_exact_fits(&bins, 25));
}

<|endoftext|>


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

extern crate libstratis;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate devicemapper;
extern crate clap;
extern crate nix;
extern crate crc;
extern crate byteorder;
extern crate uuid;
extern crate time;
extern crate dbus;
extern crate term;
extern crate rand;
extern crate serde;
extern crate libc;

extern crate custom_derive;
extern crate enum_derive;

#[cfg(test)]
extern crate quickcheck;

use std::io::Write;
use std::env;
use std::error::Error;
use std::rc::Rc;
use std::cell::RefCell;
use std::process::exit;

use clap::{App, Arg};
use log::LogLevelFilter;
use env_logger::LogBuilder;
use dbus::WatchEvent;

use libstratis::engine::Engine;
use libstratis::engine::sim_engine::SimEngine;
use libstratis::engine::strat_engine::StratEngine;
use libstratis::stratis::VERSION;
use libstratis::types::{StratisResult, StratisError};

fn write_err(err: StratisError) -> StratisResult<()> {
    let mut out = term::stderr().expect("could not get stderr");

    try!(out.fg(term::color::RED));
    try!(writeln!(out, "{}", err.description()));
    try!(out.reset());
    Ok(())
}

/// If writing a program error to stderr fails, panic.
fn write_or_panic(err: StratisError) -> () {
    if let Err(e) = write_err(err) {
        panic!("Unable to write to stderr: {}", e)
    }
}

fn run() -> StratisResult<()> {

    let matches = App::new("stratis")
        .version(VERSION)
        .about("Stratis storage management")
        .arg(Arg::with_name("debug")
                 .long("debug")
                 .help("Print additional output for debugging"))
        .arg(Arg::with_name("sim")
                 .long("sim")
                 .help("Use simulator engine"))
        .get_matches();

    let mut builder = LogBuilder::new();
    if matches.is_present("debug") {
        builder.filter(Some("stratisd"), LogLevelFilter::Debug);
        builder.filter(Some("libstratis"), LogLevelFilter::Debug);
    } else {
        if let Ok(s) = env::var("RUST_LOG") {
            builder.parse(&s);
        }
    };

    builder
        .init()
        .expect("This is the first and only initialization of the logger; it must succeed.");

    let engine: Rc<RefCell<Engine>> = {
        if matches.is_present("sim") {
            info!("Using SimEngine");
            Rc::new(RefCell::new(SimEngine::new()))
        } else {
            info!("Using StratEngine");
            Rc::new(RefCell::new(StratEngine::new()))
        }
    };

    let (dbus_conn, mut tree, dbus_context) = libstratis::dbus_api::connect(engine.clone())
        .expect("Could not connect to D-Bus");

    // Get a list of fds to poll for
    let mut fds: Vec<_> = dbus_conn
        .watch_fds()
        .iter()
        .map(|w| w.to_pollfd())
        .collect();

    loop {
        // Poll them with a 10 s timeout
        let r = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::c_ulong, 10000) };
        assert!(r >= 0);

        // And handle incoming events
        for pfd in fds.iter().filter(|pfd| pfd.revents != 0) {
            for item in dbus_conn.watch_handle(pfd.fd, WatchEvent::from_revents(pfd.revents)) {
                if let Err(r) = libstratis::dbus_api::handle(&dbus_conn,
                                                             item,
                                                             &mut tree,
                                                             &dbus_context) {
                    write_or_panic(r);
                }
            }
        }

        // Ask the engine to check its pools
        engine.borrow_mut().check()
    }
}

fn main() {
    let error_code = match run() {
        Ok(_) => 0,
        Err(err) => {
            write_or_panic(err);
            1
        }
    };
    exit(error_code);
}
<commit_msg>Do not expect() the uncertain<commit_after>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

extern crate libstratis;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate devicemapper;
extern crate clap;
extern crate nix;
extern crate crc;
extern crate byteorder;
extern crate uuid;
extern crate time;
extern crate dbus;
extern crate term;
extern crate rand;
extern crate serde;
extern crate libc;

extern crate custom_derive;
extern crate enum_derive;

#[cfg(test)]
extern crate quickcheck;

use std::io::Write;
use std::env;
use std::error::Error;
use std::rc::Rc;
use std::cell::RefCell;
use std::process::exit;

use clap::{App, Arg};
use log::LogLevelFilter;
use env_logger::LogBuilder;
use dbus::WatchEvent;

use libstratis::engine::Engine;
use libstratis::engine::sim_engine::SimEngine;
use libstratis::engine::strat_engine::StratEngine;
use libstratis::stratis::VERSION;
use libstratis::types::{StratisResult, StratisError};

fn write_err(err: StratisError) -> StratisResult<()> {
    let mut out = term::stderr().expect("could not get stderr");

    try!(out.fg(term::color::RED));
    try!(writeln!(out, "{}", err.description()));
    try!(out.reset());
    Ok(())
}

/// If writing a program error to stderr fails, panic.
fn write_or_panic(err: StratisError) -> () {
    if let Err(e) = write_err(err) {
        panic!("Unable to write to stderr: {}", e)
    }
}

fn run() -> StratisResult<()> {

    let matches = App::new("stratis")
        .version(VERSION)
        .about("Stratis storage management")
        .arg(Arg::with_name("debug")
                 .long("debug")
                 .help("Print additional output for debugging"))
        .arg(Arg::with_name("sim")
                 .long("sim")
                 .help("Use simulator engine"))
        .get_matches();

    let mut builder = LogBuilder::new();
    if matches.is_present("debug") {
        builder.filter(Some("stratisd"), LogLevelFilter::Debug);
        builder.filter(Some("libstratis"), LogLevelFilter::Debug);
    } else {
        if let Ok(s) = env::var("RUST_LOG") {
            builder.parse(&s);
        }
    };

    builder
        .init()
        .expect("This is the first and only initialization of the logger; it must succeed.");

    let engine: Rc<RefCell<Engine>> = {
        if matches.is_present("sim") {
            info!("Using SimEngine");
            Rc::new(RefCell::new(SimEngine::new()))
        } else {
            info!("Using StratEngine");
            Rc::new(RefCell::new(StratEngine::new()))
        }
    };

    let (dbus_conn, mut tree, dbus_context) = try!(libstratis::dbus_api::connect(engine.clone()));

    // Get a list of fds to poll for
    let mut fds: Vec<_> = dbus_conn
        .watch_fds()
        .iter()
        .map(|w| w.to_pollfd())
        .collect();

    loop {
        // Poll them with a 10 s timeout
        let r = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::c_ulong, 10000) };
        assert!(r >= 0);

        // And handle incoming events
        for pfd in fds.iter().filter(|pfd| pfd.revents != 0) {
            for item in dbus_conn.watch_handle(pfd.fd, WatchEvent::from_revents(pfd.revents)) {
                if let Err(r) = libstratis::dbus_api::handle(&dbus_conn,
                                                             item,
                                                             &mut tree,
                                                             &dbus_context) {
                    write_or_panic(r);
                }
            }
        }

        // Ask the engine to check its pools
        engine.borrow_mut().check()
    }
}

fn main() {
    let error_code = match run() {
        Ok(_) => 0,
        Err(err) => {
            write_or_panic(err);
            1
        }
    };
    exit(error_code);
}
<|endoftext|>


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

extern crate libstratis;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate devicemapper;
extern crate clap;
extern crate nix;
extern crate crc;
extern crate byteorder;
extern crate uuid;
extern crate time;
extern crate dbus;
extern crate term;
extern crate rand;
extern crate serde;
extern crate libc;

extern crate custom_derive;
extern crate enum_derive;

#[cfg(test)]
extern crate quickcheck;

use std::io::Write;
use std::env;
use std::error::Error;
use std::rc::Rc;
use std::cell::RefCell;

use clap::{App, Arg};
use log::LogLevelFilter;
use env_logger::LogBuilder;
use dbus::WatchEvent;

use libstratis::engine::Engine;
use libstratis::engine::sim_engine::SimEngine;
use libstratis::engine::strat_engine::StratEngine;
use libstratis::stratis::VERSION;
use libstratis::types::{StratisResult, StratisError};

fn write_err(err: StratisError) -> StratisResult<()> {
    let mut out = term::stderr().expect("could not get stderr");

    try!(out.fg(term::color::RED));
    try!(writeln!(out, "{}", err.description()));
    try!(out.reset());
    Ok(())
}

fn main() {

    let matches = App::new("stratis")
        .version(VERSION)
        .about("Stratis storage management")
        .arg(Arg::with_name("debug")
                 .long("debug")
                 .help("Print additional output for debugging"))
        .arg(Arg::with_name("sim")
                 .long("sim")
                 .help("Use simulator engine"))
        .get_matches();

    let mut builder = LogBuilder::new();
    if matches.is_present("debug") {
        builder.filter(Some("stratisd"), LogLevelFilter::Debug);
        builder.filter(Some("libstratis"), LogLevelFilter::Debug);
    } else {
        if let Ok(s) = env::var("RUST_LOG") {
            builder.parse(&s);
        }
    };

    builder
        .init()
        .expect("This is the first and only initialization of the logger; it must succeed.");

    let engine: Rc<RefCell<Engine>> = {
        if matches.is_present("sim") {
            info!("Using SimEngine");
            Rc::new(RefCell::new(SimEngine::new()))
        } else {
            info!("Using StratEngine");
            Rc::new(RefCell::new(StratEngine::new()))
        }
    };

    let (dbus_conn, mut tree, dbus_context) = libstratis::dbus_api::connect(engine.clone())
        .expect("Could not connect to D-Bus");

    // Get a list of fds to poll for
    let mut fds: Vec<_> = dbus_conn
        .watch_fds()
        .iter()
        .map(|w| w.to_pollfd())
        .collect();

    loop {
        // Poll them with a 10 s timeout
        let r = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::c_ulong, 10000) };
        assert!(r >= 0);

        // And handle incoming events
        for pfd in fds.iter().filter(|pfd| pfd.revents != 0) {
            for item in dbus_conn.watch_handle(pfd.fd, WatchEvent::from_revents(pfd.revents)) {
                if let Err(r) = libstratis::dbus_api::handle(&dbus_conn,
                                                             item,
                                                             &mut tree,
                                                             &dbus_context) {
                    if let Err(e) = write_err(r) {
                        panic!("Unable to write to stderr: {}", e)
                    }
                }
            }
        }

        // Ask the engine to check its pools
        engine.borrow_mut().check()
    }
}
<commit_msg>Add a write_or_panic() method<commit_after>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

extern crate libstratis;
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate devicemapper;
extern crate clap;
extern crate nix;
extern crate crc;
extern crate byteorder;
extern crate uuid;
extern crate time;
extern crate dbus;
extern crate term;
extern crate rand;
extern crate serde;
extern crate libc;

extern crate custom_derive;
extern crate enum_derive;

#[cfg(test)]
extern crate quickcheck;

use std::io::Write;
use std::env;
use std::error::Error;
use std::rc::Rc;
use std::cell::RefCell;

use clap::{App, Arg};
use log::LogLevelFilter;
use env_logger::LogBuilder;
use dbus::WatchEvent;

use libstratis::engine::Engine;
use libstratis::engine::sim_engine::SimEngine;
use libstratis::engine::strat_engine::StratEngine;
use libstratis::stratis::VERSION;
use libstratis::types::{StratisResult, StratisError};

fn write_err(err: StratisError) -> StratisResult<()> {
    let mut out = term::stderr().expect("could not get stderr");

    try!(out.fg(term::color::RED));
    try!(writeln!(out, "{}", err.description()));
    try!(out.reset());
    Ok(())
}

/// If writing a program error to stderr fails, panic.
fn write_or_panic(err: StratisError) -> () {
    if let Err(e) = write_err(err) {
        panic!("Unable to write to stderr: {}", e)
    }
}

fn main() {

    let matches = App::new("stratis")
        .version(VERSION)
        .about("Stratis storage management")
        .arg(Arg::with_name("debug")
                 .long("debug")
                 .help("Print additional output for debugging"))
        .arg(Arg::with_name("sim")
                 .long("sim")
                 .help("Use simulator engine"))
        .get_matches();

    let mut builder = LogBuilder::new();
    if matches.is_present("debug") {
        builder.filter(Some("stratisd"), LogLevelFilter::Debug);
        builder.filter(Some("libstratis"), LogLevelFilter::Debug);
    } else {
        if let Ok(s) = env::var("RUST_LOG") {
            builder.parse(&s);
        }
    };

    builder
        .init()
        .expect("This is the first and only initialization of the logger; it must succeed.");

    let engine: Rc<RefCell<Engine>> = {
        if matches.is_present("sim") {
            info!("Using SimEngine");
            Rc::new(RefCell::new(SimEngine::new()))
        } else {
            info!("Using StratEngine");
            Rc::new(RefCell::new(StratEngine::new()))
        }
    };

    let (dbus_conn, mut tree, dbus_context) = libstratis::dbus_api::connect(engine.clone())
        .expect("Could not connect to D-Bus");

    // Get a list of fds to poll for
    let mut fds: Vec<_> = dbus_conn
        .watch_fds()
        .iter()
        .map(|w| w.to_pollfd())
        .collect();

    loop {
        // Poll them with a 10 s timeout
        let r = unsafe { libc::poll(fds.as_mut_ptr(), fds.len() as libc::c_ulong, 10000) };
        assert!(r >= 0);

        // And handle incoming events
        for pfd in fds.iter().filter(|pfd| pfd.revents != 0) {
            for item in dbus_conn.watch_handle(pfd.fd, WatchEvent::from_revents(pfd.revents)) {
                if let Err(r) = libstratis::dbus_api::handle(&dbus_conn,
                                                             item,
                                                             &mut tree,
                                                             &dbus_context) {
                    write_or_panic(r);
                }
            }
        }

        // Ask the engine to check its pools
        engine.borrow_mut().check()
    }
}
<|endoftext|>


<commit_before><commit_msg>taskbar<commit_after>extern crate x11;

use x11::xlib;
use std::mem;
use std::slice::Iter;
use super::super::libx;
pub struct TaskBar {
    context: libx::Context,
    id: xlib::Window,
    height: u32,
    workspaces: Vec<char>,
}

impl TaskBar {
    pub fn new(context: libx::Context, height: u32, position: i32) -> TaskBar {
        let pid = context.root;
        let attrs = libx::get_window_attributes(context, pid);
        let y: i32 = if position > 0 {
            attrs.y
        }else{
            attrs.y + attrs.height - height as i32
        };
        let id = libx::create_window(context, pid, attrs.x, y,
                                     attrs.width as u32,
                                     height);

        // attributes
        let mut attrs: xlib::XSetWindowAttributes = unsafe { mem::zeroed() };
        attrs.override_redirect = 1;
        libx::set_window_attributes(context, id, xlib::CWOverrideRedirect, attrs);

        // inputs
        let mask = xlib::ButtonPressMask | xlib::ExposureMask;
        libx::select_input(context, id, mask);
        libx::map_window(context, id);
        TaskBar {
            context: context,
            id: id,
            height: height,
            workspaces: Vec::new()
        }
    }

    pub fn load(&mut self, keys: Vec<char>) {
        self.workspaces = keys;
    }

    pub fn draw_workspaces(&mut self) {
        let context = self.context;
        let gc = context.gc;
        let display = context.display;
        unsafe{
            xlib::XSetBackground(display, gc,
                                 context.focus_bg);
            xlib::XSetForeground(display, gc,
                                 context.focus_fg);

        }
        for (i, v) in self.workspaces.iter().enumerate() {
            let x = (i as u32 * (self.height + 1)) as i32 + 1;
            let y = 0;
            let width = self.height - 2;
            let height = self.height - 2;
            unsafe{
                xlib::XFillRectangle(display, self.id, gc,
                                     x, y,
                                     width, height);
            }
        }
    }

    pub fn handle(&mut self, e: &xlib::XEvent) {
        let t = e.get_type();
        match t {
            xlib::Expose => {
                let event: xlib::XExposeEvent = From::from(*e);
                if event.window == self.id {
                    self.draw_workspaces();
                }
            }
            _ => {}
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add Exercise 7.5<commit_after>/// Exercise 7.5: Use the typedef facility of C to define a new data type Exitfunc for an exit
/// handler. Redo the prototype for atexit using this data type.

extern crate libc;
#[macro_use(cstr)]
extern crate apue;
extern crate errno;

use apue::LibcResult;
use libc::{atexit, printf};

type Exitfunc = extern fn();

fn my_atexit(f:Exitfunc) -> Option<i32> {
    unsafe {
        atexit(f).to_option()
    }
}

extern "C" fn my_exit1() {
    unsafe { printf(cstr!("first exit handler\n")) };
}

extern "C" fn my_exit2() {
    unsafe { printf(cstr!("second exit handler\n")) };
}

fn main() {
    my_atexit(my_exit2).expect(&format!("can't register my_exit2: {}", errno::errno()));
    my_atexit(my_exit1).expect(&format!("can't register my_exit1: {}", errno::errno()));
    my_atexit(my_exit1).expect(&format!("can't register my_exit1: {}", errno::errno()));
    println!("main is done");
}<|endoftext|>


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

use dom::document::{AbstractDocument, Document, WrappableDocument, HTML};
use dom::bindings::codegen::HTMLDocumentBinding;
use dom::bindings::utils::{DOMString, ErrorResult, null_string};
use dom::bindings::utils::{CacheableWrapper, BindingObject, WrapperCache};
use dom::htmlcollection::HTMLCollection;
use dom::node::{AbstractNode, ScriptView};
use dom::window::Window;

use js::jsapi::{JSObject, JSContext};

use servo_util::tree::TreeUtils;

use std::libc;
use std::ptr;

pub struct HTMLDocument {
    parent: Document
}

impl HTMLDocument {
    pub fn new(root: AbstractNode<ScriptView>, window: Option<@mut Window>) -> AbstractDocument {
        let doc = @mut HTMLDocument {
            parent: Document::new(root, window, HTML)
        };

        let compartment = unsafe { (*window.get_ref().page).js_info.get_ref().js_compartment };
        AbstractDocument::as_abstract(compartment.cx.ptr, doc)
    }

    fn get_scope_and_cx(&self) -> (*JSObject, *JSContext) {
        let win = self.parent.window.get_ref();
        let cx = unsafe {(*win.page).js_info.get_ref().js_compartment.cx.ptr};
        let cache = win.get_wrappercache();
        let scope = cache.get_wrapper();
        (scope, cx)
    }
}

impl WrappableDocument for HTMLDocument {
    pub fn init_wrapper(@mut self, cx: *JSContext) {
        self.wrap_object_shared(cx, ptr::null()); //XXXjdm a proper scope would be nice
    }
}

impl HTMLDocument {
    pub fn GetDomain(&self, _rv: &mut ErrorResult) -> DOMString {
        null_string
    }

    pub fn SetDomain(&self, _domain: &DOMString, _rv: &mut ErrorResult) {
    }

    pub fn GetCookie(&self, _rv: &mut ErrorResult) -> DOMString {
        null_string
    }

    pub fn SetCookie(&self, _cookie: &DOMString, _rv: &mut ErrorResult) {
    }

    pub fn GetHead(&self) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn Images(&self) -> @mut HTMLCollection {
        self.createHTMLCollection(~"img")
    }

    pub fn Embeds(&self) -> @mut HTMLCollection {
        self.createHTMLCollection(~"embed")
    }

    pub fn Plugins(&self) -> @mut HTMLCollection {
        self.Embeds()
    }

    pub fn Links(&self) -> @mut HTMLCollection {
        self.createHTMLCollection(~"link")
    }

    pub fn Forms(&self) -> @mut HTMLCollection {
        self.createHTMLCollection(~"form")
    }

    pub fn Scripts(&self) -> @mut HTMLCollection {
        self.createHTMLCollection(~"script")
    }

    pub fn Close(&self, _rv: &mut ErrorResult) {
    }

    pub fn DesignMode(&self) -> DOMString {
        null_string
    }

    pub fn SetDesignMode(&self, _mode: &DOMString, _rv: &mut ErrorResult) {
    }

    pub fn ExecCommand(&self, _command_id: &DOMString, _show_ui: bool, _value: &DOMString, _rv: &mut ErrorResult) -> bool {
        false
    }

    pub fn QueryCommandEnabled(&self, _command_id: &DOMString, _rv: &mut ErrorResult) -> bool {
        false
    }

    pub fn QueryCommandIndeterm(&self, _command_id: &DOMString, _rv: &mut ErrorResult) -> bool {
        false
    }

    pub fn QueryCommandState(&self, _command_id: &DOMString, _rv: &mut ErrorResult) -> bool {
        false
    }

    pub fn QueryCommandSupported(&self, _command_id: &DOMString) -> bool {
        false
    }

    pub fn QueryCommandValue(&self, _command_id: &DOMString, _rv: &mut ErrorResult) -> DOMString {
        null_string
    }

    pub fn FgColor(&self) -> DOMString {
        null_string
    }

    pub fn SetFgColor(&self, _color: &DOMString) {
    }

    pub fn LinkColor(&self) -> DOMString {
        null_string
    }

    pub fn SetLinkColor(&self, _color: &DOMString) {
    }

    pub fn VlinkColor(&self) -> DOMString {
        null_string
    }

    pub fn SetVlinkColor(&self, _color: &DOMString) {
    }

    pub fn AlinkColor(&self) -> DOMString {
        null_string
    }

    pub fn SetAlinkColor(&self, _color: &DOMString) {
    }

    pub fn BgColor(&self) -> DOMString {
        null_string
    }

    pub fn SetBgColor(&self, _color: &DOMString) {
    }

    pub fn Anchors(&self) -> @mut HTMLCollection {
        self.createHTMLCollection(~"a")
    }

    pub fn Applets(&self) -> @mut HTMLCollection {
        self.createHTMLCollection(~"applet")
    }

    pub fn Clear(&self) {
    }

    pub fn GetAll(&self, _cx: *JSContext, _rv: &mut ErrorResult) -> *libc::c_void {
        ptr::null()
    }

    fn createHTMLCollection(&self, elem_name: ~str) -> @mut HTMLCollection {
        let (scope, cx) = self.get_scope_and_cx();
        let mut elements = ~[];
        let _ = for self.parent.root.traverse_preorder |child| {
            if child.is_element() {
                do child.with_imm_element |elem| {
                    match elem_name {
                        ~"link" => {
                            if elem.tag_name == ~"a" || elem.tag_name == ~"area" {
                                match elem.get_attr("href") {
                                    Some(_val) => elements.push(child),
                                    None() => ()
                                }
                            }
                        }
                        _ => {
                            if elem.tag_name == elem_name {
                                elements.push(child);
                            }
                        }
                    }
                }
            }
        };
        HTMLCollection::new(elements, cx, scope)
    }
}

impl CacheableWrapper for HTMLDocument {
    fn get_wrappercache(&mut self) -> &mut WrapperCache {
        self.parent.get_wrappercache()
    }

    fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
        let mut unused = false;
        HTMLDocumentBinding::Wrap(cx, scope, self, &mut unused)
    }
}

impl BindingObject for HTMLDocument {
    fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
        self.parent.GetParentObject(cx)
    }
}

<commit_msg>Fix some implementations for DOM tree accessors<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use dom::bindings::codegen::HTMLDocumentBinding;
use dom::bindings::utils::{DOMString, ErrorResult, null_string};
use dom::bindings::utils::{CacheableWrapper, BindingObject, WrapperCache};
use dom::document::{AbstractDocument, Document, WrappableDocument, HTML};
use dom::element::Element;
use dom::htmlcollection::HTMLCollection;
use dom::node::{AbstractNode, ScriptView};
use dom::window::Window;

use js::jsapi::{JSObject, JSContext};

use servo_util::tree::TreeUtils;

use std::libc;
use std::ptr;
use std::str::eq_slice;

pub struct HTMLDocument {
    parent: Document
}

impl HTMLDocument {
    pub fn new(root: AbstractNode<ScriptView>, window: Option<@mut Window>) -> AbstractDocument {
        let doc = @mut HTMLDocument {
            parent: Document::new(root, window, HTML)
        };

        let compartment = unsafe { (*window.get_ref().page).js_info.get_ref().js_compartment };
        AbstractDocument::as_abstract(compartment.cx.ptr, doc)
    }

    fn get_scope_and_cx(&self) -> (*JSObject, *JSContext) {
        let win = self.parent.window.get_ref();
        let cx = unsafe {(*win.page).js_info.get_ref().js_compartment.cx.ptr};
        let cache = win.get_wrappercache();
        let scope = cache.get_wrapper();
        (scope, cx)
    }
}

impl WrappableDocument for HTMLDocument {
    pub fn init_wrapper(@mut self, cx: *JSContext) {
        self.wrap_object_shared(cx, ptr::null()); //XXXjdm a proper scope would be nice
    }
}

impl HTMLDocument {
    pub fn GetDomain(&self, _rv: &mut ErrorResult) -> DOMString {
        null_string
    }

    pub fn SetDomain(&self, _domain: &DOMString, _rv: &mut ErrorResult) {
    }

    pub fn GetCookie(&self, _rv: &mut ErrorResult) -> DOMString {
        null_string
    }

    pub fn SetCookie(&self, _cookie: &DOMString, _rv: &mut ErrorResult) {
    }

    pub fn GetHead(&self) -> Option<AbstractNode<ScriptView>> {
        None
    }

    pub fn Images(&self) -> @mut HTMLCollection {
        self.createHTMLCollection(|elem| eq_slice(elem.tag_name, "img"))
    }

    pub fn Embeds(&self) -> @mut HTMLCollection {
        self.createHTMLCollection(|elem| eq_slice(elem.tag_name, "embed"))
    }

    pub fn Plugins(&self) -> @mut HTMLCollection {
        self.Embeds()
    }

    pub fn Links(&self) -> @mut HTMLCollection {
        self.createHTMLCollection(|elem| {
            if eq_slice(elem.tag_name, "a") || eq_slice(elem.tag_name, "area") {
                match elem.get_attr("href") {
                    Some(_val) => true,
                    None() => false
                }
            }
            else { false }
        })
    }

    pub fn Forms(&self) -> @mut HTMLCollection {
        self.createHTMLCollection(|elem| eq_slice(elem.tag_name, "form"))
    }

    pub fn Scripts(&self) -> @mut HTMLCollection {
        self.createHTMLCollection(|elem| eq_slice(elem.tag_name, "script"))
    }

    pub fn Close(&self, _rv: &mut ErrorResult) {
    }

    pub fn DesignMode(&self) -> DOMString {
        null_string
    }

    pub fn SetDesignMode(&self, _mode: &DOMString, _rv: &mut ErrorResult) {
    }

    pub fn ExecCommand(&self, _command_id: &DOMString, _show_ui: bool, _value: &DOMString, _rv: &mut ErrorResult) -> bool {
        false
    }

    pub fn QueryCommandEnabled(&self, _command_id: &DOMString, _rv: &mut ErrorResult) -> bool {
        false
    }

    pub fn QueryCommandIndeterm(&self, _command_id: &DOMString, _rv: &mut ErrorResult) -> bool {
        false
    }

    pub fn QueryCommandState(&self, _command_id: &DOMString, _rv: &mut ErrorResult) -> bool {
        false
    }

    pub fn QueryCommandSupported(&self, _command_id: &DOMString) -> bool {
        false
    }

    pub fn QueryCommandValue(&self, _command_id: &DOMString, _rv: &mut ErrorResult) -> DOMString {
        null_string
    }

    pub fn FgColor(&self) -> DOMString {
        null_string
    }

    pub fn SetFgColor(&self, _color: &DOMString) {
    }

    pub fn LinkColor(&self) -> DOMString {
        null_string
    }

    pub fn SetLinkColor(&self, _color: &DOMString) {
    }

    pub fn VlinkColor(&self) -> DOMString {
        null_string
    }

    pub fn SetVlinkColor(&self, _color: &DOMString) {
    }

    pub fn AlinkColor(&self) -> DOMString {
        null_string
    }

    pub fn SetAlinkColor(&self, _color: &DOMString) {
    }

    pub fn BgColor(&self) -> DOMString {
        null_string
    }

    pub fn SetBgColor(&self, _color: &DOMString) {
    }

    pub fn Anchors(&self) -> @mut HTMLCollection {
        self.createHTMLCollection(|elem| {
            if eq_slice(elem.tag_name, "a") {
                match elem.get_attr("name") {
                    Some(_val) => true,
                    None() => false
                }
            }
            else { false }
        })
    }

    pub fn Applets(&self) -> @mut HTMLCollection {
        // FIXME: This should be return OBJECT elements containing applets.
        self.createHTMLCollection(|elem| eq_slice(elem.tag_name, "applet"))
    }

    pub fn Clear(&self) {
    }

    pub fn GetAll(&self, _cx: *JSContext, _rv: &mut ErrorResult) -> *libc::c_void {
        ptr::null()
    }

    fn createHTMLCollection(&self, callback: &fn(elem: &Element) -> bool) -> @mut HTMLCollection {
        let (scope, cx) = self.get_scope_and_cx();
        let mut elements = ~[];
        let _ = for self.parent.root.traverse_preorder |child| {
            if child.is_element() {
                do child.with_imm_element |elem| {
                    if callback(elem) {
                        elements.push(child);
                    }
                }
            }
        };
        HTMLCollection::new(elements, cx, scope)
    }
}

impl CacheableWrapper for HTMLDocument {
    fn get_wrappercache(&mut self) -> &mut WrapperCache {
        self.parent.get_wrappercache()
    }

    fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
        let mut unused = false;
        HTMLDocumentBinding::Wrap(cx, scope, self, &mut unused)
    }
}

impl BindingObject for HTMLDocument {
    fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
        self.parent.GetParentObject(cx)
    }
}

<|endoftext|>


<commit_before><commit_msg>Add a test for thread locals.<commit_after>#![feature(thread_local)]

use std::thread;

#[thread_local]
static mut A: u8 = 0;
#[thread_local]
static mut B: u8 = 0;
static mut C: u8 = 0;

unsafe fn get_a_ref() -> *mut u8 {
    &mut A
}

fn main() {

    unsafe {
        let x = get_a_ref();
        *x = 5;
        assert_eq!(A, 5);
        B = 15;
        C = 25;
    }

    thread::spawn(|| {
        unsafe {
            assert_eq!(A, 0);
            assert_eq!(B, 0);
            assert_eq!(C, 25);
            B = 14;
            C = 24;
            let y = get_a_ref();
            assert_eq!(*y, 0);
            *y = 4;
            assert_eq!(A, 4);
            assert_eq!(*get_a_ref(), 4);

        }
    }).join().unwrap();

    unsafe {
        assert_eq!(*get_a_ref(), 5);
        assert_eq!(A, 5);
        assert_eq!(B, 15);
        assert_eq!(C, 24);
    }

}<|endoftext|>


<commit_before><commit_msg>Implement insert operation.<commit_after>use super::Operation;
use buffer::gap_buffer::GapBuffer;
use buffer::{Position, Range};

pub struct Insert {
    content: String,
    position: Position,
}

impl Operation for Insert {
    fn run(&mut self, buffer: &mut GapBuffer) {
        buffer.insert(&self.content, &self.position);
    }

    // We need to calculate the range of the inserted content.
    // The start of the range corresponds to the cursor position at the time of the insert,
    // which we've stored. Finding the end of the range requires that we dig into the content.
    fn reverse(&mut self, buffer: &mut GapBuffer) {
        // The line count of the content tells us the line number for the end of the
        // range (just add the number of new lines to the starting line).
        let line_count = self.content.lines().count();
        let end_line = self.position.line + line_count - 1;

        let end_offset = if line_count == 1 {
            // If there's only one line, the range starts and ends on the same line, and so its
            // offset needs to take the original insertion location into consideration.
            self.position.offset + self.content.len()
        } else {
            // If there are multiple lines, the end of the range doesn't
            // need to consider the original insertion location.
            match self.content.lines().last() {
                Some(line) => line.len(),
                None => return,
            }
        };

        // Now that we have the required info,
        // build the end position and total range.
        let end_position = Position{
            line: end_line,
            offset: end_offset,
        };
        let range = Range{
            start: self.position.clone(),
            end: end_position,
        };

        // Remove the content we'd previously inserted.
        buffer.delete(&range);
    }
}

pub fn new(content: String, position: Position) -> Insert {
    Insert{ content: content, position: position }
}

#[cfg(test)]
mod tests {
    use super::new;
    use buffer::position::Position;
    use buffer::operations::Operation;

    #[test]
    fn run_and_reverse_add_and_remove_content_without_newlines_at_cursor_position() {
        // Set up a buffer with some data.
        let mut buffer = ::buffer::gap_buffer::new(String::new());
        let start_position = Position{ line: 0, offset: 0 };
        buffer.insert(&"something", &start_position);

        // Set up a position pointing to the end of the buffer's contents.
        let insert_position = Position{ line: 0, offset: 9 };

        // Create the insert operation and run it.
        let mut insert_operation = super::new(" else".to_string(), insert_position);
        insert_operation.run(&mut buffer);

        assert_eq!(buffer.to_string(), "something else");

        insert_operation.reverse(&mut buffer);

        assert_eq!(buffer.to_string(), "something");
    }

    #[test]
    fn run_and_reverse_add_and_remove_content_with_newlines_at_cursor_position() {
        // Set up a buffer with some data.
        let mut buffer = ::buffer::gap_buffer::new(String::new());
        let start_position = Position{ line: 0, offset: 0 };
        buffer.insert(&"\n something", &start_position);

        // Set up a position pointing to the end of the buffer's contents.
        let insert_position = Position{ line: 1, offset: 10 };

        // Create the insert operation and run it.
        //
        // NOTE: The newline character ensures that the operation doesn't use a naive
        //       algorithm based purely on the content length.
        let mut insert_operation = super::new("\n else\n entirely".to_string(), insert_position);
        insert_operation.run(&mut buffer);

        assert_eq!(buffer.to_string(), "\n something\n else\n entirely");

        insert_operation.reverse(&mut buffer);

        assert_eq!(buffer.to_string(), "\n something");
    }
}
<|endoftext|>


<commit_before><commit_msg>Change in phone_metadata<commit_after><|endoftext|>


<commit_before><commit_msg>update<commit_after>fn main(){
    let day = 5;
    match day {
        6 | 7 | 8 => println!("weekend"),
        1...5 => println!("weekday"),
        _ => println!("FK"),
    }
    //使用','分开每句
    // "|"用于匹配多个值,如： 5|4 匹配5和4.
    // "..."用于匹配一个范围,如：1...5 匹配1,2,3,4,5.
    // "_"用于匹配其他值，因为match必须覆盖所有可能值.

    let x = 1;
    match x {
        e @ 1...5 => println!("x = {}", e),
        f @ 7 |f @ 8 | f @ 9 => println!("x = {}", f),
        _ => println!("Balabala"),
    }
    //使用@获得|或者...匹配到的值.

    let y = 5;
    let mut z = 5;
    match y {
        ref r => println!("r = {}", r),
    }
    match z {
        ref mut mutr => {
            *mutr = 10;
            println!("z = {}", mutr);
        },
    }
    //用ref获得一个引用，可以是mut可以是immut

    let a = (0, 2);
    match a {
        //(0, y) => println!("x = 0, y = {}", y),
        (x, 0) => println!("x = {}, y = 0", x),
        (0, 2) => println!("x = 0, y = 2"),
        _ => println!("Balabala"),
    }
    //可以用match匹配元组

    //wait more...
}
<|endoftext|>


<commit_before><commit_msg>Test case for previous commit<commit_after>fn main() {
 let x = 10, y = 20;
 let z = x + y;
 assert (z == 30);
}
<|endoftext|>


<commit_before><commit_msg>Add manual page to env, -h and --help options.<commit_after><|endoftext|>


<commit_before><commit_msg>add problem 3 in rust<commit_after>use std::time::SystemTime;

fn is_prime(number: i64) -> bool {
    let limit = (number as f64).sqrt() as i64 + 1;
    let mut factor_exists = false;

    for i in 2..limit {
        if number % i == 0 {
            factor_exists = true;
            break;
        }
    }

    !factor_exists
}

fn main() {
    let large_number = 600851475143;
    let limit = (large_number as f64).sqrt() as i64 + 1;

    let mut result = 0;

    let time_start = SystemTime::now();

    for i in (3..limit).rev() {
        if large_number % i == 0 && is_prime(i){
            result = i;
            break;
        }
    }

    match time_start.elapsed() {
        Ok(elapsed) => {
            println!("Calc duration: {}", elapsed.as_secs());
            println!("Subsec nanos: {}", elapsed.subsec_nanos());
        }
        Err(e) => {
            println!("Error: {:?}", e);
        }
    }

    println!("Result: {}", result);
}
<|endoftext|>


<commit_before><commit_msg>feat(environ): Using nix's pread to read header<commit_after><|endoftext|>


<commit_before>use clap::{Arg, ArgGroup, App, SubCommand};

use libimagentrytag::ui::tag_argument;
use libimagentrytag::ui::tag_argument_name;

pub fn build_ui<'a>(app: App<'a, 'a>) -> App<'a, 'a> {
    app
        .subcommand(SubCommand::with_name("create")
                   .about("Create a note")
                   .version("0.1")
                   .arg(Arg::with_name("name")
                        .long("name")
                        .short("n")
                        .takes_value(true)
                        .required(true)
                        .help("Create Note with this name")
                        .value_name("NAME"))
                   .arg(Arg::with_name("edit")
                        .long("edit")
                        .short("e")
                        .takes_value(false)
                        .required(false)
                        .help("Edit after creating"))
                   )

        .subcommand(SubCommand::with_name("delete")
                   .about("Delete a Note")
                   .version("0.1")
                   .arg(Arg::with_name("name")
                        .long("name")
                        .short("n")
                        .takes_value(true)
                        .required(true)
                        .help("Delete Note with this name")
                        .value_name("NAME")))

        .subcommand(SubCommand::with_name("edit")
                   .about("Edit a Note")
                   .version("0.1")
                   .arg(Arg::with_name("name")
                        .long("name")
                        .short("n")
                        .takes_value(true)
                        .required(true)
                        .help("Edit Note with this name")
                        .value_name("NAME"))

                   .arg(tag_argument())
                   )

        .subcommand(SubCommand::with_name("list")
                   .about("List Notes")
                   .version("0.1"))

}
<commit_msg>removed warnings<commit_after>use clap::{Arg, App, SubCommand};

use libimagentrytag::ui::tag_argument;

pub fn build_ui<'a>(app: App<'a, 'a>) -> App<'a, 'a> {
    app
        .subcommand(SubCommand::with_name("create")
                   .about("Create a note")
                   .version("0.1")
                   .arg(Arg::with_name("name")
                        .long("name")
                        .short("n")
                        .takes_value(true)
                        .required(true)
                        .help("Create Note with this name")
                        .value_name("NAME"))
                   .arg(Arg::with_name("edit")
                        .long("edit")
                        .short("e")
                        .takes_value(false)
                        .required(false)
                        .help("Edit after creating"))
                   )

        .subcommand(SubCommand::with_name("delete")
                   .about("Delete a Note")
                   .version("0.1")
                   .arg(Arg::with_name("name")
                        .long("name")
                        .short("n")
                        .takes_value(true)
                        .required(true)
                        .help("Delete Note with this name")
                        .value_name("NAME")))

        .subcommand(SubCommand::with_name("edit")
                   .about("Edit a Note")
                   .version("0.1")
                   .arg(Arg::with_name("name")
                        .long("name")
                        .short("n")
                        .takes_value(true)
                        .required(true)
                        .help("Edit Note with this name")
                        .value_name("NAME"))

                   .arg(tag_argument())
                   )

        .subcommand(SubCommand::with_name("list")
                   .about("List Notes")
                   .version("0.1"))

}
<|endoftext|>


<commit_before>extern crate clap;
#[macro_use] extern crate log;
extern crate semver;
extern crate toml;
#[macro_use] extern crate version;

extern crate libimagstore;
extern crate libimagrt;
extern crate libimagentrytag;
extern crate libimagerror;

use std::process::exit;

use libimagrt::runtime::Runtime;
use libimagentrytag::tagable::Tagable;
use libimagstore::storeid::build_entry_path;
use libimagerror::trace::trace_error;

mod ui;

use ui::build_ui;

fn main() {
    let name = "imag-store";
    let version = &version!()[..];
    let about = "Direct interface to the store. Use with great care!";
    let ui = build_ui(Runtime::get_default_cli_builder(name, version, about));
    let rt = {
        let rt = Runtime::new(ui);
        if rt.is_ok() {
            rt.unwrap()
        } else {
            println!("Could not set up Runtime");
            println!("{:?}", rt.unwrap_err());
            exit(1);
        }
    };

    let id = rt.cli().value_of("id").unwrap(); // enforced by clap
    rt.cli()
        .subcommand_name()
        .map_or_else(
            || {
                let add = rt.cli().values_of("add").map(|o| o.map(String::from));
                let rem = rt.cli().values_of("remove").map(|o| o.map(String::from));

                alter(&rt, id, add, rem);
            },
            |name| {
                debug!("Call: {}", name);
                match name {
                    "list" => list(id, &rt),
                    _ => {
                        warn!("Unknown command");
                        // More error handling
                    },
                };
            });
}

fn alter<SI: Iterator<Item = String>>(rt: &Runtime, id: &str, add: Option<SI>, rem: Option<SI>) {
    let path = {
        match build_entry_path(rt.store(), id) {
            Err(e) => {
                trace_error(&e);
                exit(1);
            },
            Ok(s) => s,
        }
    };
    debug!("path = {:?}", path);

    rt.store()
        // "id" must be present, enforced via clap spec
        .retrieve(path)
        .map(|mut e| {
            add.map(|tags| {
                for tag in tags {
                    debug!("Adding tag '{:?}'", tag);
                    if let Err(e) = e.add_tag(tag) {
                        trace_error(&e);
                    }
                }
            }); // it is okay to ignore a None here

            rem.map(|tags| {
                for tag in tags {
                    debug!("Removing tag '{:?}'", tag);
                    if let Err(e) = e.remove_tag(tag) {
                        trace_error(&e);
                    }
                }
            }); // it is okay to ignore a None here
        })
        .map_err(|e| {
            info!("No entry.");
            trace_error(&e);
        })
        .ok();
}

fn list(id: &str, rt: &Runtime) {
    let path = {
        match build_entry_path(rt.store(), id) {
            Err(e) => {
                trace_error(&e);
                exit(1);
            },
            Ok(s) => s,
        }
    };
    debug!("path = {:?}", path);

    let entry = rt.store().retrieve(path.clone());
    if entry.is_err() {
        debug!("Could not retrieve '{:?}' => {:?}", id, path);
        warn!("Could not retrieve entry '{}'", id);
        trace_error(&entry.unwrap_err());
        exit(1);
    }
    let entry = entry.unwrap();

    let scmd = rt.cli().subcommand_matches("list").unwrap(); // safe, we checked in main()

    let json_out = scmd.is_present("json");
    let line_out = scmd.is_present("linewise");
    let sepp_out = scmd.is_present("sep");
    let mut comm_out = scmd.is_present("commasep");

    if !vec![json_out, line_out, comm_out, sepp_out].iter().any(|v| *v) {
        // None of the flags passed, go to default
        comm_out = true;
    }

    let tags = entry.get_tags();
    if tags.is_err() {
        trace_error(&tags.unwrap_err());
        exit(1);
    }
    let tags = tags.unwrap();

    if json_out {
        unimplemented!()
    }

    if line_out {
        for tag in &tags {
            println!("{}", tag);
        }
    }

    if sepp_out {
        let sepp = scmd.value_of("sep").unwrap(); // we checked before
        println!("{}", tags.join(sepp));
    }

    if comm_out {
        println!("{}", tags.join(", "));
    }
}

<commit_msg>imag-tag: Fix commandline extracting by using helpers from libimagentrytag<commit_after>extern crate clap;
#[macro_use] extern crate log;
extern crate semver;
extern crate toml;
#[macro_use] extern crate version;

extern crate libimagstore;
extern crate libimagrt;
extern crate libimagentrytag;
extern crate libimagerror;

use std::process::exit;

use libimagrt::runtime::Runtime;
use libimagentrytag::tagable::Tagable;
use libimagentrytag::tag::Tag;
use libimagstore::storeid::build_entry_path;
use libimagerror::trace::trace_error;
use libimagentrytag::ui::{get_add_tags, get_remove_tags};

mod ui;

use ui::build_ui;

fn main() {
    let name = "imag-store";
    let version = &version!()[..];
    let about = "Direct interface to the store. Use with great care!";
    let ui = build_ui(Runtime::get_default_cli_builder(name, version, about));
    let rt = {
        let rt = Runtime::new(ui);
        if rt.is_ok() {
            rt.unwrap()
        } else {
            println!("Could not set up Runtime");
            println!("{:?}", rt.unwrap_err());
            exit(1);
        }
    };

    let id = rt.cli().value_of("id").unwrap(); // enforced by clap
    rt.cli()
        .subcommand_name()
        .map_or_else(
            || {
                let add = get_add_tags(rt.cli());
                let rem = get_remove_tags(rt.cli());
                alter(&rt, id, add, rem);
            },
            |name| {
                debug!("Call: {}", name);
                match name {
                    "list" => list(id, &rt),
                    _ => {
                        warn!("Unknown command");
                        // More error handling
                    },
                };
            });
}

fn alter(rt: &Runtime, id: &str, add: Option<Vec<Tag>>, rem: Option<Vec<Tag>>) {
    let path = {
        match build_entry_path(rt.store(), id) {
            Err(e) => {
                trace_error(&e);
                exit(1);
            },
            Ok(s) => s,
        }
    };
    debug!("path = {:?}", path);

    rt.store()
        // "id" must be present, enforced via clap spec
        .retrieve(path)
        .map(|mut e| {
            add.map(|tags| {
                for tag in tags {
                    debug!("Adding tag '{:?}'", tag);
                    if let Err(e) = e.add_tag(tag) {
                        trace_error(&e);
                    }
                }
            }); // it is okay to ignore a None here

            rem.map(|tags| {
                for tag in tags {
                    debug!("Removing tag '{:?}'", tag);
                    if let Err(e) = e.remove_tag(tag) {
                        trace_error(&e);
                    }
                }
            }); // it is okay to ignore a None here
        })
        .map_err(|e| {
            info!("No entry.");
            trace_error(&e);
        })
        .ok();
}

fn list(id: &str, rt: &Runtime) {
    let path = {
        match build_entry_path(rt.store(), id) {
            Err(e) => {
                trace_error(&e);
                exit(1);
            },
            Ok(s) => s,
        }
    };
    debug!("path = {:?}", path);

    let entry = rt.store().retrieve(path.clone());
    if entry.is_err() {
        debug!("Could not retrieve '{:?}' => {:?}", id, path);
        warn!("Could not retrieve entry '{}'", id);
        trace_error(&entry.unwrap_err());
        exit(1);
    }
    let entry = entry.unwrap();

    let scmd = rt.cli().subcommand_matches("list").unwrap(); // safe, we checked in main()

    let json_out = scmd.is_present("json");
    let line_out = scmd.is_present("linewise");
    let sepp_out = scmd.is_present("sep");
    let mut comm_out = scmd.is_present("commasep");

    if !vec![json_out, line_out, comm_out, sepp_out].iter().any(|v| *v) {
        // None of the flags passed, go to default
        comm_out = true;
    }

    let tags = entry.get_tags();
    if tags.is_err() {
        trace_error(&tags.unwrap_err());
        exit(1);
    }
    let tags = tags.unwrap();

    if json_out {
        unimplemented!()
    }

    if line_out {
        for tag in &tags {
            println!("{}", tag);
        }
    }

    if sepp_out {
        let sepp = scmd.value_of("sep").unwrap(); // we checked before
        println!("{}", tags.join(sepp));
    }

    if comm_out {
        println!("{}", tags.join(", "));
    }
}

<|endoftext|>


<commit_before><commit_msg>Update PacketHandler and add PacketSide enum.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix read_client_packet missing 2 bytes and add test.<commit_after><|endoftext|>


<commit_before><commit_msg>add basic get/put bench<commit_after>#![feature(test)]

extern crate cask;
extern crate rand;
extern crate test;

use std::fs;

use cask::CaskOptions;
use rand::Rng;
use test::Bencher;

#[bench]
fn get_latency(b: &mut Bencher) {
    let id: String = rand::thread_rng().gen_ascii_chars().take(16).collect();
    let path = format!("bench-{}.db", id);

    let cask = CaskOptions::default()
        .compaction_check_frequency(1)
        .max_file_size(50 * 1024 * 1024)
        .sync(false)
        .open(&path)
        .unwrap();

    let key = vec![1u8; 512];
    let vec = vec![1u8; 4096];

    cask.put(key.clone(), &vec).unwrap();

    b.bytes = vec.len() as u64;
    b.iter(|| cask.get(&key).unwrap());

    fs::remove_dir_all(path).unwrap();
}

#[bench]
fn put_latency(b: &mut Bencher) {
    let id: String = rand::thread_rng().gen_ascii_chars().take(16).collect();
    let path = format!("bench-{}.db", id);

    let cask = CaskOptions::default()
        .compaction_check_frequency(1)
        .max_file_size(50 * 1024 * 1024)
        .sync(false)
        .open(&path)
        .unwrap();

    let key = vec![1u8; 512];
    let vec = vec![1u8; 4096];

    b.bytes = vec.len() as u64;
    b.iter(|| cask.put(key.clone(), &vec).unwrap());

    fs::remove_dir_all(path).unwrap();
}
<|endoftext|>


<commit_before><commit_msg>Fix bench<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for issue 6157<commit_after>// Copyright 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.

pub trait OpInt<'a> { fn call<'a>(&'a self, int, int) -> int; }

impl<'a> OpInt<'a> for 'a |int, int| -> int {
    fn call(&self, a:int, b:int) -> int {
        (*self)(a, b)
    }
}

fn squarei<'a>(x: int, op: &'a OpInt) -> int { op.call(x, x) }

fn muli(x:int, y:int) -> int { x * y }

pub fn main() {
    let f = |x,y| muli(x,y);
    {
        let g = &f;
        let h = g as &OpInt;
        squarei(3, h);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add wireframe Example<commit_after>extern crate bootstrap_rs as bootstrap;
extern crate gl_util as gl;

use bootstrap::window::*;
use gl::*;

static VERTEX_POSITIONS: [f32; 9] = [
    -1.0, -1.0, 0.0,
     1.0, -1.0, 0.0,
     0.0,  1.0, 0.0,
];

static VERTEX_INDICES: [u32; 6] = [
    0, 1,
    1, 2,
    2, 0,
];

fn main() {
    let mut window = Window::new("gl-util - wireframe example");

    gl::init();
    let mut vertex_buffer = VertexBuffer::new();
    vertex_buffer.set_data_f32(&VERTEX_POSITIONS[..]);
    vertex_buffer.set_attrib_f32(AttributeLocation::from_index(0), 3, 0, 0);

    let mut index_buffer = IndexBuffer::new();
    index_buffer.set_data_u32(&VERTEX_INDICES[..]);

    'outer: loop {
        while let Some(message) = window.next_message() {
            match message {
                Message::Close => break 'outer,
                _ => {},
            }

            gl::clear();
            vertex_buffer.draw_elements(DrawMode::Lines, &index_buffer);
            gl::swap_buffers();
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Adapt cp.rs to ArgParser and fix behavior to POSIX specification<commit_after><|endoftext|>


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

use dom::bindings::error::Fallible;
use dom::bindings::error::Error::DataClone;
use dom::bindings::global::GlobalRef;

use js::glue::JS_STRUCTURED_CLONE_VERSION;
use js::jsapi::JSContext;
use js::jsapi::{JS_WriteStructuredClone, JS_ClearPendingException};
use js::jsapi::JS_ReadStructuredClone;
use js::jsval::{JSVal, UndefinedValue};

use libc::size_t;
use std::ptr;

pub struct StructuredCloneData {
    data: *mut u64,
    nbytes: size_t,
}

impl StructuredCloneData {
    pub fn write(cx: *mut JSContext, message: JSVal)
                 -> Fallible<StructuredCloneData> {
        let mut data = ptr::null_mut();
        let mut nbytes = 0;
        let result = unsafe {
            JS_WriteStructuredClone(cx, message, &mut data, &mut nbytes,
                                    ptr::null(), ptr::null_mut())
        };
        if result == 0 {
            unsafe { JS_ClearPendingException(cx); }
            return Err(DataClone);
        }
        Ok(StructuredCloneData {
            data: data,
            nbytes: nbytes,
        })
    }

    pub fn read(self, global: GlobalRef) -> JSVal {
        let mut message = UndefinedValue();
        unsafe {
            assert!(JS_ReadStructuredClone(
                global.get_cx(), self.data as *const u64, self.nbytes,
                JS_STRUCTURED_CLONE_VERSION, &mut message,
                ptr::null(), ptr::null_mut()) != 0);
        }
        message
    }
}
<commit_msg>auto merge of #4678 : Ms2ger/servo/doc-clone, r=jdm<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! This module implements structured cloning, as defined by [HTML]
//! (https://html.spec.whatwg.org/multipage/#safe-passing-of-structured-data).

#![deny(missing_docs)]

use dom::bindings::error::Fallible;
use dom::bindings::error::Error::DataClone;
use dom::bindings::global::GlobalRef;

use js::glue::JS_STRUCTURED_CLONE_VERSION;
use js::jsapi::JSContext;
use js::jsapi::{JS_WriteStructuredClone, JS_ClearPendingException};
use js::jsapi::JS_ReadStructuredClone;
use js::jsval::{JSVal, UndefinedValue};

use libc::size_t;
use std::ptr;

/// A buffer for a structured clone.
pub struct StructuredCloneData {
    data: *mut u64,
    nbytes: size_t,
}

impl StructuredCloneData {
    /// Writes a structured clone. Returns a `DataClone` error if that fails.
    pub fn write(cx: *mut JSContext, message: JSVal)
                 -> Fallible<StructuredCloneData> {
        let mut data = ptr::null_mut();
        let mut nbytes = 0;
        let result = unsafe {
            JS_WriteStructuredClone(cx, message, &mut data, &mut nbytes,
                                    ptr::null(), ptr::null_mut())
        };
        if result == 0 {
            unsafe { JS_ClearPendingException(cx); }
            return Err(DataClone);
        }
        Ok(StructuredCloneData {
            data: data,
            nbytes: nbytes,
        })
    }

    /// Reads a structured clone.
    ///
    /// Panics if `JS_ReadStructuredClone` fails.
    pub fn read(self, global: GlobalRef) -> JSVal {
        let mut message = UndefinedValue();
        unsafe {
            assert!(JS_ReadStructuredClone(
                global.get_cx(), self.data as *const u64, self.nbytes,
                JS_STRUCTURED_CLONE_VERSION, &mut message,
                ptr::null(), ptr::null_mut()) != 0);
        }
        message
    }
}
<|endoftext|>


<commit_before><commit_msg>acc config fix<commit_after>extern crate rustc_serialize;
extern crate getopts;
extern crate byteorder;
extern crate flv_toolbox_rs;

use std::path::Path;
use std::fs::File;
use std::io::{ Seek, SeekFrom, Read, Write };

use self::byteorder::{BigEndian, WriteBytesExt};
use rustc_serialize::json::Json;
use getopts::Options;

use flv_toolbox_rs::lib::{ FLVTagRead, FLVHeader, FLVTagType, FLVTag };

fn print_usage(program: &str, opts: Options) {
    let brief = format!("Usage: {} FILE [options]", program);
    eprintln!("{}", opts.usage(&brief));
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    let program = args[0].clone();

    let mut opts = Options::new();
    opts.optflagopt("o", "output", "output flv file", "OUTPUT");
    opts.optflag("h", "help", "print this help menu");
    opts.optflag("t", "check-only", "test, check only");

    let usage_str = {
        let brief = format!("Usage: {} FILE [options]", program);
        format!("{}", opts.usage(&brief))
    };

    let exit_with_usage = || {
        eprintln!("{}", usage_str);
        std::process::exit(-1);
    };

    let matches: getopts::Matches = match opts.parse(&args[1..]) {
        Ok(m) => m,
        Err(f) => {
            eprintln!("{}", f.to_string());
            return exit_with_usage();
        }
    };

    if matches.opt_present("h") {
        return exit_with_usage();
    }

    let test = matches.opt_present("t");

    let input: String = if !matches.free.is_empty() {
        matches.free[0].clone()
    } else {
        eprintln!("no input file.");
        return exit_with_usage();
    };

    let input_path: &Path = Path::new(&input);
    if !input_path.exists() {
        eprintln!("input file does not exist.");
        return exit_with_usage();
    }

    let output = match matches.opt_default("o", "") {
        Some(c) => c,
        _ => {
            let file = input_path.file_stem().unwrap().to_string_lossy().to_string();
            let mut output = input_path.with_file_name(format!("{}-fixed.flv", &file));
            let mut i: i32 = 0;
            while output.exists() {
                i += 1;
                output = input_path.with_file_name(format!("{}-fixed({}).flv", &file, i));
            }
            if !test {
                eprintln!("no output file, use {}", output.to_str().unwrap());
            }
            output.to_string_lossy().to_string()
        }
    };

    let need_fix = detect_flv_acc(input_path);
    if need_fix {
        match fix_flv_acc(input_path, &output, test) {
            Ok(_) => {
                if test {
                    eprintln!("test complete.");
                } else {
                    eprintln!("fixed.");
                }
                std::process::exit(0);
            }
            Err(e) => {
                eprintln!("fix err: {}", e);
                std::process::exit(-1);
            }
        }
    } else {
        eprintln!("pass");
    }
}

fn next_tag_of_type<'a, R: Read>(parser: &mut FLVTagRead<'a, R>, tag_type: FLVTagType) -> Option<FLVTag> {
    loop {
        if let Some(tag) = parser.next() {
            if tag.get_tag_type() == tag_type {
                break Some(tag);
            } else {
                continue;
            }
        } else {
            break None;
        }
    }
}

fn detect_flv_acc(flv_path: &Path) -> bool {
    let mut file = std::fs::File::open(flv_path).unwrap();
    let mut parser = FLVTagRead::new(&mut file);
    {
        let header: &FLVHeader = &parser.header;
        if !header.hasAudioTags {
            eprintln!("no audio stream");
            return false;
        }
    }

    let audio_tag = next_tag_of_type(&mut parser, FLVTagType::TAG_TYPE_AUDIO);
    if audio_tag.is_none() {
        return false;
    }
    let audio_tag: FLVTag = audio_tag.unwrap();
    if !audio_tag.is_acc_sequence_header() {
        eprintln!("first audio tag is not acc_sequence_header, exit");
        return false;
    }
    let data_size = audio_tag.get_data_size();
    // println!("{:?}", audio_tag.get_sound_audio_specific_config());
    return data_size == 2;
}

fn fix_flv_acc(flv_path: &Path, output_path: &str, test: bool) -> Result<(), String> {
    let new_tag = {
        let mut file = std::fs::File::open(flv_path).map_err(|_| "cannot open output file.".to_owned())?;
        let mut parser = FLVTagRead::new(&mut file);

        let meta_tag = next_tag_of_type(&mut parser, FLVTagType::TAG_TYPE_SCRIPTDATAOBJECT).ok_or("no meta tag".to_string())?;
        let mut acc_tag = next_tag_of_type(&mut parser, FLVTagType::TAG_TYPE_AUDIO).ok_or::<String>("no acc_sequence_header".into())?;
        assert!(acc_tag.is_acc_sequence_header());
        assert_eq!(acc_tag.get_data_size(), 2);
        let a_tag = next_tag_of_type(&mut parser, FLVTagType::TAG_TYPE_AUDIO).ok_or::<String>("only one acc_sequence_header".into())?;
        let meta_obj = &meta_tag.get_objects()[1];
        println!("{:?}", meta_obj);
        let sample: i64 = meta_obj.find("audiosamplerate").ok_or("no audiosamplerate in meta, can't fix.".to_owned())?.as_f64().ok_or("audiosamplerate is not f64, can't fix.".to_string())? as _;
        let stereo = meta_obj.find("stereo").ok_or("no stereo in meta, can't fix.".to_owned())?.as_boolean().ok_or("no stereo in meta or stereo is not boolean, can't fix.".to_owned())?;
        if meta_obj.find("keyframes").is_some() {
            eprintln!("warning: flv has keyframes table. filepositions should adjust, but not.");
        }
        let original_audio_object_type = 2;
        let sample_index = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350].iter().position(|i: &i64| *i == sample).ok_or("sample not in sample list.".to_owned())?;
        let channel_config = if stereo { 2 } else { 1 };

        eprintln!("use config: original_audio_object_type {} sample_index {} channel_config {}", original_audio_object_type, sample_index, channel_config);
        let mut data: Vec<u8> = Vec::with_capacity(11 + 4 + 4);
        acc_tag.write(&mut data);
        eprintln!("{:?}", data);
        // set data size
        data[1] = ((4 >> 16) & 0xff) as u8;
        data[2] = ((4 >>  8) & 0xff) as u8;
        data[3] = ((4      ) & 0xff) as u8;
        data[13] = ((original_audio_object_type as u8 & 0x1f) << 3) | ((sample_index as u8 & 0xf) >> 1);
        data[14] = ((sample_index as u8 & 1) << 7) | ((channel_config & 0xf) << 3);
        data.pop();
        data.pop();
        data.write_u32::<BigEndian>(15).unwrap();
        eprintln!("{:?}", data);
        let new_tag = FLVTag::read(&mut &*data).unwrap();
        eprintln!("{:?}", (new_tag.get_tag_type(), new_tag.get_data_size(), new_tag.get_sound_audio_specific_config()));
        new_tag
    };
    if test {
        return Ok(());
    }
    let mut new_tag = Some(new_tag);
    // reopen
    let mut file = std::fs::File::open(flv_path).map_err(|_| "cannot open output file.".to_owned())?;
    let mut parser = FLVTagRead::new(&mut file);
    let mut ofile = std::fs::File::create(output_path).map_err(|_| "cannot open output file.".to_owned())?;
    parser.header.write(&mut ofile);
    while let Some(mut tag) = parser.next() {
        if new_tag.is_some() && tag.get_tag_type() == FLVTagType::TAG_TYPE_AUDIO && tag.is_acc_sequence_header() {
            tag = new_tag.take().unwrap();// only switch once
        }
        tag.write(&mut ofile);
    }
    Ok(())
}<|endoftext|>


<commit_before><commit_msg>Fix imag-mail for new error interface<commit_after><|endoftext|>


<commit_before><commit_msg>Add debug output<commit_after><|endoftext|>


<commit_before><commit_msg>Module dedicated to the handling of kraken requests<commit_after>/*
Tristen Horton
tristen@tristenhorton.com
2017-04-03 23:37
*/
<|endoftext|>


<commit_before><commit_msg>Remove stride member from LayerBuffer<commit_after><|endoftext|>


<commit_before><commit_msg>Format macros.rs test to pass rustfmt<commit_after><|endoftext|>