<commit_before>// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![feature(plugin, custom_attribute)]
#![plugin(gfx_macros)]

extern crate cgmath;
extern crate glfw;
extern crate gfx;
extern crate gfx_device_gl;

use cgmath::FixedArray;
use cgmath::{Matrix, Point3, Vector3};
use cgmath::{Transform, AffineMatrix3};
use gfx::traits::*;
use glfw::Context;

#[vertex_format]
#[derive(Clone, Copy)]
struct Vertex {
    #[as_float]
    #[name = "a_Pos"]
    pos: [i8; 3],

    #[as_float]
    #[name = "a_TexCoord"]
    tex_coord: [u8; 2],
}

// The shader_param attribute makes sure the following struct can be used to
// pass parameters to a shader.
#[shader_param]
struct Params<R: gfx::Resources> {
    #[name = "u_Transform"]
    transform: [[f32; 4]; 4],

    #[name = "t_Color"]
    color: gfx::shade::TextureParam<R>,
}

//----------------------------------------

pub fn main() {
    let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap();
    let (mut window, events) = glfw
        .create_window(640, 480, "Cube example", glfw::WindowMode::Windowed)
        .expect("Failed to create GLFW window.");

    window.make_current();
    glfw.set_error_callback(glfw::FAIL_ON_ERRORS);
    window.set_key_polling(true);

    let (w, h) = window.get_framebuffer_size();
    let frame = gfx::Frame::new(w as u16, h as u16);

    let (mut device, mut factory) = gfx_device_gl::create(|s| window.get_proc_address(s));
    let mut renderer = factory.create_renderer();

    let vertex_data = [
        // top (0, 0, 1)
        Vertex { pos: [-1, -1,  1], tex_coord: [0, 0] },
        Vertex { pos: [ 1, -1,  1], tex_coord: [1, 0] },
        Vertex { pos: [ 1,  1,  1], tex_coord: [1, 1] },
        Vertex { pos: [-1,  1,  1], tex_coord: [0, 1] },
        // bottom (0, 0, -1)
        Vertex { pos: [-1,  1, -1], tex_coord: [1, 0] },
        Vertex { pos: [ 1,  1, -1], tex_coord: [0, 0] },
        Vertex { pos: [ 1, -1, -1], tex_coord: [0, 1] },
        Vertex { pos: [-1, -1, -1], tex_coord: [1, 1] },
        // right (1, 0, 0)
        Vertex { pos: [ 1, -1, -1], tex_coord: [0, 0] },
        Vertex { pos: [ 1,  1, -1], tex_coord: [1, 0] },
        Vertex { pos: [ 1,  1,  1], tex_coord: [1, 1] },
        Vertex { pos: [ 1, -1,  1], tex_coord: [0, 1] },
        // left (-1, 0, 0)
        Vertex { pos: [-1, -1,  1], tex_coord: [1, 0] },
        Vertex { pos: [-1,  1,  1], tex_coord: [0, 0] },
        Vertex { pos: [-1,  1, -1], tex_coord: [0, 1] },
        Vertex { pos: [-1, -1, -1], tex_coord: [1, 1] },
        // front (0, 1, 0)
        Vertex { pos: [ 1,  1, -1], tex_coord: [1, 0] },
        Vertex { pos: [-1,  1, -1], tex_coord: [0, 0] },
        Vertex { pos: [-1,  1,  1], tex_coord: [0, 1] },
        Vertex { pos: [ 1,  1,  1], tex_coord: [1, 1] },
        // back (0, -1, 0)
        Vertex { pos: [ 1, -1,  1], tex_coord: [0, 0] },
        Vertex { pos: [-1, -1,  1], tex_coord: [1, 0] },
        Vertex { pos: [-1, -1, -1], tex_coord: [1, 1] },
        Vertex { pos: [ 1, -1, -1], tex_coord: [0, 1] },
    ];

    let mesh = factory.create_mesh(&vertex_data);

    let index_data: &[u8] = &[
         0,  1,  2,  2,  3,  0, // top
         4,  5,  6,  6,  7,  4, // bottom
         8,  9, 10, 10, 11,  8, // right
        12, 13, 14, 14, 15, 12, // left
        16, 17, 18, 18, 19, 16, // front
        20, 21, 22, 22, 23, 20, // back
    ];

    let texture_info = gfx::tex::TextureInfo {
        width: 1,
        height: 1,
        depth: 1,
        levels: 1,
        kind: gfx::tex::TextureKind::Texture2D,
        format: gfx::tex::RGBA8,
    };
    let image_info = texture_info.to_image_info();
    let texture = factory.create_texture(texture_info).unwrap();
    factory.update_texture(&texture, &image_info,
                          &[0x20u8, 0xA0u8, 0xC0u8, 0x00u8],
                          None).unwrap();

    let sampler = factory.create_sampler(
        gfx::tex::SamplerInfo::new(gfx::tex::FilterMethod::Bilinear,
                                   gfx::tex::WrapMode::Clamp)
    );

    let program = {
        let vs = gfx::ShaderSource {
            glsl_120: Some(include_bytes!("cube_120.glslv")),
            glsl_150: Some(include_bytes!("cube_150.glslv")),
            .. gfx::ShaderSource::empty()
        };
        let fs = gfx::ShaderSource {
            glsl_120: Some(include_bytes!("cube_120.glslf")),
            glsl_150: Some(include_bytes!("cube_150.glslf")),
            .. gfx::ShaderSource::empty()
        };
        factory.link_program_source(vs, fs, &device.get_capabilities())
               .unwrap()
    };

    let view: AffineMatrix3<f32> = Transform::look_at(
        &Point3::new(1.5f32, -5.0, 3.0),
        &Point3::new(0f32, 0.0, 0.0),
        &Vector3::unit_z(),
    );
    let aspect = w as f32 / h as f32;
    let proj = cgmath::perspective(cgmath::deg(45.0f32), aspect, 1.0, 10.0);

    let data = Params {
        transform: proj.mul_m(&view.mat).into_fixed(),
        color: (texture, Some(sampler)),
    };

    let mut batch = gfx::batch::OwnedBatch::new(mesh, program, data).unwrap();
    batch.slice = factory.create_buffer_index::<u8>(index_data)
                         .to_slice(gfx::PrimitiveType::TriangleList);
    batch.state.depth(gfx::state::Comparison::LessEqual, true);

    let clear_data = gfx::ClearData {
        color: [0.3, 0.3, 0.3, 1.0],
        depth: 1.0,
        stencil: 0,
    };

    while !window.should_close() {
        glfw.poll_events();
        for (_, event) in glfw::flush_messages(&events) {
            match event {
                glfw::WindowEvent::Key(glfw::Key::Escape, _, glfw::Action::Press, _) =>
                    window.set_should_close(true),
                _ => {},
            }
        }

        renderer.clear(clear_data, gfx::COLOR | gfx::DEPTH, &frame);
        renderer.draw(&batch, &frame).unwrap();
        device.submit(renderer.as_buffer());
        renderer.reset();

        window.swap_buffers();
        device.after_frame();
        factory.cleanup();
    }
}
<commit_msg>Updated the cube example<commit_after>// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![feature(plugin, custom_attribute)]
#![plugin(gfx_macros)]

extern crate cgmath;
extern crate glfw;
extern crate gfx;
extern crate gfx_window_glutin;
extern crate glutin;

use cgmath::FixedArray;
use cgmath::{Matrix, Point3, Vector3};
use cgmath::{Transform, AffineMatrix3};
use gfx::traits::*;

#[vertex_format]
#[derive(Clone, Copy)]
struct Vertex {
    #[as_float]
    #[name = "a_Pos"]
    pos: [i8; 3],

    #[as_float]
    #[name = "a_TexCoord"]
    tex_coord: [u8; 2],
}

// The shader_param attribute makes sure the following struct can be used to
// pass parameters to a shader.
#[shader_param]
struct Params<R: gfx::Resources> {
    #[name = "u_Transform"]
    transform: [[f32; 4]; 4],

    #[name = "t_Color"]
    color: gfx::shade::TextureParam<R>,
}

//----------------------------------------

pub fn main() {
    let (wrap, mut device, mut factory) = gfx_window_glutin::init_titled("Cube example")
                                                             .unwrap();
    let mut renderer = factory.create_renderer();

    let vertex_data = [
        // top (0, 0, 1)
        Vertex { pos: [-1, -1,  1], tex_coord: [0, 0] },
        Vertex { pos: [ 1, -1,  1], tex_coord: [1, 0] },
        Vertex { pos: [ 1,  1,  1], tex_coord: [1, 1] },
        Vertex { pos: [-1,  1,  1], tex_coord: [0, 1] },
        // bottom (0, 0, -1)
        Vertex { pos: [-1,  1, -1], tex_coord: [1, 0] },
        Vertex { pos: [ 1,  1, -1], tex_coord: [0, 0] },
        Vertex { pos: [ 1, -1, -1], tex_coord: [0, 1] },
        Vertex { pos: [-1, -1, -1], tex_coord: [1, 1] },
        // right (1, 0, 0)
        Vertex { pos: [ 1, -1, -1], tex_coord: [0, 0] },
        Vertex { pos: [ 1,  1, -1], tex_coord: [1, 0] },
        Vertex { pos: [ 1,  1,  1], tex_coord: [1, 1] },
        Vertex { pos: [ 1, -1,  1], tex_coord: [0, 1] },
        // left (-1, 0, 0)
        Vertex { pos: [-1, -1,  1], tex_coord: [1, 0] },
        Vertex { pos: [-1,  1,  1], tex_coord: [0, 0] },
        Vertex { pos: [-1,  1, -1], tex_coord: [0, 1] },
        Vertex { pos: [-1, -1, -1], tex_coord: [1, 1] },
        // front (0, 1, 0)
        Vertex { pos: [ 1,  1, -1], tex_coord: [1, 0] },
        Vertex { pos: [-1,  1, -1], tex_coord: [0, 0] },
        Vertex { pos: [-1,  1,  1], tex_coord: [0, 1] },
        Vertex { pos: [ 1,  1,  1], tex_coord: [1, 1] },
        // back (0, -1, 0)
        Vertex { pos: [ 1, -1,  1], tex_coord: [0, 0] },
        Vertex { pos: [-1, -1,  1], tex_coord: [1, 0] },
        Vertex { pos: [-1, -1, -1], tex_coord: [1, 1] },
        Vertex { pos: [ 1, -1, -1], tex_coord: [0, 1] },
    ];

    let mesh = factory.create_mesh(&vertex_data);

    let index_data: &[u8] = &[
         0,  1,  2,  2,  3,  0, // top
         4,  5,  6,  6,  7,  4, // bottom
         8,  9, 10, 10, 11,  8, // right
        12, 13, 14, 14, 15, 12, // left
        16, 17, 18, 18, 19, 16, // front
        20, 21, 22, 22, 23, 20, // back
    ];

    let texture_info = gfx::tex::TextureInfo {
        width: 1,
        height: 1,
        depth: 1,
        levels: 1,
        kind: gfx::tex::TextureKind::Texture2D,
        format: gfx::tex::RGBA8,
    };
    let image_info = texture_info.to_image_info();
    let texture = factory.create_texture(texture_info).unwrap();
    factory.update_texture(&texture, &image_info,
                          &[0x20u8, 0xA0u8, 0xC0u8, 0x00u8],
                          None).unwrap();

    let sampler = factory.create_sampler(
        gfx::tex::SamplerInfo::new(gfx::tex::FilterMethod::Bilinear,
                                   gfx::tex::WrapMode::Clamp)
    );

    let program = {
        let vs = gfx::ShaderSource {
            glsl_120: Some(include_bytes!("cube_120.glslv")),
            glsl_150: Some(include_bytes!("cube_150.glslv")),
            .. gfx::ShaderSource::empty()
        };
        let fs = gfx::ShaderSource {
            glsl_120: Some(include_bytes!("cube_120.glslf")),
            glsl_150: Some(include_bytes!("cube_150.glslf")),
            .. gfx::ShaderSource::empty()
        };
        factory.link_program_source(vs, fs, &device.get_capabilities())
               .unwrap()
    };

    let view: AffineMatrix3<f32> = Transform::look_at(
        &Point3::new(1.5f32, -5.0, 3.0),
        &Point3::new(0f32, 0.0, 0.0),
        &Vector3::unit_z(),
    );
    let aspect = {
        let (w, h) = wrap.get_size();
        w as f32 / h as f32
    };
    let proj = cgmath::perspective(cgmath::deg(45.0f32), aspect, 1.0, 10.0);

    let data = Params {
        transform: proj.mul_m(&view.mat).into_fixed(),
        color: (texture, Some(sampler)),
    };

    let mut batch = gfx::batch::OwnedBatch::new(mesh, program, data).unwrap();
    batch.slice = factory.create_buffer_index::<u8>(index_data)
                         .to_slice(gfx::PrimitiveType::TriangleList);
    batch.state.depth(gfx::state::Comparison::LessEqual, true);

    let clear_data = gfx::ClearData {
        color: [0.3, 0.3, 0.3, 1.0],
        depth: 1.0,
        stencil: 0,
    };

    'main: loop {
        // quit when Esc is pressed.
        for event in wrap.window.poll_events() {
            match event {
                glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) => break 'main,
                glutin::Event::Closed => break 'main,
                _ => {},
            }
        }

        renderer.clear(clear_data, gfx::COLOR | gfx::DEPTH, &wrap);
        renderer.draw(&batch, &wrap).unwrap();
        device.submit(renderer.as_buffer());
        renderer.reset();

        wrap.window.swap_buffers();
        device.after_frame();
        factory.cleanup();
    }
}
<|endoftext|>


<commit_before><commit_msg>Styling, directory viewing and dumb binary detection.<commit_after>pub const CSS: &'static str =
r"
* {
	padding:0;
	margin:0;
}

body {
	color: #333;
	font: 14px Sans-Serif;
	padding: 50px;
	background: #eee;
}

h1 {
	text-align: center;
	padding: 20px 0 12px 0;
	margin: 0;
}
h2 {
	font-size: 16px;
	text-align: center;
	padding: 0 0 12px 0;
}

#container {
	box-shadow: 0 5px 10px -5px rgba(0,0,0,0.5);
	position: relative;
	background: white;
}

table {
	background-color: #F3F3F3;
	border-collapse: collapse;
	width: 100%;
	margin: 15px 0;
}

th {
	background-color: #215fa4;
	color: #FFF;
	cursor: pointer;
	padding: 5px 10px;
}

th small {
	font-size: 9px;
}

td, th {
	text-align: left;
}

a {
	text-decoration: none;
}

td a {
	color: #001c3b;
	display: block;
	padding: 5px 10px;
}
th a {
	padding-left: 0
}

tr:nth-of-type(odd) {
	background-color: #E6E6E6;
}

tr:hover td {
	background-color:#CACACA;
}

tr:hover td a {
	color: #000;
}
";
<|endoftext|>


<commit_before><commit_msg>add some test<commit_after>extern crate memcache;
extern crate r2d2;
extern crate r2d2_memcache;

use r2d2_memcache::MemcacheConnectionManager;

#[test]
fn connect() {
    let config = r2d2::Config::default();
    let manager = MemcacheConnectionManager::new("localhost:11211").unwrap();

    let pool = r2d2::Pool::new(config, manager).unwrap();
}

#[test]
fn flush() {
    let config = r2d2::Config::default();
    let manager = MemcacheConnectionManager::new("localhost:11211").unwrap();

    let pool = r2d2::Pool::new(config, manager).unwrap();

    {
        let pool = pool.clone();
        let mut conn = pool.get().unwrap();
        conn.flush().unwrap();
    }
}

#[test]
fn version() {
    let config = r2d2::Config::default();
    let manager = MemcacheConnectionManager::new("localhost:11211").unwrap();

    let pool = r2d2::Pool::new(config, manager).unwrap();

    {
        let pool = pool.clone();
        let mut conn = pool.get().unwrap();
        conn.version().unwrap();
    }
}

#[test]
fn store() {
    let config = r2d2::Config::default();
    let manager = MemcacheConnectionManager::new("localhost:11211").unwrap();

    let pool = r2d2::Pool::new(config, manager).unwrap();

    {
        let pool = pool.clone();
        let mut conn = pool.get().unwrap();
        let value = &memcache::Raw {
            bytes: b"bar",
            flags: 0,
        };
        conn.set("foo", value).unwrap();
        conn.replace("foo", value).unwrap();
        conn.add("foo", value).unwrap();
        conn.append("foo", value).unwrap();
        conn.prepend("foo", value).unwrap();
    }
}

#[test]
fn get() {
    let config = r2d2::Config::default();
    let manager = MemcacheConnectionManager::new("localhost:11211").unwrap();

    let pool = r2d2::Pool::new(config, manager).unwrap();
    {
        let pool = pool.clone();
        let mut conn = pool.get().unwrap();
        conn.flush().unwrap();
        let value = &memcache::Raw {
            bytes: b"bar",
            flags: 0,
        };
        conn.set("foo_get", value).unwrap();
        let result: (Vec<u8>, u16) = conn.get("foo_get").unwrap();
        assert!(result.0 == b"bar");
        assert!(result.1 == 0);
    }
}

#[test]
fn delete() {
    let config = r2d2::Config::default();
    let manager = MemcacheConnectionManager::new("localhost:11211").unwrap();

    let pool = r2d2::Pool::new(config, manager).unwrap();
    {
        let pool = pool.clone();
        let mut conn = pool.get().unwrap();
        conn.delete("foo").unwrap();
    }
}

#[test]
fn incr() {
    let config = r2d2::Config::default();
    let manager = MemcacheConnectionManager::new("localhost:11211").unwrap();

    let pool = r2d2::Pool::new(config, manager).unwrap();
    {
        let pool = pool.clone();
        let mut conn = pool.get().unwrap();
        let value = &memcache::Raw {
            bytes: b"100",
            flags: 0
        };
        conn.set("foo_incr", value).unwrap();
        assert!(conn.incr("foo_incr", 1).unwrap() == Some(101));
    }
}

#[test]
fn decr() {
    let config = r2d2::Config::default();
    let manager = MemcacheConnectionManager::new("localhost:11211").unwrap();

    let pool = r2d2::Pool::new(config, manager).unwrap();
    {
        let pool = pool.clone();
        let mut conn = pool.get().unwrap();
        let value = &memcache::Raw {
            bytes: b"100",
            flags: 0
        };
        conn.set("foo_decr", value).unwrap();
        assert!(conn.decr("foo_decr", 1).unwrap() == Some(99));
    }
}
<|endoftext|>


<commit_before>use std::boxed::Box;
use std::cmp;
use std::collections::BTreeSet;
use std::ops::Range;

pub struct ItemList {
    clipping_range_max_len: usize,
    clipping_range_start: usize,
    highlighted_row: Option<usize>,
    line_indices: Box<Indices>,
    marked_line_indices: BTreeSet<usize>,
}

impl ItemList {
    pub fn new(clipping_range_max_len: usize) -> Self {
        assert!(clipping_range_max_len > 0);
        ItemList {
            clipping_range_max_len: clipping_range_max_len,
            clipping_range_start: 0,
            highlighted_row: None,
            line_indices: Box::new(0..0),
            marked_line_indices: BTreeSet::new(),
        }
    }

    pub fn highlighted_row(&self) -> Option<usize> {
        self.highlighted_row
    }

    pub fn len(&self) -> usize {
        self.line_indices.count()
    }

    pub fn line_indices_in_clipping_range(&self) -> Vec<usize> {
        self.line_indices.boxed_iter()
            .skip(self.clipping_range_start)
            .take(self.clipping_range_end())
            .collect()
    }

    pub fn selected_line_indices(&self) -> Vec<usize> {
        match self.marked_line_indices.len() {
            0 => {
                match self.highlighted_row {
                    None => Vec::new(),
                    Some(row) => {
                        let i = self.clipping_range_start + row;
                        vec![self.line_indices.at(i)]
                    }
                }
            }
            _ => self.marked_line_indices.iter().cloned().collect(),
        }
    }

    pub fn marked_rows(&self) -> Vec<usize> {
        self.line_indices_in_clipping_range().iter()
            .enumerate()
            .filter_map(|(i, idx)| {
                if self.marked_line_indices.contains(idx) { Some(i) } else { None }
            })
            .collect()
    }

    pub fn toggle_mark(&mut self) {
        if let Some(row) = self.highlighted_row {
            let i = self.clipping_range_start + row;
            let line_index = self.line_indices.at(i);
            if !self.marked_line_indices.remove(&line_index) {
                self.marked_line_indices.insert(line_index);
            }
        }
    }

    pub fn set_line_indices(&mut self, line_indices: Vec<usize>) {
        self.set_line_indices_with_box::<Vec<usize>>(Box::new(line_indices));
    }

    pub fn set_line_index_range(&mut self, range: Range<usize>) {
        self.set_line_indices_with_box::<Range<usize>>(Box::new(range));
    }

    pub fn move_highlight_backward(&mut self) {
        if let Some(row) = self.highlighted_row {
            if row == 0 {
                self.scroll_backward();
                return;
            }
            self.highlighted_row = Some(row - 1);
        }
    }

    pub fn move_highlight_forward(&mut self) {
        if let Some(row) = self.highlighted_row {
            if Some(row) == self.max_row() {
                self.scroll_forward();
                return;
            }
            self.highlighted_row = Some(row + 1);
        }
    }

    pub fn scroll_backward(&mut self) {
        if self.clipping_range_start > 0 {
            self.clipping_range_start -= 1;
        }
    }

    pub fn scroll_forward(&mut self) {
        if self.clipping_range_end() < self.len() {
            self.clipping_range_start += 1;
        }
    }

    fn set_line_indices_with_box<T: Indices>(&mut self, line_indices: Box<Indices>) {
        self.line_indices = line_indices;
        let overrun = self.clipping_range_end().saturating_sub(self.len());
        self.clipping_range_start = self.clipping_range_start.saturating_sub(overrun);
        match (self.highlighted_row, self.max_row()) {
            (Some(row), Some(max_row)) if row > max_row => {
                self.highlighted_row = Some(max_row);
            }
            (None, Some(_)) => {
                self.highlighted_row = Some(0);
            }
            (_, None) => {
                self.highlighted_row = None;
            }
            (_, _) => { }
        }
        debug_assert!(
            (self.highlighted_row.is_some() && self.max_row().is_some()) ||
            (self.highlighted_row.is_none() && self.max_row().is_none()));
    }

    fn clipping_range_end(&self) -> usize {
        self.clipping_range_start + self.clipping_range_len()
    }

    fn clipping_range_len(&self) -> usize {
        cmp::min(self.len(), self.clipping_range_max_len)
    }

    fn max_row(&self) -> Option<usize> {
        match self.clipping_range_len() {
            0 => None,
            i => Some(i - 1),
        }
    }
}

pub trait Indices {
    fn at(&self, i: usize) -> usize;
    fn boxed_iter<'a>(&'a self) -> Box<Iterator<Item=usize> + 'a>;
    fn count(&self) -> usize;
}

impl Indices for Range<usize> {
    fn at(&self, i: usize) -> usize {
        assert!(i < self.end);
        i
    }

    fn boxed_iter<'a>(&'a self) -> Box<Iterator<Item=usize> + 'a> {
        Box::new(self.clone())
    }

    fn count(&self) -> usize {
        self.clone().count()
    }
}

impl Indices for Vec<usize> {
    fn at(&self, i: usize) -> usize {
        unsafe { *self.get_unchecked(i) }
    }

    fn boxed_iter<'a>(&'a self) -> Box<Iterator<Item=usize> + 'a> {
        Box::new(self.iter().map(|i| *i))
    }

    fn count(&self) -> usize {
        self.len()
    }
}
<commit_msg>Rename Indices::count() to Indices::len()<commit_after>use std::boxed::Box;
use std::cmp;
use std::collections::BTreeSet;
use std::ops::Range;

pub struct ItemList {
    clipping_range_max_len: usize,
    clipping_range_start: usize,
    highlighted_row: Option<usize>,
    line_indices: Box<Indices>,
    marked_line_indices: BTreeSet<usize>,
}

impl ItemList {
    pub fn new(clipping_range_max_len: usize) -> Self {
        assert!(clipping_range_max_len > 0);
        ItemList {
            clipping_range_max_len: clipping_range_max_len,
            clipping_range_start: 0,
            highlighted_row: None,
            line_indices: Box::new(0..0),
            marked_line_indices: BTreeSet::new(),
        }
    }

    pub fn highlighted_row(&self) -> Option<usize> {
        self.highlighted_row
    }

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

    pub fn line_indices_in_clipping_range(&self) -> Vec<usize> {
        self.line_indices.boxed_iter()
            .skip(self.clipping_range_start)
            .take(self.clipping_range_end())
            .collect()
    }

    pub fn selected_line_indices(&self) -> Vec<usize> {
        match self.marked_line_indices.len() {
            0 => {
                match self.highlighted_row {
                    None => Vec::new(),
                    Some(row) => {
                        let i = self.clipping_range_start + row;
                        vec![self.line_indices.at(i)]
                    }
                }
            }
            _ => self.marked_line_indices.iter().cloned().collect(),
        }
    }

    pub fn marked_rows(&self) -> Vec<usize> {
        self.line_indices_in_clipping_range().iter()
            .enumerate()
            .filter_map(|(i, idx)| {
                if self.marked_line_indices.contains(idx) { Some(i) } else { None }
            })
            .collect()
    }

    pub fn toggle_mark(&mut self) {
        if let Some(row) = self.highlighted_row {
            let i = self.clipping_range_start + row;
            let line_index = self.line_indices.at(i);
            if !self.marked_line_indices.remove(&line_index) {
                self.marked_line_indices.insert(line_index);
            }
        }
    }

    pub fn set_line_indices(&mut self, line_indices: Vec<usize>) {
        self.set_line_indices_with_box::<Vec<usize>>(Box::new(line_indices));
    }

    pub fn set_line_index_range(&mut self, range: Range<usize>) {
        self.set_line_indices_with_box::<Range<usize>>(Box::new(range));
    }

    pub fn move_highlight_backward(&mut self) {
        if let Some(row) = self.highlighted_row {
            if row == 0 {
                self.scroll_backward();
                return;
            }
            self.highlighted_row = Some(row - 1);
        }
    }

    pub fn move_highlight_forward(&mut self) {
        if let Some(row) = self.highlighted_row {
            if Some(row) == self.max_row() {
                self.scroll_forward();
                return;
            }
            self.highlighted_row = Some(row + 1);
        }
    }

    pub fn scroll_backward(&mut self) {
        if self.clipping_range_start > 0 {
            self.clipping_range_start -= 1;
        }
    }

    pub fn scroll_forward(&mut self) {
        if self.clipping_range_end() < self.len() {
            self.clipping_range_start += 1;
        }
    }

    fn set_line_indices_with_box<T: Indices>(&mut self, line_indices: Box<Indices>) {
        self.line_indices = line_indices;
        let overrun = self.clipping_range_end().saturating_sub(self.len());
        self.clipping_range_start = self.clipping_range_start.saturating_sub(overrun);
        match (self.highlighted_row, self.max_row()) {
            (Some(row), Some(max_row)) if row > max_row => {
                self.highlighted_row = Some(max_row);
            }
            (None, Some(_)) => {
                self.highlighted_row = Some(0);
            }
            (_, None) => {
                self.highlighted_row = None;
            }
            (_, _) => { }
        }
        debug_assert!(
            (self.highlighted_row.is_some() && self.max_row().is_some()) ||
            (self.highlighted_row.is_none() && self.max_row().is_none()));
    }

    fn clipping_range_end(&self) -> usize {
        self.clipping_range_start + self.clipping_range_len()
    }

    fn clipping_range_len(&self) -> usize {
        cmp::min(self.len(), self.clipping_range_max_len)
    }

    fn max_row(&self) -> Option<usize> {
        match self.clipping_range_len() {
            0 => None,
            i => Some(i - 1),
        }
    }
}

pub trait Indices {
    fn at(&self, i: usize) -> usize;
    fn boxed_iter<'a>(&'a self) -> Box<Iterator<Item=usize> + 'a>;
    fn len(&self) -> usize;
}

impl Indices for Range<usize> {
    fn at(&self, i: usize) -> usize {
        assert!(i < self.end);
        i
    }

    fn boxed_iter<'a>(&'a self) -> Box<Iterator<Item=usize> + 'a> {
        Box::new(self.clone())
    }

    fn len(&self) -> usize {
        <Self as ExactSizeIterator>::len(&self)
    }
}

impl Indices for Vec<usize> {
    fn at(&self, i: usize) -> usize {
        unsafe { *self.get_unchecked(i) }
    }

    fn boxed_iter<'a>(&'a self) -> Box<Iterator<Item=usize> + 'a> {
        Box::new(self.iter().map(|i| *i))
    }

    fn len(&self) -> usize {
        Vec::len(&self)
    }
}
<|endoftext|>


<commit_before><commit_msg>Simplify index sub-module.<commit_after><|endoftext|>


<commit_before>use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::ops::Deref;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::cell::UnsafeCell;
use std::marker::Sync;
use {Future, Poll, Async};
use task::{self, Task};
use lock::Lock;

/// A wrapped item of the original future.
/// It is clonable and implements Deref for ease of use.
#[derive(Debug)]
pub struct SharedItem<T> {
    item: Arc<T>,
}

impl<T> Clone for SharedItem<T> {
    fn clone(&self) -> Self {
        SharedItem { item: self.item.clone() }
    }
}

impl<T> Deref for SharedItem<T> {
    type Target = T;

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

/// A wrapped error of the original future.
/// It is clonable and implements Deref for ease of use.
#[derive(Debug)]
pub struct SharedError<E> {
    error: Arc<E>,
}

impl<T> Clone for SharedError<T> {
    fn clone(&self) -> Self {
        SharedError { error: self.error.clone() }
    }
}

impl<E> Deref for SharedError<E> {
    type Target = E;

    fn deref(&self) -> &E {
        &self.error.as_ref()
    }
}

impl<T> SharedItem<T> {
    fn new(item: T) -> Self {
        SharedItem { item: Arc::new(item) }
    }
}

impl<E> SharedError<E> {
    fn new(error: E) -> Self {
        SharedError { error: Arc::new(error) }
    }
}

/// The data that has to be synced to implement `Shared`,
/// in order to satisfy the `Future` trait's constraints.
struct SyncedInner<F>
    where F: Future
{
    original_future: F, // The original future
}

struct Inner<F>
    where F: Future
{
    synced_inner: Lock<SyncedInner<F>>,
    tasks_unpark_started: AtomicBool,
    /// When original future is polled and ready, unparks all the tasks in that channel
    tasks_receiver: Lock<Receiver<Task>>,
    /// The original future result wrapped with `SharedItem`/`SharedError`
    result: UnsafeCell<Option<Result<SharedItem<F::Item>, SharedError<F::Error>>>>,
}

unsafe impl<F> Sync for Inner<F> where F: Future {}

/// TODO: doc
#[must_use = "futures do nothing unless polled"]
pub struct Shared<F>
    where F: Future
{
    inner: Arc<Inner<F>>,
    tasks_sender: Sender<Task>,
}

impl<F> Shared<F>
    where F: Future
{
    fn result_to_polled_result(result: Result<SharedItem<F::Item>, SharedError<F::Error>>)
                               -> Result<Async<SharedItem<F::Item>>, SharedError<F::Error>> {
        match result {
            Ok(item) => Ok(Async::Ready(item)),
            Err(error) => Err(error),
        }
    }
}

pub fn new<F>(future: F) -> Shared<F>
    where F: Future
{
    let (tasks_sender, tasks_receiver) = channel();
    Shared {
        inner: Arc::new(Inner {
            synced_inner: Lock::new(SyncedInner { original_future: future }),
            tasks_unpark_started: AtomicBool::new(false),
            tasks_receiver: Lock::new(tasks_receiver),
            result: UnsafeCell::new(None),
        }),
        tasks_sender: tasks_sender,
    }
}

impl<F> Future for Shared<F>
    where F: Future
{
    type Item = SharedItem<F::Item>;
    type Error = SharedError<F::Error>;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        // The logic is as follows:
        // 1. Check if the result is ready (with tasks_unpark_started)
        //  - If the result is ready, return it.
        //  - Otherwise:
        // 2. Try lock the self.inner.synced_inner:
        //    - If successfully locked, poll the original future.
        //      If the future is ready, unpark the tasks from
        //      self.inner.tasks_receiver and return the result.
        //    - If the future is not ready:
        // 3. Create a task and send it through self.tasks_sender.
        // 4. Check again if the result is ready (with tasks_unpark_started)
        // 5. Return the result if it's ready. It is necessary because otherwise there could be
        //    a race between the task sending and the thread receiving the tasks.

        let mut should_unpark_tasks: bool = false;

        // If the result is ready, just return it
        if self.inner.tasks_unpark_started.load(Ordering::Relaxed) {
            unsafe {
                if let Some(ref result) = *self.inner.result.get() {
                    return Self::result_to_polled_result(result.clone());
                }
            }
        }

        // The result was not ready.
        match self.inner.synced_inner.try_lock() {
            Some(mut inner_guard) => {
                let ref mut inner = *inner_guard;
                unsafe {
                    // Other thread could poll the result, so we check if result has a value
                    if (*self.inner.result.get()).is_some() {
                        should_unpark_tasks = true;
                    } else {
                        match inner.original_future.poll() {
                            Ok(Async::Ready(item)) => {
                                *self.inner.result.get() = Some(Ok(SharedItem::new(item)));
                                should_unpark_tasks = true;
                            }
                            Err(error) => {
                                *self.inner.result.get() = Some(Err(SharedError::new(error)));
                                should_unpark_tasks = true;
                            }
                            Ok(Async::NotReady) => {} // Will be handled later
                        }
                    }
                }
            }
            None => {} // Will be handled later
        }

        if should_unpark_tasks {
            self.inner.tasks_unpark_started.store(true, Ordering::Relaxed);
            match self.inner.tasks_receiver.try_lock() {
                Some(tasks_receiver_guard) => {
                    let ref tasks_receiver = *tasks_receiver_guard;
                    loop {
                        match tasks_receiver.try_recv() {
                            Ok(task) => task.unpark(),
                            _ => break,
                        }
                    }
                }
                None => {} // Other thread is unparking the tasks
            }

            unsafe {
                if let Some(ref result) = *self.inner.result.get() {
                    return Self::result_to_polled_result(result.clone());
                } else {
                    // How should I use unwrap here?
                    // The compiler says cannot "move out of borrowed content"
                    unreachable!();
                }
            }
        }

        let t = task::park();
        let _ = self.tasks_sender.send(t);
        if self.inner.tasks_unpark_started.load(Ordering::Relaxed) {
            // If the tasks unpark has started, self.inner.result has a value (not None).
            // The result must be read here because it is possible that the task,
            // t (see variable above), had not been unparked.
            unsafe {
                if let Some(ref result) = *self.inner.result.get() {
                    return Self::result_to_polled_result(result.clone());
                } else {
                    // How should I use unwrap here?
                    // The compiler says cannot "move out of borrowed content"
                    unreachable!();
                }
            }
        }

        Ok(Async::NotReady)
    }
}

impl<F> Clone for Shared<F>
    where F: Future
{
    fn clone(&self) -> Self {
        Shared {
            inner: self.inner.clone(),
            tasks_sender: self.tasks_sender.clone(),
        }
    }
}
<commit_msg>Use RwLock synced methods instead of unsafe blocks<commit_after>use std::sync::{Arc, RwLock};
use std::sync::atomic::{AtomicBool, Ordering};
use std::ops::Deref;
use std::sync::mpsc::{channel, Receiver, Sender};
use {Future, Poll, Async};
use task::{self, Task};
use lock::Lock;

/// A wrapped item of the original future.
/// It is clonable and implements Deref for ease of use.
#[derive(Debug)]
pub struct SharedItem<T> {
    item: Arc<T>,
}

impl<T> Clone for SharedItem<T> {
    fn clone(&self) -> Self {
        SharedItem { item: self.item.clone() }
    }
}

impl<T> Deref for SharedItem<T> {
    type Target = T;

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

/// A wrapped error of the original future.
/// It is clonable and implements Deref for ease of use.
#[derive(Debug)]
pub struct SharedError<E> {
    error: Arc<E>,
}

impl<T> Clone for SharedError<T> {
    fn clone(&self) -> Self {
        SharedError { error: self.error.clone() }
    }
}

impl<E> Deref for SharedError<E> {
    type Target = E;

    fn deref(&self) -> &E {
        &self.error.as_ref()
    }
}

impl<T> SharedItem<T> {
    fn new(item: T) -> Self {
        SharedItem { item: Arc::new(item) }
    }
}

impl<E> SharedError<E> {
    fn new(error: E) -> Self {
        SharedError { error: Arc::new(error) }
    }
}

struct SyncedInner<F>
    where F: Future
{
    /// The original future that is wrapped as `Shared`
    original_future: F,
    /// When original future is polled and ready, all the tasks in that channel will be unparked
    tasks_receiver: Receiver<Task>,
}

struct Inner<F>
    where F: Future
{
    /// The original future and the tasks receiver behind a mutex
    synced_inner: Lock<SyncedInner<F>>,
    /// Indicates whether the result is ready, and the tasks unparking has been started
    tasks_unpark_started: AtomicBool,
    /// The original future result wrapped with `SharedItem`/`SharedError`
    result: RwLock<Option<Result<SharedItem<F::Item>, SharedError<F::Error>>>>,
}

/// TODO: doc
#[must_use = "futures do nothing unless polled"]
pub struct Shared<F>
    where F: Future
{
    inner: Arc<Inner<F>>,
    tasks_sender: Sender<Task>,
}

impl<F> Shared<F>
    where F: Future
{
    fn result_to_polled_result(result: Result<SharedItem<F::Item>, SharedError<F::Error>>)
                               -> Result<Async<SharedItem<F::Item>>, SharedError<F::Error>> {
        match result {
            Ok(item) => Ok(Async::Ready(item)),
            Err(error) => Err(error),
        }
    }

    fn unpark_tasks(&self, tasks_receiver: &mut Receiver<Task>) {
        self.inner.tasks_unpark_started.store(true, Ordering::Relaxed);
        loop {
            match tasks_receiver.try_recv() {
                Ok(task) => task.unpark(),
                _ => break,
            }
        }
    }
}

pub fn new<F>(future: F) -> Shared<F>
    where F: Future
{
    let (tasks_sender, tasks_receiver) = channel();
    Shared {
        inner: Arc::new(Inner {
            synced_inner: Lock::new(SyncedInner {
                original_future: future,
                tasks_receiver: tasks_receiver,
            }),
            tasks_unpark_started: AtomicBool::new(false),
            result: RwLock::new(None),
        }),
        tasks_sender: tasks_sender,
    }
}

impl<F> Future for Shared<F>
    where F: Future
{
    type Item = SharedItem<F::Item>;
    type Error = SharedError<F::Error>;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        // The logic is as follows:
        // 1. Check if the result is ready (with tasks_unpark_started)
        //  - If the result is ready, return it.
        //  - Otherwise:
        // 2. Try lock the self.inner.original_future:
        //    - If successfully locked, poll the original future.
        //      If the future is ready, unpark the tasks from
        //      self.inner.tasks_receiver and return the result.
        //    - If the future is not ready:
        // 3. Create a task and send it through self.tasks_sender.
        // 4. Check again if the result is ready (with tasks_unpark_started)
        // 5. Return the result if it's ready. It is necessary because otherwise there could be
        //    a race between the task sending and the thread receiving the tasks.

        // If the result is ready, just return it
        if self.inner.tasks_unpark_started.load(Ordering::Relaxed) {
            return Self::result_to_polled_result(self.inner
                .result
                .read()
                .unwrap()
                .clone()
                .unwrap());
        }

        // The result was not ready.
        // Try lock the original future.
        match self.inner.synced_inner.try_lock() {
            Some(mut synced_inner) => {
                let ref mut synced_inner = *synced_inner;
                let ref mut original_future = synced_inner.original_future;
                let mut result = self.inner.result.write().unwrap();
                // Other thread could already poll the result, so we check if result has a value
                if result.is_none() {
                    match original_future.poll() {
                        Ok(Async::Ready(item)) => {
                            *result = Some(Ok(SharedItem::new(item)));
                            self.unpark_tasks(&mut synced_inner.tasks_receiver);
                            return Self::result_to_polled_result(result.clone().unwrap());
                        }
                        Err(error) => {
                            *result = Some(Err(SharedError::new(error)));
                            self.unpark_tasks(&mut synced_inner.tasks_receiver);
                            return Self::result_to_polled_result(result.clone().unwrap());
                        }
                        Ok(Async::NotReady) => {} // A task will be parked
                    }
                }
            }
            None => {} // A task will be parked
        }

        let t = task::park();
        let _ = self.tasks_sender.send(t);
        if self.inner.tasks_unpark_started.load(Ordering::Relaxed) {
            // If the tasks unpark has been started, self.inner.result has a value (not None).
            // The result must be read now even after sending the parked task
            // because it is possible that the task, t (see variable above),
            // had not been unparked.
            // That's because self.inner.tasks_receiver could has tasks that will never be unparked,
            // because the tasks receiving loop could have ended before receiving
            // the new task, t).
            return Self::result_to_polled_result(self.inner
                .result
                .read()
                .unwrap()
                .clone()
                .unwrap());
        }

        Ok(Async::NotReady)
    }
}

impl<F> Clone for Shared<F>
    where F: Future
{
    fn clone(&self) -> Self {
        Shared {
            inner: self.inner.clone(),
            tasks_sender: self.tasks_sender.clone(),
        }
    }
}
<|endoftext|>


<commit_before>// This test attempts to force the dynamic linker to resolve
// external symbols as close to the red zone as possible.

use std;
import task;
import std::rand;

extern mod rustrt {
    fn debug_get_stk_seg() -> *u8;

    fn rust_get_sched_id() -> libc::intptr_t;
    fn last_os_error() -> ~str;
    fn rust_getcwd() -> ~str;
    fn get_task_id() -> libc::intptr_t;
    fn sched_threads();
    fn rust_get_task();
}

fn calllink01() { rustrt::rust_get_sched_id(); }
fn calllink02() { rustrt::last_os_error(); }
fn calllink03() { rustrt::rust_getcwd(); }
fn calllink08() { rustrt::get_task_id(); }
fn calllink09() { rustrt::sched_threads(); }
fn calllink10() { rustrt::rust_get_task(); }

fn runtest(f: fn~(), frame_backoff: u32) {
    runtest2(f, frame_backoff, 0 as *u8);
}

fn runtest2(f: fn~(), frame_backoff: u32, last_stk: *u8) -> u32 {
    let curr_stk = rustrt::debug_get_stk_seg();
    if (last_stk != curr_stk && last_stk != 0 as *u8) {
        // We switched stacks, go back and try to hit the dynamic linker
        frame_backoff
    } else {
        let frame_backoff = runtest2(f, frame_backoff, curr_stk);
        if frame_backoff > 1u32 {
            frame_backoff - 1u32
        } else if frame_backoff == 1u32 {
            f();
            0u32
        } else {
            0u32
        }
    }
}

fn main() {
    let fns = ~[
        calllink01,
        calllink02,
        calllink03,
        calllink08,
        calllink09,
        calllink10
    ];
    let rng = rand::rng();
    for fns.each |f| {
        let sz = rng.next() % 256u32 + 256u32;
        let frame_backoff = rng.next() % 10u32 + 1u32;
        task::try(|| runtest(f, frame_backoff) );
    }
}
<commit_msg>Remove nonexistent imports<commit_after>// This test attempts to force the dynamic linker to resolve
// external symbols as close to the red zone as possible.

extern mod rustrt {
    fn debug_get_stk_seg() -> *u8;

    fn rust_get_sched_id() -> libc::intptr_t;
    fn last_os_error() -> ~str;
    fn rust_getcwd() -> ~str;
    fn get_task_id() -> libc::intptr_t;
    fn sched_threads();
    fn rust_get_task();
}

fn calllink01() { rustrt::rust_get_sched_id(); }
fn calllink02() { rustrt::last_os_error(); }
fn calllink03() { rustrt::rust_getcwd(); }
fn calllink08() { rustrt::get_task_id(); }
fn calllink09() { rustrt::sched_threads(); }
fn calllink10() { rustrt::rust_get_task(); }

fn runtest(f: fn~(), frame_backoff: u32) {
    runtest2(f, frame_backoff, 0 as *u8);
}

fn runtest2(f: fn~(), frame_backoff: u32, last_stk: *u8) -> u32 {
    let curr_stk = rustrt::debug_get_stk_seg();
    if (last_stk != curr_stk && last_stk != 0 as *u8) {
        // We switched stacks, go back and try to hit the dynamic linker
        frame_backoff
    } else {
        let frame_backoff = runtest2(f, frame_backoff, curr_stk);
        if frame_backoff > 1u32 {
            frame_backoff - 1u32
        } else if frame_backoff == 1u32 {
            f();
            0u32
        } else {
            0u32
        }
    }
}

fn main() {
    let fns = ~[
        calllink01,
        calllink02,
        calllink03,
        calllink08,
        calllink09,
        calllink10
    ];
    let rng = rand::rng();
    for fns.each |f| {
        let sz = rng.next() % 256u32 + 256u32;
        let frame_backoff = rng.next() % 10u32 + 1u32;
        task::try(|| runtest(f, frame_backoff) );
    }
}
<|endoftext|>


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

// ignore-linux see joyent/libuv#1189
// ignore-fast
// ignore-android needs extra network permissions
// exec-env:RUST_LOG=debug

use std::libc;
use std::io::net::ip::{Ipv4Addr, SocketAddr};
use std::io::net::tcp::{TcpListener, TcpStream};
use std::io::{Acceptor, Listener};

fn main() {
    // This test has a chance to time out, try to not let it time out
    spawn(proc() {
        use std::io::timer;
        timer::sleep(30 * 1000);
        println!("timed out!");
        unsafe { libc::exit(1) }
    });

    let addr = SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 0 };
    let (p, c) = Chan::new();
    spawn(proc() {
        let mut listener = TcpListener::bind(addr).unwrap();
        c.send(listener.socket_name().unwrap());
        let mut acceptor = listener.listen();
        loop {
            let mut stream = match acceptor.accept() {
                Ok(stream) => stream,
                Err(error) => {
                    debug!("accept failed: {:?}", error);
                    continue;
                }
            };
            stream.read_byte();
            stream.write([2]);
        }
    });
    let addr = p.recv();

    let (p, c) = Chan::new();
    for _ in range(0, 1000) {
        let c = c.clone();
        spawn(proc() {
            match TcpStream::connect(addr) {
                Ok(stream) => {
                    let mut stream = stream;
                    stream.write([1]);
                    let mut buf = [0];
                    stream.read(buf);
                },
                Err(e) => debug!("{:?}", e)
            }
            c.send(());
        });
    }

    // Wait for all clients to exit, but don't wait for the server to exit. The
    // server just runs infinitely.
    drop(c);
    for _ in range(0, 1000) {
        p.recv();
    }
    unsafe { libc::exit(0) }
}
<commit_msg>auto merge of #12880 : tedhorst/rust/master, r=alexcrichton<commit_after>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-linux see joyent/libuv#1189
// ignore-fast
// ignore-android needs extra network permissions
// exec-env:RUST_LOG=debug

use std::libc;
use std::io::net::ip::{Ipv4Addr, SocketAddr};
use std::io::net::tcp::{TcpListener, TcpStream};
use std::io::{Acceptor, Listener};

fn main() {
    // This test has a chance to time out, try to not let it time out
    spawn(proc() {
        use std::io::timer;
        timer::sleep(30 * 1000);
        println!("timed out!");
        unsafe { libc::exit(1) }
    });

    let addr = SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 0 };
    let (tx, rx) = channel();
    spawn(proc() {
        let mut listener = TcpListener::bind(addr).unwrap();
        tx.send(listener.socket_name().unwrap());
        let mut acceptor = listener.listen();
        loop {
            let mut stream = match acceptor.accept() {
                Ok(stream) => stream,
                Err(error) => {
                    debug!("accept failed: {:?}", error);
                    continue;
                }
            };
            stream.read_byte();
            stream.write([2]);
        }
    });
    let addr = rx.recv();

    let (tx, rx) = channel();
    for _ in range(0, 1000) {
        let tx = tx.clone();
        spawn(proc() {
            match TcpStream::connect(addr) {
                Ok(stream) => {
                    let mut stream = stream;
                    stream.write([1]);
                    let mut buf = [0];
                    stream.read(buf);
                },
                Err(e) => debug!("{:?}", e)
            }
            tx.send(());
        });
    }

    // Wait for all clients to exit, but don't wait for the server to exit. The
    // server just runs infinitely.
    drop(tx);
    for _ in range(0, 1000) {
        rx.recv();
    }
    unsafe { libc::exit(0) }
}
<|endoftext|>


<commit_before><commit_msg>Added a (non-working) load_bin_file.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Do not ignore errors when collecting links<commit_after><|endoftext|>


<commit_before><commit_msg>fix unix process mutex<commit_after><|endoftext|>


<commit_before>// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

pub use device::target::Color;
use device::target::{Plane, PlaneEmpty};

static MAX_COLOR_TARGETS: uint = 4;

/// A complete `Frame`, which is the result of rendering.
pub struct Frame {
    /// Each color component has its own buffer.
    pub colors: [Plane, ..MAX_COLOR_TARGETS],
    /// The depth buffer for this frame.
    pub depth: Plane,
    /// The stencil buffer for this frame.
    pub stencil: Plane,
}

impl Frame {
    /// Create an empty `Frame`, which corresponds to the "default framebuffer", which for now
    /// renders directly to the window that was created with the OpenGL context.
    pub fn new() -> Frame {
        Frame {
            colors: [PlaneEmpty, ..MAX_COLOR_TARGETS],
            depth: PlaneEmpty,
            stencil: PlaneEmpty,
        }
    }

    /// An empty frame is considered to match the default framebuffer
    pub fn is_default(&self) -> bool {
        self.colors.iter().all(|&p| p==PlaneEmpty) &&
        self.depth == PlaneEmpty &&
        self.stencil == PlaneEmpty
    }
}
<commit_msg>Frame clarification<commit_after>// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

pub use device::target::Color;
use device::target::{Plane, PlaneEmpty};

static MAX_COLOR_TARGETS: uint = 4;

/// A complete `Frame`, which is the result of rendering.
pub struct Frame {
    /// Each color component has its own buffer.
    pub colors: [Plane, ..MAX_COLOR_TARGETS],
    /// The depth buffer for this frame.
    pub depth: Plane,
    /// The stencil buffer for this frame.
    pub stencil: Plane,
}

impl Frame {
    /// Create an empty `Frame`, which corresponds to the 'default framebuffer', which for now
    /// renders directly to the window that was created with the OpenGL context.
    pub fn new() -> Frame {
        Frame {
            colors: [PlaneEmpty, ..MAX_COLOR_TARGETS],
            depth: PlaneEmpty,
            stencil: PlaneEmpty,
        }
    }

    /// Returns true if this framebuffer is associated with the main window (matches `Frame::new`
    /// exactly).
    pub fn is_default(&self) -> bool {
        self.colors.iter().all(|&p| p==PlaneEmpty) &&
        self.depth == PlaneEmpty &&
        self.stencil == PlaneEmpty
    }
}
<|endoftext|>


<commit_before><commit_msg>style(tokenizer): rustfmt<commit_after><|endoftext|>


<commit_before><commit_msg>Use single-line comments in preference to multi-line comments<commit_after><|endoftext|>


<commit_before><commit_msg>Fix up public key search logic<commit_after><|endoftext|>


<commit_before><commit_msg>Auto merge of #396 - kbknapp:fix-nightly, r=kbknapp<commit_after><|endoftext|>


<commit_before><commit_msg>smart move works now<commit_after><|endoftext|>


<commit_before><commit_msg>adds node devices basics<commit_after>/*
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * Sahid Orentino Ferdjaoui <sahid.ferdjaoui@redhat.com>
 */

#![allow(improper_ctypes)]

extern crate libc;

use std::ffi::{CString, CStr};
use std::str;

use connect::{Connect, virConnectPtr};
use error::Error;

#[allow(non_camel_case_types)]
#[repr(C)]
pub struct virNodeDevice {
}

#[allow(non_camel_case_types)]
pub type virNodeDevicePtr = *const virNodeDevice;

#[link(name = "virt")]
extern {
    fn virNodeDeviceLookupByName(c: virConnectPtr,id: *const libc::c_char) -> virNodeDevicePtr;
    fn virNodeDeviceCreateXML(c: virConnectPtr, xml: *const libc::c_char, flags: libc::c_uint) -> virNodeDevicePtr;
    fn virNodeDeviceDestroy(d: virNodeDevicePtr) -> libc::c_int;
    fn virNodeDeviceFree(d: virNodeDevicePtr) -> libc::c_int;
    fn virNodeDeviceGetName(d: virNodeDevicePtr) -> *const libc::c_char;
    fn virNodeDeviceGetXMLDesc(d: virNodeDevicePtr, flags: libc::c_uint) -> *const libc::c_char;
}

pub type NodeDeviceXMLFlags = self::libc::c_uint;
pub const VIR_INTERFACE_XML_INACTIVE:NodeDeviceXMLFlags = 1 << 0;

pub struct NodeDevice {
    pub d: virNodeDevicePtr
}

impl NodeDevice {

    pub fn as_ptr(&self) -> virNodeDevicePtr {
        self.d
    }

    pub fn lookup_by_name(conn: &Connect, id: &str) -> Result<NodeDevice, Error> {
        unsafe {
            let ptr = virNodeDeviceLookupByName(
                conn.as_ptr(), CString::new(id).unwrap().as_ptr());
            if ptr.is_null() {
                return Err(Error::new());
            }
            return Ok(NodeDevice{d: ptr});
        }
    }

    pub fn create_xml(conn: &Connect, xml: &str, flags: u32) -> Result<NodeDevice, Error> {
        unsafe {
            let ptr = virNodeDeviceCreateXML(
                conn.as_ptr(), CString::new(xml).unwrap().as_ptr(),
                flags as libc::c_uint);
            if ptr.is_null() {
                return Err(Error::new());
            }
            return Ok(NodeDevice{d: ptr});
        }
    }

    pub fn get_name(&self) -> Result<&str, Error> {
        unsafe {
            let n = virNodeDeviceGetName(self.d);
            if n.is_null() {
                return Err(Error::new())
            }
            return Ok(str::from_utf8(
                CStr::from_ptr(n).to_bytes()).unwrap())
        }
    }

    pub fn get_xml_desc(&self, flags: u32) -> Result<&str, Error> {
        unsafe {
            let xml = virNodeDeviceGetXMLDesc(self.d, flags as libc::c_uint);
            if xml.is_null() {
                return Err(Error::new())
            }
            return Ok(str::from_utf8(
                CStr::from_ptr(xml).to_bytes()).unwrap())
        }
    }

    pub fn destroy(&self) -> Result<(), Error> {
        unsafe {
            if virNodeDeviceDestroy(self.d) == -1 {
                return Err(Error::new());
            }
            return Ok(());
        }
    }

    pub fn free(&self) -> Result<(), Error> {
        unsafe {
            if virNodeDeviceFree(self.d) == -1 {
                return Err(Error::new());
            }
            return Ok(());
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>use a request object to create new requests this allows us to implement e.g. pagers or others usefull stuff later<commit_after>#![allow(dead_code)]
#![allow(unused_imports)]
#![allow(warnings)]
#![allow(unused)]

use error;
use reqwest;
use reqwest::IntoUrl;
use response::Response;
use serde_derive;
use serde_json;
use serde;
use serde::Serializer;
use std;
use std::collections::HashMap;
use std::process::exit;
use std::result::Result;
use std::thread;
use std::time;
use types;

#[derive(Debug, Clone)]
pub struct Request<'a> {
    pub url: &'a str,
    parameter: HashMap<&'a str, String>,
}

impl<'a> Request<'a> {
    pub fn new(url: &'a str) -> Self {
        Self {
            parameter: HashMap::new(),
            url: url,
        }
    }

    pub fn get_paramter(self) -> HashMap<&'a str, String> {
        self.parameter.to_owned()
    }

    pub fn get_url(self) -> &'a str {
        self.url
    }

    pub fn add_parameter(&mut self, parameter: &'a str, value: String) {
        self.parameter.insert(parameter, value);
    }

    pub fn remove_parameter(&mut self, parameter: &str) {
        self.parameter.remove(parameter);
    }
}
<|endoftext|>


<commit_before><commit_msg>good option<commit_after><|endoftext|>


<commit_before><commit_msg>some additional changes<commit_after><|endoftext|>


<commit_before><commit_msg>Attempted to add a shape handle with method forwarding but it doesn't yet compile<commit_after><|endoftext|>


<commit_before><commit_msg>Add a test<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.

// @has macros/macro.my_macro!.html //pre 'macro_rules! my_macro {'
// @has - //pre '() => { ... };'
// @has - //pre '($a:tt) => { ... };'
// @has - //pre '($e:expr) => { ... };'
#[macro_export]
macro_rules! my_macro {
    () => [];
    ($a:tt) => ();
    ($e:expr) => {};
}
<|endoftext|>


<commit_before><commit_msg>Add test for #66930<commit_after>// check-pass
// compile-flags: --emit=mir,link
// Regression test for #66930, this ICE requires `--emit=mir` flag.

static UTF8_CHAR_WIDTH: [u8; 0] = [];

pub fn utf8_char_width(b: u8) -> usize {
    UTF8_CHAR_WIDTH[b as usize] as usize
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Fix Formatting in build.rs<commit_after><|endoftext|>


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

// pretty-expanded FIXME #23616

#![feature(collections)]

fn is_sync<T>(_: T) where T: Sync {}
fn is_send<T>(_: T) where T: Send {}

macro_rules! all_sync_send {
    ($ctor:expr, $($iter:ident),+) => ({
        $(
            let mut x = $ctor;
            is_sync(x.$iter());
            let mut y = $ctor;
            is_send(y.$iter());
        )+
    })
}

fn main() {
    // for char.rs
    all_sync_send!("Я", escape_default, escape_unicode);

    // for iter.rs
    // FIXME

    // for option.rs
    // FIXME

    // for result.rs
    // FIXME

    // for slice.rs
    // FIXME

    // for str/mod.rs
    // FIXME
}
<|endoftext|>


<commit_before><commit_msg>remove useless code<commit_after><|endoftext|>


<commit_before><commit_msg>Add first integration test<commit_after>extern crate ldap;

use std::thread;
use std::time::Duration;

use ldap::LDAP;
use ldap::Result;

#[test]
fn test_bind() {
    use ldap::bind::{ldap_bind_s, ldap_unbind};

    let mut conn = LDAP::connect("localhost:389").unwrap();

    ldap_bind_s(&mut conn, "cn=root,dc=aicube,dc=renet".to_string(), "secret".to_string());

    thread::sleep(Duration::new(1, 0));

    conn.read();

    ldap_unbind(&mut conn);

    thread::sleep(Duration::new(1, 0));

    conn.read();
}
<|endoftext|>


<commit_before><commit_msg>Add FxHasher, a faster alternative to FnvHasher.<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.

use std::collections::{HashMap, HashSet};
use std::default::Default;
use std::hash::{Hasher, Hash, BuildHasherDefault};
use std::ops::BitXor;

pub type FxHashMap<K, V> = HashMap<K, V, BuildHasherDefault<FxHasher>>;
pub type FxHashSet<V> = HashSet<V, BuildHasherDefault<FxHasher>>;

#[allow(non_snake_case)]
pub fn FxHashMap<K: Hash + Eq, V>() -> FxHashMap<K, V> {
    HashMap::default()
}

#[allow(non_snake_case)]
pub fn FxHashSet<V: Hash + Eq>() -> FxHashSet<V> {
    HashSet::default()
}

/// A speedy hash algorithm for use within rustc. The hashmap in libcollections
/// by default uses SipHash which isn't quite as speedy as we want. In the
/// compiler we're not really worried about DOS attempts, so we use a fast
/// non-cryptographic hash.
///
/// This is the same as the algorithm used by Firefox -- which is a homespun
/// one not based on any widely-known algorithm -- though modified to produce
/// 64-bit hash values instead of 32-bit hash values. It consistently
/// out-performs an FNV-based hash within rustc itself -- the collision rate is
/// similar or slightly worse than FNV, but the speed of the hash function
/// itself is much higher because it works on up to 8 bytes at a time.
pub struct FxHasher {
    hash: usize
}

#[cfg(target_pointer_width = "32")]
const K: usize = 0x9e3779b9;
#[cfg(target_pointer_width = "64")]
const K: usize = 0x517cc1b727220a95;

impl Default for FxHasher {
    #[inline]
    fn default() -> FxHasher {
        FxHasher { hash: 0 }
    }
}

impl FxHasher {
    #[inline]
    fn add_to_hash(&mut self, i: usize) {
        self.hash = self.hash.rotate_left(5).bitxor(i).wrapping_mul(K);
    }
}

impl Hasher for FxHasher {
    #[inline]
    fn write(&mut self, bytes: &[u8]) {
        for byte in bytes {
            let i = *byte;
            self.add_to_hash(i as usize);
        }
    }

    #[inline]
    fn write_u8(&mut self, i: u8) {
        self.add_to_hash(i as usize);
    }

    #[inline]
    fn write_u16(&mut self, i: u16) {
        self.add_to_hash(i as usize);
    }

    #[inline]
    fn write_u32(&mut self, i: u32) {
        self.add_to_hash(i as usize);
    }

    #[cfg(target_pointer_width = "32")]
    #[inline]
    fn write_u64(&mut self, i: u64) {
        self.add_to_hash(i as usize);
        self.add_to_hash((i >> 32) as usize);
    }

    #[cfg(target_pointer_width = "64")]
    #[inline]
    fn write_u64(&mut self, i: u64) {
        self.add_to_hash(i as usize);
    }

    #[inline]
    fn write_usize(&mut self, i: usize) {
        self.add_to_hash(i);
    }

    #[inline]
    fn finish(&self) -> u64 {
        self.hash as u64
    }
}

pub fn hash<T: Hash>(v: &T) -> u64 {
    let mut state = FxHasher::default();
    v.hash(&mut state);
    state.finish()
}
<|endoftext|>


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

/*!
 * Atomic types
 */

use unstable::intrinsics;
use cast;
use option::{Option,Some,None};
use libc::c_void;
use ops::Drop;

pub struct AtomicFlag {
    priv v: int
}

pub struct AtomicBool {
    priv v: uint
}

pub struct AtomicInt {
    priv v: int
}

pub struct AtomicUint {
    priv v: uint
}

pub struct AtomicPtr<T> {
    priv p: *mut T
}

pub struct AtomicOption<T> {
    priv p: *mut c_void
}

pub enum Ordering {
    Release,
    Acquire,
    SeqCst
}

impl AtomicFlag {

    fn new() -> AtomicFlag {
        AtomicFlag { v: 0 }
    }

    /**
     * Clears the atomic flag
     */
    #[inline(always)]
    fn clear(&mut self, order: Ordering) {
        unsafe {atomic_store(&mut self.v, 0, order)}
    }

    #[inline(always)]
    /**
     * Sets the flag if it was previously unset, returns the previous value of the
     * flag.
     */
    fn test_and_set(&mut self, order: Ordering) -> bool {
        unsafe {atomic_compare_and_swap(&mut self.v, 0, 1, order) > 0}
    }
}

impl AtomicBool {
    fn new(v: bool) -> AtomicBool {
        AtomicBool { v: if v { 1 } else { 0 } }
    }

    #[inline(always)]
    fn load(&self, order: Ordering) -> bool {
        unsafe { atomic_load(&self.v, order) > 0 }
    }

    #[inline(always)]
    fn store(&mut self, val: bool, order: Ordering) {
        let val = if val { 1 } else { 0 };

        unsafe { atomic_store(&mut self.v, val, order); }
    }

    #[inline(always)]
    fn swap(&mut self, val: bool, order: Ordering) -> bool {
        let val = if val { 1 } else { 0 };

        unsafe { atomic_swap(&mut self.v, val, order) > 0}
    }

    #[inline(always)]
    fn compare_and_swap(&mut self, old: bool, new: bool, order: Ordering) -> bool {
        let old = if old { 1 } else { 0 };
        let new = if new { 1 } else { 0 };

        unsafe { atomic_compare_and_swap(&mut self.v, old, new, order) > 0 }
    }
}

impl AtomicInt {
    fn new(v: int) -> AtomicInt {
        AtomicInt { v:v }
    }

    #[inline(always)]
    fn load(&self, order: Ordering) -> int {
        unsafe { atomic_load(&self.v, order) }
    }

    #[inline(always)]
    fn store(&mut self, val: int, order: Ordering) {
        unsafe { atomic_store(&mut self.v, val, order); }
    }

    #[inline(always)]
    fn swap(&mut self, val: int, order: Ordering) -> int {
        unsafe { atomic_swap(&mut self.v, val, order) }
    }

    #[inline(always)]
    fn compare_and_swap(&mut self, old: int, new: int, order: Ordering) -> int {
        unsafe { atomic_compare_and_swap(&mut self.v, old, new, order) }
    }

    #[inline(always)]
    fn fetch_add(&mut self, val: int, order: Ordering) -> int {
        unsafe { atomic_add(&mut self.v, val, order) }
    }

    #[inline(always)]
    fn fetch_sub(&mut self, val: int, order: Ordering) -> int {
        unsafe { atomic_sub(&mut self.v, val, order) }
    }
}

impl AtomicUint {
    fn new(v: uint) -> AtomicUint {
        AtomicUint { v:v }
    }

    #[inline(always)]
    fn load(&self, order: Ordering) -> uint {
        unsafe { atomic_load(&self.v, order) }
    }

    #[inline(always)]
    fn store(&mut self, val: uint, order: Ordering) {
        unsafe { atomic_store(&mut self.v, val, order); }
    }

    #[inline(always)]
    fn swap(&mut self, val: uint, order: Ordering) -> uint {
        unsafe { atomic_swap(&mut self.v, val, order) }
    }

    #[inline(always)]
    fn compare_and_swap(&mut self, old: uint, new: uint, order: Ordering) -> uint {
        unsafe { atomic_compare_and_swap(&mut self.v, old, new, order) }
    }

    #[inline(always)]
    fn fetch_add(&mut self, val: uint, order: Ordering) -> uint {
        unsafe { atomic_add(&mut self.v, val, order) }
    }

    #[inline(always)]
    fn fetch_sub(&mut self, val: uint, order: Ordering) -> uint {
        unsafe { atomic_sub(&mut self.v, val, order) }
    }
}

impl<T> AtomicPtr<T> {
    fn new(p: *mut T) -> AtomicPtr<T> {
        AtomicPtr { p:p }
    }

    #[inline(always)]
    fn load(&self, order: Ordering) -> *mut T {
        unsafe { atomic_load(&self.p, order) }
    }

    #[inline(always)]
    fn store(&mut self, ptr: *mut T, order: Ordering) {
        unsafe { atomic_store(&mut self.p, ptr, order); }
    }

    #[inline(always)]
    fn swap(&mut self, ptr: *mut T, order: Ordering) -> *mut T {
        unsafe { atomic_swap(&mut self.p, ptr, order) }
    }

    #[inline(always)]
    fn compare_and_swap(&mut self, old: *mut T, new: *mut T, order: Ordering) -> *mut T {
        unsafe { atomic_compare_and_swap(&mut self.p, old, new, order) }
    }
}

impl<T> AtomicOption<T> {
    fn new(p: ~T) -> AtomicOption<T> {
        unsafe {
            AtomicOption {
                p: cast::transmute(p)
            }
        }
    }

    fn empty() -> AtomicOption<T> {
        unsafe {
            AtomicOption {
                p: cast::transmute(0)
            }
        }
    }

    #[inline(always)]
    fn swap(&mut self, val: ~T, order: Ordering) -> Option<~T> {
        unsafe {
            let val = cast::transmute(val);

            let p = atomic_swap(&mut self.p, val, order);
            let pv : &uint = cast::transmute(&p);

            if *pv == 0 {
                None
            } else {
                Some(cast::transmute(p))
            }
        }
    }

    #[inline(always)]
    fn take(&mut self, order: Ordering) -> Option<~T> {
        unsafe {
            self.swap(cast::transmute(0), order)
        }
    }
}

#[unsafe_destructor]
impl<T> Drop for AtomicOption<T> {
    fn finalize(&self) {
        // This will ensure that the contained data is
        // destroyed, unless it's null.
        unsafe {
            let this : &mut AtomicOption<T> = cast::transmute(self);
            let _ = this.take(SeqCst);
        }
    }
}

#[inline(always)]
pub unsafe fn atomic_store<T>(dst: &mut T, val: T, order:Ordering) {
    let dst = cast::transmute(dst);
    let val = cast::transmute(val);

    match order {
        Release => intrinsics::atomic_store_rel(dst, val),
        _       => intrinsics::atomic_store(dst, val)
    }
}

#[inline(always)]
pub unsafe fn atomic_load<T>(dst: &T, order:Ordering) -> T {
    let dst = cast::transmute(dst);

    cast::transmute(match order {
        Acquire => intrinsics::atomic_load_acq(dst),
        _       => intrinsics::atomic_load(dst)
    })
}

#[inline(always)]
pub unsafe fn atomic_swap<T>(dst: &mut T, val: T, order: Ordering) -> T {
    let dst = cast::transmute(dst);
    let val = cast::transmute(val);

    cast::transmute(match order {
        Acquire => intrinsics::atomic_xchg_acq(dst, val),
        Release => intrinsics::atomic_xchg_rel(dst, val),
        _       => intrinsics::atomic_xchg(dst, val)
    })
}

#[inline(always)]
pub unsafe fn atomic_add<T>(dst: &mut T, val: T, order: Ordering) -> T {
    let dst = cast::transmute(dst);
    let val = cast::transmute(val);

    cast::transmute(match order {
        Acquire => intrinsics::atomic_xadd_acq(dst, val),
        Release => intrinsics::atomic_xadd_rel(dst, val),
        _       => intrinsics::atomic_xadd(dst, val)
    })
}

#[inline(always)]
pub unsafe fn atomic_sub<T>(dst: &mut T, val: T, order: Ordering) -> T {
    let dst = cast::transmute(dst);
    let val = cast::transmute(val);

    cast::transmute(match order {
        Acquire => intrinsics::atomic_xsub_acq(dst, val),
        Release => intrinsics::atomic_xsub_rel(dst, val),
        _       => intrinsics::atomic_xsub(dst, val)
    })
}

#[inline(always)]
pub unsafe fn atomic_compare_and_swap<T>(dst:&mut T, old:T, new:T, order: Ordering) -> T {
    let dst = cast::transmute(dst);
    let old = cast::transmute(old);
    let new = cast::transmute(new);

    cast::transmute(match order {
        Acquire => intrinsics::atomic_cxchg_acq(dst, old, new),
        Release => intrinsics::atomic_cxchg_rel(dst, old, new),
        _       => intrinsics::atomic_cxchg(dst, old, new),
    })
}

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

    #[test]
    fn flag() {
        let mut flg = AtomicFlag::new();
        assert!(!flg.test_and_set(SeqCst));
        assert!(flg.test_and_set(SeqCst));

        flg.clear(SeqCst);
        assert!(!flg.test_and_set(SeqCst));
    }

    #[test]
    fn option_swap() {
        let mut p = AtomicOption::new(~1);
        let a = ~2;

        let b = p.swap(a, SeqCst);

        assert_eq!(b, Some(~1));
        assert_eq!(p.take(SeqCst), Some(~2));
    }

    #[test]
    fn option_take() {
        let mut p = AtomicOption::new(~1);

        assert_eq!(p.take(SeqCst), Some(~1));
        assert_eq!(p.take(SeqCst), None);

        let p2 = ~2;
        p.swap(p2, SeqCst);

        assert_eq!(p.take(SeqCst), Some(~2));
    }

}
<commit_msg>Add some documentation<commit_after>// Copyright 2012-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.

/*!
 * Atomic types
 *
 * Basic atomic types supporting atomic operations. Each method takes an `Ordering` which
 * represents the strength of the memory barrier for that operation. These orderings are the same
 * as C++11 atomic orderings [http://gcc.gnu.org/wiki/Atomic/GCCMM/AtomicSync]
 *
 * All atomic types are a single word in size.
 */

use unstable::intrinsics;
use cast;
use option::{Option,Some,None};
use libc::c_void;
use ops::Drop;

/**
 * A simple atomic flag, that can be set and cleared. The most basic atomic type.
 */
pub struct AtomicFlag {
    priv v: int
}

/**
 * An atomic boolean type.
 */
pub struct AtomicBool {
    priv v: uint
}

/**
 * A signed atomic integer type, supporting basic atomic aritmetic operations
 */
pub struct AtomicInt {
    priv v: int
}

/**
 * An unsigned atomic integer type, supporting basic atomic aritmetic operations
 */
pub struct AtomicUint {
    priv v: uint
}

/**
 * An unsafe atomic pointer. Only supports basic atomic operations
 */
pub struct AtomicPtr<T> {
    priv p: *mut T
}

/**
 * An owned atomic pointer. Ensures that only a single reference to the data is held at any time.
 */
pub struct AtomicOption<T> {
    priv p: *mut c_void
}

pub enum Ordering {
    Release,
    Acquire,
    SeqCst
}

impl AtomicFlag {

    fn new() -> AtomicFlag {
        AtomicFlag { v: 0 }
    }

    /**
     * Clears the atomic flag
     */
    #[inline(always)]
    fn clear(&mut self, order: Ordering) {
        unsafe {atomic_store(&mut self.v, 0, order)}
    }

    /**
     * Sets the flag if it was previously unset, returns the previous value of the
     * flag.
     */
    #[inline(always)]
    fn test_and_set(&mut self, order: Ordering) -> bool {
        unsafe {atomic_compare_and_swap(&mut self.v, 0, 1, order) > 0}
    }
}

impl AtomicBool {
    fn new(v: bool) -> AtomicBool {
        AtomicBool { v: if v { 1 } else { 0 } }
    }

    #[inline(always)]
    fn load(&self, order: Ordering) -> bool {
        unsafe { atomic_load(&self.v, order) > 0 }
    }

    #[inline(always)]
    fn store(&mut self, val: bool, order: Ordering) {
        let val = if val { 1 } else { 0 };

        unsafe { atomic_store(&mut self.v, val, order); }
    }

    #[inline(always)]
    fn swap(&mut self, val: bool, order: Ordering) -> bool {
        let val = if val { 1 } else { 0 };

        unsafe { atomic_swap(&mut self.v, val, order) > 0}
    }

    #[inline(always)]
    fn compare_and_swap(&mut self, old: bool, new: bool, order: Ordering) -> bool {
        let old = if old { 1 } else { 0 };
        let new = if new { 1 } else { 0 };

        unsafe { atomic_compare_and_swap(&mut self.v, old, new, order) > 0 }
    }
}

impl AtomicInt {
    fn new(v: int) -> AtomicInt {
        AtomicInt { v:v }
    }

    #[inline(always)]
    fn load(&self, order: Ordering) -> int {
        unsafe { atomic_load(&self.v, order) }
    }

    #[inline(always)]
    fn store(&mut self, val: int, order: Ordering) {
        unsafe { atomic_store(&mut self.v, val, order); }
    }

    #[inline(always)]
    fn swap(&mut self, val: int, order: Ordering) -> int {
        unsafe { atomic_swap(&mut self.v, val, order) }
    }

    #[inline(always)]
    fn compare_and_swap(&mut self, old: int, new: int, order: Ordering) -> int {
        unsafe { atomic_compare_and_swap(&mut self.v, old, new, order) }
    }

    #[inline(always)]
    fn fetch_add(&mut self, val: int, order: Ordering) -> int {
        unsafe { atomic_add(&mut self.v, val, order) }
    }

    #[inline(always)]
    fn fetch_sub(&mut self, val: int, order: Ordering) -> int {
        unsafe { atomic_sub(&mut self.v, val, order) }
    }
}

impl AtomicUint {
    fn new(v: uint) -> AtomicUint {
        AtomicUint { v:v }
    }

    #[inline(always)]
    fn load(&self, order: Ordering) -> uint {
        unsafe { atomic_load(&self.v, order) }
    }

    #[inline(always)]
    fn store(&mut self, val: uint, order: Ordering) {
        unsafe { atomic_store(&mut self.v, val, order); }
    }

    #[inline(always)]
    fn swap(&mut self, val: uint, order: Ordering) -> uint {
        unsafe { atomic_swap(&mut self.v, val, order) }
    }

    #[inline(always)]
    fn compare_and_swap(&mut self, old: uint, new: uint, order: Ordering) -> uint {
        unsafe { atomic_compare_and_swap(&mut self.v, old, new, order) }
    }

    #[inline(always)]
    fn fetch_add(&mut self, val: uint, order: Ordering) -> uint {
        unsafe { atomic_add(&mut self.v, val, order) }
    }

    #[inline(always)]
    fn fetch_sub(&mut self, val: uint, order: Ordering) -> uint {
        unsafe { atomic_sub(&mut self.v, val, order) }
    }
}

impl<T> AtomicPtr<T> {
    fn new(p: *mut T) -> AtomicPtr<T> {
        AtomicPtr { p:p }
    }

    #[inline(always)]
    fn load(&self, order: Ordering) -> *mut T {
        unsafe { atomic_load(&self.p, order) }
    }

    #[inline(always)]
    fn store(&mut self, ptr: *mut T, order: Ordering) {
        unsafe { atomic_store(&mut self.p, ptr, order); }
    }

    #[inline(always)]
    fn swap(&mut self, ptr: *mut T, order: Ordering) -> *mut T {
        unsafe { atomic_swap(&mut self.p, ptr, order) }
    }

    #[inline(always)]
    fn compare_and_swap(&mut self, old: *mut T, new: *mut T, order: Ordering) -> *mut T {
        unsafe { atomic_compare_and_swap(&mut self.p, old, new, order) }
    }
}

impl<T> AtomicOption<T> {
    fn new(p: ~T) -> AtomicOption<T> {
        unsafe {
            AtomicOption {
                p: cast::transmute(p)
            }
        }
    }

    fn empty() -> AtomicOption<T> {
        unsafe {
            AtomicOption {
                p: cast::transmute(0)
            }
        }
    }

    #[inline(always)]
    fn swap(&mut self, val: ~T, order: Ordering) -> Option<~T> {
        unsafe {
            let val = cast::transmute(val);

            let p = atomic_swap(&mut self.p, val, order);
            let pv : &uint = cast::transmute(&p);

            if *pv == 0 {
                None
            } else {
                Some(cast::transmute(p))
            }
        }
    }

    #[inline(always)]
    fn take(&mut self, order: Ordering) -> Option<~T> {
        unsafe {
            self.swap(cast::transmute(0), order)
        }
    }
}

#[unsafe_destructor]
impl<T> Drop for AtomicOption<T> {
    fn finalize(&self) {
        // This will ensure that the contained data is
        // destroyed, unless it's null.
        unsafe {
            let this : &mut AtomicOption<T> = cast::transmute(self);
            let _ = this.take(SeqCst);
        }
    }
}

#[inline(always)]
pub unsafe fn atomic_store<T>(dst: &mut T, val: T, order:Ordering) {
    let dst = cast::transmute(dst);
    let val = cast::transmute(val);

    match order {
        Release => intrinsics::atomic_store_rel(dst, val),
        _       => intrinsics::atomic_store(dst, val)
    }
}

#[inline(always)]
pub unsafe fn atomic_load<T>(dst: &T, order:Ordering) -> T {
    let dst = cast::transmute(dst);

    cast::transmute(match order {
        Acquire => intrinsics::atomic_load_acq(dst),
        _       => intrinsics::atomic_load(dst)
    })
}

#[inline(always)]
pub unsafe fn atomic_swap<T>(dst: &mut T, val: T, order: Ordering) -> T {
    let dst = cast::transmute(dst);
    let val = cast::transmute(val);

    cast::transmute(match order {
        Acquire => intrinsics::atomic_xchg_acq(dst, val),
        Release => intrinsics::atomic_xchg_rel(dst, val),
        _       => intrinsics::atomic_xchg(dst, val)
    })
}

#[inline(always)]
pub unsafe fn atomic_add<T>(dst: &mut T, val: T, order: Ordering) -> T {
    let dst = cast::transmute(dst);
    let val = cast::transmute(val);

    cast::transmute(match order {
        Acquire => intrinsics::atomic_xadd_acq(dst, val),
        Release => intrinsics::atomic_xadd_rel(dst, val),
        _       => intrinsics::atomic_xadd(dst, val)
    })
}

#[inline(always)]
pub unsafe fn atomic_sub<T>(dst: &mut T, val: T, order: Ordering) -> T {
    let dst = cast::transmute(dst);
    let val = cast::transmute(val);

    cast::transmute(match order {
        Acquire => intrinsics::atomic_xsub_acq(dst, val),
        Release => intrinsics::atomic_xsub_rel(dst, val),
        _       => intrinsics::atomic_xsub(dst, val)
    })
}

#[inline(always)]
pub unsafe fn atomic_compare_and_swap<T>(dst:&mut T, old:T, new:T, order: Ordering) -> T {
    let dst = cast::transmute(dst);
    let old = cast::transmute(old);
    let new = cast::transmute(new);

    cast::transmute(match order {
        Acquire => intrinsics::atomic_cxchg_acq(dst, old, new),
        Release => intrinsics::atomic_cxchg_rel(dst, old, new),
        _       => intrinsics::atomic_cxchg(dst, old, new),
    })
}

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

    #[test]
    fn flag() {
        let mut flg = AtomicFlag::new();
        assert!(!flg.test_and_set(SeqCst));
        assert!(flg.test_and_set(SeqCst));

        flg.clear(SeqCst);
        assert!(!flg.test_and_set(SeqCst));
    }

    #[test]
    fn option_swap() {
        let mut p = AtomicOption::new(~1);
        let a = ~2;

        let b = p.swap(a, SeqCst);

        assert_eq!(b, Some(~1));
        assert_eq!(p.take(SeqCst), Some(~2));
    }

    #[test]
    fn option_take() {
        let mut p = AtomicOption::new(~1);

        assert_eq!(p.take(SeqCst), Some(~1));
        assert_eq!(p.take(SeqCst), None);

        let p2 = ~2;
        p.swap(p2, SeqCst);

        assert_eq!(p.take(SeqCst), Some(~2));
    }

}
<|endoftext|>


<commit_before><commit_msg>some initial tests for the router<commit_after><|endoftext|>


<commit_before><commit_msg>Begin writing guessing game<commit_after>use std::rand::random;

fn main() {
    let random_value = random::<u8>() % 10u8;
    let mut guess = 0u8;

    println!("{}", random_value);

}
<|endoftext|>


<commit_before><commit_msg>Add a test for extra::rl.<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.

// xfail-fast no compile flags for check-fast

// we want this to be compiled to avoid bitrot, but the actual test
//has to be conducted by a human, i.e. someone (you?) compiling this
//file with a plain rustc invocation and running it and checking it
//works.

// compile-flags: --cfg robot_mode

extern mod extra;
use extra::rl;

static HISTORY_FILE: &'static str = "rl-human-test-history.txt";

fn main() {
    // don't run this in robot mode, but still typecheck it.
    if !cfg!(robot_mode) {
        println("~~ Welcome to the rl test \"suite\". ~~");
        println!("Operations:
 - restrict the history to 2 lines,
 - set the tab-completion to suggest three copies of each of the last 3 letters (or 'empty'),
 - add 'one' and 'two' to the history,
 - save it to `{0}`,
 - add 'three',
 - prompt & save input (check the history & completion work and contains only 'two', 'three'),
 - load from `{0}`
 - prompt & save input (history should be 'one', 'two' again),
 - prompt once more.

The bool return values of each step are printed.",
                 HISTORY_FILE);

        println!("restricting history length: {}", rl::set_history_max_len(3));

        do rl::complete |line, suggest| {
            if line.is_empty() {
                suggest(~"empty")
            } else {
                for c in line.rev_iter().take(3) {
                    suggest(format!("{0}{1}{1}{1}", line, c))
                }
            }
        }

        println!("adding 'one': {}", rl::add_history("one"));
        println!("adding 'two': {}", rl::add_history("two"));

        println!("saving history: {}", rl::save_history(HISTORY_FILE));

        println!("adding 'three': {}", rl::add_history("three"));

        match rl::read("> ") {
            Some(s) => println!("saving input: {}", rl::add_history(s)),
            None => return
        }
        println!("loading history: {}", rl::load_history(HISTORY_FILE));

        match rl::read("> ") {
            Some(s) => println!("saving input: {}", rl::add_history(s)),
            None => return
        }

        rl::read("> ");
    }
}
<|endoftext|>


<commit_before>fn main() {
    log 3-2;
    assert 3-2 == 1;
}<commit_msg>Revert "Test for #954"<commit_after><|endoftext|>


<commit_before><commit_msg>Test for associated types ICE<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.

// Test that a partially specified trait object with unspecified associated
// type does not ICE.

#![feature(associated_types)]

trait Foo {
    type A;
}

fn bar(x: &Foo) {} //~ERROR missing type for associated type `A`

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


<commit_before><commit_msg>Rollup merge of #42217 - venkatagiri:issue_39974, r=Mark-Simulacrum<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.

const LENGTH: f64 = 2;

struct Thing {
    f: [[f64; 2]; LENGTH],
    //~^ ERROR mismatched types
    //~| expected usize, found f64
}

fn main() {
    let _t = Thing { f: [[0.0, 0.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]] };
}
<|endoftext|>


<commit_before>// xfail-pretty

#[legacy_modes];

extern mod std;
extern mod syntax;

use io::*;

use syntax::diagnostic;
use syntax::ast;
use syntax::codemap;
use syntax::parse;
use syntax::print::*;

trait fake_ext_ctxt {
    fn cfg() -> ast::crate_cfg;
    fn parse_sess() -> parse::parse_sess;
}

type fake_session = parse::parse_sess;

impl fake_session: fake_ext_ctxt {
    fn cfg() -> ast::crate_cfg { ~[] }
    fn parse_sess() -> parse::parse_sess { self }
}

fn mk_ctxt() -> fake_ext_ctxt {
    parse::new_parse_sess(None) as fake_ext_ctxt
}

fn main() {
    let ext_cx = mk_ctxt();

    let abc = #ast{23};
    check_pp(ext_cx, abc,  pprust::print_expr, ~"23");

    let expr3 = #ast{2 - $(abc) + 7};
    check_pp(ext_cx, expr3,  pprust::print_expr, ~"2 - 23 + 7");

    let expr4 = #ast{2 - $(#ast{3}) + 9};
    check_pp(ext_cx, expr4,  pprust::print_expr, ~"2 - 3 + 9");

    let ty = #ast[ty]{int};
    check_pp(ext_cx, ty, pprust::print_type, ~"int");

    let ty2 = #ast[ty]{option<$(ty)>};
    check_pp(ext_cx, ty2, pprust::print_type, ~"option<int>");

    let item = #ast[item]{const x : int = 10;};
    check_pp(ext_cx, item, pprust::print_item, ~"const x: int = 10;");

    let item2: @ast::item = #ast[item]{const x : int = $(abc);};
    check_pp(ext_cx, item2, pprust::print_item, ~"const x: int = 23;");

    let stmt = #ast[stmt]{let x = 20;};
    check_pp(ext_cx, *stmt, pprust::print_stmt, ~"let x = 20;");

    let stmt2 = #ast[stmt]{let x : $(ty) = $(abc);};
    check_pp(ext_cx, *stmt2, pprust::print_stmt, ~"let x: int = 23;");

    let pat = #ast[pat]{some(_)};
    check_pp(ext_cx, pat, pprust::print_pat, ~"some(_)");

    // issue #1785
    let x = #ast{1};
    let test1 = #ast{1+$(x)};
    check_pp(ext_cx, test1, pprust::print_expr, ~"1 + 1");

    let test2 = #ast{$(x)+1};
    check_pp(ext_cx, test2, pprust::print_expr, ~"1 + 1");

    let y = #ast{2};
    let test3 = #ast{$(x) + $(y)};
    check_pp(ext_cx, test3, pprust::print_expr, ~"1 + 2");

    let crate = #ast[crate] { fn a() { } };
    check_pp(ext_cx, crate, pprust::print_crate_, ~"fn a() { }\n");

    // issue #1926
    let s = #ast[expr]{__s};
    let e = #ast[expr]{__e};
    let call = #ast[expr]{$(s).foo(|__e| $(e) )};
    check_pp(ext_cx, call, pprust::print_expr, ~"__s.foo(|__e| __e)")
}

fn check_pp<T>(cx: fake_ext_ctxt,
               expr: T, f: fn(pprust::ps, T), expect: ~str) {
    let s = do io::with_str_writer |wr| {
        let pp = pprust::rust_printer(wr, cx.parse_sess().interner);
        f(pp, expr);
        pp::eof(pp.s);
    };
    stdout().write_line(s);
    if expect != ~"" {
        error!("expect: '%s', got: '%s'", expect, s);
        assert str == expect;
    }
}

<commit_msg>Fix run-pass-fulldeps/qquote.rs<commit_after>// xfail-pretty

#[legacy_modes];

extern mod std;
extern mod syntax;

use io::*;

use syntax::diagnostic;
use syntax::ast;
use syntax::codemap;
use syntax::parse;
use syntax::print::*;

trait fake_ext_ctxt {
    fn cfg() -> ast::crate_cfg;
    fn parse_sess() -> parse::parse_sess;
}

type fake_session = parse::parse_sess;

impl fake_session: fake_ext_ctxt {
    fn cfg() -> ast::crate_cfg { ~[] }
    fn parse_sess() -> parse::parse_sess { self }
}

fn mk_ctxt() -> fake_ext_ctxt {
    parse::new_parse_sess(None) as fake_ext_ctxt
}

fn main() {
    let ext_cx = mk_ctxt();

    let abc = #ast{23};
    check_pp(ext_cx, abc,  pprust::print_expr, ~"23");

    let expr3 = #ast{2 - $(abc) + 7};
    check_pp(ext_cx, expr3,  pprust::print_expr, ~"2 - 23 + 7");

    let expr4 = #ast{2 - $(#ast{3}) + 9};
    check_pp(ext_cx, expr4,  pprust::print_expr, ~"2 - 3 + 9");

    let ty = #ast[ty]{int};
    check_pp(ext_cx, ty, pprust::print_type, ~"int");

    let ty2 = #ast[ty]{option<$(ty)>};
    check_pp(ext_cx, ty2, pprust::print_type, ~"option<int>");

    let item = #ast[item]{const x : int = 10;};
    check_pp(ext_cx, item, pprust::print_item, ~"const x: int = 10;");

    let item2: @ast::item = #ast[item]{const x : int = $(abc);};
    check_pp(ext_cx, item2, pprust::print_item, ~"const x: int = 23;");

    let stmt = #ast[stmt]{let x = 20;};
    check_pp(ext_cx, *stmt, pprust::print_stmt, ~"let x = 20;");

    let stmt2 = #ast[stmt]{let x : $(ty) = $(abc);};
    check_pp(ext_cx, *stmt2, pprust::print_stmt, ~"let x: int = 23;");

    let pat = #ast[pat]{some(_)};
    check_pp(ext_cx, pat, pprust::print_pat, ~"some(_)");

    // issue #1785
    let x = #ast{1};
    let test1 = #ast{1+$(x)};
    check_pp(ext_cx, test1, pprust::print_expr, ~"1 + 1");

    let test2 = #ast{$(x)+1};
    check_pp(ext_cx, test2, pprust::print_expr, ~"1 + 1");

    let y = #ast{2};
    let test3 = #ast{$(x) + $(y)};
    check_pp(ext_cx, test3, pprust::print_expr, ~"1 + 2");

    let crate = #ast[crate] { fn a() { } };
    check_pp(ext_cx, crate, pprust::print_crate_, ~"fn a() { }\n");

    // issue #1926
    let s = #ast[expr]{__s};
    let e = #ast[expr]{__e};
    let call = #ast[expr]{$(s).foo(|__e| $(e) )};
    check_pp(ext_cx, call, pprust::print_expr, ~"__s.foo(|__e| __e)")
}

fn check_pp<T>(cx: fake_ext_ctxt,
               expr: T, f: fn(pprust::ps, T), expect: ~str) {
    let s = do io::with_str_writer |wr| {
        let pp = pprust::rust_printer(wr, cx.parse_sess().interner);
        f(pp, expr);
        pp::eof(pp.s);
    };
    stdout().write_line(s);
    if expect != ~"" {
        error!("expect: '%s', got: '%s'", expect, s);
        assert s == expect;
    }
}

<|endoftext|>


<commit_before><commit_msg>Add test of unsupported elided lifetime in extern Rust sig<commit_after>use std::marker::PhantomData;

#[cxx::bridge]
mod ffi {
    extern "Rust" {
        type T;

        fn f(t: &T) -> &str;
    }
}

pub struct T<'a> {
    _lifetime: PhantomData<&'a ()>,
}

fn f<'a>(_t: &T<'a>) -> &'a str {
    ""
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>added solution for exercise 5.2<commit_after>/// Type in the program that copies a file using line-at-a-time I/O
/// (fgets and fputs) from Figure 5.5, but use a MAXLINE of 4.

extern crate libc;
extern crate apue;

use libc::{fopen, fgets, fputs, printf};
use apue::*;

const BUFLEN: usize = 4;

fn main() {
	unsafe {
		let mut args = std::env::args();
		if args.len() != 3 {
			println!("usage:\n{} /path/to/input /path/to/output", args.next().unwrap());
			std::process::exit(1);
		}
		args.next(); // skip filename
		let f_in = args.next().unwrap();
		let f_out = args.next().unwrap();
		let fd_in = fopen(f_in.to_ptr(), "r".to_ptr());
		let fd_out = fopen(f_out.to_ptr(), "w".to_ptr());

		let buffer:[u8;BUFLEN] = std::mem::uninitialized();
		while !fgets(buffer.as_ptr() as *mut i8, BUFLEN as i32, fd_in).is_null() {
			printf("buffer = %s\n".to_ptr(), buffer.as_ptr());
			fputs(buffer.as_ptr() as *mut i8, fd_out);
		}
	}
}

// # Solution:

// What happens if you copy lines that exceed this length?
// Explain what is happening.

// Answer: the line is cut into chunks of 3 (3 bytes + null)
// the last chunk of a line can be smaller, so e.g. just 1 byte + null
//
// e.g.
// hansaplasti
// - han
// - sap
// - las
// - ti<|endoftext|>


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

struct GradFn<F: Fn() -> usize>(F);

fn main() {
    let GradFn(x_squared) : GradFn<_> = GradFn(|| -> usize { 2 });
    let _  = x_squared();
}
<|endoftext|>


<commit_before><commit_msg>Add another test for blocks as expressions<commit_after>// xfail-boot
// -*- rust -*-

// Tests for standalone blocks as expressions

fn test_basic() {
  let bool res = { true };
  check (res);
}

fn test_rec() {
  auto res = { rec(v1 = 10, v2 = 20) };
  check (res.v2 == 20);
}

fn test_filled_with_stuff() {
  auto res = {
    auto a = 0;
    while (a < 10) {
      a += 1;
    }
    a
  };
  check (res == 10);
}

fn main() {
  test_basic();
  test_rec();
  test_filled_with_stuff();
}
<|endoftext|>