<commit_before><commit_msg>Forgot to include an example script for training using the new traits.<commit_after>//extern crate devicemem_cuda;
//extern crate march;
extern crate neuralops;
//extern crate neuralops_cuda;
extern crate operator;
extern crate rand;
extern crate rng;

//use devicemem_cuda::prelude::*;
//use march::march_sgd_new::*;
use neuralops::prelude::*;
use neuralops::data::{CyclicDataIter, RandomSampleDataIter};
use neuralops::data::cifar::{CifarFlavor, CifarDataShard};
use neuralops::archs::*;
//use neuralops_cuda::archs::*;
use operator::prelude::*;
//use operator::opt::sgd_new::{SgdConfig, SgdWorker};
use operator::opt::sgd::{SgdConfig, SgdUpdate};
//use operator::opt::stochastic::{StochasticGradWorker};
use rng::xorshift::{Xorshiftplus128Rng};

use rand::{thread_rng};
use std::path::{PathBuf};

fn main() {
  let batch_sz = 128;

  let mut train_data =
      RandomSampleDataIter::new(
      CifarDataShard::new(
          CifarFlavor::Cifar10,
          PathBuf::from("datasets/cifar10/train.bin"),
      ));
  let mut valid_data =
      CyclicDataIter::new(
      CifarDataShard::new(
          CifarFlavor::Cifar10,
          PathBuf::from("datasets/cifar10/test.bin"),
      ));

  let loss = build_cifar10_resnet20_loss(batch_sz);

  let sgd_cfg = SgdConfig{
    step_size:  StepSize::Decay{init_step: 0.1, step_decay: 0.1, decay_iters: 50000},
    momentum:   Some(GradientMomentum::Nesterov(0.9)),
  };
  let mut checkpoint = CheckpointState::new(CheckpointConfig{
    prefix: PathBuf::from("logs/cifar10_resnet20_sgd"),
    trace:  true,
  });
  checkpoint.append_config_info(&sgd_cfg);
  let mut sgd: StochasticGradWorker<f32, SgdUpdate<_, _, _, _>, _, _, _> = StochasticGradWorker::new(batch_sz, batch_sz, sgd_cfg, loss);
  //checkpoint.append_config_info(&marchsgd_cfg);
  //let mut sgd: StochasticGradWorker<f32, MarchRmspropUpdateStep<_, _, _>, _, _> = StochasticGradWorker::new(batch_sz, batch_sz, marchsgd_cfg, loss);
  let mut stats = ClassLossStats::default();
  let mut display_stats = ClassLossStats::default();
  let mut rng = Xorshiftplus128Rng::new(&mut thread_rng());

  println!("DEBUG: training...");
  sgd.init(&mut rng);
  for iter_nr in 0 .. 150000 {
    checkpoint.start_timing();
    sgd.step(&mut train_data);
    checkpoint.stop_timing();
    sgd.update_stats(&mut stats);
    sgd.update_stats(&mut display_stats);
    checkpoint.append_class_stats_train(&stats);
    stats.reset();
    if (iter_nr + 1) % 1 == 0 {
      println!("DEBUG: iter: {} accuracy: {:.4} stats: {:?}", iter_nr + 1, display_stats.accuracy(), display_stats);
      display_stats.reset();
    }
    if (iter_nr + 1) % 500 == 0 {
      println!("DEBUG: validating...");
      checkpoint.start_timing();
      sgd.eval(valid_data.len(), &mut valid_data);
      checkpoint.stop_timing();
      sgd.update_stats(&mut stats);
      checkpoint.append_class_stats_valid(&stats);
      println!("DEBUG: valid: accuracy: {:.4} stats: {:?}", stats.accuracy(), stats);
      stats.reset();
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>Start adding some unit tests<commit_after>extern crate net2;

use std::net::TcpStream;
use std::io::prelude::*;
use std::thread;

use net2::TcpBuilder;

macro_rules! t {
    ($e:expr) => (match $e {
        Ok(e) => e,
        Err(e) => panic!("{} failed with: {}", stringify!($e), e),
    })
}

#[test]
fn smoke_build_listener() {
    let b = t!(TcpBuilder::new_v4());
    t!(b.bind("127.0.0.1:0"));
    let listener = t!(b.listen(200));

    let addr = t!(listener.local_addr());

    let t = thread::spawn(move || {
        let mut s = t!(listener.accept()).0;
        let mut b = [0; 4];
        t!(s.read(&mut b));
        assert_eq!(b, [1, 2, 3, 0]);
    });

    let mut stream = t!(TcpStream::connect(&addr));
    t!(stream.write(&[1,2,3]));
    t.join().unwrap();
}
<|endoftext|>


<commit_before>#![cfg(feature = "ecs")]

extern crate rusoto;

use rusoto::ecs::ECSClient;
use rusoto::credentials::DefaultAWSCredentialsProviderChain;
use rusoto::regions::Region;

#[test]
fn main() {
    let credentials = DefaultAWSCredentialsProviderChain::new();
    let region = Region::UsEast1;
    let mut ecs = ECSClient::new(
        credentials,
        &region
    );
    match ecs.list_clusters(&Default::default()) {
        Ok(clusters) => {
            for arn in clusters.clusterArns.unwrap_or(vec![]) {
                println!("arn -> {:?}", arn);
            }
        },
        Err(err) => {
            println!("Error listing container instances {:#?}", err);
        }
    }
}
<commit_msg>be more explicit in the parameter passed to method in ecs test<commit_after>#![cfg(feature = "ecs")]

extern crate rusoto;

use rusoto::ecs::{ECSClient, ListClustersRequest};
use rusoto::credentials::DefaultAWSCredentialsProviderChain;
use rusoto::regions::Region;

#[test]
fn main() {
    let credentials = DefaultAWSCredentialsProviderChain::new();
    let region = Region::UsEast1;
    let mut ecs = ECSClient::new(
        credentials,
        &region
    );

    // http://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_ListClusters.html
    match ecs.list_clusters(&ListClustersRequest::default()) {
        Ok(clusters) => {
            for arn in clusters.clusterArns.unwrap_or(vec![]) {
                println!("arn -> {:?}", arn);
            }
        },
        Err(err) => {
            println!("Error listing container instances {:#?}", err);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add ignored input tests<commit_after>extern crate httpd = "tiny-http";

use std::io::net::tcp::TcpStream;

#[test]
#[ignore]   // failing
fn input_basic_string() {
    let (server, port) = httpd::Server::new_with_random_port().unwrap();

    {
        let mut stream = std::io::net::tcp::TcpStream::connect("127.0.0.1", port).unwrap();
        write!(stream, "GET / HTTP/1.1\r\nHost: localhost\r\nContent-Type: text/plain; charset=utf8\r\nContent-Length: 5\r\n\r\nhello");
    }

    let mut request = server.recv().unwrap();

    assert_eq!(request.as_reader().read_to_string().unwrap().as_slice(), "hello");
}
<|endoftext|>


<commit_before><commit_msg>Add problem #15<commit_after>use std;
use euler;

import euler::prime::{ iterable_factors };
import euler::prime;
import euler::util;

fn mul_facti(fss: [[(u64, i64)]]) -> [(u64, i64)] {
    ret util::mergei(fss) { |f1, f2|
        let (base1, exp1) = f1;
        let (base2, exp2) = f2;
        if base1 < base2 {
            ret util::lt;
        }
        if base1 > base2 {
            ret util::gt;
        }
        ret util::eq((base1, exp1 + exp2));
    };
}

fn pow(base: u64, exp: u64) -> u64 {
    let result = 1u64;
    let itr = exp;
    let pow = base;
    while itr > 0u64 {
        if itr & 0x1u64 == 0x1u64 {
            result *= pow;
        }
        itr >>= 1u64;
        pow *= pow;
    }
    ret result;
}

fn fact_to_uint(fs: [(u64, i64)]) -> u64 {
    let result = 1u64;
    for (base, exp) in fs {
        if exp > 0 {
            result *= pow(base, exp as u64);
        } else {
            result /= pow(base, (-exp) as u64);
        }
    }
    ret result;
}

fn main() {
    let primes = prime::init();
    let numer = mul_facti(vec::map(vec::enum_uints(21u, 40u)) { |num|
        iter::to_list(prime::factors(num, primes))
    });
    let denom = vec::map(mul_facti(vec::map(vec::enum_uints(1u, 20u)) { |num|
        iter::to_list(prime::factors(num, primes))
    })) { |f|
        let (base, exp) = f;
        ret (base, -exp);
    };
    std::io::println(#fmt("%u", fact_to_uint(mul_facti([numer, denom]))));
}
<|endoftext|>


<commit_before><commit_msg>Basic tests for the new port types<commit_after>#![feature(const_fn)]
#![no_std] // don't link the Rust standard library
#![cfg_attr(not(test), no_main)] // disable all Rust-level entry points

#[cfg(not(test))]
use core::panic::PanicInfo;
use testing::{exit_qemu, serial_println};
use x86_64::instructions::port::{PortReadOnly, PortWriteOnly, Port};

// This port tells the data port which index to read from
const CRT_INDEX_PORT: u16 = 0x3D4;

// This port stores the data for the index set by the index port
const CRT_DATA_PORT: u16 = 0x3D5;

// The offset crt register is used because it's a port with no reserved
// bits that won't crash the system when written to
const OFFSET_REGISTER: u8 = 0x0A;

// A randomly chosen value to test againts
const TEST_VALUE: u8 = 0b10101010;

/// This function is the entry point, since the linker looks for a function
/// named `_start_` by default.
#[cfg(not(test))]
#[no_mangle] // don't mangle the name of this function
pub extern "C" fn _start() -> ! {
    let mut crt_index_port = PortWriteOnly::<u8>::new(CRT_INDEX_PORT);
    let mut crt_read_write_data_port = Port::<u8>::new(CRT_DATA_PORT);
    let crt_data_read_only_port = PortReadOnly::<u8>::new(CRT_DATA_PORT);

    unsafe {
        // Set the offset register as the index using PortWriteOnly
        crt_index_port.write(OFFSET_REGISTER);

        // Write the test value to the data port using Port
        crt_read_write_data_port.write(TEST_VALUE);

        // Read the test value using PortReadOnly
        let read_only_test_value = crt_data_read_only_port.read() & 0xFF;

        // Read the test value using PortReadWrite
        let read_write_test_value = crt_read_write_data_port.read() & 0xFF;

        if read_only_test_value != TEST_VALUE {
            panic!("PortReadOnly: {} does not match expected value {}", read_only_test_value, TEST_VALUE);
        }

        if read_write_test_value != TEST_VALUE {
            panic!("PortReadWrite: {} does not match expected value {}", read_write_test_value, TEST_VALUE);
        }
    }

    serial_println!("ok");

    unsafe {
        exit_qemu();
    }

    loop {}
}

/// This function is called on panic.
#[cfg(not(test))]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
    serial_println!("failed");

    serial_println!("{}", info);

    unsafe {
        exit_qemu();
    }
    loop {}
}<|endoftext|>


<commit_before><commit_msg>:art: Make possible to use TogglConfig<commit_after><|endoftext|>


<commit_before><commit_msg>lexer: boilerplate for include directive<commit_after><|endoftext|>


<commit_before><commit_msg>empty commit message<commit_after>use std::fmt;

#[allow(non_camel_case_types)]
#[derive(Copy, Clone)]
enum Piece {
    WhitePawn,
    WhiteBishop,
    WhiteKnight,
    WhiteRook,
    WhiteQueen,
    WhiteKing,
    BlackPawn,
    BlackBishop,
    BlackKnight,
    BlackRook,
    BlackQueen,
    BlackKing,
}

pub struct Board {
    board: [Option<Piece>; 64],
    white_turn: bool,
    castle_rights: [bool; 4], // [ white K, white Q, black k, black q ]
    en_passant_target: Option<usize>,
    halfmove_clock: usize,
    move_number: usize,
}

impl Board {
    pub fn new() -> Self {
        Board {
            board: [None; 64],
            white_turn: true,
            castle_rights: [true, true, true, true],
            en_passant_target: None,
            halfmove_clock: 0,
            move_number: 1,
        }
    }

    // "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
    pub fn from_fen(fen: &str) -> Self {
        let mut b = Board::new();
        let mut i = 7;
        let mut j = 0;
        for c in fen.chars() {
            match c {
                'r' => {
                    b.board[i*8+j] = Some(Piece::BlackRook);
                    j += 1;
                }

                'R' => {
                    b.board[i*8+j] = Some(Piece::WhiteRook);
                    j += 1;
                }

                _   => {},
            }
        }
        b
    }

}

impl fmt::Display for Piece {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Piece::WhitePawn   => write!(f, "P"),
            Piece::WhiteBishop => write!(f, "B"),
            Piece::WhiteKnight => write!(f, "N"),
            Piece::WhiteRook   => write!(f, "R"),
            Piece::WhiteQueen  => write!(f, "Q"),
            Piece::WhiteKing   => write!(f, "K"),
            Piece::BlackPawn   => write!(f, "p"),
            Piece::BlackBishop => write!(f, "b"),
            Piece::BlackKnight => write!(f, "n"),
            Piece::BlackRook   => write!(f, "r"),
            Piece::BlackQueen  => write!(f, "q"),
            Piece::BlackKing   => write!(f, "k"),
        }
    }
}

impl fmt::Display for Board {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for i in 0..8 {
            write!(f, "[ ")?;
            for j in 0..8 {
                match self.board[i*8+j] {
                    Some(x) => write!(f, "{} ", x)?,
                    None => write!(f, "  ")?,
                }
            }
            write!(f, "]\n")?;
        }
        write!(f, "")
    }
}
<|endoftext|>


<commit_before><commit_msg>Update to nightly<commit_after><|endoftext|>


<commit_before><commit_msg>Begin the process of generating all magics at compile time.  WIP.<commit_after>extern crate rand;

use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;

mod bitboard;
#[allow(unused_imports)]
use bitboard::{BitBoard, EMPTY};

mod square;
#[allow(unused_imports)]
use square::{Square, NUM_SQUARES, ALL_SQUARES};

mod rank;
#[allow(unused_imports)]
use rank::Rank;

mod file;
#[allow(unused_imports)]
use file::File as ChessFile;

mod piece;
#[allow(unused_imports)]
use piece::Piece;

mod color;
#[allow(unused_imports)]
pub use color::Color;

// the following things are just for move generation

#[derive(Copy, Clone)]
struct Magic {
    magic_number: BitBoard,
    mask: BitBoard,
    offset: u32,
    rightshift: u8,
}

const ROOK: usize = 0;
const BISHOP: usize = 1;

static mut MAGIC_NUMBERS: [[Magic; NUM_SQUARES]; 2 ] =
        [[Magic { magic_number: EMPTY, mask: EMPTY, offset: 0, rightshift: 0 }; 64]; 2];

const ROOK_BITS: usize = 12;
const BISHOP_BITS: usize = 9;
const NUM_MOVES: usize = 64 * (1<<ROOK_BITS) /* Rook Moves */ +
                         64 * (1<<BISHOP_BITS) /* Bishop Moves */;

static mut MOVES: [BitBoard; NUM_MOVES] = [EMPTY; NUM_MOVES];

static mut KING_MOVES: [BitBoard; 64] = [EMPTY; 64];
static mut KNIGHT_MOVES: [BitBoard; 64] = [EMPTY; 64];
static mut PAWN_MOVES: [[BitBoard; 64]; 2] = [[EMPTY; 64]; 2];
static mut PAWN_ATTACKS: [[BitBoard; 64]; 2] = [[EMPTY; 64]; 2];

// the following are helper variables to cache regularly-used values
static mut LINE: [[BitBoard; 64]; 64] = [[EMPTY; 64]; 64];
static mut BETWEEN: [[BitBoard; 64]; 64] = [[EMPTY; 64]; 64];
static mut RAYS: [[BitBoard; 64]; 2] = [[EMPTY; 64]; 2];

fn gen_bishop_rays() {
   for src in ALL_SQUARES.iter() {
        unsafe {
            RAYS[BISHOP][src.to_index()] =
                ALL_SQUARES.iter()
                           .filter(|dest| {
                                let src_rank = src.get_rank().to_index() as i8;
                                let src_file = src.get_file().to_index() as i8;
                                let dest_rank = dest.get_rank().to_index() as i8;
                                let dest_file = dest.get_file().to_index() as i8;

                                (src_rank - dest_rank).abs() == (src_file - dest_file).abs() &&
                                    *src != **dest})
                           .fold(EMPTY, |b, s| b | BitBoard::from_square(*s));
        }
    }
}

fn gen_rook_rays() {
   for src in ALL_SQUARES.iter() {
        unsafe {
            RAYS[ROOK][src.to_index()] =
                ALL_SQUARES.iter()
                           .filter(|dest| {
                                let src_rank = src.get_rank().to_index();
                                let src_file = src.get_file().to_index();
                                let dest_rank = dest.get_rank().to_index();
                                let dest_file = dest.get_file().to_index();

                                (src_rank == dest_rank || src_file == dest_file) &&
                                    *src != **dest})
                           .fold(EMPTY, |b, s| b | BitBoard::from_square(*s));
        }
    }
}

fn gen_edges() -> BitBoard {
    ALL_SQUARES.iter()
               .filter(|sq| sq.get_rank() == Rank::First ||
                            sq.get_rank() == Rank::Eighth ||
                            sq.get_file() == ChessFile::A ||
                            sq.get_file() == ChessFile::H)
               .fold(EMPTY, |b, s| b | BitBoard::from_square(*s))

}

fn gen_lines() {
    for src in ALL_SQUARES.iter() {
        for dest in ALL_SQUARES.iter() {
            unsafe {
                LINE[src.to_index()][dest.to_index()] =
                    ALL_SQUARES.iter()
                               .filter(|test| {
                                    let src_rank = src.get_rank().to_index() as i8;
                                    let src_file = src.get_file().to_index() as i8;
                                    let dest_rank = dest.get_rank().to_index() as i8;
                                    let dest_file = dest.get_file().to_index() as i8;
                                    let test_rank = test.get_rank().to_index() as i8;
                                    let test_file = test.get_file().to_index() as i8;

                                    // test diagonals first
                                    if ((src_rank - dest_rank).abs() ==
                                        (src_file - dest_file).abs() &&
                                        *src != *dest) {
                                        (src_rank - test_rank).abs() ==
                                            (src_file - test_file).abs() &&
                                        (dest_rank - test_rank).abs() ==
                                            (dest_file - test_file).abs()
                                    // next, test rank/file lines
                                    } else if ((src_rank == dest_rank || src_file == dest_file) &&
                                               *src != *dest) {
                                        (src_rank == test_rank &&
                                            dest_rank == test_rank &&
                                            src_rank == dest_rank) ||
                                        (src_file == test_file &&
                                            dest_file == test_file &&
                                            src_file == dest_file)
                                    // if src and dest don't line up, there is no line.  Return
                                    // EMPTY
                                    } else {
                                        false
                                    }
                               })
                               .fold(EMPTY, |b, s| b | BitBoard::from_square(*s));
            }
        }
    }
}

fn gen_knight_moves() {
    for src in ALL_SQUARES.iter() {
        unsafe {
            KNIGHT_MOVES[src.to_index()] =
                ALL_SQUARES.iter()
                           .filter(|dest| {
                                let src_rank = src.get_rank().to_index() as i8;
                                let src_file = src.get_file().to_index() as i8;
                                let dest_rank = dest.get_rank().to_index() as i8;
                                let dest_file = dest.get_file().to_index() as i8;

                                ((src_rank - dest_rank).abs() == 2 &&
                                 (src_file - dest_file).abs() == 1) ||
                                ((src_rank - dest_rank).abs() == 1 &&
                                 (src_file - dest_file).abs() == 2)
                           })
                           .fold(EMPTY, |b, s| b | BitBoard::from_square(*s));
        }
    }
}

fn gen_king_moves() {
    for src in ALL_SQUARES.iter() {
        unsafe {
            KING_MOVES[src.to_index()] =
                ALL_SQUARES.iter()
                           .filter(|dest| {
                                let src_rank = src.get_rank().to_index() as i8;
                                let src_file = src.get_file().to_index() as i8;
                                let dest_rank = dest.get_rank().to_index() as i8;
                                let dest_file = dest.get_file().to_index() as i8;

                                (src_rank - dest_rank).abs() == 1 ||
                                (src_file - dest_file).abs() == 1
                           })
                           .fold(EMPTY, |b, s| b | BitBoard::from_square(*s));
        }
    }
}

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    let magic_path = Path::new(&out_dir).join("magic_gen.rs");
    let mut f = File::create(&magic_path).unwrap();

    f.write_all(b"
        pub fn message() -> &'static str {
            \"Hello World\"
            }").unwrap();
}

<|endoftext|>


<commit_before><commit_msg>Stuff<commit_after>use std::io;

fn user_input(wordType: &str) -> &str {
    let input = io::stdin().read_line()
                           .ok()
                           .expect("Failed to read a line.");

    let input_num: Option<int> = from_str(input.as_slice().trim());

    let isNumber = false;
    match input_num {
        Some(number) => number,
        None         => isNumber = false
    }

    if wordType == "number" && !isNumber {
        println!("This is not a number");
        "no value"
    }

    let index = 0;

    match input.find_str(" or ") {
        Some(number) => index = number,
        None => index = 0
    }

    if index > 0 {

    }
}
<|endoftext|>


<commit_before><commit_msg>added transpose implementation<commit_after>// #![feature(scoped)]
// #![feature(collections)]

extern crate mmap;
extern crate time;
extern crate timely;
extern crate columnar;
extern crate dataflow_join;

extern crate docopt;
use docopt::Docopt;

use std::thread;

use dataflow_join::graph::{GraphTrait, GraphMMap};

use timely::progress::timestamp::RootTimestamp;
use timely::progress::scope::Scope;
use timely::progress::nested::Summary::Local;
use timely::example_static::*;
use timely::communication::*;
use timely::communication::pact::Exchange;

use timely::networking::initialize_networking;
use timely::networking::initialize_networking_from_file;

use timely::drain::DrainExt;

static USAGE: &'static str = "
Usage: pagerank <source> [options] [<arguments>...]

Options:
    -w <arg>, --workers <arg>    number of workers per process [default: 1]
    -p <arg>, --processid <arg>  identity of this process      [default: 0]
    -n <arg>, --processes <arg>  number of processes involved  [default: 1]
    -h <arg>, --hosts <arg>      list of host:port for workers
";

fn main () {
    let args = Docopt::new(USAGE).and_then(|dopt| dopt.parse()).unwrap_or_else(|e| e.exit());

    // let workers = if let Ok(threads) = args.get_str("<workers>").parse() { threads }
    //               else { panic!("invalid setting for workers: {}", args.get_str("<workers>")) };
    // println!("starting pagerank dataflow with {:?} worker{}", workers, if workers == 1 { "" } else { "s" });
    let source = args.get_str("<source>").to_owned();

    let workers: u64 = if let Ok(threads) = args.get_str("-w").parse() { threads }
                       else { panic!("invalid setting for --workers: {}", args.get_str("-t")) };
    let process_id: u64 = if let Ok(proc_id) = args.get_str("-p").parse() { proc_id }
                          else { panic!("invalid setting for --processid: {}", args.get_str("-p")) };
    let processes: u64 = if let Ok(processes) = args.get_str("-n").parse() { processes }
                         else { panic!("invalid setting for --processes: {}", args.get_str("-n")) };

    println!("Starting pagerank dataflow with");
    println!("\tworkers:\t{}", workers);
    println!("\tprocesses:\t{}", processes);
    println!("\tprocessid:\t{}", process_id);

    // vector holding communicators to use; one per local worker.
    if processes > 1 {
        println!("Initializing BinaryCommunicator");

        let hosts = args.get_str("-h");
        let communicators = if hosts != "" {
            initialize_networking_from_file(hosts, process_id, workers).ok().expect("error initializing networking")
        }
        else {
            let addresses = (0..processes).map(|index| format!("localhost:{}", 2101 + index).to_string()).collect();
            initialize_networking(addresses, process_id, workers).ok().expect("error initializing networking")
        };

        pagerank_multi(communicators, source);
    }
    else if workers > 1 {
        println!("Initializing ProcessCommunicator");
        pagerank_multi(ProcessCommunicator::new_vector(workers), source);
    }
    else {
        println!("Initializing ThreadCommunicator");
        pagerank_multi(vec![ThreadCommunicator], source);
    };
}

fn pagerank_multi<C>(communicators: Vec<C>, filename: String)
where C: Communicator+Send {
    let mut guards = Vec::new();
    let workers = communicators.len();
    for communicator in communicators.into_iter() {
        let filename = filename.clone();
        guards.push(thread::Builder::new().name(format!("timely worker {}", communicator.index()))
                                          .spawn(move || pagerank(communicator, filename, workers))
                                          .unwrap());
    }

    for guard in guards { guard.join().unwrap(); }
}

fn transpose(filename: String, index: usize, peers: usize) -> (Vec<u32>, Vec<(u32, u32)>, Vec<u32>)  {

    let graph = GraphMMap::<u32>::new(&filename);

    let mut edges = Vec::new();
    let mut deg = vec![];

    for node in 0..graph.nodes() {
        if node % peers == index {
            deg.push(graph.edges(index + peers * node).len() as u32);
            for &b in graph.edges(index + peers * node) {
                edges.push((b as u32, node as u32));
            }
        }
    }

    edges.sort();

    let mut rev = vec![(0,0);0];
    let mut reversed = vec![];
    for (d, s) in edges.drain_temp() {
        let len = rev.len();
        if len == 0 || rev[len-1].1 < d {
            rev.push((d, 0));
        }

        let len = rev.len();
        rev[len-1].1 += 1;
        reversed.push(s);
    }

    return (deg, rev, reversed);
}

fn pagerank<C>(communicator: C, filename: String, workers: usize)
where C: Communicator {
    let index = communicator.index() as usize;
    let peers = communicator.peers() as usize;

    let mut root = GraphRoot::new(communicator);

    {   // new scope avoids long borrow on root
        let mut builder = root.new_subgraph();

        // establish the beginnings of a loop,
        // 20 iterations, each time around += 1.
        let (helper, stream) = builder.loop_variable::<(u32, f32)>(RootTimestamp::new(20), Local(1));

        let mut start = time::precise_time_s();

        let (deg, rev, edges) = transpose(filename, index, peers);

        println!("sorted: {}s", time::precise_time_s() - start);
        start = time::precise_time_s();

        let mut src = vec![0.0; deg.len()];

        // from feedback, place an operator that
        // aggregates and broadcasts ranks along edges.
        let ranks = stream.enable(builder).unary_notify(

            Exchange::new(|x: &(u32, f32)| x.0 as u64),     // 1. how data should be exchanged
            format!("PageRank"),                            // 2. a tasteful, descriptive name
            vec![RootTimestamp::new(0)],                    // 3. indicate an initial capability
            move |input, output, iterator| {                // 4. provide the operator logic

                while let Some((iter, _)) = iterator.next() {

                    for node in 0..src.len() {
                        src[node] = 0.15 + 0.85 * src[node] / deg[node] as f32;
                    }

                    let mut session = output.session(&iter);

                    let mut slice = &edges[..];
                    for &(dst, deg) in &rev {
                        let mut accum = 0.0;
                        for &s in &slice[..deg as usize] {
                            accum += src[s as usize];
                        }
                        slice = &slice[deg as usize..];
                        session.give((dst, accum));
                    }

                    for s in &mut src { *s = 0.0; }

                    println!("iteration {:?}: {}s", iter, time::precise_time_s() - start);
                    start = time::precise_time_s();
                }

                while let Some((iter, data)) = input.pull() {
                    iterator.notify_at(&iter);
                    for (node, rank) in data.drain_temp() {
                        src[node as usize / peers] += rank;
                    }
                }
            }
        );

        // let local_index = index as usize % workers;
        // let mut acc = vec![0.0; src.len()];

        ranks
        // .unary_notify(
        //     Exchange::new(move |x: &(u32, f32)| (workers * (index / workers)) as u64 + (x.0 as u64 % workers as u64)),
        //     format!("Aggregation"),
        //     vec![],
        //     move |input, output, iterator| {
        //         while let Some((iter, data)) = input.pull() {
        //             iterator.notify_at(&iter);
        //             for (node, rank) in data.drain_temp() {
        //                 acc[node as usize / workers] += rank;
        //             }
        //         }
        //
        //         while let Some((item, _)) = iterator.next() {
        //
        //             output.give_at(&item, acc.drain_temp().enumerate().filter(|x| x.1 != 0.0)
        //                                      .map(|(u,f)| (((u * workers + local_index) as u32), f)));
        //
        //             for _ in 0..(1 + (nodes/workers)) { acc.push(0.0); }
        //             assert!(acc.len() == (1 + (nodes/workers)));
        //         }
        //     }
        // )
        .connect_loop(helper);
    }

    while root.step() { }
}
<|endoftext|>


<commit_before><commit_msg>Remove unused imports.<commit_after><|endoftext|>


<commit_before><commit_msg>Add hello world application<commit_after>extern crate http;
extern crate iron;

use std::io::net::ip::Ipv4Addr;
use iron::status;
use iron::{
    Iron,
    Request,
    Response,
    IronResult,
};

fn main() {
    Iron::new(hello_world).listen(Ipv4Addr(127, 0, 0, 1), 3000);
    println!("On 3000");
}

fn hello_world(_: &mut Request) -> IronResult<Response> {
    Ok(Response::with(status::Ok, "Hello, world!"))
}
<|endoftext|>


<commit_before><commit_msg>encode testing<commit_after><|endoftext|>


<commit_before><commit_msg>[fix] forgotten file<commit_after>#[derive(Debug)]
pub enum Parsed {
    Error(String),
    Empty,
    Section(String),
    Value(String, String), /* Vector(String, Vec<String>), impossible, because HashMap field has type String, not Vec */
}

pub fn parse_line(line: &str) -> Parsed {
    let content = line.split(';').nth(0).unwrap().trim();
    if content.len() == 0 {
        return Parsed::Empty;
    }
    // add checks for content
    if content.starts_with('[') {
        if content.ends_with(']') {
            let section_name = content.trim_matches(|c| c == '[' || c == ']').to_owned();
            return Parsed::Section(section_name);
        } else {
            return Parsed::Error("incorrect section syntax".to_owned());
        }
    } else if content.contains('=') {
        let mut pair = content.split('=').map(|s| s.trim());
        let key = pair.next().unwrap().to_owned();
        let value = pair.next().unwrap().to_owned();
        return Parsed::Value(key, value);
    }
    Parsed::Error("incorrect syntax".to_owned())
}

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

    #[test]
    fn test_comment() {
        match parse_line(";------") {
            Parsed::Empty => assert!(true),
            _ => assert!(false),
        }
    }

    #[test]
    fn test_entry() {
        match parse_line("name1 = 100 ; comment") {
            Parsed::Value(name, text) => {
                assert_eq!(name, String::from("name1"));
                assert_eq!(text, String::from("100"));
            }
            _ => assert!(false),
        }
    }

    #[test]
    fn test_weird_name() {
        match parse_line("_.,:(){}-#@&*| = 100") {
            Parsed::Value(name, text) => {
                assert_eq!(name, String::from("_.,:(){}-#@&*|"));
                assert_eq!(text, String::from("100"));
            }
            _ => assert!(false),
        }
    }

    #[test]
    fn test_text_entry() {
        match parse_line("text_name = hello world!") {
            Parsed::Value(name, text) => {
                assert_eq!(name, String::from("text_name"));
                assert_eq!(text, String::from("hello world!"));
            }
            _ => assert!(false),
        }
    }

    #[test]
    fn test_incorrect_token() {
        match parse_line("[section = 1, 2 = value") {
            Parsed::Error(_) => assert!(true),
            _ => assert!(false),
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>trash<commit_after><|endoftext|>


<commit_before><commit_msg>Add unit test.<commit_after><|endoftext|>


<commit_before><commit_msg>Set low/high in timer reload correctly<commit_after><|endoftext|>


<commit_before><commit_msg>Assert build script success in cargo-5730<commit_after><|endoftext|>


<commit_before><commit_msg>Added some rotation functions, properly this time<commit_after>use super::geometry::*;

fn rotate(x: f32, y: f32, around_x: f32, around_y: f32, angle: f32) -> (f32, f32) {
    use std::f32;

    let s = f32::sin(angle);
    let c = f32::cos(angle);

    let x = x - around_x;
    let y = y - around_y;

    let x = x * c - y * s;
    let y = x * s + y * c;

    (x + around_x, y + around_y)
}

pub trait Rotation {
    fn rotate_x_y(&mut self, x: f32, y: f32, angle: f32);
    fn rotate_x_z(&mut self, x: f32, y: f32, angle: f32);
    fn rotate_y_z(&mut self, x: f32, y: f32, angle: f32);
}

impl Rotation for Point {
    fn rotate_x_y(&mut self, x: f32, y: f32, angle: f32) {
        let (x, y) = rotate(self.x, self.y, x, y, angle);
        self.x = x;
        self.y = y;
    }

    fn rotate_x_z(&mut self, x: f32, z: f32, angle: f32) {
        let (x, z) = rotate(self.x, self.z, x, z, angle);
        self.x = x;
        self.z = z;
    }

    fn rotate_y_z(&mut self, y: f32, z: f32, angle: f32) {
        let (y, z) = rotate(self.y, self.z, y, z, angle);
        self.y = y;
        self.z = z;
    }
}

impl Rotation for Triangle {
    fn rotate_x_y(&mut self, x: f32, y: f32, angle: f32) {
        self.p1.rotate_x_y(x, y, angle);
        self.p2.rotate_x_y(x, y, angle);
        self.p3.rotate_x_y(x, y, angle);
    }

    fn rotate_x_z(&mut self, x: f32, z: f32, angle: f32) {
        self.p1.rotate_x_z(x, z, angle);
        self.p2.rotate_x_z(x, z, angle);
        self.p3.rotate_x_z(x, z, angle);
    }

    fn rotate_y_z(&mut self, y: f32, z: f32, angle: f32) {
        self.p1.rotate_y_z(y, z, angle);
        self.p2.rotate_y_z(y, z, angle);
        self.p3.rotate_y_z(y, z, angle);
    }
}<|endoftext|>


<commit_before><commit_msg>tests: add an api.rs test for testing api uses of scroll<commit_after>// this exists primarily to test various API usages of scroll; e.g., must compile

extern crate scroll;

#[macro_use] extern crate scroll_derive;

use std::ops::{Deref,  DerefMut};
use scroll::{ctx, Result, Pread, Gread};
use scroll::ctx::SizeWith;

pub struct Section<'a> {
    pub sectname:  [u8; 16],
    pub segname:   [u8; 16],
    pub addr:      u64,
    pub size:      u64,
    pub offset:    u32,
    pub align:     u32,
    pub reloff:    u32,
    pub nreloc:    u32,
    pub flags:     u32,
    pub data:      &'a [u8],
}

impl<'a> Section<'a> {
    pub fn name(&self) -> Result<&str> {
        self.sectname.pread::<&str>(0)
    }
    pub fn segname(&self) -> Result<&str> {
        self.segname.pread::<&str>(0)
    }
}

impl<'a> ctx::SizeWith<ctx::DefaultCtx> for Section<'a> {
    type Units = usize;
    fn size_with(_ctx: &ctx::DefaultCtx) -> usize {
        4
    }
}

#[repr(C)]
#[derive(Debug, Clone, Copy, Pread, Pwrite)]
pub struct Section32 {
    pub sectname:  [u8; 16],
    pub segname:   [u8; 16],
    pub addr:      u32,
    pub size:      u32,
    pub offset:    u32,
    pub align:     u32,
    pub reloff:    u32,
    pub nreloc:    u32,
    pub flags:     u32,
    pub reserved1: u32,
    pub reserved2: u32,
}

impl<'a> ctx::TryFromCtx<'a, (usize, ctx::DefaultCtx)> for Section<'a> {
    type Error = scroll::Error;
    fn try_from_ctx(_bytes: &'a [u8], (_offset, _ctx): (usize, ctx::DefaultCtx)) -> ::std::result::Result<Self, Self::Error> {
        //let section = Section::from_ctx(bytes, bytes.pread_with::<Section32>(offset, ctx)?);
        let section = unsafe { ::std::mem::uninitialized::<Section>()};
        Ok(section)
    }
}

pub struct Segment<'a> {
    pub cmd:      u32,
    pub cmdsize:  u32,
    pub segname:  [u8; 16],
    pub vmaddr:   u64,
    pub vmsize:   u64,
    pub fileoff:  u64,
    pub filesize: u64,
    pub maxprot:  u32,
    pub initprot: u32,
    pub nsects:   u32,
    pub flags:    u32,
    pub data:     &'a [u8],
    offset:       usize,
    raw_data:     &'a [u8],
}

impl<'a> Segment<'a> {
    pub fn name(&self) -> Result<&str> {
        Ok(self.segname.pread::<&str>(0)?)
    }
    pub fn sections(&self) -> Result<Vec<Section<'a>>> {
        let nsects = self.nsects as usize;
        let mut sections = Vec::with_capacity(nsects);
        let offset = &mut (self.offset + Self::size_with(&ctx::CTX));
        let _size = Section::size_with(&ctx::CTX);
        let raw_data: &'a [u8] = self.raw_data;
        for _ in 0..nsects {
            let section = raw_data.gread_with::<Section<'a>>(offset, ctx::CTX)?;
            sections.push(section);
            //offset += size;
        }
        Ok(sections)
    }
}

impl<'a> ctx::SizeWith<ctx::DefaultCtx> for Segment<'a> {
    type Units = usize;
    fn size_with(_ctx: &ctx::DefaultCtx) -> usize {
        4
    }
}

pub struct Segments<'a> {
    pub segments: Vec<Segment<'a>>,
}

impl<'a> Deref for Segments<'a> {
    type Target = Vec<Segment<'a>>;
    fn deref(&self) -> &Self::Target {
        &self.segments
    }
}

impl<'a> DerefMut for Segments<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.segments
    }
}

impl<'a> Segments<'a> {
    pub fn new() -> Self {
        Segments {
            segments: Vec::new(),
        }
    }
    pub fn sections(&self) -> Result<Vec<Vec<Section<'a>>>> {
        let mut sections = Vec::new();
        for segment in &self.segments {
            sections.push(segment.sections()?);
        }
        Ok(sections)
    }
}

fn lifetime_passthrough_<'a>(segments: &Segments<'a>, section_name: &str) -> Option<&'a [u8]> {
    let segment_name = "__TEXT";
    for segment in &segments.segments {
        if let Ok(name) = segment.name() {
            println!("segment.name: {}", name);
            if name == segment_name {
                if let Ok(sections) = segment.sections() {
                    for section in sections {
                        let sname = section.name().unwrap();
                        println!("section.name: {}", sname);
                        if section_name == sname {
                            return Some(section.data);
                        }
                    }
                }
            }
        }
    }
    None
}

#[test]
fn lifetime_passthrough() {
    let segments = Segments::new();
    let _res = lifetime_passthrough_(&segments, "__text");
    assert!(true)
}
<|endoftext|>


<commit_before>#![feature(macro_rules)]

#![crate_id="sdl2_image#sdl2_image:0.1"]
#![crate_type = "lib"]
#![desc = "SDL2_image bindings and wrappers"]
#![comment = "SDL2_image bindings and wrappers"]
#![license = "MIT"]

extern crate sdl2;
extern crate libc;

use libc::{c_int, c_char};
use std::ptr;
use sdl2::surface::Surface;
use sdl2::render::Texture;
use sdl2::render::Renderer;
use sdl2::rwops::RWops;
use sdl2::version::Version;
use sdl2::get_error;

// Setup linking for all targets.
#[cfg(target_os="macos")]
mod mac {
    #[cfg(mac_framework)]
    #[link(kind="framework", name="SDL2_image")]
    extern {}

    #[cfg(not(mac_framework))]
    #[link(name="SDL2_image")]
    extern {}
}

#[cfg(target_os="win32")]
#[cfg(target_os="linux")]
#[cfg(target_os="freebsd")]
mod others {
    #[link(name="SDL2_image")]
    extern {}
}

#[allow(non_camel_case_types, dead_code)]
mod ffi;

/// InitFlags are passed to init() to control which subsystem
/// functionality to load.
bitflags!(flags InitFlag : u32 {
    static InitJpg = ffi::IMG_INIT_JPG as u32,
    static InitPng = ffi::IMG_INIT_PNG as u32,
    static InitTif = ffi::IMG_INIT_TIF as u32,
    static InitWebp = ffi::IMG_INIT_WEBP as u32
})

/// Static method extensions for creating Surfaces
pub trait LoadSurface {
    // Self is only returned here to type hint to the compiler.
    // The syntax for type hinting in this case is not yet defined.
    // The intended return value is Result<~Surface, ~str>.
    fn from_file(filename: &Path) -> Result<Self, ~str>;
    fn from_xpm_array(xpm: **i8) -> Result<Self, ~str>;
}

/// Method extensions to Surface for saving to disk
pub trait SaveSurface {
    fn save(&self, filename: &Path) -> Result<(), ~str>;
    fn save_rw(&self, dst: &mut RWops) -> Result<(), ~str>;
}

impl LoadSurface for Surface {
    fn from_file(filename: &Path) -> Result<Surface, ~str> {
        //! Loads an SDL Surface from a file
        unsafe {
            let raw = ffi::IMG_Load(filename.to_c_str().unwrap());
            if raw == ptr::null() {
                Err(get_error())
            } else {
                Ok(Surface { raw: raw, owned: true })
            }
        }
    }

    fn from_xpm_array(xpm: **i8) -> Result<Surface, ~str> {
        //! Loads an SDL Surface from XPM data
        unsafe {
            let raw = ffi::IMG_ReadXPMFromArray(xpm as **c_char);
            if raw == ptr::null() {
                Err(get_error())
            } else {
                Ok(Surface { raw: raw, owned: true })
            }
        }
    }
}

impl SaveSurface for Surface {
    fn save(&self, filename: &Path) -> Result<(), ~str> {
        //! Saves an SDL Surface to a file
        unsafe {
            let status = ffi::IMG_SavePNG(self.raw,
                                          filename.to_c_str().unwrap());
            if status != 0 {
                Err(get_error())
            } else {
                Ok(())
            }
        }
    }

    fn save_rw(&self, dst: &mut RWops) -> Result<(), ~str> {
        //! Saves an SDL Surface to an RWops
        unsafe {
            let status = ffi::IMG_SavePNG_RW(self.raw, dst.raw, 0);

            if status != 0 {
                Err(get_error())
            } else {
                Ok(())
            }
        }
    }
}

/// Method extensions for creating Textures from a Renderer
pub trait LoadTexture {
    fn load_texture(&self, filename: &Path) -> Result<Texture, ~str>;
}

impl LoadTexture for Renderer {
    fn load_texture(&self, filename: &Path) -> Result<Texture, ~str> {
        //! Loads an SDL Texture from a file
        unsafe {
            let raw = ffi::IMG_LoadTexture(self.raw,
                                           filename.to_c_str().unwrap());
            if raw == ptr::null() {
                Err(get_error())
            } else {
                Ok(Texture{ raw: raw, owned: true })
            }
        }
    }
}

pub fn init(flags: InitFlag) -> InitFlag {
    //! Initializes SDL2_image with InitFlags and returns which
    //! InitFlags were actually used.
    unsafe {
        let used = ffi::IMG_Init(flags.bits() as c_int);
        InitFlag::from_bits_truncate(used as u32)
    }
}

pub fn quit() {
    //! Teardown the SDL2_Image subsystem
    unsafe { ffi::IMG_Quit(); }
}

pub fn get_linked_version() -> Version {
    //! Returns the version of the dynamically linked SDL_image library
    unsafe {
        Version::from_ll(ffi::IMG_Linked_Version())
    }
}

#[inline]
fn to_surface_result(raw: *sdl2::surface::ll::SDL_Surface) -> Result<Surface, ~str> {
    if raw == ptr::null() {
        Err(get_error())
    } else {
        Ok(Surface { raw: raw, owned: true })
    }
}

pub trait ImageRWops {
    /// load as a surface. except TGA
    fn load(&self) -> Result<Surface, ~str>;
    /// load as a surface. This can load all supported image formats.
    fn load_typed(&self, _type: &str) -> Result<Surface, ~str>;

    fn load_cur(&self) -> Result<Surface, ~str>;
    fn load_ico(&self) -> Result<Surface, ~str>;
    fn load_bmp(&self) -> Result<Surface, ~str>;
    fn load_pnm(&self) -> Result<Surface, ~str>;
    fn load_xpm(&self) -> Result<Surface, ~str>;
    fn load_xcf(&self) -> Result<Surface, ~str>;
    fn load_pcx(&self) -> Result<Surface, ~str>;
    fn load_gif(&self) -> Result<Surface, ~str>;
    fn load_jpg(&self) -> Result<Surface, ~str>;
    fn load_tif(&self) -> Result<Surface, ~str>;
    fn load_png(&self) -> Result<Surface, ~str>;
    fn load_tga(&self) -> Result<Surface, ~str>;
    fn load_lbm(&self) -> Result<Surface, ~str>;
    fn load_xv(&self)  -> Result<Surface, ~str>;
    fn load_webp(&self) -> Result<Surface, ~str>;

    fn is_cur(&self) -> bool;
    fn is_ico(&self) -> bool;
    fn is_bmp(&self) -> bool;
    fn is_pnm(&self) -> bool;
    fn is_xpm(&self) -> bool;
    fn is_xcf(&self) -> bool;
    fn is_pcx(&self) -> bool;
    fn is_gif(&self) -> bool;
    fn is_jpg(&self) -> bool;
    fn is_tif(&self) -> bool;
    fn is_png(&self) -> bool;
    fn is_lbm(&self) -> bool;
    fn is_xv(&self)  -> bool;
    fn is_webp(&self) -> bool;
}

impl ImageRWops for RWops {
    fn load(&self) -> Result<Surface, ~str> {
        let raw = unsafe {
            ffi::IMG_Load_RW(self.raw, 0)
        };
        to_surface_result(raw)
    }
    fn load_typed(&self, _type: &str) -> Result<Surface, ~str> {
        let raw = unsafe {
            ffi::IMG_LoadTyped_RW(self.raw, 0, _type.to_c_str().unwrap())
        };
        to_surface_result(raw)
    }

    fn load_cur(&self) -> Result<Surface, ~str> {
        let raw = unsafe { ffi::IMG_LoadCUR_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_ico(&self) -> Result<Surface, ~str> {
        let raw = unsafe { ffi::IMG_LoadICO_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_bmp(&self) -> Result<Surface, ~str> {
        let raw = unsafe { ffi::IMG_LoadBMP_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_pnm(&self) -> Result<Surface, ~str> {
        let raw = unsafe { ffi::IMG_LoadPNM_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_xpm(&self) -> Result<Surface, ~str> {
        let raw = unsafe { ffi::IMG_LoadXPM_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_xcf(&self) -> Result<Surface, ~str> {
        let raw = unsafe { ffi::IMG_LoadXCF_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_pcx(&self) -> Result<Surface, ~str> {
        let raw = unsafe { ffi::IMG_LoadPCX_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_gif(&self) -> Result<Surface, ~str> {
        let raw = unsafe { ffi::IMG_LoadGIF_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_jpg(&self) -> Result<Surface, ~str> {
        let raw = unsafe { ffi::IMG_LoadJPG_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_tif(&self) -> Result<Surface, ~str> {
        let raw = unsafe { ffi::IMG_LoadTIF_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_png(&self) -> Result<Surface, ~str> {
        let raw = unsafe { ffi::IMG_LoadPNG_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_tga(&self) -> Result<Surface, ~str> {
        let raw = unsafe { ffi::IMG_LoadTGA_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_lbm(&self) -> Result<Surface, ~str> {
        let raw = unsafe { ffi::IMG_LoadLBM_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_xv(&self)  -> Result<Surface, ~str> {
        let raw = unsafe { ffi::IMG_LoadXV_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_webp(&self)  -> Result<Surface, ~str> {
        let raw = unsafe { ffi::IMG_LoadWEBP_RW(self.raw) };
        to_surface_result(raw)
    }

    fn is_cur(&self) -> bool {
        unsafe { ffi::IMG_isCUR(self.raw) == 1 }
    }
    fn is_ico(&self) -> bool {
        unsafe { ffi::IMG_isICO(self.raw) == 1 }
    }
    fn is_bmp(&self) -> bool {
        unsafe { ffi::IMG_isBMP(self.raw) == 1 }
    }
    fn is_pnm(&self) -> bool {
        unsafe { ffi::IMG_isPNM(self.raw) == 1 }
    }
    fn is_xpm(&self) -> bool {
        unsafe { ffi::IMG_isXPM(self.raw) == 1 }
    }
    fn is_xcf(&self) -> bool {
        unsafe { ffi::IMG_isXCF(self.raw) == 1 }
    }
    fn is_pcx(&self) -> bool {
        unsafe { ffi::IMG_isPCX(self.raw) == 1 }
    }
    fn is_gif(&self) -> bool {
        unsafe { ffi::IMG_isGIF(self.raw) == 1 }
    }
    fn is_jpg(&self) -> bool {
        unsafe { ffi::IMG_isJPG(self.raw) == 1 }
    }
    fn is_tif(&self) -> bool {
        unsafe { ffi::IMG_isTIF(self.raw) == 1 }
    }
    fn is_png(&self) -> bool {
        unsafe { ffi::IMG_isPNG(self.raw) == 1 }
    }
    fn is_lbm(&self) -> bool {
        unsafe { ffi::IMG_isLBM(self.raw) == 1 }
    }
    fn is_xv(&self)  -> bool {
        unsafe { ffi::IMG_isXV(self.raw)  == 1 }
    }
    fn is_webp(&self) -> bool {
        unsafe { ffi::IMG_isWEBP(self.raw)  == 1 }
    }
}
<commit_msg>fix compile error: StrBuf change<commit_after>#![feature(macro_rules)]

#![crate_id="sdl2_image#sdl2_image:0.1"]
#![crate_type = "lib"]
#![desc = "SDL2_image bindings and wrappers"]
#![comment = "SDL2_image bindings and wrappers"]
#![license = "MIT"]

extern crate sdl2;
extern crate libc;

use libc::{c_int, c_char};
use std::ptr;
use sdl2::surface::Surface;
use sdl2::render::Texture;
use sdl2::render::Renderer;
use sdl2::rwops::RWops;
use sdl2::version::Version;
use sdl2::get_error;

// FIXME: this should be done in rust-sdl2
pub type SdlResult<T> = Result<T, StrBuf>;

// Setup linking for all targets.
#[cfg(target_os="macos")]
mod mac {
    #[cfg(mac_framework)]
    #[link(kind="framework", name="SDL2_image")]
    extern {}

    #[cfg(not(mac_framework))]
    #[link(name="SDL2_image")]
    extern {}
}

#[cfg(target_os="win32")]
#[cfg(target_os="linux")]
#[cfg(target_os="freebsd")]
mod others {
    #[link(name="SDL2_image")]
    extern {}
}

#[allow(non_camel_case_types, dead_code)]
mod ffi;

/// InitFlags are passed to init() to control which subsystem
/// functionality to load.
bitflags!(flags InitFlag : u32 {
    static InitJpg = ffi::IMG_INIT_JPG as u32,
    static InitPng = ffi::IMG_INIT_PNG as u32,
    static InitTif = ffi::IMG_INIT_TIF as u32,
    static InitWebp = ffi::IMG_INIT_WEBP as u32
})

/// Static method extensions for creating Surfaces
pub trait LoadSurface {
    // Self is only returned here to type hint to the compiler.
    // The syntax for type hinting in this case is not yet defined.
    // The intended return value is SdlResult<~Surface>.
    fn from_file(filename: &Path) -> SdlResult<Self>;
    fn from_xpm_array(xpm: **i8) -> SdlResult<Self>;
}

/// Method extensions to Surface for saving to disk
pub trait SaveSurface {
    fn save(&self, filename: &Path) -> SdlResult<()>;
    fn save_rw(&self, dst: &mut RWops) -> SdlResult<()>;
}

impl LoadSurface for Surface {
    fn from_file(filename: &Path) -> SdlResult<Surface> {
        //! Loads an SDL Surface from a file
        unsafe {
            let raw = ffi::IMG_Load(filename.to_c_str().unwrap());
            if raw == ptr::null() {
                Err(get_error())
            } else {
                Ok(Surface { raw: raw, owned: true })
            }
        }
    }

    fn from_xpm_array(xpm: **i8) -> SdlResult<Surface> {
        //! Loads an SDL Surface from XPM data
        unsafe {
            let raw = ffi::IMG_ReadXPMFromArray(xpm as **c_char);
            if raw == ptr::null() {
                Err(get_error())
            } else {
                Ok(Surface { raw: raw, owned: true })
            }
        }
    }
}

impl SaveSurface for Surface {
    fn save(&self, filename: &Path) -> SdlResult<()> {
        //! Saves an SDL Surface to a file
        unsafe {
            let status = ffi::IMG_SavePNG(self.raw,
                                          filename.to_c_str().unwrap());
            if status != 0 {
                Err(get_error())
            } else {
                Ok(())
            }
        }
    }

    fn save_rw(&self, dst: &mut RWops) -> SdlResult<()> {
        //! Saves an SDL Surface to an RWops
        unsafe {
            let status = ffi::IMG_SavePNG_RW(self.raw, dst.raw, 0);

            if status != 0 {
                Err(get_error())
            } else {
                Ok(())
            }
        }
    }
}

/// Method extensions for creating Textures from a Renderer
pub trait LoadTexture {
    fn load_texture(&self, filename: &Path) -> SdlResult<Texture>;
}

impl<T> LoadTexture for Renderer<T> {
    fn load_texture(&self, filename: &Path) -> SdlResult<Texture> {
        //! Loads an SDL Texture from a file
        unsafe {
            let raw = ffi::IMG_LoadTexture(self.raw,
                                           filename.to_c_str().unwrap());
            if raw == ptr::null() {
                Err(get_error())
            } else {
                Ok(Texture{ raw: raw, owned: true })
            }
        }
    }
}

pub fn init(flags: InitFlag) -> InitFlag {
    //! Initializes SDL2_image with InitFlags and returns which
    //! InitFlags were actually used.
    unsafe {
        let used = ffi::IMG_Init(flags.bits() as c_int);
        InitFlag::from_bits_truncate(used as u32)
    }
}

pub fn quit() {
    //! Teardown the SDL2_Image subsystem
    unsafe { ffi::IMG_Quit(); }
}

pub fn get_linked_version() -> Version {
    //! Returns the version of the dynamically linked SDL_image library
    unsafe {
        Version::from_ll(ffi::IMG_Linked_Version())
    }
}

#[inline]
fn to_surface_result(raw: *sdl2::surface::ll::SDL_Surface) -> SdlResult<Surface> {
    if raw == ptr::null() {
        Err(get_error())
    } else {
        Ok(Surface { raw: raw, owned: true })
    }
}

pub trait ImageRWops {
    /// load as a surface. except TGA
    fn load(&self) -> SdlResult<Surface>;
    /// load as a surface. This can load all supported image formats.
    fn load_typed(&self, _type: &str) -> SdlResult<Surface>;

    fn load_cur(&self) -> SdlResult<Surface>;
    fn load_ico(&self) -> SdlResult<Surface>;
    fn load_bmp(&self) -> SdlResult<Surface>;
    fn load_pnm(&self) -> SdlResult<Surface>;
    fn load_xpm(&self) -> SdlResult<Surface>;
    fn load_xcf(&self) -> SdlResult<Surface>;
    fn load_pcx(&self) -> SdlResult<Surface>;
    fn load_gif(&self) -> SdlResult<Surface>;
    fn load_jpg(&self) -> SdlResult<Surface>;
    fn load_tif(&self) -> SdlResult<Surface>;
    fn load_png(&self) -> SdlResult<Surface>;
    fn load_tga(&self) -> SdlResult<Surface>;
    fn load_lbm(&self) -> SdlResult<Surface>;
    fn load_xv(&self)  -> SdlResult<Surface>;
    fn load_webp(&self) -> SdlResult<Surface>;

    fn is_cur(&self) -> bool;
    fn is_ico(&self) -> bool;
    fn is_bmp(&self) -> bool;
    fn is_pnm(&self) -> bool;
    fn is_xpm(&self) -> bool;
    fn is_xcf(&self) -> bool;
    fn is_pcx(&self) -> bool;
    fn is_gif(&self) -> bool;
    fn is_jpg(&self) -> bool;
    fn is_tif(&self) -> bool;
    fn is_png(&self) -> bool;
    fn is_lbm(&self) -> bool;
    fn is_xv(&self)  -> bool;
    fn is_webp(&self) -> bool;
}

impl ImageRWops for RWops {
    fn load(&self) -> SdlResult<Surface> {
        let raw = unsafe {
            ffi::IMG_Load_RW(self.raw, 0)
        };
        to_surface_result(raw)
    }
    fn load_typed(&self, _type: &str) -> SdlResult<Surface> {
        let raw = unsafe {
            ffi::IMG_LoadTyped_RW(self.raw, 0, _type.to_c_str().unwrap())
        };
        to_surface_result(raw)
    }

    fn load_cur(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadCUR_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_ico(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadICO_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_bmp(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadBMP_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_pnm(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadPNM_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_xpm(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadXPM_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_xcf(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadXCF_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_pcx(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadPCX_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_gif(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadGIF_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_jpg(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadJPG_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_tif(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadTIF_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_png(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadPNG_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_tga(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadTGA_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_lbm(&self) -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadLBM_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_xv(&self)  -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadXV_RW(self.raw) };
        to_surface_result(raw)
    }
    fn load_webp(&self)  -> SdlResult<Surface> {
        let raw = unsafe { ffi::IMG_LoadWEBP_RW(self.raw) };
        to_surface_result(raw)
    }

    fn is_cur(&self) -> bool {
        unsafe { ffi::IMG_isCUR(self.raw) == 1 }
    }
    fn is_ico(&self) -> bool {
        unsafe { ffi::IMG_isICO(self.raw) == 1 }
    }
    fn is_bmp(&self) -> bool {
        unsafe { ffi::IMG_isBMP(self.raw) == 1 }
    }
    fn is_pnm(&self) -> bool {
        unsafe { ffi::IMG_isPNM(self.raw) == 1 }
    }
    fn is_xpm(&self) -> bool {
        unsafe { ffi::IMG_isXPM(self.raw) == 1 }
    }
    fn is_xcf(&self) -> bool {
        unsafe { ffi::IMG_isXCF(self.raw) == 1 }
    }
    fn is_pcx(&self) -> bool {
        unsafe { ffi::IMG_isPCX(self.raw) == 1 }
    }
    fn is_gif(&self) -> bool {
        unsafe { ffi::IMG_isGIF(self.raw) == 1 }
    }
    fn is_jpg(&self) -> bool {
        unsafe { ffi::IMG_isJPG(self.raw) == 1 }
    }
    fn is_tif(&self) -> bool {
        unsafe { ffi::IMG_isTIF(self.raw) == 1 }
    }
    fn is_png(&self) -> bool {
        unsafe { ffi::IMG_isPNG(self.raw) == 1 }
    }
    fn is_lbm(&self) -> bool {
        unsafe { ffi::IMG_isLBM(self.raw) == 1 }
    }
    fn is_xv(&self)  -> bool {
        unsafe { ffi::IMG_isXV(self.raw)  == 1 }
    }
    fn is_webp(&self) -> bool {
        unsafe { ffi::IMG_isWEBP(self.raw)  == 1 }
    }
}
<|endoftext|>


<commit_before><commit_msg>add an initial `MutexArc` stub<commit_after><|endoftext|>


<commit_before>#![allow(non_camel_case_types)]

extern crate libc;
use libc::{uint32_t, int32_t, uint64_t, int64_t, c_uchar, size_t, c_void, c_uint};

pub type sph_u32 = uint32_t;
pub type sph_s32 = int32_t;

#[repr(C)]
#[derive(Copy)]
#[allow(non_snake_case)]
pub struct BlakeSmallContext {
    pub buf: [c_uchar; 64usize],
    pub ptr: size_t,
    pub H: [sph_u32; 8usize],
    pub S: [sph_u32; 4usize],
    pub T0: sph_u32,
    pub T1: sph_u32,
}

impl ::std::clone::Clone for BlakeSmallContext {
    fn clone(&self) -> Self { *self }
}
impl ::std::default::Default for BlakeSmallContext {
    fn default() -> Self { unsafe { ::std::mem::zeroed() } }
}

pub type sph_blake_small_context = BlakeSmallContext;
pub type sph_blake224_context = sph_blake_small_context;
pub type sph_blake256_context = sph_blake_small_context;

pub type sph_u64 = uint64_t;
pub type sph_s64 = int64_t;

#[repr(C)]
#[derive(Copy)]
#[allow(non_snake_case)]
pub struct BlakeBigContext {
    pub buf: [c_uchar; 128usize],
    pub ptr: size_t,
    pub H: [sph_u64; 8usize],
    pub S: [sph_u64; 4usize],
    pub T0: sph_u64,
    pub T1: sph_u64,
}

impl ::std::clone::Clone for BlakeBigContext {
    fn clone(&self) -> Self { *self }
}
impl ::std::default::Default for BlakeBigContext {
    fn default() -> Self { unsafe { ::std::mem::zeroed() } }
}

pub type sph_blake_big_context = BlakeBigContext;
pub type sph_blake384_context = sph_blake_big_context;
pub type sph_blake512_context = sph_blake_big_context;

// FIXME #[link(name="sphlib", kind="static")] (Issue w/ Travis CI buiding, https://travis-ci.org/Zatvobor/rust-sphlib/jobs/78903620)
extern {
    pub fn sph_blake224_init(cc: *mut c_void) -> ();
    pub fn sph_blake224(cc: *mut c_void, data: *const c_void, len: size_t) -> ();
    pub fn sph_blake224_close(cc: *mut c_void, dst: *mut c_void) -> ();
    pub fn sph_blake224_addbits_and_close(cc: *mut c_void, ub: c_uint, n: c_uint, dst: *mut c_void) -> ();

    pub fn sph_blake256_init(cc: *mut c_void) -> ();
    pub fn sph_blake256(cc: *mut c_void, data: *const c_void, len: size_t) -> ();
    pub fn sph_blake256_close(cc: *mut c_void, dst: *mut c_void) -> ();
    pub fn sph_blake256_addbits_and_close(cc: *mut c_void, ub: c_uint, n: c_uint, dst: *mut c_void) -> ();

    pub fn sph_blake384_init(cc: *mut c_void) -> ();
    pub fn sph_blake384(cc: *mut c_void, data: *const c_void, len: size_t) -> ();
    pub fn sph_blake384_close(cc: *mut c_void, dst: *mut c_void) -> ();
    pub fn sph_blake384_addbits_and_close(cc: *mut c_void, ub: c_uint, n: c_uint, dst: *mut c_void) -> ();

    pub fn sph_blake512_init(cc: *mut c_void) -> ();
    pub fn sph_blake512(cc: *mut c_void, data: *const c_void, len: size_t) -> ();
    pub fn sph_blake512_close(cc: *mut c_void, dst: *mut c_void) -> ();
    pub fn sph_blake512_addbits_and_close(cc: *mut c_void, ub: c_uint, n: c_uint, dst: *mut c_void) -> ();
}

pub fn blake224(data: &str) -> [u8;28] {
    let mut dest: [u8;28] = [0;28];
    unsafe {
        let mut cc = BlakeSmallContext::default();
        let raw_cc = &mut cc as *mut BlakeSmallContext;
        let void_raw_cc = raw_cc as *mut c_void;
        // FIXME Figure out what's wrong here `let void_raw_cc = to_void_raw_small_ctx()`;
        sph_blake224_init(void_raw_cc);

        let (void_raw_data, len) = to_void_raw_data(data);
        sph_blake224(void_raw_cc, void_raw_data, len);

        let void_raw_dest = to_void_raw_dest(&mut dest);
        sph_blake224_close(void_raw_cc, void_raw_dest);
    }
    return dest;
}

pub fn blake256(data: &str) -> [u8;32] {
    let mut dest: [u8;32] = [0;32];
    unsafe {
        let mut cc = BlakeSmallContext::default();
        let raw_cc = &mut cc as *mut BlakeSmallContext;
        let void_raw_cc = raw_cc as *mut c_void;
        // FIXME Figure out what's wrong here `let void_raw_cc = to_void_raw_small_ctx()`;
        sph_blake256_init(void_raw_cc);

        let (void_raw_data, len) = to_void_raw_data(data);
        sph_blake256(void_raw_cc, void_raw_data, len);

        let void_raw_dest = to_void_raw_dest(&mut dest);
        sph_blake256_close(void_raw_cc, void_raw_dest);
    }
    return dest;
}

pub fn blake384(data: &str) -> [u8;48] {
    let mut dest: [u8;48] = [0;48];
    unsafe {
        let mut cc = BlakeBigContext::default();
        let raw_cc = &mut cc as *mut BlakeBigContext;
        let void_raw_cc = raw_cc as *mut c_void;
        // FIXME Figure out what's wrong here `let void_raw_cc = to_void_raw_small_ctx()`;
        sph_blake384_init(void_raw_cc);

        let (void_raw_data, len) = to_void_raw_data(data);
        sph_blake384(void_raw_cc, void_raw_data, len);

        let void_raw_dest = to_void_raw_dest(&mut dest);
        sph_blake384_close(void_raw_cc, void_raw_dest);
    }
    return dest;
}

pub fn blake512(data: &str) -> [u8;64] {
    let mut dest: [u8;64] = [0;64];
    unsafe {
        let mut cc = BlakeBigContext::default();
        let raw_cc = &mut cc as *mut BlakeBigContext;
        let void_raw_cc = raw_cc as *mut c_void;
        // FIXME Figure out what's wrong here `let void_raw_cc = to_void_raw_small_ctx()`;
        sph_blake512_init(void_raw_cc);

        let (void_raw_data, len) = to_void_raw_data(data);
        sph_blake512(void_raw_cc, void_raw_data, len);

        let void_raw_dest = to_void_raw_dest(&mut dest);
        sph_blake512_close(void_raw_cc, void_raw_dest);
    }
    return dest;
}

// private

#[allow(dead_code)]
fn to_void_raw_small_ctx() -> *mut c_void {
    let mut cc = BlakeSmallContext::default();
    let raw_cc = &mut cc as *mut BlakeSmallContext;
    let void_raw_cc = raw_cc as *mut c_void;

    return void_raw_cc;
}

fn to_void_raw_data(data: &str) -> (*const c_void, size_t) {
    let void_raw_data = data.as_ptr() as *const c_void;
    let len = data.len() as size_t;

    return (void_raw_data, len);
}

fn to_void_raw_dest(dest: &mut [u8]) -> *mut c_void {
    let raw_dest = dest.as_mut() as *mut [u8];
    let void_raw_dest = raw_dest as *mut c_void;

    return void_raw_dest;
}
<commit_msg>Remove Copy trait for Contexts<commit_after>#![allow(non_camel_case_types)]

extern crate libc;
use libc::{uint32_t, int32_t, uint64_t, int64_t, c_uchar, size_t, c_void, c_uint};

pub type sph_u32 = uint32_t;
pub type sph_s32 = int32_t;

#[repr(C)]
#[allow(non_snake_case)]
pub struct BlakeSmallContext {
    pub buf: [c_uchar; 64usize],
    pub ptr: size_t,
    pub H: [sph_u32; 8usize],
    pub S: [sph_u32; 4usize],
    pub T0: sph_u32,
    pub T1: sph_u32,
}

impl ::std::default::Default for BlakeSmallContext {
    fn default() -> Self { unsafe { ::std::mem::zeroed() } }
}

pub type sph_blake_small_context = BlakeSmallContext;
pub type sph_blake224_context = sph_blake_small_context;
pub type sph_blake256_context = sph_blake_small_context;

pub type sph_u64 = uint64_t;
pub type sph_s64 = int64_t;

#[repr(C)]
#[allow(non_snake_case)]
pub struct BlakeBigContext {
    pub buf: [c_uchar; 128usize],
    pub ptr: size_t,
    pub H: [sph_u64; 8usize],
    pub S: [sph_u64; 4usize],
    pub T0: sph_u64,
    pub T1: sph_u64,
}

impl ::std::default::Default for BlakeBigContext {
    fn default() -> Self { unsafe { ::std::mem::zeroed() } }
}

pub type sph_blake_big_context = BlakeBigContext;
pub type sph_blake384_context = sph_blake_big_context;
pub type sph_blake512_context = sph_blake_big_context;

// FIXME #[link(name="sphlib", kind="static")] (Issue w/ Travis CI buiding, https://travis-ci.org/Zatvobor/rust-sphlib/jobs/78903620)
extern {
    pub fn sph_blake224_init(cc: *mut c_void) -> ();
    pub fn sph_blake224(cc: *mut c_void, data: *const c_void, len: size_t) -> ();
    pub fn sph_blake224_close(cc: *mut c_void, dst: *mut c_void) -> ();
    pub fn sph_blake224_addbits_and_close(cc: *mut c_void, ub: c_uint, n: c_uint, dst: *mut c_void) -> ();

    pub fn sph_blake256_init(cc: *mut c_void) -> ();
    pub fn sph_blake256(cc: *mut c_void, data: *const c_void, len: size_t) -> ();
    pub fn sph_blake256_close(cc: *mut c_void, dst: *mut c_void) -> ();
    pub fn sph_blake256_addbits_and_close(cc: *mut c_void, ub: c_uint, n: c_uint, dst: *mut c_void) -> ();

    pub fn sph_blake384_init(cc: *mut c_void) -> ();
    pub fn sph_blake384(cc: *mut c_void, data: *const c_void, len: size_t) -> ();
    pub fn sph_blake384_close(cc: *mut c_void, dst: *mut c_void) -> ();
    pub fn sph_blake384_addbits_and_close(cc: *mut c_void, ub: c_uint, n: c_uint, dst: *mut c_void) -> ();

    pub fn sph_blake512_init(cc: *mut c_void) -> ();
    pub fn sph_blake512(cc: *mut c_void, data: *const c_void, len: size_t) -> ();
    pub fn sph_blake512_close(cc: *mut c_void, dst: *mut c_void) -> ();
    pub fn sph_blake512_addbits_and_close(cc: *mut c_void, ub: c_uint, n: c_uint, dst: *mut c_void) -> ();
}

pub fn blake224(data: &str) -> [u8;28] {
    let mut dest: [u8;28] = [0;28];
    unsafe {
        let mut cc = BlakeSmallContext::default();
        let raw_cc = &mut cc as *mut BlakeSmallContext;
        let void_raw_cc = raw_cc as *mut c_void;
        // FIXME Figure out what's wrong here `let void_raw_cc = to_void_raw_small_ctx()`;
        sph_blake224_init(void_raw_cc);

        let (void_raw_data, len) = to_void_raw_data(data);
        sph_blake224(void_raw_cc, void_raw_data, len);

        let void_raw_dest = to_void_raw_dest(&mut dest);
        sph_blake224_close(void_raw_cc, void_raw_dest);
    }
    return dest;
}

pub fn blake256(data: &str) -> [u8;32] {
    let mut dest: [u8;32] = [0;32];
    unsafe {
        let mut cc = BlakeSmallContext::default();
        let raw_cc = &mut cc as *mut BlakeSmallContext;
        let void_raw_cc = raw_cc as *mut c_void;
        // FIXME Figure out what's wrong here `let void_raw_cc = to_void_raw_small_ctx()`;
        sph_blake256_init(void_raw_cc);

        let (void_raw_data, len) = to_void_raw_data(data);
        sph_blake256(void_raw_cc, void_raw_data, len);

        let void_raw_dest = to_void_raw_dest(&mut dest);
        sph_blake256_close(void_raw_cc, void_raw_dest);
    }
    return dest;
}

pub fn blake384(data: &str) -> [u8;48] {
    let mut dest: [u8;48] = [0;48];
    unsafe {
        let mut cc = BlakeBigContext::default();
        let raw_cc = &mut cc as *mut BlakeBigContext;
        let void_raw_cc = raw_cc as *mut c_void;
        // FIXME Figure out what's wrong here `let void_raw_cc = to_void_raw_small_ctx()`;
        sph_blake384_init(void_raw_cc);

        let (void_raw_data, len) = to_void_raw_data(data);
        sph_blake384(void_raw_cc, void_raw_data, len);

        let void_raw_dest = to_void_raw_dest(&mut dest);
        sph_blake384_close(void_raw_cc, void_raw_dest);
    }
    return dest;
}

pub fn blake512(data: &str) -> [u8;64] {
    let mut dest: [u8;64] = [0;64];
    unsafe {
        let mut cc = BlakeBigContext::default();
        let raw_cc = &mut cc as *mut BlakeBigContext;
        let void_raw_cc = raw_cc as *mut c_void;
        // FIXME Figure out what's wrong here `let void_raw_cc = to_void_raw_small_ctx()`;
        sph_blake512_init(void_raw_cc);

        let (void_raw_data, len) = to_void_raw_data(data);
        sph_blake512(void_raw_cc, void_raw_data, len);

        let void_raw_dest = to_void_raw_dest(&mut dest);
        sph_blake512_close(void_raw_cc, void_raw_dest);
    }
    return dest;
}

// private

#[allow(dead_code)]
fn to_void_raw_small_ctx() -> *mut c_void {
    let mut cc = BlakeSmallContext::default();
    let raw_cc = &mut cc as *mut BlakeSmallContext;
    let void_raw_cc = raw_cc as *mut c_void;

    return void_raw_cc;
}

fn to_void_raw_data(data: &str) -> (*const c_void, size_t) {
    let void_raw_data = data.as_ptr() as *const c_void;
    let len = data.len() as size_t;

    return (void_raw_data, len);
}

fn to_void_raw_dest(dest: &mut [u8]) -> *mut c_void {
    let raw_dest = dest.as_mut() as *mut [u8];
    let void_raw_dest = raw_dest as *mut c_void;

    return void_raw_dest;
}
<|endoftext|>


<commit_before><commit_msg>Add test for -Z panic-in-drop=abort<commit_after>// compile-flags: -Z panic-in-drop=abort -O

// Ensure that unwinding code paths are eliminated from the output after
// optimization.

#![crate_type = "lib"]
use std::any::Any;
use std::mem::forget;

pub struct ExternDrop;
impl Drop for ExternDrop {
    #[inline(always)]
    fn drop(&mut self) {
        // This call may potentially unwind.
        extern "Rust" {
            fn extern_drop();
        }
        unsafe {
            extern_drop();
        }
    }
}

struct AssertNeverDrop;
impl Drop for AssertNeverDrop {
    #[inline(always)]
    fn drop(&mut self) {
        // This call should be optimized away as unreachable.
        extern "C" {
            fn should_not_appear_in_output();
        }
        unsafe {
            should_not_appear_in_output();
        }
    }
}

// CHECK-LABEL: normal_drop
// CHECK-NOT: should_not_appear_in_output
#[no_mangle]
pub fn normal_drop(x: ExternDrop) {
    let guard = AssertNeverDrop;
    drop(x);
    forget(guard);
}

// CHECK-LABEL: indirect_drop
// CHECK-NOT: should_not_appear_in_output
#[no_mangle]
pub fn indirect_drop(x: Box<dyn Any>) {
    let guard = AssertNeverDrop;
    drop(x);
    forget(guard);
}
<|endoftext|>


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

// compile-flags: -Z parse-only

fn foo<T>() where <T>::Item: ToString, T: Iterator { }
               //~^ syntax `where<T>` is reserved for future use

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Test case for issue #758.<commit_after>// xfail-stage1
// xfail-stage2
// xfail-stage3

// Test case for issue #758.
obj foo() { fn f() { } }

fn main() {
    let my_foo = foo();
    let f = my_foo.f;
}
<|endoftext|>


<commit_before><commit_msg>Tighten up scope of first draft and add location and resourceset types<commit_after><|endoftext|>


<commit_before><commit_msg>Inline some sdl methods<commit_after><|endoftext|>


<commit_before><commit_msg>Add some functions for getting specific metadata<commit_after>use nom::{IResult, Consumer, FileProducer};
use std::io::{Error, ErrorKind, Result};

use metadata::{
  Block, BlockData,
  StreamInfo, CueSheet, VorbisComment,
  MetaDataConsumer,
};

pub fn get_metadata(filename: &str) -> Result<Vec<Block>> {
  FileProducer::new(filename, 1024).and_then(|mut producer| {
    let mut consumer = MetaDataConsumer::new();

    consumer.run(&mut producer);

    if !consumer.data.is_empty() {
      Ok(consumer.data)
    } else {
      let error_str = "parser: couldn't find any metadata";

      Err(Error::new(ErrorKind::InvalidData, error_str))
    }
  })
}

pub fn get_stream_info(filename: &str) -> Result<StreamInfo> {
  get_metadata(filename).and_then(|blocks| {
    let error_str  = "metadata: couldn't find StreamInfo";
    let mut result = Err(Error::new(ErrorKind::NotFound, error_str));

    for block in blocks {
      if let BlockData::StreamInfo(stream_info) = block.data {
        result = Ok(stream_info);
        break;
      }
    }

    result
  })
}

pub fn get_vorbis_comment(filename: &str) -> Result<VorbisComment> {
  get_metadata(filename).and_then(|blocks| {
    let error_str  = "metadata: couldn't find VorbisComment";
    let mut result = Err(Error::new(ErrorKind::NotFound, error_str));

    for block in blocks {
      if let BlockData::VorbisComment(vorbis_comment) = block.data {
        result = Ok(vorbis_comment);
        break;
      }
    }

    result
  })
}

pub fn get_cue_sheet(filename: &str) -> Result<CueSheet> {
  get_metadata(filename).and_then(|blocks| {
    let error_str  = "metadata: couldn't find CueSheet";
    let mut result = Err(Error::new(ErrorKind::NotFound, error_str));

    for block in blocks {
      if let BlockData::CueSheet(cue_sheet) = block.data {
        result = Ok(cue_sheet);
        break;
      }
    }

    result
  })
}
<|endoftext|>


<commit_before><commit_msg>Implement Into<PacketTypes> for CustomPacket<commit_after><|endoftext|>


<commit_before><commit_msg>Scaffold Output<commit_after>use crate::{Lang, Script};

// TODO:
// Find a better name?:
// * Response
// * Info
// * DetectionResult ?
pub struct Output {
    script: Script,
    lang: Lang,
}

impl Output {
    pub fn new(script: Script, lang: Lang) -> Self {
        Self { script, lang }
    }
}
<|endoftext|>


<commit_before><commit_msg>new merging spine<commit_after>//! An append-only collection of update batches.
//!
//! The `Spine` is a general-purpose trace implementation based on collection and merging
//! immutable batches of updates. It is generic with respect to the batch type, and can be
//! instantiated for any implementor of `trace::Batch`.

use std::fmt::Debug;

use ::difference::Monoid;
use lattice::Lattice;
use trace::{Batch, BatchReader, Trace, TraceReader};
// use trace::cursor::cursor_list::CursorList;
use trace::cursor::{Cursor, CursorList};
use trace::Merger;

use ::timely::dataflow::operators::generic::OperatorInfo;

/// An append-only collection of update tuples.
///
/// A spine maintains a small number of immutable collections of update tuples, merging the collections when
/// two have similar sizes. In this way, it allows the addition of more tuples, which may then be merged with
/// other immutable collections.
pub struct Spine<K, V, T: Lattice+Ord, R: Monoid, B: Batch<K, V, T, R>> {
    operator: OperatorInfo,
    logger: Option<::logging::Logger>,
    phantom: ::std::marker::PhantomData<(K, V, R)>,
    advance_frontier: Vec<T>,                   // Times after which the trace must accumulate correctly.
    through_frontier: Vec<T>,                   // Times after which the trace must be able to subset its inputs.
    merging: Vec<Option<MergeState<K,V,T,R,B>>>,// Several possibly shared collections of updates.
    pending: Vec<B>,                       // Batches at times in advance of `frontier`.
    upper: Vec<T>,
    effort: usize,
    activator: Option<timely::scheduling::activate::Activator>,
}

impl<K, V, T, R, B> TraceReader for Spine<K, V, T, R, B>
where
    K: Ord+Clone,           // Clone is required by `batch::advance_*` (in-place could remove).
    V: Ord+Clone,           // Clone is required by `batch::advance_*` (in-place could remove).
    T: Lattice+Ord+Clone+Debug+Default,
    R: Monoid,
    B: Batch<K, V, T, R>+Clone+'static,
{
    type Key = K;
    type Val = V;
    type Time = T;
    type R = R;

    type Batch = B;
    type Cursor = CursorList<K, V, T, R, <B as BatchReader<K, V, T, R>>::Cursor>;

    fn cursor_through(&mut self, upper: &[T]) -> Option<(Self::Cursor, <Self::Cursor as Cursor<K, V, T, R>>::Storage)> {

        // The supplied `upper` should have the property that for each of our
        // batch `lower` and `upper` frontiers, the supplied upper is comparable
        // to the frontier; it should not be incomparable, because the frontiers
        // that we created form a total order. If it is, there is a bug.
        //
        // We should acquire a cursor including all batches whose upper is less
        // or equal to the supplied upper, excluding all batches whose lower is
        // greater or equal to the supplied upper, and if a batch straddles the
        // supplied upper it had better be empty.

        // We shouldn't grab a cursor into a closed trace, right?
        assert!(self.advance_frontier.len() > 0);

        // Check that `upper` is greater or equal to `self.through_frontier`.
        // Otherwise, the cut could be in `self.merging` and it is user error anyhow.
        assert!(upper.iter().all(|t1| self.through_frontier.iter().any(|t2| t2.less_equal(t1))));

        let mut cursors = Vec::new();
        let mut storage = Vec::new();

        for merge_state in self.merging.iter().rev() {
            match *merge_state {
                Some(MergeState::Merging(ref batch1, ref batch2, _, _)) => {
                    if !batch1.is_empty() {
                        cursors.push(batch1.cursor());
                        storage.push(batch1.clone());
                    }
                    if !batch2.is_empty() {
                        cursors.push(batch2.cursor());
                        storage.push(batch2.clone());
                    }
                },
                Some(MergeState::Complete(ref batch)) => {
                    if !batch.is_empty() {
                        cursors.push(batch.cursor());
                        storage.push(batch.clone());
                    }
                },
                None => { }
            }
        }

        for batch in self.pending.iter() {

            if !batch.is_empty() {

                // For a non-empty `batch`, it is a catastrophic error if `upper`
                // requires some-but-not-all of the updates in the batch. We can
                // determine this from `upper` and the lower and upper bounds of
                // the batch itself.
                //
                // TODO: It is not clear if this is the 100% correct logic, due
                // to the possible non-total-orderedness of the frontiers.

                let include_lower = upper.iter().all(|t1| batch.lower().iter().any(|t2| t2.less_equal(t1)));
                let include_upper = upper.iter().all(|t1| batch.upper().iter().any(|t2| t2.less_equal(t1)));

                if include_lower != include_upper && upper != batch.lower() {
                    panic!("`cursor_through`: `upper` straddles batch");
                }

                // include pending batches
                if include_upper {
                    cursors.push(batch.cursor());
                    storage.push(batch.clone());
                }
            }
        }

        Some((CursorList::new(cursors, &storage), storage))
    }
    fn advance_by(&mut self, frontier: &[T]) {
        self.advance_frontier = frontier.to_vec();
        if self.advance_frontier.len() == 0 {
            self.pending.clear();
            self.merging.clear();
        }
    }
    fn advance_frontier(&mut self) -> &[T] { &self.advance_frontier[..] }
    fn distinguish_since(&mut self, frontier: &[T]) {
        self.through_frontier = frontier.to_vec();
        self.consider_merges();
    }
    fn distinguish_frontier(&mut self) -> &[T] { &self.through_frontier[..] }

    fn map_batches<F: FnMut(&Self::Batch)>(&mut self, mut f: F) {
        for batch in self.merging.iter().rev() {
            match *batch {
                Some(MergeState::Merging(ref batch1, ref batch2, _, _)) => { f(batch1); f(batch2); },
                Some(MergeState::Complete(ref batch)) => { f(batch); },
                None => { },
            }
        }
        for batch in self.pending.iter() {
            f(batch);
        }
    }
}

// A trace implementation for any key type that can be borrowed from or converted into `Key`.
// TODO: Almost all this implementation seems to be generic with respect to the trace and batch types.
impl<K, V, T, R, B> Trace for Spine<K, V, T, R, B>
where
    K: Ord+Clone,
    V: Ord+Clone,
    T: Lattice+Ord+Clone+Debug+Default,
    R: Monoid,
    B: Batch<K, V, T, R>+Clone+'static,
{

    fn new(
        info: ::timely::dataflow::operators::generic::OperatorInfo,
        logging: Option<::logging::Logger>,
        activator: Option<timely::scheduling::activate::Activator>,
    ) -> Self {
        Self::with_effort(4, info, logging, activator)
    }

    fn exert(&mut self, batch_size: usize, batch_index: usize) {
        self.work_for(batch_size, batch_index);
    }

    // Ideally, this method acts as insertion of `batch`, even if we are not yet able to begin
    // merging the batch. This means it is a good time to perform amortized work proportional
    // to the size of batch.
    fn insert(&mut self, batch: Self::Batch) {

        self.logger.as_ref().map(|l| l.log(::logging::BatchEvent {
            operator: self.operator.global_id,
            length: batch.len()
        }));

        assert!(batch.lower() != batch.upper());
        assert_eq!(batch.lower(), &self.upper[..]);

        self.upper = batch.upper().to_vec();

        // TODO: Consolidate or discard empty batches.
        self.pending.push(batch);
        self.consider_merges();
    }

    fn close(&mut self) {
        if !self.upper.is_empty() {
            use trace::Builder;
            let builder = B::Builder::new();
            let batch = builder.done(&self.upper[..], &[], &self.upper[..]);
            self.insert(batch);
        }
    }
}

impl<K, V, T, R, B> Spine<K, V, T, R, B>
where
    K: Ord+Clone,
    V: Ord+Clone,
    T: Lattice+Ord+Clone+Debug+Default,
    R: Monoid,
    B: Batch<K, V, T, R>,
{
    /// Allocates a fueled `Spine` with a specified effort multiplier.
    ///
    /// This trace will merge batches progressively, with each inserted batch applying a multiple
    /// of the batch's length in effort to each merge. The `effort` parameter is that multiplier.
    /// This value should be at least one for the merging to happen; a value of zero is not helpful.
    pub fn with_effort(
        mut effort: usize,
        operator: OperatorInfo,
        logger: Option<::logging::Logger>,
        activator: Option<timely::scheduling::activate::Activator>,
    ) -> Self {

        // Zero effort is .. not smart.
        if effort == 0 { effort = 1; }

        Spine {
            operator,
            logger,
            phantom: ::std::marker::PhantomData,
            advance_frontier: vec![<T as Lattice>::minimum()],
            through_frontier: vec![<T as Lattice>::minimum()],
            merging: Vec::new(),
            pending: Vec::new(),
            upper: vec![Default::default()],
            effort,
            activator,
        }
    }

    // Migrate data from `self.pending` into `self.merging`.
    #[inline(never)]
    fn consider_merges(&mut self) {

        while self.pending.len() > 0 &&
              self.through_frontier.iter().all(|t1| self.pending[0].upper().iter().any(|t2| t2.less_equal(t1)))
        {
            // this could be a VecDeque, if we ever notice this.
            let batch = self.pending.remove(0);

            self.introduce_batch(batch, batch.len().next_power_of_two());

            // Having performed all of our work, if more than one batch remains reschedule ourself.
            if self.merging.len() > 2 && self.merging[..self.merging.len()-1].iter().any(|b| b.present()) {
                self.activator.activate();
            }
        }
    }

    /// Introduces a batch at an indicated level.
    ///
    /// The level indication is often related to the size of the batch, but
    /// it can also be used to artificially fuel the computation by supplying
    /// empty batches at non-trivial indices, to move merges along.
    pub fn introduce_batch(&mut self, batch: B, batch_index: usize) {

        // This spine is represented as a list of layers, where each element in the list is either
        //
        //   1. MergeState::Empty   empty
        //   2. MergeState::Single  a single batch
        //   3. MergeState::Double  : a pair of batches
        //
        // Each of the batches at layer i contains at most 2^i elements. The sequence of batches
        // should have the upper bound of one match the lower bound of the next. Batches may be
        // logically empty, with matching upper and lower bounds, as a bookkeeping mechanism.
        //
        // We attempt to maintain the invariant that no two adjacent levels have pairs of batches.
        // This invariant exists to make sure we have the breathing room to initiate but not
        // immediately complete merges. As soon as a layer contains two batches we initiate a merge
        // into a batch of the next sized layer, and we start to apply fuel to this merge. When it
        // completes, we install the newly merged batch in the next layer and uninstall the two
        // batches from their layer.
        //
        // We a merge completes, it vacates an entire level. Assuming we have maintained our invariant,
        // the number of updates below that level (say "k") is at most
        //
        //         2^k-1 + 2*2^k-2 + 2^k-3 + 2*2^k-4 + ...
        //      <=
        //         2^k+1 - 2^k-1
        //
        // Fortunately, the now empty layer k needs 2^k+1 updates before it will initiate a new merge,
        // and the collection must accept 2^k-1 updates before such a merge could possibly be initiated.
        // This means that if each introduced merge applies a proportionate amount of fuel to the merge,
        // we should be able to complete any merge at the next level before a new one is proposed.
        //
        // I believe most of this reasoning holds under the properties of the invariant that no adjacent
        // layers have two batches. This gives us the ability to do further housekeeping, especially as
        // we work with the largest layers, which we might expect not to grow in size. If at any point we
        // can tidy the largest layer downward without violating the invariant (e.g. draw it down to an
        // empty layer, or to a singleton layer and commence a merge) we should consider that in the
        // interests of maintaining a compact representation that does not grow without bounds.

        // Step 2. Apply fuel to each in-progress merge.
        //
        //         Ideally we apply fuel to the merges of the smallest
        //         layers first, as progress on these layers is important,
        //         and the sooner it happens the sooner we have fewer layers
        //         for cursors to navigate, which improves read performance.
        //
        //          It is important that by the end of this, we have ensured
        //          that position `batch_index+1` has at most a single batch,
        //          as our roll-up strategy will insert into that position.
        self.apply_fuel(self.effort << batch_index);

        // Step 1. Before installing the batch we must ensure the invariant,
        //         that no adjacent layers contain two batches. We can make
        //         this happen by forcibly completing all lower merges and
        //         integrating them with the batch itself, which can go at
        //         level index+1 as a single batch.
        //
        //         Note that this corresponds to the introduction of some
        //         volume of fake updates, and we will need to fuel merges
        //         by a proportional amount to ensure that they are not
        //         surprised later on.
        self.roll_up(batch_index);

        // Step 4. This insertion should be into an empty layer. It is a
        //         logical error otherwise, as we may be violating our
        //         invariant, from which all derives.
        self.insert_at(batch, batch_index);

        // Step 3. Tidy the largest layers.
        //
        //         It is important that we not tidy only smaller layers,
        //         as their ascension is what ensures the merging and
        //         eventual compaction of the largest layers.
        self.tidy_layers();
    }

    /// Ensures that layers up through and including `index` are empty.
    ///
    /// This method is used to prepare for the insertion of a single batch
    /// at `index`, which should maintain the invariant.
    fn roll_up(&mut self, index: usize) {

        let merge =
        self.merging[.. index+1]
            .iter_mut()
            .fold(None, |merge, level|
                match (merge, level.complete()) {
                    (Some(batch_new), Some(batch_old)) => {
                        Some(MergeState::begin_merge(batch_old, batch_new, None).complete())
                    },
                    (None, batch) => batch,
                    (merge, None) => merge,
                }
            );

        if let Some(batch) = merge {
            self.insert_at(batch, index + 1);
        }
    }

    /// Applies an amount of fuel to merges in progress.
    pub fn apply_fuel(mut fuel: usize) {

        // Scale fuel up by number of in-progress merges, or by the length of the spine.
        // We just need to make sure that the issued fuel is applied to each in-progress
        // merge, by the time its layer is needed to accept a new merge.

        fuel *= self.merging.len();
        for index in 0 .. self.merging.len() {
            if let Some(batch) = self.merging.work(&mut fuel) {
                self.insert_at(batch, index+1);
            }
        }
    }

    /// Inserts a batch at a specific location.
    ///
    /// This is a non-public internal method that can panic if we try and insert into a
    /// layer which already contains two batches (and is in the process of merging).
    fn insert_at(&mut self, batch: B, index: usize) {
        while self.merging.len() <= index {
            self.merging.push(MergeState::Empty);
        }
        let frontier = if index == self.merging.len()-1 { Some(self.advance_frontier.clone()) } else { None };
        self.merging[index].insert(batch, frontier);
    }

    /// Attempts to draw down large layers to size appropriate layers.
    fn tidy_layers(&mut self) {

        // If the largest layer is complete (not merging), we can attempt
        // to draw it down to the next layer if either that layer is empty,
        // or if it is a singleton and the layer below it is not merging.
        // We expect this should happen at various points if we have enough
        // fuel rolling around.

        let done = false;
        while !done {

        }

    }

}

/// Describes the state of a layer.
///
/// A layer can be empty, contain a single batch, or contain a pair of batches that are in the process
/// of merging into a batch for the next layer.
enum MergeState<K, V, T, R, B: Batch<K, V, T, R>> {
    /// An empty layer, containing no updates.
    Empty,
    /// A layer containing a single batch.
    Single(B),
    /// A layer containing two batch, in the process of merging.
    Double(B, B, Option<Vec<T>>, <B as Batch<K,V,T,R>>::Merger),
}

impl<K, V, T: Eq, R, B: Batch<K, V, T, R>> MergeState<K, V, T, R, B> {

    /// Immediately complete any merge.
    ///
    /// This consumes the layer, though we should probably consider returning the resources of the
    /// underlying source batches if we can manage that.
    fn complete(&mut self) -> Option<B>  {
        match std::mem::replace(self, MergeState::Empty) {
            Empty => None,
            Single(batch) => Some(batch),
            Double(b1, b2, frontier, merge) => {
                let mut fuel = usize::max_value();
                in_progress.work(source1, source2, frontier, &mut fuel);
                assert!(fuel > 0);
                let finished = finished.done();
                // logger.as_ref().map(|l|
                //     l.log(::logging::MergeEvent {
                //         operator,
                //         scale,
                //         length1: b1.len(),
                //         length2: b2.len(),
                //         complete: Some(finished.len()),
                //     })
                // );
                Some(finished)
            },
        }
    }

    fn work(&mut self, fuel: &mut usize) -> Option<B> {
        match std::mem::replace(self, MergeState::Empty) {
            MergeState::Double(b1, b2, frontier, merge) => {
                merge.work(b1, b2, frontier, fuel);
                if fuel > 0 {
                    let finished = finished.done();
                    // logger.as_ref().map(|l|
                    //     l.log(::logging::MergeEvent {
                    //         operator,
                    //         scale,
                    //         length1: b1.len(),
                    //         length2: b2.len(),
                    //         complete: Some(finished.len()),
                    //     })
                    // );
                    Some(finished)
                }
            }
            _ => None,
        }
    }

    /// Extract the merge state, often temporarily.
    fn take(&mut self) -> MergeState {
        std::mem::replace(self, MergeState::Empty)
    }

    /// Inserts a batch and begins a merge if needed.
    fn insert(&mut self, batch: B, frontier: Option<Vec<T>>) {
        match self.take() {
            Empty => { *self = MergeState::Single(batch); },
            Single(batch_old) => {
                *self = MergeState::begin_merge(batch_old, batch, frontier);
            }
            Double(_,_,_,_) => {
                panic!("Attempted to insert batch into incomplete merge!");
            }
        };
    }

    fn is_complete(&self) -> bool {
        match *self {
            MergeState::Complete(_) => true,
            _ => false,
        }
    }
    fn begin_merge(batch1: B, batch2: B, frontier: Option<Vec<T>>) -> Self {
        // logger.as_ref().map(|l| l.log(
        //     ::logging::MergeEvent {
        //         operator,
        //         scale,
        //         length1: batch1.len(),
        //         length2: batch2.len(),
        //         complete: None,
        //     }
        // ));
        assert!(batch1.upper() == batch2.lower());
        let begin_merge = <B as Batch<K, V, T, R>>::begin_merge(&batch1, &batch2);
        MergeState::Merging(batch1, batch2, frontier, begin_merge)
    }
    fn work(mut self, fuel: &mut usize) -> Self {
        if let MergeState::Merging(ref source1, ref source2, ref frontier, ref mut in_progress) = self {
            in_progress.work(source1, source2, frontier, fuel);
        }
        if *fuel > 0 {
            match self {
                // ALLOC: Here is where we may de-allocate batches.
                MergeState::Merging(b1, b2, _, finished) => {
                    let finished = finished.done();
                    // logger.as_ref().map(|l|
                    //     l.log(::logging::MergeEvent {
                    //         operator,
                    //         scale,
                    //         length1: b1.len(),
                    //         length2: b2.len(),
                    //         complete: Some(finished.len()),
                    //     })
                    // );
                    MergeState::Complete(finished)
                },
                MergeState::Complete(x) => MergeState::Complete(x),
            }
        }
        else { self }
    }
    fn len(&self) -> usize {
        match *self {
            MergeState::Merging(ref batch1, ref batch2, _, _) => batch1.len() + batch2.len(),
            MergeState::Complete(ref batch) => batch.len(),
        }
    }
}<|endoftext|>


<commit_before><commit_msg>Add mixed ops.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix event types in get_context<commit_after><|endoftext|>