<commit_before>extern crate rgmk;
extern crate clap;

use clap::{App, SubCommand, AppSettings};
use std::io::{self, stdin, stdout, stderr, BufReader};
use std::io::prelude::*;
use rgmk::GameData;
use std::path::Path;

fn main() {
    std::process::exit(run());
}

fn run() -> i32 {
    let strings_subcommand = SubCommand::with_name("strings")
                                 .about("Manipulate strings")
                                 .setting(AppSettings::SubcommandRequiredElseHelp)
                                 .setting(AppSettings::ArgRequiredElseHelp)
                                 .subcommand(SubCommand::with_name("dump")
                                                 .about("Dump strings.")
                                                 .args_from_usage("[OUTPUT_FILE] 'The file to \
                                                                   write the strings to. By \
                                                                   default, standard output.'"))
                                 .subcommand(SubCommand::with_name("repack")
                                                 .about("Repack strings")
                                                 .args_from_usage("[INPUT_FILE] 'The file \
                                                                   containing the strings to \
                                                                   repack. By default, standard \
                                                                   input.'"));
    let textures_subcommand = SubCommand::with_name("textures")
                                  .about("Manipulate textures")
                                  .setting(AppSettings::SubcommandRequiredElseHelp)
                                  .subcommand(SubCommand::with_name("dump").about("Dump textures"))
                                  .subcommand(SubCommand::with_name("repack")
                                                  .about("Repack textures"));
    let matches = App::new("gmktool")
                      .setting(AppSettings::SubcommandRequiredElseHelp)
                      .version(env!("CARGO_PKG_VERSION"))
                      .about("Tool for manipulating Game Maker Stdudio data files")
                      .args_from_usage("-b --backup=[BACKUP_FILE] 'Create a backup. By default, \
                                        it's DATA_FILE.bk'
                                    \
                                        <DATA_FILE> 'The game maker data file to operate on'")
                      .subcommand(strings_subcommand)
                      .subcommand(textures_subcommand)
                      .get_matches();
    let data_file_path = matches.value_of("DATA_FILE").unwrap();
    let backup = matches.is_present("backup");
    let backup_path = format!("{}.bk", data_file_path);
    let backup_path = matches.value_of("BACKUP_FILE").unwrap_or(&backup_path);
    let mut game_data = match GameData::from_file(data_file_path) {
        Ok(g) => g,
        Err(e) => {
            writeln!(stderr(),
                     "Failed to load game data for {:?}: {}",
                     data_file_path,
                     e)
                .unwrap();
            return 1;
        }
    };
    if let Some(matches) = matches.subcommand_matches("strings") {
        if let Some(matches) = matches.subcommand_matches("dump") {
            match matches.value_of("OUTPUT_FILE") {
                Some(path) => {
                    let mut file = match std::fs::File::create(path) {
                        Ok(f) => f,
                        Err(e) => {
                            writeln!(stderr(), "Failed to create output file: {}", e).unwrap();
                            return 1;
                        }
                    };
                    if let Err(e) = dump_strings(&game_data, &mut file) {
                        writeln!(stderr(), "Failed to dump strings: {}", e).unwrap();
                    }
                }
                None => {
                    let stdout = stdout();
                    let mut lock = stdout.lock();
                    if let Err(e) = dump_strings(&game_data, &mut lock) {
                        writeln!(stderr(), "Failed to dump strings: {}", e).unwrap();
                    }
                }
            }
        } else if let Some(matches) = matches.subcommand_matches("repack") {
            if backup {
                if let Err(e) = std::fs::copy(data_file_path, backup_path) {
                    writeln!(stderr(), "Failed to create backup: {}", e).unwrap();
                }
            }
            match matches.value_of("INPUT_FILE") {
                Some(path) => {
                    let file = match std::fs::File::open(path) {
                        Ok(f) => f,
                        Err(e) => {
                            writeln!(stderr(), "Failed to open input file: {}", e).unwrap();
                            return 1;
                        }
                    };
                    if let Err(e) = repack_strings(&mut game_data,
                                                   &mut BufReader::new(file),
                                                   data_file_path) {
                        writeln!(stderr(), "Failed to repack strings: {}", e).unwrap();
                    }
                }
                None => {
                    if let Err(e) = repack_strings(&mut game_data,
                                                   &mut BufReader::new(stdin()),
                                                   data_file_path) {
                        writeln!(stderr(), "Failed to repack strings: {}", e).unwrap();
                    }
                }
            }
        }
    } else if let Some(matches) = matches.subcommand_matches("textures") {
        if let Some(_) = matches.subcommand_matches("dump") {
            if let Err(e) = dump_textures(&game_data) {
                writeln!(stderr(), "Failed to dump textures: {}", e).unwrap();
                return 1;
            }
        } else if let Some(_) = matches.subcommand_matches("repack") {
            if let Err(e) = repack_textures(&mut game_data, data_file_path) {
                writeln!(stderr(), "Failed to repack textures: {}", e).unwrap();
            }
        }
    }
    0
}

fn dump_strings<W: Write>(game_data: &GameData, writer: &mut W) -> io::Result<()> {
    for s in &game_data.strings.strings {
        try!(writeln!(writer, "{}", s));
    }
    Ok(())
}

fn repack_strings<R: BufRead, P: AsRef<Path>>(game_data: &mut GameData,
                                              reader: &mut R,
                                              path: P)
                                              -> io::Result<()> {
    for (s, l) in game_data.strings.strings.iter_mut().zip(reader.lines()) {
        *s = try!(l);
    }
    game_data.save_to_file(path)
}

fn dump_textures(game_data: &GameData) -> io::Result<()> {
    for (i, t) in game_data.textures.textures.iter().enumerate() {
        let path = format!("{}.png", i);
        let mut f = try!(std::fs::File::create(path));
        try!(f.write_all(&t.png_data));
    }
    Ok(())
}

fn repack_textures<P: AsRef<Path>>(game_data: &mut GameData, path: P) -> io::Result<()> {
    for (i, t) in game_data.textures.textures.iter_mut().enumerate() {
        let path = format!("{}.png", i);
        let mut f = try!(std::fs::File::open(path));
        let mut png_data = Vec::new();
        try!(f.read_to_end(&mut png_data));
        (*t).png_data = png_data;
    }
    game_data.save_to_file(path)
}
<commit_msg>Fix broken backup option<commit_after>extern crate rgmk;
extern crate clap;

use clap::{App, SubCommand, AppSettings, Arg};
use std::io::{self, stdin, stdout, stderr, BufReader};
use std::io::prelude::*;
use rgmk::GameData;
use std::path::Path;

fn main() {
    std::process::exit(run());
}

fn run() -> i32 {
    let strings_subcommand = SubCommand::with_name("strings")
                                 .about("Manipulate strings")
                                 .setting(AppSettings::SubcommandRequiredElseHelp)
                                 .setting(AppSettings::ArgRequiredElseHelp)
                                 .subcommand(SubCommand::with_name("dump")
                                                 .about("Dump strings.")
                                                 .args_from_usage("[OUTPUT_FILE] 'The file to \
                                                                   write the strings to. By \
                                                                   default, standard output.'"))
                                 .subcommand(SubCommand::with_name("repack")
                                                 .about("Repack strings")
                                                 .args_from_usage("[INPUT_FILE] 'The file \
                                                                   containing the strings to \
                                                                   repack. By default, standard \
                                                                   input.'"));
    let textures_subcommand = SubCommand::with_name("textures")
                                  .about("Manipulate textures")
                                  .setting(AppSettings::SubcommandRequiredElseHelp)
                                  .subcommand(SubCommand::with_name("dump").about("Dump textures"))
                                  .subcommand(SubCommand::with_name("repack")
                                                  .about("Repack textures"));
    let matches = App::new("gmktool")
                      .setting(AppSettings::SubcommandRequiredElseHelp)
                      .version(env!("CARGO_PKG_VERSION"))
                      .about("Tool for manipulating Game Maker Stdudio data files")
                      .arg(Arg::with_name("BACKUP")
                               .short("b")
                               .long("backup")
                               .help("Create a backup (.bk) before writing to the data file."))
                      .args_from_usage("<DATA_FILE> 'The game maker data file to operate on'")
                      .subcommand(strings_subcommand)
                      .subcommand(textures_subcommand)
                      .get_matches();
    let data_file_path = matches.value_of("DATA_FILE").unwrap();
    let backup = matches.is_present("BACKUP");
    let backup_path = format!("{}.bk", data_file_path);
    let backup_path = matches.value_of("BACKUP_FILE").unwrap_or(&backup_path);
    let mut game_data = match GameData::from_file(data_file_path) {
        Ok(g) => g,
        Err(e) => {
            writeln!(stderr(),
                     "Failed to load game data for {:?}: {}",
                     data_file_path,
                     e)
                .unwrap();
            return 1;
        }
    };
    if let Some(matches) = matches.subcommand_matches("strings") {
        if let Some(matches) = matches.subcommand_matches("dump") {
            match matches.value_of("OUTPUT_FILE") {
                Some(path) => {
                    let mut file = match std::fs::File::create(path) {
                        Ok(f) => f,
                        Err(e) => {
                            writeln!(stderr(), "Failed to create output file: {}", e).unwrap();
                            return 1;
                        }
                    };
                    if let Err(e) = dump_strings(&game_data, &mut file) {
                        writeln!(stderr(), "Failed to dump strings: {}", e).unwrap();
                    }
                }
                None => {
                    let stdout = stdout();
                    let mut lock = stdout.lock();
                    if let Err(e) = dump_strings(&game_data, &mut lock) {
                        writeln!(stderr(), "Failed to dump strings: {}", e).unwrap();
                    }
                }
            }
        } else if let Some(matches) = matches.subcommand_matches("repack") {
            if backup {
                if let Err(e) = std::fs::copy(data_file_path, backup_path) {
                    writeln!(stderr(), "Failed to create backup: {}", e).unwrap();
                }
            }
            match matches.value_of("INPUT_FILE") {
                Some(path) => {
                    let file = match std::fs::File::open(path) {
                        Ok(f) => f,
                        Err(e) => {
                            writeln!(stderr(), "Failed to open input file: {}", e).unwrap();
                            return 1;
                        }
                    };
                    if let Err(e) = repack_strings(&mut game_data,
                                                   &mut BufReader::new(file),
                                                   data_file_path) {
                        writeln!(stderr(), "Failed to repack strings: {}", e).unwrap();
                    }
                }
                None => {
                    if let Err(e) = repack_strings(&mut game_data,
                                                   &mut BufReader::new(stdin()),
                                                   data_file_path) {
                        writeln!(stderr(), "Failed to repack strings: {}", e).unwrap();
                    }
                }
            }
        }
    } else if let Some(matches) = matches.subcommand_matches("textures") {
        if let Some(_) = matches.subcommand_matches("dump") {
            if let Err(e) = dump_textures(&game_data) {
                writeln!(stderr(), "Failed to dump textures: {}", e).unwrap();
                return 1;
            }
        } else if let Some(_) = matches.subcommand_matches("repack") {
            if let Err(e) = repack_textures(&mut game_data, data_file_path) {
                writeln!(stderr(), "Failed to repack textures: {}", e).unwrap();
            }
        }
    }
    0
}

fn dump_strings<W: Write>(game_data: &GameData, writer: &mut W) -> io::Result<()> {
    for s in &game_data.strings.strings {
        try!(writeln!(writer, "{}", s));
    }
    Ok(())
}

fn repack_strings<R: BufRead, P: AsRef<Path>>(game_data: &mut GameData,
                                              reader: &mut R,
                                              path: P)
                                              -> io::Result<()> {
    for (s, l) in game_data.strings.strings.iter_mut().zip(reader.lines()) {
        *s = try!(l);
    }
    game_data.save_to_file(path)
}

fn dump_textures(game_data: &GameData) -> io::Result<()> {
    for (i, t) in game_data.textures.textures.iter().enumerate() {
        let path = format!("{}.png", i);
        let mut f = try!(std::fs::File::create(path));
        try!(f.write_all(&t.png_data));
    }
    Ok(())
}

fn repack_textures<P: AsRef<Path>>(game_data: &mut GameData, path: P) -> io::Result<()> {
    for (i, t) in game_data.textures.textures.iter_mut().enumerate() {
        let path = format!("{}.png", i);
        let mut f = try!(std::fs::File::open(path));
        let mut png_data = Vec::new();
        try!(f.read_to_end(&mut png_data));
        (*t).png_data = png_data;
    }
    game_data.save_to_file(path)
}
<|endoftext|>


<commit_before>// Bytecode instructions
const OP_LOAD:  u8 = 1; // arity: 2 - (value: u64, dest: u8)
const OP_ADD:   u8 = 2; // arity: 3 - (a: u8, b: u8, dest: u8)
const OP_PRINT: u8 = 3; // arity: 1 - (reg: u8)
const OP_HALT:  u8 = 4; // arity: 0

fn interpret(code: &[u8]) {
    let mut pc = 0; // "Program counter", the index of the current instruction.
    let mut regs = [0u64; 256]; // Array of 256 zeros.

    loop {
        let op = code[pc];
        pc += 1;
        match op {
            OP_LOAD => {
                // Read 64 bits from the code (BUG: right now I'm only reading
                // one byte of the number!
                let val = code[pc] as u64;
                pc += 8;
                let dest = code[pc] as usize;
                pc += 1;
                regs[dest] = val;
            },
            OP_ADD => {
                let a = code[pc] as usize;
                pc += 1;
                let b = code[pc] as usize;
                pc += 1;
                let dest = code[pc] as usize;
                regs[dest] = regs[a] + regs[b];
            },
            OP_PRINT => {
                let r = code[pc] as usize;
                pc += 1;
                println!("{}", regs[r])
            },
            OP_HALT => break,
            _ => panic!("Invalid opcode at offset {}", pc)
        }
    }
}

fn main() {
    let code = [
        OP_LOAD, 73, 0, 0, 0, 0, 0, 0, 0, 0, // load the number 73 into R0.
        OP_LOAD, 68, 0, 0, 0, 0, 0, 0, 0, 1, // load the number 68 into R1.
        OP_ADD, 0, 1, 2, // compute R0 + R1 and store it in R2.
        OP_PRINT, 2,
        OP_HALT
    ];

    interpret(&code); // should print 73 + 68, which is 141.
}
<commit_msg>change OP_HALT to OP_RETURN<commit_after>// Bytecode instructions
const OP_LOAD: u8 = 1; // arity: 2 - (value: u64, dest: u8)
const OP_ADD: u8 = 2; // arity: 3 - (a: u8, b: u8, dest: u8)
const OP_PRINT: u8 = 3; // arity: 1 - (reg: u8)
const OP_RETURN: u8 = 4; // arity: 1 - (reg: u8)

fn interpret(code: &[u8]) -> u64 {
    let mut pc = 0; // "Program counter", the index of the current instruction.
    let mut regs = [0u64; 256]; // Array of 256 zeros.

    loop {
        let op = code[pc];
        pc += 1;
        match op {
            OP_LOAD => {
                // Read 64 bits from the code (BUG: right now I'm only reading
                // one byte of the number!
                let val = code[pc] as u64;
                pc += 8;
                let dest = code[pc] as usize;
                pc += 1;
                regs[dest] = val;
            },
            OP_ADD => {
                let a = code[pc] as usize;
                pc += 1;
                let b = code[pc] as usize;
                pc += 1;
                let dest = code[pc] as usize;
                pc += 1;
                regs[dest] = regs[a] + regs[b];
            },
            OP_PRINT => {
                let r = code[pc] as usize;
                pc += 1;
                println!("{}", regs[r]);
            },
            OP_RETURN => {
                let r = code[pc] as usize;
                pc += 1;
                return regs[r];
            },
            _ => panic!("Invalid opcode at offset {}", pc)
        }
    }
}

fn main() {
    let code = [
        OP_LOAD, 73, 0, 0, 0, 0, 0, 0, 0, 0, // load the number 73 into R0.
        OP_LOAD, 68, 0, 0, 0, 0, 0, 0, 0, 1, // load the number 68 into R1.
        OP_ADD, 0, 1, 2, // compute R0 + R1 and store it in R2.
        OP_PRINT, 2,
        OP_RETURN, 2
    ];

    interpret(&code); // should print 73 + 68, which is 141.
}
<|endoftext|>


<commit_before>extern crate getopts;
extern crate pnet;
extern crate time;

use getopts::Options;
use std::os;
use std::net::{IpAddr};
use std::str::FromStr;

use pnet::transport::TransportProtocol::{Ipv4};
use pnet::old_packet::ip::IpNextHeaderProtocols;
use pnet::transport::TransportChannelType::{Layer3};
use pnet::transport::{transport_channel};
use pnet::old_packet::ipv4::{Ipv4Header, Ipv4Packet};

fn main() {
    let args: Vec<String> = os::args();
    let mut opts = Options::new();
    let matches = match opts.parse(args.tail()) {
        Ok(m) => m,
        Err(f) => panic!(f.to_string())
    };
    let addr_arg = matches.free[0].as_slice();
    let addr: IpAddr = FromStr::from_str(addr_arg.as_slice()).unwrap();

    let protocol = Layer3(IpNextHeaderProtocols::Test1);
    let (mut icmp_sender, mut icmp_receiver) = match transport_channel(4096, protocol) {
        Ok((tx, rx)) => (tx, rx),
        Err(e) => panic!("An error occurred when creating the transport channel:
                        {}", e)
    };
    let packet = build_icmp_time_request_packet();
}

fn build_icmp_time_request_packet() -> IcmpRequestPacket {
    let ip_type = 14u8;
    let ip_code = 0u8;
    let ip_checksum = 0u16; // calculate; 16 bits
    let identifier = 0u16; // what should this be? used to match requests to replies; 16 bits
    let sequence = 0u16; // what should this be? used to match requests to replies;
    let originate_timestamp = 0u32; // get from systime
    let receive_timestamp = 0u32; // not used
    let transmit_timestamp = 0u32; // not used
    let mut packet = IcmpRequestPacket::new();
    packet
}

struct IcmpRequestPacket {
    ip_type: u8,
    ip_code: u8,
    ip_checksum: u16,
    identifier: u16,
    sequence: u16,
    originate_timestamp: u32,
    receive_timestamp: u32,
    transmit_timestamp: u32
}

impl IcmpRequestPacket {
    fn new() -> IcmpRequestPacket {
        let mut packet = IcmpRequestPacket {
            ip_type: 13,
            ip_code: 0,
            ip_checksum: 0,
            identifier: 0,
            sequence: 0,
            originate_timestamp: 0,
            receive_timestamp: 0,
            transmit_timestamp: 0
        };
        packet.set_originate_timestamp();
        packet.set_checksum();
        packet
    }

    fn calculate_checksum(&self) -> u16 {
        // implement me
        let mut vec: Vec<u16> = vec![];
        1
    }

    fn set_checksum(&mut self) {
        self.ip_checksum = self.calculate_checksum();
    }

    fn set_originate_timestamp(&mut self) {
        self.originate_timestamp = time_after_utc();
    }
}

fn time_after_utc() -> u32 {
    let t = time::now_utc();
    let s: i32 = t.tm_hour * 3600 + t.tm_min * 60 + t.tm_sec;
    s as u32
}
<commit_msg>code to calculate checksum for icmp packet sorta works, maybe needs tests<commit_after>extern crate getopts;
extern crate pnet;
extern crate time;

use getopts::Options;
use std::os;
use std::net::{IpAddr};
use std::str::FromStr;

use pnet::transport::TransportProtocol::{Ipv4};
use pnet::old_packet::ip::IpNextHeaderProtocols;
use pnet::transport::TransportChannelType::{Layer3};
use pnet::transport::{transport_channel};
use pnet::old_packet::ipv4::{Ipv4Header, Ipv4Packet};

fn main() {
    let args: Vec<String> = os::args();
    let mut opts = Options::new();
    let matches = match opts.parse(args.tail()) {
        Ok(m) => m,
        Err(f) => panic!(f.to_string())
    };
    let addr_arg = matches.free[0].as_slice();
    let addr: IpAddr = FromStr::from_str(addr_arg.as_slice()).unwrap();

    let protocol = Layer3(IpNextHeaderProtocols::Test1);
    let (mut icmp_sender, mut icmp_receiver) = match transport_channel(4096, protocol) {
        Ok((tx, rx)) => (tx, rx),
        Err(e) => panic!("An error occurred when creating the transport channel:
                        {}", e)
    };
    let packet = build_icmp_time_request_packet();
}

fn build_icmp_time_request_packet() -> IcmpRequestPacket {
    let mut packet = IcmpRequestPacket::new();
    packet
}

struct IcmpRequestPacket {
    ip_type: u8,
    ip_code: u8,
    ip_checksum: u16,
    identifier: u16,
    sequence: u16,
    originate_timestamp: u32,
    receive_timestamp: u32,
    transmit_timestamp: u32
}

impl IcmpRequestPacket {
    fn new() -> IcmpRequestPacket {
        let mut packet = IcmpRequestPacket {
            ip_type: 13,
            ip_code: 0,
            ip_checksum: 0,
            identifier: 0,
            sequence: 0,
            originate_timestamp: 0,
            receive_timestamp: 0,
            transmit_timestamp: 0
        };
        packet.set_originate_timestamp();
        packet.set_checksum();
        packet
    }

    fn calculate_checksum(&self) -> u16 {
        // implement me
        let mut vec: Vec<u16> = vec![];
        vec.push((self.ip_type + self.ip_code) as u16);
        vec.push(self.ip_checksum);
        vec.push(self.identifier);
        vec.push(self.sequence);
        vec.push((self.originate_timestamp >> 16) as u16);
        vec.push(self.originate_timestamp as u16);
        vec.push((self.receive_timestamp >> 16) as u16);
        vec.push(self.receive_timestamp as u16);
        vec.push((self.transmit_timestamp >> 16) as u16);
        vec.push(self.transmit_timestamp as u16);
        let sum = vec.iter().fold(0u16, |sum, x| sum + *x);
        let ones_complement = 65535 - sum;
        ones_complement
    }

    fn set_checksum(&mut self) {
        self.ip_checksum = self.calculate_checksum();
    }

    fn set_originate_timestamp(&mut self) {
        self.originate_timestamp = time_after_utc();
    }
}

fn time_after_utc() -> u32 {
    let t = time::now_utc();
    let s: i32 = t.tm_hour * 3600 + t.tm_min * 60 + t.tm_sec;
    s as u32
}
<|endoftext|>


<commit_before>#[crate_id = "dark"];
#[crate_type = "bin"];
#[deny(warnings, missing_doc)];

//! Dark compressor prototype

extern crate compress;
#[cfg(test)]
extern crate test;

use std::{io, os, vec};
use compress::bwt;
use compress::entropy::ari;

/// Suffix Array Construction Algorithm (SACA)
pub mod saca;
/// Compression models
pub mod model {
	/// Distance Coding model
	pub mod dc;
}

/// Program entry point
pub fn main() {
	let extension = &".dark";
	let args = os::args();
	if args.len() <= 1 {
		println!("Dark usage:");
		println!("\t{} input_file[.dark]", args[0]);
		return
	}
	let input_path = Path::new(args[1].clone());
	let mut model = model::dc::new();
	let file_name = input_path.filename_str().unwrap();
	if file_name.ends_with(extension) {
		let mut in_file = match io::File::open(&input_path) {
			Ok(file) => file,
			Err(e) => {
				println!("Input {} can not be read: {}", input_path.as_str(), e.to_str());
				return;
			}
		};
		let N = in_file.read_le_u32().unwrap() as uint;
		info!("Decoding N: {}", N);
		// create temporaries
		let mut input = vec::from_elem(N, 0u8);
		// decode alphabit
		let mut mtf = bwt::mtf::MTF::new();
		let E = in_file.read_u8().unwrap() as uint;
		let mut alphabet = [0u8, ..0x100];
		let alpha_opt = if E == 0 {
			info!("Alphabet is sparse");
			None
		}else {
			in_file.read( alphabet.mut_slice_to(E) ).unwrap();
			info!("Alphabet of size {}: {:?}", E, alphabet.slice_to(E));
			Some(alphabet.slice_to(E))
		};
		// decode distances
		let mut dh = ari::Decoder::new(in_file);
		dh.start().unwrap();
		bwt::dc::decode(alpha_opt, input, &mut mtf, |sym| {
			let d = model.decode(sym, &mut dh);
			info!("Distance {} for {}", d, sym);
			Ok(d as uint)
		}).unwrap();
		let origin = model.decode(0, &mut dh) as uint;
		info!("Origin: {}", origin);
		let mut suf = vec::from_elem(N, N as saca::Suffix);
		// undo BWT and write output
		let ext_pos = file_name.len() - extension.len();
		let out_path = Path::new(format!("{}{}", file_name.slice_to(ext_pos), ".orig"));
		let mut out_file = io::File::create(&out_path);
		for b in bwt::decode(input, origin, suf) {
			out_file.write_u8(b).unwrap();
		}
	}else {
		let input = match io::File::open(&input_path).read_to_end() {
			Ok(data) => data,
			Err(e) => {
				println!("Input {} can not be read: {}", input_path.as_str(), e.to_str());
				return;
			}
		};
		let N = input.len();
		// create temporary suffix array
		let mut con = saca::Constructor::new(N);
		// do BWT and DC
		let (output, origin) = {
			let suf = con.compute(input);
			let mut iter = bwt::TransformIterator::new(input, suf);
			let out = iter.to_owned_vec();
			(out, iter.get_origin())
		};
		let mut mtf = bwt::mtf::MTF::new();
		let suf = con.reuse().mut_slice_to(N);
		let dc_init = bwt::dc::encode(output, suf, &mut mtf);
		// compress to the output
		let out_path = Path::new(format!("{}{}", file_name, ".dark"));
		let mut out_file = io::File::create(&out_path).unwrap();
		info!("Encoding N: {}", N);
		out_file.write_le_u32(N as u32).unwrap();
		// encode alphabet
		let E = dc_init.len();
		let mut helper = if E > 111 {
			info!("Alphabet is sparse");
			out_file.write_u8(0).unwrap();
			let mut rd = [N as model::dc::Distance, ..0x100];
			for &(sym,d) in dc_init.iter() {
				rd[sym] = d;
			}
			let mut eh = ari::Encoder::new(out_file);
			for (sym,&d) in rd.iter().enumerate() {
				model.encode(d, sym as u8, &mut eh);
			}
			eh
		}else {
			info!("Alphabet of size {}", E);
			out_file.write_u8(E as u8).unwrap();
			out_file.write( dc_init.map(|&(s,_)| s) ).unwrap();
			let mut eh = ari::Encoder::new(out_file);
			for &(sym,d) in dc_init.iter() {
				info!("Init distance {} for {}", d, sym);
				model.encode(d, sym, &mut eh);
			}
			eh
		};
		// encode distances
		for (&d,&sym) in suf.iter().zip(output.iter()) {
			if (d as uint) < N {
				info!("Distance {} for {}", d, sym);
				model.encode(d, sym, &mut helper);
			}
		}
		// done
		info!("Origin: {}", origin);
		model.encode(origin as model::dc::Distance, 0, &mut helper);
		let (_, err) = helper.finish();
		err.unwrap();
		info!("Encoded {} distances", model.num_processed);
	}
}
<commit_msg>Buffered IO and native tasks.<commit_after>#[crate_id = "dark"];
#[crate_type = "bin"];
#[deny(warnings, missing_doc)];

//! Dark compressor prototype

extern crate native;
extern crate compress;
#[cfg(test)]
extern crate test;

use std::{io, os, vec};
use compress::bwt;
use compress::entropy::ari;

/// Suffix Array Construction Algorithm (SACA)
pub mod saca;
/// Compression models
pub mod model {
	/// Distance Coding model
	pub mod dc;
}

/// Program entry point
pub fn main() {
	let extension = &".dark";
	let args = os::args();
	if args.len() <= 1 {
		println!("Dark usage:");
		println!("\t{} input_file[.dark]", args[0]);
		return
	}
	let input_path = Path::new(args[1].clone());
	let mut model = model::dc::new();
	let file_name = input_path.filename_str().unwrap();
	if file_name.ends_with(extension) {
		let mut in_file = match io::File::open(&input_path) {
			Ok(file) => io::BufferedReader::new(file),
			Err(e) => {
				println!("Input {} can not be read: {}", input_path.as_str(), e.to_str());
				return;
			}
		};
		let N = in_file.read_le_u32().unwrap() as uint;
		info!("Decoding N: {}", N);
		// create temporaries
		let mut input = vec::from_elem(N, 0u8);
		// decode alphabit
		let mut mtf = bwt::mtf::MTF::new();
		let E = in_file.read_u8().unwrap() as uint;
		let mut alphabet = [0u8, ..0x100];
		let alpha_opt = if E == 0 {
			info!("Alphabet is sparse");
			None
		}else {
			in_file.read( alphabet.mut_slice_to(E) ).unwrap();
			info!("Alphabet of size {}: {:?}", E, alphabet.slice_to(E));
			Some(alphabet.slice_to(E))
		};
		// decode distances
		let mut dh = ari::Decoder::new(in_file);
		dh.start().unwrap();
		bwt::dc::decode(alpha_opt, input, &mut mtf, |sym| {
			let d = model.decode(sym, &mut dh);
			info!("Distance {} for {}", d, sym);
			Ok(d as uint)
		}).unwrap();
		let origin = model.decode(0, &mut dh) as uint;
		info!("Origin: {}", origin);
		let mut suf = vec::from_elem(N, N as saca::Suffix);
		// undo BWT and write output
		let ext_pos = file_name.len() - extension.len();
		let out_path = Path::new(format!("{}{}", file_name.slice_to(ext_pos), ".orig"));
		let mut out_file = io::BufferedWriter::new(io::File::create(&out_path));
		for b in bwt::decode(input, origin, suf) {
			out_file.write_u8(b).unwrap();
		}
		out_file.flush().unwrap();
	}else {
		let input = match io::File::open(&input_path).read_to_end() {
			Ok(data) => data,
			Err(e) => {
				println!("Input {} can not be read: {}", input_path.as_str(), e.to_str());
				return;
			}
		};
		let N = input.len();
		// create temporary suffix array
		let mut con = saca::Constructor::new(N);
		// do BWT and DC
		let (output, origin) = {
			let suf = con.compute(input);
			let mut iter = bwt::TransformIterator::new(input, suf);
			let out = iter.to_owned_vec();
			(out, iter.get_origin())
		};
		let mut mtf = bwt::mtf::MTF::new();
		let suf = con.reuse().mut_slice_to(N);
		let dc_init = bwt::dc::encode(output, suf, &mut mtf);
		// compress to the output
		let out_path = Path::new(format!("{}{}", file_name, ".dark"));
		let mut out_file = io::BufferedWriter::new(io::File::create(&out_path).unwrap());
		info!("Encoding N: {}", N);
		out_file.write_le_u32(N as u32).unwrap();
		// encode alphabet
		let E = dc_init.len();
		let mut helper = if E > 111 {
			info!("Alphabet is sparse");
			out_file.write_u8(0).unwrap();
			let mut rd = [N as model::dc::Distance, ..0x100];
			for &(sym,d) in dc_init.iter() {
				rd[sym] = d;
			}
			let mut eh = ari::Encoder::new(out_file);
			for (sym,&d) in rd.iter().enumerate() {
				model.encode(d, sym as u8, &mut eh);
			}
			eh
		}else {
			info!("Alphabet of size {}", E);
			out_file.write_u8(E as u8).unwrap();
			out_file.write( dc_init.map(|&(s,_)| s) ).unwrap();
			let mut eh = ari::Encoder::new(out_file);
			for &(sym,d) in dc_init.iter() {
				info!("Init distance {} for {}", d, sym);
				model.encode(d, sym, &mut eh);
			}
			eh
		};
		// encode distances
		for (&d,&sym) in suf.iter().zip(output.iter()) {
			if (d as uint) < N {
				info!("Distance {} for {}", d, sym);
				model.encode(d, sym, &mut helper);
			}
		}
		// done
		info!("Origin: {}", origin);
		model.encode(origin as model::dc::Distance, 0, &mut helper);
		let (_, err) = helper.finish();
		err.unwrap();
		info!("Encoded {} distances", model.num_processed);
	}
}
<|endoftext|>


<commit_before>use std::cmp;
use std::mem;
use std::f64;

extern crate time;

type StreamType = f64;

const HLINE: &'static str = "-------------------------------------------------------------\n";
const STREAM_ARRAY_SIZE: usize = 10000000;
const NTIMES: usize = 10;
const M: usize = 10;

static mut A: [StreamType; STREAM_ARRAY_SIZE] = [0.0; STREAM_ARRAY_SIZE];
static mut B: [StreamType; STREAM_ARRAY_SIZE] = [0.0; STREAM_ARRAY_SIZE];
static mut C: [StreamType; STREAM_ARRAY_SIZE] = [0.0; STREAM_ARRAY_SIZE];

/*
mintime[4] = {FLT_MAX,FLT_MAX,FLT_MAX,FLT_MAX};

*/
fn main() {
    /* --- SETUP --- determine precision and check timing --- */
    println!("{}", HLINE);
    println!("STREAM version $Revision: 5.10 $");
    println!("{}", HLINE);
    let bytes_per_word = mem::size_of::<StreamType>();
    println!("This system uses {} bytes per array element.", bytes_per_word);

    println!("{}", HLINE);

    println!("Array size = {} (elements)", STREAM_ARRAY_SIZE);
    println!("Memory per array = {:.1} MiB (= {:.1} GiB).",
             bytes_per_word as f64 * (STREAM_ARRAY_SIZE as f64 / 1024.0 / 1024.0),
             bytes_per_word as f64 * (STREAM_ARRAY_SIZE as f64 / 1024.0 / 1024.0 / 1024.0));
    println!("Total memory required = {:.1} MiB (= {:.1} GiB).",
            (3.0 * bytes_per_word as f64) * (STREAM_ARRAY_SIZE as f64 / 1024.0 / 1024.0),
            (3.0 * bytes_per_word as f64) * (STREAM_ARRAY_SIZE as f64 / 1024.0/1024./1024.0));
    println!("Each kernel will be executed {} times.", NTIMES);
    println!(" The *best* time for each kernel (excluding the first iteration)");
    println!(" will be used to compute the reported bandwidth.");

	println!("{}", HLINE);

    unsafe {
        for i in 0..STREAM_ARRAY_SIZE {
            A[i] = 1.0;
            B[i] = 2.0;
            C[i] = 0.0;
        }
    }

    let mut quantum = check_tick();
    if  quantum >= 1 {
        println!("Your clock granularity/precision appears to be {} microseconds.", quantum);
    } else {
	    println!("Your clock granularity appears to be less than one microsecond.");
	    quantum = 1;
    }

    let mut t = time::precise_time_s();
    unsafe {
        for i in 0..STREAM_ARRAY_SIZE {
            A[i] = 2.0 * A[i];
        }
    }
    t = 1.0E6 * (time::precise_time_s() - t);

    println!("Each test below will take on the order of {} microseconds.", t as i32);
    println!("   (= {} clock ticks)", (t / quantum as f64) as i32);
    println!("Increase the size of the arrays if this shows that");
    println!("you are not getting at least 20 clock ticks per test.");

    println!("{}", HLINE);

    println!("WARNING -- The above is only a rough guideline.");
    println!("For best results, please be sure you know the");
    println!("precision of your system timer.");
    println!("{}", HLINE);

    let mut times: [[f64; NTIMES]; 4] = [[0.0; NTIMES]; 4];

    /*	--- MAIN LOOP --- repeat test cases NTIMES times --- */

    let scalar:StreamType = 3.0;
    for k in 0..NTIMES {
        times[0][k] = time::precise_time_s();
        unsafe {
            for j in 0..STREAM_ARRAY_SIZE {
                C[j] = A[j];
            }
        }
        times[0][k] = time::precise_time_s() - times[0][k];

        times[1][k] = time::precise_time_s();
        unsafe {
            for j in 0..STREAM_ARRAY_SIZE {
                B[j] = scalar * C[j];
            }
        }
        times[1][k] = time::precise_time_s() - times[1][k];

        times[2][k] = time::precise_time_s();
        unsafe {
            for j in 0..STREAM_ARRAY_SIZE {
                C[j] = A[j] + B[j];
            }
        }
        times[2][k] = time::precise_time_s() - times[2][k];

        times[3][k] = time::precise_time_s();
        unsafe {
            for j in 0..STREAM_ARRAY_SIZE {
                A[j] = B[j] + scalar * C[j];
            }
        }
        times[3][k] = time::precise_time_s() - times[3][k];
    }

    let mut avg_time: [f64; 4] = [0.0; 4];
    let mut max_time: [f64; 4] = [0.0; 4];
    let mut min_time: [f64; 4] = [f64::MAX, f64::MAX, f64::MAX, f64::MAX];

    let label: [&'static str; 4] = ["Copy:      ", "Scale:     ",  "Add:       ", "Triad:     "];
    let bytes: [usize; 4] = [
        2 * bytes_per_word * STREAM_ARRAY_SIZE ,
        2 * bytes_per_word * STREAM_ARRAY_SIZE ,
        3 * bytes_per_word * STREAM_ARRAY_SIZE ,
        3 * bytes_per_word * STREAM_ARRAY_SIZE
    ];

    /*	--- SUMMARY --- */

    for k in 1..NTIMES /* note -- skip first iteration */
    {
        for j in 0..4
        {
            avg_time[j] = avg_time[j] + times[j][k];
            if min_time[j] > times[j][k] {
                min_time[j] = times[j][k];
            }
            if max_time[j] < times[j][k] {
                max_time[j] = times[j][k];
            }
        }
    }

    println!("Function    Best Rate MB/s  Avg time     Min time     Max time");
    for j in 0..4 {
        avg_time[j] = avg_time[j] / (NTIMES-1) as f64;

        println!("{}{:12.1}  {:11.6}  {:11.6}  {:11.6}", label[j],
            1.0E-06 * bytes[j] as f64 / min_time[j],
            avg_time[j],
            min_time[j],
            max_time[j]);
    }
    println!("{}", HLINE);

    check_stream_results();
    println!("{}", HLINE);
}

fn check_tick() -> i32 {
    let mut times_found: [f64; M] = [0.0; M];

    for i in 0..M {
        let t1 = time::precise_time_s();

        loop {
            let t2 = time::precise_time_s();
            if (t2 - t1) >= 1.0E-6 {
                times_found[i] = t2;
                break;
            }
        }
    }

    let mut min_delta = 1000000;
    for i in 1..M {
        let delta = (1.0E6 * (times_found[i] - times_found[i-1])) as i32;
        min_delta = cmp::min(min_delta, cmp::max(delta, 0));
    }

    min_delta

}

fn check_stream_results() {
    /* reproduce initialization */
    let mut aj: StreamType = 1.0;
    let mut bj: StreamType = 2.0;
    let mut cj: StreamType = 0.0;
    /* a[] is modified during timing check */
    aj = 2.0E0 * aj;
    /* now execute timing loop */
    let scalar: StreamType = 3.0;
    for _ in 0..NTIMES {
        cj = aj;
        bj = scalar * cj;
        cj = aj + bj;
        aj = bj + scalar * cj;
    }

    /* accumulate deltas between observed and expected results */
    let mut a_sum_err: StreamType = 0.0;
    let mut b_sum_err: StreamType = 0.0;
    let mut c_sum_err: StreamType = 0.0;
    for j in 0..STREAM_ARRAY_SIZE {
        unsafe {
            a_sum_err += (A[j] - aj).abs();
            b_sum_err += (B[j] - bj).abs();
            c_sum_err += (C[j] - cj).abs();
        }
    }
    let a_avg_err = a_sum_err / STREAM_ARRAY_SIZE as f64;
    let b_avg_err = b_sum_err / STREAM_ARRAY_SIZE as f64;
    let c_avg_err = c_sum_err / STREAM_ARRAY_SIZE as f64;

    let epsilon = 1.0E-13;

    let mut err = 0;
    let mut ierr = 0;

    if (a_avg_err / aj).abs() > epsilon {
        err = err + 1;
        println!("Failed Validation on array a[], AvgRelAbsErr > epsilon ({})", epsilon);
        println!("     Expected Value: {}, AvgAbsErr: {}, AvgRelAbsErr: {}",aj, a_avg_err, a_avg_err.abs()/aj);
        for j in 0..STREAM_ARRAY_SIZE {
            unsafe {
                if (A[j] / aj - 1.0).abs() > epsilon {
                    ierr = ierr + 1;
                }
            }
        }
        println!("     For array a[], {} errors were found.", ierr);
    }

    if (b_avg_err / bj).abs() > epsilon {
        err = err + 1;
        println!("Failed Validation on array b[], AvgRelAbsErr > epsilon ({})", epsilon);
        println! ("     Expected Value: {}, AvgAbsErr: {}, AvgRelAbsErr: {}",bj, b_avg_err, b_avg_err.abs()/bj);
        println! ("     AvgRelAbsErr > Epsilon {}", epsilon);
        ierr = 0;
        for j in 0..STREAM_ARRAY_SIZE {
            unsafe {
                if (B[j]/ bj - 1.0).abs() > epsilon {
                    ierr = ierr + 1;
                }
            }
        }
        println!("     For array b[], {} errors were found.", ierr);
    }

    if (c_avg_err / cj).abs() > epsilon {
        err = err + 1;
        println! ("Failed Validation on array c[], AvgRelAbsErr > epsilon ({})", epsilon);
        println! ("     Expected Value: {}, AvgAbsErr: {}, AvgRelAbsErr: {}",cj, c_avg_err, c_avg_err.abs() / cj);
        println! ("     AvgRelAbsErr > Epsilon ({})",epsilon);
        ierr = 0;
        for j in 0..STREAM_ARRAY_SIZE {
            unsafe {
                if (C[j] / cj - 1.0).abs() > epsilon {
                    ierr = ierr + 1;
                }
            }
        }
        println!("     For array c[], {} errors were found.", ierr);
    }

    if err == 0 {
        println! ("Solution Validates: avg error less than {:e} on all three arrays", epsilon);
    }

}

<commit_msg>Remove unused comment.<commit_after>use std::cmp;
use std::mem;
use std::f64;

extern crate time;

type StreamType = f64;

const HLINE: &'static str = "-------------------------------------------------------------\n";
const STREAM_ARRAY_SIZE: usize = 10000000;
const NTIMES: usize = 10;
const M: usize = 10;

static mut A: [StreamType; STREAM_ARRAY_SIZE] = [0.0; STREAM_ARRAY_SIZE];
static mut B: [StreamType; STREAM_ARRAY_SIZE] = [0.0; STREAM_ARRAY_SIZE];
static mut C: [StreamType; STREAM_ARRAY_SIZE] = [0.0; STREAM_ARRAY_SIZE];

fn main() {
    /* --- SETUP --- determine precision and check timing --- */
    println!("{}", HLINE);
    println!("STREAM version $Revision: 5.10 $");
    println!("{}", HLINE);
    let bytes_per_word = mem::size_of::<StreamType>();
    println!("This system uses {} bytes per array element.", bytes_per_word);

    println!("{}", HLINE);

    println!("Array size = {} (elements)", STREAM_ARRAY_SIZE);
    println!("Memory per array = {:.1} MiB (= {:.1} GiB).",
             bytes_per_word as f64 * (STREAM_ARRAY_SIZE as f64 / 1024.0 / 1024.0),
             bytes_per_word as f64 * (STREAM_ARRAY_SIZE as f64 / 1024.0 / 1024.0 / 1024.0));
    println!("Total memory required = {:.1} MiB (= {:.1} GiB).",
            (3.0 * bytes_per_word as f64) * (STREAM_ARRAY_SIZE as f64 / 1024.0 / 1024.0),
            (3.0 * bytes_per_word as f64) * (STREAM_ARRAY_SIZE as f64 / 1024.0/1024./1024.0));
    println!("Each kernel will be executed {} times.", NTIMES);
    println!(" The *best* time for each kernel (excluding the first iteration)");
    println!(" will be used to compute the reported bandwidth.");

	println!("{}", HLINE);

    unsafe {
        for i in 0..STREAM_ARRAY_SIZE {
            A[i] = 1.0;
            B[i] = 2.0;
            C[i] = 0.0;
        }
    }

    let mut quantum = check_tick();
    if  quantum >= 1 {
        println!("Your clock granularity/precision appears to be {} microseconds.", quantum);
    } else {
	    println!("Your clock granularity appears to be less than one microsecond.");
	    quantum = 1;
    }

    let mut t = time::precise_time_s();
    unsafe {
        for i in 0..STREAM_ARRAY_SIZE {
            A[i] = 2.0 * A[i];
        }
    }
    t = 1.0E6 * (time::precise_time_s() - t);

    println!("Each test below will take on the order of {} microseconds.", t as i32);
    println!("   (= {} clock ticks)", (t / quantum as f64) as i32);
    println!("Increase the size of the arrays if this shows that");
    println!("you are not getting at least 20 clock ticks per test.");

    println!("{}", HLINE);

    println!("WARNING -- The above is only a rough guideline.");
    println!("For best results, please be sure you know the");
    println!("precision of your system timer.");
    println!("{}", HLINE);

    let mut times: [[f64; NTIMES]; 4] = [[0.0; NTIMES]; 4];

    /*	--- MAIN LOOP --- repeat test cases NTIMES times --- */

    let scalar:StreamType = 3.0;
    for k in 0..NTIMES {
        times[0][k] = time::precise_time_s();
        unsafe {
            for j in 0..STREAM_ARRAY_SIZE {
                C[j] = A[j];
            }
        }
        times[0][k] = time::precise_time_s() - times[0][k];

        times[1][k] = time::precise_time_s();
        unsafe {
            for j in 0..STREAM_ARRAY_SIZE {
                B[j] = scalar * C[j];
            }
        }
        times[1][k] = time::precise_time_s() - times[1][k];

        times[2][k] = time::precise_time_s();
        unsafe {
            for j in 0..STREAM_ARRAY_SIZE {
                C[j] = A[j] + B[j];
            }
        }
        times[2][k] = time::precise_time_s() - times[2][k];

        times[3][k] = time::precise_time_s();
        unsafe {
            for j in 0..STREAM_ARRAY_SIZE {
                A[j] = B[j] + scalar * C[j];
            }
        }
        times[3][k] = time::precise_time_s() - times[3][k];
    }

    let mut avg_time: [f64; 4] = [0.0; 4];
    let mut max_time: [f64; 4] = [0.0; 4];
    let mut min_time: [f64; 4] = [f64::MAX, f64::MAX, f64::MAX, f64::MAX];

    let label: [&'static str; 4] = ["Copy:      ", "Scale:     ",  "Add:       ", "Triad:     "];
    let bytes: [usize; 4] = [
        2 * bytes_per_word * STREAM_ARRAY_SIZE ,
        2 * bytes_per_word * STREAM_ARRAY_SIZE ,
        3 * bytes_per_word * STREAM_ARRAY_SIZE ,
        3 * bytes_per_word * STREAM_ARRAY_SIZE
    ];

    /*	--- SUMMARY --- */

    for k in 1..NTIMES /* note -- skip first iteration */
    {
        for j in 0..4
        {
            avg_time[j] = avg_time[j] + times[j][k];
            if min_time[j] > times[j][k] {
                min_time[j] = times[j][k];
            }
            if max_time[j] < times[j][k] {
                max_time[j] = times[j][k];
            }
        }
    }

    println!("Function    Best Rate MB/s  Avg time     Min time     Max time");
    for j in 0..4 {
        avg_time[j] = avg_time[j] / (NTIMES-1) as f64;

        println!("{}{:12.1}  {:11.6}  {:11.6}  {:11.6}", label[j],
            1.0E-06 * bytes[j] as f64 / min_time[j],
            avg_time[j],
            min_time[j],
            max_time[j]);
    }
    println!("{}", HLINE);

    check_stream_results();
    println!("{}", HLINE);
}

fn check_tick() -> i32 {
    let mut times_found: [f64; M] = [0.0; M];

    for i in 0..M {
        let t1 = time::precise_time_s();

        loop {
            let t2 = time::precise_time_s();
            if (t2 - t1) >= 1.0E-6 {
                times_found[i] = t2;
                break;
            }
        }
    }

    let mut min_delta = 1000000;
    for i in 1..M {
        let delta = (1.0E6 * (times_found[i] - times_found[i-1])) as i32;
        min_delta = cmp::min(min_delta, cmp::max(delta, 0));
    }

    min_delta

}

fn check_stream_results() {
    /* reproduce initialization */
    let mut aj: StreamType = 1.0;
    let mut bj: StreamType = 2.0;
    let mut cj: StreamType = 0.0;
    /* a[] is modified during timing check */
    aj = 2.0E0 * aj;
    /* now execute timing loop */
    let scalar: StreamType = 3.0;
    for _ in 0..NTIMES {
        cj = aj;
        bj = scalar * cj;
        cj = aj + bj;
        aj = bj + scalar * cj;
    }

    /* accumulate deltas between observed and expected results */
    let mut a_sum_err: StreamType = 0.0;
    let mut b_sum_err: StreamType = 0.0;
    let mut c_sum_err: StreamType = 0.0;
    for j in 0..STREAM_ARRAY_SIZE {
        unsafe {
            a_sum_err += (A[j] - aj).abs();
            b_sum_err += (B[j] - bj).abs();
            c_sum_err += (C[j] - cj).abs();
        }
    }
    let a_avg_err = a_sum_err / STREAM_ARRAY_SIZE as f64;
    let b_avg_err = b_sum_err / STREAM_ARRAY_SIZE as f64;
    let c_avg_err = c_sum_err / STREAM_ARRAY_SIZE as f64;

    let epsilon = 1.0E-13;

    let mut err = 0;
    let mut ierr = 0;

    if (a_avg_err / aj).abs() > epsilon {
        err = err + 1;
        println!("Failed Validation on array a[], AvgRelAbsErr > epsilon ({})", epsilon);
        println!("     Expected Value: {}, AvgAbsErr: {}, AvgRelAbsErr: {}",aj, a_avg_err, a_avg_err.abs()/aj);
        for j in 0..STREAM_ARRAY_SIZE {
            unsafe {
                if (A[j] / aj - 1.0).abs() > epsilon {
                    ierr = ierr + 1;
                }
            }
        }
        println!("     For array a[], {} errors were found.", ierr);
    }

    if (b_avg_err / bj).abs() > epsilon {
        err = err + 1;
        println!("Failed Validation on array b[], AvgRelAbsErr > epsilon ({})", epsilon);
        println! ("     Expected Value: {}, AvgAbsErr: {}, AvgRelAbsErr: {}",bj, b_avg_err, b_avg_err.abs()/bj);
        println! ("     AvgRelAbsErr > Epsilon {}", epsilon);
        ierr = 0;
        for j in 0..STREAM_ARRAY_SIZE {
            unsafe {
                if (B[j]/ bj - 1.0).abs() > epsilon {
                    ierr = ierr + 1;
                }
            }
        }
        println!("     For array b[], {} errors were found.", ierr);
    }

    if (c_avg_err / cj).abs() > epsilon {
        err = err + 1;
        println! ("Failed Validation on array c[], AvgRelAbsErr > epsilon ({})", epsilon);
        println! ("     Expected Value: {}, AvgAbsErr: {}, AvgRelAbsErr: {}",cj, c_avg_err, c_avg_err.abs() / cj);
        println! ("     AvgRelAbsErr > Epsilon ({})",epsilon);
        ierr = 0;
        for j in 0..STREAM_ARRAY_SIZE {
            unsafe {
                if (C[j] / cj - 1.0).abs() > epsilon {
                    ierr = ierr + 1;
                }
            }
        }
        println!("     For array c[], {} errors were found.", ierr);
    }

    if err == 0 {
        println! ("Solution Validates: avg error less than {:e} on all three arrays", epsilon);
    }

}

<|endoftext|>


<commit_before>extern crate rand;

use std::string::String;
use std::collections::HashMap;
use std::vec::Vec;
use std::fs::{File};
use std::env;
use std::path::{Path};
use std::io::{self, BufReader, BufRead};

use rand::{random, Closed01, Rng};
use rand::distributions::{IndependentSample, Range, Sample, Gamma};

type Bag = HashMap<usize, usize>;

fn load_bags<P: AsRef<Path>>(path: P) -> io::Result<(Vec<usize>, Vec<Bag>)> {
    let mut bags = Vec::new();
    let mut labels = Vec::new();
    let file = try!(File::open(path));
    let file = BufReader::new(file);
    for line in file.lines() {
        let line = line.unwrap();
        let mut iter = line.split_whitespace();
        let label = iter.next().unwrap().parse::<usize>().unwrap();
        let mut bag = Bag::new();
        for elm in iter {
            let mut iter = elm.split(':');
            let index = iter.next().unwrap().parse::<usize>().unwrap();
            let value = iter.next().unwrap().parse::<usize>().unwrap();
            bag.insert(index - 1, value);
        }
        labels.push(label);
        bags.push(bag);
    }
    Ok((labels, bags))
}

fn load_text_vocabulary<P: AsRef<Path>>(path: P) -> io::Result<Vec<String>> {
    let mut vocab = Vec::new();
    let file = try!(File::open(path));
    let file = BufReader::new(file);
    for line in file.lines() {
        let line = line.unwrap();
        vocab.push(line);
    }
    Ok(vocab)
}

#[derive(Clone)]
struct Categorical {
    prop: Vec<f64>,
}

impl Categorical {
    fn new(weights: Vec<f64>) -> Categorical {
        let sum: f64 = weights.iter().sum();
        let prop: Vec<f64> = weights.iter().map(|w| w / sum).collect();
        Categorical {
            prop: prop,
        }
    }
}

impl Sample<usize> for Categorical {
    fn sample<R: Rng>(&mut self, rng: &mut R) -> usize {
        self.ind_sample(rng)
    }
}

impl IndependentSample<usize> for Categorical {
    fn ind_sample<R: Rng>(&self, rng: &mut R) -> usize {
        let Closed01(x) = random::<Closed01<f64>>();

        let mut sum = 0.0;
        let mut ret = self.prop.len() - 1;
        for (k, &p) in self.prop.iter().enumerate() {
            sum += p;
            if x <= sum {
                ret = k;
            }
        }
        ret
    }
}

#[derive(Clone)]
struct Dirichlet {
    alpha: Vec<f64>,
}

impl Dirichlet {
    fn new(alpha: Vec<f64>) -> Dirichlet {
        Dirichlet {
            alpha: alpha,
        }
    }
}

impl Sample<Vec<f64>> for Dirichlet {
    fn sample<R: Rng>(&mut self, rng: &mut R) -> Vec<f64> {
        self.ind_sample(rng)
    }
}

impl IndependentSample<Vec<f64>> for Dirichlet {
    fn ind_sample<R: Rng>(&self, rng: &mut R) -> Vec<f64> {
        let mut sum = 0.0;
        let mut xs = Vec::new();
        for &a in &self.alpha {
            let gamma = Gamma::new(a, 1.0);
            let y = gamma.ind_sample(rng);
            xs.push(y);
            sum += y;
        }
        for x in xs.iter_mut() {
            *x /= sum;
        }
        xs
    }
}

fn lda(num_topics: usize, dataset: Vec<Bag>, alpha: Vec<f64>, beta: Vec<f64>, num_samples: usize) {
    // Initialization
    let mut rng = rand::thread_rng();
    let topics = Range::new(0, num_topics);

    let vocab_size: usize = {
        let mut have_some = false;
        let mut max_index = 0;
        for bag in &dataset {
            for &index in bag.keys() {
                have_some = true;
                if index > max_index {
                    max_index = index;
                }
            }
        }
        if have_some {
            max_index + 1
        }
        else {
            0
        }
    };
    println!("K = {}", num_topics);
    println!("M = {}", &dataset.len());
    println!("V = {}", vocab_size);

    let mut w: Vec<Vec<usize>> = Vec::new();
    let mut z: Vec<Vec<usize>> = Vec::new();
    let mut theta: Vec<Vec<f64>> = Vec::new();
    let mut ndk: Vec<Vec<usize>> = Vec::new();
    for bag in &dataset {
        // w
        let mut w_d = Vec::new();
        for (&index, &count) in bag {
            for _ in 0..count {
                w_d.push(index);
            }
        }
        w.push(w_d);
        // z
        let mut z_d = Vec::new();
        for &count in bag.values() {
            for _ in 0..count {
                z_d.push(0);
            }
        }
        let n_d = z_d.len();
        z.push(z_d);
        // theta
        let mut theta_d = Vec::with_capacity(num_topics);
        for _k in 0..num_topics {
            theta_d.push(1.0 / num_topics as f64);
        }
        theta.push(theta_d);
        // ndk
        let mut ndk_d = Vec::with_capacity(num_topics);
        ndk_d.push(n_d);
        for _k in 1..num_topics {
            ndk_d.push(0);
        }
        ndk.push(ndk_d);
    }
    println!("z = {:?}", z);
    println!("theta = {:?}", theta);
    println!("ndk = {:?}", ndk);

    let mut phi: Vec<Vec<f64>> = Vec::new();
    let mut nkv: Vec<Vec<usize>> = Vec::new();
    // phi
    for _k in 0..num_topics {
        let mut phi_k = Vec::new();
        for _v in 0..vocab_size {
            phi_k.push(1.0 / vocab_size as f64);
        }
        phi.push(phi_k);
    }
    // nkv
    let mut nkv_0 = Vec::new();
    for _v in 0..vocab_size {
        nkv_0.push(0);
    }
    for bag in &dataset {
        for (&index, &count) in bag {
            nkv_0[index] += count;
        }
    }
    nkv.push(nkv_0);
    for _k in 1..num_topics {
        let mut nkv_k = Vec::new();
        for _v in 0..vocab_size {
            nkv_k.push(0);
        }
        nkv.push(nkv_k);
    }
    println!("phi = {:?}", phi);
    println!("nkv = {:?}", nkv);

    // Sampling
    for s in 0..num_samples {
        for (d, w_d) in w.iter().enumerate() {
            for (i, &w_di) in w_d.iter().enumerate() {
                let v = w_di;
                // Sample z_di
                let mut weights: Vec<f64> = Vec::new();
                for k in 0..num_topics {
                    weights.push(theta[d][k] * phi[k][v]);
                }
                let cat = Categorical::new(weights);
                let old_z_di = z[d][i];
                let new_z_di = cat.ind_sample(&mut rand::thread_rng());
                z[d][i] = new_z_di;
                // Update ndk and nkv
                ndk[d][old_z_di] -= 1;
                ndk[d][new_z_di] += 1;
                nkv[old_z_di][v] -= 1;
                nkv[new_z_di][v] += 1;
            }
            // Sample theta_d
            let mut alpha_d: Vec<f64> = Vec::new();
            for k in 0..num_topics {
                alpha_d.push(ndk[d][k] as f64 + alpha[k]);
            }
            let dir = Dirichlet::new(alpha_d);
            theta[d] = dir.ind_sample(&mut rand::thread_rng());
        }
        for k in 0..num_topics {
            // Sample theta_d
            let mut beta_k: Vec<f64> = Vec::new();
            for v in 0..vocab_size {
                beta_k.push(nkv[k][v] as f64 + beta[v]);
            }
            let dir = Dirichlet::new(beta_k);
            theta[k] = dir.ind_sample(&mut rand::thread_rng());
        }
    }
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let (labels, dataset) = load_bags(&args[1]).unwrap();
    let vocab: Option<Vec<String>> = if args.len() < 3 {
        None
    }
    else {
        Some(load_text_vocabulary(&args[2]).unwrap())
    };
    println!("{:?}", labels);
    println!("{:?}", dataset);
    println!("{:?}", vocab);

    lda(3, dataset, vec![1.0, 1.0, 1.0], vec![1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], 100);
}
<commit_msg>Fix a missing break<commit_after>extern crate rand;

use std::string::String;
use std::collections::HashMap;
use std::vec::Vec;
use std::fs::{File};
use std::env;
use std::path::{Path};
use std::io::{self, BufReader, BufRead};

use rand::{random, Closed01, Rng};
use rand::distributions::{IndependentSample, Range, Sample, Gamma};

type Bag = HashMap<usize, usize>;

fn load_bags<P: AsRef<Path>>(path: P) -> io::Result<(Vec<usize>, Vec<Bag>)> {
    let mut bags = Vec::new();
    let mut labels = Vec::new();
    let file = try!(File::open(path));
    let file = BufReader::new(file);
    for line in file.lines() {
        let line = line.unwrap();
        let mut iter = line.split_whitespace();
        let label = iter.next().unwrap().parse::<usize>().unwrap();
        let mut bag = Bag::new();
        for elm in iter {
            let mut iter = elm.split(':');
            let index = iter.next().unwrap().parse::<usize>().unwrap();
            let value = iter.next().unwrap().parse::<usize>().unwrap();
            bag.insert(index - 1, value);
        }
        labels.push(label);
        bags.push(bag);
    }
    Ok((labels, bags))
}

fn load_text_vocabulary<P: AsRef<Path>>(path: P) -> io::Result<Vec<String>> {
    let mut vocab = Vec::new();
    let file = try!(File::open(path));
    let file = BufReader::new(file);
    for line in file.lines() {
        let line = line.unwrap();
        vocab.push(line);
    }
    Ok(vocab)
}

#[derive(Clone)]
struct Categorical {
    prop: Vec<f64>,
}

impl Categorical {
    fn new(weights: Vec<f64>) -> Categorical {
        let sum: f64 = weights.iter().sum();
        let prop: Vec<f64> = weights.iter().map(|w| w / sum).collect();
        Categorical {
            prop: prop,
        }
    }
}

impl Sample<usize> for Categorical {
    fn sample<R: Rng>(&mut self, rng: &mut R) -> usize {
        self.ind_sample(rng)
    }
}

impl IndependentSample<usize> for Categorical {
    fn ind_sample<R: Rng>(&self, rng: &mut R) -> usize {
        let Closed01(x) = random::<Closed01<f64>>();

        let mut sum = 0.0;
        let mut ret = self.prop.len() - 1;
        for (k, &p) in self.prop.iter().enumerate() {
            sum += p;
            if x <= sum {
                ret = k;
                break;
            }
        }
        ret
    }
}

#[derive(Clone)]
struct Dirichlet {
    alpha: Vec<f64>,
}

impl Dirichlet {
    fn new(alpha: Vec<f64>) -> Dirichlet {
        Dirichlet {
            alpha: alpha,
        }
    }
}

impl Sample<Vec<f64>> for Dirichlet {
    fn sample<R: Rng>(&mut self, rng: &mut R) -> Vec<f64> {
        self.ind_sample(rng)
    }
}

impl IndependentSample<Vec<f64>> for Dirichlet {
    fn ind_sample<R: Rng>(&self, rng: &mut R) -> Vec<f64> {
        let mut sum = 0.0;
        let mut xs = Vec::new();
        for &a in &self.alpha {
            let gamma = Gamma::new(a, 1.0);
            let y = gamma.ind_sample(rng);
            xs.push(y);
            sum += y;
        }
        for x in xs.iter_mut() {
            *x /= sum;
        }
        xs
    }
}

fn lda(num_topics: usize, dataset: Vec<Bag>, alpha: Vec<f64>, beta: Vec<f64>, num_samples: usize) {
    // Initialization
    let mut rng = rand::thread_rng();
    let topics = Range::new(0, num_topics);

    let vocab_size: usize = {
        let mut have_some = false;
        let mut max_index = 0;
        for bag in &dataset {
            for &index in bag.keys() {
                have_some = true;
                if index > max_index {
                    max_index = index;
                }
            }
        }
        if have_some {
            max_index + 1
        }
        else {
            0
        }
    };
    println!("K = {}", num_topics);
    println!("M = {}", &dataset.len());
    println!("V = {}", vocab_size);

    let mut w: Vec<Vec<usize>> = Vec::new();
    let mut z: Vec<Vec<usize>> = Vec::new();
    let mut theta: Vec<Vec<f64>> = Vec::new();
    let mut ndk: Vec<Vec<usize>> = Vec::new();
    for bag in &dataset {
        // w
        let mut w_d = Vec::new();
        for (&index, &count) in bag {
            for _ in 0..count {
                w_d.push(index);
            }
        }
        w.push(w_d);
        // z
        let mut z_d = Vec::new();
        for &count in bag.values() {
            for _ in 0..count {
                z_d.push(0);
            }
        }
        let n_d = z_d.len();
        z.push(z_d);
        // theta
        let mut theta_d = Vec::with_capacity(num_topics);
        for _k in 0..num_topics {
            theta_d.push(1.0 / num_topics as f64);
        }
        theta.push(theta_d);
        // ndk
        let mut ndk_d = Vec::with_capacity(num_topics);
        ndk_d.push(n_d);
        for _k in 1..num_topics {
            ndk_d.push(0);
        }
        ndk.push(ndk_d);
    }
    println!("z = {:?}", z);
    println!("theta = {:?}", theta);
    println!("ndk = {:?}", ndk);

    let mut phi: Vec<Vec<f64>> = Vec::new();
    let mut nkv: Vec<Vec<usize>> = Vec::new();
    // phi
    for _k in 0..num_topics {
        let mut phi_k = Vec::new();
        for _v in 0..vocab_size {
            phi_k.push(1.0 / vocab_size as f64);
        }
        phi.push(phi_k);
    }
    // nkv
    let mut nkv_0 = Vec::new();
    for _v in 0..vocab_size {
        nkv_0.push(0);
    }
    for bag in &dataset {
        for (&index, &count) in bag {
            nkv_0[index] += count;
        }
    }
    nkv.push(nkv_0);
    for _k in 1..num_topics {
        let mut nkv_k = Vec::new();
        for _v in 0..vocab_size {
            nkv_k.push(0);
        }
        nkv.push(nkv_k);
    }
    println!("phi = {:?}", phi);
    println!("nkv = {:?}", nkv);

    // Sampling
    for s in 0..num_samples {
        for (d, w_d) in w.iter().enumerate() {
            for (i, &w_di) in w_d.iter().enumerate() {
                let v = w_di;
                // Sample z_di
                let mut weights: Vec<f64> = Vec::new();
                for k in 0..num_topics {
                    weights.push(theta[d][k] * phi[k][v]);
                }
                let cat = Categorical::new(weights);
                let old_z_di = z[d][i];
                let new_z_di = cat.ind_sample(&mut rand::thread_rng());
                z[d][i] = new_z_di;
                // Update ndk and nkv
                ndk[d][old_z_di] -= 1;
                ndk[d][new_z_di] += 1;
                nkv[old_z_di][v] -= 1;
                nkv[new_z_di][v] += 1;
            }
            // Sample theta_d
            let mut alpha_d: Vec<f64> = Vec::new();
            for k in 0..num_topics {
                alpha_d.push(ndk[d][k] as f64 + alpha[k]);
            }
            let dir = Dirichlet::new(alpha_d);
            theta[d] = dir.ind_sample(&mut rand::thread_rng());
        }
        for k in 0..num_topics {
            // Sample theta_d
            let mut beta_k: Vec<f64> = Vec::new();
            for v in 0..vocab_size {
                beta_k.push(nkv[k][v] as f64 + beta[v]);
            }
            let dir = Dirichlet::new(beta_k);
            theta[k] = dir.ind_sample(&mut rand::thread_rng());
        }
    }
}

fn main() {
    let args: Vec<String> = env::args().collect();
    let (labels, dataset) = load_bags(&args[1]).unwrap();
    let vocab: Option<Vec<String>> = if args.len() < 3 {
        None
    }
    else {
        Some(load_text_vocabulary(&args[2]).unwrap())
    };
    println!("{:?}", labels);
    println!("{:?}", dataset);
    println!("{:?}", vocab);

    lda(3, dataset, vec![1.0, 1.0, 1.0], vec![1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], 100);
}
<|endoftext|>


<commit_before>//
//    Stachanov
//    Copyright (C) 2017 Stachanov Developer Collective
//
//    This file is part of Stachanov.
//
//    This program is free software: you can redistribute it and/or
//    modify it under the terms of the GNU Affero General Public
//    License, version 3, as published by the Free Software Foundation.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU Affero General Public License for more details.
//
//    You should have received a copy of the
//               GNU Affero General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

extern crate rand;
extern crate crypto;
mod blockchain;
use self::rand::Rng;
use self::rand::OsRng;
use crypto::ed25519;
use blockchain::traits::Hashable;
use blockchain::header::BlockHeader;

fn main(){

    let mut seed = [0;32];
    let mut rand_gen = OsRng::new().expect("Failed to fetch random number generator");
    rand_gen.fill_bytes(& mut seed);

    let secpub_tuple = ed25519::keypair(&seed);
    let secret_key = secpub_tuple.0;
    let public_key = secpub_tuple.1;

    let mut block = BlockHeader::new(public_key, None, 0, 0xDEADBEEF, [4; 32]);

    let mut n = 0;
    while !block.verify_pow().is_ok() {
        n = n + 1;
        print!("{}: ", n);
        block.randomize_nonce();
        let bhash = block.to_sha3_hash();
        for i in 0..32 {
            print!("{:02X}", bhash[i]);
        }
        println!("");
    }

    for i in 0..32 {
        print!("{:02X}", block.nonce[i]);
    }
    println!("");

    print!("secret key: ");
    for i in 0..64 {
        print!("{:02X}", secret_key[i]);
    }
    println!("");

    print!("public_key key: ");
    for i in 0..32 {
        print!("{:02X}", public_key[i]);
    }

    println!("");
    block.sign(&secret_key);
    assert!(block.verify_internal().is_ok());

}
<commit_msg>Removed toy code in main.rs<commit_after>//
//    Stachanov
//    Copyright (C) 2017 Stachanov Developer Collective
//
//    This file is part of Stachanov.
//
//    This program is free software: you can redistribute it and/or
//    modify it under the terms of the GNU Affero General Public
//    License, version 3, as published by the Free Software Foundation.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU Affero General Public License for more details.
//
//    You should have received a copy of the
//               GNU Affero General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

mod blockchain;

fn main(){
}
<|endoftext|>


<commit_before>extern crate rustwlc;

use rustwlc::types;
use rustwlc::types::*;
use rustwlc::handle::{WlcView, WlcOutput};
use rustwlc::interface::*;
use rustwlc::input::{pointer, keyboard};

/*
struct CompositorAction {
    view: WlcView,
    grab: Point,
    edges: u32
}

static mut compositor: CompositorAction = CompositorAction {
    view: WlcView(0),
    grab: Point{ x: 0, y: 0},
    edges: 0
};
*/
fn main() {
    let interface: WlcInterface = WlcInterface {
        output: OutputInterface {
            created: Some(output_created),
            destroyed: Some(output_destroyed),
            focus: Some(output_focus),
            resolution: Some(output_resolution),

            render: OutputRenderInterface {
                pre: Some(output_render_pre),
                post: Some(output_render_post)
            }
        },
        view: ViewInterface {
            created: Some(view_created),
            destroyed: Some(view_destroyed),
            focus: Some(view_focus),
            move_to_output: Some(view_move_to_output),
            request: RequestInterface {
                geometry: Some(view_request_geometry),
                state: Some(view_request_state),
                move_: Some(view_request_move),
                resize: Some(view_request_resize),
                render: ViewRenderInterface {
                    pre: Some(view_request_render_pre),
                    post: Some(view_request_render_post)
                }
            }
        },
        keyboard: KeyboardInterface {
            key: Some(keyboard_key)
        },
        pointer: PointerInterface {
            button: Some(pointer_button),
            scroll: Some(pointer_scroll),
            motion: Some(pointer_motion)
        },
        touch: TouchInterface {
            touch: Some(touch_touch)
        },
        compositor: CompositorInterface {
            ready: Some(compositor_ready)
        },
        input: InputInterface {
            created: Some(input_created),
            destroyed: Some(input_destroyed)
        }
    };

    if !rustwlc::init(interface) {
        panic!("Unable to initialize wlc!");
    }
    rustwlc::run_wlc();
}

// Important rendering functions copied from wlc/example/example.c

fn start_interactive_action(view: WlcView, origin: Point) -> bool {
    true
}

fn stop_interactive_action() {

}

fn start_interactive_move(view: WlcView, origin: Point) {

}

fn start_interactive_resize(view: WlcView, edges: u32, origin: Point) {

}

fn get_topmost_view(output: WlcOutput, offset: Size) {

}

/// From example.c:
/// very simple layout function
/// you probably don't want to layout certain type of windows in wm
fn render_output(output: WlcOutput) {
    use std::cmp;
    let resolution = output.get_resolution();
    let views = output.get_views();
    println!("Rendering {} views for {} (resolution = {:?})", views.len(), output.get_name(), resolution);

    if views.len() == 0 { println!("Didn't find any views to render :/"); }

    for view in views {
        println!("Setting {:?}", view);
        println!("\tIts type: {}", view.get_type());
        println!("\tIts output: {}", view.get_output().get_name());
        println!("\tIts geometry: {:?}", view.get_geometry());
        println!("\tIts state: {}", view.get_state());
        println!("\tIts parent: {:?}", view.get_parent());
        println!("\tIts title: {}", view.get_title());
        // get_class doesn't work but maybe it's not supposed to
        //println!("\tIts class: {}", view.get_class());
        view.set_geometry(0,
                          &Geometry {
                              size: Size {
                                  w: 0 as u32,
                                  h: 0 as u32
                              },
                              origin: Point {
                                  x: resolution.w as i32,
                                  y: resolution.h as i32
                              }
                          });
        println!("Attempted to set geometry, got {:?}", view.get_geometry());
    }

    /*
    let mut toggle = false;
    let mut y = 0u32;
//    use std::cmp;

    let w: u32 = resolution.w as u32 / 2u32;
    let h: u32 = resolution.h as u32 / cmp::max((1u32 + views.len() as u32) / 2u32, 1);

    for view in views {
        let g = Geometry {
            size: Size {
                w: if toggle { w } else { 0 },
                h: y
            },
            origin: Point {
                x: if !toggle { resolution.w as i32 } else { w as i32 },
                y: h as i32
            }
        };
        view.set_geometry(0, g);
        toggle = !toggle;
        y = y + if !toggle { h } else { 0 };
    }*/
}

// Hook up basic callbacks

extern fn output_created(output: WlcOutput) -> bool {
    println!("output_created: {:?}: {}", output, output.get_name());
    return true;
}

extern fn output_destroyed(output: WlcOutput) {
    println!("output_destroyed");
}

extern fn output_focus(output: WlcOutput, focused: bool) {
    println!("output_focus: {}", focused);
}

extern fn output_resolution(output: WlcOutput,
                            old_size_ptr: &Size, new_size_ptr: &Size) {
    println!("output_resolution: {:?} from  {:?} to {:?}",
             output, *old_size_ptr, *new_size_ptr);
}

extern fn output_render_pre(output: WlcOutput) {
    //println!("output_render_pre");
}

extern fn output_render_post(output: WlcOutput) {
    //println!("output_render_post");
}

extern fn view_created(view: WlcView) -> bool {
    println!("view_created: {:?}", view);
    let output = view.get_output();
    view.set_mask(output.get_mask());
    view.bring_to_front();
    view.focus();
    render_output(output);
    true
}

extern fn view_destroyed(view: WlcView) {
    println!("view_destroyed: {:?}", view);
    render_output(view.get_output());
}

extern fn view_focus(current: WlcView, focused: bool) {
    println!("view_focus: {:?} {}", current, focused);
    current.set_state(ViewState::Activated, focused);
}

extern fn view_move_to_output(current: WlcView, q1: WlcView, q2: WlcView) {
    println!("view_move_to_output: {:?}, {:?}, {:?}", current, q1, q2);
}

extern fn view_request_geometry(view: WlcView, geometry: &Geometry) {
    println!("view_request_geometry: {:?} wants {:?}", view, geometry);
    view.set_geometry(0, geometry);
    render_output(view.get_output());
}

extern fn view_request_state(view: WlcView, state: ViewState, handled: bool) {
    view.set_state(state, handled);
}

extern fn view_request_move(view: WlcView, dest: &Point) {
    //println!("view_request_move: to {}, start interactive mode.", *dest);
}

extern fn view_request_resize(view: WlcView, edge: ResizeEdge, location: &Point) {
    println!("view_request_resize: size {:?}, to {}, start interactive mode.",
             edge, *location);
}

extern fn view_request_render_pre(view: WlcView) {
}

extern fn view_request_render_post(view: WlcView) {
}

extern fn keyboard_key(view: WlcView, time: u32, mods_ptr: &KeyboardModifiers,
                       key: u32, state: KeyState) -> bool {
    use std::process::{Command};
    println!("keyboard_key: time {}, mods {:?}, key {:?}, state {:?}",
             time, &*mods_ptr, key, state);
    if state == KeyState::Pressed { return false; }
    if key == 67 {
        println!("Preparing to open the terminal...");
        let mut child = Command::new("/bin/weston-terminal").spawn()
            .unwrap_or_else(|e| { println!("Error spawning child: {}", e); panic!("1") });
    }
    false
}

extern fn pointer_button(view: WlcView, button: u32, mods_ptr: &KeyboardModifiers,
                         key: u32, state: ButtonState, point_ptr: &Point) -> bool {
    println!("pointer_button: pressed {} at {}", key, *point_ptr);
    if state == ButtonState::Pressed {
        view.focus();
    }
    false
}

extern fn pointer_scroll(view: WlcView, button: u32, mods_ptr: &KeyboardModifiers,
                  axis: ScrollAxis, heights: [u64; 2]) -> bool {
    println!("pointer_scroll");
    false
}

extern fn pointer_motion(view: WlcView, time: u32, point: &Point) {
    pointer::set_position(point);
}

extern fn touch_touch(view: WlcView, time: u32, mods_ptr: &KeyboardModifiers,
               touch: TouchType, key: i32, point_ptr: &Point) -> bool {
    false
}

extern fn compositor_ready() {
    println!("Preparing compositor!");
}

extern fn input_created(device: &LibinputDevice) -> bool {
    println!("input_created");
    false
}

extern fn input_destroyed(device: &LibinputDevice) {
    println!("input_destroyed");
}
<commit_msg>Clear out old code, build unbroken<commit_after>extern crate rustwlc;

use rustwlc::types;
use rustwlc::types::*;
use rustwlc::handle::{WlcView, WlcOutput};
use rustwlc::interface::*;
use rustwlc::input::{pointer, keyboard};

fn main() {
    let interface: WlcInterface = WlcInterface::new()
        .output_created(output_created)
        .output_destroyed(output_destroyed)
        .output_focus(output_focus)
        .output_resolution(output_resolution)
        .output_render_pre(output_render_pre)
        .output_render_post(output_render_post)
        .view_created(view_created)
        .view_destroyed(view_destroyed)
        .view_focus(view_focus)
        .view_move_to_output(view_move_to_output)
        .view_request_geometry(view_request_geometry)
        .view_request_state(view_request_state)
        .view_request_move(view_request_move)
        .view_request_resize(view_request_resize)
        .view_request_render_pre(view_request_render_pre)
        .view_request_render_post(view_request_render_post)
        .keyboard_key(keyboard_key)
        .pointer_button(pointer_button)
        .pointer_scroll(pointer_scroll)
        .pointer_motion(pointer_motion)
        .touch_touch(touch_touch)
        .compositor_ready(compositor_ready);
        //.input_created(input_created)
        //.input_destroyed(input_destroyed);

    rustwlc::log_set_default_handler();

    //let run_wlc = rustwlc::init(interface).expect("Unable to initialize wlc!");
    if !rustwlc::init(interface) {
        panic!("Unable to initialize wlc!");
    }
    rustwlc::run_wlc();
}

/// From example.c:
/// very simple layout function
/// you probably don't want to layout certain type of windows in wm
fn render_output(output: WlcOutput) {
    use std::cmp;
    let resolution = output.get_resolution();
    let views = output.get_views();
    println!("Rendering {} views for {} (resolution = {:?})", views.len(), output.get_name(), resolution);

    if views.len() == 0 { println!("Didn't find any views to render :/"); }

    for view in views {
        println!("Setting {:?}", view);
        println!("\tIts type: {:?}", view.get_type());
        println!("\tIts output: {}", view.get_output().get_name());
        println!("\tIts geometry: {:?}", view.get_geometry());
        println!("\tIts state: {:?}", view.get_state());
        println!("\tIts parent: {:?}", view.get_parent());
        println!("\tIts title: {}", view.get_title());
        // get_class doesn't work but maybe it's not supposed to
        //println!("\tIts class: {}", view.get_class());
        view.set_geometry(EDGE_NONE,
                          &Geometry {
                              size: Size {
                                  w: 0 as u32,
                                  h: 0 as u32
                              },
                              origin: Point {
                                  x: resolution.w as i32,
                                  y: resolution.h as i32
                              }
                          });
        println!("Attempted to set geometry, got {:?}", view.get_geometry());
    }
}

// Hook up basic callbacks

extern fn output_created(output: WlcOutput) -> bool {
    println!("output_created: {:?}: {}", output, output.get_name());
    return true;
}

extern fn output_destroyed(output: WlcOutput) {
    println!("output_destroyed");
}

extern fn output_focus(output: WlcOutput, focused: bool) {
    println!("output_focus: {}", focused);
}

extern fn output_resolution(output: WlcOutput,
                            old_size_ptr: &Size, new_size_ptr: &Size) {
    println!("output_resolution: {:?} from  {:?} to {:?}",
             output, *old_size_ptr, *new_size_ptr);
}

extern fn output_render_pre(output: WlcOutput) {
    //println!("output_render_pre");
}

extern fn output_render_post(output: WlcOutput) {
    //println!("output_render_post");
}

extern fn view_created(view: WlcView) -> bool {
    println!("view_created: {:?}: \"{}\"", view, view.get_title());
    let output = view.get_output();
    view.set_mask(output.get_mask());
    view.bring_to_front();
    view.focus();
    render_output(output);
    true
}

extern fn view_destroyed(view: WlcView) {
    println!("view_destroyed: {:?}", view);
    render_output(view.get_output());
}

extern fn view_focus(current: WlcView, focused: bool) {
    println!("view_focus: {:?} {}", current, focused);
    current.set_state(VIEW_ACTIVATED, focused);
}

extern fn view_move_to_output(current: WlcView, o1: WlcOutput, o2: WlcOutput) {
    println!("view_move_to_output: {:?}, {:?}, {:?}", current, o1, o2);
}

extern fn view_request_geometry(view: WlcView, geometry: &Geometry) {
    println!("view_request_geometry: {:?} wants {:?}", view, geometry);
    view.set_geometry(EDGE_NONE, geometry);
    render_output(view.get_output());
}

extern fn view_request_state(view: WlcView, state: ViewState, handled: bool) {
    view.set_state(state, handled);
}

extern fn view_request_move(view: WlcView, dest: &Point) {
    //println!("view_request_move: to {}, start interactive mode.", *dest);
}

extern fn view_request_resize(view: WlcView, edge: ResizeEdge, location: &Point) {
    println!("view_request_resize: edge {:?}, to {}, start interactive mode.",
             edge, location);
}

extern fn view_request_render_pre(view: WlcView) {
}

extern fn view_request_render_post(view: WlcView) {
}

extern fn keyboard_key(view: WlcView, time: u32, mods_ptr: &KeyboardModifiers,
                       key: u32, state: KeyState) -> bool {
    println!("keyboard_key: time {}, mods {:?}, key {:?}, state {:?}",
             time, &*mods_ptr, key, state);
    false
}

extern fn pointer_button(view: WlcView, button: u32, mods_ptr: &KeyboardModifiers,
                         key: u32, state: ButtonState, point_ptr: &Point) -> bool {
    println!("pointer_button: pressed {} at {}", key, *point_ptr);
    if state == ButtonState::Pressed && !view.is_root() {
        view.focus();
    }
    false
}

extern fn pointer_scroll(view: WlcView, button: u32, mods_ptr: &KeyboardModifiers,
                  axis: ScrollAxis, heights: [u64; 2]) -> bool {
    println!("pointer_scroll");
    false
}

extern fn pointer_motion(view: WlcView, time: u32, point: &Point) -> bool {
    pointer::set_position(point);
    false
}

extern fn touch_touch(view: WlcView, time: u32, mods_ptr: &KeyboardModifiers,
               touch: TouchType, key: i32, point_ptr: &Point) -> bool {
    false
}

extern fn compositor_ready() {
    println!("Preparing compositor!");
}

extern fn input_created(device: &LibinputDevice) -> bool {
    println!("input_created");
    false
}

extern fn input_destroyed(device: &LibinputDevice) {
    println!("input_destroyed");
}
<|endoftext|>


<commit_before>#[macro_use]
extern crate rustful;
use std::error::Error;
use std::sync::Mutex;
use rustful::{Server, Context, Response, TreeRouter, Handler};
use std::io::{BufReader, BufRead};

fn print_packet(context: Context, response: Response) {
    // Print headers
    println!("Headers: ");
    for value in context.headers.iter() {
        print!(">> {}", value);
    }

    println!("Variables: ");
    for (key, value) in context.variables.iter() {
        println!("{} -> {}", key.as_utf8().unwrap(), value.as_utf8().unwrap());
    }

    println!("Query: ");
    for (key, value) in context.query.iter() {
        println!("{} -> {}", key.as_utf8().unwrap(), value.as_utf8().unwrap());
    }

    println!("Fragment: ");
    for value in context.fragment.iter() {
        println!(">> {}", value.as_utf8().unwrap());
    }

    println!("Content: ");
    let mut lines = BufReader::new(context.body).lines().enumerate();
    while let Some((lineno, Ok(line))) = lines.next() {
        println!("{}: {}", lineno + 1, line);
    }

    response.send("ok");
}

struct RequestHandler {
    mutex: Mutex<u32>,
    callback: fn(Context, Response),
}

impl RequestHandler {
    fn new(cbk: fn(Context, Response)) -> RequestHandler {
        RequestHandler {
            mutex: Mutex::new(0),
            callback: cbk
        }
    }
}

impl Handler for RequestHandler {
    fn handle_request(&self, context: Context, response: Response) {
        let _g = self.mutex.lock().unwrap();
        (self.callback)(context, response);
    }
}

fn main() {
    let server_result = Server {
            host: 8081.into(),
            handlers: insert_routes!{
            TreeRouter::new() => {
                "/" => Get: RequestHandler::new(print_packet),
                // Just an example.
                "/:endpoint/:id" => Get: RequestHandler::new(print_packet),
                "/:endpoint/:id" => Post: RequestHandler::new(print_packet)
            }
        },
            ..Server::default()
        }
        .run();

    match server_result {
        Ok(_server) => {}
        Err(e) => println!("could not start server: {}", e.description()),
    }
}
<commit_msg>Adding http method to the output<commit_after>#[macro_use]
extern crate rustful;
use std::error::Error;
use std::sync::Mutex;
use rustful::{Server, Context, Response, TreeRouter, Handler};
use std::io::{BufReader, BufRead};

fn print_packet(context: Context, response: Response) {
    println!("Method: {}", context.method);
    // Print headers
    println!("Headers: ");
    for value in context.headers.iter() {
        print!(">> {}", value);
    }

    println!("Variables: ");
    for (key, value) in context.variables.iter() {
        println!("{} -> {}", key.as_utf8().unwrap(), value.as_utf8().unwrap());
    }

    println!("Query: ");
    for (key, value) in context.query.iter() {
        println!("{} -> {}", key.as_utf8().unwrap(), value.as_utf8().unwrap());
    }

    println!("Fragment: ");
    for value in context.fragment.iter() {
        println!(">> {}", value.as_utf8().unwrap());
    }

    println!("Content: ");
    let mut lines = BufReader::new(context.body).lines().enumerate();
    while let Some((lineno, Ok(line))) = lines.next() {
        println!("{}: {}", lineno + 1, line);
    }
    response.send("ok");
}

struct RequestHandler {
    mutex: Mutex<u32>,
    callback: fn(Context, Response),
}

impl RequestHandler {
    fn new(cbk: fn(Context, Response)) -> RequestHandler {
        RequestHandler {
            mutex: Mutex::new(0),
            callback: cbk
        }
    }
}

impl Handler for RequestHandler {
    fn handle_request(&self, context: Context, response: Response) {
        let _g = self.mutex.lock().unwrap();
        (self.callback)(context, response);
    }
}

fn main() {
    let server_result = Server {
            host: 8081.into(),
            handlers: insert_routes!{
            TreeRouter::new() => {
                "/" => Get: RequestHandler::new(print_packet),
                // Just an example.
                "/:endpoint/:id" => Get: RequestHandler::new(print_packet),
                "/:endpoint/:id" => Post: RequestHandler::new(print_packet),
                "/:endpoint/:id" => Delete: RequestHandler::new(print_packet)
            }
        },
            ..Server::default()
        }
        .run();

    match server_result {
        Ok(_server) => {}
        Err(e) => println!("could not start server: {}", e.description()),
    }
}
<|endoftext|>