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

/// Entry in the element section.
pub struct ElementSegment {
    index: u32,
    offset: InitExpr,
    members: Vec<u32>,
}

impl ElementSegment {
    /// New element segment.
    pub fn new(index: u32, offset: InitExpr, members: Vec<u32>) -> Self {
        ElementSegment { index: index, offset: offset, members: members }
    }

    /// Sequence of function indices.
    pub fn members(&self) -> &[u32] { &self.members }

    /// Sequence of function indices (mutable)
    pub fn members_mut(&mut self) -> &mut Vec<u32> { &mut self.members }

    /// Table index (currently valid only value of `0`)
    pub fn index(&self) -> u32 { self.index }

    /// An i32 initializer expression that computes the offset at which to place the elements.
    pub fn offset(&self) -> &InitExpr { &self.offset }

    /// An i32 initializer expression that computes the offset at which to place the elements (mutable)
    pub fn offset_mut(&mut self) -> &mut InitExpr { &mut self.offset }
}

impl Deserialize for ElementSegment {
     type Error = Error;

    fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
        let index = VarUint32::deserialize(reader)?;
        let offset = InitExpr::deserialize(reader)?;
        let funcs: Vec<u32> = CountedList::<VarUint32>::deserialize(reader)?
            .into_inner()
            .into_iter()
            .map(Into::into)
            .collect();

        Ok(ElementSegment {
            index: index.into(),
            offset: offset,
            members: funcs,
        })
    }
}

impl Serialize for ElementSegment {
    type Error = Error;

    fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
        VarUint32::from(self.index).serialize(writer)?;
        self.offset.serialize(writer)?;
        let data = self.members;
        let counted_list = CountedListWriter::<VarUint32, _>(
            data.len(),
            data.into_iter().map(Into::into),
        );
        counted_list.serialize(writer)?;
        Ok(())
    }
}

/// Data segment definition.
pub struct DataSegment {
    index: u32,
    offset: InitExpr,
    value: Vec<u8>,
}

impl DataSegment {
    /// New data segments.
    pub fn new(index: u32, offset: InitExpr, value: Vec<u8>) -> Self {
        DataSegment {
            index: index,
            offset: offset,
            value: value,
        }
    }

    /// Linear memory index (currently the only valid value is `0`).
    pub fn index(&self) -> u32 { self.index }

    /// An i32 initializer expression that computes the offset at which to place the data.
    pub fn offset(&self) -> &InitExpr { &self.offset }

    /// An i32 initializer expression that computes the offset at which to place the data (mutable)
    pub fn offset_mut(&mut self) -> &mut InitExpr { &mut self.offset }

    /// Initial value of the data segment.
    pub fn value(&self) -> &[u8] { &self.value }

    /// Initial value of the data segment.
    pub fn value_mut(&mut self) -> &mut Vec<u8> { &mut self.value }
}

impl Deserialize for DataSegment {
     type Error = Error;

    fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
        let index = VarUint32::deserialize(reader)?;
        let offset = InitExpr::deserialize(reader)?;
        let value_len = VarUint32::deserialize(reader)?;

        let mut value_buf = vec![0u8; value_len.into()];
        reader.read_exact(&mut value_buf[..])?;

        Ok(DataSegment {
            index: index.into(),
            offset: offset,
            value: value_buf,
        })
    }
}

impl Serialize for DataSegment {
    type Error = Error;

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

        let value = self.value;
        VarUint32::from(value.len()).serialize(writer)?;
        writer.write_all(&value[..])?;
        Ok(())
    }
}<commit_msg>fix doc comment<commit_after>use std::io;
use super::{Deserialize, Serialize, Error, VarUint32, CountedList, InitExpr, CountedListWriter};

/// Entry in the element section.
pub struct ElementSegment {
    index: u32,
    offset: InitExpr,
    members: Vec<u32>,
}

impl ElementSegment {
    /// New element segment.
    pub fn new(index: u32, offset: InitExpr, members: Vec<u32>) -> Self {
        ElementSegment { index: index, offset: offset, members: members }
    }

    /// Sequence of function indices.
    pub fn members(&self) -> &[u32] { &self.members }

    /// Sequence of function indices (mutable)
    pub fn members_mut(&mut self) -> &mut Vec<u32> { &mut self.members }

    /// Table index (currently valid only value of `0`)
    pub fn index(&self) -> u32 { self.index }

    /// An i32 initializer expression that computes the offset at which to place the elements.
    pub fn offset(&self) -> &InitExpr { &self.offset }

    /// An i32 initializer expression that computes the offset at which to place the elements (mutable)
    pub fn offset_mut(&mut self) -> &mut InitExpr { &mut self.offset }
}

impl Deserialize for ElementSegment {
     type Error = Error;

    fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
        let index = VarUint32::deserialize(reader)?;
        let offset = InitExpr::deserialize(reader)?;
        let funcs: Vec<u32> = CountedList::<VarUint32>::deserialize(reader)?
            .into_inner()
            .into_iter()
            .map(Into::into)
            .collect();

        Ok(ElementSegment {
            index: index.into(),
            offset: offset,
            members: funcs,
        })
    }
}

impl Serialize for ElementSegment {
    type Error = Error;

    fn serialize<W: io::Write>(self, writer: &mut W) -> Result<(), Self::Error> {
        VarUint32::from(self.index).serialize(writer)?;
        self.offset.serialize(writer)?;
        let data = self.members;
        let counted_list = CountedListWriter::<VarUint32, _>(
            data.len(),
            data.into_iter().map(Into::into),
        );
        counted_list.serialize(writer)?;
        Ok(())
    }
}

/// Data segment definition.
pub struct DataSegment {
    index: u32,
    offset: InitExpr,
    value: Vec<u8>,
}

impl DataSegment {
    /// New data segments.
    pub fn new(index: u32, offset: InitExpr, value: Vec<u8>) -> Self {
        DataSegment {
            index: index,
            offset: offset,
            value: value,
        }
    }

    /// Linear memory index (currently the only valid value is `0`).
    pub fn index(&self) -> u32 { self.index }

    /// An i32 initializer expression that computes the offset at which to place the data.
    pub fn offset(&self) -> &InitExpr { &self.offset }

    /// An i32 initializer expression that computes the offset at which to place the data (mutable)
    pub fn offset_mut(&mut self) -> &mut InitExpr { &mut self.offset }

    /// Initial value of the data segment.
    pub fn value(&self) -> &[u8] { &self.value }

    /// Initial value of the data segment (mutable).
    pub fn value_mut(&mut self) -> &mut Vec<u8> { &mut self.value }
}

impl Deserialize for DataSegment {
     type Error = Error;

    fn deserialize<R: io::Read>(reader: &mut R) -> Result<Self, Self::Error> {
        let index = VarUint32::deserialize(reader)?;
        let offset = InitExpr::deserialize(reader)?;
        let value_len = VarUint32::deserialize(reader)?;

        let mut value_buf = vec![0u8; value_len.into()];
        reader.read_exact(&mut value_buf[..])?;

        Ok(DataSegment {
            index: index.into(),
            offset: offset,
            value: value_buf,
        })
    }
}

impl Serialize for DataSegment {
    type Error = Error;

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

        let value = self.value;
        VarUint32::from(value.len()).serialize(writer)?;
        writer.write_all(&value[..])?;
        Ok(())
    }
}<|endoftext|>


<commit_before>use std::rand;
use std::rand::Rng;
use client::PluginRegister;
use events::CommandEvent;

fn choose(event: &CommandEvent) {
    let content = event.args.connect(" ");
    let mut rng = rand::task_rng();
    let split = if content.contains(",") {
        regex!(r"\s*,\s*").split(content.as_slice()).collect::<Vec<&str>>()
    } else {
        regex!(r"\s+").split(content.as_slice()).collect::<Vec<&str>>()
    };
    let message = match rng.choose(split.as_slice()) {
        Some(v) => *v,
        None => "I don't have anything to choose from.",
    };
    event.client.send_message(event.channel(), message);
}

fn coin(event: &CommandEvent) {
    let mut rng = rand::task_rng();
    let message = format!("\x01ACTION flips a coin... \x02{}\x02\x01", rng.choose(&["heads", "tails"]).unwrap());
    event.client.send_message(event.channel(), message.as_slice());
}

pub fn register(register: &mut PluginRegister) {
    register.register_command("choose", choose);
    register.register_command("coin", coin);
}
<commit_msg>Add rand command for quickly generating random numbers to choose.rs<commit_after>use std::rand;
use std::rand::Rng;
use client::PluginRegister;
use events::CommandEvent;

fn choose(event: &CommandEvent) {
    let content = event.args.connect(" ");
    let mut rng = rand::task_rng();
    let split = if content.contains(",") {
        regex!(r"\s*,\s*").split(content.as_slice()).collect::<Vec<&str>>()
    } else {
        regex!(r"\s+").split(content.as_slice()).collect::<Vec<&str>>()
    };
    let message = match rng.choose(split.as_slice()) {
        Some(v) => *v,
        None => "I don't have anything to choose from.",
    };
    event.client.send_message(event.channel(), message);
}

fn coin(event: &CommandEvent) {
    let mut rng = rand::task_rng();
    let message = format!("\x01ACTION flips a coin... \x02{}\x02\x01", rng.choose(&["heads", "tails"]).unwrap());
    event.client.send_message(event.channel(), message.as_slice());
}

fn rand(event: &CommandEvent) {
    if event.args.len() != 1 {
        event.client.send_message(event.channel(), "Please specify exactly one argument.");
    }
    let max = match event.args[0].parse::<u64>() {
        Some(v) => v,
        None => {
            event.client.send_message(event.channel(), format!("Invalid number '{}'", event.args[0]).as_slice());
            return;
        },
    };
    let mut rng = rand::task_rng();
    event.client.send_message(event.channel(), format!("{}", rng.gen_range(1, max + 1)).as_slice())
}

pub fn register(register: &mut PluginRegister) {
    register.register_command("choose", choose);
    register.register_command("coin", coin);
    register.register_command("rand", rand);
}
<|endoftext|>


<commit_before>struct Coordinates {
    x: i32,
    y: i32,
}

fn main() {
    let origin = Coordinates { x: 0, y: 0 };

    println!("X is {} and Y is {}", origin.x + 1, origin.y + 90);

    let mut v = vec![1, 2];

    for i in &v {
        println!("A reference to {}", i);
    }

    for i in &mut v {
        println!("A mutable reference to {}", i);
    }

    for i in v {
        println!("Take ownership of the vector and its element {}", i);
    }

    println!("X is {} and Y is {}", move_right(origin.x), move_up(origin.y));
    println!("X is {} and Y is {}", move_right(origin.x), move_up(origin.y));
}

fn move_up(y_cord: i32) -> i32 {
    y_cord - 1
}

fn move_right(x_cord: i32) -> i32 {
    x_cord + 1
}
<commit_msg>can move up<commit_after>use std::cell::Cell;

struct Coordinates {
    x: Cell<i32>,
    y: Cell<i32>,
}

fn main() {
    let origin = Coordinates { x: Cell::new(0), y: Cell::new(0) };

    println!("X is {:?} and Y is {:?}", origin.x, origin.y);

    println!("X is {:?} and Y is {:?}", origin.x, move_up(origin.y));
}

fn move_up(y_cord: Cell<i32>) -> Cell<i32> {
    let new_val = y_cord.get();
    y_cord.set(&new_val + 1);
    y_cord // no semicolong here because it is the return value
}
<|endoftext|>


<commit_before>#[deriving(Show)]
#[deriving(Clone)]
pub enum Doc {
    Nil,
    Append(Box<Doc>, Box<Doc>),
    Nest(uint, Box<Doc>),
    Text(String),
    Break(uint, uint),
    Newline,
    Group(Box<Doc>)
}

impl Doc {
    pub fn append(&self, e:Doc) -> Doc {
        match self {
            &Nil => e,
            x => match e {
                Nil => x.clone(),
                y => Append(box x.clone(), box y)
            }
        }
    }
}

fn concat(ds:&[Doc]) -> Doc {
    ds.iter().fold(Nil, |a, b| Append(box a, box b.clone()))
}

fn int(i:int) -> Doc {
    Text(format!("{}", i))
}

fn char(c:char) -> Doc {
    Text(format!("{}", c))
}

fn bool(b:bool) -> Doc {
    if b {
        Text(String::from_str("true"))
    } else {
        Text(String::from_str("false"))
    }
}

mod mode {
    #[deriving(Clone)]
    pub enum Mode {
        Flat,
        Break
    }
}

fn replicate<A:Clone>(x:A, l:uint) -> Vec<A> {
    let i = 0u;
    let mut res = Vec::new();
    for _ in range(i,l) {
        res.push(x.clone());
    }
    res
}
fn pad_right(c:char, l:uint, str:String) -> String {
    let str_len = str.len();
    if l > str_len {
        let padding = replicate(String::from_chars([c]), l - str_len).concat();
        let mut res = str.clone();
        res.push_str(padding.as_slice());
        res
    } else {
        str
    }
}
fn pad_left(c:char, l:uint, str:String) -> String {
    let str_len = str.len();
    if l > str_len {
      let mut res = replicate(String::from_chars([c]), l - str_len).concat();
      res.push_str(str.as_slice());
      res
    } else {
        str
    }
}

fn nlspace<S>(outs:|S,String| -> S, s:S, i:uint) -> S {
    outs(s, pad_right(' ', i + String::from_str("\n").len(), String::from_str("\n")))
}

fn spaces<S>(outs:|S,String| -> S, s:S, i:uint) -> S {
    outs(s, pad_left(' ', i, String::from_str("")))
}

fn fitting(xs:&Vec<(uint,mode::Mode,Doc)>, left:uint) -> bool {
    if left as int >= 0 {
        match xs.as_slice() {
            [] => true,
            [(ref i, ref mode, ref doc), ref rest..] => match doc {
                &Nil => fitting(&rest.to_vec(), left),
                &Append(ref x, ref y) => {
                    let mut ys = [(*i,*mode,*x.clone()), (*i,*mode,*y.clone())].to_vec();
                    ys.push_all(*rest);
                    fitting(&ys,left)
                },
                &Nest(j, ref x) => {
                    let mut ys = [(*i+j,*mode,*x.clone())].to_vec();
                    ys.push_all(*rest);
                    fitting(&ys, left)
                },
                &Text(ref str) => fitting(&rest.to_vec(), left - str.len()),
                &Break(sp, _) => match *mode {
                    mode::Flat => fitting(&rest.to_vec(), left - sp),
                    mode::Break => true
                },
                &Newline => true,
                &Group(ref x) => {
                    let mut ys = [(*i,*mode, *x.clone())].to_vec();
                    ys.push_all(*rest);
                    fitting(&ys, left)
                }
            }
        }
    }
    else {
        false
    }
}

fn best<S:Clone>(w:uint, outs:|S, String| -> S, s:S, x:Doc) -> S {
    fn go<S:Clone>(w:uint, outs:|S,String| -> S, s:S, k:uint, xs:Vec<(uint,mode::Mode,Doc)>) -> S {
        match xs.as_slice() {
            [] => s.clone(),
            [(ref i, ref mode, ref doc), ref rest..] => match doc {
                &Nil => go(w, outs, s, k, rest.to_vec()),
                &Append(ref x, ref y) => {
                    let mut rest2 = [(*i,*mode,*x.clone()), (*i,*mode,*y.clone())].to_vec();
                    rest2.push_all(*rest);
                    go(w, outs, s, k, rest2)
                },
                &Nest(j, ref x) => {
                    let mut rest2 = [(*i+j,*mode,*x.clone())].to_vec();
                    rest2.push_all(*rest);
                    go(w, outs, s, k, rest2)
                },
                &Text(ref str) => {
                    let ss = outs(s, str.clone());
                    go(w, outs, ss, (k + str.len()), rest.to_vec())
                },
                &Newline => {
                    let ss = nlspace(|x,y| outs(x,y), s, *i);
                    go(w, outs, ss, *i, rest.to_vec())
                }
                &Break(sp, off) => {
                    match *mode {
                        mode::Flat => {
                            let ss = spaces(|x,y| outs(x,y), s.clone(), sp);
                            go(w, outs, ss, k + sp, rest.to_vec())
                        },
                        mode::Break => {
                            let ss = nlspace(|x,y| outs(x,y), s.clone(), i + off);
                            go(w, outs, ss, i + off, rest.to_vec())
                        }
                    }
                },
                &Group(ref x) => {
                    match *mode {
                        mode::Flat => {
                            let mut rest2 = [(*i,mode::Flat,*x.clone())].to_vec();
                            rest2.push_all(*rest);
                            go(w, outs, s, k, rest2)
                        },
                        mode::Break => {
                            let mut rest2 = [(*i,mode::Flat,*x.clone())].to_vec();
                            rest2.push_all(*rest);
                            if fitting(&rest2, w - k) {
                                go(w, outs, s, k, rest2)
                            } else {
                                let mut rest3 = [(*i,mode::Break,*x.clone())].to_vec();
                                rest3.push_all(*rest);
                                go(w, outs, s, k, rest3)
                            }
                        }
                    }
                }
            }
        }
    }
    go(w, outs, s, 0, [(0,mode::Break,x)].to_vec())
}

impl Doc {
    pub fn to_string(&self, w:uint) -> String {
        let outs = |strs:Vec<String>, s:String| -> Vec<String> {
            let mut welp = [s].to_vec();
            welp.push_all(strs.as_slice()); // horrible
            welp
        };

        let mut strs = best(w, outs, [].to_vec(), self.clone());
        strs.reverse();
        strs.push(String::from_str("\n"));
        strs.concat()
    }
}

fn main() {
}
<commit_msg>Futher cleanup; reduce polymorphism<commit_after>#![allow(dead_code)]
#![allow(unused_variable)]

#[deriving(Show)]
#[deriving(Clone)]
pub enum Doc {
    Nil,
    Append(Box<Doc>, Box<Doc>),
    Nest(uint, Box<Doc>),
    Text(String),
    Break(uint, uint),
    Newline,
    Group(Box<Doc>)
}

impl Doc {
    pub fn append(&self, e:Doc) -> Doc {
        match self {
            &Nil => e,
            x => match e {
                Nil => x.clone(),
                y => Append(box x.clone(), box y)
            }
        }
    }
}

fn concat(ds:&[Doc]) -> Doc {
    ds.iter().fold(Nil, |a, b| Append(box a, box b.clone()))
}

fn int(i:int) -> Doc {
    Text(format!("{}", i))
}

fn char(c:char) -> Doc {
    Text(format!("{}", c))
}

fn bool(b:bool) -> Doc {
    if b {
        Text(String::from_str("true"))
    } else {
        Text(String::from_str("false"))
    }
}

mod mode {
    #[deriving(Clone)]
    pub enum Mode {
        Flat,
        Break
    }
}

fn replicate<A:Clone>(x:A, l:uint) -> Vec<A> {
    let i = 0u;
    let mut res = Vec::new();
    for _ in range(i,l) {
        res.push(x.clone());
    }
    res
}
fn pad_right(c:char, l:uint, str:String) -> String {
    let str_len = str.len();
    if l > str_len {
        let padding = replicate(String::from_chars([c]), l - str_len).concat();
        let mut res = str.clone();
        res.push_str(padding.as_slice());
        res
    } else {
        str
    }
}
fn pad_left(c:char, l:uint, str:String) -> String {
    let str_len = str.len();
    if l > str_len {
      let mut res = replicate(String::from_chars([c]), l - str_len).concat();
      res.push_str(str.as_slice());
      res
    } else {
        str
    }
}

fn nlspace(s:Vec<String>, i:uint) -> Vec<String> {
    prepend(s, pad_right(' ', i + String::from_str("\n").len(), String::from_str("\n")))
}

fn spaces(s:Vec<String>, i:uint) -> Vec<String> {
    prepend(s, pad_left(' ', i, String::from_str("")))
}

fn fitting(xs:&Vec<(uint,mode::Mode,Doc)>, left:uint) -> bool {
    if left as int >= 0 {
        match xs.as_slice() {
            [] => true,
            [(ref i, ref mode, ref doc), ref rest..] => match *doc {
                Nil => fitting(&rest.to_vec(), left),
                Append(ref x, ref y) => {
                    let mut ys = [(*i,*mode,*x.clone()), (*i,*mode,*y.clone())].to_vec();
                    ys.push_all(*rest);
                    fitting(&ys,left)
                },
                Nest(j, ref x) => {
                    let mut ys = [(*i+j,*mode,*x.clone())].to_vec();
                    ys.push_all(*rest);
                    fitting(&ys, left)
                },
                Text(ref str) => fitting(&rest.to_vec(), left - str.len()),
                Break(sp, _) => match *mode {
                    mode::Flat => fitting(&rest.to_vec(), left - sp),
                    mode::Break => true
                },
                Newline => true,
                Group(ref x) => {
                    let mut ys = [(*i,*mode, *x.clone())].to_vec();
                    ys.push_all(*rest);
                    fitting(&ys, left)
                }
            }
        }
    }
    else {
        false
    }
}

fn prepend<A:Clone>(v: Vec<A>, x:A) -> Vec<A> {
    let mut res = [x].to_vec();
    res.push_all(v.as_slice());
    res
}

fn best(w:uint, s:Vec<String>, x:Doc) -> Vec<String> {
    fn go(w:uint, s:Vec<String>, k:uint, xs:Vec<(uint,mode::Mode,Doc)>) -> Vec<String> {
        match xs.as_slice() {
            [] => s.clone(),
            [(ref i, ref mode, ref doc), ref rest..] => match *doc {
                Nil => go(w, s, k, rest.to_vec()),
                Append(ref x, ref y) => {
                    let mut zs = [(*i, *mode, *x.clone()), (*i, *mode, *y.clone())].to_vec();
                    zs.push_all(*rest);
                    go(w, s, k, zs)
                },
                Nest(j, ref x) => {
                    let mut zs = [(*i + j, *mode, *x.clone())].to_vec();
                    zs.push_all(*rest);
                    go(w, s, k, zs)
                },
                Text(ref str) => {
                    let ss = prepend(s, str.clone());
                    go(w, ss, k + str.len(), rest.to_vec())
                },
                Newline => {
                    let ss = nlspace(s, *i);
                    go(w, ss, *i, rest.to_vec())
                },
                Break(sp, off) => {
                    match *mode {
                        mode::Flat => {
                            let ss = spaces(s.clone(), sp);
                            go(w, ss, k + sp, rest.to_vec())
                        },
                        mode::Break => {
                            let ss = nlspace(s.clone(), i + off);
                            go(w, ss, i + off, rest.to_vec())
                        }
                    }
                },
                Group(ref x) => {
                    match *mode {
                        mode::Flat => {
                            let mut zs = [(*i,mode::Flat,*x.clone())].to_vec();
                            zs.push_all(*rest);
                            go(w, s, k, zs)
                        },
                        mode::Break => {
                            let mut ys = [(*i,mode::Flat,*x.clone())].to_vec();
                            ys.push_all(*rest);
                            if fitting(&ys, w - k) {
                                go(w, s, k, ys)
                            } else {
                                let mut zs = [(*i,mode::Break,*x.clone())].to_vec();
                                zs.push_all(*rest);
                                go(w, s, k, zs)
                            }
                        }
                    }
                }
            }
        }
    }
    go(w, s, 0, [(0,mode::Break,x)].to_vec())
}

impl Doc {
    pub fn to_string(&self, w:uint) -> String {
        let mut strs = best(w, [].to_vec(), self.clone());
        strs.reverse();
        strs.push(String::from_str("\n"));
        strs.concat()
    }
}

fn main() {
}
<|endoftext|>


<commit_before>//! A simple evolutionary algorithm written in Rust.

extern crate rand;

use rand::Rng;
use std::collections::HashMap;

fn main() {
    let target = "METHINKS IT IS LIKE A WEASEL".to_string();
    println!("{}", target);

    let mut parent = String::new();
    generate_first_sentence(&mut parent);
    println!("{}", parent);

    let nb_copy = 400;
    let mutation_rate = 0.05;
    let mut counter = 0;

    while fitness(&target, &parent) != 0 {
        counter += 1;
        let mut sentences = HashMap::new();
        let mut f_min = 30;
        for _ in 0..nb_copy {
            let sentence = mutate(&mut parent, mutation_rate);
            let f = fitness(&target, &sentence);
            sentences.insert(f, sentence);

            if f < f_min {
                f_min = f
            }
        }

        if fitness(&target, &parent) > f_min {
            match sentences.get(&f_min) {
                Some(s) => {
                    parent = s.clone();
                    println!("{} : {}", parent, counter);
                }
                None => println!("Error, fitness minimum but no sentence."),
            }
        }
    }
}

fn fitness(target: &String, sentence: &String) -> u32 {
    let mut fitness = 0;
    for (c1, c2) in target.chars().zip(sentence.chars()) {
        if c1 != c2 {
            fitness += 1
        };
    }
    fitness
}

fn mutate(sentence: &mut String, mutation_rate: f64) -> String {
    let mut rng = rand::thread_rng();

    let mut mutation = String::new();
    for c in sentence.chars() {
        match mutation_rate > rng.gen_range(0f64, 1f64) {
            false => mutation.push(c),               // no mutation
            true => mutation.push(random_char()),   // mutation
        }
    }
    mutation
}

fn generate_first_sentence(parent: &mut String) {
    for _ in 0..28 {
        parent.push(random_char());
    }
}

fn random_char() -> char {
    match rand::thread_rng().gen_range('A' as u8, '\\' as u8) as char {
        '[' => ' ',
        c @ _ => c,
    }
}
<commit_msg>let the code breathe a little with some extra whitespace<commit_after>//! A simple evolutionary algorithm written in Rust.

extern crate rand;

use rand::Rng;
use std::collections::HashMap;

fn main() {
    let target = "METHINKS IT IS LIKE A WEASEL".to_string();
    println!("{}", target);

    let mut parent = String::new();
    generate_first_sentence(&mut parent);

    println!("{}", parent);

    let nb_copy = 400;
    let mutation_rate = 0.05;
    let mut counter = 0;

    while fitness(&target, &parent) != 0 {
        counter += 1;

        let mut sentences = HashMap::new();
        let mut f_min = 30;

        for _ in 0..nb_copy {
            let sentence = mutate(&mut parent, mutation_rate);
            let f = fitness(&target, &sentence);

            sentences.insert(f, sentence);

            if f < f_min {
                f_min = f
            }
        }

        if fitness(&target, &parent) > f_min {
            match sentences.get(&f_min) {
                Some(s) => {
                    parent = s.clone();
                    println!("{} : {}", parent, counter);
                }
                None => println!("Error, fitness minimum but no sentence."),
            }
        }
    }
}

fn fitness(target: &String, sentence: &String) -> u32 {
    let mut fitness = 0;

    for (c1, c2) in target.chars().zip(sentence.chars()) {
        if c1 != c2 {
            fitness += 1
        };
    }

    fitness
}

fn mutate(sentence: &mut String, mutation_rate: f64) -> String {
    let mut rng = rand::thread_rng();
    let mut mutation = String::new();

    for c in sentence.chars() {
        match mutation_rate > rng.gen_range(0f64, 1f64) {
            false => mutation.push(c),               // no mutation
            true => mutation.push(random_char()),   // mutation
        }
    }
    mutation
}

fn generate_first_sentence(parent: &mut String) {
    for _ in 0..28 {
        parent.push(random_char());
    }
}

fn random_char() -> char {
    match rand::thread_rng().gen_range('A' as u8, '\\' as u8) as char {
        '[' => ' ',
        c @ _ => c,
    }
}
<|endoftext|>


<commit_before>use std::io;
use std::io::BufReader;
use std::io::BufRead;
use std::collections::HashMap;

mod request;
mod turn;
mod region;
mod superregion;

use request::Request;
use turn::Turn;
use region::Region;
use superregion::SuperRegion;

fn main()
{
	std::env::set_var("RUST_BACKTRACE","1");
	let input = io::stdin();
	let input = BufReader::new(input);
	let input = input.lines();
	let input = input
		.map(Result::unwrap)
		.filter(|s|s.len()>0)
		.map(|s|s.parse::<Request>())
		.map(Result::unwrap);

	let mut name_you = String::new();
	let mut name_other = String::new();

	let mut sup_regions: HashMap<usize,SuperRegion> = HashMap::new();
	let mut regions: HashMap<usize,Region> = HashMap::new();

	let mut armies_left = 0;

	for req in input
	{
		use request::Request::*;
		match req
		{
			ListSuperRegions(sregions) =>
			{
				sup_regions.extend(sregions.iter().map(|sr|(sr.id,sr.clone())));
			},
			ListRegions(regs) =>
			{
				regions.extend(regs.iter().map(|r|(r.id,r.clone())));
			},
			ListNeighbours(relations) =>
			{
				for (id,neighbours) in relations
				{
					regions.get_mut(&id).unwrap().neighbours.extend(neighbours.iter());
					for n in neighbours
					{
						regions.get_mut(&n).unwrap().neighbours.push(id);
					}
				}
			},
			RequestStartingRegions(_avail) =>
			{
				println!("give me randomly");
			},
			SettingNameYou(name) => name_you = name,
			SettingNameOther(name) => name_other = name,
			SettingArmies(count) =>
			{
				armies_left = count;
			},
			UpdateMap(updates) =>
			{
				for u in updates
				{
					let mut reg = regions.get_mut(&u.0).unwrap();
					reg.player = u.1;
					reg.count = u.2;
				}
			},
			TurnOther(_turns) =>
			{
				//TODO: what the hell?
			},
			TurnPlace =>
			{
				let mut v = Vec::new();
				{
					let regs = regions.values()
						.filter(|r|r.player == name_you)
						.filter(|r|r.neighbours.iter()
							.map(|o|regions.get(o))
							.map(Option::unwrap)
							.filter(|o|o.player == name_other)
							.any(|o|o.count > r.count)
						).collect::<Vec<_>>();

					if armies_left > regs.len()
					{
						let count = if regs.len() > 0
						{
							armies_left/regs.len()
						}
						else
						{
							1
						};
						for r in regs.iter()
						{
							v.push(
								Turn::Place
								{
									name: name_you.clone(),
									region: r.id,
									count: count,
								}
							);
							armies_left -= count;
						}
						for r in regions.values()
							.filter(|r|r.player == name_you)
						{
							if armies_left <= 0
							{
								break;
							}
							v.push(
								Turn::Place
								{
									name: name_you.clone(),
									region: r.id,
									count: 1,
								}
							);
							armies_left -= 1;
						}
					}
					if v.len() <= 0
					{
						v.push(Turn::Noop);
					}
					let v = v.iter().map(|t|format!("{}",t)).collect::<Vec<_>>();
					println!("{}",v.join(","));
				}
				for r in v.iter()
				{
					if let &Turn::Place{region,count,..} = r
					{
						regions.get_mut(&region).unwrap().count += count;
					}
				}
			},
			TurnArmies =>
			{
				let mut v = Vec::new();
				let regs = regions.values()
					.filter(|r|r.player == name_you)
					.filter_map(|r|
					{
						let x =r.neighbours.iter()
						.map(|o|regions.get(o))
						.map(Option::unwrap)
						.filter(|o|o.player != name_you)
						.filter(|o|o.count*5 <= r.count*2)
						.next()
						.map(|o|o.id);
						if let Some(x) = x
						{
							Some(((r.id,(r.count*2)/3),x))
						}
						else
						{
							None
						}
					})
					.collect::<Vec<_>>();
				for ((r,count),n) in regs
				{
					v.push(
						Turn::Turn
						{
							name: name_you.clone(),
							source: r,
							target: n,
							count: count,
						}
					);
				}
				if v.len() <= 0
				{
					v.push(Turn::Noop);
				}
				let v = v.iter().map(|t|format!("{}",t)).collect::<Vec<_>>();
				println!("{}",v.join(","));
			},
		}
	}
}

<commit_msg>do not set 0 armies<commit_after>use std::io;
use std::io::BufReader;
use std::io::BufRead;
use std::collections::HashMap;

mod request;
mod turn;
mod region;
mod superregion;

use request::Request;
use turn::Turn;
use region::Region;
use superregion::SuperRegion;

fn main()
{
	std::env::set_var("RUST_BACKTRACE","1");
	let input = io::stdin();
	let input = BufReader::new(input);
	let input = input.lines();
	let input = input
		.map(Result::unwrap)
		.filter(|s|s.len()>0)
		.map(|s|s.parse::<Request>())
		.map(Result::unwrap);

	let mut name_you = String::new();
	let mut name_other = String::new();

	let mut sup_regions: HashMap<usize,SuperRegion> = HashMap::new();
	let mut regions: HashMap<usize,Region> = HashMap::new();

	let mut armies_left = 0;

	for req in input
	{
		use request::Request::*;
		match req
		{
			ListSuperRegions(sregions) =>
			{
				sup_regions.extend(sregions.iter().map(|sr|(sr.id,sr.clone())));
			},
			ListRegions(regs) =>
			{
				regions.extend(regs.iter().map(|r|(r.id,r.clone())));
			},
			ListNeighbours(relations) =>
			{
				for (id,neighbours) in relations
				{
					regions.get_mut(&id).unwrap().neighbours.extend(neighbours.iter());
					for n in neighbours
					{
						regions.get_mut(&n).unwrap().neighbours.push(id);
					}
				}
			},
			RequestStartingRegions(_avail) =>
			{
				println!("give me randomly");
			},
			SettingNameYou(name) => name_you = name,
			SettingNameOther(name) => name_other = name,
			SettingArmies(count) =>
			{
				armies_left = count;
			},
			UpdateMap(updates) =>
			{
				for u in updates
				{
					let mut reg = regions.get_mut(&u.0).unwrap();
					reg.player = u.1;
					reg.count = u.2;
				}
			},
			TurnOther(_turns) =>
			{
				//TODO: what the hell?
			},
			TurnPlace =>
			{
				let mut v = Vec::new();
				{
					let regs = regions.values()
						.filter(|r|r.player == name_you)
						.filter(|r|r.neighbours.iter()
							.map(|o|regions.get(o))
							.map(Option::unwrap)
							.filter(|o|o.player == name_other)
							.any(|o|o.count > r.count)
						).collect::<Vec<_>>();

					if armies_left > regs.len()
					{
						let count = if regs.len() > 0
						{
							armies_left/regs.len()
						}
						else
						{
							1
						};
						for r in regs.iter()
						{
							v.push(
								Turn::Place
								{
									name: name_you.clone(),
									region: r.id,
									count: count,
								}
							);
							armies_left -= count;
						}
						for r in regions.values()
							.filter(|r|r.player == name_you)
						{
							if armies_left <= 0
							{
								break;
							}
							v.push(
								Turn::Place
								{
									name: name_you.clone(),
									region: r.id,
									count: 1,
								}
							);
							armies_left -= 1;
						}
					}
					if v.len() <= 0
					{
						v.push(Turn::Noop);
					}
					let v = v.iter()
						.filter(|t|
							if let &&Turn::Place{count,..} = t
							{
								count > 0
							}
							else
							{
								true
							}
						)
						.map(|t|format!("{}",t))
						.collect::<Vec<_>>();
					println!("{}",v.join(","));
				}
				for r in v.iter()
				{
					if let &Turn::Place{region,count,..} = r
					{
						regions.get_mut(&region).unwrap().count += count;
					}
				}
			},
			TurnArmies =>
			{
				let mut v = Vec::new();
				let regs = regions.values()
					.filter(|r|r.player == name_you)
					.filter_map(|r|
					{
						let x =r.neighbours.iter()
						.map(|o|regions.get(o))
						.map(Option::unwrap)
						.filter(|o|o.player != name_you)
						.filter(|o|o.count*5 <= r.count*2)
						.next()
						.map(|o|o.id);
						if let Some(x) = x
						{
							Some(((r.id,(r.count*2)/3),x))
						}
						else
						{
							None
						}
					})
					.collect::<Vec<_>>();
				for ((r,count),n) in regs
				{
					v.push(
						Turn::Turn
						{
							name: name_you.clone(),
							source: r,
							target: n,
							count: count,
						}
					);
				}
				if v.len() <= 0
				{
					v.push(Turn::Noop);
				}
				let v = v.iter().map(|t|format!("{}",t)).collect::<Vec<_>>();
				println!("{}",v.join(","));
			},
		}
	}
}

<|endoftext|>


<commit_before>extern crate glutin;
extern crate libc;
extern crate gl;

fn main() {
    draw_window()
}

fn draw_window() {
  /// window drawing util is glutin from...  https://github.com/tomaka/glutin
    unsafe {
        let window = glutin::WindowBuilder::new()
            .with_title("Red Centipede 0.0.1-alpha".to_string())
            .build()
            .unwrap();

        window.make_current();

        gl::load_with(|symbol| window.get_proc_address(symbol));

        gl::ClearColor(0.0, 1.0, 0.0, 1.0);

        while !window.is_closed() {
            window.wait_events();

            gl::Clear(gl::COLOR_BUFFER_BIT);

            window.swap_buffers();
        }
    }
}<commit_msg>added resource and agent structs<commit_after>

fn main() {
    let first_agent = Agent {
        x: 0,
        y: 0,
        reserves: 100,
        chromosomes: vec!["ABCD1234".to_string(), "11100101".to_string()],
    };

    let some_resource = Resource {
        x: 10,
        y: 10,
        value: 100,
    };

    println!("\n")
    println!("I am first_agent my (x, y) is ({}, {})", first_agent.x, first_agent.y);
    println!("I have {} resources.", first_agent.reserves);
    println!("My chromosomes are {}.", first_agent.chromosomes);
    println!("\n")
    println!("I am some_resource my (x, y) is ({}, {})", some_resource.x, some_resource.y);
    println!("I have {} resources.", some_resource.value);
}

struct Agent  {
    x: int,
    y: int,
    reserves: int,
    chromosomes: Vec<String>,
}

struct Resource {
    x: int,
    y: int,
    value: int,
}

<|endoftext|>


<commit_before>use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;

#[derive(Debug)]
enum Token {
    LeftParen,
    RightParen,
    LeftBrace,
    RightBrace,
    Comma,
    Dot,
    Minus,
    Plus,
    Semicolon,
    Slash,
    Star,
    Bang,
    BangEqual,
    Greater,
    GreaterEqual,
    Less,
    LessEqual,
    Identifier(String),
    StringLiteral(String),
    NumberLiteral(u32),
    // Keywords
    And,
    Class,
    Else,
    False,
    Fun,
    For,
    If,
    Nil,
    Or,
    Print,
    Return,
    Super,
    This,
    True,
    Var,
    While,

    Eof,
}

#[derive(Debug)]
struct TokenWithContext {
    token: Token,
    lexeme: Option<String>, // TODO: make a reference
    line: usize,
}

struct Scanner {
    start: usize,
    current: usize,
    line: usize,
    source: String, // TODO: make a reference
}
impl Scanner {
    fn initialize(source: &String) -> Scanner {
        Scanner {
            start: 0,
            current: 0,
            line: 0,
            source: source.clone(),
        }
    }

    fn is_at_end(&self) -> bool {
        self.current >= self.source.len()
    }

    fn advance(&mut self) -> char {
        let result = self.source.chars().nth(self.current).unwrap();
        self.current += 1;
        result
    }

    fn add_simple_context(&self, token: Token) -> TokenWithContext {
        TokenWithContext {
            token: token,
            lexeme: None,
            line: self.line,
        }
    }

    fn scan_next(&mut self) -> TokenWithContext {
        match self.advance() {
            '(' => self.add_simple_context(Token::LeftParen),
            _ => unimplemented!(),
        }
    }
}

fn tokenize(source: &String) -> Result<Vec<TokenWithContext>, String> {
    let mut scanner = Scanner::initialize(source);
    let mut tokens = Vec::new();
    while !scanner.is_at_end() {
        tokens.push(scanner.scan_next());
    }
    tokens.push(TokenWithContext {
        token: Token::Eof,
        lexeme: None,
        line: scanner.line,
    });
    Ok(tokens)
}

fn run(source: &String) -> Result<(), String> {
    let tokens = try!(tokenize(source));
    for token in tokens {
        println!("{:?}", token);
    }
    Ok(())
}

fn run_file(file_name: &String) -> Result<(), String> {
    match File::open(file_name) {
        Err(_) => {
            Err("Error opening file".into()) // TODO: add context
        }
        Ok(mut file) => {
            let mut source = String::new();
            match file.read_to_string(&mut source) {
                Err(_) => {
                    Err("Error reading file".into()) // TODO: add context
                }
                Ok(_) => run(&source),
            }
        }
    }
}

fn run_prompt() -> Result<(), String> {
    loop {
        print!("> ");
        io::stdout().flush();
        let mut source = String::new();
        io::stdin().read_line(&mut source);
        try!(run(&source));
        ()
    }
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let result = match args.len() {
        // The first argument is the program name
        1 => run_prompt(),
        2 => run_file(&args[1]),
        _ => {
            println!("Usage: rulox [script]");
            Ok(())
        }
    };
    let exit_code = match result {
        Ok(_) => 0,
        Err(e) => {
            println!("{}", e);
            1
        }
    };
    std::process::exit(exit_code)
}
<commit_msg>Parentheses and braces<commit_after>use std::env;
use std::fs::File;
use std::io;
use std::io::prelude::*;

#[derive(Debug)]
enum Token {
    LeftParen,
    RightParen,
    LeftBrace,
    RightBrace,
    Comma,
    Dot,
    Minus,
    Plus,
    Semicolon,
    Slash,
    Star,
    Bang,
    BangEqual,
    Greater,
    GreaterEqual,
    Less,
    LessEqual,
    Identifier(String),
    StringLiteral(String),
    NumberLiteral(u32),
    // Keywords
    And,
    Class,
    Else,
    False,
    Fun,
    For,
    If,
    Nil,
    Or,
    Print,
    Return,
    Super,
    This,
    True,
    Var,
    While,

    Eof,
}

#[derive(Debug)]
struct TokenWithContext {
    token: Token,
    lexeme: Option<String>, // TODO: make a reference
    line: usize,
}

struct Scanner {
    start: usize,
    current: usize,
    line: usize,
    source: String, // TODO: make a reference
}
impl Scanner {
    fn initialize(source: &String) -> Scanner {
        Scanner {
            start: 0,
            current: 0,
            line: 0,
            source: source.clone(),
        }
    }

    fn is_at_end(&self) -> bool {
        self.current >= self.source.len()
    }

    fn advance(&mut self) -> char {
        let result = self.source.chars().nth(self.current).unwrap();
        self.current += 1;
        result
    }

    fn add_simple_context(&self, token: Token) -> TokenWithContext {
        TokenWithContext {
            token: token,
            lexeme: None,
            line: self.line,
        }
    }

    fn scan_next(&mut self) -> TokenWithContext {
        match self.advance() {
            '(' => self.add_simple_context(Token::LeftParen),
            ')' => self.add_simple_context(Token::RightParen),
            '{' => self.add_simple_context(Token::LeftBrace),
            '}' => self.add_simple_context(Token::RightBrace),
            _ => unimplemented!(),
        }
    }
}

fn tokenize(source: &String) -> Result<Vec<TokenWithContext>, String> {
    let mut scanner = Scanner::initialize(source);
    let mut tokens = Vec::new();
    while !scanner.is_at_end() {
        tokens.push(scanner.scan_next());
    }
    tokens.push(TokenWithContext {
        token: Token::Eof,
        lexeme: None,
        line: scanner.line,
    });
    Ok(tokens)
}

fn run(source: &String) -> Result<(), String> {
    let tokens = try!(tokenize(source));
    for token in tokens {
        println!("{:?}", token);
    }
    Ok(())
}

fn run_file(file_name: &String) -> Result<(), String> {
    match File::open(file_name) {
        Err(_) => {
            Err("Error opening file".into()) // TODO: add context
        }
        Ok(mut file) => {
            let mut source = String::new();
            match file.read_to_string(&mut source) {
                Err(_) => {
                    Err("Error reading file".into()) // TODO: add context
                }
                Ok(_) => run(&source),
            }
        }
    }
}

fn run_prompt() -> Result<(), String> {
    loop {
        print!("> ");
        io::stdout().flush();
        let mut source = String::new();
        io::stdin().read_line(&mut source);
        try!(run(&source));
        ()
    }
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let result = match args.len() {
        // The first argument is the program name
        1 => run_prompt(),
        2 => run_file(&args[1]),
        _ => {
            println!("Usage: rulox [script]");
            Ok(())
        }
    };
    let exit_code = match result {
        Ok(_) => 0,
        Err(e) => {
            println!("{}", e);
            1
        }
    };
    std::process::exit(exit_code)
}
<|endoftext|>


<commit_before>#![allow(unused)]

extern crate websocket;
extern crate futures;
extern crate tokio_core;
#[macro_use]
extern crate tokio_io;
extern crate tokio_stdin_stdout;

#[cfg(unix)]
extern crate tokio_file_unix;
#[cfg(unix)]
extern crate tokio_signal;

use std::thread;
use std::io::stdin;
use tokio_core::reactor::{Core, Handle};
use futures::future::Future;
use futures::sink::Sink;
use futures::stream::Stream;
use futures::sync::mpsc;
use websocket::result::WebSocketError;
use websocket::{ClientBuilder, OwnedMessage};
use tokio_io::{AsyncRead,AsyncWrite};
use std::io::{Read,Write};
use std::io::Result as IoResult;

use std::rc::Rc;
use std::cell::RefCell;

use websocket::stream::async::Stream as WsStream;
use futures::Async::{Ready, NotReady};

use tokio_io::io::copy;

use tokio_io::codec::FramedRead;
use std::fs::File;

#[cfg(unix)]
use tokio_file_unix::{File as UnixFile, StdFile};
#[cfg(unix)]
use std::os::unix::io::FromRawFd;

type Result<T> = std::result::Result<T, Box<std::error::Error>>;

#[cfg(feature="ssl")]
type WaitingForImplTraitFeature0 = tokio_io::codec::Framed<std::boxed::Box<websocket::async::Stream + std::marker::Send>, websocket::async::MessageCodec<websocket::OwnedMessage>>;
#[cfg(not(feature="ssl"))]
type WaitingForImplTraitFeature0 = tokio_io::codec::Framed<websocket::async::TcpStream, websocket::async::MessageCodec<websocket::OwnedMessage>>;
type WaitingForImplTraitFeature2 = futures::stream::SplitSink<WaitingForImplTraitFeature0>;
type WsSource = futures::stream::SplitStream<WaitingForImplTraitFeature0>;
type MultiProducerWsSink = Rc<RefCell<WaitingForImplTraitFeature2>>;

fn wouldblock<T>() -> std::io::Result<T> {
    Err(std::io::Error::new(std::io::ErrorKind::WouldBlock, ""))
}
fn brokenpipe<T>() -> std::io::Result<T> {
    Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, ""))
}
fn io_other_error<E : std::error::Error + Send + Sync + 'static>(e:E) -> std::io::Error {
    std::io::Error::new(std::io::ErrorKind::Other,e)
}

mod my_copy;

struct WsReadWrapper {
    s: WsSource,
    pingreply : MultiProducerWsSink,
    debt: Option<Vec<u8>>,
}

impl AsyncRead for WsReadWrapper {

}

impl WsReadWrapper {
    fn process_message(&mut self, buf: &mut [u8], buf_in: &[u8]) -> std::result::Result<usize, std::io::Error> {
        let l = buf_in.len().min(buf.len());
        buf[..l].copy_from_slice(&buf_in[..l]);

        if l < buf_in.len() {
            self.debt = Some(buf_in[l..].to_vec());
        }

        Ok(l)
    }
}

impl Read for WsReadWrapper {
    fn read(&mut self, buf: &mut [u8]) -> std::result::Result<usize, std::io::Error> {
        if let Some(debt) = self.debt.take() {
            return self.process_message(buf, debt.as_slice())
        }
        match self.s.poll().map_err(io_other_error)? {
            Ready(Some(OwnedMessage::Close(_))) => {
                brokenpipe()
            },
            Ready(None) => {
                brokenpipe()
            }
            Ready(Some(OwnedMessage::Ping(x))) => {
                let om = OwnedMessage::Pong(x);
                let mut sink = self.pingreply.borrow_mut();
                let mut proceed = false;
                // I'm not sure this is safe enough, RefCell-wise and Futures-wise
                // And pings and their replies are not tested yet
                match sink.start_send(om).map_err(io_other_error)? {
                    futures::AsyncSink::NotReady(_) => {
                        // drop the ping
                    },
                    futures::AsyncSink::Ready => {
                        proceed = true;
                    }
                }
                if proceed {
                    let _ = sink.poll_complete().map_err(io_other_error)?;
                }

                Ok(0)
            }
            Ready(Some(OwnedMessage::Pong(_))) => {
                Ok(0)
            }
            Ready(Some(OwnedMessage::Text(x))) => {
                self.process_message(buf, x.as_str().as_bytes())
            }
            Ready(Some(OwnedMessage::Binary(x))) => {
                self.process_message(buf, x.as_slice())
            }
            NotReady => {
                wouldblock()
            }
        }
    }
}

struct WsWriteWrapper(MultiProducerWsSink);

impl AsyncWrite for WsWriteWrapper {
    fn shutdown(&mut self) -> futures::Poll<(),std::io::Error> {
        // TODO: check this
        Ok(Ready(()))
    }
}

impl Write for WsWriteWrapper {
    fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
        let om = OwnedMessage::Binary(buf.to_vec());
        match self.0.borrow_mut().start_send(om).map_err(io_other_error)? {
            futures::AsyncSink::NotReady(_) => {
                wouldblock()
            },
            futures::AsyncSink::Ready => {
                Ok(buf.len())
            }
        }
    }
    fn flush(&mut self) -> IoResult<()> {
        match self.0.borrow_mut().poll_complete().map_err(io_other_error)? {
            NotReady => {
                wouldblock()
            },
            Ready(()) => {
                Ok(())
            }
        }
    }
}

impl Drop for WsWriteWrapper {
    fn drop(&mut self) {
        let mut sink = self.0.borrow_mut();
        sink.start_send(OwnedMessage::Close(None))
            .map_err(|_|())
            .map(|_|());
        sink.poll_complete()
            .map_err(|_|())
            .map(|_|());
    }
}

struct Peer(Box<AsyncRead>, Box<AsyncWrite>);

impl Peer {
    fn new<R:AsyncRead+'static, W:AsyncWrite+'static>(r:R, w:W) -> Self {
        Peer (
            Box::new(r) as Box<AsyncRead>,
            Box::new(w) as Box<AsyncWrite>,
        )
    }
}

type WaitingForImplTraitFeature4 = std::boxed::Box<futures::Future<Item=Peer, Error=std::boxed::Box<std::error::Error>>>;//futures::Map<(),Box<std::error::Error>>;

fn get_ws_client_peer(handle: &Handle, uri: &str) -> WaitingForImplTraitFeature4 {
    let before_connect = ClientBuilder::new(uri).unwrap()
        .add_protocol("rust-websocket");
    #[cfg(feature="ssl")]
    let after_connect = before_connect
        .async_connect(None, handle);
    #[cfg(not(feature="ssl"))]
    let after_connect = before_connect
        .async_connect_insecure(handle);
    Box::new(after_connect
        .map(|(duplex, _)| {
            let (sink, stream) = duplex.split();
            let mpsink = Rc::new(RefCell::new(sink));

            let ws_str = WsReadWrapper {
                s: stream,
                pingreply: mpsink.clone(),
                debt: None,
            };
            let ws_sin = WsWriteWrapper(mpsink);

            let ws = Peer::new(ws_str, ws_sin);
            ws
        })
        .map_err(|e|Box::new(e) as Box<std::error::Error>)
    ) as Box<Future<Item=Peer, Error=Box<std::error::Error>>>
}

struct Transfer {
    from: Box<AsyncRead>,
    to:   Box<AsyncWrite>,
}
struct Session(Transfer,Transfer);

type WaitingForImplTraitFeature3 = futures::stream::StreamFuture<futures::sync::mpsc::Receiver<()>>;

impl Session {
    fn run(self, handle: &Handle) -> WaitingForImplTraitFeature3 {
        let (notif1,rcv) = mpsc::channel::<()>(0);
        let notif2 = notif1.clone();
        handle.spawn(
            my_copy::copy(self.0.from, self.0.to, true)
                .map_err(|_|())
                .map(|_|{notif1;()})
        );
        handle.spawn(
            my_copy::copy(self.1.from, self.1.to, true)
                .map_err(|_|())
                .map(|_|{notif2;()})
        );
        rcv.into_future()
    }
    fn new(peer1: Peer, peer2: Peer) -> Self {
        Session (
            Transfer {
                from: peer1.0,
                to: peer2.1,
            },
            Transfer {
                from: peer2.0,
                to: peer1.1,
            },
        )
    }
}

fn run() -> Result<()> {
    let _        = std::env::args().nth(1).ok_or("Usage: websocat - ws[s]://...")?;
    let peeraddr = std::env::args().nth(2).ok_or("no second arg")?;

    //println!("Connecting to {}", peeraddr);
    let mut core = Core::new()?;
    let handle = core.handle();

    let si;
    let so;

    #[cfg(any(not(unix),feature="no_unix_stdio"))]
    {
        si = tokio_stdin_stdout::stdin(0);
        so = tokio_stdin_stdout::stdout(0);
    }

    #[cfg(all(unix,not(feature="no_unix_stdio")))]
    {
        let stdin  = UnixFile::new_nb(std::io::stdin())?;
        let stdout = UnixFile::new_nb(std::io::stdout())?;

        si = stdin.into_reader(&handle)?;
        so = stdout.into_io(&handle)?;

        let ctrl_c = tokio_signal::ctrl_c(&handle).flatten_stream();
        let prog = ctrl_c.for_each(|()| {
            UnixFile::raw_new(std::io::stdin()).set_nonblocking(false);
            UnixFile::raw_new(std::io::stdout()).set_nonblocking(false);
            ::std::process::exit(0);
            Ok(())
        });
        handle.spawn(prog.map_err(|_|()));
    }

    let runner = get_ws_client_peer(&core.handle(), peeraddr.as_ref())
        .and_then(|ws_peer| {
            let std = Peer::new(si, so);

            let s = Session::new(ws_peer,std);

            s.run(&handle)
                .map(|_|())
                .map_err(|_|unreachable!())
        });

    /*let before_connect = ClientBuilder::new(peeraddr.as_ref())?
        .add_protocol("rust-websocket");
    #[cfg(feature="ssl")]
    let after_connect = before_connect
        .async_connect(None, &core.handle());
    #[cfg(not(feature="ssl"))]
    let after_connect = before_connect
        .async_connect_insecure(&core.handle());
    let runner = after_connect
        .and_then(|(duplex, _)| {
            let (sink, stream) = duplex.split();
            let mpsink = Rc::new(RefCell::new(sink));

            let ws_str = WsReadWrapper {
                s: stream,
                pingreply: mpsink.clone(),
                debt: None,
            };
            let ws_sin = WsWriteWrapper(mpsink);

            let ws = Peer::new(ws_str, ws_sin);
            let std = Peer::new(si, so);

            let s = Session::new(ws,std);

            s.run(&handle)
                .map(|_|())
                .map_err(|_|unreachable!())
        });
    */
    core.run(runner)?;
    Ok(())
}

fn main() {
    let r = run();

    #[cfg(all(unix,not(feature="no_unix_stdio")))]
    {
        UnixFile::raw_new(std::io::stdin()).set_nonblocking(false);
        UnixFile::raw_new(std::io::stdout()).set_nonblocking(false);
    }

    if let Err(e) = r {
        eprintln!("websocat: {}", e);
        ::std::process::exit(1);
    }
}
<commit_msg>Second step in abstraction<commit_after>#![allow(unused)]

extern crate websocket;
extern crate futures;
extern crate tokio_core;
#[macro_use]
extern crate tokio_io;
extern crate tokio_stdin_stdout;

#[cfg(unix)]
extern crate tokio_file_unix;
#[cfg(unix)]
extern crate tokio_signal;

use std::thread;
use std::io::stdin;
use tokio_core::reactor::{Core, Handle};
use futures::future::Future;
use futures::sink::Sink;
use futures::stream::Stream;
use futures::sync::mpsc;
use websocket::result::WebSocketError;
use websocket::{ClientBuilder, OwnedMessage};
use tokio_io::{AsyncRead,AsyncWrite};
use std::io::{Read,Write};
use std::io::Result as IoResult;

use std::rc::Rc;
use std::cell::RefCell;

use websocket::stream::async::Stream as WsStream;
use futures::Async::{Ready, NotReady};

use tokio_io::io::copy;

use tokio_io::codec::FramedRead;
use std::fs::File;

#[cfg(unix)]
use tokio_file_unix::{File as UnixFile, StdFile};
#[cfg(unix)]
use std::os::unix::io::FromRawFd;

type Result<T> = std::result::Result<T, Box<std::error::Error>>;

#[cfg(feature="ssl")]
type WaitingForImplTraitFeature0 = tokio_io::codec::Framed<std::boxed::Box<websocket::async::Stream + std::marker::Send>, websocket::async::MessageCodec<websocket::OwnedMessage>>;
#[cfg(not(feature="ssl"))]
type WaitingForImplTraitFeature0 = tokio_io::codec::Framed<websocket::async::TcpStream, websocket::async::MessageCodec<websocket::OwnedMessage>>;
type WaitingForImplTraitFeature2 = futures::stream::SplitSink<WaitingForImplTraitFeature0>;
type WsSource = futures::stream::SplitStream<WaitingForImplTraitFeature0>;
type MultiProducerWsSink = Rc<RefCell<WaitingForImplTraitFeature2>>;

fn wouldblock<T>() -> std::io::Result<T> {
    Err(std::io::Error::new(std::io::ErrorKind::WouldBlock, ""))
}
fn brokenpipe<T>() -> std::io::Result<T> {
    Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, ""))
}
fn io_other_error<E : std::error::Error + Send + Sync + 'static>(e:E) -> std::io::Error {
    std::io::Error::new(std::io::ErrorKind::Other,e)
}

mod my_copy;

struct WsReadWrapper {
    s: WsSource,
    pingreply : MultiProducerWsSink,
    debt: Option<Vec<u8>>,
}

impl AsyncRead for WsReadWrapper {

}

impl WsReadWrapper {
    fn process_message(&mut self, buf: &mut [u8], buf_in: &[u8]) -> std::result::Result<usize, std::io::Error> {
        let l = buf_in.len().min(buf.len());
        buf[..l].copy_from_slice(&buf_in[..l]);

        if l < buf_in.len() {
            self.debt = Some(buf_in[l..].to_vec());
        }

        Ok(l)
    }
}

impl Read for WsReadWrapper {
    fn read(&mut self, buf: &mut [u8]) -> std::result::Result<usize, std::io::Error> {
        if let Some(debt) = self.debt.take() {
            return self.process_message(buf, debt.as_slice())
        }
        match self.s.poll().map_err(io_other_error)? {
            Ready(Some(OwnedMessage::Close(_))) => {
                brokenpipe()
            },
            Ready(None) => {
                brokenpipe()
            }
            Ready(Some(OwnedMessage::Ping(x))) => {
                let om = OwnedMessage::Pong(x);
                let mut sink = self.pingreply.borrow_mut();
                let mut proceed = false;
                // I'm not sure this is safe enough, RefCell-wise and Futures-wise
                // And pings and their replies are not tested yet
                match sink.start_send(om).map_err(io_other_error)? {
                    futures::AsyncSink::NotReady(_) => {
                        // drop the ping
                    },
                    futures::AsyncSink::Ready => {
                        proceed = true;
                    }
                }
                if proceed {
                    let _ = sink.poll_complete().map_err(io_other_error)?;
                }

                Ok(0)
            }
            Ready(Some(OwnedMessage::Pong(_))) => {
                Ok(0)
            }
            Ready(Some(OwnedMessage::Text(x))) => {
                self.process_message(buf, x.as_str().as_bytes())
            }
            Ready(Some(OwnedMessage::Binary(x))) => {
                self.process_message(buf, x.as_slice())
            }
            NotReady => {
                wouldblock()
            }
        }
    }
}

struct WsWriteWrapper(MultiProducerWsSink);

impl AsyncWrite for WsWriteWrapper {
    fn shutdown(&mut self) -> futures::Poll<(),std::io::Error> {
        // TODO: check this
        Ok(Ready(()))
    }
}

impl Write for WsWriteWrapper {
    fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
        let om = OwnedMessage::Binary(buf.to_vec());
        match self.0.borrow_mut().start_send(om).map_err(io_other_error)? {
            futures::AsyncSink::NotReady(_) => {
                wouldblock()
            },
            futures::AsyncSink::Ready => {
                Ok(buf.len())
            }
        }
    }
    fn flush(&mut self) -> IoResult<()> {
        match self.0.borrow_mut().poll_complete().map_err(io_other_error)? {
            NotReady => {
                wouldblock()
            },
            Ready(()) => {
                Ok(())
            }
        }
    }
}

impl Drop for WsWriteWrapper {
    fn drop(&mut self) {
        let mut sink = self.0.borrow_mut();
        sink.start_send(OwnedMessage::Close(None))
            .map_err(|_|())
            .map(|_|());
        sink.poll_complete()
            .map_err(|_|())
            .map(|_|());
    }
}

struct Peer(Box<AsyncRead>, Box<AsyncWrite>);

impl Peer {
    fn new<R:AsyncRead+'static, W:AsyncWrite+'static>(r:R, w:W) -> Self {
        Peer (
            Box::new(r) as Box<AsyncRead>,
            Box::new(w) as Box<AsyncWrite>,
        )
    }
}

type BoxedNewPeerFuture = Box<Future<Item=Peer, Error=Box<std::error::Error>>>;

fn get_ws_client_peer(handle: &Handle, uri: &str) -> BoxedNewPeerFuture {
    let stage1 = match ClientBuilder::new(uri) {
        Ok(x) => x,
        Err(e) => return Box::new(futures::future::err(Box::new(e) as Box<std::error::Error>)),
    };
    let before_connect = stage1
        .add_protocol("rust-websocket");
    #[cfg(feature="ssl")]
    let after_connect = before_connect
        .async_connect(None, handle);
    #[cfg(not(feature="ssl"))]
    let after_connect = before_connect
        .async_connect_insecure(handle);
    Box::new(after_connect
        .map(|(duplex, _)| {
            let (sink, stream) = duplex.split();
            let mpsink = Rc::new(RefCell::new(sink));

            let ws_str = WsReadWrapper {
                s: stream,
                pingreply: mpsink.clone(),
                debt: None,
            };
            let ws_sin = WsWriteWrapper(mpsink);

            let ws = Peer::new(ws_str, ws_sin);
            ws
        })
        .map_err(|e|Box::new(e) as Box<std::error::Error>)
    ) as BoxedNewPeerFuture
}

fn get_stdio_peer_impl(handle: &Handle) -> Result<Peer> {
    let si;
    let so;

    #[cfg(any(not(unix),feature="no_unix_stdio"))]
    {
        si = tokio_stdin_stdout::stdin(0);
        so = tokio_stdin_stdout::stdout(0);
    }

    #[cfg(all(unix,not(feature="no_unix_stdio")))]
    {
        let stdin  = UnixFile::new_nb(std::io::stdin())?;
        let stdout = UnixFile::new_nb(std::io::stdout())?;

        si = stdin.into_reader(&handle)?;
        so = stdout.into_io(&handle)?;

        let ctrl_c = tokio_signal::ctrl_c(&handle).flatten_stream();
        let prog = ctrl_c.for_each(|()| {
            UnixFile::raw_new(std::io::stdin()).set_nonblocking(false);
            UnixFile::raw_new(std::io::stdout()).set_nonblocking(false);
            ::std::process::exit(0);
            Ok(())
        });
        handle.spawn(prog.map_err(|_|()));
    }
    Ok(Peer::new(si,so))
}

fn get_stdio_peer(handle: &Handle) -> BoxedNewPeerFuture {
    Box::new(futures::future::result(get_stdio_peer_impl(handle))) as BoxedNewPeerFuture
}

struct Transfer {
    from: Box<AsyncRead>,
    to:   Box<AsyncWrite>,
}
struct Session(Transfer,Transfer);

type WaitingForImplTraitFeature3 = futures::stream::StreamFuture<futures::sync::mpsc::Receiver<()>>;

impl Session {
    fn run(self, handle: &Handle) -> WaitingForImplTraitFeature3 {
        let (notif1,rcv) = mpsc::channel::<()>(0);
        let notif2 = notif1.clone();
        handle.spawn(
            my_copy::copy(self.0.from, self.0.to, true)
                .map_err(|_|())
                .map(|_|{notif1;()})
        );
        handle.spawn(
            my_copy::copy(self.1.from, self.1.to, true)
                .map_err(|_|())
                .map(|_|{notif2;()})
        );
        rcv.into_future()
    }
    fn new(peer1: Peer, peer2: Peer) -> Self {
        Session (
            Transfer {
                from: peer1.0,
                to: peer2.1,
            },
            Transfer {
                from: peer2.0,
                to: peer1.1,
            },
        )
    }
}

fn run() -> Result<()> {
    let _        = std::env::args().nth(1).ok_or("Usage: websocat - ws[s]://...")?;
    let peeraddr = std::env::args().nth(2).ok_or("no second arg")?;

    //println!("Connecting to {}", peeraddr);
    let mut core = Core::new()?;
    let handle = core.handle();

    let h1 = core.handle();
    let h2 = core.handle();

    let runner = get_ws_client_peer(&h1, peeraddr.as_ref())
    .and_then(|ws_peer| {
        get_stdio_peer(&h2)
        .and_then(|std_peer| {
            let s = Session::new(ws_peer,std_peer);

            s.run(&handle)
                .map(|_|())
                .map_err(|_|unreachable!())
        })
    });

    core.run(runner)?;
    Ok(())
}

fn main() {
    let r = run();

    #[cfg(all(unix,not(feature="no_unix_stdio")))]
    {
        UnixFile::raw_new(std::io::stdin()).set_nonblocking(false);
        UnixFile::raw_new(std::io::stdout()).set_nonblocking(false);
    }

    if let Err(e) = r {
        eprintln!("websocat: {}", e);
        ::std::process::exit(1);
    }
}
<|endoftext|>


<commit_before>extern crate rayon;

use rayon::prelude::*;

use std::process::Command;
use std::fs::File;
use std::io::Write;
use std::os::raw;
use std::io::Read;

pub mod descriptions;

use descriptions::*;

#[cfg(target_os="windows")]
const VASM_EXE: &'static str = "bin/win/vasmm68k_mot.exe";

#[cfg(target_os="macos")]
const VASM_EXE: &'static str = "bin/mac/vasmm68k_mot";

#[cfg(any(target_os="linux",
          target_os="freebsd",
          target_os="dragonfly",
          target_os="netbsd",
          target_os="openbsd"))]
const VASM_EXE: &'static str = "vasmm68k_mot";

struct BuildResult {
    src: Option<Op>,
    dst: Op,
    temp_file: String,
    temp_out: String,
    cycle_count: Option<usize>,
}

#[derive(Copy, Clone)]
struct Op {
    name: &'static str,
    print_name: &'static str,
}

impl Op {
    fn new(name: &'static str, print_name: &'static str) -> Op {
        Op {
            name: name,
            print_name: print_name,
        }
    }
}
struct Instruction {
    name: &'static str,
    _desc: Option<Description>,
}

fn compile_statement(filename: &str, file_out: &str, statement: &str) -> bool {
    {
        let mut file = File::create(filename).unwrap();
        write!(file, " {}", statement).unwrap();
    }

    let output = Command::new(VASM_EXE)
        .arg(filename)
        .arg("-Fbin")
        .arg("-o")
        .arg(file_out)
        .output()
        .expect("failed to execute process");

    output.status.success()
}

fn print_grid_table(name: &str, cycles: &Vec<BuildResult>, src_table: &[Op], dest_table: &[Op]) {
    print!("| {name:<width$}", name = name, width = 9);

    for dst in dest_table {
        print!("| {} ", dst.print_name);
    }

    println!("|");
    println!("|----------|----|----|------|-------|-------|-------|----------|-------|-------|");

    let mut index = 0;

    for src in src_table {
        let mut skip_count = 0;

        for i in index..index + 9 {
            if let None = cycles[i].cycle_count {
                skip_count += 1;
            }
        }

        if skip_count != 9 {
            print!("| {name:<width$}", name = src.print_name, width = 9);

            for dest in dest_table {
                if let Some(cycle_count) = cycles[index].cycle_count {
                    print!("|{number:^width$}",
                           number = cycle_count,
                           width = dest.print_name.len() + 2);
                } else {
                    print!("|{number:^width$}",
                           number = "*",
                           width = dest.print_name.len() + 2);
                }
                index += 1;
            }

            println!("|");
        } else {
            index += 9;
        }
    }

    println!("");
}

fn print_table(name: &str, cycles: &Vec<BuildResult>, dest_table: &[Op]) {
    print!("| {name:<width$}", name = name, width = 9);

    for dst in dest_table {
        print!("| {} ", dst.print_name);
    }

    println!("|");
    println!("|----------|----|----|------|-------|-------|-------|----------|-------|-------|");

    let mut index = 0;

    print!("| {name:<width$}", name = " ", width = 9);

    for dest in dest_table {
        if let Some(cycle_count) = cycles[index].cycle_count {
            print!("|{number:^width$}",
                   number = cycle_count,
                   width = dest.print_name.len() + 2);
        } else {
            print!("|{number:^width$}",
                   number = "*",
                   width = dest.print_name.len() + 2);
        }
        index += 1;
    }

    println!("|");
    println!("");
}

fn print_instruction_header(inst: &Instruction) {
    let name = inst.name.to_uppercase();
    println!("## {}\n", name);
    if let Some(ref desc) = inst._desc {
        println!("**Operation:**      {}\n", desc.operation);

        print!("**Assembler:** ");
        for assem in desc.assembler {
            print!("{}        ", assem);
        }
        println!("\n\n**Attributes:** Size = ({})\n", desc.attributes);

        println!("**Description:** {}\n", desc.description);
    }
    else {
        println!("__No Description__\n");
    }
}

fn compile_cycle_counts(statements: &mut Vec<BuildResult>) {
    let mut instructions = Vec::new();
    let mut inst_count = 0u32;
    let mut cycle_count = Vec::<u32>::new();

    for statement in statements.iter() {
        if statement.cycle_count.is_some() {
            {
                let mut f = File::open(&statement.temp_out).unwrap();
                f.read_to_end(&mut instructions).unwrap();
                cycle_count.push(0);
                inst_count += 1;
            }
        }
    }

    unsafe {
        m68k_run_instructions(instructions.as_ptr() as *const raw::c_void, inst_count, cycle_count.as_mut_ptr());
    }

    inst_count = 0;

    for statement in statements.iter_mut() {
        if statement.cycle_count.is_some() {
            statement.cycle_count = Some(cycle_count[inst_count as usize] as usize);
            inst_count += 1;
        }
    }
}

fn generate_table(name: &str,
                  src_table: Option<&[Op]>,
                  dest_table: &[Op]) {
    let mut statements = Vec::with_capacity(20 * 20);
    let mut count = 0;

    if let Some(src_opts) = src_table {
        for src in src_opts {
            for dst in dest_table {
                let file_in = format!("target/temp_{}.s", count);
                let file_out = format!("target/temp_{}.o", count);

                statements.push(BuildResult {
                    src: Some(src.clone()),
                    dst: dst.clone(),
                    temp_file: file_in,
                    temp_out: file_out,
                    cycle_count: None,
                });

                count += 1;
            }
        }

        statements.par_iter_mut().weight_max().for_each(|v| {
            let statement = format!("{} {},{}", name, v.src.unwrap().name, v.dst.name);
            if compile_statement(&v.temp_file, &v.temp_out, &statement) {
                v.cycle_count = Some(0); // indicate that this should be processed
            }
        });

        compile_cycle_counts(&mut statements);

        print_grid_table(name, &statements, &src_opts, dest_table);
    } else {
        for dst in dest_table {
            let file_in = format!("target/temp_{}.s", count);
            let file_out = format!("target/temp_{}.o", count);

            statements.push(BuildResult {
                src: None,
                dst: dst.clone(),
                temp_file: file_in,
                temp_out: file_out,
                cycle_count: None,
            });

            count += 1;
        }

        statements.par_iter_mut().weight_max().for_each(|v| {
            let statement = format!("{} {}", name, v.dst.name);
            if compile_statement(&v.temp_file, &v.temp_out, &statement) {
                v.cycle_count = Some(0);
            }
        });

        compile_cycle_counts(&mut statements);

        print_table(name, &statements, dest_table);
    }
}

fn main() {
    let dest_types = [
        Op::new("d0", "Dn"),
        Op::new("a0", "An"),
        Op::new("(a0)", "(An)"),
        Op::new("(a0)+", "(An)+"),
        Op::new("-(a0)", "-(An)"),
        Op::new("2(a0)", "d(An)"),
        Op::new("2(a0,d0)", "d(An,Dn)"),
        Op::new("$4.W", "xxx.W"),
        Op::new("$4.L", "xxx.L")];

    let src_types = [
        Op::new("d0", "Dn"),
        Op::new("a0", "An"),
        Op::new("(a0)", "(An)"),
        Op::new("(a0)+", "(An)+"),
        Op::new("-(a0)", "-(An)"),
        Op::new("2(a0)", "d(An)"),
        Op::new("2(a0,d0)", "d(An,Dn)"),
        Op::new("$4.W", "xxx.W"),
        Op::new("$4.L", "xxx.L"),
        Op::new("2(pc)", "d(PC)"),
        Op::new("2(pc,d0)", "d(PC,Dn)"),
        Op::new("#2", "#xxx")];

    let dest_types_none = [Op::new("", "")];

    unsafe {
        m68k_wrapper_init();
    }

    let inst_2_ops_000 =
        [
        Instruction {
            name: "abcd",
            _desc: Some(ABCD_DESC),
        },

        Instruction {
            name: "add",
            _desc: Some(ADD_DESC),
        },
        Instruction {
            name: "addq",
            _desc: Some(ADDQ_DESC),
        },
        Instruction {
            name: "addx",
            _desc: Some(ADDX_DESC),
        },
        Instruction {
            name: "and",
            _desc: Some(AND_DESC),
        },
        Instruction {
            name: "bchg",
            _desc: Some(BCHG_DESC),
        },
        Instruction {
            name: "bclr",
            _desc: Some(BCLR_DESC),
        },
        Instruction {
            name: "bset",
            _desc: Some(BSET_DESC),
        },
        Instruction {
            name: "btst",
            _desc: Some(BTST_DESC),
        },
        Instruction {
            name: "cmp",
            _desc: Some(CMP_DESC),
        },
        Instruction {
            name: "divu",
            _desc: Some(DIVS_DIVU_DESC),
        },
        Instruction {
            name: "divs",
            _desc: Some(DIVS_DIVU_DESC),
        },
        Instruction {
            name: "eor",
            _desc: Some(EOR_DESC),
        },
        Instruction {
            name: "exg",
            _desc: Some(EXG_DESC),
        },
        Instruction {
            name: "lea",
            _desc: Some(LEA_DESC),
        },
        Instruction {
            name: "move",
            _desc: Some(MOVE_DESC),
        },
        Instruction {
            name: "muls",
            _desc: Some(MULS_DESC),
        },
        Instruction {
            name: "mulu",
            _desc: Some(MULU_DESC),
        },
        Instruction {
            name: "or",
            _desc: Some(OR_DESC),
        },
        Instruction {
            name: "sub",
            _desc: Some(SUB_DESC),
        },
        Instruction {
            name: "subq",
            _desc: Some(SUBQ_DESC),
        },
        Instruction {
            name: "subx",
            _desc: Some(SUBX_DESC),
        },
        ];

    let inst_1_ops_000 = [
        Instruction {
            name: "clr",
            _desc: Some(CLR_DESC),
        },
        Instruction {
            name: "ext",
            _desc: Some(EXT_DESC),
        },
        Instruction {
            name: "bsr",
            _desc: Some(BSR_DESC),
        },
        Instruction {
            name: "jsr",
            _desc: Some(JSR_DESC),
        },
        Instruction {
            name: "jmp",
            _desc: Some(JMP_DESC),
        },
        Instruction {
            name: "neg",
            _desc: Some(NEG_DESC),
        },
        Instruction {
            name: "not",
            _desc: Some(NOT_DESC),
        },
        Instruction {
            name: "swap",
            _desc: Some(SWAP_DESC),
        },
        ];

    let inst_0_ops_000 = [
        Instruction {
            name: "nop",
            _desc: Some(NOP_DESC),
        },
        Instruction {
            name: "illegal",
            _desc: None,
        },
        Instruction {
            name: "rte",
            _desc: Some(RTS_DESC),
        },
        Instruction {
            name: "rts",
            _desc: Some(RTS_DESC),
        },
    ];

    for inst in &inst_2_ops_000 {
        let name_long = format!("{}.l", inst.name);

        print_instruction_header(inst);
        generate_table(inst.name, Some(&src_types), &dest_types);
        generate_table(&name_long, Some(&src_types), &dest_types);
    }

    // Generate instructions with one op

    for inst in &inst_1_ops_000 {
        let name_long = format!("{}.l", inst.name);

        print_instruction_header(inst);
        generate_table(inst.name, None, &dest_types);
        generate_table(&name_long, None, &dest_types);
    }

    //

    // Generate instructions with no ops

    for inst in &inst_0_ops_000 {
        let name_long = format!("{}.l", inst.name);

        print_instruction_header(inst);
        generate_table(inst.name, None, &dest_types_none);
        generate_table(&name_long, None, &dest_types_none);
    }
}

extern "C" {
    fn m68k_wrapper_init();
    fn m68k_run_instructions(instructions: *const raw::c_void, count: u32, cycle_res: *mut u32);
}

<commit_msg>Force larger opts to prevnt opts<commit_after>extern crate rayon;

use rayon::prelude::*;

use std::process::Command;
use std::fs::File;
use std::io::Write;
use std::os::raw;
use std::io::Read;

pub mod descriptions;

use descriptions::*;

#[cfg(target_os="windows")]
const VASM_EXE: &'static str = "bin/win/vasmm68k_mot.exe";

#[cfg(target_os="macos")]
const VASM_EXE: &'static str = "bin/mac/vasmm68k_mot";

#[cfg(any(target_os="linux",
          target_os="freebsd",
          target_os="dragonfly",
          target_os="netbsd",
          target_os="openbsd"))]
const VASM_EXE: &'static str = "vasmm68k_mot";

struct BuildResult {
    src: Option<Op>,
    dst: Op,
    temp_file: String,
    temp_out: String,
    cycle_count: Option<usize>,
}

#[derive(Copy, Clone)]
struct Op {
    name: &'static str,
    print_name: &'static str,
}

impl Op {
    fn new(name: &'static str, print_name: &'static str) -> Op {
        Op {
            name: name,
            print_name: print_name,
        }
    }
}
struct Instruction {
    name: &'static str,
    _desc: Option<Description>,
}

fn compile_statement(filename: &str, file_out: &str, statement: &str) -> bool {
    {
        let mut file = File::create(filename).unwrap();
        write!(file, " {}", statement).unwrap();
    }

    let output = Command::new(VASM_EXE)
        .arg("-no-opt")
        .arg("-m68000")
        .arg(filename)
        .arg("-Fbin")
        .arg("-o")
        .arg(file_out)
        .output()
        .expect("failed to execute process");

    output.status.success()
}

fn print_grid_table(name: &str, cycles: &Vec<BuildResult>, src_table: &[Op], dest_table: &[Op]) {
    print!("| {name:<width$}", name = name, width = 9);

    for dst in dest_table {
        print!("| {} ", dst.print_name);
    }

    println!("|");
    println!("|----------|----|----|------|-------|-------|-------|----------|-------|-------|");

    let mut index = 0;

    for src in src_table {
        let mut skip_count = 0;

        for i in index..index + 9 {
            if let None = cycles[i].cycle_count {
                skip_count += 1;
            }
        }

        if skip_count != 9 {
            print!("| {name:<width$}", name = src.print_name, width = 9);

            for dest in dest_table {
                if let Some(cycle_count) = cycles[index].cycle_count {
                    print!("|{number:^width$}",
                           number = cycle_count,
                           width = dest.print_name.len() + 2);
                } else {
                    print!("|{number:^width$}",
                           number = "*",
                           width = dest.print_name.len() + 2);
                }
                index += 1;
            }

            println!("|");
        } else {
            index += 9;
        }
    }

    println!("");
}

fn print_table(name: &str, cycles: &Vec<BuildResult>, dest_table: &[Op]) {
    print!("| {name:<width$}", name = name, width = 9);

    for dst in dest_table {
        print!("| {} ", dst.print_name);
    }

    println!("|");
    println!("|----------|----|----|------|-------|-------|-------|----------|-------|-------|");

    let mut index = 0;

    print!("| {name:<width$}", name = " ", width = 9);

    for dest in dest_table {
        if let Some(cycle_count) = cycles[index].cycle_count {
            print!("|{number:^width$}",
                   number = cycle_count,
                   width = dest.print_name.len() + 2);
        } else {
            print!("|{number:^width$}",
                   number = "*",
                   width = dest.print_name.len() + 2);
        }
        index += 1;
    }

    println!("|");
    println!("");
}

fn print_instruction_header(inst: &Instruction) {
    let name = inst.name.to_uppercase();
    println!("## {}\n", name);
    if let Some(ref desc) = inst._desc {
        println!("**Operation:**      {}\n", desc.operation);

        print!("**Assembler:** ");
        for assem in desc.assembler {
            print!("{}        ", assem);
        }
        println!("\n\n**Attributes:** Size = ({})\n", desc.attributes);

        println!("**Description:** {}\n", desc.description);
    }
    else {
        println!("__No Description__\n");
    }
}

fn compile_cycle_counts(statements: &mut Vec<BuildResult>) {
    let mut instructions = Vec::new();
    let mut inst_count = 0u32;
    let mut cycle_count = Vec::<u32>::new();

    for statement in statements.iter() {
        if statement.cycle_count.is_some() {
            {
                let mut f = File::open(&statement.temp_out).unwrap();
                f.read_to_end(&mut instructions).unwrap();
                cycle_count.push(0);
                inst_count += 1;
            }
        }
    }

    unsafe {
        m68k_run_instructions(instructions.as_ptr() as *const raw::c_void, inst_count, cycle_count.as_mut_ptr());
    }

    inst_count = 0;

    for statement in statements.iter_mut() {
        if statement.cycle_count.is_some() {
            statement.cycle_count = Some(cycle_count[inst_count as usize] as usize);
            inst_count += 1;
        }
    }
}

fn generate_table(name: &str,
                  is_long: bool,
                  src_table: Option<&[Op]>,
                  dest_table: &[Op]) {
    let mut statements = Vec::with_capacity(20 * 20);
    let mut count = 0;

    if let Some(src_opts) = src_table {
        for src in src_opts {
            for dst in dest_table {
                let file_in = format!("target/temp_{}.s", count);
                let file_out = format!("target/temp_{}.o", count);

                statements.push(BuildResult {
                    src: Some(src.clone()),
                    dst: dst.clone(),
                    temp_file: file_in,
                    temp_out: file_out,
                    cycle_count: None,
                });

                count += 1;
            }
        }

        statements.par_iter_mut().weight_max().for_each(|v| {
            let src = v.src.unwrap();
            let statement;

            if src.print_name == "#xxx" && is_long {
                statement = format!("{} {},{}", name, "#$ffffff", v.dst.name);
            } else {
                statement = format!("{} {},{}", name, v.src.unwrap().name, v.dst.name);
            }

            //println!("Statement {}", statement);
            if compile_statement(&v.temp_file, &v.temp_out, &statement) {
                v.cycle_count = Some(0); // indicate that this should be processed
            }
        });

        compile_cycle_counts(&mut statements);

        print_grid_table(name, &statements, &src_opts, dest_table);
    } else {
        for dst in dest_table {
            let file_in = format!("target/temp_{}.s", count);
            let file_out = format!("target/temp_{}.o", count);

            statements.push(BuildResult {
                src: None,
                dst: dst.clone(),
                temp_file: file_in,
                temp_out: file_out,
                cycle_count: None,
            });

            count += 1;
        }

        statements.par_iter_mut().weight_max().for_each(|v| {
            let statement = format!("{} {}", name, v.dst.name);
            if compile_statement(&v.temp_file, &v.temp_out, &statement) {
                v.cycle_count = Some(0);
            }
        });

        compile_cycle_counts(&mut statements);

        print_table(name, &statements, dest_table);
    }
}

fn main() {
    let dest_types = [
        Op::new("d0", "Dn"),
        Op::new("a0", "An"),
        Op::new("(a0)", "(An)"),
        Op::new("(a0)+", "(An)+"),
        Op::new("-(a0)", "-(An)"),
        Op::new("2(a0)", "d(An)"),
        Op::new("2(a0,d0)", "d(An,Dn)"),
        Op::new("$4.W", "xxx.W"),
        Op::new("$4.L", "xxx.L")];

    let src_types = [
        Op::new("d0", "Dn"),
        Op::new("a0", "An"),
        Op::new("(a0)", "(An)"),
        Op::new("(a0)+", "(An)+"),
        Op::new("-(a0)", "-(An)"),
        Op::new("2(a0)", "d(An)"),
        Op::new("2(a0,d0)", "d(An,Dn)"),
        Op::new("$4.W", "xxx.W"),
        Op::new("$4.L", "xxx.L"),
        Op::new("2(pc)", "d(PC)"),
        Op::new("2(pc,d0)", "d(PC,Dn)"),
        Op::new("#2000", "#xxx")];

    let dest_types_none = [Op::new("", "")];

    unsafe {
        m68k_wrapper_init();
    }

    let inst_2_ops_000 =
        [
        Instruction {
            name: "abcd",
            _desc: Some(ABCD_DESC),
        },

        Instruction {
            name: "add",
            _desc: Some(ADD_DESC),
        },
        Instruction {
            name: "addq",
            _desc: Some(ADDQ_DESC),
        },
        Instruction {
            name: "addx",
            _desc: Some(ADDX_DESC),
        },
        Instruction {
            name: "and",
            _desc: Some(AND_DESC),
        },
        Instruction {
            name: "bchg",
            _desc: Some(BCHG_DESC),
        },
        Instruction {
            name: "bclr",
            _desc: Some(BCLR_DESC),
        },
        Instruction {
            name: "bset",
            _desc: Some(BSET_DESC),
        },
        Instruction {
            name: "btst",
            _desc: Some(BTST_DESC),
        },
        Instruction {
            name: "cmp",
            _desc: Some(CMP_DESC),
        },
        Instruction {
            name: "divu",
            _desc: Some(DIVS_DIVU_DESC),
        },
        Instruction {
            name: "divs",
            _desc: Some(DIVS_DIVU_DESC),
        },
        Instruction {
            name: "eor",
            _desc: Some(EOR_DESC),
        },
        Instruction {
            name: "exg",
            _desc: Some(EXG_DESC),
        },
        Instruction {
            name: "lea",
            _desc: Some(LEA_DESC),
        },
        Instruction {
            name: "move",
            _desc: Some(MOVE_DESC),
        },
        Instruction {
            name: "muls",
            _desc: Some(MULS_DESC),
        },
        Instruction {
            name: "mulu",
            _desc: Some(MULU_DESC),
        },
        Instruction {
            name: "or",
            _desc: Some(OR_DESC),
        },
        Instruction {
            name: "sub",
            _desc: Some(SUB_DESC),
        },
        Instruction {
            name: "subq",
            _desc: Some(SUBQ_DESC),
        },
        Instruction {
            name: "subx",
            _desc: Some(SUBX_DESC),
        },
        ];

    let inst_1_ops_000 = [
        Instruction {
            name: "clr",
            _desc: Some(CLR_DESC),
        },
        Instruction {
            name: "ext",
            _desc: Some(EXT_DESC),
        },
        Instruction {
            name: "bsr",
            _desc: Some(BSR_DESC),
        },
        Instruction {
            name: "jsr",
            _desc: Some(JSR_DESC),
        },
        Instruction {
            name: "jmp",
            _desc: Some(JMP_DESC),
        },
        Instruction {
            name: "neg",
            _desc: Some(NEG_DESC),
        },
        Instruction {
            name: "not",
            _desc: Some(NOT_DESC),
        },
        Instruction {
            name: "swap",
            _desc: Some(SWAP_DESC),
        },
        ];

    let inst_0_ops_000 = [
        Instruction {
            name: "nop",
            _desc: Some(NOP_DESC),
        },
        Instruction {
            name: "illegal",
            _desc: None,
        },
        Instruction {
            name: "rte",
            _desc: Some(RTS_DESC),
        },
        Instruction {
            name: "rts",
            _desc: Some(RTS_DESC),
        },
    ];

    for inst in &inst_2_ops_000 {
        let name_long = format!("{}.l", inst.name);

        print_instruction_header(inst);
        generate_table(inst.name, false, Some(&src_types), &dest_types);
        generate_table(&name_long, true, Some(&src_types), &dest_types);
    }

    // Generate instructions with one op

    /*
    for inst in &inst_1_ops_000 {
        let name_long = format!("{}.l", inst.name);

        print_instruction_header(inst);
        generate_table(inst.name, None, &dest_types);
        generate_table(&name_long, None, &dest_types);
    }

    //

    // Generate instructions with no ops

    for inst in &inst_0_ops_000 {
        let name_long = format!("{}.l", inst.name);

        print_instruction_header(inst);
        generate_table(inst.name, None, &dest_types_none);
        generate_table(&name_long, None, &dest_types_none);
    }
    */
}

extern "C" {
    fn m68k_wrapper_init();
    fn m68k_run_instructions(instructions: *const raw::c_void, count: u32, cycle_res: *mut u32);
}

<|endoftext|>


<commit_before>extern crate docopt;
extern crate rustc_serialize;

use docopt::Docopt;

const USAGE: &'static str = "
how-do-i-escape: Prints escape sequences for unicode graphemes

Usage:
  how-do-i-escape <grapheme>
  how-do-i-escape (--help | --version)

Options:
  -h, --help  Show this screen.
  --version   Show version.

Example:
  $ how-do-i-escape \u{00A7}
  css  = \"\\00A7\"
  html = §
  js   = \"\\u00A7\"
";

#[derive(RustcDecodable)]
struct Args {
    arg_grapheme: String
}

fn main() {
  let version = format!("v{}", env!("CARGO_PKG_VERSION"));

  let args: Args = Docopt::new(USAGE)
    .and_then(|d| d.help(true).version(Some(version)).decode())
    .unwrap_or_else(|e| e.exit());

  let grapheme = args.arg_grapheme;

  println!(r#"css  = "{}""#, escape_grapheme(&grapheme, as_css));
  println!(r#"html = {}"#, escape_grapheme(&grapheme, as_html));
  println!(r#"js   = "{}""#, escape_grapheme(&grapheme, as_js));
}

fn escape_grapheme<F>(grapheme: &str, int_to_escape_sequence: F) -> String
  where F: Fn(u32) -> String
{
  grapheme
    .chars()
    .map(|ch| ch as u32)
    .map(int_to_escape_sequence)
    .fold(String::new(), |c, s| {
      let mut copy = c;
      copy.push_str(&s);
      copy
    })
}

fn as_css(i: u32) -> String {
  format!("\\{:01$X}", i, 4)
}

fn as_html(i: u32) -> String {
  format!("&#x{:01$X};", i, 4)
}

fn as_js(i: u32) -> String {
  if i <= 0xFFFF {
    format!("\\u{:01$X}", i, 4)
  } else {
    format!("\\u{{{:X}}}", i)
  }
}

#[cfg(test)]
mod tests {
  use super::{as_css, as_html, as_js};

  #[test]
  fn test_as_css() {
    assert!(as_css(0) == r"\0000");
    assert!(as_css(0xFFFF) == r"\FFFF");
    assert!(as_css(0xBEEF) != r"\beef");
    //assert!(as_css(0x10000) == ?);
  }

  #[test]
  fn test_as_html() {
    assert!(as_html(0) == r"�");
    assert!(as_html(0xFFFF) == r"");
    assert!(as_html(0xBEEF) != r"뻯");
    //assert!(as_html(0x10000) == ?);
  }

  #[test]
  fn test_as_js() {
    assert!(as_js(0) == r"\u0000");
    assert!(as_js(0xFFFF) == r"\uFFFF");
    assert!(as_js(0xBEEF) != r"\ubeef");
    assert!(as_js(0x10000) == r"\u{10000}");
    assert!(as_js(0x10FFFF) == r"\u{10FFFF}");
    assert!(as_js(0xFFFFFFFF) == r"\u{FFFFFFFF}");
  }
}
<commit_msg>Format using rustfmt<commit_after>extern crate docopt;
extern crate rustc_serialize;

use docopt::Docopt;

const USAGE: &'static str = "
how-do-i-escape: Prints escape sequences for unicode graphemes

Usage:
  how-do-i-escape <grapheme>
  how-do-i-escape (--help | --version)

Options:
  -h, --help  Show this screen.
  --version   Show version.

Example:
  $ how-do-i-escape \u{00A7}
  css  = \"\\00A7\"
  html = §
  js   = \"\\u00A7\"
";

#[derive(RustcDecodable)]
struct Args {
    arg_grapheme: String,
}

fn main() {
    let version = format!("v{}", env!("CARGO_PKG_VERSION"));

    let args: Args = Docopt::new(USAGE)
        .and_then(|d| d.help(true).version(Some(version)).decode())
        .unwrap_or_else(|e| e.exit());

    let grapheme = args.arg_grapheme;

    println!(r#"css  = "{}""#, escape_grapheme(&grapheme, as_css));
    println!(r#"html = {}"#, escape_grapheme(&grapheme, as_html));
    println!(r#"js   = "{}""#, escape_grapheme(&grapheme, as_js));
}

fn escape_grapheme<F>(grapheme: &str, int_to_escape_sequence: F) -> String
    where F: Fn(u32) -> String
{
    grapheme.chars()
        .map(|ch| ch as u32)
        .map(int_to_escape_sequence)
        .fold(String::new(), |c, s| {
            let mut copy = c;
            copy.push_str(&s);
            copy
        })
}

fn as_css(i: u32) -> String {
    format!("\\{:01$X}", i, 4)
}

fn as_html(i: u32) -> String {
    format!("&#x{:01$X};", i, 4)
}

fn as_js(i: u32) -> String {
    if i <= 0xFFFF {
        format!("\\u{:01$X}", i, 4)
    } else {
        format!("\\u{{{:X}}}", i)
    }
}

#[cfg(test)]
mod tests {
    use super::{as_css, as_html, as_js};

    #[test]
    fn test_as_css() {
        assert!(as_css(0) == r"\0000");
        assert!(as_css(0xFFFF) == r"\FFFF");
        assert!(as_css(0xBEEF) != r"\beef");
        // assert!(as_css(0x10000) == ?);
    }

    #[test]
    fn test_as_html() {
        assert!(as_html(0) == r"�");
        assert!(as_html(0xFFFF) == r"");
        assert!(as_html(0xBEEF) != r"뻯");
        // assert!(as_html(0x10000) == ?);
    }

    #[test]
    fn test_as_js() {
        assert!(as_js(0) == r"\u0000");
        assert!(as_js(0xFFFF) == r"\uFFFF");
        assert!(as_js(0xBEEF) != r"\ubeef");
        assert!(as_js(0x10000) == r"\u{10000}");
        assert!(as_js(0x10FFFF) == r"\u{10FFFF}");
        assert!(as_js(0xFFFFFFFF) == r"\u{FFFFFFFF}");
    }
}
<|endoftext|>