<commit_before>// Copyright 2015-2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>

use std::ffi::CString;
use std::ops::Deref;
use std::path::Path;

extern crate libc;
use libc::{c_char, c_double};

use ffi;
use ::enums::SurfaceType;

use surface::{Surface, SurfaceExt};

#[cfg(feature = "use_glib")]
use glib::translate::*;

#[derive(Debug)]
pub struct PDFSurface(Surface);

extern "C" {
    pub fn cairo_pdf_surface_create (filename: *const c_char,
                                     width_in_points: c_double,
                                     height_in_points: c_double) -> *mut ffi::cairo_surface_t;
}

impl PDFSurface {
    pub fn from(surface: Surface) -> Result<PDFSurface, Surface> {
        if surface.get_type() == SurfaceType::Pdf {
            Ok(PDFSurface(surface))
        } else {
            Err(surface)
        }
    }

    pub unsafe fn from_raw_full(ptr: *mut ffi::cairo_surface_t) -> PDFSurface {
        Self::from(Surface::from_raw_full(ptr)).unwrap()
    }

    pub fn create<T: AsRef<Path>>(filename: T, width: f64, height: f64) -> PDFSurface
    {
        // Convert: AsRef<Path> -> Cow<str> -> str
        let s = filename.as_ref().to_string_lossy().into_owned();
        let file = CString::new(s).unwrap();
        unsafe { Self::from_raw_full(cairo_pdf_surface_create(file.as_ptr(), width, height)) }
    }
}

impl AsRef<Surface> for PDFSurface {
    fn as_ref(&self) -> &Surface {
        &self.0
    }
}

impl Deref for PDFSurface {
    type Target = Surface;

    fn deref(&self) -> &Surface {
        &self.0
    }
}

impl Clone for PDFSurface {
    fn clone(&self) -> PDFSurface {
        PDFSurface(self.0.clone())
    }
}

#[cfg(feature = "use_glib")]
impl<'a> ToGlibPtr<'a, *mut ffi::cairo_surface_t> for PDFSurface {
    type Storage = &'a Surface;

    #[inline]
    fn to_glib_none(&'a self) -> Stash<'a, *mut ffi::cairo_surface_t, Self> {
        let stash = self.0.to_glib_none();
        Stash(stash.0, stash.1)
    }

    #[inline]
    fn to_glib_full(&self) -> *mut ffi::cairo_surface_t {
        unsafe {
            ffi::cairo_surface_reference(self.0.to_glib_none().0)
        }
    }
}

#[cfg(feature = "use_glib")]
impl FromGlibPtrNone<*mut ffi::cairo_surface_t> for PDFSurface {
    #[inline]
    unsafe fn from_glib_none(ptr: *mut ffi::cairo_surface_t) -> PDFSurface {
        Self::from(from_glib_none(ptr)).unwrap()
    }
}

#[cfg(feature = "use_glib")]
impl FromGlibPtrBorrow<*mut ffi::cairo_surface_t> for PDFSurface {
    #[inline]
    unsafe fn from_glib_borrow(ptr: *mut ffi::cairo_surface_t) -> PDFSurface {
        Self::from(from_glib_borrow(ptr)).unwrap()
    }
}

#[cfg(feature = "use_glib")]
impl FromGlibPtrFull<*mut ffi::cairo_surface_t> for PDFSurface {
    #[inline]
    unsafe fn from_glib_full(ptr: *mut ffi::cairo_surface_t) -> PDFSurface {
        Self::from_raw_full(ptr)
    }
}

#[cfg(feature = "use_glib")]
gvalue_impl!(PDFSurface, ffi::cairo_surface_t, ffi::gobject::cairo_gobject_surface_get_type);

#[cfg(test)]
mod tests {
    use super::*;
    use context::*;
    use std::path::PathBuf;

    fn draw_x(cr: &Context) {
        cr.set_line_width(25.0);

        cr.set_source_rgba(1.0, 0.0, 0.0, 0.5);
        cr.line_to(0.,0.);
        cr.line_to(100.,100.);
        cr.stroke();

        cr.set_source_rgba(0.0, 0.0, 1.0, 0.5);
        cr.line_to(0.,100.);
        cr.line_to(100.,0.);
        cr.stroke();
    }

    #[test]
    fn pdf() {
        let output = PathBuf::from( env!("OUT_DIR") );

        { //Cow<str>
            let filename = output.join("test1.pdf");
            let surface = PDFSurface::create(filename, 100., 100.);
            let cr = Context::new(&surface);
            draw_x(&cr);
        }
        { // &str
            let filename = output.join("test2.pdf");
            let s = match filename.to_str() {
                None => panic!("Error converting Path to String"),
                Some(x) => x,
            };
            let surface = PDFSurface::create(s, 100., 100.);
            let cr = Context::new(&surface);
            draw_x(&cr);
        }
        { // String
            let filename = output.join("test3.pdf");
            let s = match filename.to_str() {
                None => panic!("Error converting Path to String"),
                Some(x) => String::from(x),
            };
            let surface = PDFSurface::create(s, 100., 100.);
            let cr = Context::new(&surface);
            draw_x(&cr);
        }
    }
}
<commit_msg>Remove old unused file pdf_surface.rs<commit_after><|endoftext|>


<commit_before>use entities::{ EntitiesState, EntitiesHelper, EntityID, ComponentID, NativeComponentType };
use std::collections::{ HashSet, HashMap };
use std::cell::RefCell;
use std::rc::Rc;
use nalgebra::na;
use nalgebra::na::{ Norm, Translation, Vec2, Vec3 };
use ncollide::geom::geom::Geom;
use nphysics::world::World;
use nphysics::object::{ RigidBody };
use log;

pub struct PhysicsSystem {
    world: World,
    bodies: HashMap<EntityID, Rc<RefCell<RigidBody>>>,
}

impl PhysicsSystem {
    pub fn new(_: &EntitiesState, log: |log::LogRecord|)
        -> PhysicsSystem
    {
        let mut world = World::new();
        world.set_gravity(Vec2::new(0.0f32, -9.8));

        let shape = ::ncollide::geom::Plane::new(Vec2::new(0.0f32, 1.0));
        let body = Rc::new(RefCell::new(RigidBody::new_static(shape, 0.3, 0.6)));
        world.add_body(body);

        PhysicsSystem {
            world: world,
            bodies: HashMap::new()
        }
    }

    pub fn process(&mut self, state: &mut EntitiesState, elapsed: &f64, log: |log::LogRecord|)
    {
        // getting the list of all entities that have physics activated
        let listOfEntities: HashSet<EntityID> = state.get_components_iter()
            .filter(|c| state.is_component_visible(*c).unwrap())
            .filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "physics", _ => false })
            .filter(|c| match state.get_as_boolean(*c, "activated") { Some(b) => b, _ => false })
            .map(|c| state.get_owner(c).unwrap())
            .collect();

        // removing from the world the elements that have disappeared
        {
            let toRemove: Vec<EntityID> = self.bodies.keys().filter(|e| !listOfEntities.contains(e.clone())).map(|e| e.clone()).collect();
            for e in toRemove.move_iter() {
                //self.bodies.find(&e).     // TODO: remove body from the world
                self.bodies.remove(&e);
            }
        }

        // adding elements that are not yet in the world
        {
            let toCreate: Vec<EntityID> = listOfEntities.iter().filter(|e| !self.bodies.contains_key(e.clone())).map(|e| e.clone()).collect();
            for e in toCreate.move_iter() {
                let shape = ::ncollide::geom::Cuboid::new(Vec2::new(0.5f32, 0.5f32));
                let body = Rc::new(RefCell::new(RigidBody::new_dynamic(shape, 1.0, 0.5, 0.0)));

                // initializing body with current position and movement
                body.borrow_mut().set_translation({ let p = PhysicsSystem::get_entity_position(state, &e); na::Vec2::new(p.x,p.y) });
                body.borrow_mut().set_lin_vel({ let p = PhysicsSystem::get_entity_movement(state, &e); na::Vec2::new(p.x,p.y) });

                self.bodies.insert(e.clone(), body.clone());
                self.world.add_body(body.clone());
            }
        }

        // setting all positions and movements
        for (entity, body) in self.bodies.iter() {
            let position = { let p = PhysicsSystem::get_entity_position(state, entity); na::Vec2::new(p.x,p.y) };
            let movement = { let p = PhysicsSystem::get_entity_movement(state, entity); na::Vec2::new(p.x,p.y) };
            let requestedMovement = PhysicsSystem::get_requested_movement(state, entity);

            let mut borrowedBody = body.borrow_mut();
            borrowedBody.set_translation(position);
            borrowedBody.set_lin_vel(movement);

            if requestedMovement.is_some() && requestedMovement != Some(movement) {
                let acceleration = na::normalize(&(requestedMovement.unwrap() - movement)) * 5.0f32;
                borrowedBody.set_lin_acc(acceleration);
            }
        }

        // step
        self.world.step(*elapsed as f32);

        //
        for (entity, body) in self.bodies.iter() {
            PhysicsSystem::set_position(state, entity, &body.borrow().translation());
            PhysicsSystem::set_movement(state, entity, &body.borrow().lin_vel());
        }
    }

    /// returns the position of an entity
    pub fn get_entity_position(state: &EntitiesState, id: &EntityID)
        -> na::Vec3<f32>
    {
        state
            .get_visible_native_components("position")
            .move_iter()

            // take only the components owned by the entity
            .filter(|c| state.get_owner(c).unwrap() == *id)

            // build a vector from each of the component
            .filter_map(|cmp| match (state.get_as_number(&cmp, "x"), state.get_as_number(&cmp, "y"), state.get_as_number(&cmp, "z")) {
                (Some(x), Some(y), Some(z))
                    => Some(na::Vec3::new(x as f32, y as f32, z as f32)),
                (Some(x), Some(y), _)
                    => Some(na::Vec3::new(x as f32, y as f32, 0.0)),
                _ => None
            })

            // add all the elements together
            .fold(na::Vec3::new(0.0, 0.0, 0.0), |vec, a| vec + a)
    }

    /// Returns the total movement of an entity.
    pub fn get_entity_movement(state: &EntitiesState, id: &EntityID)
        -> na::Vec3<f32>
    {
        state
            .get_visible_native_components("movement")
            .move_iter()

            // take only the components owned by the entity
            .filter(|c| state.get_owner(c).unwrap() == *id)

            // build a vector from each of the component
            .filter_map(|cmp| match (state.get_as_number(&cmp, "x"), state.get_as_number(&cmp, "y"), state.get_as_number(&cmp, "z")) {
                (Some(x), Some(y), Some(z))
                    => Some(na::Vec3::new(x as f32, y as f32, z as f32)),
                (Some(x), Some(y), _)
                    => Some(na::Vec3::new(x as f32, y as f32, 0.0)),
                _ => None
            })

            // add all the elements together
            .fold(na::Vec3::new(0.0, 0.0, 0.0), |vec, a| vec + a)
    }

    /// returns the total requested movement of an entity
    fn get_requested_movement(state: &EntitiesState, id: &EntityID)
        -> Option<Vec2<f32>>
    {
        state
            .get_visible_native_components("requestedMovement")
            .move_iter()

            // take only the components owned by the entity
            .filter(|c| state.get_owner(c).unwrap() == *id)

            // build a vector from each of the component
            .filter_map(|cmp| match (state.get_as_number(&cmp, "x"), state.get_as_number(&cmp, "y"), state.get_as_number(&cmp, "z")) {
                (Some(x), Some(y), _)
                    => Some(Vec2::new(x as f32, y as f32)),
                _ => None
            })

            // add all the elements together
            .fold(None, |vec: Option<Vec2<f32>>, a| match vec { None => Some(a), Some(v) => Some(v + a) })
    }

    /// changes the position of an entity
    /// TODO: this is wrong
    fn set_position(state: &mut EntitiesState, id: &EntityID, pos: &Vec2<f32>)
    {
        let list: Vec<ComponentID> = state
            .get_components_iter()
            // take only the components owned by the entity
            .filter(|c| state.get_owner(*c).unwrap() == *id)
            // take only the "position" components
            .filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "position", _ => false })
            .map(|c| c.clone()).collect();

        for cmp in list.iter()
        {
            state.set(cmp, "x", ::entities::Number(pos.x as f64));
            state.set(cmp, "y", ::entities::Number(pos.y as f64));
        }
    }

    /// changes the movement of an entity
    /// TODO: this is wrong
    fn set_movement(state: &mut EntitiesState, id: &EntityID, pos: &Vec2<f32>)
    {
        let list: Vec<ComponentID> = state
            .get_components_iter()
            // take only the components owned by the entity
            .filter(|c| state.get_owner(*c).unwrap() == *id)
            // take only the "position" components
            .filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "movement", _ => false })
            .map(|c| c.clone()).collect();

        for cmp in list.iter()
        {
            state.set(cmp, "x", ::entities::Number(pos.x as f64));
            state.set(cmp, "y", ::entities::Number(pos.y as f64));
        }
    }
}
<commit_msg>Update nphysics<commit_after>use entities::{ EntitiesState, EntitiesHelper, EntityID, ComponentID, NativeComponentType };
use std::collections::{ HashSet, HashMap };
use std::cell::RefCell;
use std::rc::Rc;
use nalgebra::na;
use nalgebra::na::{ Norm, Translation, Vec2, Vec3 };
use ncollide::geom::geom::Geom;
use nphysics::world::World;
use nphysics::object::{ RigidBody };
use log;

pub struct PhysicsSystem {
    world: World,
    bodies: HashMap<EntityID, Rc<RefCell<RigidBody>>>,
}

impl PhysicsSystem {
    pub fn new(_: &EntitiesState, log: |log::LogRecord|)
        -> PhysicsSystem
    {
        let mut world = World::new();
        world.set_gravity(Vec2::new(1.0f32, 1.0));

        let shape = ::ncollide::geom::Plane::new(Vec2::new(0.0f32, 1.0));
        let body = Rc::new(RefCell::new(RigidBody::new_static(shape, 0.3, 0.6)));
        world.add_body(body);

        PhysicsSystem {
            world: world,
            bodies: HashMap::new()
        }
    }

    pub fn process(&mut self, state: &mut EntitiesState, elapsed: &f64, log: |log::LogRecord|)
    {
        // getting the list of all entities that have physics activated
        let listOfEntities: HashSet<EntityID> = state.get_components_iter()
            .filter(|c| state.is_component_visible(*c).unwrap())
            .filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "physics", _ => false })
            .filter(|c| match state.get_as_boolean(*c, "activated") { Some(b) => b, _ => false })
            .map(|c| state.get_owner(c).unwrap())
            .collect();

        // removing from the world the elements that have disappeared
        {
            let toRemove: Vec<EntityID> = self.bodies.keys().filter(|e| !listOfEntities.contains(e.clone())).map(|e| e.clone()).collect();
            for e in toRemove.move_iter() {
                //self.bodies.find(&e).     // TODO: remove body from the world
                self.bodies.remove(&e);
            }
        }

        // adding elements that are not yet in the world
        {
            let toCreate: Vec<EntityID> = listOfEntities.iter().filter(|e| !self.bodies.contains_key(e.clone())).map(|e| e.clone()).collect();
            for e in toCreate.move_iter() {
                let shape = ::ncollide::geom::Cuboid::new(Vec2::new(0.5f32, 0.5f32));
                let body = Rc::new(RefCell::new(RigidBody::new_dynamic(shape, 1.0, 0.5, 0.0)));

                // initializing body with current position and movement
                body.borrow_mut().set_translation({ let p = PhysicsSystem::get_entity_position(state, &e); na::Vec2::new(p.x,p.y) });
                body.borrow_mut().set_lin_vel({ let p = PhysicsSystem::get_entity_movement(state, &e); na::Vec2::new(p.x,p.y) });

                self.bodies.insert(e.clone(), body.clone());
                self.world.add_body(body.clone());
            }
        }

        // setting all positions and movements
        for (entity, body) in self.bodies.iter() {
            let position = { let p = PhysicsSystem::get_entity_position(state, entity); na::Vec2::new(p.x,p.y) };
            let movement = { let p = PhysicsSystem::get_entity_movement(state, entity); na::Vec2::new(p.x,p.y) };
            let requestedMovement = PhysicsSystem::get_requested_movement(state, entity);

            let mut borrowedBody = body.borrow_mut();
            borrowedBody.set_translation(position);
            borrowedBody.set_lin_vel(movement);

            if requestedMovement.is_some() && requestedMovement != Some(movement) {
                let acceleration = na::normalize(&(requestedMovement.unwrap() - movement)) * 5.0f32;
                borrowedBody.set_lin_acc_scale(acceleration);
            }
        }

        // step
        self.world.step(*elapsed as f32);

        //
        for (entity, body) in self.bodies.iter() {
            PhysicsSystem::set_position(state, entity, &body.borrow().translation());
            PhysicsSystem::set_movement(state, entity, &body.borrow().lin_vel());
        }
    }

    /// returns the position of an entity
    pub fn get_entity_position(state: &EntitiesState, id: &EntityID)
        -> na::Vec3<f32>
    {
        state
            .get_visible_native_components("position")
            .move_iter()

            // take only the components owned by the entity
            .filter(|c| state.get_owner(c).unwrap() == *id)

            // build a vector from each of the component
            .filter_map(|cmp| match (state.get_as_number(&cmp, "x"), state.get_as_number(&cmp, "y"), state.get_as_number(&cmp, "z")) {
                (Some(x), Some(y), Some(z))
                    => Some(na::Vec3::new(x as f32, y as f32, z as f32)),
                (Some(x), Some(y), _)
                    => Some(na::Vec3::new(x as f32, y as f32, 0.0)),
                _ => None
            })

            // add all the elements together
            .fold(na::Vec3::new(0.0, 0.0, 0.0), |vec, a| vec + a)
    }

    /// Returns the total movement of an entity.
    pub fn get_entity_movement(state: &EntitiesState, id: &EntityID)
        -> na::Vec3<f32>
    {
        state
            .get_visible_native_components("movement")
            .move_iter()

            // take only the components owned by the entity
            .filter(|c| state.get_owner(c).unwrap() == *id)

            // build a vector from each of the component
            .filter_map(|cmp| match (state.get_as_number(&cmp, "x"), state.get_as_number(&cmp, "y"), state.get_as_number(&cmp, "z")) {
                (Some(x), Some(y), Some(z))
                    => Some(na::Vec3::new(x as f32, y as f32, z as f32)),
                (Some(x), Some(y), _)
                    => Some(na::Vec3::new(x as f32, y as f32, 0.0)),
                _ => None
            })

            // add all the elements together
            .fold(na::Vec3::new(0.0, 0.0, 0.0), |vec, a| vec + a)
    }

    /// returns the total requested movement of an entity
    fn get_requested_movement(state: &EntitiesState, id: &EntityID)
        -> Option<Vec2<f32>>
    {
        state
            .get_visible_native_components("requestedMovement")
            .move_iter()

            // take only the components owned by the entity
            .filter(|c| state.get_owner(c).unwrap() == *id)

            // build a vector from each of the component
            .filter_map(|cmp| match (state.get_as_number(&cmp, "x"), state.get_as_number(&cmp, "y"), state.get_as_number(&cmp, "z")) {
                (Some(x), Some(y), _)
                    => Some(Vec2::new(x as f32, y as f32)),
                _ => None
            })

            // add all the elements together
            .fold(None, |vec: Option<Vec2<f32>>, a| match vec { None => Some(a), Some(v) => Some(v + a) })
    }

    /// changes the position of an entity
    /// TODO: this is wrong
    fn set_position(state: &mut EntitiesState, id: &EntityID, pos: &Vec2<f32>)
    {
        let list: Vec<ComponentID> = state
            .get_components_iter()
            // take only the components owned by the entity
            .filter(|c| state.get_owner(*c).unwrap() == *id)
            // take only the "position" components
            .filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "position", _ => false })
            .map(|c| c.clone()).collect();

        for cmp in list.iter()
        {
            state.set(cmp, "x", ::entities::Number(pos.x as f64));
            state.set(cmp, "y", ::entities::Number(pos.y as f64));
        }
    }

    /// changes the movement of an entity
    /// TODO: this is wrong
    fn set_movement(state: &mut EntitiesState, id: &EntityID, pos: &Vec2<f32>)
    {
        let list: Vec<ComponentID> = state
            .get_components_iter()
            // take only the components owned by the entity
            .filter(|c| state.get_owner(*c).unwrap() == *id)
            // take only the "position" components
            .filter(|c| match state.get_type(*c) { Ok(NativeComponentType(t)) => t.as_slice() == "movement", _ => false })
            .map(|c| c.clone()).collect();

        for cmp in list.iter()
        {
            state.set(cmp, "x", ::entities::Number(pos.x as f64));
            state.set(cmp, "y", ::entities::Number(pos.y as f64));
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use anyhow::{anyhow, Result};
use std::process::Command;

fn check_that_version_control_has_no_unstaged_changes() -> Result<()> {
    let output = Command::new("git")
        .arg("status")
        .arg("--porcelain")
        .output()
        .unwrap();
    if !(output.stdout.is_empty() && output.status.success()) {
        Err(anyhow!(
            "Git repository should be in a clean state, but found:\n{}\n",
            std::str::from_utf8(&output.stdout).unwrap_or("<binary>"),
        ))
    } else {
        Ok(())
    }
}

#[test]
fn test_that_generated_file_are_up_to_date_in_git() {
    // Don't check if git isn't in a clean state
    if check_that_version_control_has_no_unstaged_changes().is_ok() {
        // If this assertion fails, run the following command to re-generate DPN release:
        // `cargo run --release -p framework`
        assert!(Command::new("cargo")
            .current_dir(std::env!("CARGO_MANIFEST_DIR"))
            .arg("run")
            .arg("--release")
            .arg("-p")
            .arg("framework")
            .status()
            .unwrap()
            .success());

        // If this assertion fails, run the following command to re-generate experimental release:
        // `cargo run --release -p framework -- --package experimental`
        assert!(Command::new("cargo")
            .current_dir(std::env!("CARGO_MANIFEST_DIR"))
            .arg("run")
            .arg("--release")
            .arg("-p")
            .arg("framework")
            .arg("--")
            .arg("--package")
            .arg("experimental")
            .status()
            .unwrap()
            .success());

        // Running the stdlib tool should not create unstaged changes.
        check_that_version_control_has_no_unstaged_changes()
            .unwrap_or_else(|err_msg| panic!("{}", err_msg))
    }
}
<commit_msg>[AptosFramework] check the generated file up to date<commit_after>// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use anyhow::{anyhow, Result};
use std::process::Command;

fn check_that_version_control_has_no_unstaged_changes() -> Result<()> {
    let output = Command::new("git")
        .arg("status")
        .arg("--porcelain")
        .output()
        .unwrap();
    if !(output.stdout.is_empty() && output.status.success()) {
        Err(anyhow!(
            "Git repository should be in a clean state, but found:\n{}\n",
            std::str::from_utf8(&output.stdout).unwrap_or("<binary>"),
        ))
    } else {
        Ok(())
    }
}

#[test]
fn test_that_generated_file_are_up_to_date_in_git() {
    // Don't check if git isn't in a clean state
    if check_that_version_control_has_no_unstaged_changes().is_ok() {
        // If this assertion fails, run the following command to re-generate experimental release:
        // `cargo run --release -p framework -- --package aptos-framework`
        assert!(Command::new("cargo")
            .current_dir(std::env!("CARGO_MANIFEST_DIR"))
            .arg("run")
            .arg("--release")
            .arg("-p")
            .arg("framework")
            .arg("--")
            .arg("--package")
            .arg("aptos-framework")
            .status()
            .unwrap()
            .success());

        // Running the stdlib tool should not create unstaged changes.
        check_that_version_control_has_no_unstaged_changes()
            .unwrap_or_else(|err_msg| panic!("{}", err_msg))
    }
}
<|endoftext|>


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

//! Mesh loading.
//!
//! A `Mesh` describes the geometry of an object. All or part of a `Mesh` can be drawn with a
//! single draw call. A `Mesh` consists of a series of vertices, each with a certain amount of
//! user-specified attributes. These attributes are fed into shader programs. The easiest way to
//! create a mesh is to use the `#[vertex_format]` attribute on a struct, upload them into a
//! `Buffer`, and then use `Mesh::from`.

use device;
use device::attrib;

/// Describes a single attribute of a vertex buffer, including its type, name, etc.
#[deriving(Clone, PartialEq, Show)]
pub struct Attribute {
    /// A name to match the shader input
    pub name: String,
    /// Vertex buffer to contain the data
    pub buffer: device::RawBufferHandle,
    /// Format of the attribute
    pub format: attrib::Format,
}

/// A trait implemented automatically for user vertex structure by
/// `#[vertex_format] attribute
pub trait VertexFormat {
    /// Create the attributes for this type, using the given buffer.
    fn generate(Option<Self>, buffer: device::RawBufferHandle) -> Vec<Attribute>;
}

/// Describes geometry to render.
#[deriving(Clone, PartialEq, Show)]
pub struct Mesh {
    /// Number of vertices in the mesh.
    pub num_vertices: device::VertexCount,
    /// Vertex attributes to use.
    pub attributes: Vec<Attribute>,
}

impl Mesh {
    /// Create a new mesh, which is a `TriangleList` with no attributes and `nv` vertices.
    pub fn new(nv: device::VertexCount) -> Mesh {
        Mesh {
            num_vertices: nv,
            attributes: Vec::new(),
        }
    }

    /// Create a new `Mesh` from a struct that implements `VertexFormat` and a buffer.
    pub fn from_format<V: VertexFormat>(buf: device::BufferHandle<V>, nv: device::VertexCount) -> Mesh {
        Mesh {
            num_vertices: nv,
            attributes: VertexFormat::generate(None::<V>, buf.raw()),
        }
    }

    /// Create a new intanced `Mesh` given a vertex buffer and an instance buffer.
    pub fn from_format_instanced<V: VertexFormat, U: VertexFormat>(
                                 buf: device::BufferHandle<V>, nv: device::VertexCount,
                                 inst: device::BufferHandle<U>) -> Mesh {
        let per_vertex   = VertexFormat::generate(None::<V>, buf.raw());
        let per_instance = VertexFormat::generate(None::<U>, inst.raw());

        let mut attributes = per_vertex;
        for mut at in per_instance.move_iter() {
            at.format.instance_rate = 1;
            attributes.push(at);
        }

        Mesh {
            num_vertices: nv,
            attributes: attributes,
        }
    }

    /// Return a vertex slice of the whole mesh
    pub fn get_slice(&self, pt: device::PrimitiveType) -> Slice {
        VertexSlice(pt, 0, self.num_vertices)
    }
}

/// Description of a subset of `Mesh` data to render.
/// We provide a primitive type in a slice because it is how we interpret mesh
/// contents. For example, we can have a `Point` typed vertex slice to do shape
/// blending, while still rendereing it as an indexed `TriangleList`.
#[deriving(Clone, Show)]
pub enum Slice  {
    /// Render vertex data directly from the `Mesh`'s buffer, using only the vertices between the two
    /// endpoints.
    VertexSlice(device::PrimitiveType, device::VertexCount, device::VertexCount),
    /// The `IndexSlice*` buffer contains a list of indices into the `Mesh` data, so every vertex
    /// attribute does not need to be duplicated, only its position in the `Mesh`.  For example,
    /// when drawing a square, two triangles are needed.  Using only `VertexSlice`, one would need
    /// 6 separate vertices, 3 for each triangle. However, two of the vertices will be identical,
    /// wasting space for the duplicated attributes.  Instead, the `Mesh` can store 4 vertices and
    /// an `IndexSlice8` can be used instead.
    IndexSlice8(device::PrimitiveType, device::BufferHandle<u8>, device::IndexCount, device::IndexCount),
    /// As `IndexSlice8` but with `u16` indices
    IndexSlice16(device::PrimitiveType, device::BufferHandle<u16>, device::IndexCount, device::IndexCount),
    /// As `IndexSlice8` but with `u32` indices
    IndexSlice32(device::PrimitiveType, device::BufferHandle<u32>, device::IndexCount, device::IndexCount),
}

/// Describes kinds of errors that may occur in the mesh linking
#[deriving(Clone, Show)]
pub enum LinkError {
    /// An attribute index is out of supported bounds
    ErrorMeshAttribute(uint),
    /// An input index is out of supported bounds
    ErrorShaderInput(uint),
}

static BITS_PER_ATTRIBUTE: uint = 4;
static MAX_SHADER_INPUTS: uint = 64 / BITS_PER_ATTRIBUTE;
static MESH_ATTRIBUTE_MASK: uint = (1u << BITS_PER_ATTRIBUTE) - 1;

/// An iterator over mesh attributes.
pub struct AttributeIndices {
    value: u64,
}

impl Iterator<uint> for AttributeIndices {
    fn next(&mut self) -> Option<uint> {
        let id = (self.value as uint) & MESH_ATTRIBUTE_MASK;
        self.value >>= BITS_PER_ATTRIBUTE;
        Some(id)
    }
}

/// The strcture holding remapping table from shader inputs to mesh attributes
pub struct Link {
    table: u64,
}

impl Link {
    /// Construct a new link from an iterator over attribute indices
    pub fn from_iter<I: Iterator<uint>>(iter: I) -> Result<Link, LinkError> {
        let mut table = 0u64;
        for (input, attrib) in iter.enumerate() {
            if input >= MAX_SHADER_INPUTS {
                return Err(ErrorShaderInput(input))
            }else if attrib > MESH_ATTRIBUTE_MASK {
                return Err(ErrorMeshAttribute(attrib))
            }else {
                table |= attrib as u64 << (input * BITS_PER_ATTRIBUTE);
            }
        }
        Ok(Link {
            table: table,
        })
    }

    /// Convert to an iterator returning attribute indices
    pub fn attribute_indices(&self) -> AttributeIndices {
        AttributeIndices {
            value: self.table,
        }
    }
}
<commit_msg>Improve documentation wording<commit_after>// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Mesh loading.
//!
//! A `Mesh` describes the geometry of an object. All or part of a `Mesh` can be drawn with a
//! single draw call. A `Mesh` consists of a series of vertices, each with a certain amount of
//! user-specified attributes. These attributes are fed into shader programs. The easiest way to
//! create a mesh is to use the `#[vertex_format]` attribute on a struct, upload them into a
//! `Buffer`, and then use `Mesh::from`.

use device;
use device::attrib;

/// Describes a single attribute of a vertex buffer, including its type, name, etc.
#[deriving(Clone, PartialEq, Show)]
pub struct Attribute {
    /// A name to match the shader input
    pub name: String,
    /// Vertex buffer to contain the data
    pub buffer: device::RawBufferHandle,
    /// Format of the attribute
    pub format: attrib::Format,
}

/// A trait implemented automatically for user vertex structure by
/// `#[vertex_format] attribute
pub trait VertexFormat {
    /// Create the attributes for this type, using the given buffer.
    fn generate(Option<Self>, buffer: device::RawBufferHandle) -> Vec<Attribute>;
}

/// Describes geometry to render.
#[deriving(Clone, PartialEq, Show)]
pub struct Mesh {
    /// Number of vertices in the mesh.
    pub num_vertices: device::VertexCount,
    /// Vertex attributes to use.
    pub attributes: Vec<Attribute>,
}

impl Mesh {
    /// Create a new mesh, which is a `TriangleList` with no attributes and `nv` vertices.
    pub fn new(nv: device::VertexCount) -> Mesh {
        Mesh {
            num_vertices: nv,
            attributes: Vec::new(),
        }
    }

    /// Create a new `Mesh` from a struct that implements `VertexFormat` and a buffer.
    pub fn from_format<V: VertexFormat>(buf: device::BufferHandle<V>, nv: device::VertexCount) -> Mesh {
        Mesh {
            num_vertices: nv,
            attributes: VertexFormat::generate(None::<V>, buf.raw()),
        }
    }

    /// Create a new intanced `Mesh` given a vertex buffer and an instance buffer.
    pub fn from_format_instanced<V: VertexFormat, U: VertexFormat>(
                                 buf: device::BufferHandle<V>, nv: device::VertexCount,
                                 inst: device::BufferHandle<U>) -> Mesh {
        let per_vertex   = VertexFormat::generate(None::<V>, buf.raw());
        let per_instance = VertexFormat::generate(None::<U>, inst.raw());

        let mut attributes = per_vertex;
        for mut at in per_instance.move_iter() {
            at.format.instance_rate = 1;
            attributes.push(at);
        }

        Mesh {
            num_vertices: nv,
            attributes: attributes,
        }
    }

    /// Return a vertex slice of the whole mesh
    pub fn get_slice(&self, pt: device::PrimitiveType) -> Slice {
        VertexSlice(pt, 0, self.num_vertices)
    }
}

/// Description of a subset of `Mesh` data to render.
/// We provide a primitive type in a slice because it is how we interpret mesh
/// contents. For example, we can have a `Point` typed vertex slice to do shape
/// blending, while still rendereing it as an indexed `TriangleList`.
#[deriving(Clone, Show)]
pub enum Slice  {
    /// Render vertex data directly from the `Mesh`'s buffer, using only the vertices between the two
    /// endpoints.
    VertexSlice(device::PrimitiveType, device::VertexCount, device::VertexCount),
    /// The `IndexSlice*` buffer contains a list of indices into the `Mesh` data, so every vertex
    /// attribute does not need to be duplicated, only its position in the `Mesh`.  For example,
    /// when drawing a square, two triangles are needed.  Using only `VertexSlice`, one would need
    /// 6 separate vertices, 3 for each triangle. However, two of the vertices will be identical,
    /// wasting space for the duplicated attributes.  Instead, the `Mesh` can store 4 vertices and
    /// an `IndexSlice8` can be used instead.
    IndexSlice8(device::PrimitiveType, device::BufferHandle<u8>, device::IndexCount, device::IndexCount),
    /// As `IndexSlice8` but with `u16` indices
    IndexSlice16(device::PrimitiveType, device::BufferHandle<u16>, device::IndexCount, device::IndexCount),
    /// As `IndexSlice8` but with `u32` indices
    IndexSlice32(device::PrimitiveType, device::BufferHandle<u32>, device::IndexCount, device::IndexCount),
}

/// Describes kinds of errors that may occur in the mesh linking
#[deriving(Clone, Show)]
pub enum LinkError {
    /// An attribute index is out of supported bounds
    ErrorMeshAttribute(uint),
    /// An input index is out of supported bounds
    ErrorShaderInput(uint),
}

static BITS_PER_ATTRIBUTE: uint = 4;
static MAX_SHADER_INPUTS: uint = 64 / BITS_PER_ATTRIBUTE;
static MESH_ATTRIBUTE_MASK: uint = (1u << BITS_PER_ATTRIBUTE) - 1;

/// An iterator over mesh attributes.
pub struct AttributeIndices {
    value: u64,
}

impl Iterator<uint> for AttributeIndices {
    fn next(&mut self) -> Option<uint> {
        let id = (self.value as uint) & MESH_ATTRIBUTE_MASK;
        self.value >>= BITS_PER_ATTRIBUTE;
        Some(id)
    }
}

/// Holds a remapping table from shader inputs to mesh attributes.
pub struct Link {
    table: u64,
}

impl Link {
    /// Construct a new link from an iterator over attribute indices.
    pub fn from_iter<I: Iterator<uint>>(iter: I) -> Result<Link, LinkError> {
        let mut table = 0u64;
        for (input, attrib) in iter.enumerate() {
            if input >= MAX_SHADER_INPUTS {
                return Err(ErrorShaderInput(input))
            }else if attrib > MESH_ATTRIBUTE_MASK {
                return Err(ErrorMeshAttribute(attrib))
            }else {
                table |= attrib as u64 << (input * BITS_PER_ATTRIBUTE);
            }
        }
        Ok(Link {
            table: table,
        })
    }

    /// Convert to an iterator returning attribute indices
    pub fn attribute_indices(&self) -> AttributeIndices {
        AttributeIndices {
            value: self.table,
        }
    }
}
<|endoftext|>


<commit_before>//! Types for the *m.room.member* event.

use ruma_identifiers::UserId;
use ruma_signatures::Signatures;
use serde::{Deserialize, Serialize};

state_event! {
    /// The current membership state of a user in the room.
    ///
    /// Adjusts the membership state for a user in a room. It is preferable to use the membership
    /// APIs (`/rooms/<room id>/invite` etc) when performing membership actions rather than
    /// adjusting the state directly as there are a restricted set of valid transformations. For
    /// example, user A cannot force user B to join a room, and trying to force this state change
    /// directly will fail.
    ///
    /// The `third_party_invite` property will be set if this invite is an *invite* event and is the
    /// successor of an *m.room.third_party_invite* event, and absent otherwise.
    ///
    /// This event may also include an `invite_room_state` key inside the event's unsigned data. If
    /// present, this contains an array of `StrippedState` events. These events provide information
    /// on a subset of state events such as the room name.
    ///
    /// The user for which a membership applies is represented by the `state_key`. Under some
    /// conditions, the `sender` and `state_key` may not match - this may be interpreted as the
    /// `sender` affecting the membership state of the `state_key` user.
    ///
    /// The membership for a given user can change over time. Previous membership can be retrieved
    /// from the `prev_content` object on an event. If not present, the user's previous membership
    /// must be assumed as leave.
    pub struct MemberEvent(MemberEventContent) {}
}

/// The payload of a `MemberEvent`.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct MemberEventContent {
    /// The avatar URL for this user, if any. This is added by the homeserver.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub avatar_url: Option<String>,

    /// The display name for this user, if any. This is added by the homeserver.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub displayname: Option<String>,

    /// Flag indicating if the room containing this event was created
    /// with the intention of being a direct chat.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_direct: Option<bool>,

    /// The membership state of this user.
    pub membership: MembershipState,

    /// If this member event is the successor to a third party invitation, this field will contain
    /// information about that invitation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub third_party_invite: Option<ThirdPartyInvite>,
}

/// The membership state of a user.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub enum MembershipState {
    /// The user is banned.
    #[serde(rename = "ban")]
    Ban,

    /// The user has been invited.
    #[serde(rename = "invite")]
    Invite,

    /// The user has joined.
    #[serde(rename = "join")]
    Join,

    /// The user has requested to join.
    #[serde(rename = "knock")]
    Knock,

    /// The user has left.
    #[serde(rename = "leave")]
    Leave,
}

impl_enum! {
    MembershipState {
        Ban => "ban",
        Invite => "invite",
        Join => "join",
        Knock => "knock",
        Leave => "leave",
    }
}

/// Information about a third party invitation.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ThirdPartyInvite {
    /// A name which can be displayed to represent the user instead of their third party
    /// identifier.
    pub display_name: String,
    /// A block of content which has been signed, which servers can use to verify the event.
    /// Clients should ignore this.
    pub signed: SignedContent,
}

/// A block of content which has been signed, which servers can use to verify a third party
/// invitation.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SignedContent {
    /// The invited Matrix user ID.
    ///
    /// Must be equal to the user_id property of the event.
    pub mxid: UserId,
    /// A single signature from the verifying server, in the format specified by the Signing Events
    /// section of the server-server API.
    pub signatures: Signatures,
    /// The token property of the containing third_party_invite object.
    pub token: String,
}
<commit_msg>Add a note about m.room.member's invite_room_state data.<commit_after>//! Types for the *m.room.member* event.

use ruma_identifiers::UserId;
use ruma_signatures::Signatures;
use serde::{Deserialize, Serialize};

state_event! {
    /// The current membership state of a user in the room.
    ///
    /// Adjusts the membership state for a user in a room. It is preferable to use the membership
    /// APIs (`/rooms/<room id>/invite` etc) when performing membership actions rather than
    /// adjusting the state directly as there are a restricted set of valid transformations. For
    /// example, user A cannot force user B to join a room, and trying to force this state change
    /// directly will fail.
    ///
    /// The `third_party_invite` property will be set if this invite is an *invite* event and is the
    /// successor of an *m.room.third_party_invite* event, and absent otherwise.
    ///
    /// This event may also include an `invite_room_state` key inside the event's unsigned data. If
    /// present, this contains an array of `StrippedState` events. These events provide information
    /// on a subset of state events such as the room name. Note that ruma-events treats unsigned
    /// data on events as arbitrary JSON values, and the ruma-events types for this event don't
    /// provide direct access to these `invite_room_state`. If you need this data, you must extract
    /// and convert it from a `serde_json::Value` yourself.
    ///
    /// The user for which a membership applies is represented by the `state_key`. Under some
    /// conditions, the `sender` and `state_key` may not match - this may be interpreted as the
    /// `sender` affecting the membership state of the `state_key` user.
    ///
    /// The membership for a given user can change over time. Previous membership can be retrieved
    /// from the `prev_content` object on an event. If not present, the user's previous membership
    /// must be assumed as leave.
    pub struct MemberEvent(MemberEventContent) {}
}

/// The payload of a `MemberEvent`.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct MemberEventContent {
    /// The avatar URL for this user, if any. This is added by the homeserver.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub avatar_url: Option<String>,

    /// The display name for this user, if any. This is added by the homeserver.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub displayname: Option<String>,

    /// Flag indicating if the room containing this event was created
    /// with the intention of being a direct chat.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_direct: Option<bool>,

    /// The membership state of this user.
    pub membership: MembershipState,

    /// If this member event is the successor to a third party invitation, this field will contain
    /// information about that invitation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub third_party_invite: Option<ThirdPartyInvite>,
}

/// The membership state of a user.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
pub enum MembershipState {
    /// The user is banned.
    #[serde(rename = "ban")]
    Ban,

    /// The user has been invited.
    #[serde(rename = "invite")]
    Invite,

    /// The user has joined.
    #[serde(rename = "join")]
    Join,

    /// The user has requested to join.
    #[serde(rename = "knock")]
    Knock,

    /// The user has left.
    #[serde(rename = "leave")]
    Leave,
}

impl_enum! {
    MembershipState {
        Ban => "ban",
        Invite => "invite",
        Join => "join",
        Knock => "knock",
        Leave => "leave",
    }
}

/// Information about a third party invitation.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct ThirdPartyInvite {
    /// A name which can be displayed to represent the user instead of their third party
    /// identifier.
    pub display_name: String,
    /// A block of content which has been signed, which servers can use to verify the event.
    /// Clients should ignore this.
    pub signed: SignedContent,
}

/// A block of content which has been signed, which servers can use to verify a third party
/// invitation.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SignedContent {
    /// The invited Matrix user ID.
    ///
    /// Must be equal to the user_id property of the event.
    pub mxid: UserId,
    /// A single signature from the verifying server, in the format specified by the Signing Events
    /// section of the server-server API.
    pub signatures: Signatures,
    /// The token property of the containing third_party_invite object.
    pub token: String,
}
<|endoftext|>


<commit_before>use std::rand;

pub mod ll {
    use std::libc::{c_int, uint8_t, uint32_t};

    //SDL_pixels.h
    pub struct SDL_Color {
        r: uint8_t,
        g: uint8_t,
        b: uint8_t,
        a: uint8_t,
    }

    pub struct SDL_Palette {
        ncolors: c_int,
        colors: *SDL_Color,
        version: uint32_t,
        refcount: c_int
    }

    pub struct SDL_PixelFormat {
        format: SDL_PixelFormatFlag,
        palette: *SDL_Palette,
        BitsPerPixel: uint8_t,
        BytesPerPixel: uint8_t,
        padding: [uint8_t, ..2],
        Rmask: uint8_t,
        Gmask: uint8_t,
        Bmask: uint8_t,
        Amask: uint8_t,
        Rloss: uint8_t,
        Gloss: uint8_t,
        Bloss: uint8_t,
        Aloss: uint8_t,
        Rshift: uint8_t,
        Gshift: uint8_t,
        Bshift: uint8_t,
        Ashift: uint8_t,
        refcount: c_int,
        next: *SDL_PixelFormat
    }

    pub type SDL_PixelFormatFlag = uint32_t;
    pub static SDL_PIXELFORMAT_UNKNOWN: SDL_PixelFormatFlag = 0x0;
    pub static SDL_PIXELFORMAT_INDEX1LSB: SDL_PixelFormatFlag = 0x11100100;
    pub static SDL_PIXELFORMAT_INDEX1MSB: SDL_PixelFormatFlag = 0x11200100;
    pub static SDL_PIXELFORMAT_INDEX4LSB: SDL_PixelFormatFlag = 0x12100400;
    pub static SDL_PIXELFORMAT_INDEX4MSB: SDL_PixelFormatFlag = 0x12200400;
    pub static SDL_PIXELFORMAT_INDEX8: SDL_PixelFormatFlag = 0x13000801;
    pub static SDL_PIXELFORMAT_RGB332: SDL_PixelFormatFlag = 0x14110801;
    pub static SDL_PIXELFORMAT_RGB444: SDL_PixelFormatFlag = 0x15120c02;
    pub static SDL_PIXELFORMAT_RGB555: SDL_PixelFormatFlag = 0x15130f02;
    pub static SDL_PIXELFORMAT_BGR555: SDL_PixelFormatFlag = 0x15530f02;
    pub static SDL_PIXELFORMAT_ARGB4444: SDL_PixelFormatFlag = 0x15321002;
    pub static SDL_PIXELFORMAT_RGBA4444: SDL_PixelFormatFlag = 0x15421002;
    pub static SDL_PIXELFORMAT_ABGR4444: SDL_PixelFormatFlag = 0x15721002;
    pub static SDL_PIXELFORMAT_BGRA4444: SDL_PixelFormatFlag = 0x15821002;
    pub static SDL_PIXELFORMAT_ARGB1555: SDL_PixelFormatFlag = 0x15331002;
    pub static SDL_PIXELFORMAT_RGBA5551: SDL_PixelFormatFlag = 0x15441002;
    pub static SDL_PIXELFORMAT_ABGR1555: SDL_PixelFormatFlag = 0x15731002;
    pub static SDL_PIXELFORMAT_BGRA5551: SDL_PixelFormatFlag = 0x15841002;
    pub static SDL_PIXELFORMAT_RGB565: SDL_PixelFormatFlag = 0x15151002;
    pub static SDL_PIXELFORMAT_BGR565: SDL_PixelFormatFlag = 0x15551002;
    pub static SDL_PIXELFORMAT_RGB24: SDL_PixelFormatFlag = 0x17101803;
    pub static SDL_PIXELFORMAT_BGR24: SDL_PixelFormatFlag = 0x17401803;
    pub static SDL_PIXELFORMAT_RGB888: SDL_PixelFormatFlag = 0x16161804;
    pub static SDL_PIXELFORMAT_RGBX8888: SDL_PixelFormatFlag = 0x16261804;
    pub static SDL_PIXELFORMAT_BGR888: SDL_PixelFormatFlag = 0x16561804;
    pub static SDL_PIXELFORMAT_BGRX8888: SDL_PixelFormatFlag = 0x16661804;
    pub static SDL_PIXELFORMAT_ARGB8888: SDL_PixelFormatFlag = 0x16362004;
    pub static SDL_PIXELFORMAT_RGBA8888: SDL_PixelFormatFlag = 0x16462004;
    pub static SDL_PIXELFORMAT_ABGR8888: SDL_PixelFormatFlag = 0x16762004;
    pub static SDL_PIXELFORMAT_BGRA8888: SDL_PixelFormatFlag = 0x16862004;
    pub static SDL_PIXELFORMAT_ARGB2101010: SDL_PixelFormatFlag = 0x16372004;
    pub static SDL_PIXELFORMAT_YV12: SDL_PixelFormatFlag = 0x32315659;
    pub static SDL_PIXELFORMAT_IYUV: SDL_PixelFormatFlag = 0x56555949;
    pub static SDL_PIXELFORMAT_YUY2: SDL_PixelFormatFlag = 0x32595559;
    pub static SDL_PIXELFORMAT_UYVY: SDL_PixelFormatFlag = 0x59565955;
    pub static SDL_PIXELFORMAT_YVYU: SDL_PixelFormatFlag = 0x55595659;

    extern "C" {
        pub fn SDL_GetRGB(pixel: uint32_t, format: *SDL_PixelFormat, r: *uint8_t, g: *uint8_t, b: *uint8_t);
        pub fn SDL_GetRGBA(pixel: uint32_t, format: *SDL_PixelFormat, r: *uint8_t, g: *uint8_t, b: *uint8_t, a: *uint8_t);
        pub fn SDL_MapRGB(format: *SDL_PixelFormat, r: uint8_t, g: uint8_t, b: uint8_t) -> uint32_t;
        pub fn SDL_MapRGBA(format: *SDL_PixelFormat, r: uint8_t, g: uint8_t, b: uint8_t, a: uint8_t) -> uint32_t;
    }
}
#[deriving(Eq)]
pub struct Palette {
    raw: *ll::SDL_Palette
}

#[deriving(Eq)]
pub enum Color {
    RGB(u8, u8, u8),
    RGBA(u8, u8, u8, u8)
}

impl Color {
    pub fn to_u32(&self, format: &PixelFormat) -> u32 {
        match self {
            &RGB(r, g, b) => {
                unsafe { ll::SDL_MapRGB(format.raw, r, g, b) }
            }
            &RGBA(r, g, b, a) => {
                unsafe { ll::SDL_MapRGBA(format.raw, r, g, b, a) }
            }
        }
    }

    pub fn from_u32(format: &PixelFormat, pixel: u32) -> Color {
        let r: u8 = 0;
        let g: u8 = 0;
        let b: u8 = 0;
        let a: u8 = 0;

        let result = unsafe {
             ll::SDL_GetRGBA(pixel, format.raw, &r, &g, &b, &a)
        };
        RGBA(r, g, b, a)
    }
}

impl rand::Rand for Color {
    fn rand<R: rand::Rng>(rng: &mut R) -> Color {
        if rng.gen() { RGBA(rng.gen(), rng.gen(), rng.gen(), rng.gen()) }
        else { RGB(rng.gen(), rng.gen(), rng.gen()) }
    }
}

#[deriving(Eq)]
pub struct PixelFormat {
    raw: *ll::SDL_PixelFormat
}

#[deriving(Eq, FromPrimitive)]
pub enum PixelFormatFlag {
    Unknown = ll::SDL_PIXELFORMAT_UNKNOWN as int,
    Index1LSB = ll::SDL_PIXELFORMAT_INDEX1LSB as int,
    Index1MSB = ll::SDL_PIXELFORMAT_INDEX1MSB as int,
    Index4LSB = ll::SDL_PIXELFORMAT_INDEX4LSB as int,
    Index4MSB = ll::SDL_PIXELFORMAT_INDEX4MSB as int,
    Index8 = ll::SDL_PIXELFORMAT_INDEX8 as int,
    RGB332 = ll::SDL_PIXELFORMAT_RGB332 as int,
    RGB444 = ll::SDL_PIXELFORMAT_RGB444 as int,
    RGB555 = ll::SDL_PIXELFORMAT_RGB555 as int,
    BGR555 = ll::SDL_PIXELFORMAT_BGR555 as int,
    ARGB4444 = ll::SDL_PIXELFORMAT_ARGB4444 as int,
    RGBA4444 = ll::SDL_PIXELFORMAT_RGBA4444 as int,
    ABGR4444 = ll::SDL_PIXELFORMAT_ABGR4444 as int,
    BGRA4444 = ll::SDL_PIXELFORMAT_BGRA4444 as int,
    ARGB1555 = ll::SDL_PIXELFORMAT_ARGB1555 as int,
    RGBA5551 = ll::SDL_PIXELFORMAT_RGBA5551 as int,
    ABGR1555 = ll::SDL_PIXELFORMAT_ABGR1555 as int,
    BGRA5551 = ll::SDL_PIXELFORMAT_BGRA5551 as int,
    RGB565 = ll::SDL_PIXELFORMAT_RGB565 as int,
    BGR565 = ll::SDL_PIXELFORMAT_BGR565 as int,
    RGB24 = ll::SDL_PIXELFORMAT_RGB24 as int,
    BGR24 = ll::SDL_PIXELFORMAT_BGR24 as int,
    RGB888 = ll::SDL_PIXELFORMAT_RGB888 as int,
    RGBX8888 = ll::SDL_PIXELFORMAT_RGBX8888 as int,
    BGR888 = ll::SDL_PIXELFORMAT_BGR888 as int,
    BGRX8888 = ll::SDL_PIXELFORMAT_BGRX8888 as int,
    ARGB8888 = ll::SDL_PIXELFORMAT_ARGB8888 as int,
    RGBA8888 = ll::SDL_PIXELFORMAT_RGBA8888 as int,
    ABGR8888 = ll::SDL_PIXELFORMAT_ABGR8888 as int,
    BGRA8888 = ll::SDL_PIXELFORMAT_BGRA8888 as int,
    ARGB2101010 = ll::SDL_PIXELFORMAT_ARGB2101010 as int,
    YV12 = ll::SDL_PIXELFORMAT_YV12 as int,
    IYUV = ll::SDL_PIXELFORMAT_IYUV as int,
    YUY2 = ll::SDL_PIXELFORMAT_YUY2 as int,
    UYVY = ll::SDL_PIXELFORMAT_UYVY as int,
    YVYU = ll::SDL_PIXELFORMAT_YVYU as int
}
<commit_msg>Removed unused result<commit_after>use std::rand;

pub mod ll {
    use std::libc::{c_int, uint8_t, uint32_t};

    //SDL_pixels.h
    pub struct SDL_Color {
        r: uint8_t,
        g: uint8_t,
        b: uint8_t,
        a: uint8_t,
    }

    pub struct SDL_Palette {
        ncolors: c_int,
        colors: *SDL_Color,
        version: uint32_t,
        refcount: c_int
    }

    pub struct SDL_PixelFormat {
        format: SDL_PixelFormatFlag,
        palette: *SDL_Palette,
        BitsPerPixel: uint8_t,
        BytesPerPixel: uint8_t,
        padding: [uint8_t, ..2],
        Rmask: uint8_t,
        Gmask: uint8_t,
        Bmask: uint8_t,
        Amask: uint8_t,
        Rloss: uint8_t,
        Gloss: uint8_t,
        Bloss: uint8_t,
        Aloss: uint8_t,
        Rshift: uint8_t,
        Gshift: uint8_t,
        Bshift: uint8_t,
        Ashift: uint8_t,
        refcount: c_int,
        next: *SDL_PixelFormat
    }

    pub type SDL_PixelFormatFlag = uint32_t;
    pub static SDL_PIXELFORMAT_UNKNOWN: SDL_PixelFormatFlag = 0x0;
    pub static SDL_PIXELFORMAT_INDEX1LSB: SDL_PixelFormatFlag = 0x11100100;
    pub static SDL_PIXELFORMAT_INDEX1MSB: SDL_PixelFormatFlag = 0x11200100;
    pub static SDL_PIXELFORMAT_INDEX4LSB: SDL_PixelFormatFlag = 0x12100400;
    pub static SDL_PIXELFORMAT_INDEX4MSB: SDL_PixelFormatFlag = 0x12200400;
    pub static SDL_PIXELFORMAT_INDEX8: SDL_PixelFormatFlag = 0x13000801;
    pub static SDL_PIXELFORMAT_RGB332: SDL_PixelFormatFlag = 0x14110801;
    pub static SDL_PIXELFORMAT_RGB444: SDL_PixelFormatFlag = 0x15120c02;
    pub static SDL_PIXELFORMAT_RGB555: SDL_PixelFormatFlag = 0x15130f02;
    pub static SDL_PIXELFORMAT_BGR555: SDL_PixelFormatFlag = 0x15530f02;
    pub static SDL_PIXELFORMAT_ARGB4444: SDL_PixelFormatFlag = 0x15321002;
    pub static SDL_PIXELFORMAT_RGBA4444: SDL_PixelFormatFlag = 0x15421002;
    pub static SDL_PIXELFORMAT_ABGR4444: SDL_PixelFormatFlag = 0x15721002;
    pub static SDL_PIXELFORMAT_BGRA4444: SDL_PixelFormatFlag = 0x15821002;
    pub static SDL_PIXELFORMAT_ARGB1555: SDL_PixelFormatFlag = 0x15331002;
    pub static SDL_PIXELFORMAT_RGBA5551: SDL_PixelFormatFlag = 0x15441002;
    pub static SDL_PIXELFORMAT_ABGR1555: SDL_PixelFormatFlag = 0x15731002;
    pub static SDL_PIXELFORMAT_BGRA5551: SDL_PixelFormatFlag = 0x15841002;
    pub static SDL_PIXELFORMAT_RGB565: SDL_PixelFormatFlag = 0x15151002;
    pub static SDL_PIXELFORMAT_BGR565: SDL_PixelFormatFlag = 0x15551002;
    pub static SDL_PIXELFORMAT_RGB24: SDL_PixelFormatFlag = 0x17101803;
    pub static SDL_PIXELFORMAT_BGR24: SDL_PixelFormatFlag = 0x17401803;
    pub static SDL_PIXELFORMAT_RGB888: SDL_PixelFormatFlag = 0x16161804;
    pub static SDL_PIXELFORMAT_RGBX8888: SDL_PixelFormatFlag = 0x16261804;
    pub static SDL_PIXELFORMAT_BGR888: SDL_PixelFormatFlag = 0x16561804;
    pub static SDL_PIXELFORMAT_BGRX8888: SDL_PixelFormatFlag = 0x16661804;
    pub static SDL_PIXELFORMAT_ARGB8888: SDL_PixelFormatFlag = 0x16362004;
    pub static SDL_PIXELFORMAT_RGBA8888: SDL_PixelFormatFlag = 0x16462004;
    pub static SDL_PIXELFORMAT_ABGR8888: SDL_PixelFormatFlag = 0x16762004;
    pub static SDL_PIXELFORMAT_BGRA8888: SDL_PixelFormatFlag = 0x16862004;
    pub static SDL_PIXELFORMAT_ARGB2101010: SDL_PixelFormatFlag = 0x16372004;
    pub static SDL_PIXELFORMAT_YV12: SDL_PixelFormatFlag = 0x32315659;
    pub static SDL_PIXELFORMAT_IYUV: SDL_PixelFormatFlag = 0x56555949;
    pub static SDL_PIXELFORMAT_YUY2: SDL_PixelFormatFlag = 0x32595559;
    pub static SDL_PIXELFORMAT_UYVY: SDL_PixelFormatFlag = 0x59565955;
    pub static SDL_PIXELFORMAT_YVYU: SDL_PixelFormatFlag = 0x55595659;

    extern "C" {
        pub fn SDL_GetRGB(pixel: uint32_t, format: *SDL_PixelFormat, r: *uint8_t, g: *uint8_t, b: *uint8_t);
        pub fn SDL_GetRGBA(pixel: uint32_t, format: *SDL_PixelFormat, r: *uint8_t, g: *uint8_t, b: *uint8_t, a: *uint8_t);
        pub fn SDL_MapRGB(format: *SDL_PixelFormat, r: uint8_t, g: uint8_t, b: uint8_t) -> uint32_t;
        pub fn SDL_MapRGBA(format: *SDL_PixelFormat, r: uint8_t, g: uint8_t, b: uint8_t, a: uint8_t) -> uint32_t;
    }
}
#[deriving(Eq)]
pub struct Palette {
    raw: *ll::SDL_Palette
}

#[deriving(Eq)]
pub enum Color {
    RGB(u8, u8, u8),
    RGBA(u8, u8, u8, u8)
}

impl Color {
    pub fn to_u32(&self, format: &PixelFormat) -> u32 {
        match self {
            &RGB(r, g, b) => {
                unsafe { ll::SDL_MapRGB(format.raw, r, g, b) }
            }
            &RGBA(r, g, b, a) => {
                unsafe { ll::SDL_MapRGBA(format.raw, r, g, b, a) }
            }
        }
    }

    pub fn from_u32(format: &PixelFormat, pixel: u32) -> Color {
        let r: u8 = 0;
        let g: u8 = 0;
        let b: u8 = 0;
        let a: u8 = 0;

        unsafe {
            ll::SDL_GetRGBA(pixel, format.raw, &r, &g, &b, &a)
        };
        RGBA(r, g, b, a)
    }
}

impl rand::Rand for Color {
    fn rand<R: rand::Rng>(rng: &mut R) -> Color {
        if rng.gen() { RGBA(rng.gen(), rng.gen(), rng.gen(), rng.gen()) }
        else { RGB(rng.gen(), rng.gen(), rng.gen()) }
    }
}

#[deriving(Eq)]
pub struct PixelFormat {
    raw: *ll::SDL_PixelFormat
}

#[deriving(Eq, FromPrimitive)]
pub enum PixelFormatFlag {
    Unknown = ll::SDL_PIXELFORMAT_UNKNOWN as int,
    Index1LSB = ll::SDL_PIXELFORMAT_INDEX1LSB as int,
    Index1MSB = ll::SDL_PIXELFORMAT_INDEX1MSB as int,
    Index4LSB = ll::SDL_PIXELFORMAT_INDEX4LSB as int,
    Index4MSB = ll::SDL_PIXELFORMAT_INDEX4MSB as int,
    Index8 = ll::SDL_PIXELFORMAT_INDEX8 as int,
    RGB332 = ll::SDL_PIXELFORMAT_RGB332 as int,
    RGB444 = ll::SDL_PIXELFORMAT_RGB444 as int,
    RGB555 = ll::SDL_PIXELFORMAT_RGB555 as int,
    BGR555 = ll::SDL_PIXELFORMAT_BGR555 as int,
    ARGB4444 = ll::SDL_PIXELFORMAT_ARGB4444 as int,
    RGBA4444 = ll::SDL_PIXELFORMAT_RGBA4444 as int,
    ABGR4444 = ll::SDL_PIXELFORMAT_ABGR4444 as int,
    BGRA4444 = ll::SDL_PIXELFORMAT_BGRA4444 as int,
    ARGB1555 = ll::SDL_PIXELFORMAT_ARGB1555 as int,
    RGBA5551 = ll::SDL_PIXELFORMAT_RGBA5551 as int,
    ABGR1555 = ll::SDL_PIXELFORMAT_ABGR1555 as int,
    BGRA5551 = ll::SDL_PIXELFORMAT_BGRA5551 as int,
    RGB565 = ll::SDL_PIXELFORMAT_RGB565 as int,
    BGR565 = ll::SDL_PIXELFORMAT_BGR565 as int,
    RGB24 = ll::SDL_PIXELFORMAT_RGB24 as int,
    BGR24 = ll::SDL_PIXELFORMAT_BGR24 as int,
    RGB888 = ll::SDL_PIXELFORMAT_RGB888 as int,
    RGBX8888 = ll::SDL_PIXELFORMAT_RGBX8888 as int,
    BGR888 = ll::SDL_PIXELFORMAT_BGR888 as int,
    BGRX8888 = ll::SDL_PIXELFORMAT_BGRX8888 as int,
    ARGB8888 = ll::SDL_PIXELFORMAT_ARGB8888 as int,
    RGBA8888 = ll::SDL_PIXELFORMAT_RGBA8888 as int,
    ABGR8888 = ll::SDL_PIXELFORMAT_ABGR8888 as int,
    BGRA8888 = ll::SDL_PIXELFORMAT_BGRA8888 as int,
    ARGB2101010 = ll::SDL_PIXELFORMAT_ARGB2101010 as int,
    YV12 = ll::SDL_PIXELFORMAT_YV12 as int,
    IYUV = ll::SDL_PIXELFORMAT_IYUV as int,
    YUY2 = ll::SDL_PIXELFORMAT_YUY2 as int,
    UYVY = ll::SDL_PIXELFORMAT_UYVY as int,
    YVYU = ll::SDL_PIXELFORMAT_YVYU as int
}
<|endoftext|>


<commit_before>use url::Url;

use fileid::{HashIdGenerator, IdGenerator};
use storage::{S3Storage, Storage};

pub struct Store<S: Storage, I: IdGenerator> {
    storage: S,
    id_gen: I,
}

pub type StoreImpl = Store<S3Storage, HashIdGenerator>;

impl Store<S3Storage, HashIdGenerator> {
    pub fn new(url: Url) -> Self {
        Store {
            storage: S3Storage::new(url),
            id_gen: HashIdGenerator::new(),
        }
    }
}

impl<S: Storage, I: IdGenerator> Store<S, I> {
    fn save_file(&self, bucket: &String, data: &[u8]) -> String {
        let id = self.id_gen.get_id(data);
        self.storage.store(bucket, &id, data);
        id
    }

    pub fn save_raw_image(&self, data: &[u8]) -> String {
        self.save_file(&"raw".to_string(), data)
    }

    pub fn save_image(&self, data: &[u8]) -> String {
        self.save_file(&"image".to_string(), data)
    }

    pub fn get_raw_image(&self, id: &String) -> Vec<u8> {
        self.storage.get(&"raw".to_string(), id)
    }

    pub fn get_image(&self, id: &String) -> Vec<u8> {
        self.storage.get(&"image".to_string(), id)
    }
}

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

    use super::*;

    use fileid::IdGeneratorStub;
    use storage::DummyStorage;

    fn create_test_store() -> Store<DummyStorage, IdGeneratorStub> {
        Store {
            storage: DummyStorage::new(),
            id_gen: IdGeneratorStub::new(),
        }
    }

    #[test]
    fn test_create() {
        let _story = create_test_store();
    }

    #[test]
    fn test_save_raw_image() {
        let data = b"raw";
        let store = create_test_store();

        let id = store.save_raw_image(data);

        assert_eq!("hash".to_string(), id);
    }

    #[test]
    fn test_save_image() {
        let data = b"raw";
        let store = create_test_store();

        let id = store.save_image(data);

        assert_eq!("hash".to_string(), id);
    }

    #[test]
    fn test_save_get_raw_image() {
        dotenv().unwrap();

        let store = StoreImpl::new("http://127.0.0.1:9100".parse().unwrap());

        let id = store.save_raw_image(b"raw");
        let restore = store.get_raw_image(&id);

        assert_eq!(3, restore.len());
        assert_eq!(b"raw", restore.as_slice());
    }
}
<commit_msg>Comment concurrency-critical integration test<commit_after>use url::Url;

use fileid::{HashIdGenerator, IdGenerator};
use storage::{S3Storage, Storage};

pub struct Store<S: Storage, I: IdGenerator> {
    storage: S,
    id_gen: I,
}

pub type StoreImpl = Store<S3Storage, HashIdGenerator>;

impl Store<S3Storage, HashIdGenerator> {
    pub fn new(url: Url) -> Self {
        Store {
            storage: S3Storage::new(url),
            id_gen: HashIdGenerator::new(),
        }
    }
}

impl<S: Storage, I: IdGenerator> Store<S, I> {
    fn save_file(&self, bucket: &String, data: &[u8]) -> String {
        let id = self.id_gen.get_id(data);
        self.storage.store(bucket, &id, data);
        id
    }

    pub fn save_raw_image(&self, data: &[u8]) -> String {
        self.save_file(&"raw".to_string(), data)
    }

    pub fn save_image(&self, data: &[u8]) -> String {
        self.save_file(&"image".to_string(), data)
    }

    pub fn get_raw_image(&self, id: &String) -> Vec<u8> {
        self.storage.get(&"raw".to_string(), id)
    }

    pub fn get_image(&self, id: &String) -> Vec<u8> {
        self.storage.get(&"image".to_string(), id)
    }
}

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

    use super::*;

    use fileid::IdGeneratorStub;
    use storage::DummyStorage;

    fn create_test_store() -> Store<DummyStorage, IdGeneratorStub> {
        Store {
            storage: DummyStorage::new(),
            id_gen: IdGeneratorStub::new(),
        }
    }

    #[test]
    fn test_create() {
        let _story = create_test_store();
    }

    #[test]
    fn test_save_raw_image() {
        let data = b"raw";
        let store = create_test_store();

        let id = store.save_raw_image(data);

        assert_eq!("hash".to_string(), id);
    }

    #[test]
    fn test_save_image() {
        let data = b"raw";
        let store = create_test_store();

        let id = store.save_image(data);

        assert_eq!("hash".to_string(), id);
    }

    /*
    #[test]
    fn test_save_get_raw_image() {
        dotenv().unwrap();

        let store = StoreImpl::new("http://127.0.0.1:9100".parse().unwrap());

        let id = store.save_raw_image(b"raw");
        let restore = store.get_raw_image(&id);

        assert_eq!(3, restore.len());
        assert_eq!(b"raw", restore.as_slice());
    }
    */
}
<|endoftext|>


<commit_before>// Queries.
use crate::bounding_volume::{BoundingSphere, AABB};
use crate::math::{Isometry, Vector};
use na::{self, RealField, Unit};
use crate::query::{PointQuery, RayCast};
use crate::shape::{CompositeShape, ConvexPolyhedron, DeformableShape, FeatureId, SupportMap};
use std::ops::Deref;
use std::sync::Arc;
use downcast_rs::Downcast;

pub trait ShapeClone<N: RealField> {
    fn clone_box(&self) -> Box<dyn Shape<N>> {
        unimplemented!()
    }
}

impl<N: RealField, T: 'static + Shape<N> + Clone> ShapeClone<N> for T {
    fn clone_box(&self) -> Box<dyn Shape<N>> {
        Box::new(self.clone())
    }
}

/// Trait implemented by all shapes supported by ncollide.
///
/// This allows dynamic inspection of the shape capabilities.
pub trait Shape<N: RealField>: Send + Sync + Downcast + ShapeClone<N> {
    /// The AABB of `self` transformed by `m`.
    #[inline]
    fn aabb(&self, m: &Isometry<N>) -> AABB<N>;

    /// The AABB of `self`.
    #[inline]
    fn local_aabb(&self) -> AABB<N> {
        self.aabb(&Isometry::identity())
    }

    /// The bounding sphere of `self` transformed by `m`.
    #[inline]
    fn bounding_sphere(&self, m: &Isometry<N>) -> BoundingSphere<N> {
        let aabb = self.aabb(m);
        BoundingSphere::new(aabb.center(), aabb.half_extents().norm())
    }

    /// The bounding sphere of `self`.
    #[inline]
    fn local_bounding_sphere(&self) -> BoundingSphere<N> {
        let aabb = self.local_aabb();
        BoundingSphere::new(aabb.center(), aabb.half_extents().norm())
    }

    /// Check if if the feature `_feature` of the `i-th` subshape of `self` transformed by `m` has a tangent
    /// cone that contains `dir` at the point `pt`.
    // NOTE: for the moment, we assume the tangent cone is the same for the whole feature.
    #[inline]
    fn tangent_cone_contains_dir(
        &self,
        _feature: FeatureId,
        _m: &Isometry<N>,
        _deformations: Option<&[N]>,
        _dir: &Unit<Vector<N>>,
    ) -> bool;

    /// Returns the id of the subshape containing the specified feature.
    ///
    /// If several subshape contains the same feature, any one is returned.
    fn subshape_containing_feature(&self, _i: FeatureId) -> usize {
        0
    }

    /// The `RayCast` implementation of `self`.
    #[inline]
    fn as_ray_cast(&self) -> Option<&dyn RayCast<N>> {
        None
    }

    /// The `PointQuery` implementation of `self`.
    #[inline]
    fn as_point_query(&self) -> Option<&dyn PointQuery<N>> {
        None
    }

    /// The convex polyhedron representation of `self` if applicable.
    #[inline]
    fn as_convex_polyhedron(&self) -> Option<&dyn ConvexPolyhedron<N>> {
        None
    }

    /// The support mapping of `self` if applicable.
    #[inline]
    fn as_support_map(&self) -> Option<&dyn SupportMap<N>> {
        None
    }

    /// The composite shape representation of `self` if applicable.
    #[inline]
    fn as_composite_shape(&self) -> Option<&dyn CompositeShape<N>> {
        None
    }

    /// The deformable shape representation of `self` if applicable.
    #[inline]
    fn as_deformable_shape(&self) -> Option<&dyn DeformableShape<N>> {
        None
    }

    /// The mutable deformable shape representation of `self` if applicable.
    #[inline]
    fn as_deformable_shape_mut(&mut self) -> Option<&mut dyn DeformableShape<N>> {
        None
    }

    /// Whether `self` uses a convex polyhedron representation.
    #[inline]
    fn is_convex_polyhedron(&self) -> bool {
        self.as_convex_polyhedron().is_some()
    }

    /// Whether `self` uses a support-mapping based representation.
    #[inline]
    fn is_support_map(&self) -> bool {
        self.as_support_map().is_some()
    }

    /// Whether `self` uses a composite shape-based representation.
    #[inline]
    fn is_composite_shape(&self) -> bool {
        self.as_composite_shape().is_some()
    }

    /// Whether `self` uses a composite shape-based representation.
    #[inline]
    fn is_deformable_shape(&self) -> bool {
        self.as_deformable_shape().is_some()
    }
}

impl_downcast!(Shape<N> where N: RealField);

/// Trait for casting shapes to its exact represetation.
impl<N: RealField> dyn Shape<N> {
    /// Tests if this shape has a specific type `T`.
    #[inline]
    pub fn is_shape<T: Shape<N>>(&self) -> bool {
        self.is::<T>()
    }

    /// Performs the cast.
    #[inline]
    pub fn as_shape<T: Shape<N>>(&self) -> Option<&T> {
        self.downcast_ref()
    }
}

impl<N: RealField> Clone for Box<dyn Shape<N>> {
    fn clone(&self) -> Box<dyn Shape<N>> {
        self.clone_box()
    }
}

/// A shared handle to an abstract shape.
///
/// This can be mutated using COW.
#[derive(Clone)]
pub struct ShapeHandle<N: RealField>(Arc<Box<dyn Shape<N>>>);

impl<N: RealField> ShapeHandle<N> {
    /// Creates a sharable shape handle from a shape.
    #[inline]
    pub fn new<S: Shape<N>>(shape: S) -> ShapeHandle<N> {
        ShapeHandle(Arc::new(Box::new(shape)))
    }

    /// Creates a sharable shape handle from a shape trait object.
    pub fn from_box(shape: Box<dyn Shape<N>>) -> ShapeHandle<N> {
        ShapeHandle(Arc::new(shape))
    }

    pub(crate) fn make_mut(&mut self) -> &mut dyn Shape<N> {
        &mut **Arc::make_mut(&mut self.0)
    }
}

impl<N: RealField> AsRef<dyn Shape<N>> for ShapeHandle<N> {
    #[inline]
    fn as_ref(&self) -> &dyn Shape<N> {
        &*self.deref()
    }
}

impl<N: RealField> Deref for ShapeHandle<N> {
    type Target = dyn Shape<N>;

    #[inline]
    fn deref(&self) -> &dyn Shape<N> {
        &**self.0.deref()
    }
}<commit_msg>Remove gratuitous indirection from ShapeHandle<commit_after>// Queries.
use crate::bounding_volume::{BoundingSphere, AABB};
use crate::math::{Isometry, Vector};
use na::{self, RealField, Unit};
use crate::query::{PointQuery, RayCast};
use crate::shape::{CompositeShape, ConvexPolyhedron, DeformableShape, FeatureId, SupportMap};
use std::ops::Deref;
use std::sync::Arc;
use downcast_rs::Downcast;

pub trait ShapeClone<N: RealField> {
    /// Construct an `Arc` that refers to a uniquely-owned copy of `self`
    fn clone_arc(&self) -> Arc<dyn Shape<N>>;
}

impl<N: RealField, T: 'static + Shape<N> + Clone> ShapeClone<N> for T {
    fn clone_arc(&self) -> Arc<dyn Shape<N>> {
        Arc::new(self.clone())
    }
}

/// Trait implemented by all shapes supported by ncollide.
///
/// This allows dynamic inspection of the shape capabilities.
pub trait Shape<N: RealField>: Send + Sync + Downcast + ShapeClone<N> {
    /// The AABB of `self` transformed by `m`.
    #[inline]
    fn aabb(&self, m: &Isometry<N>) -> AABB<N>;

    /// The AABB of `self`.
    #[inline]
    fn local_aabb(&self) -> AABB<N> {
        self.aabb(&Isometry::identity())
    }

    /// The bounding sphere of `self` transformed by `m`.
    #[inline]
    fn bounding_sphere(&self, m: &Isometry<N>) -> BoundingSphere<N> {
        let aabb = self.aabb(m);
        BoundingSphere::new(aabb.center(), aabb.half_extents().norm())
    }

    /// The bounding sphere of `self`.
    #[inline]
    fn local_bounding_sphere(&self) -> BoundingSphere<N> {
        let aabb = self.local_aabb();
        BoundingSphere::new(aabb.center(), aabb.half_extents().norm())
    }

    /// Check if if the feature `_feature` of the `i-th` subshape of `self` transformed by `m` has a tangent
    /// cone that contains `dir` at the point `pt`.
    // NOTE: for the moment, we assume the tangent cone is the same for the whole feature.
    #[inline]
    fn tangent_cone_contains_dir(
        &self,
        _feature: FeatureId,
        _m: &Isometry<N>,
        _deformations: Option<&[N]>,
        _dir: &Unit<Vector<N>>,
    ) -> bool;

    /// Returns the id of the subshape containing the specified feature.
    ///
    /// If several subshape contains the same feature, any one is returned.
    fn subshape_containing_feature(&self, _i: FeatureId) -> usize {
        0
    }

    /// The `RayCast` implementation of `self`.
    #[inline]
    fn as_ray_cast(&self) -> Option<&dyn RayCast<N>> {
        None
    }

    /// The `PointQuery` implementation of `self`.
    #[inline]
    fn as_point_query(&self) -> Option<&dyn PointQuery<N>> {
        None
    }

    /// The convex polyhedron representation of `self` if applicable.
    #[inline]
    fn as_convex_polyhedron(&self) -> Option<&dyn ConvexPolyhedron<N>> {
        None
    }

    /// The support mapping of `self` if applicable.
    #[inline]
    fn as_support_map(&self) -> Option<&dyn SupportMap<N>> {
        None
    }

    /// The composite shape representation of `self` if applicable.
    #[inline]
    fn as_composite_shape(&self) -> Option<&dyn CompositeShape<N>> {
        None
    }

    /// The deformable shape representation of `self` if applicable.
    #[inline]
    fn as_deformable_shape(&self) -> Option<&dyn DeformableShape<N>> {
        None
    }

    /// The mutable deformable shape representation of `self` if applicable.
    #[inline]
    fn as_deformable_shape_mut(&mut self) -> Option<&mut dyn DeformableShape<N>> {
        None
    }

    /// Whether `self` uses a convex polyhedron representation.
    #[inline]
    fn is_convex_polyhedron(&self) -> bool {
        self.as_convex_polyhedron().is_some()
    }

    /// Whether `self` uses a support-mapping based representation.
    #[inline]
    fn is_support_map(&self) -> bool {
        self.as_support_map().is_some()
    }

    /// Whether `self` uses a composite shape-based representation.
    #[inline]
    fn is_composite_shape(&self) -> bool {
        self.as_composite_shape().is_some()
    }

    /// Whether `self` uses a composite shape-based representation.
    #[inline]
    fn is_deformable_shape(&self) -> bool {
        self.as_deformable_shape().is_some()
    }
}

impl_downcast!(Shape<N> where N: RealField);

/// Trait for casting shapes to its exact represetation.
impl<N: RealField> dyn Shape<N> {
    /// Tests if this shape has a specific type `T`.
    #[inline]
    pub fn is_shape<T: Shape<N>>(&self) -> bool {
        self.is::<T>()
    }

    /// Performs the cast.
    #[inline]
    pub fn as_shape<T: Shape<N>>(&self) -> Option<&T> {
        self.downcast_ref()
    }
}

/// A shared handle to an abstract shape.
///
/// This can be mutated using COW.
#[derive(Clone)]
pub struct ShapeHandle<N: RealField>(Arc<dyn Shape<N>>);

impl<N: RealField> ShapeHandle<N> {
    /// Creates a sharable shape handle from a shape.
    #[inline]
    pub fn new<S: Shape<N>>(shape: S) -> ShapeHandle<N> {
        ShapeHandle(Arc::new(shape))
    }

    /// Creates a sharable shape handle from a shape trait object.
    pub fn from_arc(shape: Arc<dyn Shape<N>>) -> ShapeHandle<N> {
        ShapeHandle(shape)
    }

    pub(crate) fn make_mut(&mut self) -> &mut dyn Shape<N> {
        if Arc::get_mut(&mut self.0).is_none() {
            let unique_self = self.0.clone_arc();
            self.0 = unique_self;
        }
        Arc::get_mut(&mut self.0).unwrap()
    }
}

impl<N: RealField> AsRef<dyn Shape<N>> for ShapeHandle<N> {
    #[inline]
    fn as_ref(&self) -> &dyn Shape<N> {
        &*self.0
    }
}

impl<N: RealField> Deref for ShapeHandle<N> {
    type Target = dyn Shape<N>;

    #[inline]
    fn deref(&self) -> &dyn Shape<N> {
        &*self.0
    }
}
<|endoftext|>


<commit_before>/**
 * Trait of objects having a L² norm and which can be normalized.
 */
pub trait Norm<T>
{
  /// Computes the norm a an object.
  fn norm(&self)       -> T;

  /**
   * Computes the squared norm of an object.
   *
   * Computes the squared norm of an object. Computation of the squared norm
   * is usually faster than the norm itself.
   */
  fn sqnorm(&self)     -> T;

  /// Gets the normalized version of the argument.
  fn normalized(&self) -> Self;

  /// In-place version of `normalized`.
  fn normalize(&mut self)  -> T;
}
<commit_msg>Fix comment.<commit_after>/**
 * Trait of objects having a L² norm and which can be normalized.
 */
pub trait Norm<T>
{
  /// Computes the norm a an object.
  fn norm(&self)       -> T;

  /**
   * Computes the squared norm of an object. Usually faster than computing the
   * norm itself.
   */
  fn sqnorm(&self)     -> T;

  /// Gets the normalized version of the argument.
  fn normalized(&self) -> Self;

  /// In-place version of `normalized`.
  fn normalize(&mut self)  -> T;
}
<|endoftext|>


<commit_before>//! Transactions

use std::cell::Cell;
use std::fmt;
use std::ascii::AsciiExt;

use {bad_response, Result, Connection, TransactionInternals, ConfigInternals,
     IsolationLevelNew};
use error::Error;
use rows::Rows;
use stmt::Statement;
use types::ToSql;

/// An enumeration of transaction isolation levels.
///
/// See the [Postgres documentation](http://www.postgresql.org/docs/9.4/static/transaction-iso.html)
/// for full details on the semantics of each level.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IsolationLevel {
    /// The "read uncommitted" level.
    ///
    /// In current versions of Postgres, this behaves identically to
    /// `ReadCommitted`.
    ReadUncommitted,
    /// The "read committed" level.
    ///
    /// This is the default isolation level in Postgres.
    ReadCommitted,
    /// The "repeatable read" level.
    RepeatableRead,
    /// The "serializable" level.
    Serializable,
}

impl IsolationLevelNew for IsolationLevel {
    fn new(raw: &str) -> Result<IsolationLevel> {
        if raw.eq_ignore_ascii_case("READ UNCOMMITTED") {
            Ok(IsolationLevel::ReadUncommitted)
        } else if raw.eq_ignore_ascii_case("READ COMMITTED") {
            Ok(IsolationLevel::ReadCommitted)
        } else if raw.eq_ignore_ascii_case("REPEATABLE READ") {
            Ok(IsolationLevel::RepeatableRead)
        } else if raw.eq_ignore_ascii_case("SERIALIZABLE") {
            Ok(IsolationLevel::Serializable)
        } else {
            Err(Error::Io(bad_response()))
        }
    }
}

impl IsolationLevel {
    fn to_sql(&self) -> &'static str {
        match *self {
            IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
            IsolationLevel::ReadCommitted => "READ COMMITTED",
            IsolationLevel::RepeatableRead => "REPEATABLE READ",
            IsolationLevel::Serializable => "SERIALIZABLE",
        }
    }
}

/// Configuration of a transaction.
#[derive(Debug)]
pub struct Config {
    isolation_level: Option<IsolationLevel>,
    read_only: Option<bool>,
    deferrable: Option<bool>,
}

impl Default for Config {
    fn default() -> Config {
        Config {
            isolation_level: None,
            read_only: None,
            deferrable: None,
        }
    }
}

impl ConfigInternals for Config {
    fn build_command(&self, s: &mut String) {
        let mut first = true;

        if let Some(isolation_level) = self.isolation_level {
            s.push_str(" ISOLATION LEVEL ");
            s.push_str(isolation_level.to_sql());
            first = false;
        }

        if let Some(read_only) = self.read_only {
            if first {
                s.push(',');
            }
            if read_only {
                s.push_str(" READ ONLY");
            } else {
                s.push_str(" READ WRITE");
            }
            first = false;
        }

        if let Some(deferrable) = self.deferrable {
            if first {
                s.push(',');
            }
            if deferrable {
                s.push_str(" DEFERRABLE");
            } else {
                s.push_str(" NOT DEFERRABLE");
            }
        }
    }
}

impl Config {
    /// Creates a new `Config` with no configuration overrides.
    pub fn new() -> Config {
        Config::default()
    }

    /// Sets the isolation level of the configuration.
    pub fn isolation_level(&mut self, isolation_level: IsolationLevel) -> &mut Config {
        self.isolation_level = Some(isolation_level);
        self
    }

    /// Sets the read-only property of a transaction.
    ///
    /// If enabled, a transaction will be unable to modify any persistent
    /// database state.
    pub fn read_only(&mut self, read_only: bool) -> &mut Config {
        self.read_only = Some(read_only);
        self
    }

    /// Sets the deferrable property of a transaction.
    ///
    /// If enabled in a read only, serializable transaction, the transaction may
    /// block when created, after which it will run without the normal overhead
    /// of a serializable transaction and will not be forced to roll back due
    /// to serialization failures.
    pub fn deferrable(&mut self, deferrable: bool) -> &mut Config {
        self.deferrable = Some(deferrable);
        self
    }
}

/// A transaction on a database connection.
///
/// The transaction will roll back by default.
pub struct Transaction<'conn> {
    conn: &'conn Connection,
    depth: u32,
    savepoint_name: Option<String>,
    commit: Cell<bool>,
    finished: bool,
}

impl<'a> fmt::Debug for Transaction<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Transaction")
           .field("commit", &self.commit.get())
           .field("depth", &self.depth)
           .finish()
    }
}

impl<'conn> Drop for Transaction<'conn> {
    fn drop(&mut self) {
        if !self.finished {
            let _ = self.finish_inner();
        }
    }
}

impl<'conn> TransactionInternals<'conn> for Transaction<'conn> {
    fn new(conn: &'conn Connection, depth: u32) -> Transaction<'conn> {
        Transaction {
            conn: conn,
            depth: depth,
            savepoint_name: None,
            commit: Cell::new(false),
            finished: false,
        }
    }

    fn conn(&self) -> &'conn Connection {
        self.conn
    }

    fn depth(&self) -> u32 {
        self.depth
    }
}

impl<'conn> Transaction<'conn> {
    fn finish_inner(&mut self) -> Result<()> {
        let mut conn = self.conn.conn.borrow_mut();
        debug_assert!(self.depth == conn.trans_depth);
        conn.trans_depth -= 1;
        match (self.commit.get(), &self.savepoint_name) {
            (false, &Some(ref savepoint_name)) => conn.quick_query(&format!("ROLLBACK TO {}", savepoint_name)),
            (false, &None) => conn.quick_query("ROLLBACK"),
            (true, &Some(ref savepoint_name)) => conn.quick_query(&format!("RELEASE {}", savepoint_name)),
            (true, &None) => conn.quick_query("COMMIT"),
        }.map(|_| ())
    }

    /// Like `Connection::prepare`.
    pub fn prepare(&self, query: &str) -> Result<Statement<'conn>> {
        self.conn.prepare(query)
    }

    /// Like `Connection::prepare_cached`.
    ///
    /// Note that the statement will be cached for the duration of the
    /// connection, not just the duration of this transaction.
    pub fn prepare_cached(&self, query: &str) -> Result<Statement<'conn>> {
        self.conn.prepare_cached(query)
    }

    /// Like `Connection::execute`.
    pub fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64> {
        self.conn.execute(query, params)
    }

    /// Like `Connection::query`.
    pub fn query<'a>(&'a self, query: &str, params: &[&ToSql]) -> Result<Rows<'a>> {
        self.conn.query(query, params)
    }

    /// Like `Connection::batch_execute`.
    pub fn batch_execute(&self, query: &str) -> Result<()> {
        self.conn.batch_execute(query)
    }

    /// Like `Connection::transaction`, but creates a nested transaction.
    ///
    /// # Panics
    ///
    /// Panics if there is an active nested transaction.
    pub fn transaction<'a>(&'a self) -> Result<Transaction<'a>> {
        self.savepoint("sp")
    }

    /// Like `Connection::transaction`, but creates a nested transaction
    /// with the provided name.
    ///
    /// # Panics
    ///
    /// Panics if there is an active nested transaction.
    pub fn savepoint<'a>(&'a self, name: &str) -> Result<Transaction<'a>> {
        let mut conn = self.conn.conn.borrow_mut();
        check_desync!(conn);
        assert!(conn.trans_depth == self.depth,
                "`savepoint` may only be called on the active transaction");
        try!(conn.quick_query(&format!("SAVEPOINT {}", name)));
        conn.trans_depth += 1;
        Ok(Transaction {
            conn: self.conn,
            depth: self.depth + 1,
            savepoint_name: Some(name.to_owned()),
            commit: Cell::new(false),
            finished: false,
        })
    }

    /// Returns a reference to the `Transaction`'s `Connection`.
    pub fn connection(&self) -> &'conn Connection {
        self.conn
    }

    /// Like `Connection::is_active`.
    pub fn is_active(&self) -> bool {
        self.conn.conn.borrow().trans_depth == self.depth
    }

    /// Alters the configuration of the active transaction.
    pub fn set_config(&self, config: &Config) -> Result<()> {
        let mut command = "SET TRANSACTION".to_owned();
        config.build_command(&mut command);
        self.batch_execute(&command)
    }

    /// Determines if the transaction is currently set to commit or roll back.
    pub fn will_commit(&self) -> bool {
        self.commit.get()
    }

    /// Sets the transaction to commit at its completion.
    pub fn set_commit(&self) {
        self.commit.set(true);
    }

    /// Sets the transaction to roll back at its completion.
    pub fn set_rollback(&self) {
        self.commit.set(false);
    }

    /// A convenience method which consumes and commits a transaction.
    pub fn commit(self) -> Result<()> {
        self.set_commit();
        self.finish()
    }

    /// Consumes the transaction, commiting or rolling it back as appropriate.
    ///
    /// Functionally equivalent to the `Drop` implementation of `Transaction`
    /// except that it returns any error to the caller.
    pub fn finish(mut self) -> Result<()> {
        self.finished = true;
        self.finish_inner()
    }
}
<commit_msg>Cleanup<commit_after>//! Transactions

use std::cell::Cell;
use std::fmt;
use std::ascii::AsciiExt;

use {bad_response, Result, Connection, TransactionInternals, ConfigInternals,
     IsolationLevelNew};
use error::Error;
use rows::Rows;
use stmt::Statement;
use types::ToSql;

/// An enumeration of transaction isolation levels.
///
/// See the [Postgres documentation](http://www.postgresql.org/docs/9.4/static/transaction-iso.html)
/// for full details on the semantics of each level.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IsolationLevel {
    /// The "read uncommitted" level.
    ///
    /// In current versions of Postgres, this behaves identically to
    /// `ReadCommitted`.
    ReadUncommitted,
    /// The "read committed" level.
    ///
    /// This is the default isolation level in Postgres.
    ReadCommitted,
    /// The "repeatable read" level.
    RepeatableRead,
    /// The "serializable" level.
    Serializable,
}

impl IsolationLevelNew for IsolationLevel {
    fn new(raw: &str) -> Result<IsolationLevel> {
        if raw.eq_ignore_ascii_case("READ UNCOMMITTED") {
            Ok(IsolationLevel::ReadUncommitted)
        } else if raw.eq_ignore_ascii_case("READ COMMITTED") {
            Ok(IsolationLevel::ReadCommitted)
        } else if raw.eq_ignore_ascii_case("REPEATABLE READ") {
            Ok(IsolationLevel::RepeatableRead)
        } else if raw.eq_ignore_ascii_case("SERIALIZABLE") {
            Ok(IsolationLevel::Serializable)
        } else {
            Err(Error::Io(bad_response()))
        }
    }
}

impl IsolationLevel {
    fn to_sql(&self) -> &'static str {
        match *self {
            IsolationLevel::ReadUncommitted => "READ UNCOMMITTED",
            IsolationLevel::ReadCommitted => "READ COMMITTED",
            IsolationLevel::RepeatableRead => "REPEATABLE READ",
            IsolationLevel::Serializable => "SERIALIZABLE",
        }
    }
}

/// Configuration of a transaction.
#[derive(Debug)]
pub struct Config {
    isolation_level: Option<IsolationLevel>,
    read_only: Option<bool>,
    deferrable: Option<bool>,
}

impl Default for Config {
    fn default() -> Config {
        Config {
            isolation_level: None,
            read_only: None,
            deferrable: None,
        }
    }
}

impl ConfigInternals for Config {
    fn build_command(&self, s: &mut String) {
        let mut first = true;

        if let Some(isolation_level) = self.isolation_level {
            s.push_str(" ISOLATION LEVEL ");
            s.push_str(isolation_level.to_sql());
            first = false;
        }

        if let Some(read_only) = self.read_only {
            if first {
                s.push(',');
            }
            if read_only {
                s.push_str(" READ ONLY");
            } else {
                s.push_str(" READ WRITE");
            }
            first = false;
        }

        if let Some(deferrable) = self.deferrable {
            if first {
                s.push(',');
            }
            if deferrable {
                s.push_str(" DEFERRABLE");
            } else {
                s.push_str(" NOT DEFERRABLE");
            }
        }
    }
}

impl Config {
    /// Creates a new `Config` with no configuration overrides.
    pub fn new() -> Config {
        Config::default()
    }

    /// Sets the isolation level of the configuration.
    pub fn isolation_level(&mut self, isolation_level: IsolationLevel) -> &mut Config {
        self.isolation_level = Some(isolation_level);
        self
    }

    /// Sets the read-only property of a transaction.
    ///
    /// If enabled, a transaction will be unable to modify any persistent
    /// database state.
    pub fn read_only(&mut self, read_only: bool) -> &mut Config {
        self.read_only = Some(read_only);
        self
    }

    /// Sets the deferrable property of a transaction.
    ///
    /// If enabled in a read only, serializable transaction, the transaction may
    /// block when created, after which it will run without the normal overhead
    /// of a serializable transaction and will not be forced to roll back due
    /// to serialization failures.
    pub fn deferrable(&mut self, deferrable: bool) -> &mut Config {
        self.deferrable = Some(deferrable);
        self
    }
}

/// A transaction on a database connection.
///
/// The transaction will roll back by default.
pub struct Transaction<'conn> {
    conn: &'conn Connection,
    depth: u32,
    savepoint_name: Option<String>,
    commit: Cell<bool>,
    finished: bool,
}

impl<'a> fmt::Debug for Transaction<'a> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("Transaction")
           .field("commit", &self.commit.get())
           .field("depth", &self.depth)
           .finish()
    }
}

impl<'conn> Drop for Transaction<'conn> {
    fn drop(&mut self) {
        if !self.finished {
            let _ = self.finish_inner();
        }
    }
}

impl<'conn> TransactionInternals<'conn> for Transaction<'conn> {
    fn new(conn: &'conn Connection, depth: u32) -> Transaction<'conn> {
        Transaction {
            conn: conn,
            depth: depth,
            savepoint_name: None,
            commit: Cell::new(false),
            finished: false,
        }
    }

    fn conn(&self) -> &'conn Connection {
        self.conn
    }

    fn depth(&self) -> u32 {
        self.depth
    }
}

impl<'conn> Transaction<'conn> {
    fn finish_inner(&mut self) -> Result<()> {
        let mut conn = self.conn.conn.borrow_mut();
        debug_assert!(self.depth == conn.trans_depth);
        conn.trans_depth -= 1;
        match (self.commit.get(), &self.savepoint_name) {
            (false, &Some(ref savepoint_name)) => {
                conn.quick_query(&format!("ROLLBACK TO {}", savepoint_name))
            }
            (false, &None) => conn.quick_query("ROLLBACK"),
            (true, &Some(ref savepoint_name)) => {
                conn.quick_query(&format!("RELEASE {}", savepoint_name))
            }
            (true, &None) => conn.quick_query("COMMIT"),
        }.map(|_| ())
    }

    /// Like `Connection::prepare`.
    pub fn prepare(&self, query: &str) -> Result<Statement<'conn>> {
        self.conn.prepare(query)
    }

    /// Like `Connection::prepare_cached`.
    ///
    /// Note that the statement will be cached for the duration of the
    /// connection, not just the duration of this transaction.
    pub fn prepare_cached(&self, query: &str) -> Result<Statement<'conn>> {
        self.conn.prepare_cached(query)
    }

    /// Like `Connection::execute`.
    pub fn execute(&self, query: &str, params: &[&ToSql]) -> Result<u64> {
        self.conn.execute(query, params)
    }

    /// Like `Connection::query`.
    pub fn query<'a>(&'a self, query: &str, params: &[&ToSql]) -> Result<Rows<'a>> {
        self.conn.query(query, params)
    }

    /// Like `Connection::batch_execute`.
    pub fn batch_execute(&self, query: &str) -> Result<()> {
        self.conn.batch_execute(query)
    }

    /// Like `Connection::transaction`, but creates a nested transaction via
    /// a savepoint.
    ///
    /// # Panics
    ///
    /// Panics if there is an active nested transaction.
    pub fn transaction<'a>(&'a self) -> Result<Transaction<'a>> {
        self.savepoint("sp")
    }

    /// Like `Connection::transaction`, but creates a nested transaction via
    /// a savepoint with the specified name.
    ///
    /// # Panics
    ///
    /// Panics if there is an active nested transaction.
    pub fn savepoint<'a>(&'a self, name: &str) -> Result<Transaction<'a>> {
        let mut conn = self.conn.conn.borrow_mut();
        check_desync!(conn);
        assert!(conn.trans_depth == self.depth,
                "`savepoint` may only be called on the active transaction");
        try!(conn.quick_query(&format!("SAVEPOINT {}", name)));
        conn.trans_depth += 1;
        Ok(Transaction {
            conn: self.conn,
            depth: self.depth + 1,
            savepoint_name: Some(name.to_owned()),
            commit: Cell::new(false),
            finished: false,
        })
    }

    /// Returns a reference to the `Transaction`'s `Connection`.
    pub fn connection(&self) -> &'conn Connection {
        self.conn
    }

    /// Like `Connection::is_active`.
    pub fn is_active(&self) -> bool {
        self.conn.conn.borrow().trans_depth == self.depth
    }

    /// Alters the configuration of the active transaction.
    pub fn set_config(&self, config: &Config) -> Result<()> {
        let mut command = "SET TRANSACTION".to_owned();
        config.build_command(&mut command);
        self.batch_execute(&command)
    }

    /// Determines if the transaction is currently set to commit or roll back.
    pub fn will_commit(&self) -> bool {
        self.commit.get()
    }

    /// Sets the transaction to commit at its completion.
    pub fn set_commit(&self) {
        self.commit.set(true);
    }

    /// Sets the transaction to roll back at its completion.
    pub fn set_rollback(&self) {
        self.commit.set(false);
    }

    /// A convenience method which consumes and commits a transaction.
    pub fn commit(self) -> Result<()> {
        self.set_commit();
        self.finish()
    }

    /// Consumes the transaction, commiting or rolling it back as appropriate.
    ///
    /// Functionally equivalent to the `Drop` implementation of `Transaction`
    /// except that it returns any error to the caller.
    pub fn finish(mut self) -> Result<()> {
        self.finished = true;
        self.finish_inner()
    }
}
<|endoftext|>


<commit_before>use std::io::prelude::*;
use std::io;
use openssl::hash::{Hasher, MessageDigest};

pub struct HashingReader<R> {
    inner: R,
    hasher: Hasher,
}

impl<R: Read> HashingReader<R> {
    pub fn new(r: R) -> HashingReader<R> {
        HashingReader {
            inner: r,
            hasher: Hasher::new(MessageDigest::sha256()).unwrap(),
        }
    }

    pub fn finalize(mut self) -> Vec<u8> {
        /*
            rustfmt wanted to merge the lines together so had to use this
            to stop this from occurring
        */
        #[rustfmt_skip]
        #[allow(deprecated)]
        self.hasher.finish().unwrap()
    }
}

impl<R: Read> Read for HashingReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let amt = self.inner.read(buf)?;
        self.hasher.update(&buf[..amt]).unwrap();
        Ok(amt)
    }
}
<commit_msg>Changed rustfmt_skip declaration<commit_after>use std::io::prelude::*;
use std::io;
use openssl::hash::{Hasher, MessageDigest};

pub struct HashingReader<R> {
    inner: R,
    hasher: Hasher,
}

impl<R: Read> HashingReader<R> {
    pub fn new(r: R) -> HashingReader<R> {
        HashingReader {
            inner: r,
            hasher: Hasher::new(MessageDigest::sha256()).unwrap(),
        }
    }

    pub fn finalize(mut self) -> Vec<u8> {
        /*
            rustfmt wanted to merge the lines together so had to use this
            to stop this from occurring
        */
        #[cfg_attr(rustfmt, rustfmt_skip)]
        #[allow(deprecated)]
        self.hasher.finish().unwrap()
    }
}

impl<R: Read> Read for HashingReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let amt = self.inner.read(buf)?;
        self.hasher.update(&buf[..amt]).unwrap();
        Ok(amt)
    }
}
<|endoftext|>