<commit_before>// Copyright 2012-2014 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.

use hair::cx::Cx;
use rustc::middle::region::CodeExtent;
use rustc::middle::ty::{FnOutput, Ty};
use rustc::mir::repr::*;
use rustc_data_structures::fnv::FnvHashMap;
use rustc_front::hir;

use syntax::ast;
use syntax::codemap::Span;

pub struct Builder<'a, 'tcx: 'a> {
    hir: Cx<'a, 'tcx>,
    cfg: CFG<'tcx>,
    scopes: Vec<scope::Scope<'tcx>>,
    loop_scopes: Vec<scope::LoopScope>,
    unit_temp: Lvalue<'tcx>,
    var_decls: Vec<VarDecl<'tcx>>,
    var_indices: FnvHashMap<ast::NodeId, u32>,
    temp_decls: Vec<TempDecl<'tcx>>,
}

struct CFG<'tcx> {
    basic_blocks: Vec<BasicBlockData<'tcx>>,
}

///////////////////////////////////////////////////////////////////////////
// The `BlockAnd` "monad" packages up the new basic block along with a
// produced value (sometimes just unit, of course). The `unpack!`
// macro (and methods below) makes working with `BlockAnd` much more
// convenient.

#[must_use] // if you don't use one of these results, you're leaving a dangling edge
pub struct BlockAnd<T>(BasicBlock, T);

trait BlockAndExtension {
    fn and<T>(self, v: T) -> BlockAnd<T>;
    fn unit(self) -> BlockAnd<()>;
}

impl BlockAndExtension for BasicBlock {
    fn and<T>(self, v: T) -> BlockAnd<T> {
        BlockAnd(self, v)
    }

    fn unit(self) -> BlockAnd<()> {
        BlockAnd(self, ())
    }
}

/// Update a block pointer and return the value.
/// Use it like `let x = unpack!(block = self.foo(block, foo))`.
macro_rules! unpack {
    ($x:ident = $c:expr) => {
        {
            let BlockAnd(b, v) = $c;
            $x = b;
            v
        }
    };

    ($c:expr) => {
        {
            let BlockAnd(b, ()) = $c;
            b
        }
    };
}

///////////////////////////////////////////////////////////////////////////
// construct() -- the main entry point for building MIR for a function

pub fn construct<'a,'tcx>(mut hir: Cx<'a,'tcx>,
                          _span: Span,
                          implicit_arguments: Vec<Ty<'tcx>>,
                          explicit_arguments: Vec<(Ty<'tcx>, &'tcx hir::Pat)>,
                          argument_extent: CodeExtent,
                          return_ty: FnOutput<'tcx>,
                          ast_block: &'tcx hir::Block)
                          -> Mir<'tcx> {
    let cfg = CFG { basic_blocks: vec![] };

    // it's handy to have a temporary of type `()` sometimes, so make
    // one from the start and keep it available
    let temp_decls = vec![TempDecl::<'tcx> { ty: hir.unit_ty() }];
    let unit_temp = Lvalue::Temp(0);

    let mut builder = Builder {
        hir: hir,
        cfg: cfg,
        scopes: vec![],
        loop_scopes: vec![],
        temp_decls: temp_decls,
        var_decls: vec![],
        var_indices: FnvHashMap(),
        unit_temp: unit_temp,
    };

    assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
    assert_eq!(builder.cfg.start_new_block(), END_BLOCK);
    assert_eq!(builder.cfg.start_new_block(), DIVERGE_BLOCK);

    let mut block = START_BLOCK;
    let arg_decls = unpack!(block = builder.args_and_body(block,
                                                          implicit_arguments,
                                                          explicit_arguments,
                                                          argument_extent,
                                                          ast_block));

    builder.cfg.terminate(block, Terminator::Goto { target: END_BLOCK });
    builder.cfg.terminate(END_BLOCK, Terminator::Return);

    Mir {
        basic_blocks: builder.cfg.basic_blocks,
        var_decls: builder.var_decls,
        arg_decls: arg_decls,
        temp_decls: builder.temp_decls,
        return_ty: return_ty,
    }
}

impl<'a,'tcx> Builder<'a,'tcx> {
    fn args_and_body(&mut self,
                     mut block: BasicBlock,
                     implicit_arguments: Vec<Ty<'tcx>>,
                     explicit_arguments: Vec<(Ty<'tcx>, &'tcx hir::Pat)>,
                     argument_extent: CodeExtent,
                     ast_block: &'tcx hir::Block)
                     -> BlockAnd<Vec<ArgDecl<'tcx>>>
    {
        self.in_scope(argument_extent, block, |this| {
            let arg_decls = {
                let implicit_arg_decls = implicit_arguments.into_iter()
                                                           .map(|ty| ArgDecl { ty: ty });

                // to start, translate the argument patterns and collect the
                // argument types.
                let explicit_arg_decls =
                    explicit_arguments
                    .into_iter()
                    .enumerate()
                    .map(|(index, (ty, pattern))| {
                        let lvalue = Lvalue::Arg(index as u32);
                        let pattern = this.hir.irrefutable_pat(pattern);
                        unpack!(block = this.lvalue_into_pattern(block,
                                                                 argument_extent,
                                                                 pattern,
                                                                 &lvalue));
                        ArgDecl { ty: ty }
                    });

                implicit_arg_decls.chain(explicit_arg_decls).collect()
            };

            // start the first basic block and translate the body
            unpack!(block = this.ast_block(&Lvalue::ReturnPointer, block, ast_block));

            block.and(arg_decls)
        })
    }
}

///////////////////////////////////////////////////////////////////////////
// Builder methods are broken up into modules, depending on what kind
// of thing is being translated. Note that they use the `unpack` macro
// above extensively.

mod block;
mod cfg;
mod expr;
mod into;
mod matches;
mod misc;
mod scope;
mod stmt;
<commit_msg>Rollup merge of #30630 - tsion:mir-closure-args, r=nagisa<commit_after>// Copyright 2012-2014 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.

use hair::cx::Cx;
use rustc::middle::region::CodeExtent;
use rustc::middle::ty::{FnOutput, Ty};
use rustc::mir::repr::*;
use rustc_data_structures::fnv::FnvHashMap;
use rustc_front::hir;

use syntax::ast;
use syntax::codemap::Span;

pub struct Builder<'a, 'tcx: 'a> {
    hir: Cx<'a, 'tcx>,
    cfg: CFG<'tcx>,
    scopes: Vec<scope::Scope<'tcx>>,
    loop_scopes: Vec<scope::LoopScope>,
    unit_temp: Lvalue<'tcx>,
    var_decls: Vec<VarDecl<'tcx>>,
    var_indices: FnvHashMap<ast::NodeId, u32>,
    temp_decls: Vec<TempDecl<'tcx>>,
}

struct CFG<'tcx> {
    basic_blocks: Vec<BasicBlockData<'tcx>>,
}

///////////////////////////////////////////////////////////////////////////
// The `BlockAnd` "monad" packages up the new basic block along with a
// produced value (sometimes just unit, of course). The `unpack!`
// macro (and methods below) makes working with `BlockAnd` much more
// convenient.

#[must_use] // if you don't use one of these results, you're leaving a dangling edge
pub struct BlockAnd<T>(BasicBlock, T);

trait BlockAndExtension {
    fn and<T>(self, v: T) -> BlockAnd<T>;
    fn unit(self) -> BlockAnd<()>;
}

impl BlockAndExtension for BasicBlock {
    fn and<T>(self, v: T) -> BlockAnd<T> {
        BlockAnd(self, v)
    }

    fn unit(self) -> BlockAnd<()> {
        BlockAnd(self, ())
    }
}

/// Update a block pointer and return the value.
/// Use it like `let x = unpack!(block = self.foo(block, foo))`.
macro_rules! unpack {
    ($x:ident = $c:expr) => {
        {
            let BlockAnd(b, v) = $c;
            $x = b;
            v
        }
    };

    ($c:expr) => {
        {
            let BlockAnd(b, ()) = $c;
            b
        }
    };
}

///////////////////////////////////////////////////////////////////////////
// construct() -- the main entry point for building MIR for a function

pub fn construct<'a,'tcx>(mut hir: Cx<'a,'tcx>,
                          _span: Span,
                          implicit_arguments: Vec<Ty<'tcx>>,
                          explicit_arguments: Vec<(Ty<'tcx>, &'tcx hir::Pat)>,
                          argument_extent: CodeExtent,
                          return_ty: FnOutput<'tcx>,
                          ast_block: &'tcx hir::Block)
                          -> Mir<'tcx> {
    let cfg = CFG { basic_blocks: vec![] };

    // it's handy to have a temporary of type `()` sometimes, so make
    // one from the start and keep it available
    let temp_decls = vec![TempDecl::<'tcx> { ty: hir.unit_ty() }];
    let unit_temp = Lvalue::Temp(0);

    let mut builder = Builder {
        hir: hir,
        cfg: cfg,
        scopes: vec![],
        loop_scopes: vec![],
        temp_decls: temp_decls,
        var_decls: vec![],
        var_indices: FnvHashMap(),
        unit_temp: unit_temp,
    };

    assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
    assert_eq!(builder.cfg.start_new_block(), END_BLOCK);
    assert_eq!(builder.cfg.start_new_block(), DIVERGE_BLOCK);

    let mut block = START_BLOCK;
    let arg_decls = unpack!(block = builder.args_and_body(block,
                                                          implicit_arguments,
                                                          explicit_arguments,
                                                          argument_extent,
                                                          ast_block));

    builder.cfg.terminate(block, Terminator::Goto { target: END_BLOCK });
    builder.cfg.terminate(END_BLOCK, Terminator::Return);

    Mir {
        basic_blocks: builder.cfg.basic_blocks,
        var_decls: builder.var_decls,
        arg_decls: arg_decls,
        temp_decls: builder.temp_decls,
        return_ty: return_ty,
    }
}

impl<'a,'tcx> Builder<'a,'tcx> {
    fn args_and_body(&mut self,
                     mut block: BasicBlock,
                     implicit_arguments: Vec<Ty<'tcx>>,
                     explicit_arguments: Vec<(Ty<'tcx>, &'tcx hir::Pat)>,
                     argument_extent: CodeExtent,
                     ast_block: &'tcx hir::Block)
                     -> BlockAnd<Vec<ArgDecl<'tcx>>>
    {
        self.in_scope(argument_extent, block, |this| {
            // to start, translate the argument patterns and collect the argument types.
            let implicits = implicit_arguments.into_iter().map(|ty| (ty, None));
            let explicits = explicit_arguments.into_iter().map(|(ty, pat)| (ty, Some(pat)));
            let arg_decls =
                implicits
                .chain(explicits)
                .enumerate()
                .map(|(index, (ty, pattern))| {
                    if let Some(pattern) = pattern {
                        let lvalue = Lvalue::Arg(index as u32);
                        let pattern = this.hir.irrefutable_pat(pattern);
                        unpack!(block = this.lvalue_into_pattern(block,
                                                                 argument_extent,
                                                                 pattern,
                                                                 &lvalue));
                    }
                    ArgDecl { ty: ty }
                })
                .collect();

            // start the first basic block and translate the body
            unpack!(block = this.ast_block(&Lvalue::ReturnPointer, block, ast_block));

            block.and(arg_decls)
        })
    }
}

///////////////////////////////////////////////////////////////////////////
// Builder methods are broken up into modules, depending on what kind
// of thing is being translated. Note that they use the `unpack` macro
// above extensively.

mod block;
mod cfg;
mod expr;
mod into;
mod matches;
mod misc;
mod scope;
mod stmt;
<|endoftext|>


<commit_before>use request::Request;
use response::Response;
use nickel_error::NickelError;
pub use self::Action::{Continue, Halt};

pub type MiddlewareResult = Result<Action, NickelError>;

#[deriving(PartialEq)]
pub enum Action {
  Continue,
  Halt
}

// the usage of + Send is weird here because what we really want is + Static
// but that's not possible as of today. We have to use + Send for now.
pub trait Middleware: Send + Sync {
    fn invoke<'a, 'b>(&'a self, _req: &mut Request<'b, 'a>, _res: &mut Response) -> MiddlewareResult {
        Ok(Continue)
    }
}

pub trait ErrorHandler: Send + Sync {
    fn invoke(&self, _err: &NickelError, _req: &mut Request, _res: &mut Response) -> MiddlewareResult {
        Ok(Continue)
    }
}

impl ErrorHandler for fn(&NickelError, &Request, &mut Response) -> MiddlewareResult {
    fn invoke(&self, err: &NickelError, req: &mut Request, res: &mut Response) -> MiddlewareResult {
        (*self)(err, req, res)
    }
}

pub struct MiddlewareStack {
    handlers: Vec<Box<Middleware + Send + Sync>>,
    error_handlers: Vec<Box<ErrorHandler + Send + Sync>>
}

impl MiddlewareStack {
    pub fn add_middleware<T: Middleware> (&mut self, handler: T) {
        self.handlers.push(box handler);
    }

    pub fn add_error_handler<T: ErrorHandler> (&mut self, handler: T) {
        self.error_handlers.push(box handler);
    }

    pub fn invoke<'a, 'b>(&'a self, req: &mut Request<'b, 'a>, res: &mut Response) {
        for handler in self.handlers.iter() {
            match handler.invoke(req, res) {
                Ok(Halt) => {
                    debug!("{} {} {} {}", req.origin.method, req.origin.remote_addr, req.origin.request_uri, res.origin.status);
                    return
                }
                Ok(Continue) => {},
                Err(mut err) => {
                    warn!("{} {} {} {}", req.origin.method, req.origin.remote_addr, req.origin.request_uri, err.kind);
                    for error_handler in self.error_handlers.iter().rev() {
                        match error_handler.invoke(&err, req, res) {
                            Ok(Continue) => {},
                            Ok(Halt) => return,
                            // change the error so that other ErrorHandler
                            // down the stack receive the new error.
                            Err(new_err) => err = new_err,
                        }
                    }
                }
            }
        }
    }

    pub fn new () -> MiddlewareStack {
        MiddlewareStack{
            handlers: Vec::new(),
            error_handlers: Vec::new()
        }
    }
}
<commit_msg>refactor(errorhandler): generic return type for blanket impl<commit_after>use request::Request;
use response::Response;
use nickel_error::NickelError;
use middleware_handler::ResponseFinalizer;
pub use self::Action::{Continue, Halt};

pub type MiddlewareResult = Result<Action, NickelError>;

#[deriving(PartialEq)]
pub enum Action {
  Continue,
  Halt
}

// the usage of + Send is weird here because what we really want is + Static
// but that's not possible as of today. We have to use + Send for now.
pub trait Middleware: Send + Sync {
    fn invoke<'a, 'b>(&'a self, _req: &mut Request<'b, 'a>, _res: &mut Response) -> MiddlewareResult {
        Ok(Continue)
    }
}

pub trait ErrorHandler: Send + Sync {
    fn invoke(&self, _err: &NickelError, _req: &mut Request, _res: &mut Response) -> MiddlewareResult {
        Ok(Continue)
    }
}

impl<R> ErrorHandler for fn(&NickelError, &Request, &mut Response) -> R
        where R: ResponseFinalizer {
    fn invoke(&self, err: &NickelError, req: &mut Request, res: &mut Response) -> MiddlewareResult {
        let r = (*self)(err, req, res);
        r.respond(res)
    }
}

pub struct MiddlewareStack {
    handlers: Vec<Box<Middleware + Send + Sync>>,
    error_handlers: Vec<Box<ErrorHandler + Send + Sync>>
}

impl MiddlewareStack {
    pub fn add_middleware<T: Middleware> (&mut self, handler: T) {
        self.handlers.push(box handler);
    }

    pub fn add_error_handler<T: ErrorHandler> (&mut self, handler: T) {
        self.error_handlers.push(box handler);
    }

    pub fn invoke<'a, 'b>(&'a self, req: &mut Request<'b, 'a>, res: &mut Response) {
        for handler in self.handlers.iter() {
            match handler.invoke(req, res) {
                Ok(Halt) => {
                    debug!("{} {} {} {}", req.origin.method, req.origin.remote_addr, req.origin.request_uri, res.origin.status);
                    return
                }
                Ok(Continue) => {},
                Err(mut err) => {
                    warn!("{} {} {} {}", req.origin.method, req.origin.remote_addr, req.origin.request_uri, err.kind);
                    for error_handler in self.error_handlers.iter().rev() {
                        match error_handler.invoke(&err, req, res) {
                            Ok(Continue) => {},
                            Ok(Halt) => return,
                            // change the error so that other ErrorHandler
                            // down the stack receive the new error.
                            Err(new_err) => err = new_err,
                        }
                    }
                }
            }
        }
    }

    pub fn new () -> MiddlewareStack {
        MiddlewareStack{
            handlers: Vec::new(),
            error_handlers: Vec::new()
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>more multiprobe progress<commit_after>use std::cmp::Ordering;

fn bucket_distance(fi: f64, hi: f64, delta: i32, W: f64) -> f64 {
    if delta == -1 {
        W*(fi - hi)
    } else if delta == 1 {
        W - W*(fi - hi)
    } else {
        0 as f64
    }
}
fn compute_sorted_i_delta<T>(q: &[T], f_sig: &[f64], h_sig: &[f64], W: f64) -> Vec<(usize, i32)> {
    let mut intermediate_vec: Vec<((usize,i32), f64)> = f_sig.iter().zip(h_sig.iter()).enumerate().flat_map(|(i, (fi, hi))| {
        vec![((i, 1), bucket_distance(*fi, *hi, 1, W)),
         ((i, -1), bucket_distance(*fi, *hi, -1, W))].into_iter()
    }).collect();
    intermediate_vec.sort_by(|a, b| {
        if a.1 > b.1 {
            Ordering::Greater
        } else if a.1 < b.1 {
            Ordering::Less
        } else {
            Ordering::Equal
        }
    });
    intermediate_vec.iter().map(|a| {a.0}).collect()
}
#[test]
fn sorted_delta_test() {
    let test_q = vec![1.0,2.0,3.0,4.0,5.0];
    let f_sig = vec![1.5,1.2,2.2];
    let h_sig = vec![1.0,1.0,2.0];
    let W = 10.0;
    compute_sorted_i_delta(&test_q, &f_sig, &h_sig, W);
}
fn score_set(perturbation_set: &[usize], square_zj_list: &[f64]) -> f64 {
    perturbation_set.iter().map(|ind| {square_zj_list[*ind]}).sum()
}

#[derive(PartialEq)]
struct PerturbationSet<'a> {
    data: Vec<usize>,
    zj_list: &'a Vec<f64>
}

impl<'a> Eq for PerturbationSet<'a> {}

impl<'a> Ord for PerturbationSet<'a> {
    fn cmp(&self, other: &PerturbationSet) -> Ordering {
        let self_score = score_set(&(self.data), self.zj_list);
        let other_score = score_set(&(other.data), other.zj_list);
        if (self_score - other_score) <= 1e-6 {
            Ordering::Equal
        } else if self_score > other_score {
            Ordering::Greater
        } else {
            Ordering::Less
        }
    }
}

impl<'a> PartialOrd for PerturbationSet<'a> {
    fn partial_cmp(&self, other: &PerturbationSet) -> Option<Ordering> {
        let self_score = score_set(&(self.data), self.zj_list);
        let other_score = score_set(&(other.data), other.zj_list);
        self_score.partial_cmp(&other_score)
    }
}
impl<'a> PerturbationSet<'a> {
    fn shift(&self) -> PerturbationSet {
        let mut new_data = Vec::new();
        let max_val = self.data.iter().max().unwrap();
        for x in self.data.iter() {
            if *x == *max_val {
                new_data.push(*x+1);
            } else {
                new_data.push(*x);
            }
        }
        PerturbationSet {
            data: new_data,
            zj_list: self.zj_list
        }
    }
    fn expand(&self) -> PerturbationSet {
        let mut new_data = Vec::new();
        let max_val = self.data.iter().max().unwrap();
        for x in self.data.iter() {
            new_data.push(*x);
        }
        new_data.push(*max_val + 1);
        PerturbationSet {
            data: new_data,
            zj_list: self.zj_list
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Fix clippy: No need to wrap in Err(_) here<commit_after><|endoftext|>


<commit_before><commit_msg>Add create without state method to WidgetFactory<commit_after><|endoftext|>


<commit_before><commit_msg>Reorder stuff in eq<commit_after><|endoftext|>


<commit_before><commit_msg>Adicionando Estrutura de dados de um Grafo para a linguagem de programação Rust, baseado na Orientação a Objetos do Rust e com alto desempenho avaliado via entregas de atividades envolvendo grafos no beecrowd<commit_after>/*
	Autor: Gustavo Michels de Camargo

	Projeto: Algoritmo estrural de um Grafo

*/

use std::{collections::HashMap};

// Matriz de Vector usada ara construir o Grafo.
type MatrizGrafo = Vec<Vec<isize>>;

// O dicionario serve para podermos dar entrada a qualquer String e ter como abstrair suas posições dentro.
// da matriz numerica, isso serve apenas para fins de uso, não requerer transcrever um Nodo com X para valor numerico.
#[derive(PartialEq, Eq, Clone, Debug)]
struct Grafo {
	matriz: MatrizGrafo,
	dicionario: HashMap<String, usize>,
	bicondicional: bool
}

trait Projeto {
	// Geral
	fn new(tamanho: usize, tipo: &str) -> Grafo;

	// Funcçoes envolvendo o dicionario - Usuario
	fn usr_pegar_indice(&self, chave: String) -> usize;
	fn usr_pegar_chave(&self, indice: usize) -> String;

	// Usuario
	fn usr_adicionar_conexao(&mut self, a: String, b: String, valor: isize);
	fn usr_remover_conexao(&mut self, a: String, b: String);
	fn usr_numero_conexoes(&self, no: String) -> usize;
	fn usr_verificar_se_existe_conexao(&self, a: String, b: String) -> bool;
	fn usr_conexoes(&self, a: String) -> Vec<String>;

	// Maquina / uso para os Algoritmos
	fn adicionar_conexao(&mut self, a: usize, b: usize, valor: isize);
	fn remover_conexao(&mut self, a: usize, b: usize);
	fn numero_conexoes(&self, no: usize) -> usize;
	fn verificar_se_existe_conexao(&self, a: usize, b: usize) -> bool;
	fn conexoes(&self, a: usize) -> Vec<usize>;

	// Algoritmos que atuam sobre Grafos
}

// Este é a implementação da "Classe" de um grafo.
impl Projeto for Grafo {
	// Tamanho: Numero Maximo de Vertices que a matriz ppode usar de 0 até tamanho.
	// Em notação matematica relativa a limites: [0, tamanho).
	// Toda função que começa com 'usr_'(usr = usuario) é a versão da função que deve ser usada para interagir diretamente com o usuario.
	// As funções de mesmo nome mas sem 'usr_' deve ser usada apenas dentro dos algoritmos, como o Dijkstra para menor caminho entre dois nos.
	// Fiz assim para otimizar processamento e descartar necessidade de acessar e
	// consultaro dicionario o tempo todo quando se apenas como Objetivo encontrar um menor caminho com Dijkstra por exemplo.

	// Apenas essa função foge a regra por ser universal
	fn new(tamanho: usize, tipo: &str) -> Grafo {
		Grafo {
			matriz: vec![vec![-1; tamanho]; tamanho],
			dicionario: HashMap::new(),
			bicondicional: match tipo  {
				"->" => false, // Condicional
				"<->" | _ => true // Bicondicional
			}
		}
	}

	// ---- Funções para uso direto do usuario ----

	// Retorna o indice da matriz relacionada a chave
	fn usr_pegar_indice(&self, chave: String) -> usize {
		if self.dicionario.contains_key(&chave) {
			return (&self.dicionario.get(&chave)).unwrap().clone();
		}

		return 0;
	}

	// Retorna a chave do dicionario relacionada ao valor do indice da matriz do grafo
	fn usr_pegar_chave(&self, indice: usize) -> String {
		for (key, value) in self.dicionario.iter() {
			if *value == indice {
				return (*key).clone();
			}
		}

		return "".to_string();
	}

	// Conecta Dois vertices
	fn usr_adicionar_conexao(&mut self, a: String, b: String, valor: isize) {
		if !self.dicionario.contains_key(&a){
			let num: usize = self.dicionario.len();
			self.dicionario.insert(a.to_owned(), num);
		}

		if !self.dicionario.contains_key(&b){
			let num: usize = self.dicionario.len();
			self.dicionario.insert(b.to_owned(), num);
		}

		let (valor_a, valor_b): (usize, usize) = (self.usr_pegar_indice(a), self.usr_pegar_indice(b));

		self.matriz[valor_a][valor_b] = valor;

		if self.bicondicional {
			self.matriz[valor_b][valor_a] = valor;
		}

	}

	fn usr_remover_conexao(&mut self, a: String, b: String) {
		let (valor_a, valor_b): (usize, usize) = (self.usr_pegar_indice(a), self.usr_pegar_indice(b));

		self.matriz[valor_a][valor_b]  = -1;
		self.matriz[valor_b][valor_a]  = -1;
	}

	// Retorba o numero de vertices na qual ele se conecta
	fn usr_numero_conexoes(&self, no: String) -> usize {
		self.matriz[self.usr_pegar_indice(no)].iter()
						.filter(|x| **x >= 0)
						.collect::<Vec<&isize>>()
						.len() as usize | 0
	}

	// Verifica se dois nos estão conectados
	fn usr_verificar_se_existe_conexao(&self, a: String, b: String) -> bool {
		self.matriz[self.usr_pegar_indice(a)][self.usr_pegar_indice(b)]  >= 0
	}

	fn usr_conexoes(&self, a: String) -> Vec<String> {
		let mut result: Vec<String> = Vec::new();
		let a_value: usize = self.usr_pegar_indice(a);

		for i in 0..self.matriz[a_value].len() {
			if a_value != i && self.matriz[a_value][i] > -1 {
				result.push(self.usr_pegar_chave(i));
			}
		}

		return result;
	}

	// ---- Funções para uso direto dos algoritmos (tem melhor perfomance) ----

	// Retorna um array dos indice de todos os nos na qual o no 'a' se conecta
	// Esera usar esta função apenas para usos proprios dentro do Grafo, como em algoritmos tipo dijkstra
	// Conecta Dois vertices
	fn adicionar_conexao(&mut self, a: usize, b: usize, valor: isize) {
		self.matriz[a][b] = valor;

		if self.bicondicional {
			self.matriz[b][a] = valor;
		}
	}

	fn remover_conexao(&mut self, a: usize, b: usize) {
		self.matriz[a][b]  = -1;
		self.matriz[b][a]  = -1;
	}

	// Retorba o numero de vertices na qual ele se conecta
	fn numero_conexoes(&self, no: usize) -> usize {
		self.matriz[no].iter()
						.filter(|x| **x >= 0)
						.collect::<Vec<&isize>>()
						.len() as usize | 0
	}

	fn verificar_se_existe_conexao(&self, a: usize, b: usize) -> bool {
		self.matriz[a][b]  >= 0
	}

	fn conexoes(&self, a: usize) -> Vec<usize> {
		let mut result: Vec<usize> = Vec::new();

		for i in 0..self.matriz[a].len() {
			if a != i && self.matriz[a][i] > -1 {
				result.push(i);
			}
		}
		return result;
	}

	// ---- Funções dos algoritmos ----

}

// Main
fn main() {
	// Grafo com no maximo mil vertices
	 // "->" =  Grafo condicional, "<->" = Grafo Bicondicional
	let mut grafo: Grafo = Grafo::new(1000, "->");

	grafo.usr_adicionar_conexao(0.to_string(), 1.to_string(), 1);
	grafo.usr_adicionar_conexao(1.to_string(), 2.to_string(), 1);
	grafo.usr_adicionar_conexao(2.to_string(), 3.to_string(), 1);
	grafo.usr_adicionar_conexao(3.to_string(), 0.to_string(), 1);

	println!("{:?}", grafo.conexoes(2));
}

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

	#[test]
	fn usr_numero_conexoes() {
		let mut grafo: Grafo = Grafo::new(1000, "->");

		for i in 1..1000 {
			grafo.usr_adicionar_conexao(0.to_string(), i.to_string(), 1);
		}

		assert_eq!(grafo.usr_numero_conexoes(0.to_string()), 999);
		assert_eq!(grafo.usr_numero_conexoes(0.to_string()), grafo.numero_conexoes(0));
	}

	#[test]
	fn numero_conexoes() {
		let mut grafo: Grafo = Grafo::new(1000, "<->");

		for i in 1..1000 {
			grafo.adicionar_conexao(0, i, 1);
		}

		assert_eq!(grafo.numero_conexoes(0), 999);
		assert_eq!(grafo.numero_conexoes(0), grafo.usr_numero_conexoes(0.to_string()));
	}
}
<|endoftext|>


<commit_before><commit_msg>Day 20 in rust<commit_after><|endoftext|>


<commit_before><commit_msg>Add tests/lib.rs: tests for enclosure fetching<commit_after>extern crate pink_spider;

#[test]
fn it_works() {
  assert!(true);
}

#[test]
fn fetch_apple_music_track() {
    let song = pink_spider::apple_music::fetch_song("jp", "1160715431").unwrap();
    let track = pink_spider::model::Track::from_am_song(&song);
    assert_eq!(track.identifier, "1160715431");
    assert_eq!(track.title, "A Short Film");
    assert_eq!(track.owner_name.unwrap_or_default(), "LILI LIMIT");
    let artists = track.artists.unwrap();
    let artist = &artists[0];
    assert_eq!(artist.name, "LILI LIMIT");
    assert!(artist.clone().artwork_url.unwrap().len() > 0);
}

#[test]
fn fetch_apple_music_album() {
    let am_album = pink_spider::apple_music::fetch_album("jp", "1160715126").unwrap();
    let album = pink_spider::model::Album::from_am_album(&am_album);
    assert_eq!(album.identifier, "1160715126");
    assert_eq!(album.title, "a.k.a");
    assert_eq!(album.owner_name.unwrap_or_default(), "LILI LIMIT");
    let artists = album.artists.unwrap();
    let artist = &artists[0];
    assert_eq!(artist.name, "LILI LIMIT");
    assert!(artist.clone().artwork_url.unwrap().len() > 0);
}

#[test]
fn fetch_spotify_track() {
    let sp_track = pink_spider::spotify::fetch_track("3n3Ppam7vgaVa1iaRUc9Lp").unwrap();
    let track = pink_spider::model::Track::from_sp_track(&sp_track);
    assert_eq!(track.identifier, "3n3Ppam7vgaVa1iaRUc9Lp");
    assert_eq!(track.title, "Mr. Brightside");
    assert_eq!(track.owner_name.unwrap_or_default(), "The Killers");
    let artists = track.artists.unwrap();
    let artist = &artists[0];
    assert_eq!(artist.name, "The Killers");
    println!("{:?}", artist);
    assert!(artist.clone().artwork_url.unwrap().len() > 0);
}

#[test]
fn fetch_spotify_album() {
    let sp_album = pink_spider::spotify::fetch_album("4OHNH3sDzIxnmUADXzv2kT").unwrap();
    let album = pink_spider::model::Album::from_sp_album(&sp_album);
    assert_eq!(album.identifier, "4OHNH3sDzIxnmUADXzv2kT");
    assert_eq!(album.title, "Hot Fuss (Deluxe Version)");
    assert_eq!(album.owner_name.unwrap_or_default(), "The Killers");
    let artists = album.artists.unwrap();
    let artist = &artists[0];
    assert_eq!(artist.name, "The Killers");
    assert!(artist.clone().artwork_url.unwrap().len() > 0);
    assert!(album.tracks.len() > 0);
}

#[test]
fn fetch_soundcloud_track() {
    let sc_track = pink_spider::soundcloud::fetch_track("371851634").unwrap();
    let track = pink_spider::model::Track::from_sc_track(&sc_track);
    assert_eq!(track.identifier, "371851634");
    assert_eq!(track.title, "Down Wit That");
    assert_eq!(track.owner_name.unwrap_or_default(), "\"Chance The Rapper\"");
    let artists = track.artists.unwrap();
    let artist = &artists[0];
    assert_eq!(artist.name, "\"Chance The Rapper\"");
    assert!(artist.clone().artwork_url.unwrap().len() > 0);
}

#[test]
fn fetch_youtube_track() {
    let yt_video = pink_spider::youtube::fetch_video("Wr5f6hpYxmE").unwrap();
    let track = pink_spider::model::Track::from_yt_video(&yt_video);
    assert_eq!(track.identifier, "Wr5f6hpYxmE");
    assert_eq!(track.title, "Cornelius 『あなたがいるなら』If You're Here");
    assert_eq!(track.owner_name.unwrap_or_default(), "corneliusofficial");
    let artists = track.artists.unwrap();
    let artist = &artists[0];
    assert_eq!(artist.name, "corneliusofficial");
    assert!(artist.clone().artwork_url.unwrap().len() > 0);
}
<|endoftext|>


<commit_before><commit_msg>Created rough framework for simulated broker<commit_after>//! Simulated broker used for backtests.  Contains facilities for simulating trades,
//! managing balances, and reporting on statistics from previous trades.

use algobot_util::tick*;

/// A simulated broker that is used as the endpoint for trading activity in backtests.
pub struct Broker {
    accounts: Vec<Ledger>
}

// TODO: Wire TickSink into Broker so that the broker always receives up-to-date data

/// Settings for the simulated broker that determine things like trade fees,
/// estimated slippage, etc.
pub struct BrokerSettings {

}

impl Broker {
    pub fn new(settings: BrokerSettings) {
        unimplemented!();
    }

    /// Called each time a new tick is released by the backtester
    pub fn tick(t: SymbolTick) {
        unimplemented!();
    }
}

/// Any action that the platform can take using the broker
#[derive(Debug)]
pub enum BrokerAction {
    MarketBuy{symbol: String, size: usize},
    MarketStop{symbol: String, size: usize, stop: f64}
}

/// A simulated account that keeps track of open positions, historical trades, and
/// manages balances.
struct Ledger {

}

impl Ledger {
    pub fn new(starting_balance: usize) {
        unimplemented!();
    }
}
<|endoftext|>


<commit_before><commit_msg>Missing dot<commit_after><|endoftext|>


<commit_before><commit_msg>test: Adda test that all arms of an alt may result in fail<commit_after>// When all branches of an alt expression result in fail, the entire
// alt expression results in fail.

fn main() {
  auto x = alt (true) {
    case (true) {
      10
    }
    case (true) {
      alt (true) {
        case (true) {
          fail
        }
        case (false) {
          fail
        }
      }
    }
  };
}
<|endoftext|>


<commit_before><commit_msg>Added example of converting trees to vectors.<commit_after>extern crate presort;

use presort::PresortedVec;

struct TreeNode<T> {
    data: T,
    children: Vec<Tree<T>>,
}

type Tree<T> = Box<TreeNode<T>>;

fn tree<T>(data: T, children: Vec<Tree<T>>) -> Tree<T> {
    Box::new(TreeNode { data: data, children: children })
}

fn dump<T: Ord>(tree: &Tree<T>, vec: &mut PresortedVec<T>) {
    panic!("Not done yet");
}

#[test]
fn test_tree() {
    let tree = tree(37, vec![]);
    let mut vec = PresortedVec::new();
    dump(&tree, &mut vec);
    assert_eq!(vec.sorted_iter().collect::<Vec<&usize>>(), vec![&37]);
}
<|endoftext|>


<commit_before><commit_msg>fix test<commit_after><|endoftext|>


<commit_before><commit_msg>[No-auto] lib/domain/mail: Fix Clippy warnings<commit_after><|endoftext|>


<commit_before>//! Specialized demo of SDL for use on platforms that really want to
//! initialize and own the main routine and thread. This is meant to be
//! linked with object code compiled from one of the SDL_main variants
//! that one can find beneath <SDL-distribution>/src/main/.
//!
//! For example on Mac OS X one can build a runnable program from this
//! with something along the lines of:
//!
//!   rustc src/sdl-demo/sdl_main.rs -L. \
//!       -C link-args="-lSDLmain -lSDL -Wl,-framework,Cocoa"

#![no_main]

extern crate sdl;

use std::rand::Rng;

use sdl::video::{SurfaceFlag, VideoFlag};
use sdl::event::{Event, Key};

#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn SDL_main() {
    real_main()
}

pub fn real_main() {
    sdl::init([sdl::InitFlag::Video].as_slice());
    sdl::wm::set_caption("rust-sdl demo - video", "rust-sdl");

    let mut rng = std::rand::thread_rng();
    let screen = match sdl::video::set_video_mode(800, 600, 32,
                                                  [SurfaceFlag::HWSurface].as_slice(),
                                                  [VideoFlag::DoubleBuf].as_slice()) {
        Ok(screen) => screen,
        Err(err) => panic!("failed to set video mode: {}", err)
    };

    // Note: You'll want to put this and the flip call inside the main loop
    // but we don't as to not startle epileptics
    for i in range(0us, 10) {
        for j in range(0us, 10) {
            screen.fill_rect(Some(sdl::Rect {
                x: (i as i16) * 800 / 10,
                y: (j as i16) * 600 / 10,
                w: 800 / 10,
                h: 600 / 10
            }), rng.gen::<sdl::video::Color>());
        }
    }

    screen.flip();

    'main : loop {
        'event : loop {
            match sdl::event::poll_event() {
                Event::Quit => break 'main,
                Event::None => break 'event,
                Event::Key(k, _, _, _)
                    if k == Key::Escape
                        => break 'main,
                _ => {}
            }
        }
    }

    sdl::quit();
}
<commit_msg>sdl_main: fix range and slice warnings<commit_after>//! Specialized demo of SDL for use on platforms that really want to
//! initialize and own the main routine and thread. This is meant to be
//! linked with object code compiled from one of the SDL_main variants
//! that one can find beneath <SDL-distribution>/src/main/.
//!
//! For example on Mac OS X one can build a runnable program from this
//! with something along the lines of:
//!
//!   rustc src/sdl-demo/sdl_main.rs -L. \
//!       -C link-args="-lSDLmain -lSDL -Wl,-framework,Cocoa"

#![no_main]

extern crate sdl;

use std::rand::Rng;

use sdl::video::{SurfaceFlag, VideoFlag};
use sdl::event::{Event, Key};

#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn SDL_main() {
    real_main()
}

pub fn real_main() {
    sdl::init(&[sdl::InitFlag::Video]);
    sdl::wm::set_caption("rust-sdl demo - video", "rust-sdl");

    let mut rng = std::rand::thread_rng();
    let screen = match sdl::video::set_video_mode(800, 600, 32,
                                                  &[SurfaceFlag::HWSurface],
                                                  &[VideoFlag::DoubleBuf]) {
        Ok(screen) => screen,
        Err(err) => panic!("failed to set video mode: {}", err)
    };

    // Note: You'll want to put this and the flip call inside the main loop
    // but we don't as to not startle epileptics
    for i in 0us..10 {
        for j in 0us..10 {
            screen.fill_rect(Some(sdl::Rect {
                x: (i as i16) * 800 / 10,
                y: (j as i16) * 600 / 10,
                w: 800 / 10,
                h: 600 / 10
            }), rng.gen::<sdl::video::Color>());
        }
    }

    screen.flip();

    'main : loop {
        'event : loop {
            match sdl::event::poll_event() {
                Event::Quit => break 'main,
                Event::None => break 'event,
                Event::Key(k, _, _, _)
                    if k == Key::Escape
                        => break 'main,
                _ => {}
            }
        }
    }

    sdl::quit();
}
<|endoftext|>


<commit_before><commit_msg>Basic shuffle<commit_after>

fn main(){

    let x: usize = 5;

    let mut vec = vec![0; x];
    let i:usize;

    let mut v_copy ;

    for i in 0..x{
        vec[i] = i;
        println!("{}",vec[i]);
    }

    v_copy = create_new(&vec);

    let mut j : usize;
    j = 0;
    for i in 0..x/2{
        vec[j] = v_copy[i];
        vec[j+1] = v_copy[i+x/2];
        j += 2;
    }

    for i in 0..x{
        println!("{}",vec[i]);
    }

}

fn create_new<T: Clone>(vec: &[T]) -> Vec<T> {
    let mut newvec = vec.to_owned();
    newvec
}
<|endoftext|>


<commit_before>use alloc::boxed::Box;

use collections::vec::Vec;

use core::intrinsics::volatile_load;
use core::{mem, slice};

use drivers::mmio::Mmio;
use drivers::pci::config::PciConfig;

use schemes::KScheme;

use super::hci::{UsbHci, UsbMsg};
use super::setup::Setup;

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Gtd {
    flags: u32,
    buffer: u32,
    next: u32,
    end: u32,
}

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Ed {
    flags: u32,
    tail: u32,
    head: u32,
    next: u32,
}

const CTRL_CBSR: u32 = 0b11;
const CTRL_PLE: u32 = 1 << 2;
const CTRL_IE: u32 = 1 << 3;
const CTRL_CLE: u32 = 1 << 4;
const CTRL_BLE: u32 = 1 << 5;
const CTRL_HCFS: u32 = 0b11 << 6;
const CTRL_IR: u32 = 1 << 8;
const CTRL_RWC: u32 = 1 << 9;
const CTRL_RWE: u32 = 1 << 10;

const CMD_STS_HCR: u32 = 1;
const CMD_STS_CLF: u32 = 1 << 1;
const CMD_STS_BLF: u32 = 1 << 2;
const CMD_STS_OCR: u32 = 1 << 3;

const PORT_STS_CCS: u32 = 1;
const PORT_STS_PES: u32 = 1 << 1;
const PORT_STS_PSS: u32 = 1 << 2;
const PORT_STS_POCI: u32 = 1 << 3;
const PORT_STS_PPS: u32 = 1 << 8;
const PORT_STS_LSDA: u32 = 1 << 9;
const PORT_STS_CSC: u32 = 1 << 16;
const PORT_STS_PESC: u32 = 1 << 17;
const PORT_STS_PSSC: u32 = 1 << 18;
const PORT_STS_OCIC: u32 = 1 << 19;
const PORT_STS_PRSC: u32 = 1 << 20;

#[repr(packed)]
pub struct OhciRegs {
    pub revision: Mmio<u32>,
    pub control: Mmio<u32>,
    pub cmd_sts: Mmio<u32>,
    pub int_sts: Mmio<u32>,
    pub int_en: Mmio<u32>,
    pub int_dis: Mmio<u32>,
    pub hcca: Mmio<u32>,
    pub period_current: Mmio<u32>,
    pub control_head: Mmio<u32>,
    pub control_current: Mmio<u32>,
    pub bulk_head: Mmio<u32>,
    pub bulk_current: Mmio<u32>,
    pub done_head: Mmio<u32>,
    pub fm_interval: Mmio<u32>,
    pub fm_remain: Mmio<u32>,
    pub fm_num: Mmio<u32>,
    pub periodic_start: Mmio<u32>,
    pub ls_thresh: Mmio<u32>,
    pub rh_desc_a: Mmio<u32>,
    pub rh_desc_b: Mmio<u32>,
    pub rh_sts: Mmio<u32>,
    pub port_sts: [Mmio<u32>; 15],
}

pub struct Ohci {
    pub regs: &'static mut OhciRegs,
    pub irq: u8,
}

impl KScheme for Ohci {
    fn on_irq(&mut self, irq: u8) {
        if irq == self.irq {
            // d("OHCI IRQ\n");
        }
    }

    fn on_poll(&mut self) {
    }
}

impl Ohci {
    pub unsafe fn new(mut pci: PciConfig) -> Box<Self> {
        pci.flag(4, 4, true); // Bus mastering

        let base = pci.read(0x10) as usize & 0xFFFFFFF0;
        let regs = &mut *(base as *mut OhciRegs);

        let mut module = box Ohci {
            regs: regs,
            irq: pci.read(0x3C) as u8 & 0xF,
        };

        module.init();

        return module;
    }

    pub unsafe fn init(&mut self) {
        debugln!("OHCI on: {:X}, IRQ: {:X}", (self.regs as *mut OhciRegs) as usize, self.irq);

        debugln!("Reset: {:X}", self.regs.control.read());
        loop {
            let ctrl = self.regs.control.read();
            let desired_ctrl = ctrl & (0xFFFFFFFF - CTRL_HCFS);
            if ctrl != desired_ctrl {
                self.regs.control.write(desired_ctrl);
            } else {
                break;
            }
        }

        debugln!("Enable: {:X}", self.regs.control.read());
        loop {
            let ctrl = self.regs.control.read();
            let desired_ctrl = (ctrl & (0xFFFFFFFF - CTRL_HCFS)) | 0b10 << 6;
            if ctrl != desired_ctrl {
                self.regs.control.write(desired_ctrl);
            } else {
                break;
            }
        }

        debugln!("Port Enumeration: {:X}", self.regs.control.read());

        let ndp = self.regs.rh_desc_a.read() & 0xF;
        for i in 0..ndp as usize {
            debugln!("Port {}: {:X}", i, self.regs.port_sts[i].read());

            if self.regs.port_sts[i].readf(PORT_STS_CCS) {
                debugln!("Device");

                debugln!("Enable");
                while ! self.regs.port_sts[i].readf(PORT_STS_PES) {
                    self.regs.port_sts[i].writef(PORT_STS_PES, true);
                }

                self.device(i as u8);
            }
        }
    }
}

impl UsbHci for Ohci {
    fn msg(&mut self, address: u8, endpoint: u8, msgs: &[UsbMsg]) -> usize {
        let mut tds = Vec::new();
        for msg in msgs.iter().rev() {
            let link_ptr = match tds.last() {
                Some(td) => (td as *const Gtd) as u32,
                None => 0
            };

            match *msg {
                UsbMsg::Setup(setup) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b00 << 19,
                    buffer: (setup as *const Setup) as u32,
                    next: link_ptr,
                    end: (setup as *const Setup) as u32 + mem::size_of::<Setup>() as u32
                }),
                UsbMsg::In(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::InIso(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::Out(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::OutIso(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                })
            }
        }

        let mut count = 0;

        if ! tds.is_empty() {
            let ed = box Ed {
                //TODO: Remove 1 << 13, it sets it to low speed
                flags: 0x3FF << 16 | 1 << 13 | (endpoint as u32) << 7 | address as u32,
                tail: 0,
                head: (tds.last().unwrap() as *const Gtd) as u32,
                next: 0
            };

            //TODO: Calculate actual bytes
            for td in tds.iter().rev() {
                count += (td.end - td.buffer) as usize;
            }

            self.regs.control_head.write((&*ed as *const Ed) as u32);
            while ! self.regs.control.readf(CTRL_CLE) {
                self.regs.control.writef(CTRL_CLE, true);
            }
            while ! self.regs.cmd_sts.readf(CMD_STS_CLF) {
                self.regs.cmd_sts.writef(CMD_STS_CLF, true);
            }

            for td in tds.iter().rev() {
                while unsafe { volatile_load(td as *const Gtd).flags } & 0b1111 << 28 == 0b1111 << 28 {
                    //unsafe { context_switch(false) };
                }
                let condition = (unsafe { volatile_load(td as *const Gtd).flags } & 0b1111 << 28) >> 28;
                if condition != 0 {
                    debugln!("Condition: {:X}", condition);
                    break;
                }
            }

            while self.regs.cmd_sts.readf(CMD_STS_CLF) {
                self.regs.cmd_sts.writef(CMD_STS_CLF, false);
            }
            while self.regs.control.readf(CTRL_CLE) {
                self.regs.control.writef(CTRL_CLE, false);
            }
            self.regs.control_head.write(0);
        }

        count
    }
}
<commit_msg>Prevent halts in virtualbox<commit_after>use alloc::boxed::Box;

use collections::vec::Vec;

use core::intrinsics::volatile_load;
use core::{mem, slice};

use drivers::mmio::Mmio;
use drivers::pci::config::PciConfig;

use schemes::KScheme;

use super::hci::{UsbHci, UsbMsg};
use super::setup::Setup;

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Gtd {
    flags: u32,
    buffer: u32,
    next: u32,
    end: u32,
}

#[repr(packed)]
#[derive(Copy, Clone, Debug, Default)]
struct Ed {
    flags: u32,
    tail: u32,
    head: u32,
    next: u32,
}

const CTRL_CBSR: u32 = 0b11;
const CTRL_PLE: u32 = 1 << 2;
const CTRL_IE: u32 = 1 << 3;
const CTRL_CLE: u32 = 1 << 4;
const CTRL_BLE: u32 = 1 << 5;
const CTRL_HCFS: u32 = 0b11 << 6;
const CTRL_IR: u32 = 1 << 8;
const CTRL_RWC: u32 = 1 << 9;
const CTRL_RWE: u32 = 1 << 10;

const CMD_STS_HCR: u32 = 1;
const CMD_STS_CLF: u32 = 1 << 1;
const CMD_STS_BLF: u32 = 1 << 2;
const CMD_STS_OCR: u32 = 1 << 3;

const PORT_STS_CCS: u32 = 1;
const PORT_STS_PES: u32 = 1 << 1;
const PORT_STS_PSS: u32 = 1 << 2;
const PORT_STS_POCI: u32 = 1 << 3;
const PORT_STS_PPS: u32 = 1 << 8;
const PORT_STS_LSDA: u32 = 1 << 9;
const PORT_STS_CSC: u32 = 1 << 16;
const PORT_STS_PESC: u32 = 1 << 17;
const PORT_STS_PSSC: u32 = 1 << 18;
const PORT_STS_OCIC: u32 = 1 << 19;
const PORT_STS_PRSC: u32 = 1 << 20;

#[repr(packed)]
pub struct OhciRegs {
    pub revision: Mmio<u32>,
    pub control: Mmio<u32>,
    pub cmd_sts: Mmio<u32>,
    pub int_sts: Mmio<u32>,
    pub int_en: Mmio<u32>,
    pub int_dis: Mmio<u32>,
    pub hcca: Mmio<u32>,
    pub period_current: Mmio<u32>,
    pub control_head: Mmio<u32>,
    pub control_current: Mmio<u32>,
    pub bulk_head: Mmio<u32>,
    pub bulk_current: Mmio<u32>,
    pub done_head: Mmio<u32>,
    pub fm_interval: Mmio<u32>,
    pub fm_remain: Mmio<u32>,
    pub fm_num: Mmio<u32>,
    pub periodic_start: Mmio<u32>,
    pub ls_thresh: Mmio<u32>,
    pub rh_desc_a: Mmio<u32>,
    pub rh_desc_b: Mmio<u32>,
    pub rh_sts: Mmio<u32>,
    pub port_sts: [Mmio<u32>; 15],
}

pub struct Ohci {
    pub regs: &'static mut OhciRegs,
    pub irq: u8,
}

impl KScheme for Ohci {
    fn on_irq(&mut self, irq: u8) {
        if irq == self.irq {
            // d("OHCI IRQ\n");
        }
    }

    fn on_poll(&mut self) {
    }
}

impl Ohci {
    pub unsafe fn new(mut pci: PciConfig) -> Box<Self> {
        pci.flag(4, 4, true); // Bus mastering

        let base = pci.read(0x10) as usize & 0xFFFFFFF0;
        let regs = &mut *(base as *mut OhciRegs);

        let mut module = box Ohci {
            regs: regs,
            irq: pci.read(0x3C) as u8 & 0xF,
        };

        module.init();

        return module;
    }

    pub unsafe fn init(&mut self) {
        debugln!("OHCI on: {:X}, IRQ: {:X}", (self.regs as *mut OhciRegs) as usize, self.irq);

        debugln!("Reset: {:X}", self.regs.control.read());
        loop {
            let ctrl = self.regs.control.read();
            let desired_ctrl = ctrl & (0xFFFFFFFF - CTRL_HCFS);
            if ctrl != desired_ctrl {
                self.regs.control.write(desired_ctrl);
            } else {
                break;
            }
        }

        debugln!("Enable: {:X}", self.regs.control.read());
        loop {
            let ctrl = self.regs.control.read();
            let desired_ctrl = (ctrl & (0xFFFFFFFF - CTRL_HCFS)) | 0b10 << 6;
            if ctrl != desired_ctrl {
                self.regs.control.write(desired_ctrl);
            } else {
                break;
            }
        }

        debugln!("Port Enumeration: {:X}", self.regs.control.read());

        let ndp = self.regs.rh_desc_a.read() & 0xF;
        for i in 0..ndp as usize {
            debugln!("Port {}: {:X}", i, self.regs.port_sts[i].read());

            if self.regs.port_sts[i].readf(PORT_STS_CCS) {
                debugln!("Device");

                debugln!("Enable");
                while ! self.regs.port_sts[i].readf(PORT_STS_PES) {
                    self.regs.port_sts[i].writef(PORT_STS_PES, true);
                }

                self.device(i as u8);
            }
        }
    }
}

impl UsbHci for Ohci {
    fn msg(&mut self, address: u8, endpoint: u8, msgs: &[UsbMsg]) -> usize {
        let mut tds = Vec::new();
        for msg in msgs.iter().rev() {
            let link_ptr = match tds.last() {
                Some(td) => (td as *const Gtd) as u32,
                None => 0
            };

            match *msg {
                UsbMsg::Setup(setup) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b00 << 19,
                    buffer: (setup as *const Setup) as u32,
                    next: link_ptr,
                    end: (setup as *const Setup) as u32 + mem::size_of::<Setup>() as u32
                }),
                UsbMsg::In(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::InIso(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b10 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::Out(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                }),
                UsbMsg::OutIso(ref data) => tds.push(Gtd {
                    flags: 0b1111 << 28 | 0b01 << 19,
                    buffer: data.as_ptr() as u32,
                    next: link_ptr,
                    end: data.as_ptr() as u32 + data.len() as u32
                })
            }
        }

        let mut count = 0;

        if ! tds.is_empty() {
            let ed = box Ed {
                //TODO: Remove 1 << 13, it sets it to low speed
                flags: 0x3FF << 16 | 1 << 13 | (endpoint as u32) << 7 | address as u32,
                tail: 0,
                head: (tds.last().unwrap() as *const Gtd) as u32,
                next: 0
            };

            //TODO: Calculate actual bytes
            for td in tds.iter().rev() {
                count += (td.end - td.buffer) as usize;
            }

            self.regs.control_head.write((&*ed as *const Ed) as u32);
            while ! self.regs.control.readf(CTRL_CLE) {
                self.regs.control.writef(CTRL_CLE, true);
            }
            while ! self.regs.cmd_sts.readf(CMD_STS_CLF) {
                self.regs.cmd_sts.writef(CMD_STS_CLF, true);
            }

            for td in tds.iter().rev() {
                let mut spin = 1000000;
                while unsafe { volatile_load(td as *const Gtd).flags } & 0b1111 << 28 == 0b1111 << 28 && spin > 0 {
                    spin -= 1;
                    //unsafe { context_switch(false) };
                }
                let condition = (unsafe { volatile_load(td as *const Gtd).flags } & 0b1111 << 28) >> 28;
                if condition != 0 {
                    debugln!("Condition: {:X}", condition);
                    break;
                }
            }

            /*
            while self.regs.cmd_sts.readf(CMD_STS_CLF) {
                self.regs.cmd_sts.writef(CMD_STS_CLF, false);
            }
            */
            while self.regs.control.readf(CTRL_CLE) {
                self.regs.control.writef(CTRL_CLE, false);
            }
            self.regs.control_head.write(0);
        }

        count
    }
}
<|endoftext|>


<commit_before><commit_msg>Generate test cases with a macro.<commit_after><|endoftext|>


<commit_before><commit_msg>test iterator chain type length blowup<commit_after>// run-pass
//! This snippet causes the type length to blowup exponentially,
//! so check that we don't accidentially exceed the type length limit.
// FIXME: Once the size of iterator adaptors is further reduced,
// increase the complexity of this test.

fn main() {
    let c = 2;
    let bv = vec![2];
    let b = bv
        .iter()
        .filter(|a| **a == c);

    let _a = vec![1, 2, 3]
        .into_iter()
        .filter(|a| b.clone().any(|b| *b == *a))
        .filter(|a| b.clone().any(|b| *b == *a))
        .filter(|a| b.clone().any(|b| *b == *a))
        .filter(|a| b.clone().any(|b| *b == *a))
        .filter(|a| b.clone().any(|b| *b == *a))
        .filter(|a| b.clone().any(|b| *b == *a))
        .filter(|a| b.clone().any(|b| *b == *a))
        .filter(|a| b.clone().any(|b| *b == *a))
        .filter(|a| b.clone().any(|b| *b == *a))
        .filter(|a| b.clone().any(|b| *b == *a))
        .filter(|a| b.clone().any(|b| *b == *a))
        .filter(|a| b.clone().any(|b| *b == *a))
        .filter(|a| b.clone().any(|b| *b == *a))
        .filter(|a| b.clone().any(|b| *b == *a))
        .collect::<Vec<_>>();
}
<|endoftext|>


<commit_before><commit_msg>Minor refactorings for the guessing game<commit_after><|endoftext|>


<commit_before>//! Implement a Poisson Disc distribution algorithm.

use rand;
use std::cmp;

use coord::Coord;
use surface::points::Points;

/// Container for constructing different randomly sampled distributions.
pub struct Distribution;

impl Distribution {
    /// Return a set of points that have been generated using a Poisson disk sampling
    /// algorithm. They will be separated from each other at minimum by an input distance.
    pub fn poisson(rmin: f64, size_x: f64, size_y: f64) -> Points {
        self::density::PoissonDistribution::new(rmin, size_x, size_y)
    }

    /// Return a set of an input number of points that have been generated using
    /// a blue noise sampling algorithm.
    pub fn blue_noise(num_points: u64, size_x: f64, size_y: f64) -> Points {
        self::number::BlueNoiseDistribution::new(num_points, size_x, size_y)
    }
}

mod number {
    use rand::distributions::IndependentSample;
    use super::*;

    pub struct BlueNoiseDistribution;

    impl BlueNoiseDistribution {
        pub fn new(num_points: u64, size_x: f64, size_y: f64) -> Points {
            let mut coords = vec![gen_coord(size_x, size_y)];
            const NUM_CANDIDATES_MULTIPLIER: u64 = 1;

            for i in 1..num_points {
                let mut current_best = gen_coord(size_x, size_y);
                let mut max_dist = calc_min_dist(current_best, &coords, size_x, size_y);

                for _ in 0..(NUM_CANDIDATES_MULTIPLIER * i) {
                    let candidate = gen_coord(size_x, size_y);
                    let dist = calc_min_dist(candidate, &coords, size_x, size_y);

                    if dist > max_dist {
                        max_dist = dist;
                        current_best = candidate;
                    }
                };

                coords.push(current_best);
            }

            Points {
                box_size: Coord::new(size_x, size_y, 0.0),
                coords,
            }
        }
    }

    pub fn calc_min_dist(coord: Coord, samples: &[Coord], size_x: f64, size_y: f64) -> f64 {
        use std::f64;
        samples.iter()
               .fold(f64::MAX, |dist, &other| {
                    dist.min(calc_toroidal_distance(coord, other, size_x, size_y))
               })
    }

    pub fn calc_toroidal_distance(coord: Coord, other: Coord, size_x: f64, size_y: f64) -> f64 {
        let mut dx = (coord.x - other.x).abs();
        let mut dy = (coord.y - other.y).abs();

        if dx > size_x / 2.0 {
           dx = size_x - dx;
        }

        if dy > size_y / 2.0 {
            dy = size_y - dy;
        }

        dx.powi(2) + dy.powi(2)
    }

    fn gen_coord(dx: f64, dy: f64) -> Coord {
        let mut rng = rand::thread_rng();
        let range_x = rand::distributions::Range::new(0.0, dx);
        let range_y = rand::distributions::Range::new(0.0, dy);

        Coord::new(range_x.ind_sample(&mut rng), range_y.ind_sample(&mut rng), 0.0)
    }
}

mod density {
    use rand::distributions::IndependentSample;
    use super::*;

    pub struct PoissonDistribution;

    impl PoissonDistribution {
        pub fn new(rmin: f64, size_x: f64, size_y: f64) -> Points {
            let mut grid = PoissonGrid::new(rmin, size_x, size_y);

            let init_coord = gen_grid_coord(size_x, size_y);
            let mut active: Vec<Coord> = vec![init_coord];
            grid.set_coord(init_coord).expect("There was an error when creating the Poisson disc distribution");

            while !active.is_empty() {
                let index = select_coordinate(&active);

                if let Some(candidate) = find_candidate(&active[index], &grid) {
                    if grid.set_coord(candidate).is_ok() {
                        active.push(candidate);
                    }
                } else {
                    active.remove(index);
                };
            }

            Points {
                box_size: Coord::new(size_x, size_y, 0.0),
                coords: grid.into_coords(),
            }
        }
    }

    struct PoissonGrid {
        spacing: f64,
        rmin: f64,
        size: (f64, f64),
        shape: (usize, usize),
        cells: Vec<Option<Coord>>,
    }

    impl PoissonGrid {
        fn new(rmin: f64, size_x: f64, size_y: f64) -> PoissonGrid {
            let a = rmin / 2.0f64.sqrt();
            let nx = (size_x / a).ceil() as usize;
            let ny = (size_y / a).ceil() as usize;

            PoissonGrid {
                spacing: a,
                rmin: rmin,
                size: (size_x, size_y),
                shape: (nx, ny),
                cells: vec![None; nx * ny],
            }
        }

        fn cell_at_position(&self, col: usize, row: usize) -> usize {
            let (nx, _) = self.shape;
            row * nx + col
        }

        fn cell_at_coord(&self, coord: &Coord) -> usize {
            let col = (coord.x / self.spacing).floor() as usize;
            let row = (coord.y / self.spacing).floor() as usize;
            self.cell_at_position(col, row)
        }

        fn collision(&self, coord: &Coord) -> bool {
            let index = self.cell_at_coord(&coord);
            self.get_neighbours(index)
                .iter()
                .filter_map(|opt| opt.map(|c| c.distance(*coord)))
                .any(|r| r < self.rmin)
        }

        fn get_neighbours(&self, index: usize) -> Vec<Option<Coord>> {
            let (nx, ny) = self.shape;
            let i = (index % nx) as isize;
            let j = (index / nx) as isize;

            let mut neighbours = Vec::new();

            // Since rmin = sqrt(2) * spacing we need to check cells
            // that are up to two positions away
            let (imin, imax) = (cmp::max(0, i - 2), cmp::min(nx as isize, i + 3));
            let (jmin, jmax) = (cmp::max(0, j - 2), cmp::min(ny as isize, j + 3));

            for col in imin..imax {
                for row in jmin..jmax {
                    let neighbour_index = self.cell_at_position(col as usize, row as usize);
                    neighbours.push(self.cells[neighbour_index]);
                }
            }

            neighbours
        }

        fn into_coords(self) -> Vec<Coord> {
            self.cells.iter().filter_map(|&c| c).collect()
        }

        fn set_coord(&mut self, coord: Coord) -> Result<(), &'static str> {
            let index = self.cell_at_coord(&coord);

            // Consistency check for the algorithm: this should never be reached
            // but we prefer to not panic if it happens
            if self.cells[index].is_some() {
                return Err("Cannot add a coordinate to a cell which is already occupied");
            }

            self.cells[index] = Some(coord);
            Ok(())
        }
    }

    fn find_candidate(coord: &Coord, grid: &PoissonGrid) -> Option<Coord> {
        const NUM_CANDIDATES: usize = 30;

        for _ in 0..NUM_CANDIDATES {
            let candidate = gen_coord_around(&coord, &grid);

            if !grid.collision(&candidate) {
                return Some(candidate);
            }
        }

        None
    }

    fn gen_coord_around(coord: &Coord, grid: &PoissonGrid) -> Coord {
        use std::f64::consts::PI;
        let mut rng = rand::thread_rng();
        let range_dr = rand::distributions::Range::new(grid.rmin, 2.0 * grid.rmin);
        let range_angle = rand::distributions::Range::new(0.0, 2.0 * PI);

        let (max_x, max_y) = grid.size;

        loop {
            let dr = range_dr.ind_sample(&mut rng);
            let angle = range_angle.ind_sample(&mut rng);
            let x = coord.x + dr * angle.cos();
            let y = coord.y + dr * angle.sin();

            if x >= 0.0 && x < max_x && y >= 0.0 && y < max_y {
                return Coord::new(x, y, 0.0);
            }
        }
    }

    fn gen_grid_coord(x: f64, y: f64) -> Coord {
        let mut rng = rand::thread_rng();
        let range_x = rand::distributions::Range::new(0.0, x);
        let range_y = rand::distributions::Range::new(0.0, y);

        Coord::new(range_x.ind_sample(&mut rng), range_y.ind_sample(&mut rng), 0.0)
    }

    fn select_coordinate(coords: &Vec<Coord>) -> usize {
        let mut rng = rand::thread_rng();
        let range = rand::distributions::Range::new(0, coords.len());

        range.ind_sample(&mut rng)
    }
}

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

    #[test]
    fn create_poisson_distribution() {
        let rmin = 1.0;
        let (size_x, size_y) = (5.0, 10.0);
        let distribution = density::PoissonDistribution::new(rmin, size_x, size_y);

        // We can only assert that no coordinates are within the minimum
        // distance of each other, or outside the box.
        assert!(distribution.coords.len() > 0);

        for (i, &x1) in distribution.coords.iter().enumerate() {
            assert!(x1.x >= 0.0 && x1.x <= size_x);
            assert!(x1.y >= 0.0 && x1.y <= size_y);

            for &x2 in distribution.coords.iter().skip(i + 1) {
                assert!(Coord::distance(x1, x2) >= rmin);
            }
        }
    }

    #[test]
    fn create_blue_noise_distribution() {
        let num_points = 152;
        let (size_x, size_y) = (5.0, 10.0);
        let distribution = number::BlueNoiseDistribution::new(num_points, size_x, size_y);

        // We can only (easily) assert that we have the input number of points
        // and that none are outside of the box.
        assert_eq!(distribution.coords.len() , num_points as usize);

        for coord in distribution.coords {
            assert!(coord.x >= 0.0 && coord.x <= size_x);
            assert!(coord.y >= 0.0 && coord.y <= size_y);
        }
    }

    #[test]
    fn calculate_toroidal_distance_is_squared_and_wraps_coordinates_to_closest() {
        let coord = Coord::new(0.0, 0.0, 10.0); // skip the z value
        let other = Coord::new(1.5, 2.5, -10.0);

        let (size_x, size_y) = (2.0_f64, 3.0_f64);

        // Both coordinates are closer by wrapping around! Also, ignore the z coordinate!
        let dist = (size_x - 1.5).powi(2) + (size_y - 2.5).powi(2);

        assert_eq!(number::calc_toroidal_distance(coord, other, size_x, size_y), dist);
    }

    #[test]
    fn calculate_min_distance_squared_between_a_coordinate_and_a_set() {
        let coord = Coord::new(2.0, 2.0, 2.0);

        let candidates = vec![
            Coord::new(0.0, 0.0, 0.0), // distance squared: 2^2 + 2^2 =  8
            Coord::new(3.0, 1.0, 3.0), //                   1^2 + 1^2 =  2, minimum!
            Coord::new(5.0, 5.0, 5.0)  //                   3^2 + 3^2 = 18
        ];

        let dist = 2.0 * 1.0_f64.powi(2);

        let (size_x, size_y) = (10.0, 10.0);

        assert_eq!(number::calc_min_dist(coord, &candidates, size_x, size_y), dist);
    }
}
<commit_msg>Comment about performance improvements for `BlueNoise` construction<commit_after>//! Implement a Poisson Disc distribution algorithm.

use rand;
use std::cmp;

use coord::Coord;
use surface::points::Points;

/// Container for constructing different randomly sampled distributions.
pub struct Distribution;

impl Distribution {
    /// Return a set of points that have been generated using a Poisson disk sampling
    /// algorithm. They will be separated from each other at minimum by an input distance.
    pub fn poisson(rmin: f64, size_x: f64, size_y: f64) -> Points {
        self::density::PoissonDistribution::new(rmin, size_x, size_y)
    }

    /// Return a set of an input number of points that have been generated using
    /// a blue noise sampling algorithm.
    pub fn blue_noise(num_points: u64, size_x: f64, size_y: f64) -> Points {
        self::number::BlueNoiseDistribution::new(num_points, size_x, size_y)
    }
}

mod number {
    use rand::distributions::IndependentSample;
    use super::*;

    pub struct BlueNoiseDistribution;

    impl BlueNoiseDistribution {
        // This algorithm is quite expensive since every candidate has to be checked
        // against every coordinate that has been constructed, and the number of candidates
        // which we create increases equally. Thus it scales very poorly with the number
        // of points that are created.
        //
        // Could be sped up by implementing a grid for the final coordinates and compare
        // every candidate to those inside a neighbouring area only. Also by making it
        // parallel, but more power cannot substitute bad algorithms.
        //
        // **Note that before any performance improvements are made, a benchmark test should
        // be created!**
        pub fn new(num_points: u64, size_x: f64, size_y: f64) -> Points {
            let mut coords = vec![gen_coord(size_x, size_y)];
            const NUM_CANDIDATES_MULTIPLIER: u64 = 1;

            for i in 1..num_points {
                let mut current_best = gen_coord(size_x, size_y);
                let mut max_dist = calc_min_dist(current_best, &coords, size_x, size_y);

                for _ in 0..(NUM_CANDIDATES_MULTIPLIER * i) {
                    let candidate = gen_coord(size_x, size_y);
                    let dist = calc_min_dist(candidate, &coords, size_x, size_y);

                    if dist > max_dist {
                        max_dist = dist;
                        current_best = candidate;
                    }
                };

                coords.push(current_best);
            }

            Points {
                box_size: Coord::new(size_x, size_y, 0.0),
                coords,
            }
        }
    }

    pub fn calc_min_dist(coord: Coord, samples: &[Coord], size_x: f64, size_y: f64) -> f64 {
        use std::f64::MAX;

        samples.iter()
               .fold(MAX, |dist, &other| {
                    dist.min(calc_toroidal_distance(coord, other, size_x, size_y))
               })
    }

    pub fn calc_toroidal_distance(coord: Coord, other: Coord, size_x: f64, size_y: f64) -> f64 {
        let mut dx = (coord.x - other.x).abs();
        let mut dy = (coord.y - other.y).abs();

        if dx > size_x / 2.0 {
           dx = size_x - dx;
        }

        if dy > size_y / 2.0 {
            dy = size_y - dy;
        }

        dx.powi(2) + dy.powi(2)
    }

    fn gen_coord(dx: f64, dy: f64) -> Coord {
        let mut rng = rand::thread_rng();
        let range_x = rand::distributions::Range::new(0.0, dx);
        let range_y = rand::distributions::Range::new(0.0, dy);

        Coord::new(range_x.ind_sample(&mut rng), range_y.ind_sample(&mut rng), 0.0)
    }
}

mod density {
    use rand::distributions::IndependentSample;
    use super::*;

    pub struct PoissonDistribution;

    impl PoissonDistribution {
        pub fn new(rmin: f64, size_x: f64, size_y: f64) -> Points {
            let mut grid = PoissonGrid::new(rmin, size_x, size_y);

            let init_coord = gen_grid_coord(size_x, size_y);
            let mut active: Vec<Coord> = vec![init_coord];
            grid.set_coord(init_coord).expect("There was an error when creating the Poisson disc distribution");

            while !active.is_empty() {
                let index = select_coordinate(&active);

                if let Some(candidate) = find_candidate(&active[index], &grid) {
                    if grid.set_coord(candidate).is_ok() {
                        active.push(candidate);
                    }
                } else {
                    active.remove(index);
                };
            }

            Points {
                box_size: Coord::new(size_x, size_y, 0.0),
                coords: grid.into_coords(),
            }
        }
    }

    struct PoissonGrid {
        spacing: f64,
        rmin: f64,
        size: (f64, f64),
        shape: (usize, usize),
        cells: Vec<Option<Coord>>,
    }

    impl PoissonGrid {
        fn new(rmin: f64, size_x: f64, size_y: f64) -> PoissonGrid {
            let a = rmin / 2.0f64.sqrt();
            let nx = (size_x / a).ceil() as usize;
            let ny = (size_y / a).ceil() as usize;

            PoissonGrid {
                spacing: a,
                rmin: rmin,
                size: (size_x, size_y),
                shape: (nx, ny),
                cells: vec![None; nx * ny],
            }
        }

        fn cell_at_position(&self, col: usize, row: usize) -> usize {
            let (nx, _) = self.shape;
            row * nx + col
        }

        fn cell_at_coord(&self, coord: &Coord) -> usize {
            let col = (coord.x / self.spacing).floor() as usize;
            let row = (coord.y / self.spacing).floor() as usize;
            self.cell_at_position(col, row)
        }

        fn collision(&self, coord: &Coord) -> bool {
            let index = self.cell_at_coord(&coord);
            self.get_neighbours(index)
                .iter()
                .filter_map(|opt| opt.map(|c| c.distance(*coord)))
                .any(|r| r < self.rmin)
        }

        fn get_neighbours(&self, index: usize) -> Vec<Option<Coord>> {
            let (nx, ny) = self.shape;
            let i = (index % nx) as isize;
            let j = (index / nx) as isize;

            let mut neighbours = Vec::new();

            // Since rmin = sqrt(2) * spacing we need to check cells
            // that are up to two positions away
            let (imin, imax) = (cmp::max(0, i - 2), cmp::min(nx as isize, i + 3));
            let (jmin, jmax) = (cmp::max(0, j - 2), cmp::min(ny as isize, j + 3));

            for col in imin..imax {
                for row in jmin..jmax {
                    let neighbour_index = self.cell_at_position(col as usize, row as usize);
                    neighbours.push(self.cells[neighbour_index]);
                }
            }

            neighbours
        }

        fn into_coords(self) -> Vec<Coord> {
            self.cells.iter().filter_map(|&c| c).collect()
        }

        fn set_coord(&mut self, coord: Coord) -> Result<(), &'static str> {
            let index = self.cell_at_coord(&coord);

            // Consistency check for the algorithm: this should never be reached
            // but we prefer to not panic if it happens
            if self.cells[index].is_some() {
                return Err("Cannot add a coordinate to a cell which is already occupied");
            }

            self.cells[index] = Some(coord);
            Ok(())
        }
    }

    fn find_candidate(coord: &Coord, grid: &PoissonGrid) -> Option<Coord> {
        const NUM_CANDIDATES: usize = 30;

        for _ in 0..NUM_CANDIDATES {
            let candidate = gen_coord_around(&coord, &grid);

            if !grid.collision(&candidate) {
                return Some(candidate);
            }
        }

        None
    }

    fn gen_coord_around(coord: &Coord, grid: &PoissonGrid) -> Coord {
        use std::f64::consts::PI;
        let mut rng = rand::thread_rng();
        let range_dr = rand::distributions::Range::new(grid.rmin, 2.0 * grid.rmin);
        let range_angle = rand::distributions::Range::new(0.0, 2.0 * PI);

        let (max_x, max_y) = grid.size;

        loop {
            let dr = range_dr.ind_sample(&mut rng);
            let angle = range_angle.ind_sample(&mut rng);
            let x = coord.x + dr * angle.cos();
            let y = coord.y + dr * angle.sin();

            if x >= 0.0 && x < max_x && y >= 0.0 && y < max_y {
                return Coord::new(x, y, 0.0);
            }
        }
    }

    fn gen_grid_coord(x: f64, y: f64) -> Coord {
        let mut rng = rand::thread_rng();
        let range_x = rand::distributions::Range::new(0.0, x);
        let range_y = rand::distributions::Range::new(0.0, y);

        Coord::new(range_x.ind_sample(&mut rng), range_y.ind_sample(&mut rng), 0.0)
    }

    fn select_coordinate(coords: &Vec<Coord>) -> usize {
        let mut rng = rand::thread_rng();
        let range = rand::distributions::Range::new(0, coords.len());

        range.ind_sample(&mut rng)
    }
}

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

    #[test]
    fn create_poisson_distribution() {
        let rmin = 1.0;
        let (size_x, size_y) = (5.0, 10.0);
        let distribution = density::PoissonDistribution::new(rmin, size_x, size_y);

        // We can only assert that no coordinates are within the minimum
        // distance of each other, or outside the box.
        assert!(distribution.coords.len() > 0);

        for (i, &x1) in distribution.coords.iter().enumerate() {
            assert!(x1.x >= 0.0 && x1.x <= size_x);
            assert!(x1.y >= 0.0 && x1.y <= size_y);

            for &x2 in distribution.coords.iter().skip(i + 1) {
                assert!(Coord::distance(x1, x2) >= rmin);
            }
        }
    }

    #[test]
    fn create_blue_noise_distribution() {
        let num_points = 152;
        let (size_x, size_y) = (5.0, 10.0);
        let distribution = number::BlueNoiseDistribution::new(num_points, size_x, size_y);

        // We can only (easily) assert that we have the input number of points
        // and that none are outside of the box.
        assert_eq!(distribution.coords.len() , num_points as usize);

        for coord in distribution.coords {
            assert!(coord.x >= 0.0 && coord.x <= size_x);
            assert!(coord.y >= 0.0 && coord.y <= size_y);
        }
    }

    #[test]
    fn calculate_toroidal_distance_is_squared_and_wraps_coordinates_to_closest() {
        let coord = Coord::new(0.0, 0.0, 10.0); // skip the z value
        let other = Coord::new(1.5, 2.5, -10.0);

        let (size_x, size_y) = (2.0_f64, 3.0_f64);

        // Both coordinates are closer by wrapping around! Also, ignore the z coordinate!
        let dist = (size_x - 1.5).powi(2) + (size_y - 2.5).powi(2);

        assert_eq!(number::calc_toroidal_distance(coord, other, size_x, size_y), dist);
    }

    #[test]
    fn calculate_min_distance_squared_between_a_coordinate_and_a_set() {
        let coord = Coord::new(2.0, 2.0, 2.0);

        let candidates = vec![
            Coord::new(0.0, 0.0, 0.0), // distance squared: 2^2 + 2^2 =  8
            Coord::new(3.0, 1.0, 3.0), //                   1^2 + 1^2 =  2, minimum!
            Coord::new(5.0, 5.0, 5.0)  //                   3^2 + 3^2 = 18
        ];

        let dist = 2.0 * 1.0_f64.powi(2);

        let (size_x, size_y) = (10.0, 10.0);

        assert_eq!(number::calc_min_dist(coord, &candidates, size_x, size_y), dist);
    }
}
<|endoftext|>


<commit_before>#![feature(default_type_params)]
extern crate curl;
extern crate http;
extern crate hyper;

extern crate test;

use std::fmt::{mod, Show};
use std::from_str::from_str;
use std::io::{IoResult, MemReader};
use std::io::net::ip::{SocketAddr, ToSocketAddr};
use std::os;
use std::path::BytesContainer;

use http::connecter::Connecter;

use hyper::net;

static README: &'static [u8] = include_bin!("../README.md");

struct MockStream {
    read: MemReader,
}

impl Clone for MockStream {
    fn clone(&self) -> MockStream {
        MockStream::new()
    }
}

impl MockStream {
    fn new() -> MockStream {
        let head = b"HTTP/1.1 200 OK\r\nServer: Mock\r\n\r\n";
        let mut res = head.to_vec();
        res.push_all(README);
        MockStream {
            read: MemReader::new(res),
        }
    }
}

impl Reader for MockStream {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
        self.read.read(buf)
    }
}

impl Writer for MockStream {
    fn write(&mut self, _msg: &[u8]) -> IoResult<()> {
        // we're mocking, what do we care.
        Ok(())
    }
}

#[bench]
fn bench_mock_curl(b: &mut test::Bencher) {
    let mut cwd = os::getcwd();
    cwd.push("README.md");
    let s = format!("file://{}", cwd.container_as_str().unwrap());
    let url = s.as_slice();
    b.iter(|| {
        curl::http::handle()
            .get(url)
            .header("X-Foo", "Bar")
            .exec()
            .unwrap()
    });
}

struct Foo;

impl hyper::header::Header for Foo {
    fn header_name(_: Option<Foo>) -> &'static str {
        "x-foo"
    }
    fn parse_header(_: &[Vec<u8>]) -> Option<Foo> {
        None
    }
}

impl hyper::header::HeaderFormat for Foo {
    fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        "Bar".fmt(fmt)
    }
}

impl net::NetworkStream for MockStream {
    fn peer_name(&mut self) -> IoResult<SocketAddr> {
        Ok(from_str("127.0.0.1:1337").unwrap())
    }
}

impl net::NetworkConnector for MockStream {
    fn connect<To: ToSocketAddr>(_addr: To, _scheme: &str) -> IoResult<MockStream> {
        Ok(MockStream::new())
    }

}

#[bench]
fn bench_mock_hyper(b: &mut test::Bencher) {
    let url = "http://127.0.0.1:1337/";
    b.iter(|| {
        let mut req = hyper::client::Request::with_stream::<MockStream>(
            hyper::Get, hyper::Url::parse(url).unwrap()).unwrap();
        req.headers_mut().set(Foo);

        req
            .start().unwrap()
            .send().unwrap()
            .read_to_string().unwrap()
    });
}

impl Connecter for MockStream {
    fn connect(_addr: SocketAddr, _host: &str, _use_ssl: bool) -> IoResult<MockStream> {
        Ok(MockStream::new())
    }
}

#[bench]
fn bench_mock_http(b: &mut test::Bencher) {
    let url = "http://127.0.0.1:1337/";
    b.iter(|| {
        let mut req: http::client::RequestWriter<MockStream> = http::client::RequestWriter::new(
            http::method::Get,
            hyper::Url::parse(url).unwrap()
        ).unwrap();
        req.headers.extensions.insert("x-foo".to_string(), "Bar".to_string());
        // cant unwrap because Err contains RequestWriter, which does not implement Show
        let mut res = match req.read_response() {
            Ok(res) => res,
            Err(..) => panic!("http response failed")
        };
        res.read_to_string().unwrap();
    });
}

<commit_msg>(fix) Fix benchmarks for rust API changes.<commit_after>#![feature(default_type_params)]
extern crate curl;
extern crate http;
extern crate hyper;

extern crate test;

use std::fmt::{mod, Show};
use std::str::from_str;
use std::io::{IoResult, MemReader};
use std::io::net::ip::{SocketAddr, ToSocketAddr};
use std::os;
use std::path::BytesContainer;

use http::connecter::Connecter;

use hyper::net;

static README: &'static [u8] = include_bin!("../README.md");

struct MockStream {
    read: MemReader,
}

impl Clone for MockStream {
    fn clone(&self) -> MockStream {
        MockStream::new()
    }
}

impl MockStream {
    fn new() -> MockStream {
        let head = b"HTTP/1.1 200 OK\r\nServer: Mock\r\n\r\n";
        let mut res = head.to_vec();
        res.push_all(README);
        MockStream {
            read: MemReader::new(res),
        }
    }
}

impl Reader for MockStream {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
        self.read.read(buf)
    }
}

impl Writer for MockStream {
    fn write(&mut self, _msg: &[u8]) -> IoResult<()> {
        // we're mocking, what do we care.
        Ok(())
    }
}

#[bench]
fn bench_mock_curl(b: &mut test::Bencher) {
    let mut cwd = os::getcwd().unwrap();
    cwd.push("README.md");
    let s = format!("file://{}", cwd.container_as_str().unwrap());
    let url = s.as_slice();
    b.iter(|| {
        curl::http::handle()
            .get(url)
            .header("X-Foo", "Bar")
            .exec()
            .unwrap()
    });
}

struct Foo;

impl hyper::header::Header for Foo {
    fn header_name(_: Option<Foo>) -> &'static str {
        "x-foo"
    }
    fn parse_header(_: &[Vec<u8>]) -> Option<Foo> {
        None
    }
}

impl hyper::header::HeaderFormat for Foo {
    fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        "Bar".fmt(fmt)
    }
}

impl net::NetworkStream for MockStream {
    fn peer_name(&mut self) -> IoResult<SocketAddr> {
        Ok(from_str("127.0.0.1:1337").unwrap())
    }
}

impl net::NetworkConnector for MockStream {
    fn connect<To: ToSocketAddr>(_addr: To, _scheme: &str) -> IoResult<MockStream> {
        Ok(MockStream::new())
    }

}

#[bench]
fn bench_mock_hyper(b: &mut test::Bencher) {
    let url = "http://127.0.0.1:1337/";
    b.iter(|| {
        let mut req = hyper::client::Request::with_stream::<MockStream>(
            hyper::Get, hyper::Url::parse(url).unwrap()).unwrap();
        req.headers_mut().set(Foo);

        req
            .start().unwrap()
            .send().unwrap()
            .read_to_string().unwrap()
    });
}

impl Connecter for MockStream {
    fn connect(_addr: SocketAddr, _host: &str, _use_ssl: bool) -> IoResult<MockStream> {
        Ok(MockStream::new())
    }
}

#[bench]
fn bench_mock_http(b: &mut test::Bencher) {
    let url = "http://127.0.0.1:1337/";
    b.iter(|| {
        let mut req: http::client::RequestWriter<MockStream> = http::client::RequestWriter::new(
            http::method::Get,
            hyper::Url::parse(url).unwrap()
        ).unwrap();
        req.headers.extensions.insert("x-foo".to_string(), "Bar".to_string());
        // cant unwrap because Err contains RequestWriter, which does not implement Show
        let mut res = match req.read_response() {
            Ok(res) => res,
            Err(..) => panic!("http response failed")
        };
        res.read_to_string().unwrap();
    });
}

<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use eutil::slice_to_str;
use libc::{c_int};
use std::boxed;
use std::collections::BTreeMap;
use string::{cef_string_userfree_utf16_alloc, cef_string_userfree_utf16_free};
use string::{cef_string_utf16_set};
use types::{cef_string_map_t, cef_string_t};

//cef_string_map

#[no_mangle]
pub extern "C" fn cef_string_map_alloc() -> *mut cef_string_map_t {
    boxed::into_raw(box BTreeMap::new())
}

#[no_mangle]
pub extern "C" fn cef_string_map_size(sm: *mut cef_string_map_t) -> c_int {
    unsafe {
        if sm.is_null() { return 0; }
        (*sm).len() as c_int
    }
}

#[no_mangle]
pub extern "C" fn cef_string_map_append(sm: *mut cef_string_map_t, key: *const cef_string_t, value: *const cef_string_t) -> c_int {
    unsafe {
        if sm.is_null() { return 0; }
        slice_to_str((*key).str as *const u8, (*key).length as usize, |result| {
            let csv = cef_string_userfree_utf16_alloc();
            cef_string_utf16_set((*value).str as *const u16, (*value).length, csv, 1);
            (*sm).insert(result.to_owned(), csv);
            1
        })
    }
}

#[no_mangle]
pub extern "C" fn cef_string_map_find(sm: *mut cef_string_map_t, key: *const cef_string_t, value: *mut cef_string_t) -> c_int {
    unsafe {
        if sm.is_null() { return 0; }
        slice_to_str((*key).str as *const u8, (*key).length as usize, |result| {
            match (*sm).get(result) {
                Some(s) => {
                    cef_string_utf16_set((**s).str as *const u16, (**s).length, value, 1);
                    1
                }
                None => 0
            }
        })
    }
}

#[no_mangle]
pub extern "C" fn cef_string_map_key(sm: *mut cef_string_map_t, index: c_int, value: *mut cef_string_t) -> c_int {
    unsafe {
        if index < 0 || sm.is_null() { return 0; }
        if index as usize > (*sm).len() - 1 { return 0; }

        match (*sm).keys().nth(index as usize) {
            Some(k) => {
                cef_string_utf16_set(k.as_bytes().as_ptr() as *const u16,
                                     k.len() as u64,
                                     value,
                                     1);
                1
            },
            None => 0,
        }
    }
}

#[no_mangle]
pub extern "C" fn cef_string_map_value(sm: *mut cef_string_map_t, index: c_int, value: *mut cef_string_t) -> c_int {
    unsafe {
        if index < 0 || sm.is_null() { return 0; }
        if index as usize > (*sm).len() - 1 { return 0; }

        match (*sm).values().nth(index as usize) {
            Some(val) => {
                cef_string_utf16_set((**val).str as *const u16, (**val).length, value, 1);
                1
            },
            None => 0,
        }
    }
}

#[no_mangle]
pub extern "C" fn cef_string_map_clear(sm: *mut cef_string_map_t) {
    unsafe {
        if sm.is_null() { return; }
        for val in (*sm).values() {
            cef_string_userfree_utf16_free(*val);
        }
        (*sm).clear();
    }
}

#[no_mangle]
pub extern "C" fn cef_string_map_free(sm: *mut cef_string_map_t) {
    unsafe {
        if sm.is_null() { return; }
        cef_string_map_clear(sm);
        drop(Box::from_raw(sm));
    }
}
<commit_msg>Return the result of cef_string_utf16_set in string_map.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use eutil::slice_to_str;
use libc::{c_int};
use std::boxed;
use std::collections::BTreeMap;
use string::{cef_string_userfree_utf16_alloc, cef_string_userfree_utf16_free};
use string::{cef_string_utf16_set};
use types::{cef_string_map_t, cef_string_t};

//cef_string_map

#[no_mangle]
pub extern "C" fn cef_string_map_alloc() -> *mut cef_string_map_t {
    boxed::into_raw(box BTreeMap::new())
}

#[no_mangle]
pub extern "C" fn cef_string_map_size(sm: *mut cef_string_map_t) -> c_int {
    unsafe {
        if sm.is_null() { return 0; }
        (*sm).len() as c_int
    }
}

#[no_mangle]
pub extern "C" fn cef_string_map_append(sm: *mut cef_string_map_t, key: *const cef_string_t, value: *const cef_string_t) -> c_int {
    unsafe {
        if sm.is_null() { return 0; }
        slice_to_str((*key).str as *const u8, (*key).length as usize, |result| {
            let csv = cef_string_userfree_utf16_alloc();
            cef_string_utf16_set((*value).str as *const u16, (*value).length, csv, 1);
            (*sm).insert(result.to_owned(), csv);
            1
        })
    }
}

#[no_mangle]
pub extern "C" fn cef_string_map_find(sm: *mut cef_string_map_t, key: *const cef_string_t, value: *mut cef_string_t) -> c_int {
    unsafe {
        if sm.is_null() { return 0; }
        slice_to_str((*key).str as *const u8, (*key).length as usize, |result| {
            match (*sm).get(result) {
                Some(s) => {
                    cef_string_utf16_set((**s).str as *const u16, (**s).length, value, 1)
                }
                None => 0
            }
        })
    }
}

#[no_mangle]
pub extern "C" fn cef_string_map_key(sm: *mut cef_string_map_t, index: c_int, value: *mut cef_string_t) -> c_int {
    unsafe {
        if index < 0 || sm.is_null() { return 0; }
        if index as usize > (*sm).len() - 1 { return 0; }

        match (*sm).keys().nth(index as usize) {
            Some(k) => {
                cef_string_utf16_set(k.as_bytes().as_ptr() as *const u16,
                                     k.len() as u64,
                                     value,
                                     1)
            },
            None => 0,
        }
    }
}

#[no_mangle]
pub extern "C" fn cef_string_map_value(sm: *mut cef_string_map_t, index: c_int, value: *mut cef_string_t) -> c_int {
    unsafe {
        if index < 0 || sm.is_null() { return 0; }
        if index as usize > (*sm).len() - 1 { return 0; }

        match (*sm).values().nth(index as usize) {
            Some(val) => {
                cef_string_utf16_set((**val).str as *const u16, (**val).length, value, 1);
                1
            },
            None => 0,
        }
    }
}

#[no_mangle]
pub extern "C" fn cef_string_map_clear(sm: *mut cef_string_map_t) {
    unsafe {
        if sm.is_null() { return; }
        for val in (*sm).values() {
            cef_string_userfree_utf16_free(*val);
        }
        (*sm).clear();
    }
}

#[no_mangle]
pub extern "C" fn cef_string_map_free(sm: *mut cef_string_map_t) {
    unsafe {
        if sm.is_null() { return; }
        cef_string_map_clear(sm);
        drop(Box::from_raw(sm));
    }
}
<|endoftext|>