<commit_before>extern crate inkwell;

use self::inkwell::attributes::Attribute;
use self::inkwell::context::Context;

use std::ffi::CString;

#[test]
fn test_enum_attribute_kinds() {
    // Does not exist:
    assert_eq!(Attribute::get_named_enum_kind_id("foo"), 0);
    assert_eq!(Attribute::get_named_enum_kind_id("bar"), 0);

    // Many of the values change and are not consistent across LLVM versions
    // so it only seems to make sense to test some consistent subset.
    // Otherwise it's not worth keeping track of. Users will have to
    // play around with it and determine which ones they are interested in
    // for their particular LLVM version

    // Function Attributes:
    assert_eq!(Attribute::get_named_enum_kind_id("allocsize"), 2);
    assert_eq!(Attribute::get_named_enum_kind_id("alwaysinline"), 3);
    assert_eq!(Attribute::get_named_enum_kind_id("argmemonly"), 4);
    assert_eq!(Attribute::get_named_enum_kind_id("builtin"), 5);
    assert_eq!(Attribute::get_named_enum_kind_id("cold"), 7);
    assert_eq!(Attribute::get_named_enum_kind_id("convergent"), 8);
    assert_eq!(Attribute::get_named_enum_kind_id("inaccessiblememonly"), 13);
    assert_eq!(Attribute::get_named_enum_kind_id("inaccessiblemem_or_argmemonly"), 14);
    assert_eq!(Attribute::get_named_enum_kind_id("inlinehint"), 15);
    assert_eq!(Attribute::get_named_enum_kind_id("jumptable"), 16);
    assert_eq!(Attribute::get_named_enum_kind_id("minsize"), 17);
    assert_eq!(Attribute::get_named_enum_kind_id("naked"), 18);
    assert_eq!(Attribute::get_named_enum_kind_id("nobuiltin"), 21);

    // REVIEW: The LLVM docs suggest these fn attrs exist, but don't turn up:
    // assert_eq!(Attribute::get_named_enum_kind_id("no-jump-tables"), 19);
    // assert_eq!(Attribute::get_named_enum_kind_id("null-pointer-is-valid"), 31);
    // assert_eq!(Attribute::get_named_enum_kind_id("optforfuzzing"), 32);
    // assert_eq!(Attribute::get_named_enum_kind_id("patchable-function"), 35);
    // assert_eq!(Attribute::get_named_enum_kind_id("probe-stack"), 36);
    // assert_eq!(Attribute::get_named_enum_kind_id("stack-probe-size"), 36);
    // assert_eq!(Attribute::get_named_enum_kind_id("no-stack-arg-probe"), 32);
    // assert_eq!(Attribute::get_named_enum_kind_id("thunk"), 45);
    // assert_eq!(Attribute::get_named_enum_kind_id("nocf_check"), 45);
    // assert_eq!(Attribute::get_named_enum_kind_id("shadowcallstack"), 45);

    // Parameter Attributes:
    assert_eq!(Attribute::get_named_enum_kind_id("align"), 1);
    assert_eq!(Attribute::get_named_enum_kind_id("byval"), 6);
    assert_eq!(Attribute::get_named_enum_kind_id("dereferenceable"), 9);
    assert_eq!(Attribute::get_named_enum_kind_id("dereferenceable_or_null"), 10);
    assert_eq!(Attribute::get_named_enum_kind_id("inalloca"), 11);
    assert_eq!(Attribute::get_named_enum_kind_id("inreg"), 12);
    assert_eq!(Attribute::get_named_enum_kind_id("nest"), 19);
    assert_eq!(Attribute::get_named_enum_kind_id("noalias"), 20);
    assert_eq!(Attribute::get_named_enum_kind_id("nocapture"), 22);
}

#[test]
fn test_enum_attributes() {
    let context = Context::create();
    let enum_attribute = context.create_enum_attribute(0, 10);

    assert!(enum_attribute.is_enum());
    assert!(!enum_attribute.is_string());

    assert_eq!(enum_attribute.get_enum_kind_id(), 0);
    assert_eq!(enum_attribute.get_enum_value(), 10);

    let enum_attribute2 = context.create_enum_attribute(3, 14);

    assert!(enum_attribute2.is_enum());
    assert!(!enum_attribute2.is_string());

    assert_eq!(enum_attribute2.get_enum_kind_id(), 3);
    assert_eq!(enum_attribute2.get_enum_value(), 14);

    let enum_attribute3 = context.create_enum_attribute(56, 20);

    assert!(enum_attribute3.is_enum());
    assert!(!enum_attribute3.is_string());

    assert_eq!(enum_attribute3.get_enum_kind_id(), 56);
    assert_eq!(enum_attribute3.get_enum_value(), 20);
}

#[test]
fn test_string_attributes() {
    let context = Context::create();
    let string_attribute = context.create_string_attribute("my_key_123", "my_val");

    assert!(!string_attribute.is_enum());
    assert!(string_attribute.is_string());

    assert_eq!(*string_attribute.get_string_kind_id(), *CString::new("my_key_123").unwrap());
    assert_eq!(*string_attribute.get_string_value(), *CString::new("my_val").unwrap());
}

#[test]
fn test_attributes_on_function_values() {
    let context = Context::create();
    let builder = context.create_builder();
    let module = context.create_module("my_mod");
    let void_type = context.void_type();
    let i32_type = context.i32_type();
    let fn_type = void_type.fn_type(&[i32_type.into()], false);
    let fn_value = module.add_function("my_fn", fn_type, None);
    let entry_bb = fn_value.append_basic_block("entry");
    let string_attribute = context.create_string_attribute("my_key", "my_val");
    let enum_attribute = context.create_enum_attribute(1, 1);

    builder.position_at_end(&entry_bb);
    builder.build_return(None);

    assert_eq!(fn_value.count_attributes(0), 0);
    assert_eq!(fn_value.count_attributes(1), 0);

    fn_value.remove_string_attribute(0, "my_key"); // Noop
    fn_value.remove_enum_attribute(0, 1); // Noop

    // define align 1 "my_key"="my_val" void @my_fn()
    fn_value.add_attribute(0, string_attribute);
    fn_value.add_attribute(1, string_attribute); // Applied to 1st param
    fn_value.add_attribute(0, enum_attribute);

    assert_eq!(fn_value.count_attributes(0), 2);
    assert_eq!(fn_value.get_enum_attribute(0, 1), Some(enum_attribute));
    assert_eq!(fn_value.get_string_attribute(0, "my_key"), Some(string_attribute));

    fn_value.remove_string_attribute(0, "my_key");

    assert_eq!(fn_value.count_attributes(0), 1);

    fn_value.remove_enum_attribute(0, 1);

    assert_eq!(fn_value.count_attributes(0), 0);
    assert!(fn_value.get_enum_attribute(0, 1).is_none());
    assert!(fn_value.get_string_attribute(0, "my_key").is_none());
}

#[test]
fn test_attributes_on_call_site_values() {
    let context = Context::create();
    let builder = context.create_builder();
    let module = context.create_module("my_mod");
    let void_type = context.void_type();
    let i32_type = context.i32_type();
    let fn_type = void_type.fn_type(&[i32_type.into()], false);
    let fn_value = module.add_function("my_fn", fn_type, None);
    let entry_bb = fn_value.append_basic_block("entry");
    let string_attribute = context.create_string_attribute("my_key", "my_val");
    let enum_attribute = context.create_enum_attribute(1, 1);

    builder.position_at_end(&entry_bb);

    let call_site_value = builder.build_call(fn_value, &[], "my_fn");

    builder.build_return(None);

    assert_eq!(call_site_value.count_arguments(), 0);
    assert_eq!(call_site_value.count_attributes(0), 0);
    assert_eq!(call_site_value.count_attributes(1), 0);

    call_site_value.remove_string_attribute(0, "my_key"); // Noop
    call_site_value.remove_enum_attribute(0, 1); // Noop

    // define align 1 "my_key"="my_val" void @my_fn()
    call_site_value.add_attribute(0, string_attribute);
    call_site_value.add_attribute(1, string_attribute); // Applied to 1st param
    call_site_value.add_attribute(0, enum_attribute);

    assert_eq!(call_site_value.count_attributes(0), 2);
    assert_eq!(call_site_value.get_enum_attribute(0, 1), Some(enum_attribute));
    assert_eq!(call_site_value.get_string_attribute(0, "my_key"), Some(string_attribute));

    call_site_value.remove_string_attribute(0, "my_key");

    assert_eq!(call_site_value.count_attributes(0), 1);

    call_site_value.remove_enum_attribute(0, 1);

    assert_eq!(call_site_value.count_attributes(0), 0);
    assert!(call_site_value.get_enum_attribute(0, 1).is_none());
    assert!(call_site_value.get_string_attribute(0, "my_key").is_none());
    assert_eq!(call_site_value.get_called_fn_value(), fn_value);

    call_site_value.set_param_alignment_attribute(0, 12);

    assert_eq!(call_site_value.count_attributes(0), 1);
    assert!(call_site_value.get_enum_attribute(0, 1).is_some());
}
<commit_msg>Use known int attribute 'alignstack' instead of attribute with id #1.<commit_after>extern crate inkwell;

use self::inkwell::attributes::Attribute;
use self::inkwell::context::Context;

use std::ffi::CString;

#[test]
fn test_enum_attribute_kinds() {
    // Does not exist:
    assert_eq!(Attribute::get_named_enum_kind_id("foo"), 0);
    assert_eq!(Attribute::get_named_enum_kind_id("bar"), 0);

    // Many of the values change and are not consistent across LLVM versions
    // so it only seems to make sense to test some consistent subset.
    // Otherwise it's not worth keeping track of. Users will have to
    // play around with it and determine which ones they are interested in
    // for their particular LLVM version

    // Function Attributes:
    assert_eq!(Attribute::get_named_enum_kind_id("allocsize"), 2);
    assert_eq!(Attribute::get_named_enum_kind_id("alwaysinline"), 3);
    assert_eq!(Attribute::get_named_enum_kind_id("argmemonly"), 4);
    assert_eq!(Attribute::get_named_enum_kind_id("builtin"), 5);
    assert_eq!(Attribute::get_named_enum_kind_id("cold"), 7);
    assert_eq!(Attribute::get_named_enum_kind_id("convergent"), 8);
    assert_eq!(Attribute::get_named_enum_kind_id("inaccessiblememonly"), 13);
    assert_eq!(Attribute::get_named_enum_kind_id("inaccessiblemem_or_argmemonly"), 14);
    assert_eq!(Attribute::get_named_enum_kind_id("inlinehint"), 15);
    assert_eq!(Attribute::get_named_enum_kind_id("jumptable"), 16);
    assert_eq!(Attribute::get_named_enum_kind_id("minsize"), 17);
    assert_eq!(Attribute::get_named_enum_kind_id("naked"), 18);
    assert_eq!(Attribute::get_named_enum_kind_id("nobuiltin"), 21);

    // REVIEW: The LLVM docs suggest these fn attrs exist, but don't turn up:
    // assert_eq!(Attribute::get_named_enum_kind_id("no-jump-tables"), 19);
    // assert_eq!(Attribute::get_named_enum_kind_id("null-pointer-is-valid"), 31);
    // assert_eq!(Attribute::get_named_enum_kind_id("optforfuzzing"), 32);
    // assert_eq!(Attribute::get_named_enum_kind_id("patchable-function"), 35);
    // assert_eq!(Attribute::get_named_enum_kind_id("probe-stack"), 36);
    // assert_eq!(Attribute::get_named_enum_kind_id("stack-probe-size"), 36);
    // assert_eq!(Attribute::get_named_enum_kind_id("no-stack-arg-probe"), 32);
    // assert_eq!(Attribute::get_named_enum_kind_id("thunk"), 45);
    // assert_eq!(Attribute::get_named_enum_kind_id("nocf_check"), 45);
    // assert_eq!(Attribute::get_named_enum_kind_id("shadowcallstack"), 45);

    // Parameter Attributes:
    assert_eq!(Attribute::get_named_enum_kind_id("align"), 1);
    assert_eq!(Attribute::get_named_enum_kind_id("byval"), 6);
    assert_eq!(Attribute::get_named_enum_kind_id("dereferenceable"), 9);
    assert_eq!(Attribute::get_named_enum_kind_id("dereferenceable_or_null"), 10);
    assert_eq!(Attribute::get_named_enum_kind_id("inalloca"), 11);
    assert_eq!(Attribute::get_named_enum_kind_id("inreg"), 12);
    assert_eq!(Attribute::get_named_enum_kind_id("nest"), 19);
    assert_eq!(Attribute::get_named_enum_kind_id("noalias"), 20);
    assert_eq!(Attribute::get_named_enum_kind_id("nocapture"), 22);
}

#[test]
fn test_enum_attributes() {
    let context = Context::create();
    let enum_attribute = context.create_enum_attribute(0, 10);

    assert!(enum_attribute.is_enum());
    assert!(!enum_attribute.is_string());

    assert_eq!(enum_attribute.get_enum_kind_id(), 0);
    assert_eq!(enum_attribute.get_enum_value(), 10);

    let enum_attribute2 = context.create_enum_attribute(3, 14);

    assert!(enum_attribute2.is_enum());
    assert!(!enum_attribute2.is_string());

    assert_eq!(enum_attribute2.get_enum_kind_id(), 3);
    assert_eq!(enum_attribute2.get_enum_value(), 14);

    let enum_attribute3 = context.create_enum_attribute(56, 20);

    assert!(enum_attribute3.is_enum());
    assert!(!enum_attribute3.is_string());

    assert_eq!(enum_attribute3.get_enum_kind_id(), 56);
    assert_eq!(enum_attribute3.get_enum_value(), 20);
}

#[test]
fn test_string_attributes() {
    let context = Context::create();
    let string_attribute = context.create_string_attribute("my_key_123", "my_val");

    assert!(!string_attribute.is_enum());
    assert!(string_attribute.is_string());

    assert_eq!(*string_attribute.get_string_kind_id(), *CString::new("my_key_123").unwrap());
    assert_eq!(*string_attribute.get_string_value(), *CString::new("my_val").unwrap());
}

#[test]
fn test_attributes_on_function_values() {
    let context = Context::create();
    let builder = context.create_builder();
    let module = context.create_module("my_mod");
    let void_type = context.void_type();
    let i32_type = context.i32_type();
    let fn_type = void_type.fn_type(&[i32_type.into()], false);
    let fn_value = module.add_function("my_fn", fn_type, None);
    let entry_bb = fn_value.append_basic_block("entry");
    let string_attribute = context.create_string_attribute("my_key", "my_val");
    let alignstack_attribute = Attribute::get_named_enum_kind_id("alignstack");
    let enum_attribute = context.create_enum_attribute(alignstack_attribute, 1);

    builder.position_at_end(&entry_bb);
    builder.build_return(None);

    assert_eq!(fn_value.count_attributes(0), 0);
    assert_eq!(fn_value.count_attributes(1), 0);

    fn_value.remove_string_attribute(0, "my_key"); // Noop
    fn_value.remove_enum_attribute(0, alignstack_attribute); // Noop

    // define align 1 "my_key"="my_val" void @my_fn()
    fn_value.add_attribute(0, string_attribute);
    fn_value.add_attribute(1, string_attribute); // Applied to 1st param
    fn_value.add_attribute(0, enum_attribute);

    assert_eq!(fn_value.count_attributes(0), 2);
    assert_eq!(fn_value.get_enum_attribute(0, alignstack_attribute), Some(enum_attribute));
    assert_eq!(fn_value.get_string_attribute(0, "my_key"), Some(string_attribute));

    fn_value.remove_string_attribute(0, "my_key");

    assert_eq!(fn_value.count_attributes(0), 1);

    fn_value.remove_enum_attribute(0, alignstack_attribute);

    assert_eq!(fn_value.count_attributes(0), 0);
    assert!(fn_value.get_enum_attribute(0, alignstack_attribute).is_none());
    assert!(fn_value.get_string_attribute(0, "my_key").is_none());
}

#[test]
fn test_attributes_on_call_site_values() {
    let context = Context::create();
    let builder = context.create_builder();
    let module = context.create_module("my_mod");
    let void_type = context.void_type();
    let i32_type = context.i32_type();
    let fn_type = void_type.fn_type(&[i32_type.into()], false);
    let fn_value = module.add_function("my_fn", fn_type, None);
    let entry_bb = fn_value.append_basic_block("entry");
    let string_attribute = context.create_string_attribute("my_key", "my_val");
    let alignstack_attribute = Attribute::get_named_enum_kind_id("alignstack");
    let enum_attribute = context.create_enum_attribute(alignstack_attribute, 1);

    builder.position_at_end(&entry_bb);

    let call_site_value = builder.build_call(fn_value, &[], "my_fn");

    builder.build_return(None);

    assert_eq!(call_site_value.count_arguments(), 0);
    assert_eq!(call_site_value.count_attributes(0), 0);
    assert_eq!(call_site_value.count_attributes(1), 0);

    call_site_value.remove_string_attribute(0, "my_key"); // Noop
    call_site_value.remove_enum_attribute(0, alignstack_attribute); // Noop

    // define align 1 "my_key"="my_val" void @my_fn()
    call_site_value.add_attribute(0, string_attribute);
    call_site_value.add_attribute(1, string_attribute); // Applied to 1st param
    call_site_value.add_attribute(0, enum_attribute);

    assert_eq!(call_site_value.count_attributes(0), 2);
    assert_eq!(call_site_value.get_enum_attribute(0, alignstack_attribute), Some(enum_attribute));
    assert_eq!(call_site_value.get_string_attribute(0, "my_key"), Some(string_attribute));

    call_site_value.remove_string_attribute(0, "my_key");

    assert_eq!(call_site_value.count_attributes(0), 1);

    call_site_value.remove_enum_attribute(0, alignstack_attribute);

    assert_eq!(call_site_value.count_attributes(0), 0);
    assert!(call_site_value.get_enum_attribute(0, alignstack_attribute).is_none());
    assert!(call_site_value.get_string_attribute(0, "my_key").is_none());
    assert_eq!(call_site_value.get_called_fn_value(), fn_value);

    call_site_value.set_param_alignment_attribute(0, 16);

    assert_eq!(call_site_value.count_attributes(0), 1);
    assert!(call_site_value.get_enum_attribute(0, 1).is_some());
}
<|endoftext|>


<commit_before>import stb_image::*;
import stb_image::bindgen::*;
import libc::types::os::arch::c95::c_int;
import ptr::{addr_of, is_null};
import str::as_c_str;
import vec::as_buf;
import vec::unsafe::from_buf;

class image {
    let width: uint;
    let height: uint;
    let depth: uint;
    let data: ~[u8];

    new(width: uint, height: uint, depth: uint, -data: ~[u8]) {
        self.width = width;
        self.height = height;
        self.depth = depth;
        self.data = data;
    }
}

fn load(path: ~str) -> option<image> unsafe {
    let mut width = 0 as c_int;
    let mut height = 0 as c_int;
    let mut depth = 0 as c_int;
    let buffer = as_c_str(path, |bytes| {
        stbi_load(bytes, addr_of(width), addr_of(height), addr_of(depth), 0 as c_int)
    });
    if is_null(buffer) {
        return none;
    }

    // FIXME: Shouldn't copy; instead we should use a sendable resource. They
    // aren't particularly safe yet though.
    let data = from_buf(buffer, (width * height * depth) as uint);
    return some(image(width as uint, height as uint, depth as uint, data));
}

fn load_from_memory(buffer: &[u8]) -> option<image> unsafe {
    let mut width = 0 as c_int;
    let mut height = 0 as c_int;
    let mut depth = 0 as c_int;
    let buffer = as_buf(buffer, |bytes, len| {
        stbi_load_from_memory(bytes, len as c_int, addr_of(width), addr_of(height), addr_of(depth), 0 as c_int)
    });
    if is_null(buffer) {
        return none;
    }

    // FIXME: Shouldn't copy; instead we should use a sendable resource. They
    // aren't particularly safe yet though.
    let data = from_buf(buffer, (width * height * depth) as uint);
    return some(image(width as uint, height as uint, depth as uint, data));
}
<commit_msg>s/class/struct/g<commit_after>import stb_image::*;
import stb_image::bindgen::*;
import libc::types::os::arch::c95::c_int;
import ptr::{addr_of, is_null};
import str::as_c_str;
import vec::as_buf;
import vec::unsafe::from_buf;

struct image {
    let width: uint;
    let height: uint;
    let depth: uint;
    let data: ~[u8];

    new(width: uint, height: uint, depth: uint, -data: ~[u8]) {
        self.width = width;
        self.height = height;
        self.depth = depth;
        self.data = data;
    }
}

fn load(path: ~str) -> option<image> unsafe {
    let mut width = 0 as c_int;
    let mut height = 0 as c_int;
    let mut depth = 0 as c_int;
    let buffer = as_c_str(path, |bytes| {
        stbi_load(bytes, addr_of(width), addr_of(height), addr_of(depth), 0 as c_int)
    });
    if is_null(buffer) {
        return none;
    }

    // FIXME: Shouldn't copy; instead we should use a sendable resource. They
    // aren't particularly safe yet though.
    let data = from_buf(buffer, (width * height * depth) as uint);
    return some(image(width as uint, height as uint, depth as uint, data));
}

fn load_from_memory(buffer: &[u8]) -> option<image> unsafe {
    let mut width = 0 as c_int;
    let mut height = 0 as c_int;
    let mut depth = 0 as c_int;
    let buffer = as_buf(buffer, |bytes, len| {
        stbi_load_from_memory(bytes, len as c_int, addr_of(width), addr_of(height), addr_of(depth), 0 as c_int)
    });
    if is_null(buffer) {
        return none;
    }

    // FIXME: Shouldn't copy; instead we should use a sendable resource. They
    // aren't particularly safe yet though.
    let data = from_buf(buffer, (width * height * depth) as uint);
    return some(image(width as uint, height as uint, depth as uint, data));
}
<|endoftext|>


<commit_before>use std::mem;
use utils::{GenerationalId, IdAllocator};
use shape::FeatureId;
use math::{Isometry, Point};

use na::{self, Real, Unit};

/// Geometric description of a contact.
#[derive(Debug, PartialEq, Clone)]
pub struct Contact<P: Point> {
    /// Position of the contact on the first object. The position is expressed in world space.
    pub world1: P,

    /// Position of the contact on the second object. The position is expressed in world space.
    pub world2: P,

    /// Contact normal
    pub normal: Unit<P::Vector>,

    /// Penetration depth
    pub depth: P::Real,
}

impl<P: Point> Contact<P> {
    /// Creates a new contact.
    #[inline]
    pub fn new(world1: P, world2: P, normal: Unit<P::Vector>, depth: P::Real) -> Contact<P> {
        Contact {
            world1: world1,
            world2: world2,
            normal: normal,
            depth: depth,
        }
    }
}

impl<P: Point> Contact<P> {
    /// Reverts the contact normal and swaps `world1` and `world2`.
    #[inline]
    pub fn flip(&mut self) {
        mem::swap(&mut self.world1, &mut self.world2);
        self.normal = -self.normal;
    }
}

#[derive(Clone, Debug)]
pub enum ContactKinematic<V> {
    PlanePoint,
    PointPlane,
    PointPoint,
    PointLine(Unit<V>),
    LinePoint(Unit<V>),
    LineLine(Unit<V>, Unit<V>),
    Unknown,
}

#[derive(Clone, Debug)]
pub struct TrackedContact<P: Point> {
    pub contact: Contact<P>,

    /// The contact location in the local space of the first object.
    pub local1: P,

    /// The contact location in the local space of the second object.
    pub local2: P,

    /// The contact normal in the local space of the first object.
    pub normal1: Unit<P::Vector>,

    /// The contact normal in the local space of the second object.
    pub normal2: Unit<P::Vector>,

    pub feature1: FeatureId,
    pub feature2: FeatureId,
    pub kinematic: ContactKinematic<P::Vector>,
    pub id: GenerationalId,
}

impl<P: Point> TrackedContact<P> {
    pub fn new(
        contact: Contact<P>,
        local1: P,
        local2: P,
        normal1: Unit<P::Vector>,
        normal2: Unit<P::Vector>,
        feature1: FeatureId,
        feature2: FeatureId,
        kinematic: ContactKinematic<P::Vector>,
        id: GenerationalId,
    ) -> Self {
        TrackedContact {
            contact,
            local1,
            local2,
            normal1,
            normal2,
            feature1,
            feature2,
            kinematic,
            id,
        }
    }

    pub fn new_with_transforms<M: Isometry<P>>(
        m1: &M,
        m2: &M,
        contact: Contact<P>,
        feature1: FeatureId,
        feature2: FeatureId,
        kinematic: ContactKinematic<P::Vector>,
        id: GenerationalId,
    ) -> Self {
        let local1 = m1.inverse_transform_point(&contact.world1);
        let local2 = m2.inverse_transform_point(&contact.world2);
        let normal1 = Unit::new_unchecked(m1.inverse_transform_vector(&*contact.normal));
        let normal2 = Unit::new_unchecked(m2.inverse_transform_vector(&-*contact.normal));

        Self::new(
            contact,
            local1,
            local2,
            normal1,
            normal2,
            feature1,
            feature2,
            kinematic,
            id,
        )
    }
}

/// The prediction parameters for contact determination.n
pub struct ContactPrediction<N: Real> {
    /// The linear prediction.
    pub linear: N,
    /// The angular regularization for the first solid.
    pub angular1: N,
    /// The angular regularization for the second solid.
    pub angular2: N,
}

impl<N: Real> ContactPrediction<N> {
    /// Initialize prediction parameters.
    pub fn new(linear: N, angular1: N, angular2: N) -> Self {
        ContactPrediction {
            linear,
            angular1,
            angular2,
        }
    }
}

#[derive(Clone, Debug)]
pub struct ContactManifold<P: Point> {
    deepest: usize,
    contacts: Vec<TrackedContact<P>>,
    cache: Vec<TrackedContact<P>>,
    cached_contact_used: Vec<Option<usize>>,
}

impl<P: Point> ContactManifold<P> {
    pub fn new() -> Self {
        ContactManifold {
            deepest: 0,
            contacts: Vec::new(),
            cache: Vec::new(),
            cached_contact_used: Vec::new(),
        }
    }

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

    pub fn contacts(&self) -> &[TrackedContact<P>] {
        &self.contacts[..]
    }

    pub fn deepest_contact(&self) -> &TrackedContact<P> {
        &self.contacts[self.deepest]
    }

    pub fn save_cache_and_clear(&mut self, gen: &mut IdAllocator) {
        for (valid, c) in self.cached_contact_used.iter().zip(self.cache.iter()) {
            if !valid.is_some() {
                gen.free(c.id)
            }
        }

        mem::swap(&mut self.contacts, &mut self.cache);

        for val in &mut self.cached_contact_used {
            *val = None;
        }

        self.cached_contact_used.resize(self.cache.len(), None);
        self.contacts.clear();
        self.deepest = 0;
    }

    pub fn push<M: Isometry<P>>(
        &mut self,
        m1: &M,
        m2: &M,
        contact: Contact<P>,
        feature1: FeatureId,
        feature2: FeatureId,
        gen: &mut IdAllocator,
    ) -> bool {
        let local1 = m1.inverse_transform_point(&contact.world1);
        let mut closest = GenerationalId::invalid();
        let mut closest_i = 0;
        let mut closest_is_contact = false;
        let mut closest_dist: P::Real = na::convert(0.02 * 0.02); // FIXME: don't hard-code this.

        for i in 0..self.cache.len() {
            /*if !self.cached_contact_used[i] && self.cache[i].feature1 == feature1
                && self.cache[i].feature2 == feature2*/

            let dist = na::distance_squared(&local1, &self.cache[i].local1);
            if dist < closest_dist {
                closest_dist = dist;
                closest = self.cache[i].id;
                closest_i = i;
            }
        }

        for i in 0..self.contacts.len() {
            /*if !self.cached_contact_used[i] && self.cache[i].feature1 == feature1
                && self.cache[i].feature2 == feature2*/

            let dist = na::distance_squared(&local1, &self.contacts[i].local1);
            if dist < closest_dist {
                closest_is_contact = true;
                closest_dist = dist;
                closest = self.contacts[i].id;
                closest_i = i;
            }
        }

        let is_deepest =
            self.contacts.len() == 0 || contact.depth > self.contacts[self.deepest].contact.depth;

        let kinematic = ContactKinematic::Unknown;
        let mut matched = false;
        if closest.is_invalid() {
            closest = gen.alloc();
        } else {
            if closest_is_contact {
                self.contacts[closest_i] = TrackedContact::new_with_transforms(
                    m1,
                    m2,
                    contact,
                    feature1,
                    feature2,
                    kinematic,
                    closest,
                );
                if is_deepest {
                    self.deepest = closest_i;
                }
                return false;
            }
            if let Some(used_i) = self.cached_contact_used[closest_i] {
                self.contacts[used_i] = TrackedContact::new_with_transforms(
                    m1,
                    m2,
                    contact,
                    feature1,
                    feature2,
                    kinematic,
                    closest,
                );

                if is_deepest {
                    self.deepest = used_i;
                }
                return false;
            } else {
                self.cached_contact_used[closest_i] = Some(self.contacts.len());
                matched = true;
            }
        }

        if is_deepest {
            self.deepest = self.contacts.len();
        }
        let tracked = TrackedContact::new_with_transforms(
            m1,
            m2,
            contact,
            feature1,
            feature2,
            kinematic,
            closest,
        );
        self.contacts.push(tracked);
        return matched;
    }
    /*
    pub fn push<M: Isometry<P>>(
        &mut self,
        m1: &M,
        m2: &M,
        contact: Contact<P>,
        feature1: FeatureId,
        feature2: FeatureId,
        gen: &mut IdAllocator,
    ) {
        let mut id = GenerationalId::invalid();

        for i in 0..self.cache.len() {
            if self.cached_contact_used[i].is_none() && self.cache[i].feature1 == feature1
                && self.cache[i].feature2 == feature2
            {
                self.cached_contact_used[i] = Some(self.contacts.len());
                id = self.cache[i].id;
            }
        }

        if id.is_invalid() {
            id = gen.alloc();
        }

        let tracked = TrackedContact::new_with_transforms(m1, m2, contact, feature1, feature2, id);
        self.contacts.push(tracked)
    }*/
}
<commit_msg>Make ContactKinematic Copy-able.<commit_after>use std::mem;
use utils::{GenerationalId, IdAllocator};
use shape::FeatureId;
use math::{Isometry, Point};

use na::{self, Real, Unit};

/// Geometric description of a contact.
#[derive(Debug, PartialEq, Clone)]
pub struct Contact<P: Point> {
    /// Position of the contact on the first object. The position is expressed in world space.
    pub world1: P,

    /// Position of the contact on the second object. The position is expressed in world space.
    pub world2: P,

    /// Contact normal
    pub normal: Unit<P::Vector>,

    /// Penetration depth
    pub depth: P::Real,
}

impl<P: Point> Contact<P> {
    /// Creates a new contact.
    #[inline]
    pub fn new(world1: P, world2: P, normal: Unit<P::Vector>, depth: P::Real) -> Contact<P> {
        Contact {
            world1: world1,
            world2: world2,
            normal: normal,
            depth: depth,
        }
    }
}

impl<P: Point> Contact<P> {
    /// Reverts the contact normal and swaps `world1` and `world2`.
    #[inline]
    pub fn flip(&mut self) {
        mem::swap(&mut self.world1, &mut self.world2);
        self.normal = -self.normal;
    }
}

#[derive(Copy, Clone, Debug)]
pub enum ContactKinematic<V> {
    PlanePoint,
    PointPlane,
    PointPoint,
    PointLine(Unit<V>),
    LinePoint(Unit<V>),
    LineLine(Unit<V>, Unit<V>),
    Unknown,
}

#[derive(Clone, Debug)]
pub struct TrackedContact<P: Point> {
    pub contact: Contact<P>,

    /// The contact location in the local space of the first object.
    pub local1: P,

    /// The contact location in the local space of the second object.
    pub local2: P,

    /// The contact normal in the local space of the first object.
    pub normal1: Unit<P::Vector>,

    /// The contact normal in the local space of the second object.
    pub normal2: Unit<P::Vector>,

    pub feature1: FeatureId,
    pub feature2: FeatureId,
    pub kinematic: ContactKinematic<P::Vector>,
    pub id: GenerationalId,
}

impl<P: Point> TrackedContact<P> {
    pub fn new(
        contact: Contact<P>,
        local1: P,
        local2: P,
        normal1: Unit<P::Vector>,
        normal2: Unit<P::Vector>,
        feature1: FeatureId,
        feature2: FeatureId,
        kinematic: ContactKinematic<P::Vector>,
        id: GenerationalId,
    ) -> Self {
        TrackedContact {
            contact,
            local1,
            local2,
            normal1,
            normal2,
            feature1,
            feature2,
            kinematic,
            id,
        }
    }

    pub fn new_with_transforms<M: Isometry<P>>(
        m1: &M,
        m2: &M,
        contact: Contact<P>,
        feature1: FeatureId,
        feature2: FeatureId,
        kinematic: ContactKinematic<P::Vector>,
        id: GenerationalId,
    ) -> Self {
        let local1 = m1.inverse_transform_point(&contact.world1);
        let local2 = m2.inverse_transform_point(&contact.world2);
        let normal1 = Unit::new_unchecked(m1.inverse_transform_vector(&*contact.normal));
        let normal2 = Unit::new_unchecked(m2.inverse_transform_vector(&-*contact.normal));

        Self::new(
            contact,
            local1,
            local2,
            normal1,
            normal2,
            feature1,
            feature2,
            kinematic,
            id,
        )
    }
}

/// The prediction parameters for contact determination.n
pub struct ContactPrediction<N: Real> {
    /// The linear prediction.
    pub linear: N,
    /// The angular regularization for the first solid.
    pub angular1: N,
    /// The angular regularization for the second solid.
    pub angular2: N,
}

impl<N: Real> ContactPrediction<N> {
    /// Initialize prediction parameters.
    pub fn new(linear: N, angular1: N, angular2: N) -> Self {
        ContactPrediction {
            linear,
            angular1,
            angular2,
        }
    }
}

#[derive(Clone, Debug)]
pub struct ContactManifold<P: Point> {
    deepest: usize,
    contacts: Vec<TrackedContact<P>>,
    cache: Vec<TrackedContact<P>>,
    cached_contact_used: Vec<Option<usize>>,
}

impl<P: Point> ContactManifold<P> {
    pub fn new() -> Self {
        ContactManifold {
            deepest: 0,
            contacts: Vec::new(),
            cache: Vec::new(),
            cached_contact_used: Vec::new(),
        }
    }

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

    pub fn contacts(&self) -> &[TrackedContact<P>] {
        &self.contacts[..]
    }

    pub fn deepest_contact(&self) -> &TrackedContact<P> {
        &self.contacts[self.deepest]
    }

    pub fn save_cache_and_clear(&mut self, gen: &mut IdAllocator) {
        for (valid, c) in self.cached_contact_used.iter().zip(self.cache.iter()) {
            if !valid.is_some() {
                gen.free(c.id)
            }
        }

        mem::swap(&mut self.contacts, &mut self.cache);

        for val in &mut self.cached_contact_used {
            *val = None;
        }

        self.cached_contact_used.resize(self.cache.len(), None);
        self.contacts.clear();
        self.deepest = 0;
    }

    pub fn push<M: Isometry<P>>(
        &mut self,
        m1: &M,
        m2: &M,
        contact: Contact<P>,
        feature1: FeatureId,
        feature2: FeatureId,
        gen: &mut IdAllocator,
    ) -> bool {
        let local1 = m1.inverse_transform_point(&contact.world1);
        let mut closest = GenerationalId::invalid();
        let mut closest_i = 0;
        let mut closest_is_contact = false;
        let mut closest_dist: P::Real = na::convert(0.02 * 0.02); // FIXME: don't hard-code this.

        for i in 0..self.cache.len() {
            /*if !self.cached_contact_used[i] && self.cache[i].feature1 == feature1
                && self.cache[i].feature2 == feature2*/

            let dist = na::distance_squared(&local1, &self.cache[i].local1);
            if dist < closest_dist {
                closest_dist = dist;
                closest = self.cache[i].id;
                closest_i = i;
            }
        }

        for i in 0..self.contacts.len() {
            /*if !self.cached_contact_used[i] && self.cache[i].feature1 == feature1
                && self.cache[i].feature2 == feature2*/

            let dist = na::distance_squared(&local1, &self.contacts[i].local1);
            if dist < closest_dist {
                closest_is_contact = true;
                closest_dist = dist;
                closest = self.contacts[i].id;
                closest_i = i;
            }
        }

        let is_deepest =
            self.contacts.len() == 0 || contact.depth > self.contacts[self.deepest].contact.depth;

        let kinematic = ContactKinematic::Unknown;
        let mut matched = false;
        if closest.is_invalid() {
            closest = gen.alloc();
        } else {
            if closest_is_contact {
                self.contacts[closest_i] = TrackedContact::new_with_transforms(
                    m1,
                    m2,
                    contact,
                    feature1,
                    feature2,
                    kinematic,
                    closest,
                );
                if is_deepest {
                    self.deepest = closest_i;
                }
                return false;
            }
            if let Some(used_i) = self.cached_contact_used[closest_i] {
                self.contacts[used_i] = TrackedContact::new_with_transforms(
                    m1,
                    m2,
                    contact,
                    feature1,
                    feature2,
                    kinematic,
                    closest,
                );

                if is_deepest {
                    self.deepest = used_i;
                }
                return false;
            } else {
                self.cached_contact_used[closest_i] = Some(self.contacts.len());
                matched = true;
            }
        }

        if is_deepest {
            self.deepest = self.contacts.len();
        }
        let tracked = TrackedContact::new_with_transforms(
            m1,
            m2,
            contact,
            feature1,
            feature2,
            kinematic,
            closest,
        );
        self.contacts.push(tracked);
        return matched;
    }
    /*
    pub fn push<M: Isometry<P>>(
        &mut self,
        m1: &M,
        m2: &M,
        contact: Contact<P>,
        feature1: FeatureId,
        feature2: FeatureId,
        gen: &mut IdAllocator,
    ) {
        let mut id = GenerationalId::invalid();

        for i in 0..self.cache.len() {
            if self.cached_contact_used[i].is_none() && self.cache[i].feature1 == feature1
                && self.cache[i].feature2 == feature2
            {
                self.cached_contact_used[i] = Some(self.contacts.len());
                id = self.cache[i].id;
            }
        }

        if id.is_invalid() {
            id = gen.alloc();
        }

        let tracked = TrackedContact::new_with_transforms(m1, m2, contact, feature1, feature2, id);
        self.contacts.push(tracked)
    }*/
}
<|endoftext|>


<commit_before>use simplepattern::ParameterDictionary;
use simplepattern::SimplePattern;
use simplepattern::PatternMatcher;

pub struct HttpContext{
    request: Request,
    response: Response,
}

impl HttpContext{
}

pub struct Request {
    path: ~str,
    querystring: ~str
}

pub struct Response{
    contenttype: ~str,
    body: ~str
}

impl Response{
    pub fn new() -> Response{
        Response{contenttype: ~"text/html", body: ~""}
    }
}

pub struct Route {
    matcher: ~PatternMatcher:Freeze+Send,
    handler: ~fn:Send+Freeze(&mut ControllerContext)
}

pub struct Router{
    routes: ~[Route],
}

impl Router{
    pub fn new() -> Router{
        Router{routes: ~[]}
    }
    pub fn add(&mut self, r: ~Route){
        self.routes.push(*r);
    }
    pub fn execute(&self, c: &mut HttpContext) {
        for route in self.routes.iter(){
            let res=route.matcher.matches(c.request.path);

            if(res.is_match){
                (route.handler)(&mut ControllerContext{http: c, router: self, route_params: res.params});
                return;
            }
        }
        default_handler(&mut ControllerContext{http: c, router: self, route_params: ParameterDictionary::new()});
    }
    pub fn controller<'r,T>(&'r mut self, creator: ~fn:Send+Freeze(&mut ControllerContext) -> T) -> ControllerBox<'r,T>
    {
        ControllerBox{
            router: self,
            path: ~"",
            creator: Some(creator)
        }
    }
}

pub struct ControllerContext<'self>
{
    http: &'self mut HttpContext,
    router: &'self Router,
    route_params: ParameterDictionary
}

pub trait HttpController{

}

pub struct ControllerBox<'self,T>{
    router: &'self mut Router,
    path: ~str,
    creator: Option<~fn:Send+Freeze(&mut ControllerContext) -> T>
}

impl<'self,T> ControllerBox<'self,T>{
    pub fn handles(&'self mut self, path: ~str) -> &'self mut ControllerBox<'self,T>{
        self.path=path;
        self
    }
    pub fn with(&'self mut self, invoker: ~fn:Send+Freeze(&mut T, &mut ControllerContext)) -> &'self mut ControllerBox<'self,T>{
        let tmp=self.creator.take();

        self.router.add(~Route{matcher: ~SimplePattern::new(self.path) as ~PatternMatcher:Freeze+Send, handler: |c| {
            match tmp {
                None => (),
                Some(ref t) => {
                    let mut ctrl=(*t)(c);
                    invoker(&mut ctrl, c);
                }
            };
        }});
        self
    }
}
/*
struct Meh{
    biz: ~fn(int) -> int
}

impl Meh{
    fn foo(@mut self
}
*/
/*
struct TestController;

impl TestController{
    fn new() -> TestController{
    TestController
    }
    fn index(&mut self, context: &mut ControllerContext) {
        context.http.response.body.push_str("test index");
    }
    fn say(&mut self, context: &mut ControllerContext) {
        context.http.response.body.push_str(context.route_params[~"message"]);
    }
}
*/

fn default_handler(context: &mut ControllerContext){
    context.http.response.body.push_str("404 not found");
}
/*
fn main() {
    let mut context=HttpContext::create();
    let mut router=Router::new();
    {
        let mut test = router.controller(|_| TestController::new());
        test.handles(~"/test").with(|c,ctx| c.index(ctx));
    }
    {
        let mut test = router.controller(|_| TestController::new());
        test.handles(~"/say/[message]").with(|c,ctx| c.say(ctx));
    }

    router.execute(&mut context);

    println(context.response.contenttype);
    println("");
    println(context.response.body);
}
*/
<commit_msg>well, no lifetime errors now at least<commit_after>use simplepattern::ParameterDictionary;
use simplepattern::SimplePattern;
use simplepattern::PatternMatcher;

pub struct HttpContext{
    request: Request,
    response: Response,
}

impl HttpContext{
}

pub struct Request {
    path: ~str,
    querystring: ~str
}

pub struct Response{
    contenttype: ~str,
    body: ~str
}

impl Response{
    pub fn new() -> Response{
        Response{contenttype: ~"text/html", body: ~""}
    }
}

pub struct Route {
    matcher: ~PatternMatcher:Freeze+Send,
    handler: ~fn:Send+Freeze(&mut ControllerContext)
}

pub struct Router{
    routes: ~[Route],
}

impl Router{
    pub fn new() -> Router{
        Router{routes: ~[]}
    }
    pub fn add(&mut self, r: ~Route){
        self.routes.push(*r);
    }
    pub fn execute(&self, c: &mut HttpContext) {
        for route in self.routes.iter(){
            let res=route.matcher.matches(c.request.path);

            if(res.is_match){
                (route.handler)(&mut ControllerContext{http: c, router: self, route_params: res.params});
                return;
            }
        }
        default_handler(&mut ControllerContext{http: c, router: self, route_params: ParameterDictionary::new()});
    }
    pub fn controller<'r,T>(&'r mut self, creator: ~fn:Send+Freeze(&mut ControllerContext) -> T) -> ControllerBox<'r,T>
    {
        ControllerBox{
            router: self,
            path: ~"",
            creator: Some(creator)
        }
    }
}

pub struct ControllerContext<'l>
{
    http: &'l mut HttpContext,
    router: &'l Router,
    route_params: ParameterDictionary
}

pub trait HttpController{

}

pub struct ControllerBox<'l,T>{
    router: &'l mut Router,
    path: ~str,
    creator: Option<~fn:Send+Freeze(&mut ControllerContext) -> T>
}

impl<'l,T> ControllerBox<'l,T>{
    pub fn handles(&'l mut self, path: ~str) -> &'l mut ControllerBox<'l,T>{
        self.path=path;
        self
    }
    pub fn with(&'l mut self, invoker: ~fn:Send+Freeze(&mut T, &mut ControllerContext)) -> &'l mut ControllerBox<'l,T>{
        let tmp=self.creator.take();

        self.router.add(~Route{matcher: ~SimplePattern::new(self.path) as ~PatternMatcher:Freeze+Send, handler: |c| {
            match tmp {
                None => (),
                Some(ref t) => {
                    let mut ctrl=(*t)(c);
                    invoker(&mut ctrl, c);
                }
            };
        }});
        self
    }
}
/*
struct Meh{
    biz: ~fn(int) -> int
}

impl Meh{
    fn foo(@mut self
}
*/
/*
struct TestController;

impl TestController{
    fn new() -> TestController{
    TestController
    }
    fn index(&mut self, context: &mut ControllerContext) {
        context.http.response.body.push_str("test index");
    }
    fn say(&mut self, context: &mut ControllerContext) {
        context.http.response.body.push_str(context.route_params[~"message"]);
    }
}
*/

fn default_handler(context: &mut ControllerContext){
    context.http.response.body.push_str("404 not found");
}
/*
fn main() {
    let mut context=HttpContext::create();
    let mut router=Router::new();
    {
        let mut test = router.controller(|_| TestController::new());
        test.handles(~"/test").with(|c,ctx| c.index(ctx));
    }
    {
        let mut test = router.controller(|_| TestController::new());
        test.handles(~"/say/[message]").with(|c,ctx| c.say(ctx));
    }

    router.execute(&mut context);

    println(context.response.contenttype);
    println("");
    println(context.response.body);
}
*/
<|endoftext|>


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

use prelude::v1::*;

use cell::UnsafeCell;
use error::FromError;
use fmt;
use thread::Thread;

pub struct Flag { failed: UnsafeCell<bool> }
pub const FLAG_INIT: Flag = Flag { failed: UnsafeCell { value: false } };

impl Flag {
    #[inline]
    pub fn borrow(&self) -> LockResult<Guard> {
        let ret = Guard { panicking: Thread::panicking() };
        if unsafe { *self.failed.get() } {
            Err(new_poison_error(ret))
        } else {
            Ok(ret)
        }
    }

    #[inline]
    pub fn done(&self, guard: &Guard) {
        if !guard.panicking && Thread::panicking() {
            unsafe { *self.failed.get() = true; }
        }
    }

    #[inline]
    pub fn get(&self) -> bool {
        unsafe { *self.failed.get() }
    }
}

#[allow(missing_copy_implementations)]
pub struct Guard {
    panicking: bool,
}

/// A type of error which can be returned whenever a lock is acquired.
///
/// Both Mutexes and RwLocks are poisoned whenever a task fails while the lock
/// is held. The precise semantics for when a lock is poisoned is documented on
/// each lock, but once a lock is poisoned then all future acquisitions will
/// return this error.
#[stable]
pub struct PoisonError<T> {
    guard: T,
}

/// An enumeration of possible errors which can occur while calling the
/// `try_lock` method.
#[stable]
pub enum TryLockError<T> {
    /// The lock could not be acquired because another task failed while holding
    /// the lock.
    #[stable]
    Poisoned(PoisonError<T>),
    /// The lock could not be acquired at this time because the operation would
    /// otherwise block.
    #[stable]
    WouldBlock,
}

/// A type alias for the result of a lock method which can be poisoned.
///
/// The `Ok` variant of this result indicates that the primitive was not
/// poisoned, and the `Guard` is contained within. The `Err` variant indicates
/// that the primitive was poisoned. Note that the `Err` variant *also* carries
/// the associated guard, and it can be acquired through the `into_inner`
/// method.
#[stable]
pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;

/// A type alias for the result of a nonblocking locking method.
///
/// For more information, see `LockResult`. A `TryLockResult` doesn't
/// necessarily hold the associated guard in the `Err` type as the lock may not
/// have been acquired for other reasons.
#[stable]
pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;

impl<T> fmt::Show for PoisonError<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        "poisoned lock: another task failed inside".fmt(f)
    }
}

impl<T> PoisonError<T> {
    /// Consumes this error indicating that a lock is poisoned, returning the
    /// underlying guard to allow access regardless.
    #[deprecated="renamed to into_inner"]
    pub fn into_guard(self) -> T { self.guard }

    /// Consumes this error indicating that a lock is poisoned, returning the
    /// underlying guard to allow access regardless.
    #[unstable]
    pub fn into_inner(self) -> T { self.guard }

    /// Reaches into this error indicating that a lock is poisoned, returning a
    /// reference to the underlying guard to allow access regardless.
    #[unstable]
    pub fn get_ref(&self) -> &T { &self.guard }

    /// Reaches into this error indicating that a lock is poisoned, returning a
    /// mutable reference to the underlying guard to allow access regardless.
    #[unstable]
    pub fn get_mut(&mut self) -> &mut T { &mut self.guard }
}

impl<T> FromError<PoisonError<T>> for TryLockError<T> {
    fn from_error(err: PoisonError<T>) -> TryLockError<T> {
        TryLockError::Poisoned(err)
    }
}

impl<T> fmt::Show for TryLockError<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            TryLockError::Poisoned(ref p) => p.fmt(f),
            TryLockError::WouldBlock => {
                "try_lock failed because the operation would block".fmt(f)
            }
        }
    }
}

pub fn new_poison_error<T>(guard: T) -> PoisonError<T> {
    PoisonError { guard: guard }
}

pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
                           -> LockResult<U>
                           where F: FnOnce(T) -> U {
    match result {
        Ok(t) => Ok(f(t)),
        Err(PoisonError { guard }) => Err(new_poison_error(f(guard)))
    }
}
<commit_msg>Implement the error trait for errors in std::sync.<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use prelude::v1::*;

use cell::UnsafeCell;
use error::{Error, FromError};
use fmt;
use thread::Thread;

pub struct Flag { failed: UnsafeCell<bool> }
pub const FLAG_INIT: Flag = Flag { failed: UnsafeCell { value: false } };

impl Flag {
    #[inline]
    pub fn borrow(&self) -> LockResult<Guard> {
        let ret = Guard { panicking: Thread::panicking() };
        if unsafe { *self.failed.get() } {
            Err(new_poison_error(ret))
        } else {
            Ok(ret)
        }
    }

    #[inline]
    pub fn done(&self, guard: &Guard) {
        if !guard.panicking && Thread::panicking() {
            unsafe { *self.failed.get() = true; }
        }
    }

    #[inline]
    pub fn get(&self) -> bool {
        unsafe { *self.failed.get() }
    }
}

#[allow(missing_copy_implementations)]
pub struct Guard {
    panicking: bool,
}

/// A type of error which can be returned whenever a lock is acquired.
///
/// Both Mutexes and RwLocks are poisoned whenever a task fails while the lock
/// is held. The precise semantics for when a lock is poisoned is documented on
/// each lock, but once a lock is poisoned then all future acquisitions will
/// return this error.
#[stable]
pub struct PoisonError<T> {
    guard: T,
}

/// An enumeration of possible errors which can occur while calling the
/// `try_lock` method.
#[stable]
pub enum TryLockError<T> {
    /// The lock could not be acquired because another task failed while holding
    /// the lock.
    #[stable]
    Poisoned(PoisonError<T>),
    /// The lock could not be acquired at this time because the operation would
    /// otherwise block.
    #[stable]
    WouldBlock,
}

/// A type alias for the result of a lock method which can be poisoned.
///
/// The `Ok` variant of this result indicates that the primitive was not
/// poisoned, and the `Guard` is contained within. The `Err` variant indicates
/// that the primitive was poisoned. Note that the `Err` variant *also* carries
/// the associated guard, and it can be acquired through the `into_inner`
/// method.
#[stable]
pub type LockResult<Guard> = Result<Guard, PoisonError<Guard>>;

/// A type alias for the result of a nonblocking locking method.
///
/// For more information, see `LockResult`. A `TryLockResult` doesn't
/// necessarily hold the associated guard in the `Err` type as the lock may not
/// have been acquired for other reasons.
#[stable]
pub type TryLockResult<Guard> = Result<Guard, TryLockError<Guard>>;

impl<T> fmt::Show for PoisonError<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.description().fmt(f)
    }
}

impl<T> Error for PoisonError<T> {
    fn description(&self) -> &str {
        "poisoned lock: another task failed inside"
    }
}

impl<T> PoisonError<T> {
    /// Consumes this error indicating that a lock is poisoned, returning the
    /// underlying guard to allow access regardless.
    #[deprecated="renamed to into_inner"]
    pub fn into_guard(self) -> T { self.guard }

    /// Consumes this error indicating that a lock is poisoned, returning the
    /// underlying guard to allow access regardless.
    #[unstable]
    pub fn into_inner(self) -> T { self.guard }

    /// Reaches into this error indicating that a lock is poisoned, returning a
    /// reference to the underlying guard to allow access regardless.
    #[unstable]
    pub fn get_ref(&self) -> &T { &self.guard }

    /// Reaches into this error indicating that a lock is poisoned, returning a
    /// mutable reference to the underlying guard to allow access regardless.
    #[unstable]
    pub fn get_mut(&mut self) -> &mut T { &mut self.guard }
}

impl<T> FromError<PoisonError<T>> for TryLockError<T> {
    fn from_error(err: PoisonError<T>) -> TryLockError<T> {
        TryLockError::Poisoned(err)
    }
}

impl<T> fmt::Show for TryLockError<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.description().fmt(f)
    }
}

impl<T> Error for TryLockError<T> {
    fn description(&self) -> &str {
        match *self {
            TryLockError::Poisoned(ref p) => p.description(),
            TryLockError::WouldBlock => "try_lock failed because the operation would block"
        }
    }

    fn cause(&self) -> Option<&Error> {
        match *self {
            TryLockError::Poisoned(ref p) => Some(p),
            _ => None
        }
    }
}

pub fn new_poison_error<T>(guard: T) -> PoisonError<T> {
    PoisonError { guard: guard }
}

pub fn map_result<T, U, F>(result: LockResult<T>, f: F)
                           -> LockResult<U>
                           where F: FnOnce(T) -> U {
    match result {
        Ok(t) => Ok(f(t)),
        Err(PoisonError { guard }) => Err(new_poison_error(f(guard)))
    }
}
<|endoftext|>


<commit_before>use fallible_iterator::FallibleIterator;
use futures::{Async, Future, Poll, Stream};
use std::io::{self, Read};
use tokio_postgres::tls::{MakeTlsConnect, TlsConnect};
use tokio_postgres::types::{ToSql, Type};
#[cfg(feature = "runtime")]
use tokio_postgres::Socket;
use tokio_postgres::{Error, Row, SimpleQueryMessage};

#[cfg(feature = "runtime")]
use crate::Config;
use crate::{CopyOutReader, QueryIter, SimpleQueryIter, Statement, ToStatement, Transaction};

/// A synchronous PostgreSQL client.
///
/// This is a lightweight wrapper over the asynchronous tokio_postgres `Client`.
pub struct Client(tokio_postgres::Client);

impl Client {
    /// A convenience function which parses a configuration string into a `Config` and then connects to the database.
    ///
    /// Requires the `runtime` Cargo feature (enabled by default).
    #[cfg(feature = "runtime")]
    pub fn connect<T>(params: &str, tls_mode: T) -> Result<Client, Error>
    where
        T: MakeTlsConnect<Socket> + 'static + Send,
        T::TlsConnect: Send,
        T::Stream: Send,
        <T::TlsConnect as TlsConnect<Socket>>::Future: Send,
    {
        params.parse::<Config>()?.connect(tls_mode)
    }

    /// Returns a new `Config` object which can be used to configure and connect to a database.
    ///
    /// Requires the `runtime` Cargo feature (enabled by default).
    #[cfg(feature = "runtime")]
    pub fn configure() -> Config {
        Config::new()
    }

    /// Creates a new prepared statement.
    ///
    /// Prepared statements can be executed repeatedly, and may contain query parameters (indicated by `$1`, `$2`, etc),
    /// which are set when executed. Prepared statements can only be used with the connection that created them.
    pub fn prepare(&mut self, query: &str) -> Result<Statement, Error> {
        self.0.prepare(query).wait()
    }

    /// Like `prepare`, but allows the types of query parameters to be explicitly specified.
    ///
    /// The list of types may be smaller than the number of parameters - the types of the remaining parameters will be
    /// inferred. For example, `client.prepare_typed(query, &[])` is equivalent to `client.prepare(query)`.
    pub fn prepare_typed(&mut self, query: &str, types: &[Type]) -> Result<Statement, Error> {
        self.0.prepare_typed(query, types).wait()
    }

    /// Executes a statement, returning the number of rows modified.
    ///
    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
    /// provided, 1-indexed.
    ///
    /// If the statement does not modify any rows (e.g. `SELECT`), 0 is returned.
    ///
    /// The `query` argument can either be a `Statement`, or a raw query string. If the same statement will be
    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
    /// with the `prepare` method.
    ///
    /// # Panics
    ///
    /// Panics if the number of parameters provided does not match the number expected.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use postgres::{Client, NoTls};
    ///
    /// # fn main() -> Result<(), postgres::Error> {
    /// let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
    ///
    /// let bar = 1i32;
    /// let baz = true;
    /// let rows_updated = client.execute(
    ///     "UPDATE foo SET bar = $1 WHERE baz = $2",
    ///     &[&bar, &baz],
    /// )?;
    ///
    /// println!("{} rows updated", rows_updated);
    /// # Ok(())
    /// # }
    /// ```
    pub fn execute<T>(&mut self, query: &T, params: &[&dyn ToSql]) -> Result<u64, Error>
    where
        T: ?Sized + ToStatement,
    {
        let statement = query.__statement(self)?;
        self.0.execute(&statement, params).wait()
    }

    /// Executes a statement, returning the resulting rows.
    ///
    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
    /// provided, 1-indexed.
    ///
    /// The `query` argument can either be a `Statement`, or a raw query string. If the same statement will be
    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
    /// with the `prepare` method.
    ///
    /// The `query_iter` method can be used to avoid buffering all rows in memory at once.
    ///
    /// # Panics
    ///
    /// Panics if the number of parameters provided does not match the number expected.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use postgres::{Client, NoTls};
    ///
    /// # fn main() -> Result<(), postgres::Error> {
    /// let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
    ///
    /// let baz = true;
    /// for row in client.query("SELECT foo FROM bar WHERE baz = $1", &[&baz])? {
    ///     let foo: i32 = row.get("foo");
    ///     println!("foo: {}", foo);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn query<T>(&mut self, query: &T, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error>
    where
        T: ?Sized + ToStatement,
    {
        self.query_iter(query, params)?.collect()
    }

    /// Like `query`, except that it returns a fallible iterator over the resulting rows rather than buffering the
    /// response in memory.
    ///
    /// # Panics
    ///
    /// Panics if the number of parameters provided does not match the number expected.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use postgres::{Client, NoTls};
    /// use fallible_iterator::FallibleIterator;
    ///
    /// # fn main() -> Result<(), postgres::Error> {
    /// let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
    ///
    /// let baz = true;
    /// let mut it = client.query_iter("SELECT foo FROM bar WHERE baz = $1", &[&baz])?;
    ///
    /// while let Some(row) = it.next()? {
    ///     let foo: i32 = row.get("foo");
    ///     println!("foo: {}", foo);
    /// }
    /// # Ok(())
    /// # }
    pub fn query_iter<T>(
        &mut self,
        query: &T,
        params: &[&dyn ToSql],
    ) -> Result<QueryIter<'_>, Error>
    where
        T: ?Sized + ToStatement,
    {
        let statement = query.__statement(self)?;
        Ok(QueryIter::new(self.0.query(&statement, params)))
    }

    /// Executes a `COPY FROM STDIN` statement, returning the number of rows created.
    ///
    /// The `query` argument can either be a `Statement`, or a raw query string. The data in the provided reader is
    /// passed along to the server verbatim; it is the caller's responsibility to ensure it uses the proper format.
    pub fn copy_in<T, R>(
        &mut self,
        query: &T,
        params: &[&dyn ToSql],
        reader: R,
    ) -> Result<u64, Error>
    where
        T: ?Sized + ToStatement,
        R: Read,
    {
        let statement = query.__statement(self)?;
        self.0
            .copy_in(&statement, params, CopyInStream(reader))
            .wait()
    }

    /// Executes a `COPY TO STDOUT` statement, returning a reader of the resulting data.
    ///
    /// The `query` argument can either be a `Statement`, or a raw query string.
    pub fn copy_out<T>(
        &mut self,
        query: &T,
        params: &[&dyn ToSql],
    ) -> Result<CopyOutReader<'_>, Error>
    where
        T: ?Sized + ToStatement,
    {
        let statement = query.__statement(self)?;
        let stream = self.0.copy_out(&statement, params);
        CopyOutReader::new(stream)
    }

    /// Executes a sequence of SQL statements using the simple query protocol.
    ///
    /// Statements should be separated by semicolons. If an error occurs, execution of the sequence will stop at that
    /// point. The simple query protocol returns the values in rows as strings rather than in their binary encodings,
    /// so the associated row type doesn't work with the `FromSql` trait. Rather than simply returning the rows, this
    /// method returns a sequence of an enum which indicates either the completion of one of the commands, or a row of
    /// data. This preserves the framing between the separate statements in the request.
    ///
    /// This is a simple convenience method over `simple_query_iter`.
    ///
    /// # Warning
    ///
    /// Prepared statements should be use for any query which contains user-specified data, as they provided the
    /// functionality to safely imbed that data in the request. Do not form statements via string concatenation and pass
    /// them to this method!
    pub fn simple_query(&mut self, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
        self.simple_query_iter(query)?.collect()
    }

    /// Executes a sequence of SQL statements using the simple query protocol.
    ///
    /// Statements should be separated by semicolons. If an error occurs, execution of the sequence will stop at that
    /// point. The simple query protocol returns the values in rows as strings rather than in their binary encodings,
    /// so the associated row type doesn't work with the `FromSql` trait. Rather than simply returning the rows, this
    /// method returns a sequence of an enum which indicates either the completion of one of the commands, or a row of
    /// data. This preserves the framing between the separate statements in the request.
    ///
    /// # Warning
    ///
    /// Prepared statements should be use for any query which contains user-specified data, as they provided the
    /// functionality to safely imbed that data in the request. Do not form statements via string concatenation and pass
    /// them to this method!
    pub fn simple_query_iter(&mut self, query: &str) -> Result<SimpleQueryIter<'_>, Error> {
        Ok(SimpleQueryIter::new(self.0.simple_query(query)))
    }

    /// Begins a new database transaction.
    pub fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
        self.simple_query("BEGIN")?;
        Ok(Transaction::new(self))
    }

    pub fn is_closed(&self) -> bool {
        self.0.is_closed()
    }

    pub fn get_ref(&self) -> &tokio_postgres::Client {
        &self.0
    }

    pub fn get_mut(&mut self) -> &mut tokio_postgres::Client {
        &mut self.0
    }

    pub fn into_inner(self) -> tokio_postgres::Client {
        self.0
    }
}

impl From<tokio_postgres::Client> for Client {
    fn from(c: tokio_postgres::Client) -> Client {
        Client(c)
    }
}

struct CopyInStream<R>(R);

impl<R> Stream for CopyInStream<R>
where
    R: Read,
{
    type Item = Vec<u8>;
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Option<Vec<u8>>, io::Error> {
        let mut buf = vec![];
        match self.0.by_ref().take(4096).read_to_end(&mut buf)? {
            0 => Ok(Async::Ready(None)),
            _ => Ok(Async::Ready(Some(buf))),
        }
    }
}
<commit_msg>Finish Client docs<commit_after>use fallible_iterator::FallibleIterator;
use futures::{Async, Future, Poll, Stream};
use std::io::{self, Read};
use tokio_postgres::tls::{MakeTlsConnect, TlsConnect};
use tokio_postgres::types::{ToSql, Type};
#[cfg(feature = "runtime")]
use tokio_postgres::Socket;
use tokio_postgres::{Error, Row, SimpleQueryMessage};

#[cfg(feature = "runtime")]
use crate::Config;
use crate::{CopyOutReader, QueryIter, SimpleQueryIter, Statement, ToStatement, Transaction};

/// A synchronous PostgreSQL client.
///
/// This is a lightweight wrapper over the asynchronous tokio_postgres `Client`.
pub struct Client(tokio_postgres::Client);

impl Client {
    /// A convenience function which parses a configuration string into a `Config` and then connects to the database.
    ///
    /// See the documentation for [`Config`] for information about the connection syntax.
    ///
    /// Requires the `runtime` Cargo feature (enabled by default).
    ///
    /// [`Config`]: config/struct.Config.html
    #[cfg(feature = "runtime")]
    pub fn connect<T>(params: &str, tls_mode: T) -> Result<Client, Error>
    where
        T: MakeTlsConnect<Socket> + 'static + Send,
        T::TlsConnect: Send,
        T::Stream: Send,
        <T::TlsConnect as TlsConnect<Socket>>::Future: Send,
    {
        params.parse::<Config>()?.connect(tls_mode)
    }

    /// Returns a new `Config` object which can be used to configure and connect to a database.
    ///
    /// Requires the `runtime` Cargo feature (enabled by default).
    #[cfg(feature = "runtime")]
    pub fn configure() -> Config {
        Config::new()
    }

    /// Executes a statement, returning the number of rows modified.
    ///
    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
    /// provided, 1-indexed.
    ///
    /// If the statement does not modify any rows (e.g. `SELECT`), 0 is returned.
    ///
    /// The `query` argument can either be a `Statement`, or a raw query string. If the same statement will be
    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
    /// with the `prepare` method.
    ///
    /// # Panics
    ///
    /// Panics if the number of parameters provided does not match the number expected.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use postgres::{Client, NoTls};
    ///
    /// # fn main() -> Result<(), postgres::Error> {
    /// let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
    ///
    /// let bar = 1i32;
    /// let baz = true;
    /// let rows_updated = client.execute(
    ///     "UPDATE foo SET bar = $1 WHERE baz = $2",
    ///     &[&bar, &baz],
    /// )?;
    ///
    /// println!("{} rows updated", rows_updated);
    /// # Ok(())
    /// # }
    /// ```
    pub fn execute<T>(&mut self, query: &T, params: &[&dyn ToSql]) -> Result<u64, Error>
    where
        T: ?Sized + ToStatement,
    {
        let statement = query.__statement(self)?;
        self.0.execute(&statement, params).wait()
    }

    /// Executes a statement, returning the resulting rows.
    ///
    /// A statement may contain parameters, specified by `$n`, where `n` is the index of the parameter of the list
    /// provided, 1-indexed.
    ///
    /// The `query` argument can either be a `Statement`, or a raw query string. If the same statement will be
    /// repeatedly executed (perhaps with different query parameters), consider preparing the statement up front
    /// with the `prepare` method.
    ///
    /// The `query_iter` method can be used to avoid buffering all rows in memory at once.
    ///
    /// # Panics
    ///
    /// Panics if the number of parameters provided does not match the number expected.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use postgres::{Client, NoTls};
    ///
    /// # fn main() -> Result<(), postgres::Error> {
    /// let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
    ///
    /// let baz = true;
    /// for row in client.query("SELECT foo FROM bar WHERE baz = $1", &[&baz])? {
    ///     let foo: i32 = row.get("foo");
    ///     println!("foo: {}", foo);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn query<T>(&mut self, query: &T, params: &[&dyn ToSql]) -> Result<Vec<Row>, Error>
    where
        T: ?Sized + ToStatement,
    {
        self.query_iter(query, params)?.collect()
    }

    /// Like `query`, except that it returns a fallible iterator over the resulting rows rather than buffering the
    /// response in memory.
    ///
    /// # Panics
    ///
    /// Panics if the number of parameters provided does not match the number expected.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use postgres::{Client, NoTls};
    /// use fallible_iterator::FallibleIterator;
    ///
    /// # fn main() -> Result<(), postgres::Error> {
    /// let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
    ///
    /// let baz = true;
    /// let mut it = client.query_iter("SELECT foo FROM bar WHERE baz = $1", &[&baz])?;
    ///
    /// while let Some(row) = it.next()? {
    ///     let foo: i32 = row.get("foo");
    ///     println!("foo: {}", foo);
    /// }
    /// # Ok(())
    /// # }
    pub fn query_iter<T>(
        &mut self,
        query: &T,
        params: &[&dyn ToSql],
    ) -> Result<QueryIter<'_>, Error>
    where
        T: ?Sized + ToStatement,
    {
        let statement = query.__statement(self)?;
        Ok(QueryIter::new(self.0.query(&statement, params)))
    }

    /// Creates a new prepared statement.
    ///
    /// Prepared statements can be executed repeatedly, and may contain query parameters (indicated by `$1`, `$2`, etc),
    /// which are set when executed. Prepared statements can only be used with the connection that created them.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use postgres::{Client, NoTls};
    ///
    /// # fn main() -> Result<(), postgres::Error> {
    /// let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
    ///
    /// let statement = client.prepare("SELECT name FROM people WHERE id = $1")?;
    ///
    /// for id in 0..10 {
    ///     let rows = client.query(&statement, &[&id])?;
    ///     let name: &str = rows[0].get(0);
    ///     println!("name: {}", name);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn prepare(&mut self, query: &str) -> Result<Statement, Error> {
        self.0.prepare(query).wait()
    }

    /// Like `prepare`, but allows the types of query parameters to be explicitly specified.
    ///
    /// The list of types may be smaller than the number of parameters - the types of the remaining parameters will be
    /// inferred. For example, `client.prepare_typed(query, &[])` is equivalent to `client.prepare(query)`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use postgres::{Client, NoTls};
    /// use postgres::types::Type;
    ///
    /// # fn main() -> Result<(), postgres::Error> {
    /// let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
    ///
    /// let statement = client.prepare_typed(
    ///     "SELECT name FROM people WHERE id = $1",
    ///     &[Type::INT8],
    /// )?;
    ///
    /// for id in 0..10 {
    ///     let rows = client.query(&statement, &[&id])?;
    ///     let name: &str = rows[0].get(0);
    ///     println!("name: {}", name);
    /// }
    /// # Ok(())
    /// # }
    pub fn prepare_typed(&mut self, query: &str, types: &[Type]) -> Result<Statement, Error> {
        self.0.prepare_typed(query, types).wait()
    }

    /// Executes a `COPY FROM STDIN` statement, returning the number of rows created.
    ///
    /// The `query` argument can either be a `Statement`, or a raw query string. The data in the provided reader is
    /// passed along to the server verbatim; it is the caller's responsibility to ensure it uses the proper format.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use postgres::{Client, NoTls};
    ///
    /// # fn main() -> Result<(), postgres::Error> {
    /// let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
    ///
    /// client.copy_in("COPY people FROM stdin", &[], &mut "1\tjohn\n2\tjane\n".as_bytes())?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn copy_in<T, R>(
        &mut self,
        query: &T,
        params: &[&dyn ToSql],
        reader: R,
    ) -> Result<u64, Error>
    where
        T: ?Sized + ToStatement,
        R: Read,
    {
        let statement = query.__statement(self)?;
        self.0
            .copy_in(&statement, params, CopyInStream(reader))
            .wait()
    }

    /// Executes a `COPY TO STDOUT` statement, returning a reader of the resulting data.
    ///
    /// The `query` argument can either be a `Statement`, or a raw query string.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use postgres::{Client, NoTls};
    /// use std::io::Read;
    ///
    /// # fn main() -> Result<(), Box<std::error::Error>> {
    /// let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
    ///
    /// let mut reader = client.copy_out("COPY people TO stdout", &[])?;
    /// let mut buf = vec![];
    /// reader.read_to_end(&mut buf)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn copy_out<T>(
        &mut self,
        query: &T,
        params: &[&dyn ToSql],
    ) -> Result<CopyOutReader<'_>, Error>
    where
        T: ?Sized + ToStatement,
    {
        let statement = query.__statement(self)?;
        let stream = self.0.copy_out(&statement, params);
        CopyOutReader::new(stream)
    }

    /// Executes a sequence of SQL statements using the simple query protocol.
    ///
    /// Statements should be separated by semicolons. If an error occurs, execution of the sequence will stop at that
    /// point. The simple query protocol returns the values in rows as strings rather than in their binary encodings,
    /// so the associated row type doesn't work with the `FromSql` trait. Rather than simply returning the rows, this
    /// method returns a sequence of an enum which indicates either the completion of one of the commands, or a row of
    /// data. This preserves the framing between the separate statements in the request.
    ///
    /// This is a simple convenience method over `simple_query_iter`.
    ///
    /// # Warning
    ///
    /// Prepared statements should be use for any query which contains user-specified data, as they provided the
    /// functionality to safely imbed that data in the request. Do not form statements via string concatenation and pass
    /// them to this method!
    pub fn simple_query(&mut self, query: &str) -> Result<Vec<SimpleQueryMessage>, Error> {
        self.simple_query_iter(query)?.collect()
    }

    /// Like `simple_query`, except that it returns a fallible iterator over the resulting values rather than buffering
    /// the response in memory.
    ///
    /// # Warning
    ///
    /// Prepared statements should be use for any query which contains user-specified data, as they provided the
    /// functionality to safely imbed that data in the request. Do not form statements via string concatenation and pass
    /// them to this method!
    pub fn simple_query_iter(&mut self, query: &str) -> Result<SimpleQueryIter<'_>, Error> {
        Ok(SimpleQueryIter::new(self.0.simple_query(query)))
    }

    /// Begins a new database transaction.
    ///
    /// The transaction will roll back by default - use the `commit` method to commit it.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use postgres::{Client, NoTls};
    ///
    /// # fn main() -> Result<(), postgres::Error> {
    /// let mut client = Client::connect("host=localhost user=postgres", NoTls)?;
    ///
    /// let mut transaction = client.transaction()?;
    /// transaction.execute("UPDATE foo SET bar = 10", &[])?;
    /// // ...
    ///
    /// transaction.commit()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn transaction(&mut self) -> Result<Transaction<'_>, Error> {
        self.simple_query("BEGIN")?;
        Ok(Transaction::new(self))
    }

    /// Determines if the client's connection has already closed.
    ///
    /// If this returns `true`, the client is no longer usable.
    pub fn is_closed(&self) -> bool {
        self.0.is_closed()
    }

    /// Returns a shared reference to the inner nonblocking client.
    pub fn get_ref(&self) -> &tokio_postgres::Client {
        &self.0
    }

    /// Returns a mutable reference to the inner nonblocking client.
    pub fn get_mut(&mut self) -> &mut tokio_postgres::Client {
        &mut self.0
    }

    /// Consumes the client, returning the inner nonblocking client.
    pub fn into_inner(self) -> tokio_postgres::Client {
        self.0
    }
}

impl From<tokio_postgres::Client> for Client {
    fn from(c: tokio_postgres::Client) -> Client {
        Client(c)
    }
}

struct CopyInStream<R>(R);

impl<R> Stream for CopyInStream<R>
where
    R: Read,
{
    type Item = Vec<u8>;
    type Error = io::Error;

    fn poll(&mut self) -> Poll<Option<Vec<u8>>, io::Error> {
        let mut buf = vec![];
        match self.0.by_ref().take(4096).read_to_end(&mut buf)? {
            0 => Ok(Async::Ready(None)),
            _ => Ok(Async::Ready(Some(buf))),
        }
    }
}
<|endoftext|>


<commit_before>use chrono::{DateTime, FixedOffset};
use serde_derive::Deserialize;

#[derive(Deserialize)]
pub(super) struct Page {
    title: Option<String>,
    subtitle: Option<String>,
    summary: Option<String>,
    qualifiers: Option<Qualifiers>,
    date: Option<DateTime<FixedOffset>>,
    updated: Option<DateTime<FixedOffset>>,
    permalink: Option<String>,
    thanks: Option<String>,
    tags: Vec<String>,
    featured: bool,
    layout: Option<String>,
}

#[derive(Deserialize)]
struct Qualifiers {
    audience: Option<String>,
    epistemic: Option<String>,
}

#[derive(Deserialize)]
struct Book {
    title: String,
    author: String,
    editors: Vec<String>,
    translators: Vec<String>,
    cover: Option<String>,
    link: Option<String>,
    year: u16,
    review: Review,
}

#[derive(Deserialize)]
struct Review {
    rating: Rating,
    summary: String,
}

#[derive(Deserialize)]
enum Rating {
    NotRecommended,
    WithQualifications,
    Recommended,
    Required,
}

impl std::fmt::Display for Rating {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Rating::NotRecommended => "Not recommended",
                Rating::WithQualifications => "Recommended with qualifications",
                Rating::Recommended => "Recommended",
                Rating::Required => "Required",
            }
        )
    }
}
<commit_msg>Add 'Series' to supported metadata<commit_after>use chrono::{DateTime, FixedOffset};
use serde_derive::Deserialize;

#[derive(Deserialize)]
pub(super) struct Page {
    title: Option<String>,
    subtitle: Option<String>,
    summary: Option<String>,
    qualifiers: Option<Qualifiers>,
    date: Option<DateTime<FixedOffset>>,
    updated: Option<DateTime<FixedOffset>>,
    permalink: Option<String>,
    thanks: Option<String>,
    tags: Vec<String>,
    featured: bool,
    layout: Option<String>,
    series: Option<Series>,
}

#[derive(Deserialize)]
struct Qualifiers {
    audience: Option<String>,
    epistemic: Option<String>,
}

#[derive(Deserialize)]
struct Book {
    title: String,
    author: String,
    editors: Vec<String>,
    translators: Vec<String>,
    cover: Option<String>,
    link: Option<String>,
    year: u16,
    review: Review,
}

#[derive(Deserialize)]
struct Review {
    rating: Rating,
    summary: String,
}

#[derive(Deserialize)]
enum Rating {
    NotRecommended,
    WithQualifications,
    Recommended,
    Required,
}

impl std::fmt::Display for Rating {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Rating::NotRecommended => "Not recommended",
                Rating::WithQualifications => "Recommended with qualifications",
                Rating::Recommended => "Recommended",
                Rating::Required => "Required",
            }
        )
    }
}

#[derive(Deserialize)]
struct Series {
    name: String,
    part: u8,
}
<|endoftext|>


<commit_before><commit_msg>Improve the documentation of DeviceEvent::Motion (#321)<commit_after><|endoftext|>


<commit_before><commit_msg>todo for cleanup<commit_after><|endoftext|>


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


<commit_before><commit_msg>Explicitly describe schema instead of infering it from database<commit_after><|endoftext|>


<commit_before><commit_msg>If we get a single search result, auto-redirect (fixes #6)<commit_after><|endoftext|>


<commit_before>#![no_std]
#![feature(asm, panic_implementation, panic_info_message)]

#[path = "arch/x86/"]
pub mod platform {
	pub mod vga;
	pub mod cpu;
	pub mod mmu;
	mod io;
	pub mod keyboard;
}

pub mod kernel {
	pub mod main;
	pub mod interrupts;
	mod stdio;
	mod keyboard;
}

#[no_mangle]
pub extern "C" fn _Unwind_Resume() -> ! {
    loop {}
}
<commit_msg>Update for latest nightly<commit_after>#![no_std]
#![feature(asm, panic_info_message)]

#[path = "arch/x86/"]
pub mod platform {
	pub mod vga;
	pub mod cpu;
	pub mod mmu;
	mod io;
	pub mod keyboard;
}

pub mod kernel {
	pub mod main;
	pub mod interrupts;
	mod stdio;
	mod keyboard;
}

#[no_mangle]
pub extern "C" fn _Unwind_Resume() -> ! {
    loop {}
}
<|endoftext|>


<commit_before>use super::internal_prelude::*;
// TODO: someday look into better algorithms - see http://colorconstancy.com/ and http://ipg.fer.hr/ipg/resources/color_constancy
// http://localhost:39876/ir4/proxy_unsplash/photo-1496264057429-6a331647b69e?a.balancewhite=true&w=800
// http://localhost:39876/ir4/proxy_unsplash/photo-1496264057429-6a331647b69e?w=800

    pub static  WHITE_BALANCE_SRGB: WhiteBalanceSrgbMutDef = WhiteBalanceSrgbMutDef{};
    pub static  WHITE_BALANCE_SRGB_MUTATE: MutProtect<WhiteBalanceSrgbMutDef> = MutProtect{node: &WHITE_BALANCE_SRGB, fqn: "imazen.white_balance_srgb"};

fn area_threshold(histogram: &[u64], total_pixels: u64, low_threshold: f64, high_threshold: f64) -> (usize, usize){
    let mut low = 0;
    let mut high = histogram.len() - 1;
    let mut area = 0u64;
    let pixel_count = total_pixels as f64;
    for (ix, value) in histogram.iter().enumerate(){
        area += u64::from(*value);
        if area as f64 / f64::from(pixel_count) > low_threshold {
            low = ix;
            break;
        }
    }
    area = 0u64;
    for (ix, value) in histogram.iter().enumerate().rev(){
        area += u64::from(*value);
        if area as f64 / f64::from(pixel_count) > low_threshold {
            high = ix;
            break;
        }
    }
    eprintln!("{},{}", low,high);
    (low, high)
}

fn create_byte_mapping(low: usize, high: usize) -> Vec<u8>{
    let scale = 255.0 / ((high - low) as f64);

    (0..256usize).map(|v| (v.saturating_sub(low) as f64 * scale).round().min(255f64).max(0f64) as u8).collect()
}

fn apply_mappings(bitmap: *mut BitmapBgra, map_red: &[u8], map_green: &[u8], map_blue: &[u8]) -> Result<()>{

    let input: &BitmapBgra = unsafe{ &*bitmap };
    let bytes: &mut [u8] = unsafe { slice::from_raw_parts_mut::<u8>(input.pixels, (input.stride * input.h) as usize) };

    if map_red.len() < 256 || map_green.len() < 256 || map_blue.len() < 256{
        return Err(nerror!(crate::ErrorKind::InvalidState));
    }

    match input.fmt {
        PixelFormat::Gray8 =>
            Err(unimpl!())
        ,
        PixelFormat::Bgra32 | PixelFormat::Bgr32=> {
            for row in bytes.chunks_mut(input.stride as usize){
                for pixel in row.chunks_mut(4).take(input.w as usize){
                    //pixel[0] = map_blue[pixel[0]];
                    //pixel[1] = map_green[pixel[1]];
                    //pixel[2] = map_red[pixel[2]];
                    unsafe {
                        *pixel.get_unchecked_mut(0) = *map_blue.get_unchecked(*pixel.get_unchecked(0) as usize);
                        *pixel.get_unchecked_mut(1) = *map_green.get_unchecked(*pixel.get_unchecked(1) as usize);
                        *pixel.get_unchecked_mut(2) = *map_red.get_unchecked(*pixel.get_unchecked(2) as usize);
                    }
                }
            }
            Ok(())
        },
        PixelFormat::Bgr24 => {
            for row in bytes.chunks_mut(input.stride as usize){
                for pixel in row.chunks_mut(3).take(input.w as usize){
                    //pixel[0] = *map_blue[pixel[0]];
                    //pixel[1] = *map_green[pixel[1]];
                    //pixel[2] = *map_red[pixel[2]];
                    unsafe {
                        *pixel.get_unchecked_mut(0) = *map_blue.get_unchecked(*pixel.get_unchecked(0) as usize);
                        *pixel.get_unchecked_mut(1) = *map_green.get_unchecked(*pixel.get_unchecked(1) as usize);
                        *pixel.get_unchecked_mut(2) = *map_red.get_unchecked(*pixel.get_unchecked(2) as usize);
                    }
                }
            }
            Ok(())
        },
    }
}

fn white_balance_srgb_mut(bitmap: *mut BitmapBgra, histograms: &[u64;768], pixels_sampled: u64, low_threshold: Option<f32>, high_threshold: Option<f32>) -> Result<()>{
    let low_threshold = f64::from(low_threshold.unwrap_or(0.006));
    let high_threshold = f64::from(high_threshold.unwrap_or(0.006));

    let (red_low, red_high) = area_threshold(&histograms[0..256], pixels_sampled, low_threshold, high_threshold);
    let (green_low, green_high) = area_threshold(&histograms[256..512], pixels_sampled, low_threshold, high_threshold);
    let (blue_low, blue_high) = area_threshold(&histograms[512..768], pixels_sampled, low_threshold, high_threshold);

    let red_map = create_byte_mapping(red_low, red_high);
    let green_map = create_byte_mapping(green_low, green_high);
    let blue_map = create_byte_mapping(blue_low, blue_high);

    apply_mappings(bitmap, &red_map, &green_map, &blue_map)
}

#[derive(Debug, Clone)]
pub struct WhiteBalanceSrgbMutDef;
impl NodeDef for WhiteBalanceSrgbMutDef{
    fn as_one_mutate_bitmap(&self) -> Option<&dyn NodeDefMutateBitmap>{
        Some(self)
    }
}
impl NodeDefMutateBitmap for WhiteBalanceSrgbMutDef{
    fn fqn(&self) -> &'static str{
        "imazen.white_balance_srgb_mut"
    }
    fn mutate(&self, c: &Context, bitmap_key: BitmapKey,  p: &NodeParams) -> Result<()> {

        unsafe {

            let bitmaps = c.borrow_bitmaps()
                .map_err(|e| e.at(here!()))?;
            let mut bitmap_bitmap = bitmaps.try_borrow_mut(bitmap_key)
                .map_err(|e| e.at(here!()))?;

            let mut bitmap = bitmap_bitmap.get_window_u8().unwrap().to_bitmap_bgra()?;

            let mut histograms: [u64; 768] = [0; 768];
            let mut pixels_sampled: u64 = 0;
            if !crate::ffi::flow_bitmap_bgra_populate_histogram(c.flow_c(), &mut bitmap as *mut BitmapBgra, histograms.as_mut_ptr(), 256, 3, &mut pixels_sampled as *mut u64) {
                return Err(cerror!(c, "Failed to populate histogram"))
            }
            if let NodeParams::Json(s::Node::WhiteBalanceHistogramAreaThresholdSrgb { threshold }) = *p {
                white_balance_srgb_mut(&mut bitmap, &histograms, pixels_sampled, threshold, threshold)
            } else {
                Err(nerror!(crate::ErrorKind::NodeParamsMismatch, "Need ColorMatrixSrgb, got {:?}", p))
            }
        }

    }
}
<commit_msg>Don't print data to error stream during white balance<commit_after>use super::internal_prelude::*;
// TODO: someday look into better algorithms - see http://colorconstancy.com/ and http://ipg.fer.hr/ipg/resources/color_constancy
// http://localhost:39876/ir4/proxy_unsplash/photo-1496264057429-6a331647b69e?a.balancewhite=true&w=800
// http://localhost:39876/ir4/proxy_unsplash/photo-1496264057429-6a331647b69e?w=800

    pub static  WHITE_BALANCE_SRGB: WhiteBalanceSrgbMutDef = WhiteBalanceSrgbMutDef{};
    pub static  WHITE_BALANCE_SRGB_MUTATE: MutProtect<WhiteBalanceSrgbMutDef> = MutProtect{node: &WHITE_BALANCE_SRGB, fqn: "imazen.white_balance_srgb"};

fn area_threshold(histogram: &[u64], total_pixels: u64, low_threshold: f64, high_threshold: f64) -> (usize, usize){
    let mut low = 0;
    let mut high = histogram.len() - 1;
    let mut area = 0u64;
    let pixel_count = total_pixels as f64;
    for (ix, value) in histogram.iter().enumerate(){
        area += u64::from(*value);
        if area as f64 / f64::from(pixel_count) > low_threshold {
            low = ix;
            break;
        }
    }
    area = 0u64;
    for (ix, value) in histogram.iter().enumerate().rev(){
        area += u64::from(*value);
        if area as f64 / f64::from(pixel_count) > low_threshold {
            high = ix;
            break;
        }
    }
    // eprintln!("{},{}", low,high);
    (low, high)
}

fn create_byte_mapping(low: usize, high: usize) -> Vec<u8>{
    let scale = 255.0 / ((high - low) as f64);

    (0..256usize).map(|v| (v.saturating_sub(low) as f64 * scale).round().min(255f64).max(0f64) as u8).collect()
}

fn apply_mappings(bitmap: *mut BitmapBgra, map_red: &[u8], map_green: &[u8], map_blue: &[u8]) -> Result<()>{

    let input: &BitmapBgra = unsafe{ &*bitmap };
    let bytes: &mut [u8] = unsafe { slice::from_raw_parts_mut::<u8>(input.pixels, (input.stride * input.h) as usize) };

    if map_red.len() < 256 || map_green.len() < 256 || map_blue.len() < 256{
        return Err(nerror!(crate::ErrorKind::InvalidState));
    }

    match input.fmt {
        PixelFormat::Gray8 =>
            Err(unimpl!())
        ,
        PixelFormat::Bgra32 | PixelFormat::Bgr32=> {
            for row in bytes.chunks_mut(input.stride as usize){
                for pixel in row.chunks_mut(4).take(input.w as usize){
                    //pixel[0] = map_blue[pixel[0]];
                    //pixel[1] = map_green[pixel[1]];
                    //pixel[2] = map_red[pixel[2]];
                    unsafe {
                        *pixel.get_unchecked_mut(0) = *map_blue.get_unchecked(*pixel.get_unchecked(0) as usize);
                        *pixel.get_unchecked_mut(1) = *map_green.get_unchecked(*pixel.get_unchecked(1) as usize);
                        *pixel.get_unchecked_mut(2) = *map_red.get_unchecked(*pixel.get_unchecked(2) as usize);
                    }
                }
            }
            Ok(())
        },
        PixelFormat::Bgr24 => {
            for row in bytes.chunks_mut(input.stride as usize){
                for pixel in row.chunks_mut(3).take(input.w as usize){
                    //pixel[0] = *map_blue[pixel[0]];
                    //pixel[1] = *map_green[pixel[1]];
                    //pixel[2] = *map_red[pixel[2]];
                    unsafe {
                        *pixel.get_unchecked_mut(0) = *map_blue.get_unchecked(*pixel.get_unchecked(0) as usize);
                        *pixel.get_unchecked_mut(1) = *map_green.get_unchecked(*pixel.get_unchecked(1) as usize);
                        *pixel.get_unchecked_mut(2) = *map_red.get_unchecked(*pixel.get_unchecked(2) as usize);
                    }
                }
            }
            Ok(())
        },
    }
}

fn white_balance_srgb_mut(bitmap: *mut BitmapBgra, histograms: &[u64;768], pixels_sampled: u64, low_threshold: Option<f32>, high_threshold: Option<f32>) -> Result<()>{
    let low_threshold = f64::from(low_threshold.unwrap_or(0.006));
    let high_threshold = f64::from(high_threshold.unwrap_or(0.006));

    let (red_low, red_high) = area_threshold(&histograms[0..256], pixels_sampled, low_threshold, high_threshold);
    let (green_low, green_high) = area_threshold(&histograms[256..512], pixels_sampled, low_threshold, high_threshold);
    let (blue_low, blue_high) = area_threshold(&histograms[512..768], pixels_sampled, low_threshold, high_threshold);

    let red_map = create_byte_mapping(red_low, red_high);
    let green_map = create_byte_mapping(green_low, green_high);
    let blue_map = create_byte_mapping(blue_low, blue_high);

    apply_mappings(bitmap, &red_map, &green_map, &blue_map)
}

#[derive(Debug, Clone)]
pub struct WhiteBalanceSrgbMutDef;
impl NodeDef for WhiteBalanceSrgbMutDef{
    fn as_one_mutate_bitmap(&self) -> Option<&dyn NodeDefMutateBitmap>{
        Some(self)
    }
}
impl NodeDefMutateBitmap for WhiteBalanceSrgbMutDef{
    fn fqn(&self) -> &'static str{
        "imazen.white_balance_srgb_mut"
    }
    fn mutate(&self, c: &Context, bitmap_key: BitmapKey,  p: &NodeParams) -> Result<()> {

        unsafe {

            let bitmaps = c.borrow_bitmaps()
                .map_err(|e| e.at(here!()))?;
            let mut bitmap_bitmap = bitmaps.try_borrow_mut(bitmap_key)
                .map_err(|e| e.at(here!()))?;

            let mut bitmap = bitmap_bitmap.get_window_u8().unwrap().to_bitmap_bgra()?;

            let mut histograms: [u64; 768] = [0; 768];
            let mut pixels_sampled: u64 = 0;
            if !crate::ffi::flow_bitmap_bgra_populate_histogram(c.flow_c(), &mut bitmap as *mut BitmapBgra, histograms.as_mut_ptr(), 256, 3, &mut pixels_sampled as *mut u64) {
                return Err(cerror!(c, "Failed to populate histogram"))
            }
            if let NodeParams::Json(s::Node::WhiteBalanceHistogramAreaThresholdSrgb { threshold }) = *p {
                white_balance_srgb_mut(&mut bitmap, &histograms, pixels_sampled, threshold, threshold)
            } else {
                Err(nerror!(crate::ErrorKind::NodeParamsMismatch, "Need ColorMatrixSrgb, got {:?}", p))
            }
        }

    }
}
<|endoftext|>