<commit_before>//! RAII guards for hazards.

use std::ops;
use std::sync::atomic;
use {hazard, local};

/// A RAII guard protecting from garbage collection.
///
/// This "guards" the held pointer against garbage collection. First when all guards of said
/// pointer is gone (the data is unreachable), it can be collected.
// TODO: Remove this `'static` bound.
#[must_use = "You are getting a `conc::Guard<T>` without using it, which means it is potentially \
              unnecessary overhead. Consider replacing the method with something that doesn't \
              return a guard."]
#[derive(Debug)]
pub struct Guard<T: 'static> {
    /// The inner hazard.
    hazard: hazard::Writer,
    /// The pointer to the protected object.
    pointer: &'static T,
}

impl<T> Guard<T> {
    /// (Failably) create a new guard.
    ///
    /// This has all the same restrictions and properties as `Guard::new()` (please read its
    /// documentation before using), with the exception of being failable.
    ///
    /// This means that the closure can return and error and abort the creation of the guard.
    pub fn try_new<F, E>(ptr: F) -> Result<Guard<T>, E>
    where F: FnOnce() -> Result<&'static T, E> {
        // Get a hazard in blocked state.
        let hazard = local::get_hazard();

        // This fence is necessary for ensuring that `hazard` does not get reordered to after `ptr`
        // has run.
        // TODO: Is this fence even necessary?
        atomic::fence(atomic::Ordering::SeqCst);

        // Right here, any garbage collection is blocked, due to the hazard above. This ensures
        // that between the potential read in `ptr` and it being protected by the hazard, there
        // will be no premature free.

        // Evaluate the pointer through the closure.
        match ptr() {
            Ok(ptr) => {
                // Now that we have the pointer, we can protect it by the hazard, unblocking a pending
                // garbage collection if it exists.
                hazard.set(hazard::State::Protect(ptr as *const T as *const u8));

                Ok(Guard {
                    hazard: hazard,
                    pointer: ptr,
                })
            },
            Err(err) => {
                // Set the hazard to free to ensure that the hazard doesn't remain blocking.
                hazard.set(hazard::State::Free);

                Err(err)
            }
        }
    }

    /// Create a new guard.
    ///
    /// Because it must ensure that no garbage collection happens until the pointer is read, it
    /// takes a closure, which is evaluated to the pointer the guard will hold. During the span of
    /// this closure, garbage collection is ensured to not happen, making it safe to read from an
    /// atomic pointer without risking the ABA problem.
    ///
    /// # Important!
    ///
    /// It is very important that this closure does not contain anything which might cause a
    /// garbage collection, as garbage collecting inside this closure will cause the current thread
    /// to be blocked infinitely (because the hazard is blocked) and stop all other threads from
    /// collecting garbage, leading to memory leaks in those.
    pub fn new<F>(ptr: F) -> Guard<T>
    where F: FnOnce() -> &'static T {
        Guard::try_new::<_, ()>(|| Ok(ptr())).unwrap()
    }

    /// Conditionally create a guard.
    ///
    /// This acts `try_new`, but with `Option` instead of `Result`.
    pub fn maybe_new<F>(ptr: F) -> Option<Guard<T>>
    where F: FnOnce() -> Option<&'static T> {
        Guard::try_new(|| ptr().ok_or(())).ok()
    }

    /// Map the pointer to another.
    ///
    /// This allows one to map a pointer to a pointer e.g. to an object referenced by the old. It
    /// is very convenient for creating APIs without the need for creating a wrapper type.
    // TODO: Is this sound?
    pub fn map<U, F>(self, f: F) -> Guard<U>
    where F: FnOnce(&T) -> &U {
        Guard {
            hazard: self.hazard,
            pointer: f(self.pointer),
        }
    }

    /// Get the raw pointer of this guard.
    pub fn as_raw(&self) -> *const T {
        self.pointer
    }
}

impl<T> ops::Deref for Guard<T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.pointer
    }
}

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

    #[test]
    #[should_panic]
    fn panic_during_guard_creation() {
        let _ = Guard::new(|| -> &'static u8 { panic!() });
    }
}
<commit_msg>Don't expect `T: ?Sized` for `conc::Guard<T>`.<commit_after>//! RAII guards for hazards.

use std::ops;
use std::sync::atomic;
use {hazard, local};

/// A RAII guard protecting from garbage collection.
///
/// This "guards" the held pointer against garbage collection. First when all guards of said
/// pointer is gone (the data is unreachable), it can be collected.
// TODO: Remove this `'static` bound.
#[must_use = "You are getting a `conc::Guard<T>` without using it, which means it is potentially \
              unnecessary overhead. Consider replacing the method with something that doesn't \
              return a guard."]
#[derive(Debug)]
pub struct Guard<T: 'static + ?Sized> {
    /// The inner hazard.
    hazard: hazard::Writer,
    /// The pointer to the protected object.
    pointer: &'static T,
}

impl<T: ?Sized> Guard<T> {
    /// (Failably) create a new guard.
    ///
    /// This has all the same restrictions and properties as `Guard::new()` (please read its
    /// documentation before using), with the exception of being failable.
    ///
    /// This means that the closure can return and error and abort the creation of the guard.
    pub fn try_new<F, E>(ptr: F) -> Result<Guard<T>, E>
    where F: FnOnce() -> Result<&'static T, E> {
        // Get a hazard in blocked state.
        let hazard = local::get_hazard();

        // This fence is necessary for ensuring that `hazard` does not get reordered to after `ptr`
        // has run.
        // TODO: Is this fence even necessary?
        atomic::fence(atomic::Ordering::SeqCst);

        // Right here, any garbage collection is blocked, due to the hazard above. This ensures
        // that between the potential read in `ptr` and it being protected by the hazard, there
        // will be no premature free.

        // Evaluate the pointer through the closure.
        match ptr() {
            Ok(ptr) => {
                // Now that we have the pointer, we can protect it by the hazard, unblocking a pending
                // garbage collection if it exists.
                hazard.set(hazard::State::Protect(ptr as *const T as *const u8));

                Ok(Guard {
                    hazard: hazard,
                    pointer: ptr,
                })
            },
            Err(err) => {
                // Set the hazard to free to ensure that the hazard doesn't remain blocking.
                hazard.set(hazard::State::Free);

                Err(err)
            }
        }
    }

    /// Create a new guard.
    ///
    /// Because it must ensure that no garbage collection happens until the pointer is read, it
    /// takes a closure, which is evaluated to the pointer the guard will hold. During the span of
    /// this closure, garbage collection is ensured to not happen, making it safe to read from an
    /// atomic pointer without risking the ABA problem.
    ///
    /// # Important!
    ///
    /// It is very important that this closure does not contain anything which might cause a
    /// garbage collection, as garbage collecting inside this closure will cause the current thread
    /// to be blocked infinitely (because the hazard is blocked) and stop all other threads from
    /// collecting garbage, leading to memory leaks in those.
    pub fn new<F>(ptr: F) -> Guard<T>
    where F: FnOnce() -> &'static T {
        Guard::try_new::<_, ()>(|| Ok(ptr())).unwrap()
    }

    /// Conditionally create a guard.
    ///
    /// This acts `try_new`, but with `Option` instead of `Result`.
    pub fn maybe_new<F>(ptr: F) -> Option<Guard<T>>
    where F: FnOnce() -> Option<&'static T> {
        Guard::try_new(|| ptr().ok_or(())).ok()
    }

    /// Map the pointer to another.
    ///
    /// This allows one to map a pointer to a pointer e.g. to an object referenced by the old. It
    /// is very convenient for creating APIs without the need for creating a wrapper type.
    // TODO: Is this sound?
    pub fn map<U, F>(self, f: F) -> Guard<U>
    where F: FnOnce(&T) -> &U {
        Guard {
            hazard: self.hazard,
            pointer: f(self.pointer),
        }
    }

    /// Get the raw pointer of this guard.
    pub fn as_raw(&self) -> *const T {
        self.pointer
    }
}

impl<T> ops::Deref for Guard<T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.pointer
    }
}

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

    #[test]
    #[should_panic]
    fn panic_during_guard_creation() {
        let _ = Guard::new(|| -> &'static u8 { panic!() });
    }

    #[test]
    fn nested_guard_creation() {
        for i in 0..100 {
            Guard::new(|| {
                Guard::new(|| "blah");
                "blah"
            });
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Sample test file<commit_after>#[test]
fn this_tests_code() {
  fail!("This test has failed because of <%= @reason %>");
}
<|endoftext|>


<commit_before><commit_msg>Add a test suite<commit_after>#[macro_use] extern crate enum_primitive as ep;

enum_from_primitive! {
enum Unused {
    A = 17,
    B = 42
}
}

enum_from_primitive! {
#[derive(Debug, PartialEq)]
enum Empty {
}
}

#[test]
fn empty() {
    use ep::FromPrimitive;
    assert_eq!(Empty::from_i32(91), None);
}

enum_from_primitive! {
#[derive(Debug, PartialEq)]
enum One {
    A = 17
}
}

#[test]
fn one() {
    use ep::FromPrimitive;
    assert_eq!(One::from_isize(17), Some(One::A));
    assert_eq!(One::from_isize(91), None);
    assert_eq!(One::from_i8(17), Some(One::A));
    assert_eq!(One::from_i8(91), None);
    assert_eq!(One::from_i16(17), Some(One::A));
    assert_eq!(One::from_i16(91), None);
    assert_eq!(One::from_i32(17), Some(One::A));
    assert_eq!(One::from_i32(91), None);
    assert_eq!(One::from_i64(17), Some(One::A));
    assert_eq!(One::from_i64(91), None);
    assert_eq!(One::from_usize(17), Some(One::A));
    assert_eq!(One::from_usize(91), None);
    assert_eq!(One::from_u8(17), Some(One::A));
    assert_eq!(One::from_u8(91), None);
    assert_eq!(One::from_u16(17), Some(One::A));
    assert_eq!(One::from_u16(91), None);
    assert_eq!(One::from_u32(17), Some(One::A));
    assert_eq!(One::from_u32(91), None);
    assert_eq!(One::from_u64(17), Some(One::A));
    assert_eq!(One::from_u64(91), None);
}

enum_from_primitive! {
#[derive(Debug, PartialEq)]
enum OneComma {
    A = 17,
}
}

#[test]
fn one_comma() {
    use ep::FromPrimitive;
    assert_eq!(OneComma::from_i32(17), Some(OneComma::A));
    assert_eq!(OneComma::from_i32(91), None);
}

enum_from_primitive! {
#[derive(Debug, PartialEq)]
enum Two {
    A = 17,
    B = 42
}
}

#[test]
fn two() {
    use ep::FromPrimitive;
    assert_eq!(PubTwo::from_i32(17), Some(PubTwo::A));
    assert_eq!(PubTwo::from_i32(42), Some(PubTwo::B));
    assert_eq!(PubTwo::from_i32(91), None);
}

enum_from_primitive! {
#[derive(Debug, PartialEq)]
enum TwoComma {
    A = 17,
    B = 42,
}
}

#[test]
fn two_comma() {
    use ep::FromPrimitive;
    assert_eq!(TwoComma::from_i32(17), Some(TwoComma::A));
    assert_eq!(TwoComma::from_i32(42), Some(TwoComma::B));
    assert_eq!(TwoComma::from_i32(91), None);
}

enum_from_primitive! {
#[derive(Debug, PartialEq)]
pub enum PubEmpty {
}
}

#[test]
fn pub_empty() {
    use ep::FromPrimitive;
    assert_eq!(PubEmpty::from_i32(91), None);
}

enum_from_primitive! {
#[derive(Debug, PartialEq)]
pub enum PubOne {
    A = 17
}
}

#[test]
fn pub_one() {
    use ep::FromPrimitive;
    assert_eq!(PubOne::from_i32(17), Some(PubOne::A));
    assert_eq!(PubOne::from_i32(91), None);
}

enum_from_primitive! {
#[derive(Debug, PartialEq)]
pub enum PubOneComma {
    A = 17,
}
}

#[test]
fn pub_one_comma() {
    use ep::FromPrimitive;
    assert_eq!(PubOneComma::from_i32(17), Some(PubOneComma::A));
    assert_eq!(PubOneComma::from_i32(91), None);
}

enum_from_primitive! {
#[derive(Debug, PartialEq)]
pub enum PubTwo {
    A = 17,
    B = 42
}
}

#[test]
fn pub_two() {
    use ep::FromPrimitive;
    assert_eq!(PubTwo::from_i32(17), Some(PubTwo::A));
    assert_eq!(PubTwo::from_i32(42), Some(PubTwo::B));
    assert_eq!(PubTwo::from_i32(91), None);
}

enum_from_primitive! {
#[derive(Debug, PartialEq)]
pub enum PubTwoComma {
    A = 17,
    B = 42,
}
}

#[test]
fn pub_two_comma() {
    use ep::FromPrimitive;
    assert_eq!(PubTwoComma::from_i32(17), Some(PubTwoComma::A));
    assert_eq!(PubTwoComma::from_i32(42), Some(PubTwoComma::B));
    assert_eq!(PubTwoComma::from_i32(91), None);
}

enum_from_primitive! {
#[derive(Debug, PartialEq)]
enum Negative {
    A = -17
}
}

#[test]
fn negative() {
    use ep::FromPrimitive;
    assert_eq!(Negative::from_isize(-17), Some(Negative::A));
    assert_eq!(Negative::from_isize(-91), None);
    assert_eq!(Negative::from_i8(-17), Some(Negative::A));
    assert_eq!(Negative::from_i8(-91), None);
    assert_eq!(Negative::from_i16(-17), Some(Negative::A));
    assert_eq!(Negative::from_i16(-91), None);
    assert_eq!(Negative::from_i32(-17), Some(Negative::A));
    assert_eq!(Negative::from_i32(-91), None);
    assert_eq!(Negative::from_i64(-17), Some(Negative::A));
    assert_eq!(Negative::from_i64(-91), None);
    assert_eq!(Negative::from_usize(!16), Some(Negative::A));
    assert_eq!(Negative::from_usize(!90), None);
    assert_eq!(Negative::from_u8(!16), None);
    assert_eq!(Negative::from_u8(!90), None);
    assert_eq!(Negative::from_u16(!16), None);
    assert_eq!(Negative::from_u16(!90), None);
    assert_eq!(Negative::from_u32(!16), None);
    assert_eq!(Negative::from_u32(!90), None);
    assert_eq!(Negative::from_u64(!16), Some(Negative::A));
    assert_eq!(Negative::from_u64(!90), None);
}

#[test]
fn in_local_mod() {
    mod local_mod {
        enum_from_primitive! {
        #[derive(Debug, PartialEq)]
        pub enum InLocalMod {
            A = 17,
            B = 42,
        }
        }
    }

    use ep::FromPrimitive;
    assert_eq!(local_mod::InLocalMod::from_i32(17), Some(local_mod::InLocalMod::A));
    assert_eq!(local_mod::InLocalMod::from_i32(42), Some(local_mod::InLocalMod::B));
    assert_eq!(local_mod::InLocalMod::from_i32(91), None);
}

enum_from_primitive! {
#[derive(Debug, PartialEq)]
#[doc = "Documented"]
pub enum Documented {
    A = 17
}
}

#[test]
fn documented() {
    use ep::FromPrimitive;
    assert_eq!(Documented::from_i32(17), Some(Documented::A));
    assert_eq!(Documented::from_i32(91), None);
}
<|endoftext|>


<commit_before><commit_msg>Add a compile-fail test for #3255<commit_after>fn main() {
    let x = some(unsafe::exclusive(false));
    match x {
        some(copy z) => { //~ ERROR copying a noncopyable value
            do z.with |b| { assert !*b; }
        }
        none => fail
    }
}
<|endoftext|>


<commit_before><commit_msg>Update stats command to be 1-indexed<commit_after><|endoftext|>


<commit_before><commit_msg>Words:<commit_after>use std::boxed::FnBox;
use std::sync::{Arc, Mutex};
use std::thread::{JoinHandle, spawn};
use std::any::{Any};
use std::panic::{recover, RecoverSafe};

use world_state;

pub type ExampleResult = Result<(), Box<Any + Send>>;
pub type ExampleBlock = Box<FnBox(Arc<Mutex<world_state::WorldState>>) -> ExampleResult + Send + 'static>;

pub struct Example<T: Fn() + Send + RecoverSafe + 'static> {
    _description: String,
    block: ExampleBlock,
}

impl <T> Example<T> {
    pub fn new<T>(description: String, block: ExampleBlock, definition_block: T) -> Example<T> where T: Fn() + Send + RecoverSafe + 'static {
        Example {
            _description: description,
            block: block,
            definition_block: definition_block,
        }
    }

    pub fn spawn(self, state: Arc<Mutex<world_state::WorldState>>) -> JoinHandle<ExampleResult> {
        spawn(move || self.run(state))
    }

    fn run(self, state: Arc<Mutex<world_state::WorldState>>) -> ExampleResult {
        let block = self.block;
        block(state)
    }
}
<|endoftext|>


<commit_before><commit_msg>Add define_network_struct and define_packet macro with tests.<commit_after><|endoftext|>


<commit_before><commit_msg>terra<commit_after><|endoftext|>


<commit_before><commit_msg>Move voice code around a lot<commit_after><|endoftext|>


<commit_before><commit_msg>regression and unit tests for Adapton engine<commit_after>#[macro_use]
extern crate adapton;

mod engine {
    #[test]
    fn force_cell () {
        use adapton::engine::*;
        manage::init_dcg();
        let a : u32      = 1234;
        let b : Art<u32> = cell(name_of_usize(0), a);
        let c : u32      = force(&b);
        assert_eq!(a, c);
    }

    #[test]
    fn force_map_cell () {
        use adapton::engine::*;
        manage::init_dcg();
        let a : u32      = 1234;
        let b : Art<u32> = cell(name_of_usize(0), a);
        let c : u64      = force_map(&b, |x| x as u64);
        assert_eq!(a as u64, c);
    }

    #[test]
    fn force_map_cell_project () {
        use adapton::engine::*;
        manage::init_dcg();
        let pair = (1234 as usize, 5678 as usize);
        let c    = cell(name_of_usize(0), pair);
        let fst  = force_map(&c, |x| x.0);
        let snd  = force_map(&c, |x| x.1);
        assert_eq!(pair.0, fst);
        assert_eq!(pair.1, snd);
    }

    #[test]
    fn force_map_prunes_dirty_traversal () {
        // Test whether using force_map correctly prunes dirtying;
        // this test traces the engine, counts the number of dirtying
        // steps, and ensures that this count is zero, as expected.
        use std::rc::Rc;
        use adapton::macros::*;
        use adapton::engine::*;
        manage::init_dcg();
        reflect::dcg_reflect_begin();
        let pair = (1234 as usize, 5678 as usize);
        let c    = cell(name_of_usize(0), pair);
        let t = thunk![ name_of_usize(1) =>> {
            let fst = force_map(&c, |x| x.0);
            fst + 100
        }];
        assert_eq!(force(&t), 1334);
        let pair = (1234 as usize, 8765 as usize);
        let _    = cell(name_of_usize(0), pair);
        assert_eq!(force(&t), 1334);
        let traces = reflect::dcg_reflect_end();
        let counts = reflect::trace::trace_count(&traces, Some(1));
        assert_eq!(counts.dirty.0, 0);
        assert_eq!(counts.dirty.1, 0);
    }

    #[test]
    fn force_map_thunk () {
        use std::rc::Rc;
        use adapton::macros::*;
        use adapton::engine::*;
        manage::init_dcg();
        let a : u32      = 1234;
        let b : Art<u32> = thunk![ name_of_usize(0) =>> a];
        let c : u64      = force_map(&b, |x| x as u64);
        assert_eq!(a as u64, c);
    }
}
<|endoftext|>


<commit_before><commit_msg>Looping and breaking<commit_after><|endoftext|>


<commit_before>/// An example of sending data to a prometheus server with a local webserver
extern crate iron;
extern crate metrics;
extern crate histogram;

use iron::prelude::*;
use iron::status;
use metrics::metrics::counter::*;
use metrics::metrics::gauge::*;
use metrics::metrics::meter::*;
use metrics::registry::{Registry, StdRegistry};
use metrics::reporter::prometheus::PrometheusReporter;
use std::sync::Arc;
use std::collections::HashMap;
use histogram::*;

fn main() {
    println!("WebServer Starting");
    extern crate hyper;
    let m = StdMeter::new();
    m.mark(100);

    let mut c: StdCounter = StdCounter::new();
    c.inc();

    let mut g: StdGauge = StdGauge { value: 0f64 };
    g.set(1.2);

    let mut hc = HistogramConfig::new();
    hc.max_value(100).precision(1);
    let mut h = Histogram::configured(hc).unwrap();

    h.record(1, 1);

    let mut labels = HashMap::new();
    labels.insert(String::from("test"), String::from("test"));
    let mut r = StdRegistry::new_with_labels(labels);
    // r.insert("meter1", m);
   // r.insert("counter1", c);
   // r.insert("gauge1", g);
   // r.insert("histogram", h);

    let arc_registry = Arc::new(r);
    let reporter = PrometheusReporter::new(arc_registry.clone(),
                        "test",
                        "0.0.0.0:9090",
                        "asd.asdf");
    reporter.start();
    Iron::new(|_: &mut Request| {
        Ok(Response::with(status::NotFound))
    }).http("0.0.0.0:3000").unwrap();
    println!("WebServer Running");

}
<commit_msg>Rustfmt<commit_after>/// An example of sending data to a prometheus server with a local webserver
extern crate iron;
extern crate metrics;
extern crate histogram;

use iron::prelude::*;
use iron::status;
use metrics::metrics::counter::*;
use metrics::metrics::gauge::*;
use metrics::metrics::meter::*;
use metrics::registry::{Registry, StdRegistry};
use metrics::reporter::prometheus::PrometheusReporter;
use std::sync::Arc;
use std::collections::HashMap;
use histogram::*;

fn main() {
    println!("WebServer Starting");
    extern crate hyper;
    let m = StdMeter::new();
    m.mark(100);

    let mut c: StdCounter = StdCounter::new();
    c.inc();

    let mut g: StdGauge = StdGauge { value: 0f64 };
    g.set(1.2);

    let mut hc = HistogramConfig::new();
    hc.max_value(100).precision(1);
    let mut h = Histogram::configured(hc).unwrap();

    h.record(1, 1);

    let mut labels = HashMap::new();
    labels.insert(String::from("test"), String::from("test"));
    let mut r = StdRegistry::new_with_labels(labels);
    // r.insert("meter1", m);
    // r.insert("counter1", c);
    // r.insert("gauge1", g);
    // r.insert("histogram", h);

    let arc_registry = Arc::new(r);
    let reporter =
        PrometheusReporter::new(arc_registry.clone(), "test", "0.0.0.0:9090", "asd.asdf");
    reporter.start();
    Iron::new(|_: &mut Request| Ok(Response::with(status::NotFound)))
        .http("0.0.0.0:3000")
        .unwrap();
    println!("WebServer Running");

}
<|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 text::glyph::CharIndex;

#[deriving(PartialEq)]
pub enum CompressionMode {
    CompressNone,
    CompressWhitespace,
    CompressWhitespaceNewline,
    DiscardNewline
}

// ported from Gecko's nsTextFrameUtils::TransformText.
//
// High level TODOs:
//
// * Issue #113: consider incoming text state (arabic, etc)
//               and propogate outgoing text state (dual of above)
//
// * Issue #114: record skipped and kept chars for mapping original to new text
//
// * Untracked: various edge cases for bidi, CJK, etc.
pub fn transform_text(text: &str, mode: CompressionMode,
                      incoming_whitespace: bool,
                      new_line_pos: &mut Vec<CharIndex>) -> (String, bool) {
    let mut out_str = String::new();
    let out_whitespace = match mode {
        CompressNone | DiscardNewline => {
            let mut new_line_index = CharIndex(0);
            for ch in text.chars() {
                if is_discardable_char(ch, mode) {
                    // TODO: record skipped char
                } else {
                    // TODO: record kept char
                    if ch == '\t' {
                        // TODO: set "has tab" flag
                    } else if ch == '\n' {
                        // Save new-line's position for line-break
                        // This value is relative(not absolute)
                        new_line_pos.push(new_line_index);
                        new_line_index = CharIndex(0);
                    }

                    if ch != '\n' {
                        new_line_index = new_line_index + CharIndex(1);
                    }
                    out_str.push_char(ch);
                }
            }
            text.len() > 0 && is_in_whitespace(text.char_at_reverse(0), mode)
        },

        CompressWhitespace | CompressWhitespaceNewline => {
            let mut in_whitespace: bool = incoming_whitespace;
            for ch in text.chars() {
                // TODO: discard newlines between CJK chars
                let mut next_in_whitespace: bool = is_in_whitespace(ch, mode);

                if !next_in_whitespace {
                    if is_always_discardable_char(ch) {
                        // revert whitespace setting, since this char was discarded
                        next_in_whitespace = in_whitespace;
                        // TODO: record skipped char
                    } else {
                        // TODO: record kept char
                        out_str.push_char(ch);
                    }
                } else { /* next_in_whitespace; possibly add a space char */
                    if in_whitespace {
                        // TODO: record skipped char
                    } else {
                        // TODO: record kept char
                        out_str.push_char(' ');
                    }
                }
                // save whitespace context for next char
                in_whitespace = next_in_whitespace;
            } /* /for str::each_char */
            in_whitespace
        }
    };

    return (out_str, out_whitespace);

    fn is_in_whitespace(ch: char, mode: CompressionMode) -> bool {
        match (ch, mode) {
            (' ', _)  => true,
            ('\t', _) => true,
            ('\n', CompressWhitespaceNewline) => true,
            (_, _)    => false
        }
    }

    fn is_discardable_char(ch: char, mode: CompressionMode) -> bool {
        if is_always_discardable_char(ch) {
            return true;
        }
        match mode {
            DiscardNewline | CompressWhitespaceNewline => ch == '\n',
            _ => false
        }
    }

    fn is_always_discardable_char(_ch: char) -> bool {
        // TODO: check for bidi control chars, soft hyphens.
        false
    }
}

pub fn float_to_fixed(before: int, f: f64) -> i32 {
    (1i32 << before as uint) * (f as i32)
}

pub fn fixed_to_float(before: int, f: i32) -> f64 {
    f as f64 * 1.0f64 / ((1i32 << before as uint) as f64)
}

pub fn fixed_to_rounded_int(before: int, f: i32) -> int {
    let half = 1i32 << (before-1) as uint;
    if f > 0i32 {
        ((half + f) >> before as uint) as int
    } else {
       -((half - f) >> before as uint) as int
    }
}

/* Generate a 32-bit TrueType tag from its 4 characters */
pub fn true_type_tag(a: char, b: char, c: char, d: char) -> u32 {
    let a = a as u32;
    let b = b as u32;
    let c = c as u32;
    let d = d as u32;
    (a << 24 | b << 16 | c << 8 | d) as u32
}

#[test]
fn test_true_type_tag() {
    assert_eq!(true_type_tag('c', 'm', 'a', 'p'), 0x_63_6D_61_70_u32);
}

#[test]
fn test_transform_compress_none() {
    let test_strs = vec!(
        "  foo bar",
        "foo bar  ",
        "foo\n bar",
        "foo \nbar",
        "  foo  bar  \nbaz",
        "foo bar baz",
        "foobarbaz\n\n"
    );
    let mode = CompressNone;

    for test in test_strs.iter() {
        let mut new_line_pos = vec!();
        let (trimmed_str, _out) = transform_text(*test, mode, true, &mut new_line_pos);
        assert_eq!(trimmed_str.as_slice(), *test)
    }
}

#[test]
fn test_transform_discard_newline() {
    let test_strs = vec!(
        "  foo bar",
        "foo bar  ",
        "foo\n bar",
        "foo \nbar",
        "  foo  bar  \nbaz",
        "foo bar baz",
        "foobarbaz\n\n"
    );

    let oracle_strs = vec!(
        "  foo bar",
        "foo bar  ",
        "foo bar",
        "foo bar",
        "  foo  bar  baz",
        "foo bar baz",
        "foobarbaz"
    );

    assert_eq!(test_strs.len(), oracle_strs.len());
    let mode = DiscardNewline;

    for (test, oracle) in test_strs.iter().zip(oracle_strs.iter()) {
        let mut new_line_pos = vec!();
        let (trimmed_str, _out) = transform_text(*test, mode, true, &mut new_line_pos);
        assert_eq!(trimmed_str.as_slice(), *oracle)
    }
}

/* FIXME: Fix and re-enable
#[test]
fn test_transform_compress_whitespace() {
    let  test_strs : ~[String] = ~["  foo bar".to_string(),
                                 "foo bar  ".to_string(),
                                 "foo\n bar".to_string(),
                                 "foo \nbar".to_string(),
                                 "  foo  bar  \nbaz".to_string(),
                                 "foo bar baz".to_string(),
                                 "foobarbaz\n\n".to_string()];

    let oracle_strs : ~[String] = ~[" foo bar".to_string(),
                                 "foo bar ".to_string(),
                                 "foo\n bar".to_string(),
                                 "foo \nbar".to_string(),
                                 " foo bar \nbaz".to_string(),
                                 "foo bar baz".to_string(),
                                 "foobarbaz\n\n".to_string()];

    assert_eq!(test_strs.len(), oracle_strs.len());
    let mode = CompressWhitespace;

    for i in range(0, test_strs.len()) {
        let mut new_line_pos = ~[];
        let (trimmed_str, _out) = transform_text(test_strs[i], mode, true, &mut new_line_pos);
        assert_eq!(&trimmed_str, &oracle_strs[i])
    }
}

#[test]
fn test_transform_compress_whitespace_newline() {
    let  test_strs : ~[String] = ~["  foo bar".to_string(),
                                 "foo bar  ".to_string(),
                                 "foo\n bar".to_string(),
                                 "foo \nbar".to_string(),
                                 "  foo  bar  \nbaz".to_string(),
                                 "foo bar baz".to_string(),
                                 "foobarbaz\n\n".to_string()];

    let oracle_strs : ~[String] = ~["foo bar".to_string(),
                                 "foo bar ".to_string(),
                                 "foo bar".to_string(),
                                 "foo bar".to_string(),
                                 " foo bar baz".to_string(),
                                 "foo bar baz".to_string(),
                                 "foobarbaz ".to_string()];

    assert_eq!(test_strs.len(), oracle_strs.len());
    let mode = CompressWhitespaceNewline;

    for i in range(0, test_strs.len()) {
        let mut new_line_pos = ~[];
        let (trimmed_str, _out) = transform_text(test_strs[i], mode, true, &mut new_line_pos);
        assert_eq!(&trimmed_str, &oracle_strs[i])
    }
}
*/

#[test]
fn test_transform_compress_whitespace_newline_no_incoming() {
    let test_strs = vec!(
        "  foo bar",
        "\nfoo bar",
        "foo bar  ",
        "foo\n bar",
        "foo \nbar",
        "  foo  bar  \nbaz",
        "foo bar baz",
        "foobarbaz\n\n"
    );

    let oracle_strs = vec!(
        " foo bar",
        " foo bar",
        "foo bar ",
        "foo bar",
        "foo bar",
        " foo bar baz",
        "foo bar baz",
        "foobarbaz "
    );

    assert_eq!(test_strs.len(), oracle_strs.len());
    let mode = CompressWhitespaceNewline;

    for (test, oracle) in test_strs.iter().zip(oracle_strs.iter()) {
        let mut new_line_pos = vec!();
        let (trimmed_str, _out) = transform_text(*test, mode, false, &mut new_line_pos);
        assert_eq!(trimmed_str.as_slice(), *oracle)
    }
}
<commit_msg>auto merge of #3549 : pcwalton/servo/fix-float-to-fixed, r=zwarich<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 text::glyph::CharIndex;

#[deriving(PartialEq)]
pub enum CompressionMode {
    CompressNone,
    CompressWhitespace,
    CompressWhitespaceNewline,
    DiscardNewline
}

// ported from Gecko's nsTextFrameUtils::TransformText.
//
// High level TODOs:
//
// * Issue #113: consider incoming text state (arabic, etc)
//               and propogate outgoing text state (dual of above)
//
// * Issue #114: record skipped and kept chars for mapping original to new text
//
// * Untracked: various edge cases for bidi, CJK, etc.
pub fn transform_text(text: &str, mode: CompressionMode,
                      incoming_whitespace: bool,
                      new_line_pos: &mut Vec<CharIndex>) -> (String, bool) {
    let mut out_str = String::new();
    let out_whitespace = match mode {
        CompressNone | DiscardNewline => {
            let mut new_line_index = CharIndex(0);
            for ch in text.chars() {
                if is_discardable_char(ch, mode) {
                    // TODO: record skipped char
                } else {
                    // TODO: record kept char
                    if ch == '\t' {
                        // TODO: set "has tab" flag
                    } else if ch == '\n' {
                        // Save new-line's position for line-break
                        // This value is relative(not absolute)
                        new_line_pos.push(new_line_index);
                        new_line_index = CharIndex(0);
                    }

                    if ch != '\n' {
                        new_line_index = new_line_index + CharIndex(1);
                    }
                    out_str.push_char(ch);
                }
            }
            text.len() > 0 && is_in_whitespace(text.char_at_reverse(0), mode)
        },

        CompressWhitespace | CompressWhitespaceNewline => {
            let mut in_whitespace: bool = incoming_whitespace;
            for ch in text.chars() {
                // TODO: discard newlines between CJK chars
                let mut next_in_whitespace: bool = is_in_whitespace(ch, mode);

                if !next_in_whitespace {
                    if is_always_discardable_char(ch) {
                        // revert whitespace setting, since this char was discarded
                        next_in_whitespace = in_whitespace;
                        // TODO: record skipped char
                    } else {
                        // TODO: record kept char
                        out_str.push_char(ch);
                    }
                } else { /* next_in_whitespace; possibly add a space char */
                    if in_whitespace {
                        // TODO: record skipped char
                    } else {
                        // TODO: record kept char
                        out_str.push_char(' ');
                    }
                }
                // save whitespace context for next char
                in_whitespace = next_in_whitespace;
            } /* /for str::each_char */
            in_whitespace
        }
    };

    return (out_str, out_whitespace);

    fn is_in_whitespace(ch: char, mode: CompressionMode) -> bool {
        match (ch, mode) {
            (' ', _)  => true,
            ('\t', _) => true,
            ('\n', CompressWhitespaceNewline) => true,
            (_, _)    => false
        }
    }

    fn is_discardable_char(ch: char, mode: CompressionMode) -> bool {
        if is_always_discardable_char(ch) {
            return true;
        }
        match mode {
            DiscardNewline | CompressWhitespaceNewline => ch == '\n',
            _ => false
        }
    }

    fn is_always_discardable_char(_ch: char) -> bool {
        // TODO: check for bidi control chars, soft hyphens.
        false
    }
}

pub fn float_to_fixed(before: int, f: f64) -> i32 {
    ((1i32 << before as uint) as f64 * f) as i32
}

pub fn fixed_to_float(before: int, f: i32) -> f64 {
    f as f64 * 1.0f64 / ((1i32 << before as uint) as f64)
}

pub fn fixed_to_rounded_int(before: int, f: i32) -> int {
    let half = 1i32 << (before-1) as uint;
    if f > 0i32 {
        ((half + f) >> before as uint) as int
    } else {
       -((half - f) >> before as uint) as int
    }
}

/* Generate a 32-bit TrueType tag from its 4 characters */
pub fn true_type_tag(a: char, b: char, c: char, d: char) -> u32 {
    let a = a as u32;
    let b = b as u32;
    let c = c as u32;
    let d = d as u32;
    (a << 24 | b << 16 | c << 8 | d) as u32
}

#[test]
fn test_true_type_tag() {
    assert_eq!(true_type_tag('c', 'm', 'a', 'p'), 0x_63_6D_61_70_u32);
}

#[test]
fn test_transform_compress_none() {
    let test_strs = vec!(
        "  foo bar",
        "foo bar  ",
        "foo\n bar",
        "foo \nbar",
        "  foo  bar  \nbaz",
        "foo bar baz",
        "foobarbaz\n\n"
    );
    let mode = CompressNone;

    for test in test_strs.iter() {
        let mut new_line_pos = vec!();
        let (trimmed_str, _out) = transform_text(*test, mode, true, &mut new_line_pos);
        assert_eq!(trimmed_str.as_slice(), *test)
    }
}

#[test]
fn test_transform_discard_newline() {
    let test_strs = vec!(
        "  foo bar",
        "foo bar  ",
        "foo\n bar",
        "foo \nbar",
        "  foo  bar  \nbaz",
        "foo bar baz",
        "foobarbaz\n\n"
    );

    let oracle_strs = vec!(
        "  foo bar",
        "foo bar  ",
        "foo bar",
        "foo bar",
        "  foo  bar  baz",
        "foo bar baz",
        "foobarbaz"
    );

    assert_eq!(test_strs.len(), oracle_strs.len());
    let mode = DiscardNewline;

    for (test, oracle) in test_strs.iter().zip(oracle_strs.iter()) {
        let mut new_line_pos = vec!();
        let (trimmed_str, _out) = transform_text(*test, mode, true, &mut new_line_pos);
        assert_eq!(trimmed_str.as_slice(), *oracle)
    }
}

/* FIXME: Fix and re-enable
#[test]
fn test_transform_compress_whitespace() {
    let  test_strs : ~[String] = ~["  foo bar".to_string(),
                                 "foo bar  ".to_string(),
                                 "foo\n bar".to_string(),
                                 "foo \nbar".to_string(),
                                 "  foo  bar  \nbaz".to_string(),
                                 "foo bar baz".to_string(),
                                 "foobarbaz\n\n".to_string()];

    let oracle_strs : ~[String] = ~[" foo bar".to_string(),
                                 "foo bar ".to_string(),
                                 "foo\n bar".to_string(),
                                 "foo \nbar".to_string(),
                                 " foo bar \nbaz".to_string(),
                                 "foo bar baz".to_string(),
                                 "foobarbaz\n\n".to_string()];

    assert_eq!(test_strs.len(), oracle_strs.len());
    let mode = CompressWhitespace;

    for i in range(0, test_strs.len()) {
        let mut new_line_pos = ~[];
        let (trimmed_str, _out) = transform_text(test_strs[i], mode, true, &mut new_line_pos);
        assert_eq!(&trimmed_str, &oracle_strs[i])
    }
}

#[test]
fn test_transform_compress_whitespace_newline() {
    let  test_strs : ~[String] = ~["  foo bar".to_string(),
                                 "foo bar  ".to_string(),
                                 "foo\n bar".to_string(),
                                 "foo \nbar".to_string(),
                                 "  foo  bar  \nbaz".to_string(),
                                 "foo bar baz".to_string(),
                                 "foobarbaz\n\n".to_string()];

    let oracle_strs : ~[String] = ~["foo bar".to_string(),
                                 "foo bar ".to_string(),
                                 "foo bar".to_string(),
                                 "foo bar".to_string(),
                                 " foo bar baz".to_string(),
                                 "foo bar baz".to_string(),
                                 "foobarbaz ".to_string()];

    assert_eq!(test_strs.len(), oracle_strs.len());
    let mode = CompressWhitespaceNewline;

    for i in range(0, test_strs.len()) {
        let mut new_line_pos = ~[];
        let (trimmed_str, _out) = transform_text(test_strs[i], mode, true, &mut new_line_pos);
        assert_eq!(&trimmed_str, &oracle_strs[i])
    }
}
*/

#[test]
fn test_transform_compress_whitespace_newline_no_incoming() {
    let test_strs = vec!(
        "  foo bar",
        "\nfoo bar",
        "foo bar  ",
        "foo\n bar",
        "foo \nbar",
        "  foo  bar  \nbaz",
        "foo bar baz",
        "foobarbaz\n\n"
    );

    let oracle_strs = vec!(
        " foo bar",
        " foo bar",
        "foo bar ",
        "foo bar",
        "foo bar",
        " foo bar baz",
        "foo bar baz",
        "foobarbaz "
    );

    assert_eq!(test_strs.len(), oracle_strs.len());
    let mode = CompressWhitespaceNewline;

    for (test, oracle) in test_strs.iter().zip(oracle_strs.iter()) {
        let mut new_line_pos = vec!();
        let (trimmed_str, _out) = transform_text(*test, mode, false, &mut new_line_pos);
        assert_eq!(trimmed_str.as_slice(), *oracle)
    }
}
<|endoftext|>


<commit_before>import ctypes::*;

#[abi = "cdecl"]
#[link_name = ""]
native mod libc {
    fn read(fd: fd_t, buf: *u8, count: size_t) -> ssize_t;
    fn write(fd: fd_t, buf: *u8, count: size_t) -> ssize_t;
    fn fread(buf: *u8, size: size_t, n: size_t, f: libc::FILE) -> size_t;
    fn fwrite(buf: *u8, size: size_t, n: size_t, f: libc::FILE) -> size_t;
    #[link_name = "_open"]
    fn open(s: str::sbuf, flags: c_int, mode: unsigned) -> c_int;
    #[link_name = "_close"]
    fn close(fd: fd_t) -> c_int;
    type FILE;
    fn fopen(path: str::sbuf, mode: str::sbuf) -> FILE;
    fn _fdopen(fd: fd_t, mode: str::sbuf) -> FILE;
    fn fclose(f: FILE);
    fn fflush(f: FILE) -> c_int;
    fn fileno(f: FILE) -> fd_t;
    fn fgetc(f: FILE) -> c_int;
    fn ungetc(c: c_int, f: FILE);
    fn feof(f: FILE) -> c_int;
    fn fseek(f: FILE, offset: long, whence: c_int) -> c_int;
    fn ftell(f: FILE) -> long;
    fn _pipe(fds: *mutable fd_t, size: unsigned, mode: c_int) -> c_int;
}

mod libc_constants {
    const O_RDONLY: c_int    = 0i32;
    const O_WRONLY: c_int    = 1i32;
    const O_RDWR: c_int      = 2i32;
    const O_APPEND: c_int    = 8i32;
    const O_CREAT: c_int     = 256i32;
    const O_EXCL: c_int      = 1024i32;
    const O_TRUNC: c_int     = 512i32;
    const O_TEXT: c_int      = 16384i32;
    const O_BINARY: c_int    = 32768i32;
    const O_NOINHERIT: c_int = 128i32;
    const S_IRUSR: unsigned  = 256u32; // really _S_IREAD  in win32
    const S_IWUSR: unsigned  = 128u32; // really _S_IWRITE in win32
}

type DWORD = u32;
type HMODULE = uint;
type LPTSTR = str::sbuf;
type LPCTSTR = str::sbuf;

#[abi = "stdcall"]
native mod kernel32 {
    type LPSECURITY_ATTRIBUTES;
    fn GetEnvironmentVariableA(n: str::sbuf, v: str::sbuf, nsize: uint) ->
       uint;
    fn SetEnvironmentVariableA(n: str::sbuf, v: str::sbuf) -> int;
    fn GetModuleFileNameA(hModule: HMODULE,
                          lpFilename: LPTSTR,
                          nSize: DWORD) -> DWORD;
    fn CreateDirectoryA(lpPathName: LPCTSTR,
                        lpSecurityAttributes: LPSECURITY_ATTRIBUTES) -> bool;
    fn RemoveDirectoryA(lpPathName: LPCTSTR) -> bool;
    fn SetCurrentDirectoryA(lpPathName: LPCTSTR) -> bool;
}

// FIXME turn into constants
fn exec_suffix() -> str { ret ".exe"; }
fn target_os() -> str { ret "win32"; }

fn dylib_filename(base: str) -> str { ret base + ".dll"; }

fn pipe() -> {in: fd_t, out: fd_t} {
    // Windows pipes work subtly differently than unix pipes, and their
    // inheritance has to be handled in a different way that I don't fully
    // understand. Here we explicitly make the pipe non-inheritable,
    // which means to pass it to a subprocess they need to be duplicated
    // first, as in rust_run_program.
    let fds = {mutable in: 0i32, mutable out: 0i32};
    let res =
        os::libc::_pipe(ptr::mut_addr_of(fds.in), 1024u32,
                        libc_constants::O_BINARY |
                            libc_constants::O_NOINHERIT);
    assert (res == 0i32);
    assert (fds.in != -1i32 && fds.in != 0i32);
    assert (fds.out != -1i32 && fds.in != 0i32);
    ret {in: fds.in, out: fds.out};
}

fn fd_FILE(fd: fd_t) -> libc::FILE {
    ret str::as_buf("r", {|modebuf| libc::_fdopen(fd, modebuf) });
}

fn close(fd: fd_t) -> c_int {
    libc::close(fd)
}

fn fclose(file: libc::FILE) {
    libc::fclose(file)
}

fn fsync_fd(fd: fd_t, level: io::fsync::level) -> c_int {
    // FIXME (1253)
}

#[abi = "cdecl"]
native mod rustrt {
    fn rust_process_wait(handle: c_int) -> c_int;
    fn rust_getcwd() -> str;
}

fn waitpid(pid: pid_t) -> i32 { ret rustrt::rust_process_wait(pid); }

fn getcwd() -> str { ret rustrt::rust_getcwd(); }

fn get_exe_path() -> option::t<fs::path> {
    // FIXME: This doesn't handle the case where the buffer is too small
    let bufsize = 1023u;
    let path = str::unsafe_from_bytes(vec::init_elt(0u8, bufsize));
    ret str::as_buf(path, { |path_buf|
        if kernel32::GetModuleFileNameA(0u, path_buf,
                                        bufsize as u32) != 0u32 {
            option::some(fs::dirname(path) + fs::path_sep())
        } else {
            option::none
        }
    });
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<commit_msg>stdlib: Actually write the word 'fail' instead of just thinking it<commit_after>import ctypes::*;

#[abi = "cdecl"]
#[link_name = ""]
native mod libc {
    fn read(fd: fd_t, buf: *u8, count: size_t) -> ssize_t;
    fn write(fd: fd_t, buf: *u8, count: size_t) -> ssize_t;
    fn fread(buf: *u8, size: size_t, n: size_t, f: libc::FILE) -> size_t;
    fn fwrite(buf: *u8, size: size_t, n: size_t, f: libc::FILE) -> size_t;
    #[link_name = "_open"]
    fn open(s: str::sbuf, flags: c_int, mode: unsigned) -> c_int;
    #[link_name = "_close"]
    fn close(fd: fd_t) -> c_int;
    type FILE;
    fn fopen(path: str::sbuf, mode: str::sbuf) -> FILE;
    fn _fdopen(fd: fd_t, mode: str::sbuf) -> FILE;
    fn fclose(f: FILE);
    fn fflush(f: FILE) -> c_int;
    fn fileno(f: FILE) -> fd_t;
    fn fgetc(f: FILE) -> c_int;
    fn ungetc(c: c_int, f: FILE);
    fn feof(f: FILE) -> c_int;
    fn fseek(f: FILE, offset: long, whence: c_int) -> c_int;
    fn ftell(f: FILE) -> long;
    fn _pipe(fds: *mutable fd_t, size: unsigned, mode: c_int) -> c_int;
}

mod libc_constants {
    const O_RDONLY: c_int    = 0i32;
    const O_WRONLY: c_int    = 1i32;
    const O_RDWR: c_int      = 2i32;
    const O_APPEND: c_int    = 8i32;
    const O_CREAT: c_int     = 256i32;
    const O_EXCL: c_int      = 1024i32;
    const O_TRUNC: c_int     = 512i32;
    const O_TEXT: c_int      = 16384i32;
    const O_BINARY: c_int    = 32768i32;
    const O_NOINHERIT: c_int = 128i32;
    const S_IRUSR: unsigned  = 256u32; // really _S_IREAD  in win32
    const S_IWUSR: unsigned  = 128u32; // really _S_IWRITE in win32
}

type DWORD = u32;
type HMODULE = uint;
type LPTSTR = str::sbuf;
type LPCTSTR = str::sbuf;

#[abi = "stdcall"]
native mod kernel32 {
    type LPSECURITY_ATTRIBUTES;
    fn GetEnvironmentVariableA(n: str::sbuf, v: str::sbuf, nsize: uint) ->
       uint;
    fn SetEnvironmentVariableA(n: str::sbuf, v: str::sbuf) -> int;
    fn GetModuleFileNameA(hModule: HMODULE,
                          lpFilename: LPTSTR,
                          nSize: DWORD) -> DWORD;
    fn CreateDirectoryA(lpPathName: LPCTSTR,
                        lpSecurityAttributes: LPSECURITY_ATTRIBUTES) -> bool;
    fn RemoveDirectoryA(lpPathName: LPCTSTR) -> bool;
    fn SetCurrentDirectoryA(lpPathName: LPCTSTR) -> bool;
}

// FIXME turn into constants
fn exec_suffix() -> str { ret ".exe"; }
fn target_os() -> str { ret "win32"; }

fn dylib_filename(base: str) -> str { ret base + ".dll"; }

fn pipe() -> {in: fd_t, out: fd_t} {
    // Windows pipes work subtly differently than unix pipes, and their
    // inheritance has to be handled in a different way that I don't fully
    // understand. Here we explicitly make the pipe non-inheritable,
    // which means to pass it to a subprocess they need to be duplicated
    // first, as in rust_run_program.
    let fds = {mutable in: 0i32, mutable out: 0i32};
    let res =
        os::libc::_pipe(ptr::mut_addr_of(fds.in), 1024u32,
                        libc_constants::O_BINARY |
                            libc_constants::O_NOINHERIT);
    assert (res == 0i32);
    assert (fds.in != -1i32 && fds.in != 0i32);
    assert (fds.out != -1i32 && fds.in != 0i32);
    ret {in: fds.in, out: fds.out};
}

fn fd_FILE(fd: fd_t) -> libc::FILE {
    ret str::as_buf("r", {|modebuf| libc::_fdopen(fd, modebuf) });
}

fn close(fd: fd_t) -> c_int {
    libc::close(fd)
}

fn fclose(file: libc::FILE) {
    libc::fclose(file)
}

fn fsync_fd(fd: fd_t, level: io::fsync::level) -> c_int {
    // FIXME (1253)
    fail;
}

#[abi = "cdecl"]
native mod rustrt {
    fn rust_process_wait(handle: c_int) -> c_int;
    fn rust_getcwd() -> str;
}

fn waitpid(pid: pid_t) -> i32 { ret rustrt::rust_process_wait(pid); }

fn getcwd() -> str { ret rustrt::rust_getcwd(); }

fn get_exe_path() -> option::t<fs::path> {
    // FIXME: This doesn't handle the case where the buffer is too small
    let bufsize = 1023u;
    let path = str::unsafe_from_bytes(vec::init_elt(0u8, bufsize));
    ret str::as_buf(path, { |path_buf|
        if kernel32::GetModuleFileNameA(0u, path_buf,
                                        bufsize as u32) != 0u32 {
            option::some(fs::dirname(path) + fs::path_sep())
        } else {
            option::none
        }
    });
}

// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<|endoftext|>


<commit_before><commit_msg>test(ser): Port another test from toml-rs<commit_after>#![cfg(feature = "easy")]

use serde::{Deserialize, Serialize};
use toml_edit::ser::to_string;

#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
struct User {
    pub name: String,
    pub surname: String,
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
struct Users {
    pub user: Vec<User>,
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
struct TwoUsers {
    pub user0: User,
    pub user1: User,
}

#[test]
fn no_unnecessary_newlines_array() {
    let toml = to_string(&Users {
        user: vec![
            User {
                name: "John".to_string(),
                surname: "Doe".to_string(),
            },
            User {
                name: "Jane".to_string(),
                surname: "Dough".to_string(),
            },
        ],
    })
    .unwrap();
    assert!(!toml.starts_with('\n'));
}

#[test]
fn no_unnecessary_newlines_table() {
    let toml = to_string(&TwoUsers {
        user0: User {
            name: "John".to_string(),
            surname: "Doe".to_string(),
        },
        user1: User {
            name: "Jane".to_string(),
            surname: "Dough".to_string(),
        },
    })
    .unwrap();
    assert!(!toml.starts_with('\n'));
}
<|endoftext|>


<commit_before><commit_msg>Add test for #203<commit_after>use parking_lot::RwLock;
use std::thread;

struct Bar(RwLock<()>);

impl Drop for Bar {
    fn drop(&mut self) {
        let _n = self.0.write();
    }
}

thread_local! {
    static B: Bar = Bar(RwLock::new(()));
}

#[test]
fn main() {
    thread::spawn(|| {
        B.with(|_| ());

        let a = RwLock::new(());
        let _a = a.read();
    })
    .join()
    .unwrap();
}
<|endoftext|>


<commit_before><commit_msg>Problem 09<commit_after>fn pack<T: Clone+Eq>(list: &[T]) -> ~[~[T]] {
    let mut it = list.iter();
    let mut result = ~[];
    let mut l = 1;
    loop {
        match it.nth(l - 1) {
            Some(e) => {
                let mut slice = ~[];
                slice.push(e.clone());
                for f in it.take_while(|&a| *a == *e) {
                    slice.push(f.clone());
                }
                l = slice.len();
                result.push(slice);
            },
            None    => break
        }
    }
    result
}

fn main() {
    let list =
        ~['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e'];

    println!("{:?}", pack(list));
}
<|endoftext|>


<commit_before><commit_msg>Add example that show the posiotion of the bits in a slice bitfield<commit_after>#[macro_use]
extern crate simple_bitfield;

use simple_bitfield::Bit;
use simple_bitfield::BitRange;

simple_bitfield!{
    struct BitsLocations([u8]);
}

simple_bitfield!{
    struct BitsLocationsMsb0(MSB0 [u8]);
}

fn println_slice_bits(slice: &[u8]) {
    if slice.is_empty() {
        println!("[]");

    } else {
        print!("[{:08b}", slice[0]);

        for byte in &slice[1..] {
            print!(", {:08b}", byte);
        }

        println!("]");
    }
}

fn main() {

    let mut bits_locations = BitsLocations([0; 3]);
    let mut bits_locations_msb0 = BitsLocationsMsb0([0; 3]);

    println!("Default version:");
    for i in 0..(3 * 8) {
        bits_locations.set_bit(i, true);
        print!("{:2}: ", i);
        println_slice_bits(&bits_locations.0);
        bits_locations.set_bit(i, false);
    }

    for i in 0..(3 * 8 - 3) {
        let msb = i + 3;
        let lsb = i;
        for value in &[0b1111u8, 0b0001, 0b1000] {
            bits_locations.set_bit_range(msb, lsb, *value);
            print!("{:2} - {:2} ({:04b}): ", msb, lsb, value);
            println_slice_bits(&bits_locations.0);
        }
        println!("");
        bits_locations.set_bit_range(msb, lsb, 0u8);
    }

    println!("MSB0 version:");

    for i in 0..(3 * 8) {
        bits_locations_msb0.set_bit(i, true);
        print!("{:2}: ", i);
        println_slice_bits(&bits_locations_msb0.0);

        bits_locations_msb0.set_bit(i, false);
    }

    for i in 0..(3 * 8 - 3) {
        let msb = i + 3;
        let lsb = i;
        for value in &[0b1111u8, 0b0001, 0b1000] {
            bits_locations_msb0.set_bit_range(msb, lsb, *value);
            print!("{:2} - {:2} ({:04b}): ", msb, lsb, value);
            println_slice_bits(&bits_locations_msb0.0);
        }
        println!("");

        bits_locations_msb0.set_bit_range(msb, lsb, 0u8);
    }
}
<|endoftext|>


<commit_before><commit_msg>Remove len() != 0 comparison with negation and ::is_empty() call<commit_after><|endoftext|>


<commit_before><commit_msg>Added „Hello World“ example in Rust programming language<commit_after>fn main() {
  println("Hello, World.");
}<|endoftext|>


<commit_before><commit_msg>wtf wtf wtf<commit_after><|endoftext|>


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

#![feature(underscore_lifetimes)]

struct Foo<'a>(&'a u8);

fn foo<'_> //~ ERROR invalid lifetime parameter name: `'_`
(_: Foo<'_>) {}

trait Meh<'a> {}
impl<'a> Meh<'a> for u8 {}

fn meh() -> Box<for<'_> Meh<'_>> //~ ERROR invalid lifetime parameter name: `'_`
//~^ ERROR missing lifetime specifier
//~^^ ERROR missing lifetime specifier
{
  Box::new(5u8)
}

fn foo2(_: &'_ u8, y: &'_ u8) -> &'_ u8 { y } //~ ERROR missing lifetime specifier

fn main() {
    let x = 5;
    foo(Foo(&x));
    let _ = meh();
}
<commit_msg>Add tests for underscore lifetimes in impl headers and struct definitions<commit_after>// Copyright 2017 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.

#![feature(underscore_lifetimes)]

struct Foo<'a>(&'a u8);
struct Baz<'a>(&'_ &'a u8); //~ ERROR missing lifetime specifier

impl Foo<'_> { //~ ERROR missing lifetime specifier
    fn x() {}
}

fn foo<'_> //~ ERROR invalid lifetime parameter name: `'_`
(_: Foo<'_>) {}

trait Meh<'a> {}
impl<'a> Meh<'a> for u8 {}

fn meh() -> Box<for<'_> Meh<'_>> //~ ERROR invalid lifetime parameter name: `'_`
//~^ ERROR missing lifetime specifier
//~^^ ERROR missing lifetime specifier
{
  Box::new(5u8)
}

fn foo2(_: &'_ u8, y: &'_ u8) -> &'_ u8 { y } //~ ERROR missing lifetime specifier

fn main() {
    let x = 5;
    foo(Foo(&x));
    let _ = meh();
}
<|endoftext|>


<commit_before><commit_msg>Add problem #78<commit_after>use core::hashmap::{ HashMap };
use core::util::{ unreachable };

use common::problem::{ Problem };

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

static million: int = 1000000;

#[inline(always)]
fn penta(n: int) -> int { n * (3 * n - 1) / 2 }

#[inline(always)]
fn each_penta(f: &fn(int) -> bool) {
    let mut i = 1;
    loop {
        if !f(penta(i)) { break; }
        if !f(penta(-i)) { break; }
        i += 1;
    }
}

#[inline(always)]
fn each_way(f: &fn(int, int) -> bool) {
    let mut v = HashMap::new();
    v.insert(0, 1);

    let mut n = 1;
    loop {
        let mut way = 0;
        let mut i = 0;
        for each_penta |p| {
            if p > n { break; }

            let sign = if i % 4 > 1 { -1 } else { 1 };
            way += sign * *v.get(&(n - p));
            way %= million;
            i += 1;
        }

        if !f((n + million) % million, way) { return; }
        v.insert(n, way);
        n += 1;
    }
}

fn solve() -> ~str {
    for each_way |n, way| {
        if way % million == 0 {
            return n.to_str();
        }
    }

    unreachable();
}
<|endoftext|>


<commit_before><commit_msg>Add problem #82<commit_after>use common::problem::{ Problem };

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

fn solve() -> ~str {
    let result = io::file_reader(&Path("files/matrix.txt")).map(|file| {
        let mut mat = ~[];
        for file.each_line |line| {
            let mut row = ~[];
            for line.each_split_char(',') |n| {
                row.push(uint::from_str(n).get());
            }
            mat.push(row);
            assert_eq!(mat[0].len(), mat.last().len());
        }
        let w = mat[0].len();
        let h = mat.len();
        ((w, h), mat)
    }).map(|&((w, h), mat)| {
        let mut sum = vec::from_fn(h, |_y| vec::from_elem(w, 0));
        for uint::range(0, h) |y| { sum[y][0] = mat[y][0]; }
        for uint::range(1, w) |x| {
            for uint::range(0, h) |y| {
                let mut min = sum[y][x - 1];

                let mut s = 0;
                for uint::range(1, y) |dy| {
                    s += mat[y - dy][x];
                    min = uint::min(sum[y - dy][x - 1] + s, min);
                }

                let mut s = 0;
                for uint::range(1, h - y) |dy| {
                    s += mat[y + dy][x];
                    min = uint::min(sum[y + dy][x - 1] + s, min);
                }

                sum[y][x] = mat[y][x] + min;
            }
        }
        let mut min = uint::max_value;
        for uint::range(0, h) |y| {
            min = uint::min(sum[y][w - 1], min);
        }
        min
    });

    match result {
        Err(msg) => fail!(msg),
        Ok(value) => return value.to_str()
    }
}
<|endoftext|>


<commit_before><commit_msg>I don't know what this is or why it's here.<commit_after><|endoftext|>


<commit_before><commit_msg>chore: guess<commit_after><|endoftext|>


<commit_before><commit_msg>birthday_cake_candles<commit_after>//https://www.hackerrank.com/challenges/birthday-cake-candles

use std::io;
use std::io::prelude::*;

fn main() {
    let stdin = io::stdin();

    let values: Vec<i32> = stdin.lock()
        .lines()
        .skip(1).next()
        .unwrap()
        .unwrap()
        .trim()
        .split(' ')
        //https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map
        .map(|x| x.parse::<i32>().unwrap())
        .collect();

    let max = values.iter().max().unwrap();
    let count = values.iter().fold(0, |acc, x| acc + if x == max {1} else {0});

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


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


<commit_before><commit_msg>Auto merge of #11292 - arlosi:compression, r=epage<commit_after><|endoftext|>


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

/// A simple static assertion macro. The first argument should be a unique
/// ALL_CAPS identifier that describes the condition.
#[macro_export]
macro_rules! static_assert {
    ($name:ident: $test:expr) => {
        // Use the bool to access an array such that if the bool is false, the access
        // is out-of-bounds.
        #[allow(dead_code)]
        static $name: () = [()][!$test as usize];
    }
}
<commit_msg>Rollup merge of #55945 - oli-obk:static_assert_arg_type, r=michaelwoerister<commit_after>// Copyright 2018 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.

/// A simple static assertion macro. The first argument should be a unique
/// ALL_CAPS identifier that describes the condition.
#[macro_export]
#[allow_internal_unstable]
macro_rules! static_assert {
    ($name:ident: $test:expr) => {
        // Use the bool to access an array such that if the bool is false, the access
        // is out-of-bounds.
        #[allow(dead_code)]
        static $name: () = [()][!($test: bool) as usize];
    }
}
<|endoftext|>


<commit_before>use std::hash::{Hash, Hasher};

use rustc::ich::{StableHashingContext, StableHashingContextProvider};
use rustc::mir;
use rustc::mir::interpret::{AllocId, Pointer, Scalar, ScalarMaybeUndef, Relocations, Allocation, UndefMask};
use rustc::ty;
use rustc::ty::layout::Align;
use rustc_data_structures::indexed_vec::IndexVec;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
use syntax::ast::Mutability;
use syntax::source_map::Span;

use super::eval_context::{LocalValue, StackPopCleanup};
use super::{Frame, Memory, Machine, Operand, MemPlace, Place, Value};

trait SnapshotContext<'a> {
    type To;
    type From;
    fn resolve(&'a self, id: &Self::From) -> Option<&'a Self::To>;
}

trait Snapshot<'a, Ctx: SnapshotContext<'a>> {
    type Item;
    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item;
}

impl<'a, Ctx, T> Snapshot<'a, Ctx> for Option<T>
    where Ctx: SnapshotContext<'a>,
          T: Snapshot<'a, Ctx>
{
    type Item = Option<<T as Snapshot<'a, Ctx>>::Item>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        match self {
            Some(x) => Some(x.snapshot(ctx)),
            None => None,
        }
    }
}

#[derive(Eq, PartialEq)]
struct AllocIdSnapshot<'a>(Option<AllocationSnapshot<'a>>);

impl<'a, Ctx> Snapshot<'a, Ctx> for AllocId
    where Ctx: SnapshotContext<'a, To=Allocation, From=AllocId>,
{
    type Item = AllocIdSnapshot<'a>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        AllocIdSnapshot(ctx.resolve(self).map(|alloc| alloc.snapshot(ctx)))
    }
}

type PointerSnapshot<'a> = Pointer<AllocIdSnapshot<'a>>;

impl<'a, Ctx> Snapshot<'a, Ctx> for Pointer
    where Ctx: SnapshotContext<'a, To=Allocation, From=AllocId>,
{
    type Item = PointerSnapshot<'a>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        let Pointer{ alloc_id, offset } = self;

        Pointer {
            alloc_id: alloc_id.snapshot(ctx),
            offset: *offset,
        }
    }
}

type ScalarSnapshot<'a> = Scalar<AllocIdSnapshot<'a>>;

impl<'a, Ctx> Snapshot<'a, Ctx> for Scalar
    where Ctx: SnapshotContext<'a, To=Allocation, From=AllocId>,
{
    type Item = ScalarSnapshot<'a>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        match self {
            Scalar::Ptr(p) => Scalar::Ptr(p.snapshot(ctx)),
            Scalar::Bits{ size, bits } => Scalar::Bits{
                size: *size,
                bits: *bits,
            },
        }
    }
}

type ScalarMaybeUndefSnapshot<'a> = ScalarMaybeUndef<AllocIdSnapshot<'a>>;

impl<'a, Ctx> Snapshot<'a, Ctx> for ScalarMaybeUndef
    where Ctx: SnapshotContext<'a, To=Allocation, From=AllocId>,
{
    type Item = ScalarMaybeUndefSnapshot<'a>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        match self {
            ScalarMaybeUndef::Scalar(s) => ScalarMaybeUndef::Scalar(s.snapshot(ctx)),
            ScalarMaybeUndef::Undef => ScalarMaybeUndef::Undef,
        }
    }
}

type MemPlaceSnapshot<'a> = MemPlace<AllocIdSnapshot<'a>>;

impl<'a, Ctx> Snapshot<'a, Ctx> for MemPlace
    where Ctx: SnapshotContext<'a, To=Allocation, From=AllocId>,
{
    type Item = MemPlaceSnapshot<'a>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        let MemPlace{ ptr, extra, align } = self;

        MemPlaceSnapshot{
            ptr: ptr.snapshot(ctx),
            extra: extra.snapshot(ctx),
            align: *align,
        }
    }
}

type PlaceSnapshot<'a> = Place<AllocIdSnapshot<'a>>;

impl<'a, Ctx> Snapshot<'a, Ctx> for Place
    where Ctx: SnapshotContext<'a, To=Allocation, From=AllocId>,
{
    type Item = PlaceSnapshot<'a>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        match self {
            Place::Ptr(p) => Place::Ptr(p.snapshot(ctx)),

            Place::Local{ frame, local } => Place::Local{
                frame: *frame,
                local: *local,
            },
        }
    }
}

type ValueSnapshot<'a> = Value<AllocIdSnapshot<'a>>;

impl<'a, Ctx> Snapshot<'a, Ctx> for Value
    where Ctx: SnapshotContext<'a, To=Allocation, From=AllocId>,
{
    type Item = ValueSnapshot<'a>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        match self {
            Value::Scalar(s) => Value::Scalar(s.snapshot(ctx)),
            Value::ScalarPair(a, b) => Value::ScalarPair(a.snapshot(ctx), b.snapshot(ctx)),
        }
    }
}

type OperandSnapshot<'a> = Operand<AllocIdSnapshot<'a>>;

impl<'a, Ctx> Snapshot<'a, Ctx> for Operand
    where Ctx: SnapshotContext<'a, To=Allocation, From=AllocId>,
{
    type Item = OperandSnapshot<'a>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        match self {
            Operand::Immediate(v) => Operand::Immediate(v.snapshot(ctx)),
            Operand::Indirect(m) => Operand::Indirect(m.snapshot(ctx)),
        }
    }
}

type LocalValueSnapshot<'a> = LocalValue<AllocIdSnapshot<'a>>;

impl<'a, Ctx> Snapshot<'a, Ctx> for LocalValue
    where Ctx: SnapshotContext<'a, To=Allocation, From=AllocId>,
{
    type Item = LocalValueSnapshot<'a>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        match self {
            LocalValue::Live(v) => LocalValue::Live(v.snapshot(ctx)),
            LocalValue::Dead => LocalValue::Dead,
        }
    }
}

type RelocationsSnapshot<'a> = Relocations<AllocIdSnapshot<'a>>;

impl<'a, Ctx> Snapshot<'a, Ctx> for Relocations
    where Ctx: SnapshotContext<'a, To=Allocation, From=AllocId>,
{
    type Item = RelocationsSnapshot<'a>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        Relocations::from_presorted(self.iter().map(|(size, id)| (*size, id.snapshot(ctx))).collect())
    }
}

#[derive(Eq, PartialEq)]
struct AllocationSnapshot<'a> {
    bytes: &'a [u8],
    relocations: RelocationsSnapshot<'a>,
    undef_mask: &'a UndefMask,
    align: &'a Align,
    mutability: &'a Mutability,
}

impl<'a, Ctx> Snapshot<'a, Ctx> for &'a Allocation
    where Ctx: SnapshotContext<'a, To=Allocation, From=AllocId>,
{
    type Item = AllocationSnapshot<'a>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        let Allocation { bytes, relocations, undef_mask, align, mutability } = self;

        AllocationSnapshot {
            bytes,
            undef_mask,
            align,
            mutability,
            relocations: relocations.snapshot(ctx),
        }
    }
}

#[derive(Eq, PartialEq)]
struct FrameSnapshot<'a, 'tcx: 'a> {
    instance: &'a ty::Instance<'tcx>,
    span: &'a Span,
    return_to_block: &'a StackPopCleanup,
    return_place: PlaceSnapshot<'a>,
    locals: IndexVec<mir::Local, LocalValueSnapshot<'a>>,
    block: &'a mir::BasicBlock,
    stmt: usize,
}

impl<'a, 'mir, 'tcx, Ctx> Snapshot<'a, Ctx> for &'a Frame<'mir, 'tcx>
    where Ctx: SnapshotContext<'a, To=Allocation, From=AllocId>,
{
    type Item = FrameSnapshot<'a, 'tcx>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        let Frame {
            mir: _,
            instance,
            span,
            return_to_block,
            return_place,
            locals,
            block,
            stmt,
        } = self;

        FrameSnapshot {
            instance,
            span,
            return_to_block,
            block,
            stmt: *stmt,
            return_place: return_place.snapshot(ctx),
            locals: locals.iter().map(|local| local.snapshot(ctx)).collect(),
        }
    }
}

#[derive(Eq, PartialEq)]
struct MemorySnapshot<'a, 'mir: 'a, 'tcx: 'a + 'mir, M: Machine<'mir, 'tcx> + 'a> {
    data: &'a M::MemoryData,
}

impl<'a, 'mir, 'tcx, M> Memory<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
{
    fn snapshot<'b: 'a>(&'b self) -> MemorySnapshot<'b, 'mir, 'tcx, M> {
        let Memory { data, .. } = self;
        MemorySnapshot { data }
    }
}

impl<'a, 'b, 'mir, 'tcx, M> SnapshotContext<'b> for Memory<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
{
    type To = Allocation;
    type From = AllocId;
    fn resolve(&'b self, id: &Self::From) -> Option<&'b Self::To> {
        self.get(*id).ok()
    }
}

/// The virtual machine state during const-evaluation at a given point in time.
pub struct EvalSnapshot<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'mir, 'tcx>> {
    machine: M,
    memory: Memory<'a, 'mir, 'tcx, M>,
    stack: Vec<Frame<'mir, 'tcx>>,
}

impl<'a, 'mir, 'tcx, M> EvalSnapshot<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
{
    pub fn new(machine: &M, memory: &Memory<'a, 'mir, 'tcx, M>, stack: &[Frame<'mir, 'tcx>]) -> Self {
        EvalSnapshot {
            machine: machine.clone(),
            memory: memory.clone(),
            stack: stack.into(),
        }
    }

    fn snapshot<'b: 'a>(&'b self) -> (&'b M, MemorySnapshot<'b, 'mir, 'tcx, M>, Vec<FrameSnapshot<'a, 'tcx>>) {
        let EvalSnapshot{ machine, memory, stack } = self;
        (&machine, memory.snapshot(), stack.iter().map(|frame| frame.snapshot(memory)).collect())
    }
}

impl<'a, 'mir, 'tcx, M> Hash for EvalSnapshot<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        // Implement in terms of hash stable, so that k1 == k2 -> hash(k1) == hash(k2)
        let mut hcx = self.memory.tcx.get_stable_hashing_context();
        let mut hasher = StableHasher::<u64>::new();
        self.hash_stable(&mut hcx, &mut hasher);
        hasher.finish().hash(state)
    }
}

impl<'a, 'b, 'mir, 'tcx, M> HashStable<StableHashingContext<'b>> for EvalSnapshot<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
{
    fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'b>, hasher: &mut StableHasher<W>) {
        let EvalSnapshot{ machine, memory, stack } = self;
        (machine, &memory.data, stack).hash_stable(hcx, hasher);
    }
}

impl<'a, 'mir, 'tcx, M> Eq for EvalSnapshot<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
{}

impl<'a, 'mir, 'tcx, M> PartialEq for EvalSnapshot<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
{
    fn eq(&self, other: &Self) -> bool {
        self.snapshot() == other.snapshot()
    }
}
<commit_msg>Add a convenience macro to reduce code duplication<commit_after>use std::hash::{Hash, Hasher};

use rustc::ich::{StableHashingContext, StableHashingContextProvider};
use rustc::mir;
use rustc::mir::interpret::{AllocId, Pointer, Scalar, ScalarMaybeUndef, Relocations, Allocation, UndefMask};
use rustc::ty;
use rustc::ty::layout::Align;
use rustc_data_structures::indexed_vec::IndexVec;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult};
use syntax::ast::Mutability;
use syntax::source_map::Span;

use super::eval_context::{LocalValue, StackPopCleanup};
use super::{Frame, Memory, Machine, Operand, MemPlace, Place, Value};

trait SnapshotContext<'a> {
    fn resolve(&'a self, id: &AllocId) -> Option<&'a Allocation>;
}

trait Snapshot<'a, Ctx: SnapshotContext<'a>> {
    type Item;
    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item;
}

macro_rules! __impl_snapshot_field {
    ($field:ident, $ctx:expr) => ($field.snapshot($ctx));
    ($field:ident, $ctx:expr, $delegate:expr) => ($delegate);
}

macro_rules! impl_snapshot_for {
    // FIXME(mark-i-m): Some of these should be `?` rather than `*`.
    (enum $enum_name:ident { $( $variant:ident $( ( $($field:ident $(-> $delegate:expr)*),* ) )* ),* $(,)* }) => {
        impl<'a, Ctx> self::Snapshot<'a, Ctx> for $enum_name
            where Ctx: self::SnapshotContext<'a>,
        {
            type Item = $enum_name<AllocIdSnapshot<'a>>;

            #[inline]
            fn snapshot(&self, __ctx: &'a Ctx) -> Self::Item {
                match *self {
                    $(
                        $enum_name::$variant $( ( $(ref $field),* ) )* =>
                            $enum_name::$variant $( ( $( __impl_snapshot_field!($field, __ctx $(, $delegate)*) ),* ), )*
                    )*
                }
            }
        }
    };

    // FIXME(mark-i-m): same here.
    (struct $struct_name:ident { $($field:ident $(-> $delegate:expr)*),*  $(,)* }) => {
        impl<'a, Ctx> self::Snapshot<'a, Ctx> for $struct_name
            where Ctx: self::SnapshotContext<'a>,
        {
            type Item = $struct_name<AllocIdSnapshot<'a>>;

            #[inline]
            fn snapshot(&self, __ctx: &'a Ctx) -> Self::Item {
                let $struct_name {
                    $(ref $field),*
                } = *self;

                $struct_name {
                    $( $field: __impl_snapshot_field!($field, __ctx $(, $delegate)*) ),*
                }
            }
        }
    };
}

impl<'a, Ctx, T> Snapshot<'a, Ctx> for Option<T>
    where Ctx: SnapshotContext<'a>,
          T: Snapshot<'a, Ctx>
{
    type Item = Option<<T as Snapshot<'a, Ctx>>::Item>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        match self {
            Some(x) => Some(x.snapshot(ctx)),
            None => None,
        }
    }
}

#[derive(Eq, PartialEq)]
struct AllocIdSnapshot<'a>(Option<AllocationSnapshot<'a>>);

impl<'a, Ctx> Snapshot<'a, Ctx> for AllocId
    where Ctx: SnapshotContext<'a>,
{
    type Item = AllocIdSnapshot<'a>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        AllocIdSnapshot(ctx.resolve(self).map(|alloc| alloc.snapshot(ctx)))
    }
}

impl_snapshot_for!(struct Pointer {
    alloc_id,
    offset -> *offset,
});

impl<'a, Ctx> Snapshot<'a, Ctx> for Scalar
    where Ctx: SnapshotContext<'a>,
{
    type Item = Scalar<AllocIdSnapshot<'a>>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        match self {
            Scalar::Ptr(p) => Scalar::Ptr(p.snapshot(ctx)),
            Scalar::Bits{ size, bits } => Scalar::Bits {
                size: *size,
                bits: *bits,
            },
        }
    }
}

impl_snapshot_for!(enum ScalarMaybeUndef {
    Scalar(s),
    Undef,
});

impl_snapshot_for!(struct MemPlace {
    ptr,
    extra,
    align -> *align,
});

impl<'a, Ctx> Snapshot<'a, Ctx> for Place
    where Ctx: SnapshotContext<'a>,
{
    type Item = Place<AllocIdSnapshot<'a>>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        match self {
            Place::Ptr(p) => Place::Ptr(p.snapshot(ctx)),

            Place::Local{ frame, local } => Place::Local{
                frame: *frame,
                local: *local,
            },
        }
    }
}

impl_snapshot_for!(enum Value {
    Scalar(s),
    ScalarPair(s, t),
});

impl_snapshot_for!(enum Operand {
    Immediate(v),
    Indirect(m),
});

impl_snapshot_for!(enum LocalValue {
    Live(v),
    Dead,
});

impl<'a, Ctx> Snapshot<'a, Ctx> for Relocations
    where Ctx: SnapshotContext<'a>,
{
    type Item = Relocations<AllocIdSnapshot<'a>>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        Relocations::from_presorted(self.iter().map(|(size, id)| (*size, id.snapshot(ctx))).collect())
    }
}

#[derive(Eq, PartialEq)]
struct AllocationSnapshot<'a> {
    bytes: &'a [u8],
    relocations: Relocations<AllocIdSnapshot<'a>>,
    undef_mask: &'a UndefMask,
    align: &'a Align,
    mutability: &'a Mutability,
}

impl<'a, Ctx> Snapshot<'a, Ctx> for &'a Allocation
    where Ctx: SnapshotContext<'a>,
{
    type Item = AllocationSnapshot<'a>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        let Allocation { bytes, relocations, undef_mask, align, mutability } = self;

        AllocationSnapshot {
            bytes,
            undef_mask,
            align,
            mutability,
            relocations: relocations.snapshot(ctx),
        }
    }
}

#[derive(Eq, PartialEq)]
struct FrameSnapshot<'a, 'tcx: 'a> {
    instance: &'a ty::Instance<'tcx>,
    span: &'a Span,
    return_to_block: &'a StackPopCleanup,
    return_place: Place<AllocIdSnapshot<'a>>,
    locals: IndexVec<mir::Local, LocalValue<AllocIdSnapshot<'a>>>,
    block: &'a mir::BasicBlock,
    stmt: usize,
}

impl<'a, 'mir, 'tcx, Ctx> Snapshot<'a, Ctx> for &'a Frame<'mir, 'tcx>
    where Ctx: SnapshotContext<'a>,
{
    type Item = FrameSnapshot<'a, 'tcx>;

    fn snapshot(&self, ctx: &'a Ctx) -> Self::Item {
        let Frame {
            mir: _,
            instance,
            span,
            return_to_block,
            return_place,
            locals,
            block,
            stmt,
        } = self;

        FrameSnapshot {
            instance,
            span,
            return_to_block,
            block,
            stmt: *stmt,
            return_place: return_place.snapshot(ctx),
            locals: locals.iter().map(|local| local.snapshot(ctx)).collect(),
        }
    }
}

#[derive(Eq, PartialEq)]
struct MemorySnapshot<'a, 'mir: 'a, 'tcx: 'a + 'mir, M: Machine<'mir, 'tcx> + 'a> {
    data: &'a M::MemoryData,
}

impl<'a, 'mir, 'tcx, M> Memory<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
{
    fn snapshot<'b: 'a>(&'b self) -> MemorySnapshot<'b, 'mir, 'tcx, M> {
        let Memory { data, .. } = self;
        MemorySnapshot { data }
    }
}

impl<'a, 'b, 'mir, 'tcx, M> SnapshotContext<'b> for Memory<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
{
    fn resolve(&'b self, id: &AllocId) -> Option<&'b Allocation> {
        self.get(*id).ok()
    }
}

/// The virtual machine state during const-evaluation at a given point in time.
pub struct EvalSnapshot<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'mir, 'tcx>> {
    machine: M,
    memory: Memory<'a, 'mir, 'tcx, M>,
    stack: Vec<Frame<'mir, 'tcx>>,
}

impl<'a, 'mir, 'tcx, M> EvalSnapshot<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
{
    pub fn new(machine: &M, memory: &Memory<'a, 'mir, 'tcx, M>, stack: &[Frame<'mir, 'tcx>]) -> Self {
        EvalSnapshot {
            machine: machine.clone(),
            memory: memory.clone(),
            stack: stack.into(),
        }
    }

    fn snapshot<'b: 'a>(&'b self) -> (&'b M, MemorySnapshot<'b, 'mir, 'tcx, M>, Vec<FrameSnapshot<'a, 'tcx>>) {
        let EvalSnapshot{ machine, memory, stack } = self;
        (&machine, memory.snapshot(), stack.iter().map(|frame| frame.snapshot(memory)).collect())
    }
}

impl<'a, 'mir, 'tcx, M> Hash for EvalSnapshot<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        // Implement in terms of hash stable, so that k1 == k2 -> hash(k1) == hash(k2)
        let mut hcx = self.memory.tcx.get_stable_hashing_context();
        let mut hasher = StableHasher::<u64>::new();
        self.hash_stable(&mut hcx, &mut hasher);
        hasher.finish().hash(state)
    }
}

impl<'a, 'b, 'mir, 'tcx, M> HashStable<StableHashingContext<'b>> for EvalSnapshot<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
{
    fn hash_stable<W: StableHasherResult>(&self, hcx: &mut StableHashingContext<'b>, hasher: &mut StableHasher<W>) {
        let EvalSnapshot{ machine, memory, stack } = self;
        (machine, &memory.data, stack).hash_stable(hcx, hasher);
    }
}

impl<'a, 'mir, 'tcx, M> Eq for EvalSnapshot<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
{}

impl<'a, 'mir, 'tcx, M> PartialEq for EvalSnapshot<'a, 'mir, 'tcx, M>
    where M: Machine<'mir, 'tcx>,
{
    fn eq(&self, other: &Self) -> bool {
        self.snapshot() == other.snapshot()
    }
}
<|endoftext|>


<commit_before><commit_msg>[tests] Add passing test<commit_after>trait Foo {
    fn a() -> int;
    fn b() -> int {
        self.a() + 2
    }
}

impl int: Foo {
    fn a() -> int {
        3
    }
}

fn main() {
    assert(3.b() == 5);
}
<|endoftext|>


<commit_before><commit_msg>Add generic-temporary.rs minimal test showing cause of lib-deque.rs failure on stage0.<commit_after>
// xfail-stage0

fn mk() -> int {
  ret 1;
}

fn chk(&int a) {
  log a;
  check (a == 1);
}

fn apply[T](fn() -> T produce, fn(&T) consume) {
  consume(produce());
}

fn main() {
  let (fn()->int) produce = mk;
  let (fn(&int)) consume = chk;
  apply[int](produce, consume);
}
<|endoftext|>


<commit_before><commit_msg>Add tests<commit_after>// Copyright 2016 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.

// compile-flags: --test

#![crate_type = "proc-macro"]
#![feature(proc_macro)]

extern crate proc_macro;

#[proc_macro_derive(A)]
//~^ ERROR: `--test` cannot be used with proc-macro crates
pub fn foo1(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    "".parse().unwrap()
}
<|endoftext|>


<commit_before><commit_msg>cleanup: A test applicable to windows<commit_after>//! One indirect test for cleanup.
//!
//! Unlike the ones in cleanup.rs, this one is usable on windows too. But because the library can't
//! recover from cleanup, we have just one here.

extern crate libc;
extern crate signal_hook;

use std::sync::atomic::AtomicBool;
use std::sync::Arc;

use libc::{c_int, raise, sighandler_t, signal};
use signal_hook::SIGTERM;

extern "C" fn handler(_: c_int) {}

#[test]
fn cleanup_indirect() {
    // Read what the default is.
    let orig = unsafe { signal(SIGTERM, handler as sighandler_t) };
    signal_hook::flag::register(SIGTERM, Arc::new(AtomicBool::new(false))).unwrap();
    signal_hook::cleanup::register(SIGTERM, vec![SIGTERM]).unwrap();
    // By now, it is switched to something else.
    unsafe {
        // This'll change it back to the default due to the cleanup.
        raise(SIGTERM);
        // Check it really did.
        assert_eq!(orig, signal(SIGTERM, handler as sighandler_t));
    }
}
<|endoftext|>


<commit_before><commit_msg>easage-unpack: Truncate files before writing to them<commit_after><|endoftext|>


<commit_before><commit_msg>Add test for self-referencing pattern blocked by #20551. Fixes #20551.<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.

// Test references to the trait `Stream` in the bounds for associated
// types defined on `Stream`. Issue #20551.

trait Stream {
    type Car;
    type Cdr: Stream;

    fn car(&self) -> Self::Car;
    fn cdr(self) -> Self::Cdr;
}

impl Stream for () {
    type Car = ();
    type Cdr = ();
    fn car(&self) -> () { () }
    fn cdr(self) -> () { self }
}

impl<T,U> Stream for (T, U)
    where T : Clone, U : Stream
{
    type Car = T;
    type Cdr = U;
    fn car(&self) -> T { self.0.clone() }
    fn cdr(self) -> U { self.1 }
}

fn main() {
    let p = (22, (44, (66, ())));
    assert_eq!(p.car(), 22);

    let p = p.cdr();
    assert_eq!(p.car(), 44);

    let p = p.cdr();
    assert_eq!(p.car(), 66);
}
<|endoftext|>


<commit_before>// High-level bindings to Cairo.

import cairo::{CAIRO_STATUS_SUCCESS, cairo_format_t, cairo_status_t, cairo_surface_t, cairo_t};
import cairo::bindgen::{cairo_create, cairo_fill, cairo_image_surface_create};
import cairo::bindgen::{cairo_image_surface_get_data, cairo_image_surface_get_format};
import cairo::bindgen::{cairo_image_surface_get_height, cairo_image_surface_get_stride};
import cairo::bindgen::{cairo_image_surface_get_width, cairo_rectangle, cairo_set_line_width};
import cairo::bindgen::{cairo_set_source_rgb, cairo_stroke, cairo_surface_destroy};
import cairo::bindgen::{cairo_surface_reference, cairo_surface_write_to_png_stream};
import io::{MemBuffer, Writer};
import ptr::addr_of;
import result::{Err, Ok, Result};
import unsafe::reinterpret_cast;
import vec::unsafe::{form_slice, from_buf};

// FIXME: We should have a hierarchy of surfaces, but this needs to wait on case classes.
struct ImageSurface {
    let cairo_surface: *cairo_surface_t;

    fn width()  -> c_int    { cairo_image_surface_get_width(self.cairo_surface)  }
    fn height() -> c_int    { cairo_image_surface_get_height(self.cairo_surface) }
    fn stride() -> c_int    { cairo_image_surface_get_stride(self.cairo_surface) }
    fn format() -> c_int    { cairo_image_surface_get_format(self.cairo_surface) }

    // FIXME: This should not copy!
    pure fn data() -> ~[u8] unsafe {
        let buffer = cairo_image_surface_get_data(self.cairo_surface);
        return from_buf(buffer, (self.stride() * self.height()) as uint);
    }

    drop {
        cairo_surface_destroy(self.cairo_surface);
    }
}

// Should be private.
fn image_surface_from_cairo_surface(cairo_surface: *cairo_surface_t) -> ImageSurface {
    assert !cairo_surface.is_null();
    ImageSurface { cairo_surface: cairo_surface }
}

fn ImageSurface(format: cairo_format_t, width: c_int, height: c_int) -> ImageSurface {
    let cairo_surface = cairo_image_surface_create(format, width, height);
    if cairo_surface.is_null() {
        fail ~"couldn't create Cairo image surface";
    }
    return image_surface_from_cairo_surface(move cairo_surface);
}

impl ImageSurface {
    fn write_to_png_stream(buffer: &io::MemBuffer) -> Result<(),cairo_status_t> unsafe {
        extern fn write_fn(closure: *c_void, data: *c_uchar, len: c_uint)
                        -> cairo_status_t unsafe {
            let writer: *MemBuffer = reinterpret_cast(&closure);
            do form_slice(data, len as uint) |bytes| {
                (*writer).write(bytes);
            }
            return CAIRO_STATUS_SUCCESS;
        }

        let buffer_ptr = reinterpret_cast(buffer);
        let status = cairo_surface_write_to_png_stream(self.cairo_surface, write_fn, buffer_ptr);
        if status != CAIRO_STATUS_SUCCESS {
            return Err(status);
        }

        return Ok(());
    }

    fn clone() -> ImageSurface {
        cairo_surface_reference(self.cairo_surface);
        return image_surface_from_cairo_surface(self.cairo_surface);
    }
}

struct Context {
    let cairo_context: *cairo_t;

    new(&&surface: ImageSurface) {
        self.cairo_context = cairo_create(surface.cairo_surface);
    }

    fn set_line_width(width: c_double) {
        cairo_set_line_width(self.cairo_context, width);
    }

    fn set_source_rgb(r: c_double, g: c_double, b: c_double) {
        cairo_set_source_rgb(self.cairo_context, r, g, b);
    }

    fn rectangle(x: c_double, y: c_double, width: c_double, height: c_double) {
        cairo_rectangle(self.cairo_context, x, y, width, height);
    }

    fn stroke() {
        cairo_stroke(self.cairo_context);
    }

    fn fill() {
        cairo_fill(self.cairo_context);
    }
}

<commit_msg>Fix a reinterpret_cast call<commit_after>// High-level bindings to Cairo.

import cairo::{CAIRO_STATUS_SUCCESS, cairo_format_t, cairo_status_t, cairo_surface_t, cairo_t};
import cairo::bindgen::{cairo_create, cairo_fill, cairo_image_surface_create};
import cairo::bindgen::{cairo_image_surface_get_data, cairo_image_surface_get_format};
import cairo::bindgen::{cairo_image_surface_get_height, cairo_image_surface_get_stride};
import cairo::bindgen::{cairo_image_surface_get_width, cairo_rectangle, cairo_set_line_width};
import cairo::bindgen::{cairo_set_source_rgb, cairo_stroke, cairo_surface_destroy};
import cairo::bindgen::{cairo_surface_reference, cairo_surface_write_to_png_stream};
import io::{MemBuffer, Writer};
import ptr::addr_of;
import result::{Err, Ok, Result};
import unsafe::reinterpret_cast;
import vec::unsafe::{form_slice, from_buf};

// FIXME: We should have a hierarchy of surfaces, but this needs to wait on case classes.
struct ImageSurface {
    let cairo_surface: *cairo_surface_t;

    fn width()  -> c_int    { cairo_image_surface_get_width(self.cairo_surface)  }
    fn height() -> c_int    { cairo_image_surface_get_height(self.cairo_surface) }
    fn stride() -> c_int    { cairo_image_surface_get_stride(self.cairo_surface) }
    fn format() -> c_int    { cairo_image_surface_get_format(self.cairo_surface) }

    // FIXME: This should not copy!
    pure fn data() -> ~[u8] unsafe {
        let buffer = cairo_image_surface_get_data(self.cairo_surface);
        return from_buf(buffer, (self.stride() * self.height()) as uint);
    }

    drop {
        cairo_surface_destroy(self.cairo_surface);
    }
}

// Should be private.
fn image_surface_from_cairo_surface(cairo_surface: *cairo_surface_t) -> ImageSurface {
    assert !cairo_surface.is_null();
    ImageSurface { cairo_surface: cairo_surface }
}

fn ImageSurface(format: cairo_format_t, width: c_int, height: c_int) -> ImageSurface {
    let cairo_surface = cairo_image_surface_create(format, width, height);
    if cairo_surface.is_null() {
        fail ~"couldn't create Cairo image surface";
    }
    return image_surface_from_cairo_surface(move cairo_surface);
}

impl ImageSurface {
    fn write_to_png_stream(buffer: &io::MemBuffer) -> Result<(),cairo_status_t> unsafe {
        extern fn write_fn(closure: *c_void, data: *c_uchar, len: c_uint)
                        -> cairo_status_t unsafe {
            let writer: *MemBuffer = reinterpret_cast(&closure);
            do form_slice(data, len as uint) |bytes| {
                (*writer).write(bytes);
            }
            return CAIRO_STATUS_SUCCESS;
        }

        let buffer_ptr = reinterpret_cast(&buffer);
        let status = cairo_surface_write_to_png_stream(self.cairo_surface, write_fn, buffer_ptr);
        if status != CAIRO_STATUS_SUCCESS {
            return Err(status);
        }

        return Ok(());
    }

    fn clone() -> ImageSurface {
        cairo_surface_reference(self.cairo_surface);
        return image_surface_from_cairo_surface(self.cairo_surface);
    }
}

struct Context {
    let cairo_context: *cairo_t;

    new(&&surface: ImageSurface) {
        self.cairo_context = cairo_create(surface.cairo_surface);
    }

    fn set_line_width(width: c_double) {
        cairo_set_line_width(self.cairo_context, width);
    }

    fn set_source_rgb(r: c_double, g: c_double, b: c_double) {
        cairo_set_source_rgb(self.cairo_context, r, g, b);
    }

    fn rectangle(x: c_double, y: c_double, width: c_double, height: c_double) {
        cairo_rectangle(self.cairo_context, x, y, width, height);
    }

    fn stroke() {
        cairo_stroke(self.cairo_context);
    }

    fn fill() {
        cairo_fill(self.cairo_context);
    }
}

<|endoftext|>


<commit_before><commit_msg>Add an ASCII test for Commands<commit_after><|endoftext|>


<commit_before><commit_msg>Add test that runs every nannou example listed in the Cargo.toml<commit_after>// A simple little script that attempts to run every example listed within the `Cargo.toml`.
//
// This will fail if any of the examples `panic!`.
#[test]
#[ignore]
fn test_run_all_examples() {
    // Read the nannou cargo manifest to a `toml::Value`.
    let manifest_dir = env!("CARGO_MANIFEST_DIR");
    let manifest_path = std::path::Path::new(manifest_dir).join("Cargo").with_extension("toml");
    let bytes = std::fs::read(&manifest_path).unwrap();
    let toml: toml::Value = toml::from_slice(&bytes).unwrap();

    // Find the `examples` table within the `toml::Value` to find all example names.
    let examples = toml["example"].as_array().expect("failed to retrieve example array");
    for example in examples {
        let name = example["name"].as_str().expect("failed to retrieve example name");

        // For each example, invoke a cargo sub-process to run the example.
        let mut child = std::process::Command::new("cargo")
            .arg("run")
            .arg("--example")
            .arg(&name)
            .spawn()
            .expect("failed to spawn `cargo run --example` process");

        // Allow each example to run for 3 secs each.
        std::thread::sleep(std::time::Duration::from_secs(3));

        // Kill the example and retrieve any output.
        child.kill().ok();
        let output = child.wait_with_output().expect("failed to wait for child process");

        // If the example wrote to `stderr` it must have failed.
        if !output.stderr.is_empty() {
            panic!("example {} wrote to stderr: {:?}", name, output);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Ensure we capture errors from the stomp and db connections.<commit_after><|endoftext|>


<commit_before><commit_msg>c_types: allow lowercase type identifiers<commit_after><|endoftext|>


<commit_before><commit_msg>start new<commit_after>// pub fn find_kth_number(n: i32, k: i32) -> i32 {
//     let mut count = k;
//     for l in 1.. {
//         count -= 1;
//         if count == 0 {
//             return l;
//         }

//         let result = inner_rec(l, n, &mut count);
//         if result != 0 {
//             return result;
//         };
//     }
//     0
// }

// fn inner_rec(head: i32, k: i32, count: &mut i32) -> i32 {
//     if head * 10 < n {
//         0
//     }
//     0
// }

pub fn find_kth_number(n: i32, k: i32) -> i32 {
    let mut count = k;
    return test_inner_rec(1 as u64, &(n as u64), &mut count);
}

fn test_inner_rec(head: u64, n: &u64, count: &mut i32) -> i32 {
    if head > *n {
        return 0;
    }
    //print!("{:?} ", head);
    *count -= 1;

    if *count == 0 {
        return head as i32;
    }

    let re = test_inner_rec(head * 10, n, count);
    if re != 0 {
        return re;
    } else {
        if head % 10 == 9 {
            return 0;
        }
        return test_inner_rec(head + 1, n, count);
    }
}

fn main() {
    let testcase0 = 13;
    let k = 2;
    //dbg!(test_inner_rec(1, &testcase0, &mut k));
    //dbg!(find_kth_number(testcase0, k)); // => 10

    let testcase1 = 100;
    let k = 90;
    //dbg!(find_kth_number(testcase1, k)); // => 9

    let testcase1 = 681692778;
    let k = 351251360;
    //dbg!(find_kth_number(testcase1, k)); // => 416126219

    let testcase1 = 957747794;
    let k = 424238336;
    dbg!(find_kth_number(testcase1, k)); // => 416126219
}
<|endoftext|>


<commit_before><commit_msg>style: convert NS_STYLE_WINDOW_SHADOW_* to an enum class in nsStyleConsts.h<commit_after><|endoftext|>


<commit_before><commit_msg>start rust version<commit_after>#[derive(Debug)]
struct Tree {
    enter: Node,
    left: Option<Box<Tree>>,
    right: Option<Box<Tree>>,
}

//for red-black tree
#[derive(Debug)]
enum Color {
    Black,
    Red,
    White,
}

#[derive(Debug)]
struct Node {
    val: i32,
    color: Color,
}

impl Node {
    fn new(v: &i32) -> Node {
        Node {
            val: *v,
            color: Color::White,
        }
    }
}

impl Tree {
    fn new(v: &i32) -> Tree {
        Tree {
            enter: Node::new(v),
            left: None,
            right: None,
        }
    }

    fn insert(&mut self, v: &i32) {
        let target = if *v > self.enter.val {
            &mut self.right
        } else {
            &mut self.left
        };

        match target {
            Some(next) => next.insert(v),
            None => {
                let new_node = Node::new(v);
                let new_tree = Tree {
                    enter: new_node,
                    left: None,
                    right: None,
                };
                *target = Some(Box::new(new_tree));
            }
        }
    }
}

fn main() {}
<|endoftext|>