<commit_before>use Device;
use NVML;
#[cfg(not(feature = "test-local"))]
use NvLink;
use Unit;

use bitmasks::{
    device::*,
    event::*
};

use enum_wrappers::device::*;
use enums::unit::*;
use error::*;
use event::EventSet;
use std::fmt::Debug;

use struct_wrappers::{
    *,
    device::*,
    event::*,
    unit::*
};
#[cfg(not(feature = "test-local"))]
use struct_wrappers::nv_link::*;

use structs::device::*;
#[cfg(not(feature = "test-local"))]
use structs::nv_link::*;

#[cfg(target_os = "windows")]
use structs::device::DriverModelState;

pub trait ShouldPrint: Debug {
    fn should_print(&self) -> bool {
        true
    }
}

impl ShouldPrint for () {
    fn should_print(&self) -> bool {
        false
    }
}

impl<'nvml> ShouldPrint for Device<'nvml> {
    fn should_print(&self) -> bool {
        false
    }
}

impl<'nvml> ShouldPrint for Unit<'nvml> {
    fn should_print(&self) -> bool {
        false
    }
}

impl<'nvml> ShouldPrint for EventSet<'nvml> {
    fn should_print(&self) -> bool {
        false
    }
}

impl ShouldPrint for bool {}
impl ShouldPrint for u32 {}
impl ShouldPrint for i32 {}
impl ShouldPrint for (u32, u32) {}
impl ShouldPrint for u64 {}
impl ShouldPrint for String {}
impl ShouldPrint for Brand {}
impl ShouldPrint for [i8; 16] {}
impl ShouldPrint for Vec<ProcessInfo> {}
impl ShouldPrint for Vec<ProcessUtilizationSample> {}
impl<'nvml> ShouldPrint for Vec<Device<'nvml>> {}
impl ShouldPrint for Vec<u32> {}
impl ShouldPrint for Vec<u64> {}
impl ShouldPrint for Vec<Sample> {}
impl ShouldPrint for Vec<Result<FieldValueSample>> {}
impl ShouldPrint for Vec<HwbcEntry> {}
impl ShouldPrint for Utilization {}
impl ShouldPrint for EncoderStats {}
impl ShouldPrint for FbcStats {}
impl ShouldPrint for Vec<FbcSessionInfo> {}
impl ShouldPrint for Vec<EncoderSessionInfo> {}
impl ShouldPrint for AutoBoostClocksEnabledInfo {}
impl ShouldPrint for BAR1MemoryInfo {}
impl ShouldPrint for BridgeChipHierarchy {}
impl ShouldPrint for ComputeMode {}
impl ShouldPrint for UtilizationInfo {}
impl ShouldPrint for EccModeState {}
impl ShouldPrint for OperationModeState {}
impl ShouldPrint for InfoRom {}
impl ShouldPrint for Vec<RetiredPage> {}
impl ShouldPrint for BlacklistDeviceInfo {}
impl ShouldPrint for MemoryInfo {}
impl ShouldPrint for PciInfo {}
impl ShouldPrint for PerformanceState {}
impl ShouldPrint for PowerManagementConstraints {}
impl ShouldPrint for ThrottleReasons {}
impl ShouldPrint for ViolationTime {}
impl ShouldPrint for AccountingStats {}
impl ShouldPrint for EventTypes {}
impl<'nvml> ShouldPrint for EventData<'nvml> {}
impl ShouldPrint for FansInfo {}
impl ShouldPrint for LedState {}
impl ShouldPrint for PsuInfo {}
impl ShouldPrint for UnitInfo {}
#[cfg(not(feature = "test-local"))]
impl ShouldPrint for UtilizationControl {}
#[cfg(not(feature = "test-local"))]
impl ShouldPrint for UtilizationCounter {}

#[cfg(target_os = "windows")]
impl ShouldPrint for DriverModelState {}

pub fn nvml() -> NVML {
    NVML::init().expect("initialized library")
}

pub fn device<'nvml>(nvml: &'nvml NVML) -> Device<'nvml> {
    nvml.device_by_index(0).expect("device")
}

#[cfg(not(feature = "test-local"))]
pub fn unit<'nvml>(nvml: &'nvml NVML) -> Unit<'nvml> {
    nvml.unit_by_index(0).expect("unit")
}

pub fn assert_send<T: Send>() {}
pub fn assert_sync<T: Sync>() {}

/// Run all testing methods for the given test.
pub fn test<T, R>(reps: usize, test: T)
where
    T: Fn() -> (Result<R>),
    R: ShouldPrint,
{
    single(|| test());

    multi(reps, || test());
}

pub fn test_with_device<T, R>(reps: usize, nvml: &NVML, test: T)
where
    T: Fn(&Device) -> (Result<R>),
    R: ShouldPrint,
{
    let device = device(nvml);

    single(|| test(&device));

    multi(reps, || test(&device));
}

#[cfg(not(feature = "test-local"))]
pub fn test_with_unit<T, R>(reps: usize, nvml: &NVML, test: T)
where
    T: Fn(&Unit) -> (Result<R>),
    R: ShouldPrint,
{
    let unit = unit(nvml);

    single(|| test(&unit));

    multi(reps, || test(&unit));
}

#[cfg(not(feature = "test-local"))]
pub fn test_with_link<T, R>(reps: usize, nvml: &NVML, test: T)
where
    T: Fn(&NvLink) -> (Result<R>),
    R: ShouldPrint,
{
    // Is 0 a good default???
    let device = device(&nvml);
    let link = device.link_wrapper_for(0);

    single(|| test(&link));

    multi(reps, || test(&link));
}

/// Run the given test once.
pub fn single<T, R>(test: T)
where
    T: Fn() -> (Result<R>),
    R: ShouldPrint,
{
    let res = test().expect("successful single test");

    if res.should_print() {
        print!("{:?} ... ", res);
    }
}

/// Run the given test multiple times.
pub fn multi<T, R>(count: usize, test: T)
where
    T: Fn() -> (Result<R>),
    R: ShouldPrint,
{
    for i in 0..count {
        test().expect(&format!("successful multi call #{}", i));
    }
}
<commit_msg>Fix warnings in test utils<commit_after>use Device;
use NVML;
#[cfg(not(feature = "test-local"))]
use NvLink;
use Unit;

use bitmasks::{
    device::*,
    event::*
};

use enum_wrappers::device::*;
use enums::unit::*;
use error::*;
use event::EventSet;
use std::fmt::Debug;

use struct_wrappers::{
    *,
    device::*,
    event::*,
    unit::*
};
#[cfg(not(feature = "test-local"))]
use struct_wrappers::nv_link::*;

use structs::device::*;
#[cfg(not(feature = "test-local"))]
use structs::nv_link::*;

#[cfg(target_os = "windows")]
use structs::device::DriverModelState;

pub trait ShouldPrint: Debug {
    fn should_print(&self) -> bool {
        true
    }
}

impl ShouldPrint for () {
    fn should_print(&self) -> bool {
        false
    }
}

impl<'nvml> ShouldPrint for Device<'nvml> {
    fn should_print(&self) -> bool {
        false
    }
}

impl<'nvml> ShouldPrint for Unit<'nvml> {
    fn should_print(&self) -> bool {
        false
    }
}

impl<'nvml> ShouldPrint for EventSet<'nvml> {
    fn should_print(&self) -> bool {
        false
    }
}

impl ShouldPrint for bool {}
impl ShouldPrint for u32 {}
impl ShouldPrint for i32 {}
impl ShouldPrint for (u32, u32) {}
impl ShouldPrint for u64 {}
impl ShouldPrint for String {}
impl ShouldPrint for Brand {}
impl ShouldPrint for [i8; 16] {}
impl ShouldPrint for Vec<ProcessInfo> {}
impl ShouldPrint for Vec<ProcessUtilizationSample> {}
impl<'nvml> ShouldPrint for Vec<Device<'nvml>> {}
impl ShouldPrint for Vec<u32> {}
impl ShouldPrint for Vec<u64> {}
impl ShouldPrint for Vec<Sample> {}
impl ShouldPrint for Vec<Result<FieldValueSample>> {}
impl ShouldPrint for Vec<HwbcEntry> {}
impl ShouldPrint for Utilization {}
impl ShouldPrint for EncoderStats {}
impl ShouldPrint for FbcStats {}
impl ShouldPrint for Vec<FbcSessionInfo> {}
impl ShouldPrint for Vec<EncoderSessionInfo> {}
impl ShouldPrint for AutoBoostClocksEnabledInfo {}
impl ShouldPrint for BAR1MemoryInfo {}
impl ShouldPrint for BridgeChipHierarchy {}
impl ShouldPrint for ComputeMode {}
impl ShouldPrint for UtilizationInfo {}
impl ShouldPrint for EccModeState {}
impl ShouldPrint for OperationModeState {}
impl ShouldPrint for InfoRom {}
impl ShouldPrint for Vec<RetiredPage> {}
impl ShouldPrint for BlacklistDeviceInfo {}
impl ShouldPrint for MemoryInfo {}
impl ShouldPrint for PciInfo {}
impl ShouldPrint for PerformanceState {}
impl ShouldPrint for PowerManagementConstraints {}
impl ShouldPrint for ThrottleReasons {}
impl ShouldPrint for ViolationTime {}
impl ShouldPrint for AccountingStats {}
impl ShouldPrint for EventTypes {}
impl<'nvml> ShouldPrint for EventData<'nvml> {}
impl ShouldPrint for FansInfo {}
impl ShouldPrint for LedState {}
impl ShouldPrint for PsuInfo {}
impl ShouldPrint for UnitInfo {}
#[cfg(not(feature = "test-local"))]
impl ShouldPrint for UtilizationControl {}
#[cfg(not(feature = "test-local"))]
impl ShouldPrint for UtilizationCounter {}

#[cfg(target_os = "windows")]
impl ShouldPrint for DriverModelState {}

pub fn nvml() -> NVML {
    NVML::init().expect("initialized library")
}

pub fn device<'nvml>(nvml: &'nvml NVML) -> Device<'nvml> {
    nvml.device_by_index(0).expect("device")
}

#[cfg(not(feature = "test-local"))]
pub fn unit<'nvml>(nvml: &'nvml NVML) -> Unit<'nvml> {
    nvml.unit_by_index(0).expect("unit")
}

pub fn assert_send<T: Send>() {}
pub fn assert_sync<T: Sync>() {}

/// Run all testing methods for the given test.
pub fn test<T, R>(reps: usize, test: T)
where
    T: Fn() -> Result<R>,
    R: ShouldPrint,
{
    single(|| test());

    multi(reps, || test());
}

pub fn test_with_device<T, R>(reps: usize, nvml: &NVML, test: T)
where
    T: Fn(&Device) -> Result<R>,
    R: ShouldPrint,
{
    let device = device(nvml);

    single(|| test(&device));

    multi(reps, || test(&device));
}

#[cfg(not(feature = "test-local"))]
pub fn test_with_unit<T, R>(reps: usize, nvml: &NVML, test: T)
where
    T: Fn(&Unit) -> Result<R>,
    R: ShouldPrint,
{
    let unit = unit(nvml);

    single(|| test(&unit));

    multi(reps, || test(&unit));
}

#[cfg(not(feature = "test-local"))]
pub fn test_with_link<T, R>(reps: usize, nvml: &NVML, test: T)
where
    T: Fn(&NvLink) -> Result<R>,
    R: ShouldPrint,
{
    // Is 0 a good default???
    let device = device(&nvml);
    let link = device.link_wrapper_for(0);

    single(|| test(&link));

    multi(reps, || test(&link));
}

/// Run the given test once.
pub fn single<T, R>(test: T)
where
    T: Fn() -> Result<R>,
    R: ShouldPrint,
{
    let res = test().expect("successful single test");

    if res.should_print() {
        print!("{:?} ... ", res);
    }
}

/// Run the given test multiple times.
pub fn multi<T, R>(count: usize, test: T)
where
    T: Fn() -> Result<R>,
    R: ShouldPrint,
{
    for i in 0..count {
        test().expect(&format!("successful multi call #{}", i));
    }
}
<|endoftext|>


<commit_before>use scene::{BoxedScene, Scene};
use event::{Event, RenderArgs};
use conrod::UiContext;
use opengl_graphics::{Gl, Texture};
use graphics::{Context, AddImage, Draw};
use conrod::{
    Background,
    Color,
    Colorable,
    Drawable,
    Label,
    Labelable,
    Positionable
};
use input::{Release, Keyboard, keyboard};
use uorustlibs::art::{ArtReader, TileOrStatic, Art};
use uorustlibs::color::Color16;
use uorustlibs::color::Color as ColorTrait;
use image::{GenericImage, ImageBuf, Rgba};

use std::io::IoResult;

pub struct TileScene {
    reader: IoResult<ArtReader>,
    image: ImageBuf<Rgba<u8>>,
    texture: Texture
}

impl TileScene {
    pub fn new() -> BoxedScene {
        let mut reader = ArtReader::new(&Path::new("./assets/artidx.mul"), &Path::new("./assets/art.mul"));
        let mut image = match reader {
            Ok(ref mut reader) => {
                let tile = match reader.read(0).ok().expect("Couldn't load tile 0") {
                    TileOrStatic::Tile(tile) => tile,
                    TileOrStatic::Static(tile) => panic!("LOL")
                };
                let (width, height, data) = tile.to_32bit();
                ImageBuf::from_pixels(data, width, height)
            }
            _ => ImageBuf::new(44, 44)
        };
        let mut texture = Texture::from_image(&image);

        let mut scene = box TileScene {
            reader: reader,
            image: image,
            texture: texture
        };

        scene
    }

    fn render(&self, args: RenderArgs, uic: &mut UiContext, gl: &mut Gl) {
        uic.background().color(Color::black()).draw(gl);
        let c = Context::abs(args.width as f64, args.height as f64);
        c.image(&self.texture).draw(gl);
    }
}

impl Scene for TileScene {
    fn handle_event(&mut self, e: &Event, ui_context: &mut UiContext, gl: &mut Gl) -> Option<BoxedScene> {
        match *e {
            Event::Render(args) => {
                self.render(args, ui_context, gl);
            },
            Event::Input(Release(Keyboard(key))) => {
                match key {
                    keyboard::Left => {
                    },
                    keyboard::Right => {
                    },
                    _ => ()
                }
            },
            _ => ()
        };
        None
    }
}
<commit_msg>Tile 0 renders<commit_after>use scene::{BoxedScene, Scene};
use event::{Event, RenderArgs};
use conrod::UiContext;
use opengl_graphics::{Gl, Texture};
use graphics::{Context, AddImage, Draw};
use conrod::{
    Background,
    Color,
    Colorable,
    Drawable,
    Label,
    Labelable,
    Positionable
};
use input::{Release, Keyboard, keyboard};
use uorustlibs::art::{ArtReader, TileOrStatic, Art};
use uorustlibs::color::{Color16, Color32};
use uorustlibs::color::Color as ColorTrait;
use image::{GenericImage, ImageBuf, Rgba};

use std::io::IoResult;

pub struct TileScene {
    reader: IoResult<ArtReader>,
    image: ImageBuf<Rgba<u8>>,
    texture: Texture
}

impl TileScene {
    pub fn new() -> BoxedScene {
        let mut reader = ArtReader::new(&Path::new("./assets/artidx.mul"), &Path::new("./assets/art.mul"));
        let mut image = match reader {
            Ok(ref mut reader) => {
                let tile = match reader.read(0).ok().expect("Couldn't load tile 0") {
                    TileOrStatic::Tile(tile) => tile,
                    TileOrStatic::Static(tile) => panic!("LOL")
                };
                let (width, height, data) = tile.to_32bit();
                ImageBuf::from_fn(width, height, |x, y| {
                    let (r, g, b, a) = data[((x % height) + (y * width)) as uint].to_rgba();
                    Rgba(r, g, b, a)
                })
            }
            _ => ImageBuf::new(44, 44)
        };
        let mut texture = Texture::from_image(&image);

        let mut scene = box TileScene {
            reader: reader,
            image: image,
            texture: texture
        };

        scene
    }

    fn render(&self, args: RenderArgs, uic: &mut UiContext, gl: &mut Gl) {
        uic.background().color(Color::black()).draw(gl);
        let c = Context::abs(args.width as f64, args.height as f64);
        c.image(&self.texture).draw(gl);
    }
}

impl Scene for TileScene {
    fn handle_event(&mut self, e: &Event, ui_context: &mut UiContext, gl: &mut Gl) -> Option<BoxedScene> {
        match *e {
            Event::Render(args) => {
                self.render(args, ui_context, gl);
            },
            Event::Input(Release(Keyboard(key))) => {
                match key {
                    keyboard::Left => {
                    },
                    keyboard::Right => {
                    },
                    _ => ()
                }
            },
            _ => ()
        };
        None
    }
}
<|endoftext|>


<commit_before>#![feature(proc_macro)]

mod tests {
    extern crate bitfield_register;
    extern crate bitfield_register_macro;

    use self::bitfield_register_macro::register;

    #[register()]
    struct Bit0Test {
        #[bitfield(at=0)]
        bit: u8,
    }

    #[test]
    fn bit_0_is_lsb() {
        let mut test = Bit0Test::default();

        assert_eq!(test.get_bit(), 0);
        assert_eq!(test.0, [0;1]);

        test.set_bit(1);

        assert_eq!(test.get_bit(), 1);
        assert_eq!(test.0, [1;1]);
    }
}
<commit_msg>Add more tests<commit_after>#![feature(proc_macro)]

mod tests {
    extern crate bitfield_register;
    extern crate bitfield_register_macro;

    use self::bitfield_register_macro::register;

    #[register()]
    struct Bit0Test {
        #[bitfield(at=0)]
        bit: u8,
    }

    #[test]
    fn bit_0_is_lsb() {
        let mut test = Bit0Test::default();

        assert_eq!(test.get_bit(), 0);
        assert_eq!(test.0, [0;1]);

        test.set_bit(1);

        assert_eq!(test.get_bit(), 1);
        assert_eq!(test.0, [1;1]);
    }

    #[register()]
    struct Bit7Test {
        #[bitfield(at=7)]
        bit: u8,
    }

    #[test]
    fn bit_7_is_msb() {
        let mut test = Bit7Test::default();

        assert_eq!(test.get_bit(), 0);
        assert_eq!(test.0, [0;1]);

        test.set_bit(1);

        assert_eq!(test.get_bit(), 1);
        assert_eq!(test.0, [128;1]);
    }

    #[register()]
    struct Bit8Test {
        #[bitfield(at=8)]
        bit: u8,
    }

    #[test]
    fn bit_8_is_lsb() {
        let mut test = Bit8Test::default();

        assert_eq!(test.get_bit(), 0);
        assert_eq!(test.0, [0;2]);

        test.set_bit(1);

        assert_eq!(test.get_bit(), 1);
        assert_eq!(test.0, [0,1]);
    }

    #[register()]
    struct Bit15Test {
        #[bitfield(at=15)]
        bit: u8,
    }

    #[test]
    fn bit_15_is_msb() {
        let mut test = Bit15Test::default();

        assert_eq!(test.get_bit(), 0);
        assert_eq!(test.0, [0;2]);

        test.set_bit(1);

        assert_eq!(test.get_bit(), 1);
        assert_eq!(test.0, [0,128]);
    }

    #[register()]
    struct Field00Test {
        #[bitfield(from=0, to=0)]
        field: u8,
    }

    #[test]
    fn field_0_0_is_in_lsb() {
        let mut test = Field00Test::default();

        assert_eq!(test.get_field(), 0);
        assert_eq!(test.0, [0;1]);

        test.set_field(0b1);

        assert_eq!(test.get_field(), 1);
        assert_eq!(test.0, [0b1]);

        test.set_field(0b11);

        assert_eq!(test.get_field(), 0b1);
        assert_eq!(test.0, [0b1]);

        test.0 = [0b11111111];
        assert_eq!(test.get_field(), 0b1);
        assert_eq!(test.0, [0b11111111]);
    }

    #[register()]
    struct Field03Test {
        #[bitfield(from=0, to=3)]
        field: u8,
    }

    #[test]
    fn field_0_3_is_in_lsb() {
        let mut test = Field03Test::default();

        assert_eq!(test.get_field(), 0);
        assert_eq!(test.0, [0;1]);

        test.set_field(0b1);

        assert_eq!(test.get_field(), 1);
        assert_eq!(test.0, [0b1]);

        test.set_field(0b1111);

        assert_eq!(test.get_field(), 0b1111);
        assert_eq!(test.0, [0b1111]);

        test.set_field(0b11111);

        assert_eq!(test.get_field(), 0b1111);
        assert_eq!(test.0, [0b1111]);

        test.0 = [0b11111111];
        assert_eq!(test.get_field(), 0b1111);
        assert_eq!(test.0, [0b11111111]);
    }

    #[register()]
    struct Field25Test {
        #[bitfield(from=2, to=5)]
        field: u8,
    }

    #[test]
    fn field_2_5_test() {
        let mut test = Field25Test::default();

        assert_eq!(test.get_field(), 0);
        assert_eq!(test.0, [0;1]);

        test.set_field(0b1);

        assert_eq!(test.get_field(), 0b1);
        assert_eq!(test.0, [0b100]);

        test.set_field(0b1111);

        assert_eq!(test.get_field(), 0b1111);
        assert_eq!(test.0, [0b111100]);

        test.set_field(0b11111);

        assert_eq!(test.get_field(), 0b1111);
        assert_eq!(test.0, [0b111100]);

        test.0 = [0b11111111];
        assert_eq!(test.get_field(), 0b1111);
        assert_eq!(test.0, [0b11111111]);
    }
}
<|endoftext|>


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

extern crate cgmath;

use cgmath::{Point1, Point2, Point3, Vector1, Vector2, Vector3, Vector4};

// Sanity checks
#[test]
fn test_point() {
    let p1 = Point1::new(1.0);
    let p2 = Point2::new(1.0, 2.0);
    let p3 = Point3::new(1.0, 2.0, 3.0);
    assert_eq!(p1.x(), p1);
    assert_eq!(p2.x(), p1);
    assert_eq!(p2.y(), Point1::new(2.0));
    assert_eq!(p2.xx(), Point2::new(1.0, 1.0));
    assert_eq!(p2.xy(), p2);
    assert_eq!(p2.yx(), Point2::new(2.0, 1.0));
    assert_eq!(p2.yy(), Point2::new(2.0, 2.0));
    assert_eq!(p3.x(), p1);
    assert_eq!(p3.y(), Point1::new(2.0));
    assert_eq!(p3.xy(), p2);
    assert_eq!(p3.zy(), Point2::new(3.0, 2.0));
    assert_eq!(p3.yyx(), Point3::new(2.0, 2.0, 1.0));
}

#[test]
fn test_vector() {
    let p1 = Vector1::new(1.0);
    let p2 = Vector2::new(1.0, 2.0);
    let p3 = Vector3::new(1.0, 2.0, 3.0);
    let p4 = Vector4::new(1.0, 2.0, 3.0, 4.0);
    assert_eq!(p1.x(), p1);
    assert_eq!(p2.x(), p1);
    assert_eq!(p2.y(), Vector1::new(2.0));
    assert_eq!(p2.xx(), Vector2::new(1.0, 1.0));
    assert_eq!(p2.xy(), p2);
    assert_eq!(p2.yx(), Vector2::new(2.0, 1.0));
    assert_eq!(p2.yy(), Vector2::new(2.0, 2.0));
    assert_eq!(p3.x(), p1);
    assert_eq!(p3.y(), Vector1::new(2.0));
    assert_eq!(p3.xy(), p2);
    assert_eq!(p3.zy(), Vector2::new(3.0, 2.0));
    assert_eq!(p3.yyx(), Vector3::new(2.0, 2.0, 1.0));
    assert_eq!(p4.xyxy(), Vector4::new(1.0, 2.0, 1.0, 2.0));
}
<commit_msg>Guard the swizzle test by the "swizzle" feature flag. Also rename the swizzle tests with a "swizzle" postfix to easier see these in the test log.<commit_after>// Copyright 2013-2017 The CGMath Developers. For a full listing of the authors,
// refer to the Cargo.toml file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![cfg(feature = "swizzle")]

extern crate cgmath;

use cgmath::{Point1, Point2, Point3, Vector1, Vector2, Vector3, Vector4};

// Sanity checks
#[test]
fn test_point_swizzle() {
    let p1 = Point1::new(1.0);
    let p2 = Point2::new(1.0, 2.0);
    let p3 = Point3::new(1.0, 2.0, 3.0);
    assert_eq!(p1.x(), p1);
    assert_eq!(p2.x(), p1);
    assert_eq!(p2.y(), Point1::new(2.0));
    assert_eq!(p2.xx(), Point2::new(1.0, 1.0));
    assert_eq!(p2.xy(), p2);
    assert_eq!(p2.yx(), Point2::new(2.0, 1.0));
    assert_eq!(p2.yy(), Point2::new(2.0, 2.0));
    assert_eq!(p3.x(), p1);
    assert_eq!(p3.y(), Point1::new(2.0));
    assert_eq!(p3.xy(), p2);
    assert_eq!(p3.zy(), Point2::new(3.0, 2.0));
    assert_eq!(p3.yyx(), Point3::new(2.0, 2.0, 1.0));
}

#[test]
fn test_vector_swizzle() {
    let p1 = Vector1::new(1.0);
    let p2 = Vector2::new(1.0, 2.0);
    let p3 = Vector3::new(1.0, 2.0, 3.0);
    let p4 = Vector4::new(1.0, 2.0, 3.0, 4.0);
    assert_eq!(p1.x(), p1);
    assert_eq!(p2.x(), p1);
    assert_eq!(p2.y(), Vector1::new(2.0));
    assert_eq!(p2.xx(), Vector2::new(1.0, 1.0));
    assert_eq!(p2.xy(), p2);
    assert_eq!(p2.yx(), Vector2::new(2.0, 1.0));
    assert_eq!(p2.yy(), Vector2::new(2.0, 2.0));
    assert_eq!(p3.x(), p1);
    assert_eq!(p3.y(), Vector1::new(2.0));
    assert_eq!(p3.xy(), p2);
    assert_eq!(p3.zy(), Vector2::new(3.0, 2.0));
    assert_eq!(p3.yyx(), Vector3::new(2.0, 2.0, 1.0));
    assert_eq!(p4.xyxy(), Vector4::new(1.0, 2.0, 1.0, 2.0));
}
<|endoftext|>


<commit_before>use std::sync::{Once, ONCE_INIT};

use declare::ClassDecl;
use encode;
use runtime::{Class, Object, Sel};
use {Encode, Encoding, Id};

pub fn sample_object() -> Id<Object> {
    let cls = Class::get("NSObject").unwrap();
    unsafe {
        let obj: *mut Object = msg_send![cls, alloc];
        let obj: *mut Object = msg_send![obj, init];
        Id::from_retained_ptr(obj)
    }
}

#[derive(Eq, PartialEq)]
pub struct CustomStruct {
    pub a: u64,
    pub b: u64,
    pub c: u64,
    pub d: u64,
}

unsafe impl Encode for CustomStruct {
    fn encode() -> Encoding {
        let code = encode!(struct CustomStruct { u64, u64, u64, u64 });
        encode::from_static_str(code)
    }
}

static REGISTER_CUSTOM_CLASS: Once = ONCE_INIT;

pub fn custom_class() -> &'static Class {
    REGISTER_CUSTOM_CLASS.call_once(|| {
        let superclass = Class::get("NSObject").unwrap();
        let mut decl = ClassDecl::new(superclass, "CustomObject").unwrap();

        decl.add_ivar::<u32>("_foo");

        extern fn custom_obj_set_foo(this: &mut Object, _cmd: Sel, foo: u32) {
            unsafe { this.set_ivar::<u32>("_foo", foo); }
        }

        extern fn custom_obj_get_foo(this: &Object, _cmd: Sel) -> u32 {
            unsafe { *this.get_ivar::<u32>("_foo") }
        }

        extern fn custom_obj_get_struct(_this: &Object, _cmd: Sel) -> CustomStruct {
            CustomStruct { a: 1, b: 2, c: 3, d: 4 }
        }

        extern fn custom_obj_class_method(_this: &Class, _cmd: Sel) -> u32 {
            7
        }

        unsafe {
            let set_foo: extern fn(&mut Object, Sel, u32) = custom_obj_set_foo;
            decl.add_method(sel!(setFoo:), set_foo);
            let get_foo: extern fn(&Object, Sel) -> u32 = custom_obj_get_foo;
            decl.add_method(sel!(foo), get_foo);
            let get_struct: extern fn(&Object, Sel) -> CustomStruct = custom_obj_get_struct;
            decl.add_method(sel!(customStruct), get_struct);
            let class_method: extern fn(&Class, Sel) -> u32 = custom_obj_class_method;
            decl.add_class_method(sel!(classFoo), class_method);
        }

        decl.register();
    });

    Class::get("CustomObject").unwrap()
}

pub fn custom_object() -> Id<Object> {
    let cls = custom_class();
    unsafe {
        let obj: *mut Object = msg_send![cls, alloc];
        let obj: *mut Object = msg_send![obj, init];
        Id::from_retained_ptr(obj)
    }
}

static REGISTER_CUSTOM_SUBCLASS: Once = ONCE_INIT;

pub fn custom_subclass() -> &'static Class {
    REGISTER_CUSTOM_SUBCLASS.call_once(|| {
        let superclass = custom_class();
        let mut decl = ClassDecl::new(superclass, "CustomSubclassObject").unwrap();

        extern fn custom_subclass_get_foo(this: &Object, _cmd: Sel) -> u32 {
            let foo: u32 = unsafe {
                msg_send![super(this, custom_class()), foo]
            };
            foo + 2
        }

        unsafe {
            let get_foo: extern fn(&Object, Sel) -> u32 = custom_subclass_get_foo;
            decl.add_method(sel!(foo), get_foo);
        }

        decl.register();
    });

    Class::get("CustomSubclassObject").unwrap()
}

pub fn custom_subclass_object() -> Id<Object> {
    let cls = custom_subclass();
    unsafe {
        let obj: *mut Object = msg_send![cls, alloc];
        let obj: *mut Object = msg_send![obj, init];
        Id::from_retained_ptr(obj)
    }
}
<commit_msg>Replace Id in test_utils.<commit_after>use std::ops::Deref;
use std::sync::{Once, ONCE_INIT};

use declare::ClassDecl;
use encode;
use runtime::{Class, Object, Sel};
use {Encode, Encoding};

pub struct StrongPtr(*mut Object);

impl Deref for StrongPtr {
    type Target = Object;

    fn deref(&self) -> &Object {
        unsafe { &*self.0 }
    }
}

impl Drop for StrongPtr {
    fn drop(&mut self) {
        let _: () = unsafe { msg_send![self.0, release] };
    }
}

pub fn sample_object() -> StrongPtr {
    let cls = Class::get("NSObject").unwrap();
    unsafe {
        let obj: *mut Object = msg_send![cls, alloc];
        let obj: *mut Object = msg_send![obj, init];
        StrongPtr(obj)
    }
}

#[derive(Eq, PartialEq)]
pub struct CustomStruct {
    pub a: u64,
    pub b: u64,
    pub c: u64,
    pub d: u64,
}

unsafe impl Encode for CustomStruct {
    fn encode() -> Encoding {
        let code = encode!(struct CustomStruct { u64, u64, u64, u64 });
        encode::from_static_str(code)
    }
}

static REGISTER_CUSTOM_CLASS: Once = ONCE_INIT;

pub fn custom_class() -> &'static Class {
    REGISTER_CUSTOM_CLASS.call_once(|| {
        let superclass = Class::get("NSObject").unwrap();
        let mut decl = ClassDecl::new(superclass, "CustomObject").unwrap();

        decl.add_ivar::<u32>("_foo");

        extern fn custom_obj_set_foo(this: &mut Object, _cmd: Sel, foo: u32) {
            unsafe { this.set_ivar::<u32>("_foo", foo); }
        }

        extern fn custom_obj_get_foo(this: &Object, _cmd: Sel) -> u32 {
            unsafe { *this.get_ivar::<u32>("_foo") }
        }

        extern fn custom_obj_get_struct(_this: &Object, _cmd: Sel) -> CustomStruct {
            CustomStruct { a: 1, b: 2, c: 3, d: 4 }
        }

        extern fn custom_obj_class_method(_this: &Class, _cmd: Sel) -> u32 {
            7
        }

        unsafe {
            let set_foo: extern fn(&mut Object, Sel, u32) = custom_obj_set_foo;
            decl.add_method(sel!(setFoo:), set_foo);
            let get_foo: extern fn(&Object, Sel) -> u32 = custom_obj_get_foo;
            decl.add_method(sel!(foo), get_foo);
            let get_struct: extern fn(&Object, Sel) -> CustomStruct = custom_obj_get_struct;
            decl.add_method(sel!(customStruct), get_struct);
            let class_method: extern fn(&Class, Sel) -> u32 = custom_obj_class_method;
            decl.add_class_method(sel!(classFoo), class_method);
        }

        decl.register();
    });

    Class::get("CustomObject").unwrap()
}

pub fn custom_object() -> StrongPtr {
    let cls = custom_class();
    unsafe {
        let obj: *mut Object = msg_send![cls, alloc];
        let obj: *mut Object = msg_send![obj, init];
        StrongPtr(obj)
    }
}

static REGISTER_CUSTOM_SUBCLASS: Once = ONCE_INIT;

pub fn custom_subclass() -> &'static Class {
    REGISTER_CUSTOM_SUBCLASS.call_once(|| {
        let superclass = custom_class();
        let mut decl = ClassDecl::new(superclass, "CustomSubclassObject").unwrap();

        extern fn custom_subclass_get_foo(this: &Object, _cmd: Sel) -> u32 {
            let foo: u32 = unsafe {
                msg_send![super(this, custom_class()), foo]
            };
            foo + 2
        }

        unsafe {
            let get_foo: extern fn(&Object, Sel) -> u32 = custom_subclass_get_foo;
            decl.add_method(sel!(foo), get_foo);
        }

        decl.register();
    });

    Class::get("CustomSubclassObject").unwrap()
}

pub fn custom_subclass_object() -> StrongPtr {
    let cls = custom_subclass();
    unsafe {
        let obj: *mut Object = msg_send![cls, alloc];
        let obj: *mut Object = msg_send![obj, init];
        StrongPtr(obj)
    }
}
<|endoftext|>


<commit_before>pub fn main() {
    let number = 13;
    // TODO ^ Try different values for `number`

    println!("Tell me about {}", number);
    match number {
        // Match a single value
        1 => println!("One!"),
        // Match several values
        2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
        // Match an inclusive range
        13...19 => println!("A teen"),
        // Handle the rest of cases
        _ => println!("Ain't special"),
    }

    let boolean = true;
    // Match is an expression too
    let binary = match boolean {
        // The arms of a match must cover all the possible values
        false => 0,
        //true => 1,
        _ => 1,
        // TODO ^ Try commenting out one of these arms
    };

    println!("{} -> {}", boolean, binary);

    destructured_tuples();
}

fn destructured_tuples() {
    let pair = (0, -2);
    // TODO ^ Try different values for `pair`

    println!("Tell me about {:?}", pair);
    // Match can be used to destructure a tuple
    match pair {
        // Destructure the second
        (0, y) => println!("First is `0` and `y` is `{:?}`", y),
        (x, 0) => println!("`x` is `{:?}` and last is `0`", x),
        _      => println!("It doesn't matter what they are"),
        // `_` means don't bind the value to a variable
    }
}<commit_msg>Rust By Examples [RBE] - destructured - 7.5.1.2 enums<commit_after>pub fn main() {
    let number = 13;
    // TODO ^ Try different values for `number`

    println!("Tell me about {}", number);
    match number {
        // Match a single value
        1 => println!("One!"),
        // Match several values
        2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
        // Match an inclusive range
        13...19 => println!("A teen"),
        // Handle the rest of cases
        _ => println!("Ain't special"),
    }

    let boolean = true;
    // Match is an expression too
    let binary = match boolean {
        // The arms of a match must cover all the possible values
        false => 0,
        //true => 1,
        _ => 1,
        // TODO ^ Try commenting out one of these arms
    };

    println!("{} -> {}", boolean, binary);

    destructured_tuples();
    destructured_enums();
}

fn destructured_tuples() {
    let pair = (0, -2);
    // TODO ^ Try different values for `pair`

    println!("Tell me about {:?}", pair);
    // Match can be used to destructure a tuple
    match pair {
        // Destructure the second
        (0, y) => println!("First is `0` and `y` is `{:?}`", y),
        (x, 0) => println!("`x` is `{:?}` and last is `0`", x),
        _      => println!("It doesn't matter what they are"),
        // `_` means don't bind the value to a variable
    }
}

// `allow` required to silence warnings because only
// one variant is used.
#[allow(dead_code)]
enum Color {
    // These 3 are specified solely by their name.
    Red,
    Blue,
    Green,
    // These likewise tie `u32` tuples to different names: color models.
    RGB(u32, u32, u32),
    HSV(u32, u32, u32),
    HSL(u32, u32, u32),
    CMY(u32, u32, u32),
    CMYK(u32, u32, u32, u32),
}

/// Match - Desctuctured Enums
fn destructured_enums() {
    let color = Color::RGB(122, 17, 40);
    // TODO ^ Try different variants for `color`

    println!("What color is it?");
    // An `enum` can be destructured using a `match`.
    match color {
        Color::Red   => println!("The color is Red!"),
        Color::Blue  => println!("The color is Blue!"),
        Color::Green => println!("The color is Green!"),
        Color::RGB(r, g, b) =>
            println!("Red: {}, green: {}, and blue: {}!", r, g, b),
        Color::HSV(h, s, v) =>
            println!("Hue: {}, saturation: {}, value: {}!", h, s, v),
        Color::HSL(h, s, l) =>
            println!("Hue: {}, saturation: {}, lightness: {}!", h, s, l),
        Color::CMY(c, m, y) =>
            println!("Cyan: {}, magenta: {}, yellow: {}!", c, m, y),
        Color::CMYK(c, m, y, k) =>
            println!("Cyan: {}, magenta: {}, yellow: {}, key (black): {}!",
                c, m, y, k),
        // Don't need another arm because all variants have been examined
    }
}
<|endoftext|>


<commit_before>#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
    }
}
<commit_msg>Remove tm2 module<commit_after><|endoftext|>


<commit_before>use context::Context;
use errors::Result;
use tera::Tera;

use super::NestedObject;

#[test]
fn render_macros() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros", "{% macro hello()%}Hello{% endmacro hello %}"),
        ("tpl", "{% import \"macros\" as macros %}{% block hey %}{{macros::hello()}}{% endblock hey %}"),
    ]).unwrap();

    let result = tera.render("tpl", &Context::new());

    assert_eq!(result.unwrap(), "Hello".to_string());
}

#[test]
fn render_macros_expression_arg() {
    let mut context = Context::new();
    context.add("pages", &vec![1, 2, 3, 4, 5]);
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros", "{% macro hello(val)%}{{val}}{% endmacro hello %}"),
        ("tpl", "{% import \"macros\" as macros %}{{macros::hello(val=pages|last)}}"),
    ]).unwrap();

    let result = tera.render("tpl", &context);

    assert_eq!(result.unwrap(), "5".to_string());
}

#[test]
fn render_macros_in_child_templates_same_namespace() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("grandparent", "{% block hey %}hello{% endblock hey %}"),
        ("macros", "{% macro hello()%}Hello{% endmacro hello %}"),
        ("macros2", "{% macro hi()%}Hi{% endmacro hi %}"),
        ("parent", "{% extends \"grandparent\" %}{% import \"macros\" as macros %}{% block hey %}{{macros::hello()}}{% endblock hey %}"),
        ("child", "{% extends \"parent\" %}{% import \"macros2\" as macros %}{% block hey %}{{super()}}/{{macros::hi()}}{% endblock hey %}"),
    ]).unwrap();

    let result = tera.render("child", &Context::new());

    assert_eq!(result.unwrap(), "Hello/Hi".to_string());
}

#[test]
fn render_macros_in_child_templates_different_namespace() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("grandparent", "{% block hey %}hello{% endblock hey %}"),
        ("macros", "{% macro hello()%}Hello{% endmacro hello %}"),
        ("macros2", "{% macro hi()%}Hi{% endmacro hi %}"),
        ("parent", "{% extends \"grandparent\" %}{% import \"macros\" as macros %}{% block hey %}{{macros::hello()}}{% endblock hey %}"),
        ("child", "{% extends \"parent\" %}{% import \"macros2\" as macros2 %}{% block hey %}{{super()}}/{{macros2::hi()}}{% endblock hey %}"),
    ]).unwrap();

    let result = tera.render("child", &Context::new());

    assert_eq!(result.unwrap(), "Hello/Hi".to_string());
}

#[test]
fn render_macros_in_parent_template_with_inheritance() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros", "{% macro hello()%}Hello{% endmacro hello %}"),
        ("grandparent", "{% import \"macros\" as macros %}{% block hey %}{{macros::hello()}}{% endblock hey %}"),
        ("child", "{% extends \"grandparent\" %}{% import \"macros\" as macros %}{% block hey %}{{super()}}/{{macros::hello()}}{% endblock hey %}"),
    ]).unwrap();

    let result = tera.render("child", &Context::new());

    assert_eq!(result.unwrap(), "Hello/Hello".to_string());
}

#[test]
fn macro_param_arent_escaped() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros.html", r#"{% macro print(val) %}{{val|safe}}{% endmacro print %}"#),
        ("hello.html", r#"{% import "macros.html" as macros %}{{ macros::print(val=my_var)}}"#),
    ]).unwrap();
    let mut context = Context::new();
    context.add("my_var", &"&");
    let result = tera.render("hello.html", &context);

    assert_eq!(result.unwrap(), "&".to_string());
}

#[test]
fn render_set_tag_macro() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros", "{% macro hello()%}Hello{% endmacro hello %}"),
        ("hello.html", "{% import \"macros\" as macros %}{% set my_var = macros::hello() %}{{my_var}}"),
    ]).unwrap();
    let result = tera.render("hello.html", &Context::new());

    assert_eq!(result.unwrap(), "Hello".to_string());
}

#[test]
fn render_macros_with_default_args() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros", "{% macro hello(val=1) %}{{val}}{% endmacro hello %}"),
        ("hello.html", "{% import \"macros\" as macros %}{{macros::hello()}}"),
    ]).unwrap();
    let result = tera.render("hello.html", &Context::new());

    assert_eq!(result.unwrap(), "1".to_string());
}

#[test]
fn render_macros_override_default_args() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros", "{% macro hello(val=1) %}{{val}}{% endmacro hello %}"),
        ("hello.html", "{% import \"macros\" as macros %}{{macros::hello(val=2)}}"),
    ]).unwrap();
    let result = tera.render("hello.html", &Context::new());

    assert_eq!(result.unwrap(), "2".to_string());
}

#[test]
fn render_recursive_macro() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros", "{% macro factorial(n) %}{% if n > 1 %}{{ n }} - {{ self::factorial(n=n-1) }}{% else %}1{% endif %}{{ n }}{% endmacro factorial %}"),
        ("hello.html", "{% import \"macros\" as macros %}{{macros::factorial(n=7)}}"),
    ]).unwrap();
    let result = tera.render("hello.html", &Context::new());

    assert_eq!(result.unwrap(), "7 - 6 - 5 - 4 - 3 - 2 - 11234567".to_string());
}

// https://github.com/Keats/tera/issues/202
#[test]
fn recursive_macro_with_loops() {
    let parent = NestedObject { label: "Parent".to_string(), parent: None, numbers: vec![1, 2, 3] };
    let child = NestedObject { label: "Child".to_string(), parent: Some(Box::new(parent)), numbers: vec![1, 2, 3] };
    let mut context = Context::new();
    context.add("objects", &vec![child]);
    let mut tera = Tera::default();

    tera.add_raw_templates(vec![
        (
            "macros.html",
            r#"
{% macro label_for(obj, sep) -%}
  {%- if obj.parent -%}
    {{ self::label_for(obj=obj.parent, sep=sep) }}{{sep}}
  {%- endif -%}
  {{obj.label}}
  {%- for i in obj.numbers -%}{{ i }}{%- endfor -%}
{%- endmacro label_for %}
            "#
        ),
        (
            "recursive",
            r#"
{%- import "macros.html" as macros -%}
{%- for obj in objects -%}
    {{ macros::label_for(obj=obj, sep="|") }}
{%- endfor -%}
"#
        ),
    ]).unwrap();

    let result = tera.render("recursive", &context);

    assert_eq!(result.unwrap(), "Parent123|Child123".to_string());
}
<commit_msg>Add regression test<commit_after>use context::Context;
use errors::Result;
use tera::Tera;

use super::NestedObject;

#[test]
fn render_macros() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros", "{% macro hello()%}Hello{% endmacro hello %}"),
        ("tpl", "{% import \"macros\" as macros %}{% block hey %}{{macros::hello()}}{% endblock hey %}"),
    ]).unwrap();

    let result = tera.render("tpl", &Context::new());

    assert_eq!(result.unwrap(), "Hello".to_string());
}

#[test]
fn render_macros_expression_arg() {
    let mut context = Context::new();
    context.add("pages", &vec![1, 2, 3, 4, 5]);
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros", "{% macro hello(val)%}{{val}}{% endmacro hello %}"),
        ("tpl", "{% import \"macros\" as macros %}{{macros::hello(val=pages|last)}}"),
    ]).unwrap();

    let result = tera.render("tpl", &context);

    assert_eq!(result.unwrap(), "5".to_string());
}

#[test]
fn render_macros_in_child_templates_same_namespace() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("grandparent", "{% block hey %}hello{% endblock hey %}"),
        ("macros", "{% macro hello()%}Hello{% endmacro hello %}"),
        ("macros2", "{% macro hi()%}Hi{% endmacro hi %}"),
        ("parent", "{% extends \"grandparent\" %}{% import \"macros\" as macros %}{% block hey %}{{macros::hello()}}{% endblock hey %}"),
        ("child", "{% extends \"parent\" %}{% import \"macros2\" as macros %}{% block hey %}{{super()}}/{{macros::hi()}}{% endblock hey %}"),
    ]).unwrap();

    let result = tera.render("child", &Context::new());

    assert_eq!(result.unwrap(), "Hello/Hi".to_string());
}

#[test]
fn render_macros_in_child_templates_different_namespace() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("grandparent", "{% block hey %}hello{% endblock hey %}"),
        ("macros", "{% macro hello()%}Hello{% endmacro hello %}"),
        ("macros2", "{% macro hi()%}Hi{% endmacro hi %}"),
        ("parent", "{% extends \"grandparent\" %}{% import \"macros\" as macros %}{% block hey %}{{macros::hello()}}{% endblock hey %}"),
        ("child", "{% extends \"parent\" %}{% import \"macros2\" as macros2 %}{% block hey %}{{super()}}/{{macros2::hi()}}{% endblock hey %}"),
    ]).unwrap();

    let result = tera.render("child", &Context::new());

    assert_eq!(result.unwrap(), "Hello/Hi".to_string());
}

#[test]
fn render_macros_in_parent_template_with_inheritance() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros", "{% macro hello()%}Hello{% endmacro hello %}"),
        ("grandparent", "{% import \"macros\" as macros %}{% block hey %}{{macros::hello()}}{% endblock hey %}"),
        ("child", "{% extends \"grandparent\" %}{% import \"macros\" as macros %}{% block hey %}{{super()}}/{{macros::hello()}}{% endblock hey %}"),
    ]).unwrap();

    let result = tera.render("child", &Context::new());

    assert_eq!(result.unwrap(), "Hello/Hello".to_string());
}

#[test]
fn macro_param_arent_escaped() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros.html", r#"{% macro print(val) %}{{val|safe}}{% endmacro print %}"#),
        ("hello.html", r#"{% import "macros.html" as macros %}{{ macros::print(val=my_var)}}"#),
    ]).unwrap();
    let mut context = Context::new();
    context.add("my_var", &"&");
    let result = tera.render("hello.html", &context);

    assert_eq!(result.unwrap(), "&".to_string());
}

#[test]
fn render_set_tag_macro() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros", "{% macro hello()%}Hello{% endmacro hello %}"),
        ("hello.html", "{% import \"macros\" as macros %}{% set my_var = macros::hello() %}{{my_var}}"),
    ]).unwrap();
    let result = tera.render("hello.html", &Context::new());

    assert_eq!(result.unwrap(), "Hello".to_string());
}

#[test]
fn render_macros_with_default_args() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros", "{% macro hello(val=1) %}{{val}}{% endmacro hello %}"),
        ("hello.html", "{% import \"macros\" as macros %}{{macros::hello()}}"),
    ]).unwrap();
    let result = tera.render("hello.html", &Context::new());

    assert_eq!(result.unwrap(), "1".to_string());
}

#[test]
fn render_macros_override_default_args() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros", "{% macro hello(val=1) %}{{val}}{% endmacro hello %}"),
        ("hello.html", "{% import \"macros\" as macros %}{{macros::hello(val=2)}}"),
    ]).unwrap();
    let result = tera.render("hello.html", &Context::new());

    assert_eq!(result.unwrap(), "2".to_string());
}

#[test]
fn render_recursive_macro() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros", "{% macro factorial(n) %}{% if n > 1 %}{{ n }} - {{ self::factorial(n=n-1) }}{% else %}1{% endif %}{{ n }}{% endmacro factorial %}"),
        ("hello.html", "{% import \"macros\" as macros %}{{macros::factorial(n=7)}}"),
    ]).unwrap();
    let result = tera.render("hello.html", &Context::new());

    assert_eq!(result.unwrap(), "7 - 6 - 5 - 4 - 3 - 2 - 11234567".to_string());
}

// https://github.com/Keats/tera/issues/202
#[test]
fn recursive_macro_with_loops() {
    let parent = NestedObject { label: "Parent".to_string(), parent: None, numbers: vec![1, 2, 3] };
    let child = NestedObject { label: "Child".to_string(), parent: Some(Box::new(parent)), numbers: vec![1, 2, 3] };
    let mut context = Context::new();
    context.add("objects", &vec![child]);
    let mut tera = Tera::default();

    tera.add_raw_templates(vec![
        (
            "macros.html",
            r#"
{% macro label_for(obj, sep) -%}
  {%- if obj.parent -%}
    {{ self::label_for(obj=obj.parent, sep=sep) }}{{sep}}
  {%- endif -%}
  {{obj.label}}
  {%- for i in obj.numbers -%}{{ i }}{%- endfor -%}
{%- endmacro label_for %}
            "#
        ),
        (
            "recursive",
            r#"
{%- import "macros.html" as macros -%}
{%- for obj in objects -%}
    {{ macros::label_for(obj=obj, sep="|") }}
{%- endfor -%}
"#
        ),
    ]).unwrap();

    let result = tera.render("recursive", &context);

    assert_eq!(result.unwrap(), "Parent123|Child123".to_string());
}

// https://github.com/Keats/tera/issues/250
#[test]
fn render_macros_in_included() {
    let mut tera = Tera::default();
    tera.add_raw_templates(vec![
        ("macros", "{% macro my_macro() %}my macro{% endmacro %}"),
        ("includeme", r#"{% import "macros" as macros %}{{ macros::my_macro() }}"#),
        ("example", r#"{% include "includeme" %}"#),
    ]).unwrap();
    let result = tera.render("example", &Context::new());

    assert_eq!(result.unwrap(), "my macro".to_string());
}
<|endoftext|>


<commit_before>use std::fs::File;
use std::io::{Read, Write};
use std::mem;

use orbclient::MouseEvent;

bitflags! {
    flags MousePacketFlags: u8 {
        const LEFT_BUTTON = 1,
        const RIGHT_BUTTON = 1 << 1,
        const MIDDLE_BUTTON = 1 << 2,
        const ALWAYS_ON = 1 << 3,
        const X_SIGN = 1 << 4,
        const Y_SIGN = 1 << 5,
        const X_OVERFLOW = 1 << 6,
        const Y_OVERFLOW = 1 << 7
    }
}

pub fn mouse(extra_packet: bool) {
    let mut file = File::open("irq:12").expect("ps2d: failed to open irq:12");
    let mut input = File::open("display:input").expect("ps2d: failed to open display:input");

    let mut packets = [0; 4];
    let mut packet_i = 0;
    loop {
        let mut irqs = [0; 8];
        if file.read(&mut irqs).expect("ps2d: failed to read irq:12") >= mem::size_of::<usize>() {
            let data: u8;
            unsafe {
                asm!("in al, dx" : "={al}"(data) : "{dx}"(0x60) : : "intel", "volatile");
            }

            packets[packet_i] = data;
            packet_i += 1;

            let flags = MousePacketFlags::from_bits_truncate(packets[0]);
            if ! flags.contains(ALWAYS_ON) {
                println!("MOUSE MISALIGN {:X}", packets[0]);

                packets = [0; 4];
                packet_i = 0;
            } else if packet_i >= packets.len() || (!extra_packet && packet_i >= 3) {
                if ! flags.contains(X_OVERFLOW) && ! flags.contains(Y_OVERFLOW) {
                    let mut dx = packets[1] as i32;
                    if flags.contains(X_SIGN) {
                        dx -= 0x100;
                    }

                    let mut dy = -(packets[2] as i32);
                    if flags.contains(Y_SIGN) {
                        dy += 0x100;
                    }

                    let _extra = if extra_packet {
                        packets[3]
                    } else {
                        0
                    };

                    input.write(&MouseEvent {
                        x: dx,
                        y: dy,
                        left_button: flags.contains(LEFT_BUTTON),
                        middle_button: flags.contains(MIDDLE_BUTTON),
                        right_button: flags.contains(RIGHT_BUTTON)
                    }.to_event()).expect("ps2d: failed to write mouse event");
                } else {
                    println!("ps2d: overflow {:X} {:X} {:X} {:X}", packets[0], packets[1], packets[2], packets[3]);
                }

                packets = [0; 4];
                packet_i = 0;
            }

            file.write(&irqs).expect("ps2d: failed to write irq:12");
        }
    }
}
<commit_msg>Move IRQ ack higher in mouse driver<commit_after>use std::fs::File;
use std::io::{Read, Write};
use std::mem;

use orbclient::MouseEvent;

bitflags! {
    flags MousePacketFlags: u8 {
        const LEFT_BUTTON = 1,
        const RIGHT_BUTTON = 1 << 1,
        const MIDDLE_BUTTON = 1 << 2,
        const ALWAYS_ON = 1 << 3,
        const X_SIGN = 1 << 4,
        const Y_SIGN = 1 << 5,
        const X_OVERFLOW = 1 << 6,
        const Y_OVERFLOW = 1 << 7
    }
}

pub fn mouse(extra_packet: bool) {
    let mut file = File::open("irq:12").expect("ps2d: failed to open irq:12");
    let mut input = File::open("display:input").expect("ps2d: failed to open display:input");

    let mut packets = [0; 4];
    let mut packet_i = 0;
    loop {
        let mut irqs = [0; 8];
        if file.read(&mut irqs).expect("ps2d: failed to read irq:12") >= mem::size_of::<usize>() {
            let data: u8;
            unsafe {
                asm!("in al, dx" : "={al}"(data) : "{dx}"(0x60) : : "intel", "volatile");
            }

            file.write(&irqs).expect("ps2d: failed to write irq:12");

            packets[packet_i] = data;
            packet_i += 1;

            let flags = MousePacketFlags::from_bits_truncate(packets[0]);
            if ! flags.contains(ALWAYS_ON) {
                println!("MOUSE MISALIGN {:X}", packets[0]);

                packets = [0; 4];
                packet_i = 0;
            } else if packet_i >= packets.len() || (!extra_packet && packet_i >= 3) {
                if ! flags.contains(X_OVERFLOW) && ! flags.contains(Y_OVERFLOW) {
                    let mut dx = packets[1] as i32;
                    if flags.contains(X_SIGN) {
                        dx -= 0x100;
                    }

                    let mut dy = -(packets[2] as i32);
                    if flags.contains(Y_SIGN) {
                        dy += 0x100;
                    }

                    let _extra = if extra_packet {
                        packets[3]
                    } else {
                        0
                    };

                    input.write(&MouseEvent {
                        x: dx,
                        y: dy,
                        left_button: flags.contains(LEFT_BUTTON),
                        middle_button: flags.contains(MIDDLE_BUTTON),
                        right_button: flags.contains(RIGHT_BUTTON)
                    }.to_event()).expect("ps2d: failed to write mouse event");
                } else {
                    println!("ps2d: overflow {:X} {:X} {:X} {:X}", packets[0], packets[1], packets[2], packets[3]);
                }

                packets = [0; 4];
                packet_i = 0;
            }
        }
    }
}
<|endoftext|>


<commit_before>#![crate_id="CSVProvider#0.1-pre"]
#![crate_type="dylib"]

// why doesn't "lib" work?

// rustc 0.11.0-pre (b47f2226a25654c5b781d27a91f2fa5274b3a347 2014-06-28 14:31:37 +0000)

#![feature(globs, macro_rules, quote, managed_boxes, plugin_registrar)]

#![allow(unused_imports)]
#![allow(unused_variable)]

extern crate syntax;
extern crate rustc;

use syntax::ast::{
   Name,
   TokenTree,
   Expr,
   ExprLit,
   ExprVec,
   LitStr,
   Ident,
   DUMMY_NODE_ID,
   MutImmutable
};
use syntax::codemap::Span;
use syntax::ext::base::{
   SyntaxExtension,
   BasicMacroExpander,
   ExtCtxt,
   MacResult,
   MacPat,
   MacItem,
   DummyResult,
   MacExpr,
   NormalTT
};
use std::gc::Gc;
use syntax::parse;
use syntax::parse::token;
use syntax::parse::token::{InternedString, COMMA, EOF};

use std::io;
use std::io::fs;
use std::os;
use std::str;
use std::io::Process;
use syntax::ast;
use syntax::ast::Name;

use syntax::util::small_vector::SmallVector;

use std::collections::HashMap;
use std::gc::{Gc, GC};

use rustc::plugin::Registry;

#[plugin_registrar]
pub fn macro_registrar(reg: &mut Registry) {
   reg.register_macro("ProvideCSV_labels", provide_csv_given_labels);
}

#[deriving(Clone)]
struct Entry {
   str: InternedString,
   expr: Gc<Expr>
}

// see https://github.com/sfackler/syntax-ext-talk/blob/gh-pages/simple-ext/lib.rs
fn parse_entries(cx: &mut ExtCtxt, tts: &[TokenTree]) -> Option<Vec<Entry>> {
   let mut parser = parse::new_parser_from_tts(
       cx.parse_sess(),
       cx.cfg(),
       tts.iter()
          .map(|x| (*x).clone())
          .collect()
   );

   let mut entries: Vec<Entry> = Vec::new();

   let mut error = false;
   while parser.token != EOF {
      let entry = parser.parse_expr();

      let entry_str = match entry.node {
         ExprLit(lit) => {
            match lit.node {
               LitStr(ref s, _) => s.clone(),
               _ => {
                  cx.span_err(entry.span, "expected string literal (1)");
                  error = true;
                  InternedString::new("")
               }
            }
         }
         _ => {
                cx.span_err(entry.span, "expected string literal (2)");
                error = true;
                InternedString::new("")
         }
      };

      entries.push(Entry { str: entry_str, expr: entry });

      if !parser.eat(&COMMA) && parser.token != EOF {
         cx.span_err(parser.span, "expected `,`");
         return None;
      }
    }

   if error {
      return None;
   }

   Some(entries)
}

/// A convenience type for macros that return a single item.
pub struct MacItems {
   items: Vec<Gc<ast::Item>>
}

impl MacItems {
   pub fn new(items: Vec<Gc<ast::Item>>) -> Box<MacResult> {
      box MacItems { items: items } as Box<MacResult>
   }
}
impl MacResult for MacItems {
   fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
      Some(SmallVector::many(self.items.clone()))
   }
}

fn provide_csv_given_labels(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult> {
   let mut entries = match parse_entries(cx, tts) {
      Some(entries) => entries,
      None => return DummyResult::expr(sp),
   };

   let raw_name   : Entry = entries.shift().expect("should be given a type name");
   let raw_path   : Entry = entries.shift().expect("should be given a CSV file path");
   let raw_labels : Entry = entries.shift().expect("should be given column labels");

   let name   : InternedString = raw_name.str;
   let path   : InternedString = raw_path.str;
   let labels : InternedString = raw_labels.str;

   println!("provide_csv_given_labels: name:   {}", name);
   println!("provide_csv_given_labels: path:   {}", path);
   println!("provide_csv_given_labels: labels: {}", labels);

   // PENDING
   // read the CSV and try to get the type of data in it
   // create a type with
   //  * this name,
   //  * these labeled columns,
   //  * discovered type of data
   //  * a constructor which reads the whole file

/* OLD
   let banana = "YAY! BANANA!";
   return MacExpr::new(quote_expr!(cx, {let x: $banana = 44}));
 */

   let MyCSV : Ident = token::str_to_ident("MyCSV");

//   fn define_my_csv(cx0: &mut ExtCtxt) -> Option<Gc<syntax::ast::Item>> {
   let define_my_csv = |cx0 : &mut ExtCtxt| {
      let item1: Option<Gc<syntax::ast::Item>> = quote_item!(cx0,
//         pub struct  MyCSV {
         pub struct $MyCSV {
            pub data: Vec<(String)>,
         }
      );
      return item1;
   };
//   }

   let item1: Option<Gc<syntax::ast::Item>> = define_my_csv(cx);  // (1) Why is this necessary?

   let item2: Option<Gc<syntax::ast::Item>>  = quote_item!(cx,
      impl $MyCSV {
         pub fn new() -> $MyCSV {
            println!("HMMMMMM.");
            return $MyCSV {
               data: (vec!["zero".to_string(), "one".to_string(), "two".to_string()]),
            };
         }
      }
   );

   let items = vec![item1.expect("Should be able to construct MyCSV."),
                    item2.expect("Should be able to construct MyCSV.")];
   return MacItems::new(items);
}

<commit_msg>cleanup (still need to get interned string into &str, though)<commit_after>#![crate_id="CSVProvider#0.1-pre"]
#![crate_type="dylib"]

// why doesn't "lib" work?

// rustc 0.11.0-pre (b47f2226a25654c5b781d27a91f2fa5274b3a347 2014-06-28 14:31:37 +0000)

#![feature(globs, macro_rules, quote, managed_boxes, plugin_registrar)]

#![allow(unused_imports)]
//#![allow(unused_variable)]
#![allow(uppercase_variables)]

extern crate syntax;
extern crate rustc;

use syntax::ast::{
   Name,
   TokenTree,
   Expr,
   ExprLit,
   ExprVec,
   LitStr,
   Ident,
   DUMMY_NODE_ID,
   MutImmutable
};
use syntax::codemap::Span;
use syntax::ext::base::{
   SyntaxExtension,
   BasicMacroExpander,
   ExtCtxt,
   MacResult,
   MacPat,
   MacItem,
   DummyResult,
   MacExpr,
   NormalTT
};
use std::gc::Gc;
use syntax::parse;
use syntax::parse::token;
use syntax::parse::token::{InternedString, COMMA, EOF};

use std::io;
use std::io::fs;
use std::os;
use std::str;
use std::io::Process;
use syntax::ast;
use syntax::ast::Name;

use syntax::util::small_vector::SmallVector;

use std::collections::HashMap;
use std::gc::{Gc, GC};

use rustc::plugin::Registry;

#[plugin_registrar]
pub fn macro_registrar(reg: &mut Registry) {
   reg.register_macro("ProvideCSV_labels", provide_csv_given_labels);
}

#[deriving(Clone)]
struct Entry {
   str: InternedString,
   expr: Gc<Expr>
}

// see https://github.com/sfackler/syntax-ext-talk/blob/gh-pages/simple-ext/lib.rs
fn parse_entries(cx: &mut ExtCtxt, tts: &[TokenTree]) -> Option<Vec<Entry>> {
   let mut parser = parse::new_parser_from_tts(
       cx.parse_sess(),
       cx.cfg(),
       tts.iter()
          .map(|x| (*x).clone())
          .collect()
   );

   let mut entries: Vec<Entry> = Vec::new();

   let mut error = false;
   while parser.token != EOF {
      let entry = parser.parse_expr();

      let entry_str = match entry.node {
         ExprLit(lit) => {
            match lit.node {
               LitStr(ref s, _) => s.clone(),
               _ => {
                  cx.span_err(entry.span, "expected string literal (1)");
                  error = true;
                  InternedString::new("")
               }
            }
         }
         _ => {
                cx.span_err(entry.span, "expected string literal (2)");
                error = true;
                InternedString::new("")
         }
      };

      entries.push(Entry { str: entry_str, expr: entry });

      if !parser.eat(&COMMA) && parser.token != EOF {
         cx.span_err(parser.span, "expected `,`");
         return None;
      }
    }

   if error {
      return None;
   }

   Some(entries)
}

pub struct MacItems {
   items: Vec<Gc<ast::Item>>
}
impl MacItems {
   pub fn new(items: Vec<Gc<ast::Item>>) -> Box<MacResult> {
      box MacItems { items: items } as Box<MacResult>
   }
}
impl MacResult for MacItems {
   fn make_items(&self) -> Option<SmallVector<Gc<ast::Item>>> {
      Some(SmallVector::many(self.items.clone()))
   }
}

fn provide_csv_given_labels(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult> {
   let mut entries = match parse_entries(cx, tts) {
      Some(entries) => entries,
      None => return DummyResult::expr(sp),
   };

   let raw_name   : Entry = entries.shift().expect("should be given a type name");
   let raw_path   : Entry = entries.shift().expect("should be given a CSV file path");
   let raw_labels : Entry = entries.shift().expect("should be given column labels");

   let name   : InternedString = raw_name.str;
   let path   : InternedString = raw_path.str;
   let labels : InternedString = raw_labels.str;

   println!("provide_csv_given_labels: name:   {}", name);
   println!("provide_csv_given_labels: path:   {}", path);
   println!("provide_csv_given_labels: labels: {}", labels);

   // PENDING
   // read the CSV and try to get the type of data in it
   // create a type with
   //  * this name,
   //  * these labeled columns,
   //  * discovered type of data
   //  * a constructor which reads the whole file

   let MyCSV: Ident = token::str_to_ident("MyCSV");

   // FIXME: Why is this fn necessary?
   let define_my_csv = |cx0 : &mut ExtCtxt| {
      let item1: Option<Gc<syntax::ast::Item>> = quote_item!(cx0,
         pub struct $MyCSV {
            pub data: Vec<(String)>,
         }
      );
      return item1;
   };

   let item1: Option<Gc<syntax::ast::Item>> = define_my_csv(cx);

   let item2: Option<Gc<syntax::ast::Item>> = quote_item!(cx,
      impl $MyCSV {
         pub fn new() -> $MyCSV {
            println!("HMMMMMM.");
            return $MyCSV {
               data: (vec!["zero".to_string(), "one".to_string(), "two".to_string()]),
            };
         }
      }
   );

   let items = vec![item1.expect("Should be able to construct MyCSV."),
                    item2.expect("Should be able to construct MyCSV.")];
   return MacItems::new(items);
}

<|endoftext|>


<commit_before>#[macro_use]
extern crate askama_derive;
extern crate askama;

use askama::Template;

#[derive(Template)]
#[template(path = "simple.html")]
struct VariablesTemplate {
    strvar: String,
    num: i64,
    i18n: String,
}

#[test]
fn test_variables() {
    let s = VariablesTemplate {
        strvar: "foo".to_string(),
        num: 42,
        i18n: "Iñtërnâtiônàlizætiøn".to_string(),
    };
    assert_eq!(s.render(), "hello world, foo\n\
                            with number: 42\n\
                            Iñtërnâtiônàlizætiøn is important\n\
                            in vars too: Iñtërnâtiônàlizætiøn\n");
}

#[derive(Template)]
#[template(path = "if.html")]
struct IfTemplate {
    cond: bool,
}

#[test]
fn test_if() {
    let s = IfTemplate { cond: true };
    assert_eq!(s.render(), "true\n");
}

#[derive(Template)]
#[template(path = "else.html")]
struct ElseTemplate {
    cond: bool,
}

#[test]
fn test_else() {
    let s = ElseTemplate { cond: false };
    assert_eq!(s.render(), "false\n");
}

#[derive(Template)]
#[template(path = "else-if.html")]
struct ElseIfTemplate {
    cond: bool,
    check: bool,
}

#[test]
fn test_else_if() {
    let s = ElseIfTemplate { cond: false, check: true };
    assert_eq!(s.render(), "checked\n");
}

#[derive(Template)]
#[template(path = "for.html")]
struct ForTemplate {
    strings: Vec<String>,
}

#[test]
fn test_for() {
    let s = ForTemplate {
        strings: vec!["A".to_string(), "alfa".to_string(), "1".to_string()],
    };
    assert_eq!(s.render(), "\n  A\n\n  alfa\n\n  1\n\n");
}
<commit_msg>Use &str instead of String for test cases<commit_after>#[macro_use]
extern crate askama_derive;
extern crate askama;

use askama::Template;

#[derive(Template)]
#[template(path = "simple.html")]
struct VariablesTemplate<'a> {
    strvar: &'a str,
    num: i64,
    i18n: String,
}

#[test]
fn test_variables() {
    let s = VariablesTemplate {
        strvar: "foo",
        num: 42,
        i18n: "Iñtërnâtiônàlizætiøn".to_string(),
    };
    assert_eq!(s.render(), "hello world, foo\n\
                            with number: 42\n\
                            Iñtërnâtiônàlizætiøn is important\n\
                            in vars too: Iñtërnâtiônàlizætiøn\n");
}

#[derive(Template)]
#[template(path = "if.html")]
struct IfTemplate {
    cond: bool,
}

#[test]
fn test_if() {
    let s = IfTemplate { cond: true };
    assert_eq!(s.render(), "true\n");
}

#[derive(Template)]
#[template(path = "else.html")]
struct ElseTemplate {
    cond: bool,
}

#[test]
fn test_else() {
    let s = ElseTemplate { cond: false };
    assert_eq!(s.render(), "false\n");
}

#[derive(Template)]
#[template(path = "else-if.html")]
struct ElseIfTemplate {
    cond: bool,
    check: bool,
}

#[test]
fn test_else_if() {
    let s = ElseIfTemplate { cond: false, check: true };
    assert_eq!(s.render(), "checked\n");
}

#[derive(Template)]
#[template(path = "for.html")]
struct ForTemplate<'a> {
    strings: Vec<&'a str>,
}

#[test]
fn test_for() {
    let s = ForTemplate {
        strings: vec!["A", "alfa", "1"],
    };
    assert_eq!(s.render(), "\n  A\n\n  alfa\n\n  1\n\n");
}
<|endoftext|>


<commit_before>//! An example demonstrating sRGB color spaces.
//!
//! sRGB is one of those things that's a bit subtle, a bit obscure,
//! and easy to get wrong, but worth knowing because it crops up
//! from time to time and makes things mysteriously "look wrong" in
//! some cases.  It also is sort of overloaded to do two things at
//! once.  The first is what you will find [Wikipedia talking about](https://en.wikipedia.org/wiki/Srgb),
//! which is "how do you prove that 'green' on my monitor is the same
//! as 'green' on your monitor?".  That part we can safely ignore,
//! since it's a job for your monitor manufacturer.
//!
//! The other part is [gamma
//! correction](https://en.wikipedia.org/wiki/Gamma_correction) which
//! deals with the fact that the response of the human visual system
//! is non-linear, or in non-science talk, if you make a pixel twice
//! as bright, it doesn't *look* twice as bright.  To make something
//! *look* twice as bright, you have to make it about 2^2.2 times
//! brighter.  The exact math for how to fiddle the numbers to make
//! things Look Nice is defined as part of the sRGB standard, so often
//! a color scheme that complies with this gamma correction process is
//! just called "sRGB".
//!
//! In a perfect world, we don't ever have to worry about this.
//! Images are generally all stored in the sRGB color space (or
//! something similar to it), monitors all display in the sRGB color
//! space, and our graphics drivers know how to do whatever is
//! necessary to make the two line up.  The problem comes because we
//! are programmers, and have to be able to poke things instead of
//! just using pre-loaded assets.  So the question is: if you do
//! `Color::new(0.5, 0.0, 0.0, 1.0)` and `Color::new(1.0, 0.0, 0.0, 1.0)`,
//! will the second color LOOK twice as bright as the first one?
//!
//! So we have to know what color space we are talking about when we
//! say `Color`!  Are we talking about linear, "real" color where your
//! pixel puts out twice as many photons for the second color as the
//! first?  Or are we talking about sRGB color, where the pixel
//! actually LOOKS twice as bright?  And if we want to, say, write a
//! shader that does math to these colors, AND to colors that come
//! from images that use the sRGB color space, how do we make sure
//! everything matches?  To make it even worse, the sRGB conversion
//! done by graphics drivers is toggle-able, and can be set on a
//! per-render-target or per-texture basis, so it's possible for
//! things to get REAL mixed up in subtle ways.
//!
//! The Right Answer, as far as I know, is this: All colors that a
//! human specifies or touches are sRGB-encoded, so a number that is
//! twice as big then .  We do our color math in shaders, and (if we
//! set our render target to be an sRGB texture, which ggez always
//! does) the graphics driver will turn the linear colors we specify
//! into sRGB colors.  So if we do `vec4 x = vec4(0.25, 0.0, 0.0, 1.0);`,
//! assigning one pixel `x` and another `x * 2` will make the
//! second one *look* twice as bright as the first.
//!
//! BUT, this process also has to be done on INPUT as well; if we pass
//! the shader a value taken from an image file, that image file is in
//! sRGB color.  The graphics driver must THEN convert the sRGB color into
//! a linear color when passing it to the shader, so that if we get the
//! color and call it `x`, assigning one output pixel `x` and another
//! `x * 2` again makes the second one LOOK twice as bright as the first.
//! Then it converts the value back on the way out.
//!
//! ggez should handle all of this for you.  `graphics::Color` is
//! explicitly a sRGB-corrected color, all textures including the
//! final render target are sRGB-enabled, and when you provide
//! a linear color to something like `graphics::Mesh` it turns it
//! into sRGB for you to match everything else.  The purpose of this
//! example is to show that this actually *works* correctly!

use ggez;
use ggez::event;
use ggez::graphics::{self, DrawParam};
use ggez::nalgebra as na;
use ggez::{Context, GameResult};

/// This is a nice aqua test color that will look a lot brighter
/// than it should if we mess something up.
/// See https://github.com/ggez/ggez/issues/209 for examples.
const AQUA: graphics::Color = graphics::Color::new(0.0078, 0.7647, 0.6039, 1.0);

struct MainState {
    demo_mesh: graphics::Mesh,
    square_mesh: graphics::Mesh,
    demo_image: graphics::Image,
}

impl MainState {
    fn new(ctx: &mut Context) -> GameResult<MainState> {
        let demo_mesh = graphics::Mesh::new_circle(
            ctx,
            graphics::DrawMode::fill(),
            na::Point2::new(0.0, 0.0),
            100.0,
            2.0,
            AQUA,
        )?;
        let square_mesh = graphics::Mesh::new_rectangle(
            ctx,
            graphics::DrawMode::fill(),
            graphics::Rect::new(0.0, 0.0, 400.0, 400.0),
            graphics::WHITE,
        )?;
        let demo_image = graphics::Image::solid(ctx, 200, AQUA)?;
        let s = MainState {
            demo_mesh,
            square_mesh,
            demo_image,
        };
        Ok(s)
    }
}

impl event::EventHandler for MainState {
    fn update(&mut self, _ctx: &mut Context) -> GameResult {
        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        graphics::clear(ctx, AQUA);

        // Draw a white square so we can see things
        graphics::draw(
            ctx,
            &self.square_mesh,
            DrawParam::default().dest(na::Point2::new(200.0, 100.0)),
        )?;

        // Draw things partially over the white square so we can see
        // where they are; they SHOULD be the same color as the
        // background.
        graphics::draw(
            ctx,
            &self.demo_mesh,
            DrawParam::default().dest(na::Point2::new(150.0, 200.0)),
        )?;

        graphics::draw(
            ctx,
            &self.demo_image,
            DrawParam::default().dest(na::Point2::new(450.0, 200.0)),
        )?;

        graphics::present(ctx)?;
        Ok(())
    }
}

pub fn main() -> GameResult {
    use std::env;
    use std::path;
    let resource_dir = if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
        let mut path = path::PathBuf::from(manifest_dir);
        path.push("resources");
        path
    } else {
        path::PathBuf::from("./resources")
    };

    let cb = ggez::ContextBuilder::new("super_simple", "ggez").add_resource_path(resource_dir);
    let (ctx, event_loop) = &mut cb.build()?;
    let state = &mut MainState::new(ctx)?;
    event::run(ctx, event_loop, state)
}
<commit_msg>created colorspace example of a Text Drawable<commit_after>//! An example demonstrating sRGB color spaces.
//!
//! sRGB is one of those things that's a bit subtle, a bit obscure,
//! and easy to get wrong, but worth knowing because it crops up
//! from time to time and makes things mysteriously "look wrong" in
//! some cases.  It also is sort of overloaded to do two things at
//! once.  The first is what you will find [Wikipedia talking about](https://en.wikipedia.org/wiki/Srgb),
//! which is "how do you prove that 'green' on my monitor is the same
//! as 'green' on your monitor?".  That part we can safely ignore,
//! since it's a job for your monitor manufacturer.
//!
//! The other part is [gamma
//! correction](https://en.wikipedia.org/wiki/Gamma_correction) which
//! deals with the fact that the response of the human visual system
//! is non-linear, or in non-science talk, if you make a pixel twice
//! as bright, it doesn't *look* twice as bright.  To make something
//! *look* twice as bright, you have to make it about 2^2.2 times
//! brighter.  The exact math for how to fiddle the numbers to make
//! things Look Nice is defined as part of the sRGB standard, so often
//! a color scheme that complies with this gamma correction process is
//! just called "sRGB".
//!
//! In a perfect world, we don't ever have to worry about this.
//! Images are generally all stored in the sRGB color space (or
//! something similar to it), monitors all display in the sRGB color
//! space, and our graphics drivers know how to do whatever is
//! necessary to make the two line up.  The problem comes because we
//! are programmers, and have to be able to poke things instead of
//! just using pre-loaded assets.  So the question is: if you do
//! `Color::new(0.5, 0.0, 0.0, 1.0)` and `Color::new(1.0, 0.0, 0.0, 1.0)`,
//! will the second color LOOK twice as bright as the first one?
//!
//! So we have to know what color space we are talking about when we
//! say `Color`!  Are we talking about linear, "real" color where your
//! pixel puts out twice as many photons for the second color as the
//! first?  Or are we talking about sRGB color, where the pixel
//! actually LOOKS twice as bright?  And if we want to, say, write a
//! shader that does math to these colors, AND to colors that come
//! from images that use the sRGB color space, how do we make sure
//! everything matches?  To make it even worse, the sRGB conversion
//! done by graphics drivers is toggle-able, and can be set on a
//! per-render-target or per-texture basis, so it's possible for
//! things to get REAL mixed up in subtle ways.
//!
//! The Right Answer, as far as I know, is this: All colors that a
//! human specifies or touches are sRGB-encoded, so a number that is
//! twice as big then .  We do our color math in shaders, and (if we
//! set our render target to be an sRGB texture, which ggez always
//! does) the graphics driver will turn the linear colors we specify
//! into sRGB colors.  So if we do `vec4 x = vec4(0.25, 0.0, 0.0, 1.0);`,
//! assigning one pixel `x` and another `x * 2` will make the
//! second one *look* twice as bright as the first.
//!
//! BUT, this process also has to be done on INPUT as well; if we pass
//! the shader a value taken from an image file, that image file is in
//! sRGB color.  The graphics driver must THEN convert the sRGB color into
//! a linear color when passing it to the shader, so that if we get the
//! color and call it `x`, assigning one output pixel `x` and another
//! `x * 2` again makes the second one LOOK twice as bright as the first.
//! Then it converts the value back on the way out.
//!
//! ggez should handle all of this for you.  `graphics::Color` is
//! explicitly a sRGB-corrected color, all textures including the
//! final render target are sRGB-enabled, and when you provide
//! a linear color to something like `graphics::Mesh` it turns it
//! into sRGB for you to match everything else.  The purpose of this
//! example is to show that this actually *works* correctly!

use ggez;
use ggez::event;
use ggez::graphics::{self, DrawParam};
use ggez::nalgebra as na;
use ggez::{Context, GameResult};

/// This is a nice aqua test color that will look a lot brighter
/// than it should if we mess something up.
/// See https://github.com/ggez/ggez/issues/209 for examples.
const AQUA: graphics::Color = graphics::Color::new(0.0078, 0.7647, 0.6039, 1.0);

struct MainState {
    demo_mesh: graphics::Mesh,
    square_mesh: graphics::Mesh,
    demo_image: graphics::Image,
    demo_text: graphics::Text,
}

impl MainState {
    fn new(ctx: &mut Context) -> GameResult<MainState> {
        let demo_mesh = graphics::Mesh::new_circle(
            ctx,
            graphics::DrawMode::fill(),
            na::Point2::new(0.0, 0.0),
            100.0,
            2.0,
            AQUA,
        )?;
        let square_mesh = graphics::Mesh::new_rectangle(
            ctx,
            graphics::DrawMode::fill(),
            graphics::Rect::new(0.0, 0.0, 400.0, 400.0),
            graphics::WHITE,
        )?;
        let demo_image = graphics::Image::solid(ctx, 200, AQUA)?;
        let demo_text = graphics::Text::new(graphics::TextFragment {
            text: "-".to_string(),
            color: Some(AQUA),
            font: Some(graphics::Font::default()),
            scale: Some(graphics::Scale::uniform(300.0)),
        });

        let s = MainState {
            demo_mesh,
            square_mesh,
            demo_image,
            demo_text,
        };
        Ok(s)
    }
}

impl event::EventHandler for MainState {
    fn update(&mut self, _ctx: &mut Context) -> GameResult {
        Ok(())
    }

    fn draw(&mut self, ctx: &mut Context) -> GameResult {
        graphics::clear(ctx, AQUA);

        // Draw a white square so we can see things
        graphics::draw(
            ctx,
            &self.square_mesh,
            DrawParam::default().dest(na::Point2::new(200.0, 100.0)),
        )?;

        // Draw things partially over the white square so we can see
        // where they are; they SHOULD be the same color as the
        // background.
        graphics::draw(
            ctx,
            &self.demo_mesh,
            DrawParam::default().dest(na::Point2::new(150.0, 200.0)),
        )?;

        graphics::draw(
            ctx,
            &self.demo_image,
            DrawParam::default().dest(na::Point2::new(450.0, 200.0)),
        )?;

        graphics::draw(
            ctx,
            &self.demo_text,
            DrawParam::default().dest(na::Point2::new(150.0, 135.0)),
        )?;

        graphics::present(ctx)?;
        Ok(())
    }
}

pub fn main() -> GameResult {
    use std::env;
    use std::path;
    let resource_dir = if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
        let mut path = path::PathBuf::from(manifest_dir);
        path.push("resources");
        path
    } else {
        path::PathBuf::from("./resources")
    };

    let cb = ggez::ContextBuilder::new("super_simple", "ggez").add_resource_path(resource_dir);
    let (ctx, event_loop) = &mut cb.build()?;
    let state = &mut MainState::new(ctx)?;
    event::run(ctx, event_loop, state)
}
<|endoftext|>


<commit_before>extern crate timely;
extern crate timely_sort;
extern crate differential_dataflow;

use timely::dataflow::*;
use timely::dataflow::operators::*;

use differential_dataflow::ring::RingPair;
use differential_dataflow::AsCollection;
use differential_dataflow::operators::Consolidate;

fn main() {

    let keys: usize = std::env::args().nth(1).unwrap().parse().unwrap();
    let batch: usize = std::env::args().nth(2).unwrap().parse().unwrap();

    // This computation demonstrates in-place accumulation of arbitrarily large
    // volumes of input data, so long as the number of distinct keys is moderate.
    //
    // Specifically, the program aims to accumulate (key, val) pairs where we are
    // interested in the sum of values for each key, as well as the count of the
    // number of records, so that we can produce the average.
    timely::execute_from_args(std::env::args().skip(4), move |computation| {

        let mut input = computation.scoped::<(), _, _>(|scope| {

            let (input, data) = scope.new_input::<((usize, isize), isize)>();

            // move `val` into the ring component.
            data.map(|((x,y),d)| (x, Default::default(), RingPair::new(y,d)))
				.as_collection()
                .consolidate();

            input
        });

        let timer = ::std::time::Instant::now();

        for val in 0 .. {
        	// introduce some data with bounded key.
        	input.send(((val % keys, (val as isize) % 100), 1 as isize));

        	// we must still give the computation the opportunity to act.
        	if val > 0 && val % batch == 0 {
        		computation.step();
        		let elapsed = timer.elapsed();
        		let secs = elapsed.as_secs() as f64 + (elapsed.subsec_nanos() as f64)/1000000000.0;
        		println!("tuples: {:?},\telts/sec: {:?}", val, val as f64 / secs);
        	}
        }

    }).unwrap();
}<commit_msg>actually save edits this time<commit_after>extern crate timely;
extern crate timely_sort;
extern crate differential_dataflow;

use timely::dataflow::*;
use timely::dataflow::operators::*;

use differential_dataflow::difference::DiffPair;
use differential_dataflow::AsCollection;
use differential_dataflow::operators::Consolidate;

fn main() {

    let keys: usize = std::env::args().nth(1).unwrap().parse().unwrap();
    let batch: usize = std::env::args().nth(2).unwrap().parse().unwrap();

    // This computation demonstrates in-place accumulation of arbitrarily large
    // volumes of input data, so long as the number of distinct keys is moderate.
    //
    // Specifically, the program aims to accumulate (key, val) pairs where we are
    // interested in the sum of values for each key, as well as the count of the
    // number of records, so that we can produce the average.
    timely::execute_from_args(std::env::args().skip(4), move |computation| {

        let mut input = computation.scoped::<(), _, _>(|scope| {

            let (input, data) = scope.new_input::<((usize, isize), isize)>();

            // move `val` into the ring component.
            data.map(|((x,y),d)| (x, Default::default(), DiffPair::new(y,d)))
				.as_collection()
                .consolidate();

            input
        });

        let timer = ::std::time::Instant::now();

        for val in 0 .. {
        	// introduce some data with bounded key.
        	input.send(((val % keys, (val as isize) % 100), 1 as isize));

        	// we must still give the computation the opportunity to act.
        	if val > 0 && val % batch == 0 {
        		computation.step();
        		let elapsed = timer.elapsed();
        		let secs = elapsed.as_secs() as f64 + (elapsed.subsec_nanos() as f64)/1000000000.0;
        		println!("tuples: {:?},\telts/sec: {:?}", val, val as f64 / secs);
        	}
        }

    }).unwrap();
}<|endoftext|>


<commit_before>extern crate c_ares_resolver;
extern crate dns_parser;
extern crate tokio_core;

use std::error::Error;
use std::thread;
use std::time::Duration;

use c_ares_resolver::{
    Options,
    Resolver
};
use dns_parser::Packet;

fn main() {
    // Create Resolver.
    let options = Options::new();
    let resolver = Resolver::new(options)
        .expect("Failed to create resolver");

    // Make an A-query, but use a third-party DNS parser to handle the result.
    resolver.query(
        "apple.com",
        1,  // internet
        1,  // Host address
        |result| {
            match result {
                Err(e) => {
                    println!("Query failed with error '{}'", e.description());
                },
                Ok(bytes) => {
                    match Packet::parse(bytes) {
                        Err(e) => {
                            println!(
                                "Parser failed with error '{}'",
                                e.description()
                            );
                        },
                        Ok(packet) => {
                            for answer in &packet.answers {
                                println!("{:?}", answer.data);
                            }
                        },
                    }
                },
            }
        }
    );
    thread::sleep(Duration::from_millis(100));
}
<commit_msg>Proper synchronisation in example<commit_after>extern crate c_ares;
extern crate c_ares_resolver;
extern crate dns_parser;
extern crate tokio_core;

use std::error::Error;
use std::sync::mpsc;

use c_ares_resolver::{
    Options,
    Resolver
};
use dns_parser::Packet;

fn handle_result(result: Result<&[u8], c_ares::Error>) {
    match result {
        Err(e) => {
            println!("Query failed with error '{}'", e.description());
        },
        Ok(bytes) => {
            match Packet::parse(bytes) {
                Err(e) => {
                    println!(
                        "Parser failed with error '{}'",
                        e.description()
                    );
                },
                Ok(packet) => {
                    for answer in &packet.answers {
                        println!("{:?}", answer.data);
                    }
                },
            }
        },
    }
}

fn main() {
    // Create Resolver.
    let options = Options::new();
    let resolver = Resolver::new(options)
        .expect("Failed to create resolver");

    // Make an A-query, but use a third-party DNS parser to handle the result.
    let (tx, rx) = mpsc::channel();
    resolver.query(
        "apple.com",
        1,  // internet
        1,  // Host address
        move |result| {
            handle_result(result);
            tx.send(()).expect("failed to send on channel!");
        }
    );

    // If we allowed the resolver to be dropped, we'd shut down c-ares and the
    // query would fail.  Wait for the handler to signal that it is done.
    rx.recv().expect("query did not complete!");
}
<|endoftext|>


<commit_before>extern crate iron;
extern crate env_logger;
extern crate clap;
extern crate serde;
extern crate bodyparser;
extern crate exonum;
extern crate router;
extern crate configuration_service;

use clap::App;

use exonum::blockchain::{Blockchain, Service};
use exonum::node::Node;
use exonum::helpers::clap::{GenerateCommand, RunCommand};

use configuration_service::ConfigurationService;

fn main() {
    exonum::crypto::init();
    exonum::helpers::init_logger().unwrap();

    let app = App::new("Simple configuration api demo program")
        .version(env!("CARGO_PKG_VERSION"))
        .author("Exonum Team <exonum@bitfury.com>")
        .about("Demo validator node")
        .subcommand(GenerateCommand::new())
        .subcommand(RunCommand::new());
    let matches = app.get_matches();

    match matches.subcommand() {
        ("generate", Some(matches)) => GenerateCommand::execute(matches),
        ("run", Some(matches)) => {
            let node_cfg = RunCommand::node_config(matches);
            let db = RunCommand::db(matches);

            let services: Vec<Box<Service>> = vec![Box::new(ConfigurationService::new())];
            let blockchain = Blockchain::new(db, services);

            let mut node = Node::new(blockchain, node_cfg);
            node.run().unwrap();
        }
        _ => {
            unreachable!("Wrong subcommand");
        }
    }
}
<commit_msg>fix example<commit_after>extern crate exonum;
extern crate configuration_service;

use exonum::helpers::fabric::NodeBuilder;

use configuration_service::ConfigurationService;

fn main() {
    exonum::helpers::init_logger().unwrap();
    NodeBuilder::new()
                .with_service::<ConfigurationService>()
                .run();
}
<|endoftext|>