<commit_before>use core::mem;

use {Future, IntoFuture, Async, Poll};
use stream::Stream;

/// Creates a `Stream` from a seed and a closure returning a `Future`.
///
/// This function is the dual for the `Stream::fold()` adapter: while `Stream:fold()` reduces a
/// `Stream` to one single value, `unfold()` creates a `Stream` from a seed value.
///
/// `unfold()` will call the provided closure with the provided seed, then wait for the
/// returned `Future` to complete with `(a, b)`. It will then yield the value `a`, and use `b`
/// as the next internal state.
///
/// If the closure returns `None` instead of `Some(Future)`, then the `unfold()` will stop
/// producing items and return `Ok(Async::Ready(None))` in future calls to `poll()`.
///
/// In case of error generated by the returned `Future`, the error will be returned by the `Stream`.
/// The `Stream` will then yield `Ok(Async::Ready(None))` in future calls to `poll()`.
///
/// This function can typically be used when wanting to go from the "world of futures" to the
/// "world of streams": the provided closure can build a `Future` using other library functions
/// working on futures, and `unfold()` will turn it into a `Stream` by repeating the operation.
///
/// # Example
///
/// ```rust
/// use futures::*;
///
/// let mut stream = stream::unfold(0, |state| {
///     if state <= 2 {
///         let next_state = state + 1;
///         let yielded = state  * 2;
///         let fut = futures::finished::<_, u32>((yielded, next_state));
///         Some(fut)
///     } else {
///         None
///     }
/// });
///
/// let result = stream.collect().wait();
/// assert_eq!(result, Ok(vec![0, 2, 4]));
/// ```
pub fn unfold<T, F, Fut, It>(init: T, f: F) -> Unfold<T, F, Fut>
where F: FnMut(T) -> Option<Fut>,
      Fut: IntoFuture<Item = (It, T)>,
{
    Unfold {
        f: f,
        state: State::Ready(init),
    }
}

/// A stream which creates futures, polls them and return their result
///
/// This stream is returned by the `futures::stream::unfold` method
#[must_use = "streams do nothing unless polled"]
pub struct Unfold<T, F, Fut> where Fut: IntoFuture {
    f: F,
    state: State<T, Fut::Future>,
}

impl <T, F, Fut, It> Stream for Unfold<T, F, Fut>
where F: FnMut(T) -> Option<Fut>,
      Fut: IntoFuture<Item = (It, T)>,
{
    type Item = It;
    type Error = Fut::Error;

    fn poll(&mut self) -> Poll<Option<It>, Fut::Error> {
        loop {
            match mem::replace(&mut self.state, State::Empty) {
                // State::Empty may happen if the future returned an error
                State::Empty => { return Ok(Async::Ready(None)); }
                State::Ready(state) => {
                    match (self.f)(state) {
                        Some(fut) => { self.state = State::Processing(fut.into_future()); }
                        None => { return Ok(Async::Ready(None)); }
                    }
                }
                State::Processing(mut fut) => {
                    match try!(fut.poll()) {
                        Async:: Ready((item, next_state)) => {
                            self.state = State::Ready(next_state);
                            return Ok(Async::Ready(Some(item)));
                        }
                        Async::NotReady => {
                            self.state = State::Processing(fut);
                            return Ok(Async::NotReady);
                        }
                    }
                }
            }
        }
    }
}

enum State<T, F> where F: Future {
    /// Placeholder state when doing work, or when the returned Future generated an error
    Empty,

    /// Ready to generate new future; current internal state is the `T`
    Ready(T),

    /// Working on a future generated previously
    Processing(F),
}
<commit_msg>Touch up style of unfold a bit<commit_after>use core::mem;

use {Future, IntoFuture, Async, Poll};
use stream::Stream;

/// Creates a `Stream` from a seed and a closure returning a `Future`.
///
/// This function is the dual for the `Stream::fold()` adapter: while
/// `Stream:fold()` reduces a `Stream` to one single value, `unfold()` creates a
/// `Stream` from a seed value.
///
/// `unfold()` will call the provided closure with the provided seed, then wait
/// for the returned `Future` to complete with `(a, b)`. It will then yield the
/// value `a`, and use `b` as the next internal state.
///
/// If the closure returns `None` instead of `Some(Future)`, then the `unfold()`
/// will stop producing items and return `Ok(Async::Ready(None))` in future
/// calls to `poll()`.
///
/// In case of error generated by the returned `Future`, the error will be
/// returned by the `Stream`.  The `Stream` will then yield
/// `Ok(Async::Ready(None))` in future calls to `poll()`.
///
/// This function can typically be used when wanting to go from the "world of
/// futures" to the "world of streams": the provided closure can build a
/// `Future` using other library functions working on futures, and `unfold()`
/// will turn it into a `Stream` by repeating the operation.
///
/// # Example
///
/// ```rust
/// use futures::*;
///
/// let mut stream = stream::unfold(0, |state| {
///     if state <= 2 {
///         let next_state = state + 1;
///         let yielded = state  * 2;
///         let fut = futures::finished::<_, u32>((yielded, next_state));
///         Some(fut)
///     } else {
///         None
///     }
/// });
///
/// let result = stream.collect().wait();
/// assert_eq!(result, Ok(vec![0, 2, 4]));
/// ```
pub fn unfold<T, F, Fut, It>(init: T, f: F) -> Unfold<T, F, Fut>
    where F: FnMut(T) -> Option<Fut>,
          Fut: IntoFuture<Item = (It, T)>,
{
    Unfold {
        f: f,
        state: State::Ready(init),
    }
}

/// A stream which creates futures, polls them and return their result
///
/// This stream is returned by the `futures::stream::unfold` method
#[must_use = "streams do nothing unless polled"]
pub struct Unfold<T, F, Fut> where Fut: IntoFuture {
    f: F,
    state: State<T, Fut::Future>,
}

impl <T, F, Fut, It> Stream for Unfold<T, F, Fut>
    where F: FnMut(T) -> Option<Fut>,
          Fut: IntoFuture<Item = (It, T)>,
{
    type Item = It;
    type Error = Fut::Error;

    fn poll(&mut self) -> Poll<Option<It>, Fut::Error> {
        loop {
            match mem::replace(&mut self.state, State::Empty) {
                // State::Empty may happen if the future returned an error
                State::Empty => { return Ok(Async::Ready(None)); }
                State::Ready(state) => {
                    match (self.f)(state) {
                        Some(fut) => { self.state = State::Processing(fut.into_future()); }
                        None => { return Ok(Async::Ready(None)); }
                    }
                }
                State::Processing(mut fut) => {
                    match try!(fut.poll()) {
                        Async:: Ready((item, next_state)) => {
                            self.state = State::Ready(next_state);
                            return Ok(Async::Ready(Some(item)));
                        }
                        Async::NotReady => {
                            self.state = State::Processing(fut);
                            return Ok(Async::NotReady);
                        }
                    }
                }
            }
        }
    }
}

enum State<T, F> where F: Future {
    /// Placeholder state when doing work, or when the returned Future generated an error
    Empty,

    /// Ready to generate new future; current internal state is the `T`
    Ready(T),

    /// Working on a future generated previously
    Processing(F),
}
<|endoftext|>


<commit_before><commit_msg>implement builder interface for conv2d<commit_after>use nn::modules::module::*;
use nn::parameter::Parameter;

#[derive(ModParse)]
pub struct Conv2d<'a> {
    delegate: Module<'a>,
	weight: Parameter<'a>
}

impl <'a>Conv2d<'a> {
	pub fn build(in_channels: u32, out_channels: u32, kernel_size: u32) -> Conv2dArgsBuilder {
		Conv2dArgsBuilder::default()
			.in_channels(in_channels)
			.out_channels(out_channels)
			.kernel_size(kernel_size)
	}
	pub fn new(args: Conv2dArgs) -> Conv2d<'a> {
		Conv2d {delegate: Module::new(), weight: Parameter::default()}
	}
}

#[builder(pattern="owned")]
#[derive(Builder)]
pub struct Conv2dArgs {
	in_channels: u32,
	out_channels: u32,
	kernel_size: u32,
	#[builder(default="1")]
	stride: u32,
	#[builder(default="0")]
	padding: u32,
	#[builder(default="1")]
	dilation: u32,
	#[builder(default="1")]
	groups: u32,
	#[builder(default="true")]
	bias: bool,
}
impl Conv2dArgsBuilder {
	pub fn done<'a>(self) -> Conv2d<'a> {
		let args = self.build().unwrap();
		Conv2d::new(args)
	}
}<|endoftext|>


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

use std::uint;

enum RangeRelation {
    OverlapsBegin(/* overlap */ uint),
    OverlapsEnd(/* overlap */ uint),
    ContainedBy,
    Contains,
    Coincides,
    EntirelyBefore,
    EntirelyAfter
}

pub struct Range {
    priv off: uint,
    priv len: uint
}

impl Range {
    pub fn new(off: uint, len: uint) -> Range {
        Range { off: off, len: len }
    }

    pub fn empty() -> Range {
        Range::new(0, 0)
    }
}

impl Range {
    pub fn begin(&self) -> uint { self.off  }
    pub fn length(&self) -> uint { self.len }
    pub fn end(&self) -> uint { self.off + self.len }

    pub fn eachi(&self, callback: &fn(uint) -> bool) -> bool {
        for uint::range(self.off, self.off + self.len) |i| {
            if !callback(i) {
                break
            }
        }
        true
    }

    pub fn contains(&self, i: uint) -> bool {
        i >= self.begin() && i < self.end()
    }

    pub fn is_valid_for_string(&self, s: &str) -> bool {
        self.begin() < s.len() && self.end() <= s.len() && self.length() <= s.len()
    }

    pub fn shift_by(&mut self, i: int) {
        self.off = ((self.off as int) + i) as uint;
    }

    pub fn extend_by(&mut self, i: int) {
        self.len = ((self.len as int) + i) as uint;
    }

    pub fn extend_to(&mut self, i: uint) {
        self.len = i - self.off;
    }

    pub fn adjust_by(&mut self, off_i: int, len_i: int) {
        self.off = ((self.off as int) + off_i) as uint;
        self.len = ((self.len as int) + len_i) as uint;
    }

    pub fn reset(&mut self, off_i: uint, len_i: uint) {
        self.off = off_i;
        self.len = len_i;
    }

    /// Computes the relationship between two ranges (`self` and `other`),
    /// from the point of view of `self`. So, 'EntirelyBefore' means
    /// that the `self` range is entirely before `other` range.
    pub fn relation_to_range(&self, other: &Range) -> RangeRelation {
        if other.begin() > self.end() {
            return EntirelyBefore;
        }
        if self.begin() > other.end() {
            return EntirelyAfter;
        }
        if self.begin() == other.begin() && self.end() == other.end() {
            return Coincides;
        }
        if self.begin() <= other.begin() && self.end() >= other.end() {
            return Contains;
        }
        if self.begin() >= other.begin() && self.end() <= other.end() {
            return ContainedBy;
        }
        if self.begin() < other.begin() && self.end() < other.end() {
            let overlap = self.end() - other.begin();
            return OverlapsBegin(overlap);
        }
        if self.begin() > other.begin() && self.end() > other.end() {
            let overlap = other.end() - self.begin();
            return OverlapsEnd(overlap);
        }
        fail!(fmt!("relation_to_range(): didn't classify self=%?, other=%?",
                  self, other));
    }

    pub fn repair_after_coalesced_range(&mut self, other: &Range) {
        let relation = self.relation_to_range(other);
        debug!("repair_after_coalesced_range: possibly repairing range %?", self);
        debug!("repair_after_coalesced_range: relation of original range and coalesced range(%?): %?",
               other, relation);
        match relation {
            EntirelyBefore => { },
            EntirelyAfter =>  { self.shift_by(-(other.length() as int)); },
            Coincides | ContainedBy =>   { self.reset(other.begin(), 1); },
            Contains =>      { self.extend_by(-(other.length() as int)); },
            OverlapsBegin(overlap) => { self.extend_by(1 - (overlap as int)); },
            OverlapsEnd(overlap) => {
                let len = self.length() - overlap + 1;
                self.reset(other.begin(), len);
            }
        };
        debug!("repair_after_coalesced_range: new range: ---- %?", self);
    }
}
<commit_msg>Add utility methods to Range<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use std::uint;
use std::cmp::{max, min};

enum RangeRelation {
    OverlapsBegin(/* overlap */ uint),
    OverlapsEnd(/* overlap */ uint),
    ContainedBy,
    Contains,
    Coincides,
    EntirelyBefore,
    EntirelyAfter
}

pub struct Range {
    priv off: uint,
    priv len: uint
}

impl Range {
    pub fn new(off: uint, len: uint) -> Range {
        Range { off: off, len: len }
    }

    pub fn empty() -> Range {
        Range::new(0, 0)
    }
}

impl Range {
    pub fn begin(&self) -> uint { self.off  }
    pub fn length(&self) -> uint { self.len }
    pub fn end(&self) -> uint { self.off + self.len }

    pub fn eachi(&self, callback: &fn(uint) -> bool) -> bool {
        for uint::range(self.off, self.off + self.len) |i| {
            if !callback(i) {
                break
            }
        }
        true
    }

    pub fn contains(&self, i: uint) -> bool {
        i >= self.begin() && i < self.end()
    }

    pub fn is_valid_for_string(&self, s: &str) -> bool {
        self.begin() < s.len() && self.end() <= s.len() && self.length() <= s.len()
    }

    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    pub fn shift_by(&mut self, i: int) {
        self.off = ((self.off as int) + i) as uint;
    }

    pub fn extend_by(&mut self, i: int) {
        self.len = ((self.len as int) + i) as uint;
    }

    pub fn extend_to(&mut self, i: uint) {
        self.len = i - self.off;
    }

    pub fn adjust_by(&mut self, off_i: int, len_i: int) {
        self.off = ((self.off as int) + off_i) as uint;
        self.len = ((self.len as int) + len_i) as uint;
    }

    pub fn reset(&mut self, off_i: uint, len_i: uint) {
        self.off = off_i;
        self.len = len_i;
    }

    pub fn intersect(&self, other: &Range) -> Range {
        let begin = max(self.begin(), other.begin());
        let end = min(self.end(), other.end());

        if end < begin {
            Range::empty()
        } else {
            Range::new(begin, end - begin)
        }
    }

    /// Computes the relationship between two ranges (`self` and `other`),
    /// from the point of view of `self`. So, 'EntirelyBefore' means
    /// that the `self` range is entirely before `other` range.
    pub fn relation_to_range(&self, other: &Range) -> RangeRelation {
        if other.begin() > self.end() {
            return EntirelyBefore;
        }
        if self.begin() > other.end() {
            return EntirelyAfter;
        }
        if self.begin() == other.begin() && self.end() == other.end() {
            return Coincides;
        }
        if self.begin() <= other.begin() && self.end() >= other.end() {
            return Contains;
        }
        if self.begin() >= other.begin() && self.end() <= other.end() {
            return ContainedBy;
        }
        if self.begin() < other.begin() && self.end() < other.end() {
            let overlap = self.end() - other.begin();
            return OverlapsBegin(overlap);
        }
        if self.begin() > other.begin() && self.end() > other.end() {
            let overlap = other.end() - self.begin();
            return OverlapsEnd(overlap);
        }
        fail!(fmt!("relation_to_range(): didn't classify self=%?, other=%?",
                  self, other));
    }

    pub fn repair_after_coalesced_range(&mut self, other: &Range) {
        let relation = self.relation_to_range(other);
        debug!("repair_after_coalesced_range: possibly repairing range %?", self);
        debug!("repair_after_coalesced_range: relation of original range and coalesced range(%?): %?",
               other, relation);
        match relation {
            EntirelyBefore => { },
            EntirelyAfter =>  { self.shift_by(-(other.length() as int)); },
            Coincides | ContainedBy =>   { self.reset(other.begin(), 1); },
            Contains =>      { self.extend_by(-(other.length() as int)); },
            OverlapsBegin(overlap) => { self.extend_by(1 - (overlap as int)); },
            OverlapsEnd(overlap) => {
                let len = self.length() - overlap + 1;
                self.reset(other.begin(), len);
            }
        };
        debug!("repair_after_coalesced_range: new range: ---- %?", self);
    }
}
<|endoftext|>


<commit_before>use collections::borrow::ToOwned;
use collections::String;

use common::time::Duration;

#[derive(Copy, Clone)]
pub enum LogLevel {
    Critical,
    Error,
    Warning,
    Info,
    Debug,
}

/// Add message to kernel logs with format
#[macro_export]
macro_rules! syslog {
    ($level:expr, $($arg:tt)*) => ({
        $crate::logging::syslog_inner($level, format!($($arg)*));
    });
}

#[macro_export]
macro_rules! syslog_debug {
    ($($arg:tt)*) => ({
        $crate::logging::syslog_inner($crate::logging::LogLevel::Debug, format!($($arg)*));
    });
}

#[macro_export]
macro_rules! syslog_info {
    ($($arg:tt)*) => ({
        $crate::logging::syslog_inner($crate::logging::LogLevel::Info, format!($($arg)*));
    });
}

#[macro_export]
macro_rules! syslog_warning {
    ($($arg:tt)*) => ({
        $crate::logging::syslog_inner($crate::logging::LogLevel::Warning, format!($($arg)*));
    });
}

#[macro_export]
macro_rules! syslog_critical {
    ($($arg:tt)*) => ({
        $crate::logging::syslog_inner($crate::logging::LogLevel::Critical, format!($($arg)*));
    });
}

#[macro_export]
macro_rules! syslog_error {
    ($($arg:tt)*) => ({
        $crate::logging::syslog_inner($crate::logging::LogLevel::Error, format!($($arg)*));
    });
}

/// Add `message` to the kernel logs, with a priority level of `level`
pub fn syslog(level: LogLevel, message: &str) {
    syslog_inner(level, message.to_owned());
}

//TODO: Limit log message size
pub fn syslog_inner(level: LogLevel, message: String) {
    let time = Duration::monotonic();
    let logs = unsafe { &mut *::env().logs.get() };
    while logs.len() >= 4096 {
        logs.pop_front();
    }
    logs.push_back((time, level, message));
    //TODO: Print messages that are above priority
}
<commit_msg>Print out syslog messages<commit_after>use collections::borrow::ToOwned;
use collections::String;

use common::time::Duration;

#[derive(Copy, Clone)]
pub enum LogLevel {
    Critical,
    Error,
    Warning,
    Info,
    Debug,
}

/// Add message to kernel logs with format
#[macro_export]
macro_rules! syslog {
    ($level:expr, $($arg:tt)*) => ({
        $crate::logging::syslog_inner($level, format!($($arg)*));
    });
}

#[macro_export]
macro_rules! syslog_debug {
    ($($arg:tt)*) => ({
        $crate::logging::syslog_inner($crate::logging::LogLevel::Debug, format!($($arg)*));
    });
}

#[macro_export]
macro_rules! syslog_info {
    ($($arg:tt)*) => ({
        $crate::logging::syslog_inner($crate::logging::LogLevel::Info, format!($($arg)*));
    });
}

#[macro_export]
macro_rules! syslog_warning {
    ($($arg:tt)*) => ({
        $crate::logging::syslog_inner($crate::logging::LogLevel::Warning, format!($($arg)*));
    });
}

#[macro_export]
macro_rules! syslog_critical {
    ($($arg:tt)*) => ({
        $crate::logging::syslog_inner($crate::logging::LogLevel::Critical, format!($($arg)*));
    });
}

#[macro_export]
macro_rules! syslog_error {
    ($($arg:tt)*) => ({
        $crate::logging::syslog_inner($crate::logging::LogLevel::Error, format!($($arg)*));
    });
}

/// Add `message` to the kernel logs, with a priority level of `level`
pub fn syslog(level: LogLevel, message: &str) {
    syslog_inner(level, message.to_owned());
}

//TODO: Limit log message size
pub fn syslog_inner(level: LogLevel, message: String) {
    let time = Duration::monotonic();

    let prefix: &str = match level {
        LogLevel::Debug    => "DEBUG ",
        LogLevel::Info     => "INFO  ",
        LogLevel::Warning  => "WARN  ",
        LogLevel::Error    => "ERROR ",
        LogLevel::Critical => "CRIT  ",
    };
    debugln!("[{}.{:>03}] {}{}", time.secs, time.nanos/1000000, prefix, message);

    let logs = unsafe { &mut *::env().logs.get() };
    while logs.len() >= 4096 {
        logs.pop_front();
    }
    logs.push_back((time, level, message));
}
<|endoftext|>


<commit_before><commit_msg>Add the start to a basic integration test<commit_after>extern crate thoughtfuck;

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(None);
    program.execute(&mut vm);
}
<|endoftext|>


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

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

extern crate libc;

use libc::{c_int, c_void, size_t};

// Linkage directives to pull in jemalloc and its dependencies.
//
// On some platforms we need to be sure to link in `pthread` which jemalloc
// depends on, and specifically on android we need to also link to libgcc.
// Currently jemalloc is compiled with gcc which will generate calls to
// intrinsics that are libgcc specific (e.g. those intrinsics aren't present in
// libcompiler-rt), so link that in to get that support.
#[link(name = "jemalloc", kind = "static")]
#[cfg_attr(target_os = "android", link(name = "gcc"))]
#[cfg_attr(all(not(windows),
               not(target_os = "android"),
               not(target_env = "musl")),
           link(name = "pthread"))]
#[cfg(not(cargobuild))]
extern {}

// Note that the symbols here are prefixed by default on OSX (we don't
// explicitly request it), and on Android and DragonFly we explicitly request
// it as unprefixing cause segfaults (mismatches in allocators).
extern {
    #[cfg_attr(any(target_os = "macos", target_os = "android", target_os = "ios",
                   target_os = "dragonfly"),
               link_name = "je_mallocx")]
    fn mallocx(size: size_t, flags: c_int) -> *mut c_void;
    #[cfg_attr(any(target_os = "macos", target_os = "android", target_os = "ios",
                   target_os = "dragonfly"),
               link_name = "je_rallocx")]
    fn rallocx(ptr: *mut c_void, size: size_t, flags: c_int) -> *mut c_void;
    #[cfg_attr(any(target_os = "macos", target_os = "android", target_os = "ios",
                   target_os = "dragonfly"),
               link_name = "je_xallocx")]
    fn xallocx(ptr: *mut c_void, size: size_t, extra: size_t, flags: c_int) -> size_t;
    #[cfg_attr(any(target_os = "macos", target_os = "android", target_os = "ios",
                   target_os = "dragonfly"),
               link_name = "je_sdallocx")]
    fn sdallocx(ptr: *mut c_void, size: size_t, flags: c_int);
    #[cfg_attr(any(target_os = "macos", target_os = "android", target_os = "ios",
                   target_os = "dragonfly"),
               link_name = "je_nallocx")]
    fn nallocx(size: size_t, flags: c_int) -> size_t;
}

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

// MALLOCX_ALIGN(a) macro
fn mallocx_align(a: usize) -> c_int {
    a.trailing_zeros() as c_int
}

fn align_to_flags(align: usize) -> c_int {
    if align <= MIN_ALIGN {
        0
    } else {
        mallocx_align(align)
    }
}

#[no_mangle]
pub extern "C" fn __rust_allocate(size: usize, align: usize) -> *mut u8 {
    let flags = align_to_flags(align);
    unsafe { mallocx(size as size_t, flags) as *mut u8 }
}

#[no_mangle]
pub extern "C" fn __rust_reallocate(ptr: *mut u8,
                                    _old_size: usize,
                                    size: usize,
                                    align: usize)
                                    -> *mut u8 {
    let flags = align_to_flags(align);
    unsafe { rallocx(ptr as *mut c_void, size as size_t, flags) as *mut u8 }
}

#[no_mangle]
pub extern "C" fn __rust_reallocate_inplace(ptr: *mut u8,
                                            _old_size: usize,
                                            size: usize,
                                            align: usize)
                                            -> usize {
    let flags = align_to_flags(align);
    unsafe { xallocx(ptr as *mut c_void, size as size_t, 0, flags) as usize }
}

#[no_mangle]
pub extern "C" fn __rust_deallocate(ptr: *mut u8, old_size: usize, align: usize) {
    let flags = align_to_flags(align);
    unsafe { sdallocx(ptr as *mut c_void, old_size as size_t, flags) }
}

#[no_mangle]
pub extern "C" fn __rust_usable_size(size: usize, align: usize) -> usize {
    let flags = align_to_flags(align);
    unsafe { nallocx(size as size_t, flags) as usize }
}

// These symbols are used by jemalloc on android but the really old android
// we're building on doesn't have them defined, so just make sure the symbols
// are available.
#[no_mangle]
#[cfg(target_os = "android")]
pub extern fn pthread_atfork(_prefork: *mut u8,
                             _postfork_parent: *mut u8,
                             _postfork_child: *mut u8) -> i32 {
    0
}
<commit_msg>Auto merge of #33308 - ollie27:wingnu_jemalloc, r=alexcrichton<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

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

extern crate libc;

use libc::{c_int, c_void, size_t};

// Linkage directives to pull in jemalloc and its dependencies.
//
// On some platforms we need to be sure to link in `pthread` which jemalloc
// depends on, and specifically on android we need to also link to libgcc.
// Currently jemalloc is compiled with gcc which will generate calls to
// intrinsics that are libgcc specific (e.g. those intrinsics aren't present in
// libcompiler-rt), so link that in to get that support.
#[link(name = "jemalloc", kind = "static")]
#[cfg_attr(target_os = "android", link(name = "gcc"))]
#[cfg_attr(all(not(windows),
               not(target_os = "android"),
               not(target_env = "musl")),
           link(name = "pthread"))]
#[cfg(not(cargobuild))]
extern {}

// Note that the symbols here are prefixed by default on OSX and Windows (we
// don't explicitly request it), and on Android and DragonFly we explicitly
// request it as unprefixing cause segfaults (mismatches in allocators).
extern {
    #[cfg_attr(any(target_os = "macos", target_os = "android", target_os = "ios",
                   target_os = "dragonfly", target_os = "windows"),
               link_name = "je_mallocx")]
    fn mallocx(size: size_t, flags: c_int) -> *mut c_void;
    #[cfg_attr(any(target_os = "macos", target_os = "android", target_os = "ios",
                   target_os = "dragonfly", target_os = "windows"),
               link_name = "je_rallocx")]
    fn rallocx(ptr: *mut c_void, size: size_t, flags: c_int) -> *mut c_void;
    #[cfg_attr(any(target_os = "macos", target_os = "android", target_os = "ios",
                   target_os = "dragonfly", target_os = "windows"),
               link_name = "je_xallocx")]
    fn xallocx(ptr: *mut c_void, size: size_t, extra: size_t, flags: c_int) -> size_t;
    #[cfg_attr(any(target_os = "macos", target_os = "android", target_os = "ios",
                   target_os = "dragonfly", target_os = "windows"),
               link_name = "je_sdallocx")]
    fn sdallocx(ptr: *mut c_void, size: size_t, flags: c_int);
    #[cfg_attr(any(target_os = "macos", target_os = "android", target_os = "ios",
                   target_os = "dragonfly", target_os = "windows"),
               link_name = "je_nallocx")]
    fn nallocx(size: size_t, flags: c_int) -> size_t;
}

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

// MALLOCX_ALIGN(a) macro
fn mallocx_align(a: usize) -> c_int {
    a.trailing_zeros() as c_int
}

fn align_to_flags(align: usize) -> c_int {
    if align <= MIN_ALIGN {
        0
    } else {
        mallocx_align(align)
    }
}

#[no_mangle]
pub extern "C" fn __rust_allocate(size: usize, align: usize) -> *mut u8 {
    let flags = align_to_flags(align);
    unsafe { mallocx(size as size_t, flags) as *mut u8 }
}

#[no_mangle]
pub extern "C" fn __rust_reallocate(ptr: *mut u8,
                                    _old_size: usize,
                                    size: usize,
                                    align: usize)
                                    -> *mut u8 {
    let flags = align_to_flags(align);
    unsafe { rallocx(ptr as *mut c_void, size as size_t, flags) as *mut u8 }
}

#[no_mangle]
pub extern "C" fn __rust_reallocate_inplace(ptr: *mut u8,
                                            _old_size: usize,
                                            size: usize,
                                            align: usize)
                                            -> usize {
    let flags = align_to_flags(align);
    unsafe { xallocx(ptr as *mut c_void, size as size_t, 0, flags) as usize }
}

#[no_mangle]
pub extern "C" fn __rust_deallocate(ptr: *mut u8, old_size: usize, align: usize) {
    let flags = align_to_flags(align);
    unsafe { sdallocx(ptr as *mut c_void, old_size as size_t, flags) }
}

#[no_mangle]
pub extern "C" fn __rust_usable_size(size: usize, align: usize) -> usize {
    let flags = align_to_flags(align);
    unsafe { nallocx(size as size_t, flags) as usize }
}

// These symbols are used by jemalloc on android but the really old android
// we're building on doesn't have them defined, so just make sure the symbols
// are available.
#[no_mangle]
#[cfg(target_os = "android")]
pub extern fn pthread_atfork(_prefork: *mut u8,
                             _postfork_parent: *mut u8,
                             _postfork_child: *mut u8) -> i32 {
    0
}
<|endoftext|>


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

use dot;
use rustc::mir::repr::*;
use rustc::middle::ty;
use std::fmt::Debug;
use std::io::{self, Write};

/// Write a graphviz DOT graph for the given MIR.
pub fn write_mir_graphviz<W: Write>(mir: &Mir, w: &mut W) -> io::Result<()> {
    try!(writeln!(w, "digraph Mir {{"));

    // Global graph properties
    try!(writeln!(w, r#"    graph [fontname="monospace"];"#));
    try!(writeln!(w, r#"    node [fontname="monospace"];"#));
    try!(writeln!(w, r#"    edge [fontname="monospace"];"#));

    // Graph label
    try!(write_graph_label(mir, w));

    // Nodes
    for block in mir.all_basic_blocks() {
        try!(write_node(block, mir, w));
    }

    // Edges
    for source in mir.all_basic_blocks() {
        try!(write_edges(source, mir, w));
    }

    writeln!(w, "}}")
}

/// Write a graphviz DOT node for the given basic block.
fn write_node<W: Write>(block: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> {
    let data = mir.basic_block_data(block);

    // Start a new node with the label to follow, in one of DOT's pseudo-HTML tables.
    try!(write!(w, r#"    {} [shape="none", label=<"#, node(block)));
    try!(write!(w, r#"
"#));

    // Basic block number at the top.
    try!(write!(w, r#"
{}
"#, block.index()));

    // List of statements in the middle.
    if !data.statements.is_empty() {
        try!(write!(w, r#"
"#));
        for statement in &data.statements {
            try!(write!(w, "{}
", escape(statement)));
        }
        try!(write!(w, "
"));
    }

    // Terminator head at the bottom, not including the list of successor blocks. Those will be
    // displayed as labels on the edges between blocks.
    let mut terminator_head = String::new();
    data.terminator.fmt_head(&mut terminator_head).unwrap();
    try!(write!(w, r#"
{}
"#, dot::escape_html(&terminator_head)));

    // Close the table, node label, and the node itself.
    writeln!(w, "
>];")
}

/// Write graphviz DOT edges with labels between the given basic block and all of its successors.
fn write_edges<W: Write>(source: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> {
    let terminator = &mir.basic_block_data(source).terminator;
    let labels = terminator.fmt_successor_labels();

    for (&target, label) in terminator.successors().iter().zip(labels) {
        try!(writeln!(w, r#"    {} -> {} [label="{}"];"#, node(source), node(target), label));
    }

    Ok(())
}

/// Write the graphviz DOT label for the overall graph. This is essentially a block of text that
/// will appear below the graph, showing the type of the `fn` this MIR represents and the types of
/// all the variables and temporaries.
fn write_graph_label<W: Write>(mir: &Mir, w: &mut W) -> io::Result<()> {
    try!(write!(w, "    label=<fn("));

    // fn argument types.
    for (i, arg) in mir.arg_decls.iter().enumerate() {
        if i > 0 {
            try!(write!(w, ", "));
        }
        try!(write!(w, "{:?}: {}", Lvalue::Arg(i as u32), escape(&arg.ty)));
    }

    try!(write!(w, ") -> "));

    // fn return type.
    match mir.return_ty {
        ty::FnOutput::FnConverging(ty) => try!(write!(w, "{}", escape(ty))),
        ty::FnOutput::FnDiverging => try!(write!(w, "!")),
    }

    try!(write!(w, r#"
"#));

    // User variable types (including the user's name in a comment).
    for (i, var) in mir.var_decls.iter().enumerate() {
        try!(write!(w, "let "));
        if var.mutability == Mutability::Mut {
            try!(write!(w, "mut "));
        }
        try!(write!(w, r#"{:?}: {}; // {}
"#,
                    Lvalue::Var(i as u32), escape(&var.ty), var.name));
    }

    // Compiler-introduced temporary types.
    for (i, temp) in mir.temp_decls.iter().enumerate() {
        try!(write!(w, r#"let {:?}: {};
"#,
                    Lvalue::Temp(i as u32), escape(&temp.ty)));
    }

    writeln!(w, ">;")
}

fn node(block: BasicBlock) -> String {
    format!("bb{}", block.index())
}

fn escape<T: Debug>(t: &T) -> String {
    dot::escape_html(&format!("{:?}", t))
}
<commit_msg>Add 'mut' to temporary vars in MIR graphviz output.<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.

use dot;
use rustc::mir::repr::*;
use rustc::middle::ty;
use std::fmt::Debug;
use std::io::{self, Write};

/// Write a graphviz DOT graph for the given MIR.
pub fn write_mir_graphviz<W: Write>(mir: &Mir, w: &mut W) -> io::Result<()> {
    try!(writeln!(w, "digraph Mir {{"));

    // Global graph properties
    try!(writeln!(w, r#"    graph [fontname="monospace"];"#));
    try!(writeln!(w, r#"    node [fontname="monospace"];"#));
    try!(writeln!(w, r#"    edge [fontname="monospace"];"#));

    // Graph label
    try!(write_graph_label(mir, w));

    // Nodes
    for block in mir.all_basic_blocks() {
        try!(write_node(block, mir, w));
    }

    // Edges
    for source in mir.all_basic_blocks() {
        try!(write_edges(source, mir, w));
    }

    writeln!(w, "}}")
}

/// Write a graphviz DOT node for the given basic block.
fn write_node<W: Write>(block: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> {
    let data = mir.basic_block_data(block);

    // Start a new node with the label to follow, in one of DOT's pseudo-HTML tables.
    try!(write!(w, r#"    {} [shape="none", label=<"#, node(block)));
    try!(write!(w, r#"
"#));

    // Basic block number at the top.
    try!(write!(w, r#"
{}
"#, block.index()));

    // List of statements in the middle.
    if !data.statements.is_empty() {
        try!(write!(w, r#"
"#));
        for statement in &data.statements {
            try!(write!(w, "{}
", escape(statement)));
        }
        try!(write!(w, "
"));
    }

    // Terminator head at the bottom, not including the list of successor blocks. Those will be
    // displayed as labels on the edges between blocks.
    let mut terminator_head = String::new();
    data.terminator.fmt_head(&mut terminator_head).unwrap();
    try!(write!(w, r#"
{}
"#, dot::escape_html(&terminator_head)));

    // Close the table, node label, and the node itself.
    writeln!(w, "
>];")
}

/// Write graphviz DOT edges with labels between the given basic block and all of its successors.
fn write_edges<W: Write>(source: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> {
    let terminator = &mir.basic_block_data(source).terminator;
    let labels = terminator.fmt_successor_labels();

    for (&target, label) in terminator.successors().iter().zip(labels) {
        try!(writeln!(w, r#"    {} -> {} [label="{}"];"#, node(source), node(target), label));
    }

    Ok(())
}

/// Write the graphviz DOT label for the overall graph. This is essentially a block of text that
/// will appear below the graph, showing the type of the `fn` this MIR represents and the types of
/// all the variables and temporaries.
fn write_graph_label<W: Write>(mir: &Mir, w: &mut W) -> io::Result<()> {
    try!(write!(w, "    label=<fn("));

    // fn argument types.
    for (i, arg) in mir.arg_decls.iter().enumerate() {
        if i > 0 {
            try!(write!(w, ", "));
        }
        try!(write!(w, "{:?}: {}", Lvalue::Arg(i as u32), escape(&arg.ty)));
    }

    try!(write!(w, ") -> "));

    // fn return type.
    match mir.return_ty {
        ty::FnOutput::FnConverging(ty) => try!(write!(w, "{}", escape(ty))),
        ty::FnOutput::FnDiverging => try!(write!(w, "!")),
    }

    try!(write!(w, r#"
"#));

    // User variable types (including the user's name in a comment).
    for (i, var) in mir.var_decls.iter().enumerate() {
        try!(write!(w, "let "));
        if var.mutability == Mutability::Mut {
            try!(write!(w, "mut "));
        }
        try!(write!(w, r#"{:?}: {}; // {}
"#,
                    Lvalue::Var(i as u32), escape(&var.ty), var.name));
    }

    // Compiler-introduced temporary types.
    for (i, temp) in mir.temp_decls.iter().enumerate() {
        try!(write!(w, r#"let mut {:?}: {};
"#,
                    Lvalue::Temp(i as u32), escape(&temp.ty)));
    }

    writeln!(w, ">;")
}

fn node(block: BasicBlock) -> String {
    format!("bb{}", block.index())
}

fn escape<T: Debug>(t: &T) -> String {
    dot::escape_html(&format!("{:?}", t))
}
<|endoftext|>


<commit_before><commit_msg>Added logging and tracking of custom emojis<commit_after><|endoftext|>


<commit_before>use std::mem;
use std::slice;
use std::default::Default;

use color;
use color:: {
    Pixel,
    ColorType
};

/// An enumeration of Image Errors
#[deriving(Show, PartialEq, Eq)]
pub enum ImageError {
    ///The Image is not formatted properly
    FormatError,

    ///The Image's dimensions are either too small or too large
    DimensionError,

    ///The Decoder does not support this image format
    UnsupportedError,

    ///The Decoder does not support this color type
    UnsupportedColor,

    ///Not enough data was provided to the Decoder
    ///to decode the image
    NotEnoughData,

    ///An I/O Error occurred while decoding the image
    IoError,

    ///The end of the image has been reached
    ImageEnd
}

pub type ImageResult<T> = Result<T, ImageError>;

/// An enumeration of supported image formats.
/// Not all formats support both encoding and decoding.
#[deriving(PartialEq, Eq, Show)]
pub enum ImageFormat {
    /// An Image in PNG Format
    PNG,

    /// An Image in JPEG Format
    JPEG,

    /// An Image in GIF Format
    GIF,

    /// An Image in WEBP Format
    WEBP,

    /// An Image in PPM Format
    PPM
}

/// The trait that all decoders implement
pub trait ImageDecoder {
    ///Return a tuple containing the width and height of the image
    fn dimensions(&mut self) -> ImageResult<(u32, u32)>;

    ///Return the color type of the image e.g RGB(8) (8bit RGB)
    fn colortype(&mut self) -> ImageResult<ColorType>;

    ///Returns the length in bytes of one decoded row of the image
    fn row_len(&mut self) -> ImageResult<uint>;

    ///Read one row from the image into buf
    ///Returns the row index
    fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32>;

    ///Decode the entire image and return it as a Vector
    fn read_image(&mut self) -> ImageResult<Vec<u8>>;

    ///Decode a specific region of the image, represented by the rectangle
    ///starting from ```x``` and ```y``` and having ```length``` and ```width```
    fn load_rect(&mut self, x: u32, y: u32, length: u32, width: u32) -> ImageResult<Vec<u8>> {
        let (w, h) = try!(self.dimensions());

        if length > h || width > w || x > w || y > h {
            return Err(DimensionError)
        }

        let c = try!(self.colortype());

        let bpp = color::bits_per_pixel(c) / 8;

        let rowlen  = try!(self.row_len());

        let mut buf = Vec::from_elem(length as uint * width as uint * bpp, 0u8);
        let mut tmp = Vec::from_elem(rowlen, 0u8);

        loop {
            let row = try!(self.read_scanline(tmp.as_mut_slice()));

            if row - 1 == y {
                break
            }
        }

        for i in range(0, length as uint) {
            {
                let from = tmp.slice_from(x as uint * bpp)
                              .slice_to(width as uint * bpp);

                let to   = buf.mut_slice_from(i * width as uint * bpp)
                              .mut_slice_to(width as uint * bpp);

                slice::bytes::copy_memory(to, from);
            }

            let _ = try!(self.read_scanline(tmp.as_mut_slice()));
        }

        Ok(buf)
    }
}

/// Immutable pixel iterator
pub struct Pixels<'a, I> {
    image:  &'a I,
    x:      u32,
    y:      u32,
    width:  u32,
    height: u32
}

impl<'a, T: Primitive, P: Pixel<T>, I: GenericImage<P>> Iterator<(u32, u32, P)> for Pixels<'a, I> {
    fn next(&mut self) -> Option<(u32, u32, P)> {
        if self.x >= self.width {
            self.x =  0;
            self.y += 1;
        }

        if self.y >= self.height {
            None
        } else {
            let pixel = self.image.get_pixel(self.x, self.y);
            let p = (self.x, self.y, pixel);

            self.x += 1;

            Some(p)
        }
    }
}

/// Mutable pixel iterator
pub struct MutPixels<'a, I> {
    image:  &'a mut I,
    x:      u32,
    y:      u32,
    width:  u32,
    height: u32
}

impl<'a, T: Primitive, P: Pixel<T>, I: MutableRefImage<P>> Iterator<(u32, u32, &'a mut P)> for MutPixels<'a, I> {
    fn next(&mut self) -> Option<(u32, u32, &'a mut P)> {
        if self.x >= self.width {
            self.x =  0;
            self.y += 1;
        }

        if self.y >= self.height {
            None
        } else {
            let tmp = self.image.get_mut_pixel(self.x, self.y);

            //error: lifetime of `self` is too short to guarantee its contents
            //       can be safely reborrowed...
            let ptr = unsafe {
                mem::transmute(tmp)
            };

            let p = (self.x, self.y, ptr);

            self.x += 1;

            Some(p)
        }
    }
}

///A trait for manipulating images.
pub trait GenericImage<P> {
    ///The width and height of this image.
    fn dimensions(&self) -> (u32, u32);

    ///The bounding rectangle of this image.
    fn bounds(&self) -> (u32, u32, u32, u32);

    ///Return the pixel located at (x, y)
    fn get_pixel(&self, x: u32, y: u32) -> P;

    ///Put a pixel at location (x, y)
    fn put_pixel(&mut self, x: u32, y: u32, pixel: P);

    ///Return an Iterator over the pixels of this image.
    ///The iterator yields the coordinates of each pixel
    ///along with their value
    fn pixels(&self) -> Pixels<Self> {
        let (width, height) = self.dimensions();

        Pixels {
            image:  self,
            x:      0,
            y:      0,
            width:  width,
            height: height,
        }
    }
}

///A trait for images that allow providing mutable references to pixels.
pub trait MutableRefImage<P>: GenericImage<P> {
    ///Return a mutable reference to the pixel located at (x, y)
    fn get_mut_pixel(&mut self, x: u32, y: u32) -> &mut P;

    ///Return an Iterator over mutable pixels of this image.
    ///The iterator yields the coordinates of each pixel
    ///along with a mutable reference to them.
    fn mut_pixels(&mut self) -> MutPixels<Self> {
        let (width, height) = self.dimensions();

        MutPixels {
            image:  self,
            x:      0,
            y:      0,
            width:  width,
            height: height,
        }
    }
}

///An Image whose pixels are contained within a vector
#[deriving(Clone)]
pub struct ImageBuf<P> {
    pixels:  Vec<P>,
    width:   u32,
    height:  u32,
}

impl<T: Primitive, P: Pixel<T>> ImageBuf<P> {
    ///Construct a new ImageBuf with the specified width and height.
    pub fn new(width: u32, height: u32) -> ImageBuf<P> {
        let pixel: P = Default::default();
        let pixels = Vec::from_elem((width * height) as uint, pixel.clone());

        ImageBuf {
            pixels:  pixels,
            width:   width,
            height:  height,
        }
    }

    ///Construct a new ImageBuf by repeated application of the supplied function.
    ///The arguments to the function are the pixel's x and y coordinates.
    pub fn from_fn(width: u32, height: u32, f: | u32, u32 | -> P) -> ImageBuf<P> {
        let mut pixels: Vec<P> = Vec::with_capacity((width * height) as uint);

        for y in range(0, height) {
            for x in range(0, width) {
                pixels.insert((y * width + x) as uint, f(x, y));
            }
        }

        ImageBuf::from_pixels(pixels, width, height)
    }

    ///Construct a new ImageBuf from a vector of pixels.
    pub fn from_pixels(pixels: Vec<P>, width: u32, height: u32) -> ImageBuf<P> {
        ImageBuf {
            pixels: pixels,
            width:  width,
            height: height,
        }
    }

    ///Construct a new ImageBuf from a pixel.
    pub fn from_pixel(width: u32, height: u32, pixel: P) -> ImageBuf<P> {
        let buf = Vec::from_elem(width as uint * height as uint, pixel.clone());

        ImageBuf::from_pixels(buf, width, height)
    }

    ///Return an immutable reference to this image's pixel buffer
    pub fn pixelbuf(&self) -> & [P] {
        self.pixels.as_slice()
    }

    ///Return a mutable reference to this image's pixel buffer
    pub fn mut_pixelbuf(&mut self) -> &mut [P] {
        self.pixels.as_mut_slice()
    }
}

impl<T: Primitive, P: Pixel<T> + Clone + Copy> GenericImage<P> for ImageBuf<P> {
    fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    fn bounds(&self) -> (u32, u32, u32, u32) {
        (0, 0, self.width, self.height)
    }

    fn get_pixel(&self, x: u32, y: u32) -> P {
        let index  = y * self.width + x;

        self.pixels[index as uint]
    }

    fn put_pixel(&mut self, x: u32, y: u32, pixel: P) {
        let index  = y * self.width + x;
        let buf    = self.pixels.as_mut_slice();

        buf[index as uint] = pixel;
    }
}

impl<T: Primitive, P: Pixel<T> + Clone + Copy> MutableRefImage<P> for ImageBuf<P> {
    fn get_mut_pixel(&mut self, x: u32, y: u32) -> &mut P {
        let index = y * self.width + x;

        self.pixels.get_mut(index as uint)
    }
}

impl<T: Primitive, P: Pixel<T>> Index<(u32, u32), P> for ImageBuf<P> {
    fn index(&self, coords: &(u32, u32)) -> &P {
        let &(x, y) = coords;
        let index  = y * self.width + x;

        &self.pixels[index as uint]
    }
}

/// A View into another image
pub struct SubImage <'a, I> {
    image:   &'a mut I,
    xoffset: u32,
    yoffset: u32,
    xstride: u32,
    ystride: u32,
}

impl<'a, T: Primitive, P: Pixel<T>, I: GenericImage<P>> SubImage<'a, I> {
    ///Construct a new subimage
    pub fn new(image: &mut I, x: u32, y: u32, width: u32, height: u32) -> SubImage<I> {
        SubImage {
            image:   image,
            xoffset: x,
            yoffset: y,
            xstride: width,
            ystride: height,
        }
    }

    ///Return a mutable reference to the wrapped image.
    pub fn mut_inner(&mut self) -> &mut I {
        &mut (*self.image)
    }

    ///Change the coordinates of this subimage.
    pub fn change_bounds(&mut self, x: u32, y: u32, width: u32, height: u32) {
        self.xoffset = x;
        self.yoffset = y;
        self.xstride = width;
        self.ystride = height;
    }

    ///Convert this subimage to an ImageBuf
    pub fn to_image(&self) -> ImageBuf<P> {
        let p: P = Default::default();
        let mut out = ImageBuf::from_pixel(self.xstride, self.ystride, p.clone());

        for y in range(0, self.ystride) {
            for x in range(0, self.xstride) {
                let p = self.get_pixel(x, y);
                out.put_pixel(x, y, p);
            }
        }

        out
    }
}

impl<'a, T: Primitive, P: Pixel<T>, I: GenericImage<P>> GenericImage<P> for SubImage<'a, I> {
    fn dimensions(&self) -> (u32, u32) {
        (self.xstride, self.ystride)
    }

    fn bounds(&self) -> (u32, u32, u32, u32) {
        (self.xoffset, self.yoffset, self.xstride, self.ystride)
    }

    fn get_pixel(&self, x: u32, y: u32) -> P {
        self.image.get_pixel(x + self.xoffset, y + self.yoffset)
    }

    fn put_pixel(&mut self, x: u32, y: u32, pixel: P) {
        self.image.put_pixel(x + self.xoffset, y + self.yoffset, pixel)
    }
}

impl<'a, T: Primitive, P: Pixel<T>, I: MutableRefImage<P>> MutableRefImage<P> for SubImage<'a, I> {
    fn get_mut_pixel(&mut self, x: u32, y: u32) -> &mut P {
        self.image.get_mut_pixel(x + self.xoffset, y + self.yoffset)
    }
}
<commit_msg>Add ImageBuf::into_vec<commit_after>use std::mem;
use std::slice;
use std::default::Default;

use color;
use color:: {
    Pixel,
    ColorType
};

/// An enumeration of Image Errors
#[deriving(Show, PartialEq, Eq)]
pub enum ImageError {
    ///The Image is not formatted properly
    FormatError,

    ///The Image's dimensions are either too small or too large
    DimensionError,

    ///The Decoder does not support this image format
    UnsupportedError,

    ///The Decoder does not support this color type
    UnsupportedColor,

    ///Not enough data was provided to the Decoder
    ///to decode the image
    NotEnoughData,

    ///An I/O Error occurred while decoding the image
    IoError,

    ///The end of the image has been reached
    ImageEnd
}

pub type ImageResult<T> = Result<T, ImageError>;

/// An enumeration of supported image formats.
/// Not all formats support both encoding and decoding.
#[deriving(PartialEq, Eq, Show)]
pub enum ImageFormat {
    /// An Image in PNG Format
    PNG,

    /// An Image in JPEG Format
    JPEG,

    /// An Image in GIF Format
    GIF,

    /// An Image in WEBP Format
    WEBP,

    /// An Image in PPM Format
    PPM
}

/// The trait that all decoders implement
pub trait ImageDecoder {
    ///Return a tuple containing the width and height of the image
    fn dimensions(&mut self) -> ImageResult<(u32, u32)>;

    ///Return the color type of the image e.g RGB(8) (8bit RGB)
    fn colortype(&mut self) -> ImageResult<ColorType>;

    ///Returns the length in bytes of one decoded row of the image
    fn row_len(&mut self) -> ImageResult<uint>;

    ///Read one row from the image into buf
    ///Returns the row index
    fn read_scanline(&mut self, buf: &mut [u8]) -> ImageResult<u32>;

    ///Decode the entire image and return it as a Vector
    fn read_image(&mut self) -> ImageResult<Vec<u8>>;

    ///Decode a specific region of the image, represented by the rectangle
    ///starting from ```x``` and ```y``` and having ```length``` and ```width```
    fn load_rect(&mut self, x: u32, y: u32, length: u32, width: u32) -> ImageResult<Vec<u8>> {
        let (w, h) = try!(self.dimensions());

        if length > h || width > w || x > w || y > h {
            return Err(DimensionError)
        }

        let c = try!(self.colortype());

        let bpp = color::bits_per_pixel(c) / 8;

        let rowlen  = try!(self.row_len());

        let mut buf = Vec::from_elem(length as uint * width as uint * bpp, 0u8);
        let mut tmp = Vec::from_elem(rowlen, 0u8);

        loop {
            let row = try!(self.read_scanline(tmp.as_mut_slice()));

            if row - 1 == y {
                break
            }
        }

        for i in range(0, length as uint) {
            {
                let from = tmp.slice_from(x as uint * bpp)
                              .slice_to(width as uint * bpp);

                let to   = buf.mut_slice_from(i * width as uint * bpp)
                              .mut_slice_to(width as uint * bpp);

                slice::bytes::copy_memory(to, from);
            }

            let _ = try!(self.read_scanline(tmp.as_mut_slice()));
        }

        Ok(buf)
    }
}

/// Immutable pixel iterator
pub struct Pixels<'a, I> {
    image:  &'a I,
    x:      u32,
    y:      u32,
    width:  u32,
    height: u32
}

impl<'a, T: Primitive, P: Pixel<T>, I: GenericImage<P>> Iterator<(u32, u32, P)> for Pixels<'a, I> {
    fn next(&mut self) -> Option<(u32, u32, P)> {
        if self.x >= self.width {
            self.x =  0;
            self.y += 1;
        }

        if self.y >= self.height {
            None
        } else {
            let pixel = self.image.get_pixel(self.x, self.y);
            let p = (self.x, self.y, pixel);

            self.x += 1;

            Some(p)
        }
    }
}

/// Mutable pixel iterator
pub struct MutPixels<'a, I> {
    image:  &'a mut I,
    x:      u32,
    y:      u32,
    width:  u32,
    height: u32
}

impl<'a, T: Primitive, P: Pixel<T>, I: MutableRefImage<P>> Iterator<(u32, u32, &'a mut P)> for MutPixels<'a, I> {
    fn next(&mut self) -> Option<(u32, u32, &'a mut P)> {
        if self.x >= self.width {
            self.x =  0;
            self.y += 1;
        }

        if self.y >= self.height {
            None
        } else {
            let tmp = self.image.get_mut_pixel(self.x, self.y);

            //error: lifetime of `self` is too short to guarantee its contents
            //       can be safely reborrowed...
            let ptr = unsafe {
                mem::transmute(tmp)
            };

            let p = (self.x, self.y, ptr);

            self.x += 1;

            Some(p)
        }
    }
}

///A trait for manipulating images.
pub trait GenericImage<P> {
    ///The width and height of this image.
    fn dimensions(&self) -> (u32, u32);

    ///The bounding rectangle of this image.
    fn bounds(&self) -> (u32, u32, u32, u32);

    ///Return the pixel located at (x, y)
    fn get_pixel(&self, x: u32, y: u32) -> P;

    ///Put a pixel at location (x, y)
    fn put_pixel(&mut self, x: u32, y: u32, pixel: P);

    ///Return an Iterator over the pixels of this image.
    ///The iterator yields the coordinates of each pixel
    ///along with their value
    fn pixels(&self) -> Pixels<Self> {
        let (width, height) = self.dimensions();

        Pixels {
            image:  self,
            x:      0,
            y:      0,
            width:  width,
            height: height,
        }
    }
}

///A trait for images that allow providing mutable references to pixels.
pub trait MutableRefImage<P>: GenericImage<P> {
    ///Return a mutable reference to the pixel located at (x, y)
    fn get_mut_pixel(&mut self, x: u32, y: u32) -> &mut P;

    ///Return an Iterator over mutable pixels of this image.
    ///The iterator yields the coordinates of each pixel
    ///along with a mutable reference to them.
    fn mut_pixels(&mut self) -> MutPixels<Self> {
        let (width, height) = self.dimensions();

        MutPixels {
            image:  self,
            x:      0,
            y:      0,
            width:  width,
            height: height,
        }
    }
}

///An Image whose pixels are contained within a vector
#[deriving(Clone)]
pub struct ImageBuf<P> {
    pixels:  Vec<P>,
    width:   u32,
    height:  u32,
}

impl<T: Primitive, P: Pixel<T>> ImageBuf<P> {
    ///Construct a new ImageBuf with the specified width and height.
    pub fn new(width: u32, height: u32) -> ImageBuf<P> {
        let pixel: P = Default::default();
        let pixels = Vec::from_elem((width * height) as uint, pixel.clone());

        ImageBuf {
            pixels:  pixels,
            width:   width,
            height:  height,
        }
    }

    ///Construct a new ImageBuf by repeated application of the supplied function.
    ///The arguments to the function are the pixel's x and y coordinates.
    pub fn from_fn(width: u32, height: u32, f: | u32, u32 | -> P) -> ImageBuf<P> {
        let mut pixels: Vec<P> = Vec::with_capacity((width * height) as uint);

        for y in range(0, height) {
            for x in range(0, width) {
                pixels.insert((y * width + x) as uint, f(x, y));
            }
        }

        ImageBuf::from_pixels(pixels, width, height)
    }

    ///Construct a new ImageBuf from a vector of pixels.
    pub fn from_pixels(pixels: Vec<P>, width: u32, height: u32) -> ImageBuf<P> {
        ImageBuf {
            pixels: pixels,
            width:  width,
            height: height,
        }
    }

    ///Construct a new ImageBuf from a pixel.
    pub fn from_pixel(width: u32, height: u32, pixel: P) -> ImageBuf<P> {
        let buf = Vec::from_elem(width as uint * height as uint, pixel.clone());

        ImageBuf::from_pixels(buf, width, height)
    }

    ///Return an immutable reference to this image's pixel buffer
    pub fn pixelbuf(&self) -> & [P] {
        self.pixels.as_slice()
    }

    ///Return a mutable reference to this image's pixel buffer
    pub fn mut_pixelbuf(&mut self) -> &mut [P] {
        self.pixels.as_mut_slice()
    }

    ///Destroy this ImageBuf, returning the internal vector
    pub fn into_vec(self) -> Vec<P> {
        self.pixels
    }
}

impl<T: Primitive, P: Pixel<T> + Clone + Copy> GenericImage<P> for ImageBuf<P> {
    fn dimensions(&self) -> (u32, u32) {
        (self.width, self.height)
    }

    fn bounds(&self) -> (u32, u32, u32, u32) {
        (0, 0, self.width, self.height)
    }

    fn get_pixel(&self, x: u32, y: u32) -> P {
        let index  = y * self.width + x;

        self.pixels[index as uint]
    }

    fn put_pixel(&mut self, x: u32, y: u32, pixel: P) {
        let index  = y * self.width + x;
        let buf    = self.pixels.as_mut_slice();

        buf[index as uint] = pixel;
    }
}

impl<T: Primitive, P: Pixel<T> + Clone + Copy> MutableRefImage<P> for ImageBuf<P> {
    fn get_mut_pixel(&mut self, x: u32, y: u32) -> &mut P {
        let index = y * self.width + x;

        self.pixels.get_mut(index as uint)
    }
}

impl<T: Primitive, P: Pixel<T>> Index<(u32, u32), P> for ImageBuf<P> {
    fn index(&self, coords: &(u32, u32)) -> &P {
        let &(x, y) = coords;
        let index  = y * self.width + x;

        &self.pixels[index as uint]
    }
}

/// A View into another image
pub struct SubImage <'a, I> {
    image:   &'a mut I,
    xoffset: u32,
    yoffset: u32,
    xstride: u32,
    ystride: u32,
}

impl<'a, T: Primitive, P: Pixel<T>, I: GenericImage<P>> SubImage<'a, I> {
    ///Construct a new subimage
    pub fn new(image: &mut I, x: u32, y: u32, width: u32, height: u32) -> SubImage<I> {
        SubImage {
            image:   image,
            xoffset: x,
            yoffset: y,
            xstride: width,
            ystride: height,
        }
    }

    ///Return a mutable reference to the wrapped image.
    pub fn mut_inner(&mut self) -> &mut I {
        &mut (*self.image)
    }

    ///Change the coordinates of this subimage.
    pub fn change_bounds(&mut self, x: u32, y: u32, width: u32, height: u32) {
        self.xoffset = x;
        self.yoffset = y;
        self.xstride = width;
        self.ystride = height;
    }

    ///Convert this subimage to an ImageBuf
    pub fn to_image(&self) -> ImageBuf<P> {
        let p: P = Default::default();
        let mut out = ImageBuf::from_pixel(self.xstride, self.ystride, p.clone());

        for y in range(0, self.ystride) {
            for x in range(0, self.xstride) {
                let p = self.get_pixel(x, y);
                out.put_pixel(x, y, p);
            }
        }

        out
    }
}

impl<'a, T: Primitive, P: Pixel<T>, I: GenericImage<P>> GenericImage<P> for SubImage<'a, I> {
    fn dimensions(&self) -> (u32, u32) {
        (self.xstride, self.ystride)
    }

    fn bounds(&self) -> (u32, u32, u32, u32) {
        (self.xoffset, self.yoffset, self.xstride, self.ystride)
    }

    fn get_pixel(&self, x: u32, y: u32) -> P {
        self.image.get_pixel(x + self.xoffset, y + self.yoffset)
    }

    fn put_pixel(&mut self, x: u32, y: u32, pixel: P) {
        self.image.put_pixel(x + self.xoffset, y + self.yoffset, pixel)
    }
}

impl<'a, T: Primitive, P: Pixel<T>, I: MutableRefImage<P>> MutableRefImage<P> for SubImage<'a, I> {
    fn get_mut_pixel(&mut self, x: u32, y: u32) -> &mut P {
        self.image.get_mut_pixel(x + self.xoffset, y + self.yoffset)
    }
}
<|endoftext|>


<commit_before><commit_msg>Codeforces 740A<commit_after>use std::io::stdin;
use std::cmp::min;

fn main() {
    let mut input_line = String::new();
    stdin().read_line(&mut input_line);

    let mut input_iter = input_line.
        split_whitespace().
        map(|x| x.parse::<u64>().unwrap());

    let owned = input_iter.next().unwrap();
    let price1 = input_iter.next().unwrap();
    let price2 = input_iter.next().unwrap();
    let price3 = input_iter.next().unwrap();

    if owned % 4 == 0 {
        // Already meet criteria
        println!("0");
        return;
    }

    let purchase = 4 - owned % 4;
    let result = match purchase {
        1 => min(price1, min(price3 * 3, price2 + price3)),
        2 => min(price2, min(price1 * 2, price3 * 2)),
        3 => min(price3, min(price1 * 3, price2 + price1)),
        _ => u64::max_value()
    };

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


<commit_before><commit_msg>refactor: refactor `Param.process` method<commit_after><|endoftext|>


<commit_before><commit_msg>Add examples.<commit_after><|endoftext|>


<commit_before><commit_msg>First, not working, version of unit-test-server.rs<commit_after>extern crate libmodbus_rs;

use libmodbus_rs::{Modbus, ModbusServer};
use libmodbus_rs::errors::*; // for the `Result<T>` type
use std::env;

enum Backend {
    TCP,
    TCPPI,
    RTU,
}

fn run() -> Result<()> {
    let backend;
    let modbus: Modbus;

    let args: Vec<_> = env::args().collect();
    if args.len() > 1 {
        match args[1].to_lowercase().as_ref() {
            "tcp" => backend = Backend::TCP,
            "tcppi" => backend = Backend::TCPPI,
            "rtu" => backend = Backend::RTU,
            _ => {
                println!("Usage:\n  {} [tcp|tcppi|rtu] - Modbus server for unit testing\n\n", args[0]);
                std::process::exit(-1);
            }
        }
    } else {
        // By default
        backend = Backend::TCP;
    }

    let mut modbus = match backend {
        Backend::TCP => {
            use libmodbus_rs::ModbusTCP;

            Modbus::new_tcp("127.0.0.1", 1502)
        }
        Backend::TCPPI => {
            use libmodbus_rs::ModbusTCPPI;

            Modbus::new_tcp_pi("::0", "1502")
        }
        Backend::RTU => {
            use libmodbus_rs::ModbusRTU;

            Modbus::new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1)
        }
    }?;

    let header_lenght = modbus.get_header_length();
    println!("{:?}", header_lenght);

    let socket = modbus.get_socket();
    println!("{:?}", socket);

    Ok(())
}

fn main() {
    if let Err(ref err) = run() {
        println!("Error: {}", err);

        std::process::exit(1)
    }
}
<|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/.

// Handles invoking external binaries.
// This module assumes that, for a given machine, there is only one place
// where the desired executable might be installed. It expects the engine
// to identify that place at its initialization by invoking verify_binaries(),
// and to exit immediately if verify_binaries() return an error. If this
// protocol is followed then when any command is executed the unique absolute
// path of the binary for this machine will already have been identified.
// However stratisd may run for a while and it is possible for the binary
// to be caused to be uninstalled while stratisd is being run. Therefore,
// the existence of the file is checked before the command is invoked, and
// an explicit error is returned if the executable can not be found.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Command;

use uuid::Uuid;

use stratis::{StratisError, StratisResult};

/// Find the binary with the given name by looking in likely locations.
/// Return None if no binary was found.
/// Search an explicit list of directories rather than the user's PATH
/// environment variable. stratisd may be running when there is no PATH
/// variable set.
fn find_binary(name: &str) -> Option<PathBuf> {
    ["/usr/sbin", "/sbin", "/usr/bin", "/bin"]
        .iter()
        .map(|pre| [pre, name].iter().collect::<PathBuf>())
        .find(|path| path.exists())
}

// These are the external binaries that stratisd relies on.
// Any change in this list requires a corresponding change to BINARIES,
// and vice-versa.
const MKFS_XFS: &str = "mkfs.xfs";
const THIN_CHECK: &str = "thin_check";
const THIN_REPAIR: &str = "thin_repair";
const XFS_DB: &str = "xfs_db";
const XFS_GROWFS: &str = "xfs_growfs";

lazy_static! {
    static ref BINARIES: HashMap<String, Option<PathBuf>> = [
        (MKFS_XFS.to_string(), find_binary(MKFS_XFS)),
        (THIN_CHECK.to_string(), find_binary(THIN_CHECK)),
        (THIN_REPAIR.to_string(), find_binary(THIN_REPAIR)),
        (XFS_DB.to_string(), find_binary(XFS_DB)),
        (XFS_GROWFS.to_string(), find_binary(XFS_GROWFS)),
    ].iter()
        .cloned()
        .collect();
}

/// Verify that all binaries that the engine might invoke are available at some
/// path. Return an error if any are missing. Required to be called on engine
/// initialization.
pub fn verify_binaries() -> StratisResult<()> {
    match BINARIES.iter().find(|&(_, ref path)| path.is_none()) {
        None => Ok(()),
        Some((ref name, _)) => Err(StratisError::Error(format!(
            "Unable to find absolute path for \"{}\"",
            name
        ))),
    }
}

/// Invoke the specified command. Return an error if invoking the command
/// fails or if the command itself fails.
fn execute_cmd(cmd: &mut Command) -> StratisResult<()> {
    match cmd.output() {
        Err(err) => Err(StratisError::Error(format!(
            "Failed to execute command {:?}, err: {:?}",
            cmd, err
        ))),
        Ok(result) => {
            if result.status.success() {
                Ok(())
            } else {
                let std_out_txt = String::from_utf8_lossy(&result.stdout);
                let std_err_txt = String::from_utf8_lossy(&result.stderr);
                let err_msg = format!(
                    "Command failed: cmd: {:?}, stdout: {} stderr: {}",
                    cmd, std_out_txt, std_err_txt
                );
                Err(StratisError::Error(err_msg))
            }
        }
    }
}

/// Get an absolute path for the executable with the given name.
/// Precondition: verify_binaries() has already been invoked.
fn get_executable(name: &str) -> &Path {
    BINARIES
        .get(name)
        .expect("name arguments are all constants defined with BINARIES, lookup can not fail")
        .as_ref()
        .expect("verify_binaries() was previously called and returned no error")
}

/// Create a filesystem on devnode.
pub fn create_fs(devnode: &Path, uuid: Uuid) -> StratisResult<()> {
    execute_cmd(
        Command::new(get_executable(MKFS_XFS).as_os_str())
            .arg("-f")
            .arg("-q")
            .arg(&devnode)
            .arg("-m")
            .arg(format!("uuid={}", uuid)),
    )
}

/// Use the xfs_growfs command to expand a filesystem mounted at the given
/// mount point.
pub fn xfs_growfs(mount_point: &Path) -> StratisResult<()> {
    execute_cmd(
        Command::new(get_executable(XFS_GROWFS).as_os_str())
            .arg(mount_point)
            .arg("-d"),
    )
}

/// Set a new UUID for filesystem on the devnode.
pub fn set_uuid(devnode: &Path, uuid: Uuid) -> StratisResult<()> {
    execute_cmd(
        Command::new(get_executable(XFS_DB).as_os_str())
            .arg(format!("-c uuid {}", uuid))
            .arg(&devnode),
    )
}

/// Call thin_check on a thinpool
pub fn thin_check(devnode: &Path) -> StratisResult<()> {
    execute_cmd(
        Command::new(get_executable(THIN_CHECK).as_os_str())
            .arg("-q")
            .arg(devnode),
    )
}

/// Call thin_repair on a thinpool
pub fn thin_repair(meta_dev: &Path, new_meta_dev: &Path) -> StratisResult<()> {
    execute_cmd(
        Command::new(get_executable(THIN_REPAIR).as_os_str())
            .arg("-i")
            .arg(meta_dev)
            .arg("-o")
            .arg(new_meta_dev),
    )
}

/// Call udevadm settle
#[cfg(test)]
pub fn udev_settle() -> StratisResult<()> {
    execute_cmd(Command::new("udevadm").arg("settle"))
}

#[cfg(test)]
pub fn create_ext3_fs(devnode: &Path) -> StratisResult<()> {
    execute_cmd(Command::new("mkfs.ext3").arg(&devnode))
}
<commit_msg>Use "-x", expert flag<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/.

// Handles invoking external binaries.
// This module assumes that, for a given machine, there is only one place
// where the desired executable might be installed. It expects the engine
// to identify that place at its initialization by invoking verify_binaries(),
// and to exit immediately if verify_binaries() return an error. If this
// protocol is followed then when any command is executed the unique absolute
// path of the binary for this machine will already have been identified.
// However stratisd may run for a while and it is possible for the binary
// to be caused to be uninstalled while stratisd is being run. Therefore,
// the existence of the file is checked before the command is invoked, and
// an explicit error is returned if the executable can not be found.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Command;

use uuid::Uuid;

use stratis::{StratisError, StratisResult};

/// Find the binary with the given name by looking in likely locations.
/// Return None if no binary was found.
/// Search an explicit list of directories rather than the user's PATH
/// environment variable. stratisd may be running when there is no PATH
/// variable set.
fn find_binary(name: &str) -> Option<PathBuf> {
    ["/usr/sbin", "/sbin", "/usr/bin", "/bin"]
        .iter()
        .map(|pre| [pre, name].iter().collect::<PathBuf>())
        .find(|path| path.exists())
}

// These are the external binaries that stratisd relies on.
// Any change in this list requires a corresponding change to BINARIES,
// and vice-versa.
const MKFS_XFS: &str = "mkfs.xfs";
const THIN_CHECK: &str = "thin_check";
const THIN_REPAIR: &str = "thin_repair";
const XFS_DB: &str = "xfs_db";
const XFS_GROWFS: &str = "xfs_growfs";

lazy_static! {
    static ref BINARIES: HashMap<String, Option<PathBuf>> = [
        (MKFS_XFS.to_string(), find_binary(MKFS_XFS)),
        (THIN_CHECK.to_string(), find_binary(THIN_CHECK)),
        (THIN_REPAIR.to_string(), find_binary(THIN_REPAIR)),
        (XFS_DB.to_string(), find_binary(XFS_DB)),
        (XFS_GROWFS.to_string(), find_binary(XFS_GROWFS)),
    ].iter()
        .cloned()
        .collect();
}

/// Verify that all binaries that the engine might invoke are available at some
/// path. Return an error if any are missing. Required to be called on engine
/// initialization.
pub fn verify_binaries() -> StratisResult<()> {
    match BINARIES.iter().find(|&(_, ref path)| path.is_none()) {
        None => Ok(()),
        Some((ref name, _)) => Err(StratisError::Error(format!(
            "Unable to find absolute path for \"{}\"",
            name
        ))),
    }
}

/// Invoke the specified command. Return an error if invoking the command
/// fails or if the command itself fails.
fn execute_cmd(cmd: &mut Command) -> StratisResult<()> {
    match cmd.output() {
        Err(err) => Err(StratisError::Error(format!(
            "Failed to execute command {:?}, err: {:?}",
            cmd, err
        ))),
        Ok(result) => {
            if result.status.success() {
                Ok(())
            } else {
                let std_out_txt = String::from_utf8_lossy(&result.stdout);
                let std_err_txt = String::from_utf8_lossy(&result.stderr);
                let err_msg = format!(
                    "Command failed: cmd: {:?}, stdout: {} stderr: {}",
                    cmd, std_out_txt, std_err_txt
                );
                Err(StratisError::Error(err_msg))
            }
        }
    }
}

/// Get an absolute path for the executable with the given name.
/// Precondition: verify_binaries() has already been invoked.
fn get_executable(name: &str) -> &Path {
    BINARIES
        .get(name)
        .expect("name arguments are all constants defined with BINARIES, lookup can not fail")
        .as_ref()
        .expect("verify_binaries() was previously called and returned no error")
}

/// Create a filesystem on devnode.
pub fn create_fs(devnode: &Path, uuid: Uuid) -> StratisResult<()> {
    execute_cmd(
        Command::new(get_executable(MKFS_XFS).as_os_str())
            .arg("-f")
            .arg("-q")
            .arg(&devnode)
            .arg("-m")
            .arg(format!("uuid={}", uuid)),
    )
}

/// Use the xfs_growfs command to expand a filesystem mounted at the given
/// mount point.
pub fn xfs_growfs(mount_point: &Path) -> StratisResult<()> {
    execute_cmd(
        Command::new(get_executable(XFS_GROWFS).as_os_str())
            .arg(mount_point)
            .arg("-d"),
    )
}

/// Set a new UUID for filesystem on the devnode.
pub fn set_uuid(devnode: &Path, uuid: Uuid) -> StratisResult<()> {
    execute_cmd(
        Command::new(get_executable(XFS_DB).as_os_str())
            .arg("-x")
            .arg(format!("-c uuid {}", uuid))
            .arg(&devnode),
    )
}

/// Call thin_check on a thinpool
pub fn thin_check(devnode: &Path) -> StratisResult<()> {
    execute_cmd(
        Command::new(get_executable(THIN_CHECK).as_os_str())
            .arg("-q")
            .arg(devnode),
    )
}

/// Call thin_repair on a thinpool
pub fn thin_repair(meta_dev: &Path, new_meta_dev: &Path) -> StratisResult<()> {
    execute_cmd(
        Command::new(get_executable(THIN_REPAIR).as_os_str())
            .arg("-i")
            .arg(meta_dev)
            .arg("-o")
            .arg(new_meta_dev),
    )
}

/// Call udevadm settle
#[cfg(test)]
pub fn udev_settle() -> StratisResult<()> {
    execute_cmd(Command::new("udevadm").arg("settle"))
}

#[cfg(test)]
pub fn create_ext3_fs(devnode: &Path) -> StratisResult<()> {
    execute_cmd(Command::new("mkfs.ext3").arg(&devnode))
}
<|endoftext|>


<commit_before><commit_msg>07 - if else<commit_after>fn main() {
    let n = 5i;

    if n < 0 {
        print!("{} is negative", n);
    } else if n > 0 {
        print!("{} is positive", n);
    } else {
        print!("{} is zero", n);
    }

    let big_n =
        if n < 10 && n > -10 {
            println!(", and is a small number, increase ten-fold");

            // This expression returns an `int`
            10 * n
        } else {
            println!(", and is a big number, reduce by two");

            // This expression must return an `int` as well
            n / 2
            // Try suppressing this expression with a semicolon
        };
    // Don't forget to put a semicolon here! All the `let` bindings need it

    println!("{} -> {}", n, big_n);
}
<|endoftext|>


<commit_before><commit_msg>Add problem #103<commit_after>#[link(name = "prob0103", vers = "0.0")];
#[crate_type = "lib"];

extern mod extra;
extern mod common;

use std::{uint, vec};
use extra::priority_queue::PriorityQueue;
use common::problem::Problem;

pub static problem: Problem<'static> = Problem {
    id: 103,
    answer: "20313839404245",
    solver: solve
};

struct SSSElem {
    avg: float,
    sss: ~[uint],
    sums: ~[uint]
}

impl Ord for SSSElem {
    #[inline(always)]
    fn lt(&self, other: &SSSElem) -> bool { self.avg >  other.avg }
    #[inline(always)]
    fn le(&self, other: &SSSElem) -> bool { self.avg >= other.avg }
    #[inline(always)]
    fn gt(&self, other: &SSSElem) -> bool { self.avg <  other.avg }
    #[inline(always)]
    fn ge(&self, other: &SSSElem) -> bool { self.avg <= other.avg }
}

impl SSSElem {
    #[inline]
    pub fn new_pair(a: uint, b: uint) -> SSSElem {
        assert!(a < b);
        return SSSElem {
            avg: ((a + b) as float) / 2f,
            sss: ~[a, b],
            sums: ~[0, a, b, a + b]
        };
    }

    pub fn add_num(&self, n: uint) -> Option<SSSElem> {
        let mut i = 0;
        let mut j = 0;
        let len = self.sums.len();
        let mut sums = vec::with_capacity(len * 2);

        while i < len {
            assert!(j <= i);

            match self.sums[i].cmp(&(self.sums[j] + n)) {
                Equal => { return None; }
                Less => {
                    sums.push(self.sums[i]);
                    i += 1;
                }
                Greater => {
                    sums.push(self.sums[j] + n);
                    j += 1;
                }
            }
        }

        while j < len {
            sums.push(self.sums[j] + n);
            j += 1;
        }

        let avg = (self.avg * (len as float) + n as float) / ((len as float) + 1f);
        let sss = self.sss + [n];
        return Some(SSSElem { avg: avg, sss: sss, sums: sums });
    }

    // 6: [a, b, c, d, e, f] => (a + b + c + d) - (e + f) - 1
    // 5: [a, b, c, d, e]    => (a + b + c)     - e       - 1
    // 4: [a, b, c, d]       => (a + b + c)     - d       - 1
    // 3: [a, b, c]          => (a + b)                   - 1
    // 2: [a, b]             => (a + b)                   - 1
    #[inline]
    pub fn max_addable(&self) -> uint {
        let len   = self.sss.len();
        let add_len = len / 2 + 1;
        let sub_len = len / 2 - 1;

        let add = self.sss.slice(0, add_len).iter().fold(0, |a, &b| a + b);
        let sub = self.sss.slice(len - sub_len, len).iter().fold(0, |a, &b| a + b);
        return add - sub - 1;
    }

    #[inline(always)]
    pub fn each_next(&self, f: &fn(SSSElem) -> bool) -> bool {
        if self.sss.len() == 2 {
            let (a, b) = (self.sss[0], self.sss[1]);
            if !f(SSSElem::new_pair(a, b + 1)) { return false; }
            if a == b - 1 && !f(SSSElem::new_pair(a + 1, b + 1)) { return false; }
        }

        for uint::range(self.sss.last() + 1, self.max_addable() + 1) |n| {
            match self.add_num(n) {
                Some(x) => {
                    if !f(x) { return false; }
                }
                None => {}
            }
        }
        return true;
    }
}

#[inline(always)]
pub fn each_sss(f: &fn(&SSSElem) -> bool) -> bool {
    let mut pq = PriorityQueue::new();
    pq.push(SSSElem::new_pair(1, 2));
    while !pq.is_empty() {
        let e = pq.pop();
        if !f(&e) { return false; }
        for e.each_next |next| {
            pq.push(next);
        }
    }
    return true;
}

// (a, b) => SSS if a > b
// (a, b, c) => SSS if a > b > c && a + b > c
// (a, b, c, d) +> SSS if a > b > c > d && a + b > d &&
pub fn solve() -> ~str {
    for each_sss |&sss| {
        if sss.sss.len() == 7 {
            return sss.sss.map(|&n| n.to_str()).concat();
        }
    }
    fail!();
}
<|endoftext|>