<commit_before><commit_msg>Added an example for message-box<commit_after>extern crate sdl2;

use sdl2::pixels::Color;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;
use ::sdl2::messagebox::*;

pub fn main() {
    let sdl_context = sdl2::init().unwrap();
    let video_subsystem = sdl_context.video().unwrap();

    let window = video_subsystem.window("rust-sdl2 demo: Video", 800, 600)
        .position_centered()
        .opengl()
        .build()
        .unwrap();

    let mut renderer = window.renderer().build().unwrap();

    renderer.set_draw_color(Color::RGB(255, 0, 0));
    renderer.clear();
    renderer.present();
    let mut event_pump = sdl_context.event_pump().unwrap();

    'running: loop {
        for event in event_pump.poll_iter() {
            match event {
                Event::Quit {..} | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => {
                    let res =
                        show_simple_message_box(MESSAGEBOX_ERROR,
                                                "Some title",
                                                "Some information inside the window",
                                                renderer.window());
                    match res {
                        Ok(_) => {}
                        Err(ShowMessageError::SdlError(string)) => {
                            println!("An error occured : {}",string);
                        }
                        Err(_) => println!("Unexpected error occured !"),
                    };
                    break 'running
                },
                _ => {}
            }
        }
        // The rest of the game loop goes here...
    }
}
<|endoftext|>


<commit_before><commit_msg>Regression test for incremental treatment of rustc_scalar_valid_range_{start,end}.<commit_after>// We should not see the unused_attributes lint fire for
// rustc_layout_scalar_valid_range_start, but with this bug we are
// seeing it fire (on subsequent runs) if incremental compilation is
// enabled.

// revisions: rpass1 rpass2
// compile-pass

#![feature(rustc_attrs)]
#![deny(unused_attributes)]

#[rustc_layout_scalar_valid_range_start(10)]
#[rustc_layout_scalar_valid_range_end(30)]
struct RestrictedRange(u32);
const OKAY_RANGE: RestrictedRange = unsafe { RestrictedRange(20) };

fn main() {
    OKAY_RANGE.0;
}
<|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.

use std::iter;

use super::{LinkerFlavor, Target, TargetOptions, PanicStrategy};

pub fn target() -> Result<Target, String> {
    const PRE_LINK_ARGS: &[&str] = &[
        "-Wl,--as-needed",
        "-Wl,-z,noexecstack",
        "-m64",
         "-fuse-ld=gold",
         "-nostdlib",
         "-shared",
         "-Wl,-e,sgx_entry",
         "-Wl,-Bstatic",
         "-Wl,--gc-sections",
         "-Wl,-z,text",
         "-Wl,-z,norelro",
         "-Wl,--rosegment",
         "-Wl,--no-undefined",
         "-Wl,--error-unresolved-symbols",
         "-Wl,--no-undefined-version",
         "-Wl,-Bsymbolic",
         "-Wl,--export-dynamic",
    ];
    const EXPORT_SYMBOLS: &[&str] = &[
        "sgx_entry",
        "HEAP_BASE",
        "HEAP_SIZE",
        "RELA",
        "RELACOUNT",
        "ENCLAVE_SIZE",
        "CFGDATA_BASE",
        "DEBUG",
    ];
    let opts = TargetOptions {
        dynamic_linking: false,
        executables: true,
        linker_is_gnu: true,
        max_atomic_width: Some(64),
        panic_strategy: PanicStrategy::Abort,
        cpu: "x86-64".into(),
        position_independent_executables: true,
        pre_link_args: iter::once(
                (LinkerFlavor::Gcc, PRE_LINK_ARGS.iter().cloned().map(String::from).collect())
        ).collect(),
        override_export_symbols: Some(EXPORT_SYMBOLS.iter().cloned().map(String::from).collect()),
        ..Default::default()
    };
    Ok(Target {
        llvm_target: "x86_64-unknown-linux-gnu".into(),
        target_endian: "little".into(),
        target_pointer_width: "64".into(),
        target_c_int_width: "32".into(),
        target_os: "unknown".into(),
        target_env: "sgx".into(),
        target_vendor: "fortanix".into(),
        data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".into(),
        arch: "x86_64".into(),
        linker_flavor: LinkerFlavor::Gcc,
        options: opts,
    })
}
<commit_msg>Rollup merge of #56710 - jethrogb:jb/sgx-target-features, r=alexcrichton<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.

use std::iter;

use super::{LinkerFlavor, Target, TargetOptions, PanicStrategy};

pub fn target() -> Result<Target, String> {
    const PRE_LINK_ARGS: &[&str] = &[
        "-Wl,--as-needed",
        "-Wl,-z,noexecstack",
        "-m64",
         "-fuse-ld=gold",
         "-nostdlib",
         "-shared",
         "-Wl,-e,sgx_entry",
         "-Wl,-Bstatic",
         "-Wl,--gc-sections",
         "-Wl,-z,text",
         "-Wl,-z,norelro",
         "-Wl,--rosegment",
         "-Wl,--no-undefined",
         "-Wl,--error-unresolved-symbols",
         "-Wl,--no-undefined-version",
         "-Wl,-Bsymbolic",
         "-Wl,--export-dynamic",
    ];
    const EXPORT_SYMBOLS: &[&str] = &[
        "sgx_entry",
        "HEAP_BASE",
        "HEAP_SIZE",
        "RELA",
        "RELACOUNT",
        "ENCLAVE_SIZE",
        "CFGDATA_BASE",
        "DEBUG",
    ];
    let opts = TargetOptions {
        dynamic_linking: false,
        executables: true,
        linker_is_gnu: true,
        max_atomic_width: Some(64),
        panic_strategy: PanicStrategy::Abort,
        cpu: "x86-64".into(),
        features: "+rdrnd,+rdseed".into(),
        position_independent_executables: true,
        pre_link_args: iter::once(
                (LinkerFlavor::Gcc, PRE_LINK_ARGS.iter().cloned().map(String::from).collect())
        ).collect(),
        override_export_symbols: Some(EXPORT_SYMBOLS.iter().cloned().map(String::from).collect()),
        ..Default::default()
    };
    Ok(Target {
        llvm_target: "x86_64-unknown-linux-gnu".into(),
        target_endian: "little".into(),
        target_pointer_width: "64".into(),
        target_c_int_width: "32".into(),
        target_os: "unknown".into(),
        target_env: "sgx".into(),
        target_vendor: "fortanix".into(),
        data_layout: "e-m:e-i64:64-f80:128-n8:16:32:64-S128".into(),
        arch: "x86_64".into(),
        linker_flavor: LinkerFlavor::Gcc,
        options: opts,
    })
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate glium;

fn main() {
    use glium::{Api, DisplayBuild, Profile, Version};
    use glium::backend::Facade;
    use glium::glutin;

    // building the display, ie. the main object
    let display = glutin::WindowBuilder::new()
        .with_visibility(false)
        .build_glium()
        .unwrap();

    let version = *display.get_opengl_version();
    let api = match version {
        Version(Api::Gl, _, _) => "OpenGL",
        Version(Api::GlEs, _, _) => "OpenGL ES"
    };

    println!("{} context verson: {}", api, display.get_opengl_vendor_string());

    print!("{} context flags:", api);
    if display.is_forward_compatible() {
        print!(" forward-compatible");
    }
    if display.is_debug() {
        print!(" debug");
    }
    if display.is_robust() {
        print!(" robustness");
    }
    print!("\n");

    if version >= Version(Api::Gl, 3, 2) {
        println!("{} profile mask: {}", api,
                 match display.get_opengl_profile() {
                     Some(Profile::Core) => "core",
                     Some(Profile::Compatibility) => "compatibility",
                     None => "unknown"
                 });
    }

    println!("{} robustness strategy: {}", api,
             if display.is_context_loss_possible() {
                 "lose"
             } else {
                 "none"
             });

    println!("{} context renderer: {}", api, display.get_opengl_renderer_string());
    println!("{} context vendor: {}", api, display.get_opengl_vendor_string());
}
<commit_msg>Small bug fix to info example<commit_after>#[macro_use]
extern crate glium;

fn main() {
    use glium::{Api, DisplayBuild, Profile, Version};
    use glium::glutin;

    // building the display, ie. the main object
    let display = glutin::WindowBuilder::new()
        .with_visibility(false)
        .build_glium()
        .unwrap();

    let version = *display.get_opengl_version();
    let api = match version {
        Version(Api::Gl, _, _) => "OpenGL",
        Version(Api::GlEs, _, _) => "OpenGL ES"
    };

    println!("{} context verson: {}", api, display.get_opengl_version_string());

    print!("{} context flags:", api);
    if display.is_forward_compatible() {
        print!(" forward-compatible");
    }
    if display.is_debug() {
        print!(" debug");
    }
    if display.is_robust() {
        print!(" robustness");
    }
    print!("\n");

    if version >= Version(Api::Gl, 3, 2) {
        println!("{} profile mask: {}", api,
                 match display.get_opengl_profile() {
                     Some(Profile::Core) => "core",
                     Some(Profile::Compatibility) => "compatibility",
                     None => "unknown"
                 });
    }

    println!("{} robustness strategy: {}", api,
             if display.is_context_loss_possible() {
                 "lose"
             } else {
                 "none"
             });

    println!("{} context renderer: {}", api, display.get_opengl_renderer_string());
    println!("{} context vendor: {}", api, display.get_opengl_vendor_string());
}
<|endoftext|>


<commit_before><commit_msg>Embolden more in the stats command<commit_after><|endoftext|>


<commit_before><commit_msg>fix windows version for command refactor<commit_after><|endoftext|>


<commit_before><commit_msg>Auto merge of #28565 - apasel422:issue-28561, r=Manishearth<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.

#[derive(Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct Array<T> {
    f00: [T; 00],
    f01: [T; 01],
    f02: [T; 02],
    f03: [T; 03],
    f04: [T; 04],
    f05: [T; 05],
    f06: [T; 06],
    f07: [T; 07],
    f08: [T; 08],
    f09: [T; 09],
    f10: [T; 10],
    f11: [T; 11],
    f12: [T; 12],
    f13: [T; 13],
    f14: [T; 14],
    f15: [T; 15],
    f16: [T; 16],
    f17: [T; 17],
    f18: [T; 18],
    f19: [T; 19],
    f20: [T; 20],
    f21: [T; 21],
    f22: [T; 22],
    f23: [T; 23],
    f24: [T; 24],
    f25: [T; 25],
    f26: [T; 26],
    f27: [T; 27],
    f28: [T; 28],
    f29: [T; 29],
    f30: [T; 30],
    f31: [T; 31],
    f32: [T; 32],
}

// FIXME(#7622): merge with `Array` once `[T; N]: Clone` where `T: Clone`
#[derive(Clone, Copy)]
struct CopyArray<T: Copy> {
    f00: [T; 00],
    f01: [T; 01],
    f02: [T; 02],
    f03: [T; 03],
    f04: [T; 04],
    f05: [T; 05],
    f06: [T; 06],
    f07: [T; 07],
    f08: [T; 08],
    f09: [T; 09],
    f10: [T; 10],
    f11: [T; 11],
    f12: [T; 12],
    f13: [T; 13],
    f14: [T; 14],
    f15: [T; 15],
    f16: [T; 16],
    f17: [T; 17],
    f18: [T; 18],
    f19: [T; 19],
    f20: [T; 20],
    f21: [T; 21],
    f22: [T; 22],
    f23: [T; 23],
    f24: [T; 24],
    f25: [T; 25],
    f26: [T; 26],
    f27: [T; 27],
    f28: [T; 28],
    f29: [T; 29],
    f30: [T; 30],
    f31: [T; 31],
    f32: [T; 32],
}

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct Fn<A, B, C, D, E, F, G, H, I, J, K, L> {
    f00: fn(),
    f01: fn(A),
    f02: fn(A, B),
    f03: fn(A, B, C),
    f04: fn(A, B, C, D),
    f05: fn(A, B, C, D, E),
    f06: fn(A, B, C, D, E, F),
    f07: fn(A, B, C, D, E, F, G),
    f08: fn(A, B, C, D, E, F, G, H),
    f09: fn(A, B, C, D, E, F, G, H, I),
    f10: fn(A, B, C, D, E, F, G, H, I, J),
    f11: fn(A, B, C, D, E, F, G, H, I, J, K),
    f12: fn(A, B, C, D, E, F, G, H, I, J, K, L),
}

#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
struct Tuple<A, B, C, D, E, F, G, H, I, J, K, L> {
    f00: (),
    f01: (A),
    f02: (A, B),
    f03: (A, B, C),
    f04: (A, B, C, D),
    f05: (A, B, C, D, E),
    f06: (A, B, C, D, E, F),
    f07: (A, B, C, D, E, F, G),
    f08: (A, B, C, D, E, F, G, H),
    f09: (A, B, C, D, E, F, G, H, I),
    f10: (A, B, C, D, E, F, G, H, I, J),
    f11: (A, B, C, D, E, F, G, H, I, J, K),
    f12: (A, B, C, D, E, F, G, H, I, J, K, L),
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add regression test for #48551<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.

use std::ops::{Mul, MulAssign};

pub trait ClosedMul<Right>: Sized + Mul<Right, Output = Self> + MulAssign<Right> {}
impl<T, Right> ClosedMul<Right> for T
where
    T: Mul<Right, Output = T> + MulAssign<Right>,
{
}

pub trait InnerSpace: ClosedMul<<Self as InnerSpace>::Real> {
    type Real;
}

pub trait FiniteDimVectorSpace: ClosedMul<<Self as FiniteDimVectorSpace>::Field> {
    type Field;
}

pub trait FiniteDimInnerSpace
    : InnerSpace + FiniteDimVectorSpace<Field = <Self as InnerSpace>::Real> {
}

pub trait EuclideanSpace: ClosedMul<<Self as EuclideanSpace>::Real> {
    type Coordinates: FiniteDimInnerSpace<Real = Self::Real>
        + Mul<Self::Real, Output = Self::Coordinates>
        + MulAssign<Self::Real>;

    type Real;
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Import householder reflection from 'arnoldi' branch<commit_after>use super::*;
use crate::{inner::*, norm::*};
use num_traits::Zero;

/// Iterative orthogonalizer using Householder reflection
#[derive(Debug, Clone)]
pub struct Householder<A: Scalar> {
    /// Dimension of orthogonalizer
    dim: usize,

    /// Store Householder reflector.
    ///
    /// The coefficient is copied into another array, and this does not contain
    v: Vec<Array1<A>>,
}

impl<A: Scalar> Householder<A> {
    /// Create a new orthogonalizer
    pub fn new(dim: usize) -> Self {
        Householder { dim, v: Vec::new() }
    }

    /// Take a Reflection `P = I - 2ww^T`
    fn reflect<S: DataMut<Elem = A>>(&self, k: usize, a: &mut ArrayBase<S, Ix1>) {
        assert!(k < self.v.len());
        assert_eq!(a.len(), self.dim, "Input array size mismaches to the dimension");

        let w = self.v[k].slice(s![k..]);
        let mut a_slice = a.slice_mut(s![k..]);
        let c = A::from(2.0).unwrap() * w.inner(&a_slice);
        for l in 0..self.dim - k {
            a_slice[l] -= c * w[l];
        }
    }
}

impl<A: Scalar + Lapack> Orthogonalizer for Householder<A> {
    type Elem = A;

    fn dim(&self) -> usize {
        self.dim
    }

    fn len(&self) -> usize {
        self.v.len()
    }

    fn orthogonalize<S>(&self, a: &mut ArrayBase<S, Ix1>) -> A::Real
    where
        S: DataMut<Elem = A>,
    {
        for k in 0..self.len() {
            self.reflect(k, a);
        }
        if self.is_full() {
            return Zero::zero();
        }
        // residual norm
        a.slice(s![self.len()..]).norm_l2()
    }

    fn append<S>(&mut self, mut a: ArrayBase<S, Ix1>, rtol: A::Real) -> Result<Array1<A>, Array1<A>>
    where
        S: DataMut<Elem = A>,
    {
        assert_eq!(a.len(), self.dim);
        let k = self.len();
        let alpha = self.orthogonalize(&mut a);
        let mut coef = Array::zeros(k + 1);
        for i in 0..k {
            coef[i] = a[i];
        }
        if alpha < rtol {
            // linearly dependent
            coef[k] = A::from_real(alpha);
            return Err(coef);
        }

        // Add reflector
        assert!(k < a.len()); // this must hold because `alpha == 0` if k >= a.len()
        let alpha = if a[k].abs() > Zero::zero() {
            a[k].mul_real(alpha / a[k].abs())
        } else {
            A::from_real(alpha)
        };
        coef[k] = alpha;

        a[k] -= alpha;
        let norm = a.slice(s![k..]).norm_l2();
        azip!(mut a (a.slice_mut(s![..k])) in { *a = Zero::zero() }); // this can be omitted
        azip!(mut a (a.slice_mut(s![k..])) in { *a = a.div_real(norm) });
        self.v.push(a.into_owned());
        Ok(coef)
    }

    fn get_q(&self) -> Q<A> {
        assert!(self.len() > 0);
        let mut a = Array::zeros((self.dim(), self.len()));
        for (i, mut col) in a.axis_iter_mut(Axis(1)).enumerate() {
            col[i] = A::one();
            for l in (0..self.len()).rev() {
                self.reflect(l, &mut col);
            }
        }
        a
    }
}
<|endoftext|>


<commit_before><commit_msg>Initial Display struct and test<commit_after><|endoftext|>


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

use cast::transmute;
use libc::{c_char, c_void, size_t, STDERR_FILENO};
use io;
use io::{Writer, WriterUtil};
use option::{Option, None, Some};
use uint;
use str;
use str::{OwnedStr, StrSlice};
use sys;
use unstable::raw;
use vec::ImmutableVector;

#[allow(non_camel_case_types)]
type rust_task = c_void;

pub static FROZEN_BIT: uint = 1 << (uint::bits - 1);
pub static MUT_BIT: uint = 1 << (uint::bits - 2);
static ALL_BITS: uint = FROZEN_BIT | MUT_BIT;

#[deriving(Eq)]
struct BorrowRecord {
    box: *mut raw::Box<()>,
    file: *c_char,
    line: size_t
}

fn try_take_task_borrow_list() -> Option<~[BorrowRecord]> {
    unsafe {
        let cur_task: *rust_task = rust_try_get_task();
        if cur_task.is_not_null() {
            let ptr = rust_take_task_borrow_list(cur_task);
            if ptr.is_null() {
                None
            } else {
                let v: ~[BorrowRecord] = transmute(ptr);
                Some(v)
            }
        } else {
            None
        }
    }
}

fn swap_task_borrow_list(f: &fn(~[BorrowRecord]) -> ~[BorrowRecord]) {
    unsafe {
        let cur_task: *rust_task = rust_try_get_task();
        if cur_task.is_not_null() {
            let mut borrow_list: ~[BorrowRecord] = {
                let ptr = rust_take_task_borrow_list(cur_task);
                if ptr.is_null() { ~[] } else { transmute(ptr) }
            };
            borrow_list = f(borrow_list);
            rust_set_task_borrow_list(cur_task, transmute(borrow_list));
        }
    }
}

pub unsafe fn clear_task_borrow_list() {
    // pub because it is used by the box annihilator.
    let _ = try_take_task_borrow_list();
}

unsafe fn fail_borrowed(box: *mut raw::Box<()>, file: *c_char, line: size_t) {
    debug_borrow("fail_borrowed: ", box, 0, 0, file, line);

    match try_take_task_borrow_list() {
        None => { // not recording borrows
            let msg = "borrowed";
            do msg.as_c_str |msg_p| {
                sys::begin_unwind_(msg_p as *c_char, file, line);
            }
        }
        Some(borrow_list) => { // recording borrows
            let mut msg = ~"borrowed";
            let mut sep = " at ";
            foreach entry in borrow_list.rev_iter() {
                if entry.box == box {
                    msg.push_str(sep);
                    let filename = str::raw::from_c_str(entry.file);
                    msg.push_str(filename);
                    msg.push_str(fmt!(":%u", entry.line as uint));
                    sep = " and at ";
                }
            }
            do msg.as_c_str |msg_p| {
                sys::begin_unwind_(msg_p as *c_char, file, line)
            }
        }
    }
}

/// Because this code is so perf. sensitive, use a static constant so that
/// debug printouts are compiled out most of the time.
static ENABLE_DEBUG: bool = false;

#[inline]
unsafe fn debug_borrow<T>(tag: &'static str,
                          p: *const T,
                          old_bits: uint,
                          new_bits: uint,
                          filename: *c_char,
                          line: size_t) {
    //! A useful debugging function that prints a pointer + tag + newline
    //! without allocating memory.

    if ENABLE_DEBUG && ::rt::env::get().debug_borrow {
        debug_borrow_slow(tag, p, old_bits, new_bits, filename, line);
    }

    unsafe fn debug_borrow_slow<T>(tag: &'static str,
                                   p: *const T,
                                   old_bits: uint,
                                   new_bits: uint,
                                   filename: *c_char,
                                   line: size_t) {
        let dbg = STDERR_FILENO as io::fd_t;
        dbg.write_str(tag);
        dbg.write_hex(p as uint);
        dbg.write_str(" ");
        dbg.write_hex(old_bits);
        dbg.write_str(" ");
        dbg.write_hex(new_bits);
        dbg.write_str(" ");
        dbg.write_cstr(filename);
        dbg.write_str(":");
        dbg.write_hex(line as uint);
        dbg.write_str("\n");
    }
}

trait DebugPrints {
    fn write_hex(&self, val: uint);
    unsafe fn write_cstr(&self, str: *c_char);
}

impl DebugPrints for io::fd_t {
    fn write_hex(&self, mut i: uint) {
        let letters = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
                       '9', 'a', 'b', 'c', 'd', 'e', 'f'];
        static UINT_NIBBLES: uint = ::uint::bytes << 1;
        let mut buffer = [0_u8, ..UINT_NIBBLES+1];
        let mut c = UINT_NIBBLES;
        while c > 0 {
            c -= 1;
            buffer[c] = letters[i & 0xF] as u8;
            i >>= 4;
        }
        self.write(buffer.slice(0, UINT_NIBBLES));
    }

    unsafe fn write_cstr(&self, p: *c_char) {
        use libc::strlen;
        use vec;

        let len = strlen(p);
        let p: *u8 = transmute(p);
        do vec::raw::buf_as_slice(p, len as uint) |s| {
            self.write(s);
        }
    }
}

#[inline]
pub unsafe fn borrow_as_imm(a: *u8, file: *c_char, line: size_t) -> uint {
    let a = a as *mut raw::Box<()>;
    let old_ref_count = (*a).ref_count;
    let new_ref_count = old_ref_count | FROZEN_BIT;

    debug_borrow("borrow_as_imm:", a, old_ref_count, new_ref_count, file, line);

    if (old_ref_count & MUT_BIT) != 0 {
        fail_borrowed(a, file, line);
    }

    (*a).ref_count = new_ref_count;

    old_ref_count
}

#[inline]
pub unsafe fn borrow_as_mut(a: *u8, file: *c_char, line: size_t) -> uint {
    let a = a as *mut raw::Box<()>;
    let old_ref_count = (*a).ref_count;
    let new_ref_count = old_ref_count | MUT_BIT | FROZEN_BIT;

    debug_borrow("borrow_as_mut:", a, old_ref_count, new_ref_count, file, line);

    if (old_ref_count & (MUT_BIT|FROZEN_BIT)) != 0 {
        fail_borrowed(a, file, line);
    }

    (*a).ref_count = new_ref_count;

    old_ref_count
}

pub unsafe fn record_borrow(a: *u8, old_ref_count: uint,
                            file: *c_char, line: size_t) {
    if (old_ref_count & ALL_BITS) == 0 {
        // was not borrowed before
        let a = a as *mut raw::Box<()>;
        debug_borrow("record_borrow:", a, old_ref_count, 0, file, line);
        do swap_task_borrow_list |borrow_list| {
            let mut borrow_list = borrow_list;
            borrow_list.push(BorrowRecord {box: a, file: file, line: line});
            borrow_list
        }
    }
}

pub unsafe fn unrecord_borrow(a: *u8, old_ref_count: uint,
                              file: *c_char, line: size_t) {
    if (old_ref_count & ALL_BITS) == 0 {
        // was not borrowed before, so we should find the record at
        // the end of the list
        let a = a as *mut raw::Box<()>;
        debug_borrow("unrecord_borrow:", a, old_ref_count, 0, file, line);
        do swap_task_borrow_list |borrow_list| {
            let mut borrow_list = borrow_list;
            assert!(!borrow_list.is_empty());
            let br = borrow_list.pop();
            if br.box != a || br.file != file || br.line != line {
                let err = fmt!("wrong borrow found, br=%?", br);
                do err.as_c_str |msg_p| {
                    sys::begin_unwind_(msg_p as *c_char, file, line)
                }
            }
            borrow_list
        }
    }
}

#[inline]
pub unsafe fn return_to_mut(a: *u8, orig_ref_count: uint,
                            file: *c_char, line: size_t) {
    // Sometimes the box is null, if it is conditionally frozen.
    // See e.g. #4904.
    if !a.is_null() {
        let a = a as *mut raw::Box<()>;
        let old_ref_count = (*a).ref_count;
        let new_ref_count =
            (old_ref_count & !ALL_BITS) | (orig_ref_count & ALL_BITS);

        debug_borrow("return_to_mut:",
                     a, old_ref_count, new_ref_count, file, line);

        (*a).ref_count = new_ref_count;
    }
}

#[inline]
pub unsafe fn check_not_borrowed(a: *u8,
                                 file: *c_char,
                                 line: size_t) {
    let a = a as *mut raw::Box<()>;
    let ref_count = (*a).ref_count;
    debug_borrow("check_not_borrowed:", a, ref_count, 0, file, line);
    if (ref_count & FROZEN_BIT) != 0 {
        fail_borrowed(a, file, line);
    }
}

extern {
    #[rust_stack]
    pub fn rust_take_task_borrow_list(task: *rust_task) -> *c_void;

    #[rust_stack]
    pub fn rust_set_task_borrow_list(task: *rust_task, map: *c_void);

    #[rust_stack]
    pub fn rust_try_get_task() -> *rust_task;
}
<commit_msg>std: minor cleanup<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use cast::transmute;
use libc::{c_char, c_void, size_t, STDERR_FILENO};
use io;
use io::{Writer, WriterUtil};
use option::{Option, None, Some};
use uint;
use str;
use str::{OwnedStr, StrSlice};
use sys;
use unstable::raw;
use vec::ImmutableVector;

#[allow(non_camel_case_types)]
type rust_task = c_void;

pub static FROZEN_BIT: uint = 1 << (uint::bits - 1);
pub static MUT_BIT: uint = 1 << (uint::bits - 2);
static ALL_BITS: uint = FROZEN_BIT | MUT_BIT;

#[deriving(Eq)]
struct BorrowRecord {
    box: *mut raw::Box<()>,
    file: *c_char,
    line: size_t
}

fn try_take_task_borrow_list() -> Option<~[BorrowRecord]> {
    unsafe {
        let cur_task: *rust_task = rust_try_get_task();
        if cur_task.is_not_null() {
            let ptr = rust_take_task_borrow_list(cur_task);
            if ptr.is_null() {
                None
            } else {
                let v: ~[BorrowRecord] = transmute(ptr);
                Some(v)
            }
        } else {
            None
        }
    }
}

fn swap_task_borrow_list(f: &fn(~[BorrowRecord]) -> ~[BorrowRecord]) {
    unsafe {
        let cur_task: *rust_task = rust_try_get_task();
        if cur_task.is_not_null() {
            let mut borrow_list: ~[BorrowRecord] = {
                let ptr = rust_take_task_borrow_list(cur_task);
                if ptr.is_null() { ~[] } else { transmute(ptr) }
            };
            borrow_list = f(borrow_list);
            rust_set_task_borrow_list(cur_task, transmute(borrow_list));
        }
    }
}

pub unsafe fn clear_task_borrow_list() {
    // pub because it is used by the box annihilator.
    let _ = try_take_task_borrow_list();
}

unsafe fn fail_borrowed(box: *mut raw::Box<()>, file: *c_char, line: size_t) {
    debug_borrow("fail_borrowed: ", box, 0, 0, file, line);

    match try_take_task_borrow_list() {
        None => { // not recording borrows
            let msg = "borrowed";
            do msg.as_c_str |msg_p| {
                sys::begin_unwind_(msg_p, file, line);
            }
        }
        Some(borrow_list) => { // recording borrows
            let mut msg = ~"borrowed";
            let mut sep = " at ";
            foreach entry in borrow_list.rev_iter() {
                if entry.box == box {
                    msg.push_str(sep);
                    let filename = str::raw::from_c_str(entry.file);
                    msg.push_str(filename);
                    msg.push_str(fmt!(":%u", entry.line as uint));
                    sep = " and at ";
                }
            }
            do msg.as_c_str |msg_p| {
                sys::begin_unwind_(msg_p, file, line)
            }
        }
    }
}

/// Because this code is so perf. sensitive, use a static constant so that
/// debug printouts are compiled out most of the time.
static ENABLE_DEBUG: bool = false;

#[inline]
unsafe fn debug_borrow<T>(tag: &'static str,
                          p: *const T,
                          old_bits: uint,
                          new_bits: uint,
                          filename: *c_char,
                          line: size_t) {
    //! A useful debugging function that prints a pointer + tag + newline
    //! without allocating memory.

    if ENABLE_DEBUG && ::rt::env::get().debug_borrow {
        debug_borrow_slow(tag, p, old_bits, new_bits, filename, line);
    }

    unsafe fn debug_borrow_slow<T>(tag: &'static str,
                                   p: *const T,
                                   old_bits: uint,
                                   new_bits: uint,
                                   filename: *c_char,
                                   line: size_t) {
        let dbg = STDERR_FILENO as io::fd_t;
        dbg.write_str(tag);
        dbg.write_hex(p as uint);
        dbg.write_str(" ");
        dbg.write_hex(old_bits);
        dbg.write_str(" ");
        dbg.write_hex(new_bits);
        dbg.write_str(" ");
        dbg.write_cstr(filename);
        dbg.write_str(":");
        dbg.write_hex(line as uint);
        dbg.write_str("\n");
    }
}

trait DebugPrints {
    fn write_hex(&self, val: uint);
    unsafe fn write_cstr(&self, str: *c_char);
}

impl DebugPrints for io::fd_t {
    fn write_hex(&self, mut i: uint) {
        let letters = ['0', '1', '2', '3', '4', '5', '6', '7', '8',
                       '9', 'a', 'b', 'c', 'd', 'e', 'f'];
        static UINT_NIBBLES: uint = ::uint::bytes << 1;
        let mut buffer = [0_u8, ..UINT_NIBBLES+1];
        let mut c = UINT_NIBBLES;
        while c > 0 {
            c -= 1;
            buffer[c] = letters[i & 0xF] as u8;
            i >>= 4;
        }
        self.write(buffer.slice(0, UINT_NIBBLES));
    }

    unsafe fn write_cstr(&self, p: *c_char) {
        use libc::strlen;
        use vec;

        let len = strlen(p);
        let p: *u8 = transmute(p);
        do vec::raw::buf_as_slice(p, len as uint) |s| {
            self.write(s);
        }
    }
}

#[inline]
pub unsafe fn borrow_as_imm(a: *u8, file: *c_char, line: size_t) -> uint {
    let a = a as *mut raw::Box<()>;
    let old_ref_count = (*a).ref_count;
    let new_ref_count = old_ref_count | FROZEN_BIT;

    debug_borrow("borrow_as_imm:", a, old_ref_count, new_ref_count, file, line);

    if (old_ref_count & MUT_BIT) != 0 {
        fail_borrowed(a, file, line);
    }

    (*a).ref_count = new_ref_count;

    old_ref_count
}

#[inline]
pub unsafe fn borrow_as_mut(a: *u8, file: *c_char, line: size_t) -> uint {
    let a = a as *mut raw::Box<()>;
    let old_ref_count = (*a).ref_count;
    let new_ref_count = old_ref_count | MUT_BIT | FROZEN_BIT;

    debug_borrow("borrow_as_mut:", a, old_ref_count, new_ref_count, file, line);

    if (old_ref_count & (MUT_BIT|FROZEN_BIT)) != 0 {
        fail_borrowed(a, file, line);
    }

    (*a).ref_count = new_ref_count;

    old_ref_count
}

pub unsafe fn record_borrow(a: *u8, old_ref_count: uint,
                            file: *c_char, line: size_t) {
    if (old_ref_count & ALL_BITS) == 0 {
        // was not borrowed before
        let a = a as *mut raw::Box<()>;
        debug_borrow("record_borrow:", a, old_ref_count, 0, file, line);
        do swap_task_borrow_list |borrow_list| {
            let mut borrow_list = borrow_list;
            borrow_list.push(BorrowRecord {box: a, file: file, line: line});
            borrow_list
        }
    }
}

pub unsafe fn unrecord_borrow(a: *u8, old_ref_count: uint,
                              file: *c_char, line: size_t) {
    if (old_ref_count & ALL_BITS) == 0 {
        // was not borrowed before, so we should find the record at
        // the end of the list
        let a = a as *mut raw::Box<()>;
        debug_borrow("unrecord_borrow:", a, old_ref_count, 0, file, line);
        do swap_task_borrow_list |borrow_list| {
            let mut borrow_list = borrow_list;
            assert!(!borrow_list.is_empty());
            let br = borrow_list.pop();
            if br.box != a || br.file != file || br.line != line {
                let err = fmt!("wrong borrow found, br=%?", br);
                do err.as_c_str |msg_p| {
                    sys::begin_unwind_(msg_p, file, line)
                }
            }
            borrow_list
        }
    }
}

#[inline]
pub unsafe fn return_to_mut(a: *u8, orig_ref_count: uint,
                            file: *c_char, line: size_t) {
    // Sometimes the box is null, if it is conditionally frozen.
    // See e.g. #4904.
    if !a.is_null() {
        let a = a as *mut raw::Box<()>;
        let old_ref_count = (*a).ref_count;
        let new_ref_count =
            (old_ref_count & !ALL_BITS) | (orig_ref_count & ALL_BITS);

        debug_borrow("return_to_mut:",
                     a, old_ref_count, new_ref_count, file, line);

        (*a).ref_count = new_ref_count;
    }
}

#[inline]
pub unsafe fn check_not_borrowed(a: *u8,
                                 file: *c_char,
                                 line: size_t) {
    let a = a as *mut raw::Box<()>;
    let ref_count = (*a).ref_count;
    debug_borrow("check_not_borrowed:", a, ref_count, 0, file, line);
    if (ref_count & FROZEN_BIT) != 0 {
        fail_borrowed(a, file, line);
    }
}

extern {
    #[rust_stack]
    pub fn rust_take_task_borrow_list(task: *rust_task) -> *c_void;

    #[rust_stack]
    pub fn rust_set_task_borrow_list(task: *rust_task, map: *c_void);

    #[rust_stack]
    pub fn rust_try_get_task() -> *rust_task;
}
<|endoftext|>


<commit_before><commit_msg>Implement decrypt.<commit_after><|endoftext|>


<commit_before>extern crate getopts;

use file::File;
use column::Column;
use column::Column::*;
use term::dimensions;

use std::ascii::AsciiExt;

pub enum SortField {
    Unsorted, Name, Extension, Size, FileInode
}

impl SortField {
    fn from_word(word: String) -> SortField {
        match word.as_slice() {
            "name"  => SortField::Name,
            "size"  => SortField::Size,
            "ext"   => SortField::Extension,
            "none"  => SortField::Unsorted,
            "inode" => SortField::FileInode,
            _       => panic!("Invalid sorting order"),
        }
    }
}

pub enum View {
    Details(Vec<Column>),
    Lines,
    Grid(bool, uint),
}

pub struct Options {
    pub show_invisibles: bool,
    pub sort_field: SortField,
    pub reverse: bool,
    pub dirs: Vec<String>,
    pub view: View,
    pub header: bool,
}

impl Options {
    pub fn getopts(args: Vec<String>) -> Result<Options, getopts::Fail_> {
        let opts = &[
            getopts::optflag("1", "oneline", "display one entry per line"),
            getopts::optflag("a", "all", "show dot-files"),
            getopts::optflag("b", "binary", "use binary prefixes in file sizes"),
            getopts::optflag("g", "group", "show group as well as user"),
            getopts::optflag("h", "header", "show a header row at the top"),
            getopts::optflag("H", "links", "show number of hard links"),
            getopts::optflag("l", "long", "display extended details and attributes"),
            getopts::optflag("i", "inode", "show each file's inode number"),
            getopts::optflag("r", "reverse", "reverse order of files"),
            getopts::optopt("s", "sort", "field to sort by", "WORD"),
            getopts::optflag("S", "blocks", "show number of file system blocks"),
            getopts::optflag("x", "across", "sort multi-column view entries across"),
        ];

        match getopts::getopts(args.tail(), opts) {
            Err(f) => Err(f),
            Ok(matches) => Ok(Options {
                show_invisibles: matches.opt_present("all"),
                reverse: matches.opt_present("reverse"),
                header: matches.opt_present("header"),
                sort_field: matches.opt_str("sort").map(|word| SortField::from_word(word)).unwrap_or(SortField::Name),
                dirs: if matches.free.is_empty() { vec![ ".".to_string() ] } else { matches.free.clone() },
                view: Options::view(matches),
            })
        }
    }

    fn view(matches: getopts::Matches) -> View {
        if matches.opt_present("long") {
            View::Details(Options::columns(matches))
        }
        else if matches.opt_present("oneline") {
            View::Lines
        }
        else {
            match dimensions() {
                None => View::Lines,
                Some((width, _)) => View::Grid(matches.opt_present("across"), width),
            }
        }
    }

    fn columns(matches: getopts::Matches) -> Vec<Column> {
        let mut columns = vec![];

        if matches.opt_present("inode") {
            columns.push(Inode);
        }

        columns.push(Permissions);

        if matches.opt_present("links") {
            columns.push(HardLinks);
        }

        columns.push(FileSize(matches.opt_present("binary")));

        if matches.opt_present("blocks") {
            columns.push(Blocks);
        }

        columns.push(User);

        if matches.opt_present("group") {
            columns.push(Group);
        }

        columns.push(FileName);

        return columns;
    }

    fn should_display(&self, f: &File) -> bool {
        if self.show_invisibles {
            true
        } else {
            !f.name.as_slice().starts_with(".")
        }
    }

    pub fn transform_files<'a>(&self, unordered_files: &'a Vec<File<'a>>) -> Vec<&'a File<'a>> {
        let mut files: Vec<&'a File<'a>> = unordered_files.iter()
            .filter(|&f| self.should_display(f))
            .collect();

        match self.sort_field {
            SortField::Unsorted => {},
            SortField::Name => files.sort_by(|a, b| a.parts.cmp(&b.parts)),
            SortField::Size => files.sort_by(|a, b| a.stat.size.cmp(&b.stat.size)),
            SortField::FileInode => files.sort_by(|a, b| a.stat.unstable.inode.cmp(&b.stat.unstable.inode)),
            SortField::Extension => files.sort_by(|a, b| {
                let exts = a.ext.clone().map(|e| e.to_ascii_lower()).cmp(&b.ext.clone().map(|e| e.to_ascii_lower()));
                let names = a.name.to_ascii_lower().cmp(&b.name.to_ascii_lower());
                exts.cmp(&names)
            }),
        }

        if self.reverse {
            files.reverse();
        }

        return files;
    }
}
<commit_msg>Add some pointers<commit_after>extern crate getopts;

use file::File;
use column::Column;
use column::Column::*;
use term::dimensions;

use std::ascii::AsciiExt;

pub enum SortField {
    Unsorted, Name, Extension, Size, FileInode
}

impl SortField {
    fn from_word(word: String) -> SortField {
        match word.as_slice() {
            "name"  => SortField::Name,
            "size"  => SortField::Size,
            "ext"   => SortField::Extension,
            "none"  => SortField::Unsorted,
            "inode" => SortField::FileInode,
            _       => panic!("Invalid sorting order"),
        }
    }
}

pub enum View {
    Details(Vec<Column>),
    Lines,
    Grid(bool, uint),
}

pub struct Options {
    pub show_invisibles: bool,
    pub sort_field: SortField,
    pub reverse: bool,
    pub dirs: Vec<String>,
    pub view: View,
    pub header: bool,
}

impl Options {
    pub fn getopts(args: Vec<String>) -> Result<Options, getopts::Fail_> {
        let opts = &[
            getopts::optflag("1", "oneline", "display one entry per line"),
            getopts::optflag("a", "all", "show dot-files"),
            getopts::optflag("b", "binary", "use binary prefixes in file sizes"),
            getopts::optflag("g", "group", "show group as well as user"),
            getopts::optflag("h", "header", "show a header row at the top"),
            getopts::optflag("H", "links", "show number of hard links"),
            getopts::optflag("l", "long", "display extended details and attributes"),
            getopts::optflag("i", "inode", "show each file's inode number"),
            getopts::optflag("r", "reverse", "reverse order of files"),
            getopts::optopt("s", "sort", "field to sort by", "WORD"),
            getopts::optflag("S", "blocks", "show number of file system blocks"),
            getopts::optflag("x", "across", "sort multi-column view entries across"),
        ];

        match getopts::getopts(args.tail(), opts) {
            Err(f) => Err(f),
            Ok(ref matches) => Ok(Options {
                show_invisibles: matches.opt_present("all"),
                reverse: matches.opt_present("reverse"),
                header: matches.opt_present("header"),
                sort_field: matches.opt_str("sort").map(|word| SortField::from_word(word)).unwrap_or(SortField::Name),
                dirs: if matches.free.is_empty() { vec![ ".".to_string() ] } else { matches.free.clone() },
                view: Options::view(matches),
            })
        }
    }

    fn view(matches: &getopts::Matches) -> View {
        if matches.opt_present("long") {
            View::Details(Options::columns(matches))
        }
        else if matches.opt_present("oneline") {
            View::Lines
        }
        else {
            match dimensions() {
                None => View::Lines,
                Some((width, _)) => View::Grid(matches.opt_present("across"), width),
            }
        }
    }

    fn columns(matches: &getopts::Matches) -> Vec<Column> {
        let mut columns = vec![];

        if matches.opt_present("inode") {
            columns.push(Inode);
        }

        columns.push(Permissions);

        if matches.opt_present("links") {
            columns.push(HardLinks);
        }

        columns.push(FileSize(matches.opt_present("binary")));

        if matches.opt_present("blocks") {
            columns.push(Blocks);
        }

        columns.push(User);

        if matches.opt_present("group") {
            columns.push(Group);
        }

        columns.push(FileName);

        return columns;
    }

    fn should_display(&self, f: &File) -> bool {
        if self.show_invisibles {
            true
        } else {
            !f.name.as_slice().starts_with(".")
        }
    }

    pub fn transform_files<'a>(&self, unordered_files: &'a Vec<File<'a>>) -> Vec<&'a File<'a>> {
        let mut files: Vec<&'a File<'a>> = unordered_files.iter()
            .filter(|&f| self.should_display(f))
            .collect();

        match self.sort_field {
            SortField::Unsorted => {},
            SortField::Name => files.sort_by(|a, b| a.parts.cmp(&b.parts)),
            SortField::Size => files.sort_by(|a, b| a.stat.size.cmp(&b.stat.size)),
            SortField::FileInode => files.sort_by(|a, b| a.stat.unstable.inode.cmp(&b.stat.unstable.inode)),
            SortField::Extension => files.sort_by(|a, b| {
                let exts = a.ext.clone().map(|e| e.to_ascii_lower()).cmp(&b.ext.clone().map(|e| e.to_ascii_lower()));
                let names = a.name.to_ascii_lower().cmp(&b.name.to_ascii_lower());
                exts.cmp(&names)
            }),
        }

        if self.reverse {
            files.reverse();
        }

        return files;
    }
}
<|endoftext|>


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

// xfail-fast

extern mod extra;

use extra::tempfile;
use std::io::WriterUtil;
use std::io;
use std::os;
use std::uint;

pub fn main() {
    let dir = tempfile::mkdtemp(&Path("."), "").unwrap();
    let path = dir.with_filename("file");

    {
        match io::file_writer(&path, [io::Create, io::Truncate]) {
            Err(ref e) => fail!(e.clone()),
            Ok(f) => {
                for uint::range(0, 1000) |_i| {
                    f.write_u8(0);
                }
            }
        }
    }

    assert!(path.exists());
    assert_eq!(path.get_size(), Some(1000));

    os::remove_dir(&dir);
}
<commit_msg>auto merge of #6960 : msullivan/rust/fix-pollution, r=brson<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// xfail-fast

extern mod extra;

use extra::tempfile;
use std::io::WriterUtil;
use std::io;
use std::os;
use std::uint;

pub fn main() {
    let dir = tempfile::mkdtemp(&Path("."), "").unwrap();
    let path = dir.push("file");

    {
        match io::file_writer(&path, [io::Create, io::Truncate]) {
            Err(ref e) => fail!(e.clone()),
            Ok(f) => {
                for uint::range(0, 1000) |_i| {
                    f.write_u8(0);
                }
            }
        }
    }

    assert!(path.exists());
    assert_eq!(path.get_size(), Some(1000));

    os::remove_file(&path);
    os::remove_dir(&dir);
}
<|endoftext|>


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

// Test that we are able to compile calls to associated fns like
// `decode()` where the bound on the `Self` parameter references a
// lifetime parameter of the trait. This example indicates why trait
// lifetime parameters must be early bound in the type of the
// associated item.

pub enum Value<'v> {
    A(&'v str),
    B,
}

pub trait Decoder<'v> {
    fn read(&mut self) -> Value<'v>;
}

pub trait Decodable<'v, D: Decoder<'v>> {
    fn decode(d: &mut D) -> Self;
}

impl<'v, D: Decoder<'v>> Decodable<'v, D> for () {
    fn decode(d: &mut D) -> () {
        match d.read() {
            A(..) => (),
            B => Decodable::decode(d),
        }
    }
}

fn main() { }
<commit_msg>Fix test for #10391 to have pub main<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// Test that we are able to compile calls to associated fns like
// `decode()` where the bound on the `Self` parameter references a
// lifetime parameter of the trait. This example indicates why trait
// lifetime parameters must be early bound in the type of the
// associated item.

pub enum Value<'v> {
    A(&'v str),
    B,
}

pub trait Decoder<'v> {
    fn read(&mut self) -> Value<'v>;
}

pub trait Decodable<'v, D: Decoder<'v>> {
    fn decode(d: &mut D) -> Self;
}

impl<'v, D: Decoder<'v>> Decodable<'v, D> for () {
    fn decode(d: &mut D) -> () {
        match d.read() {
            A(..) => (),
            B => Decodable::decode(d),
        }
    }
}

pub fn main() { }
<|endoftext|>


<commit_before><commit_msg>Extract the file watcher glue.<commit_after><|endoftext|>


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

//! A standard, garbage-collected linked list.

#[deriving(Clone, Eq)]
#[allow(missing_doc)]
pub enum List<T> {
    Cons(T, @List<T>),
    Nil,
}

/// Create a list from a vector
pub fn from_vec<T:Clone + 'static>(v: &[T]) -> @List<T> {
    v.rev_iter().fold(@Nil::<T>, |t, h| @Cons((*h).clone(), t))
}

/**
 * Left fold
 *
 * Applies `f` to `u` and the first element in the list, then applies `f` to
 * the result of the previous call and the second element, and so on,
 * returning the accumulated result.
 *
 * # Arguments
 *
 * * ls - The list to fold
 * * z - The initial value
 * * f - The function to apply
 */
pub fn foldl<T:Clone,U>(z: T, ls: @List<U>, f: |&T, &U| -> T) -> T {
    let mut accum: T = z;
    iter(ls, |elt| accum = f(&accum, elt));
    accum
}

/**
 * Search for an element that matches a given predicate
 *
 * Apply function `f` to each element of `ls`, starting from the first.
 * When function `f` returns true then an option containing the element
 * is returned. If `f` matches no elements then none is returned.
 */
pub fn find<T:Clone>(ls: @List<T>, f: |&T| -> bool) -> Option<T> {
    let mut ls = ls;
    loop {
        ls = match *ls {
          Cons(ref hd, tl) => {
            if f(hd) { return Some((*hd).clone()); }
            tl
          }
          Nil => return None
        }
    };
}

/// Returns true if a list contains an element with the given value
pub fn has<T:Eq>(ls: @List<T>, elt: T) -> bool {
    let mut found = false;
    each(ls, |e| {
        if *e == elt { found = true; false } else { true }
    });
    return found;
}

/// Returns true if the list is empty
pub fn is_empty<T>(ls: @List<T>) -> bool {
    match *ls {
        Nil => true,
        _ => false
    }
}

/// Returns the length of a list
pub fn len<T>(ls: @List<T>) -> uint {
    let mut count = 0u;
    iter(ls, |_e| count += 1u);
    count
}

/// Returns all but the first element of a list
pub fn tail<T>(ls: @List<T>) -> @List<T> {
    match *ls {
        Cons(_, tl) => return tl,
        Nil => fail!("list empty")
    }
}

/// Returns the first element of a list
pub fn head<T:Clone>(ls: @List<T>) -> T {
    match *ls {
      Cons(ref hd, _) => (*hd).clone(),
      // makes me sad
      _ => fail!("head invoked on empty list")
    }
}

/// Appends one list to another
pub fn append<T:Clone + 'static>(l: @List<T>, m: @List<T>) -> @List<T> {
    match *l {
      Nil => return m,
      Cons(ref x, xs) => {
        let rest = append(xs, m);
        return @Cons((*x).clone(), rest);
      }
    }
}

/*
/// Push one element into the front of a list, returning a new list
/// THIS VERSION DOESN'T ACTUALLY WORK
fn push<T:Clone>(ll: &mut @list<T>, vv: T) {
    ll = &mut @cons(vv, *ll)
}
*/

/// Iterate over a list
pub fn iter<T>(l: @List<T>, f: |&T|) {
    let mut cur = l;
    loop {
        cur = match *cur {
          Cons(ref hd, tl) => {
            f(hd);
            tl
          }
          Nil => break
        }
    }
}

/// Iterate over a list
pub fn each<T>(l: @List<T>, f: |&T| -> bool) -> bool {
    let mut cur = l;
    loop {
        cur = match *cur {
          Cons(ref hd, tl) => {
            if !f(hd) { return false; }
            tl
          }
          Nil => { return true; }
        }
    }
}

#[cfg(test)]
mod tests {
    use list::{List, Nil, from_vec, head, is_empty, tail};
    use list;

    use std::option;

    #[test]
    fn test_is_empty() {
        let empty : @list::List<int> = from_vec([]);
        let full1 = from_vec([1]);
        let full2 = from_vec(['r', 'u']);

        assert!(is_empty(empty));
        assert!(!is_empty(full1));
        assert!(!is_empty(full2));
    }

    #[test]
    fn test_from_vec() {
        let l = from_vec([0, 1, 2]);

        assert_eq!(head(l), 0);

        let tail_l = tail(l);
        assert_eq!(head(tail_l), 1);

        let tail_tail_l = tail(tail_l);
        assert_eq!(head(tail_tail_l), 2);
    }

    #[test]
    fn test_from_vec_empty() {
        let empty : @list::List<int> = from_vec([]);
        assert_eq!(empty, @list::Nil::<int>);
    }

    #[test]
    fn test_foldl() {
        fn add(a: &uint, b: &int) -> uint { return *a + (*b as uint); }
        let l = from_vec([0, 1, 2, 3, 4]);
        let empty = @list::Nil::<int>;
        assert_eq!(list::foldl(0u, l, add), 10u);
        assert_eq!(list::foldl(0u, empty, add), 0u);
    }

    #[test]
    fn test_foldl2() {
        fn sub(a: &int, b: &int) -> int {
            *a - *b
        }
        let l = from_vec([1, 2, 3, 4]);
        assert_eq!(list::foldl(0, l, sub), -10);
    }

    #[test]
    fn test_find_success() {
        fn match_(i: &int) -> bool { return *i == 2; }
        let l = from_vec([0, 1, 2]);
        assert_eq!(list::find(l, match_), option::Some(2));
    }

    #[test]
    fn test_find_fail() {
        fn match_(_i: &int) -> bool { return false; }
        let l = from_vec([0, 1, 2]);
        let empty = @list::Nil::<int>;
        assert_eq!(list::find(l, match_), option::None::<int>);
        assert_eq!(list::find(empty, match_), option::None::<int>);
    }

    #[test]
    fn test_has() {
        let l = from_vec([5, 8, 6]);
        let empty = @list::Nil::<int>;
        assert!((list::has(l, 5)));
        assert!((!list::has(l, 7)));
        assert!((list::has(l, 8)));
        assert!((!list::has(empty, 5)));
    }

    #[test]
    fn test_len() {
        let l = from_vec([0, 1, 2]);
        let empty = @list::Nil::<int>;
        assert_eq!(list::len(l), 3u);
        assert_eq!(list::len(empty), 0u);
    }

    #[test]
    fn test_append() {
        assert!(from_vec([1,2,3,4])
            == list::append(list::from_vec([1,2]), list::from_vec([3,4])));
    }
}
<commit_msg>Implement List's any() function<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A standard, garbage-collected linked list.

#[deriving(Clone, Eq)]
#[allow(missing_doc)]
pub enum List<T> {
    Cons(T, @List<T>),
    Nil,
}

/// Create a list from a vector
pub fn from_vec<T:Clone + 'static>(v: &[T]) -> @List<T> {
    v.rev_iter().fold(@Nil::<T>, |t, h| @Cons((*h).clone(), t))
}

/**
 * Left fold
 *
 * Applies `f` to `u` and the first element in the list, then applies `f` to
 * the result of the previous call and the second element, and so on,
 * returning the accumulated result.
 *
 * # Arguments
 *
 * * ls - The list to fold
 * * z - The initial value
 * * f - The function to apply
 */
pub fn foldl<T:Clone,U>(z: T, ls: @List<U>, f: |&T, &U| -> T) -> T {
    let mut accum: T = z;
    iter(ls, |elt| accum = f(&accum, elt));
    accum
}

/**
 * Search for an element that matches a given predicate
 *
 * Apply function `f` to each element of `ls`, starting from the first.
 * When function `f` returns true then an option containing the element
 * is returned. If `f` matches no elements then none is returned.
 */
pub fn find<T:Clone>(ls: @List<T>, f: |&T| -> bool) -> Option<T> {
    let mut ls = ls;
    loop {
        ls = match *ls {
          Cons(ref hd, tl) => {
            if f(hd) { return Some((*hd).clone()); }
            tl
          }
          Nil => return None
        }
    };
}

/**
 * Returns true if a list contains an element that matches a given predicate
 *
 * Apply function `f` to each element of `ls`, starting from the first.
 * When function `f` returns true then it also returns true. If `f` matches no
 * elements then false is returned.
 */
pub fn any<T>(ls: @List<T>, f: |&T| -> bool) -> bool {
    let mut ls = ls;
    loop {
        ls = match *ls {
            Cons(ref hd, tl) => {
                if f(hd) { return true; }
                tl
            }
            Nil => return false
        }
    };
}

/// Returns true if a list contains an element with the given value
pub fn has<T:Eq>(ls: @List<T>, elt: T) -> bool {
    let mut found = false;
    each(ls, |e| {
        if *e == elt { found = true; false } else { true }
    });
    return found;
}

/// Returns true if the list is empty
pub fn is_empty<T>(ls: @List<T>) -> bool {
    match *ls {
        Nil => true,
        _ => false
    }
}

/// Returns the length of a list
pub fn len<T>(ls: @List<T>) -> uint {
    let mut count = 0u;
    iter(ls, |_e| count += 1u);
    count
}

/// Returns all but the first element of a list
pub fn tail<T>(ls: @List<T>) -> @List<T> {
    match *ls {
        Cons(_, tl) => return tl,
        Nil => fail!("list empty")
    }
}

/// Returns the first element of a list
pub fn head<T:Clone>(ls: @List<T>) -> T {
    match *ls {
      Cons(ref hd, _) => (*hd).clone(),
      // makes me sad
      _ => fail!("head invoked on empty list")
    }
}

/// Appends one list to another
pub fn append<T:Clone + 'static>(l: @List<T>, m: @List<T>) -> @List<T> {
    match *l {
      Nil => return m,
      Cons(ref x, xs) => {
        let rest = append(xs, m);
        return @Cons((*x).clone(), rest);
      }
    }
}

/*
/// Push one element into the front of a list, returning a new list
/// THIS VERSION DOESN'T ACTUALLY WORK
fn push<T:Clone>(ll: &mut @list<T>, vv: T) {
    ll = &mut @cons(vv, *ll)
}
*/

/// Iterate over a list
pub fn iter<T>(l: @List<T>, f: |&T|) {
    let mut cur = l;
    loop {
        cur = match *cur {
          Cons(ref hd, tl) => {
            f(hd);
            tl
          }
          Nil => break
        }
    }
}

/// Iterate over a list
pub fn each<T>(l: @List<T>, f: |&T| -> bool) -> bool {
    let mut cur = l;
    loop {
        cur = match *cur {
          Cons(ref hd, tl) => {
            if !f(hd) { return false; }
            tl
          }
          Nil => { return true; }
        }
    }
}

#[cfg(test)]
mod tests {
    use list::{List, Nil, from_vec, head, is_empty, tail};
    use list;

    use std::option;

    #[test]
    fn test_is_empty() {
        let empty : @list::List<int> = from_vec([]);
        let full1 = from_vec([1]);
        let full2 = from_vec(['r', 'u']);

        assert!(is_empty(empty));
        assert!(!is_empty(full1));
        assert!(!is_empty(full2));
    }

    #[test]
    fn test_from_vec() {
        let l = from_vec([0, 1, 2]);

        assert_eq!(head(l), 0);

        let tail_l = tail(l);
        assert_eq!(head(tail_l), 1);

        let tail_tail_l = tail(tail_l);
        assert_eq!(head(tail_tail_l), 2);
    }

    #[test]
    fn test_from_vec_empty() {
        let empty : @list::List<int> = from_vec([]);
        assert_eq!(empty, @list::Nil::<int>);
    }

    #[test]
    fn test_foldl() {
        fn add(a: &uint, b: &int) -> uint { return *a + (*b as uint); }
        let l = from_vec([0, 1, 2, 3, 4]);
        let empty = @list::Nil::<int>;
        assert_eq!(list::foldl(0u, l, add), 10u);
        assert_eq!(list::foldl(0u, empty, add), 0u);
    }

    #[test]
    fn test_foldl2() {
        fn sub(a: &int, b: &int) -> int {
            *a - *b
        }
        let l = from_vec([1, 2, 3, 4]);
        assert_eq!(list::foldl(0, l, sub), -10);
    }

    #[test]
    fn test_find_success() {
        fn match_(i: &int) -> bool { return *i == 2; }
        let l = from_vec([0, 1, 2]);
        assert_eq!(list::find(l, match_), option::Some(2));
    }

    #[test]
    fn test_find_fail() {
        fn match_(_i: &int) -> bool { return false; }
        let l = from_vec([0, 1, 2]);
        let empty = @list::Nil::<int>;
        assert_eq!(list::find(l, match_), option::None::<int>);
        assert_eq!(list::find(empty, match_), option::None::<int>);
    }

    #[test]
    fn test_any() {
        fn match_(i: &int) -> bool { return *i == 2; }
        let l = from_vec([0, 1, 2]);
        let empty = @list::Nil::<int>;
        assert_eq!(list::any(l, match_), true);
        assert_eq!(list::any(empty, match_), false);
    }

    #[test]
    fn test_has() {
        let l = from_vec([5, 8, 6]);
        let empty = @list::Nil::<int>;
        assert!((list::has(l, 5)));
        assert!((!list::has(l, 7)));
        assert!((list::has(l, 8)));
        assert!((!list::has(empty, 5)));
    }

    #[test]
    fn test_len() {
        let l = from_vec([0, 1, 2]);
        let empty = @list::Nil::<int>;
        assert_eq!(list::len(l), 3u);
        assert_eq!(list::len(empty), 0u);
    }

    #[test]
    fn test_append() {
        assert!(from_vec([1,2,3,4])
            == list::append(list::from_vec([1,2]), list::from_vec([3,4])));
    }
}
<|endoftext|>


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

//! Unwind library interface

#[allow(non_camel_case_types)];
#[allow(dead_code)]; // these are just bindings

use libc;

#[cfg(not(target_arch = "arm"))]
#[repr(C)]
pub enum _Unwind_Action
{
    _UA_SEARCH_PHASE = 1,
    _UA_CLEANUP_PHASE = 2,
    _UA_HANDLER_FRAME = 4,
    _UA_FORCE_UNWIND = 8,
    _UA_END_OF_STACK = 16,
}

#[cfg(target_arch = "arm")]
#[repr(C)]
pub enum _Unwind_State
{
  _US_VIRTUAL_UNWIND_FRAME = 0,
  _US_UNWIND_FRAME_STARTING = 1,
  _US_UNWIND_FRAME_RESUME = 2,
  _US_ACTION_MASK = 3,
  _US_FORCE_UNWIND = 8,
  _US_END_OF_STACK = 16
}

#[repr(C)]
pub enum _Unwind_Reason_Code {
    _URC_NO_REASON = 0,
    _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
    _URC_FATAL_PHASE2_ERROR = 2,
    _URC_FATAL_PHASE1_ERROR = 3,
    _URC_NORMAL_STOP = 4,
    _URC_END_OF_STACK = 5,
    _URC_HANDLER_FOUND = 6,
    _URC_INSTALL_CONTEXT = 7,
    _URC_CONTINUE_UNWIND = 8,
    _URC_FAILURE = 9, // used only by ARM EABI
}

pub type _Unwind_Exception_Class = u64;

pub type _Unwind_Word = libc::uintptr_t;

#[cfg(target_arch = "x86")]
pub static unwinder_private_data_size: int = 5;

#[cfg(target_arch = "x86_64")]
pub static unwinder_private_data_size: int = 2;

#[cfg(target_arch = "arm")]
pub static unwinder_private_data_size: int = 20;

pub struct _Unwind_Exception {
    exception_class: _Unwind_Exception_Class,
    exception_cleanup: _Unwind_Exception_Cleanup_Fn,
    private: [_Unwind_Word, ..unwinder_private_data_size],
}

pub enum _Unwind_Context {}

pub type _Unwind_Exception_Cleanup_Fn =
        extern "C" fn(unwind_code: _Unwind_Reason_Code,
                      exception: *_Unwind_Exception);

pub type _Unwind_Trace_Fn =
        extern "C" fn(ctx: *_Unwind_Context,
                      arg: *libc::c_void) -> _Unwind_Reason_Code;

#[cfg(target_os = "linux")]
#[cfg(target_os = "freebsd")]
#[cfg(target_os = "win32")]
#[link(name = "gcc_s")]
extern {}

#[cfg(target_os = "android")]
#[link(name = "gcc")]
extern {}

extern "C" {
    pub fn _Unwind_RaiseException(exception: *_Unwind_Exception)
                -> _Unwind_Reason_Code;
    pub fn _Unwind_DeleteException(exception: *_Unwind_Exception);
    pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
                             trace_argument: *libc::c_void)
                -> _Unwind_Reason_Code;
    #[cfg(not(target_os = "android"))]
    pub fn _Unwind_GetIP(ctx: *_Unwind_Context) -> libc::uintptr_t;
    #[cfg(not(target_os = "android"))]
    pub fn _Unwind_FindEnclosingFunction(pc: *libc::c_void) -> *libc::c_void;
}

// On android, the function _Unwind_GetIP is a macro, and this is the expansion
// of the macro. This is all copy/pasted directly from the header file with the
// definition of _Unwind_GetIP.
#[cfg(target_os = "android")]
pub unsafe fn _Unwind_GetIP(ctx: *_Unwind_Context) -> libc::uintptr_t {
    #[repr(C)]
    enum _Unwind_VRS_Result {
        _UVRSR_OK = 0,
        _UVRSR_NOT_IMPLEMENTED = 1,
        _UVRSR_FAILED = 2,
    }
    #[repr(C)]
    enum _Unwind_VRS_RegClass {
        _UVRSC_CORE = 0,
        _UVRSC_VFP = 1,
        _UVRSC_FPA = 2,
        _UVRSC_WMMXD = 3,
        _UVRSC_WMMXC = 4,
    }
    #[repr(C)]
    enum _Unwind_VRS_DataRepresentation {
        _UVRSD_UINT32 = 0,
        _UVRSD_VFPX = 1,
        _UVRSD_FPAX = 2,
        _UVRSD_UINT64 = 3,
        _UVRSD_FLOAT = 4,
        _UVRSD_DOUBLE = 5,
    }

    type _Unwind_Word = libc::c_uint;
    extern {
        fn _Unwind_VRS_Get(ctx: *_Unwind_Context,
                           klass: _Unwind_VRS_RegClass,
                           word: _Unwind_Word,
                           repr: _Unwind_VRS_DataRepresentation,
                           data: *mut libc::c_void) -> _Unwind_VRS_Result;
    }

    let mut val: _Unwind_Word = 0;
    let ptr = &mut val as *mut _Unwind_Word;
    let _ = _Unwind_VRS_Get(ctx, _UVRSC_CORE, 15, _UVRSD_UINT32,
                            ptr as *mut libc::c_void);
    (val & !1) as libc::uintptr_t
}

// This function also doesn't exist on android, so make it a no-op
#[cfg(target_os = "android")]
pub unsafe fn _Unwind_FindEnclosingFunction(pc: *libc::c_void) -> *libc::c_void{
    pc
}
<commit_msg>std: Fix backtraces on arm linux<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Unwind library interface

#[allow(non_camel_case_types)];
#[allow(dead_code)]; // these are just bindings

use libc;

#[cfg(not(target_arch = "arm"))]
#[repr(C)]
pub enum _Unwind_Action
{
    _UA_SEARCH_PHASE = 1,
    _UA_CLEANUP_PHASE = 2,
    _UA_HANDLER_FRAME = 4,
    _UA_FORCE_UNWIND = 8,
    _UA_END_OF_STACK = 16,
}

#[cfg(target_arch = "arm")]
#[repr(C)]
pub enum _Unwind_State
{
  _US_VIRTUAL_UNWIND_FRAME = 0,
  _US_UNWIND_FRAME_STARTING = 1,
  _US_UNWIND_FRAME_RESUME = 2,
  _US_ACTION_MASK = 3,
  _US_FORCE_UNWIND = 8,
  _US_END_OF_STACK = 16
}

#[repr(C)]
pub enum _Unwind_Reason_Code {
    _URC_NO_REASON = 0,
    _URC_FOREIGN_EXCEPTION_CAUGHT = 1,
    _URC_FATAL_PHASE2_ERROR = 2,
    _URC_FATAL_PHASE1_ERROR = 3,
    _URC_NORMAL_STOP = 4,
    _URC_END_OF_STACK = 5,
    _URC_HANDLER_FOUND = 6,
    _URC_INSTALL_CONTEXT = 7,
    _URC_CONTINUE_UNWIND = 8,
    _URC_FAILURE = 9, // used only by ARM EABI
}

pub type _Unwind_Exception_Class = u64;

pub type _Unwind_Word = libc::uintptr_t;

#[cfg(target_arch = "x86")]
pub static unwinder_private_data_size: int = 5;

#[cfg(target_arch = "x86_64")]
pub static unwinder_private_data_size: int = 2;

#[cfg(target_arch = "arm")]
pub static unwinder_private_data_size: int = 20;

pub struct _Unwind_Exception {
    exception_class: _Unwind_Exception_Class,
    exception_cleanup: _Unwind_Exception_Cleanup_Fn,
    private: [_Unwind_Word, ..unwinder_private_data_size],
}

pub enum _Unwind_Context {}

pub type _Unwind_Exception_Cleanup_Fn =
        extern "C" fn(unwind_code: _Unwind_Reason_Code,
                      exception: *_Unwind_Exception);

pub type _Unwind_Trace_Fn =
        extern "C" fn(ctx: *_Unwind_Context,
                      arg: *libc::c_void) -> _Unwind_Reason_Code;

#[cfg(target_os = "linux")]
#[cfg(target_os = "freebsd")]
#[cfg(target_os = "win32")]
#[link(name = "gcc_s")]
extern {}

#[cfg(target_os = "android")]
#[link(name = "gcc")]
extern {}

extern "C" {
    pub fn _Unwind_RaiseException(exception: *_Unwind_Exception)
                -> _Unwind_Reason_Code;
    pub fn _Unwind_DeleteException(exception: *_Unwind_Exception);
    pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
                             trace_argument: *libc::c_void)
                -> _Unwind_Reason_Code;
    #[cfg(stage0, not(target_os = "android"))]
    pub fn _Unwind_GetIP(ctx: *_Unwind_Context) -> libc::uintptr_t;
    #[cfg(stage0, not(target_os = "android"))]
    pub fn _Unwind_FindEnclosingFunction(pc: *libc::c_void) -> *libc::c_void;

    #[cfg(not(stage0),
          not(target_os = "android"),
          not(target_os = "linux", target_arch = "arm"))]
    pub fn _Unwind_GetIP(ctx: *_Unwind_Context) -> libc::uintptr_t;
    #[cfg(not(stage0),
          not(target_os = "android"),
          not(target_os = "linux", target_arch = "arm"))]
    pub fn _Unwind_FindEnclosingFunction(pc: *libc::c_void) -> *libc::c_void;
}

// On android, the function _Unwind_GetIP is a macro, and this is the expansion
// of the macro. This is all copy/pasted directly from the header file with the
// definition of _Unwind_GetIP.
#[cfg(target_os = "android")]
#[cfg(target_os = "linux", target_os = "arm")]
pub unsafe fn _Unwind_GetIP(ctx: *_Unwind_Context) -> libc::uintptr_t {
    #[repr(C)]
    enum _Unwind_VRS_Result {
        _UVRSR_OK = 0,
        _UVRSR_NOT_IMPLEMENTED = 1,
        _UVRSR_FAILED = 2,
    }
    #[repr(C)]
    enum _Unwind_VRS_RegClass {
        _UVRSC_CORE = 0,
        _UVRSC_VFP = 1,
        _UVRSC_FPA = 2,
        _UVRSC_WMMXD = 3,
        _UVRSC_WMMXC = 4,
    }
    #[repr(C)]
    enum _Unwind_VRS_DataRepresentation {
        _UVRSD_UINT32 = 0,
        _UVRSD_VFPX = 1,
        _UVRSD_FPAX = 2,
        _UVRSD_UINT64 = 3,
        _UVRSD_FLOAT = 4,
        _UVRSD_DOUBLE = 5,
    }

    type _Unwind_Word = libc::c_uint;
    extern {
        fn _Unwind_VRS_Get(ctx: *_Unwind_Context,
                           klass: _Unwind_VRS_RegClass,
                           word: _Unwind_Word,
                           repr: _Unwind_VRS_DataRepresentation,
                           data: *mut libc::c_void) -> _Unwind_VRS_Result;
    }

    let mut val: _Unwind_Word = 0;
    let ptr = &mut val as *mut _Unwind_Word;
    let _ = _Unwind_VRS_Get(ctx, _UVRSC_CORE, 15, _UVRSD_UINT32,
                            ptr as *mut libc::c_void);
    (val & !1) as libc::uintptr_t
}

// This function also doesn't exist on android, so make it a no-op
#[cfg(target_os = "android")]
#[cfg(target_os = "linux", target_os = "arm")]
pub unsafe fn _Unwind_FindEnclosingFunction(pc: *libc::c_void) -> *libc::c_void{
    pc
}
<|endoftext|>


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

/* The compiler code necessary to support the bytes! extension. */

use ast;
use codemap::Span;
use ext::base::*;
use ext::base;
use ext::build::AstBuilder;

pub fn expand_syntax_ext<'cx>(cx: &'cx mut ExtCtxt,
                              sp: Span,
                              tts: &[ast::TokenTree])
                              -> Box<base::MacResult+'cx> {
    cx.span_warn(sp, "`bytes!` is deprecated, use `b\"foo\"` literals instead");
    cx.parse_sess.span_diagnostic.span_note(sp,
        "see http://doc.rust-lang.org/reference.html#byte-and-byte-string-literals \
         for documentation");
    cx.parse_sess.span_diagnostic.span_note(sp,
        "see https://github.com/rust-lang/rust/blob/master/src/etc/2014-06-rewrite-bytes-macros.py \
         for an automated migration");

    // Gather all argument expressions
    let exprs = match get_exprs_from_tts(cx, sp, tts) {
        None => return DummyResult::expr(sp),
        Some(e) => e,
    };
    let mut bytes = Vec::new();
    let mut err = false;

    for expr in exprs.iter() {
        match expr.node {
            // expression is a literal
            ast::ExprLit(ref lit) => match lit.node {
                // string literal, push each byte to vector expression
                ast::LitStr(ref s, _) => {
                    for byte in s.get().bytes() {
                        bytes.push(cx.expr_u8(expr.span, byte));
                    }
                }

                // u8 literal, push to vector expression
                ast::LitInt(v, ast::UnsignedIntLit(ast::TyU8)) => {
                    if v > 0xFF {
                        cx.span_err(expr.span, "too large u8 literal in bytes!");
                        err = true;
                    } else {
                        bytes.push(cx.expr_u8(expr.span, v as u8));
                    }
                }

                // integer literal, push to vector expression
                ast::LitInt(_, ast::UnsuffixedIntLit(ast::Minus)) => {
                    cx.span_err(expr.span, "negative integer literal in bytes!");
                    err = true;
                }
                ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => {
                    if v > 0xFF {
                        cx.span_err(expr.span, "too large integer literal in bytes!");
                        err = true;
                    } else {
                        bytes.push(cx.expr_u8(expr.span, v as u8));
                    }
                }

                // char literal, push to vector expression
                ast::LitChar(v) => {
                    if v.is_ascii() {
                        bytes.push(cx.expr_u8(expr.span, v as u8));
                    } else {
                        cx.span_err(expr.span, "non-ascii char literal in bytes!");
                        err = true;
                    }
                }

                _ => {
                    cx.span_err(expr.span, "unsupported literal in bytes!");
                    err = true;
                }
            },

            _ => {
                cx.span_err(expr.span, "non-literal in bytes!");
                err = true;
            }
        }
    }

    // For some reason using quote_expr!() here aborts if we threw an error.
    // I'm assuming that the end of the recursive parse tricks the compiler
    // into thinking this is a good time to stop. But we'd rather keep going.
    if err {
        // Since the compiler will stop after the macro expansion phase anyway, we
        // don't need type info, so we can just return a DummyResult
        return DummyResult::expr(sp);
    }

    let e = cx.expr_vec_slice(sp, bytes);
    let ty = cx.ty(sp, ast::TyVec(cx.ty_ident(sp, cx.ident_of("u8"))));
    let lifetime = cx.lifetime(sp, cx.ident_of("'static").name);
    let item = cx.item_static(sp,
                              cx.ident_of("BYTES"),
                              cx.ty_rptr(sp,
                                         ty,
                                         Some(lifetime),
                                         ast::MutImmutable),
                              ast::MutImmutable,
                              e);
    let e = cx.expr_block(cx.block(sp,
                                   vec!(cx.stmt_item(sp, item)),
                                   Some(cx.expr_ident(sp, cx.ident_of("BYTES")))));
    MacExpr::new(e)
}
<commit_msg>syntax: Tweak the return value of bytes!()<commit_after>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

/* The compiler code necessary to support the bytes! extension. */

use ast;
use codemap::Span;
use ext::base::*;
use ext::base;
use ext::build::AstBuilder;

pub fn expand_syntax_ext<'cx>(cx: &'cx mut ExtCtxt,
                              sp: Span,
                              tts: &[ast::TokenTree])
                              -> Box<base::MacResult+'cx> {
    cx.span_warn(sp, "`bytes!` is deprecated, use `b\"foo\"` literals instead");
    cx.parse_sess.span_diagnostic.span_note(sp,
        "see http://doc.rust-lang.org/reference.html#byte-and-byte-string-literals \
         for documentation");
    cx.parse_sess.span_diagnostic.span_note(sp,
        "see https://github.com/rust-lang/rust/blob/master/src/etc/2014-06-rewrite-bytes-macros.py \
         for an automated migration");

    // Gather all argument expressions
    let exprs = match get_exprs_from_tts(cx, sp, tts) {
        None => return DummyResult::expr(sp),
        Some(e) => e,
    };
    let mut bytes = Vec::new();
    let mut err = false;

    for expr in exprs.iter() {
        match expr.node {
            // expression is a literal
            ast::ExprLit(ref lit) => match lit.node {
                // string literal, push each byte to vector expression
                ast::LitStr(ref s, _) => {
                    for byte in s.get().bytes() {
                        bytes.push(cx.expr_u8(expr.span, byte));
                    }
                }

                // u8 literal, push to vector expression
                ast::LitInt(v, ast::UnsignedIntLit(ast::TyU8)) => {
                    if v > 0xFF {
                        cx.span_err(expr.span, "too large u8 literal in bytes!");
                        err = true;
                    } else {
                        bytes.push(cx.expr_u8(expr.span, v as u8));
                    }
                }

                // integer literal, push to vector expression
                ast::LitInt(_, ast::UnsuffixedIntLit(ast::Minus)) => {
                    cx.span_err(expr.span, "negative integer literal in bytes!");
                    err = true;
                }
                ast::LitInt(v, ast::UnsuffixedIntLit(ast::Plus)) => {
                    if v > 0xFF {
                        cx.span_err(expr.span, "too large integer literal in bytes!");
                        err = true;
                    } else {
                        bytes.push(cx.expr_u8(expr.span, v as u8));
                    }
                }

                // char literal, push to vector expression
                ast::LitChar(v) => {
                    if v.is_ascii() {
                        bytes.push(cx.expr_u8(expr.span, v as u8));
                    } else {
                        cx.span_err(expr.span, "non-ascii char literal in bytes!");
                        err = true;
                    }
                }

                _ => {
                    cx.span_err(expr.span, "unsupported literal in bytes!");
                    err = true;
                }
            },

            _ => {
                cx.span_err(expr.span, "non-literal in bytes!");
                err = true;
            }
        }
    }

    // For some reason using quote_expr!() here aborts if we threw an error.
    // I'm assuming that the end of the recursive parse tricks the compiler
    // into thinking this is a good time to stop. But we'd rather keep going.
    if err {
        // Since the compiler will stop after the macro expansion phase anyway, we
        // don't need type info, so we can just return a DummyResult
        return DummyResult::expr(sp);
    }

    let len = bytes.len();
    let e = cx.expr_vec(sp, bytes);
    let ty = cx.ty(sp, ast::TyFixedLengthVec(cx.ty_ident(sp, cx.ident_of("u8")),
                                             cx.expr_uint(sp, len)));
    let item = cx.item_static(sp, cx.ident_of("BYTES"), ty, ast::MutImmutable, e);
    let ret = cx.expr_ident(sp, cx.ident_of("BYTES"));
    let ret = cx.expr_addr_of(sp, ret);
    let e = cx.expr_block(cx.block(sp, vec![cx.stmt_item(sp, item)],
                                   Some(ret)));
    MacExpr::new(e)
}
<|endoftext|>


<commit_before><commit_msg>some rust tweaking<commit_after>extern crate rand;

use rand::Rng;

fn main() {
    let mut rng = rand::thread_rng();
    let letter: char = rng.gen_range(b'A', b'Z') as char;
    let number: u32 = rng.gen_range(0, 999999);
    let s = format!("{}{:06}", letter, number);
    println!("{}", s);
}
<|endoftext|>


<commit_before><commit_msg>Create a non-compiling example on ownership<commit_after>fn main(){
    let original = vec![1, 2, 3];
    let owner = original;

    println!("Will not compile {}", original[0]);
 }
<|endoftext|>


<commit_before><commit_msg>add analyse.rs. Guess that basic analysis might be more fun in Rust<commit_after>#![crate_type = "staticlib"]

use std::ffi::CString;
use std::os::raw::c_char;

#[repr(C)]
struct mpc_state_t
{
    pos: i64,
    row: i64,
    col: i64,
}

#[repr(C)]
struct mpc_ast_t
{
    tag: *mut c_char,
    contents: *mut c_char,
    children_num: i32,
    children: *mut *mut mpc_ast_t,
}

extern
{
    fn puts(s: *const c_char);
}

#[no_mangle]
unsafe extern fn analyse()
{
    puts(CString::new("Hello world").unwrap().as_ptr());
}

#[no_mangle]
pub unsafe extern fn main()
{
    analyse();
}
<|endoftext|>


<commit_before><commit_msg>fix(Help Message): required args no longer double list in usage<commit_after><|endoftext|>


<commit_before><commit_msg>Add a simple (temp) tree structure<commit_after>#[derive(Debug, PartialEq)]
pub enum Expression {
    Number(f64),
    Identifier(String),
}<|endoftext|>


<commit_before>fn main() {
    let decimal = 65.4321_f32;

    // Error! No implicit conversion
    let integer: u8 = decimal;
    // FIXME ^ Comment out this line

    // Explicit conversion
    let integer = decimal as u8;
    let character = integer as char;

    println!("Casting: {} -> {} -> {}", decimal, integer, character);

    // when casting any value to an unsigned type, T,
    // std::T::MAX + 1 is added or subtracted until the value
    // fits into the new type

    // 1000 already fits in a u16
    println!("1000 as a u16 is: {}", 1000 as u16);

    // 1000 - 256 - 256 = 232
    println!("1000 as a u8 is : {}", 1000 as u8);
    // -1 + 256 = 255
    println!("  -1 as a u8 is : {}", (-1i8) as u8);

    // For positive numbers, this is the same as the modulus
    println!("1000 mod 256 is : {}", 1000 % 256);

    // When casting to a signed type, the result is the same as
    // first casting to the corresponding unsigned type then
    // taking the two's complement.

    // Unless it already fits, of course.
    println!(" 128 as a i16 is: {}", 128 as i16);
    // 128 as u8 -> 128, whose two's complement in eight bits is:
    println!(" 128 as a i8 is : {}", 128 as i8);

    // repeating the example above
    // 1000 as u8 -> 232
    println!("1000 as a i8 is : {}", 1000 as i8);
    // and the two's complement of 232 is -24
    println!(" 232 as a i8 is : {}", 232 as i8);

}
<commit_msg>type/cast: fix math in comment<commit_after>fn main() {
    let decimal = 65.4321_f32;

    // Error! No implicit conversion
    let integer: u8 = decimal;
    // FIXME ^ Comment out this line

    // Explicit conversion
    let integer = decimal as u8;
    let character = integer as char;

    println!("Casting: {} -> {} -> {}", decimal, integer, character);

    // when casting any value to an unsigned type, T,
    // std::T::MAX + 1 is added or subtracted until the value
    // fits into the new type

    // 1000 already fits in a u16
    println!("1000 as a u16 is: {}", 1000 as u16);

    // 1000 - 256 - 256 -256 = 232
    println!("1000 as a u8 is : {}", 1000 as u8);
    // -1 + 256 = 255
    println!("  -1 as a u8 is : {}", (-1i8) as u8);

    // For positive numbers, this is the same as the modulus
    println!("1000 mod 256 is : {}", 1000 % 256);

    // When casting to a signed type, the result is the same as
    // first casting to the corresponding unsigned type then
    // taking the two's complement.

    // Unless it already fits, of course.
    println!(" 128 as a i16 is: {}", 128 as i16);
    // 128 as u8 -> 128, whose two's complement in eight bits is:
    println!(" 128 as a i8 is : {}", 128 as i8);

    // repeating the example above
    // 1000 as u8 -> 232
    println!("1000 as a i8 is : {}", 1000 as i8);
    // and the two's complement of 232 is -24
    println!(" 232 as a i8 is : {}", 232 as i8);

}
<|endoftext|>


<commit_before><commit_msg>Add problem #38<commit_after>extern mod std;
use std::sort::{ quick_sort };

extern mod euler;
use euler::calc::{ permutate_num, num_to_digits };

fn main() {
    for permutate_num(~[9, 8, 7, 6, 5, 4, 3, 2, 1], 4, 0, 9999) |num, rest| {
        let mut ds = num_to_digits(num * 2, 10);
        quick_sort(|a, b| a >= b, ds);

        if vec::eq(ds, rest) {
            io::println(fmt!("%u%u", num, num * 2));
            break;
        }
    }
}
<|endoftext|>