<commit_before>use std::fmt;
use std::default::Default;
use std::old_io::IoResult;
use std::old_io::stdio::{self, StdWriter};
use std::num::Int;
use board::{Board, Edge, Side};
use geom::{Geom, Point, UP, LEFT};
use term::{self, Terminal, StdTerminal};
use term::color::{self, Color};

#[derive(Copy, Debug, RustcDecodable)]
pub enum Mode {
    Ascii, Unicode
}
impl Default for Mode {
    fn default() -> Mode { Mode::Unicode }
}

pub struct Config {
    pub mode: Mode,
    pub is_cjk: bool,
    pub cell_width: usize,
    pub cell_height: usize
}

enum Output<T> {
    Pretty(Box<StdTerminal>),
    Raw(T)
}

fn side_to_color(ty: Option<Side>) -> (Color, Color) {
    match ty {
        Some(Side::In)  => (color::BRIGHT_YELLOW, color::BLACK),
        Some(Side::Out) => (color::BLACK,         color::BRIGHT_WHITE),
        None            => (color::BRIGHT_WHITE,  color::BLACK),
    }
}

struct Printer {
    output: Output<StdWriter>
}

impl Printer {
    fn new() -> Printer {
        let output = if stdio::stdout_raw().isatty() {
            match term::stdout() {
                Some(t) => Output::Pretty(t),
                None    => Output::Raw(stdio::stdout_raw())
            }
        } else {
            Output::Raw(stdio::stdout_raw())
        };
        Printer { output: output }
    }

    fn write_pretty(&mut self, ty: Option<Side>, s: &str) -> IoResult<()> {
        match self.output {
            Output::Pretty(ref mut term) => {
                let (bg, fg) = side_to_color(ty);
                try!(term.fg(fg));
                try!(term.bg(bg));
                try!(term.write_all(s.as_bytes()));
                try!(term.reset());
                Ok(())
            }
            Output::Raw(ref mut stdout) => stdout.write_all(s.as_bytes())
        }
    }
    fn write_pretty_fmt(&mut self, ty: Option<Side>, fmt: fmt::Arguments) -> IoResult<()> {
        match self.output {
            Output::Pretty(ref mut term) => {
                let (bg, fg) = side_to_color(ty);
                try!(term.fg(fg));
                try!(term.bg(bg));
                try!(term.write_fmt(fmt));
                try!(term.reset());
                Ok(())
            }
            Output::Raw(ref mut stdout) => stdout.write_fmt(fmt)
        }
    }
    fn write_plain(&mut self, s: &str) -> IoResult<()> {
        match self.output {
            Output::Pretty(ref mut term) => term.write_all(s.as_bytes()),
            Output::Raw(ref mut stdout) => stdout.write_all(s.as_bytes())
        }
    }

    fn write_plain_fmt(&mut self, fmt: fmt::Arguments) -> IoResult<()> {
        match self.output {
            Output::Pretty(ref mut term) => term.write_fmt(fmt),
            Output::Raw(ref mut stdout) => stdout.write_fmt(fmt)
        }
    }
}

struct Table;
impl Table {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board)
              -> IoResult<()>
    {
        let row = board.row();
        try!(LabelRow::pprint(printer, conf, board));
        for y in (0 .. row) {
            try!(EdgeRow::pprint(printer, conf, board, y));
            try!(CellRow::pprint(printer, conf, board, y));
        }
        try!(EdgeRow::pprint(printer, conf, board, row));
        try!(LabelRow::pprint(printer, conf, board));
        Ok(())
    }
}

struct LabelRow;
impl LabelRow {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board)
              -> IoResult<()>
    {
        try!(printer.write_plain_fmt(
            format_args!("{:1$}", "", conf.cell_width)));
        for x in 0 .. board.column() {
            try!(printer.write_plain_fmt(
                format_args!("{:1$}", "", "─".width(conf.is_cjk))));
            try!(Label::pprint(printer, conf, x, true));
        }
        try!(printer.write_plain("\n"));
        Ok(())
   }
}

struct EdgeRow;
impl EdgeRow {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board, y: i32)
              -> IoResult<()>
    {
        let col = board.column();
        try!(printer.write_plain_fmt(
            format_args!("{:1$}", "", conf.cell_width)));
        for x in (0 .. col) {
            try!(Corner::pprint(printer, conf, board, Point(y, x)));
            try!(EdgeH::pprint(printer, conf, board, Point(y, x)));
        }
        try!(Corner::pprint(printer, conf, board, Point(y, col)));
        try!(printer.write_plain("\n"));
        Ok(())
    }
}

struct CellRow;
impl CellRow {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board, y: i32) -> IoResult<()> {
        let col = board.column();
        for i in (0 .. conf.cell_height) {
            let num_line = (conf.cell_height - 1) / 2 == i;
            try!(Label::pprint(printer, conf, y, num_line));
            for x in (0 .. col) {
                try!(EdgeV::pprint(printer, conf, board, Point(y, x)));
                try!(Cell::pprint(printer, conf, board, Point(y, x), num_line));
            }
            try!(EdgeV::pprint(printer, conf, board, Point(y, col)));
            try!(Label::pprint(printer, conf, y, num_line));
            try!(printer.write_plain("\n"));
        }
        Ok(())
    }
}

struct Corner;
impl Corner {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board, p: Point)
              -> IoResult<()>
    {
        let l = p + LEFT;
        let u = p + UP;
        let eh_p = board.edge_h()[p];
        let eh_l = board.edge_h()[l];
        let ev_p = board.edge_v()[p];
        let ev_u = board.edge_v()[u];

        let is_same_all =
            (eh_p == Some(Edge::Cross)) &&
            (eh_l == Some(Edge::Cross)) &&
            (ev_p == Some((Edge::Cross))) &&
            (ev_u == Some((Edge::Cross)));

        let ty = if is_same_all {
            board.side()[p]
        } else {
            None
        };
        let is_h = eh_p == Some(Edge::Line) &&
            eh_l == Some(Edge::Line);
        let is_v = ev_p == Some(Edge::Line) &&
            ev_u == Some(Edge::Line);

        match conf.mode {
            Mode::Ascii => {
                if is_same_all {
                    try!(printer.write_pretty(ty, "."));
                } else if is_h {
                    try!(printer.write_pretty(ty, "-"));
                } else if is_v {
                    try!(printer.write_pretty(ty, "|"));
                } else {
                    try!(printer.write_pretty(ty, "+"));
                }
            }
            Mode::Unicode => {
                let width = '┼'.width(conf.is_cjk).unwrap();
                if is_same_all {
                    for _ in (0 .. width) {
                        try!(printer.write_pretty(ty, " "));
                    }
                } else if is_h {
                    try!(printer.write_pretty(ty, "─"));
                } else if is_v {
                    try!(printer.write_pretty(ty, "│"));
                } else if eh_p == Some(Edge::Line) && ev_p == Some(Edge::Line) {
                    try!(printer.write_pretty(ty, "┌"));
                } else if eh_l == Some(Edge::Line) && ev_p == Some(Edge::Line) {
                    try!(printer.write_pretty(ty, "┐"));
                } else if eh_l == Some(Edge::Line) && ev_u == Some(Edge::Line) {
                    try!(printer.write_pretty(ty, "┘"));
                } else if eh_p == Some(Edge::Line) && ev_u == Some(Edge::Line) {
                    try!(printer.write_pretty(ty, "└"));
                } else {
                    try!(printer.write_pretty(ty, "┼"));
                }
            }
        }
        Ok(())
    }
}

struct EdgeH;
impl EdgeH {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board, p: Point)
              -> IoResult<()>
    {
        match conf.mode {
            Mode::Ascii => {
                let (s, ty) = match board.edge_h()[p] {
                    Some(Edge::Cross) => (" ", board.side()[p]),
                    Some(Edge::Line)  => ("-", None),
                    None => ("~", None)
                };
                for _ in (0 .. conf.cell_width) {
                    try!(printer.write_pretty(ty, s));
                }
            }
            Mode::Unicode => {
                let (s, ty) = match board.edge_h()[p] {
                    Some(Edge::Cross) => (" ", board.side()[p]),
                    Some(Edge::Line)  => ("─", None),
                    None => ("~", None)
                };
                let w = s.width(conf.is_cjk);
                for _ in (0 .. (conf.cell_width + w - 1) / w) {
                    try!(printer.write_pretty(ty, s));
                }
            }
        }
        Ok(())
    }
}

struct Label;
impl Label {
    fn pprint(printer: &mut Printer, conf: &Config, n: i32, num_line: bool)
              -> IoResult<()>
    {
        if num_line {
            let order = 10.pow(conf.cell_width);
            try!(printer.write_plain_fmt(
                format_args!("{:^1$}", n % order, conf.cell_width)));
        } else {
            try!(printer.write_plain_fmt(
                format_args!("{:1$}", "", conf.cell_width)));
        }
        Ok(())
    }
}

struct EdgeV;
impl EdgeV {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board, p: Point)
              -> IoResult<()>
    {
        match conf.mode {
            Mode::Ascii => {
                let (s, ty) = match board.edge_v()[p] {
                    Some(Edge::Cross) => (" ", board.side()[p]),
                    Some(Edge::Line)  => ("|", None),
                    None => ("?", None)
                };
                try!(printer.write_pretty(ty, s));
            }
            Mode::Unicode => {
                let width = "│".width(conf.is_cjk);
                let (s, ty) = match board.edge_v()[p] {
                    Some(Edge::Cross) => (" ", board.side()[p]),
                    Some(Edge::Line)  => ("│", None),
                    None => ("/", None)
                };
                for _ in (0 .. width / s.width(conf.is_cjk)) {
                    try!(printer.write_pretty(ty, s));
                }
            }
        }
        Ok(())
    }
}

struct Cell;
impl Cell {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board, p: Point,
              num_line: bool)
              -> IoResult<()>
    {
        let ty = board.side()[p];
        match board[p] {
            Some(x) if num_line => {
                try!(printer.write_pretty_fmt(
                    ty, format_args!("{:^1$}", x, conf.cell_width)));
            },
            _ => {
                try!(printer.write_pretty_fmt(
                    ty, format_args!("{:^1$}", "", conf.cell_width)));
            }
        };
        Ok(())
    }
}

pub fn print(conf: &Config, board: &Board) -> IoResult<()> {
    Table::pprint(&mut Printer::new(), conf, board)
}
<commit_msg>update to rustc 1.0.0-nightly (157614249 2015-03-01) (built 2015-03-02)<commit_after>use std::fmt;
use std::default::Default;
use std::old_io::IoResult;
use std::old_io::stdio::{self, StdWriter};
use std::num::Int;
use board::{Board, Edge, Side};
use geom::{Geom, Point, UP, LEFT};
use term::{self, Terminal, StdTerminal};
use term::color::{self, Color};

#[derive(Copy, Debug, RustcDecodable)]
pub enum Mode {
    Ascii, Unicode
}
impl Default for Mode {
    fn default() -> Mode { Mode::Unicode }
}

pub struct Config {
    pub mode: Mode,
    pub is_cjk: bool,
    pub cell_width: usize,
    pub cell_height: usize
}

enum Output<T> {
    Pretty(Box<StdTerminal>),
    Raw(T)
}

fn side_to_color(ty: Option<Side>) -> (Color, Color) {
    match ty {
        Some(Side::In)  => (color::BRIGHT_YELLOW, color::BLACK),
        Some(Side::Out) => (color::BLACK,         color::BRIGHT_WHITE),
        None            => (color::BRIGHT_WHITE,  color::BLACK),
    }
}

struct Printer {
    output: Output<StdWriter>
}

impl Printer {
    fn new() -> Printer {
        let output = if stdio::stdout_raw().isatty() {
            match term::stdout() {
                Some(t) => Output::Pretty(t),
                None    => Output::Raw(stdio::stdout_raw())
            }
        } else {
            Output::Raw(stdio::stdout_raw())
        };
        Printer { output: output }
    }

    fn write_pretty(&mut self, ty: Option<Side>, s: &str) -> IoResult<()> {
        match self.output {
            Output::Pretty(ref mut term) => {
                let (bg, fg) = side_to_color(ty);
                try!(term.fg(fg));
                try!(term.bg(bg));
                try!(term.write_all(s.as_bytes()));
                try!(term.reset());
                Ok(())
            }
            Output::Raw(ref mut stdout) => stdout.write_all(s.as_bytes())
        }
    }
    fn write_pretty_fmt(&mut self, ty: Option<Side>, fmt: fmt::Arguments) -> IoResult<()> {
        match self.output {
            Output::Pretty(ref mut term) => {
                let (bg, fg) = side_to_color(ty);
                try!(term.fg(fg));
                try!(term.bg(bg));
                try!(term.write_fmt(fmt));
                try!(term.reset());
                Ok(())
            }
            Output::Raw(ref mut stdout) => stdout.write_fmt(fmt)
        }
    }
    fn write_plain(&mut self, s: &str) -> IoResult<()> {
        match self.output {
            Output::Pretty(ref mut term) => term.write_all(s.as_bytes()),
            Output::Raw(ref mut stdout) => stdout.write_all(s.as_bytes())
        }
    }

    fn write_plain_fmt(&mut self, fmt: fmt::Arguments) -> IoResult<()> {
        match self.output {
            Output::Pretty(ref mut term) => term.write_fmt(fmt),
            Output::Raw(ref mut stdout) => stdout.write_fmt(fmt)
        }
    }
}

struct Table;
impl Table {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board)
              -> IoResult<()>
    {
        let row = board.row();
        try!(LabelRow::pprint(printer, conf, board));
        for y in (0 .. row) {
            try!(EdgeRow::pprint(printer, conf, board, y));
            try!(CellRow::pprint(printer, conf, board, y));
        }
        try!(EdgeRow::pprint(printer, conf, board, row));
        try!(LabelRow::pprint(printer, conf, board));
        Ok(())
    }
}

struct LabelRow;
impl LabelRow {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board)
              -> IoResult<()>
    {
        try!(printer.write_plain_fmt(
            format_args!("{:1$}", "", conf.cell_width)));
        for x in 0 .. board.column() {
            try!(printer.write_plain_fmt(
                format_args!("{:1$}", "", "─".width(conf.is_cjk))));
            try!(Label::pprint(printer, conf, x, true));
        }
        try!(printer.write_plain("\n"));
        Ok(())
   }
}

struct EdgeRow;
impl EdgeRow {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board, y: i32)
              -> IoResult<()>
    {
        let col = board.column();
        try!(printer.write_plain_fmt(
            format_args!("{:1$}", "", conf.cell_width)));
        for x in (0 .. col) {
            try!(Corner::pprint(printer, conf, board, Point(y, x)));
            try!(EdgeH::pprint(printer, conf, board, Point(y, x)));
        }
        try!(Corner::pprint(printer, conf, board, Point(y, col)));
        try!(printer.write_plain("\n"));
        Ok(())
    }
}

struct CellRow;
impl CellRow {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board, y: i32) -> IoResult<()> {
        let col = board.column();
        for i in (0 .. conf.cell_height) {
            let num_line = (conf.cell_height - 1) / 2 == i;
            try!(Label::pprint(printer, conf, y, num_line));
            for x in (0 .. col) {
                try!(EdgeV::pprint(printer, conf, board, Point(y, x)));
                try!(Cell::pprint(printer, conf, board, Point(y, x), num_line));
            }
            try!(EdgeV::pprint(printer, conf, board, Point(y, col)));
            try!(Label::pprint(printer, conf, y, num_line));
            try!(printer.write_plain("\n"));
        }
        Ok(())
    }
}

struct Corner;
impl Corner {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board, p: Point)
              -> IoResult<()>
    {
        let l = p + LEFT;
        let u = p + UP;
        let eh_p = board.edge_h()[p];
        let eh_l = board.edge_h()[l];
        let ev_p = board.edge_v()[p];
        let ev_u = board.edge_v()[u];

        let is_same_all =
            (eh_p == Some(Edge::Cross)) &&
            (eh_l == Some(Edge::Cross)) &&
            (ev_p == Some((Edge::Cross))) &&
            (ev_u == Some((Edge::Cross)));

        let ty = if is_same_all {
            board.side()[p]
        } else {
            None
        };
        let is_h = eh_p == Some(Edge::Line) &&
            eh_l == Some(Edge::Line);
        let is_v = ev_p == Some(Edge::Line) &&
            ev_u == Some(Edge::Line);

        match conf.mode {
            Mode::Ascii => {
                if is_same_all {
                    try!(printer.write_pretty(ty, "."));
                } else if is_h {
                    try!(printer.write_pretty(ty, "-"));
                } else if is_v {
                    try!(printer.write_pretty(ty, "|"));
                } else {
                    try!(printer.write_pretty(ty, "+"));
                }
            }
            Mode::Unicode => {
                let width = '┼'.width(conf.is_cjk).unwrap();
                if is_same_all {
                    for _ in (0 .. width) {
                        try!(printer.write_pretty(ty, " "));
                    }
                } else if is_h {
                    try!(printer.write_pretty(ty, "─"));
                } else if is_v {
                    try!(printer.write_pretty(ty, "│"));
                } else if eh_p == Some(Edge::Line) && ev_p == Some(Edge::Line) {
                    try!(printer.write_pretty(ty, "┌"));
                } else if eh_l == Some(Edge::Line) && ev_p == Some(Edge::Line) {
                    try!(printer.write_pretty(ty, "┐"));
                } else if eh_l == Some(Edge::Line) && ev_u == Some(Edge::Line) {
                    try!(printer.write_pretty(ty, "┘"));
                } else if eh_p == Some(Edge::Line) && ev_u == Some(Edge::Line) {
                    try!(printer.write_pretty(ty, "└"));
                } else {
                    try!(printer.write_pretty(ty, "┼"));
                }
            }
        }
        Ok(())
    }
}

struct EdgeH;
impl EdgeH {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board, p: Point)
              -> IoResult<()>
    {
        match conf.mode {
            Mode::Ascii => {
                let (s, ty) = match board.edge_h()[p] {
                    Some(Edge::Cross) => (" ", board.side()[p]),
                    Some(Edge::Line)  => ("-", None),
                    None => ("~", None)
                };
                for _ in (0 .. conf.cell_width) {
                    try!(printer.write_pretty(ty, s));
                }
            }
            Mode::Unicode => {
                let (s, ty) = match board.edge_h()[p] {
                    Some(Edge::Cross) => (" ", board.side()[p]),
                    Some(Edge::Line)  => ("─", None),
                    None => ("~", None)
                };
                let w = s.width(conf.is_cjk);
                for _ in (0 .. (conf.cell_width + w - 1) / w) {
                    try!(printer.write_pretty(ty, s));
                }
            }
        }
        Ok(())
    }
}

struct Label;
impl Label {
    fn pprint(printer: &mut Printer, conf: &Config, n: i32, num_line: bool)
              -> IoResult<()>
    {
        if num_line {
            let order = 10.pow(conf.cell_width as u32);
            try!(printer.write_plain_fmt(
                format_args!("{:^1$}", n % order, conf.cell_width)));
        } else {
            try!(printer.write_plain_fmt(
                format_args!("{:1$}", "", conf.cell_width)));
        }
        Ok(())
    }
}

struct EdgeV;
impl EdgeV {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board, p: Point)
              -> IoResult<()>
    {
        match conf.mode {
            Mode::Ascii => {
                let (s, ty) = match board.edge_v()[p] {
                    Some(Edge::Cross) => (" ", board.side()[p]),
                    Some(Edge::Line)  => ("|", None),
                    None => ("?", None)
                };
                try!(printer.write_pretty(ty, s));
            }
            Mode::Unicode => {
                let width = "│".width(conf.is_cjk);
                let (s, ty) = match board.edge_v()[p] {
                    Some(Edge::Cross) => (" ", board.side()[p]),
                    Some(Edge::Line)  => ("│", None),
                    None => ("/", None)
                };
                for _ in (0 .. width / s.width(conf.is_cjk)) {
                    try!(printer.write_pretty(ty, s));
                }
            }
        }
        Ok(())
    }
}

struct Cell;
impl Cell {
    fn pprint(printer: &mut Printer, conf: &Config, board: &Board, p: Point,
              num_line: bool)
              -> IoResult<()>
    {
        let ty = board.side()[p];
        match board[p] {
            Some(x) if num_line => {
                try!(printer.write_pretty_fmt(
                    ty, format_args!("{:^1$}", x, conf.cell_width)));
            },
            _ => {
                try!(printer.write_pretty_fmt(
                    ty, format_args!("{:^1$}", "", conf.cell_width)));
            }
        };
        Ok(())
    }
}

pub fn print(conf: &Config, board: &Board) -> IoResult<()> {
    Table::pprint(&mut Printer::new(), conf, board)
}
<|endoftext|>


<commit_before>use solitaire::card::*;

use std::char;
use std::cmp;
use std::iter::range_inclusive;

#[deriving(PartialEq, Show)]
pub struct Deck {
    pub d: Vec<Card>,
}

impl Iterator<uint> for Deck {
    fn next(&mut self) -> Option<uint> {
        Some(self.gen_keystream_letter())
    }
}

impl Deck {
    pub fn new() -> Deck {
        let per_suit = 13;
        let mut deck = Deck { d: Vec::new() };
        for i in range_inclusive(1, per_suit) {
            deck.d.push(Clubs(i));
        }
        for i in range_inclusive(1, per_suit) {
            deck.d.push(Diamonds(i));
        }
        for i in range_inclusive(1, per_suit) {
            deck.d.push(Hearts(i));
        }
        for i in range_inclusive(1, per_suit) {
            deck.d.push(Spades(i));
        }

        deck.d.push(JokerA);
        deck.d.push(JokerB);
        return deck;
    }

    pub fn with_key(key: &str) -> Deck {
        let mut deck = Deck::new();
        let a = 'A' as uint - 1;
        let k = key.chars()
                   .filter(|x| char::is_alphabetic(*x))
                   .map(|x| char::to_uppercase(x))
                   .collect::<String>();
        for e in k.as_bytes().iter() {
            deck.with_key_helper(*e as uint - a);
        }

        return deck;
    }

    fn with_key_helper(&mut self, i: uint) {
        self.move_joker(JokerA, 1);
        self.move_joker(JokerB, 2);
        self.triple_cut();
        self.count_cut();
        let mut new = Vec::with_capacity(self.d.len());
        new.push_all(self.d.slice(i, self.d.len()-1));
        new.push_all(self.d.slice(0, i));
        new.push(*self.d.last().unwrap());
        self.d = new;
    }

    pub fn encrypt(&mut self, plain: &str) -> String {
        let a = 'A' as u8;
        plain.chars().map(|x|
                          match char::is_alphabetic(x) {
                              true => (((x as u8 - a + self.gen_keystream_letter() as u8) % 26) + a) as char,
                              false => x,
                          }).collect::<String>()
    }

    pub fn gen_keystream_letter(&mut self) -> uint {
        self.move_joker(JokerA, 1);
        self.move_joker(JokerB, 2);
        self.triple_cut();
        let i = self.d.last().unwrap().count_index();
        self.count_cut(i);
        let i = self.d[0].count_index();
        let output_card = self.d[i];
        match output_card {
            Clubs(i) => i,
            Diamonds(i) => i + 13,
            Hearts(i) => i,
            Spades(i) => i + 13,
            _ => self.gen_keystream_letter(),
        }
    }

    pub fn move_joker(&mut self, j: Card, count: int) {
        let mut i = self.d.as_slice().position_elem(&j).unwrap();
        for _ in range(0i, count) {
            if i < self.d.len()-1 {
                self.d.as_mut_slice().swap(i, i+1);
            } else {
                // if card is the last card in the deck, move below the first card of the deck
                // every card needs to be moved... maybe this should have been a linked list
                let mut new = Vec::with_capacity(self.d.len());
                new.push(self.d[0]);
                new.push(*self.d.last().unwrap());
                new.push_all(self.d.slice(1, self.d.len()-1));
                self.d = new;
            }
            i = if i != self.d.len()-1 {
                i + 1
            } else {
                1
            };
        }
    }

    pub fn triple_cut(&mut self) {
        let mut new = Vec::with_capacity(self.d.len());
        let ai = self.d.as_slice().position_elem(&JokerA).unwrap();
        let bi = self.d.as_slice().position_elem(&JokerB).unwrap();
        let first = cmp::min(ai, bi);
        let secnd = cmp::max(ai, bi);
        new.push_all(self.d.slice(secnd+1, self.d.len()));
        new.push_all(self.d.slice(first, secnd + 1));
        new.push_all(self.d.slice(0, first));
        self.d = new;
    }

    pub fn count_cut(&mut self, c: uint) {
        // cut after c
        let mut new = Vec::with_capacity(self.d.len());
        for i in range(c, self.d.len()) {
            new.push(self.d[i]);
        }

        for i in range(0, c) {
            new.push(self.d[i]);
        }
        self.d = new;
    }

}

#[test]
fn new_deck() {
    let d = Deck::new();
    assert_eq!(d, Deck { d: vec![Clubs(1), Clubs(2), Clubs(3), Clubs(4), Clubs(5), Clubs(6), Clubs(7), Clubs(8), Clubs(9), Clubs(10), Clubs(11), Clubs(12), Clubs(13), Diamonds(1), Diamonds(2), Diamonds(3), Diamonds(4), Diamonds(5), Diamonds(6), Diamonds(7), Diamonds(8), Diamonds(9), Diamonds(10), Diamonds(11), Diamonds(12), Diamonds(13), Hearts(1), Hearts(2), Hearts(3), Hearts(4), Hearts(5), Hearts(6), Hearts(7), Hearts(8), Hearts(9), Hearts(10), Hearts(11), Hearts(12), Hearts(13), Spades(1), Spades(2), Spades(3), Spades(4), Spades(5), Spades(6), Spades(7), Spades(8), Spades(9), Spades(10), Spades(11), Spades(12), Spades(13), JokerA, JokerB] });
}

#[test]
fn move_joker() {
    let mut d = Deck{ d: vec![Clubs(1), Clubs(2), JokerA] };
    d.move_joker(JokerA, 1);
    assert_eq!(d.d, vec![Clubs(1), JokerA, Clubs(2)]);

    let mut d = Deck{ d: vec![Clubs(1), Clubs(2), Hearts(3), JokerA, JokerB] };
    d.move_joker(JokerA, 1);
    d.move_joker(JokerB, 2);
    assert_eq!(d.d, vec![Clubs(1), JokerB, Clubs(2), Hearts(3), JokerA]);
}

#[test]
fn triple_cut() {
    let tests = vec![
        (vec![Clubs(1), JokerA, Clubs(2), JokerB, Clubs(3)], vec![Clubs(3), JokerA, Clubs(2), JokerB, Clubs(1)]),
        (vec![Clubs(1), Hearts(1), JokerA, Clubs(2), JokerB, Clubs(3), Hearts(3)], vec![Clubs(3), Hearts(3), JokerA, Clubs(2), JokerB, Clubs(1), Hearts(1)]),
        (vec![JokerA, JokerB], vec![JokerA, JokerB]),
        ];

    for test in tests.iter() {
        let (initial, expect) = test.clone();
        let mut got = Deck{ d: initial };
        got.triple_cut();
        assert_eq!(got.d, expect);
    }
}

#[test]
fn gen_keystream_letter() {
    let mut d = Deck::new();
    let expects = vec![4, 49, 10, 24, 8, 51, 44, 6, 4, 33];
    for e in expects.iter() {
        assert_eq!(d.gen_keystream_letter(), *e);
    }
}

#[test]
fn count_cut() {
    let mut d = Deck{ d: vec![Clubs(7), Clubs(3), Clubs(13), Clubs(14), Clubs(15), Clubs(16), Clubs(17), Clubs(18), Clubs(4), Clubs(5), Clubs(8), Clubs(9)]};
    let expect = Deck{ d: vec![Clubs(5), Clubs(8), Clubs(7), Clubs(3), Clubs(13), Clubs(14), Clubs(15), Clubs(16), Clubs(17), Clubs(18), Clubs(4), Clubs(9)] };
    d.count_cut();
    assert_eq!(d, expect);
}

#[test]
fn key() {
    let mut d = Deck::with_key("FOO");
    let expects = vec![8, 19, 7, 25, 20, 9, 8, 22, 32, 43, 5, 26, 17, 38, 48];
    for e in expects.iter() {
        assert_eq!(d.gen_keystream_letter(), *e);
    }
}
<commit_msg>Fix so gen_keystream_letter test passes<commit_after>use solitaire::card::*;

use std::char;
use std::cmp;
use std::iter::range_inclusive;

#[deriving(PartialEq, Show)]
pub struct Deck {
    pub d: Vec<Card>,
}

impl Iterator<uint> for Deck {
    fn next(&mut self) -> Option<uint> {
        Some(self.gen_keystream_letter())
    }
}

impl Deck {
    pub fn new() -> Deck {
        let per_suit = 13;
        let mut deck = Deck { d: Vec::new() };
        for i in range_inclusive(1, per_suit) {
            deck.d.push(Clubs(i));
        }
        for i in range_inclusive(1, per_suit) {
            deck.d.push(Diamonds(i));
        }
        for i in range_inclusive(1, per_suit) {
            deck.d.push(Hearts(i));
        }
        for i in range_inclusive(1, per_suit) {
            deck.d.push(Spades(i));
        }

        deck.d.push(JokerA);
        deck.d.push(JokerB);
        return deck;
    }

    pub fn with_key(key: &str) -> Deck {
        let mut deck = Deck::new();
        let a = 'A' as uint - 1;
        let k = key.chars()
                   .filter(|x| char::is_alphabetic(*x))
                   .map(|x| char::to_uppercase(x))
                   .collect::<String>();
        for e in k.as_bytes().iter() {
            deck.with_key_helper(*e as uint - a);
        }

        return deck;
    }

    fn with_key_helper(&mut self, i: uint) {
        self.move_joker(JokerA, 1);
        self.move_joker(JokerB, 2);
        self.triple_cut();
        self.count_cut();
        let mut new = Vec::with_capacity(self.d.len());
        new.push_all(self.d.slice(i, self.d.len()-1));
        new.push_all(self.d.slice(0, i));
        new.push(*self.d.last().unwrap());
        self.d = new;
    }

    pub fn encrypt(&mut self, plain: &str) -> String {
        let a = 'A' as u8;
        plain.chars().map(|x|
                          match char::is_alphabetic(x) {
                              true => (((x as u8 - a + self.gen_keystream_letter() as u8) % 26) + a) as char,
                              false => x,
                          }).collect::<String>()
    }

    pub fn gen_keystream_letter(&mut self) -> uint {
        self.move_joker(JokerA, 1);
        self.move_joker(JokerB, 2);
        self.triple_cut();
        self.count_cut();
        let i = self.d[0].count_index();
        match self.d[i].count_index() {
            53 => self.gen_keystream_letter(),
            i => i,
        }
    }

    pub fn move_joker(&mut self, j: Card, count: int) {
        let mut i = self.d.as_slice().position_elem(&j).unwrap();
        for _ in range(0i, count) {
            if i < self.d.len()-1 {
                self.d.as_mut_slice().swap(i, i+1);
            } else {
                // if card is the last card in the deck, move below the first card of the deck
                // every card needs to be moved... maybe this should have been a linked list
                let mut new = Vec::with_capacity(self.d.len());
                new.push(self.d[0]);
                new.push(*self.d.last().unwrap());
                new.push_all(self.d.slice(1, self.d.len()-1));
                self.d = new;
            }
            i = if i != self.d.len()-1 {
                i + 1
            } else {
                1
            };
        }
    }

    pub fn triple_cut(&mut self) {
        let mut new = Vec::with_capacity(self.d.len());
        let ai = self.d.as_slice().position_elem(&JokerA).unwrap();
        let bi = self.d.as_slice().position_elem(&JokerB).unwrap();
        let first = cmp::min(ai, bi);
        let secnd = cmp::max(ai, bi);
        new.push_all(self.d.slice(secnd+1, self.d.len()));
        new.push_all(self.d.slice(first, secnd + 1));
        new.push_all(self.d.slice(0, first));
        self.d = new;
    }

    pub fn count_cut(&mut self) {
        // cut after c
        let i = self.d.last().unwrap().count_index();
        let mut new = Vec::with_capacity(self.d.len());
        new.push_all(self.d.slice(i, self.d.len()-1));
        new.push_all(self.d.slice(0, i));
        new.push(*self.d.last().unwrap());
        self.d = new;
    }

}

#[test]
fn new_deck() {
    let d = Deck::new();
    assert_eq!(d, Deck { d: vec![Clubs(1), Clubs(2), Clubs(3), Clubs(4), Clubs(5), Clubs(6), Clubs(7), Clubs(8), Clubs(9), Clubs(10), Clubs(11), Clubs(12), Clubs(13), Diamonds(1), Diamonds(2), Diamonds(3), Diamonds(4), Diamonds(5), Diamonds(6), Diamonds(7), Diamonds(8), Diamonds(9), Diamonds(10), Diamonds(11), Diamonds(12), Diamonds(13), Hearts(1), Hearts(2), Hearts(3), Hearts(4), Hearts(5), Hearts(6), Hearts(7), Hearts(8), Hearts(9), Hearts(10), Hearts(11), Hearts(12), Hearts(13), Spades(1), Spades(2), Spades(3), Spades(4), Spades(5), Spades(6), Spades(7), Spades(8), Spades(9), Spades(10), Spades(11), Spades(12), Spades(13), JokerA, JokerB] });
}

#[test]
fn move_joker() {
    let mut d = Deck{ d: vec![Clubs(1), Clubs(2), JokerA] };
    d.move_joker(JokerA, 1);
    assert_eq!(d.d, vec![Clubs(1), JokerA, Clubs(2)]);

    let mut d = Deck{ d: vec![Clubs(1), Clubs(2), Hearts(3), JokerA, JokerB] };
    d.move_joker(JokerA, 1);
    d.move_joker(JokerB, 2);
    assert_eq!(d.d, vec![Clubs(1), JokerB, Clubs(2), Hearts(3), JokerA]);
}

#[test]
fn triple_cut() {
    let tests = vec![
        (vec![Clubs(1), JokerA, Clubs(2), JokerB, Clubs(3)], vec![Clubs(3), JokerA, Clubs(2), JokerB, Clubs(1)]),
        (vec![Clubs(1), Hearts(1), JokerA, Clubs(2), JokerB, Clubs(3), Hearts(3)], vec![Clubs(3), Hearts(3), JokerA, Clubs(2), JokerB, Clubs(1), Hearts(1)]),
        (vec![JokerA, JokerB], vec![JokerA, JokerB]),
        ];

    for test in tests.iter() {
        let (initial, expect) = test.clone();
        let mut got = Deck{ d: initial };
        got.triple_cut();
        assert_eq!(got.d, expect);
    }
}

#[test]
fn gen_keystream_letter() {
    let mut d = Deck::new();
    let expects = vec![4, 49, 10, 24, 8, 51, 44, 6, 4, 33];
    for e in expects.iter() {
        assert_eq!(d.gen_keystream_letter(), *e);
    }
}

#[test]
fn count_cut() {
    let mut d = Deck{ d: vec![Clubs(7), Clubs(3), Clubs(13), Clubs(14), Clubs(15), Clubs(16), Clubs(17), Clubs(18), Clubs(4), Clubs(5), Clubs(8), Clubs(9)]};
    let expect = Deck{ d: vec![Clubs(5), Clubs(8), Clubs(7), Clubs(3), Clubs(13), Clubs(14), Clubs(15), Clubs(16), Clubs(17), Clubs(18), Clubs(4), Clubs(9)] };
    d.count_cut();
    assert_eq!(d, expect);
}

#[test]
fn key() {
    let mut d = Deck::with_key("FOO");
    let expects = vec![8, 19, 7, 25, 20, 9, 8, 22, 32, 43, 5, 26, 17, 38, 48];
    for e in expects.iter() {
        assert_eq!(d.gen_keystream_letter(), *e);
    }
}
<|endoftext|>


<commit_before>use rand::{thread_rng, Rng};

#[derive(Debug, Copy, Clone)]
pub enum TerrainType {
	Water,
	Grass,
	TallGrass,
	Sand,
	Snow,
	Tundra
}

#[derive(Debug)]
pub struct Tile {
	typ:TerrainType,
}

pub struct Terrain {
	data:Vec<Tile>,
}

impl Terrain {
	pub fn new(size:usize) -> Terrain {
		// create the terrain data
		let mut terrain = Terrain {
			data:Vec::with_capacity(size*size),
		};

		// fill up the terrain with random tiles
		let choices = [
			TerrainType::Water,
			TerrainType::Grass,
			TerrainType::TallGrass,
			TerrainType::Sand,
			TerrainType::Snow,
			TerrainType::Tundra
		];
		let mut rng = thread_rng();
		for n in 0..(size*size) {
			terrain.data.push(Tile { typ:*rng.choose(&choices).unwrap() });
		}

		println!("Terrain: {:?}",terrain.data);

		terrain
	}
}<commit_msg>Add height to the struct<commit_after>use rand::{thread_rng, Rng};

#[derive(Debug, Copy, Clone)]
pub enum TerrainType {
	Water,
	Grass,
	TallGrass,
	Sand,
	Snow,
	Tundra
}

#[derive(Debug)]
pub struct Tile {
	typ:TerrainType,
	height:u16,
}

pub struct Terrain {
	data:Vec<Tile>,
}

impl Terrain {
	pub fn new(size:usize) -> Terrain {
		// create the terrain data
		let mut terrain = Terrain {
			data:Vec::with_capacity(size*size),
		};

		// fill up the terrain with random tiles
		let choices = [
			TerrainType::Water,
			TerrainType::Grass,
			TerrainType::TallGrass,
			TerrainType::Sand,
			TerrainType::Snow,
			TerrainType::Tundra
		];
		let mut rng = thread_rng();
		for n in 0..(size*size) {
			terrain.data.push(Tile { typ:*rng.choose(&choices).unwrap(), height:0 });
		}

		println!("Terrain: {:?}",terrain.data);

		terrain
	}
}<|endoftext|>


<commit_before>use std::io;
use super::{
    Deserialize, Error, ValueType, VarUint32, CountedList, Opcodes,
    Serialize, CountedWriter, CountedListWriter,
};

/// Function signature (type reference)
pub struct Func(u32);

impl Func {
    /// New function signature
    pub fn new(type_ref: u32) -> Self { Func(type_ref) }

    /// Function signature type reference.
    pub fn type_ref(&self) -> u32 {
        self.0
    }
}

/// Local definition inside the function body.
pub struct Local {
    count: u32,
    value_type: ValueType,
}

impl Local {
    /// New local with `count` and `value_type`.
    pub fn new(count: u32, value_type: ValueType) -> Self {
        Local { count: count, value_type: value_type }
    }

    /// Number of locals with the shared type.
    pub fn count(&self) -> u32 { self.count }

    /// Type of the locals.
    pub fn value_type(&self) -> ValueType { self.value_type }
}

impl Deserialize for Local {
     type Error = Error;

    fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
        let count = VarUint32::deserialize(reader)?;
        let value_type = ValueType::deserialize(reader)?;
        Ok(Local { count: count.into(), value_type: value_type })
    }
}

impl Serialize for Local {
    type Error = Error;

    fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
        VarUint32::from(self.count).serialize(writer)?;
        self.value_type.serialize(writer)?;
        Ok(())
    }
}

/// Function body definition.
pub struct FuncBody {
    locals: Vec<Local>,
    opcodes: Opcodes,
}

impl FuncBody {
    /// New function body with given `locals` and `opcodes`
    pub fn new(locals: Vec<Local>, opcodes: Opcodes) -> Self {
        FuncBody { locals: locals, opcodes: opcodes }
    }

    /// List of individual opcodes
    pub fn empty() -> Self {
        FuncBody { locals: Vec::new(), opcodes: Opcodes::empty() }
    }

    /// Locals declared in function body.
    pub fn locals(&self) -> &[Local] { &self.locals }

    /// Opcode sequence of the function body. Minimal opcode sequence
    /// is just `&[Opcode::End]`
    pub fn code(&self) -> &Opcodes { &self.opcodes }

    /// Locals declared in function body (mutable).
    pub fn locals_mut(&mut self) -> &mut Vec<Local> { &mut self.locals }

    /// Opcode sequence of the function body (mutable).
    pub fn code_mut(&mut self) -> &mut Opcodes { &mut self.opcodes }
}

impl Deserialize for FuncBody {
     type Error = Error;

    fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
        // todo: maybe use reader.take(section_length)
        let _body_size = VarUint32::deserialize(reader)?;
        let locals: Vec<Local> = CountedList::deserialize(reader)?.into_inner();
        let opcodes = Opcodes::deserialize(reader)?;
        Ok(FuncBody { locals: locals, opcodes: opcodes })
    }
}

impl Serialize for FuncBody {
    type Error = Error;

    fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
        let mut counted_writer = CountedWriter::new(writer);

        let data = self.locals;
        let counted_list = CountedListWriter::<Local, _>(
            data.len(),
            data.into_iter().map(Into::into),
        );
        counted_list.serialize(&mut counted_writer)?;

        let code = self.opcodes;
        code.serialize(&mut counted_writer)?;

        counted_writer.done()?;

        Ok(())
    }
}<commit_msg>mutable typeref<commit_after>use std::io;
use super::{
    Deserialize, Error, ValueType, VarUint32, CountedList, Opcodes,
    Serialize, CountedWriter, CountedListWriter,
};

/// Function signature (type reference)
pub struct Func(u32);

impl Func {
    /// New function signature
    pub fn new(type_ref: u32) -> Self { Func(type_ref) }

    /// Function signature type reference.
    pub fn type_ref(&self) -> u32 {
        self.0
    }

    /// Function signature type reference (mutable).
    pub fn type_ref_mut(&mut self) -> &mut u32 {
        &mut self.0
    }
}

/// Local definition inside the function body.
pub struct Local {
    count: u32,
    value_type: ValueType,
}

impl Local {
    /// New local with `count` and `value_type`.
    pub fn new(count: u32, value_type: ValueType) -> Self {
        Local { count: count, value_type: value_type }
    }

    /// Number of locals with the shared type.
    pub fn count(&self) -> u32 { self.count }

    /// Type of the locals.
    pub fn value_type(&self) -> ValueType { self.value_type }
}

impl Deserialize for Local {
     type Error = Error;

    fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
        let count = VarUint32::deserialize(reader)?;
        let value_type = ValueType::deserialize(reader)?;
        Ok(Local { count: count.into(), value_type: value_type })
    }
}

impl Serialize for Local {
    type Error = Error;

    fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
        VarUint32::from(self.count).serialize(writer)?;
        self.value_type.serialize(writer)?;
        Ok(())
    }
}

/// Function body definition.
pub struct FuncBody {
    locals: Vec<Local>,
    opcodes: Opcodes,
}

impl FuncBody {
    /// New function body with given `locals` and `opcodes`
    pub fn new(locals: Vec<Local>, opcodes: Opcodes) -> Self {
        FuncBody { locals: locals, opcodes: opcodes }
    }

    /// List of individual opcodes
    pub fn empty() -> Self {
        FuncBody { locals: Vec::new(), opcodes: Opcodes::empty() }
    }

    /// Locals declared in function body.
    pub fn locals(&self) -> &[Local] { &self.locals }

    /// Opcode sequence of the function body. Minimal opcode sequence
    /// is just `&[Opcode::End]`
    pub fn code(&self) -> &Opcodes { &self.opcodes }

    /// Locals declared in function body (mutable).
    pub fn locals_mut(&mut self) -> &mut Vec<Local> { &mut self.locals }

    /// Opcode sequence of the function body (mutable).
    pub fn code_mut(&mut self) -> &mut Opcodes { &mut self.opcodes }
}

impl Deserialize for FuncBody {
     type Error = Error;

    fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
        // todo: maybe use reader.take(section_length)
        let _body_size = VarUint32::deserialize(reader)?;
        let locals: Vec<Local> = CountedList::deserialize(reader)?.into_inner();
        let opcodes = Opcodes::deserialize(reader)?;
        Ok(FuncBody { locals: locals, opcodes: opcodes })
    }
}

impl Serialize for FuncBody {
    type Error = Error;

    fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
        let mut counted_writer = CountedWriter::new(writer);

        let data = self.locals;
        let counted_list = CountedListWriter::<Local, _>(
            data.len(),
            data.into_iter().map(Into::into),
        );
        counted_list.serialize(&mut counted_writer)?;

        let code = self.opcodes;
        code.serialize(&mut counted_writer)?;

        counted_writer.done()?;

        Ok(())
    }
}<|endoftext|>


<commit_before>use std::default::Default;

use cgmath::transform::Transform3D;
use cgmath::quaternion::Quat;
use cgmath::vector::Vec3;
use cgmath::matrix::{Mat4, ToMat4, Matrix};

use OpenCL::hl::{Device, Context, CommandQueue, Program, Kernel};
use OpenCL::mem::CLBuffer;
use OpenCL::CL::CL_MEM_READ_WRITE;

use time::precise_time_ns;

static opencl_program: &'static str = "
struct q4 {
    float s, x, y, z;
};

struct f4 {
    float x, y, z, w;
};

struct f3 {
    float x, y, z;
};

typedef struct q4 q4;
typedef struct f4 f4;
typedef struct f3 f3;

struct mat4 {
    f4 x, y, z, w;
};

struct transform
{
    q4 rot;
    f3 pos;
    float scale;
    int parent;
    int padd[3];
};

typedef struct mat4 Mat4;
typedef struct transform Transform3D;

#define DOT(OUT, A, B, i, j) \
    OUT.j.i = A.x.i * B.j.x + \
    A.y.i * B.j.y + \
    A.z.i * B.j.z + \
    A.w.i * B.j.w

Mat4
mult_m(const Mat4 a, const Mat4 b)
{
    Mat4 out;

    DOT(out, a, b, x, x);
    DOT(out, a, b, x, y);
    DOT(out, a, b, x, z);
    DOT(out, a, b, x, w);

    DOT(out, a, b, y, x);
    DOT(out, a, b, y, y);
    DOT(out, a, b, y, z);
    DOT(out, a, b, y, w);

    DOT(out, a, b, z, x);
    DOT(out, a, b, z, y);
    DOT(out, a, b, z, z);
    DOT(out, a, b, z, w);

    DOT(out, a, b, w, x);
    DOT(out, a, b, w, y);
    DOT(out, a, b, w, z);
    DOT(out, a, b, w, w);

    return out;
}

Mat4
transform_to_mat4(const Transform3D trans)
{
    Mat4 mat;

    float x2 = trans.rot.x + trans.rot.x;
    float y2 = trans.rot.y + trans.rot.y;
    float z2 = trans.rot.z + trans.rot.z;

    float xx2 = x2 * trans.rot.x;
    float xy2 = x2 * trans.rot.y;
    float xz2 = x2 * trans.rot.z;

    float yy2 = y2 * trans.rot.y;
    float yz2 = y2 * trans.rot.z;
    float zz2 = z2 * trans.rot.z;

    float sy2 = y2 * trans.rot.s;
    float sz2 = z2 * trans.rot.s;
    float sx2 = x2 * trans.rot.s;

    mat.x.x = (1. - yy2 - zz2) * trans.scale;
    mat.x.y = (xy2 + sz2) * trans.scale;
    mat.x.z = (xz2 - sy2) * trans.scale;
    mat.x.w = 0.;

    mat.y.x = (xy2 - sz2) * trans.scale;
    mat.y.y = (1. - xx2 - zz2) * trans.scale;
    mat.y.z = (yz2 + sx2) * trans.scale;
    mat.y.w = 0.;

    mat.z.x = (xy2 + sy2) * trans.scale;
    mat.z.y = (yz2 - sx2) * trans.scale;
    mat.z.z = (1. - xx2 - yy2) * trans.scale;
    mat.z.w = 0.;

    mat.w.x = trans.pos.x;
    mat.w.y = trans.pos.y;
    mat.w.z = trans.pos.z;
    mat.w.w = 1.;

    return mat;
}

kernel void
calc_gen(global Transform3D *t, global Mat4 *gen, int offset_last, int offset_this)
{
    int id = get_global_id(0);
    global Transform3D *trans = &t[offset_this+id];
    Mat4 mat = transform_to_mat4(trans[0]);
    gen[offset_this+id] = mult_m(gen[offset_last+trans->parent], mat);
}
";

pub struct Delta
{
    delta : Transform3D<f32>,
    parent: u32,
    padd: [u32, ..3]

}

impl Default for Delta
{
    fn default() -> Delta
    {
        Delta {
            parent: 0,
            delta: Transform3D::new(1f32, Quat::zero(), Vec3::zero()),
            padd: [0, 0, 0]
        }
    }
}

impl Clone for Delta
{
    fn clone(&self) -> Delta
    {
        let tras = self.delta.get();
        Delta {
            parent: self.parent.clone(),
            delta: Transform3D::new(tras.scale.clone(),
                                    tras.rot.clone(),
                                    tras.disp.clone()),
            padd: [0, 0, 0]
        }
    }
}

pub struct Deltas
{
    gen: ~[(u32, u32)],
    delta: ~[Delta],
}

impl Clone for Deltas
{
    fn clone(&self) -> Deltas
    {
        let mut vec = ~[];
        vec.reserve(self.delta.len());
        unsafe {
            vec.set_len(self.delta.len());
            vec.copy_memory(self.delta.as_slice())
        }
        Deltas {
            gen: self.gen.clone(),
            delta: vec
        }
    }
}

#[deriving(Clone, Default, Eq, TotalOrd, TotalEq, Ord)]
pub struct Id(u32, u32);

impl Deltas
{
    pub fn new() -> Deltas
    {
        Deltas {
            gen: ~[(0, 1)],
            delta: ~[Default::default()],
        }
    }

    pub fn root() -> Id {Id(0, 0)}

    pub fn get_loc(&self, id: Id) -> uint
    {
        let Id(gen, offset) = id;
        let (gen_offset, _) = self.gen[gen as uint];

        (gen_offset + offset) as uint
    }

    fn add_loc(&mut self, gen: u32) -> (uint, u32)
    {
        if gen as uint == self.gen.len() {
            let (s, len) = self.gen[(gen-1) as uint];
            self.gen.push((s+len, 1));

            ((s+len) as uint, 0)
        } else {
            for t in self.gen.mut_slice_from((gen+1) as uint).mut_iter() {
                let (off, len) = *t;
                *t = (off+1, len);
            }

            let (off, len) = self.gen[gen as uint];
            self.gen[gen as uint] = (off, len+1);

            ((off+len) as uint, len)
        }
    }

    pub fn insert(&mut self, parent: Id, delta: Transform3D<f32>) -> Id
    {
        let Id(gen, pid) = parent;

        assert!((gen as uint) < self.gen.len());

        let (loc, id) = self.add_loc(gen+1);
        self.delta.insert(loc, Delta {
            parent: pid,
            delta: delta,
            padd: [0, 0, 0]
        });

        Id(gen+1, id)
    }

    pub fn update(&mut self, id: Id, delta: Transform3D<f32>)
    {
        let loc = self.get_loc(id);
        self.delta[loc].delta = delta;
    }

    pub fn get_delta(&self, id :Id) -> Transform3D<f32>
    {
        let loc = self.get_loc(id);
        self.delta[loc].delta
    }

    pub fn get_mat(&self, id :Id) -> Mat4<f32>
    {
        let loc = self.get_loc(id);
        match id {
            Id(0, _) => {
                self.delta[loc].delta.to_mat4()
            },
            Id(gen, _) => {
                let mat = self.delta[loc].delta.to_mat4();
                let parent = Id(gen-1, self.delta[loc].parent);

                self.get_mat(parent).mul_m(&mat)
            }
        }
    }

    pub fn to_positions(&self) -> Positions
    {
        let mut mat = ~[];
        mat.reserve(self.delta.len());
        unsafe {mat.set_len(1);}
        mat[0] = Mat4::identity();

        let mut last_gen_off = 0;
        for &(gen_off, len) in self.gen.slice_from(1).iter() {
            for off in range(gen_off, gen_off+len) {
                let ploc = last_gen_off + self.delta[off as uint].parent;
                let nmat = mat[ploc as uint].mul_m(&self.delta[off as uint].delta.to_mat4());
                mat.push(nmat);
            }
            last_gen_off = gen_off;
        }

        Positions {
            gen: self.gen.clone(),
            pos: mat
        }
    }

    pub fn to_positions_cl(&self, cq: &CommandQueue, ctx: &mut CalcPositionsCl) -> Positions
    {
        let default: &[Mat4<f32>] = &[Mat4::identity()];

        if self.gen.len() == 1 {
            return Positions {
                gen: self.gen.clone(),
                pos: ~[Mat4::identity()]
            };
        }

        let start = precise_time_ns();

        cq.write(&ctx.input, &self.delta.as_slice(), ());
        cq.write(&ctx.output, &default, ());

        let write_end = precise_time_ns();

        ctx.kernel.set_arg(0, &ctx.input);
        ctx.kernel.set_arg(1, &ctx.output);

        let (off, _) = self.gen[0];
        ctx.kernel.set_arg(2, &off);
        let (off, len) = self.gen[1];
        ctx.kernel.set_arg(3, &off);

        let mut event = cq.enqueue_async_kernel(&ctx.kernel, len as uint, None, ());

        for idx in range(2, self.gen.len()) {
            let (off, _) = self.gen[idx-1];
            ctx.kernel.set_arg(2, &off);
            let (off, len) = self.gen[idx];
            ctx.kernel.set_arg(3, &off);
            println!("{} {}", off, len);
            event = cq.enqueue_async_kernel(&ctx.kernel, len as uint, None, event);
        }

        let mut mat = ~[];
        mat.reserve(self.delta.len());
        unsafe {mat.set_len(self.delta.len());}

        let compute_done = precise_time_ns();

        cq.read(&ctx.output, &mut mat.as_mut_slice(), event);

        let download = precise_time_ns();

        println!("{} {} {}",
            write_end - start,
            compute_done - write_end,
            download - compute_done);

        Positions {
            gen: self.gen.clone(),
            pos: mat
        }
    }

    pub fn to_positions_gl(&self, out_delta: &mut [Delta]) -> PositionsGL
    {
        for (idx, delta) in self.delta.iter().enumerate() {
            out_delta[idx] = delta.clone();
        }

        PositionsGL {
            gen: self.gen.clone()
        }
    }
}

pub struct PositionsGL {
    pub gen: ~[(u32, u32)]
}

impl PositionsGL
{
    pub fn get_loc(&self, id: Id) -> uint
    {
        let Id(gen, offset) = id;
        let (gen_offset, _) = self.gen[gen as uint];

        (gen_offset + offset) as uint
    }
}

pub struct Positions
{
    gen: ~[(u32, u32)],
    pos: ~[Mat4<f32>],
}

impl Clone for Positions
{
    #[inline(never)]
    fn clone(&self) -> Positions
    {
        let mut vec = ~[];
        vec.reserve(self.pos.len());
        unsafe {
            vec.set_len(self.pos.len());
            vec.copy_memory(self.pos.as_slice())
        }
        Positions {
            gen: self.gen.clone(),
            pos: vec
        }
    }
}

impl Positions
{
    pub fn root() -> Id {Id(0, 0)}

    pub fn get_loc(&self, id: Id) -> uint
    {
        let Id(gen, offset) = id;
        let (gen_offset, _) = self.gen[gen as uint];

        (gen_offset + offset) as uint
    }

    pub fn get_mat(&self, id :Id) -> Mat4<f32>
    {
        self.pos[self.get_loc(id)].clone()
    }

    pub fn all_mats<'a>(&'a self) -> &'a [Mat4<f32>]
    {
        self.pos.as_slice()
    }
}

pub struct CalcPositionsCl
{
    program: Program,
    kernel: Kernel,
    input: CLBuffer<Delta>,
    output: CLBuffer<Mat4<f32>>
}

impl CalcPositionsCl
{
    pub fn new(ctx: &Context, device: &Device) -> CalcPositionsCl
    {
        let program = ctx.create_program_from_source(opencl_program);

        match program.build(device) {
            Ok(()) => (),
            Err(build_log) => {
                println!("Error building program:");
                println!("{:s}", build_log);
                fail!("");
            }
        }

        let kernel = program.create_kernel("calc_gen");

        let mat_mem: CLBuffer<Mat4<f32>> = ctx.create_buffer(1024*1024, CL_MEM_READ_WRITE);
        let delta_mem: CLBuffer<Delta> = ctx.create_buffer(1024*1024, CL_MEM_READ_WRITE);

        CalcPositionsCl {
            program: program,
            kernel: kernel,
            input: delta_mem,
            output: mat_mem
        }
    }
}

<commit_msg>cleanup formatting in position<commit_after>use std::default::Default;

use cgmath::transform::Transform3D;
use cgmath::quaternion::Quat;
use cgmath::vector::Vec3;
use cgmath::matrix::{Mat4, ToMat4, Matrix};

use OpenCL::hl::{Device, Context, CommandQueue, Program, Kernel};
use OpenCL::mem::CLBuffer;
use OpenCL::CL::CL_MEM_READ_WRITE;

static opencl_program: &'static str = "
struct q4 {
    float s, x, y, z;
};

struct f4 {
    float x, y, z, w;
};

struct f3 {
    float x, y, z;
};

typedef struct q4 q4;
typedef struct f4 f4;
typedef struct f3 f3;

struct mat4 {
    f4 x, y, z, w;
};

struct transform
{
    q4 rot;
    f3 pos;
    float scale;
    int parent;
    int padd[3];
};

typedef struct mat4 Mat4;
typedef struct transform Transform3D;

#define DOT(OUT, A, B, i, j) \
    OUT.j.i = A.x.i * B.j.x + \
    A.y.i * B.j.y + \
    A.z.i * B.j.z + \
    A.w.i * B.j.w

Mat4
mult_m(const Mat4 a, const Mat4 b)
{
    Mat4 out;

    DOT(out, a, b, x, x);
    DOT(out, a, b, x, y);
    DOT(out, a, b, x, z);
    DOT(out, a, b, x, w);

    DOT(out, a, b, y, x);
    DOT(out, a, b, y, y);
    DOT(out, a, b, y, z);
    DOT(out, a, b, y, w);

    DOT(out, a, b, z, x);
    DOT(out, a, b, z, y);
    DOT(out, a, b, z, z);
    DOT(out, a, b, z, w);

    DOT(out, a, b, w, x);
    DOT(out, a, b, w, y);
    DOT(out, a, b, w, z);
    DOT(out, a, b, w, w);

    return out;
}

Mat4
transform_to_mat4(const Transform3D trans)
{
    Mat4 mat;

    float x2 = trans.rot.x + trans.rot.x;
    float y2 = trans.rot.y + trans.rot.y;
    float z2 = trans.rot.z + trans.rot.z;

    float xx2 = x2 * trans.rot.x;
    float xy2 = x2 * trans.rot.y;
    float xz2 = x2 * trans.rot.z;

    float yy2 = y2 * trans.rot.y;
    float yz2 = y2 * trans.rot.z;
    float zz2 = z2 * trans.rot.z;

    float sy2 = y2 * trans.rot.s;
    float sz2 = z2 * trans.rot.s;
    float sx2 = x2 * trans.rot.s;

    mat.x.x = (1. - yy2 - zz2) * trans.scale;
    mat.x.y = (xy2 + sz2) * trans.scale;
    mat.x.z = (xz2 - sy2) * trans.scale;
    mat.x.w = 0.;

    mat.y.x = (xy2 - sz2) * trans.scale;
    mat.y.y = (1. - xx2 - zz2) * trans.scale;
    mat.y.z = (yz2 + sx2) * trans.scale;
    mat.y.w = 0.;

    mat.z.x = (xy2 + sy2) * trans.scale;
    mat.z.y = (yz2 - sx2) * trans.scale;
    mat.z.z = (1. - xx2 - yy2) * trans.scale;
    mat.z.w = 0.;

    mat.w.x = trans.pos.x;
    mat.w.y = trans.pos.y;
    mat.w.z = trans.pos.z;
    mat.w.w = 1.;

    return mat;
}

kernel void
calc_gen(global Transform3D *t, global Mat4 *gen, int offset_last, int offset_this)
{
    int id = get_global_id(0);
    global Transform3D *trans = &t[offset_this+id];
    Mat4 mat = transform_to_mat4(trans[0]);
    gen[offset_this+id] = mult_m(gen[offset_last+trans->parent], mat);
}
";

pub struct Delta {
    delta : Transform3D<f32>,
    parent: u32,
    padd: [u32, ..3]

}

impl Default for Delta {
    fn default() -> Delta {
        Delta {
            parent: 0,
            delta: Transform3D::new(1f32, Quat::zero(), Vec3::zero()),
            padd: [0, 0, 0]
        }
    }
}

impl Clone for Delta {
    fn clone(&self) -> Delta {
        let tras = self.delta.get();
        Delta {
            parent: self.parent.clone(),
            delta: Transform3D::new(tras.scale.clone(),
                                    tras.rot.clone(),
                                    tras.disp.clone()),
            padd: [0, 0, 0]
        }
    }
}

pub struct Deltas {
    gen: ~[(u32, u32)],
    delta: ~[Delta],
}

impl Clone for Deltas {
    fn clone(&self) -> Deltas {
        let mut vec = ~[];
        vec.reserve(self.delta.len());
        unsafe {
            vec.set_len(self.delta.len());
            vec.copy_memory(self.delta.as_slice())
        }
        Deltas {
            gen: self.gen.clone(),
            delta: vec
        }
    }
}

#[deriving(Clone, Default, Eq, TotalOrd, TotalEq, Ord)]
pub struct Id(u32, u32);

impl Deltas {
    pub fn new() -> Deltas {
        Deltas {
            gen: ~[(0, 1)],
            delta: ~[Default::default()],
        }
    }

    pub fn root() -> Id {Id(0, 0)}

    pub fn get_loc(&self, id: Id) -> uint {
        let Id(gen, offset) = id;
        let (gen_offset, _) = self.gen[gen as uint];

        (gen_offset + offset) as uint
    }

    fn add_location(&mut self, gen: u32) -> (uint, u32) {
        if gen as uint == self.gen.len() {
            let (s, len) = self.gen[(gen-1) as uint];
            self.gen.push((s+len, 1));

            ((s+len) as uint, 0)
        } else {
            for t in self.gen.mut_slice_from((gen+1) as uint).mut_iter() {
                let (off, len) = *t;
                *t = (off+1, len);
            }

            let (off, len) = self.gen[gen as uint];
            self.gen[gen as uint] = (off, len+1);

            ((off+len) as uint, len)
        }
    }

    pub fn insert(&mut self, parent: Id, delta: Transform3D<f32>) -> Id {
        let Id(gen, pid) = parent;

        assert!((gen as uint) < self.gen.len());

        let (loc, id) = self.add_location(gen+1);
        self.delta.insert(loc, Delta {
            parent: pid,
            delta: delta,
            padd: [0, 0, 0]
        });

        Id(gen+1, id)
    }

    pub fn update(&mut self, id: Id, delta: Transform3D<f32>) {
        let loc = self.get_loc(id);
        self.delta[loc].delta = delta;
    }

    pub fn get_delta(&self, id :Id) -> Transform3D<f32> {
        let loc = self.get_loc(id);
        self.delta[loc].delta
    }

    pub fn get_mat(&self, id :Id) -> Mat4<f32> {
        let loc = self.get_loc(id);
        match id {
            Id(0, _) => {
                self.delta[loc].delta.to_mat4()
            },
            Id(gen, _) => {
                let mat = self.delta[loc].delta.to_mat4();
                let parent = Id(gen-1, self.delta[loc].parent);

                self.get_mat(parent).mul_m(&mat)
            }
        }
    }

    pub fn to_positions(&self) -> Positions {
        let mut mat = ~[];
        mat.reserve(self.delta.len());
        unsafe {mat.set_len(1);}
        mat[0] = Mat4::identity();

        let mut last_gen_off = 0;
        for &(gen_off, len) in self.gen.slice_from(1).iter() {
            for off in range(gen_off, gen_off+len) {
                let ploc = last_gen_off + self.delta[off as uint].parent;
                let nmat = mat[ploc as uint].mul_m(&self.delta[off as uint].delta.to_mat4());
                mat.push(nmat);
            }
            last_gen_off = gen_off;
        }

        Positions {
            gen: self.gen.clone(),
            pos: mat
        }
    }

    pub fn to_positions_cl(&self, cq: &CommandQueue, ctx: &mut CalcPositionsCl) -> Positions {
        let default: &[Mat4<f32>] = &[Mat4::identity()];

        if self.gen.len() == 1 {
            return Positions {
                gen: self.gen.clone(),
                pos: ~[Mat4::identity()]
            };
        }

        cq.write(&ctx.input, &self.delta.as_slice(), ());
        cq.write(&ctx.output, &default, ());

        ctx.kernel.set_arg(0, &ctx.input);
        ctx.kernel.set_arg(1, &ctx.output);

        let (off, _) = self.gen[0];
        ctx.kernel.set_arg(2, &off);
        let (off, len) = self.gen[1];
        ctx.kernel.set_arg(3, &off);

        let mut event = cq.enqueue_async_kernel(&ctx.kernel, len as uint, None, ());

        for idx in range(2, self.gen.len()) {
            let (off, _) = self.gen[idx-1];
            ctx.kernel.set_arg(2, &off);
            let (off, len) = self.gen[idx];
            ctx.kernel.set_arg(3, &off);
            event = cq.enqueue_async_kernel(&ctx.kernel, len as uint, None, event);
        }

        let mut mat = ~[];
        mat.reserve(self.delta.len());
        unsafe {mat.set_len(self.delta.len());}

        cq.read(&ctx.output, &mut mat.as_mut_slice(), event);

        Positions {
            gen: self.gen.clone(),
            pos: mat
        }
    }

    pub fn to_positions_gl(&self, out_delta: &mut [Delta]) -> PositionsGL {
        for (idx, delta) in self.delta.iter().enumerate() {
            out_delta[idx] = delta.clone();
        }

        PositionsGL {
            gen: self.gen.clone()
        }
    }
}

pub struct PositionsGL {
    pub gen: ~[(u32, u32)]
}

impl PositionsGL {
    pub fn get_loc(&self, id: Id) -> uint {
        let Id(gen, offset) = id;
        let (gen_offset, _) = self.gen[gen as uint];

        (gen_offset + offset) as uint
    }
}

pub struct Positions {
    gen: ~[(u32, u32)],
    pos: ~[Mat4<f32>],
}

impl Clone for Positions {
    #[inline(never)]
    fn clone(&self) -> Positions
    {
        let mut vec = ~[];
        vec.reserve(self.pos.len());
        unsafe {
            vec.set_len(self.pos.len());
            vec.copy_memory(self.pos.as_slice())
        }
        Positions {
            gen: self.gen.clone(),
            pos: vec
        }
    }
}

impl Positions {
    pub fn root() -> Id {Id(0, 0)}

    pub fn get_loc(&self, id: Id) -> uint {
        let Id(gen, offset) = id;
        let (gen_offset, _) = self.gen[gen as uint];

        (gen_offset + offset) as uint
    }

    pub fn get_mat(&self, id :Id) -> Mat4<f32> {
        self.pos[self.get_loc(id)].clone()
    }

    pub fn all_mats<'a>(&'a self) -> &'a [Mat4<f32>] {
        self.pos.as_slice()
    }
}

pub struct CalcPositionsCl {
    program: Program,
    kernel: Kernel,
    input: CLBuffer<Delta>,
    output: CLBuffer<Mat4<f32>>
}

impl CalcPositionsCl {
    pub fn new(ctx: &Context, device: &Device) -> CalcPositionsCl {
        let program = ctx.create_program_from_source(opencl_program);

        match program.build(device) {
            Ok(()) => (),
            Err(build_log) => {
                println!("Error building program:");
                println!("{:s}", build_log);
                fail!("");
            }
        }

        let kernel = program.create_kernel("calc_gen");

        let mat_mem: CLBuffer<Mat4<f32>> = ctx.create_buffer(1024*1024, CL_MEM_READ_WRITE);
        let delta_mem: CLBuffer<Delta> = ctx.create_buffer(1024*1024, CL_MEM_READ_WRITE);

        CalcPositionsCl {
            program: program,
            kernel: kernel,
            input: delta_mem,
            output: mat_mem
        }
    }
}

<|endoftext|>


<commit_before>//! A not-quite-trivial HTTP server which responds to requests by showing the request and response
//! headers and any other information it has.

extern mod extra;
extern mod rusthttpserver;

use rusthttpserver::request::Request;
use rusthttpserver::response::ResponseWriter;
use std::rt::io::net::ip::{SocketAddr, Ipv4Addr};
use std::rt::io::Writer;
use extra::time;

use rusthttpserver::server::{Config, Server, ServerUtil};
use rusthttpserver::rfc2616::format_http_time;

#[deriving(Clone)]
struct InfoServer;

impl Server for InfoServer {
    fn get_config(&self) -> Config {
        Config { bind_address: SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 8001 } }
    }

    fn handle_request(&self, r: &Request, w: &mut ResponseWriter) {
        w.headers.insert(~"Date", format_http_time(time::now_utc()));
        w.headers.insert(~"Content-Type", ~"text/html");
        w.headers.insert(~"Server", ~"Rust Thingummy/0.0-pre");
        w.write(bytes!("<!DOCTYPE html><title>Rust HTTP server</title>"));

        w.write(bytes!("
Request
"));
        let s = fmt!("

Method

%s

Host

%?

Request URI

%?

HTTP version

%?

Close connection

%?

",
            r.method.to_str(),
            r.host,
            r.request_uri,
            r.version,
            r.close_connection);
        w.write(s.as_bytes().to_owned());
        w.write(bytes!("
Headers
"));
        w.write(bytes!("

Name	Value

"));
        for (k, v) in r.headers.iter() {
            let line = fmt!("
%s	%s
", *k, *v);
            w.write(line.as_bytes().to_owned());
        }
        w.write(bytes!("

"));
        w.write(bytes!("
Body

"));
        w.write(r.body.as_bytes().to_owned());
        w.write(bytes!("
"));

        w.write(bytes!("
Response
"));
        let s = fmt!("

Status

%s

", w.status.to_str());
        w.write(s.as_bytes().to_owned());
        w.write(bytes!("
Headers
"));
        w.write(bytes!("

Name	Value

"));
        {
            let h = w.headers.clone();
            for (k, v) in h.iter() {
                let line = fmt!("
%s	%s
", *k, *v);
                w.write(line.as_bytes().to_owned());
            }
        }
        w.write(bytes!("

"));
    }
}

fn main() {
    InfoServer.serve_forever();
}
<commit_msg>Make info example close the connection (temporary solution).<commit_after>//! A not-quite-trivial HTTP server which responds to requests by showing the request and response
//! headers and any other information it has.

extern mod extra;
extern mod rusthttpserver;

use rusthttpserver::request::Request;
use rusthttpserver::response::ResponseWriter;
use std::rt::io::net::ip::{SocketAddr, Ipv4Addr};
use std::rt::io::Writer;
use extra::time;

use rusthttpserver::server::{Config, Server, ServerUtil};
use rusthttpserver::rfc2616::format_http_time;

#[deriving(Clone)]
struct InfoServer;

impl Server for InfoServer {
    fn get_config(&self) -> Config {
        Config { bind_address: SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 8001 } }
    }

    fn handle_request(&self, r: &Request, w: &mut ResponseWriter) {
        w.headers.insert(~"Date", format_http_time(time::now_utc()));
        w.headers.insert(~"Content-Type", ~"text/html");
        w.headers.insert(~"Server", ~"Rust Thingummy/0.0-pre");
        w.write(bytes!("<!DOCTYPE html><title>Rust HTTP server</title>"));

        w.write(bytes!("
Request
"));
        let s = fmt!("

Method

%s

Host

%?

Request URI

%?

HTTP version

%?

Close connection

%?

",
            r.method.to_str(),
            r.host,
            r.request_uri,
            r.version,
            r.close_connection);
        w.write(s.as_bytes().to_owned());
        w.write(bytes!("
Headers
"));
        w.write(bytes!("

Name	Value

"));
        for (k, v) in r.headers.iter() {
            let line = fmt!("
%s	%s
", *k, *v);
            w.write(line.as_bytes().to_owned());
        }
        w.write(bytes!("

"));
        w.write(bytes!("
Body

"));
        w.write(r.body.as_bytes().to_owned());
        w.write(bytes!("
"));

        w.write(bytes!("
Response
"));
        let s = fmt!("

Status

%s

", w.status.to_str());
        w.write(s.as_bytes().to_owned());
        w.write(bytes!("
Headers
"));
        w.write(bytes!("

Name	Value

"));
        {
            let h = w.headers.clone();
            for (k, v) in h.iter() {
                let line = fmt!("
%s	%s
", *k, *v);
                w.write(line.as_bytes().to_owned());
            }
        }
        w.write(bytes!("

"));
        // Server doesn't yet support the chunked transfer coding, nor was Content-Length specified,
        // so we'd better close the connection to ensure the page finishes loading.
        // DON'T COPY THIS WAY OF DOING THINGS. EVER. OR ELSE.
        unsafe { ::std::cast::transmute::<&Request, &mut Request>(r).close_connection = true; }
    }
}

fn main() {
    InfoServer.serve_forever();
}
<|endoftext|>


<commit_before>use ::helper::*;
use ::Fake;
use ::faker::{Name, Number};

pub trait Address: Fake + Name + Number {
    #[inline]
    fn time_zone() -> &'static str {
        take_one(Self::address_time_zone_data())
    }

    #[inline]
    fn city_prefix() -> &'static str {
        take_one(Self::address_city_prefix_data())
    }

    #[inline]
    fn city_suffix() -> &'static str {
        take_one(Self::address_city_suffix_data())
    }

    #[inline]
    fn street_suffix() -> &'static str {
        take_one(Self::address_street_suffix_data())
    }

    #[inline]
    fn state() -> &'static str {
        take_one(Self::address_state_data())
    }

    #[inline]
    fn state_abbr() -> &'static str {
        take_one(Self::address_state_abbr_data())
    }

    #[inline]
    fn city() -> String {
        match gen_range(0, 5) {
            0 => {
                format!("{} {} {}",
                        Self::city_prefix(),
                        <Self as Name>::first_name(),
                        Self::city_suffix())
            }
            1 => {
                format!("{} {}",
                        <Self as Name>::first_name(),
                        Self::city_suffix())
            }
            _ => {
                format!("{} {}",
                        <Self as Name>::last_name(),
                        Self::city_suffix())
            }
        }
    }

    #[inline]
    fn street_name() -> String {
        match gen_range(0, 2) {
            0 => {
                format!("{} {}",
                        <Self as Name>::first_name(),
                        Self::street_suffix())
            }
            _ => {
                format!("{} {}",
                        <Self as Name>::last_name(),
                        Self::street_suffix())
            }
        }
    }

    #[inline]
    fn building_number() -> String {
        let number_format =
            take_one(Self::address_building_number_format_data());
        numerify_sym(number_format)
    }

    #[inline]
    fn street_address() -> String {
        format!("{} {}",
                Self::building_number(),
                Self::street_name())
    }

    #[inline]
    fn secondary_address() -> String {
        format!("{} {}",
                take_one(&["Apt.", "Suit."]),
                <Self as Number>::number(3))
    }

    #[inline]
    fn zip() -> String {
        let number_format = take_one(Self::address_zip_format_data());
        numerify_sym(number_format)
    }

    #[inline]
    fn postcode() -> String {
        let number_format =
            take_one(Self::address_postcode_format_data());
        numerify_sym(number_format)
    }

    #[inline]
    fn latitude() -> String {
        ((random::<f64>() * 180_f64) - 90_f64).to_string()
    }

    #[inline]
    fn longitude() -> String {
        ((random::<f64>() * 360_f64) - 180_f64).to_string()
    }
}
<commit_msg>city suffix should be appended without space<commit_after>use ::helper::*;
use ::Fake;
use ::faker::{Name, Number};

pub trait Address: Fake + Name + Number {
    #[inline]
    fn time_zone() -> &'static str {
        take_one(Self::address_time_zone_data())
    }

    #[inline]
    fn city_prefix() -> &'static str {
        take_one(Self::address_city_prefix_data())
    }

    #[inline]
    fn city_suffix() -> &'static str {
        take_one(Self::address_city_suffix_data())
    }

    #[inline]
    fn street_suffix() -> &'static str {
        take_one(Self::address_street_suffix_data())
    }

    #[inline]
    fn state() -> &'static str {
        take_one(Self::address_state_data())
    }

    #[inline]
    fn state_abbr() -> &'static str {
        take_one(Self::address_state_abbr_data())
    }

    #[inline]
    fn city() -> String {
        match gen_range(0, 5) {
            0 => {
                format!("{} {}{}",
                        Self::city_prefix(),
                        <Self as Name>::first_name(),
                        Self::city_suffix())
            }
            1 => {
                format!("{}{}",
                        <Self as Name>::first_name(),
                        Self::city_suffix())
            }
            _ => {
                format!("{}{}",
                        <Self as Name>::last_name(),
                        Self::city_suffix())
            }
        }
    }

    #[inline]
    fn street_name() -> String {
        match gen_range(0, 2) {
            0 => {
                format!("{} {}",
                        <Self as Name>::first_name(),
                        Self::street_suffix())
            }
            _ => {
                format!("{} {}",
                        <Self as Name>::last_name(),
                        Self::street_suffix())
            }
        }
    }

    #[inline]
    fn building_number() -> String {
        let number_format =
            take_one(Self::address_building_number_format_data());
        numerify_sym(number_format)
    }

    #[inline]
    fn street_address() -> String {
        format!("{} {}",
                Self::building_number(),
                Self::street_name())
    }

    #[inline]
    fn secondary_address() -> String {
        format!("{} {}",
                take_one(&["Apt.", "Suit."]),
                <Self as Number>::number(3))
    }

    #[inline]
    fn zip() -> String {
        let number_format = take_one(Self::address_zip_format_data());
        numerify_sym(number_format)
    }

    #[inline]
    fn postcode() -> String {
        let number_format =
            take_one(Self::address_postcode_format_data());
        numerify_sym(number_format)
    }

    #[inline]
    fn latitude() -> String {
        ((random::<f64>() * 180_f64) - 90_f64).to_string()
    }

    #[inline]
    fn longitude() -> String {
        ((random::<f64>() * 360_f64) - 180_f64).to_string()
    }
}
<|endoftext|>


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

//! Memory allocation APIs

#![stable(feature = "alloc_module", since = "1.28.0")]

use core::intrinsics::{min_align_of_val, size_of_val};
use core::ptr::{NonNull, Unique};
use core::usize;

#[stable(feature = "alloc_module", since = "1.28.0")]
#[doc(inline)]
pub use core::alloc::*;

extern "Rust" {
    #[allocator]
    #[rustc_allocator_nounwind]
    fn __rust_alloc(size: usize, align: usize) -> *mut u8;
    #[rustc_allocator_nounwind]
    fn __rust_dealloc(ptr: *mut u8, size: usize, align: usize);
    #[rustc_allocator_nounwind]
    fn __rust_realloc(ptr: *mut u8,
                      old_size: usize,
                      align: usize,
                      new_size: usize) -> *mut u8;
    #[rustc_allocator_nounwind]
    fn __rust_alloc_zeroed(size: usize, align: usize) -> *mut u8;
}

/// The global memory allocator.
///
/// This type implements the [`Alloc`] trait by forwarding calls
/// to the allocator registered with the `#[global_allocator]` attribute
/// if there is one, or the `std` crate’s default.
#[unstable(feature = "allocator_api", issue = "32838")]
#[derive(Copy, Clone, Default, Debug)]
pub struct Global;

/// Allocate memory with the global allocator.
///
/// This function forwards calls to the [`GlobalAlloc::alloc`] method
/// of the allocator registered with the `#[global_allocator]` attribute
/// if there is one, or the `std` crate’s default.
///
/// This function is expected to be deprecated in favor of the `alloc` method
/// of the [`Global`] type when it and the [`Alloc`] trait become stable.
///
/// # Safety
///
/// See [`GlobalAlloc::alloc`].
#[stable(feature = "global_alloc", since = "1.28.0")]
#[inline]
pub unsafe fn alloc(layout: Layout) -> *mut u8 {
    __rust_alloc(layout.size(), layout.align())
}

/// Deallocate memory with the global allocator.
///
/// This function forwards calls to the [`GlobalAlloc::dealloc`] method
/// of the allocator registered with the `#[global_allocator]` attribute
/// if there is one, or the `std` crate’s default.
///
/// This function is expected to be deprecated in favor of the `dealloc` method
/// of the [`Global`] type when it and the [`Alloc`] trait become stable.
///
/// # Safety
///
/// See [`GlobalAlloc::dealloc`].
#[stable(feature = "global_alloc", since = "1.28.0")]
#[inline]
pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
    __rust_dealloc(ptr, layout.size(), layout.align())
}

/// Reallocate memory with the global allocator.
///
/// This function forwards calls to the [`GlobalAlloc::realloc`] method
/// of the allocator registered with the `#[global_allocator]` attribute
/// if there is one, or the `std` crate’s default.
///
/// This function is expected to be deprecated in favor of the `realloc` method
/// of the [`Global`] type when it and the [`Alloc`] trait become stable.
///
/// # Safety
///
/// See [`GlobalAlloc::realloc`].
#[stable(feature = "global_alloc", since = "1.28.0")]
#[inline]
pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
    __rust_realloc(ptr, layout.size(), layout.align(), new_size)
}

/// Allocate zero-initialized memory with the global allocator.
///
/// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
/// of the allocator registered with the `#[global_allocator]` attribute
/// if there is one, or the `std` crate’s default.
///
/// This function is expected to be deprecated in favor of the `alloc_zeroed` method
/// of the [`Global`] type when it and the [`Alloc`] trait become stable.
///
/// # Safety
///
/// See [`GlobalAlloc::alloc_zeroed`].
#[stable(feature = "global_alloc", since = "1.28.0")]
#[inline]
pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
    __rust_alloc_zeroed(layout.size(), layout.align())
}

#[unstable(feature = "allocator_api", issue = "32838")]
unsafe impl Alloc for Global {
    #[inline]
    unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
        NonNull::new(alloc(layout)).ok_or(AllocErr)
    }

    #[inline]
    unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
        dealloc(ptr.as_ptr(), layout)
    }

    #[inline]
    unsafe fn realloc(&mut self,
                      ptr: NonNull<u8>,
                      layout: Layout,
                      new_size: usize)
                      -> Result<NonNull<u8>, AllocErr>
    {
        NonNull::new(realloc(ptr.as_ptr(), layout, new_size)).ok_or(AllocErr)
    }

    #[inline]
    unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
        NonNull::new(alloc_zeroed(layout)).ok_or(AllocErr)
    }
}

/// The allocator for unique pointers.
// This function must not unwind. If it does, MIR codegen will fail.
#[cfg(not(test))]
#[lang = "exchange_malloc"]
#[inline]
unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
    if size == 0 {
        align as *mut u8
    } else {
        let layout = Layout::from_size_align_unchecked(size, align);
        let ptr = alloc(layout);
        if !ptr.is_null() {
            ptr
        } else {
            handle_alloc_error(layout)
        }
    }
}

#[cfg_attr(not(test), lang = "box_free")]
#[inline]
pub(crate) unsafe fn box_free<T: ?Sized>(ptr: Unique<T>) {
    let ptr = ptr.as_ptr();
    let size = size_of_val(&*ptr);
    let align = min_align_of_val(&*ptr);
    // We do not allocate for Box<T> when T is ZST, so deallocation is also not necessary.
    if size != 0 {
        let layout = Layout::from_size_align_unchecked(size, align);
        dealloc(ptr as *mut u8, layout);
    }
}

/// Abort on memory allocation error or failure.
///
/// Callers of memory allocation APIs wishing to abort computation
/// in response to an allocation error are encouraged to call this function,
/// rather than directly invoking `panic!` or similar.
///
/// The default behavior of this function is to print a message to standard error
/// and abort the process.
/// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
///
/// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
/// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
#[stable(feature = "global_alloc", since = "1.28.0")]
#[rustc_allocator_nounwind]
pub fn handle_alloc_error(layout: Layout) -> ! {
    #[allow(improper_ctypes)]
    extern "Rust" {
        #[lang = "oom"]
        fn oom_impl(layout: Layout) -> !;
    }
    unsafe { oom_impl(layout) }
}

#[cfg(test)]
mod tests {
    extern crate test;
    use self::test::Bencher;
    use boxed::Box;
    use alloc::{Global, Alloc, Layout, handle_alloc_error};

    #[test]
    fn allocate_zeroed() {
        unsafe {
            let layout = Layout::from_size_align(1024, 1).unwrap();
            let ptr = Global.alloc_zeroed(layout.clone())
                .unwrap_or_else(|_| handle_alloc_error(layout));

            let mut i = ptr.cast::<u8>().as_ptr();
            let end = i.offset(layout.size() as isize);
            while i < end {
                assert_eq!(*i, 0);
                i = i.offset(1);
            }
            Global.dealloc(ptr, layout);
        }
    }

    #[bench]
    fn alloc_owned_small(b: &mut Bencher) {
        b.iter(|| {
            let _: Box<_> = box 10;
        })
    }
}
<commit_msg>Add doc examples for std::alloc::{alloc,alloc_zeroed}.<commit_after>// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Memory allocation APIs

#![stable(feature = "alloc_module", since = "1.28.0")]

use core::intrinsics::{min_align_of_val, size_of_val};
use core::ptr::{NonNull, Unique};
use core::usize;

#[stable(feature = "alloc_module", since = "1.28.0")]
#[doc(inline)]
pub use core::alloc::*;

extern "Rust" {
    #[allocator]
    #[rustc_allocator_nounwind]
    fn __rust_alloc(size: usize, align: usize) -> *mut u8;
    #[rustc_allocator_nounwind]
    fn __rust_dealloc(ptr: *mut u8, size: usize, align: usize);
    #[rustc_allocator_nounwind]
    fn __rust_realloc(ptr: *mut u8,
                      old_size: usize,
                      align: usize,
                      new_size: usize) -> *mut u8;
    #[rustc_allocator_nounwind]
    fn __rust_alloc_zeroed(size: usize, align: usize) -> *mut u8;
}

/// The global memory allocator.
///
/// This type implements the [`Alloc`] trait by forwarding calls
/// to the allocator registered with the `#[global_allocator]` attribute
/// if there is one, or the `std` crate’s default.
#[unstable(feature = "allocator_api", issue = "32838")]
#[derive(Copy, Clone, Default, Debug)]
pub struct Global;

/// Allocate memory with the global allocator.
///
/// This function forwards calls to the [`GlobalAlloc::alloc`] method
/// of the allocator registered with the `#[global_allocator]` attribute
/// if there is one, or the `std` crate’s default.
///
/// This function is expected to be deprecated in favor of the `alloc` method
/// of the [`Global`] type when it and the [`Alloc`] trait become stable.
///
/// # Safety
///
/// See [`GlobalAlloc::alloc`].
///
/// # Examples
///
/// ```
/// use std::alloc::{alloc, dealloc, Layout};
///
/// unsafe {
///     let layout = Layout::new::<u16>();
///     let ptr = alloc(layout);
///
///     *(ptr as *mut u16) = 42;
///     assert_eq!(*(ptr as *mut u16), 42);
///
///     dealloc(ptr, layout);
/// }
/// ```
#[stable(feature = "global_alloc", since = "1.28.0")]
#[inline]
pub unsafe fn alloc(layout: Layout) -> *mut u8 {
    __rust_alloc(layout.size(), layout.align())
}

/// Deallocate memory with the global allocator.
///
/// This function forwards calls to the [`GlobalAlloc::dealloc`] method
/// of the allocator registered with the `#[global_allocator]` attribute
/// if there is one, or the `std` crate’s default.
///
/// This function is expected to be deprecated in favor of the `dealloc` method
/// of the [`Global`] type when it and the [`Alloc`] trait become stable.
///
/// # Safety
///
/// See [`GlobalAlloc::dealloc`].
#[stable(feature = "global_alloc", since = "1.28.0")]
#[inline]
pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
    __rust_dealloc(ptr, layout.size(), layout.align())
}

/// Reallocate memory with the global allocator.
///
/// This function forwards calls to the [`GlobalAlloc::realloc`] method
/// of the allocator registered with the `#[global_allocator]` attribute
/// if there is one, or the `std` crate’s default.
///
/// This function is expected to be deprecated in favor of the `realloc` method
/// of the [`Global`] type when it and the [`Alloc`] trait become stable.
///
/// # Safety
///
/// See [`GlobalAlloc::realloc`].
#[stable(feature = "global_alloc", since = "1.28.0")]
#[inline]
pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
    __rust_realloc(ptr, layout.size(), layout.align(), new_size)
}

/// Allocate zero-initialized memory with the global allocator.
///
/// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method
/// of the allocator registered with the `#[global_allocator]` attribute
/// if there is one, or the `std` crate’s default.
///
/// This function is expected to be deprecated in favor of the `alloc_zeroed` method
/// of the [`Global`] type when it and the [`Alloc`] trait become stable.
///
/// # Safety
///
/// See [`GlobalAlloc::alloc_zeroed`].
///
/// # Examples
///
/// ```
/// use std::alloc::{alloc_zeroed, dealloc, Layout};
///
/// unsafe {
///     let layout = Layout::new::<u16>();
///     let ptr = alloc_zeroed(layout);
///
///     assert_eq!(*(ptr as *mut u16), 0);
///
///     dealloc(ptr, layout);
/// }
/// ```
#[stable(feature = "global_alloc", since = "1.28.0")]
#[inline]
pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
    __rust_alloc_zeroed(layout.size(), layout.align())
}

#[unstable(feature = "allocator_api", issue = "32838")]
unsafe impl Alloc for Global {
    #[inline]
    unsafe fn alloc(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
        NonNull::new(alloc(layout)).ok_or(AllocErr)
    }

    #[inline]
    unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
        dealloc(ptr.as_ptr(), layout)
    }

    #[inline]
    unsafe fn realloc(&mut self,
                      ptr: NonNull<u8>,
                      layout: Layout,
                      new_size: usize)
                      -> Result<NonNull<u8>, AllocErr>
    {
        NonNull::new(realloc(ptr.as_ptr(), layout, new_size)).ok_or(AllocErr)
    }

    #[inline]
    unsafe fn alloc_zeroed(&mut self, layout: Layout) -> Result<NonNull<u8>, AllocErr> {
        NonNull::new(alloc_zeroed(layout)).ok_or(AllocErr)
    }
}

/// The allocator for unique pointers.
// This function must not unwind. If it does, MIR codegen will fail.
#[cfg(not(test))]
#[lang = "exchange_malloc"]
#[inline]
unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
    if size == 0 {
        align as *mut u8
    } else {
        let layout = Layout::from_size_align_unchecked(size, align);
        let ptr = alloc(layout);
        if !ptr.is_null() {
            ptr
        } else {
            handle_alloc_error(layout)
        }
    }
}

#[cfg_attr(not(test), lang = "box_free")]
#[inline]
pub(crate) unsafe fn box_free<T: ?Sized>(ptr: Unique<T>) {
    let ptr = ptr.as_ptr();
    let size = size_of_val(&*ptr);
    let align = min_align_of_val(&*ptr);
    // We do not allocate for Box<T> when T is ZST, so deallocation is also not necessary.
    if size != 0 {
        let layout = Layout::from_size_align_unchecked(size, align);
        dealloc(ptr as *mut u8, layout);
    }
}

/// Abort on memory allocation error or failure.
///
/// Callers of memory allocation APIs wishing to abort computation
/// in response to an allocation error are encouraged to call this function,
/// rather than directly invoking `panic!` or similar.
///
/// The default behavior of this function is to print a message to standard error
/// and abort the process.
/// It can be replaced with [`set_alloc_error_hook`] and [`take_alloc_error_hook`].
///
/// [`set_alloc_error_hook`]: ../../std/alloc/fn.set_alloc_error_hook.html
/// [`take_alloc_error_hook`]: ../../std/alloc/fn.take_alloc_error_hook.html
#[stable(feature = "global_alloc", since = "1.28.0")]
#[rustc_allocator_nounwind]
pub fn handle_alloc_error(layout: Layout) -> ! {
    #[allow(improper_ctypes)]
    extern "Rust" {
        #[lang = "oom"]
        fn oom_impl(layout: Layout) -> !;
    }
    unsafe { oom_impl(layout) }
}

#[cfg(test)]
mod tests {
    extern crate test;
    use self::test::Bencher;
    use boxed::Box;
    use alloc::{Global, Alloc, Layout, handle_alloc_error};

    #[test]
    fn allocate_zeroed() {
        unsafe {
            let layout = Layout::from_size_align(1024, 1).unwrap();
            let ptr = Global.alloc_zeroed(layout.clone())
                .unwrap_or_else(|_| handle_alloc_error(layout));

            let mut i = ptr.cast::<u8>().as_ptr();
            let end = i.offset(layout.size() as isize);
            while i < end {
                assert_eq!(*i, 0);
                i = i.offset(1);
            }
            Global.dealloc(ptr, layout);
        }
    }

    #[bench]
    fn alloc_owned_small(b: &mut Bencher) {
        b.iter(|| {
            let _: Box<_> = box 10;
        })
    }
}
<|endoftext|>