<commit_before>const MAX_TEMP: f32 = 1.0;
const MIN_TEMP: f32 = 0.0;
const HEAT_PER_SHOT: f32 = 0.025;
const NATURAL_COOL_DOWN_RATE: f32 = 0.2;
const OVERHEAT_COOL_DOWN_RATE: f32 = 0.4;

/// This is the player's gun: it slowly overheats with every shot so that the player can't just
/// spam shooting and ruin the gameplay
#[derive(Default)]
pub struct Gun {
    /// The current temperature of the gun - a percentage between 0 and 1
    pub temperature: f32,
    /// Whether or not the gun has overheated
    overheated: bool,
}

impl Gun {
    pub fn new() -> Gun {
        Gun::default()
    }

    /// This is called every tick and slowly cools the gun down
    pub fn cool_down(&mut self, dt: f32){
        if self.overheated{
            self.overheat_cool_down(dt);
        } else {
            self.natural_cool_down(dt);
        }
    }

    /// Whenever the gun is fired it heats up
    pub fn heat_up(&mut self){
        self.temperature = MAX_TEMP.min(self.temperature + MAX_TEMP * HEAT_PER_SHOT);
        if self.temperature == MAX_TEMP {
            self.overheated = true;
        }
    }

    /// Check if the gun has overheated or not
    pub fn is_available(&self) -> bool {
        !self.overheated
    }

    /// Reset the gun's state back to its defaults
    pub fn reset(&mut self){
        self.temperature = MIN_TEMP;
        self.overheated = false;
    }

    /// Cool down the gun naturally
    fn natural_cool_down(&mut self, dt: f32){
        self.temperature = MIN_TEMP.max(self.temperature - NATURAL_COOL_DOWN_RATE * dt);
    }

    /// The gun cools down faster if it has overheated
    fn overheat_cool_down(&mut self, dt: f32){
        self.temperature = MIN_TEMP.max(self.temperature - OVERHEAT_COOL_DOWN_RATE * dt);
        if self.temperature == MIN_TEMP {
            self.overheated = false;
        }
    }
}
<commit_msg>Simplify gun even more<commit_after>const HEAT_PER_SHOT: f32 = 0.025;
const NATURAL_COOL_DOWN_RATE: f32 = 0.2;
const OVERHEAT_COOL_DOWN_RATE: f32 = 0.4;

/// This is the player's gun: it slowly overheats with every shot so that the player can't just
/// spam shooting and ruin the gameplay
#[derive(Default)]
pub struct Gun {
    /// The current temperature of the gun - a percentage between 0 and 1
    pub temperature: f32,
    /// Whether or not the gun has overheated
    overheated: bool,
}

impl Gun {
    pub fn new() -> Gun {
        Gun::default()
    }

    /// This is called every tick and slowly cools the gun down
    pub fn cool_down(&mut self, dt: f32){
        if self.overheated{
            self.overheat_cool_down(dt);
        } else {
            self.natural_cool_down(dt);
        }
    }

    /// Whenever the gun is fired it heats up
    pub fn heat_up(&mut self){
        self.temperature = f32::min(1.0, self.temperature + HEAT_PER_SHOT);
        if self.temperature == 1.0 {
            self.overheated = true;
        }
    }

    /// Check if the gun has overheated or not
    pub fn is_available(&self) -> bool {
        !self.overheated
    }

    /// Reset the gun's state back to its defaults
    pub fn reset(&mut self){
        self.temperature = 0.0;
        self.overheated = false;
    }

    /// Cool down the gun naturally
    fn natural_cool_down(&mut self, dt: f32){
        self.temperature = f32::max(0.0, self.temperature - NATURAL_COOL_DOWN_RATE * dt);
    }

    /// The gun cools down faster if it has overheated
    fn overheat_cool_down(&mut self, dt: f32){
        self.temperature = f32::max(0.0, self.temperature - OVERHEAT_COOL_DOWN_RATE * dt);
        if self.temperature == 0.0 {
            self.overheated = false;
        }
    }
}
<|endoftext|>


<commit_before>use std::str::Chars;
use std::io::Reader;
use span::Span;

#[deriving(PartialEq, Show)]
pub enum Token {
    PLUS,
    MINUS,
    TIMES,
    AT,
    CARET,
    LPAREN,
    RPAREN,
    Noop,
    Done
}

/// The lexer is the system that has any notion of an input stream. The
/// stream can come from many sources, thus, we use the Reader trait
/// that is implemented for strings, files, tcp, etc...
///
/// The lexer should also not consume the whole stream at once, as
/// that will be a bottleneck for larger input sources.
pub struct Lexer<'a> {
    source: &'a str,
    iter: Chars<'a>,
    token: Token,
    span: Span
}

impl<'a> Lexer<'a> {
    pub fn new(source: &'a str) -> Lexer<'a> {
        Lexer {
            source: source,
            iter: source.chars(),
            token: Noop,
            span: Span::new(0, 0)
        }
    }

    /// Parse and fetch the next token in the text stream.
    /// This doesn't return the token, it stores it
    /// in the lexer.
    pub fn bump(&mut self) {
        // Fetch the next char.
        let c = match self.iter.next() {
            Some(c) => c,
            None => {
                self.token = Done;
                return;
            }
        };

        // Begin parsing an s-expression.
        if c == '(' {

        }
    }

    /// Expect a given token to come next, otherwise
    /// fail. Failing will result in a formatted
    /// error message that uses the Span and lets
    /// the user know what went wrong.
    pub fn expect(&mut self, tok: &Token) {
        if self.token == *tok {
            self.bump();
        } else {
            fail!("Expected {} but found {}", *tok, self.token);
        }
    }

    /// Optionally eat a given token. If the token is not
    /// found, this will simply return false and
    /// won't fail.
    pub fn eat(&mut self, tok: &Token) -> bool {
        if self.token == *tok {
            self.bump();
            true
        } else {
            false
        }
    }
}
<commit_msg>Added a noop test<commit_after>use std::str::Chars;
use std::io::Reader;
use span::Span;

#[deriving(PartialEq, Show)]
pub enum Token {
    PLUS,
    MINUS,
    TIMES,
    AT,
    CARET,
    LPAREN,
    RPAREN,
    Noop,
    Done
}

/// The lexer is the system that has any notion of an input stream. The
/// stream can come from many sources, thus, we use the Reader trait
/// that is implemented for strings, files, tcp, etc...
///
/// The lexer should also not consume the whole stream at once, as
/// that will be a bottleneck for larger input sources.
pub struct Lexer<'a> {
    source: &'a str,
    iter: Chars<'a>,
    token: Token,
    span: Span
}

impl<'a> Lexer<'a> {
    pub fn new(source: &'a str) -> Lexer<'a> {
        Lexer {
            source: source,
            iter: source.chars(),
            token: Noop,
            span: Span::new(0, 0)
        }
    }

    /// Parse and fetch the next token in the text stream.
    /// This doesn't return the token, it stores it
    /// in the lexer.
    pub fn bump(&mut self) {
        // Fetch the next char.
        let c = match self.iter.next() {
            Some(c) => c,
            None => {
                self.token = Done;
                return;
            }
        };

        // Begin parsing an s-expression.
        if c == '(' {

        }
    }

    /// Expect a given token to come next, otherwise
    /// fail. Failing will result in a formatted
    /// error message that uses the Span and lets
    /// the user know what went wrong.
    pub fn expect(&mut self, tok: &Token) {
        if self.token == *tok {
            self.bump();
        } else {
            fail!("Expected {} but found {}", *tok, self.token);
        }
    }

    /// Optionally eat a given token. If the token is not
    /// found, this will simply return false and
    /// won't fail.
    pub fn eat(&mut self, tok: &Token) -> bool {
        if self.token == *tok {
            self.bump();
            true
        } else {
            false
        }
    }
}

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

    #[test]
    fn noop() {
        let lexer = Lexer::new("foo");
        assert_eq!(lexer.token, Noop);
    }

}
<|endoftext|>


<commit_before><commit_msg>Add new 'Buffer' enum.<commit_after><|endoftext|>


<commit_before>use super::{ControlHandle, Window, Button, CheckBox, RadioButton, TextInput, Label, ImageFrame};
use std::convert::From;

#[allow(unused)]
use std::fmt::Display;

macro_rules! handles {
    ($control:ty) => {
        #[allow(deprecated)]
        impl From<&$control> for ControlHandle {
            fn from(control: &$control) -> Self { control.handle }
        }

        #[allow(deprecated)]
        impl From<&mut $control> for ControlHandle {
            fn from(control: &mut $control) -> Self { control.handle }
        }

        #[allow(deprecated)]
        impl PartialEq<ControlHandle> for $control {
            fn eq(&self, other: &ControlHandle) -> bool {
                self.handle == *other
            }
        }

        #[allow(deprecated)]
        impl PartialEq<$control> for ControlHandle {
            fn eq(&self, other: &$control) -> bool {
                *self == other.handle
            }
        }
    };
}

/**
Automatically implements the functionnalities required to process an external struct as a NWG control

```rust
#[macro_use] extern crate native_windows_gui as nwg;

pub struct TestControl {
    edit: nwg::TextInput,
    custom_data: String,
}

subclass_control!(TestControl, TextInput, edit);
```
*/
#[macro_export]
macro_rules! subclass_control {
    ($ty:ident, $base_type:ident, $field: ident) => {
        impl ::std::ops::Deref for $ty {
            type Target = $crate::$base_type;
            fn deref(&self) -> &$crate::$base_type { &self.$field }
        }

        impl ::std::ops::DerefMut for $ty {
            fn deref_mut(&mut self) -> &mut Self::Target {&mut self.$field }
        }

        impl Into<$crate::ControlHandle> for &$ty {
            fn into(self) -> $crate::ControlHandle { self.$field.handle.clone() }
        }

        impl Into<$crate::ControlHandle> for &mut $ty {
            fn into(self) -> $crate::ControlHandle { self.$field.handle.clone() }
        }

        impl PartialEq<$ty> for $crate::ControlHandle {
            fn eq(&self, other: &$ty) -> bool {
                *self == other.$field.handle
            }
        }

    }
}

handles!(Window);
handles!(Button);
handles!(ImageFrame);
handles!(Label);
handles!(CheckBox);
handles!(RadioButton);
handles!(TextInput);

#[cfg(feature = "textbox")]
use super::TextBox;

#[cfg(feature = "textbox")]
handles!(TextBox);

#[cfg(feature = "status-bar")]
use super::StatusBar;

#[cfg(feature = "status-bar")]
handles!(StatusBar);

#[cfg(feature = "tooltip")]
use super::Tooltip;

#[cfg(feature = "tooltip")]
handles!(Tooltip);

#[cfg(feature = "trackbar")]
use super::TrackBar;

#[cfg(feature = "trackbar")]
handles!(TrackBar);

#[cfg(feature = "menu")]
use super::{Menu, MenuItem, MenuSeparator};

#[cfg(feature = "menu")]
handles!(Menu);
#[cfg(feature = "menu")]
handles!(MenuItem);
#[cfg(feature = "menu")]
handles!(MenuSeparator);

#[cfg(feature = "combobox")]
use super::ComboBox;

#[cfg(feature = "combobox")]
impl<D: Display+Default> From<&ComboBox<D>> for ControlHandle {
    fn from(control: &ComboBox<D>) -> Self { control.handle }
}

#[cfg(feature = "combobox")]
impl<D: Display+Default> PartialEq<ControlHandle> for ComboBox<D> {
    fn eq(&self, other: &ControlHandle) -> bool {
        self.handle == *other
    }
}

#[cfg(feature = "combobox")]
impl<D: Display+Default> PartialEq<ComboBox<D>> for ControlHandle {
    fn eq(&self, other: &ComboBox<D>) -> bool {
        *self == other.handle
    }
}

#[cfg(feature = "listbox")]
use super::ListBox;

#[cfg(feature = "listbox")]
impl<D: Display+Default> From<&ListBox<D>> for ControlHandle {
    fn from(control: &ListBox<D>) -> Self { control.handle }
}

#[cfg(feature = "listbox")]
impl<D: Display+Default> PartialEq<ControlHandle> for ListBox<D> {
    fn eq(&self, other: &ControlHandle) -> bool {
        self.handle == *other
    }
}

#[cfg(feature = "listbox")]
impl<D: Display+Default> PartialEq<ListBox<D>> for ControlHandle {
    fn eq(&self, other: &ListBox<D>) -> bool {
        *self == other.handle
    }
}

#[cfg(feature = "tabs")]
use super::{TabsContainer, Tab};

#[cfg(feature = "tabs")]
handles!(TabsContainer);

#[cfg(feature = "tabs")]
handles!(Tab);

#[cfg(feature = "datetime-picker")]
use super::{DatePicker};

#[cfg(feature = "datetime-picker")]
handles!(DatePicker);

#[cfg(feature = "progress-bar")]
use super::ProgressBar;

#[cfg(feature = "progress-bar")]
handles!(ProgressBar);

#[cfg(feature = "tree-view")]
use super::TreeView;

#[cfg(feature = "tree-view")]
handles!(TreeView);

#[cfg(feature = "tray-notification")]
use super::TrayNotification;

#[cfg(feature = "tray-notification")]
handles!(TrayNotification);

#[cfg(feature = "message-window")]
use super::MessageWindow;

#[cfg(feature = "message-window")]
handles!(MessageWindow);

#[cfg(feature = "timer")]
#[allow(deprecated)]
use super::Timer;

#[cfg(feature = "timer")]
handles!(Timer);

#[cfg(feature = "animation-timer")]
use super::AnimationTimer;

#[cfg(feature = "animation-timer")]
handles!(AnimationTimer);

#[cfg(feature = "notice")]
use super::Notice;

#[cfg(feature = "notice")]
handles!(Notice);

#[cfg(feature = "list-view")]
use super::ListView;

#[cfg(feature = "list-view")]
handles!(ListView);

#[cfg(feature = "extern-canvas")]
use super::ExternCanvas;

#[cfg(feature = "extern-canvas")]
handles!(ExternCanvas);

#[cfg(feature = "frame")]
use super::Frame;

#[cfg(feature = "frame")]
handles!(Frame);

#[cfg(feature = "rich-textbox")]
use super::RichTextBox;

#[cfg(feature = "rich-textbox")]
handles!(RichTextBox);

#[cfg(feature = "rich-textbox")]
use super::RichLabel;

#[cfg(feature = "rich-textbox")]
handles!(RichLabel);

#[cfg(feature = "scroll-bar")]
use super::ScrollBar;

#[cfg(feature = "scroll-bar")]
handles!(ScrollBar);

#[cfg(feature = "plotting")]
use super::Plotters;

#[cfg(feature = "plotting")]
handles!(Plotters);
<commit_msg>add number select from handle<commit_after>use super::{ControlHandle, Window, Button, CheckBox, RadioButton, TextInput, Label, ImageFrame};
use std::convert::From;

#[allow(unused)]
use std::fmt::Display;

macro_rules! handles {
    ($control:ty) => {
        #[allow(deprecated)]
        impl From<&$control> for ControlHandle {
            fn from(control: &$control) -> Self { control.handle }
        }

        #[allow(deprecated)]
        impl From<&mut $control> for ControlHandle {
            fn from(control: &mut $control) -> Self { control.handle }
        }

        #[allow(deprecated)]
        impl PartialEq<ControlHandle> for $control {
            fn eq(&self, other: &ControlHandle) -> bool {
                self.handle == *other
            }
        }

        #[allow(deprecated)]
        impl PartialEq<$control> for ControlHandle {
            fn eq(&self, other: &$control) -> bool {
                *self == other.handle
            }
        }
    };
}

/**
Automatically implements the functionnalities required to process an external struct as a NWG control

```rust
#[macro_use] extern crate native_windows_gui as nwg;

pub struct TestControl {
    edit: nwg::TextInput,
    custom_data: String,
}

subclass_control!(TestControl, TextInput, edit);
```
*/
#[macro_export]
macro_rules! subclass_control {
    ($ty:ident, $base_type:ident, $field: ident) => {
        impl ::std::ops::Deref for $ty {
            type Target = $crate::$base_type;
            fn deref(&self) -> &$crate::$base_type { &self.$field }
        }

        impl ::std::ops::DerefMut for $ty {
            fn deref_mut(&mut self) -> &mut Self::Target {&mut self.$field }
        }

        impl Into<$crate::ControlHandle> for &$ty {
            fn into(self) -> $crate::ControlHandle { self.$field.handle.clone() }
        }

        impl Into<$crate::ControlHandle> for &mut $ty {
            fn into(self) -> $crate::ControlHandle { self.$field.handle.clone() }
        }

        impl PartialEq<$ty> for $crate::ControlHandle {
            fn eq(&self, other: &$ty) -> bool {
                *self == other.$field.handle
            }
        }

    }
}

handles!(Window);
handles!(Button);
handles!(ImageFrame);
handles!(Label);
handles!(CheckBox);
handles!(RadioButton);
handles!(TextInput);

#[cfg(feature = "textbox")]
use super::TextBox;

#[cfg(feature = "textbox")]
handles!(TextBox);

#[cfg(feature = "status-bar")]
use super::StatusBar;

#[cfg(feature = "status-bar")]
handles!(StatusBar);

#[cfg(feature = "tooltip")]
use super::Tooltip;

#[cfg(feature = "tooltip")]
handles!(Tooltip);

#[cfg(feature = "trackbar")]
use super::TrackBar;

#[cfg(feature = "trackbar")]
handles!(TrackBar);

#[cfg(feature = "menu")]
use super::{Menu, MenuItem, MenuSeparator};

#[cfg(feature = "menu")]
handles!(Menu);
#[cfg(feature = "menu")]
handles!(MenuItem);
#[cfg(feature = "menu")]
handles!(MenuSeparator);

#[cfg(feature = "combobox")]
use super::ComboBox;

#[cfg(feature = "combobox")]
impl<D: Display+Default> From<&ComboBox<D>> for ControlHandle {
    fn from(control: &ComboBox<D>) -> Self { control.handle }
}

#[cfg(feature = "combobox")]
impl<D: Display+Default> PartialEq<ControlHandle> for ComboBox<D> {
    fn eq(&self, other: &ControlHandle) -> bool {
        self.handle == *other
    }
}

#[cfg(feature = "combobox")]
impl<D: Display+Default> PartialEq<ComboBox<D>> for ControlHandle {
    fn eq(&self, other: &ComboBox<D>) -> bool {
        *self == other.handle
    }
}

#[cfg(feature = "listbox")]
use super::ListBox;

#[cfg(feature = "listbox")]
impl<D: Display+Default> From<&ListBox<D>> for ControlHandle {
    fn from(control: &ListBox<D>) -> Self { control.handle }
}

#[cfg(feature = "listbox")]
impl<D: Display+Default> PartialEq<ControlHandle> for ListBox<D> {
    fn eq(&self, other: &ControlHandle) -> bool {
        self.handle == *other
    }
}

#[cfg(feature = "listbox")]
impl<D: Display+Default> PartialEq<ListBox<D>> for ControlHandle {
    fn eq(&self, other: &ListBox<D>) -> bool {
        *self == other.handle
    }
}

#[cfg(feature = "tabs")]
use super::{TabsContainer, Tab};

#[cfg(feature = "tabs")]
handles!(TabsContainer);

#[cfg(feature = "tabs")]
handles!(Tab);

#[cfg(feature = "datetime-picker")]
use super::{DatePicker};

#[cfg(feature = "datetime-picker")]
handles!(DatePicker);

#[cfg(feature = "progress-bar")]
use super::ProgressBar;

#[cfg(feature = "progress-bar")]
handles!(ProgressBar);

#[cfg(feature = "tree-view")]
use super::TreeView;

#[cfg(feature = "tree-view")]
handles!(TreeView);

#[cfg(feature = "tray-notification")]
use super::TrayNotification;

#[cfg(feature = "tray-notification")]
handles!(TrayNotification);

#[cfg(feature = "message-window")]
use super::MessageWindow;

#[cfg(feature = "message-window")]
handles!(MessageWindow);

#[cfg(feature = "timer")]
#[allow(deprecated)]
use super::Timer;

#[cfg(feature = "timer")]
handles!(Timer);

#[cfg(feature = "animation-timer")]
use super::AnimationTimer;

#[cfg(feature = "animation-timer")]
handles!(AnimationTimer);

#[cfg(feature = "notice")]
use super::Notice;

#[cfg(feature = "notice")]
handles!(Notice);

#[cfg(feature = "list-view")]
use super::ListView;

#[cfg(feature = "list-view")]
handles!(ListView);

#[cfg(feature = "extern-canvas")]
use super::ExternCanvas;

#[cfg(feature = "extern-canvas")]
handles!(ExternCanvas);

#[cfg(feature = "frame")]
use super::Frame;

#[cfg(feature = "frame")]
handles!(Frame);

#[cfg(feature = "rich-textbox")]
use super::RichTextBox;

#[cfg(feature = "rich-textbox")]
handles!(RichTextBox);

#[cfg(feature = "rich-textbox")]
use super::RichLabel;

#[cfg(feature = "rich-textbox")]
handles!(RichLabel);

#[cfg(feature = "scroll-bar")]
use super::ScrollBar;

#[cfg(feature = "scroll-bar")]
handles!(ScrollBar);

#[cfg(feature = "number-select")]
use super::NumberSelect;

#[cfg(feature = "number-select")]
handles!(NumberSelect);

#[cfg(feature = "plotting")]
use super::Plotters;

#[cfg(feature = "plotting")]
handles!(Plotters);
<|endoftext|>


<commit_before>//! Module containing color-related functions using the `colored` crate.
//!
//! This module is only available when the `colored` feature is enabled for `fern`.
//! This can be done with the following in `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! # ...
//! fern = { version = "0.4", features = ["colored"] }
//! ```
use std::fmt;
use colored::Color;
use log::LogLevel;

/// Extension crate allowing the use of `.colored` on LogLevels.
pub trait ColoredLogLevel {
    /// Colors this log level with the given color.
    fn colored(&self, color: Color) -> LogLevelWithColor;
}

/// Opaque structure representing a log level with an associated color. This implements [`fmt::Display`] so that it is
/// displayed as the underlying log level surrounded with ASCII markers for the given color.
// this is necessary in order to avoid using colored::ColorString, which has a Display
// implementation involving many allocations, and would involve two more string allocations
// even to create it.
pub struct LogLevelWithColor {
    level: LogLevel,
    color: Color,
}

impl fmt::Display for LogLevelWithColor {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "\x1B[{}m{}\x1B[0m", self.color.to_fg_str(), self.level)
    }
}

/// Configuration specifying colors a log level can be colored as.
#[derive(Copy, Clone)]
pub struct ColoredLogLevelConfig {
    /// The color to color logs with the [`Error`] level.
    ///
    /// [`Error`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Error
    pub error: Color,
    /// The color to color logs with the [`Warn`] level.
    ///
    /// [`Warn`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Warn
    pub warn: Color,
    /// The color to color logs with the [`Info`] level.
    ///
    /// [`Info`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Info
    pub info: Color,
    /// The color to color logs with the [`Debug`] level.
    ///
    /// [`Debug`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Debug
    pub debug: Color,
    /// The color to color logs with the [`Trace`] level.
    ///
    /// [`Trace`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Trace
    pub trace: Color,
}

impl ColoredLogLevelConfig {
    /// Creates a new ColoredLogLevelConfig with the default colors.
    ///
    /// This matches the behavior of [`ColoredLogLevelConfig::default`].
    ///
    /// [`ColoredLogLevelConfig::default`]: #method.default
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Overrides the [`Error`] level color with the given color.
    ///
    /// The default color is [`Color::Red`].
    ///
    /// [`Error`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Error
    /// [`Color::Red`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.Red
    pub fn error(&mut self, error: Color) -> &mut Self {
        self.error = error;
        self
    }

    /// Overrides the [`Warn`] level color with the given color.
    ///
    /// The default color is [`Color::Yellow`].
    ///
    /// [`Warn`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Warn
    /// [`Color::Yellow`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.Yellow
    pub fn warn(&mut self, warn: Color) -> &mut Self {
        self.warn = warn;
        self
    }

    /// Overrides the [`Info`] level color with the given color.
    ///
    /// The default color is [`Color::White`].
    ///
    /// [`Info`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Info
    /// [`Color::White`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.White
    pub fn info(&mut self, info: Color) -> &mut Self {
        self.info = info;
        self
    }

    /// Overrides the [`Debug`] level color with the given color.
    ///
    /// The default color is [`Color::White`].
    ///
    /// [`Debug`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Debug
    /// [`Color::White`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.White
    pub fn debug(&mut self, debug: Color) -> &mut Self {
        self.debug = debug;
        self
    }

    /// Overrides the [`Trace`] level color with the given color.
    ///
    /// The default color is [`Color::White`].
    ///
    /// [`Trace`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Trace
    /// [`Color::White`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.White
    pub fn trace(&mut self, trace: Color) -> &mut Self {
        self.trace = trace;
        self
    }

    /// Retrieves the default configuration. This has:
    ///
    /// - [`Error`] as [`Color::Red`]
    /// - [`Warn`] as [`Color::Yellow`]
    /// - [`Info`] as [`Color::White`]
    /// - [`Debug`] as [`Color::White`]
    /// - [`Trace`] as [`Color::White`]
    ///
    /// [`Error`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Error
    /// [`Warn`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Warn
    /// [`Info`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Info
    /// [`Debug`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Debug
    /// [`Trace`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Trace
    /// [`Color::White`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.White
    /// [`Color::Yellow`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.Yellow
    /// [`Color::Red`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.Red
    pub fn default() -> Self {
        ColoredLogLevelConfig {
            error: Color::Red,
            warn: Color::Yellow,
            debug: Color::White,
            info: Color::White,
            trace: Color::White,
        }
    }

    /// Colors the given log level with the correct color.
    ///
    /// This will output ANSI escapes correctly coloring the log level when printed
    /// to a Unix terminal. Due to behavior of the [`colored`] crate, this does not
    /// function on Windows terminals.
    ///
    /// [`colored`]: https://github.com/mackwic/colored
    pub fn color(&self, level: LogLevel) -> LogLevelWithColor {
        level.colored(self.get_color(&level))
    }

    /// Retrieves the color that a log level should be colored as.
    pub fn get_color(&self, level: &LogLevel) -> Color {
        match *level {
            LogLevel::Error => self.error,
            LogLevel::Warn => self.warn,
            LogLevel::Info => self.info,
            LogLevel::Debug => self.debug,
            LogLevel::Trace => self.trace,
        }
    }
}

impl ColoredLogLevel for LogLevel {
    fn colored(&self, color: Color) -> LogLevelWithColor {
        LogLevelWithColor {
            level: *self,
            color: color,
        }
    }
}
<commit_msg>Make ColoredLogLevel private for an MVP colored release.<commit_after>//! Module containing color-related functions using the `colored` crate.
//!
//! This module is only available when the `colored` feature is enabled for `fern`.
//! This can be done with the following in `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! # ...
//! fern = { version = "0.4", features = ["colored"] }
//! ```
use std::fmt;
use colored::Color;
use log::LogLevel;

/// Extension crate allowing the use of `.colored` on LogLevels.
trait ColoredLogLevel {
    /// Colors this log level with the given color.
    fn colored(&self, color: Color) -> LogLevelWithColor;
}

/// Opaque structure representing a log level with an associated color. This implements [`fmt::Display`] so that it is
/// displayed as the underlying log level surrounded with ASCII markers for the given color.
// this is necessary in order to avoid using colored::ColorString, which has a Display
// implementation involving many allocations, and would involve two more string allocations
// even to create it.
pub struct LogLevelWithColor {
    level: LogLevel,
    color: Color,
}

impl fmt::Display for LogLevelWithColor {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "\x1B[{}m{}\x1B[0m", self.color.to_fg_str(), self.level)
    }
}

/// Configuration specifying colors a log level can be colored as.
#[derive(Copy, Clone)]
pub struct ColoredLogLevelConfig {
    /// The color to color logs with the [`Error`] level.
    ///
    /// [`Error`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Error
    pub error: Color,
    /// The color to color logs with the [`Warn`] level.
    ///
    /// [`Warn`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Warn
    pub warn: Color,
    /// The color to color logs with the [`Info`] level.
    ///
    /// [`Info`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Info
    pub info: Color,
    /// The color to color logs with the [`Debug`] level.
    ///
    /// [`Debug`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Debug
    pub debug: Color,
    /// The color to color logs with the [`Trace`] level.
    ///
    /// [`Trace`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Trace
    pub trace: Color,
}

impl ColoredLogLevelConfig {
    /// Creates a new ColoredLogLevelConfig with the default colors.
    ///
    /// This matches the behavior of [`ColoredLogLevelConfig::default`].
    ///
    /// [`ColoredLogLevelConfig::default`]: #method.default
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Overrides the [`Error`] level color with the given color.
    ///
    /// The default color is [`Color::Red`].
    ///
    /// [`Error`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Error
    /// [`Color::Red`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.Red
    pub fn error(&mut self, error: Color) -> &mut Self {
        self.error = error;
        self
    }

    /// Overrides the [`Warn`] level color with the given color.
    ///
    /// The default color is [`Color::Yellow`].
    ///
    /// [`Warn`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Warn
    /// [`Color::Yellow`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.Yellow
    pub fn warn(&mut self, warn: Color) -> &mut Self {
        self.warn = warn;
        self
    }

    /// Overrides the [`Info`] level color with the given color.
    ///
    /// The default color is [`Color::White`].
    ///
    /// [`Info`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Info
    /// [`Color::White`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.White
    pub fn info(&mut self, info: Color) -> &mut Self {
        self.info = info;
        self
    }

    /// Overrides the [`Debug`] level color with the given color.
    ///
    /// The default color is [`Color::White`].
    ///
    /// [`Debug`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Debug
    /// [`Color::White`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.White
    pub fn debug(&mut self, debug: Color) -> &mut Self {
        self.debug = debug;
        self
    }

    /// Overrides the [`Trace`] level color with the given color.
    ///
    /// The default color is [`Color::White`].
    ///
    /// [`Trace`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Trace
    /// [`Color::White`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.White
    pub fn trace(&mut self, trace: Color) -> &mut Self {
        self.trace = trace;
        self
    }

    /// Retrieves the default configuration. This has:
    ///
    /// - [`Error`] as [`Color::Red`]
    /// - [`Warn`] as [`Color::Yellow`]
    /// - [`Info`] as [`Color::White`]
    /// - [`Debug`] as [`Color::White`]
    /// - [`Trace`] as [`Color::White`]
    ///
    /// [`Error`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Error
    /// [`Warn`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Warn
    /// [`Info`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Info
    /// [`Debug`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Debug
    /// [`Trace`]: https://docs.rs/log/0.3/log/enum.LogLevel.html#variant.Trace
    /// [`Color::White`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.White
    /// [`Color::Yellow`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.Yellow
    /// [`Color::Red`]: https://docs.rs/colored/1/colored/enum.Color.html#variant.Red
    pub fn default() -> Self {
        ColoredLogLevelConfig {
            error: Color::Red,
            warn: Color::Yellow,
            debug: Color::White,
            info: Color::White,
            trace: Color::White,
        }
    }

    /// Colors the given log level with the correct color.
    ///
    /// This will output ANSI escapes correctly coloring the log level when printed
    /// to a Unix terminal. Due to behavior of the [`colored`] crate, this does not
    /// function on Windows terminals.
    ///
    /// [`colored`]: https://github.com/mackwic/colored
    pub fn color(&self, level: LogLevel) -> LogLevelWithColor {
        level.colored(self.get_color(&level))
    }

    /// Retrieves the color that a log level should be colored as.
    pub fn get_color(&self, level: &LogLevel) -> Color {
        match *level {
            LogLevel::Error => self.error,
            LogLevel::Warn => self.warn,
            LogLevel::Info => self.info,
            LogLevel::Debug => self.debug,
            LogLevel::Trace => self.trace,
        }
    }
}

impl ColoredLogLevel for LogLevel {
    fn colored(&self, color: Color) -> LogLevelWithColor {
        LogLevelWithColor {
            level: *self,
            color: color,
        }
    }
}
<|endoftext|>


<commit_before>use actix_web::{HttpRequest, HttpResponse};
use hyper::header::CONTENT_TYPE;
use json;
use mustache;
use mustache::MapBuilder;
use reqwest_mock::{Client, StubClient, StubDefault, StubSettings, StubStrictness};
use std::env;
use std::ops::Deref;
use std::sync::Mutex;
use url::percent_encoding;

pub enum ClientType {
    LIVE,
    TESTING,
}

lazy_static! {
    static ref CLIENT: Mutex<Option<ClientType>> = Mutex::new(Some(ClientType::LIVE));
}

pub fn set_client(ct: ClientType) {
    CLIENT.lock().unwrap().replace(ct);
}

pub fn json_for_url(url: &String) -> Result<json::JsonValue, String> {
    let client = match CLIENT.lock().unwrap().deref() {
        Some(ClientType::LIVE) => reqwest_mock::client::GenericClient::direct(),
        Some(ClientType::TESTING) => {
            if env::var("RECORDING").is_ok() {
                reqwest_mock::client::GenericClient::replay_dir("tests/requests")
            } else {
                reqwest_mock::client::GenericClient::stub(StubClient::new(StubSettings {
                    default: StubDefault::Error,
                    strictness: StubStrictness::MethodUrl,
                }))
            }
        }
        None => panic!(),
    };
    let res = match client.get(url).send() {
        Ok(val) => val,
        Err(err) => {
            return Err(format!("Can't connect to TfL: {}", err));
        }
    };
    let buffer: String = res.body_to_utf8().unwrap();
    let obj = match json::parse(&buffer) {
        Ok(val) => val,
        Err(_) => {
            return Err(format!("Bad json: {} ", buffer));
        }
    };
    return Ok(obj);
}

pub fn render_to_response(path: &str, data: &mustache::Data) -> HttpResponse {
    let template = mustache::compile_path(path).expect("working template");
    let mut buffer: Vec<u8> = vec![];
    template.render_data(&mut buffer, data).unwrap();
    let mut response = HttpResponse::Ok();
    response.header(CONTENT_TYPE, "text/html");
    response.body(buffer)
}

pub static KEY: &'static str = "favourites";

pub fn favourites(req: &HttpRequest) -> json::JsonValue {
    let cookie = req.cookie(KEY);
    match cookie {
        Some(val) => {
            match json::parse(&val.value()) {
                Ok(val) => val,
                Err(_) => json::JsonValue::new_object(), // assume junk
            }
        }
        None => json::JsonValue::new_object(),
    }
}

pub fn mustache_favourites(req: &HttpRequest) -> mustache::Data {
    let favourites = favourites(req);
    MapBuilder::new()
        .insert_vec("favourites", |vecbuilder| {
            let mut vecb = vecbuilder;
            for fav in favourites.entries() {
                vecb = vecb
                    .push_map(|mapbuilder| mapbuilder.insert_str("key", fav.0).insert_str("value", fav.1));
            }
            vecb
        })
        .build()
}

pub fn query_encode(input: &str) -> String {
    percent_encoding::utf8_percent_encode(input, percent_encoding::QUERY_ENCODE_SET).collect::<String>()
}
<commit_msg>Rip out non-recording options for reqwest_mock<commit_after>use actix_web::{HttpRequest, HttpResponse};
use hyper::header::CONTENT_TYPE;
use json;
use mustache;
use mustache::MapBuilder;
use reqwest_mock::Client;
use std::ops::Deref;
use std::sync::Mutex;
use url::percent_encoding;

pub enum ClientType {
    LIVE,
    TESTING,
}

lazy_static! {
    static ref CLIENT: Mutex<Option<ClientType>> = Mutex::new(Some(ClientType::LIVE));
}

pub fn set_client(ct: ClientType) {
    CLIENT.lock().unwrap().replace(ct);
}

pub fn json_for_url(url: &String) -> Result<json::JsonValue, String> {
    let client = match CLIENT.lock().unwrap().deref() {
        Some(ClientType::LIVE) => reqwest_mock::client::GenericClient::direct(),
        Some(ClientType::TESTING) => {
            reqwest_mock::client::GenericClient::replay_dir("tests/requests")
        }
        None => panic!(),
    };
    let res = match client.get(url).send() {
        Ok(val) => val,
        Err(err) => {
            return Err(format!("Can't connect to TfL: {}", err));
        }
    };
    let buffer: String = res.body_to_utf8().unwrap();
    let obj = match json::parse(&buffer) {
        Ok(val) => val,
        Err(_) => {
            return Err(format!("Bad json: {} ", buffer));
        }
    };
    return Ok(obj);
}

pub fn render_to_response(path: &str, data: &mustache::Data) -> HttpResponse {
    let template = mustache::compile_path(path).expect("working template");
    let mut buffer: Vec<u8> = vec![];
    template.render_data(&mut buffer, data).unwrap();
    let mut response = HttpResponse::Ok();
    response.header(CONTENT_TYPE, "text/html");
    response.body(buffer)
}

pub static KEY: &'static str = "favourites";

pub fn favourites(req: &HttpRequest) -> json::JsonValue {
    let cookie = req.cookie(KEY);
    match cookie {
        Some(val) => {
            match json::parse(&val.value()) {
                Ok(val) => val,
                Err(_) => json::JsonValue::new_object(), // assume junk
            }
        }
        None => json::JsonValue::new_object(),
    }
}

pub fn mustache_favourites(req: &HttpRequest) -> mustache::Data {
    let favourites = favourites(req);
    MapBuilder::new()
        .insert_vec("favourites", |vecbuilder| {
            let mut vecb = vecbuilder;
            for fav in favourites.entries() {
                vecb = vecb
                    .push_map(|mapbuilder| mapbuilder.insert_str("key", fav.0).insert_str("value", fav.1));
            }
            vecb
        })
        .build()
}

pub fn query_encode(input: &str) -> String {
    percent_encoding::utf8_percent_encode(input, percent_encoding::QUERY_ENCODE_SET).collect::<String>()
}
<|endoftext|>


<commit_before>use node;
use time;
use std::collections::VecDeque;
use node::receptions;

pub const POLL_FREQUENCY_MS: u64 = 50;
pub const TRIES: u8 = 5;

#[test]
fn node_ping() {
   let alpha = node::Node::new();
   let beta  = node::Node::new();
   let beta_seed = beta.local_info();
   let span = time::Duration::seconds(1);

   // Bootstrapping alpha:
   alpha.bootstrap(beta_seed);

   let beta_receptions = alpha.receptions().during(span).from(beta.id().clone());

   // Alpha pings beta.
   assert_eq!(alpha.ping(beta.resources.id.clone()), node::PingResult::Alive);
   assert_eq!(1, beta_receptions.count());
}

#[test]
fn reception_iterator_times_out_correctly() {
   let alpha = node::Node::new();
   let span = time::Duration::seconds(1);
   let maximum = time::Duration::seconds(3);
   let receptions = alpha.receptions().during(span);

   let before = time::SteadyTime::now();

   // nothing is happening, so this should time out in around a second (not necessarily precise)
   assert_eq!(0, receptions.count());

   let after = time::SteadyTime::now();

   assert!(after - before < maximum);
}

#[test]
fn chained_node_find() {
   let mut nodes: VecDeque<node::Node> = (0..10).map(|_| { node::Node::new() }).collect();

   // We inform each node of the existance of the next three.
   for i in 1..4 {
      for (alpha, beta) in nodes.iter().zip(nodes.iter().skip(i)) {
         alpha.resources.table.insert_node(beta.local_info());
      }
   }

   // Head finds tail
   let head = nodes.pop_front().unwrap();
   let tail = nodes.pop_back().unwrap();
   assert_eq!(head.find_node(tail.id()).unwrap(), tail.local_info());
}

#[test]
fn bootstrapping_and_finding_on_simulated_network() {
   let origin = node::Node::new();

   let mut nodes: VecDeque<node::Node> = (0..100).map(|_| { node::Node::new() }).collect();

   for node in nodes.iter() {
      node.bootstrap(origin.local_info());
   }

   // Head finds tail in a few steps.
   let head = nodes.pop_front().unwrap();
   let tail = nodes.pop_back().unwrap();

   let receptions =
      head.receptions()
          .during(time::Duration::seconds(3))
          .rpc(receptions::RpcFilter::FindNodeResponse);

   assert_eq!(head.find_node(tail.id()).unwrap(), tail.local_info());
   let maximum_steps = 10;
   assert!(receptions.count() < maximum_steps);
}
<commit_msg>Bootstrap working<commit_after>use node;
use time;
use std::collections::VecDeque;
use node::receptions;

pub const POLL_FREQUENCY_MS: u64 = 50;
pub const TRIES: u8 = 5;

#[test]
fn node_ping() {
   let alpha = node::Node::new();
   let beta  = node::Node::new();
   let beta_seed = beta.local_info();
   let span = time::Duration::seconds(1);

   // Bootstrapping alpha:
   alpha.bootstrap(beta_seed);

   let beta_receptions = alpha.receptions().during(span).from(beta.id().clone());

   // Alpha pings beta.
   assert_eq!(alpha.ping(beta.resources.id.clone()), node::PingResult::Alive);
   assert_eq!(1, beta_receptions.count());
}

#[test]
fn reception_iterator_times_out_correctly() {
   let alpha = node::Node::new();
   let span = time::Duration::seconds(1);
   let maximum = time::Duration::seconds(3);
   let receptions = alpha.receptions().during(span);

   let before = time::SteadyTime::now();

   // nothing is happening, so this should time out in around a second (not necessarily precise)
   assert_eq!(0, receptions.count());

   let after = time::SteadyTime::now();

   assert!(after - before < maximum);
}

#[test]
fn chained_node_find() {
   let mut nodes: VecDeque<node::Node> = (0..10).map(|_| { node::Node::new() }).collect();

   // We inform each node of the existance of the next three.
   for i in 1..4 {
      for (alpha, beta) in nodes.iter().zip(nodes.iter().skip(i)) {
         alpha.resources.table.insert_node(beta.local_info());
      }
   }

   // Head finds tail
   let head = nodes.pop_front().unwrap();
   let tail = nodes.pop_back().unwrap();
   assert_eq!(head.find_node(tail.id()).unwrap(), tail.local_info());
}

#[test]
fn bootstrapping_and_finding_on_simulated_network() {
   let origin = node::Node::new();

   let mut nodes: VecDeque<node::Node> = (0..100).map(|_| { node::Node::new() }).collect();

   for node in nodes.iter() {
      node.bootstrap(origin.local_info());
   }

   // Head finds tail in a few steps.
   let head = nodes.pop_front().unwrap();
   let tail = nodes.pop_back().unwrap();

   let receptions =
      head.receptions()
          .during(time::Duration::seconds(3))
          .rpc(receptions::RpcFilter::FindNodeResponse);

   assert_eq!(head.find_node(tail.id()).unwrap().id, tail.local_info().id);
   let maximum_steps = 10;
   assert!(receptions.count() < maximum_steps);
}
<|endoftext|>


<commit_before>//! Stuff that uses the global state.
use crate::{atlas_cache::AtlasCache, Flick, FontData, ImageData, ImageKey};
use lazy_static::lazy_static;
use std::sync::Mutex;

#[derive(Default)]
pub struct EngineState {
    pub atlas_cache: AtlasCache<String>,
    pub average_frame_duration: Flick,
}

lazy_static! {
    /// Global game engine state.
    pub static ref ENGINE_STATE: Mutex<EngineState> = { Mutex::new(EngineState::default()) };
}

/// Return the average frame duration for recent frames.
///
/// Panics if called when an app isn't running via `run_app`.
pub fn get_frame_duration() -> Flick { ENGINE_STATE.lock().unwrap().average_frame_duration }

/// Add a named image into the engine image atlas.
pub fn add_sheet(id: impl Into<String>, sheet: impl Into<image::RgbaImage>) -> ImageKey {
    ENGINE_STATE
        .lock()
        .unwrap()
        .atlas_cache
        .add_sheet(id, sheet)
}

/// Add a tilesheet image that gets automatically split to subimages based on image structure.
///
/// Tiles are bounding boxes of non-background pixel groups surrounded by only background pixels or
/// image edges. Background color is the color of the bottom right corner pixel of the image. The
/// bounding boxes are returned lexically sorted by the coordinates of their bottom right corners,
/// first along the y-axis then along the x-axis. This produces a natural left-to-right,
/// bottom-to-top ordering for a cleanly laid out tile sheet.
///
/// Note that the background color is a solid color, not transparent pixels. The inner tiles may
/// have transparent parts, so a solid color is needed to separate them.
pub fn add_tilesheet(
    id: impl Into<String>,
    sheet: impl Into<image::RgbaImage>,
    _span: impl IntoIterator<Item = char>,
) -> Vec<ImageKey> {
    ENGINE_STATE
        .lock()
        .unwrap()
        .atlas_cache
        .add_tilesheet(id, sheet)
}

/// Add a bitmap font read from a tilesheet image.
pub fn add_tilesheet_font(
    id: impl Into<String>,
    sheet: impl Into<image::RgbaImage>,
    span: impl IntoIterator<Item = char>,
) -> FontData {
    ENGINE_STATE
        .lock()
        .unwrap()
        .atlas_cache
        .add_tilesheet_font(id, sheet, span)
}

/// Get a drawable (sub)image from the cache corresponding to the given `ImageKey`.
///
/// If the `ImageKey` specifies a sheet not found in the cache or invalid dimensions, will return
/// `None`.
pub fn get_image(key: &ImageKey) -> Option<ImageData> {
    ENGINE_STATE.lock().unwrap().atlas_cache.get(key)
}
<commit_msg>Simplify<commit_after>//! Stuff that uses the global state.
use crate::{atlas_cache::AtlasCache, Flick, FontData, ImageData, ImageKey};
use lazy_static::lazy_static;
use std::sync::Mutex;

#[derive(Default)]
pub struct EngineState {
    pub atlas_cache: AtlasCache<String>,
    pub average_frame_duration: Flick,
}

lazy_static! {
    /// Global game engine state.
    pub static ref ENGINE_STATE: Mutex<EngineState> = { Default::default() };
}

/// Return the average frame duration for recent frames.
///
/// Panics if called when an app isn't running via `run_app`.
pub fn get_frame_duration() -> Flick { ENGINE_STATE.lock().unwrap().average_frame_duration }

/// Add a named image into the engine image atlas.
pub fn add_sheet(id: impl Into<String>, sheet: impl Into<image::RgbaImage>) -> ImageKey {
    ENGINE_STATE
        .lock()
        .unwrap()
        .atlas_cache
        .add_sheet(id, sheet)
}

/// Add a tilesheet image that gets automatically split to subimages based on image structure.
///
/// Tiles are bounding boxes of non-background pixel groups surrounded by only background pixels or
/// image edges. Background color is the color of the bottom right corner pixel of the image. The
/// bounding boxes are returned lexically sorted by the coordinates of their bottom right corners,
/// first along the y-axis then along the x-axis. This produces a natural left-to-right,
/// bottom-to-top ordering for a cleanly laid out tile sheet.
///
/// Note that the background color is a solid color, not transparent pixels. The inner tiles may
/// have transparent parts, so a solid color is needed to separate them.
pub fn add_tilesheet(
    id: impl Into<String>,
    sheet: impl Into<image::RgbaImage>,
    _span: impl IntoIterator<Item = char>,
) -> Vec<ImageKey> {
    ENGINE_STATE
        .lock()
        .unwrap()
        .atlas_cache
        .add_tilesheet(id, sheet)
}

/// Add a bitmap font read from a tilesheet image.
pub fn add_tilesheet_font(
    id: impl Into<String>,
    sheet: impl Into<image::RgbaImage>,
    span: impl IntoIterator<Item = char>,
) -> FontData {
    ENGINE_STATE
        .lock()
        .unwrap()
        .atlas_cache
        .add_tilesheet_font(id, sheet, span)
}

/// Get a drawable (sub)image from the cache corresponding to the given `ImageKey`.
///
/// If the `ImageKey` specifies a sheet not found in the cache or invalid dimensions, will return
/// `None`.
pub fn get_image(key: &ImageKey) -> Option<ImageData> {
    ENGINE_STATE.lock().unwrap().atlas_cache.get(key)
}
<|endoftext|>


<commit_before><commit_msg>Don't break on Cargo.toml without package.metadata.sphinx. (Fixes #26) (#31)<commit_after><|endoftext|>


<commit_before>use num::Num;

#[inline(always)]
pub fn create<T: Num>(x: T, y: T, z: T, w: T) -> [T; 4] {[x, y, z, w]}
#[test]
fn test_create() {
    let v = create(1, 2, 3, 4);
    assert!(v[0] == 1);
    assert!(v[1] == 2);
    assert!(v[2] == 3);
    assert!(v[3] == 4);
}

#[inline(always)]
pub fn zero<T: Num>() -> [T; 4] {create(T::zero(), T::zero(), T::zero(), T::zero())}
#[inline(always)]
pub fn up<T: Num>() -> [T; 4] {create(T::zero(), T::zero(), T::one(), T::one())}
#[inline(always)]
pub fn down<T: Num>() -> [T; 4] {create(T::zero(), T::zero(), -T::one(), T::one())}
#[inline(always)]
pub fn forward<T: Num>() -> [T; 4] {create(T::zero(), T::one(), T::zero(), T::one())}
#[inline(always)]
pub fn back<T: Num>() -> [T; 4] {create(T::zero(), -T::one(), -T::zero(), T::one())}
#[inline(always)]
pub fn right<T: Num>() -> [T; 4] {create(T::one(), T::zero(), T::zero(), T::one())}
#[inline(always)]
pub fn left<T: Num>() -> [T; 4] {create(-T::one(), T::zero(), T::zero(), T::one())}

#[inline(always)]
pub fn copy<T: Num>(v: [T; 4]) -> [T; 4] {create(v[0], v[1], v[2], v[3])}
#[inline(always)]
pub fn clone<T: Num>(v: [T; 4]) -> [T; 4] {create(v[0], v[1], v[2], v[3])}
<commit_msg>updates<commit_after>use num::Num;

#[inline(always)]
pub fn create<T: Num>(x: T, y: T, z: T, w: T) -> [T; 4] {[x, y, z, w]}
#[test]
fn test_create() {
    let v = create(1, 2, 3, 4);
    assert!(v[0] == 1);
    assert!(v[1] == 2);
    assert!(v[2] == 3);
    assert!(v[3] == 4);
}

#[inline(always)]
pub fn zero<T: Num>() -> [T; 4] {create(T::zero(), T::zero(), T::zero(), T::zero())}
#[inline(always)]
pub fn identity<T: Num>() -> [T; 4] {create(T::zero(), T::zero(), T::zero(), T::one())}
#[inline(always)]
pub fn up<T: Num>() -> [T; 4] {create(T::zero(), T::zero(), T::one(), T::one())}
#[inline(always)]
pub fn down<T: Num>() -> [T; 4] {create(T::zero(), T::zero(), -T::one(), T::one())}
#[inline(always)]
pub fn forward<T: Num>() -> [T; 4] {create(T::zero(), T::one(), T::zero(), T::one())}
#[inline(always)]
pub fn back<T: Num>() -> [T; 4] {create(T::zero(), -T::one(), -T::zero(), T::one())}
#[inline(always)]
pub fn right<T: Num>() -> [T; 4] {create(T::one(), T::zero(), T::zero(), T::one())}
#[inline(always)]
pub fn left<T: Num>() -> [T; 4] {create(-T::one(), T::zero(), T::zero(), T::one())}

#[inline(always)]
pub fn copy<T: Num>(v: [T; 4]) -> [T; 4] {create(v[0], v[1], v[2], v[3])}
#[inline(always)]
pub fn clone<T: Num>(v: [T; 4]) -> [T; 4] {create(v[0], v[1], v[2], v[3])}
<|endoftext|>


<commit_before>mod document_spec;

use futures::future::{Future, ok, err, result};
use hyper;
use hyper::{Get, Post, Head, StatusCode};
use hyper::server::{Request, Response};
use serde_json;
use slog;
use tokio_service::{NewService, Service};
use tokio_core::reactor::Remote;

use http::*;
use error::{Error, ErrorKind};
pub use self::document_spec::{DocumentSpec, PapersUri};
use workspace::Workspace;

pub struct Papers {
    remote: Remote,
    logger: slog::Logger,
}

impl Papers {
    pub fn new(remote: Remote, logger: slog::Logger) -> Papers {
        Papers {
            remote: remote,
            logger: logger,
        }
    }

    fn submit(&self, req: Request) -> Box<Future<Item=Response, Error=Error>> {
        info!(
            self.logger,
            "Received a submit request ({}) from {:?}",
            req.method(),
            req.remote_addr().unwrap(),
        );
        debug!(self.logger, "Full request: {:#?}", req);

        if !req.has_content_type(mime!(Application/Json)) {
            return Box::new(err(ErrorKind::UnprocessableEntity.into()));
        }

        let remote = self.remote.clone();
        let handle = self.remote.handle().unwrap().clone();
        let logger = self.logger.clone();

        let response = req.get_body_bytes()

        // Parse the body into a DocumentSpec
        .and_then(|body| {
            result(
                serde_json::from_slice::<DocumentSpec>(body.as_slice())
                    .map_err(|err| Error::with_chain(err, ErrorKind::UnprocessableEntity))
            )
        })

        // Handle the parsed request
        .map_err(|_| ErrorKind::InternalServerError.into())
        .and_then(|document_spec| {
            result(Workspace::new(remote, document_spec, logger))
        }).and_then(move |workspace| {
            handle.spawn(workspace.execute());
            ok(Response::new().with_status(StatusCode::Ok))
        }).map_err(|_| ErrorKind::InternalServerError.into());

        Box::new(response)
    }

    fn preview(&self, req: Request) -> Box<Future<Item=Response, Error=Error>> {
        info!(
            self.logger,
            "Received a preview request ({}) from: {:?}",
            req.method(),
            req.remote_addr().unwrap(),
        );
        debug!(self.logger, "Full request: {:#?}", req);

        if !req.has_content_type(mime!(Application/Json)) {
            return Box::new(err(ErrorKind::UnprocessableEntity.into()));
        }

        let remote = self.remote.clone();
        let logger = self.logger.clone();

        let response = req.get_body_bytes()

        // Parse the body into a DocumentSpec
        .and_then(|body| {
            result(
                serde_json::from_slice::<DocumentSpec>(body.as_slice())
                    .map_err(|_| ErrorKind::UnprocessableEntity.into())
            )
        })

        // Handle the parsed request
        .and_then(|document_spec| {
            result(Workspace::new(remote, document_spec, logger))
                .map_err(|err| Error::with_chain(err, ErrorKind::InternalServerError))
        })
        .and_then(|workspace| {
            workspace.preview()
        }).and_then(|populated_template| {
            ok(Response::new()
                .with_status(StatusCode::Ok)
                .with_body(populated_template))
        });

        Box::new(response)

    }

    fn health_check(&self, req: Request) -> Box<Future<Item=Response, Error=Error>> {
        info!(
            self.logger,
            "Received a health check request ({}) from {:?}",
            req.method(),
            req.remote_addr().unwrap(),
        );
        Box::new(ok(Response::new().with_status(StatusCode::Ok)))
    }
}

impl Service for Papers {
    type Request = Request;
    type Response = Response;
    type Error = hyper::Error;
    type Future = Box<Future<Item=Response, Error=hyper::Error>>;

    fn call(&self, req: Self::Request) -> Self::Future {
        let response = match (req.method(), req.path()) {
            (&Get, "/healthz") | (&Head, "/healthz") => self.health_check(req),
            (&Post, "/preview") => self.preview(req),
            (&Post, "/submit") => self.submit(req),
            _ => {
                info!(
                    self.logger,
                    "Received a {} request to a non-existing endpoint \"{}\" from {:?}",
                    req.method(),
                    req.path(),
                    req.remote_addr().unwrap(),
                );
                Box::new(ok(Response::new().with_status(StatusCode::NotFound)))
            }
        }.then(|handler_result| {
            match handler_result {
                Ok(response) => ok(response),
                Err(err) => ok(err.into_response()),
            }
        });

        Box::new(response)
    }
}

impl NewService for Papers {
    type Request = Request;
    type Response = Response;
    type Error = hyper::Error;
    type Instance = Papers;

    fn new_service(&self) -> Result<Self::Instance, ::std::io::Error> {
        Ok(Papers {
            remote: self.remote.clone(),
            logger: self.logger.clone(),
        })
    }
}
<commit_msg>:hammer: Improve log format<commit_after>mod document_spec;

use futures::future::{Future, ok, err, result};
use hyper;
use hyper::{Get, Post, Head, StatusCode};
use hyper::server::{Request, Response};
use serde_json;
use slog;
use tokio_service::{NewService, Service};
use tokio_core::reactor::Remote;

use http::*;
use error::{Error, ErrorKind};
pub use self::document_spec::{DocumentSpec, PapersUri};
use workspace::Workspace;

pub fn log_request(logger, req) {
    info!(
        logger,
        "{} {} IP={:?}",
        req.method(),
        req.path(),
        req.remote_addr().unwrap(),
    );
}

pub struct Papers {
    remote: Remote,
    logger: slog::Logger,
}

impl Papers {
    pub fn new(remote: Remote, logger: slog::Logger) -> Papers {
        Papers {
            remote: remote,
            logger: logger,
        }
    }

    fn submit(&self, req: Request) -> Box<Future<Item=Response, Error=Error>> {
        log_request(self.logger, req);
        debug!(self.logger, "{:#?}", req);

        if !req.has_content_type(mime!(Application/Json)) {
            return Box::new(err(ErrorKind::UnprocessableEntity.into()));
        }

        let remote = self.remote.clone();
        let handle = self.remote.handle().unwrap().clone();
        let logger = self.logger.clone();

        let response = req.get_body_bytes()

        // Parse the body into a DocumentSpec
        .and_then(|body| {
            result(
                serde_json::from_slice::<DocumentSpec>(body.as_slice())
                    .map_err(|err| Error::with_chain(err, ErrorKind::UnprocessableEntity))
            )
        })

        // Handle the parsed request
        .map_err(|_| ErrorKind::InternalServerError.into())
        .and_then(|document_spec| {
            result(Workspace::new(remote, document_spec, logger))
        }).and_then(move |workspace| {
            handle.spawn(workspace.execute());
            ok(Response::new().with_status(StatusCode::Ok))
        }).map_err(|_| ErrorKind::InternalServerError.into());

        Box::new(response)
    }

    fn preview(&self, req: Request) -> Box<Future<Item=Response, Error=Error>> {
        info!(
            self.logger,
            "{} {} IP={:?}",
            req.method(),
            req.path(),
            req.remote_addr().unwrap(),
        );
        debug!(self.logger, "{:#?}", req);

        if !req.has_content_type(mime!(Application/Json)) {
            return Box::new(err(ErrorKind::UnprocessableEntity.into()));
        }

        let remote = self.remote.clone();
        let logger = self.logger.clone();

        let response = req.get_body_bytes()

        // Parse the body into a DocumentSpec
        .and_then(|body| {
            result(
                serde_json::from_slice::<DocumentSpec>(body.as_slice())
                    .map_err(|_| ErrorKind::UnprocessableEntity.into())
            )
        })

        // Handle the parsed request
        .and_then(|document_spec| {
            result(Workspace::new(remote, document_spec, logger))
                .map_err(|err| Error::with_chain(err, ErrorKind::InternalServerError))
        })
        .and_then(|workspace| {
            workspace.preview()
        }).and_then(|populated_template| {
            ok(Response::new()
                .with_status(StatusCode::Ok)
                .with_body(populated_template))
        });

        Box::new(response)

    }

    fn health_check(&self, req: Request) -> Box<Future<Item=Response, Error=Error>> {
        info!(
            self.logger,
            "{} {} IP={:?}",
            req.method(),
            req.path(),
            req.remote_addr().unwrap(),
        );
        Box::new(ok(Response::new().with_status(StatusCode::Ok)))
    }
}

impl Service for Papers {
    type Request = Request;
    type Response = Response;
    type Error = hyper::Error;
    type Future = Box<Future<Item=Response, Error=hyper::Error>>;

    fn call(&self, req: Self::Request) -> Self::Future {
        let response = match (req.method(), req.path()) {
            (&Get, "/healthz") | (&Head, "/healthz") => self.health_check(req),
            (&Post, "/preview") => self.preview(req),
            (&Post, "/submit") => self.submit(req),
            _ => {
                info!(
                    self.logger,
                    "{} {} IP={:?}",
                    req.method(),
                    req.path(),
                    req.remote_addr().unwrap(),
                );
                Box::new(ok(Response::new().with_status(StatusCode::NotFound)))
            }
        }.then(|handler_result| {
            match handler_result {
                Ok(response) => ok(response),
                Err(err) => ok(err.into_response()),
            }
        });

        Box::new(response)
    }
}

impl NewService for Papers {
    type Request = Request;
    type Response = Response;
    type Error = hyper::Error;
    type Instance = Papers;

    fn new_service(&self) -> Result<Self::Instance, ::std::io::Error> {
        Ok(Papers {
            remote: self.remote.clone(),
            logger: self.logger.clone(),
        })
    }
}
<|endoftext|>


<commit_before>use ascii::{AsciiChar, AsciiStr};
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::convert::AsRef;
use std::iter::{ExactSizeIterator, Iterator};
use std::ops::{Index, IndexMut, Range, RangeFull, RangeFrom, RangeTo};
use std::slice::{Iter, IterMut};
use ::{PASCAL_STRING_BUF_SIZE, PascalString};

/// A borrowed slice from a `PascalString`. Does not own its data.
#[derive(Eq, Hash, PartialEq, PartialOrd)]
pub struct PascalStr {
    /// The `AsciiStr`, borrowed from the original `PascalString`
    string: AsciiStr
}

impl PascalStr {
    /// Get a pointer to the first byte of the string buffer.
    #[inline]
    pub fn as_ptr(&self) -> *const AsciiChar {
        self.string.as_ptr()
    }

    /// Get a mutable pointer to the first byte of the string buffer.
    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut AsciiChar {
        self.string.as_mut_ptr()
    }

    /// Returns the number of characters used in the string.
    #[inline]
    pub fn len(&self) -> usize {
        self.string.len()
    }

    /// Returns true if the string has a length of 0
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns true if the string has a length of 255.
    ///
    /// When this value is true, no more elements can be pushed onto the string.
    #[inline]
    pub fn is_full(&self) -> bool {
        self.len() == PASCAL_STRING_BUF_SIZE
    }

    /// Get an immutable iterator to the internal character array.
    #[inline]
    pub fn chars<'a>(&'a self) -> Chars<'a> {
        Chars(self.string.as_slice().iter())
    }

    /// Get a mutable iterator to the internal character array.
    #[inline]
    pub fn chars_mut<'a>(&'a mut self) -> CharsMut<'a> {
        CharsMut(self.string.as_mut_slice().iter_mut())
    }
}

impl AsciiExt for PascalStr {
    type Owned = PascalString;

    fn is_ascii(&self) -> bool {
        true
    }

    fn to_ascii_uppercase(&self) -> Self::Owned {
        let bytes: &[u8] = self.as_ref();
        let mut upper = PascalString::from(bytes).unwrap();
        upper.make_ascii_uppercase();
        upper
    }

    fn to_ascii_lowercase(&self) -> Self::Owned {
        let bytes: &[u8] = self.as_ref();
        let mut lower = PascalString::from(bytes).unwrap();
        lower.make_ascii_lowercase();
        lower
    }

    fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
        self.string.eq_ignore_ascii_case(&other.string)
    }

    fn make_ascii_uppercase(&mut self) {
        self.string.make_ascii_uppercase()
    }

    fn make_ascii_lowercase(&mut self) {
        self.string.make_ascii_lowercase()
    }
}

impl ToOwned for PascalStr {
    type Owned = PascalString;
    fn to_owned(&self) -> Self::Owned {
        PascalString::from(&self.string).unwrap()
    }
}

impl AsRef<str> for PascalStr {
    fn as_ref(&self) -> &str {
        self.string.as_ref()
    }
}

impl AsRef<[u8]> for PascalStr {
    fn as_ref(&self) -> &[u8] {
        self.string.as_ref()
    }
}

impl AsRef<AsciiStr> for PascalStr {
    fn as_ref(&self) -> &AsciiStr {
        &self.string
    }
}

impl AsMut<AsciiStr> for PascalStr {
    fn as_mut(&mut self) -> &mut AsciiStr {
        &mut self.string
    }
}

impl AsRef<[AsciiChar]> for PascalStr {
    fn as_ref(&self) -> &[AsciiChar] {
        self.string.as_ref()
    }
}

impl AsMut<[AsciiChar]> for PascalStr {
    fn as_mut(&mut self) -> &mut [AsciiChar] {
        self.string.as_mut()
    }
}

impl Index<u8> for PascalStr {
    type Output = AsciiChar;
    fn index(&self, index: u8) -> &Self::Output {
        let index = index as usize;
        assert!(index < self.len());
        &self.string[index]
    }
}

impl IndexMut<u8> for PascalStr {
    fn index_mut(&mut self, index: u8) -> &mut Self::Output {
        let index = index as usize;
        assert!(index < self.len());
        &mut self.string[index]
    }
}

impl Index<usize> for PascalStr {
    type Output = AsciiChar;
    fn index(&self, index: usize) -> &Self::Output {
        assert!(index < self.len());
        &self.string[index]
    }
}

impl IndexMut<usize> for PascalStr {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        assert!(index < self.len());
        &mut self.string[index]
    }
}

impl Index<RangeFull> for PascalStr {
    type Output = [AsciiChar];
    fn index(&self, _: RangeFull) -> &Self::Output {
        let char_array: &[AsciiChar] = self.string.as_ref();
        &char_array[..]
    }
}

impl IndexMut<RangeFull> for PascalStr {
    fn index_mut(&mut self, _: RangeFull) -> &mut Self::Output {
        let char_array: &mut [AsciiChar] = self.string.as_mut();
        &mut char_array[..]
    }
}

impl Index<Range<u8>> for PascalStr {
    type Output = [AsciiChar];
    fn index(&self, range: Range<u8>) -> &Self::Output {
        assert!((range.end as usize) < self.len());
        let char_array: &[AsciiChar] = self.string.as_ref();
        &char_array[range.start as usize..range.end as usize]
    }
}

impl IndexMut<Range<u8>> for PascalStr {
    fn index_mut(&mut self, range: Range<u8>) -> &mut Self::Output {
        assert!((range.end as usize) < self.len());
        let char_array: &mut [AsciiChar] = self.string.as_mut();
        &mut char_array[range.start as usize..range.end as usize]
    }
}

impl Index<Range<usize>> for PascalStr {
    type Output = [AsciiChar];
    fn index(&self, range: Range<usize>) -> &Self::Output {
        assert!(range.end < self.len());
        let char_array: &[AsciiChar] = self.string.as_ref();
        &char_array[range.start..range.end]
    }
}

impl IndexMut<Range<usize>> for PascalStr {
    fn index_mut(&mut self, range: Range<usize>) -> &mut Self::Output {
        assert!(range.end < self.len());
        let char_array: &mut [AsciiChar] = self.string.as_mut();
        &mut char_array[range.start..range.end]
    }
}

impl Index<RangeFrom<u8>> for PascalStr {
    type Output = [AsciiChar];
    fn index(&self, range: RangeFrom<u8>) -> &Self::Output {
        assert!((range.start as usize) < self.len());
        let char_array: &[AsciiChar] = self.string.as_ref();
        &char_array[range.start as usize..]
    }
}

impl IndexMut<RangeFrom<u8>> for PascalStr {
    fn index_mut(&mut self, range: RangeFrom<u8>) -> &mut Self::Output {
        assert!((range.start as usize) < self.len());
        let char_array: &mut [AsciiChar] = self.string.as_mut();
        &mut char_array[range.start as usize..]
    }
}

impl Index<RangeFrom<usize>> for PascalStr {
    type Output = [AsciiChar];
    fn index(&self, range: RangeFrom<usize>) -> &Self::Output {
        assert!(range.start < self.len());
        let char_array: &[AsciiChar] = self.string.as_ref();
        &char_array[range.start..]
    }
}

impl IndexMut<RangeFrom<usize>> for PascalStr {
    fn index_mut(&mut self, range: RangeFrom<usize>) -> &mut Self::Output {
        assert!(range.start < self.len());
        let char_array: &mut [AsciiChar] = self.string.as_mut();
        &mut char_array[range.start..]
    }
}

impl Index<RangeTo<u8>> for PascalStr {
    type Output = [AsciiChar];
    fn index(&self, range: RangeTo<u8>) -> &Self::Output {
        assert!((range.end as usize) < self.len());
        let char_array: &[AsciiChar] = self.string.as_ref();
        &char_array[..range.end as usize]
    }
}

impl IndexMut<RangeTo<u8>> for PascalStr {
    fn index_mut(&mut self, range: RangeTo<u8>) -> &mut Self::Output {
        assert!((range.end as usize) < self.len());
        let char_array: &mut [AsciiChar] = self.string.as_mut();
        &mut char_array[..range.end as usize]
    }
}

impl Index<RangeTo<usize>> for PascalStr {
    type Output = [AsciiChar];
    fn index(&self, range: RangeTo<usize>) -> &Self::Output {
        assert!(range.end < self.len());
        let char_array: &[AsciiChar] = self.string.as_ref();
        &char_array[..range.end]
    }
}

impl IndexMut<RangeTo<usize>> for PascalStr {
    fn index_mut(&mut self, range: RangeTo<usize>) -> &mut Self::Output {
        assert!(range.end < self.len());
        let char_array: &mut [AsciiChar] = self.string.as_mut();
        &mut char_array[..range.end]
    }
}

/// An immutable iterator over the buffer of a `PascalStr`.
pub struct Chars<'a>(Iter<'a, AsciiChar>);

impl<'a> Iterator for Chars<'a> {
    type Item = &'a AsciiChar;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

impl<'a> ExactSizeIterator for Chars<'a> {
    fn len(&self) -> usize {
        self.0.len()
    }
}

/// A mutable iterator over the buffer of a `PascalStr`.
pub struct CharsMut<'a>(IterMut<'a, AsciiChar>);

impl<'a> Iterator for CharsMut<'a> {
    type Item = &'a mut AsciiChar;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

impl<'a> ExactSizeIterator for CharsMut<'a> {
    fn len(&self) -> usize {
        self.0.len()
    }
}
<commit_msg>Add PascalStr::as_str method<commit_after>use ascii::{AsciiChar, AsciiStr};
use std::ascii::AsciiExt;
use std::borrow::ToOwned;
use std::convert::AsRef;
use std::iter::{ExactSizeIterator, Iterator};
use std::ops::{Index, IndexMut, Range, RangeFull, RangeFrom, RangeTo};
use std::slice::{Iter, IterMut};
use ::{PASCAL_STRING_BUF_SIZE, PascalString};

/// A borrowed slice from a `PascalString`. Does not own its data.
#[derive(Eq, Hash, PartialEq, PartialOrd)]
pub struct PascalStr {
    /// The `AsciiStr`, borrowed from the original `PascalString`
    string: AsciiStr
}

impl PascalStr {
    /// Get a pointer to the first byte of the string buffer.
    #[inline]
    pub fn as_ptr(&self) -> *const AsciiChar {
        self.string.as_ptr()
    }

    /// Get a mutable pointer to the first byte of the string buffer.
    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut AsciiChar {
        self.string.as_mut_ptr()
    }

    /// Get the `PascalStr` as an immutable `&str` reference.
    #[inline]
    pub fn as_str(&self) -> &str {
        self.string.as_str()
    }

    /// Returns the number of characters used in the string.
    #[inline]
    pub fn len(&self) -> usize {
        self.string.len()
    }

    /// Returns true if the string has a length of 0
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns true if the string has a length of 255.
    ///
    /// When this value is true, no more elements can be pushed onto the string.
    #[inline]
    pub fn is_full(&self) -> bool {
        self.len() == PASCAL_STRING_BUF_SIZE
    }

    /// Get an immutable iterator to the internal character array.
    #[inline]
    pub fn chars<'a>(&'a self) -> Chars<'a> {
        Chars(self.string.as_slice().iter())
    }

    /// Get a mutable iterator to the internal character array.
    #[inline]
    pub fn chars_mut<'a>(&'a mut self) -> CharsMut<'a> {
        CharsMut(self.string.as_mut_slice().iter_mut())
    }
}

impl AsciiExt for PascalStr {
    type Owned = PascalString;

    fn is_ascii(&self) -> bool {
        true
    }

    fn to_ascii_uppercase(&self) -> Self::Owned {
        let bytes: &[u8] = self.as_ref();
        let mut upper = PascalString::from(bytes).unwrap();
        upper.make_ascii_uppercase();
        upper
    }

    fn to_ascii_lowercase(&self) -> Self::Owned {
        let bytes: &[u8] = self.as_ref();
        let mut lower = PascalString::from(bytes).unwrap();
        lower.make_ascii_lowercase();
        lower
    }

    fn eq_ignore_ascii_case(&self, other: &Self) -> bool {
        self.string.eq_ignore_ascii_case(&other.string)
    }

    fn make_ascii_uppercase(&mut self) {
        self.string.make_ascii_uppercase()
    }

    fn make_ascii_lowercase(&mut self) {
        self.string.make_ascii_lowercase()
    }
}

impl ToOwned for PascalStr {
    type Owned = PascalString;
    fn to_owned(&self) -> Self::Owned {
        PascalString::from(&self.string).unwrap()
    }
}

impl AsRef<str> for PascalStr {
    fn as_ref(&self) -> &str {
        self.string.as_ref()
    }
}

impl AsRef<[u8]> for PascalStr {
    fn as_ref(&self) -> &[u8] {
        self.string.as_ref()
    }
}

impl AsRef<AsciiStr> for PascalStr {
    fn as_ref(&self) -> &AsciiStr {
        &self.string
    }
}

impl AsMut<AsciiStr> for PascalStr {
    fn as_mut(&mut self) -> &mut AsciiStr {
        &mut self.string
    }
}

impl AsRef<[AsciiChar]> for PascalStr {
    fn as_ref(&self) -> &[AsciiChar] {
        self.string.as_ref()
    }
}

impl AsMut<[AsciiChar]> for PascalStr {
    fn as_mut(&mut self) -> &mut [AsciiChar] {
        self.string.as_mut()
    }
}

impl Index<u8> for PascalStr {
    type Output = AsciiChar;
    fn index(&self, index: u8) -> &Self::Output {
        let index = index as usize;
        assert!(index < self.len());
        &self.string[index]
    }
}

impl IndexMut<u8> for PascalStr {
    fn index_mut(&mut self, index: u8) -> &mut Self::Output {
        let index = index as usize;
        assert!(index < self.len());
        &mut self.string[index]
    }
}

impl Index<usize> for PascalStr {
    type Output = AsciiChar;
    fn index(&self, index: usize) -> &Self::Output {
        assert!(index < self.len());
        &self.string[index]
    }
}

impl IndexMut<usize> for PascalStr {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        assert!(index < self.len());
        &mut self.string[index]
    }
}

impl Index<RangeFull> for PascalStr {
    type Output = [AsciiChar];
    fn index(&self, _: RangeFull) -> &Self::Output {
        let char_array: &[AsciiChar] = self.string.as_ref();
        &char_array[..]
    }
}

impl IndexMut<RangeFull> for PascalStr {
    fn index_mut(&mut self, _: RangeFull) -> &mut Self::Output {
        let char_array: &mut [AsciiChar] = self.string.as_mut();
        &mut char_array[..]
    }
}

impl Index<Range<u8>> for PascalStr {
    type Output = [AsciiChar];
    fn index(&self, range: Range<u8>) -> &Self::Output {
        assert!((range.end as usize) < self.len());
        let char_array: &[AsciiChar] = self.string.as_ref();
        &char_array[range.start as usize..range.end as usize]
    }
}

impl IndexMut<Range<u8>> for PascalStr {
    fn index_mut(&mut self, range: Range<u8>) -> &mut Self::Output {
        assert!((range.end as usize) < self.len());
        let char_array: &mut [AsciiChar] = self.string.as_mut();
        &mut char_array[range.start as usize..range.end as usize]
    }
}

impl Index<Range<usize>> for PascalStr {
    type Output = [AsciiChar];
    fn index(&self, range: Range<usize>) -> &Self::Output {
        assert!(range.end < self.len());
        let char_array: &[AsciiChar] = self.string.as_ref();
        &char_array[range.start..range.end]
    }
}

impl IndexMut<Range<usize>> for PascalStr {
    fn index_mut(&mut self, range: Range<usize>) -> &mut Self::Output {
        assert!(range.end < self.len());
        let char_array: &mut [AsciiChar] = self.string.as_mut();
        &mut char_array[range.start..range.end]
    }
}

impl Index<RangeFrom<u8>> for PascalStr {
    type Output = [AsciiChar];
    fn index(&self, range: RangeFrom<u8>) -> &Self::Output {
        assert!((range.start as usize) < self.len());
        let char_array: &[AsciiChar] = self.string.as_ref();
        &char_array[range.start as usize..]
    }
}

impl IndexMut<RangeFrom<u8>> for PascalStr {
    fn index_mut(&mut self, range: RangeFrom<u8>) -> &mut Self::Output {
        assert!((range.start as usize) < self.len());
        let char_array: &mut [AsciiChar] = self.string.as_mut();
        &mut char_array[range.start as usize..]
    }
}

impl Index<RangeFrom<usize>> for PascalStr {
    type Output = [AsciiChar];
    fn index(&self, range: RangeFrom<usize>) -> &Self::Output {
        assert!(range.start < self.len());
        let char_array: &[AsciiChar] = self.string.as_ref();
        &char_array[range.start..]
    }
}

impl IndexMut<RangeFrom<usize>> for PascalStr {
    fn index_mut(&mut self, range: RangeFrom<usize>) -> &mut Self::Output {
        assert!(range.start < self.len());
        let char_array: &mut [AsciiChar] = self.string.as_mut();
        &mut char_array[range.start..]
    }
}

impl Index<RangeTo<u8>> for PascalStr {
    type Output = [AsciiChar];
    fn index(&self, range: RangeTo<u8>) -> &Self::Output {
        assert!((range.end as usize) < self.len());
        let char_array: &[AsciiChar] = self.string.as_ref();
        &char_array[..range.end as usize]
    }
}

impl IndexMut<RangeTo<u8>> for PascalStr {
    fn index_mut(&mut self, range: RangeTo<u8>) -> &mut Self::Output {
        assert!((range.end as usize) < self.len());
        let char_array: &mut [AsciiChar] = self.string.as_mut();
        &mut char_array[..range.end as usize]
    }
}

impl Index<RangeTo<usize>> for PascalStr {
    type Output = [AsciiChar];
    fn index(&self, range: RangeTo<usize>) -> &Self::Output {
        assert!(range.end < self.len());
        let char_array: &[AsciiChar] = self.string.as_ref();
        &char_array[..range.end]
    }
}

impl IndexMut<RangeTo<usize>> for PascalStr {
    fn index_mut(&mut self, range: RangeTo<usize>) -> &mut Self::Output {
        assert!(range.end < self.len());
        let char_array: &mut [AsciiChar] = self.string.as_mut();
        &mut char_array[..range.end]
    }
}

/// An immutable iterator over the buffer of a `PascalStr`.
pub struct Chars<'a>(Iter<'a, AsciiChar>);

impl<'a> Iterator for Chars<'a> {
    type Item = &'a AsciiChar;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

impl<'a> ExactSizeIterator for Chars<'a> {
    fn len(&self) -> usize {
        self.0.len()
    }
}

/// A mutable iterator over the buffer of a `PascalStr`.
pub struct CharsMut<'a>(IterMut<'a, AsciiChar>);

impl<'a> Iterator for CharsMut<'a> {
    type Item = &'a mut AsciiChar;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

impl<'a> ExactSizeIterator for CharsMut<'a> {
    fn len(&self) -> usize {
        self.0.len()
    }
}
<|endoftext|>


<commit_before>use std::path::PathBuf;
use std::path::Path;
use std::fs::OpenOptions;
use std::io::Write;

pub fn gen_schemata_modfile(modfile_path: &Path, proto_path: &PathBuf) {
    let mut f = OpenOptions::new()
        .create(true)
        .write(true)
        .append(true)
        .open(modfile_path)
        .unwrap();

    write!(f, "pub mod {};\n", proto_path.file_stem().unwrap().to_str().unwrap()).unwrap();
}

pub fn gen_protob_file(protob_path: &Path, msgdefs: &Vec<String>) {
    let mut f = OpenOptions::new()
        .create(true)
        .write(true)
        .append(true)
        .open(protob_path)
        .unwrap();

    write!(&mut f, "mod schemata;

use protobuf::Message;
use protobuf::CodedInputStream;
use protobuf::ProtobufResult;

{}

pub fn process_stream(stdin_stream: &mut Read) {{
    let mut stream = CodedInputStream::new(stdin_stream);
{}
}}
", format_msgdef_imports(msgdefs), format_mergefrom_calls(msgdefs)).unwrap();
}

fn format_msgdef_imports(msgdefs: &Vec<String>) -> String {
    let mut ret = Vec::new();

    for m in msgdefs {
        ret.push(format!("use schemata::{};", m));
    }
    ret.join("\n")
}

fn format_mergefrom_calls(msgdefs: &Vec<String>) -> String {
    let mut ret = Vec::new();

    ret.push("
    loop {
        match stream.eof() {
            Err(e) => panic!(e),
            Ok(true) => break,
            Ok(false) => {".to_string());

    for m in msgdefs {
        let split = m.split("::");
        let vec = split.collect::<Vec<&str>>();
        ret.push(format!("
            match stream.read_message::<{0}>() {{
                Err(e) => println!(\"{{}}\", e),
                Ok(x) => println!(\"{{:?}}\", x),
            }}", vec.last().unwrap()));
    }

    ret.push("
            }
        }
    }".to_string());

    ret.join("\n")
}
<commit_msg>Fix indentation of generated code<commit_after>use std::path::PathBuf;
use std::path::Path;
use std::fs::OpenOptions;
use std::io::Write;

pub fn gen_schemata_modfile(modfile_path: &Path, proto_path: &PathBuf) {
    let mut f = OpenOptions::new()
        .create(true)
        .write(true)
        .append(true)
        .open(modfile_path)
        .unwrap();

    write!(f, "pub mod {};\n", proto_path.file_stem().unwrap().to_str().unwrap()).unwrap();
}

pub fn gen_protob_file(protob_path: &Path, msgdefs: &Vec<String>) {
    let mut f = OpenOptions::new()
        .create(true)
        .write(true)
        .append(true)
        .open(protob_path)
        .unwrap();

    write!(&mut f, "mod schemata;

use protobuf::Message;
use protobuf::CodedInputStream;
use protobuf::ProtobufResult;

{}

pub fn process_stream(stdin_stream: &mut Read) {{
    let mut stream = CodedInputStream::new(stdin_stream);
{}
}}
", format_msgdef_imports(msgdefs), format_mergefrom_calls(msgdefs)).unwrap();
}

fn format_msgdef_imports(msgdefs: &Vec<String>) -> String {
    let mut ret = Vec::new();

    for m in msgdefs {
        ret.push(format!("use schemata::{};", m));
    }
    ret.join("\n")
}

fn format_mergefrom_calls(msgdefs: &Vec<String>) -> String {
    let mut ret = Vec::new();

    ret.push("
    loop {
        match stream.eof() {
            Err(e) => panic!(e),
            Ok(true) => break,
            Ok(false) => {".to_string());

    for m in msgdefs {
        let split = m.split("::");
        let vec = split.collect::<Vec<&str>>();
        ret.push(format!("\t\t\t\tmatch stream.read_message::<{0}>() {{
                    Err(e) => println!(\"{{}}\", e),
                    Ok(x) => println!(\"{{:?}}\", x),
                }}", vec.last().unwrap()));
    }

    ret.push("\t\t\t}
        }
    }".to_string());

    ret.join("\n")
}
<|endoftext|>


<commit_before>use num::Float;

use std::marker::PhantomData;

use {Color, Alpha, Rgb, Rgba, clamp, flt};

use pixel::RgbPixel;
use white_point::{WhitePoint, D65};

///An sRGB encoded color.
///
///sRGB is a common kind of gamma encoding, but it doesn't exactly follow the
///power-law, as in [`GammaRgb`](struct.GammaRgb.html). It's perhaps the most
///common color space for monitors and on the Internet, so it's usually safe
///to assume that an image or pixel with unknown gamma is sRGB encoded.
///
///```
///use palette::Rgb;
///use palette::pixel::Srgb;
///
///let c: Rgb = Srgb::new(0.5, 0.3, 0.1).into();
///assert_eq!((0.5f32, 0.3, 0.1), Srgb::from(c).to_pixel());
///```
#[derive(Debug, PartialEq)]
pub struct Srgb<Wp = D65, T = f32>
    where T: Float,
        Wp: WhitePoint<T>
{
    ///The red component, where 0.0 is no red light and 1.0 is the
    ///highest displayable amount.
    pub red: T,

    ///The green component, where 0.0 is no red light and 1.0 is the
    ///highest displayable amount.
    pub green: T,

    ///The blue component, where 0.0 is no red light and 1.0 is the
    ///highest displayable amount.
    pub blue: T,

    ///The transparency of the color. 0.0 is completely transparent and 1.0 is
    ///completely opaque.
    pub alpha: T,

    ///The white point associated with the color's illuminant and observer.
///D65 for 2 degree observer is used by default.
pub white_point: PhantomData<Wp>,
}

impl<Wp, T> Copy for Srgb<Wp, T>
    where T: Float,
        Wp: WhitePoint<T>
{}

impl<Wp, T> Clone for Srgb<Wp, T>
    where T: Float,
        Wp: WhitePoint<T>
{
    fn clone(&self) -> Srgb<Wp, T> { *self }
}

impl<T> Srgb<D65, T>
    where T: Float,
{
    ///Create a new opaque sRGB encoded color.
    pub fn new(red: T, green: T, blue: T) -> Srgb<D65, T> {
        Srgb::with_alpha(red, green, blue, T::one())
    }

    ///Create a new sRGB encoded color with transparency.
    pub fn with_alpha(red: T, green: T, blue: T, alpha: T) -> Srgb<D65, T> {
        Srgb {
            red: red,
            green: green,
            blue: blue,
            alpha: alpha,
            white_point: PhantomData,
        }
    }

    ///Create a new opaque sRGB encoded color from `u8` values.
    pub fn new_u8(red: u8, green: u8, blue: u8) -> Srgb<D65, T> {
        Srgb::with_alpha_u8(red, green, blue, 255)
    }

    ///Create a new sRGB encoded color, with transparency, from `u8` values.
    pub fn with_alpha_u8(red: u8, green: u8, blue: u8, alpha: u8) -> Srgb<D65, T> {
        Srgb {
            red: flt::<T,_>(red) / flt(255.0),
            green: flt::<T,_>(green) / flt(255.0),
            blue: flt::<T,_>(blue) / flt(255.0),
            alpha: flt::<T,_>(alpha) / flt(255.0),
            white_point: PhantomData,
        }
    }
}

impl<Wp, T> Srgb<Wp, T>
    where T: Float,
        Wp: WhitePoint<T>
{
    ///Create a new opaque sRGB encoded color.
    pub fn with_wp(red: T, green: T, blue: T) -> Srgb<Wp, T> {
        Srgb::with_wp_alpha(red, green, blue, T::one())
    }

    ///Create a new sRGB encoded color with transparency.
    pub fn with_wp_alpha(red: T, green: T, blue: T, alpha: T) -> Srgb<Wp, T> {
        Srgb {
            red: red,
            green: green,
            blue: blue,
            alpha: alpha,
            white_point: PhantomData,
        }
    }

    ///Create a new opaque sRGB encoded color from `u8` values.
    pub fn with_wp_u8(red: u8, green: u8, blue: u8) -> Srgb<Wp, T> {
        Srgb::with_wp_alpha_u8(red, green, blue, 255)
    }

    ///Create a new sRGB encoded color, with transparency, from `u8` values.
    pub fn with_wp_alpha_u8(red: u8, green: u8, blue: u8, alpha: u8) -> Srgb<Wp, T> {
        Srgb {
            red: flt::<T,_>(red) / flt(255.0),
            green: flt::<T,_>(green) / flt(255.0),
            blue: flt::<T,_>(blue) / flt(255.0),
            alpha: flt::<T,_>(alpha) / flt(255.0),
            white_point: PhantomData,
        }
    }

    ///Create a new sRGB encoded color from a pixel value.
    pub fn from_pixel<P: RgbPixel<T>>(pixel: &P) -> Srgb<Wp, T> {
        let (r, g, b, a) = pixel.to_rgba();
        Srgb::with_wp_alpha(r, g, b, a)
    }

    ///Transform this color into a pixel representation.
    pub fn to_pixel<P: RgbPixel<T>>(&self) -> P {
        P::from_rgba(
            clamp(self.red, T::zero(), T::one()),
            clamp(self.green, T::zero(), T::one()),
            clamp(self.blue, T::zero(), T::one()),
            clamp(self.alpha, T::zero(), T::one()),
        )
    }

    ///Convert linear color components to sRGB encoding.
    pub fn from_linear<C: Into<Rgba<Wp, T>>>(color: C) -> Srgb<Wp, T> {
        let rgb = color.into();
        Srgb {
            red: to_srgb(rgb.red),
            green: to_srgb(rgb.green),
            blue: to_srgb(rgb.blue),
            alpha: rgb.alpha,
            white_point: PhantomData,
        }
    }

    ///Decode this color to a linear representation.
    pub fn to_linear(&self) -> Rgba<Wp, T> {
        Alpha {
            color: Rgb::with_wp(
                from_srgb(self.red),
                from_srgb(self.green),
                from_srgb(self.blue),
            ),
            alpha: self.alpha,
        }
    }

    ///Shortcut to convert a linear color to an sRGB encoded pixel.
    pub fn linear_to_pixel<C: Into<Rgba<Wp, T>>, P: RgbPixel<T>>(color: C) -> P {
        Srgb::from_linear(color).to_pixel()
    }
}

impl<Wp, T> From<Rgb<Wp, T>> for Srgb<Wp, T>
    where T: Float,
        Wp: WhitePoint<T>
{
    fn from(rgb: Rgb<Wp, T>) -> Srgb<Wp, T> {
        Rgba::from(rgb).into()
    }
}

impl<Wp, T> From<Rgba<Wp, T>> for Srgb<Wp, T>
    where T: Float,
        Wp: WhitePoint<T>
{
    fn from(rgba: Rgba<Wp, T>) -> Srgb<Wp, T> {
        Srgb::from_linear(rgba)
    }
}

impl<Wp, T> From<Color<Wp, T>> for Srgb<Wp, T>
    where T: Float,
        Wp: WhitePoint<T>
{
    fn from(color: Color<Wp, T>) -> Srgb<Wp, T> {
        Rgb::from(color).into()
    }
}

fn from_srgb<T: Float>(x: T) -> T {
    if x <= flt(0.04045) {
        x / flt(12.92)
    } else {
        ((x + flt(0.055)) / flt(1.055)).powf(flt(2.4))
    }
}

fn to_srgb<T: Float>(x: T) -> T {
    if x <= flt(0.0031308) {
        x * flt(12.92)
    } else {
        x.powf(T::one() / flt(2.4)) * flt(1.055)  - flt(0.055)
    }
}
<commit_msg>Fix failing Srgb doc test<commit_after>use num::Float;

use std::marker::PhantomData;

use {Color, Alpha, Rgb, Rgba, clamp, flt};

use pixel::RgbPixel;
use white_point::{WhitePoint, D65};

///An sRGB encoded color.
///
///sRGB is a common kind of gamma encoding, but it doesn't exactly follow the
///power-law, as in [`GammaRgb`](struct.GammaRgb.html). It's perhaps the most
///common color space for monitors and on the Internet, so it's usually safe
///to assume that an image or pixel with unknown gamma is sRGB encoded.
///
///```
/// #[macro_use] extern crate approx;
/// # extern crate palette;
/// # use palette::Rgb;
/// # use palette::pixel::Srgb;
///
/// # fn main() {
/// let c: Rgb = Srgb::new(0.5, 0.3, 0.1).into();
/// let (r, g, b) = Srgb::from(c).to_pixel();
/// assert_relative_eq!(0.5f32, r);
/// assert_relative_eq!(0.3f32, g);
/// assert_relative_eq!(0.1f32, b);
/// # }
///```
#[derive(Debug, PartialEq)]
pub struct Srgb<Wp = D65, T = f32>
    where T: Float,
        Wp: WhitePoint<T>
{
    ///The red component, where 0.0 is no red light and 1.0 is the
    ///highest displayable amount.
    pub red: T,

    ///The green component, where 0.0 is no red light and 1.0 is the
    ///highest displayable amount.
    pub green: T,

    ///The blue component, where 0.0 is no red light and 1.0 is the
    ///highest displayable amount.
    pub blue: T,

    ///The transparency of the color. 0.0 is completely transparent and 1.0 is
    ///completely opaque.
    pub alpha: T,

    ///The white point associated with the color's illuminant and observer.
///D65 for 2 degree observer is used by default.
pub white_point: PhantomData<Wp>,
}

impl<Wp, T> Copy for Srgb<Wp, T>
    where T: Float,
        Wp: WhitePoint<T>
{}

impl<Wp, T> Clone for Srgb<Wp, T>
    where T: Float,
        Wp: WhitePoint<T>
{
    fn clone(&self) -> Srgb<Wp, T> { *self }
}

impl<T> Srgb<D65, T>
    where T: Float,
{
    ///Create a new opaque sRGB encoded color.
    pub fn new(red: T, green: T, blue: T) -> Srgb<D65, T> {
        Srgb::with_alpha(red, green, blue, T::one())
    }

    ///Create a new sRGB encoded color with transparency.
    pub fn with_alpha(red: T, green: T, blue: T, alpha: T) -> Srgb<D65, T> {
        Srgb {
            red: red,
            green: green,
            blue: blue,
            alpha: alpha,
            white_point: PhantomData,
        }
    }

    ///Create a new opaque sRGB encoded color from `u8` values.
    pub fn new_u8(red: u8, green: u8, blue: u8) -> Srgb<D65, T> {
        Srgb::with_alpha_u8(red, green, blue, 255)
    }

    ///Create a new sRGB encoded color, with transparency, from `u8` values.
    pub fn with_alpha_u8(red: u8, green: u8, blue: u8, alpha: u8) -> Srgb<D65, T> {
        Srgb {
            red: flt::<T,_>(red) / flt(255.0),
            green: flt::<T,_>(green) / flt(255.0),
            blue: flt::<T,_>(blue) / flt(255.0),
            alpha: flt::<T,_>(alpha) / flt(255.0),
            white_point: PhantomData,
        }
    }
}

impl<Wp, T> Srgb<Wp, T>
    where T: Float,
        Wp: WhitePoint<T>
{
    ///Create a new opaque sRGB encoded color.
    pub fn with_wp(red: T, green: T, blue: T) -> Srgb<Wp, T> {
        Srgb::with_wp_alpha(red, green, blue, T::one())
    }

    ///Create a new sRGB encoded color with transparency.
    pub fn with_wp_alpha(red: T, green: T, blue: T, alpha: T) -> Srgb<Wp, T> {
        Srgb {
            red: red,
            green: green,
            blue: blue,
            alpha: alpha,
            white_point: PhantomData,
        }
    }

    ///Create a new opaque sRGB encoded color from `u8` values.
    pub fn with_wp_u8(red: u8, green: u8, blue: u8) -> Srgb<Wp, T> {
        Srgb::with_wp_alpha_u8(red, green, blue, 255)
    }

    ///Create a new sRGB encoded color, with transparency, from `u8` values.
    pub fn with_wp_alpha_u8(red: u8, green: u8, blue: u8, alpha: u8) -> Srgb<Wp, T> {
        Srgb {
            red: flt::<T,_>(red) / flt(255.0),
            green: flt::<T,_>(green) / flt(255.0),
            blue: flt::<T,_>(blue) / flt(255.0),
            alpha: flt::<T,_>(alpha) / flt(255.0),
            white_point: PhantomData,
        }
    }

    ///Create a new sRGB encoded color from a pixel value.
    pub fn from_pixel<P: RgbPixel<T>>(pixel: &P) -> Srgb<Wp, T> {
        let (r, g, b, a) = pixel.to_rgba();
        Srgb::with_wp_alpha(r, g, b, a)
    }

    ///Transform this color into a pixel representation.
    pub fn to_pixel<P: RgbPixel<T>>(&self) -> P {
        P::from_rgba(
            clamp(self.red, T::zero(), T::one()),
            clamp(self.green, T::zero(), T::one()),
            clamp(self.blue, T::zero(), T::one()),
            clamp(self.alpha, T::zero(), T::one()),
        )
    }

    ///Convert linear color components to sRGB encoding.
    pub fn from_linear<C: Into<Rgba<Wp, T>>>(color: C) -> Srgb<Wp, T> {
        let rgb = color.into();
        Srgb {
            red: to_srgb(rgb.red),
            green: to_srgb(rgb.green),
            blue: to_srgb(rgb.blue),
            alpha: rgb.alpha,
            white_point: PhantomData,
        }
    }

    ///Decode this color to a linear representation.
    pub fn to_linear(&self) -> Rgba<Wp, T> {
        Alpha {
            color: Rgb::with_wp(
                from_srgb(self.red),
                from_srgb(self.green),
                from_srgb(self.blue),
            ),
            alpha: self.alpha,
        }
    }

    ///Shortcut to convert a linear color to an sRGB encoded pixel.
    pub fn linear_to_pixel<C: Into<Rgba<Wp, T>>, P: RgbPixel<T>>(color: C) -> P {
        Srgb::from_linear(color).to_pixel()
    }
}

impl<Wp, T> From<Rgb<Wp, T>> for Srgb<Wp, T>
    where T: Float,
        Wp: WhitePoint<T>
{
    fn from(rgb: Rgb<Wp, T>) -> Srgb<Wp, T> {
        Rgba::from(rgb).into()
    }
}

impl<Wp, T> From<Rgba<Wp, T>> for Srgb<Wp, T>
    where T: Float,
        Wp: WhitePoint<T>
{
    fn from(rgba: Rgba<Wp, T>) -> Srgb<Wp, T> {
        Srgb::from_linear(rgba)
    }
}

impl<Wp, T> From<Color<Wp, T>> for Srgb<Wp, T>
    where T: Float,
        Wp: WhitePoint<T>
{
    fn from(color: Color<Wp, T>) -> Srgb<Wp, T> {
        Rgb::from(color).into()
    }
}

fn from_srgb<T: Float>(x: T) -> T {
    if x <= flt(0.04045) {
        x / flt(12.92)
    } else {
        ((x + flt(0.055)) / flt(1.055)).powf(flt(2.4))
    }
}

fn to_srgb<T: Float>(x: T) -> T {
    if x <= flt(0.0031308) {
        x * flt(12.92)
    } else {
        x.powf(T::one() / flt(2.4)) * flt(1.055)  - flt(0.055)
    }
}
<|endoftext|>


<commit_before>use std::iter::AdditiveIterator;

struct FibonacciIterator {
    last: uint,
    penultimate: uint,
    max: uint,
}

impl FibonacciIterator {
    fn new(max: uint) -> FibonacciIterator {
        FibonacciIterator {
            last: 1u,
            penultimate: 0u,
            max: max,
        }
    }
}

impl Iterator<uint> for FibonacciIterator {
    fn next(&mut self) -> Option<uint> {
        let fib = self.last + self.penultimate;
        self.penultimate = self.last;
        self.last = fib;
        if fib <= self.max {
            Some(fib)
        } else {
            None
        }
    }
}
/// Returns the sum of the fibonacci numbers less than `target`
fn sum_fibonacci(target: uint) -> uint{
    let mut iter = FibonacciIterator::new(target);
    iter.sum()
}

#[cfg(test)]
mod test {
    use super::{FibonacciIterator,sum_fibonacci};

    #[test]
    fn test_iterator() {
        let mut result = Vec::new();
        let mut iter = FibonacciIterator::new(10);
        for i in iter {
            result.push(i);
        }
        assert_eq!(result, vec![1, 2, 3, 5, 8]);
    }

    #[test]
    fn provided_example() {
        assert_eq!(sum_fibonacci(89), 231u);
    }

    #[test]
    fn expected_result() {
        assert_eq!(sum_fibonacci(4_000_000), 9227463u);
    }
}
<commit_msg>Correct problem 2 (It's even only)<commit_after>use std::iter::AdditiveIterator;

struct FibonacciIterator {
    last: uint,
    penultimate: uint,
    max: uint,
}

impl FibonacciIterator {
    fn new(max: uint) -> FibonacciIterator {
        FibonacciIterator {
            last: 1u,
            penultimate: 0u,
            max: max,
        }
    }
}

impl Iterator<uint> for FibonacciIterator {
    fn next(&mut self) -> Option<uint> {
        let fib = self.last + self.penultimate;
        self.penultimate = self.last;
        self.last = fib;
        if fib <= self.max {
            Some(fib)
        } else {
            None
        }
    }
}
/// Returns the sum of the fibonacci numbers less than `target`
fn sum_fibonacci(target: uint) -> uint{
    let mut iter = FibonacciIterator::new(target).filter(|a| { *a % 2 == 0 });
    iter.sum()
}

#[cfg(test)]
mod test {
    use super::{FibonacciIterator,sum_fibonacci};

    #[test]
    fn test_iterator() {
        let mut result = Vec::new();
        let mut iter = FibonacciIterator::new(10);
        for i in iter {
            result.push(i);
        }
        assert_eq!(result, vec![1, 2, 3, 5, 8]);
    }

    #[test]
    fn provided_example() {
        assert_eq!(sum_fibonacci(89), 44u);
    }

    #[test]
    fn expected_result() {
        assert_eq!(sum_fibonacci(4_000_000), 4613732u);
    }
}
<|endoftext|>