<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use geom::length::Length;
use geom::point::Point2D;
use geom::rect::Rect;
use geom::size::Size2D;
use geom::num::Zero;

use std::default::Default;
use std::i32;
use std::fmt;
use std::ops::{Add, Sub, Neg, Mul, Div, Rem};

use rustc_serialize::{Encoder, Encodable};

// Units for use with geom::length and geom::scale_factor.

/// A normalized "pixel" at the default resolution for the display.
///
/// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it
/// should approximate a device-independent reference length.  This unit corresponds to Android's
/// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel."
///
/// The relationship between DevicePixel and ScreenPx is defined by the OS.  On most low-dpi
/// screens, one ScreenPx is equal to one DevicePixel.  But on high-density screens it can be
/// some larger number.  For example, by default on Apple "retina" displays, one ScreenPx equals
/// two DevicePixels.  On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels.
///
/// The ratio between ScreenPx and DevicePixel for a given display be found by calling
/// `servo::windowing::WindowMethods::hidpi_factor`.
#[derive(Debug, Copy, Clone)]
pub enum ScreenPx {}

/// One CSS "px" in the coordinate system of the "initial viewport":
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
///
/// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user.  This is
/// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport
/// so it still exactly fits the visible area.
///
/// At the default zoom level of 100%, one PagePx is equal to one ScreenPx.  However, if the
/// document is zoomed in or out then this scale may be larger or smaller.
#[derive(RustcEncodable, Debug, Copy, Clone)]
pub enum ViewportPx {}

/// One CSS "px" in the root coordinate system for the content document.
///
/// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user.
/// This is the mobile-style "pinch zoom" that enlarges content without reflowing it.  When the
/// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size
/// as the viewable area.
#[derive(RustcEncodable, Debug, Copy, Clone)]
pub enum PagePx {}

// In summary, the hierarchy of pixel units and the factors to convert from one to the next:
//
// DevicePixel
//   / hidpi_ratio => ScreenPx
//     / desktop_zoom => ViewportPx
//       / pinch_zoom => PagePx

// An Au is an "App Unit" and represents 1/60th of a CSS pixel.  It was
// originally proposed in 2002 as a standard unit of measure in Gecko.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info.
//
// FIXME: Implement Au using Length and ScaleFactor instead of a custom type.
#[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord)]
pub struct Au(pub i32);

impl Default for Au {
    #[inline]
    fn default() -> Au {
        Au(0)
    }
}

impl Zero for Au {
    #[inline]
    fn zero() -> Au {
        Au(0)
    }
}

pub static ZERO_POINT: Point2D<Au> = Point2D {
    x: Au(0),
    y: Au(0),
};

pub static ZERO_RECT: Rect<Au> = Rect {
    origin: Point2D {
        x: Au(0),
        y: Au(0),
    },
    size: Size2D {
        width: Au(0),
        height: Au(0),
    }
};

pub static MAX_RECT: Rect<Au> = Rect {
    origin: Point2D {
        x: Au(i32::MIN / 2),
        y: Au(i32::MIN / 2),
    },
    size: Size2D {
        width: MAX_AU,
        height: MAX_AU,
    }
};

pub const MIN_AU: Au = Au(i32::MIN);
pub const MAX_AU: Au = Au(i32::MAX);

impl Encodable for Au {
    fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
        e.emit_f64(self.to_f64_px())
    }
}

impl fmt::Debug for Au {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}px", self.to_f64_px())
    }}

impl Add for Au {
    type Output = Au;

    #[inline]
    fn add(self, other: Au) -> Au {
        let Au(s) = self;
        let Au(o) = other;
        Au(s.wrapping_add(o))
    }
}

impl Sub for Au {
    type Output = Au;

    #[inline]
    fn sub(self, other: Au) -> Au {
        let Au(s) = self;
        let Au(o) = other;
        Au(s.wrapping_sub(o))
    }

}

impl Mul<i32> for Au {
    type Output = Au;

    #[inline]
    fn mul(self, other: i32) -> Au {
        let Au(s) = self;
        Au(s.wrapping_mul(other))
    }
}

impl Div<i32> for Au {
    type Output = Au;

    #[inline]
    fn div(self, other: i32) -> Au {
        let Au(s) = self;
        Au(s / other)
    }
}

impl Rem<i32> for Au {
    type Output = Au;

    #[inline]
    fn rem(self, other: i32) -> Au {
        let Au(s) = self;
        Au(s % other)
    }
}

impl Neg for Au {
    type Output = Au;

    #[inline]
    fn neg(self) -> Au {
        let Au(s) = self;
        Au(-s)
    }
}

impl Au {
    /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs!
    #[inline]
    pub fn new(value: i32) -> Au {
        Au(value)
    }

    #[inline]
    pub fn scale_by(self, factor: f32) -> Au {
        let Au(s) = self;
        Au(((s as f32) * factor) as i32)
    }

    #[inline]
    pub fn from_px(px: i32) -> Au {
        Au((px * 60) as i32)
    }

    #[inline]
    pub fn from_page_px(px: Length<PagePx, f32>) -> Au {
        Au((px.get() * 60f32) as i32)
    }

    /// Rounds this app unit down to the pixel towards zero and returns it.
    #[inline]
    pub fn to_px(&self) -> i32 {
        let Au(a) = *self;
        (a / 60)
    }

    /// Rounds this app unit down to the previous (left or top) pixel and returns it.
    #[inline]
    pub fn to_prev_px(&self) -> i32 {
        let Au(s) = *self;
        ((s as f64) / 60f64).floor() as i32
    }

    /// Rounds this app unit up to the next (right or bottom) pixel and returns it.
    #[inline]
    pub fn to_next_px(&self) -> i32 {
        let Au(s) = *self;
        ((s as f64) / 60f64).ceil() as i32
    }

    #[inline]
    pub fn to_nearest_px(&self) -> i32 {
        let Au(s) = *self;
        ((s as f64) / 60f64).round() as i32
    }

    #[inline]
    pub fn to_f32_px(&self) -> f32 {
        let Au(s) = *self;
        (s as f32) / 60f32
    }

    #[inline]
    pub fn to_f64_px(&self) -> f64 {
        let Au(s) = *self;
        (s as f64) / 60f64
    }

    #[inline]
    pub fn to_snapped(&self) -> Au {
        let Au(s) = *self;
        let res = s % 60i32;
        return if res >= 30i32 { return Au(s - res + 60i32) }
                       else { return Au(s - res) };
    }

    #[inline]
    pub fn from_f32_px(px: f32) -> Au {
        Au((px * 60f32) as i32)
    }

    #[inline]
    pub fn from_pt(pt: f64) -> Au {
        Au::from_f64_px(pt_to_px(pt))
    }

    #[inline]
    pub fn from_f64_px(px: f64) -> Au {
        Au((px * 60.) as i32)
    }
}

// assumes 72 points per inch, and 96 px per inch
pub fn pt_to_px(pt: f64) -> f64 {
    pt / 72. * 96.
}

// assumes 72 points per inch, and 96 px per inch
pub fn px_to_pt(px: f64) -> f64 {
    px / 96. * 72.
}

/// Returns true if the rect contains the given point. Points on the top or left sides of the rect
/// are considered inside the rectangle, while points on the right or bottom sides of the rect are
/// not considered inside the rectangle.
pub fn rect_contains_point<T:PartialOrd + Add<T, Output=T>>(rect: Rect<T>, point: Point2D<T>) -> bool {
    point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width &&
        point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height
}

/// A helper function to convert a rect of `f32` pixels to a rect of app units.
pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> {
    Rect(Point2D(Au::from_f32_px(rect.origin.x), Au::from_f32_px(rect.origin.y)),
         Size2D(Au::from_f32_px(rect.size.width), Au::from_f32_px(rect.size.height)))
}

<commit_msg>Used `foo.0` tuple access notation instead of `let Au(a) = a;`<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use geom::length::Length;
use geom::point::Point2D;
use geom::rect::Rect;
use geom::size::Size2D;
use geom::num::Zero;

use std::default::Default;
use std::i32;
use std::fmt;
use std::ops::{Add, Sub, Neg, Mul, Div, Rem};

use rustc_serialize::{Encoder, Encodable};

// Units for use with geom::length and geom::scale_factor.

/// A normalized "pixel" at the default resolution for the display.
///
/// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it
/// should approximate a device-independent reference length.  This unit corresponds to Android's
/// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel."
///
/// The relationship between DevicePixel and ScreenPx is defined by the OS.  On most low-dpi
/// screens, one ScreenPx is equal to one DevicePixel.  But on high-density screens it can be
/// some larger number.  For example, by default on Apple "retina" displays, one ScreenPx equals
/// two DevicePixels.  On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels.
///
/// The ratio between ScreenPx and DevicePixel for a given display be found by calling
/// `servo::windowing::WindowMethods::hidpi_factor`.
#[derive(Debug, Copy, Clone)]
pub enum ScreenPx {}

/// One CSS "px" in the coordinate system of the "initial viewport":
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
///
/// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user.  This is
/// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport
/// so it still exactly fits the visible area.
///
/// At the default zoom level of 100%, one PagePx is equal to one ScreenPx.  However, if the
/// document is zoomed in or out then this scale may be larger or smaller.
#[derive(RustcEncodable, Debug, Copy, Clone)]
pub enum ViewportPx {}

/// One CSS "px" in the root coordinate system for the content document.
///
/// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user.
/// This is the mobile-style "pinch zoom" that enlarges content without reflowing it.  When the
/// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size
/// as the viewable area.
#[derive(RustcEncodable, Debug, Copy, Clone)]
pub enum PagePx {}

// In summary, the hierarchy of pixel units and the factors to convert from one to the next:
//
// DevicePixel
//   / hidpi_ratio => ScreenPx
//     / desktop_zoom => ViewportPx
//       / pinch_zoom => PagePx

// An Au is an "App Unit" and represents 1/60th of a CSS pixel.  It was
// originally proposed in 2002 as a standard unit of measure in Gecko.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info.
//
// FIXME: Implement Au using Length and ScaleFactor instead of a custom type.
#[derive(Clone, Copy, Hash, PartialEq, PartialOrd, Eq, Ord)]
pub struct Au(pub i32);

impl Default for Au {
    #[inline]
    fn default() -> Au {
        Au(0)
    }
}

impl Zero for Au {
    #[inline]
    fn zero() -> Au {
        Au(0)
    }
}

pub static ZERO_POINT: Point2D<Au> = Point2D {
    x: Au(0),
    y: Au(0),
};

pub static ZERO_RECT: Rect<Au> = Rect {
    origin: Point2D {
        x: Au(0),
        y: Au(0),
    },
    size: Size2D {
        width: Au(0),
        height: Au(0),
    }
};

pub static MAX_RECT: Rect<Au> = Rect {
    origin: Point2D {
        x: Au(i32::MIN / 2),
        y: Au(i32::MIN / 2),
    },
    size: Size2D {
        width: MAX_AU,
        height: MAX_AU,
    }
};

pub const MIN_AU: Au = Au(i32::MIN);
pub const MAX_AU: Au = Au(i32::MAX);

impl Encodable for Au {
    fn encode<S: Encoder>(&self, e: &mut S) -> Result<(), S::Error> {
        e.emit_f64(self.to_f64_px())
    }
}

impl fmt::Debug for Au {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}px", self.to_f64_px())
    }}

impl Add for Au {
    type Output = Au;

    #[inline]
    fn add(self, other: Au) -> Au {
        Au(self.0.wrapping_add(other.0))
    }
}

impl Sub for Au {
    type Output = Au;

    #[inline]
    fn sub(self, other: Au) -> Au {
        Au(self.0.wrapping_sub(other.0))
    }

}

impl Mul<i32> for Au {
    type Output = Au;

    #[inline]
    fn mul(self, other: i32) -> Au {
        Au(self.0.wrapping_mul(other))
    }
}

impl Div<i32> for Au {
    type Output = Au;

    #[inline]
    fn div(self, other: i32) -> Au {
        Au(self.0 / other)
    }
}

impl Rem<i32> for Au {
    type Output = Au;

    #[inline]
    fn rem(self, other: i32) -> Au {
        Au(self.0 % other)
    }
}

impl Neg for Au {
    type Output = Au;

    #[inline]
    fn neg(self) -> Au {
        Au(-self.0)
    }
}

impl Au {
    /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs!
    #[inline]
    pub fn new(value: i32) -> Au {
        Au(value)
    }

    #[inline]
    pub fn scale_by(self, factor: f32) -> Au {
        Au(((self.0 as f32) * factor) as i32)
    }

    #[inline]
    pub fn from_px(px: i32) -> Au {
        Au((px * 60) as i32)
    }

    #[inline]
    pub fn from_page_px(px: Length<PagePx, f32>) -> Au {
        Au((px.get() * 60f32) as i32)
    }

    /// Rounds this app unit down to the pixel towards zero and returns it.
    #[inline]
    pub fn to_px(&self) -> i32 {
        self.0 / 60
    }

    /// Rounds this app unit down to the previous (left or top) pixel and returns it.
    #[inline]
    pub fn to_prev_px(&self) -> i32 {
        ((self.0 as f64) / 60f64).floor() as i32
    }

    /// Rounds this app unit up to the next (right or bottom) pixel and returns it.
    #[inline]
    pub fn to_next_px(&self) -> i32 {
        ((self.0 as f64) / 60f64).ceil() as i32
    }

    #[inline]
    pub fn to_nearest_px(&self) -> i32 {
        ((self.0 as f64) / 60f64).round() as i32
    }

    #[inline]
    pub fn to_f32_px(&self) -> f32 {
        (self.0 as f32) / 60f32
    }

    #[inline]
    pub fn to_f64_px(&self) -> f64 {
        (self.0 as f64) / 60f64
    }

    #[inline]
    pub fn to_snapped(&self) -> Au {
        let res = self.0 % 60i32;
        return if res >= 30i32 { return Au(self.0 - res + 60i32) }
                       else { return Au(self.0 - res) };
    }

    #[inline]
    pub fn from_f32_px(px: f32) -> Au {
        Au((px * 60f32) as i32)
    }

    #[inline]
    pub fn from_pt(pt: f64) -> Au {
        Au::from_f64_px(pt_to_px(pt))
    }

    #[inline]
    pub fn from_f64_px(px: f64) -> Au {
        Au((px * 60.) as i32)
    }
}

// assumes 72 points per inch, and 96 px per inch
pub fn pt_to_px(pt: f64) -> f64 {
    pt / 72. * 96.
}

// assumes 72 points per inch, and 96 px per inch
pub fn px_to_pt(px: f64) -> f64 {
    px / 96. * 72.
}

/// Returns true if the rect contains the given point. Points on the top or left sides of the rect
/// are considered inside the rectangle, while points on the right or bottom sides of the rect are
/// not considered inside the rectangle.
pub fn rect_contains_point<T:PartialOrd + Add<T, Output=T>>(rect: Rect<T>, point: Point2D<T>) -> bool {
    point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width &&
        point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height
}

/// A helper function to convert a rect of `f32` pixels to a rect of app units.
pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> {
    Rect(Point2D(Au::from_f32_px(rect.origin.x), Au::from_f32_px(rect.origin.y)),
         Size2D(Au::from_f32_px(rect.size.width), Au::from_f32_px(rect.size.height)))
}

<|endoftext|>


<commit_before><fold text='/ * ... * / '>/*
hello
*/ < / fold>

< fold text='/ * ... * / '>///
/// Outer doc
///</fold>
fn foo() < fold text='{ ... }'>{}< / fold >

mod m < fold text ='{ ... }'>{
< fold text = '/ * ... * / '>//!
    //! Inner doc
    //!</fold>
}< / fold >

< fold text = '/ * ... * / '>/*
hello
*/ < / fold >

< fold text = '/ * ... * / '>/*
fn foo() {}
*/ < /fold >

mod m < fold text = '{ ...}'>{
< fold text = '/ * ... * / '>/*
    */ < / fold >
} < / fold >
<commit_msg>TYPE: fix the test again<commit_after><fold text='/* ... */'>/*
hello
*/</fold>

<fold text='/* ... */'>///
/// Outer doc
///</fold>
fn foo() <fold text='{...}'>{}</fold>

mod m <fold text='{...}'>{
<fold text='/* ... */'>//!
    //! Inner doc
    //!</fold>
}</fold>

<fold text='/* ... */'>/*
hello
*/</fold>

<fold text='/* ... */'>/*
fn foo() {}
*/</fold>

mod m <fold text='{...}'>{
<fold text='/* ... */'>/*
    */</fold>
}</fold>
<|endoftext|>


<commit_before>use crate::result::TockError;
use crate::util;
use core::cell::Cell;
use core::mem;
use libtock_core::{callback, syscalls};

const DRIVER_NUMBER: usize = 0x30003;

mod command_nr {
    pub const TRANSMIT: usize = 1;
    pub const RECEIVE: usize = 2;
    pub const EMULATE: usize = 3;
    pub const CONFIGURE: usize = 4;
    pub const FRAMEDELAYMAX: usize = 5;
}

mod subscribe_nr {
    pub const TRANSMIT: usize = 1;
    pub const RECEIVE: usize = 2;
    pub const SELECT: usize = 3;
}

mod allow_nr {
    pub const TRANSMIT: usize = 1;
    pub const RECEIVE: usize = 2;
}

#[allow(dead_code)]
pub struct RecvOp {
    pub result_code: usize,
    pub recv_amount: usize,
}

pub struct NfcTag {}

impl NfcTag {
    pub fn enable_emulation() -> bool {
        NfcTag::emulate(true)
    }

    pub fn disable_emulation() -> bool {
        NfcTag::emulate(false)
    }

    fn emulate(enabled: bool) -> bool {
        syscalls::command(DRIVER_NUMBER, command_nr::EMULATE, enabled as usize, 0).is_ok()
    }

    /// Subscribe to the tag being SELECTED callback.
    pub fn selected() -> bool {
        let is_selected = Cell::new(false);
        let mut is_selected_alarm = || is_selected.set(true);
        let subscription = syscalls::subscribe::<callback::Identity0Consumer, _>(
            DRIVER_NUMBER,
            subscribe_nr::SELECT,
            &mut is_selected_alarm,
        );
        if subscription.is_err() {
            return false;
        }

        util::yieldk_for(|| is_selected.get());
        true
    }

    /// Configure the tag type command.
    pub fn configure(tag_type: u8) -> bool {
        syscalls::command(DRIVER_NUMBER, command_nr::CONFIGURE, tag_type as usize, 0).is_ok()
    }

    /// Set the maximum frame delay value to support transmission with the reader.
    pub fn set_framedelaymax(delay: u32) -> bool {
        syscalls::command(DRIVER_NUMBER, command_nr::FRAMEDELAYMAX, delay as usize, 0).is_ok()
    }

    /// 1. Share with the driver a buffer.
    /// 2. Subscribe to having a successful receive callback.
    /// 3. Issue the request for reception.
    pub fn receive(buf: &mut [u8; 256]) -> Result<RecvOp, TockError> {
        let result = syscalls::allow(DRIVER_NUMBER, allow_nr::RECEIVE, buf)?;
        // set callback with 2 arguments, to receive ReturnCode and RX Amount
        let done = Cell::new(false);
        let result_code = Cell::new(None);
        let recv_amount = Cell::new(None);
        let mut callback = |result, amount| {
            result_code.set(Some(result));
            recv_amount.set(Some(amount));
            done.set(true)
        };
        let subscription = syscalls::subscribe::<callback::Identity2Consumer, _>(
            DRIVER_NUMBER,
            subscribe_nr::RECEIVE,
            &mut callback,
        )?;
        syscalls::command(DRIVER_NUMBER, command_nr::RECEIVE, 0, 0)?;
        util::yieldk_for(|| done.get());
        mem::drop(subscription);
        mem::drop(result);
        Ok(RecvOp {
            result_code: result_code.get().unwrap(),
            recv_amount: recv_amount.get().unwrap(),
        })
    }

    /// 1. Share with the driver a buffer containing the app's reply.
    /// 2. Subscribe to having a successful transmission callback.
    /// 3. Issue the request for transmitting.
    pub fn transmit(buf: &mut [u8], amount: usize) -> Result<usize, TockError> {
        let result = syscalls::allow(DRIVER_NUMBER, allow_nr::TRANSMIT, buf)?;
        // set callback with 1 argument, to receive ReturnCode
        let done = Cell::new(false);
        let result_code = Cell::new(None);
        let mut callback = |result| {
            result_code.set(Some(result));
            done.set(true)
        };
        let subscription = syscalls::subscribe::<callback::Identity1Consumer, _>(
            DRIVER_NUMBER,
            subscribe_nr::TRANSMIT,
            &mut callback,
        )?;
        syscalls::command(DRIVER_NUMBER, command_nr::TRANSMIT, amount, 0)?;
        util::yieldk_for(|| done.get());
        mem::drop(subscription);
        mem::drop(result);
        Ok(result_code.get().unwrap())
    }
}
<commit_msg>Remove unnecessary `done.get()`<commit_after>use crate::result::TockError;
use crate::util;
use core::cell::Cell;
use core::mem;
use libtock_core::{callback, syscalls};

const DRIVER_NUMBER: usize = 0x30003;

mod command_nr {
    pub const TRANSMIT: usize = 1;
    pub const RECEIVE: usize = 2;
    pub const EMULATE: usize = 3;
    pub const CONFIGURE: usize = 4;
    pub const FRAMEDELAYMAX: usize = 5;
}

mod subscribe_nr {
    pub const TRANSMIT: usize = 1;
    pub const RECEIVE: usize = 2;
    pub const SELECT: usize = 3;
}

mod allow_nr {
    pub const TRANSMIT: usize = 1;
    pub const RECEIVE: usize = 2;
}

#[allow(dead_code)]
pub struct RecvOp {
    pub result_code: usize,
    pub recv_amount: usize,
}

pub struct NfcTag {}

impl NfcTag {
    pub fn enable_emulation() -> bool {
        NfcTag::emulate(true)
    }

    pub fn disable_emulation() -> bool {
        NfcTag::emulate(false)
    }

    fn emulate(enabled: bool) -> bool {
        syscalls::command(DRIVER_NUMBER, command_nr::EMULATE, enabled as usize, 0).is_ok()
    }

    /// Subscribe to the tag being SELECTED callback.
    pub fn selected() -> bool {
        let is_selected = Cell::new(false);
        let mut is_selected_alarm = || is_selected.set(true);
        let subscription = syscalls::subscribe::<callback::Identity0Consumer, _>(
            DRIVER_NUMBER,
            subscribe_nr::SELECT,
            &mut is_selected_alarm,
        );
        if subscription.is_err() {
            return false;
        }

        util::yieldk_for(|| is_selected.get());
        true
    }

    /// Configure the tag type command.
    pub fn configure(tag_type: u8) -> bool {
        syscalls::command(DRIVER_NUMBER, command_nr::CONFIGURE, tag_type as usize, 0).is_ok()
    }

    /// Set the maximum frame delay value to support transmission with the reader.
    pub fn set_framedelaymax(delay: u32) -> bool {
        syscalls::command(DRIVER_NUMBER, command_nr::FRAMEDELAYMAX, delay as usize, 0).is_ok()
    }

    /// 1. Share with the driver a buffer.
    /// 2. Subscribe to having a successful receive callback.
    /// 3. Issue the request for reception.
    pub fn receive(buf: &mut [u8; 256]) -> Result<RecvOp, TockError> {
        let result = syscalls::allow(DRIVER_NUMBER, allow_nr::RECEIVE, buf)?;
        // set callback with 2 arguments, to receive ReturnCode and RX Amount
        let result_code = Cell::new(None);
        let recv_amount = Cell::new(None);
        let mut callback = |result, amount| {
            result_code.set(Some(result));
            recv_amount.set(Some(amount))
        };
        let subscription = syscalls::subscribe::<callback::Identity2Consumer, _>(
            DRIVER_NUMBER,
            subscribe_nr::RECEIVE,
            &mut callback,
        )?;
        syscalls::command(DRIVER_NUMBER, command_nr::RECEIVE, 0, 0)?;
        util::yieldk_for(|| recv_amount.get().is_some());
        mem::drop(subscription);
        mem::drop(result);
        Ok(RecvOp {
            result_code: result_code.get().unwrap(),
            recv_amount: recv_amount.get().unwrap(),
        })
    }

    /// 1. Share with the driver a buffer containing the app's reply.
    /// 2. Subscribe to having a successful transmission callback.
    /// 3. Issue the request for transmitting.
    pub fn transmit(buf: &mut [u8], amount: usize) -> Result<usize, TockError> {
        let result = syscalls::allow(DRIVER_NUMBER, allow_nr::TRANSMIT, buf)?;
        // set callback with 1 argument, to receive ReturnCode
        let result_code = Cell::new(None);
        let mut callback = |result| result_code.set(Some(result));
        let subscription = syscalls::subscribe::<callback::Identity1Consumer, _>(
            DRIVER_NUMBER,
            subscribe_nr::TRANSMIT,
            &mut callback,
        )?;
        syscalls::command(DRIVER_NUMBER, command_nr::TRANSMIT, amount, 0)?;
        util::yieldk_for(|| result_code.get().is_some());
        mem::drop(subscription);
        mem::drop(result);
        Ok(result_code.get().unwrap())
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 The vulkano developers
// 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. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.

//! Targets on which your draw commands are executed.
//!
//! # Render passes and framebuffers
//!
//! There are two concepts in Vulkan:
//!
//! - A *render pass* describes the target which you are going to render to. It is a collection
//!   of descriptions of one or more attachments (ie. image that are rendered to), and of one or
//!   multiples subpasses. The render pass contains the format and number of samples of each
//!   attachment, and the attachments that are attached to each subpass. They are represented
//!   in vulkano with the `RenderPass` object.
//! - A *framebuffer* contains the list of actual images that are attached. It is created from a
//!   render pass and has to match its characteristics. They are represented in vulkano with the
//!   `Framebuffer` object.
//!
//! Render passes are typically created at initialization only (for example during a loading
//! screen) because they can be costly, while framebuffers can be created and destroyed either at
//! initialization or during the frame.
//!
//! Consequently you can create graphics pipelines from a render pass object alone.
//! A `Framebuffer` object is only needed when you actually add draw commands to a command buffer.
//!
//! # Render passes
//!
//! In vulkano a render pass is represented by the `RenderPass` struct. This struct has a template
//! parameter that contains the description of the render pass. The `RenderPassAbstract` trait is
//! implemented on all instances of `RenderPass<_>` and makes it easier to store render passes
//! without having to explicitely write its type.
//!
//! The template parameter of the `RenderPass` struct must implement the `RenderPassDesc` trait.
//! In order to create a render pass, you can create an object that implements this trait, then
//! call the `build_render_pass` method on it.
//!
//! ```
//! use vulkano::framebuffer::EmptySinglePassRenderPassDesc;
//! use vulkano::framebuffer::RenderPassDesc;
//!
//! # let device: std::sync::Arc<vulkano::device::Device> = return;
//! let desc = EmptySinglePassRenderPassDesc;
//! let render_pass = desc.build_render_pass(device.clone()).unwrap();
//! // The type of `render_pass` is `RenderPass<EmptySinglePassRenderPassDesc>`.
//! ```
//!
//! This example creates a render pass with no attachment and one single subpass that doesn't draw
//! on anything. While it's sometimes useful, most of the time it's not what you want.
//!
//! The easiest way to create a "real" render pass is to use the `single_pass_renderpass!` macro.
//!
//! ```
//! # #[macro_use] extern crate vulkano;
//! # fn main() {
//! # let device: std::sync::Arc<vulkano::device::Device> = return;
//! use vulkano::format::Format;
//!
//! let render_pass = single_pass_renderpass!(device.clone(),
//!     attachments: {
//!         // `foo` is a custom name we give to the first and only attachment.
//!         foo: {
//!             load: Clear,
//!             store: Store,
//!             format: Format::R8G8B8A8Unorm,
//!             samples: 1,
//!         }
//!     },
//!     pass: {
//!         color: [foo],       // Repeat the attachment name here.
//!         depth_stencil: {}
//!     }
//! ).unwrap();
//! # }
//! ```
//!
//! See the documentation of the macro for more details. TODO: put link here
//!
//! Once a `RenderPass<_>` struct is created, it implements the same render-pass-related traits as
//! its template parameter.
//!
//! # Framebuffers
//!
//! See [the documentation of the `Framebuffer` struct](struct.Framebuffer.html) for information
//! about how to create a framebuffer.
//!

pub use self::attachments_list::AttachmentsList;
pub use self::compat_atch::ensure_image_view_compatible;
pub use self::compat_atch::IncompatibleRenderPassAttachmentError;
pub use self::desc::LayoutAttachmentDescription;
pub use self::desc::LayoutPassDescription;
pub use self::desc::LayoutPassDependencyDescription;
pub use self::desc::RenderPassDesc;
pub use self::desc::RenderPassDescAttachments;
pub use self::desc::RenderPassDescSubpasses;
pub use self::desc::RenderPassDescDependencies;
pub use self::desc::StoreOp;
pub use self::desc::LoadOp;
pub use self::empty::EmptySinglePassRenderPassDesc;
pub use self::framebuffer::Framebuffer;
pub use self::framebuffer::FramebufferCreationError;
pub use self::framebuffer::FramebufferSys;
pub use self::sys::RenderPass;
pub use self::sys::RenderPassCreationError;
pub use self::sys::RenderPassSys;
pub use self::traits::FramebufferAbstract;
pub use self::traits::RenderPassDescClearValues;
pub use self::traits::RenderPassCompatible;
pub use self::traits::RenderPassAbstract;
pub use self::traits::RenderPassSubpassInterface;
pub use self::traits::Subpass;

#[macro_use]
mod macros;
mod attachments_list;
mod compat_atch;
mod desc;
mod empty;
mod framebuffer;
mod sys;
mod traits;
<commit_msg>Reexport FramebufferBuilder<commit_after>// Copyright (c) 2016 The vulkano developers
// 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. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.

//! Targets on which your draw commands are executed.
//!
//! # Render passes and framebuffers
//!
//! There are two concepts in Vulkan:
//!
//! - A *render pass* describes the target which you are going to render to. It is a collection
//!   of descriptions of one or more attachments (ie. image that are rendered to), and of one or
//!   multiples subpasses. The render pass contains the format and number of samples of each
//!   attachment, and the attachments that are attached to each subpass. They are represented
//!   in vulkano with the `RenderPass` object.
//! - A *framebuffer* contains the list of actual images that are attached. It is created from a
//!   render pass and has to match its characteristics. They are represented in vulkano with the
//!   `Framebuffer` object.
//!
//! Render passes are typically created at initialization only (for example during a loading
//! screen) because they can be costly, while framebuffers can be created and destroyed either at
//! initialization or during the frame.
//!
//! Consequently you can create graphics pipelines from a render pass object alone.
//! A `Framebuffer` object is only needed when you actually add draw commands to a command buffer.
//!
//! # Render passes
//!
//! In vulkano a render pass is represented by the `RenderPass` struct. This struct has a template
//! parameter that contains the description of the render pass. The `RenderPassAbstract` trait is
//! implemented on all instances of `RenderPass<_>` and makes it easier to store render passes
//! without having to explicitely write its type.
//!
//! The template parameter of the `RenderPass` struct must implement the `RenderPassDesc` trait.
//! In order to create a render pass, you can create an object that implements this trait, then
//! call the `build_render_pass` method on it.
//!
//! ```
//! use vulkano::framebuffer::EmptySinglePassRenderPassDesc;
//! use vulkano::framebuffer::RenderPassDesc;
//!
//! # let device: std::sync::Arc<vulkano::device::Device> = return;
//! let desc = EmptySinglePassRenderPassDesc;
//! let render_pass = desc.build_render_pass(device.clone()).unwrap();
//! // The type of `render_pass` is `RenderPass<EmptySinglePassRenderPassDesc>`.
//! ```
//!
//! This example creates a render pass with no attachment and one single subpass that doesn't draw
//! on anything. While it's sometimes useful, most of the time it's not what you want.
//!
//! The easiest way to create a "real" render pass is to use the `single_pass_renderpass!` macro.
//!
//! ```
//! # #[macro_use] extern crate vulkano;
//! # fn main() {
//! # let device: std::sync::Arc<vulkano::device::Device> = return;
//! use vulkano::format::Format;
//!
//! let render_pass = single_pass_renderpass!(device.clone(),
//!     attachments: {
//!         // `foo` is a custom name we give to the first and only attachment.
//!         foo: {
//!             load: Clear,
//!             store: Store,
//!             format: Format::R8G8B8A8Unorm,
//!             samples: 1,
//!         }
//!     },
//!     pass: {
//!         color: [foo],       // Repeat the attachment name here.
//!         depth_stencil: {}
//!     }
//! ).unwrap();
//! # }
//! ```
//!
//! See the documentation of the macro for more details. TODO: put link here
//!
//! Once a `RenderPass<_>` struct is created, it implements the same render-pass-related traits as
//! its template parameter.
//!
//! # Framebuffers
//!
//! See [the documentation of the `Framebuffer` struct](struct.Framebuffer.html) for information
//! about how to create a framebuffer.
//!

pub use self::attachments_list::AttachmentsList;
pub use self::compat_atch::ensure_image_view_compatible;
pub use self::compat_atch::IncompatibleRenderPassAttachmentError;
pub use self::desc::LayoutAttachmentDescription;
pub use self::desc::LayoutPassDescription;
pub use self::desc::LayoutPassDependencyDescription;
pub use self::desc::RenderPassDesc;
pub use self::desc::RenderPassDescAttachments;
pub use self::desc::RenderPassDescSubpasses;
pub use self::desc::RenderPassDescDependencies;
pub use self::desc::StoreOp;
pub use self::desc::LoadOp;
pub use self::empty::EmptySinglePassRenderPassDesc;
pub use self::framebuffer::Framebuffer;
pub use self::framebuffer::FramebufferBuilder;
pub use self::framebuffer::FramebufferCreationError;
pub use self::framebuffer::FramebufferSys;
pub use self::sys::RenderPass;
pub use self::sys::RenderPassCreationError;
pub use self::sys::RenderPassSys;
pub use self::traits::FramebufferAbstract;
pub use self::traits::RenderPassDescClearValues;
pub use self::traits::RenderPassCompatible;
pub use self::traits::RenderPassAbstract;
pub use self::traits::RenderPassSubpassInterface;
pub use self::traits::Subpass;

#[macro_use]
mod macros;
mod attachments_list;
mod compat_atch;
mod desc;
mod empty;
mod framebuffer;
mod sys;
mod traits;
<|endoftext|>


<commit_before>// Copyright (c) 2016 The vulkano developers
// 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. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.

use std::iter::Empty;
use std::sync::Arc;
use smallvec::SmallVec;

use device::Device;
use device::Queue;
use format::FormatDesc;
use image::Dimensions;
use image::sys::ImageCreationError;
use image::sys::Layout;
use image::sys::UnsafeImage;
use image::sys::UnsafeImageView;
use image::sys::Usage;
use image::traits::Image;
use image::traits::ImageContent;
use image::traits::ImageView;
use instance::QueueFamily;
use memory::pool::AllocLayout;
use memory::pool::MemoryPool;
use memory::pool::MemoryPoolAlloc;
use memory::pool::StdMemoryPool;
use sync::Sharing;

/// Image whose purpose is to be used for read-only purposes. You can write to the image once,
/// but then you must only ever read from it. TODO: clarify because of blit operations
// TODO: type (2D, 3D, array, etc.) as template parameter
#[derive(Debug)]
pub struct ImmutableImage<F, A = Arc<StdMemoryPool>> where A: MemoryPool {
    image: UnsafeImage,
    view: UnsafeImageView,
    dimensions: Dimensions,
    memory: A::Alloc,
    format: F,
}

impl<F> ImmutableImage<F> {
    /// Builds a new immutable image.
    pub fn new<'a, I>(device: &Arc<Device>, dimensions: Dimensions, format: F, queue_families: I)
                      -> Result<Arc<ImmutableImage<F>>, ImageCreationError>
        where F: FormatDesc, I: IntoIterator<Item = QueueFamily<'a>>
    {
        let usage = Usage {
            transfer_source: true,  // for blits
            transfer_dest: true,
            sampled: true,
            .. Usage::none()
        };

        let queue_families = queue_families.into_iter().map(|f| f.id())
                                           .collect::<SmallVec<[u32; 4]>>();

        let (image, mem_reqs) = unsafe {
            let sharing = if queue_families.len() >= 2 {
                Sharing::Concurrent(queue_families.iter().cloned())
            } else {
                Sharing::Exclusive
            };

            try!(UnsafeImage::new(device, &usage, format.format(), dimensions.to_image_dimensions(),
                                  1, 1, Sharing::Exclusive::<Empty<u32>>, false, false))
        };

        let mem_ty = {
            let device_local = device.physical_device().memory_types()
                                     .filter(|t| (mem_reqs.memory_type_bits & (1 << t.id())) != 0)
                                     .filter(|t| t.is_device_local());
            let any = device.physical_device().memory_types()
                            .filter(|t| (mem_reqs.memory_type_bits & (1 << t.id())) != 0);
            device_local.chain(any).next().unwrap()
        };

        let mem = try!(MemoryPool::alloc(&Device::standard_pool(device), mem_ty,
                                         mem_reqs.size, mem_reqs.alignment, AllocLayout::Optimal));
        debug_assert!((mem.offset() % mem_reqs.alignment) == 0);
        unsafe { try!(image.bind_memory(mem.memory(), mem.offset())); }

        let view = unsafe {
            try!(UnsafeImageView::raw(&image, dimensions.to_view_type(), 0 .. image.mipmap_levels(),
                                      0 .. image.dimensions().array_layers()))
        };

        Ok(Arc::new(ImmutableImage {
            image: image,
            view: view,
            memory: mem,
            dimensions: dimensions,
            format: format,
        }))
    }
}

impl<F, A> ImmutableImage<F, A> where A: MemoryPool {
    /// Returns the dimensions of the image.
    #[inline]
    pub fn dimensions(&self) -> Dimensions {
        self.dimensions
    }
}

unsafe impl<F, A> Image for ImmutableImage<F, A> where F: 'static + Send + Sync, A: MemoryPool {
    #[inline]
    fn inner(&self) -> &UnsafeImage {
        &self.image
    }

    #[inline]
    fn conflict_key(&self, _: u32, _: u32, _: u32, _: u32) -> u64 {
        self.image.key()
    }

    #[inline]
    fn gpu_access(&self, exclusive_access: bool, queue: &Queue) -> bool {
        true        // FIXME:
    }
}

unsafe impl<P, F, A> ImageContent<P> for ImmutableImage<F, A>
    where F: 'static + Send + Sync, A: MemoryPool
{
    #[inline]
    fn matches_format(&self) -> bool {
        true        // FIXME:
    }
}

unsafe impl<F: 'static, A> ImageView for ImmutableImage<F, A>
    where F: 'static + Send + Sync, A: MemoryPool
{
    #[inline]
    fn parent(&self) -> &Image {
        self
    }

    #[inline]
    fn dimensions(&self) -> Dimensions {
        self.dimensions
    }

    #[inline]
    fn inner(&self) -> &UnsafeImageView {
        &self.view
    }

    #[inline]
    fn descriptor_set_storage_image_layout(&self) -> Layout {
        Layout::ShaderReadOnlyOptimal
    }

    #[inline]
    fn descriptor_set_combined_image_sampler_layout(&self) -> Layout {
        Layout::ShaderReadOnlyOptimal
    }

    #[inline]
    fn descriptor_set_sampled_image_layout(&self) -> Layout {
        Layout::ShaderReadOnlyOptimal
    }

    #[inline]
    fn descriptor_set_input_attachment_layout(&self) -> Layout {
        Layout::ShaderReadOnlyOptimal
    }

    #[inline]
    fn identity_swizzle(&self) -> bool {
        true
    }
}
<commit_msg>Update immutable.rs<commit_after>// Copyright (c) 2016 The vulkano developers
// 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. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.

use std::iter::Empty;
use std::sync::Arc;
use smallvec::SmallVec;

use device::Device;
use device::Queue;
use format::FormatDesc;
use image::Dimensions;
use image::sys::ImageCreationError;
use image::sys::Layout;
use image::sys::UnsafeImage;
use image::sys::UnsafeImageView;
use image::sys::Usage;
use image::traits::Image;
use image::traits::ImageContent;
use image::traits::ImageView;
use instance::QueueFamily;
use memory::pool::AllocLayout;
use memory::pool::MemoryPool;
use memory::pool::MemoryPoolAlloc;
use memory::pool::StdMemoryPool;
use sync::Sharing;

/// Image whose purpose is to be used for read-only purposes. You can write to the image once,
/// but then you must only ever read from it. TODO: clarify because of blit operations
// TODO: type (2D, 3D, array, etc.) as template parameter
#[derive(Debug)]
pub struct ImmutableImage<F, A = Arc<StdMemoryPool>> where A: MemoryPool {
    image: UnsafeImage,
    view: UnsafeImageView,
    dimensions: Dimensions,
    memory: A::Alloc,
    format: F,
}

impl<F> ImmutableImage<F> {
    /// Builds a new immutable image.
    pub fn new<'a, I>(device: &Arc<Device>, dimensions: Dimensions, format: F, queue_families: I)
                      -> Result<Arc<ImmutableImage<F>>, ImageCreationError>
        where F: FormatDesc, I: IntoIterator<Item = QueueFamily<'a>>
    {
        let usage = Usage {
            transfer_source: true,  // for blits
            transfer_dest: true,
            sampled: true,
            .. Usage::none()
        };

        let queue_families = queue_families.into_iter().map(|f| f.id())
                                           .collect::<SmallVec<[u32; 4]>>();

        let (image, mem_reqs) = unsafe {
            let sharing = if queue_families.len() >= 2 {
                Sharing::Concurrent(queue_families.iter().cloned())
            } else {
                Sharing::Exclusive
            };

            try!(UnsafeImage::new(device, &usage, format.format(), dimensions.to_image_dimensions(),
                                  1, 1, sharing, false, false))
        };

        let mem_ty = {
            let device_local = device.physical_device().memory_types()
                                     .filter(|t| (mem_reqs.memory_type_bits & (1 << t.id())) != 0)
                                     .filter(|t| t.is_device_local());
            let any = device.physical_device().memory_types()
                            .filter(|t| (mem_reqs.memory_type_bits & (1 << t.id())) != 0);
            device_local.chain(any).next().unwrap()
        };

        let mem = try!(MemoryPool::alloc(&Device::standard_pool(device), mem_ty,
                                         mem_reqs.size, mem_reqs.alignment, AllocLayout::Optimal));
        debug_assert!((mem.offset() % mem_reqs.alignment) == 0);
        unsafe { try!(image.bind_memory(mem.memory(), mem.offset())); }

        let view = unsafe {
            try!(UnsafeImageView::raw(&image, dimensions.to_view_type(), 0 .. image.mipmap_levels(),
                                      0 .. image.dimensions().array_layers()))
        };

        Ok(Arc::new(ImmutableImage {
            image: image,
            view: view,
            memory: mem,
            dimensions: dimensions,
            format: format,
        }))
    }
}

impl<F, A> ImmutableImage<F, A> where A: MemoryPool {
    /// Returns the dimensions of the image.
    #[inline]
    pub fn dimensions(&self) -> Dimensions {
        self.dimensions
    }
}

unsafe impl<F, A> Image for ImmutableImage<F, A> where F: 'static + Send + Sync, A: MemoryPool {
    #[inline]
    fn inner(&self) -> &UnsafeImage {
        &self.image
    }

    #[inline]
    fn conflict_key(&self, _: u32, _: u32, _: u32, _: u32) -> u64 {
        self.image.key()
    }

    #[inline]
    fn gpu_access(&self, exclusive_access: bool, queue: &Queue) -> bool {
        true        // FIXME:
    }
}

unsafe impl<P, F, A> ImageContent<P> for ImmutableImage<F, A>
    where F: 'static + Send + Sync, A: MemoryPool
{
    #[inline]
    fn matches_format(&self) -> bool {
        true        // FIXME:
    }
}

unsafe impl<F: 'static, A> ImageView for ImmutableImage<F, A>
    where F: 'static + Send + Sync, A: MemoryPool
{
    #[inline]
    fn parent(&self) -> &Image {
        self
    }

    #[inline]
    fn dimensions(&self) -> Dimensions {
        self.dimensions
    }

    #[inline]
    fn inner(&self) -> &UnsafeImageView {
        &self.view
    }

    #[inline]
    fn descriptor_set_storage_image_layout(&self) -> Layout {
        Layout::ShaderReadOnlyOptimal
    }

    #[inline]
    fn descriptor_set_combined_image_sampler_layout(&self) -> Layout {
        Layout::ShaderReadOnlyOptimal
    }

    #[inline]
    fn descriptor_set_sampled_image_layout(&self) -> Layout {
        Layout::ShaderReadOnlyOptimal
    }

    #[inline]
    fn descriptor_set_input_attachment_layout(&self) -> Layout {
        Layout::ShaderReadOnlyOptimal
    }

    #[inline]
    fn identity_swizzle(&self) -> bool {
        true
    }
}
<|endoftext|>


<commit_before>extern crate std;

use std::collections::HashMap;

/**
 * Identifier of an entity
 */
pub type EntityID = uint;

/**
 * Identifier of a component
 */
pub type ComponentID = uint;

/**
 * An error while doing an operation on the state
 */
#[deriving(Show)]
pub enum StateError {
    EntityNotFound(EntityID),
    ComponentNotFound(ComponentID),
    FieldDoesNotExist(ComponentID, String)
}

/**
 *
 */
#[unstable]
pub struct EntitiesState {
    components: HashMap<ComponentID, Component>,
    entities: HashMap<EntityID, EntityData>,

    next_component_id: ComponentID,
    next_entity_id: EntityID,

    components_of_native_type: HashMap<String, ComponentID>
}

struct EntityData {
    // name of the entity with its path as prefix
    name: Option<String>,
    visible: bool,

    // components owned by the entity
    components: Vec<ComponentID>,

    // components whose type is the entity
    components_of_type: Vec<ComponentID>,

    // list of parameters of the current entity
    default_parameters: HashMap<String, Data>
}

struct Component {
    owner: EntityID,

    cmp_type: ComponentType,

    data: ComponentData,

    // all components in this list have their data as a ComponentDataLink to this one
    linked_from: Vec<ComponentID>,

    parent: Option<ComponentID>,
    // when a component is destroyed, all children are destroyed too
    children: Vec<ComponentID>
}

enum ComponentData {
    ComponentDataNative(HashMap<String, Data>),
    ComponentDataLink(ComponentID)
}

/**
 * Type of a component
 */
#[deriving(Clone,Show)]
pub enum ComponentType {
    NativeComponentType(String),
    EntityComponentType(EntityID)
}

#[deriving(Clone,Show)]
pub enum Data {
    Number(f64),
    String(String),
    Boolean(bool),
    List(Vec<Data>),
    Entity(EntityID),
    FromProperty(String),
    Empty
}

impl EntitiesState {
    /**
     * Builds a new empty state
     */
    pub fn new() -> EntitiesState
    {
        EntitiesState {
            components: HashMap::new(),
            entities: HashMap::new(),
            next_component_id: 1,
            next_entity_id: 1,
            components_of_native_type: HashMap::new()
        }
    }

    /**
     * Creates a new empty entity in the state
     */
    pub fn create_entity(&mut self, name: Option<String>, visible: bool)
        -> EntityID
    {
        let id = self.next_entity_id;

        let entity = EntityData {
            name: name,
            visible: visible,

            components: Vec::new(),

            components_of_type: Vec::new(),
            default_parameters: std::collections::HashMap::new()
        };

        self.entities.insert(id, entity);
        self.next_entity_id += 1;
        id
    }

    /**
     * Destroys an entity
     * This operation will also destroy all the components owned by this entity and all components whose type is this entity
     */
    pub fn destroy_entity(&mut self, id: &EntityID)
        -> Result<(), StateError>
    {
        let components_list = {
            let entity = try!(self.get_entity_by_id(id));

            if entity.components_of_type.len() != 0 {
                unimplemented!()
                //return Err(format!("Cannot destroy entity with ID {} (name: {}) because it has components of its type", id, entity.name));
            }

            entity.components.clone()
        };

        for cmp in components_list.iter() {
            // ignoring error from destroying component because we don't want to recreate them
            self.destroy_component(cmp).ok();
        }

        self.entities.remove(id);
        Ok(())
    }

    /**
     * Creates a new component of native type
     */
    pub fn create_native_component(&mut self, owner: &EntityID, typename: &str, data: HashMap<String, Data>)
        -> Result<ComponentID, StateError>
    {
        let newID = self.next_component_id;

        let newComponent = Component {
            owner: owner.clone(),
            data: ComponentDataNative(data),
            linked_from: Vec::new(),
            parent: None,
            children: Vec::new(),
            cmp_type: NativeComponentType(typename.to_string())
        };

        (try!(self.get_entity_by_id_mut(owner))).components.push(newID);

        self.components.insert(newID, newComponent);
        self.next_component_id = self.next_component_id + 1;

        self.components_of_native_type.insert(typename.to_string(), newID);

        Ok(newID)
    }

    /**
     * Creates a new component of an entity type
     */
    /// TODO: better error handling
    pub fn create_component_from_entity(&mut self, owner: &EntityID, typename: &EntityID, data: HashMap<String, Data>)
        -> Result<ComponentID, StateError>
    {
        let newID = self.next_component_id;

        let newComponent = Component {
            owner: owner.clone(),
            data: ComponentDataNative(data),
            linked_from: Vec::new(),
            parent: None,
            children: Vec::new(),
            cmp_type: EntityComponentType(typename.clone())
        };

        (try!(self.get_entity_by_id_mut(owner))).components.push(newID);
        (try!(self.get_entity_by_id_mut(typename))).components_of_type.push(newID);

        // creating the list of components to inherit
        let components_to_inherit: Vec<ComponentID> = (try!(self.get_entity_by_id(typename))).components.iter().map(|c| c.clone()).collect();

        self.components.insert(newID, newComponent);
        self.next_component_id = self.next_component_id + 1;

        // inheriting components
        for cmp in components_to_inherit.move_iter() {
            match self.create_inherited_component(owner, &newID, &cmp) {
                Ok(_) => (),
                Err(err) => {
                    self.destroy_component(&newID);
                    return Err(err);
                }
            }
        }

        Ok(newID)
    }

    /**
     * Destroys a component
     */
    pub fn destroy_component(&mut self, id: &ComponentID)
        -> Result<(), StateError>
    {
        let children = (try!(self.get_component_by_id(id))).children.clone();
        let linked = (try!(self.get_component_by_id(id))).linked_from.clone();

        let parent = (try!(self.get_component_by_id(id))).parent;
        if parent.is_some() {
            let mut p = (try!(self.get_component_by_id_mut(&parent.unwrap())));
            let pos = p.children.iter().position(|c| *c == *id).unwrap();
            p.children.remove(pos);
        }

        for child in children.iter() {
            self.destroy_component(child).ok();
        }

        for cmp in linked.iter() {
            self.destroy_component(cmp).ok();
        }

        // removing from entity
        {
            let owner = (try!(self.get_component_by_id(id))).owner;
            let mut entity = try!(self.get_entity_by_id_mut(&owner));
            let pos = entity.components.iter().position(|e| *e == *id).unwrap();
            entity.components.remove(pos);
        }

        // TODO: remove from components_of_native_type

        // removing from components list
        self.components.remove(id);

        Ok(())
    }

    pub fn set(&mut self, id: &ComponentID, field: &str, data: Data)
        -> Result<(), StateError>
    {
        let mut idIter = id.clone();

        loop {
            let mut component = match self.components.find_mut(&idIter) {
                None => return Err(ComponentNotFound(idIter)),
                Some(c) => c
            };

            match &mut component.data {
                &ComponentDataNative(ref mut val) => {
                    val.insert(field.to_string(), data);
                    return Ok(());
                },
                &ComponentDataLink(c) => {
                    idIter = c.clone();
                    continue;
                }
            }
        }

        unreachable!();
    }

    pub fn get<'a>(&'a self, id: &ComponentID, field: &str)
        -> Result<&'a Data, StateError>
    {
        match (try!(self.get_component_by_id(id))).data {
            ComponentDataNative(ref data) => {
                match data.find_equiv(&field) {
                    Some(a) => Ok(a),
                    None => Err(FieldDoesNotExist(id.clone(), field.to_string()))
                }
            },
            ComponentDataLink(c) => {
                self.get(&c, field)
            }
        }
    }

    pub fn get_owner(&self, id: &ComponentID)
        -> Result<EntityID, StateError>
    {
        Ok((try!(self.get_component_by_id(id))).owner)
    }

    pub fn get_type(&self, id: &ComponentID)
        -> Result<ComponentType, StateError>
    {
        Ok((try!(self.get_component_by_id(id))).cmp_type.clone())
    }

    pub fn get_entities_iter<'a>(&'a self)
        -> std::collections::hashmap::Keys<'a, EntityID, EntityData>
    {
        self.entities.keys()
    }

    pub fn get_entity_name<'a>(&'a self, id: &EntityID)
        -> Result<Option<String>, StateError>
    {
        Ok((try!(self.get_entity_by_id(id))).name.clone())
    }

    pub fn get_entities_by_name<'a>(&'a self, name: &str)
        -> Vec<EntityID>
    {
        self.entities.iter().filter(|&(_, ref e)| e.name == Some(name.to_string())).map(|(id, _)| id.clone()).collect()
    }

    pub fn get_components_iter<'a>(&'a self)
        -> std::collections::hashmap::Keys<'a, ComponentID, Component>
    {
        self.components.keys()
    }

    pub fn is_component_visible(&self, id: &ComponentID)
        -> Result<bool, StateError>
    {
        let owner = try!(self.get_owner(id));
        Ok((try!(self.get_entity_by_id(&owner))).visible)
    }

    pub fn set_component_parent(&mut self, component: &ComponentID, parent: &ComponentID)
        -> Result<(), StateError>
    {
        if (try!(self.get_component_by_id_mut(component))).parent.is_some() {
            self.clear_component_parent(component);
        }

        (try!(self.get_component_by_id_mut(component))).parent = Some(parent.clone());
        (try!(self.get_component_by_id_mut(parent))).children.push(component.clone());

        Ok(())
    }

    pub fn clear_component_parent(&mut self, component: &ComponentID) {
        unimplemented!()
    }

    pub fn get_component_children(&self, component: &ComponentID)
        -> Result<Vec<ComponentID>, StateError>
    {
        Ok((try!(self.get_component_by_id(component))).children.clone())
    }

    /**
     * Creates a component inherited from another
     */
    // TODO: better error handling
    fn create_inherited_component(&mut self, owner: &EntityID, parent: &ComponentID, inherit: &ComponentID)
        -> Result<ComponentID, StateError>
    {
        let newID = self.next_component_id;

        let newComponent = Component {
            owner: owner.clone(),
            data: ComponentDataLink(inherit.clone()),
            linked_from: Vec::new(),
            parent: Some(parent.clone()),
            children: Vec::new(),
            cmp_type: (try!(self.get_component_by_id(inherit))).cmp_type.clone()
        };

        (try!(self.get_component_by_id_mut(inherit))).linked_from.push(newID);
        (try!(self.get_component_by_id_mut(parent))).children.push(newID);
        (try!(self.get_entity_by_id_mut(owner))).components.push(newID);

        self.components.insert(newID, newComponent);

        self.next_component_id = self.next_component_id + 1;

        Ok(newID)
    }

    fn get_entity_by_id<'a>(&'a self, id: &ComponentID)
        -> Result<&'a EntityData, StateError>
    {
        match self.entities.find(id) {
            None => Err(EntityNotFound(id.clone())),
            Some(c) => Ok(c)
        }
    }

    fn get_entity_by_id_mut<'a>(&'a mut self, id: &ComponentID)
        -> Result<&'a mut EntityData, StateError>
    {
        match self.entities.find_mut(id) {
            None => Err(EntityNotFound(id.clone())),
            Some(c) => Ok(c)
        }
    }

    fn get_component_by_id<'a>(&'a self, id: &ComponentID)
        -> Result<&'a Component, StateError>
    {
        match self.components.find(id) {
            None => Err(ComponentNotFound(id.clone())),
            Some(c) => Ok(c)
        }
    }

    fn get_component_by_id_mut<'a>(&'a mut self, id: &ComponentID)
        -> Result<&'a mut Component, StateError>
    {
        match self.components.find_mut(id) {
            None => Err(ComponentNotFound(id.clone())),
            Some(c) => Ok(c)
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::EntitiesState;

    #[test]
    fn basic() {
        let mut state = EntitiesState::new();

        let eID = state.create_entity(Some(format!("myname")), true);

        let cmpID = state.create_native_component(&eID, "test", HashMap::new());
    }
}
<commit_msg>Work on entities state structure<commit_after>extern crate std;

use std::collections::HashMap;

/**
 * Identifier of an entity
 */
pub type EntityID = uint;

/**
 * Identifier of a component
 */
pub type ComponentID = uint;

/**
 * An error while doing an operation on the state
 */
#[deriving(Show)]
pub enum StateError {
    EntityNotFound(EntityID),
    ComponentNotFound(ComponentID),
    FieldDoesNotExist(ComponentID, String)
}

/**
 *
 */
#[unstable]
pub struct EntitiesState {
    components: HashMap<ComponentID, Component>,
    entities: HashMap<EntityID, EntityData>,

    next_component_id: ComponentID,
    next_entity_id: EntityID,

    components_of_native_type: HashMap<String, ComponentID>
}

struct EntityData {
    // name of the entity with its path as prefix
    name: Option<String>,
    visible: bool,

    // components owned by the entity
    components: Vec<ComponentID>,

    // components whose type is the entity
    components_of_type: Vec<ComponentID>,

    // list of parameters of the current entity
    default_parameters: HashMap<String, Data>
}

struct Component {
    owner: EntityID,

    cmp_type: ComponentType,

    data: ComponentData,

    // all components in this list have their data as a ComponentDataLink to this one
    linked_from: Vec<ComponentID>,

    parent: Option<ComponentID>,
    // when a component is destroyed, all children are destroyed too
    children: Vec<ComponentID>
}

enum ComponentData {
    ComponentDataNative(HashMap<String, Data>),
    ComponentDataLink(ComponentID)
}

/**
 * Type of a component
 */
#[deriving(Clone,Show)]
pub enum ComponentType {
    NativeComponentType(String),
    EntityComponentType(EntityID)
}

#[deriving(Clone,Show)]
pub enum Data {
    Number(f64),
    String(String),
    Boolean(bool),
    List(Vec<Data>),
    Entity(EntityID),
    FromProperty(String),
    Empty
}

impl EntitiesState {
    /**
     * Builds a new empty state
     */
    pub fn new() -> EntitiesState
    {
        EntitiesState {
            components: HashMap::new(),
            entities: HashMap::new(),
            next_component_id: 1,
            next_entity_id: 1,
            components_of_native_type: HashMap::new()
        }
    }

    /**
     * Creates a new empty entity in the state
     */
    pub fn create_entity(&mut self, name: Option<String>, visible: bool)
        -> EntityID
    {
        let id = self.next_entity_id;

        let entity = EntityData {
            name: name,
            visible: visible,

            components: Vec::new(),

            components_of_type: Vec::new(),
            default_parameters: std::collections::HashMap::new()
        };

        self.entities.insert(id, entity);
        self.next_entity_id += 1;
        id
    }

    /**
     * Destroys an entity
     * This operation will also destroy all the components owned by this entity and all components whose type is this entity
     */
    pub fn destroy_entity(&mut self, id: &EntityID)
        -> Result<(), StateError>
    {
        let components_list = {
            let entity = try!(self.get_entity_by_id(id));

            if entity.components_of_type.len() != 0 {
                unimplemented!()
                //return Err(format!("Cannot destroy entity with ID {} (name: {}) because it has components of its type", id, entity.name));
            }

            entity.components.clone()
        };

        for cmp in components_list.iter() {
            // ignoring error from destroying component because we don't want to recreate them
            self.destroy_component(cmp).ok();
        }

        self.entities.remove(id);
        Ok(())
    }

    /**
     * Creates a new component of native type
     */
    pub fn create_native_component(&mut self, owner: &EntityID, typename: &str, data: HashMap<String, Data>)
        -> Result<ComponentID, StateError>
    {
        if !self.entities.contains_key(owner) {
            return Err(EntityNotFound(owner.clone()))
        }

        let newID = self.next_component_id;

        let newComponent = Component {
            owner: owner.clone(),
            data: ComponentDataNative(data),
            linked_from: Vec::new(),
            parent: None,
            children: Vec::new(),
            cmp_type: NativeComponentType(typename.to_string())
        };

        self.get_entity_by_id_mut(owner).unwrap().components.push(newID);

        self.components.insert(newID, newComponent);
        self.next_component_id = self.next_component_id + 1;

        self.components_of_native_type.insert(typename.to_string(), newID);

        Ok(newID)
    }

    /**
     * Creates a new component of an entity type
     */
    pub fn create_component_from_entity(&mut self, owner: &EntityID, typename: &EntityID, data: HashMap<String, Data>)
        -> Result<ComponentID, StateError>
    {
        if !self.entities.contains_key(owner) {
            return Err(EntityNotFound(owner.clone()))
        }
        if !self.entities.contains_key(typename) {
            return Err(EntityNotFound(typename.clone()))
        }

        let newID = self.next_component_id;

        let newComponent = Component {
            owner: owner.clone(),
            data: ComponentDataNative(data),
            linked_from: Vec::new(),
            parent: None,
            children: Vec::new(),
            cmp_type: EntityComponentType(typename.clone())
        };

        self.get_entity_by_id_mut(owner).unwrap().components.push(newID);
        self.get_entity_by_id_mut(typename).unwrap().components_of_type.push(newID);

        // creating the list of components to inherit
        let components_to_inherit: Vec<ComponentID> = self.get_entity_by_id(typename).unwrap().components.iter().map(|c| c.clone()).collect();

        self.components.insert(newID, newComponent);
        self.next_component_id = self.next_component_id + 1;

        // inheriting components
        for cmp in components_to_inherit.move_iter() {
            match self.create_inherited_component(owner, &newID, &cmp) {
                Ok(_) => (),
                Err(err) => {
                    self.destroy_component(&newID);     // rollback
                    return Err(err);
                }
            }
        }

        Ok(newID)
    }

    /**
     * Destroys a component
     */
    pub fn destroy_component(&mut self, id: &ComponentID)
        -> Result<(), StateError>
    {
        let (children, linked, parent) = {
            let cmp = try!(self.get_component_by_id(id));
            (cmp.children.clone(), cmp.linked_from.clone(), cmp.parent)
        };

        if parent.is_some() {
            let mut p = self.get_component_by_id_mut(&parent.unwrap()).unwrap();
            let pos = p.children.iter().position(|c| *c == *id).unwrap();
            p.children.remove(pos);
        }

        for child in children.iter() {
            self.destroy_component(child).ok();
        }

        for cmp in linked.iter() {
            self.destroy_component(cmp).ok();
        }

        // removing from entity
        {
            let owner = self.get_component_by_id(id).unwrap().owner;
            let mut entity = self.get_entity_by_id_mut(&owner).unwrap();
            let pos = entity.components.iter().position(|e| *e == *id).unwrap();
            entity.components.remove(pos);
        }

        // TODO: remove from components_of_native_type

        // removing from components list
        self.components.remove(id);

        Ok(())
    }

    /**
     * Modifies an element of a component
     */
    pub fn set(&mut self, id: &ComponentID, field: &str, data: Data)
        -> Result<(), StateError>
    {
        let mut idIter = id.clone();

        loop {
            let mut component = try!(self.get_component_by_id_mut(&idIter));

            match &mut component.data {
                &ComponentDataNative(ref mut val) => {
                    val.insert(field.to_string(), data);
                    return Ok(());
                },
                &ComponentDataLink(c) => {
                    idIter = c.clone();
                    continue;
                }
            }
        }

        unreachable!();
    }

    /**
     * Returns an element of a component
     */
    pub fn get<'a>(&'a self, id: &ComponentID, field: &str)
        -> Result<&'a Data, StateError>
    {
        match (try!(self.get_component_by_id(id))).data {
            ComponentDataNative(ref data) => {
                match data.find_equiv(&field) {
                    Some(a) => Ok(a),
                    None => Err(FieldDoesNotExist(id.clone(), field.to_string()))
                }
            },
            ComponentDataLink(c) => {
                self.get(&c, field)
            }
        }
    }

    /**
     * Returns the owner of the component
     */
    pub fn get_owner(&self, id: &ComponentID)
        -> Result<EntityID, StateError>
    {
        Ok((try!(self.get_component_by_id(id))).owner)
    }

    /**
     * Returns the type of the component
     */
    pub fn get_type(&self, id: &ComponentID)
        -> Result<ComponentType, StateError>
    {
        Ok((try!(self.get_component_by_id(id))).cmp_type.clone())
    }

    /**
     * Returns an iterator to all the entities in the state
     */
    pub fn get_entities_iter<'a>(&'a self)
        -> std::collections::hashmap::Keys<'a, EntityID, EntityData>
    {
        self.entities.keys()
    }

    /**
     * Returns the name of an entity
     */
    pub fn get_entity_name<'a>(&'a self, id: &EntityID)
        -> Result<Option<String>, StateError>
    {
        Ok((try!(self.get_entity_by_id(id))).name.clone())
    }

    /**
     * Returns the list of all entities with the given name
     */
    pub fn get_entities_by_name<'a>(&'a self, name: &str)
        -> Vec<EntityID>
    {
        self.entities.iter().filter(|&(_, ref e)| e.name == Some(name.to_string())).map(|(id, _)| id.clone()).collect()
    }

    /**
     * Returns an iterator to all the components in the state
     */
    pub fn get_components_iter<'a>(&'a self)
        -> std::collections::hashmap::Keys<'a, ComponentID, Component>
    {
        self.components.keys()
    }

    /**
     * Returns true if the component is visible
     */
    pub fn is_component_visible(&self, id: &ComponentID)
        -> Result<bool, StateError>
    {
        let owner = try!(self.get_owner(id));
        Ok((try!(self.get_entity_by_id(&owner))).visible)
    }

    /**
     * Sets an entity as parent of another one
     * When a component is destroyed, all its children are destroyed it
     * If the component already has a parent, it's removed
     */
    pub fn set_component_parent(&mut self, component: &ComponentID, parent: &ComponentID)
        -> Result<(), StateError>
    {
        if !self.components.contains_key(component) {
            return Err(ComponentNotFound(component.clone()))
        }
        if !self.components.contains_key(parent) {
            return Err(ComponentNotFound(parent.clone()))
        }

        if self.get_component_by_id_mut(component).unwrap().parent.is_some() {
            self.clear_component_parent(component);
        }

        self.get_component_by_id_mut(component).unwrap().parent = Some(parent.clone());
        self.get_component_by_id_mut(parent).unwrap().children.push(component.clone());

        Ok(())
    }

    /**
     * Resets the parent of an entity, breaking the parent-child link
     */
    pub fn clear_component_parent(&mut self, component: &ComponentID) {
        unimplemented!()
    }

    /**
     * Returns the list of children of a component
     */
    pub fn get_component_children(&self, component: &ComponentID)
        -> Result<Vec<ComponentID>, StateError>
    {
        Ok((try!(self.get_component_by_id(component))).children.clone())
    }

    /**
     * Creates a component inherited from another
     */
    fn create_inherited_component(&mut self, owner: &EntityID, parent: &ComponentID, inherit: &ComponentID)
        -> Result<ComponentID, StateError>
    {
        if !self.entities.contains_key(owner) {
            return Err(EntityNotFound(owner.clone()))
        }
        if !self.components.contains_key(parent) {
            return Err(ComponentNotFound(parent.clone()))
        }
        if !self.components.contains_key(inherit) {
            return Err(ComponentNotFound(inherit.clone()))
        }

        let newID = self.next_component_id;

        let newComponent = Component {
            owner: owner.clone(),
            data: ComponentDataLink(inherit.clone()),
            linked_from: Vec::new(),
            parent: Some(parent.clone()),
            children: Vec::new(),
            cmp_type: self.get_component_by_id(inherit).unwrap().cmp_type.clone()
        };

        self.get_component_by_id_mut(inherit).unwrap().linked_from.push(newID);
        self.get_component_by_id_mut(parent).unwrap().children.push(newID);
        self.get_entity_by_id_mut(owner).unwrap().components.push(newID);

        self.components.insert(newID, newComponent);

        self.next_component_id = self.next_component_id + 1;

        // recursively inheriting if necessary
        match self.get_component_by_id(inherit).unwrap().cmp_type.clone() {
            NativeComponentType(_) => (),
            EntityComponentType(entity) => {
                let components_to_inherit: Vec<ComponentID> = self.get_entity_by_id(&entity).unwrap().components.iter().map(|c| c.clone()).collect();

                // inheriting components
                for cmp in components_to_inherit.move_iter() {
                    match self.create_inherited_component(owner, &newID, &cmp) {
                        Ok(_) => (),
                        Err(err) => {
                            self.destroy_component(&newID);     // rollback
                            return Err(err);
                        }
                    }
                }
            }
        }

        // returning ID
        Ok(newID)
    }

    fn get_entity_by_id<'a>(&'a self, id: &ComponentID)
        -> Result<&'a EntityData, StateError>
    {
        match self.entities.find(id) {
            None => Err(EntityNotFound(id.clone())),
            Some(c) => Ok(c)
        }
    }

    fn get_entity_by_id_mut<'a>(&'a mut self, id: &ComponentID)
        -> Result<&'a mut EntityData, StateError>
    {
        match self.entities.find_mut(id) {
            None => Err(EntityNotFound(id.clone())),
            Some(c) => Ok(c)
        }
    }

    fn get_component_by_id<'a>(&'a self, id: &ComponentID)
        -> Result<&'a Component, StateError>
    {
        match self.components.find(id) {
            None => Err(ComponentNotFound(id.clone())),
            Some(c) => Ok(c)
        }
    }

    fn get_component_by_id_mut<'a>(&'a mut self, id: &ComponentID)
        -> Result<&'a mut Component, StateError>
    {
        match self.components.find_mut(id) {
            None => Err(ComponentNotFound(id.clone())),
            Some(c) => Ok(c)
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::EntitiesState;

    #[test]
    fn basic() {
        let mut state = EntitiesState::new();

        let eID = state.create_entity(Some(format!("myname")), true);

        let cmpID = state.create_native_component(&eID, "test", HashMap::new());
    }
}
<|endoftext|>


<commit_before>fn value(c: char) -> u32 {
    match c {
        'a' | 'e' | 'i' | 'o' | 'u' | 'l' | 'n' | 'r' | 's' | 't' => 1,
        'd' | 'g' => 2,
        'b' | 'c' | 'm' | 'p' => 3,
        'f' | 'h' | 'v' | 'w' | 'y' => 4,
        'k' => 5,
        'j' | 'x' => 8,
        'q' | 'z' => 10,
        _ => 0,
    }
}

pub fn score(word: &str) -> u32 {
    let owned_word = String::from(word).to_lowercase();

    owned_word.chars().fold(0, |acc, x| acc + value(x))
}
<commit_msg>Improve scrabble by removing unnecessary String::from()<commit_after>fn value(c: char) -> u32 {
    match c {
        'a' | 'e' | 'i' | 'o' | 'u' | 'l' | 'n' | 'r' | 's' | 't' => 1,
        'd' | 'g' => 2,
        'b' | 'c' | 'm' | 'p' => 3,
        'f' | 'h' | 'v' | 'w' | 'y' => 4,
        'k' => 5,
        'j' | 'x' => 8,
        'q' | 'z' => 10,
        _ => 0,
    }
}

pub fn score(word: &str) -> u32 {
    word.to_lowercase().chars().fold(0, |acc, x| acc + value(x))
}
<|endoftext|>


<commit_before>//! Crate `ruma_events_macros` provides a procedural macro for generating
//! [ruma-events](https://github.com/ruma/ruma-events) events.
//!
//! See the documentation for the `ruma_event!` macro for usage details.
#![deny(
    missing_copy_implementations,
    missing_debug_implementations,
    // missing_docs, # Uncomment when https://github.com/rust-lang/rust/pull/60562 is released.
)]
#![warn(
    clippy::empty_line_after_outer_attr,
    clippy::expl_impl_clone_on_copy,
    clippy::if_not_else,
    clippy::items_after_statements,
    clippy::match_same_arms,
    clippy::mem_forget,
    clippy::multiple_inherent_impl,
    clippy::mut_mut,
    clippy::needless_borrow,
    clippy::needless_continue,
    clippy::single_match_else,
    clippy::unicode_not_nfc,
    clippy::use_self,
    clippy::used_underscore_binding,
    clippy::wrong_pub_self_convention,
    clippy::wrong_self_convention
)]
// Since we support Rust 1.36.0, we can't apply this suggestion yet
#![allow(clippy::use_self)]
#![recursion_limit = "128"]

extern crate proc_macro;

use proc_macro::TokenStream;
use quote::ToTokens;
use syn::{parse_macro_input, DeriveInput};

use self::{
    collection::{expand_collection, parse::RumaCollectionInput},
    event_content::{expand_message_event, expand_state_event},
    from_raw::expand_from_raw,
    gen::RumaEvent,
    parse::RumaEventInput,
};

mod collection;
mod event_content;
mod from_raw;
mod gen;
mod parse;

// A note about the `example` modules that appears in doctests:
//
// This is necessary because otherwise the expanded code appears in function context, which makes
// the compiler interpret the output of the macro as a statement, and proc macros currently aren't
// allowed to expand to statements, resulting in a compiler error.

/// Generates a Rust type for a Matrix event.
///
/// # Examples
///
/// The most common form of event is a struct with all the standard fields for an event of its
/// kind and a struct for its `content` field:
///
/// ```ignore
/// # pub mod example {
/// # use ruma_events_macros::ruma_event;
/// ruma_event! {
///     /// Informs the room about what room aliases it has been given.
///     AliasesEvent {
///         kind: StateEvent,
///         event_type: RoomAliases,
///         content: {
///             /// A list of room aliases.
///             pub aliases: Vec<ruma_identifiers::RoomAliasId>,
///         }
///     }
/// }
/// # }
/// ```
///
/// Occasionally an event will have non-standard fields at its top level (outside the `content`
/// field). These extra fields are declared in block labeled with `fields`:
///
/// ```ignore
/// # pub mod example {
/// # use ruma_events_macros::ruma_event;
/// ruma_event! {
///     /// A redaction of an event.
///     RedactionEvent {
///         kind: RoomEvent,
///         event_type: RoomRedaction,
///         fields: {
///             /// The ID of the event that was redacted.
///             pub redacts: ruma_identifiers::EventId
///         },
///         content: {
///             /// The reason for the redaction, if any.
///             pub reason: Option<String>,
///         },
///     }
/// }
/// # }
/// ```
///
/// Sometimes the type of the `content` should be a type alias rather than a struct or enum. This
/// is designated with `content_type_alias`:
///
/// ```ignore
/// # pub mod example {
/// # use ruma_events_macros::ruma_event;
/// ruma_event! {
///     /// Informs the client about the rooms that are considered direct by a user.
///     DirectEvent {
///         kind: Event,
///         event_type: Direct,
///         content_type_alias: {
///             /// The payload of a `DirectEvent`.
///             ///
///             /// A mapping of `UserId`'s to a collection of `RoomId`'s which are considered
///             /// *direct* for that particular user.
///             std::collections::BTreeMap<ruma_identifiers::UserId, Vec<ruma_identifiers::RoomId>>
///         }
///     }
/// }
/// # }
/// ```
///
/// If `content` and `content_type_alias` are both supplied, the second one listed will overwrite
/// the first.
///
/// The event type and content type will have copies generated inside a private `raw` module. These
/// "raw" versions are the same, except they implement `serde::Deserialize`. An implementation of
/// `FromRaw` will be provided, which will allow the user to deserialize the event type as
/// `EventJson<EventType>`.
#[proc_macro]
pub fn ruma_event(input: TokenStream) -> TokenStream {
    let ruma_event_input = syn::parse_macro_input!(input as RumaEventInput);

    let ruma_event = RumaEvent::from(ruma_event_input);

    ruma_event.into_token_stream().into()
}

/// Generates a collection type to represent the various Matrix event types.
///
/// This macro also implements the necessary traits for the type to serialize and deserialize itself.
// TODO more docs/example
#[proc_macro]
pub fn event_content_collection(input: TokenStream) -> TokenStream {
    let ruma_collection_input = syn::parse_macro_input!(input as RumaCollectionInput);
    expand_collection(ruma_collection_input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Generates an implementation of `ruma_events::FromRaw`. Only usable inside of `ruma_events`.
/// Requires there to be a `raw` module in the same scope, with a type with the same name and fields
/// as the one that this macro is used on.
#[proc_macro_derive(FromRaw)]
pub fn derive_from_raw(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_from_raw(input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Generates an implementation of `ruma_events::MessageEventContent` and it's super traits.
#[proc_macro_derive(MessageEventContent, attributes(ruma_event))]
pub fn derive_message_event_content(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_message_event(input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Generates an implementation of `ruma_events::StateEventContent` and it's super traits.
#[proc_macro_derive(StateEventContent, attributes(ruma_event))]
pub fn derive_state_event_content(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_state_event(input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}
<commit_msg>Clean up macro crate attributes<commit_after>//! Crate `ruma_events_macros` provides a procedural macro for generating
//! [ruma-events](https://github.com/ruma/ruma-events) events.
//!
//! See the documentation for the invidiual macros for usage details.
#![deny(
    missing_copy_implementations,
    missing_debug_implementations,
    missing_docs
)]

extern crate proc_macro;

use proc_macro::TokenStream;
use quote::ToTokens;
use syn::{parse_macro_input, DeriveInput};

use self::{
    collection::{expand_collection, parse::RumaCollectionInput},
    event_content::{expand_message_event, expand_state_event},
    from_raw::expand_from_raw,
    gen::RumaEvent,
    parse::RumaEventInput,
};

mod collection;
mod event_content;
mod from_raw;
mod gen;
mod parse;

// A note about the `example` modules that appears in doctests:
//
// This is necessary because otherwise the expanded code appears in function context, which makes
// the compiler interpret the output of the macro as a statement, and proc macros currently aren't
// allowed to expand to statements, resulting in a compiler error.

/// Generates a Rust type for a Matrix event.
///
/// # Examples
///
/// The most common form of event is a struct with all the standard fields for an event of its
/// kind and a struct for its `content` field:
///
/// ```ignore
/// # pub mod example {
/// # use ruma_events_macros::ruma_event;
/// ruma_event! {
///     /// Informs the room about what room aliases it has been given.
///     AliasesEvent {
///         kind: StateEvent,
///         event_type: RoomAliases,
///         content: {
///             /// A list of room aliases.
///             pub aliases: Vec<ruma_identifiers::RoomAliasId>,
///         }
///     }
/// }
/// # }
/// ```
///
/// Occasionally an event will have non-standard fields at its top level (outside the `content`
/// field). These extra fields are declared in block labeled with `fields`:
///
/// ```ignore
/// # pub mod example {
/// # use ruma_events_macros::ruma_event;
/// ruma_event! {
///     /// A redaction of an event.
///     RedactionEvent {
///         kind: RoomEvent,
///         event_type: RoomRedaction,
///         fields: {
///             /// The ID of the event that was redacted.
///             pub redacts: ruma_identifiers::EventId
///         },
///         content: {
///             /// The reason for the redaction, if any.
///             pub reason: Option<String>,
///         },
///     }
/// }
/// # }
/// ```
///
/// Sometimes the type of the `content` should be a type alias rather than a struct or enum. This
/// is designated with `content_type_alias`:
///
/// ```ignore
/// # pub mod example {
/// # use ruma_events_macros::ruma_event;
/// ruma_event! {
///     /// Informs the client about the rooms that are considered direct by a user.
///     DirectEvent {
///         kind: Event,
///         event_type: Direct,
///         content_type_alias: {
///             /// The payload of a `DirectEvent`.
///             ///
///             /// A mapping of `UserId`'s to a collection of `RoomId`'s which are considered
///             /// *direct* for that particular user.
///             std::collections::BTreeMap<ruma_identifiers::UserId, Vec<ruma_identifiers::RoomId>>
///         }
///     }
/// }
/// # }
/// ```
///
/// If `content` and `content_type_alias` are both supplied, the second one listed will overwrite
/// the first.
///
/// The event type and content type will have copies generated inside a private `raw` module. These
/// "raw" versions are the same, except they implement `serde::Deserialize`. An implementation of
/// `FromRaw` will be provided, which will allow the user to deserialize the event type as
/// `EventJson<EventType>`.
#[proc_macro]
pub fn ruma_event(input: TokenStream) -> TokenStream {
    let ruma_event_input = syn::parse_macro_input!(input as RumaEventInput);

    let ruma_event = RumaEvent::from(ruma_event_input);

    ruma_event.into_token_stream().into()
}

/// Generates a collection type to represent the various Matrix event types.
///
/// This macro also implements the necessary traits for the type to serialize and deserialize itself.
// TODO more docs/example
#[proc_macro]
pub fn event_content_collection(input: TokenStream) -> TokenStream {
    let ruma_collection_input = syn::parse_macro_input!(input as RumaCollectionInput);
    expand_collection(ruma_collection_input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Generates an implementation of `ruma_events::FromRaw`. Only usable inside of `ruma_events`.
/// Requires there to be a `raw` module in the same scope, with a type with the same name and fields
/// as the one that this macro is used on.
#[proc_macro_derive(FromRaw)]
pub fn derive_from_raw(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_from_raw(input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Generates an implementation of `ruma_events::MessageEventContent` and it's super traits.
#[proc_macro_derive(MessageEventContent, attributes(ruma_event))]
pub fn derive_message_event_content(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_message_event(input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}

/// Generates an implementation of `ruma_events::StateEventContent` and it's super traits.
#[proc_macro_derive(StateEventContent, attributes(ruma_event))]
pub fn derive_state_event_content(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand_state_event(input)
        .unwrap_or_else(|err| err.to_compile_error())
        .into()
}
<|endoftext|>


<commit_before>use markup5ever::{expanded_name, local_name, namespace_url, ns};

use crate::document::AcquiredNodes;
use crate::drawing_ctx::DrawingCtx;
use crate::element::{ElementResult, SetAttributes};
use crate::node::Node;
use crate::parsers::ParseValue;
use crate::properties::ColorInterpolationFilters;
use crate::rect::IRect;
use crate::session::Session;
use crate::xml::Attributes;

use super::bounds::BoundsBuilder;
use super::context::{FilterContext, FilterOutput};
use super::{
    FilterEffect, FilterError, FilterResolveError, Input, Primitive, PrimitiveParams,
    ResolvedPrimitive,
};

/// The `feOffset` filter primitive.
#[derive(Default)]
pub struct FeOffset {
    base: Primitive,
    params: Offset,
}

/// Resolved `feOffset` primitive for rendering.
#[derive(Clone, Default)]
pub struct Offset {
    pub in1: Input,
    pub dx: f64,
    pub dy: f64,
}

impl SetAttributes for FeOffset {
    fn set_attributes(&mut self, attrs: &Attributes, session: &Session) -> ElementResult {
        self.params.in1 = self.base.parse_one_input(attrs, session);

        for (attr, value) in attrs.iter() {
            match attr.expanded() {
                expanded_name!("", "dx") => self.params.dx = attr.parse(value)?,
                expanded_name!("", "dy") => self.params.dy = attr.parse(value)?,
                _ => (),
            }
        }

        Ok(())
    }
}

impl Offset {
    pub fn render(
        &self,
        bounds_builder: BoundsBuilder,
        ctx: &FilterContext,
        acquired_nodes: &mut AcquiredNodes<'_>,
        draw_ctx: &mut DrawingCtx,
    ) -> Result<FilterOutput, FilterError> {
        // https://www.w3.org/TR/filter-effects/#ColorInterpolationFiltersProperty
        //
        // "Note: The color-interpolation-filters property just has an
        // effect on filter operations. Therefore, it has no effect on
        // filter primitives like feOffset"
        //
        // This is why we pass Auto here.
        let input_1 = ctx.get_input(
            acquired_nodes,
            draw_ctx,
            &self.in1,
            ColorInterpolationFilters::Auto,
        )?;
        let bounds: IRect = bounds_builder
            .add_input(&input_1)
            .compute(ctx)
            .clipped
            .into();

        let (dx, dy) = ctx.paffine().transform_distance(self.dx, self.dy);

        let surface = input_1.surface().offset(bounds, dx, dy)?;

        Ok(FilterOutput { surface, bounds })
    }
}

impl FilterEffect for FeOffset {
    fn resolve(
        &self,
        _acquired_nodes: &mut AcquiredNodes<'_>,
        _node: &Node,
    ) -> Result<ResolvedPrimitive, FilterResolveError> {
        Ok(ResolvedPrimitive {
            primitive: self.base.clone(),
            params: PrimitiveParams::Offset(self.params.clone()),
        })
    }
}
<commit_msg>filters/offset.rs: use set_attribute()<commit_after>use markup5ever::{expanded_name, local_name, namespace_url, ns};

use crate::document::AcquiredNodes;
use crate::drawing_ctx::DrawingCtx;
use crate::element::{set_attribute, ElementResult, SetAttributes};
use crate::node::Node;
use crate::parsers::ParseValue;
use crate::properties::ColorInterpolationFilters;
use crate::rect::IRect;
use crate::session::Session;
use crate::xml::Attributes;

use super::bounds::BoundsBuilder;
use super::context::{FilterContext, FilterOutput};
use super::{
    FilterEffect, FilterError, FilterResolveError, Input, Primitive, PrimitiveParams,
    ResolvedPrimitive,
};

/// The `feOffset` filter primitive.
#[derive(Default)]
pub struct FeOffset {
    base: Primitive,
    params: Offset,
}

/// Resolved `feOffset` primitive for rendering.
#[derive(Clone, Default)]
pub struct Offset {
    pub in1: Input,
    pub dx: f64,
    pub dy: f64,
}

impl SetAttributes for FeOffset {
    fn set_attributes(&mut self, attrs: &Attributes, session: &Session) -> ElementResult {
        self.params.in1 = self.base.parse_one_input(attrs, session);

        for (attr, value) in attrs.iter() {
            match attr.expanded() {
                expanded_name!("", "dx") => {
                    set_attribute(&mut self.params.dx, attr.parse(value), session)
                }
                expanded_name!("", "dy") => {
                    set_attribute(&mut self.params.dy, attr.parse(value), session)
                }
                _ => (),
            }
        }

        Ok(())
    }
}

impl Offset {
    pub fn render(
        &self,
        bounds_builder: BoundsBuilder,
        ctx: &FilterContext,
        acquired_nodes: &mut AcquiredNodes<'_>,
        draw_ctx: &mut DrawingCtx,
    ) -> Result<FilterOutput, FilterError> {
        // https://www.w3.org/TR/filter-effects/#ColorInterpolationFiltersProperty
        //
        // "Note: The color-interpolation-filters property just has an
        // effect on filter operations. Therefore, it has no effect on
        // filter primitives like feOffset"
        //
        // This is why we pass Auto here.
        let input_1 = ctx.get_input(
            acquired_nodes,
            draw_ctx,
            &self.in1,
            ColorInterpolationFilters::Auto,
        )?;
        let bounds: IRect = bounds_builder
            .add_input(&input_1)
            .compute(ctx)
            .clipped
            .into();

        let (dx, dy) = ctx.paffine().transform_distance(self.dx, self.dy);

        let surface = input_1.surface().offset(bounds, dx, dy)?;

        Ok(FilterOutput { surface, bounds })
    }
}

impl FilterEffect for FeOffset {
    fn resolve(
        &self,
        _acquired_nodes: &mut AcquiredNodes<'_>,
        _node: &Node,
    ) -> Result<ResolvedPrimitive, FilterResolveError> {
        Ok(ResolvedPrimitive {
            primitive: self.base.clone(),
            params: PrimitiveParams::Offset(self.params.clone()),
        })
    }
}
<|endoftext|>


<commit_before>use super::ease::Easing;
pub struct Expo;

impl Easing for Expo {
    fn ease_in(t: f32, b: f32, c: f32, d: f32) -> f32 {
        if t == 0.0 {
            b
        } else {
            c * 2_f32.powf(10.0 * (t / d - 1.0)) + b
        }
    }

    fn ease_out(t: f32, b: f32, c: f32, d: f32) -> f32 {
        if t == d {
            b + c
        } else {
            c * (-2_f32.powf(-10.0 * t / d) + 1.0) + b
        }
    }

    fn ease_in_out(t: f32, b: f32, c: f32, d: f32) -> f32 {
        if t == d {
            return b;
        }
        if t == d {
            return b + c;
        }
        let mut inner_t = t / d / 2.0;
        if inner_t < 1.0 {
            return c / 2.0 * 2_f32.powf(10.0 * (t - 1.0)) + b;
        }
        inner_t -= 1.0;
        return c / 2.0 * (-(2_f32.powf(-10.0 * inner_t)) + 2.0) + b;
    }
}
<commit_msg>expo function tests added<commit_after>use super::ease::Easing;
pub struct Expo;

impl Easing for Expo {
    fn ease_in(t: f32, b: f32, c: f32, d: f32) -> f32 {
        if t == 0.0 {
            b
        } else {
            c * 2_f32.powf(10.0 * (t / d - 1.0)) + b
        }
    }

    fn ease_out(t: f32, b: f32, c: f32, d: f32) -> f32 {
        if t == d {
            b + c
        } else {
            c * (-2_f32.powf(-10.0 * t / d) + 1.0) + b
        }
    }

    fn ease_in_out(t: f32, b: f32, c: f32, d: f32) -> f32 {
        if t == 0.0 {
            return b;
        }
        if t == d {
            return b + c;
        }
        let mut inner_t = t / (d / 2.0);
        if inner_t < 1.0 {
            return c / 2.0 * 2_f32.powf(10.0 * (inner_t - 1.0)) + b;
        }
        inner_t -= 1.0;
        return c / 2.0 * (-(2_f32.powf(-10.0 * inner_t)) + 2.0) + b;
    }
}

mod test {
    use functions::ease::Easing;
    #[test]
    fn ease_in() {
        assert_relative_eq!(super::Expo::ease_in(1.0, 2.0, 3.0, 4.0), 2.016573);
    }

    #[test]
    fn ease_out() {
        assert_relative_eq!(super::Expo::ease_out(1.0, 2.0, 3.0, 4.0), 4.469670);
    }

    #[test]
    fn ease_in_out() {
        assert_relative_eq!(super::Expo::ease_in_out(1.0, 2.0, 3.0, 4.0), 2.046875);
    }

}
<|endoftext|>


<commit_before>extern crate mp4parse;

use std::env;
use std::fs::File;
use std::io::BufReader;

extern crate byteorder;
use byteorder::Error;

fn dump_file(filename: &String) {
    let file = File::open(filename).unwrap();
    let mut reader = BufReader::new(file);
    let mut context = mp4parse::MediaContext { tracks: Vec::new() };
    loop {
        match mp4parse::read_box(&mut reader, &mut context) {
            Ok(_) => {},
            Err(Error::UnexpectedEOF) => { break },
            Err(e) => { panic!(e); },
        }
    }
}

fn main() {
    for filename in env::args().skip(1) {
        println!("-- dump of '{}' --", filename);
        dump_file(&filename);
        println!("-- end of '{}' --", filename);
    }
}
<commit_msg>dump.rs: Print the final result after traversing the file.<commit_after>extern crate mp4parse;

use std::env;
use std::fs::File;
use std::io::BufReader;

extern crate byteorder;
use byteorder::Error;

fn dump_file(filename: &String) {
    let file = File::open(filename).unwrap();
    let mut reader = BufReader::new(file);
    let mut context = mp4parse::MediaContext { tracks: Vec::new() };
    loop {
        match mp4parse::read_box(&mut reader, &mut context) {
            Ok(_) => {},
            Err(Error::UnexpectedEOF) => { break },
            Err(e) => { panic!(e); },
        }
    }
    println!("-- result of parsing '{}' --\n{}", filename, context);
}

fn main() {
    for filename in env::args().skip(1) {
        println!("-- dump of '{}' --", filename);
        dump_file(&filename);
        println!("-- end of '{}' --", filename);
    }
}
<|endoftext|>