<commit_before><commit_msg>Add reftest that checks the layout of repr(int) on non-c-like enums<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// This test deserializes an enum in-place by transmuting to a union that
// should have the same layout, and manipulating the tag and payloads
// independently. This verifies that `repr(some_int)` has a stable representation,
// and that we don't miscompile these kinds of manipulations.

use std::time::Duration;
use std::mem;

#[repr(u8)]
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum MyEnum {
    A(u32),                 // Single primitive value
    B { x: u8, y: i16 },    // Composite, and the offset of `y` depends on tag being internal
    C,                      // Empty
    D(Option<u32>),         // Contains an enum
    E(Duration),            // Contains a struct
}

#[allow(non_snake_case)]
#[repr(C)]
union MyEnumRepr {
    A: MyEnumVariantA,
    B: MyEnumVariantB,
    C: MyEnumVariantC,
    D: MyEnumVariantD,
    E: MyEnumVariantE,
}

#[repr(u8)] #[derive(Copy, Clone)] enum MyEnumTag { A, B, C, D, E }
#[repr(C)] #[derive(Copy, Clone)] struct MyEnumVariantA(MyEnumTag, u32);
#[repr(C)] #[derive(Copy, Clone)] struct MyEnumVariantB { tag: MyEnumTag, x: u8, y: i16 }
#[repr(C)] #[derive(Copy, Clone)] struct MyEnumVariantC(MyEnumTag);
#[repr(C)] #[derive(Copy, Clone)] struct MyEnumVariantD(MyEnumTag, Option<u32>);
#[repr(C)] #[derive(Copy, Clone)] struct MyEnumVariantE(MyEnumTag, Duration);

fn main() {
    let result: Vec<Result<MyEnum, ()>> = vec![
        Ok(MyEnum::A(17)),
        Ok(MyEnum::B { x: 206, y: 1145 }),
        Ok(MyEnum::C),
        Err(()),
        Ok(MyEnum::D(Some(407))),
        Ok(MyEnum::D(None)),
        Ok(MyEnum::E(Duration::from_secs(100))),
        Err(()),
    ];

    // Binary serialized version of the above (little-endian)
    let input: Vec<u8> = vec![
        0,  17, 0, 0, 0,
        1,  206,  121, 4,
        2,
        8,  /* invalid tag value */
        3,  0,  151, 1, 0, 0,
        3,  1,
        4,  100, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,
        0,  /* incomplete value */
    ];

    let mut output = vec![];
    let mut buf = &input[..];

    unsafe {
        // This should be safe, because we don't match on it unless it's fully formed,
        // and it doesn't have a destructor.
        let mut dest: MyEnum = mem::uninitialized();
        while buf.len() > 0 {
            match parse_my_enum(&mut dest, &mut buf) {
                Ok(()) => output.push(Ok(dest)),
                Err(()) => output.push(Err(())),
            }
        }
    }

    assert_eq!(output, result);
}

fn parse_my_enum<'a>(dest: &'a mut MyEnum, buf: &mut &[u8]) -> Result<(), ()> {
    unsafe {
        // Should be correct to do this transmute.
        let dest: &'a mut MyEnumRepr = mem::transmute(dest);
        let tag = read_u8(buf)?;

        dest.A.0 = match tag {
            0 => MyEnumTag::A,
            1 => MyEnumTag::B,
            2 => MyEnumTag::C,
            3 => MyEnumTag::D,
            4 => MyEnumTag::E,
            _ => return Err(()),
        };

        match dest.B.tag {
            MyEnumTag::A => {
                dest.A.1 = read_u32_le(buf)?;
            }
            MyEnumTag::B => {
                dest.B.x = read_u8(buf)?;
                dest.B.y = read_u16_le(buf)? as i16;
            }
            MyEnumTag::C => {
                /* do nothing */
            }
            MyEnumTag::D => {
                let is_some = read_u8(buf)? == 0;
                if is_some {
                    dest.D.1 = Some(read_u32_le(buf)?);
                } else {
                    dest.D.1 = None;
                }
            }
            MyEnumTag::E => {
                let secs = read_u64_le(buf)?;
                let nanos = read_u32_le(buf)?;
                dest.E.1 = Duration::new(secs, nanos);
            }
        }
        Ok(())
    }
}

// reader helpers

fn read_u64_le(buf: &mut &[u8]) -> Result<u64, ()> {
    if buf.len() < 8 { return Err(()) }
    let val = (buf[0] as u64) << 0
            | (buf[1] as u64) << 8
            | (buf[2] as u64) << 16
            | (buf[3] as u64) << 24
            | (buf[4] as u64) << 32
            | (buf[5] as u64) << 40
            | (buf[6] as u64) << 48
            | (buf[7] as u64) << 56;
    *buf = &buf[8..];
    Ok(val)
}

fn read_u32_le(buf: &mut &[u8]) -> Result<u32, ()> {
    if buf.len() < 4 { return Err(()) }
    let val = (buf[0] as u32) << 0
            | (buf[1] as u32) << 8
            | (buf[2] as u32) << 16
            | (buf[3] as u32) << 24;
    *buf = &buf[4..];
    Ok(val)
}

fn read_u16_le(buf: &mut &[u8]) -> Result<u16, ()> {
    if buf.len() < 2 { return Err(()) }
    let val = (buf[0] as u16) << 0
            | (buf[1] as u16) << 8;
    *buf = &buf[2..];
    Ok(val)
}

fn read_u8(buf: &mut &[u8]) -> Result<u8, ()> {
    if buf.len() < 1 { return Err(()) }
    let val = buf[0];
    *buf = &buf[1..];
    Ok(val)
}
<|endoftext|>


<commit_before><commit_msg>Added tic tac toe example (just for fun)<commit_after>#[macro_use]extern crate prettytable;
use prettytable::Table;

use std::io;
use std::io::Write;
use std::str::FromStr;

const CROSS: &'static str = "X";
const EMPTY: &'static str = " ";
const ROUND: &'static str = "O";

fn main() {
    let mut table = table![[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]];
    table.printstd();
    let stdin = io::stdin();
    let mut stdout = io::stdout();
    let mut current = CROSS;
    loop {
        let mut line = String::new();
        print!("{} plays > ", current);
        stdout.flush().unwrap();
        stdin.read_line(&mut line).expect("Cannot read input");
        let i = match usize::from_str(line.trim()) {
            Ok(i) => i,
            _ => {
                println!("Bad input");
                continue;
            }
        };
        if i < 1 || i > 9 {
            println!("Bad input, should be between 1 and 9");
            continue;
        }
        let x = (i-1)%3;
        let y = (i-1)/3;
        {
            let mut row = table.get_mut_row(y).unwrap();
            if row.get_cell(x).unwrap().to_string() != EMPTY {
                println!("There's already someone there");
                continue;
            }
            row.set_cell(cell!(current), x).unwrap();
        }
        table.printstd();
        if check(&table) {
            return
        }
        if current == CROSS {
            current = ROUND;
        } else {
            current = CROSS;
        }
    }
}

fn get(table: &Table, x: usize, y: usize) -> String {
    match table.get_row(y) {
        Some(ref r) => match r.get_cell(x){
            Some(ref c) => c.to_string(),
            _ => EMPTY.to_string()
        },
        _ => EMPTY.to_string()
    }
}

fn is(table: &Table, s : &str, x: usize, y: usize) -> bool {
    get(table, x, y).as_str() == s
}

fn check(table: &Table) -> bool {
    let mut full = true;
    for y in 0..3 {
        for x in 0..3 {
            if is(table, EMPTY, x, y) {
                full = false;
                continue;
            }
            let current = get(table, x, y);
            let c = current.as_str();
            if is(table, c, x+1, y) && is(table, c, x+2, y) || is(table, c, x+1, y+1) && is(table, c, x+2, y+2) || x >= 2 && is(table, c, x-1, y+1) && is(table, c, x-2, y+2) || is(table, c, x, y+1) && is(table, c, x, y+2) {
                println!("Game is over. {} is the winner", current);
                return true;
            }
        }
    }
    if full {
        println!("Game is over. It's a draw");
    }
    return full;
}
<|endoftext|>


<commit_before><commit_msg>Reformat code<commit_after><|endoftext|>


<commit_before><commit_msg>Fix the atmosphere rendering, which the previous commit broke<commit_after><|endoftext|>


<commit_before><commit_msg>adding mod prelude<commit_after>// mod prelude

pub use client::{Client, ClientList};
pub use channel::{Channel, ChannelList};
pub use connection::Connection;
pub use command::Command;

pub use error::{Result, Error, SQError};
<|endoftext|>


<commit_before><commit_msg>start a test to see if simulations are deterministic. they... aren't :(<commit_after>extern crate control;
extern crate geom;
extern crate map_model;
extern crate sim;

#[test]
fn from_scratch() {
    // This assumes this map has been built
    let input = "../data/small.abst";
    let rng_seed = 42;
    let spawn_count = 1000;

    println!("Creating two simulations");
    let data = map_model::load_pb(input).expect("Couldn't load input");
    let map = map_model::Map::new(&data);
    let geom_map = geom::GeomMap::new(&map);
    let control_map = control::ControlMap::new(&map, &geom_map);

    let mut sim1 = sim::straw_model::Sim::new(&map, &geom_map, Some(rng_seed));
    let mut sim2 = sim::straw_model::Sim::new(&map, &geom_map, Some(rng_seed));
    sim1.spawn_many_on_empty_roads(spawn_count);
    sim2.spawn_many_on_empty_roads(spawn_count);

    for _ in 1..1200 {
        if sim1 != sim2 {
            // TODO need to sort dicts in json output to compare
            sim1.write_savestate("sim1_state.json").unwrap();
            sim2.write_savestate("sim2_state.json").unwrap();
            panic!("sim state differs at {}. compare sim1_state.json and sim2_state.json", sim1.time);
        }
        sim1.step(&geom_map, &map, &control_map);
        sim2.step(&geom_map, &map, &control_map);
    }
}
<|endoftext|>


<commit_before><commit_msg>Add Abandon example<commit_after>use ldap3::result::Result;
use ldap3::{LdapConnAsync, Scope};

#[tokio::main]
async fn main() -> Result<()> {
    let (conn, mut ldap) = LdapConnAsync::new("ldap://localhost:2389").await?;
    ldap3::drive!(conn);
    let mut stream = ldap
        .streaming_search(
            "ou=Places,dc=example,dc=org",
            Scope::Subtree,
            "objectClass=locality",
            vec!["l"],
        )
        .await?;
    while let Some(_r) = stream.next().await? {
        break;
    }
    let msgid = stream.ldap_handle().last_id();
    let _res = stream.finish().await;
    ldap.abandon(msgid).await?;
    Ok(ldap.unbind().await?)
}
<|endoftext|>


<commit_before>use layers::{ARGB32Format, ContainerLayerKind, Image, ImageLayerKind, RGB24Format};
use layers::{TiledImageLayerKind};
use scene::Scene;

use geom::matrix::{Matrix4, ortho};
use opengles::gl2::{ARRAY_BUFFER, COLOR_BUFFER_BIT, COMPILE_STATUS};
use opengles::gl2::{FRAGMENT_SHADER, LINEAR, LINK_STATUS, NEAREST, NO_ERROR, REPEAT, RGB, RGBA,
                      BGRA};
use opengles::gl2::{STATIC_DRAW, TEXTURE_2D, TEXTURE_MAG_FILTER, TEXTURE_MIN_FILTER};
use opengles::gl2::{TEXTURE_WRAP_S, TEXTURE_WRAP_T};
use opengles::gl2::{TRIANGLE_STRIP, UNPACK_ALIGNMENT, UNPACK_CLIENT_STORAGE_APPLE, UNSIGNED_BYTE};
use opengles::gl2::{UNSIGNED_INT_8_8_8_8_REV, VERTEX_SHADER, GLclampf};
use opengles::gl2::{GLenum, GLint, GLsizei, GLuint, attach_shader, bind_buffer, bind_texture};
use opengles::gl2::{buffer_data, create_program, clear, clear_color};
use opengles::gl2::{compile_shader, create_shader, draw_arrays, enable};
use opengles::gl2::{enable_vertex_attrib_array, gen_buffers, gen_textures};
use opengles::gl2::{get_attrib_location, get_error, get_program_iv};
use opengles::gl2::{get_shader_info_log, get_shader_iv};
use opengles::gl2::{get_uniform_location, link_program, pixel_store_i, shader_source};
use opengles::gl2::{tex_image_2d, tex_parameter_i, uniform_1i, uniform_matrix_4fv, use_program};
use opengles::gl2::{vertex_attrib_pointer_f32, viewport};

use io::println;
use libc::c_int;
use str::to_bytes;

// Convert ARGB to ABGR.
pub fn FRAGMENT_SHADER_SOURCE() -> ~str {
    ~"
        #ifdef GLES2
            precision mediump float;
        #endif

        varying vec2 vTextureCoord;

        uniform sampler2D uSampler;

        void main(void) {
            gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
        }
    "
}

pub fn VERTEX_SHADER_SOURCE() -> ~str {
    ~"
        attribute vec3 aVertexPosition;
        attribute vec2 aTextureCoord;

        uniform mat4 uMVMatrix;
        uniform mat4 uPMatrix;

        varying vec2 vTextureCoord;

        void main(void) {
            gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
            vTextureCoord = aTextureCoord;
        }
    "
}

pub fn load_shader(source_string: ~str, shader_type: GLenum) -> GLuint {
    let shader_id = create_shader(shader_type);
    shader_source(shader_id, ~[ to_bytes(source_string) ]);
    compile_shader(shader_id);

    if get_error() != NO_ERROR {
        println(#fmt("error: %d", get_error() as int));
        fail ~"failed to compile shader";
    }

    if get_shader_iv(shader_id, COMPILE_STATUS) == (0 as GLint) {
        println(#fmt("shader info log: %s", get_shader_info_log(shader_id)));
        fail ~"failed to compile shader";
    }

    return shader_id;
}

pub struct RenderContext {
    program: GLuint,
    vertex_position_attr: c_int,
    texture_coord_attr: c_int,
    modelview_uniform: c_int,
    projection_uniform: c_int,
    sampler_uniform: c_int,
    vertex_buffer: GLuint,
    texture_coord_buffer: GLuint,
}

pub fn RenderContext(program: GLuint) -> RenderContext {
    let (vertex_buffer, texture_coord_buffer) = init_buffers();
    let rc = RenderContext {
        program: program,
        vertex_position_attr: get_attrib_location(program, ~"aVertexPosition"),
        texture_coord_attr: get_attrib_location(program, ~"aTextureCoord"),
        modelview_uniform: get_uniform_location(program, ~"uMVMatrix"),
        projection_uniform: get_uniform_location(program, ~"uPMatrix"),
        sampler_uniform: get_uniform_location(program, ~"uSampler"),
        vertex_buffer: vertex_buffer,
        texture_coord_buffer: texture_coord_buffer,
    };

    enable_vertex_attrib_array(rc.vertex_position_attr as GLuint);
    enable_vertex_attrib_array(rc.texture_coord_attr as GLuint);

    rc
}

pub fn init_render_context() -> RenderContext {
    let vertex_shader = load_shader(VERTEX_SHADER_SOURCE(), VERTEX_SHADER);
    let fragment_shader = load_shader(FRAGMENT_SHADER_SOURCE(), FRAGMENT_SHADER);

    let program = create_program();
    attach_shader(program, vertex_shader);
    attach_shader(program, fragment_shader);
    link_program(program);

    if get_program_iv(program, LINK_STATUS) == (0 as GLint) {
        fail ~"failed to initialize program";
    }

    use_program(program);

    enable(TEXTURE_2D);

    return RenderContext(program);
}

pub fn init_buffers() -> (GLuint, GLuint) {
    let triangle_vertex_buffer = gen_buffers(1 as GLsizei)[0];
    bind_buffer(ARRAY_BUFFER, triangle_vertex_buffer);

    let (_0, _1) = (0.0f32, 1.0f32);
    let vertices = ~[
        _0, _0, _0,
        _0, _1, _0,
        _1, _0, _0,
        _1, _1, _0
    ];

    buffer_data(ARRAY_BUFFER, vertices, STATIC_DRAW);

    let texture_coord_buffer = gen_buffers(1 as GLsizei)[0];
    bind_buffer(ARRAY_BUFFER, texture_coord_buffer);

    let vertices = ~[
        _0, _0,
        _0, _1,
        _1, _0,
        _1, _1
    ];

    buffer_data(ARRAY_BUFFER, vertices, STATIC_DRAW);

    return (triangle_vertex_buffer, texture_coord_buffer);
}

pub fn create_texture_for_image_if_necessary(image: @Image) {
    match image.texture {
        None => {}
        Some(_) => { return; /* Nothing to do. */ }
    }

    #debug("making texture");

    let texture = gen_textures(1 as GLsizei)[0];
    bind_texture(TEXTURE_2D, texture);

    tex_parameter_i(TEXTURE_2D, TEXTURE_WRAP_S, REPEAT as GLint);
    tex_parameter_i(TEXTURE_2D, TEXTURE_WRAP_T, REPEAT as GLint);
    tex_parameter_i(TEXTURE_2D, TEXTURE_MAG_FILTER, LINEAR as GLint);
    tex_parameter_i(TEXTURE_2D, TEXTURE_MIN_FILTER, LINEAR as GLint);

    pixel_store_i(UNPACK_ALIGNMENT, 1);

    // FIXME: This makes the lifetime requirements somewhat complex...
    pixel_store_i(UNPACK_CLIENT_STORAGE_APPLE, 1);

    let size = image.data.size();
    match image.data.format() {
        RGB24Format => {
            do image.data.with_data |data| {
                tex_image_2d(TEXTURE_2D, 0 as GLint, RGB as GLint, size.width as GLsizei,
                             size.height as GLsizei, 0 as GLint, RGB, UNSIGNED_BYTE,
                             Some(data));
            }
        }
        ARGB32Format => {
            do image.data.with_data |data| {
                tex_image_2d(TEXTURE_2D, 0 as GLint, RGBA as GLint, size.width as GLsizei,
                             size.height as GLsizei, 0 as GLint, BGRA, UNSIGNED_INT_8_8_8_8_REV,
                             Some(data));
            }
        }
    }

    image.texture = Some(texture);
}

pub fn bind_and_render_quad(render_context: RenderContext, texture: GLuint) {
    bind_texture(TEXTURE_2D, texture);

    uniform_1i(render_context.sampler_uniform, 0);

    bind_buffer(ARRAY_BUFFER, render_context.vertex_buffer);
    vertex_attrib_pointer_f32(render_context.vertex_position_attr as GLuint, 3, false, 0, 0);

    bind_buffer(ARRAY_BUFFER, render_context.texture_coord_buffer);
    vertex_attrib_pointer_f32(render_context.texture_coord_attr as GLuint, 2, false, 0, 0);

    draw_arrays(TRIANGLE_STRIP, 0, 4);
}

// Layer rendering

pub trait Render {
    fn render(render_context: RenderContext);
}

impl @layers::ImageLayer : Render {
    fn render(render_context: RenderContext) {
        create_texture_for_image_if_necessary(self.image);

        uniform_matrix_4fv(render_context.modelview_uniform, false,
                           self.common.transform.to_array());

        bind_and_render_quad(render_context, option::get(&self.image.texture));
    }
}

impl @layers::TiledImageLayer : Render {
    fn render(render_context: RenderContext) {
        let tiles_down = self.tiles.len() / self.tiles_across;
        for self.tiles.eachi |i, tile| {
            create_texture_for_image_if_necessary(*tile);

            let x = ((i % self.tiles_across) as f32);
            let y = ((i / self.tiles_across) as f32);

            let transform = self.common.transform.scale(&(1.0f32 / (self.tiles_across as f32)),
                                                        &(1.0f32 / (tiles_down as f32)),
                                                        &1.0f32);
            let transform = transform.translate(&(x * 1.0f32), &(y * 1.0f32), &0.0f32);

            uniform_matrix_4fv(render_context.modelview_uniform, false, transform.to_array());

            bind_and_render_quad(render_context, option::get(&tile.texture));
        }
    }
}

pub fn render_scene(render_context: RenderContext, scene: &Scene) {
    // Set the viewport.
    viewport(0 as GLint, 0 as GLint, scene.size.width as GLsizei, scene.size.height as GLsizei);

    // Clear the screen.
    clear_color(0.38f32, 0.36f32, 0.36f32, 1.0f32);
    clear(COLOR_BUFFER_BIT);

    // Set the projection matrix.
    let projection_matrix = ortho(0.0f32, copy scene.size.width, copy scene.size.height, 0.0f32,
                                  -10.0f32, 10.0f32);
    uniform_matrix_4fv(render_context.projection_uniform, false, projection_matrix.to_array());

    match copy scene.root {
        ContainerLayerKind(*) => fail ~"container layers unsupported",
        ImageLayerKind(image_layer) => image_layer.render(render_context),
        TiledImageLayerKind(tiled_image_layer) => tiled_image_layer.render(render_context)
    }
}

<commit_msg>Use GL_TEXTURE_RECTANGLE_ARB, since it's friendlier to Apple extensions<commit_after>use layers::{ARGB32Format, ContainerLayerKind, Image, ImageLayerKind, RGB24Format};
use layers::{TiledImageLayerKind};
use scene::Scene;

use geom::matrix::{Matrix4, ortho};
use opengles::gl2::{ARRAY_BUFFER, COLOR_BUFFER_BIT, CLAMP_TO_EDGE, COMPILE_STATUS};
use opengles::gl2::{FRAGMENT_SHADER, LINEAR, LINK_STATUS, NEAREST, NO_ERROR, REPEAT, RGB, RGBA,
                      BGRA};
use opengles::gl2::{STATIC_DRAW, TEXTURE_2D, TEXTURE_MAG_FILTER, TEXTURE_MIN_FILTER};
use opengles::gl2::{TEXTURE_RECTANGLE_ARB, TEXTURE_WRAP_S, TEXTURE_WRAP_T};
use opengles::gl2::{TRIANGLE_STRIP, UNPACK_ALIGNMENT, UNPACK_CLIENT_STORAGE_APPLE, UNSIGNED_BYTE};
use opengles::gl2::{UNSIGNED_INT_8_8_8_8_REV, VERTEX_SHADER, GLclampf};
use opengles::gl2::{GLenum, GLint, GLsizei, GLuint, attach_shader, bind_buffer, bind_texture};
use opengles::gl2::{buffer_data, create_program, clear, clear_color};
use opengles::gl2::{compile_shader, create_shader, draw_arrays, enable};
use opengles::gl2::{enable_vertex_attrib_array, gen_buffers, gen_textures};
use opengles::gl2::{get_attrib_location, get_error, get_program_iv};
use opengles::gl2::{get_shader_info_log, get_shader_iv};
use opengles::gl2::{get_uniform_location, link_program, pixel_store_i, shader_source};
use opengles::gl2::{tex_image_2d, tex_parameter_i, uniform_1i, uniform_matrix_4fv, use_program};
use opengles::gl2::{vertex_attrib_pointer_f32, viewport};

use io::println;
use libc::c_int;
use str::to_bytes;

pub fn FRAGMENT_SHADER_SOURCE() -> ~str {
    ~"
        #ifdef GLES2
            precision mediump float;
        #endif

        varying vec2 vTextureCoord;

        uniform sampler2DRect uSampler;

        void main(void) {
            gl_FragColor = texture2DRect(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
        }
    "
}

pub fn VERTEX_SHADER_SOURCE() -> ~str {
    ~"
        attribute vec3 aVertexPosition;
        attribute vec2 aTextureCoord;

        uniform mat4 uMVMatrix;
        uniform mat4 uPMatrix;

        varying vec2 vTextureCoord;

        void main(void) {
            gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
            vTextureCoord = aTextureCoord;
        }
    "
}

pub fn load_shader(source_string: ~str, shader_type: GLenum) -> GLuint {
    let shader_id = create_shader(shader_type);
    shader_source(shader_id, ~[ to_bytes(source_string) ]);
    compile_shader(shader_id);

    if get_error() != NO_ERROR {
        println(#fmt("error: %d", get_error() as int));
        fail ~"failed to compile shader";
    }

    if get_shader_iv(shader_id, COMPILE_STATUS) == (0 as GLint) {
        println(#fmt("shader info log: %s", get_shader_info_log(shader_id)));
        fail ~"failed to compile shader";
    }

    return shader_id;
}

pub struct RenderContext {
    program: GLuint,
    vertex_position_attr: c_int,
    texture_coord_attr: c_int,
    modelview_uniform: c_int,
    projection_uniform: c_int,
    sampler_uniform: c_int,
    vertex_buffer: GLuint,
    texture_coord_buffer: GLuint,
}

pub fn RenderContext(program: GLuint) -> RenderContext {
    let (vertex_buffer, texture_coord_buffer) = init_buffers();
    let rc = RenderContext {
        program: program,
        vertex_position_attr: get_attrib_location(program, ~"aVertexPosition"),
        texture_coord_attr: get_attrib_location(program, ~"aTextureCoord"),
        modelview_uniform: get_uniform_location(program, ~"uMVMatrix"),
        projection_uniform: get_uniform_location(program, ~"uPMatrix"),
        sampler_uniform: get_uniform_location(program, ~"uSampler"),
        vertex_buffer: vertex_buffer,
        texture_coord_buffer: texture_coord_buffer,
    };

    enable_vertex_attrib_array(rc.vertex_position_attr as GLuint);
    enable_vertex_attrib_array(rc.texture_coord_attr as GLuint);

    rc
}

pub fn init_render_context() -> RenderContext {
    let vertex_shader = load_shader(VERTEX_SHADER_SOURCE(), VERTEX_SHADER);
    let fragment_shader = load_shader(FRAGMENT_SHADER_SOURCE(), FRAGMENT_SHADER);

    let program = create_program();
    attach_shader(program, vertex_shader);
    attach_shader(program, fragment_shader);
    link_program(program);

    if get_program_iv(program, LINK_STATUS) == (0 as GLint) {
        fail ~"failed to initialize program";
    }

    use_program(program);

    enable(TEXTURE_2D);
    enable(TEXTURE_RECTANGLE_ARB);

    return RenderContext(program);
}

pub fn init_buffers() -> (GLuint, GLuint) {
    let triangle_vertex_buffer = gen_buffers(1 as GLsizei)[0];
    bind_buffer(ARRAY_BUFFER, triangle_vertex_buffer);

    let (_0, _1) = (0.0f32, 1.0f32);
    let vertices = ~[
        _0, _0, _0,
        _0, _1, _0,
        _1, _0, _0,
        _1, _1, _0
    ];

    buffer_data(ARRAY_BUFFER, vertices, STATIC_DRAW);

    let texture_coord_buffer = gen_buffers(1 as GLsizei)[0];
    bind_buffer(ARRAY_BUFFER, texture_coord_buffer);

    return (triangle_vertex_buffer, texture_coord_buffer);
}

pub fn create_texture_for_image_if_necessary(image: @Image) {
    match image.texture {
        None => {}
        Some(_) => { return; /* Nothing to do. */ }
    }

    #debug("making texture");

    let texture = gen_textures(1 as GLsizei)[0];
    bind_texture(TEXTURE_RECTANGLE_ARB, texture);

    tex_parameter_i(TEXTURE_RECTANGLE_ARB, TEXTURE_WRAP_S, CLAMP_TO_EDGE as GLint);
    tex_parameter_i(TEXTURE_RECTANGLE_ARB, TEXTURE_WRAP_T, CLAMP_TO_EDGE as GLint);
    tex_parameter_i(TEXTURE_RECTANGLE_ARB, TEXTURE_MAG_FILTER, LINEAR as GLint);
    tex_parameter_i(TEXTURE_RECTANGLE_ARB, TEXTURE_MIN_FILTER, LINEAR as GLint);

    //pixel_store_i(UNPACK_ALIGNMENT, 1);

    // FIXME: This makes the lifetime requirements somewhat complex...
    //pixel_store_i(UNPACK_CLIENT_STORAGE_APPLE, 1);

    let size = image.data.size();
    match image.data.format() {
        RGB24Format => {
            do image.data.with_data |data| {
                tex_image_2d(TEXTURE_RECTANGLE_ARB, 0 as GLint, RGB as GLint,
                             size.width as GLsizei, size.height as GLsizei, 0 as GLint, RGB,
                             UNSIGNED_BYTE, Some(data));
            }
        }
        ARGB32Format => {
            do image.data.with_data |data| {
                tex_image_2d(TEXTURE_RECTANGLE_ARB, 0 as GLint, RGBA as GLint,
                             size.width as GLsizei, size.height as GLsizei, 0 as GLint, BGRA,
                             UNSIGNED_INT_8_8_8_8_REV, Some(data));
            }
        }
    }

    image.texture = Some(texture);
}

pub fn bind_and_render_quad(render_context: RenderContext, size: Size2D<uint>, texture: GLuint) {
    bind_texture(TEXTURE_2D, texture);

    uniform_1i(render_context.sampler_uniform, 0);

    bind_buffer(ARRAY_BUFFER, render_context.vertex_buffer);
    vertex_attrib_pointer_f32(render_context.vertex_position_attr as GLuint, 3, false, 0, 0);

    // Create the texture coordinate array.
    bind_buffer(ARRAY_BUFFER, render_context.texture_coord_buffer);

    let (width, height) = (size.width as f32, size.height as f32);
    let vertices = [
        0.0f32, 0.0f32,
        0.0f32, height,
        width,  0.0f32,
        width,  height
    ];
    buffer_data(ARRAY_BUFFER, vertices, STATIC_DRAW);

    vertex_attrib_pointer_f32(render_context.texture_coord_attr as GLuint, 2, false, 0, 0);

    draw_arrays(TRIANGLE_STRIP, 0, 4);
}

// Layer rendering

pub trait Render {
    fn render(render_context: RenderContext);
}

impl @layers::ImageLayer : Render {
    fn render(render_context: RenderContext) {
        create_texture_for_image_if_necessary(self.image);

        uniform_matrix_4fv(render_context.modelview_uniform, false,
                           self.common.transform.to_array());

        bind_and_render_quad(
            render_context, self.image.data.size(), option::get(&self.image.texture));
    }
}

impl @layers::TiledImageLayer : Render {
    fn render(render_context: RenderContext) {
        let tiles_down = self.tiles.len() / self.tiles_across;
        for self.tiles.eachi |i, tile| {
            create_texture_for_image_if_necessary(*tile);

            let x = ((i % self.tiles_across) as f32);
            let y = ((i / self.tiles_across) as f32);

            let transform = self.common.transform.scale(&(1.0f32 / (self.tiles_across as f32)),
                                                        &(1.0f32 / (tiles_down as f32)),
                                                        &1.0f32);
            let transform = transform.translate(&(x * 1.0f32), &(y * 1.0f32), &0.0f32);

            uniform_matrix_4fv(render_context.modelview_uniform, false, transform.to_array());

            bind_and_render_quad(render_context, tile.data.size(), option::get(&tile.texture));
        }
    }
}

pub fn render_scene(render_context: RenderContext, scene: &Scene) {
    // Set the viewport.
    viewport(0 as GLint, 0 as GLint, scene.size.width as GLsizei, scene.size.height as GLsizei);

    // Clear the screen.
    clear_color(0.38f32, 0.36f32, 0.36f32, 1.0f32);
    clear(COLOR_BUFFER_BIT);

    // Set the projection matrix.
    let projection_matrix = ortho(0.0f32, copy scene.size.width, copy scene.size.height, 0.0f32,
                                  -10.0f32, 10.0f32);
    uniform_matrix_4fv(render_context.projection_uniform, false, projection_matrix.to_array());

    match copy scene.root {
        ContainerLayerKind(*) => fail ~"container layers unsupported",
        ImageLayerKind(image_layer) => image_layer.render(render_context),
        TiledImageLayerKind(tiled_image_layer) => tiled_image_layer.render(render_context)
    }
}

<|endoftext|>


<commit_before>use alloc::boxed::Box;

use core::cmp;

use arch::memory;

use system::graphics::{fast_copy, fast_set};

use super::FONT;
use super::color::Color;

/// The info of the VBE mode
#[derive(Copy, Clone, Default, Debug)]
#[repr(packed)]
pub struct VBEModeInfo {
    attributes: u16,
    win_a: u8,
    win_b: u8,
    granularity: u16,
    winsize: u16,
    segment_a: u16,
    segment_b: u16,
    winfuncptr: u32,
    bytesperscanline: u16,
    pub xresolution: u16,
    pub yresolution: u16,
    xcharsize: u8,
    ycharsize: u8,
    numberofplanes: u8,
    bitsperpixel: u8,
    numberofbanks: u8,
    memorymodel: u8,
    banksize: u8,
    numberofimagepages: u8,
    unused: u8,
    redmasksize: u8,
    redfieldposition: u8,
    greenmasksize: u8,
    greenfieldposition: u8,
    bluemasksize: u8,
    bluefieldposition: u8,
    rsvdmasksize: u8,
    rsvdfieldposition: u8,
    directcolormodeinfo: u8,
    physbaseptr: u32,
    offscreenmemoryoffset: u32,
    offscreenmemsize: u16,
}

pub static mut VBEMODEINFO: Option<VBEModeInfo> = None;

pub unsafe fn vbe_init(){
    let mode_info = *(0x5200 as *const VBEModeInfo);
    if mode_info.physbaseptr > 0 {
        VBEMODEINFO = Some(mode_info);
    }else{
        VBEMODEINFO = None;
    }
}

/// A display
pub struct Display {
    pub offscreen: *mut u32,
    pub onscreen: *mut u32,
    pub size: usize,
    pub width: usize,
    pub height: usize,
}

impl Display {
    pub fn root() -> Option<Box<Self>> {
        if let Some(mode_info) = unsafe { VBEMODEINFO } {
            let ret = box Display {
                offscreen: unsafe { memory::alloc(mode_info.xresolution as usize *
                                         mode_info.yresolution as usize * 4) as *mut u32 },
                onscreen: mode_info.physbaseptr as usize as *mut u32,
                size: mode_info.xresolution as usize * mode_info.yresolution as usize,
                width: mode_info.xresolution as usize,
                height: mode_info.yresolution as usize,
            };

            Some(ret)
        } else {
            None
        }
    }

    /// Set the color
    pub fn set(&self, color: Color) {
        unsafe {
            fast_set(self.offscreen, color.data, self.size);
        }
    }

    /// Scroll the display
    pub fn scroll(&self, rows: usize, color: Color) {
        if rows > 0 && rows < self.height {
            let offset = rows * self.width;
            unsafe {
                fast_copy(self.offscreen, self.offscreen.offset(offset as isize), self.size - offset);
                fast_set(self.offscreen.offset((self.size - offset) as isize), color.data, offset);
            }
        }
    }

    /// Flip the display
    pub fn flip(&self) {
        unsafe {
            fast_copy(self.onscreen, self.offscreen, self.size);
        }
    }

    /// Draw a rectangle
    pub fn rect(&self, x: usize, y: usize, w: usize, h: usize, color: Color) {
        let data = color.data;

        let start_y = cmp::min(self.height - 1, y);
        let end_y = cmp::min(self.height - 1, y + h);

        let start_x = cmp::min(self.width - 1, x);
        let len = cmp::min(self.width - 1, x + w) - start_x;

        for y in start_y..end_y {
            unsafe {
                fast_set(self.offscreen.offset((y * self.width + start_x) as isize), data, len);
            }
        }
    }

    /// Draw a char
    pub fn char(&self, x: usize, y: usize, character: char, color: Color) {
        if x + 8 <= self.width && y + 16 <= self.height {
            let data = color.data;
            let mut dst = unsafe { self.offscreen.offset((y * self.width + x) as isize) };

            let font_i = 16 * (character as usize);
            for row in 0..16 {
                let row_data = FONT[font_i + row];
                for col in 0..8 {
                    if (row_data >> (7 - col)) & 1 == 1 {
                        unsafe { *dst.offset(col) = data; }
                    }
                }
                dst = unsafe { dst.offset(self.width as isize) };
            }
        }
    }
}

impl Drop for Display {
    fn drop(&mut self) {
        unsafe {
            if self.offscreen as usize > 0 {
                memory::unalloc(self.offscreen as usize);
            }
        }
    }
}
<commit_msg>Fixes for real hardware - clear display on creation<commit_after>use alloc::boxed::Box;

use core::cmp;

use arch::memory;

use system::graphics::{fast_copy, fast_set};

use super::FONT;
use super::color::Color;

/// The info of the VBE mode
#[derive(Copy, Clone, Default, Debug)]
#[repr(packed)]
pub struct VBEModeInfo {
    attributes: u16,
    win_a: u8,
    win_b: u8,
    granularity: u16,
    winsize: u16,
    segment_a: u16,
    segment_b: u16,
    winfuncptr: u32,
    bytesperscanline: u16,
    pub xresolution: u16,
    pub yresolution: u16,
    xcharsize: u8,
    ycharsize: u8,
    numberofplanes: u8,
    bitsperpixel: u8,
    numberofbanks: u8,
    memorymodel: u8,
    banksize: u8,
    numberofimagepages: u8,
    unused: u8,
    redmasksize: u8,
    redfieldposition: u8,
    greenmasksize: u8,
    greenfieldposition: u8,
    bluemasksize: u8,
    bluefieldposition: u8,
    rsvdmasksize: u8,
    rsvdfieldposition: u8,
    directcolormodeinfo: u8,
    physbaseptr: u32,
    offscreenmemoryoffset: u32,
    offscreenmemsize: u16,
}

pub static mut VBEMODEINFO: Option<VBEModeInfo> = None;

pub unsafe fn vbe_init(){
    let mode_info = *(0x5200 as *const VBEModeInfo);
    if mode_info.physbaseptr > 0 {
        VBEMODEINFO = Some(mode_info);
    }else{
        VBEMODEINFO = None;
    }
}

/// A display
pub struct Display {
    pub offscreen: *mut u32,
    pub onscreen: *mut u32,
    pub size: usize,
    pub width: usize,
    pub height: usize,
}

impl Display {
    pub fn root() -> Option<Box<Self>> {
        if let Some(mode_info) = unsafe { VBEMODEINFO } {
            let ret = box Display {
                offscreen: unsafe { memory::alloc(mode_info.xresolution as usize *
                                         mode_info.yresolution as usize * 4) as *mut u32 },
                onscreen: mode_info.physbaseptr as usize as *mut u32,
                size: mode_info.xresolution as usize * mode_info.yresolution as usize,
                width: mode_info.xresolution as usize,
                height: mode_info.yresolution as usize,
            };

            ret.set(Color::new(0, 0, 0));

            Some(ret)
        } else {
            None
        }
    }

    /// Set the color
    pub fn set(&self, color: Color) {
        unsafe {
            fast_set(self.offscreen, color.data, self.size);
        }
    }

    /// Scroll the display
    pub fn scroll(&self, rows: usize, color: Color) {
        if rows > 0 && rows < self.height {
            let offset = rows * self.width;
            unsafe {
                fast_copy(self.offscreen, self.offscreen.offset(offset as isize), self.size - offset);
                fast_set(self.offscreen.offset((self.size - offset) as isize), color.data, offset);
            }
        }
    }

    /// Flip the display
    pub fn flip(&self) {
        unsafe {
            fast_copy(self.onscreen, self.offscreen, self.size);
        }
    }

    /// Draw a rectangle
    pub fn rect(&self, x: usize, y: usize, w: usize, h: usize, color: Color) {
        let data = color.data;

        let start_y = cmp::min(self.height - 1, y);
        let end_y = cmp::min(self.height - 1, y + h);

        let start_x = cmp::min(self.width - 1, x);
        let len = cmp::min(self.width - 1, x + w) - start_x;

        for y in start_y..end_y {
            unsafe {
                fast_set(self.offscreen.offset((y * self.width + start_x) as isize), data, len);
            }
        }
    }

    /// Draw a char
    pub fn char(&self, x: usize, y: usize, character: char, color: Color) {
        if x + 8 <= self.width && y + 16 <= self.height {
            let data = color.data;
            let mut dst = unsafe { self.offscreen.offset((y * self.width + x) as isize) };

            let font_i = 16 * (character as usize);
            for row in 0..16 {
                let row_data = FONT[font_i + row];
                for col in 0..8 {
                    if (row_data >> (7 - col)) & 1 == 1 {
                        unsafe { *dst.offset(col) = data; }
                    }
                }
                dst = unsafe { dst.offset(self.width as isize) };
            }
        }
    }
}

impl Drop for Display {
    fn drop(&mut self) {
        unsafe {
            if self.offscreen as usize > 0 {
                memory::unalloc(self.offscreen as usize);
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add file for installation check<commit_after><|endoftext|>


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

use fmt;
use from_str::from_str;
use libc::{uintptr_t, exit};
use option::{Some, None, Option};
use rt;
use rt::util::dumb_println;
use rt::crate_map::{ModEntry, iter_crate_map};
use rt::crate_map::get_crate_map;
use str::StrSlice;
use str::raw::from_c_str;
use u32;
use vec::ImmutableVector;
use cast::transmute;

struct LogDirective {
    name: Option<~str>,
    level: u32
}

static MAX_LOG_LEVEL: u32 = 255;
static DEFAULT_LOG_LEVEL: u32 = 1;
static log_level_names : &'static[&'static str] = &'static["error", "warn", "info", "debug"];

/// Parse an individual log level that is either a number or a symbolic log level
fn parse_log_level(level: &str) -> Option<u32> {
    let num = from_str::<u32>(level);
    let mut log_level;
    match num {
        Some(num) => {
            if num < MAX_LOG_LEVEL {
                log_level = Some(num);
            } else {
                log_level = Some(MAX_LOG_LEVEL);
            }
        }
        _ => {
            let position = log_level_names.iter().position(|&name| name == level);
            match position {
                Some(position) => {
                    log_level = Some(u32::min(MAX_LOG_LEVEL, (position + 1) as u32))
                },
                _ => {
                    log_level = None;
                }
            }
        }
    }
    log_level
}

/// Parse a logging specification string (e.g: "crate1,crate2::mod3,crate3::x=1")
/// and return a vector with log directives.
/// Valid log levels are 0-255, with the most likely ones being 1-4 (defined in std::).
/// Also supports string log levels of error, warn, info, and debug
fn parse_logging_spec(spec: ~str) -> ~[LogDirective]{
    let mut dirs = ~[];
    for s in spec.split_iter(',') {
        let parts: ~[&str] = s.split_iter('=').collect();
        let mut log_level;
        let mut name = Some(parts[0].to_owned());
        match parts.len() {
            1 => {
                //if the single argument is a log-level string or number,
                //treat that as a global fallback
                let possible_log_level = parse_log_level(parts[0]);
                match possible_log_level {
                    Some(num) => {
                        name = None;
                        log_level = num;
                    },
                    _ => {
                        log_level = MAX_LOG_LEVEL
                    }
                }
            }
            2 => {
                let possible_log_level = parse_log_level(parts[1]);
                match possible_log_level {
                    Some(num) => {
                        log_level = num;
                    },
                    _ => {
                        dumb_println(fmt!("warning: invalid logging spec \
                                           '%s', ignoring it", parts[1]));
                        loop;
                    }
                }
            },
            _ => {
                dumb_println(fmt!("warning: invalid logging spec '%s',\
                                  ignoring it", s));
                loop;
            }
        }
        let dir = LogDirective {name: name, level: log_level};
        dirs.push(dir);
    }
    return dirs;
}

/// Set the log level of an entry in the crate map depending on the vector
/// of log directives
fn update_entry(dirs: &[LogDirective], entry: *mut ModEntry) -> u32 {
    let mut new_lvl: u32 = DEFAULT_LOG_LEVEL;
    let mut longest_match = -1i;
    unsafe {
        for dir in dirs.iter() {
            match dir.name {
                None => {
                    if longest_match == -1 {
                        longest_match = 0;
                        new_lvl = dir.level;
                    }
                }
                Some(ref dir_name) => {
                    let name = from_c_str((*entry).name);
                    let len = dir_name.len() as int;
                    if name.starts_with(*dir_name) &&
                        len >= longest_match {
                        longest_match = len;
                        new_lvl = dir.level;
                    }
                }
            };
        }
        *(*entry).log_level = new_lvl;
    }
    if longest_match >= 0 { return 1; } else { return 0; }
}

#[fixed_stack_segment] #[inline(never)]
/// Set log level for every entry in crate_map according to the sepecification
/// in settings
fn update_log_settings(crate_map: *u8, settings: ~str) {
    let mut dirs = ~[];
    if settings.len() > 0 {
        if settings == ~"::help" || settings == ~"?" {
            dumb_println("\nCrate log map:\n");
            unsafe {
                do iter_crate_map(transmute(crate_map)) |entry: *mut ModEntry| {
                    dumb_println(" "+from_c_str((*entry).name));
                }
                exit(1);
            }
        }
        dirs = parse_logging_spec(settings);
    }

    let mut n_matches: u32 = 0;
    unsafe {
        do iter_crate_map(transmute(crate_map)) |entry: *mut ModEntry| {
            let m = update_entry(dirs, entry);
            n_matches += m;
        }
    }

    if n_matches < (dirs.len() as u32) {
        dumb_println(fmt!("warning: got %u RUST_LOG specs but only matched %u of them.\n\
                          You may have mistyped a RUST_LOG spec.\n\
                          Use RUST_LOG=::help to see the list of crates and modules.\n",
                          dirs.len() as uint, n_matches as uint));
    }
}

pub trait Logger {
    fn log(&mut self, args: &fmt::Arguments);
}

pub struct StdErrLogger;

impl Logger for StdErrLogger {
    fn log(&mut self, args: &fmt::Arguments) {
        if should_log_console() {
            fmt::write(self as &mut rt::io::Writer, args);
        }
    }
}

impl rt::io::Writer for StdErrLogger {
    fn write(&mut self, buf: &[u8]) {
        // Nothing like swapping between I/O implementations! In theory this
        // could use the libuv bindings for writing to file descriptors, but
        // that may not necessarily be desirable because logging should work
        // outside of the uv loop. (modify with caution)
        use io::Writer;
        let dbg = ::libc::STDERR_FILENO as ::io::fd_t;
        dbg.write(buf);
    }

    fn flush(&mut self) {}
}

/// Configure logging by traversing the crate map and setting the
/// per-module global logging flags based on the logging spec
pub fn init() {
    use os;

    let crate_map = get_crate_map() as *u8;

    let log_spec = os::getenv("RUST_LOG");
    match log_spec {
        Some(spec) => {
            update_log_settings(crate_map, spec);
        }
        None => {
            update_log_settings(crate_map, ~"");
        }
    }
}

#[fixed_stack_segment] #[inline(never)]
pub fn console_on() { unsafe { rust_log_console_on() } }

#[fixed_stack_segment] #[inline(never)]
pub fn console_off() { unsafe { rust_log_console_off() } }

#[fixed_stack_segment] #[inline(never)]
fn should_log_console() -> bool { unsafe { rust_should_log_console() != 0 } }

extern {
    fn rust_log_console_on();
    fn rust_log_console_off();
    fn rust_should_log_console() -> uintptr_t;
}

// Tests for parse_logging_spec()
#[test]
fn parse_logging_spec_valid() {
    let dirs = parse_logging_spec(~"crate1::mod1=1,crate1::mod2,crate2=4");
    assert_eq!(dirs.len(), 3);
    assert!(dirs[0].name == Some(~"crate1::mod1"));
    assert_eq!(dirs[0].level, 1);

    assert!(dirs[1].name == Some(~"crate1::mod2"));
    assert_eq!(dirs[1].level, MAX_LOG_LEVEL);

    assert!(dirs[2].name == Some(~"crate2"));
    assert_eq!(dirs[2].level, 4);
}

#[test]
fn parse_logging_spec_invalid_crate() {
    // test parse_logging_spec with multiple = in specification
    let dirs = parse_logging_spec(~"crate1::mod1=1=2,crate2=4");
    assert_eq!(dirs.len(), 1);
    assert!(dirs[0].name == Some(~"crate2"));
    assert_eq!(dirs[0].level, 4);
}

#[test]
fn parse_logging_spec_invalid_log_level() {
    // test parse_logging_spec with 'noNumber' as log level
    let dirs = parse_logging_spec(~"crate1::mod1=noNumber,crate2=4");
    assert_eq!(dirs.len(), 1);
    assert!(dirs[0].name == Some(~"crate2"));
    assert_eq!(dirs[0].level, 4);
}

#[test]
fn parse_logging_spec_string_log_level() {
    // test parse_logging_spec with 'warn' as log level
    let dirs = parse_logging_spec(~"crate1::mod1=wrong,crate2=warn");
    assert_eq!(dirs.len(), 1);
    assert!(dirs[0].name == Some(~"crate2"));
    assert_eq!(dirs[0].level, 2);
}

#[test]
fn parse_logging_spec_global() {
    // test parse_logging_spec with no crate
    let dirs = parse_logging_spec(~"warn,crate2=4");
    assert_eq!(dirs.len(), 2);
    assert!(dirs[0].name == None);
    assert_eq!(dirs[0].level, 2);
    assert!(dirs[1].name == Some(~"crate2"));
    assert_eq!(dirs[1].level, 4);
}

// Tests for update_entry
#[test]
fn update_entry_match_full_path() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3}];
    let level = &mut 0;
    unsafe {
        do "crate1::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 2);
            assert!(m == 1);
        }
    }
}

#[test]
fn update_entry_no_match() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3}];
    let level = &mut 0;
    unsafe {
        do "crate3::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == DEFAULT_LOG_LEVEL);
            assert!(m == 0);
        }
    }
}

#[test]
fn update_entry_match_beginning() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3}];
    let level = &mut 0;
    unsafe {
        do "crate2::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 3);
            assert!(m == 1);
        }
    }
}

#[test]
fn update_entry_match_beginning_longest_match() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3},
                 LogDirective {name: Some(~"crate2::mod"), level: 4}];
    let level = &mut 0;
    unsafe {
        do "crate2::mod1".with_c_str |ptr| {
            let entry = &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 4);
            assert!(m == 1);
        }
    }
}

#[test]
fn update_entry_match_default() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: None, level: 3}
                ];
    let level = &mut 0;
    unsafe {
        do "crate1::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 2);
            assert!(m == 1);
        }
        do "crate2::mod2".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 3);
            assert!(m == 1);
        }
    }
}
<commit_msg>Put a newline after each logging message<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.

use fmt;
use from_str::from_str;
use libc::{uintptr_t, exit};
use option::{Some, None, Option};
use rt;
use rt::util::dumb_println;
use rt::crate_map::{ModEntry, iter_crate_map};
use rt::crate_map::get_crate_map;
use str::StrSlice;
use str::raw::from_c_str;
use u32;
use vec::ImmutableVector;
use cast::transmute;

struct LogDirective {
    name: Option<~str>,
    level: u32
}

static MAX_LOG_LEVEL: u32 = 255;
static DEFAULT_LOG_LEVEL: u32 = 1;
static log_level_names : &'static[&'static str] = &'static["error", "warn", "info", "debug"];

/// Parse an individual log level that is either a number or a symbolic log level
fn parse_log_level(level: &str) -> Option<u32> {
    let num = from_str::<u32>(level);
    let mut log_level;
    match num {
        Some(num) => {
            if num < MAX_LOG_LEVEL {
                log_level = Some(num);
            } else {
                log_level = Some(MAX_LOG_LEVEL);
            }
        }
        _ => {
            let position = log_level_names.iter().position(|&name| name == level);
            match position {
                Some(position) => {
                    log_level = Some(u32::min(MAX_LOG_LEVEL, (position + 1) as u32))
                },
                _ => {
                    log_level = None;
                }
            }
        }
    }
    log_level
}

/// Parse a logging specification string (e.g: "crate1,crate2::mod3,crate3::x=1")
/// and return a vector with log directives.
/// Valid log levels are 0-255, with the most likely ones being 1-4 (defined in std::).
/// Also supports string log levels of error, warn, info, and debug
fn parse_logging_spec(spec: ~str) -> ~[LogDirective]{
    let mut dirs = ~[];
    for s in spec.split_iter(',') {
        let parts: ~[&str] = s.split_iter('=').collect();
        let mut log_level;
        let mut name = Some(parts[0].to_owned());
        match parts.len() {
            1 => {
                //if the single argument is a log-level string or number,
                //treat that as a global fallback
                let possible_log_level = parse_log_level(parts[0]);
                match possible_log_level {
                    Some(num) => {
                        name = None;
                        log_level = num;
                    },
                    _ => {
                        log_level = MAX_LOG_LEVEL
                    }
                }
            }
            2 => {
                let possible_log_level = parse_log_level(parts[1]);
                match possible_log_level {
                    Some(num) => {
                        log_level = num;
                    },
                    _ => {
                        dumb_println(fmt!("warning: invalid logging spec \
                                           '%s', ignoring it", parts[1]));
                        loop;
                    }
                }
            },
            _ => {
                dumb_println(fmt!("warning: invalid logging spec '%s',\
                                  ignoring it", s));
                loop;
            }
        }
        let dir = LogDirective {name: name, level: log_level};
        dirs.push(dir);
    }
    return dirs;
}

/// Set the log level of an entry in the crate map depending on the vector
/// of log directives
fn update_entry(dirs: &[LogDirective], entry: *mut ModEntry) -> u32 {
    let mut new_lvl: u32 = DEFAULT_LOG_LEVEL;
    let mut longest_match = -1i;
    unsafe {
        for dir in dirs.iter() {
            match dir.name {
                None => {
                    if longest_match == -1 {
                        longest_match = 0;
                        new_lvl = dir.level;
                    }
                }
                Some(ref dir_name) => {
                    let name = from_c_str((*entry).name);
                    let len = dir_name.len() as int;
                    if name.starts_with(*dir_name) &&
                        len >= longest_match {
                        longest_match = len;
                        new_lvl = dir.level;
                    }
                }
            };
        }
        *(*entry).log_level = new_lvl;
    }
    if longest_match >= 0 { return 1; } else { return 0; }
}

#[fixed_stack_segment] #[inline(never)]
/// Set log level for every entry in crate_map according to the sepecification
/// in settings
fn update_log_settings(crate_map: *u8, settings: ~str) {
    let mut dirs = ~[];
    if settings.len() > 0 {
        if settings == ~"::help" || settings == ~"?" {
            dumb_println("\nCrate log map:\n");
            unsafe {
                do iter_crate_map(transmute(crate_map)) |entry: *mut ModEntry| {
                    dumb_println(" "+from_c_str((*entry).name));
                }
                exit(1);
            }
        }
        dirs = parse_logging_spec(settings);
    }

    let mut n_matches: u32 = 0;
    unsafe {
        do iter_crate_map(transmute(crate_map)) |entry: *mut ModEntry| {
            let m = update_entry(dirs, entry);
            n_matches += m;
        }
    }

    if n_matches < (dirs.len() as u32) {
        dumb_println(fmt!("warning: got %u RUST_LOG specs but only matched %u of them.\n\
                          You may have mistyped a RUST_LOG spec.\n\
                          Use RUST_LOG=::help to see the list of crates and modules.\n",
                          dirs.len() as uint, n_matches as uint));
    }
}

pub trait Logger {
    fn log(&mut self, args: &fmt::Arguments);
}

pub struct StdErrLogger;

impl Logger for StdErrLogger {
    fn log(&mut self, args: &fmt::Arguments) {
        if should_log_console() {
            fmt::writeln(self as &mut rt::io::Writer, args);
        }
    }
}

impl rt::io::Writer for StdErrLogger {
    fn write(&mut self, buf: &[u8]) {
        // Nothing like swapping between I/O implementations! In theory this
        // could use the libuv bindings for writing to file descriptors, but
        // that may not necessarily be desirable because logging should work
        // outside of the uv loop. (modify with caution)
        use io::Writer;
        let dbg = ::libc::STDERR_FILENO as ::io::fd_t;
        dbg.write(buf);
    }

    fn flush(&mut self) {}
}

/// Configure logging by traversing the crate map and setting the
/// per-module global logging flags based on the logging spec
pub fn init() {
    use os;

    let crate_map = get_crate_map() as *u8;

    let log_spec = os::getenv("RUST_LOG");
    match log_spec {
        Some(spec) => {
            update_log_settings(crate_map, spec);
        }
        None => {
            update_log_settings(crate_map, ~"");
        }
    }
}

#[fixed_stack_segment] #[inline(never)]
pub fn console_on() { unsafe { rust_log_console_on() } }

#[fixed_stack_segment] #[inline(never)]
pub fn console_off() { unsafe { rust_log_console_off() } }

#[fixed_stack_segment] #[inline(never)]
fn should_log_console() -> bool { unsafe { rust_should_log_console() != 0 } }

extern {
    fn rust_log_console_on();
    fn rust_log_console_off();
    fn rust_should_log_console() -> uintptr_t;
}

// Tests for parse_logging_spec()
#[test]
fn parse_logging_spec_valid() {
    let dirs = parse_logging_spec(~"crate1::mod1=1,crate1::mod2,crate2=4");
    assert_eq!(dirs.len(), 3);
    assert!(dirs[0].name == Some(~"crate1::mod1"));
    assert_eq!(dirs[0].level, 1);

    assert!(dirs[1].name == Some(~"crate1::mod2"));
    assert_eq!(dirs[1].level, MAX_LOG_LEVEL);

    assert!(dirs[2].name == Some(~"crate2"));
    assert_eq!(dirs[2].level, 4);
}

#[test]
fn parse_logging_spec_invalid_crate() {
    // test parse_logging_spec with multiple = in specification
    let dirs = parse_logging_spec(~"crate1::mod1=1=2,crate2=4");
    assert_eq!(dirs.len(), 1);
    assert!(dirs[0].name == Some(~"crate2"));
    assert_eq!(dirs[0].level, 4);
}

#[test]
fn parse_logging_spec_invalid_log_level() {
    // test parse_logging_spec with 'noNumber' as log level
    let dirs = parse_logging_spec(~"crate1::mod1=noNumber,crate2=4");
    assert_eq!(dirs.len(), 1);
    assert!(dirs[0].name == Some(~"crate2"));
    assert_eq!(dirs[0].level, 4);
}

#[test]
fn parse_logging_spec_string_log_level() {
    // test parse_logging_spec with 'warn' as log level
    let dirs = parse_logging_spec(~"crate1::mod1=wrong,crate2=warn");
    assert_eq!(dirs.len(), 1);
    assert!(dirs[0].name == Some(~"crate2"));
    assert_eq!(dirs[0].level, 2);
}

#[test]
fn parse_logging_spec_global() {
    // test parse_logging_spec with no crate
    let dirs = parse_logging_spec(~"warn,crate2=4");
    assert_eq!(dirs.len(), 2);
    assert!(dirs[0].name == None);
    assert_eq!(dirs[0].level, 2);
    assert!(dirs[1].name == Some(~"crate2"));
    assert_eq!(dirs[1].level, 4);
}

// Tests for update_entry
#[test]
fn update_entry_match_full_path() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3}];
    let level = &mut 0;
    unsafe {
        do "crate1::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 2);
            assert!(m == 1);
        }
    }
}

#[test]
fn update_entry_no_match() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3}];
    let level = &mut 0;
    unsafe {
        do "crate3::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == DEFAULT_LOG_LEVEL);
            assert!(m == 0);
        }
    }
}

#[test]
fn update_entry_match_beginning() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3}];
    let level = &mut 0;
    unsafe {
        do "crate2::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 3);
            assert!(m == 1);
        }
    }
}

#[test]
fn update_entry_match_beginning_longest_match() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: Some(~"crate2"), level: 3},
                 LogDirective {name: Some(~"crate2::mod"), level: 4}];
    let level = &mut 0;
    unsafe {
        do "crate2::mod1".with_c_str |ptr| {
            let entry = &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 4);
            assert!(m == 1);
        }
    }
}

#[test]
fn update_entry_match_default() {
    use c_str::ToCStr;
    let dirs = ~[LogDirective {name: Some(~"crate1::mod1"), level: 2 },
                 LogDirective {name: None, level: 3}
                ];
    let level = &mut 0;
    unsafe {
        do "crate1::mod1".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 2);
            assert!(m == 1);
        }
        do "crate2::mod2".with_c_str |ptr| {
            let entry= &ModEntry {name: ptr, log_level: level};
            let m = update_entry(dirs, transmute(entry));
            assert!(*entry.log_level == 3);
            assert!(m == 1);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Bench BiLock<commit_after>#![feature(test)]

extern crate futures;
extern crate test;

use futures::Async;
use futures::executor;
use futures::executor::{Notify, NotifyHandle};
use futures::sync::BiLock;

use test::Bencher;

fn notify_noop() -> NotifyHandle {
    struct Noop;

    impl Notify for Noop {
        fn notify(&self, _id: usize) {}
    }

    const NOOP : &'static Noop = &Noop;

    NotifyHandle::from(NOOP)
}

#[bench]
fn contended(b: &mut Bencher) {
    b.iter(|| {
        let mut t = BiLock::new(1);
        for _ in 0..1000 {
            let (x, y) = t;
            let x_lock = match executor::spawn(x.lock()).poll_future_notify(&notify_noop(), 11).unwrap() {
                Async::Ready(lock) => lock,
                Async::NotReady => panic!(),
            };

            // Try poll second lock while first lock still holds the lock
            let mut y = executor::spawn(y.lock());
            match y.poll_future_notify(&notify_noop(), 11).unwrap() {
                Async::Ready(_) => panic!(),
                Async::NotReady => (),
            };

            let x = x_lock.unlock();

            let y_lock = match y.poll_future_notify(&notify_noop(), 11).unwrap() {
                Async::Ready(lock) => lock,
                Async::NotReady => panic!(),
            };

            let y = y_lock.unlock();
            t = (x, y);
        }
        t
    });
}

#[bench]
fn lock_unlock(b: &mut Bencher) {
    b.iter(|| {
        let mut t = BiLock::new(1);
        for _ in 0..1000 {
            let (x, y) = t;
            let x_lock = match executor::spawn(x.lock()).poll_future_notify(&notify_noop(), 11).unwrap() {
                Async::Ready(lock) => lock,
                Async::NotReady => panic!(),
            };

            let x = x_lock.unlock();

            let mut y = executor::spawn(y.lock());
            let y_lock = match y.poll_future_notify(&notify_noop(), 11).unwrap() {
                Async::Ready(lock) => lock,
                Async::NotReady => panic!(),
            };

            let y = y_lock.unlock();
            t = (x, y);
        }
        t
    })
}
<|endoftext|>


<commit_before><commit_msg>solved 0018 with Rust<commit_after>use std::io::prelude::*;
use std::str::FromStr;

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

    let l = stdin.lock().lines().next().unwrap().unwrap();
    let mut d : Vec<i32> = l.split_whitespace().map(|x| i32::from_str(x).unwrap()).collect();
    d.sort_by(|a,b| b.cmp(a));
    let s : String = d.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(" ");
    println!("{}",s);
}
<|endoftext|>


<commit_before><commit_msg>BDA::read change function return values<commit_after><|endoftext|>


<commit_before><commit_msg>add mark.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Add a simple error stack<commit_after>pub enum ErrorLevel {
    Info,
    Warning,
    Error,
}

// Use a hashmap which contains an error level and a string
type ErrorStack = Vec<(ErrorLevel, String)>;<|endoftext|>


<commit_before><commit_msg>add expermintal drawing api<commit_after>//Just some thought on makeing drawing a little bit better

/*
path!(
M 23.,23.;

);
*/

macro_rules! conv_path(
	(M) => (PathInstr::Move);
	(L) => (PathInstr::Line);
	(Q) => (PathInstr::QuadCurve);
	(B) => (PathInstr::BeizierCurve);
	(A) => (PathInstr::Arc);
	(C) => (PathInstr::ClosePath);
);

#[macro_export]
macro_rules! path(
	( $( $pi:ident : $( $val:expr ),* );+ )=>({
		(
			&[ $( conv_path!( $pi ), )+ ],
			&[ $( $( $val, )* )+ ]
		)
	})
);

#[test]
fn test_path(){
	use self::PathInstr::*;

	assert_eq!(
		path!(M:12.,3.; L:100.,30.),
		(
			&[Move, Line],
			&[12.,3.,100.,30.]
		)
	);
}

/// enum of path instructions
#[derive(Debug, Clone, PartialEq)]
pub enum PathInstr{
	/// Move to a given position
	Move,
	/// Line to a given pos
	Line,
	/// a
	QuadCurve,

	BeizierCurve,

	Arc,

	ClosePath,
}

/// a structure containing all data for a path
pub struct Path{
	instr: Vec<PathInstr>,
	vals: Vec<f32>,
	//TODO: add fill and stroke
}

impl Path{
	fn new() -> Path{
		Path{
			instr: Vec::new(),
			vals: Vec::new(),
		}
	}
}

/// api to construct a path the way it is done in nanovg or HTML5 Canvas
impl Path{
	fn move_to(&mut self, x: f32, y: f32){
		self.instr.push(PathInstr::Move);
		self.vals.push_all(&[x,y]);
	}

	fn line_to(&mut self, x: f32, y: f32){
		self.instr.push(PathInstr::Line);
		self.vals.push_all(&[x,y]);
	}

	fn bezier_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32){
		self.instr.push(PathInstr::BeizierCurve);
		self.vals.push_all(&[c1x,c1y,c2x,c2y,x,y]);
	}

	fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32){
		self.instr.push(PathInstr::QuadCurve);
		self.vals.push_all(&[cx,cy,x,y]);
	}

	fn arc_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, radius: f32){
		self.instr.push(PathInstr::Arc);
		self.vals.push_all(&[x1,y1,x2,y2,radius]);
	}

	fn close_path(&mut self){
		self.instr.push(PathInstr::ClosePath);
	}
}
<|endoftext|>


<commit_before><commit_msg>107:24 warning: statement with no effect, #[warn(no_effect)] on by default<commit_after><|endoftext|>


<commit_before><commit_msg>medium_from_gridfs accepts any query; generic request handler.<commit_after><|endoftext|>


<commit_before><commit_msg>Update the sensitivities for the joystick inputs (game controller only)<commit_after><|endoftext|>


<commit_before><commit_msg>Use io::copy to serve static files.<commit_after><|endoftext|>


<commit_before><commit_msg>Forwards error message in resolve_uri<commit_after><|endoftext|>


<commit_before><commit_msg>HTTPリクエストメッセージをラップする構造体を作成<commit_after><|endoftext|>


<commit_before><commit_msg>start visual style for listed save games<commit_after><|endoftext|>


<commit_before><commit_msg>Add rust code for wordy case<commit_after>pub struct WordProblem {
    cmd: String,
}

#[derive(PartialEq, Debug)]
enum Token {
    CmdWhat,
    CmdIs,
    Number,
    Operator,
    OperatorBy,
}

enum Operator {
    Plus,
    Minus,
    Multiply,
    Divide,
}

impl WordProblem {
    pub fn new(command: &str) -> WordProblem {
        WordProblem {
            cmd: command.to_string(),
        }
    }

    pub fn answer(&self) -> Result<i32, String> {
        let command = self.cmd
            .split(|x| x == '?' || char::is_whitespace(x))
            .filter(|w| !w.is_empty())
            .collect::<Vec<_>>();

        let mut result: i32 = 0;
        let mut lastop = Operator::Plus;
        let mut status = Token::CmdWhat;

        for word in command {
            match word {
                "What" if status == Token::CmdWhat => status = Token::CmdIs,
                "is" if status == Token::CmdIs => status = Token::Number,
                "plus" if status == Token::Operator => {
                    lastop = Operator::Plus;
                    status = Token::Number
                }
                "minus" if status == Token::Operator => {
                    lastop = Operator::Minus;
                    status = Token::Number
                }
                "multiplied" if status == Token::Operator => {
                    lastop = Operator::Multiply;
                    status = Token::OperatorBy
                }
                "divided" if status == Token::Operator => {
                    lastop = Operator::Divide;
                    status = Token::OperatorBy
                }
                "by" if status == Token::OperatorBy => status = Token::Number,
                _ if status == Token::Number => {
                    let value: i32;
                    if let Ok(v) = word.parse::<i32>() {
                        value = v;
                    } else {
                        return Err("Invalid number".to_string());
                    }

                    match lastop {
                        Operator::Plus => result += value,
                        Operator::Minus => result -= value,
                        Operator::Multiply => result *= value,
                        Operator::Divide => result /= value,
                    }

                    status = Token::Operator
                }
                _ => return Err("Invalid command".to_string()),
            }
        }

        Ok(result)
    }
}
<|endoftext|>


<commit_before><commit_msg>remove allow_overlap field from object struct<commit_after><|endoftext|>


<commit_before>//! Data structure of a scene node.

use std::borrow;
use std::cell::RefCell;
use std::rc::Rc;
use gl::types::*;
use nalgebra::na::{Mat3, Vec2, Vec3, Iso3, Rotation, Rotate, Translation, Transformation};
use nalgebra::na;
use resource::{Texture, TextureManager, Material, Mesh};
use camera::Camera;
use light::Light;

#[path = "error.rs"]
mod error;

type Transform3d = Iso3<f32>;
type Scale3d     = Mat3<GLfloat>;

/// Set of data identifying a scene node.
pub struct ObjectData {
    priv scale:     Scale3d,
    priv transform: Transform3d,
    priv texture:   Rc<Texture>,
    priv color:     Vec3<f32>,
    priv visible:   bool,
    priv user_data: ~Any
}

impl ObjectData {
    /// The scale matrix of this object.
    pub fn scale<'a>(&'a self) -> &'a Scale3d {
        &'a self.scale
    }

    /// The transformation matrix (scaling excluded) of this object.
    pub fn transform<'a>(&'a self) -> &'a Transform3d {
        &'a self.transform
    }

    /// The texture of this object.
    pub fn texture<'a>(&'a self) -> &'a Rc<Texture> {
        &'a self.texture
    }

    /// The color of this object.
    pub fn color<'a>(&'a self) -> &'a Vec3<f32> {
        &'a self.color
    }

    /// Checks whether this object is visible or not.
    pub fn visible(&self) -> bool {
        self.visible
    }

    /// An user-defined data.
    ///
    /// Use dynamic typing capabilities of the `Any` type to recover the actual data.
    pub fn user_data<'a>(&'a self) -> &'a Any {
        let res: &'a Any = self.user_data;

        res
    }
}

/// A 3d objects on the scene.
///
/// This is the only interface to manipulate the object position, color, vertices and texture.
#[deriving(Clone)]
pub struct Object {
    priv material: Rc<RefCell<Rc<RefCell<~Material>>>>,
    priv data:     Rc<RefCell<ObjectData>>,
    priv mesh:     Rc<RefCell<Mesh>>
}

impl Object {
    #[doc(hidden)]
    pub fn new(mesh:     Rc<RefCell<Mesh>>,
               r:        f32,
               g:        f32,
               b:        f32,
               texture:  Rc<Texture>,
               sx:       GLfloat,
               sy:       GLfloat,
               sz:       GLfloat,
               material: Rc<RefCell<~Material>>) -> Object {
        let data = ObjectData {
            scale:     Mat3::new(sx, 0.0, 0.0,
                                 0.0, sy, 0.0,
                                 0.0, 0.0, sz),
            transform: na::one(),
            color:     Vec3::new(r, g, b),
            texture:   texture,
            visible:   true,
            user_data: ~() as ~Any
        };

        Object {
            data:     Rc::new(RefCell::new(data)),
            mesh:     mesh,
            material: Rc::new(RefCell::new(material))
        }
    }

    #[doc(hidden)]
    pub fn render(&self, pass: uint, camera: &mut Camera, light: &Light) {
        let visible = self.data.borrow().borrow().get().visible;

        if visible {
            self.material.borrow().borrow().get().borrow().borrow_mut().get().render(
                pass,
                camera,
                light,
                self.data.borrow().borrow().get(),
                self.mesh.borrow().borrow_mut().get());
        }
    }

    /// Gets the data of this object.
    #[inline]
    pub fn data<'a>(&'a self) -> &'a Rc<RefCell<ObjectData>> {
        &'a self.data
    }

    /// Attaches user-defined data to this object.
    #[inline]
    pub fn set_user_data(&mut self, user_data: ~Any) {
        self.data.borrow().borrow_mut().get().user_data = user_data;
    }

    /// Gets the material of this object.
    #[inline]
    pub fn material(&self) -> Rc<RefCell<~Material>> {
        self.material.borrow().borrow().get().clone()
    }

    /// Sets the material of this object.
    #[inline]
    pub fn set_material(&mut self, material: Rc<RefCell<~Material>>) {
        *self.material.borrow().borrow_mut().get() = material;
    }

    /// Sets the visible state of this object.
    ///
    /// An invisible object is not drawn.
    #[inline]
    pub fn set_visible(&mut self, visible: bool) {
        self.data.borrow().borrow_mut().get().visible = visible
    }

    /// Returns true if this object can be visible.
    #[inline]
    pub fn visible(&self) -> bool {
        self.data.borrow().borrow().get().visible
    }

    /// Sets the local scaling factor of the object.
    #[inline]
    pub fn set_scale(&mut self, sx: f32, sy: f32, sz: f32) {
        self.data.borrow().borrow_mut().get().scale = Mat3::new(sx, 0.0, 0.0,
                                                                0.0, sy, 0.0,
                                                                0.0, 0.0, sz)
    }

    /// This object's mesh.
    #[inline]
    pub fn mesh<'a>(&'a self) -> &'a Rc<RefCell<Mesh>> {
        &'a self.mesh
    }

    /// Mutably access the object's vertices.
    #[inline(always)]
    pub fn modify_vertices(&mut self, f: |&mut ~[Vec3<GLfloat>]| -> ()) {
        let     m  = self.mesh();
        let mut bm = m.borrow().borrow_mut();

        let coords = bm.get().coords();

        coords.write(|coords| coords.write(|coords| { f(coords) }));
    }

    /// Access the object's vertices.
    #[inline(always)]
    pub fn read_vertices(&self, f: |&[Vec3<GLfloat>]| -> ()) {
        let m  = self.mesh();
        let bm = m.borrow().borrow();

        let coords = bm.get().coords();

        coords.read(|coords| coords.read(|coords| { f(coords) }));
    }

    /// Recomputes the normals of this object's mesh.
    #[inline]
    pub fn recompute_normals(&mut self) {
        let     m  = self.mesh();
        let mut bm = m.borrow().borrow_mut();

        bm.get().recompute_normals();
    }

    /// Mutably access the object's normals.
    #[inline(always)]
    pub fn modify_normals(&mut self, f: |&mut ~[Vec3<GLfloat>]| -> ()) {
        let     m  = self.mesh();
        let mut bm = m.borrow().borrow_mut();

        let normals = bm.get().normals();

        normals.write(|normals| normals.write(|normals| { f(normals) }));
    }

    /// Access the object's normals.
    #[inline(always)]
    pub fn read_normals(&self, f: |&[Vec3<GLfloat>]| -> ()) {
        let m  = self.mesh();
        let bm = m.borrow().borrow();

        let normals = bm.get().normals();

        normals.read(|normals| normals.read(|normals| { f(normals) }));
    }

    /// Mutably access the object's faces.
    #[inline(always)]
    pub fn modify_faces(&mut self, f: |&mut ~[Vec3<GLuint>]| -> ()) {
        let     m  = self.mesh();
        let mut bm = m.borrow().borrow_mut();

        let faces = bm.get().faces();

        faces.write(|faces| faces.write(|faces| { f(faces) }));
    }

    /// Access the object's faces.
    #[inline(always)]
    pub fn read_faces(&self, f: |&[Vec3<GLuint>]| -> ()) {
        let m  = self.mesh();
        let bm = m.borrow().borrow();

        let faces = bm.get().faces();

        faces.read(|faces| faces.read(|faces| { f(faces) }));
    }

    /// Mutably access the object's texture coordinates.
    #[inline(always)]
    pub fn modify_uvs(&mut self, f: |&mut ~[Vec2<GLfloat>]| -> ()) {
        let     m  = self.mesh();
        let mut bm = m.borrow().borrow_mut();

        let uvs = bm.get().uvs();

        uvs.write(|uvs| uvs.write(|uvs| { f(uvs) }));
    }

    /// Access the object's texture coordinates.
    #[inline(always)]
    pub fn read_uvs(&self, f: |&[Vec2<GLfloat>]| -> ()) {
        let m  = self.mesh();
        let bm = m.borrow().borrow();

        let uvs = bm.get().uvs();

        uvs.read(|uvs| uvs.read(|uvs| { f(uvs) }));
    }

    /// Sets the color of the object.
    ///
    /// Colors components must be on the range `[0.0, 1.0]`.
    #[inline]
    pub fn set_color(&mut self, r: f32, g: f32, b: f32) {
        let mut d = self.data.borrow().borrow_mut();
        let d = d.get();

        d.color.x = r;
        d.color.y = g;
        d.color.z = b;
    }

    /// Sets the texture of the object.
    ///
    /// # Arguments
    ///   * `path` - relative path of the texture on the disk
    #[inline]
    pub fn set_texture(&mut self, path: &Path, name: &str) {
        let texture = TextureManager::get_global_manager(|tm| tm.add(path, name));

        self.data.borrow().borrow_mut().get().texture = texture;
    }

    /// Sets the texture of the object.
    ///
    /// The texture must already have been registered as `name`.
    #[inline]
    pub fn set_texture_with_name(&mut self, name: &str) {
        let texture = TextureManager::get_global_manager(|tm| tm.get(name).unwrap_or_else(
            || fail!("Invalid attempt to use the unregistered texture: " + name)));

        self.data.borrow().borrow_mut().get().texture = texture;
    }

    /// Move and orient the object such that it is placed at the point `eye` and have its `x` axis
    /// oriented toward `at`.
    #[inline]
    pub fn look_at(&mut self, eye: &Vec3<f32>, at: &Vec3<f32>, up: &Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.look_at(eye, at, up)
    }

    /// Move and orient the object such that it is placed at the point `eye` and have its `z` axis
    /// oriented toward `at`.
    #[inline]
    pub fn look_at_z(&mut self, eye: &Vec3<f32>, at: &Vec3<f32>, up: &Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.look_at_z(eye, at, up)
    }
}

impl Transformation<Transform3d> for Object {
    #[inline]
    fn transformation(&self) -> Transform3d {
        self.data.borrow().borrow().get().transform.clone()
    }

    #[inline]
    fn inv_transformation(&self) -> Transform3d {
        self.data.borrow().borrow().get().transform.inv_transformation()
    }

    #[inline]
    fn append_transformation(&mut self, t: &Transform3d) {
        self.data.borrow().borrow_mut().get().transform.append_transformation(t)
    }

    #[inline]
    fn append_transformation_cpy(_: &Object, _: &Transform3d) -> Object {
        fail!("Cannot clone an object.")
    }

    #[inline]
    fn prepend_transformation(&mut self, t: &Transform3d) {
        self.data.borrow().borrow_mut().get().transform.prepend_transformation(t)
    }

    #[inline]
    fn prepend_transformation_cpy(_: &Object, _: &Transform3d) -> Object {
        fail!("Cannot clone an object.")
    }

    #[inline]
    fn set_transformation(&mut self, t: Transform3d) {
        self.data.borrow().borrow_mut().get().transform.set_transformation(t)
    }
}

impl na::Transform<Vec3<f32>> for Object {
    #[inline]
    fn transform(&self, v: &Vec3<f32>) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.transform(v)
    }

    #[inline]
    fn inv_transform(&self, v: &Vec3<f32>) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.inv_transform(v)
    }
}

impl Rotation<Vec3<f32>> for Object {
    #[inline]
    fn rotation(&self) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.rotation()
    }

    #[inline]
    fn inv_rotation(&self) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.inv_rotation()
    }

    #[inline]
    fn append_rotation(&mut self, t: &Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.append_rotation(t)
    }

    #[inline]
    fn append_rotation_cpy(_: &Object, _: &Vec3<f32>) -> Object {
        fail!("Cannot clone an object.")
    }

    #[inline]
    fn prepend_rotation(&mut self, t: &Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.prepend_rotation(t)
    }

    #[inline]
    fn prepend_rotation_cpy(_: &Object, _: &Vec3<f32>) -> Object {
        fail!("Cannot clone an object.")
    }

    #[inline]
    fn set_rotation(&mut self, r: Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.set_rotation(r)
    }
}

impl Rotate<Vec3<f32>> for Object {
    #[inline]
    fn rotate(&self, v: &Vec3<f32>) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.rotate(v)
    }

    #[inline]
    fn inv_rotate(&self, v: &Vec3<f32>) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.inv_rotate(v)
    }
}

impl Translation<Vec3<f32>> for Object {
    #[inline]
    fn translation(&self) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.translation()
    }

    #[inline]
    fn inv_translation(&self) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.inv_translation()
    }

    #[inline]
    fn append_translation(&mut self, t: &Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.append_translation(t)
    }

    #[inline]
    fn append_translation_cpy(_: &Object, _: &Vec3<f32>) -> Object {
        fail!("Cannot clone an object.")
    }

    #[inline]
    fn prepend_translation(&mut self, t: &Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.prepend_translation(t)
    }

    #[inline]
    fn prepend_translation_cpy(_: &Object, _: &Vec3<f32>) -> Object {
        fail!("Cannot clone an object.")
    }

    #[inline]
    fn set_translation(&mut self, t: Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.set_translation(t)
    }
}

impl Eq for Object {
    #[inline]
    fn eq(&self, other: &Object) -> bool {
        let d1 = self.data.borrow().borrow();
        let d2 = other.data.borrow().borrow();

        borrow::ref_eq(d1.get(), d2.get())
    }
}
<commit_msg>Update to the last Rust.<commit_after>//! Data structure of a scene node.

use std::cell::RefCell;
use std::rc::Rc;
use gl::types::*;
use nalgebra::na::{Mat3, Vec2, Vec3, Iso3, Rotation, Rotate, Translation, Transformation};
use nalgebra::na;
use resource::{Texture, TextureManager, Material, Mesh};
use camera::Camera;
use light::Light;

#[path = "error.rs"]
mod error;

type Transform3d = Iso3<f32>;
type Scale3d     = Mat3<GLfloat>;

/// Set of data identifying a scene node.
pub struct ObjectData {
    priv scale:     Scale3d,
    priv transform: Transform3d,
    priv texture:   Rc<Texture>,
    priv color:     Vec3<f32>,
    priv visible:   bool,
    priv user_data: ~Any
}

impl ObjectData {
    /// The scale matrix of this object.
    pub fn scale<'a>(&'a self) -> &'a Scale3d {
        &'a self.scale
    }

    /// The transformation matrix (scaling excluded) of this object.
    pub fn transform<'a>(&'a self) -> &'a Transform3d {
        &'a self.transform
    }

    /// The texture of this object.
    pub fn texture<'a>(&'a self) -> &'a Rc<Texture> {
        &'a self.texture
    }

    /// The color of this object.
    pub fn color<'a>(&'a self) -> &'a Vec3<f32> {
        &'a self.color
    }

    /// Checks whether this object is visible or not.
    pub fn visible(&self) -> bool {
        self.visible
    }

    /// An user-defined data.
    ///
    /// Use dynamic typing capabilities of the `Any` type to recover the actual data.
    pub fn user_data<'a>(&'a self) -> &'a Any {
        let res: &'a Any = self.user_data;

        res
    }
}

/// A 3d objects on the scene.
///
/// This is the only interface to manipulate the object position, color, vertices and texture.
#[deriving(Clone)]
pub struct Object {
    priv material: Rc<RefCell<Rc<RefCell<~Material>>>>,
    priv data:     Rc<RefCell<ObjectData>>,
    priv mesh:     Rc<RefCell<Mesh>>
}

impl Object {
    #[doc(hidden)]
    pub fn new(mesh:     Rc<RefCell<Mesh>>,
               r:        f32,
               g:        f32,
               b:        f32,
               texture:  Rc<Texture>,
               sx:       GLfloat,
               sy:       GLfloat,
               sz:       GLfloat,
               material: Rc<RefCell<~Material>>) -> Object {
        let data = ObjectData {
            scale:     Mat3::new(sx, 0.0, 0.0,
                                 0.0, sy, 0.0,
                                 0.0, 0.0, sz),
            transform: na::one(),
            color:     Vec3::new(r, g, b),
            texture:   texture,
            visible:   true,
            user_data: ~() as ~Any
        };

        Object {
            data:     Rc::new(RefCell::new(data)),
            mesh:     mesh,
            material: Rc::new(RefCell::new(material))
        }
    }

    #[doc(hidden)]
    pub fn render(&self, pass: uint, camera: &mut Camera, light: &Light) {
        let visible = self.data.borrow().borrow().get().visible;

        if visible {
            self.material.borrow().borrow().get().borrow().borrow_mut().get().render(
                pass,
                camera,
                light,
                self.data.borrow().borrow().get(),
                self.mesh.borrow().borrow_mut().get());
        }
    }

    /// Gets the data of this object.
    #[inline]
    pub fn data<'a>(&'a self) -> &'a Rc<RefCell<ObjectData>> {
        &'a self.data
    }

    /// Attaches user-defined data to this object.
    #[inline]
    pub fn set_user_data(&mut self, user_data: ~Any) {
        self.data.borrow().borrow_mut().get().user_data = user_data;
    }

    /// Gets the material of this object.
    #[inline]
    pub fn material(&self) -> Rc<RefCell<~Material>> {
        self.material.borrow().borrow().get().clone()
    }

    /// Sets the material of this object.
    #[inline]
    pub fn set_material(&mut self, material: Rc<RefCell<~Material>>) {
        *self.material.borrow().borrow_mut().get() = material;
    }

    /// Sets the visible state of this object.
    ///
    /// An invisible object is not drawn.
    #[inline]
    pub fn set_visible(&mut self, visible: bool) {
        self.data.borrow().borrow_mut().get().visible = visible
    }

    /// Returns true if this object can be visible.
    #[inline]
    pub fn visible(&self) -> bool {
        self.data.borrow().borrow().get().visible
    }

    /// Sets the local scaling factor of the object.
    #[inline]
    pub fn set_scale(&mut self, sx: f32, sy: f32, sz: f32) {
        self.data.borrow().borrow_mut().get().scale = Mat3::new(sx, 0.0, 0.0,
                                                                0.0, sy, 0.0,
                                                                0.0, 0.0, sz)
    }

    /// This object's mesh.
    #[inline]
    pub fn mesh<'a>(&'a self) -> &'a Rc<RefCell<Mesh>> {
        &'a self.mesh
    }

    /// Mutably access the object's vertices.
    #[inline(always)]
    pub fn modify_vertices(&mut self, f: |&mut ~[Vec3<GLfloat>]| -> ()) {
        let     m  = self.mesh();
        let mut bm = m.borrow().borrow_mut();

        let coords = bm.get().coords();

        coords.write(|coords| coords.write(|coords| { f(coords) }));
    }

    /// Access the object's vertices.
    #[inline(always)]
    pub fn read_vertices(&self, f: |&[Vec3<GLfloat>]| -> ()) {
        let m  = self.mesh();
        let bm = m.borrow().borrow();

        let coords = bm.get().coords();

        coords.read(|coords| coords.read(|coords| { f(coords) }));
    }

    /// Recomputes the normals of this object's mesh.
    #[inline]
    pub fn recompute_normals(&mut self) {
        let     m  = self.mesh();
        let mut bm = m.borrow().borrow_mut();

        bm.get().recompute_normals();
    }

    /// Mutably access the object's normals.
    #[inline(always)]
    pub fn modify_normals(&mut self, f: |&mut ~[Vec3<GLfloat>]| -> ()) {
        let     m  = self.mesh();
        let mut bm = m.borrow().borrow_mut();

        let normals = bm.get().normals();

        normals.write(|normals| normals.write(|normals| { f(normals) }));
    }

    /// Access the object's normals.
    #[inline(always)]
    pub fn read_normals(&self, f: |&[Vec3<GLfloat>]| -> ()) {
        let m  = self.mesh();
        let bm = m.borrow().borrow();

        let normals = bm.get().normals();

        normals.read(|normals| normals.read(|normals| { f(normals) }));
    }

    /// Mutably access the object's faces.
    #[inline(always)]
    pub fn modify_faces(&mut self, f: |&mut ~[Vec3<GLuint>]| -> ()) {
        let     m  = self.mesh();
        let mut bm = m.borrow().borrow_mut();

        let faces = bm.get().faces();

        faces.write(|faces| faces.write(|faces| { f(faces) }));
    }

    /// Access the object's faces.
    #[inline(always)]
    pub fn read_faces(&self, f: |&[Vec3<GLuint>]| -> ()) {
        let m  = self.mesh();
        let bm = m.borrow().borrow();

        let faces = bm.get().faces();

        faces.read(|faces| faces.read(|faces| { f(faces) }));
    }

    /// Mutably access the object's texture coordinates.
    #[inline(always)]
    pub fn modify_uvs(&mut self, f: |&mut ~[Vec2<GLfloat>]| -> ()) {
        let     m  = self.mesh();
        let mut bm = m.borrow().borrow_mut();

        let uvs = bm.get().uvs();

        uvs.write(|uvs| uvs.write(|uvs| { f(uvs) }));
    }

    /// Access the object's texture coordinates.
    #[inline(always)]
    pub fn read_uvs(&self, f: |&[Vec2<GLfloat>]| -> ()) {
        let m  = self.mesh();
        let bm = m.borrow().borrow();

        let uvs = bm.get().uvs();

        uvs.read(|uvs| uvs.read(|uvs| { f(uvs) }));
    }

    /// Sets the color of the object.
    ///
    /// Colors components must be on the range `[0.0, 1.0]`.
    #[inline]
    pub fn set_color(&mut self, r: f32, g: f32, b: f32) {
        let mut d = self.data.borrow().borrow_mut();
        let d = d.get();

        d.color.x = r;
        d.color.y = g;
        d.color.z = b;
    }

    /// Sets the texture of the object.
    ///
    /// # Arguments
    ///   * `path` - relative path of the texture on the disk
    #[inline]
    pub fn set_texture(&mut self, path: &Path, name: &str) {
        let texture = TextureManager::get_global_manager(|tm| tm.add(path, name));

        self.data.borrow().borrow_mut().get().texture = texture;
    }

    /// Sets the texture of the object.
    ///
    /// The texture must already have been registered as `name`.
    #[inline]
    pub fn set_texture_with_name(&mut self, name: &str) {
        let texture = TextureManager::get_global_manager(|tm| tm.get(name).unwrap_or_else(
            || fail!("Invalid attempt to use the unregistered texture: " + name)));

        self.data.borrow().borrow_mut().get().texture = texture;
    }

    /// Move and orient the object such that it is placed at the point `eye` and have its `x` axis
    /// oriented toward `at`.
    #[inline]
    pub fn look_at(&mut self, eye: &Vec3<f32>, at: &Vec3<f32>, up: &Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.look_at(eye, at, up)
    }

    /// Move and orient the object such that it is placed at the point `eye` and have its `z` axis
    /// oriented toward `at`.
    #[inline]
    pub fn look_at_z(&mut self, eye: &Vec3<f32>, at: &Vec3<f32>, up: &Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.look_at_z(eye, at, up)
    }
}

impl Transformation<Transform3d> for Object {
    #[inline]
    fn transformation(&self) -> Transform3d {
        self.data.borrow().borrow().get().transform.clone()
    }

    #[inline]
    fn inv_transformation(&self) -> Transform3d {
        self.data.borrow().borrow().get().transform.inv_transformation()
    }

    #[inline]
    fn append_transformation(&mut self, t: &Transform3d) {
        self.data.borrow().borrow_mut().get().transform.append_transformation(t)
    }

    #[inline]
    fn append_transformation_cpy(_: &Object, _: &Transform3d) -> Object {
        fail!("Cannot clone an object.")
    }

    #[inline]
    fn prepend_transformation(&mut self, t: &Transform3d) {
        self.data.borrow().borrow_mut().get().transform.prepend_transformation(t)
    }

    #[inline]
    fn prepend_transformation_cpy(_: &Object, _: &Transform3d) -> Object {
        fail!("Cannot clone an object.")
    }

    #[inline]
    fn set_transformation(&mut self, t: Transform3d) {
        self.data.borrow().borrow_mut().get().transform.set_transformation(t)
    }
}

impl na::Transform<Vec3<f32>> for Object {
    #[inline]
    fn transform(&self, v: &Vec3<f32>) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.transform(v)
    }

    #[inline]
    fn inv_transform(&self, v: &Vec3<f32>) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.inv_transform(v)
    }
}

impl Rotation<Vec3<f32>> for Object {
    #[inline]
    fn rotation(&self) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.rotation()
    }

    #[inline]
    fn inv_rotation(&self) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.inv_rotation()
    }

    #[inline]
    fn append_rotation(&mut self, t: &Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.append_rotation(t)
    }

    #[inline]
    fn append_rotation_cpy(_: &Object, _: &Vec3<f32>) -> Object {
        fail!("Cannot clone an object.")
    }

    #[inline]
    fn prepend_rotation(&mut self, t: &Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.prepend_rotation(t)
    }

    #[inline]
    fn prepend_rotation_cpy(_: &Object, _: &Vec3<f32>) -> Object {
        fail!("Cannot clone an object.")
    }

    #[inline]
    fn set_rotation(&mut self, r: Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.set_rotation(r)
    }
}

impl Rotate<Vec3<f32>> for Object {
    #[inline]
    fn rotate(&self, v: &Vec3<f32>) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.rotate(v)
    }

    #[inline]
    fn inv_rotate(&self, v: &Vec3<f32>) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.inv_rotate(v)
    }
}

impl Translation<Vec3<f32>> for Object {
    #[inline]
    fn translation(&self) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.translation()
    }

    #[inline]
    fn inv_translation(&self) -> Vec3<f32> {
        self.data.borrow().borrow().get().transform.inv_translation()
    }

    #[inline]
    fn append_translation(&mut self, t: &Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.append_translation(t)
    }

    #[inline]
    fn append_translation_cpy(_: &Object, _: &Vec3<f32>) -> Object {
        fail!("Cannot clone an object.")
    }

    #[inline]
    fn prepend_translation(&mut self, t: &Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.prepend_translation(t)
    }

    #[inline]
    fn prepend_translation_cpy(_: &Object, _: &Vec3<f32>) -> Object {
        fail!("Cannot clone an object.")
    }

    #[inline]
    fn set_translation(&mut self, t: Vec3<f32>) {
        self.data.borrow().borrow_mut().get().transform.set_translation(t)
    }
}

impl Eq for Object {
    #[inline]
    fn eq(&self, other: &Object) -> bool {
        let d1 = self.data.borrow().borrow();
        let d2 = other.data.borrow().borrow();

        d1.get() as *ObjectData == d2.get() as *ObjectData
    }
}
<|endoftext|>


<commit_before><commit_msg>fix dereference<commit_after><|endoftext|>


<commit_before><commit_msg>Add regression tests for previously ambiguous syntactic forms<commit_after>// A bunch of tests for syntactic forms involving blocks that were
// previously ambiguous (e.g. 'if true { } *val;' gets parsed as a
// binop)

fn test1() { let val = @0; { } *val; }

fn test2() -> int { let val = @0; { } *val }

fn test3() {
    let regs = @{mutable eax: 0};
    alt true { true { } }
    (*regs).eax = 1;
}

fn test4() -> bool { let regs = @true; if true { } *regs || false }

fn test5() -> (int, int) { { } (0, 1) }

fn test6() -> bool { { } (true || false) && true }

fn test7() -> uint {
    let regs = @0;
    alt true { true { } }
    (*regs < 2) as uint
}

fn test8() -> int { let val = @0; alt true { true { } } *val < 1 ? 0 : 1 }

fn test9() { let regs = @mutable 0; alt true { true { } } *regs += 1; }

fn test10() -> int {
    let regs = @mutable [0];
    alt true { true { } }
    (*regs)[0]
}

fn test11() -> [int] { if true { } [1, 2] }
<|endoftext|>


<commit_before><commit_msg>fixed benchmarking bug<commit_after><|endoftext|>


<commit_before><commit_msg>:sparkles: Enable to ignore specified projects<commit_after><|endoftext|>


<commit_before><commit_msg>Includes test for reading data out of bit type table<commit_after>use fitsio::FitsFile;
use std::path::Path;

#[test]
fn test_reading_bit_data_type() {
    let source_file = Path::new("tests/fixtures/1065880128_01.mwaf");
    let mut f = FitsFile::open(source_file).unwrap();

    let table_hdu = f.hdu(1).unwrap();
    let flags: Vec<u32> = table_hdu.read_col(&mut f, "FLAGS").unwrap();
    assert_eq!(flags.len(), 1_849_344);
}
<|endoftext|>