<commit_before>#![crate_name="console"]
#![crate_type="lib"]
#![feature(alloc)]
#![feature(collections)]
#![no_std]

extern crate alloc;

#[macro_use]
extern crate collections;

use alloc::boxed::Box;

use collections::String;
use collections::Vec;

use core::cmp;

pub use block::Block;
pub use color::Color;
pub use style::Style;

pub mod block;
pub mod color;
pub mod style;

pub struct Console {
    pub display: Box<[Block]>,
    pub x: usize,
    pub y: usize,
    pub w: usize,
    pub h: usize,
    pub foreground: Color,
    pub background: Color,
    pub style: Style,
    pub cursor: bool,
    pub redraw: bool,
    pub escape: bool,
    pub escape_sequence: bool,
    pub escape_extra: bool,
    pub sequence: Vec<String>,
    pub raw_mode: bool,
}

impl Console {
    pub fn new(w: usize, h: usize) -> Console {
        Console {
            display: vec![Block::new(); w * h].into_boxed_slice(),
            x: 0,
            y: 0,
            w: w,
            h: h,
            foreground: Color::ansi(7),
            background: Color::ansi(0),
            style: Style::Normal,
            cursor: true,
            redraw: true,
            escape: false,
            escape_sequence: false,
            escape_extra: false,
            sequence: Vec::new(),
            raw_mode: false,
        }
    }

    fn block(&self, c: char) -> Block {
        Block {
            c: c,
            fg: self.foreground,
            bg: self.background,
            style: self.style
        }
    }

    pub fn code(&mut self, c: char) {
        if self.escape_sequence {
            match c {
                '0' ... '9' => {
                    // Add a number to the sequence list
                    if let Some(mut value) = self.sequence.last_mut() {
                        value.push(c);
                    }
                },
                ';' => {
                    // Split sequence into list
                    self.sequence.push(String::new());
                },
                'm' => {
                    // Display attributes
                    let mut value_iter = self.sequence.iter();
                    while let Some(value_str) = value_iter.next() {
                        let value = value_str.parse::<u8>().unwrap_or(0);
                        match value {
                            0 => {
                                self.foreground = Color::ansi(7);
                                self.background = Color::ansi(0);
                                self.style = Style::Normal;
                            },
                            1 => {
                                self.style = Style::Bold;
                            },
                            30 ... 37 => self.foreground = Color::ansi(value - 30),
                            38 => match value_iter.next().map_or("", |s| &s).parse::<usize>().unwrap_or(0) {
                                2 => {
                                    //True color
                                    let r = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    let g = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    let b = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    self.foreground = Color::new(r, g, b);
                                },
                                5 => {
                                    //256 color
                                    let color_value = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    self.foreground = Color::ansi(color_value);
                                },
                                _ => {}
                            },
                            40 ... 47 => self.background = Color::ansi(value - 40),
                            48 => match value_iter.next().map_or("", |s| &s).parse::<usize>().unwrap_or(0) {
                                2 => {
                                    //True color
                                    let r = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    let g = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    let b = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    self.background = Color::new(r, g, b);
                                },
                                5 => {
                                    //256 color
                                    let color_value = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    self.background = Color::ansi(color_value);
                                },
                                _ => {}
                            },
                            _ => {},
                        }
                    }

                    self.escape_sequence = false;
                },
                'H' | 'f' => {
                    let row = self.sequence.get(0).map_or("", |p| &p).parse::<isize>().unwrap_or(1);
                    self.y = cmp::max(0, row - 1) as usize;

                    let col = self.sequence.get(1).map_or("", |p| &p).parse::<isize>().unwrap_or(1);
                    self.x = cmp::max(0, col - 1) as usize;

                    self.escape_sequence = false;
                },
                'J' => {
                    match self.sequence.get(0).map_or("", |p| &p).parse::<usize>().unwrap_or(0) {
                        0 => {
                            let block = self.block(' ');
                            for c in self.display[self.y * self.w + self.x ..].iter_mut() {
                                *c = block;
                            }
                            if ! self.raw_mode {
                                self.redraw = true;
                            }
                        },
                        1 => {
                            let block = self.block(' ');
                            /* Should this add one? */
                            for c in self.display[.. self.y * self.w + self.x + 1].iter_mut() {
                                *c = block;
                            }
                            if ! self.raw_mode {
                                self.redraw = true;
                            }
                        },
                        2 => {
                            // Erase all
                            self.x = 0;
                            self.y = 0;
                            let block = self.block(' ');
                            for c in self.display.iter_mut() {
                                *c = block;
                            }
                            if ! self.raw_mode {
                                self.redraw = true;
                            }
                        },
                        _ => {}
                    }

                    self.escape_sequence = false;
                },
                'K' => {
                    match self.sequence.get(0).map_or("", |p| &p).parse::<usize>().unwrap_or(0) {
                        0 => {
                            let block = self.block(' ');
                            for c in self.display[self.y * self.w + self.x .. self.y * self.w + self.w].iter_mut() {
                                *c = block;
                            }
                            if ! self.raw_mode {
                                self.redraw = true;
                            }
                        },
                        1 => {
                            let block = self.block(' ');
                            /* Should this add one? */
                            for c in self.display[self.y * self.w .. self.y * self.w + self.x + 1].iter_mut() {
                                *c = block;
                            }
                            if ! self.raw_mode {
                                self.redraw = true;
                            }
                        },
                        2 => {
                            // Erase all
                            self.x = 0;
                            self.y = 0;
                            let block = self.block(' ');
                            for c in self.display.iter_mut() {
                                *c = block;
                            }
                            if ! self.raw_mode {
                                self.redraw = true;
                            }
                        },
                        _ => {}
                    }

                    self.escape_sequence = false;
                },
                /*
                @MANSTART{terminal-raw-mode}
                INTRODUCTION
                    Since Redox has no ioctl syscall, it uses escape codes for switching to raw mode.

                ENTERING AND EXITING RAW MODE
                    Entering raw mode is done using CSI-r (^[r). Unsetting raw mode is done by CSI-R (^[R).

                RAW MODE
                    Raw mode means that the stdin must be handled solely by the program itself. It will not automatically be printed nor will it be modified in any way (modulo escape codes).

                    This means that:
                        - stdin is not printed.
                        - newlines are interpreted as carriage returns in stdin.
                        - stdin is not buffered, meaning that the stream of bytes goes directly to the program, without the user having to press enter.
                @MANEND
                */
                'r' => {
                    self.raw_mode = true;
                    self.escape_sequence = false;
                },
                'R' => {
                    self.raw_mode = false;
                    self.escape_sequence = false;
                },
                '?' => self.escape_extra = true,
                'h' if self.escape_extra => {
                    match self.sequence.get(0).map_or("", |p| &p).parse::<usize>().unwrap_or(0) {
                        25 => self.cursor = true,
                        _ => ()
                    }

                    self.escape_sequence = false;
                },
                'l' if self.escape_extra => {
                    match self.sequence.get(0).map_or("", |p| &p).parse::<usize>().unwrap_or(0) {
                        25 => self.cursor = false,
                        _ => ()
                    }

                    self.escape_sequence = false;
                },
                _ => self.escape_sequence = false,
            }

            if !self.escape_sequence {
                self.sequence.clear();
                self.escape = false;
                self.escape_extra = false;
            }
        } else {
            match c {
                '[' => {
                    // Control sequence initiator

                    self.escape_sequence = true;
                    self.sequence.push(String::new());
                },
                'c' => {
                    // Reset
                    self.x = 0;
                    self.y = 0;
                    self.raw_mode = false;
                    self.foreground = Color::ansi(7);
                    self.background = Color::ansi(0);
                    self.style = Style::Normal;
                    let block = self.block(' ');
                    for c in self.display.iter_mut() {
                        *c = block;
                    }
                    self.redraw = true;

                    self.escape = false;
                }
                _ => self.escape = false,
            }
        }
    }

    pub fn character(&mut self, c: char) {
        match c {
            '\0' => {},
            '\x1B' => self.escape = true,
            '\n' => {
                self.x = 0;
                self.y += 1;
                if ! self.raw_mode {
                    self.redraw = true;
                }
            },
            '\t' => self.x = ((self.x / 8) + 1) * 8,
            '\r' => self.x = 0,
            '\x08' => {
                if self.x >= 1 {
                    self.x -= 1;

                    if ! self.raw_mode {
                        self.display[self.y * self.w + self.x] = self.block(' ');
                    }
                }
            },
            ' ' => {
                self.display[self.y * self.w + self.x] = self.block(' ');

                self.x += 1;
            },
            _ => {
                self.display[self.y * self.w + self.x] = self.block(c);

                self.x += 1;
            }
        }

        if self.x >= self.w {
            self.x = 0;
            self.y += 1;
        }

        while self.y + 1 > self.h {
            for y in 1..self.h {
                for x in 0..self.w {
                    let c = self.display[y * self.w + x];
                    self.display[(y - 1) * self.w + x] = c;
                }
            }
            let block = self.block(' ');
            for x in 0..self.w {
                self.display[(self.h - 1) * self.w + x] = block;
            }
            self.y -= 1;
        }
    }

    pub fn write(&mut self, bytes: &[u8]) {
        for byte in bytes.iter() {
            let c = *byte as char;

            if self.escape {
                self.code(c);
            } else {
                self.character(c);
            }
        }
    }
}
<commit_msg>Cursor movement<commit_after>#![crate_name="console"]
#![crate_type="lib"]
#![feature(alloc)]
#![feature(collections)]
#![no_std]

extern crate alloc;

#[macro_use]
extern crate collections;

use alloc::boxed::Box;

use collections::String;
use collections::Vec;

use core::cmp;

pub use block::Block;
pub use color::Color;
pub use style::Style;

pub mod block;
pub mod color;
pub mod style;

pub struct Console {
    pub display: Box<[Block]>,
    pub x: usize,
    pub y: usize,
    pub w: usize,
    pub h: usize,
    pub foreground: Color,
    pub background: Color,
    pub style: Style,
    pub cursor: bool,
    pub redraw: bool,
    pub escape: bool,
    pub escape_sequence: bool,
    pub escape_extra: bool,
    pub sequence: Vec<String>,
    pub raw_mode: bool,
}

impl Console {
    pub fn new(w: usize, h: usize) -> Console {
        Console {
            display: vec![Block::new(); w * h].into_boxed_slice(),
            x: 0,
            y: 0,
            w: w,
            h: h,
            foreground: Color::ansi(7),
            background: Color::ansi(0),
            style: Style::Normal,
            cursor: true,
            redraw: true,
            escape: false,
            escape_sequence: false,
            escape_extra: false,
            sequence: Vec::new(),
            raw_mode: false,
        }
    }

    fn block(&self, c: char) -> Block {
        Block {
            c: c,
            fg: self.foreground,
            bg: self.background,
            style: self.style
        }
    }

    pub fn code(&mut self, c: char) {
        if self.escape_sequence {
            match c {
                '0' ... '9' => {
                    // Add a number to the sequence list
                    if let Some(mut value) = self.sequence.last_mut() {
                        value.push(c);
                    }
                },
                ';' => {
                    // Split sequence into list
                    self.sequence.push(String::new());
                },
                'm' => {
                    // Display attributes
                    let mut value_iter = self.sequence.iter();
                    while let Some(value_str) = value_iter.next() {
                        let value = value_str.parse::<u8>().unwrap_or(0);
                        match value {
                            0 => {
                                self.foreground = Color::ansi(7);
                                self.background = Color::ansi(0);
                                self.style = Style::Normal;
                            },
                            1 => {
                                self.style = Style::Bold;
                            },
                            30 ... 37 => self.foreground = Color::ansi(value - 30),
                            38 => match value_iter.next().map_or("", |s| &s).parse::<usize>().unwrap_or(0) {
                                2 => {
                                    //True color
                                    let r = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    let g = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    let b = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    self.foreground = Color::new(r, g, b);
                                },
                                5 => {
                                    //256 color
                                    let color_value = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    self.foreground = Color::ansi(color_value);
                                },
                                _ => {}
                            },
                            40 ... 47 => self.background = Color::ansi(value - 40),
                            48 => match value_iter.next().map_or("", |s| &s).parse::<usize>().unwrap_or(0) {
                                2 => {
                                    //True color
                                    let r = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    let g = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    let b = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    self.background = Color::new(r, g, b);
                                },
                                5 => {
                                    //256 color
                                    let color_value = value_iter.next().map_or("", |s| &s).parse::<u8>().unwrap_or(0);
                                    self.background = Color::ansi(color_value);
                                },
                                _ => {}
                            },
                            _ => {},
                        }
                    }

                    self.escape_sequence = false;
                },
                'A' => {
                    self.y -= cmp::min(self.y, self.sequence.get(0).map_or("", |p| &p).parse::<usize>().unwrap_or(1));
                    self.escape_sequence = false;
                },
                'B' => {
                    self.y += cmp::min(self.h - 1 - self.y, self.sequence.get(0).map_or("", |p| &p).parse::<usize>().unwrap_or(1));
                    self.escape_sequence = false;
                },
                'C' => {
                    self.x += cmp::min(self.w - 1 - self.x, self.sequence.get(0).map_or("", |p| &p).parse::<usize>().unwrap_or(1));
                    self.escape_sequence = false;
                },
                'D' => {
                    self.x -= cmp::min(self.x, self.sequence.get(0).map_or("", |p| &p).parse::<usize>().unwrap_or(1));
                    self.escape_sequence = false;
                },
                'H' | 'f' => {
                    let row = self.sequence.get(0).map_or("", |p| &p).parse::<isize>().unwrap_or(1);
                    self.y = cmp::max(0, row - 1) as usize;

                    let col = self.sequence.get(1).map_or("", |p| &p).parse::<isize>().unwrap_or(1);
                    self.x = cmp::max(0, col - 1) as usize;

                    self.escape_sequence = false;
                },
                'J' => {
                    match self.sequence.get(0).map_or("", |p| &p).parse::<usize>().unwrap_or(0) {
                        0 => {
                            let block = self.block(' ');
                            for c in self.display[self.y * self.w + self.x ..].iter_mut() {
                                *c = block;
                            }
                            if ! self.raw_mode {
                                self.redraw = true;
                            }
                        },
                        1 => {
                            let block = self.block(' ');
                            /* Should this add one? */
                            for c in self.display[.. self.y * self.w + self.x + 1].iter_mut() {
                                *c = block;
                            }
                            if ! self.raw_mode {
                                self.redraw = true;
                            }
                        },
                        2 => {
                            // Erase all
                            self.x = 0;
                            self.y = 0;
                            let block = self.block(' ');
                            for c in self.display.iter_mut() {
                                *c = block;
                            }
                            if ! self.raw_mode {
                                self.redraw = true;
                            }
                        },
                        _ => {}
                    }

                    self.escape_sequence = false;
                },
                'K' => {
                    match self.sequence.get(0).map_or("", |p| &p).parse::<usize>().unwrap_or(0) {
                        0 => {
                            let block = self.block(' ');
                            for c in self.display[self.y * self.w + self.x .. self.y * self.w + self.w].iter_mut() {
                                *c = block;
                            }
                            if ! self.raw_mode {
                                self.redraw = true;
                            }
                        },
                        1 => {
                            let block = self.block(' ');
                            /* Should this add one? */
                            for c in self.display[self.y * self.w .. self.y * self.w + self.x + 1].iter_mut() {
                                *c = block;
                            }
                            if ! self.raw_mode {
                                self.redraw = true;
                            }
                        },
                        2 => {
                            // Erase all
                            self.x = 0;
                            self.y = 0;
                            let block = self.block(' ');
                            for c in self.display.iter_mut() {
                                *c = block;
                            }
                            if ! self.raw_mode {
                                self.redraw = true;
                            }
                        },
                        _ => {}
                    }

                    self.escape_sequence = false;
                },
                /*
                @MANSTART{terminal-raw-mode}
                INTRODUCTION
                    Since Redox has no ioctl syscall, it uses escape codes for switching to raw mode.

                ENTERING AND EXITING RAW MODE
                    Entering raw mode is done using CSI-r (^[r). Unsetting raw mode is done by CSI-R (^[R).

                RAW MODE
                    Raw mode means that the stdin must be handled solely by the program itself. It will not automatically be printed nor will it be modified in any way (modulo escape codes).

                    This means that:
                        - stdin is not printed.
                        - newlines are interpreted as carriage returns in stdin.
                        - stdin is not buffered, meaning that the stream of bytes goes directly to the program, without the user having to press enter.
                @MANEND
                */
                'r' => {
                    self.raw_mode = true;
                    self.escape_sequence = false;
                },
                'R' => {
                    self.raw_mode = false;
                    self.escape_sequence = false;
                },
                '?' => self.escape_extra = true,
                'h' if self.escape_extra => {
                    match self.sequence.get(0).map_or("", |p| &p).parse::<usize>().unwrap_or(0) {
                        25 => self.cursor = true,
                        _ => ()
                    }

                    self.escape_sequence = false;
                },
                'l' if self.escape_extra => {
                    match self.sequence.get(0).map_or("", |p| &p).parse::<usize>().unwrap_or(0) {
                        25 => self.cursor = false,
                        _ => ()
                    }

                    self.escape_sequence = false;
                },
                _ => self.escape_sequence = false,
            }

            if !self.escape_sequence {
                self.sequence.clear();
                self.escape = false;
                self.escape_extra = false;
            }
        } else {
            match c {
                '[' => {
                    // Control sequence initiator

                    self.escape_sequence = true;
                    self.sequence.push(String::new());
                },
                'c' => {
                    // Reset
                    self.x = 0;
                    self.y = 0;
                    self.raw_mode = false;
                    self.foreground = Color::ansi(7);
                    self.background = Color::ansi(0);
                    self.style = Style::Normal;
                    let block = self.block(' ');
                    for c in self.display.iter_mut() {
                        *c = block;
                    }
                    self.redraw = true;

                    self.escape = false;
                }
                _ => self.escape = false,
            }
        }
    }

    pub fn character(&mut self, c: char) {
        match c {
            '\0' => {},
            '\x1B' => self.escape = true,
            '\n' => {
                self.x = 0;
                self.y += 1;
                if ! self.raw_mode {
                    self.redraw = true;
                }
            },
            '\t' => self.x = ((self.x / 8) + 1) * 8,
            '\r' => self.x = 0,
            '\x08' => {
                if self.x >= 1 {
                    self.x -= 1;

                    if ! self.raw_mode {
                        self.display[self.y * self.w + self.x] = self.block(' ');
                    }
                }
            },
            ' ' => {
                self.display[self.y * self.w + self.x] = self.block(' ');

                self.x += 1;
            },
            _ => {
                self.display[self.y * self.w + self.x] = self.block(c);

                self.x += 1;
            }
        }

        if self.x >= self.w {
            self.x = 0;
            self.y += 1;
        }

        while self.y + 1 > self.h {
            for y in 1..self.h {
                for x in 0..self.w {
                    let c = self.display[y * self.w + x];
                    self.display[(y - 1) * self.w + x] = c;
                }
            }
            let block = self.block(' ');
            for x in 0..self.w {
                self.display[(self.h - 1) * self.w + x] = block;
            }
            self.y -= 1;
        }
    }

    pub fn write(&mut self, bytes: &[u8]) {
        for byte in bytes.iter() {
            let c = *byte as char;

            if self.escape {
                self.code(c);
            } else {
                self.character(c);
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>updated build.rs to use 'git describe --all'<commit_after><|endoftext|>


<commit_before><commit_msg>Add build script to set up limb width cfg<commit_after>fn main() {
    // Decide ideal limb width for arithmetic in the float parser. Refer to
    // src/lexical/math.rs for where this has an effect.
    let limb_width_64 = cfg!(any(
        target_arch = "aarch64",
        target_arch = "mips64",
        target_arch = "powerpc64",
        target_arch = "x86_64"
    ));
    if limb_width_64 {
        println!("cargo:rustc-cfg=limb_width_64");
    } else {
        println!("cargo:rustc-cfg=limb_width_32");
    }
}
<|endoftext|>


<commit_before><commit_msg>All line endings should be in Unix format<commit_after><|endoftext|>


<commit_before><commit_msg>build.rs work<commit_after><|endoftext|>


<commit_before>type pair<A,B> = {
    a: A, b: B
};

tag rec<A> = _rec<A>;
type _rec<A> = {
    val: A,
    mutable rec: option<@rec<A>>
};

fn make_cycle<A:copy>(a: A) {
    let g: @rec<A> = @rec({val: a, mutable rec: none});
    g.rec = some(g);
}

fn f<A:send,B:send>(a: A, b: B) -> fn@() -> (A, B) {
    fn@() -> (A, B) { (a, b) }
}

fn main() {
    let x = 22_u8;
    let y = 44_u64;
    let z = f(~x, y);
    make_cycle(z);
    let (a, b) = z();
    #debug["a=%u b=%u", *a as uint, b as uint];
    assert *a == x;
    assert b == y;
}<commit_msg>update to new tag syntax<commit_after>type pair<A,B> = {
    a: A, b: B
};

enum rec<A> = _rec<A>;
type _rec<A> = {
    val: A,
    mutable rec: option<@rec<A>>
};

fn make_cycle<A:copy>(a: A) {
    let g: @rec<A> = @rec({val: a, mutable rec: none});
    g.rec = some(g);
}

fn f<A:send,B:send>(a: A, b: B) -> fn@() -> (A, B) {
    fn@() -> (A, B) { (a, b) }
}

fn main() {
    let x = 22_u8;
    let y = 44_u64;
    let z = f(~x, y);
    make_cycle(z);
    let (a, b) = z();
    #debug["a=%u b=%u", *a as uint, b as uint];
    assert *a == x;
    assert b == y;
}<|endoftext|>


<commit_before><commit_msg>Implement error rates as aggregated metric<commit_after>use log_parser::log_events::HttpError;

#[derive(PartialEq, Debug)]
pub struct ErrorRatesResult {
    pub client_error_4xx: f32,
    pub server_error_5xx: f32,
}

pub trait HttpErrorState {
    fn error(&self) -> Option<HttpError>;
}

pub struct AggregatedErrorRates {
    total_count: usize,
    client_error_4xx_count: usize,
    server_error_5xx_count: usize,
}

impl AggregatedErrorRates {
    pub fn new() -> AggregatedErrorRates {
        AggregatedErrorRates {
            total_count: 0,
            client_error_4xx_count: 0,
            server_error_5xx_count: 0,
        }
    }

    pub fn add<T>(&mut self, value: &T)
        where T: HttpErrorState
    {
        self.total_count += 1;

        match value.error() {
            Some(HttpError::ClientError4xx) => self.client_error_4xx_count += 1,
            Some(HttpError::ServerError5xx) => self.server_error_5xx_count += 1,
            None => (),
        }
    }

    pub fn result(&self) -> Option<ErrorRatesResult> {
        if self.total_count == 0 {
            return None;
        }

        Some(ErrorRatesResult {
            client_error_4xx: (self.client_error_4xx_count as f32 / self.total_count as f32 *
                               10000.0)
                .round() / 10000.0,
            server_error_5xx: (self.server_error_5xx_count as f32 / self.total_count as f32 *
                               10000.0)
                .round() / 10000.0,
        })
    }
}
#[cfg(test)]
mod tests {
    use super::*;

    impl HttpErrorState for String {
        fn error(&self) -> Option<HttpError> {
            match self.chars().nth(0) {
                Some('4') => Some(HttpError::ClientError4xx),
                Some('5') => Some(HttpError::ServerError5xx),
                _ => None,
            }
        }
    }

    #[test]
    fn test_all_ok() {
        let mut error_rates = AggregatedErrorRates::new();

        error_rates.add(&String::from("200"));
        error_rates.add(&String::from("200"));

        let result = error_rates.result();
        let expected = Some(ErrorRatesResult {
            client_error_4xx: 0.0,
            server_error_5xx: 0.0,
        });
        assert_eq!(result, expected);
    }

    #[test]
    fn test_50_percent_client_errors() {
        let mut error_rates = AggregatedErrorRates::new();

        error_rates.add(&String::from("200"));
        error_rates.add(&String::from("403"));

        let result = error_rates.result();
        let expected = Some(ErrorRatesResult {
            client_error_4xx: 0.5,
            server_error_5xx: 0.0,
        });
        assert_eq!(result, expected);
    }

    #[test]
    fn test_50_percent_server_errors() {
        let mut error_rates = AggregatedErrorRates::new();

        error_rates.add(&String::from("201"));
        error_rates.add(&String::from("500"));

        let result = error_rates.result();
        let expected = Some(ErrorRatesResult {
            client_error_4xx: 0.0,
            server_error_5xx: 0.5,
        });
        assert_eq!(result, expected);
    }

    #[test]
    fn test_mixed_errors() {
        let mut error_rates = AggregatedErrorRates::new();

        error_rates.add(&String::from("302"));
        error_rates.add(&String::from("500"));
        error_rates.add(&String::from("403"));
        error_rates.add(&String::from("200"));

        let result = error_rates.result();
        let expected = Some(ErrorRatesResult {
            client_error_4xx: 0.25,
            server_error_5xx: 0.25,
        });
        assert_eq!(result, expected);
    }

    #[test]
    fn test_empty() {
        let error_rates = AggregatedErrorRates::new();

        let result = error_rates.result();
        assert_eq!(result, None);
    }

    #[test]
    fn test_rounding() {
        let mut error_rates = AggregatedErrorRates::new();

        error_rates.add(&String::from("200"));
        error_rates.add(&String::from("500"));
        error_rates.add(&String::from("403"));

        let result = error_rates.result();
        let expected = Some(ErrorRatesResult {
            client_error_4xx: 0.3333,
            server_error_5xx: 0.3333,
        });
        assert_eq!(result, expected);
    }
}
<|endoftext|>


<commit_before><commit_msg>Rename AssociatedItems to AssocItems<commit_after>#![allow(missing_docs)]

use embedded_hal::digital::v2::{InputPin, OutputPin};
use generic_array::{ArrayLength, GenericArray};
use heapless::Vec;

pub trait HeterogenousArray {
    type Len;
}

/// Macro to implement a iterator on trait objects from a tuple struct.
#[macro_export]
macro_rules! impl_heterogenous_array {
    ($s:ident, $t:ty, $len:tt, [$($idx:tt),+]) => {
        impl<'a> IntoIterator for &'a $s {
            type Item = &'a $t;
            type IntoIter = generic_array::GenericArrayIter<&'a $t, $len>;
            fn into_iter(self) -> Self::IntoIter {
                self.as_array().into_iter()
            }
        }
        impl<'a> IntoIterator for &'a mut $s {
            type Item = &'a mut $t;
            type IntoIter = generic_array::GenericArrayIter<&'a mut $t, $len>;
            fn into_iter(self) -> Self::IntoIter {
                self.as_mut_array().into_iter()
            }
        }
        impl $crate::matrix::HeterogenousArray for $s {
            type Len = $len;
        }
        impl $s {
            pub fn as_array(&self) -> generic_array::GenericArray<&$t, $len> {
                generic_array::arr![&$t; $( &self.$idx as &$t, )+]
            }
            pub fn as_mut_array(&mut self) -> generic_array::GenericArray<&mut $t, $len> {
                generic_array::arr![&mut $t; $( &mut self.$idx as &mut $t, )+]
            }
        }
    }
}

pub struct Matrix<C, R> {
    cols: C,
    rows: R,
}

impl<C, R> Matrix<C, R> {
    pub fn new<E>(cols: C, rows: R) -> Result<Self, E>
        where
                for<'a> &'a mut R: IntoIterator<Item = &'a mut dyn OutputPin<Error = E>>,
    {
        let mut res = Self { cols, rows };
        res.clear()?;
        Ok(res)
    }
    pub fn clear<'a, E: 'a>(&'a mut self) -> Result<(), E>
        where
            &'a mut R: IntoIterator<Item = &'a mut dyn OutputPin<Error = E>>,
    {
        for r in self.rows.into_iter() {
            r.set_high()?;
        }
        Ok(())
    }
    pub fn get<'a, E: 'a>(&'a mut self) -> Result<PressedKeys<R::Len, C::Len>, E>
        where
            &'a mut R: IntoIterator<Item = &'a mut dyn OutputPin<Error = E>>,
            R: HeterogenousArray,
            R::Len: ArrayLength<GenericArray<bool, C::Len>>,
            &'a C: IntoIterator<Item = &'a dyn InputPin<Error = E>>,
            C: HeterogenousArray,
            C::Len: ArrayLength<bool>,
    {
        let cols = &self.cols;
        self.rows
            .into_iter()
            .map(|r| {
                r.set_low()?;
                let col = cols
                    .into_iter()
                    .map(|c| c.is_low())
                    .collect::<Result<Vec<_, C::Len>, E>>()?
                    .into_iter()
                    .collect();
                r.set_high()?;
                Ok(col)
            })
            .collect::<Result<Vec<_, R::Len>, E>>()
            .map(|res| PressedKeys(res.into_iter().collect()))
    }
}

#[derive(Default, PartialEq, Eq)]
pub struct PressedKeys<U, V>(pub GenericArray<GenericArray<bool, V>, U>)
    where
        V: ArrayLength<bool>,
        U: ArrayLength<GenericArray<bool, V>>;

impl<U, V> PressedKeys<U, V>
    where
        V: ArrayLength<bool>,
        U: ArrayLength<GenericArray<bool, V>>,
{
    pub fn iter_pressed<'a>(&'a self) -> impl Iterator<Item = (usize, usize)> + Clone + 'a {
        self.0.iter().enumerate().flat_map(|(i, r)| {
            r.iter()
                .enumerate()
                .filter_map(move |(j, &b)| if b { Some((i, j)) } else { None })
        })
    }
}

impl<'a, U, V> IntoIterator for &'a PressedKeys<U, V>
    where
        V: ArrayLength<bool>,
        U: ArrayLength<GenericArray<bool, V>>,
        U: ArrayLength<&'a GenericArray<bool, V>>,
{
    type IntoIter = core::slice::Iter<'a, GenericArray<bool, V>>;
    type Item = &'a GenericArray<bool, V>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}<|endoftext|>


<commit_before><commit_msg>Add example (but work in progress....)<commit_after>extern crate ruroonga;
use ruroonga::*;
use std::ffi::CStr;
use std::str;

fn main() {
    unsafe {
        let rc = grn_init();
        let ctx = grn_ctx_open(rc);
        let slice = CStr::from_ptr(ruroonga::grn_get_version());
        println!("Hello in Ruroonga with Groonga: {}", str::from_utf8(slice.to_bytes()).unwrap());
        let _ = grn_fin();
    }
}
<|endoftext|>


<commit_before>extern crate "portmidi" as pm;

#[main]
fn main() {
    match get_devices() {
        Err(e) => println!("{:?}", e),
        Ok(d) => print_devices(d)
    }
}

fn get_devices() -> pm::PortMidiResult<Vec<pm::DeviceInfo>> {
    try!(pm::initialize());
    let no = pm::count_devices();
    // use filter_map to discard None, and unwrap the Some(_)
    let devices = (0..no).filter_map(|i| pm::get_device_info(i))
                         .collect::<Vec<_>>();
    try!(pm::terminate());
    Ok(devices)
}

fn print_devices(devices: Vec<pm::DeviceInfo>) {
    println!("Id  Name                 Input? Output?");
    println!("=======================================");
    for d in devices.into_iter() {
        println!("{:<3} {:<20} {:<6} {:<6}", d.device_id, d.name, d.input, d.output);
    }
}

<commit_msg>remove #[main]<commit_after>extern crate "portmidi" as pm;

fn main() {
    match get_devices() {
        Err(e) => println!("{:?}", e),
        Ok(d) => print_devices(d)
    }
}

fn get_devices() -> pm::PortMidiResult<Vec<pm::DeviceInfo>> {
    try!(pm::initialize());
    let no = pm::count_devices();
    // use filter_map to discard None, and unwrap the Some(_)
    let devices = (0..no).filter_map(|i| pm::get_device_info(i))
                         .collect::<Vec<_>>();
    try!(pm::terminate());
    Ok(devices)
}

fn print_devices(devices: Vec<pm::DeviceInfo>) {
    println!("Id  Name                 Input? Output?");
    println!("=======================================");
    for d in devices.into_iter() {
        println!("{:<3} {:<20} {:<6} {:<6}", d.device_id, d.name, d.input, d.output);
    }
}

<|endoftext|>


<commit_before><commit_msg>Test column offset for #11184<commit_after># //~ ERROR 1:1: 1:2 error: expected item
<|endoftext|>


<commit_before><commit_msg>Making a messy text repl thing<commit_after><|endoftext|>


<commit_before>pub mod wireframe;
pub mod filled;
pub mod textured;

/// Do perspective calculation on a point, return (x, y).
fn perpective(x: f32, y: f32, z: f32) -> (f32, f32) {
    (x/z, y/z)
}

/// Turn floating point coordinates to something drawable on the screen, return (x, y)
fn screen(x: f32, y: f32, screen_width: i32, screen_height: i32) -> (i32, i32) {
    ((x * (screen_height/2) as f32) as i32 + (screen_width/2),
     (y * (screen_height/2) as f32) as i32 + (screen_height/2))
}<commit_msg>Add floating point normalized to screen coordinate conversion<commit_after>pub mod wireframe;
pub mod filled;
pub mod textured;

/// Do perspective calculation on a point, return (x, y).
fn perpective(x: f32, y: f32, z: f32) -> (f32, f32) {
    (x/z, y/z)
}

/// Turn floating point coordinates to something drawable on the screen, return (x, y)
fn screen(x: f32, y: f32, screen_width: i32, screen_height: i32) -> (i32, i32) {
    ((x * (screen_height/2) as f32) as i32 + (screen_width/2),
     (y * (screen_height/2) as f32) as i32 + (screen_height/2))
}

fn screen_f(x: f32, y: f32, screen_width: i32, screen_height: i32) -> (f32, f32) {
    (x * (screen_height/2) as f32 + (screen_width/2) as f32,
     y * (screen_height/2) as f32 + (screen_height/2) as f32)
}<|endoftext|>


<commit_before><commit_msg>an empy message<commit_after><|endoftext|>


<commit_before><commit_msg>examples(17_yaml): conditinonally compile 17_yaml example<commit_after><|endoftext|>


<commit_before><commit_msg>Started making a version of bouncy_circles with the new API<commit_after>
use time_steward::support;
use time_steward::support::time_functions::QuadraticTrajectory;
use nalgebra::Vector2;
use time_steward::support::rounding_error_tolerant_math::right_shift_round_up;

pub type Time = i64;
pub type SpaceCoordinate = i64;

pub const HOW_MANY_CIRCLES: i32 = 20;
pub const ARENA_SIZE_SHIFT: u32 = 20;
pub const ARENA_SIZE: SpaceCoordinate = 1 << 20;
pub const GRID_SIZE_SHIFT: u32 = ARENA_SIZE_SHIFT - 3;
// pub const GRID_SIZE: SpaceCoordinate = 1 << GRID_SIZE_SHIFT;
pub const MAX_DISTANCE_TRAVELED_AT_ONCE: SpaceCoordinate = ARENA_SIZE << 4;
pub const TIME_SHIFT: u32 = 20;
pub const SECOND: Time = 1 << TIME_SHIFT;

pub struct Basics {};
impl BasicsTrait for Basics {
  type Time = Time;
  type GlobalTimeline = ConstantTimeline <Vec<DataTimelineHandle <Circle>>>;
});

pub type Steward = simple_flat::Steward <Basics>;

#[derive (Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
pub struct Circle {
  pub index: usize,
  pub position: QuadraticTrajectory,
  pub radius: SpaceCoordinate,
  pub relationships: Vec<DataTimelineHandle <SimpleTimeline <Relationship>>>,
}

#[derive (Clone, PartialEq, Eq, Serialize, Deserialize, Debug)]
pub struct Relationship {
  pub circles: (DataTimelineHandle <SimpleTimeline <Circle>>, DataTimelineHandle <SimpleTimeline <Circle>>),
  pub induced_acceleration: Option <Vector2<SpaceCoordinate>>,
  pub next_change: Option <PredictionHandle <RelationshipChange>>,
}

pub fn update_relationship_change_prediction <Accessor: EventAccessor <Steward = Steward>>(accessor: &mut Accessor, relationship_handle: DataTimelineHandle <Relationship>) {
  let relationship = query_simple_timeline (accessor, relationship_handle, QueryOffset::After);

  let us = (query_simple_timeline (accessor, relationship.circles.0, QueryOffset::After)
      .expect("a nearness exists for a circle that doesn't"),
              query_simple_timeline (accessor, relationship.circles.1, QueryOffset::After)
      .expect("a nearness exists for a circle that doesn't"));

  let time = QuadraticTrajectory::approximately_when_distance_passes((us.0).0.radius +
                                                                   (us.1).0.radius,
                                                                   if relationship.induced_acceleration.is_none() {
                                                                     -1
                                                                   } else {
                                                                     1
                                                                   },
                                                                   ((us.0).0.base.clone(),
                                                                    &(us.0).1.position),
                                                                   ((us.1).0.base.clone(),
                                                                    &(us.1).1.position));
  // println!("Planning for {} At {}, {}", id, (us.0).1, (us.1).1);
  if time.is_none() && relationship.induced_acceleration.is_some() {
    panic!(" fail {:?} {:?} {:?} {:?}", relationship, us)
  }

  if let Some (discarded) = relationship.next_change.take() {
    accessor.destroy_prediction (&discarded);
  }
  if let Some(yes) = time {
    if yes >= *accessor.now() {
      // println!(" planned for {}", &yes);
      relationship.next_change = Some(accessor.create_prediction (yes, DeterministicRandomId::new (&(us.0).1.index, (us.1).1.index)), RelationshipChange {relationship: relationship_handle}));
    }
  }
  modify_simple_timeline (accessor, relationship_handle, Some (relationship)) ;
}

time_steward_event! (
  pub struct Collision {id: RowId}, Basics, EventId (0x2312e29e341a2495),
  | &self, mutator | {
    let new_relationship;
    let mut new;
    let ids = Nearness::get_ids(mutator, self.id).0;
    {
      let relationship = mutator.get::<Intersection>(self.id).clone();
      let us = (mutator.data_and_last_change::<Circle>(ids[0])
                    .expect("a nearness exists for a circle that \
                             doesn't (event)"),
             mutator.data_and_last_change::<Circle>(ids[1])
                    .expect("a nearness exists for a circle that \
                             doesn't (event)"));
      new = ((us.0).0.clone(), (us.1).0.clone());
      new.0.position.update_by(mutator.now() - (us.0).1);
      new.1.position.update_by(mutator.now() - (us.1).1);
      if let Some(intersection) = relationship {
        new.0
          .position
          .add_acceleration(-intersection.induced_acceleration);
        new.1
          .position
          .add_acceleration(intersection.induced_acceleration);
        new_relationship = None;
        //println!("Parted {} At {}", self.id, mutator.now());
      } else {
        let acceleration = (new.0.position.evaluate() -
                           new.1.position.evaluate()) *
                          (ARENA_SIZE * 4 /
                           (new.0.radius + new.1.radius));
        new.0.position.add_acceleration(acceleration);
        new.1.position.add_acceleration(-acceleration);
        new_relationship = Some(Intersection {
         induced_acceleration: acceleration,
        });

        //println!("Joined {} At {}", self.id, mutator.now());
      }
    }
    mutator.set::<Intersection>(self.id, new_relationship);
    mutator.set::<Circle>(ids[0], Some(new.0));
    mutator.set::<Circle>(ids[1], Some(new.1));
  }
);

pub fn boundary_predictor<PA: PredictorAccessor<Basics = Basics>>(accessor: &mut PA, id: RowId) {
  let time;
  {
    let arena_center = QuadraticTrajectory::new(TIME_SHIFT,
                                                MAX_DISTANCE_TRAVELED_AT_ONCE,
                                                [ARENA_SIZE / 2, ARENA_SIZE / 2, 0, 0, 0, 0]);
    let me = accessor.data_and_last_change::<Circle>(id)
      .expect("a prediction was recorded for a circle that doesn't exist");

    let relationship = accessor.get::<Intersection>(id);
    time = QuadraticTrajectory::approximately_when_distance_passes(ARENA_SIZE - me.0.radius,
                                                                   if relationship.is_some() {
                                                                     -1
                                                                   } else {
                                                                     1
                                                                   },
                                                                   (me.1.clone(),
                                                                    &(me.0.position)),
                                                                   (0, &(arena_center)));
  }
  if let Some(yes) = time {
    // println!(" planned for {}", &yes);
    accessor.predict_at_time(yes, BoundaryCollision::new(id));
  }
}

time_steward_event! (
  pub struct BoundaryCollision {id: RowId}, Basics, EventId (0x59732d675b2329ad),
  | &self, mutator | {
    let new_relationship;
    let mut new;
    {
      let relationship = mutator.get::<Intersection>(self.id).clone();
      let me = mutator.data_and_last_change::<Circle>(self.id)
                   .expect("a an event was recorded for a circle \
                            that doesn't exist)");
      new = me.0.clone();
      new.position.update_by(mutator.now() - me.1);
      if let Some(intersection) = relationship {
        new.position
          .add_acceleration(-intersection.induced_acceleration);
        new_relationship = None;
      } else {
      let acceleration = -(new.position.evaluate() -
                            Vector2::new(ARENA_SIZE / 2,
                                         ARENA_SIZE / 2)) *
                          (ARENA_SIZE * 400 / (ARENA_SIZE - me.0.radius));
        new.position.add_acceleration(acceleration);
        new_relationship = Some(Intersection {
         induced_acceleration: acceleration,
      });

      }
    }
    mutator.set::<Intersection>(self.id, new_relationship);
    mutator.set::<Circle>(self.id, Some(new));
  }
);

time_steward_predictor! (pub struct CollisionPredictor, Basics, PredictorId(0x5375592f4da8682c), watching Nearness, fn collision_predictor);
time_steward_predictor! (pub struct BoundaryPredictor, Basics, PredictorId(0x87d8a4a095350d30), watching Circle, fn boundary_predictor);

time_steward_event! (
  pub struct Initialize {}, Basics, EventId (0xa2a17317b84f96e5),
  | &self, mutator | {
    for i in 0..HOW_MANY_CIRCLES {
      let thingy = ARENA_SIZE / 20;
      let radius = mutator.gen_range(ARENA_SIZE / 30, ARENA_SIZE / 15);
      let id = get_circle_id(i);

      let position =
      QuadraticTrajectory::new(TIME_SHIFT,
                              MAX_DISTANCE_TRAVELED_AT_ONCE,
                              [mutator.gen_range(0, ARENA_SIZE),
                               mutator.gen_range(0, ARENA_SIZE),
                               mutator.gen_range(-thingy, thingy),
                               mutator.gen_range(-thingy, thingy),
                               0,
                               0]);
      mutator.set::<Circle>(id,
                         Some(Circle {
                           position: position,
                           radius: radius,
                         }));
      collisions::insert::<CollisionBasics, _>(mutator, id, ());
    }
  }
);

time_steward_event! (
  pub struct Disturb {coordinates: [SpaceCoordinate; 2]}, Basics, EventId(0x058cb70d89116605),
  | &self, mutator | {
    let mut best_id = RowId::new (& 0u8);
    let mut best_distance_squared = i64::max_value();
    for i in 0..HOW_MANY_CIRCLES {
      let id = get_circle_id(i);
      let (circle, time) = mutator.data_and_last_change::<Circle>(id)
          .expect("missing circle")
          .clone();
      let position = circle.position.updated_by(mutator.now() - time).unwrap().evaluate();
      let distance_squared = (self.coordinates [0] - position [0]) * (self.coordinates [0] - position [0]) + (self.coordinates [1] - position [1]) * (self.coordinates [1] - position [1]);
      if distance_squared <best_distance_squared {
        best_distance_squared = distance_squared;
        best_id = id;
      }
    }    let mut new;{
    let (a, time) = mutator.data_and_last_change::<Circle>(best_id)
              .expect("missing circle")
              .clone();
    new =a.clone();
    new.position.update_by(mutator.now() - time);
    let impulse = -(new.position.evaluate() -
                            Vector2::new(ARENA_SIZE / 2,
                                         ARENA_SIZE / 2)) *
                          (ARENA_SIZE * 4 / (ARENA_SIZE ));
    new.position.add_velocity(impulse);}
    mutator.set::<Circle>(best_id, Some(new));
  }
);
<|endoftext|>


<commit_before><commit_msg>chore: implement BFS<commit_after><|endoftext|>


<commit_before><commit_msg>Made compilation on the master branch fail.<commit_after>fn main() {
    compile_error!("This branch is no longer updated, please use the current branch instead.")
}
<|endoftext|>


<commit_before><commit_msg>parser: add test for 'extern crate async'<commit_after>// Make sure that we don't parse `extern crate async`
// the front matter of a function leading us astray.

// check-pass

fn main() {}

#[cfg(FALSE)]
extern crate async;

#[cfg(FALSE)]
extern crate async as something_else;
<|endoftext|>


<commit_before>use inflector::Inflector;

use botocore::{Operation, Service};
use super::GenerateProtocol;

pub struct JsonGenerator;

impl GenerateProtocol for JsonGenerator {
    fn generate_methods(&self, service: &Service) -> String {
        service.operations.values().map(|operation| {
            let output_type = operation.output_shape_or("()");

            format!("
                {documentation}
                pub fn {method_name}(&mut self, input: &{input_type}) -> AwsResult<{output_type}> {{
                    let encoded = serde_json::to_string(input).unwrap();
                    let mut request = SignedRequest::new(\"{http_method}\", \"{endpoint_prefix}\", self.region, \"{request_uri}\");
                    request.set_content_type(\"application/x-amz-json-1.1\".to_owned());
                    request.add_header(\"x-amz-target\", \"{target_prefix}.{name}\");
                    request.set_payload(Some(encoded.as_bytes()));
                    let mut result = request.sign_and_execute(try!(self.credentials_provider.credentials()));
                    let status = result.status.to_u16();
                    let mut body = String::new();
                    result.read_to_string(&mut body).unwrap();
                    match status {{
                        200 => {{
                            {ok_response}
                        }}
                        _ => Err(parse_json_protocol_error(&body)),
                    }}
                }}
                ",
                documentation = generate_documentation(operation).unwrap_or("".to_owned()),
                endpoint_prefix = service.metadata.endpoint_prefix,
                http_method = operation.http.method,
                input_type = operation.input_shape(),
                method_name = operation.name.to_snake_case(),
                name = operation.name,
                ok_response = generate_ok_response(operation, output_type),
                output_type = output_type,
                request_uri = operation.http.request_uri,
                target_prefix = service.metadata.target_prefix.as_ref().unwrap(),
            )
        }).collect::<Vec<String>>().join("\n")
    }

    fn generate_prelude(&self) -> String {
        "use std::io::Read;

        use serde_json;

        use credential::ProvideAwsCredentials;
        use error::{AwsResult, parse_json_protocol_error};
        use region::Region;
        use signature::SignedRequest;
        ".to_owned()
    }

    fn generate_struct_attributes(&self) -> String {
        "#[derive(Debug, Default, Deserialize, Serialize)]".to_owned()
    }

}

fn generate_documentation(operation: &Operation) -> Option<String> {
    operation.documentation.as_ref().map(|docs| {
        format!("#[doc=\"{}\"]", docs.replace("\"", "\\\""))
    })
}

fn generate_ok_response(operation: &Operation, output_type: &str) -> String {
    if operation.output.is_some() {
        format!("Ok(serde_json::from_str::<{}>(&body).unwrap())", output_type)
    } else {
        "Ok(())".to_owned()
    }
}
<commit_msg>Use jsonVersion from the Botoscore service definition<commit_after>use inflector::Inflector;

use botocore::{Operation, Service};
use super::GenerateProtocol;

pub struct JsonGenerator;

impl GenerateProtocol for JsonGenerator {
    fn generate_methods(&self, service: &Service) -> String {
        service.operations.values().map(|operation| {
            let output_type = operation.output_shape_or("()");

            format!("
                {documentation}
                pub fn {method_name}(&mut self, input: &{input_type}) -> AwsResult<{output_type}> {{
                    let encoded = serde_json::to_string(input).unwrap();
                    let mut request = SignedRequest::new(\"{http_method}\", \"{endpoint_prefix}\", self.region, \"{request_uri}\");
                    request.set_content_type(\"application/x-amz-json-{json_version}\".to_owned());
                    request.add_header(\"x-amz-target\", \"{target_prefix}.{name}\");
                    request.set_payload(Some(encoded.as_bytes()));
                    let mut result = request.sign_and_execute(try!(self.credentials_provider.credentials()));
                    let status = result.status.to_u16();
                    let mut body = String::new();
                    result.read_to_string(&mut body).unwrap();
                    match status {{
                        200 => {{
                            {ok_response}
                        }}
                        _ => Err(parse_json_protocol_error(&body)),
                    }}
                }}
                ",
                documentation = generate_documentation(operation).unwrap_or("".to_owned()),
                endpoint_prefix = service.metadata.endpoint_prefix,
                http_method = operation.http.method,
                input_type = operation.input_shape(),
                method_name = operation.name.to_snake_case(),
                name = operation.name,
                ok_response = generate_ok_response(operation, output_type),
                output_type = output_type,
                request_uri = operation.http.request_uri,
                target_prefix = service.metadata.target_prefix.as_ref().unwrap(),
                json_version = service.metadata.json_version.as_ref().map(|x| x as &str).unwrap_or("1.0")
            )
        }).collect::<Vec<String>>().join("\n")
    }

    fn generate_prelude(&self) -> String {
        "use std::io::Read;

        use serde_json;

        use credential::ProvideAwsCredentials;
        use error::{AwsResult, parse_json_protocol_error};
        use region::Region;
        use signature::SignedRequest;
        ".to_owned()
    }

    fn generate_struct_attributes(&self) -> String {
        "#[derive(Debug, Default, Deserialize, Serialize)]".to_owned()
    }

}

fn generate_documentation(operation: &Operation) -> Option<String> {
    operation.documentation.as_ref().map(|docs| {
        format!("#[doc=\"{}\"]", docs.replace("\"", "\\\""))
    })
}

fn generate_ok_response(operation: &Operation, output_type: &str) -> String {
    if operation.output.is_some() {
        format!("Ok(serde_json::from_str::<{}>(&body).unwrap())", output_type)
    } else {
        "Ok(())".to_owned()
    }
}
<|endoftext|>


<commit_before><commit_msg>LeetCode: 13. Roman to Integer<commit_after>use std::collections::HashMap;

// #[derive(Debug)]
// struct Solution {}

impl Solution {
    pub fn roman_to_int(s: String) -> i32 {
        let mut sum: i32 = 0;
        let table: HashMap<char, i32> = [
            ('I', 1),
            ('V', 5),
            ('X', 10),
            ('L', 50),
            ('C', 100),
            ('D', 500),
            ('M', 1000),
            (' ', 0)]
            .iter().cloned().collect();
        for (c, n) in s.chars().zip(s.chars().skip(1).chain(" ".chars())) {
            let cv = table.get(&c).unwrap();
            let nv = table.get(&n).unwrap();
            if cv >= nv {
                sum += cv;
            } else {
                sum -= cv;
            }
            // println!("{:?}", c);
        }
        return sum;

    }
}

// fn main() {
//     println!("{}", Solution::roman_to_int(String::from("IV")));
//     println!("{}", Solution::roman_to_int(String::from("IX")));
//     println!("{}", Solution::roman_to_int(String::from("VII")));
//     println!("{}", Solution::roman_to_int(String::from("VI")));
//     println!("{}", Solution::roman_to_int(String::from("LVIII")));
//     println!("{}", Solution::roman_to_int(String::from("MCMXCIV")));
//     println!("{}", Solution::roman_to_int(String::from("MCDLXXVI")));
// }
<|endoftext|>


<commit_before><commit_msg>Add some tests for GC<commit_after><|endoftext|>


<commit_before><commit_msg>syntax: remove abi::Os and abi::Architecture<commit_after><|endoftext|>


<commit_before><commit_msg>genet-kernel: throw filter errors<commit_after><|endoftext|>


<commit_before><commit_msg>remove duplicate macro<commit_after><|endoftext|>


<commit_before><commit_msg>util::shared: Always compile<commit_after><|endoftext|>


<commit_before><commit_msg>script to build app files which will serve in rocket as static files.<commit_after>use std::process::{self, Command, ExitStatus, Output};

// Move a file (just an mv alias)
// fn mv_file(source_name: &str, destination_name: &str) {
//     let output = process::Command::new("mv")
//         .arg(source_name)
//         .arg(destination_name)
//         .output()
//         .expect("failed to execute process");
//     println!("status: {} stderr: {} stdout: {}",
//              output.status,
//              String::from_utf8_lossy(&output.stderr),
//              String::from_utf8_lossy(&output.stdout));
// }

pub fn exec_shell(arg: &str) -> Output {
    Command::new("sh")
        .arg("-c")
        .arg(arg)
        .output()
        .expect("failed to execute process")
}

pub fn exec_shell_with_output(arg: &str) -> ExitStatus {
    Command::new("sh")
        .arg("-c")
        .arg(arg)
        .status()
        .expect("failed to execute process")
}

fn main() {
    println!("cargo:rerun-if-changed=./app/elm/Main.elm");
    println!("cargo:rerun-if-changed=./app/static/index.html.hbs");
    println!("Running brunch builder...");
    exec_shell("rm -rf css js");
    // Command::new("rm")
    //     .current_dir("./")
    //     .args(vec!["-rf", "css"]);
    println!("Deleting stale css directory.");

    exec_shell("rm -rf css js");
    // Command::new("rm")
    //     .current_dir("./")
    //     .args(vec!["-rf", "js"]);
    println!("Deleting stale js directory.");

    exec_shell("cd ~/rust/tuxedo/public && mv css ~/rust/tuxedo");
    // Command::new("mv")
    //     .current_dir("./public")
    //     .args(vec!["css", "../"])
    //     .status()
    //     .unwrap();
    println!("Moving new stylesheet folder to root.");

    exec_shell("cd ~/rust/tuxedo/public && mv js ~/rust/tuxedo");
    // Command::new("mv")
    //     .current_dir("./public")
    //     .args(vec!["js", "../"])
    //     .status()
    //     .unwrap();
    println!("Moving new script folder to root.");

    exec_shell("cd ~/rust/tuxedo/public && mv index.html ~/rust/tuxedo/views/index.html.hbs");
    // Command::new("mv")
    //     .current_dir("./public")
    //     .args(vec!["index.html", "../views/index.html.hbs"])
    //     .status()
    //     .unwrap();
    println!("Replacing index handlebars in view folder.");
}
<|endoftext|>


<commit_before><commit_msg>style: Fix Servo_IsCssPropertyRecordedInUseCounter so that we also report disabled properties.<commit_after><|endoftext|>


<commit_before><commit_msg>changed to_str() to to_string() for mime gens<commit_after><|endoftext|>


<commit_before><commit_msg>Very ugly workaround for Vulkan fullscreen startup (issue #30)<commit_after><|endoftext|>


<commit_before><commit_msg>std: Prefix jemalloc symbols on iOS<commit_after><|endoftext|>


<commit_before>#[doc = "Operations and constants for `float`"];

// Even though this module exports everything defined in it,
// because it contains re-exports, we also have to explicitly
// export locally defined things. That's a bit annoying.
export to_str_common, to_str_exact, to_str, from_str;
export add, sub, mul, div, rem, lt, le, gt, eq, eq, ne;
export is_positive, is_negative, is_nonpositive, is_nonnegative;
export is_zero, is_infinite, is_finite;
export NaN, is_NaN, infinity, neg_infinity;
export consts;
export logarithm;
export acos, asin, atan, atan2, cbrt, ceil, copysign, cos, cosh, floor;
export erf, erfc, exp, expm1, exp2, abs, abs_sub;
export mul_add, fmax, fmin, nextafter, frexp, hypot, ldexp;
export lgamma, ln, log_radix, ln1p, log10, log2, ilog_radix;
export modf, pow, round, sin, sinh, sqrt, tan, tanh, tgamma, trunc;
export signbit;
export pow_with_uint;

// export when m_float == c_double

export j0, j1, jn, y0, y1, yn;

// PORT this must match in width according to architecture

import m_float = f64;
import f64::*;

/**
 * Section: String Conversions
 */

#[doc = "
Converts a float to a string

# Arguments

* num - The float value
* digits - The number of significant digits
* exact - Whether to enforce the exact number of significant digits
"]
fn to_str_common(num: float, digits: uint, exact: bool) -> str {
    if is_NaN(num) { ret "NaN"; }
    if num == infinity { ret "inf"; }
    if num == neg_infinity { ret "-inf"; }
    let mut (num, accum) = if num < 0.0 { (-num, "-") } else { (num, "") };
    let trunc = num as uint;
    let mut frac = num - (trunc as float);
    accum += uint::str(trunc);
    if (frac < epsilon && !exact) || digits == 0u { ret accum; }
    accum += ".";
    let mut i = digits;
    let mut epsilon = 1. / pow_with_uint(10u, i);
    while i > 0u && (frac >= epsilon || exact) {
        frac *= 10.0;
        epsilon *= 10.0;
        let digit = frac as uint;
        accum += uint::str(digit);
        frac -= digit as float;
        i -= 1u;
    }
    ret accum;

}

#[doc = "
Converts a float to a string with exactly the number of
provided significant digits

# Arguments

* num - The float value
* digits - The number of significant digits
"]
fn to_str_exact(num: float, digits: uint) -> str {
    to_str_common(num, digits, true)
}

#[test]
fn test_to_str_exact_do_decimal() {
    let s = to_str_exact(5.0, 4u);
    assert s == "5.0000";
}

#[doc = "
Converts a float to a string with a maximum number of
significant digits

# Arguments

* num - The float value
* digits - The number of significant digits
"]
fn to_str(num: float, digits: uint) -> str {
    to_str_common(num, digits, false)
}

#[doc = "
Convert a string to a float

This function accepts strings such as

* '3.14'
* '+3.14', equivalent to '3.14'
* '-3.14'
* '2.5E10', or equivalently, '2.5e10'
* '2.5E-10'
* '', or, equivalently, '.' (understood as 0)
* '5.'
* '.5', or, equivalently,  '0.5'

Leading and trailing whitespace are ignored.

# Arguments

* num - A string

# Return value

`none` if the string did not represent a valid number.  Otherwise, `some(n)`
where `n` is the floating-point number represented by `[num]`.
"]
fn from_str(num: str) -> option<float> {
   let mut pos = 0u;               //Current byte position in the string.
                                   //Used to walk the string in O(n).
   let len = str::len(num);        //Length of the string, in bytes.

   if len == 0u { ret none; }
   let mut total = 0f;             //Accumulated result
   let mut c     = 'z';            //Latest char.

   //The string must start with one of the following characters.
   alt str::char_at(num, 0u) {
      '-' | '+' | '0' to '9' | '.' {}
      _ { ret none; }
   }

   //Determine if first char is '-'/'+'. Set [pos] and [neg] accordingly.
   let mut neg = false;               //Sign of the result
   alt str::char_at(num, 0u) {
      '-' {
          neg = true;
          pos = 1u;
      }
      '+' {
          pos = 1u;
      }
      _ {}
   }

   //Examine the following chars until '.', 'e', 'E'
   while(pos < len) {
       let char_range = str::char_range_at(num, pos);
       c   = char_range.ch;
       pos = char_range.next;
       alt c {
         '0' to '9' {
           total = total * 10f;
           total += ((c as int) - ('0' as int)) as float;
         }
         '.' | 'e' | 'E' {
           break;
         }
         _ {
           ret none;
         }
       }
   }

   if c == '.' {//Examine decimal part
      let mut decimal = 1f;
      while(pos < len) {
         let char_range = str::char_range_at(num, pos);
         c = char_range.ch;
         pos = char_range.next;
         alt c {
            '0' | '1' | '2' | '3' | '4' | '5' | '6'| '7' | '8' | '9'  {
                 decimal /= 10f;
                 total += (((c as int) - ('0' as int)) as float)*decimal;
             }
             'e' | 'E' {
                 break;
             }
             _ {
                 ret none;
             }
         }
      }
   }

   if (c == 'e') | (c == 'E') {//Examine exponent
      let mut exponent = 0u;
      let mut neg_exponent = false;
      if(pos < len) {
          let char_range = str::char_range_at(num, pos);
          c   = char_range.ch;
          alt c  {
             '+' {
                pos = char_range.next;
             }
             '-' {
                pos = char_range.next;
                neg_exponent = true;
             }
             _ {}
          }
          while(pos < len) {
             let char_range = str::char_range_at(num, pos);
             c = char_range.ch;
             alt c {
                 '0' | '1' | '2' | '3' | '4' | '5' | '6'| '7' | '8' | '9' {
                     exponent *= 10u;
                     exponent += ((c as uint) - ('0' as uint));
                 }
                 _ {
                     break;
                 }
             }
             pos = char_range.next;
          }
          let multiplier = pow_with_uint(10u, exponent);
              //Note: not [int::pow], otherwise, we'll quickly
              //end up with a nice overflow
          if neg_exponent {
             total = total / multiplier;
          } else {
             total = total * multiplier;
          }
      } else {
         ret none;
      }
   }

   if(pos < len) {
     ret none;
   } else {
     if(neg) {
        total *= -1f;
     }
     ret some(total);
   }
}

/**
 * Section: Arithmetics
 */

#[doc = "
Compute the exponentiation of an integer by another integer as a float

# Arguments

* x - The base
* pow - The exponent

# Return value

`NaN` if both `x` and `pow` are `0u`, otherwise `x^pow`
"]
fn pow_with_uint(base: uint, pow: uint) -> float {
   if base == 0u {
      if pow == 0u {
        ret NaN;
      }
       ret 0.;
   }
   let mut my_pow     = pow;
   let mut total      = 1f;
   let mut multiplier = base as float;
   while (my_pow > 0u) {
     if my_pow % 2u == 1u {
       total = total * multiplier;
     }
     my_pow     /= 2u;
     multiplier *= multiplier;
   }
   ret total;
}

#[test]
fn test_from_str() {
   assert from_str("3") == some(3.);
   assert from_str("3") == some(3.);
   assert from_str("3.14") == some(3.14);
   assert from_str("+3.14") == some(3.14);
   assert from_str("-3.14") == some(-3.14);
   assert from_str("2.5E10") == some(25000000000.);
   assert from_str("2.5e10") == some(25000000000.);
   assert from_str("25000000000.E-10") == some(2.5);
   assert from_str(".") == some(0.);
   assert from_str(".e1") == some(0.);
   assert from_str(".e-1") == some(0.);
   assert from_str("5.") == some(5.);
   assert from_str(".5") == some(0.5);
   assert from_str("0.5") == some(0.5);
   assert from_str("0.5") == some(0.5);
   assert from_str("0.5") == some(0.5);
   assert from_str("-.5") == some(-0.5);
   assert from_str("-.5") == some(-0.5);
   assert from_str("-5") == some(-5.);

   assert from_str("") == none;
   assert from_str("x") == none;
   assert from_str(" ") == none;
   assert from_str("   ") == none;
   assert from_str("e") == none;
   assert from_str("E") == none;
   assert from_str("E1") == none;
   assert from_str("1e1e1") == none;
   assert from_str("1e1.1") == none;
   assert from_str("1e1-1") == none;
}

#[test]
fn test_positive() {
  assert(is_positive(infinity));
  assert(is_positive(1.));
  assert(is_positive(0.));
  assert(!is_positive(-1.));
  assert(!is_positive(neg_infinity));
  assert(!is_positive(1./neg_infinity));
  assert(!is_positive(NaN));
}

#[test]
fn test_negative() {
  assert(!is_negative(infinity));
  assert(!is_negative(1.));
  assert(!is_negative(0.));
  assert(is_negative(-1.));
  assert(is_negative(neg_infinity));
  assert(is_negative(1./neg_infinity));
  assert(!is_negative(NaN));
}

#[test]
fn test_nonpositive() {
  assert(!is_nonpositive(infinity));
  assert(!is_nonpositive(1.));
  assert(!is_nonpositive(0.));
  assert(is_nonpositive(-1.));
  assert(is_nonpositive(neg_infinity));
  assert(is_nonpositive(1./neg_infinity));
  assert(!is_nonpositive(NaN));
}

#[test]
fn test_nonnegative() {
  assert(is_nonnegative(infinity));
  assert(is_nonnegative(1.));
  assert(is_nonnegative(0.));
  assert(!is_nonnegative(-1.));
  assert(!is_nonnegative(neg_infinity));
  assert(!is_nonnegative(1./neg_infinity));
  assert(!is_nonnegative(NaN));
}

#[test]
fn test_to_str_inf() {
    assert to_str(infinity, 10u) == "inf";
    assert to_str(-infinity, 10u) == "-inf";
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//

<commit_msg>add inf/-inf/NaN parsing to float::from_str<commit_after>#[doc = "Operations and constants for `float`"];

// Even though this module exports everything defined in it,
// because it contains re-exports, we also have to explicitly
// export locally defined things. That's a bit annoying.
export to_str_common, to_str_exact, to_str, from_str;
export add, sub, mul, div, rem, lt, le, gt, eq, eq, ne;
export is_positive, is_negative, is_nonpositive, is_nonnegative;
export is_zero, is_infinite, is_finite;
export NaN, is_NaN, infinity, neg_infinity;
export consts;
export logarithm;
export acos, asin, atan, atan2, cbrt, ceil, copysign, cos, cosh, floor;
export erf, erfc, exp, expm1, exp2, abs, abs_sub;
export mul_add, fmax, fmin, nextafter, frexp, hypot, ldexp;
export lgamma, ln, log_radix, ln1p, log10, log2, ilog_radix;
export modf, pow, round, sin, sinh, sqrt, tan, tanh, tgamma, trunc;
export signbit;
export pow_with_uint;

// export when m_float == c_double

export j0, j1, jn, y0, y1, yn;

// PORT this must match in width according to architecture

import m_float = f64;
import f64::*;

/**
 * Section: String Conversions
 */

#[doc = "
Converts a float to a string

# Arguments

* num - The float value
* digits - The number of significant digits
* exact - Whether to enforce the exact number of significant digits
"]
fn to_str_common(num: float, digits: uint, exact: bool) -> str {
    if is_NaN(num) { ret "NaN"; }
    if num == infinity { ret "inf"; }
    if num == neg_infinity { ret "-inf"; }
    let mut (num, accum) = if num < 0.0 { (-num, "-") } else { (num, "") };
    let trunc = num as uint;
    let mut frac = num - (trunc as float);
    accum += uint::str(trunc);
    if (frac < epsilon && !exact) || digits == 0u { ret accum; }
    accum += ".";
    let mut i = digits;
    let mut epsilon = 1. / pow_with_uint(10u, i);
    while i > 0u && (frac >= epsilon || exact) {
        frac *= 10.0;
        epsilon *= 10.0;
        let digit = frac as uint;
        accum += uint::str(digit);
        frac -= digit as float;
        i -= 1u;
    }
    ret accum;

}

#[doc = "
Converts a float to a string with exactly the number of
provided significant digits

# Arguments

* num - The float value
* digits - The number of significant digits
"]
fn to_str_exact(num: float, digits: uint) -> str {
    to_str_common(num, digits, true)
}

#[test]
fn test_to_str_exact_do_decimal() {
    let s = to_str_exact(5.0, 4u);
    assert s == "5.0000";
}

#[doc = "
Converts a float to a string with a maximum number of
significant digits

# Arguments

* num - The float value
* digits - The number of significant digits
"]
fn to_str(num: float, digits: uint) -> str {
    to_str_common(num, digits, false)
}

#[doc = "
Convert a string to a float

This function accepts strings such as

* '3.14'
* '+3.14', equivalent to '3.14'
* '-3.14'
* '2.5E10', or equivalently, '2.5e10'
* '2.5E-10'
* '', or, equivalently, '.' (understood as 0)
* '5.'
* '.5', or, equivalently,  '0.5'
* 'inf', '-inf', 'NaN'

Leading and trailing whitespace are ignored.

# Arguments

* num - A string

# Return value

`none` if the string did not represent a valid number.  Otherwise, `some(n)`
where `n` is the floating-point number represented by `[num]`.
"]
fn from_str(num: str) -> option<float> {
   if num == "inf" {
       ret some(infinity);
   } else if num == "-inf" {
       ret some(neg_infinity);
   } else if num == "NaN" {
       ret some(NaN);
   }

   let mut pos = 0u;               //Current byte position in the string.
                                   //Used to walk the string in O(n).
   let len = str::len(num);        //Length of the string, in bytes.

   if len == 0u { ret none; }
   let mut total = 0f;             //Accumulated result
   let mut c     = 'z';            //Latest char.

   //The string must start with one of the following characters.
   alt str::char_at(num, 0u) {
      '-' | '+' | '0' to '9' | '.' {}
      _ { ret none; }
   }

   //Determine if first char is '-'/'+'. Set [pos] and [neg] accordingly.
   let mut neg = false;               //Sign of the result
   alt str::char_at(num, 0u) {
      '-' {
          neg = true;
          pos = 1u;
      }
      '+' {
          pos = 1u;
      }
      _ {}
   }

   //Examine the following chars until '.', 'e', 'E'
   while(pos < len) {
       let char_range = str::char_range_at(num, pos);
       c   = char_range.ch;
       pos = char_range.next;
       alt c {
         '0' to '9' {
           total = total * 10f;
           total += ((c as int) - ('0' as int)) as float;
         }
         '.' | 'e' | 'E' {
           break;
         }
         _ {
           ret none;
         }
       }
   }

   if c == '.' {//Examine decimal part
      let mut decimal = 1f;
      while(pos < len) {
         let char_range = str::char_range_at(num, pos);
         c = char_range.ch;
         pos = char_range.next;
         alt c {
            '0' | '1' | '2' | '3' | '4' | '5' | '6'| '7' | '8' | '9'  {
                 decimal /= 10f;
                 total += (((c as int) - ('0' as int)) as float)*decimal;
             }
             'e' | 'E' {
                 break;
             }
             _ {
                 ret none;
             }
         }
      }
   }

   if (c == 'e') | (c == 'E') {//Examine exponent
      let mut exponent = 0u;
      let mut neg_exponent = false;
      if(pos < len) {
          let char_range = str::char_range_at(num, pos);
          c   = char_range.ch;
          alt c  {
             '+' {
                pos = char_range.next;
             }
             '-' {
                pos = char_range.next;
                neg_exponent = true;
             }
             _ {}
          }
          while(pos < len) {
             let char_range = str::char_range_at(num, pos);
             c = char_range.ch;
             alt c {
                 '0' | '1' | '2' | '3' | '4' | '5' | '6'| '7' | '8' | '9' {
                     exponent *= 10u;
                     exponent += ((c as uint) - ('0' as uint));
                 }
                 _ {
                     break;
                 }
             }
             pos = char_range.next;
          }
          let multiplier = pow_with_uint(10u, exponent);
              //Note: not [int::pow], otherwise, we'll quickly
              //end up with a nice overflow
          if neg_exponent {
             total = total / multiplier;
          } else {
             total = total * multiplier;
          }
      } else {
         ret none;
      }
   }

   if(pos < len) {
     ret none;
   } else {
     if(neg) {
        total *= -1f;
     }
     ret some(total);
   }
}

/**
 * Section: Arithmetics
 */

#[doc = "
Compute the exponentiation of an integer by another integer as a float

# Arguments

* x - The base
* pow - The exponent

# Return value

`NaN` if both `x` and `pow` are `0u`, otherwise `x^pow`
"]
fn pow_with_uint(base: uint, pow: uint) -> float {
   if base == 0u {
      if pow == 0u {
        ret NaN;
      }
       ret 0.;
   }
   let mut my_pow     = pow;
   let mut total      = 1f;
   let mut multiplier = base as float;
   while (my_pow > 0u) {
     if my_pow % 2u == 1u {
       total = total * multiplier;
     }
     my_pow     /= 2u;
     multiplier *= multiplier;
   }
   ret total;
}

#[test]
fn test_from_str() {
   assert from_str("3") == some(3.);
   assert from_str("3") == some(3.);
   assert from_str("3.14") == some(3.14);
   assert from_str("+3.14") == some(3.14);
   assert from_str("-3.14") == some(-3.14);
   assert from_str("2.5E10") == some(25000000000.);
   assert from_str("2.5e10") == some(25000000000.);
   assert from_str("25000000000.E-10") == some(2.5);
   assert from_str(".") == some(0.);
   assert from_str(".e1") == some(0.);
   assert from_str(".e-1") == some(0.);
   assert from_str("5.") == some(5.);
   assert from_str(".5") == some(0.5);
   assert from_str("0.5") == some(0.5);
   assert from_str("0.5") == some(0.5);
   assert from_str("0.5") == some(0.5);
   assert from_str("-.5") == some(-0.5);
   assert from_str("-.5") == some(-0.5);
   assert from_str("-5") == some(-5.);
   assert from_str("-0") == some(-0.);
   assert from_str("0") == some(0.);
   assert from_str("inf") == some(infinity);
   assert from_str("-inf") == some(neg_infinity);
   // note: NaN != NaN, hence this slightly complex test
   alt from_str("NaN") {
       some(f) { assert is_NaN(f); }
       none { fail; }
   }

   assert from_str("") == none;
   assert from_str("x") == none;
   assert from_str(" ") == none;
   assert from_str("   ") == none;
   assert from_str("e") == none;
   assert from_str("E") == none;
   assert from_str("E1") == none;
   assert from_str("1e1e1") == none;
   assert from_str("1e1.1") == none;
   assert from_str("1e1-1") == none;
}

#[test]
fn test_positive() {
  assert(is_positive(infinity));
  assert(is_positive(1.));
  assert(is_positive(0.));
  assert(!is_positive(-1.));
  assert(!is_positive(neg_infinity));
  assert(!is_positive(1./neg_infinity));
  assert(!is_positive(NaN));
}

#[test]
fn test_negative() {
  assert(!is_negative(infinity));
  assert(!is_negative(1.));
  assert(!is_negative(0.));
  assert(is_negative(-1.));
  assert(is_negative(neg_infinity));
  assert(is_negative(1./neg_infinity));
  assert(!is_negative(NaN));
}

#[test]
fn test_nonpositive() {
  assert(!is_nonpositive(infinity));
  assert(!is_nonpositive(1.));
  assert(!is_nonpositive(0.));
  assert(is_nonpositive(-1.));
  assert(is_nonpositive(neg_infinity));
  assert(is_nonpositive(1./neg_infinity));
  assert(!is_nonpositive(NaN));
}

#[test]
fn test_nonnegative() {
  assert(is_nonnegative(infinity));
  assert(is_nonnegative(1.));
  assert(is_nonnegative(0.));
  assert(!is_nonnegative(-1.));
  assert(!is_nonnegative(neg_infinity));
  assert(!is_nonnegative(1./neg_infinity));
  assert(!is_nonnegative(NaN));
}

#[test]
fn test_to_str_inf() {
    assert to_str(infinity, 10u) == "inf";
    assert to_str(-infinity, 10u) == "-inf";
}

//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//

<|endoftext|>