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

use std::num::Zero;
use sync::{Arc, RWLock};
use gl::types::*;
use nalgebra::na::{Vec2, Vec3};
use nalgebra::na;
use resource::ShaderAttribute;
use resource::gpu_vector::{GPUVector, DynamicDraw, StaticDraw, ArrayBuffer, ElementArrayBuffer};
use ncollide::procedural::TriMesh;

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

/// Aggregation of vertices, indices, normals and texture coordinates.
///
/// It also contains the GPU location of those buffers.
pub struct Mesh {
    coords:  Arc<RWLock<GPUVector<Vec3<GLfloat>>>>,
    faces:   Arc<RWLock<GPUVector<Vec3<GLuint>>>>,
    normals: Arc<RWLock<GPUVector<Vec3<GLfloat>>>>,
    uvs:     Arc<RWLock<GPUVector<Vec2<GLfloat>>>>
}

impl Mesh {
    /// Creates a new mesh.
    ///
    /// If the normals and uvs are not given, they are automatically computed.
    pub fn new(coords:       Vec<Vec3<GLfloat>>,
               faces:        Vec<Vec3<GLuint>>,
               normals:      Option<Vec<Vec3<GLfloat>>>,
               uvs:          Option<Vec<Vec2<GLfloat>>>,
               dynamic_draw: bool)
               -> Mesh {
        let normals = match normals {
            Some(ns) => ns,
            None     => Mesh::compute_normals_array(coords.as_slice(), faces.as_slice())
        };

        let uvs = match uvs {
            Some(us) => us,
            None     => Vec::from_elem(coords.len(), na::zero())
        };

        let location = if dynamic_draw { DynamicDraw } else { StaticDraw };
        let cs = Arc::new(RWLock::new(GPUVector::new(coords, ArrayBuffer, location)));
        let fs = Arc::new(RWLock::new(GPUVector::new(faces, ElementArrayBuffer, location)));
        let ns = Arc::new(RWLock::new(GPUVector::new(normals, ArrayBuffer, location)));
        let us = Arc::new(RWLock::new(GPUVector::new(uvs, ArrayBuffer, location)));

        Mesh::new_with_gpu_vectors(cs, fs, ns, us)
    }

    /// Creates a new mesh from a mesh descr.
    ///
    /// In the normals and uvs are not given, they are automatically computed.
    pub fn from_trimesh(mesh: TriMesh<GLfloat, Vec3<GLfloat>>, dynamic_draw: bool) -> Mesh {
        let mut mesh = mesh;

        mesh.unify_index_buffer();

        let TriMesh { coords, normals, uvs, indices } = mesh;

        Mesh::new(coords, indices.unwrap_unified(), normals, uvs, dynamic_draw)
    }

    /// Creates a new mesh. Arguments set to `None` are automatically computed.
    pub fn new_with_gpu_vectors(coords:  Arc<RWLock<GPUVector<Vec3<GLfloat>>>>,
                                faces:   Arc<RWLock<GPUVector<Vec3<GLuint>>>>,
                                normals: Arc<RWLock<GPUVector<Vec3<GLfloat>>>>,
                                uvs:     Arc<RWLock<GPUVector<Vec2<GLfloat>>>>)
                                -> Mesh {
        Mesh {
            coords:  coords,
            faces:   faces,
            normals: normals,
            uvs:     uvs
        }
    }

    /// Binds this mesh vertex coordinates buffer to a vertex attribute.
    pub fn bind_coords(&mut self, coords: &mut ShaderAttribute<Vec3<GLfloat>>) {
        coords.bind(self.coords.write().deref_mut());
    }

    /// Binds this mesh vertex normals buffer to a vertex attribute.
    pub fn bind_normals(&mut self, normals: &mut ShaderAttribute<Vec3<GLfloat>>) {
        normals.bind(self.normals.write().deref_mut());
    }

    /// Binds this mesh vertex uvs buffer to a vertex attribute.
    pub fn bind_uvs(&mut self, uvs: &mut ShaderAttribute<Vec2<GLfloat>>) {
        uvs.bind(self.uvs.write().deref_mut());
    }

    /// Binds this mesh vertex uvs buffer to a vertex attribute.
    pub fn bind_faces(&mut self) {
        self.faces.write().bind();
    }

    /// Binds this mesh buffers to vertex attributes.
    pub fn bind(&mut self,
                coords:  &mut ShaderAttribute<Vec3<GLfloat>>,
                normals: &mut ShaderAttribute<Vec3<GLfloat>>,
                uvs:     &mut ShaderAttribute<Vec2<GLfloat>>) {
        self.bind_coords(coords);
        self.bind_normals(normals);
        self.bind_uvs(uvs);
        self.bind_faces();
    }

    /// Unbind this mesh buffers to vertex attributes.
    pub fn unbind(&self) {
        self.coords.write().unbind();
        self.normals.write().unbind();
        self.uvs.write().unbind();
        self.faces.write().unbind();
    }

    /// Number of points needed to draw this mesh.
    pub fn num_pts(&self) -> uint {
        self.faces.read().len() * 3
    }

    /// Recompute this mesh normals.
    pub fn recompute_normals(&mut self) {
        Mesh::compute_normals(self.coords.read().data().get_ref().as_slice(),
                              self.faces.read().data().get_ref().as_slice(),
                              self.normals.write().data_mut().get_mut_ref());
    }

    /// This mesh faces.
    pub fn faces<'a>(&'a self) -> &'a Arc<RWLock<GPUVector<Vec3<GLuint>>>> {
        &self.faces
    }

    /// This mesh normals.
    pub fn normals<'a>(&'a self) -> &'a Arc<RWLock<GPUVector<Vec3<GLfloat>>>> {
        &self.normals
    }

    /// This mesh vertex coordinates.
    pub fn coords<'a>(&'a self) -> &'a Arc<RWLock<GPUVector<Vec3<GLfloat>>>> {
        &self.coords
    }

    /// This mesh texture coordinates.
    pub fn uvs<'a>(&'a self) -> &'a Arc<RWLock<GPUVector<Vec2<GLfloat>>>> {
        &self.uvs
    }

    /// Computes normals from a set of faces.
    pub fn compute_normals_array(coordinates: &[Vec3<GLfloat>], faces: &[Vec3<GLuint>]) -> Vec<Vec3<GLfloat>> {
        let mut res = Vec::new();

        Mesh::compute_normals(coordinates, faces, &mut res);

        res
    }

    /// Computes normals from a set of faces.
    pub fn compute_normals(coordinates: &[Vec3<GLfloat>],
                           faces:       &[Vec3<GLuint>],
                           normals:     &mut Vec<Vec3<GLfloat>>) {
        let mut divisor = Vec::from_elem(coordinates.len(), 0f32);

        // Shrink the output buffer if it is too big.
        if normals.len() > coordinates.len() {
            normals.truncate(coordinates.len())
        }

        // Reinit all normals to zero.
        for n in normals.mut_iter() {
            *n = na::zero()
        }

        // Grow the output buffer if it is too small.
        normals.grow_set(coordinates.len() - 1, &na::zero(), na::zero());

        // Accumulate normals ...
        for f in faces.iter() {
            let edge1  = coordinates[f.y as uint] - coordinates[f.x as uint];
            let edge2  = coordinates[f.z as uint] - coordinates[f.x as uint];
            let cross  = na::cross(&edge1, &edge2);
            let normal;

            if !cross.is_zero() {
                normal = na::normalize(&cross)
            }
            else {
                normal = cross
            }

            *normals.get_mut(f.x as uint) = (*normals)[f.x as uint] + normal;
            *normals.get_mut(f.y as uint) = (*normals)[f.y as uint] + normal;
            *normals.get_mut(f.z as uint) = (*normals)[f.z as uint] + normal;

            *divisor.get_mut(f.x as uint) = divisor[f.x as uint] + 1.0;
            *divisor.get_mut(f.y as uint) = divisor[f.y as uint] + 1.0;
            *divisor.get_mut(f.z as uint) = divisor[f.z as uint] + 1.0;
        }

        // ... and compute the mean
        for (n, divisor) in normals.mut_iter().zip(divisor.iter()) {
            *n = *n / *divisor
        }
    }
}
<commit_msg>Add a way to construct a Mesh from a TriMesh.<commit_after>//! Data structure of a scene node geometry.

use std::num::Zero;
use sync::{Arc, RWLock};
use gl::types::*;
use nalgebra::na::{Vec2, Vec3};
use nalgebra::na;
use ncollide::procedural::{TriMesh, UnifiedIndexBuffer};
use resource::ShaderAttribute;
use resource::gpu_vector::{GPUVector, DynamicDraw, StaticDraw, ArrayBuffer, ElementArrayBuffer};

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

/// Aggregation of vertices, indices, normals and texture coordinates.
///
/// It also contains the GPU location of those buffers.
pub struct Mesh {
    coords:  Arc<RWLock<GPUVector<Vec3<GLfloat>>>>,
    faces:   Arc<RWLock<GPUVector<Vec3<GLuint>>>>,
    normals: Arc<RWLock<GPUVector<Vec3<GLfloat>>>>,
    uvs:     Arc<RWLock<GPUVector<Vec2<GLfloat>>>>
}

impl Mesh {
    /// Creates a new mesh.
    ///
    /// If the normals and uvs are not given, they are automatically computed.
    pub fn new(coords:       Vec<Vec3<GLfloat>>,
               faces:        Vec<Vec3<GLuint>>,
               normals:      Option<Vec<Vec3<GLfloat>>>,
               uvs:          Option<Vec<Vec2<GLfloat>>>,
               dynamic_draw: bool)
               -> Mesh {
        let normals = match normals {
            Some(ns) => ns,
            None     => Mesh::compute_normals_array(coords.as_slice(), faces.as_slice())
        };

        let uvs = match uvs {
            Some(us) => us,
            None     => Vec::from_elem(coords.len(), na::zero())
        };

        let location = if dynamic_draw { DynamicDraw } else { StaticDraw };
        let cs = Arc::new(RWLock::new(GPUVector::new(coords, ArrayBuffer, location)));
        let fs = Arc::new(RWLock::new(GPUVector::new(faces, ElementArrayBuffer, location)));
        let ns = Arc::new(RWLock::new(GPUVector::new(normals, ArrayBuffer, location)));
        let us = Arc::new(RWLock::new(GPUVector::new(uvs, ArrayBuffer, location)));

        Mesh::new_with_gpu_vectors(cs, fs, ns, us)
    }

    /// Creates a new mesh from a mesh descr.
    ///
    /// In the normals and uvs are not given, they are automatically computed.
    pub fn from_trimesh(mesh: TriMesh<GLfloat, Vec3<GLfloat>>, dynamic_draw: bool) -> Mesh {
        let mut mesh = mesh;

        mesh.unify_index_buffer();

        let TriMesh { coords, normals, uvs, indices } = mesh;

        Mesh::new(coords, indices.unwrap_unified(), normals, uvs, dynamic_draw)
    }

    /// Creates a triangle mesh from this mesh.
    pub fn to_trimesh(&self) -> Option<TriMesh<GLfloat, Vec3<GLfloat>>> {
        let unload_coords  = !self.coords.read().is_on_ram();
        let unload_faces   = !self.faces.read().is_on_ram();
        let unload_normals = !self.normals.read().is_on_ram();
        let unload_uvs     = !self.uvs.read().is_on_ram();

        self.coords.write().load_to_ram();
        self.faces.write().load_to_ram();
        self.normals.write().load_to_ram();
        self.uvs.write().load_to_ram();

        let coords  = self.coords.read().to_owned();
        let faces   = self.faces.read().to_owned();
        let normals = self.normals.read().to_owned();
        let uvs     = self.uvs.read().to_owned();

        if unload_coords {
            self.coords.write().unload_from_ram();
        }
        if unload_faces {
            self.coords.write().unload_from_ram();
        }
        if unload_normals {
            self.coords.write().unload_from_ram();
        }
        if unload_uvs {
            self.coords.write().unload_from_ram();
        }

        if coords.is_none() || faces.is_none() {
            None
        }
        else {
            Some(TriMesh::new(coords.unwrap(), normals, uvs, Some(UnifiedIndexBuffer(faces.unwrap()))))
        }
    }

    /// Creates a new mesh. Arguments set to `None` are automatically computed.
    pub fn new_with_gpu_vectors(coords:  Arc<RWLock<GPUVector<Vec3<GLfloat>>>>,
                                faces:   Arc<RWLock<GPUVector<Vec3<GLuint>>>>,
                                normals: Arc<RWLock<GPUVector<Vec3<GLfloat>>>>,
                                uvs:     Arc<RWLock<GPUVector<Vec2<GLfloat>>>>)
                                -> Mesh {
        Mesh {
            coords:  coords,
            faces:   faces,
            normals: normals,
            uvs:     uvs
        }
    }

    /// Binds this mesh vertex coordinates buffer to a vertex attribute.
    pub fn bind_coords(&mut self, coords: &mut ShaderAttribute<Vec3<GLfloat>>) {
        coords.bind(self.coords.write().deref_mut());
    }

    /// Binds this mesh vertex normals buffer to a vertex attribute.
    pub fn bind_normals(&mut self, normals: &mut ShaderAttribute<Vec3<GLfloat>>) {
        normals.bind(self.normals.write().deref_mut());
    }

    /// Binds this mesh vertex uvs buffer to a vertex attribute.
    pub fn bind_uvs(&mut self, uvs: &mut ShaderAttribute<Vec2<GLfloat>>) {
        uvs.bind(self.uvs.write().deref_mut());
    }

    /// Binds this mesh vertex uvs buffer to a vertex attribute.
    pub fn bind_faces(&mut self) {
        self.faces.write().bind();
    }

    /// Binds this mesh buffers to vertex attributes.
    pub fn bind(&mut self,
                coords:  &mut ShaderAttribute<Vec3<GLfloat>>,
                normals: &mut ShaderAttribute<Vec3<GLfloat>>,
                uvs:     &mut ShaderAttribute<Vec2<GLfloat>>) {
        self.bind_coords(coords);
        self.bind_normals(normals);
        self.bind_uvs(uvs);
        self.bind_faces();
    }

    /// Unbind this mesh buffers to vertex attributes.
    pub fn unbind(&self) {
        self.coords.write().unbind();
        self.normals.write().unbind();
        self.uvs.write().unbind();
        self.faces.write().unbind();
    }

    /// Number of points needed to draw this mesh.
    pub fn num_pts(&self) -> uint {
        self.faces.read().len() * 3
    }

    /// Recompute this mesh normals.
    pub fn recompute_normals(&mut self) {
        Mesh::compute_normals(self.coords.read().data().get_ref().as_slice(),
                              self.faces.read().data().get_ref().as_slice(),
                              self.normals.write().data_mut().get_mut_ref());
    }

    /// This mesh faces.
    pub fn faces<'a>(&'a self) -> &'a Arc<RWLock<GPUVector<Vec3<GLuint>>>> {
        &self.faces
    }

    /// This mesh normals.
    pub fn normals<'a>(&'a self) -> &'a Arc<RWLock<GPUVector<Vec3<GLfloat>>>> {
        &self.normals
    }

    /// This mesh vertex coordinates.
    pub fn coords<'a>(&'a self) -> &'a Arc<RWLock<GPUVector<Vec3<GLfloat>>>> {
        &self.coords
    }

    /// This mesh texture coordinates.
    pub fn uvs<'a>(&'a self) -> &'a Arc<RWLock<GPUVector<Vec2<GLfloat>>>> {
        &self.uvs
    }

    /// Computes normals from a set of faces.
    pub fn compute_normals_array(coordinates: &[Vec3<GLfloat>], faces: &[Vec3<GLuint>]) -> Vec<Vec3<GLfloat>> {
        let mut res = Vec::new();

        Mesh::compute_normals(coordinates, faces, &mut res);

        res
    }

    /// Computes normals from a set of faces.
    pub fn compute_normals(coordinates: &[Vec3<GLfloat>],
                           faces:       &[Vec3<GLuint>],
                           normals:     &mut Vec<Vec3<GLfloat>>) {
        let mut divisor = Vec::from_elem(coordinates.len(), 0f32);

        // Shrink the output buffer if it is too big.
        if normals.len() > coordinates.len() {
            normals.truncate(coordinates.len())
        }

        // Reinit all normals to zero.
        for n in normals.mut_iter() {
            *n = na::zero()
        }

        // Grow the output buffer if it is too small.
        normals.grow_set(coordinates.len() - 1, &na::zero(), na::zero());

        // Accumulate normals ...
        for f in faces.iter() {
            let edge1  = coordinates[f.y as uint] - coordinates[f.x as uint];
            let edge2  = coordinates[f.z as uint] - coordinates[f.x as uint];
            let cross  = na::cross(&edge1, &edge2);
            let normal;

            if !cross.is_zero() {
                normal = na::normalize(&cross)
            }
            else {
                normal = cross
            }

            *normals.get_mut(f.x as uint) = (*normals)[f.x as uint] + normal;
            *normals.get_mut(f.y as uint) = (*normals)[f.y as uint] + normal;
            *normals.get_mut(f.z as uint) = (*normals)[f.z as uint] + normal;

            *divisor.get_mut(f.x as uint) = divisor[f.x as uint] + 1.0;
            *divisor.get_mut(f.y as uint) = divisor[f.y as uint] + 1.0;
            *divisor.get_mut(f.z as uint) = divisor[f.z as uint] + 1.0;
        }

        // ... and compute the mean
        for (n, divisor) in normals.mut_iter().zip(divisor.iter()) {
            *n = *n / *divisor
        }
    }
}
<|endoftext|>


<commit_before>#![deny(missing_docs)]

// TODO(doc) clarify the different type of queues and what is accessible from the high-level API
// vs what belongs to core-ll. There doesn't seem to be a "ComputeEncoder" can I submit something
// built with a GraphicsEncoder to a ComputeQueue?

//! # gfx
//!
//! An efficient, low-level, bindless graphics API for Rust.
//!
//! # Overview
//!
//! ## Command buffers and encoders and queues
//!
//! A command buffer is a serialized list of drawing and compute commands.
//! Unlike with vulkan, command buffers are not what you use to create commands, but only
//! the result of creating these commands. Gfx, borrowing metal's terminology, uses
//! encoders to build command buffers. This means that, in general, users of the gfx crate
//! don't manipulate command buffers directly much and interact mostly with graphics encoders.
//! In order to be executed, a command buffer is then submitted to a queue.
//!
//! Manipulating a `GraphicsEncoder` in gfx corresponds to interacting with:
//!
//! - a `VkCommandBuffer` in vulkan,
//! - a `MTLCommandEncoder` in metal,
//! - an `ID3D12GraphicsCommandList` in D3D12.
//!
//! OpenGL and earlier versions of D3D don't have an explicit notion of command buffers
//! encoders or queues (with the exception of draw indirect commands in late versions of OpenGL,
//! which can be seen as a GPU-side command buffer). They are managed implicitly by the driver.
//!
//! See:
//!
//! - The [`GraphicsEncoder` struct](struct.GraphicsEncoder.html).
//! - The [`CommandBuffer` trait](trait.CommandBuffer.html).
//! - The [`CommandQueue` struct](struct.CommandQueue.html).
//!
//! ## Devoce
//!
//! The device is what lets you allocate GPU resources such as buffers and textures.
//!
//! Each gfx backend provides its own device type which implements both:
//!
//! - The [`Device` trait](traits/trait.Device.html#overview).
//! - The [`DeviceExt` trait](traits/trait.DeviceExt.html).
//!
//! `gfx::Device` is roughly equivalent to:
//!
//! - `VkDevice` in vulkan,
//! - `ID3D11Device` in D3D11,
//! - `MTLDevice` in metal.
//!
//! OpenGL does not have a notion of device (resources are created directly off of the global
//! context). D3D11 has a DXGI factory but it is only used to interface with other processes
//! and the window manager, resources like textures are usually created using the device.
//!
//! ## Gpu
//!
//! The `Gpu` contains the `Device` and the `Queue`s.
//!
//! ## Pipeline state (PSO)
//!
//! See [the documentation of the gfx::pso module](pso/index.html).
//!
//! ## Memory management
//!
//! Handles internally use atomically reference counted pointers to deal with memory management.
//! GPU resources are not destroyed right away when all references to them are gone. Instead they
//! are destroyed the next time `cleanup` is called on the queue.
//!
//! # Examples
//!
//! See [the examples in the repository](https://github.com/gfx-rs/gfx/tree/master/examples).
//!
//! # Useful resources
//!
//!  - [Documentation for some of the technical terms](doc/terminology/index.html)
//! used in the API.
//!  - [Learning gfx](https://wiki.alopex.li/LearningGfx) tutorial.
//!  - See [the blog](http://gfx-rs.github.io/) for more explanations and annotated examples.
//!

#[cfg(feature = "mint")]
extern crate mint;

#[macro_use]
extern crate log;
#[macro_use]
extern crate derivative;
extern crate draw_state;
extern crate gfx_core as core;

/// public re-exported traits
pub mod traits {
    pub use core::{Device};
    pub use core::memory::Pod;
    pub use device::DeviceExt;
}

// draw state re-exports
pub use draw_state::{preset, state};
pub use draw_state::target::*;

// public re-exports
pub use core::{Adapter, Backend, CommandQueue, Gpu, Frame, FrameSync, Headless, Primitive, QueueFamily, QueueType,
               Resources, SubmissionError, SubmissionResult, Surface, Swapchain, SwapchainConfig, WindowExt};
pub use core::{VertexCount, InstanceCount};
pub use core::{ShaderSet, VertexShader, HullShader, DomainShader, GeometryShader, PixelShader};
pub use core::{GeneralCommandPool, GraphicsCommandPool, ComputeCommandPool, SubpassCommandPool};
pub use core::{buffer, format, handle, texture, mapping, queue};
pub use core::device::{Device, ResourceViewError, TargetViewError, CombinedError, WaitFor};
pub use core::memory::{self, Bind, TRANSFER_SRC, TRANSFER_DST, RENDER_TARGET,
                       DEPTH_STENCIL, SHADER_RESOURCE, UNORDERED_ACCESS};
pub use core::command::{Buffer as CommandBuffer, InstanceParams};
pub use core::shade::{ProgramInfo, UniformValue};

pub use encoder::{CopyBufferResult, CopyBufferTextureResult, CopyError,
                  CopyTextureBufferResult, GraphicsEncoder, UpdateError, GraphicsPoolExt};
pub use device::PipelineStateError;
pub use slice::{Slice, IntoIndexBuffer, IndexBuffer};
pub use swapchain::SwapchainExt;
pub use pso::{PipelineState};
pub use pso::buffer::{VertexBuffer, InstanceBuffer, RawVertexBuffer,
                      ConstantBuffer, RawConstantBuffer, Global, RawGlobal};
pub use pso::resource::{ShaderResource, RawShaderResource, UnorderedAccess,
                        Sampler, TextureSampler};
pub use pso::target::{DepthStencilTarget, DepthTarget, StencilTarget,
                      RenderTarget, RawRenderTarget, BlendTarget, BlendRef, Scissor};
pub use pso::bundle::{Bundle};

/// Render commands encoder
mod encoder;
/// Device extensions
mod device;
/// Slices
mod slice;
/// Swapchain extensions
mod swapchain;
// Pipeline states
pub mod pso;
/// Shaders
pub mod shade;
/// Convenience macros
pub mod macros;
<commit_msg>Make `GraphicsSubmission` public.<commit_after>#![deny(missing_docs)]

// TODO(doc) clarify the different type of queues and what is accessible from the high-level API
// vs what belongs to core-ll. There doesn't seem to be a "ComputeEncoder" can I submit something
// built with a GraphicsEncoder to a ComputeQueue?

//! # gfx
//!
//! An efficient, low-level, bindless graphics API for Rust.
//!
//! # Overview
//!
//! ## Command buffers and encoders and queues
//!
//! A command buffer is a serialized list of drawing and compute commands.
//! Unlike with vulkan, command buffers are not what you use to create commands, but only
//! the result of creating these commands. Gfx, borrowing metal's terminology, uses
//! encoders to build command buffers. This means that, in general, users of the gfx crate
//! don't manipulate command buffers directly much and interact mostly with graphics encoders.
//! In order to be executed, a command buffer is then submitted to a queue.
//!
//! Manipulating a `GraphicsEncoder` in gfx corresponds to interacting with:
//!
//! - a `VkCommandBuffer` in vulkan,
//! - a `MTLCommandEncoder` in metal,
//! - an `ID3D12GraphicsCommandList` in D3D12.
//!
//! OpenGL and earlier versions of D3D don't have an explicit notion of command buffers
//! encoders or queues (with the exception of draw indirect commands in late versions of OpenGL,
//! which can be seen as a GPU-side command buffer). They are managed implicitly by the driver.
//!
//! See:
//!
//! - The [`GraphicsEncoder` struct](struct.GraphicsEncoder.html).
//! - The [`CommandBuffer` trait](trait.CommandBuffer.html).
//! - The [`CommandQueue` struct](struct.CommandQueue.html).
//!
//! ## Devoce
//!
//! The device is what lets you allocate GPU resources such as buffers and textures.
//!
//! Each gfx backend provides its own device type which implements both:
//!
//! - The [`Device` trait](traits/trait.Device.html#overview).
//! - The [`DeviceExt` trait](traits/trait.DeviceExt.html).
//!
//! `gfx::Device` is roughly equivalent to:
//!
//! - `VkDevice` in vulkan,
//! - `ID3D11Device` in D3D11,
//! - `MTLDevice` in metal.
//!
//! OpenGL does not have a notion of device (resources are created directly off of the global
//! context). D3D11 has a DXGI factory but it is only used to interface with other processes
//! and the window manager, resources like textures are usually created using the device.
//!
//! ## Gpu
//!
//! The `Gpu` contains the `Device` and the `Queue`s.
//!
//! ## Pipeline state (PSO)
//!
//! See [the documentation of the gfx::pso module](pso/index.html).
//!
//! ## Memory management
//!
//! Handles internally use atomically reference counted pointers to deal with memory management.
//! GPU resources are not destroyed right away when all references to them are gone. Instead they
//! are destroyed the next time `cleanup` is called on the queue.
//!
//! # Examples
//!
//! See [the examples in the repository](https://github.com/gfx-rs/gfx/tree/master/examples).
//!
//! # Useful resources
//!
//!  - [Documentation for some of the technical terms](doc/terminology/index.html)
//! used in the API.
//!  - [Learning gfx](https://wiki.alopex.li/LearningGfx) tutorial.
//!  - See [the blog](http://gfx-rs.github.io/) for more explanations and annotated examples.
//!

#[cfg(feature = "mint")]
extern crate mint;

#[macro_use]
extern crate log;
#[macro_use]
extern crate derivative;
extern crate draw_state;
extern crate gfx_core as core;

/// public re-exported traits
pub mod traits {
    pub use core::{Device};
    pub use core::memory::Pod;
    pub use device::DeviceExt;
}

// draw state re-exports
pub use draw_state::{preset, state};
pub use draw_state::target::*;

// public re-exports
pub use core::{Adapter, Backend, CommandQueue, Gpu, Frame, FrameSync, Headless, Primitive, QueueFamily, QueueType,
               Resources, SubmissionError, SubmissionResult, Surface, Swapchain, SwapchainConfig, WindowExt};
pub use core::{VertexCount, InstanceCount};
pub use core::{ShaderSet, VertexShader, HullShader, DomainShader, GeometryShader, PixelShader};
pub use core::{GeneralCommandPool, GraphicsCommandPool, ComputeCommandPool, SubpassCommandPool};
pub use core::{buffer, format, handle, texture, mapping, queue};
pub use core::device::{Device, ResourceViewError, TargetViewError, CombinedError, WaitFor};
pub use core::memory::{self, Bind, TRANSFER_SRC, TRANSFER_DST, RENDER_TARGET,
                       DEPTH_STENCIL, SHADER_RESOURCE, UNORDERED_ACCESS};
pub use core::command::{Buffer as CommandBuffer, InstanceParams};
pub use core::shade::{ProgramInfo, UniformValue};

pub use encoder::{CopyBufferResult, CopyBufferTextureResult, CopyError,
                  CopyTextureBufferResult, GraphicsEncoder, GraphicsSubmission, UpdateError,
                  GraphicsPoolExt, };
pub use device::PipelineStateError;
pub use slice::{Slice, IntoIndexBuffer, IndexBuffer};
pub use swapchain::SwapchainExt;
pub use pso::{PipelineState};
pub use pso::buffer::{VertexBuffer, InstanceBuffer, RawVertexBuffer,
                      ConstantBuffer, RawConstantBuffer, Global, RawGlobal};
pub use pso::resource::{ShaderResource, RawShaderResource, UnorderedAccess,
                        Sampler, TextureSampler};
pub use pso::target::{DepthStencilTarget, DepthTarget, StencilTarget,
                      RenderTarget, RawRenderTarget, BlendTarget, BlendRef, Scissor};
pub use pso::bundle::{Bundle};

/// Render commands encoder
mod encoder;
/// Device extensions
mod device;
/// Slices
mod slice;
/// Swapchain extensions
mod swapchain;
// Pipeline states
pub mod pso;
/// Shaders
pub mod shade;
/// Convenience macros
pub mod macros;
<|endoftext|>


<commit_before>extern crate rust_base58;
extern crate serde_json;
extern crate zmq;

use self::rust_base58::FromBase58;
use std::cell::RefCell;
use std::thread;

use errors::common::CommonError;
use errors::pool::PoolError;
use utils::json::{JsonDecodable, JsonEncodable};
use utils::sequence::SequenceUtils;

struct RemoteAgent {
    socket: zmq::Socket,
    addr: String,
    public_key: Vec<u8>,
    secret_key: Vec<u8>,
    server_key: Vec<u8>,
}

struct AgentWorker {
    cmd_socket: zmq::Socket,
    agent_connections: Vec<RemoteAgent>,
}

struct Agent {
    cmd_socket: zmq::Socket,
    worker: Option<thread::JoinHandle<()>>,
}

impl Drop for Agent {
    fn drop(&mut self) {
        trace!("agent drop >>");
        self.cmd_socket.send_str(AgentWorkerCommand::Exit.to_json().unwrap().as_str(), zmq::DONTWAIT).unwrap(); //TODO
        self.worker.take().unwrap().join().unwrap();
        trace!("agent drop <<");
    }
}

pub struct AgentService {
    agent: RefCell<Option<Agent>>,
}

impl Agent {
    pub fn new() -> Agent {
        let ctx = zmq::Context::new();
        let (send_soc, recv_soc) = _create_zmq_socket_pair("agent", true).unwrap();
        let mut worker = AgentWorker {
            cmd_socket: recv_soc,
            agent_connections: Vec::new(),
        };
        Agent {
            cmd_socket: send_soc,
            worker: Some(thread::spawn(move || { worker.run() }))
        }
    }
}

impl AgentService {
    pub fn new() -> AgentService {
        AgentService { agent: RefCell::new((None)) }
    }

    pub fn connect(&self, sender_did: &str, my_sk: &str, my_pk: &str, endpoint: &str, server_key: &str) -> Result<(), CommonError> {
        let mut agent = self.agent.borrow_mut();
        if agent.is_none() {
            *agent = Some(Agent::new());
        }
        let conn_handle = SequenceUtils::get_next_id();
        let connect_cmd: AgentWorkerCommand = AgentWorkerCommand::Connect(ConnectCmd {
            did: sender_did.to_string(),
            secret_key: my_sk.to_string(),
            public_key: my_pk.to_string(),
            endpoint: endpoint.to_string(),
            server_key: server_key.to_string(),
        });
        agent.as_ref().unwrap().cmd_socket.send_str(connect_cmd.to_json().unwrap().as_str(), zmq::DONTWAIT).unwrap();
        Ok(())
    }
}

impl AgentWorker {
    fn run(&mut self) {
        loop {
            trace!("agent worker poll loop >>");
            self.cmd_socket.poll(zmq::POLLIN, -1).unwrap();
            let s = self.cmd_socket.recv_string(zmq::DONTWAIT).unwrap().unwrap();
            let cmd = AgentWorkerCommand::from_json(s.as_str()).unwrap();
            match cmd {
                AgentWorkerCommand::Connect(cmd) => self.connect(&cmd).unwrap(),
                AgentWorkerCommand::Exit => break,
            }
            info!("received cmd {}", s);
            trace!("agent worker poll loop <<");
        }
        trace!("agent poll finished");
    }

    fn connect(&mut self, cmd: &ConnectCmd) -> Result<(), PoolError> {
        let ra = RemoteAgent::new(cmd.public_key.as_str(), cmd.secret_key.as_str(),
                                  cmd.server_key.as_str(), cmd.endpoint.as_str())
            .map_err(map_err_trace!("RemoteAgent::new failed"))?;
        ra.connect().map_err(map_err_trace!("RemoteAgent::connect failed"))?;
        self.agent_connections.push(ra);
        Ok(())
    }
}

impl RemoteAgent {
    fn new(pub_key: &str, sec_key: &str, ver_key: &str, addr: &str) -> Result<RemoteAgent, PoolError> {
        Ok(RemoteAgent {
            socket: zmq::Context::new().socket(zmq::SocketType::DEALER)?,
            public_key: pub_key.from_base58()
                .map_err(PoolError::from_displayable_as_invalid_config)?,
            secret_key: sec_key.from_base58()
                .map_err(PoolError::from_displayable_as_invalid_config)?,
            server_key: ver_key.from_base58()
                .map_err(PoolError::from_displayable_as_invalid_config)?,
            addr: addr.to_string(),
        })
    }

    fn connect(&self) -> Result<(), PoolError> {
        impl From<zmq::EncodeError> for PoolError {
            fn from(err: zmq::EncodeError) -> PoolError {
                PoolError::InvalidState(format!("Invalid data stored RemoteAgent detected while connect {:?}", err))
            }
        }
        self.socket.set_identity(zmq::z85_encode(self.public_key.as_slice())?.as_bytes())
            .map_err(map_err_trace!())?;
        self.socket.set_curve_secretkey(zmq::z85_encode(self.secret_key.as_slice())?.as_str())
            .map_err(map_err_trace!())?;
        self.socket.set_curve_publickey(zmq::z85_encode(self.public_key.as_slice())?.as_str())
            .map_err(map_err_trace!())?;
        self.socket.set_curve_serverkey(zmq::z85_encode(self.server_key.as_slice())?.as_str())
            .map_err(map_err_trace!())?;
        self.socket.set_linger(0).map_err(map_err_trace!())?; //TODO set correct timeout
        self.socket.connect(self.addr.as_str()).map_err(map_err_trace!())?;
        self.socket.send_str("DID", zmq::DONTWAIT).map_err(map_err_trace!())?;
        Ok(())
    }
}

#[serde(tag = "cmd")]
#[derive(Serialize, Deserialize, Debug)]
enum AgentWorkerCommand {
    Connect(ConnectCmd),
    Exit,
}

impl JsonEncodable for AgentWorkerCommand {}

impl<'a> JsonDecodable<'a> for AgentWorkerCommand {}

#[derive(Serialize, Deserialize, Debug)]
struct ConnectCmd {
    endpoint: String,
    did: String,
    secret_key: String,
    public_key: String,
    server_key: String,
}

fn _create_zmq_socket_pair(address: &str, connect_and_bind: bool) -> Result<(zmq::Socket, zmq::Socket), zmq::Error> {
    let ctx = zmq::Context::new();
    let recv_soc = ctx.socket(zmq::SocketType::PAIR)?;
    let send_soc = ctx.socket(zmq::SocketType::PAIR)?;
    if connect_and_bind {
        let address = format!("inproc://{}", address);
        recv_soc.bind(&address)?;
        send_soc.connect(&address)?;
    }
    Ok((send_soc, recv_soc))
}

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

    use std::sync::mpsc::channel;
    use super::rust_base58::ToBase58;

    use utils::timeout::TimeoutUtils;

    #[test]
    fn agent_can_be_dropped() {
        let (sender, receiver) = channel();
        thread::spawn(move || {
            {
                let agent = Agent::new();
            }
            sender.send(true).unwrap();
        });
        receiver.recv_timeout(TimeoutUtils::short_timeout()).expect("drop not finished");
    }

    #[test]
    fn agent_service_connect_works() {
        let (sender, receiver) = channel();
        let (send_soc, recv_soc) = _create_zmq_socket_pair("test_connect", true).unwrap();
        let agent = Agent {
            cmd_socket: send_soc,
            worker: Some(thread::spawn(move || {
                sender.send(recv_soc.recv_string(0).unwrap().unwrap()).unwrap()
            }))
        };
        let agent_service = AgentService {
            agent: RefCell::new(Some(agent)),
        };
        agent_service.connect("sd", "sk", "pk", "ep", "serv").unwrap();
        let expected_cmd = ConnectCmd {
            server_key: "serv".to_string(),
            public_key: "pk".to_string(),
            secret_key: "sk".to_string(),
            endpoint: "ep".to_string(),
            did: "sd".to_string(),
        };
        let str = receiver.recv_timeout(TimeoutUtils::short_timeout()).unwrap();
        assert_eq!(str, AgentWorkerCommand::Connect(expected_cmd).to_json().unwrap());
    }

    #[test]
    fn agent_worker_connect_works() {
        ::utils::logger::LoggerUtils::init();
        let send_key_pair = zmq::CurveKeyPair::new().unwrap();
        let recv_key_pair = zmq::CurveKeyPair::new().unwrap();
        let ctx = zmq::Context::new();
        let recv_soc = ctx.socket(zmq::SocketType::ROUTER).unwrap();
        recv_soc.set_curve_publickey(recv_key_pair.public_key.as_str()).unwrap();
        recv_soc.set_curve_secretkey(recv_key_pair.secret_key.as_str()).unwrap();
        recv_soc.set_curve_server(true).unwrap();
        recv_soc.bind("tcp://127.0.0.1:*").unwrap();
        let addr = recv_soc.get_last_endpoint().unwrap().unwrap();
        info!("addr {}", addr);

        let mut agent_worker = AgentWorker {
            agent_connections: Vec::new(),
            cmd_socket: zmq::Context::new().socket(zmq::SocketType::PAIR).unwrap(),
        };
        let cmd = ConnectCmd {
            endpoint: addr,
            public_key: zmq::z85_decode(send_key_pair.public_key.as_str()).unwrap().to_base58(),
            secret_key: zmq::z85_decode(send_key_pair.secret_key.as_str()).unwrap().to_base58(),
            did: "".to_string(),
            server_key: zmq::z85_decode(recv_key_pair.public_key.as_str()).unwrap().to_base58(),
        };

        agent_worker.connect(&cmd).unwrap();

        assert_eq!(agent_worker.agent_connections.len(), 1);
        recv_soc.recv_string(0).unwrap().unwrap(); //ignore identity
        assert_eq!(recv_soc.recv_string(zmq::DONTWAIT).unwrap().unwrap(), "DID");
    }

    #[test]
    fn remote_agent_connect_works() {
        let dest = "test_agent_connect";
        let addr: String = format!("inproc://{}", dest);
        let (send_soc, recv_soc) = _create_zmq_socket_pair(dest, false).unwrap();
        recv_soc.bind(addr.as_str()).unwrap(); //TODO enable CurveCP
        let send_key_pair = zmq::CurveKeyPair::new().unwrap();
        let recv_key_pair = zmq::CurveKeyPair::new().unwrap();
        let agent = RemoteAgent {
            socket: send_soc,
            addr: addr,
            server_key: zmq::z85_decode(send_key_pair.public_key.as_str()).unwrap(),
            secret_key: zmq::z85_decode(recv_key_pair.secret_key.as_str()).unwrap(),
            public_key: zmq::z85_decode(recv_key_pair.public_key.as_str()).unwrap(),
        };
        agent.connect().unwrap();
        assert_eq!(recv_soc.recv_string(zmq::DONTWAIT).unwrap().unwrap(), "DID");
    }

    #[test]
    fn agent_service_static_create_zmq_socket_pair_works() {
        let msg = "msg";
        let sockets = _create_zmq_socket_pair("test_pair", true).unwrap();
        sockets.0.send_str(msg, zmq::DONTWAIT).unwrap();
        assert_eq!(sockets.1.recv_string(zmq::DONTWAIT).unwrap().unwrap(), msg);
    }
}<commit_msg>Implement AgentWorker::poll.<commit_after>extern crate rust_base58;
extern crate serde_json;
extern crate zmq;

use self::rust_base58::FromBase58;
use std::cell::RefCell;
use std::thread;

use errors::common::CommonError;
use errors::pool::PoolError;
use utils::json::{JsonDecodable, JsonEncodable};
use utils::sequence::SequenceUtils;

struct RemoteAgent {
    socket: zmq::Socket,
    addr: String,
    public_key: Vec<u8>,
    secret_key: Vec<u8>,
    server_key: Vec<u8>,
}

struct AgentWorker {
    cmd_socket: zmq::Socket,
    agent_connections: Vec<RemoteAgent>,
}

struct Agent {
    cmd_socket: zmq::Socket,
    worker: Option<thread::JoinHandle<()>>,
}

impl Drop for Agent {
    fn drop(&mut self) {
        trace!("agent drop >>");
        self.cmd_socket.send_str(AgentWorkerCommand::Exit.to_json().unwrap().as_str(), zmq::DONTWAIT).unwrap(); //TODO
        self.worker.take().unwrap().join().unwrap();
        trace!("agent drop <<");
    }
}

pub struct AgentService {
    agent: RefCell<Option<Agent>>,
}

impl Agent {
    pub fn new() -> Agent {
        let ctx = zmq::Context::new();
        let (send_soc, recv_soc) = _create_zmq_socket_pair("agent", true).unwrap();
        let mut worker = AgentWorker {
            cmd_socket: recv_soc,
            agent_connections: Vec::new(),
        };
        Agent {
            cmd_socket: send_soc,
            worker: Some(thread::spawn(move || { worker.run() }))
        }
    }
}

impl AgentService {
    pub fn new() -> AgentService {
        AgentService { agent: RefCell::new((None)) }
    }

    pub fn connect(&self, sender_did: &str, my_sk: &str, my_pk: &str, endpoint: &str, server_key: &str) -> Result<(), CommonError> {
        let mut agent = self.agent.borrow_mut();
        if agent.is_none() {
            *agent = Some(Agent::new());
        }
        let conn_handle = SequenceUtils::get_next_id();
        let connect_cmd: AgentWorkerCommand = AgentWorkerCommand::Connect(ConnectCmd {
            did: sender_did.to_string(),
            secret_key: my_sk.to_string(),
            public_key: my_pk.to_string(),
            endpoint: endpoint.to_string(),
            server_key: server_key.to_string(),
        });
        agent.as_ref().unwrap().cmd_socket.send_str(connect_cmd.to_json().unwrap().as_str(), zmq::DONTWAIT).unwrap();
        Ok(())
    }
}

impl AgentWorker {
    fn run(&mut self) {
        'agent_pool_loop: loop {
            trace!("agent worker poll loop >>");
            let cmds = self.poll().unwrap();
            for cmd in cmds {
                info!("received cmd {:?}", cmd);
                match cmd {
                    AgentWorkerCommand::Connect(cmd) => self.connect(&cmd).unwrap(),
                    AgentWorkerCommand::Response(resp) => self.agent_connections[resp.agent_ind].handle_response(resp.msg),
                    AgentWorkerCommand::Exit => break 'agent_pool_loop,
                }
            }
            trace!("agent worker poll loop <<");
        }
        trace!("agent poll finished");
    }

    fn connect(&mut self, cmd: &ConnectCmd) -> Result<(), PoolError> {
        let ra = RemoteAgent::new(cmd.public_key.as_str(), cmd.secret_key.as_str(),
                                  cmd.server_key.as_str(), cmd.endpoint.as_str())
            .map_err(map_err_trace!("RemoteAgent::new failed"))?;
        ra.connect().map_err(map_err_trace!("RemoteAgent::connect failed"))?;
        self.agent_connections.push(ra);
        Ok(())
    }

    fn poll(&self) -> Result<Vec<AgentWorkerCommand>, zmq::Error> {
        let mut result = Vec::new();
        let mut poll_items: Vec<zmq::PollItem> = Vec::new();
        poll_items.push(self.cmd_socket.as_poll_item(zmq::POLLIN));

        for agent_conn in &self.agent_connections {
            poll_items.push(agent_conn.socket.as_poll_item(zmq::POLLIN));
        }

        zmq::poll(poll_items.as_mut_slice(), -1).map_err(map_err_trace!("agent poll failed"))?;

        if poll_items[0].is_readable() {
            let msg = self.cmd_socket.recv_string(zmq::DONTWAIT).unwrap().unwrap();
            info!("Input on cmd socket {}", msg);
            result.push(AgentWorkerCommand::from_json(msg.as_str()).unwrap());
        }

        for i in 0..self.agent_connections.len() {
            if poll_items[1 + i].is_readable() {
                let msg = self.agent_connections[i].socket.recv_string(zmq::DONTWAIT).unwrap().unwrap();
                info!("Input on agent socket {}: {}", i, msg);
                result.push(AgentWorkerCommand::Response(Response {
                    agent_ind: i,
                    msg: msg,
                }))
            }
        }

        Ok(result)
    }
}

impl RemoteAgent {
    fn new(pub_key: &str, sec_key: &str, ver_key: &str, addr: &str) -> Result<RemoteAgent, PoolError> {
        Ok(RemoteAgent {
            socket: zmq::Context::new().socket(zmq::SocketType::DEALER)?,
            public_key: pub_key.from_base58()
                .map_err(PoolError::from_displayable_as_invalid_config)?,
            secret_key: sec_key.from_base58()
                .map_err(PoolError::from_displayable_as_invalid_config)?,
            server_key: ver_key.from_base58()
                .map_err(PoolError::from_displayable_as_invalid_config)?,
            addr: addr.to_string(),
        })
    }

    fn connect(&self) -> Result<(), PoolError> {
        impl From<zmq::EncodeError> for PoolError {
            fn from(err: zmq::EncodeError) -> PoolError {
                PoolError::InvalidState(format!("Invalid data stored RemoteAgent detected while connect {:?}", err))
            }
        }
        self.socket.set_identity(zmq::z85_encode(self.public_key.as_slice())?.as_bytes())
            .map_err(map_err_trace!())?;
        self.socket.set_curve_secretkey(zmq::z85_encode(self.secret_key.as_slice())?.as_str())
            .map_err(map_err_trace!())?;
        self.socket.set_curve_publickey(zmq::z85_encode(self.public_key.as_slice())?.as_str())
            .map_err(map_err_trace!())?;
        self.socket.set_curve_serverkey(zmq::z85_encode(self.server_key.as_slice())?.as_str())
            .map_err(map_err_trace!())?;
        self.socket.set_linger(0).map_err(map_err_trace!())?; //TODO set correct timeout
        self.socket.connect(self.addr.as_str())
            .map_err(map_err_trace!("RemoteAgent::connect self.socket.connect failed"))?;
        self.socket.send_str("DID", zmq::DONTWAIT).map_err(map_err_trace!())?;
        Ok(())
    }

    fn handle_response(&self, msg: String) {
        unimplemented!();
    }
}

#[serde(tag = "cmd")]
#[derive(Serialize, Deserialize, Debug)]
enum AgentWorkerCommand {
    Connect(ConnectCmd),
    Response(Response),
    Exit,
}

impl JsonEncodable for AgentWorkerCommand {}

impl<'a> JsonDecodable<'a> for AgentWorkerCommand {}

#[derive(Serialize, Deserialize, Debug)]
struct ConnectCmd {
    endpoint: String,
    did: String,
    secret_key: String,
    public_key: String,
    server_key: String,
}

#[derive(Serialize, Deserialize, Debug)]
struct Response {
    agent_ind: usize,
    msg: String,
}

fn _create_zmq_socket_pair(address: &str, connect_and_bind: bool) -> Result<(zmq::Socket, zmq::Socket), zmq::Error> {
    let ctx = zmq::Context::new();
    let recv_soc = ctx.socket(zmq::SocketType::PAIR)?;
    let send_soc = ctx.socket(zmq::SocketType::PAIR)?;
    if connect_and_bind {
        let address = format!("inproc://{}", address);
        recv_soc.bind(&address)?;
        send_soc.connect(&address)?;
    }
    Ok((send_soc, recv_soc))
}

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

    use std::sync::mpsc::channel;
    use super::rust_base58::ToBase58;

    use utils::timeout::TimeoutUtils;

    #[test]
    fn agent_can_be_dropped() {
        let (sender, receiver) = channel();
        thread::spawn(move || {
            {
                let agent = Agent::new();
            }
            sender.send(true).unwrap();
        });
        receiver.recv_timeout(TimeoutUtils::short_timeout()).expect("drop not finished");
    }

    #[test]
    fn agent_service_connect_works() {
        let (sender, receiver) = channel();
        let (send_soc, recv_soc) = _create_zmq_socket_pair("test_connect", true).unwrap();
        let agent = Agent {
            cmd_socket: send_soc,
            worker: Some(thread::spawn(move || {
                sender.send(recv_soc.recv_string(0).unwrap().unwrap()).unwrap()
            }))
        };
        let agent_service = AgentService {
            agent: RefCell::new(Some(agent)),
        };
        agent_service.connect("sd", "sk", "pk", "ep", "serv").unwrap();
        let expected_cmd = ConnectCmd {
            server_key: "serv".to_string(),
            public_key: "pk".to_string(),
            secret_key: "sk".to_string(),
            endpoint: "ep".to_string(),
            did: "sd".to_string(),
        };
        let str = receiver.recv_timeout(TimeoutUtils::short_timeout()).unwrap();
        assert_eq!(str, AgentWorkerCommand::Connect(expected_cmd).to_json().unwrap());
    }

    #[test]
    fn agent_worker_connect_works() {
        ::utils::logger::LoggerUtils::init();
        let send_key_pair = zmq::CurveKeyPair::new().unwrap();
        let recv_key_pair = zmq::CurveKeyPair::new().unwrap();
        let ctx = zmq::Context::new();
        let recv_soc = ctx.socket(zmq::SocketType::ROUTER).unwrap();
        recv_soc.set_curve_publickey(recv_key_pair.public_key.as_str()).unwrap();
        recv_soc.set_curve_secretkey(recv_key_pair.secret_key.as_str()).unwrap();
        recv_soc.set_curve_server(true).unwrap();
        recv_soc.bind("tcp://127.0.0.1:*").unwrap();
        let addr = recv_soc.get_last_endpoint().unwrap().unwrap();
        info!("addr {}", addr);

        let mut agent_worker = AgentWorker {
            agent_connections: Vec::new(),
            cmd_socket: zmq::Context::new().socket(zmq::SocketType::PAIR).unwrap(),
        };
        let cmd = ConnectCmd {
            endpoint: addr,
            public_key: zmq::z85_decode(send_key_pair.public_key.as_str()).unwrap().to_base58(),
            secret_key: zmq::z85_decode(send_key_pair.secret_key.as_str()).unwrap().to_base58(),
            did: "".to_string(),
            server_key: zmq::z85_decode(recv_key_pair.public_key.as_str()).unwrap().to_base58(),
        };

        agent_worker.connect(&cmd).unwrap();

        assert_eq!(agent_worker.agent_connections.len(), 1);
        recv_soc.recv_string(0).unwrap().unwrap(); //ignore identity
        assert_eq!(recv_soc.recv_string(zmq::DONTWAIT).unwrap().unwrap(), "DID");
    }

    #[test]
    fn agent_worker_poll_works_for_cmd_socket() {
        let (send_soc, recv_soc) = _create_zmq_socket_pair("aw_poll_cmd", true).unwrap();
        let agent_worker = AgentWorker {
            agent_connections: Vec::new(),
            cmd_socket: recv_soc,
        };
        send_soc.send_str(r#"{"cmd": "Exit"}"#, zmq::DONTWAIT).unwrap();

        let cmds = agent_worker.poll().unwrap();

        assert_eq!(cmds.len(), 1);
        assert_match!(AgentWorkerCommand::Exit, cmds[0]);
    }

    #[test]
    fn agent_worker_poll_works_for_agent_socket() {
        let (send_soc, recv_soc) = _create_zmq_socket_pair("aw_poll_cmd", true).unwrap();
        let agent_worker = AgentWorker {
            agent_connections: vec!(RemoteAgent {
                socket: recv_soc,
                addr: String::new(),
                public_key: Vec::new(),
                secret_key: Vec::new(),
                server_key: Vec::new(),
            }),
            cmd_socket: zmq::Context::new().socket(zmq::SocketType::PAIR).unwrap(),
        };
        send_soc.send_str("msg", zmq::DONTWAIT).unwrap();

        let mut cmds = agent_worker.poll().unwrap();

        assert_eq!(cmds.len(), 1);
        let cmd = cmds.remove(0);
        match cmd {
            AgentWorkerCommand::Response(resp) => {
                assert_eq!(resp.agent_ind, 0);
                assert_eq!(resp.msg, "msg");
            }
            _ => panic!("unexpected cmd {:?}", cmd),
        }
    }

    #[test]
    fn remote_agent_connect_works() {
        let dest = "test_agent_connect";
        let addr: String = format!("inproc://{}", dest);
        let (send_soc, recv_soc) = _create_zmq_socket_pair(dest, false).unwrap();
        recv_soc.bind(addr.as_str()).unwrap(); //TODO enable CurveCP
        let send_key_pair = zmq::CurveKeyPair::new().unwrap();
        let recv_key_pair = zmq::CurveKeyPair::new().unwrap();
        let agent = RemoteAgent {
            socket: send_soc,
            addr: addr,
            server_key: zmq::z85_decode(send_key_pair.public_key.as_str()).unwrap(),
            secret_key: zmq::z85_decode(recv_key_pair.secret_key.as_str()).unwrap(),
            public_key: zmq::z85_decode(recv_key_pair.public_key.as_str()).unwrap(),
        };
        agent.connect().unwrap();
        assert_eq!(recv_soc.recv_string(zmq::DONTWAIT).unwrap().unwrap(), "DID");
    }

    #[test]
    fn agent_service_static_create_zmq_socket_pair_works() {
        let msg = "msg";
        let sockets = _create_zmq_socket_pair("test_pair", true).unwrap();
        sockets.0.send_str(msg, zmq::DONTWAIT).unwrap();
        assert_eq!(sockets.1.recv_string(zmq::DONTWAIT).unwrap().unwrap(), msg);
    }
}<|endoftext|>


<commit_before><commit_msg>Add examples<commit_after>#[macro_use]
extern crate rblas as blas;
use blas::math::Mat;
use blas::{Matrix, Vector};
use blas::math::Marker::T;

fn main() {
    let x = vec![1.0, 2.0];
    let xr = &x as &Vector<_>;
    let i = mat![1.0, 0.0; 0.0, 1.0];
    let ir = &i as &Matrix<_>;

    assert!(xr + &x == 2.0 * xr);
    assert!(ir * xr == x);

    let dot = (xr ^ T) * xr;
    assert!(dot == 5.0);
}
<|endoftext|>


<commit_before>extern crate sass_sys;
extern crate libc;

mod bindings;
mod options;
// mod dispatcher;

pub use options::Options;
pub use bindings::Context;

/// Takes a file path and compiles it with the options given
pub fn compile_file(path: &str, options: Options) -> Result<String, String> {
    let mut context = Context::new_file(path);
    context.set_options(options);
    context.compile()
}

/// Takes a string and compiles it with the options given
pub fn compile_string(content: &str, options: Options) -> Result<String, String> {
    let mut context = Context::new_data(content);
    context.set_options(options);
    context.compile()
}

#[cfg(test)]
mod tests {
    use super::{Options, compile_string};

    #[test]
    fn can_compile_some_valid_scss_input() {
        let input = "body { .hey { color: red; } }";
        compile_string(input, Options::default()).is_ok();
    }

    #[test]
    fn errors_with_invalid_scss_input() {
        let input = "body { .hey { color: ; } }";
        let res = compile_string(input, Options::default());
        assert!(res.is_err());
    }
}
<commit_msg>Make OutputStyle struct public<commit_after>extern crate sass_sys;
extern crate libc;

mod bindings;
mod options;
// mod dispatcher;

pub use options::{Options, OutputStyle};
pub use bindings::Context;

/// Takes a file path and compiles it with the options given
pub fn compile_file(path: &str, options: Options) -> Result<String, String> {
    let mut context = Context::new_file(path);
    context.set_options(options);
    context.compile()
}

/// Takes a string and compiles it with the options given
pub fn compile_string(content: &str, options: Options) -> Result<String, String> {
    let mut context = Context::new_data(content);
    context.set_options(options);
    context.compile()
}

#[cfg(test)]
mod tests {
    use super::{Options, OutputStyle, compile_string};

    #[test]
    fn can_compile_some_valid_scss_input() {
        let input = "body { .hey { color: red; } }";
        assert_eq!(compile_string(input, Options::default()),
            Ok("body .hey {\n  color: red; }\n".to_string()));
    }

    #[test]
    fn errors_with_invalid_scss_input() {
        let input = "body { .hey { color: ; } }";
        let res = compile_string(input, Options::default());
        assert!(res.is_err());
    }

    #[test]
    fn can_use_alternative_options() {
        let input = "body { .hey { color: red; } }";
        let mut opts = Options::default();
        opts.output_style = OutputStyle::Compressed;
        assert_eq!(compile_string(input, opts),
            Ok("body .hey{color:red}\n".to_string()));
    }
}
<|endoftext|>


<commit_before><commit_msg>Create separate symbol_table module<commit_after>
use hamt::HamtMap;
use itertools::*;

use std::error::Error;
use std::fmt::{self, Display, Debug, Formatter};
use std::sync::atomic::{AtomicUsize, ATOMIC_USIZE_INIT, Ordering};

pub struct SymbolTable {
    ident_map: HamtMap<String, u32>,
    id_map: HamtMap<u32, Record>,
}

impl SymbolTable {
    pub fn empty() -> Self {
        SymbolTable {
            ident_map: Default::default(),
            id_map: Default::default(),
        }
    }

    pub fn add_ident(&mut self, ident: String) -> Result<&Record, Box<Error>> {
        if let Some(record) = self.lookup_ident(&*ident) {
            let msg = format!("Error adding identifier {} to {:?}, that record already exists: \
                               {:#?}",
                              ident,
                              self,
                              record);
            return Err(msg.into());
        }

        let id = next_id();
        let record = Record {
            id: id,
            ident: ident.clone(),
        };

        self.ident_map = self.ident_map.clone().plus(ident, id);
        self.id_map = self.id_map.clone().plus(id, record);

        Ok(self.lookup_id(id).unwrap())
    }

    pub fn lookup_ident<T: Into<String>>(&self, ident: T) -> Option<&Record> {
        self.ident_map.find(&ident.into()).and_then(|&id| self.lookup_id(id))
    }

    pub fn lookup_id(&self, id: u32) -> Option<&Record> {
        self.id_map.find(&id)
    }

    // TODO tree api
    // probably leave it until it's needed (and thus requirements are known)
}

#[derive(Debug)]
pub struct Record {
    ident: String,
    id: u32,
}

impl Record {
    pub fn id(&self) -> u32 {
        self.id
    }

    pub fn ident(&self) -> &str {
        &*self.ident
    }
}

fn next_id() -> u32 {
    static COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;

    COUNTER.fetch_add(1, Ordering::SeqCst) as u32
}

impl Debug for SymbolTable {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        use std::cmp;

        let mut records = self.id_map.iter().map(|kv| kv.1).collect::<Vec<_>>();
        records.sort_by(|a, b| a.id().cmp(&b.id()));

        let id_size = cmp::max("id".len(),
                               records.last().map_or(0, |r| r.id().to_string().len()));
        let ident_size = cmp::max("ident".len(),
                                  records.iter().map(|r| r.ident().len()).max().unwrap_or(0));

        let fmt_record = |a: &Display, b: &Display| -> String {
            format!("| {:>2$} | {:>3$} |", a, b, id_size, ident_size)
        };

        let header = format!("| {:>2$} | {:>3$} |", "id", "ident", id_size, ident_size);
        let sep = format!("|-{0:->1$}-|-{0:->2$}-|", "", id_size, ident_size);

        try!(writeln!(f, "SymbolTable:"));
        try!(writeln!(f, "{}", header));
        try!(writeln!(f, "{}", sep));

        for r in records {
            try!(writeln!(f, "{}", fmt_record(&r.id(), &r.ident())))
        }

        Ok(())
    }
}

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

    #[test]
    fn pretty_print() {
        let pp = "SymbolTable:\n\
                  | id | ident |\n\
                  |----|-------|\n\
                  |  0 | hello |\n\
                  |  1 | world |\n\
                  |  2 |   how |\n\
                  |  3 |   are |\n\
                  |  4 |   you |\n";

        let mut st = SymbolTable::empty();

        for &i in &["hello", "world", "how", "are", "you"] {
            st.add_ident(i.into()).unwrap();
        }

        println!("\n{}\n\n", pp);
        println!("{:?}", st);

        assert_eq!(format!("{:?}", st), pp);
    }
}
<|endoftext|>


<commit_before><commit_msg>using string references in other places<commit_after><|endoftext|>


<commit_before><commit_msg>Draw Sprite<commit_after><|endoftext|>


<commit_before><commit_msg>Implement Clone for mio::event::Iter. (#687)<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor raise interrupt pattern a bit in VIP<commit_after><|endoftext|>


<commit_before><commit_msg>Outline of a client hello<commit_after>extern mod crypto;

enum ProtocolVersion {
    TlsVersion10 = 0x0301,
    TlsVersion11 = 0x0302,
    TlsVersion12 = 0x0303
}

struct Extension {

}

struct ClientHelloData {
    version: ProtocolVersion,
    random: ~[u8],
    session_id: ~[u8],
    ciphersuites: ~[u16],
    compression: ~[u8],
    extensions: ~[Extension]
}

impl ClientHelloData {

    static fn new(version: ProtocolVersion) -> ClientHelloData {
        let ch: ClientHelloData = ClientHelloData {
            version: version,
            random: crypto::rand::rand_bytes(16),
            session_id: ~[],
            ciphersuites: ~[],
            compression: ~[0u8]
        };

        ch
    }

    static fn deserialize(data: ~[u8]) -> ClientHelloData {
        let ch: ClientHelloData = ClientHelloData {
            version: TlsVersion12,
            random: crypto::rand::rand_bytes(16),
            session_id: ~[],
            ciphersuites: ~[],
            compression: ~[0u8]
        };

        ch

    }

    fn serialize(&self) -> ~[u8] {
        ~[]
    }
}

enum HandshakeMessage {
    ClientHello(ClientHelloData)
}

impl HandshakeMessage {

    fn serialize(&self) -> ~[u8] {
        match self {
            &ClientHello(ref data) => data.serialize()
        }
    }

    fn typecode(&self) -> u8 {
        match self {
            &ClientHello(_) => 1
        }
    }
}

fn main() {
    io::println("morning?");

    let ch = ClientHelloData::new(TlsVersion12);

    io::println(fmt!("%?", ch));

}
<|endoftext|>


<commit_before><commit_msg>Add `utils` tests<commit_after>extern crate rosc;

use std::net;

#[test]
fn test_parse_ip_and_port() {
    let valid_addr = "127.0.0.1:8080".to_string();
    let mut addr = rosc::utils::parse_ip_and_port(&valid_addr);
    assert!(addr.is_ok());
    let (ip, port) = addr.unwrap();
    assert_eq!(port, 8080u16);
    assert_eq!(ip, net::Ipv4Addr::new(127u8, 0u8, 0u8, 1u8));

    let bad_addr = "127..1:8080".to_string();
    addr = rosc::utils::parse_ip_and_port(&bad_addr);
    assert!(addr.is_err());

    let bad_addr_port = "192.168.0.10:99999".to_string();
    addr = rosc::utils::parse_ip_and_port(&bad_addr_port);
    assert!(addr.is_err());
}<|endoftext|>


<commit_before><commit_msg>Change directory error messages in test server.<commit_after><|endoftext|>


<commit_before><commit_msg>Add a simple decoder benchmark<commit_after>#![feature(test)]
extern crate test;
extern crate rosc;

use self::test::Bencher;

#[bench]
fn bench_decode(b: &mut Bencher) {
    // The message was captured from the `ytterbium` lemur patch looks like this:
    // OSC Bundle: OscBundle { timetag: Time(0, 1), content: [Message(OscMessage { addr: "/OSCILLATORS/OSC2/ADSR/x", args: Some([Float(0.1234567), Float(0.1234567), Float(0.1234567), Float(0.1234567)]) })] }
    let raw_msg: [u8; 72] = [35, 98, 117, 110, 100, 108, 101, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0,
                             52, 47, 79, 83, 67, 73, 76, 76, 65, 84, 79, 82, 83, 47, 79, 83, 67,
                             50, 47, 65, 68, 83, 82, 47, 122, 0, 0, 0, 0, 44, 102, 102, 102, 102,
                             0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    b.iter(|| rosc::decoder::decode(&raw_msg).unwrap());
}
<|endoftext|>


<commit_before><commit_msg>Get started with importing ethernet scheme to userspace<commit_after>use redox::Box;
use redox::fs::file::File;
use redox::io::{Read, Write, Seek, SeekFrom};
use redox::mem;
use redox::net::*;
use redox::ptr;
use redox::rand;
use redox::slice;
use redox::{str, String, ToString};
use redox::to_num::*;
use redox::Vec;

/// Ethernet resource
pub struct Resource {
    /// The network
    network: Box<Resource>,
    /// The data
    data: Vec<u8>,
    /// The MAC addresss
    peer_addr: MACAddr,
    /// The ethernet type
    ethertype: u16,
}

impl Resource {
    fn dup(&self) -> Option<Box<Self>> {
        match self.network.dup() {
            Some(network) => Some(box Resource {
                network: network,
                data: self.data.clone(),
                peer_addr: self.peer_addr,
                ethertype: self.ethertype,
            }),
            None => None
        }
    }

    pub fn path(&self, buf: &mut [u8]) -> Option<usize> {
        let path = format!("ethernet://{}/{}", self.peer_addr.to_string(), String::from_num_radix(self.ethertype as usize, 16));

        let mut i = 0;
        for b in path.bytes() {
            if i < buf.len() {
                buf[i] = b;
                i += 1;
            } else {
                break;
            }
        }

        Some(i)
    }

    fn read(&mut self, buf: &mut [u8]) -> Option<usize> {
        /*
        if self.data.len() > 0 {
            let mut bytes: Vec<u8> = Vec::new();
            swap(&mut self.data, &mut bytes);
            vec.push_all(&bytes);
            return Some(bytes.len());
        }

        loop {
            let mut bytes: Vec<u8> = Vec::new();
            match self.network.read_to_end(&mut bytes) {
                Some(_) => {
                    if let Some(frame) = EthernetII::from_bytes(bytes) {
                        if frame.header.ethertype.get() == self.ethertype &&
                           (unsafe { frame.header.dst.equals(MAC_ADDR) } ||
                            frame.header.dst.equals(BROADCAST_MAC_ADDR)) &&
                           (frame.header.src.equals(self.peer_addr) ||
                            self.peer_addr.equals(BROADCAST_MAC_ADDR)) {
                            vec.push_all(&frame.data);
                            return Some(frame.data.len());
                        }
                    }
                }
                None => return None,
            }
        }
        */
        None
    }

    fn write(&mut self, buf: &[u8]) -> Option<usize> {
        let data = Vec::from(buf);

        /*
        match self.network.write(EthernetII {
            header: EthernetIIHeader {
                src: unsafe { MAC_ADDR },
                dst: self.peer_addr,
                ethertype: n16::new(self.ethertype),
            },
            data: data,
        }.to_bytes().as_slice()) {
            Some(_) => return Some(buf.len()),
            None => return None,
        }
        */
        None
    }

    fn seek(&mut self, pos: SeekFrom) -> Option<usize> {
        None
    }

    fn sync(&mut self) -> bool {
        self.network.sync()
    }
}

pub struct Scheme;

impl Scheme {
    fn new() -> Box<Self> {
        box Scheme
    }

    fn open(&mut self, url: &str) -> Option<Box<Resource>> {
        //Split scheme from the rest of the URL
        let (scheme, mut not_scheme) = url.split_at(url.find(':').unwrap_or(url.len()));

        //Remove the starting two slashes
        if not_scheme.starts_with("//") {
            not_scheme = &not_scheme[2..not_scheme.len() - 2];
        }

        //Check host and port vs path
        if not_scheme.starts_with("/") {
            if let Some(mut network) = File::open("network://") {
                if url.path().len() > 0 {
                    let ethertype = url.path().to_num_radix(16) as u16;

                    if url.host().len() > 0 {
                        return Some(box Resource {
                            network: network,
                            data: Vec::new(),
                            peer_addr: MACAddr::from_string(&url.host()),
                            ethertype: ethertype,
                        });
                    } else {
                        loop {
                            let mut bytes: Vec<u8> = Vec::new();
                            match network.read_to_end(&mut bytes) {
                                Some(_) => {
                                    if let Some(frame) = EthernetII::from_bytes(bytes) {
                                        if frame.header.ethertype.get() == ethertype &&
                                           (unsafe { frame.header.dst.equals(MAC_ADDR) } ||
                                            frame.header.dst.equals(BROADCAST_MAC_ADDR)) {
                                            return Some(box Resource {
                                                network: network,
                                                data: frame.data,
                                                peer_addr: frame.header.src,
                                                ethertype: ethertype,
                                            });
                                        }
                                    }
                                }
                                None => break,
                            }
                        }
                    }
                } else {
                    /*
                    debug::d("Ethernet: No ethertype provided\n");
                    */
                }
            }
        }

        None
    }
}
<|endoftext|>


<commit_before><commit_msg>Add Rust support<commit_after>use std;

fn main(args: [str]) {
	std::io::println("Fuck you Mendez.");
}
<|endoftext|>


<commit_before><commit_msg>Added a benchmark for insert_or_update_document<commit_after>#![feature(test)]

#[macro_use]
extern crate maplit;
extern crate test;
extern crate kite;
extern crate kite_rocksdb;

use test::Bencher;
use std::fs::remove_dir_all;

use kite::term::Term;
use kite::token::Token;
use kite::schema::{FieldType, FIELD_INDEXED, FIELD_STORED};
use kite::document::{Document, FieldValue};

use kite_rocksdb::RocksDBIndexStore;

#[bench]
fn bench_insert_single_document(b: &mut Bencher) {
    remove_dir_all("test_indices/bench_insert_single_document");

    let mut store = RocksDBIndexStore::create("test_indices/bench_insert_single_document").unwrap();
    store.add_field("title".to_string(), FieldType::Text, FIELD_INDEXED).unwrap();
    store.add_field("body".to_string(), FieldType::Text, FIELD_INDEXED).unwrap();
    store.add_field("id".to_string(), FieldType::I64, FIELD_STORED).unwrap();

    let mut tokens = Vec::new();
    for t in 0..5000 {
        tokens.push(Token {
            term: Term::String(t.to_string()),
            position: t
        });
    }

    let mut i = 0;
    b.iter(|| {
        i += 1;

        store.insert_or_update_document(Document {
            key: i.to_string(),
            indexed_fields: hashmap! {
                "body".to_string() => tokens.clone(),
                "title".to_string() => vec![Token { term: Term::String(i.to_string()), position: 1}],
            },
            stored_fields: hashmap! {
                "id".to_string() => FieldValue::Integer(i),
            },
        });
    });
}
<|endoftext|>


<commit_before><commit_msg>am 708fd1a5: Merge "Make launchtestxlw use constant."<commit_after><|endoftext|>


<commit_before><commit_msg>Beginning of example take_mut implementation using noleak.<commit_after>extern crate noleak;

use noleak::{Lock, Acceptor, Handle};

pub struct HiddenHole<'t, T: 't> {
    filled: bool,
    mut_t: &'t mut T
}

impl<'t, T> Drop for HiddenHole<'t, T> {
    fn drop(&mut self) {
        println!("Dropping HiddenHole!");
        if !self.filled {
            panic!("Unfilled hole!");
        }
    }
}

pub struct Hole<'lock, 't: 'lock, T: 't> {
    hidden_hole: Handle<'lock, HiddenHole<'t, T>>,
}

impl<'lock, 't, T> Hole<'lock, 't, T> {
    fn fill(mut self, t: T) {
        use std::ptr;
        //let mut hidden_hole = self.hidden_hole;
        unsafe {
            ptr::write(&mut *self.hidden_hole.mut_t, t); // Compiler was complaining without the reborrow
        }
        self.hidden_hole.filled = true;
    }
}

pub fn take<'lock, 't: 'lock, T: 't>(acc: Acceptor<'lock, HiddenHole<'t, T>>, mut_t: &'t mut T) -> (T, Hole<'lock, 't, T>) {
    use std::ptr;
    let t = unsafe { ptr::read(mut_t) };
    let hidden_hole = HiddenHole {
        filled: false,
        mut_t: mut_t
    };
    let hole = Hole {
        hidden_hole: acc.fill(hidden_hole)
    };
    (t, hole)
}

fn main() {
}<|endoftext|>


<commit_before><commit_msg>Add test to deserialize unsigned int<commit_after>#![cfg(feature = "preserve_order")]

extern crate indexmap;

#[derive(serde::Deserialize, Eq, PartialEq, Debug)]
struct Container<T> {
    inner: T,
}

#[derive(serde::Deserialize, Eq, PartialEq, Debug)]
struct Unsigned {
    unsigned: u16,
}

impl Default for Unsigned {
    fn default() -> Self {
        Self { unsigned: 128 }
    }
}

impl From<Unsigned> for config::ValueKind {
    fn from(unsigned: Unsigned) -> Self {
        let mut properties = indexmap::IndexMap::new();
        properties.insert(
            "unsigned".to_string(),
            config::Value::from(unsigned.unsigned),
        );

        Self::Table(properties)
    }
}

#[test]
fn test_deser_unsigned_int() {
    let container = Container {
        inner: Unsigned::default(),
    };

    let built = config::Config::builder()
        .set_default("inner", Unsigned::default())
        .unwrap()
        .build()
        .unwrap()
        .try_deserialize::<Container<Unsigned>>()
        .unwrap();

    assert_eq!(container, built);
}
<|endoftext|>


<commit_before><commit_msg>Factor out login page rendering.<commit_after><|endoftext|>


<commit_before><commit_msg>Add FromPrimitive to a few enums, to allow casting from primitive types.<commit_after><|endoftext|>


<commit_before><commit_msg>More and more test<commit_after><|endoftext|>


<commit_before><commit_msg>Alright I'm done with Rust for this time around.<commit_after><|endoftext|>


<commit_before><commit_msg>fixed compilation error with InternedString<commit_after><|endoftext|>


<commit_before><commit_msg>Correct initial logic in matches_request_ctx.<commit_after><|endoftext|>


<commit_before><commit_msg>Modify scope of unsafe usage<commit_after><|endoftext|>


<commit_before><commit_msg>Mark RC4 struct and certain methods as public.<commit_after><|endoftext|>


<commit_before><commit_msg>let remove return element and fix pop<commit_after><|endoftext|>


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

#[deny(missing_docs)]

extern crate gfx;
extern crate gfx_device_gl;
extern crate glutin;

use gfx::tex::Size;

/// A wrapper around the window that implements `Output`.
pub struct Wrap<R: gfx::Resources> {
    /// Glutin window in the open.
    pub window: glutin::Window,
    frame: gfx::FrameBufferHandle<R>,
    mask: gfx::Mask,
    srgb: bool,
}

impl<R: gfx::Resources> gfx::Output<R> for Wrap<R> {
    fn get_handle(&self) -> Option<&gfx::FrameBufferHandle<R>> {
        Some(&self.frame)
    }

    fn get_size(&self) -> (Size, Size) {
        let (w, h) = self.window.get_inner_size().unwrap_or((0, 0));
        (w as Size, h as Size)
    }

    fn get_mask(&self) -> gfx::Mask {
        self.mask
    }

    fn does_convert_gamma(&self) -> bool {
        self.srgb
    }
}

/// Result of successful context initialization.
pub type Success = (
    Wrap<gfx_device_gl::Resources>,
    gfx_device_gl::Device,
    gfx_device_gl::Factory,
);

/// Initialize with a window builder.
pub fn init<'a>(builder: glutin::WindowBuilder<'a>)
            -> Result<Success, glutin::CreationError>
{
    let (mask, srgb) = {
        let attribs = builder.get_attributes();
        //let mut mask = gfx::Mask::empty(); // need Glutin to really expose defaults
        let mut mask = gfx::COLOR | gfx::DEPTH | gfx::STENCIL;
        match attribs.color_bits {
            Some(b) if b>0 => mask.insert(gfx::COLOR),
            _ => (),
        }
        match attribs.depth_bits {
            Some(b) if b>0 => mask.insert(gfx::DEPTH),
            _ => (),
        }
        match attribs.stencil_bits {
            Some(b) if b>0 => mask.insert(gfx::STENCIL),
            _ => (),
        }
        (mask, attribs.srgb == Some(true))
    };
    // create window
    builder.build().map(|window| {
        unsafe { window.make_current() };
        let (device, factory) = gfx_device_gl::create(|s| window.get_proc_address(s));
        let wrap = Wrap {
            window: window,
            frame: factory.get_main_frame_buffer(),
            mask: mask,
            srgb: srgb,
        };
        (wrap, device, factory)
    })
}

/// Initialize with just a title string.
pub fn init_titled(title: &str) -> Result<Success, glutin::CreationError>
{
    let builder = glutin::WindowBuilder::new()
        .with_title(title.to_string());
    init(builder)
}
<commit_msg>Refactored gamma usage<commit_after>// Copyright 2015 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.

#[deny(missing_docs)]

extern crate gfx;
extern crate gfx_device_gl;
extern crate glutin;

use gfx::tex::Size;

/// A wrapper around the window that implements `Output`.
pub struct Wrap<R: gfx::Resources> {
    /// Glutin window in the open.
    pub window: glutin::Window,
    frame: gfx::FrameBufferHandle<R>,
    mask: gfx::Mask,
    gamma: gfx::Gamma,
}

impl<R: gfx::Resources> gfx::Output<R> for Wrap<R> {
    fn get_handle(&self) -> Option<&gfx::FrameBufferHandle<R>> {
        Some(&self.frame)
    }

    fn get_size(&self) -> (Size, Size) {
        let (w, h) = self.window.get_inner_size().unwrap_or((0, 0));
        (w as Size, h as Size)
    }

    fn get_mask(&self) -> gfx::Mask {
        self.mask
    }

    fn get_gamma(&self) -> gfx::Gamma {
        self.gamma
    }
}

/// Result of successful context initialization.
pub type Success = (
    Wrap<gfx_device_gl::Resources>,
    gfx_device_gl::Device,
    gfx_device_gl::Factory,
);

/// Initialize with a window builder.
pub fn init<'a>(builder: glutin::WindowBuilder<'a>)
            -> Result<Success, glutin::CreationError>
{
    let (mask, srgb) = {
        let attribs = builder.get_attributes();
        //let mut mask = gfx::Mask::empty(); // need Glutin to really expose defaults
        let mut mask = gfx::COLOR | gfx::DEPTH | gfx::STENCIL;
        match attribs.color_bits {
            Some(b) if b>0 => mask.insert(gfx::COLOR),
            _ => (),
        }
        match attribs.depth_bits {
            Some(b) if b>0 => mask.insert(gfx::DEPTH),
            _ => (),
        }
        match attribs.stencil_bits {
            Some(b) if b>0 => mask.insert(gfx::STENCIL),
            _ => (),
        }
        (mask, attribs.srgb == Some(true))
    };
    // create window
    builder.build().map(|window| {
        unsafe { window.make_current() };
        let (device, factory) = gfx_device_gl::create(|s| window.get_proc_address(s));
        let wrap = Wrap {
            window: window,
            frame: factory.get_main_frame_buffer(),
            mask: mask,
            gamma: if srgb {gfx::Gamma::Convert} else {gfx::Gamma::Original},
        };
        (wrap, device, factory)
    })
}

/// Initialize with just a title string.
pub fn init_titled(title: &str) -> Result<Success, glutin::CreationError>
{
    let builder = glutin::WindowBuilder::new()
        .with_title(title.to_string());
    init(builder)
}
<|endoftext|>


<commit_before><commit_msg>Begin wrapper<commit_after><|endoftext|>


<commit_before><commit_msg>Make panic behave better<commit_after><|endoftext|>


<commit_before><commit_msg>Refactoring: better variable name<commit_after><|endoftext|>


<commit_before><commit_msg>Add constant USER_FORWARD_PAYLOAD_SIZE<commit_after><|endoftext|>


<commit_before><commit_msg>Only the refunc machine should be passed a stack<commit_after><|endoftext|>


<commit_before><commit_msg>Remove dnsrecord.rs<commit_after><|endoftext|>


<commit_before><commit_msg>added fibonacci sequence implementation<commit_after>// Implements http://rosettacode.org/wiki/Fibonacci_sequence
#[cfg(not(test))]
fn main() {
    let fns=vec![
        (fib_recursive, "recursive implementation"),
        (fib_tail_recursive, "tail recursive implementation"),
        (fib_iterative, "iterative implementation")];

    for (f, desc) in fns.move_iter() {
        let r: Vec<u64> = range(0u64, 10).map(|i| f(i)).collect();
        println!("{}:\n {}\n", desc, r);
    }
}

// Fibonacci "classic" recursive version
// not tail recursive (it's going to blow the stack
// for n too high
fn fib_recursive(n: u64) -> u64 {
    match n {
        n if n<2 => n,
        m => fib_recursive(m - 1) + fib_recursive(m-2)
    }
}

// tail recursive version
fn fib_tail_recursive(n: u64) -> u64 {
        fn in_fib(n : u64, current : u64, next : u64) -> u64 {
            match n {
                0 => current,
                _ => in_fib(n - 1, next, current + next)
            }
        }
        in_fib(n, 0, 1)
}

// iterative version
fn fib_iterative(n: u64) -> u64 {
    let (mut fib1, mut fib2) = (0u64, 1u64);
    let mut fib = n;

    for _ in range(1u64,n) {
        fib = fib1 + fib2;
        fib1 = fib2;
        fib2 = fib;
    }
    fib
}

#[cfg(test)]
fn tester(f: fn(u64)->u64) -> bool {
    let exp = [0u64,1,1,2,3,5,8,13,21,34];
    for i in range(0u, 10) {
        let ret=f(i as u64);
        assert_eq!(ret, exp[i]);
    }
    true
}

#[test]
fn fib_values() {
    let fns=vec![fib_recursive, fib_tail_recursive, fib_iterative];
    fns.move_iter()
        .advance(|f| tester(f));
}<|endoftext|>


<commit_before><commit_msg>Use an iterator for string_from_slice<commit_after><|endoftext|>


<commit_before><commit_msg>Use the count of incidents when scoring which edge to remove.<commit_after><|endoftext|>


<commit_before><commit_msg>Hope this will work.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix an extra comma and add unused flag in define_packet_set macro.<commit_after><|endoftext|>


<commit_before><commit_msg>20171107 start<commit_after><|endoftext|>


<commit_before><commit_msg>Add helloworld/rust<commit_after>fn main() {
    println!("helloworld");
}
<|endoftext|>


<commit_before><commit_msg>Cleaned up for tidy checks.<commit_after><|endoftext|>