<commit_before>%------------------------------------------------------------%
%	Switching version of									 %
%	"Global Dynamics at the Zero Lower Bound" by			 %
%	William T. Gavin, Benjamin D. Keen, Alexander W. Richter %
%	And Nathaniel A. Throckmorton							 %
%   (Model 2: Baseline with Capital)						 %
%------------------------------------------------------------%

endogenous W "Real wages"
N "Labor Hours"
C "Consumption"
R "Nominal interest rate"
BETA "Discount factor"
PAI	"Inflation rate"
Z "TFP process"
Y "Output"
PSI	"Real Marginal Cost"
RK "Rental Rate"
I "Investment"
K "Capital"
RTAYLOR

exogenous  EZ "TFP shock" EBETA	"Discount shock"

parameters	chi, eta, sigma, betass, delta, alpha, varphi, theta, paistar, phi_pai, phi_y
zbar, rhoz, rhobeta, sigmabeta, sigmaz,nu, g_over_y, g, rbar
gam	kappa1 kappa2

parameters	k_over_y n_over_y i_over_y c_over_y

@#if exogenous_switching
	zlb_tp_1_2, zlb_tp_2_1
@#end

parameters(zlb,2) zlb_flag	% indicator

model
	# paibar = paistar;
	# omicron1 = 1/kappa1-1;
	# omicron2 = 1/kappa2-1;
	% endogenous switching imposes some disciplin:
	% you have to say how exactly you move from one regime
	% to the other and vice-versa
	%-----------------------------------------------------
	@#if ~exogenous_switching
		! zlb_tp_1_2 = 1/(1+omicron1*exp(-gam*(BETA-betass)));% 0.1;
		! zlb_tp_2_1 = 1/(1+omicron2*exp(gam*(BETA-betass)));% 0.2;
	@#end

	W = chi*N^eta*C^sigma;

	1 = R*BETA{+1}*(C/C{+1})^sigma/PAI{+1};

	1 = betass*(C/C{+1})^sigma*(RK{+1}+1-delta);

	Y = Z*K{-1}^alpha*N^(1-alpha);

	K = (1-delta)*K{-1}+I;

	PSI =W^(1-alpha)*RK^alpha*(1-alpha)^(1-alpha)*alpha^alpha/Z;

	K{-1}/N = alpha/(1-alpha)*W/RK;

	varphi*(PAI/paibar-1)*PAI/paibar = (1-theta)+theta*PSI+varphi*BETA{+1}*(C/C{+1})^sigma*(PAI{+1}/paibar-1)*PAI{+1}/paibar*Y{+1}/Y;

	C + I + g = (1-0.5*varphi*(PAI/paibar-1)^2)*Y;

	RTAYLOR = steady_state(R)*(PAI/steady_state(PAI))^phi_pai*(Y/steady_state(Y))^phi_y;

	R = zlb_flag*1+(1-zlb_flag)*RTAYLOR;  % <---	R = max(1,RTAYLOR);

	Z = zbar*(Z{-1}/zbar)^rhoz*exp(sigmaz*EZ);

	BETA = betass*(BETA{-1}/betass)^rhobeta*exp(sigmabeta*EBETA);

steady_state_model(imposed) %,unique
	PSI = (theta-1)/theta;
	Z = zbar;
	BETA =  betass;
	RK = 1/BETA-1+delta;
	rbar=paistar/BETA;
	RTAYLOR = rbar;
	R = zlb_flag*1+(1-zlb_flag)*RTAYLOR;
	PAI = BETA*R;
	W = (PSI*Z/(RK^alpha*(1-alpha)^(1-alpha)*alpha^alpha))^(1/(1-alpha));
	i_over_y = delta/Z*(alpha/(1-alpha)*W/RK)^(1-alpha);
	c_over_y = (1-g_over_y-i_over_y);
	n_over_y = ((1-alpha)/alpha*RK/W)^alpha/Z;
	Y = (W/(chi*n_over_y^eta*c_over_y^sigma))^(1/(eta+sigma));
	N = n_over_y*Y;
	I = i_over_y*Y;
	K = alpha/(1-alpha)*W/RK*N;
	C = c_over_y*Y;
	g = g_over_y*Y;

parameterization
	chi, 4.507;
	eta, 1/3;
	sigma, 1;
	betass,0.99;
	delta, 0.025;
	alpha, 0.33;
	varphi, 58.25;
	theta, 6;
	nu, 2.5;
	g_over_y,0.2;
	paistar, 1.005;
	phi_pai, 1.5;
	phi_y, 0.125;
	zbar, 1;
	rhoz, 0.8;
	rhobeta,0.8;
	sigmabeta,0.0025;
	sigmaz, 0.012;
	zlb_flag(zlb,1),0;
	zlb_flag(zlb,2),1;
	@#if exogenous_switching
		zlb_tp_1_2, 0.1;
		zlb_tp_2_1,	0.2;
	@#end
	gam, 10;
	kappa1, 0.1;
	kappa2, 0.2;
<commit_msg>nothing important<commit_after>%------------------------------------------------------------%
%	Switching version of									 %
%	"Global Dynamics at the Zero Lower Bound" by			 %
%	William T. Gavin, Benjamin D. Keen, Alexander W. Richter %
%	And Nathaniel A. Throckmorton							 %
%   (Model 2: Baseline with Capital)						 %
%------------------------------------------------------------%

endogenous W "Real wages"
N "Labor Hours"
C "Consumption"
R "Nominal interest rate"
BETA "Discount factor"
PAI	"Inflation rate"
Z "TFP process"
Y "Output"
PSI	"Real Marginal Cost"
RK "Rental Rate"
I "Investment"
K "Capital"
RTAYLOR

exogenous  EZ "TFP shock" EBETA	"Discount shock"

parameters	chi, eta, sigma, betass, delta, alpha, varphi, theta, paistar, phi_pai, phi_y
zbar, rhoz, rhobeta, sigmabeta, sigmaz,nu, g_over_y, g, rbar
gam	kappa1 kappa2

parameters	k_over_y n_over_y i_over_y c_over_y

@#if exogenous_switching
	zlb_tp_1_2, zlb_tp_2_1
@#end

parameters(zlb,2) zlb_flag	% indicator

model
	# paibar = paistar;
	# omicron1 = 1/kappa1-1;
	# omicron2 = 1/kappa2-1;
	% endogenous switching imposes some disciplin:
	% you have to say how exactly you move from one regime
	% to the other and vice-versa
	%-----------------------------------------------------
	@#if ~exogenous_switching
		! zlb_tp_1_2 = 1/(1+omicron1*exp(-gam*(BETA-betass)));% 0.1;
		! zlb_tp_2_1 = 1/(1+omicron2*exp(gam*(BETA-betass)));% 0.2;
	@#end

	W = chi*N^eta*C^sigma;

	1 = R*BETA{+1}*(C/C{+1})^sigma/PAI{+1};

	1 = betass*(C/C{+1})^sigma*(RK{+1}+1-delta);

	Y = Z*K{-1}^alpha*N^(1-alpha);

	K = (1-delta)*K{-1}+I;

	PSI =W^(1-alpha)*RK^alpha*(1-alpha)^(1-alpha)*alpha^alpha/Z;

	K{-1}/N = alpha/(1-alpha)*W/RK;

	varphi*(PAI/paibar-1)*PAI/paibar = (1-theta)+theta*PSI+varphi*BETA{+1}*(C/C{+1})^sigma*(PAI{+1}/paibar-1)*PAI{+1}/paibar*Y{+1}/Y;

	C + I + g = (1-0.5*varphi*(PAI/paibar-1)^2)*Y;

	RTAYLOR = steady_state(R)*(PAI/steady_state(PAI))^phi_pai*(Y/steady_state(Y))^phi_y;

	R = zlb_flag*1+(1-zlb_flag)*RTAYLOR;  % <---	R = max(1,RTAYLOR);

	Z = zbar*(Z{-1}/zbar)^rhoz*exp(sigmaz*EZ);

	BETA = betass*(BETA{-1}/betass)^rhobeta*exp(sigmabeta*EBETA);

steady_state_model(imposed) %,unique
	PSI = (theta-1)/theta;
	Z = zbar;
	BETA =  betass;
	RK = 1/BETA-1+delta;
	rbar=paistar/BETA;
	RTAYLOR = rbar;
	R = zlb_flag*1+(1-zlb_flag)*RTAYLOR;
	PAI = BETA*R;
	W = (PSI*Z/(RK^alpha*(1-alpha)^(1-alpha)*alpha^alpha))^(1/(1-alpha));
	i_over_y = delta/Z*(alpha/(1-alpha)*W/RK)^(1-alpha);%xx_ssmdef_1
	c_over_y = (1-g_over_y-i_over_y);
	n_over_y = ((1-alpha)/alpha*RK/W)^alpha/Z;
	Y = (W/(chi*n_over_y^eta*c_over_y^sigma))^(1/(eta+sigma));
	N = n_over_y*Y;
	I = i_over_y*Y;
	K = alpha/(1-alpha)*W/RK*N;
	C = c_over_y*Y;
	g = g_over_y*Y;

parameterization
	chi, 4.507;
	eta, 1/3;
	sigma, 1;
	betass,0.99;
	delta, 0.025;
	alpha, 0.33;
	varphi, 58.25;
	theta, 6;
	nu, 2.5;
	g_over_y,0.2;
	paistar, 1.005;
	phi_pai, 1.5;
	phi_y, 0.125;
	zbar, 1;
	rhoz, 0.8;
	rhobeta,0.8;
	sigmabeta,0.0025;
	sigmaz, 0.012;
	zlb_flag(zlb,1),0;
	zlb_flag(zlb,2),1;
	@#if exogenous_switching
		zlb_tp_1_2, 0.1;
		zlb_tp_2_1,	0.2;
	@#end
	gam, 10;
	kappa1, 0.1;
	kappa2, 0.2;
<|endoftext|>


<commit_before>// Bloom
//
// HTTP REST API caching middleware
// Copyright: 2017, Valerian Saliou <valerian@valeriansaliou.name>
// License: Mozilla Public License v2.0 (MPL v2.0)

use std::net::TcpListener;
use std::process;
use std::thread;

use super::handle::ControlHandle;
use crate::{APP_CONF, THREAD_NAME_CONTROL_CLIENT, THREAD_NAME_CONTROL_MASTER};

pub struct ControlListenBuilder;
pub struct ControlListen;

impl ControlListenBuilder {
    pub fn new() -> ControlListen {
        ControlListen {}
    }
}

impl ControlListen {
    pub fn run(&self) {
        thread::Builder::new()
            .name(THREAD_NAME_CONTROL_MASTER.to_string())
            .spawn(move || {
                match TcpListener::bind(APP_CONF.control.inet) {
                    Ok(listener) => {
                        for stream in listener.incoming() {
                            match stream {
                                Ok(stream) => {
                                    thread::Builder::new()
                                        .name(THREAD_NAME_CONTROL_CLIENT.to_string())
                                        .spawn(move || {
                                            if let Ok(peer_addr) = stream.peer_addr() {
                                                debug!("control client connecting: {}", peer_addr);
                                            }

                                            // Create client
                                            ControlHandle::client(stream);
                                        })
                                        .ok();
                                }
                                Err(err) => {
                                    warn!("error handling stream: {}", err);
                                }
                            }
                        }

                        info!("listening on tcp://{}", APP_CONF.control.inet);
                    }
                    Err(err) => {
                        error!("error binding control listener: {}", err);

                        // Exit Bloom
                        process::exit(1);
                    }
                }
            })
            .ok();
    }
}
<commit_msg>Fix<commit_after>// Bloom
//
// HTTP REST API caching middleware
// Copyright: 2017, Valerian Saliou <valerian@valeriansaliou.name>
// License: Mozilla Public License v2.0 (MPL v2.0)

use std::net::TcpListener;
use std::process;
use std::thread;

use super::handle::ControlHandle;
use crate::{APP_CONF, THREAD_NAME_CONTROL_CLIENT, THREAD_NAME_CONTROL_MASTER};

pub struct ControlListenBuilder;
pub struct ControlListen;

impl ControlListenBuilder {
    pub fn new() -> ControlListen {
        ControlListen {}
    }
}

impl ControlListen {
    pub fn run(&self) {
        thread::Builder::new()
            .name(THREAD_NAME_CONTROL_MASTER.to_string())
            .spawn(move || {
                match TcpListener::bind(APP_CONF.control.inet) {
                    Ok(listener) => {
                        info!("listening on tcp://{}", APP_CONF.control.inet);

                        for stream in listener.incoming() {
                            match stream {
                                Ok(stream) => {
                                    thread::Builder::new()
                                        .name(THREAD_NAME_CONTROL_CLIENT.to_string())
                                        .spawn(move || {
                                            if let Ok(peer_addr) = stream.peer_addr() {
                                                debug!("control client connecting: {}", peer_addr);
                                            }

                                            // Create client
                                            ControlHandle::client(stream);
                                        })
                                        .ok();
                                }
                                Err(err) => {
                                    warn!("error handling stream: {}", err);
                                }
                            }
                        }
                    }
                    Err(err) => {
                        error!("error binding control listener: {}", err);

                        // Exit Bloom
                        process::exit(1);
                    }
                }
            })
            .ok();
    }
}
<|endoftext|>


<commit_before>extern crate crossbeam;
#[macro_use] extern crate version;
extern crate walkdir;

use std::env;
use std::process::exit;
use std::process::Command;
use std::process::Stdio;
use std::io::ErrorKind;

use walkdir::WalkDir;
use crossbeam::*;

fn help(cmds: Vec<String>) {
    println!(r#"

     _
    (_)_ __ ___   __ _  __ _
    | | '_ \` _ \/ _\`|/ _\`|
    | | | | | | | (_| | (_| |
    |_|_| |_| |_|\__,_|\__, |
                       |___/
    -------------------------

    Usage: imag [--version | --versions | -h | --help] <command> <args...>

    imag - the personal information management suite for the commandline

    imag is a PIM suite for the commandline. It consists of several commands,
    called "modules". Each module implements one PIM aspect and all of these
    modules can be used independently.

    Available commands:
    "#);

    for cmd in cmds.iter() {
        println!("\t{}", cmd);
    }

    println!(r#"

    Call a command with 'imag <command> <args>'
    Each command can be called with "--help" to get the respective helptext.

    Please visit https://github.com/matthiasbeyer/imag to view the source code,
    follow the development of imag or maybe even contribute to imag.

    imag is free software. It is released under the terms of LGPLv2.1

    (c) 2016 Matthias Beyer and contributors"#);
}

fn get_commands() -> Vec<String> {
    let path = env::var("PATH");
    if path.is_err() {
        println!("PATH error: {:?}", path);
        exit(1);
    }
    let pathelements = path.unwrap();
    let pathelements = pathelements.split(":");

    let joinhandles : Vec<ScopedJoinHandle<Vec<String>>> = pathelements
        .map(|elem| {
            crossbeam::scope(|scope| {
                scope.spawn(|| {
                    WalkDir::new(elem)
                        .max_depth(1)
                        .into_iter()
                        .filter(|path| {
                            match path {
                                &Ok(ref p) => p.file_name()
                                    .to_str()
                                    .map_or(false, |filename| filename.starts_with("imag-")),
                                &Err(_)   => false,
                            }
                        })
                        .filter_map(|x| x.ok())
                        .filter_map(|path| {
                           path.file_name()
                               .to_str()
                               .map(String::from)
                        })
                        .collect()
                })
            })
        })
        .collect();

    let mut execs = vec![];
    for joinhandle in joinhandles.into_iter() {
        let mut v = joinhandle.join();
        execs.append(&mut v);
    }

    execs
}

fn find_command() -> Option<String> {
    env::args().skip(1).filter(|x| !x.starts_with("-")).next()
}

fn find_args(command: &str) -> Vec<String> {
    env::args()
        .skip(1)
        .position(|e| e == command)
        .map(|pos| env::args().skip(pos + 2).collect::<Vec<String>>())
        .unwrap_or(vec![])
}

fn main() {
    let commands  = get_commands();
    let mut args  = env::args();
    let _         = args.next();
    let first_arg = match find_command() {
        Some(s) => s,
        None    => {
            help(commands);
            exit(0);
        },
    };

    match &first_arg[..] {
        "--help" | "-h" => {
            help(commands);
            exit(0);
        },

        "--version"  => println!("imag {}", &version!()[..]),

        "--versions" => {
            let mut result = vec![];
            for command in commands.iter() {
                result.push(crossbeam::scope(|scope| {
                    scope.spawn(|| {
                        let v = Command::new(command).arg("--version").output();
                        match v {
                            Ok(v) => match String::from_utf8(v.stdout) {
                                Ok(s) => format!("{} -> {}", command, s),
                                Err(e) => format!("Failed calling {} -> {:?}", command, e),
                            },
                            Err(e) => format!("Failed calling {} -> {:?}", command, e),
                        }
                    })
                }))
            }

            for versionstring in result.into_iter().map(|handle| handle.join()) {
                println!("{}", versionstring);
            }
        },

        s => {
            match Command::new(format!("imag-{}", s))
                .stdin(Stdio::inherit())
                .stdout(Stdio::inherit())
                .stderr(Stdio::inherit())
                .args(&find_args(s)[..])
                .spawn()
                .and_then(|mut handle| handle.wait())
            {
                Ok(exit_status) => {
                    if !exit_status.success() {
                        println!("{} exited with non-zero exit code", s);
                        exit(exit_status.code().unwrap_or(42));
                    }
                },

                Err(e) => {
                    match e.kind() {
                        ErrorKind::NotFound => {
                            println!("No such command: 'imag-{}'", s);
                            exit(2);
                        },
                        ErrorKind::PermissionDenied => {
                            println!("No permission to execute: 'imag-{}'", s);
                            exit(1);
                        },
                        _ => {
                            println!("Error spawning: {:?}", e);
                            exit(1337);
                        }
                    }
                }
            }

        },
    }
}
<commit_msg>Remove dash from command listing<commit_after>extern crate crossbeam;
#[macro_use] extern crate version;
extern crate walkdir;

use std::env;
use std::process::exit;
use std::process::Command;
use std::process::Stdio;
use std::io::ErrorKind;

use walkdir::WalkDir;
use crossbeam::*;

fn help(cmds: Vec<String>) {
    println!(r#"

     _
    (_)_ __ ___   __ _  __ _
    | | '_ \` _ \/ _\`|/ _\`|
    | | | | | | | (_| | (_| |
    |_|_| |_| |_|\__,_|\__, |
                       |___/
    -------------------------

    Usage: imag [--version | --versions | -h | --help] <command> <args...>

    imag - the personal information management suite for the commandline

    imag is a PIM suite for the commandline. It consists of several commands,
    called "modules". Each module implements one PIM aspect and all of these
    modules can be used independently.

    Available commands:
    "#);

    for cmd in cmds.iter() {
        println!("\t{}", cmd);
    }

    println!(r#"

    Call a command with 'imag <command> <args>'
    Each command can be called with "--help" to get the respective helptext.

    Please visit https://github.com/matthiasbeyer/imag to view the source code,
    follow the development of imag or maybe even contribute to imag.

    imag is free software. It is released under the terms of LGPLv2.1

    (c) 2016 Matthias Beyer and contributors"#);
}

fn get_commands() -> Vec<String> {
    let path = env::var("PATH");
    if path.is_err() {
        println!("PATH error: {:?}", path);
        exit(1);
    }
    let pathelements = path.unwrap();
    let pathelements = pathelements.split(":");

    let joinhandles : Vec<ScopedJoinHandle<Vec<String>>> = pathelements
        .map(|elem| {
            crossbeam::scope(|scope| {
                scope.spawn(|| {
                    WalkDir::new(elem)
                        .max_depth(1)
                        .into_iter()
                        .filter(|path| {
                            match path {
                                &Ok(ref p) => p.file_name()
                                    .to_str()
                                    .map_or(false, |filename| filename.starts_with("imag-")),
                                &Err(_)   => false,
                            }
                        })
                        .filter_map(|x| x.ok())
                        .filter_map(|path| {
                           path.file_name()
                               .to_str()
                               .and_then(|s| s.splitn(2, "-").nth(1).map(|s| format!("imag {}", s)))
                        })
                        .collect()
                })
            })
        })
        .collect();

    let mut execs = vec![];
    for joinhandle in joinhandles.into_iter() {
        let mut v = joinhandle.join();
        execs.append(&mut v);
    }

    execs
}

fn find_command() -> Option<String> {
    env::args().skip(1).filter(|x| !x.starts_with("-")).next()
}

fn find_args(command: &str) -> Vec<String> {
    env::args()
        .skip(1)
        .position(|e| e == command)
        .map(|pos| env::args().skip(pos + 2).collect::<Vec<String>>())
        .unwrap_or(vec![])
}

fn main() {
    let commands  = get_commands();
    let mut args  = env::args();
    let _         = args.next();
    let first_arg = match find_command() {
        Some(s) => s,
        None    => {
            help(commands);
            exit(0);
        },
    };

    match &first_arg[..] {
        "--help" | "-h" => {
            help(commands);
            exit(0);
        },

        "--version"  => println!("imag {}", &version!()[..]),

        "--versions" => {
            let mut result = vec![];
            for command in commands.iter() {
                result.push(crossbeam::scope(|scope| {
                    scope.spawn(|| {
                        let v = Command::new(command).arg("--version").output();
                        match v {
                            Ok(v) => match String::from_utf8(v.stdout) {
                                Ok(s) => format!("{} -> {}", command, s),
                                Err(e) => format!("Failed calling {} -> {:?}", command, e),
                            },
                            Err(e) => format!("Failed calling {} -> {:?}", command, e),
                        }
                    })
                }))
            }

            for versionstring in result.into_iter().map(|handle| handle.join()) {
                println!("{}", versionstring);
            }
        },

        s => {
            match Command::new(format!("imag-{}", s))
                .stdin(Stdio::inherit())
                .stdout(Stdio::inherit())
                .stderr(Stdio::inherit())
                .args(&find_args(s)[..])
                .spawn()
                .and_then(|mut handle| handle.wait())
            {
                Ok(exit_status) => {
                    if !exit_status.success() {
                        println!("{} exited with non-zero exit code", s);
                        exit(exit_status.code().unwrap_or(42));
                    }
                },

                Err(e) => {
                    match e.kind() {
                        ErrorKind::NotFound => {
                            println!("No such command: 'imag-{}'", s);
                            exit(2);
                        },
                        ErrorKind::PermissionDenied => {
                            println!("No permission to execute: 'imag-{}'", s);
                            exit(1);
                        },
                        _ => {
                            println!("Error spawning: {:?}", e);
                            exit(1337);
                        }
                    }
                }
            }

        },
    }
}
<|endoftext|>


<commit_before>use std::hash::Hash;

use utils::HashIter;

pub struct CountMinSketch {
    table: Vec<usize>,
    w: usize,
    d: usize,
}

impl CountMinSketch {
    pub fn with_params(w: usize, d: usize) -> CountMinSketch {
        let table = vec![0; w.checked_mul(d).unwrap()];
        CountMinSketch {
            table: table,
            w: w,
            d: d,
        }
    }

    pub fn add<T>(&mut self, obj: &T)
    where
        T: Hash,
    {
        self.add_n(&obj, 1)
    }

    pub fn add_n<T>(&mut self, obj: &T, n: usize)
    where
        T: Hash,
    {
        for (i, pos) in HashIter::new(self.w, self.d, obj).enumerate() {
            let x = i * self.w + pos;
            self.table[x] += n;
        }
    }

    pub fn query_point<T>(&self, obj: &T) -> usize
    where
        T: Hash,
    {
        HashIter::new(self.w, self.d, obj)
            .enumerate()
            .map(|(i, pos)| i * self.w + pos)
            .map(|x| self.table[x])
            .min()
            .unwrap()
    }
}

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

    #[test]
    fn empty() {
        let cms = CountMinSketch::with_params(10, 10);
        assert_eq!(cms.query_point(&1), 0);
    }

    #[test]
    fn add_1() {
        let mut cms = CountMinSketch::with_params(10, 10);

        cms.add(&1);
        assert_eq!(cms.query_point(&1), 1);
        assert_eq!(cms.query_point(&2), 0);
    }

    #[test]
    fn add_2() {
        let mut cms = CountMinSketch::with_params(10, 10);

        cms.add(&1);
        cms.add(&1);
        assert_eq!(cms.query_point(&1), 2);
        assert_eq!(cms.query_point(&2), 0);
    }

    #[test]
    fn add_2_1() {
        let mut cms = CountMinSketch::with_params(10, 10);

        cms.add(&1);
        cms.add(&2);
        cms.add(&1);
        assert_eq!(cms.query_point(&1), 2);
        assert_eq!(cms.query_point(&2), 1);
        assert_eq!(cms.query_point(&3), 0);
    }
}
<commit_msg>countminsketch: use checked_add<commit_after>use std::hash::Hash;

use utils::HashIter;

pub struct CountMinSketch {
    table: Vec<usize>,
    w: usize,
    d: usize,
}

impl CountMinSketch {
    pub fn with_params(w: usize, d: usize) -> CountMinSketch {
        let table = vec![0; w.checked_mul(d).unwrap()];
        CountMinSketch {
            table: table,
            w: w,
            d: d,
        }
    }

    pub fn add<T>(&mut self, obj: &T)
    where
        T: Hash,
    {
        self.add_n(&obj, 1)
    }

    pub fn add_n<T>(&mut self, obj: &T, n: usize)
    where
        T: Hash,
    {
        for (i, pos) in HashIter::new(self.w, self.d, obj).enumerate() {
            let x = i * self.w + pos;
            self.table[x] = self.table[x].checked_add(n).unwrap();
        }
    }

    pub fn query_point<T>(&self, obj: &T) -> usize
    where
        T: Hash,
    {
        HashIter::new(self.w, self.d, obj)
            .enumerate()
            .map(|(i, pos)| i * self.w + pos)
            .map(|x| self.table[x])
            .min()
            .unwrap()
    }
}

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

    #[test]
    fn empty() {
        let cms = CountMinSketch::with_params(10, 10);
        assert_eq!(cms.query_point(&1), 0);
    }

    #[test]
    fn add_1() {
        let mut cms = CountMinSketch::with_params(10, 10);

        cms.add(&1);
        assert_eq!(cms.query_point(&1), 1);
        assert_eq!(cms.query_point(&2), 0);
    }

    #[test]
    fn add_2() {
        let mut cms = CountMinSketch::with_params(10, 10);

        cms.add(&1);
        cms.add(&1);
        assert_eq!(cms.query_point(&1), 2);
        assert_eq!(cms.query_point(&2), 0);
    }

    #[test]
    fn add_2_1() {
        let mut cms = CountMinSketch::with_params(10, 10);

        cms.add(&1);
        cms.add(&2);
        cms.add(&1);
        assert_eq!(cms.query_point(&1), 2);
        assert_eq!(cms.query_point(&2), 1);
        assert_eq!(cms.query_point(&3), 0);
    }
}
<|endoftext|>


<commit_before>/// Value that either holds a single A or B, or both.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum EitherOrBoth<A, B> {
    /// Both values are present.
    Both(A, B),
    /// Only the left value of type `A` is present.
    Left(A),
    /// Only the right value of type `B` is present.
    Right(B),
}
<commit_msg>Add some convenience methods to EitherOrBoth<commit_after>use EitherOrBoth::*;

/// Value that either holds a single A or B, or both.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum EitherOrBoth<A, B> {
    /// Both values are present.
    Both(A, B),
    /// Only the left value of type `A` is present.
    Left(A),
    /// Only the right value of type `B` is present.
    Right(B),
}

impl<A, B> EitherOrBoth<A, B> {
    /// If `Left`, or `Both`, return true, otherwise, return false.
    pub fn has_left(&self) -> bool {
        self.as_ref().left().is_some()
    }

    /// If `Right`, or `Both`, return true, otherwise, return false.
    pub fn has_right(&self) -> bool {
        self.as_ref().right().is_some()
    }

    /// If `Left`, or `Both`, return `Some` with the left value, otherwise, return `None`.
    pub fn left(self) -> Option<A> {
        match self {
            Left(left) | Both(left, _) => Some(left),
            _ => None
        }
    }

    /// If `Right`, or `Both`, return `Some` with the right value, otherwise, return `None`.
    pub fn right(self) -> Option<B> {
        match self {
            Right(right) | Both(_, right) => Some(right),
            _ => None
        }
    }

    /// Converts from `&EitherOrBoth<A, B>` to `EitherOrBoth<&A, &B>`.
    pub fn as_ref(&self) -> EitherOrBoth<&A, &B> {
        match *self {
            Left(ref left) => Left(left),
            Right(ref right) => Right(right),
            Both(ref left, ref right) => Both(left, right),
        }
    }

    /// Converts from `&mut EitherOrBoth<A, B>` to `EitherOrBoth<&mut A, &mut B>`.
    pub fn as_mut(&mut self) -> EitherOrBoth<&mut A, &mut B> {
        match *self {
            Left(ref mut left) => Left(left),
            Right(ref mut right) => Right(right),
            Both(ref mut left, ref mut right) => Both(left, right),
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (C) 2015  Jonas Pollok <jonas.p@gmail.com>

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.

// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

use std::fmt;
use std::str::FromStr;

use matching::Match;
use binding::Bind;

mod parser;

// TODO: implement equality check
/// The `Expression` type.
#[unstable(feature = "ers1")]
pub enum Expression {
    /// Contains a boxed slice of `Expressions`
    List(Vec<Expression>),
    /// Represents a string expression
    Atom(String),
    /// An unnamed pattern matching a single expression
    Blank,
    /// An unnamed pattern matching one or more expressions
    BlankSeq,
    /// An unnamed pattern matching zero or more expressions
    BlankNullSeq,
    /// A named pattern matching a single expression
    Pattern(String),
    /// A named pattern matching one or more expressions
    PatternSeq(String),
    /// A named pattern matching zero or more expressions
    PatternNullSeq(String),
}

#[unstable(feature = "ers1")]
impl Expression {
    /// Matches the `Expression` with a pattern and if successful binds returns
    /// the bound template.
    ///
    /// # Example
    /// ```
    /// use ers::Expression;
    ///
    /// let expr = "(x z)".parse::<Expression>().unwrap();
    /// let pattern = "(x a_)".parse::<Expression>().unwrap();
    /// let template = "(y a)".parse::<Expression>().unwrap();
    ///
    /// expr.replace(&pattern, template).unwrap(); // => (y z)
    /// ```
    #[unstable(feature = "ers1")]
    pub fn replace(&self, pattern: &Expression, template: Expression) -> Option<Expression> {
        self.match_pattern(pattern).map(move |bs| template.bind(&bs))
    }

    /// Replaces all expressions and subexpressions with the provided pattern
    /// and replaces it by the bound template
    ///
    /// # Example
    /// ```
    /// use ers::Expression;
    ///
    /// let expr = "((x r) (x s))".parse::<Expression>().unwrap();
    /// let pattern = "(x a_)".parse::<Expression>().unwrap();
    /// let template = "(y a)".parse::<Expression>().unwrap();
    ///
    /// expr.replace_all(&pattern, template); // => ((y r) (y s))
    /// ```
    #[unstable(feature = "ers1")]
    pub fn replace_all(&self, pattern: &Expression, template: Expression) -> Expression {
        let (e, _) = self.replace_rec(pattern, template);
        e
    }

    /// Replaces all expressions and subexpression repeatedly until the
    /// expression does not change anymore.
    /// The hardcoded limit is 1000 repetitions. The function panics if the
    /// limit is reached.
    ///
    /// # Example
    /// ```
    /// use ers::Expression;
    ///
    /// let expr = "(x (x (x z)))".parse::<Expression>().unwrap();
    /// let pattern = "(x a_)".parse::<Expression>().unwrap();
    /// let template = "(y a)".parse::<Expression>().unwrap();
    ///
    /// expr.replace_repeated(&pattern, template); // => (y (y (y z)))
    /// ```
    #[unstable(feature = "experimental")]
    pub fn replace_repeated(&self, pattern: &Expression, template: Expression) -> Expression {
        // TODO: set limit as global constant
        let mut limit = 1000;
        let mut expr = self.clone();
        while limit >= 0 {
            limit -= 1;
            let (new_expr, replaced) = expr.replace_rec(pattern, template.clone());
            if !replaced {
                return new_expr;
            }
            expr = new_expr;
        }
        // TODO: panic might not be the right thing to do
        panic!("replacement limit reached!");
    }

    fn replace_rec(&self, pattern: &Expression, template: Expression) -> (Expression, bool) {
        match self.match_pattern(pattern) {
            None => {
                match self {
                    &Expression::List(ref es) => {
                        let mut v: Vec<Expression> = Vec::new();
                        let mut replaced = false;
                        for e in es.iter() {
                            let (new_e, r) = e.replace_rec(pattern, template.clone());
                            if r {
                                replaced = true;
                            }
                            v.push(new_e);
                        }
                        (Expression::List(v), replaced)
                    }
                    _ => (self.clone(), false) // not replaced
                }
            }
            Some(bs) => (template.bind(&bs), true) // replaced
        }
    }
}

impl Clone for Expression {
    fn clone(&self) -> Self {
        match self {
            &Expression::List(ref es) => {
                let mut v: Vec<Expression> = Vec::new();
                for e in es.iter() {
                    v.push(e.clone());
                }
                Expression::List(v)
            }
            &Expression::Atom(ref s) => {
                Expression::Atom(s.clone())
            }
            &Expression::Blank => {
                Expression::Blank
            }
            &Expression::BlankSeq => {
                Expression::BlankSeq
            }
            &Expression::BlankNullSeq => {
                Expression::BlankNullSeq
            }
            &Expression::Pattern(ref s) => {
                Expression::Pattern(s.clone())
            }
            &Expression::PatternSeq(ref s) => {
                Expression::PatternSeq(s.clone())
            }
            &Expression::PatternNullSeq(ref s) => {
                Expression::PatternNullSeq(s.clone())
            }
        }
    }
}

impl fmt::Debug for Expression {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Expression::Atom(ref s) => { write!(f, "{}", s) }
            Expression::List(ref es) => {
                let mut s = String::new();
                for i in (0..es.len()) {
                    let f = format!("{:?}", es[i]);
                    s = s + &f[];
                    if i != es.len() - 1 {
                        s.push(' ');
                    }
                }
                write!(f, "({})", s)
            }
            Expression::Blank => { write!(f, "_") }
            Expression::BlankSeq => { write!(f, "__") }
            Expression::BlankNullSeq => { write!(f, "___") }
            Expression::Pattern(ref s) => { write!(f, "{}_", s)}
            Expression::PatternSeq(ref s) => { write!(f, "{}__", s)}
            Expression::PatternNullSeq(ref s) => { write!(f, "{}___", s)}
        }
    }
}

impl FromStr for Expression {
    type Err = parser::ParserError;
    fn from_str(s: &str) -> Result<Expression, parser::ParserError> {
        let mut parser = parser::Parser::new(s.chars());

        parser.parse()
    }
}

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

    #[test]
    fn debug() {
        let a = Expression::Atom("a".to_string());
        let b = Expression::Atom("b".to_string());
        let c = Expression::Atom("c".to_string());
        let d = Expression::Atom("d".to_string());

        let ls = Expression::List(vec![c, d]);

        let expr = Expression::List(vec![a, b, ls]);

        assert_eq!(format!("{:?}", expr), "(a b (c d))");
    }

    #[test]
    fn parse() {
        let expr = "(a b (c d))".parse::<Expression>();
        assert_eq!(format!("{:?}", expr.unwrap()), "(a b (c d))");
    }

    #[test]
    fn replace() {
        let expr = "(x z)".parse::<Expression>().unwrap();
        let pattern = "(x a_)".parse::<Expression>().unwrap();
        let template = "(y a)".parse::<Expression>().unwrap();

        let res = expr.replace(&pattern, template).unwrap();

        assert_eq!(format!("{:?}", res), "(y z)");
    }

    #[test]
    fn replace_all() {
        let expr = "((x r) (x s))".parse::<Expression>().unwrap();
        let pattern = "(x a_)".parse::<Expression>().unwrap();
        let template = "(y a)".parse::<Expression>().unwrap();

        let res = expr.replace_all(&pattern, template);

        assert_eq!(format!("{:?}", res), "((y r) (y s))");
    }

    #[test]
    fn replace_repeated() {
        let expr = "(x (x (x z)))".parse::<Expression>().unwrap();
        let pattern = "(x a_)".parse::<Expression>().unwrap();
        let template = "(y a)".parse::<Expression>().unwrap();

        let res = expr.replace_repeated(&pattern, template);

        assert_eq!(format!("{:?}", res), "(y (y (y z)))");
    }
}
<commit_msg>no need to call iter() in for loops over vec<commit_after>// Copyright (C) 2015  Jonas Pollok <jonas.p@gmail.com>

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.

// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

use std::fmt;
use std::str::FromStr;

use matching::Match;
use binding::Bind;

mod parser;

// TODO: implement equality check
/// The `Expression` type.
#[unstable(feature = "ers1")]
pub enum Expression {
    /// Contains a boxed slice of `Expressions`
    List(Vec<Expression>),
    /// Represents a string expression
    Atom(String),
    /// An unnamed pattern matching a single expression
    Blank,
    /// An unnamed pattern matching one or more expressions
    BlankSeq,
    /// An unnamed pattern matching zero or more expressions
    BlankNullSeq,
    /// A named pattern matching a single expression
    Pattern(String),
    /// A named pattern matching one or more expressions
    PatternSeq(String),
    /// A named pattern matching zero or more expressions
    PatternNullSeq(String),
}

#[unstable(feature = "ers1")]
impl Expression {
    /// Matches the `Expression` with a pattern and if successful binds returns
    /// the bound template.
    ///
    /// # Example
    /// ```
    /// use ers::Expression;
    ///
    /// let expr = "(x z)".parse::<Expression>().unwrap();
    /// let pattern = "(x a_)".parse::<Expression>().unwrap();
    /// let template = "(y a)".parse::<Expression>().unwrap();
    ///
    /// expr.replace(&pattern, template).unwrap(); // => (y z)
    /// ```
    #[unstable(feature = "ers1")]
    pub fn replace(&self, pattern: &Expression, template: Expression) -> Option<Expression> {
        self.match_pattern(pattern).map(move |bs| template.bind(&bs))
    }

    /// Replaces all expressions and subexpressions with the provided pattern
    /// and replaces it by the bound template
    ///
    /// # Example
    /// ```
    /// use ers::Expression;
    ///
    /// let expr = "((x r) (x s))".parse::<Expression>().unwrap();
    /// let pattern = "(x a_)".parse::<Expression>().unwrap();
    /// let template = "(y a)".parse::<Expression>().unwrap();
    ///
    /// expr.replace_all(&pattern, template); // => ((y r) (y s))
    /// ```
    #[unstable(feature = "ers1")]
    pub fn replace_all(&self, pattern: &Expression, template: Expression) -> Expression {
        let (e, _) = self.replace_rec(pattern, template);
        e
    }

    /// Replaces all expressions and subexpression repeatedly until the
    /// expression does not change anymore.
    /// The hardcoded limit is 1000 repetitions. The function panics if the
    /// limit is reached.
    ///
    /// # Example
    /// ```
    /// use ers::Expression;
    ///
    /// let expr = "(x (x (x z)))".parse::<Expression>().unwrap();
    /// let pattern = "(x a_)".parse::<Expression>().unwrap();
    /// let template = "(y a)".parse::<Expression>().unwrap();
    ///
    /// expr.replace_repeated(&pattern, template); // => (y (y (y z)))
    /// ```
    #[unstable(feature = "experimental")]
    pub fn replace_repeated(&self, pattern: &Expression, template: Expression) -> Expression {
        // TODO: set limit as global constant
        let mut limit = 1000;
        let mut expr = self.clone();
        while limit >= 0 {
            limit -= 1;
            let (new_expr, replaced) = expr.replace_rec(pattern, template.clone());
            if !replaced {
                return new_expr;
            }
            expr = new_expr;
        }
        // TODO: panic might not be the right thing to do
        panic!("replacement limit reached!");
    }

    fn replace_rec(&self, pattern: &Expression, template: Expression) -> (Expression, bool) {
        match self.match_pattern(pattern) {
            None => {
                match self {
                    &Expression::List(ref es) => {
                        let mut v: Vec<Expression> = Vec::new();
                        let mut replaced = false;
                        for e in es {
                            let (new_e, r) = e.replace_rec(pattern, template.clone());
                            if r {
                                replaced = true;
                            }
                            v.push(new_e);
                        }
                        (Expression::List(v), replaced)
                    }
                    _ => (self.clone(), false) // not replaced
                }
            }
            Some(bs) => (template.bind(&bs), true) // replaced
        }
    }
}

impl Clone for Expression {
    fn clone(&self) -> Self {
        match self {
            &Expression::List(ref es) => {
                let mut v: Vec<Expression> = Vec::new();
                for e in es {
                    v.push(e.clone());
                }
                Expression::List(v)
            }
            &Expression::Atom(ref s) => {
                Expression::Atom(s.clone())
            }
            &Expression::Blank => {
                Expression::Blank
            }
            &Expression::BlankSeq => {
                Expression::BlankSeq
            }
            &Expression::BlankNullSeq => {
                Expression::BlankNullSeq
            }
            &Expression::Pattern(ref s) => {
                Expression::Pattern(s.clone())
            }
            &Expression::PatternSeq(ref s) => {
                Expression::PatternSeq(s.clone())
            }
            &Expression::PatternNullSeq(ref s) => {
                Expression::PatternNullSeq(s.clone())
            }
        }
    }
}

impl fmt::Debug for Expression {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Expression::Atom(ref s) => { write!(f, "{}", s) }
            Expression::List(ref es) => {
                let mut s = String::new();
                for i in (0..es.len()) {
                    let f = format!("{:?}", es[i]);
                    s = s + &f[];
                    if i != es.len() - 1 {
                        s.push(' ');
                    }
                }
                write!(f, "({})", s)
            }
            Expression::Blank => { write!(f, "_") }
            Expression::BlankSeq => { write!(f, "__") }
            Expression::BlankNullSeq => { write!(f, "___") }
            Expression::Pattern(ref s) => { write!(f, "{}_", s)}
            Expression::PatternSeq(ref s) => { write!(f, "{}__", s)}
            Expression::PatternNullSeq(ref s) => { write!(f, "{}___", s)}
        }
    }
}

impl FromStr for Expression {
    type Err = parser::ParserError;
    fn from_str(s: &str) -> Result<Expression, parser::ParserError> {
        let mut parser = parser::Parser::new(s.chars());

        parser.parse()
    }
}

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

    #[test]
    fn debug() {
        let a = Expression::Atom("a".to_string());
        let b = Expression::Atom("b".to_string());
        let c = Expression::Atom("c".to_string());
        let d = Expression::Atom("d".to_string());

        let ls = Expression::List(vec![c, d]);

        let expr = Expression::List(vec![a, b, ls]);

        assert_eq!(format!("{:?}", expr), "(a b (c d))");
    }

    #[test]
    fn parse() {
        let expr = "(a b (c d))".parse::<Expression>();
        assert_eq!(format!("{:?}", expr.unwrap()), "(a b (c d))");
    }

    #[test]
    fn replace() {
        let expr = "(x z)".parse::<Expression>().unwrap();
        let pattern = "(x a_)".parse::<Expression>().unwrap();
        let template = "(y a)".parse::<Expression>().unwrap();

        let res = expr.replace(&pattern, template).unwrap();

        assert_eq!(format!("{:?}", res), "(y z)");
    }

    #[test]
    fn replace_all() {
        let expr = "((x r) (x s))".parse::<Expression>().unwrap();
        let pattern = "(x a_)".parse::<Expression>().unwrap();
        let template = "(y a)".parse::<Expression>().unwrap();

        let res = expr.replace_all(&pattern, template);

        assert_eq!(format!("{:?}", res), "((y r) (y s))");
    }

    #[test]
    fn replace_repeated() {
        let expr = "(x (x (x z)))".parse::<Expression>().unwrap();
        let pattern = "(x a_)".parse::<Expression>().unwrap();
        let template = "(y a)".parse::<Expression>().unwrap();

        let res = expr.replace_repeated(&pattern, template);

        assert_eq!(format!("{:?}", res), "(y (y (y z)))");
    }
}
<|endoftext|>


<commit_before>
use num::*;
use mat::Mat4;
use vec::Vec3;
use std::ops::*;

#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(C)]
pub struct Quaternion<T: Num + Float + Copy> {
    pub x: T,
    pub y: T,
    pub w: T,
    pub z: T,
}

impl<T: Num + Float + Copy> Default for Quaternion<T> {
    fn default() -> Quaternion<T> {
        Quaternion::new()
    }
}

impl<T: Num + Float + Copy> Quaternion<T> {
    /// Creates a new identity quaternion
    pub fn new() -> Quaternion<T> {
        Quaternion {
            x: T::zero(),
            y: T::zero(),
            z: T::zero(),
            w: T::one(),
        }
    }

    /// Creates a quaternion representing a counterclockwise rotation of `angle` radians around the
    /// given axis. This function normalizes the axis, but if the axis is `(0, 0, 0)` the quaternion
    /// will have its `x`, `y` and `z` fields set to 0.
    pub fn rotation(angle: T, axis: Vec3<T>) -> Quaternion<T> {
        let axis = axis.normalize();
        let angle = angle / (T::one() + T::one());
        let (sin, cos) = angle.sin_cos();
        Quaternion {
            x: axis.x*sin,
            y: axis.y*sin,
            z: axis.z*sin,
            w: cos,
        }
    }

    /// Calculates the length of this quaternion, raised to the power of two. Note that this is
    /// cheaper than computing the actual length.
    pub fn len_sqr(&self) -> T {
        self.x*self.x + self.y*self.y + self.z*self.z + self.w*self.w
    }

    /// Calculates the length of this quaternion.
    pub fn len(&self) -> T {
        (self.x*self.x + self.y*self.y + self.z*self.z + self.w*self.w).sqrt()
    }

    /// Normalizes this quaternion, returning a new quaternion with length 1.
    pub fn normalize(&self) -> Quaternion<T> {
        *self / self.len()
    }
}

// Quaternion vector multiplication
impl<T: Num + Float + Copy> Mul<Vec3<T>> for Quaternion<T> {
    type Output = Vec3<T>;
    fn mul(self, vec: Vec3<T>) -> Vec3<T> {
        let one = T::one();
        let two = one + one;

        let a11 = one - two*self.y*self.y - two*self.z*self.z;
        let a12 = two*self.x*self.y - two*self.z*self.w;
        let a13 = two*self.x*self.z + two*self.y*self.w;

        let a21 = two*self.x*self.y + two*self.w*self.z;
        let a22 = one - two*self.x*self.x - two*self.z*self.z;
        let a23 = two*self.y*self.z - two*self.w*self.x;

        let a31 = two*self.x*self.z - two*self.w*self.y;
        let a32 = two*self.y*self.z + two*self.w*self.x;
        let a33 = one - two*self.x*self.x - two*self.y*self.y;

        Vec3 {
            x: vec.x*a11 + vec.y*a12 + vec.z*a13,
            y: vec.x*a21 + vec.y*a22 + vec.z*a23,
            z: vec.x*a31 + vec.y*a32 + vec.z*a33,
        }
    }
}

// Quaternion quaternion multiplication
impl<T: Num + Float + Copy> Mul for Quaternion<T> {
    type Output = Self;
    fn mul(self, other: Quaternion<T>) -> Self {
        Quaternion {
            x: self.w*other.x + self.x*other.w + self.y*other.z - self.z*other.y,
            y: self.w*other.y + self.y*other.w + self.z*other.x - self.x*other.z,
            z: self.w*other.z + self.z*other.w + self.x*other.y - self.y*other.x,
            w: self.w*other.w - self.x*other.x - self.y*other.y - self.z*other.z,
        }
    }
}
impl<T: Num + Float + Copy> MulAssign for Quaternion<T> {
    fn mul_assign(&mut self, other: Quaternion<T>) {
        let x = self.w*other.x + self.x*other.w + self.y*other.z - self.z*other.y;
        let y = self.w*other.y + self.y*other.w + self.z*other.x - self.x*other.z;
        let z = self.w*other.z + self.z*other.w + self.x*other.y - self.y*other.x;
        let w = self.w*other.w - self.x*other.x - self.y*other.y - self.z*other.z;
        self.x = x;
        self.y = y;
        self.z = z;
        self.w = w;
    }
}

// Quaternion scalar multiplication
impl<T: Num + Float + Copy> Mul<T> for Quaternion<T> {
    type Output = Self;
    fn mul(self, scalar: T) -> Self {
        Quaternion {
            x: self.x * scalar,
            y: self.y * scalar,
            z: self.z * scalar,
            w: self.w * scalar,
        }
    }
}
impl<T: Num + Float + Copy> MulAssign<T> for Quaternion<T> {
    fn mul_assign(&mut self, scalar: T) {
        self.x = self.x * scalar;
        self.y = self.y * scalar;
        self.z = self.z * scalar;
        self.w = self.w * scalar;
    }
}
impl<T: Num + Float + Copy> Div<T> for Quaternion<T> {
    type Output = Self;
    fn div(self, scalar: T) -> Self {
        Quaternion {
            x: self.x / scalar,
            y: self.y / scalar,
            z: self.z / scalar,
            w: self.w / scalar,
        }
    }
}
impl<T: Num + Float + Copy> DivAssign<T> for Quaternion<T> {
    fn div_assign(&mut self, scalar: T) {
        self.x = self.x / scalar;
        self.y = self.y / scalar;
        self.z = self.z / scalar;
        self.w = self.w / scalar;
    }
}

impl<T: Num + Float + Copy> From<Quaternion<T>> for Mat4<T> {
    fn from(quat: Quaternion<T>) -> Mat4<T> {
        Mat4::from_quaternion(quat.x, quat.y, quat.z, quat.w)
    }
}

#[cfg(test)]
mod tests {
    use std::f32;
    use super::*;
    use {Mat4, Vec4};

    #[test]
    fn identity() {
        let identity = Quaternion::<f32>::new();
        assert_eq!(identity, identity*identity);
        assert_eq!(identity, identity*identity*identity);
    }

    #[test]
    fn matrix_rotation() {
        let quat = Quaternion::<f32>::rotation(f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0));
        let mat: Mat4<f32> = quat.into();

        let a = Vec4::new(0.0, 1.0, 0.0, 1.0);
        let b = Vec4::new(0.0, 0.0, 1.0, 1.0);

        let diff = (mat*a - b).len();
        assert!(diff < 0.001);
    }

    #[test]
    fn matrix_rotation_reverse() {
        let mat_a: Mat4<f32> = Quaternion::rotation(f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0)).into();
        let mat_b: Mat4<f32> = Quaternion::rotation(-f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0)).into();

        let a = Vec4::new(0.0, 1.0, 0.0, 1.0);

        let diff = (mat_a*mat_b*a - a).len();
        assert!(diff < 0.001);
    }

    #[test]
    fn quaternion_rotation() {
        let quat: Quaternion<f32> = Quaternion::rotation(f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0)).into();

        let a = Vec3::new(0.0, 1.0, 0.0);
        let b = Vec3::new(0.0, 0.0, 1.0);

        let diff = (quat*a - b).len();
        assert!(diff < 0.001);
    }
}
<commit_msg>Calculate angle between quaternions<commit_after>
use num::*;
use mat::Mat4;
use vec::Vec3;
use std::ops::*;

#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(C)]
pub struct Quaternion<T: Num + Float + Copy> {
    pub x: T,
    pub y: T,
    pub w: T,
    pub z: T,
}

impl<T: Num + Float + Copy> Default for Quaternion<T> {
    fn default() -> Quaternion<T> {
        Quaternion::new()
    }
}

impl<T: Num + Float + Copy> Quaternion<T> {
    /// Creates a new identity quaternion
    pub fn new() -> Quaternion<T> {
        Quaternion {
            x: T::zero(),
            y: T::zero(),
            z: T::zero(),
            w: T::one(),
        }
    }

    /// Creates a quaternion representing a counterclockwise rotation of `angle` radians around the
    /// given axis. This function normalizes the axis, but if the axis is `(0, 0, 0)` the quaternion
    /// will have its `x`, `y` and `z` fields set to 0.
    pub fn rotation(angle: T, axis: Vec3<T>) -> Quaternion<T> {
        let axis = axis.normalize();
        let angle = angle / (T::one() + T::one());
        let (sin, cos) = angle.sin_cos();
        Quaternion {
            x: axis.x*sin,
            y: axis.y*sin,
            z: axis.z*sin,
            w: cos,
        }
    }

    /// Calculates the length of this quaternion, raised to the power of two. Note that this is
    /// cheaper than computing the actual length.
    pub fn len_sqr(&self) -> T {
        self.x*self.x + self.y*self.y + self.z*self.z + self.w*self.w
    }

    /// Calculates the length of this quaternion.
    pub fn len(&self) -> T {
        (self.x*self.x + self.y*self.y + self.z*self.z + self.w*self.w).sqrt()
    }

    /// Normalizes this quaternion, returning a new quaternion with length 1.
    pub fn normalize(&self) -> Quaternion<T> {
        *self / self.len()
    }

    /// Calculates the angle between the two given quaternions
    pub fn angle_between(a: Quaternion<T>, b: Quaternion<T>) -> T {
        let unit = Vec3::new(T::one(), T::zero(), T::zero()); // Any unit vector would work
        let a_dir = a*unit;
        let b_dir = b*unit;

        Vec3::dot(a_dir, b_dir).acos()
    }
}

// Quaternion vector multiplication
impl<T: Num + Float + Copy> Mul<Vec3<T>> for Quaternion<T> {
    type Output = Vec3<T>;
    fn mul(self, vec: Vec3<T>) -> Vec3<T> {
        let one = T::one();
        let two = one + one;

        let a11 = one - two*self.y*self.y - two*self.z*self.z;
        let a12 = two*self.x*self.y - two*self.z*self.w;
        let a13 = two*self.x*self.z + two*self.y*self.w;

        let a21 = two*self.x*self.y + two*self.w*self.z;
        let a22 = one - two*self.x*self.x - two*self.z*self.z;
        let a23 = two*self.y*self.z - two*self.w*self.x;

        let a31 = two*self.x*self.z - two*self.w*self.y;
        let a32 = two*self.y*self.z + two*self.w*self.x;
        let a33 = one - two*self.x*self.x - two*self.y*self.y;

        Vec3 {
            x: vec.x*a11 + vec.y*a12 + vec.z*a13,
            y: vec.x*a21 + vec.y*a22 + vec.z*a23,
            z: vec.x*a31 + vec.y*a32 + vec.z*a33,
        }
    }
}

// Quaternion quaternion multiplication
impl<T: Num + Float + Copy> Mul for Quaternion<T> {
    type Output = Self;
    fn mul(self, other: Quaternion<T>) -> Self {
        Quaternion {
            x: self.w*other.x + self.x*other.w + self.y*other.z - self.z*other.y,
            y: self.w*other.y + self.y*other.w + self.z*other.x - self.x*other.z,
            z: self.w*other.z + self.z*other.w + self.x*other.y - self.y*other.x,
            w: self.w*other.w - self.x*other.x - self.y*other.y - self.z*other.z,
        }
    }
}
impl<T: Num + Float + Copy> MulAssign for Quaternion<T> {
    fn mul_assign(&mut self, other: Quaternion<T>) {
        let x = self.w*other.x + self.x*other.w + self.y*other.z - self.z*other.y;
        let y = self.w*other.y + self.y*other.w + self.z*other.x - self.x*other.z;
        let z = self.w*other.z + self.z*other.w + self.x*other.y - self.y*other.x;
        let w = self.w*other.w - self.x*other.x - self.y*other.y - self.z*other.z;
        self.x = x;
        self.y = y;
        self.z = z;
        self.w = w;
    }
}

// Quaternion scalar multiplication
impl<T: Num + Float + Copy> Mul<T> for Quaternion<T> {
    type Output = Self;
    fn mul(self, scalar: T) -> Self {
        Quaternion {
            x: self.x * scalar,
            y: self.y * scalar,
            z: self.z * scalar,
            w: self.w * scalar,
        }
    }
}
impl<T: Num + Float + Copy> MulAssign<T> for Quaternion<T> {
    fn mul_assign(&mut self, scalar: T) {
        self.x = self.x * scalar;
        self.y = self.y * scalar;
        self.z = self.z * scalar;
        self.w = self.w * scalar;
    }
}
impl<T: Num + Float + Copy> Div<T> for Quaternion<T> {
    type Output = Self;
    fn div(self, scalar: T) -> Self {
        Quaternion {
            x: self.x / scalar,
            y: self.y / scalar,
            z: self.z / scalar,
            w: self.w / scalar,
        }
    }
}
impl<T: Num + Float + Copy> DivAssign<T> for Quaternion<T> {
    fn div_assign(&mut self, scalar: T) {
        self.x = self.x / scalar;
        self.y = self.y / scalar;
        self.z = self.z / scalar;
        self.w = self.w / scalar;
    }
}

impl<T: Num + Float + Copy> From<Quaternion<T>> for Mat4<T> {
    fn from(quat: Quaternion<T>) -> Mat4<T> {
        Mat4::from_quaternion(quat.x, quat.y, quat.z, quat.w)
    }
}

#[cfg(test)]
mod tests {
    use std::f32;
    use super::*;
    use {Mat4, Vec4};

    #[test]
    fn identity() {
        let identity = Quaternion::<f32>::new();
        assert_eq!(identity, identity*identity);
        assert_eq!(identity, identity*identity*identity);
    }

    #[test]
    fn matrix_rotation() {
        let quat = Quaternion::<f32>::rotation(f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0));
        let mat: Mat4<f32> = quat.into();

        let a = Vec4::new(0.0, 1.0, 0.0, 1.0);
        let b = Vec4::new(0.0, 0.0, 1.0, 1.0);

        let diff = (mat*a - b).len();
        assert!(diff < 0.001);
    }

    #[test]
    fn matrix_rotation_reverse() {
        let mat_a: Mat4<f32> = Quaternion::rotation(f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0)).into();
        let mat_b: Mat4<f32> = Quaternion::rotation(-f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0)).into();

        let a = Vec4::new(0.0, 1.0, 0.0, 1.0);

        let diff = (mat_a*mat_b*a - a).len();
        assert!(diff < 0.001);
    }

    #[test]
    fn quaternion_rotation() {
        let quat: Quaternion<f32> = Quaternion::rotation(f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0)).into();

        let a = Vec3::new(0.0, 1.0, 0.0);
        let b = Vec3::new(0.0, 0.0, 1.0);

        let diff = (quat*a - b).len();
        assert!(diff < 0.001);
    }

    #[test]
    fn angle_between() {
        let a: Quaternion<f32> = Quaternion::rotation(f32::consts::PI/2.0, Vec3::new(1.0, 0.0, 0.0)).into();
        let b: Quaternion<f32> = Quaternion::rotation(f32::consts::PI/2.0, Vec3::new(0.0, 1.0, 0.0)).into();

        let diff = Quaternion::angle_between(a, b) - f32::consts::PI/2.0;
        assert!(diff < 0.001);
    }
}
<|endoftext|>


<commit_before>use lapin_async::queue::Message;

use std::io;
use futures::{Async,Poll,Stream};
use tokio_io::{AsyncRead,AsyncWrite};
use std::sync::{Arc,Mutex};

use transport::*;

#[derive(Clone)]
pub struct Consumer<T> {
  pub transport:    Arc<Mutex<AMQPTransport<T>>>,
  pub channel_id:   u16,
  pub queue:        String,
  pub consumer_tag: String,
}

impl<T: AsyncRead+AsyncWrite+'static> Stream for Consumer<T> {
  type Item = Message;
  type Error = io::Error;

  fn poll(&mut self) -> Poll<Option<Message>, io::Error> {
    //trace!("consumer[{}] poll", self.consumer_tag);
    if let Ok(mut transport) = self.transport.try_lock() {
      transport.handle_frames();
      //FIXME: if the consumer closed, we should return Ok(Async::Ready(None))
      if let Some(message) = transport.conn.next_message(self.channel_id, &self.queue, &self.consumer_tag) {
        transport.poll();
        //debug!("consumer[{}] ready", self.consumer_tag);
        Ok(Async::Ready(Some(message)))
      } else {
        transport.poll();
        trace!("consumer[{}] not ready", self.consumer_tag);
        Ok(Async::NotReady)
      }
    } else {
      //FIXME: return an error in case of mutex failure
      return Ok(Async::NotReady);
    }
  }
}

<commit_msg>futures: don't eat poll retval in consumer<commit_after>use lapin_async::queue::Message;

use std::io;
use futures::{Async,Poll,Stream};
use tokio_io::{AsyncRead,AsyncWrite};
use std::sync::{Arc,Mutex};

use transport::*;

#[derive(Clone)]
pub struct Consumer<T> {
  pub transport:    Arc<Mutex<AMQPTransport<T>>>,
  pub channel_id:   u16,
  pub queue:        String,
  pub consumer_tag: String,
}

impl<T: AsyncRead+AsyncWrite+'static> Stream for Consumer<T> {
  type Item = Message;
  type Error = io::Error;

  fn poll(&mut self) -> Poll<Option<Message>, io::Error> {
    //trace!("consumer[{}] poll", self.consumer_tag);
    if let Ok(mut transport) = self.transport.try_lock() {
      transport.handle_frames()?;
      //FIXME: if the consumer closed, we should return Ok(Async::Ready(None))
      if let Some(message) = transport.conn.next_message(self.channel_id, &self.queue, &self.consumer_tag) {
        transport.poll()?;
        //debug!("consumer[{}] ready", self.consumer_tag);
        Ok(Async::Ready(Some(message)))
      } else {
        transport.poll()?;
        trace!("consumer[{}] not ready", self.consumer_tag);
        Ok(Async::NotReady)
      }
    } else {
      //FIXME: return an error in case of mutex failure
      return Ok(Async::NotReady);
    }
  }
}

<|endoftext|>


<commit_before>//! Higher order geometric traits.
//!
//! See the `geometry::compose` module. This module's contents are re-exported
//! there.

use std::ops::{Add, Sub};

use crate::geometry::alias::*;
use crate::geometry::convert::AsPosition;
use crate::geometry::ops::{Average, Cross, Interpolate, Normalize, Project};
use crate::geometry::Geometry;
use crate::graph::container::Reborrow;
use crate::graph::payload::{ArcPayload, EdgePayload, FacePayload, VertexPayload};
use crate::graph::storage::convert::AsStorage;
use crate::graph::view::{ArcView, EdgeView, FaceView};
use crate::graph::GraphError;

pub trait FaceNormal: Geometry {
    type Normal;

    fn normal<M>(face: FaceView<M, Self>) -> Result<Self::Normal, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>>
            + AsStorage<FacePayload<Self>>
            + AsStorage<VertexPayload<Self>>;
}

impl<G> FaceNormal for G
where
    G: Geometry,
    G::Vertex: AsPosition,
    VertexPosition<G>: Clone + Sub,
    <VertexPosition<G> as Sub>::Output: Cross,
    <<VertexPosition<G> as Sub>::Output as Cross>::Output: Normalize,
{
    type Normal = <<VertexPosition<G> as Sub>::Output as Cross>::Output;

    fn normal<M>(face: FaceView<M, Self>) -> Result<Self::Normal, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>>
            + AsStorage<FacePayload<Self>>
            + AsStorage<VertexPayload<Self>>,
    {
        let positions = face
            .reachable_vertices()
            .take(3)
            .map(|vertex| vertex.geometry.as_position().clone())
            .collect::<Vec<_>>();
        let (a, b, c) = (&positions[0], &positions[1], &positions[2]);
        let ab = a.clone() - b.clone();
        let bc = b.clone() - c.clone();
        Ok(ab.cross(bc).normalize())
    }
}

pub trait FaceCentroid: Geometry {
    type Centroid;

    fn centroid<M>(face: FaceView<M, Self>) -> Result<Self::Centroid, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>>
            + AsStorage<FacePayload<Self>>
            + AsStorage<VertexPayload<Self>>;
}

impl<G> FaceCentroid for G
where
    G: Geometry,
    G::Vertex: Average,
{
    type Centroid = G::Vertex;

    // TODO: This should operate over the result of `AsPosition`.
    fn centroid<M>(face: FaceView<M, Self>) -> Result<Self::Centroid, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>>
            + AsStorage<FacePayload<Self>>
            + AsStorage<VertexPayload<Self>>,
    {
        Ok(G::Vertex::average(
            face.reachable_vertices()
                .map(|vertex| vertex.geometry.clone()),
        ))
    }
}

pub trait EdgeMidpoint: Geometry {
    type Midpoint;

    fn midpoint<M>(edge: EdgeView<M, Self>) -> Result<Self::Midpoint, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>>
            + AsStorage<EdgePayload<Self>>
            + AsStorage<VertexPayload<Self>>;
}

impl<G> EdgeMidpoint for G
where
    G: Geometry,
    G::Vertex: AsPosition,
    VertexPosition<G>: Clone + Interpolate,
{
    type Midpoint = <VertexPosition<G> as Interpolate>::Output;

    fn midpoint<M>(edge: EdgeView<M, Self>) -> Result<Self::Midpoint, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>>
            + AsStorage<EdgePayload<Self>>
            + AsStorage<VertexPayload<Self>>,
    {
        let a = edge
            .reachable_arc()
            .ok_or_else(|| GraphError::TopologyNotFound)
            .and_then(|arc| {
                arc.reachable_source_vertex()
                    .ok_or_else(|| GraphError::TopologyNotFound)
                    .map(|vertex| vertex.geometry.as_position().clone())
            })?;
        let b = edge
            .reachable_arc()
            .ok_or_else(|| GraphError::TopologyNotFound)
            .and_then(|arc| {
                arc.reachable_destination_vertex()
                    .ok_or_else(|| GraphError::TopologyNotFound)
                    .map(|vertex| vertex.geometry.as_position().clone())
            })?;
        Ok(a.midpoint(b))
    }
}

pub trait ArcNormal: Geometry {
    type Normal;

    fn normal<M>(arc: ArcView<M, Self>) -> Result<Self::Normal, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>> + AsStorage<VertexPayload<Self>>;
}

impl<G> ArcNormal for G
where
    G: Geometry,
    G::Vertex: AsPosition,
    VertexPosition<G>: Clone
        + Add<
            <<VertexPosition<G> as Sub>::Output as Project>::Output,
            Output = VertexPosition<G>,
        > + Sub,
    <VertexPosition<G> as Sub>::Output: Normalize + Project,
{
    type Normal = <VertexPosition<G> as Sub>::Output;

    fn normal<M>(arc: ArcView<M, Self>) -> Result<Self::Normal, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>> + AsStorage<VertexPayload<Self>>,
    {
        let a = arc
            .reachable_source_vertex()
            .ok_or_else(|| GraphError::TopologyNotFound)?
            .geometry
            .as_position()
            .clone();
        let b = arc
            .reachable_destination_vertex()
            .ok_or_else(|| GraphError::TopologyNotFound)?
            .geometry
            .as_position()
            .clone();
        let c = arc
            .reachable_opposite_arc()
            .ok_or_else(|| GraphError::TopologyNotFound)?
            .reachable_previous_arc()
            .ok_or_else(|| GraphError::TopologyNotFound)?
            .reachable_destination_vertex()
            .ok_or_else(|| GraphError::TopologyNotFound)?
            .geometry
            .as_position()
            .clone();
        let ab = a - b.clone();
        let cb = c.clone() - b.clone();
        let p = b + ab.project(cb);
        Ok((p - c).normalize())
    }
}
<commit_msg>Express geometric trait bounds in terms of a vector space.<commit_after>//! Higher order geometric traits.
//!
//! See the `geometry::compose` module. This module's contents are re-exported
//! there.

use crate::geometry::alias::*;
use crate::geometry::convert::AsPosition;
use crate::geometry::ops::{Average, Cross, Interpolate, Normalize, Project};
use crate::geometry::{Geometry, Space};
use crate::graph::container::Reborrow;
use crate::graph::payload::{ArcPayload, EdgePayload, FacePayload, VertexPayload};
use crate::graph::storage::convert::AsStorage;
use crate::graph::view::{ArcView, EdgeView, FaceView};
use crate::graph::GraphError;

pub trait FaceNormal: Geometry {
    type Normal;

    fn normal<M>(face: FaceView<M, Self>) -> Result<Self::Normal, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>>
            + AsStorage<FacePayload<Self>>
            + AsStorage<VertexPayload<Self>>;
}

impl<G> FaceNormal for G
where
    G: Geometry + Space,
    G::Vertex: AsPosition<Target = G::Point>,
    G::Vector: Cross<Output = G::Vector> + Normalize,
{
    type Normal = G::Vector;

    fn normal<M>(face: FaceView<M, Self>) -> Result<Self::Normal, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>>
            + AsStorage<FacePayload<Self>>
            + AsStorage<VertexPayload<Self>>,
    {
        let mut positions = face
            .reachable_vertices()
            .take(3)
            .map(|vertex| vertex.geometry.as_position().clone());
        let a = positions
            .next()
            .ok_or_else(|| GraphError::TopologyNotFound)?;
        let b = positions
            .next()
            .ok_or_else(|| GraphError::TopologyNotFound)?;
        let c = positions
            .next()
            .ok_or_else(|| GraphError::TopologyNotFound)?;
        let ab = a.clone() - b.clone();
        let bc = b.clone() - c.clone();
        Ok(ab.cross(bc).normalize())
    }
}

pub trait FaceCentroid: Geometry {
    type Centroid;

    fn centroid<M>(face: FaceView<M, Self>) -> Result<Self::Centroid, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>>
            + AsStorage<FacePayload<Self>>
            + AsStorage<VertexPayload<Self>>;
}

impl<G> FaceCentroid for G
where
    G: Geometry,
    G::Vertex: Average,
{
    type Centroid = G::Vertex;

    // TODO: Should this only operate over the result of `AsPosition`?
    fn centroid<M>(face: FaceView<M, Self>) -> Result<Self::Centroid, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>>
            + AsStorage<FacePayload<Self>>
            + AsStorage<VertexPayload<Self>>,
    {
        Ok(G::Vertex::average(
            face.reachable_vertices()
                .map(|vertex| vertex.geometry.clone()),
        ))
    }
}

pub trait EdgeMidpoint: Geometry {
    type Midpoint;

    fn midpoint<M>(edge: EdgeView<M, Self>) -> Result<Self::Midpoint, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>>
            + AsStorage<EdgePayload<Self>>
            + AsStorage<VertexPayload<Self>>;
}

impl<G> EdgeMidpoint for G
where
    G: Geometry,
    G::Vertex: AsPosition,
    VertexPosition<G>: Clone + Interpolate,
{
    type Midpoint = <VertexPosition<G> as Interpolate>::Output;

    fn midpoint<M>(edge: EdgeView<M, Self>) -> Result<Self::Midpoint, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>>
            + AsStorage<EdgePayload<Self>>
            + AsStorage<VertexPayload<Self>>,
    {
        let a = edge
            .reachable_arc()
            .ok_or_else(|| GraphError::TopologyNotFound)
            .and_then(|arc| {
                arc.reachable_source_vertex()
                    .ok_or_else(|| GraphError::TopologyNotFound)
                    .map(|vertex| vertex.geometry.as_position().clone())
            })?;
        let b = edge
            .reachable_arc()
            .ok_or_else(|| GraphError::TopologyNotFound)
            .and_then(|arc| {
                arc.reachable_destination_vertex()
                    .ok_or_else(|| GraphError::TopologyNotFound)
                    .map(|vertex| vertex.geometry.as_position().clone())
            })?;
        Ok(a.midpoint(b))
    }
}

pub trait ArcNormal: Geometry {
    type Normal;

    fn normal<M>(arc: ArcView<M, Self>) -> Result<Self::Normal, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>> + AsStorage<VertexPayload<Self>>;
}

impl<G> ArcNormal for G
where
    G: Geometry + Space,
    G::Vertex: AsPosition<Target = G::Point>,
    G::Vector: Project<Output = G::Vector> + Normalize,
{
    type Normal = G::Vector;

    fn normal<M>(arc: ArcView<M, Self>) -> Result<Self::Normal, GraphError>
    where
        M: Reborrow,
        M::Target: AsStorage<ArcPayload<Self>> + AsStorage<VertexPayload<Self>>,
    {
        let a = arc
            .reachable_source_vertex()
            .ok_or_else(|| GraphError::TopologyNotFound)?
            .geometry
            .as_position()
            .clone();
        let b = arc
            .reachable_destination_vertex()
            .ok_or_else(|| GraphError::TopologyNotFound)?
            .geometry
            .as_position()
            .clone();
        let c = arc
            .reachable_opposite_arc()
            .ok_or_else(|| GraphError::TopologyNotFound)?
            .reachable_previous_arc()
            .ok_or_else(|| GraphError::TopologyNotFound)?
            .reachable_destination_vertex()
            .ok_or_else(|| GraphError::TopologyNotFound)?
            .geometry
            .as_position()
            .clone();
        let ab = a - b.clone();
        let cb = c.clone() - b.clone();
        let p = b + ab.project(cb);
        Ok((p - c).normalize())
    }
}
<|endoftext|>


<commit_before>use crate::{Diagnostic, DiagnosticsContext};

// Diagnostic: mismatched-arg-count
//
// This diagnostic is triggered if a function is invoked with an incorrect amount of arguments.
pub(crate) fn mismatched_arg_count(
    ctx: &DiagnosticsContext<'_>,
    d: &hir::MismatchedArgCount,
) -> Diagnostic {
    let s = if d.expected == 1 { "" } else { "s" };
    let message = format!("expected {} argument{}, found {}", d.expected, s, d.found);
    Diagnostic::new(
        "mismatched-arg-count",
        message,
        ctx.sema.diagnostics_display_range(d.call_expr.clone().map(|it| it.into())).range,
    )
}

#[cfg(test)]
mod tests {
    use crate::tests::check_diagnostics;

    #[test]
    fn simple_free_fn_zero() {
        check_diagnostics(
            r#"
fn zero() {}
fn f() { zero(1); }
       //^^^^^^^ error: expected 0 arguments, found 1
"#,
        );

        check_diagnostics(
            r#"
fn zero() {}
fn f() { zero(); }
"#,
        );
    }

    #[test]
    fn simple_free_fn_one() {
        check_diagnostics(
            r#"
fn one(arg: u8) {}
fn f() { one(); }
       //^^^^^ error: expected 1 argument, found 0
"#,
        );

        check_diagnostics(
            r#"
fn one(arg: u8) {}
fn f() { one(1); }
"#,
        );
    }

    #[test]
    fn method_as_fn() {
        check_diagnostics(
            r#"
struct S;
impl S { fn method(&self) {} }

fn f() {
    S::method();
} //^^^^^^^^^^^ error: expected 1 argument, found 0
"#,
        );

        check_diagnostics(
            r#"
struct S;
impl S { fn method(&self) {} }

fn f() {
    S::method(&S);
    S.method();
}
"#,
        );
    }

    #[test]
    fn method_with_arg() {
        check_diagnostics(
            r#"
struct S;
impl S { fn method(&self, arg: u8) {} }

            fn f() {
                S.method();
            } //^^^^^^^^^^ error: expected 1 argument, found 0
            "#,
        );

        check_diagnostics(
            r#"
struct S;
impl S { fn method(&self, arg: u8) {} }

fn f() {
    S::method(&S, 0);
    S.method(1);
}
"#,
        );
    }

    #[test]
    fn method_unknown_receiver() {
        // note: this is incorrect code, so there might be errors on this in the
        // future, but we shouldn't emit an argument count diagnostic here
        check_diagnostics(
            r#"
trait Foo { fn method(&self, arg: usize) {} }

fn f() {
    let x;
    x.method();
}
"#,
        );
    }

    #[test]
    fn tuple_struct() {
        check_diagnostics(
            r#"
struct Tup(u8, u16);
fn f() {
    Tup(0);
} //^^^^^^ error: expected 2 arguments, found 1
"#,
        )
    }

    #[test]
    fn enum_variant() {
        check_diagnostics(
            r#"
enum En { Variant(u8, u16), }
fn f() {
    En::Variant(0);
} //^^^^^^^^^^^^^^ error: expected 2 arguments, found 1
"#,
        )
    }

    #[test]
    fn enum_variant_type_macro() {
        check_diagnostics(
            r#"
macro_rules! Type {
    () => { u32 };
}
enum Foo {
    Bar(Type![])
}
impl Foo {
    fn new() {
        Foo::Bar(0);
        Foo::Bar(0, 1);
      //^^^^^^^^^^^^^^ error: expected 1 argument, found 2
        Foo::Bar();
      //^^^^^^^^^^ error: expected 1 argument, found 0
    }
}
        "#,
        );
    }

    #[test]
    fn varargs() {
        check_diagnostics(
            r#"
extern "C" {
    fn fixed(fixed: u8);
    fn varargs(fixed: u8, ...);
    fn varargs2(...);
}

fn f() {
    unsafe {
        fixed(0);
        fixed(0, 1);
      //^^^^^^^^^^^ error: expected 1 argument, found 2
        varargs(0);
        varargs(0, 1);
        varargs2();
        varargs2(0);
        varargs2(0, 1);
    }
}
        "#,
        )
    }

    #[test]
    fn arg_count_lambda() {
        check_diagnostics(
            r#"
fn main() {
    let f = |()| ();
    f();
  //^^^ error: expected 1 argument, found 0
    f(());
    f((), ());
  //^^^^^^^^^ error: expected 1 argument, found 2
}
"#,
        )
    }

    #[test]
    fn cfgd_out_call_arguments() {
        check_diagnostics(
            r#"
struct C(#[cfg(FALSE)] ());
impl C {
    fn new() -> Self {
        Self(
            #[cfg(FALSE)]
            (),
        )
    }

    fn method(&self) {}
}

fn main() {
    C::new().method(#[cfg(FALSE)] 0);
}
            "#,
        );
    }

    #[test]
    fn cfgd_out_fn_params() {
        check_diagnostics(
            r#"
fn foo(#[cfg(NEVER)] x: ()) {}

struct S;

impl S {
    fn method(#[cfg(NEVER)] self) {}
    fn method2(#[cfg(NEVER)] self, arg: u8) {}
    fn method3(self, #[cfg(NEVER)] arg: u8) {}
}

extern "C" {
    fn fixed(fixed: u8, #[cfg(NEVER)] ...);
    fn varargs(#[cfg(not(NEVER))] ...);
}

fn main() {
    foo();
    S::method();
    S::method2(0);
    S::method3(S);
    S.method3();
    unsafe {
        fixed(0);
        varargs(1, 2, 3);
    }
}
            "#,
        )
    }
}
<commit_msg>feat: be more precise in mismatch arg counts highlighting<commit_after>use ide_db::base_db::{FileRange, SourceDatabase};
use syntax::{
    algo::find_node_at_range,
    ast::{self, HasArgList},
    AstNode,
};

use crate::{Diagnostic, DiagnosticsContext};

// Diagnostic: mismatched-arg-count
//
// This diagnostic is triggered if a function is invoked with an incorrect amount of arguments.
pub(crate) fn mismatched_arg_count(
    ctx: &DiagnosticsContext<'_>,
    d: &hir::MismatchedArgCount,
) -> Diagnostic {
    let s = if d.expected == 1 { "" } else { "s" };
    let message = format!("expected {} argument{}, found {}", d.expected, s, d.found);
    Diagnostic::new(
        "mismatched-arg-count",
        message,
        invalid_args_range(ctx, d).unwrap_or_else(|it| it).range,
    )
}

fn invalid_args_range(
    ctx: &DiagnosticsContext<'_>,
    d: &hir::MismatchedArgCount,
) -> Result<FileRange, FileRange> {
    let full_range = ctx.sema.diagnostics_display_range(d.call_expr.clone().map(|it| it.into()));

    let source_file = ctx.sema.db.parse(full_range.file_id);
    let expr = find_node_at_range::<ast::Expr>(&source_file.syntax_node(), full_range.range)
        .filter(|it| it.syntax().text_range() == full_range.range);
    let arg_list = match expr {
        Some(ast::Expr::CallExpr(call)) => call.arg_list(),
        Some(ast::Expr::MethodCallExpr(call)) => call.arg_list(),
        _ => None,
    };
    let arg_list = match arg_list {
        Some(it) => it,
        None => return Err(full_range),
    };
    let arg_list_range =
        FileRange { file_id: full_range.file_id, range: arg_list.syntax().text_range() };
    if d.found < d.expected {
        if d.found == 0 {
            return Ok(arg_list_range);
        }
        if let Some(r_paren) = arg_list.r_paren_token() {
            return Ok(FileRange { file_id: full_range.file_id, range: r_paren.text_range() });
        }
    }
    if d.expected < d.found {
        return Ok(arg_list_range);
    }

    Err(full_range)
}

#[cfg(test)]
mod tests {
    use crate::tests::check_diagnostics;

    #[test]
    fn simple_free_fn_zero() {
        check_diagnostics(
            r#"
fn zero() {}
fn f() { zero(1); }
           //^^^ error: expected 0 arguments, found 1
"#,
        );

        check_diagnostics(
            r#"
fn zero() {}
fn f() { zero(); }
"#,
        );
    }

    #[test]
    fn simple_free_fn_one() {
        check_diagnostics(
            r#"
fn one(arg: u8) {}
fn f() { one(); }
          //^^ error: expected 1 argument, found 0
"#,
        );

        check_diagnostics(
            r#"
fn one(arg: u8) {}
fn f() { one(1); }
"#,
        );
    }

    #[test]
    fn method_as_fn() {
        check_diagnostics(
            r#"
struct S;
impl S { fn method(&self) {} }

fn f() {
    S::method();
}          //^^ error: expected 1 argument, found 0
"#,
        );

        check_diagnostics(
            r#"
struct S;
impl S { fn method(&self) {} }

fn f() {
    S::method(&S);
    S.method();
}
"#,
        );
    }

    #[test]
    fn method_with_arg() {
        check_diagnostics(
            r#"
struct S;
impl S { fn method(&self, arg: u8) {} }

            fn f() {
                S.method();
            }         //^^ error: expected 1 argument, found 0
            "#,
        );

        check_diagnostics(
            r#"
struct S;
impl S { fn method(&self, arg: u8) {} }

fn f() {
    S::method(&S, 0);
    S.method(1);
}
"#,
        );
    }

    #[test]
    fn method_unknown_receiver() {
        // note: this is incorrect code, so there might be errors on this in the
        // future, but we shouldn't emit an argument count diagnostic here
        check_diagnostics(
            r#"
trait Foo { fn method(&self, arg: usize) {} }

fn f() {
    let x;
    x.method();
}
"#,
        );
    }

    #[test]
    fn tuple_struct() {
        check_diagnostics(
            r#"
struct Tup(u8, u16);
fn f() {
    Tup(0);
}      //^ error: expected 2 arguments, found 1
"#,
        )
    }

    #[test]
    fn enum_variant() {
        check_diagnostics(
            r#"
enum En { Variant(u8, u16), }
fn f() {
    En::Variant(0);
}              //^ error: expected 2 arguments, found 1
"#,
        )
    }

    #[test]
    fn enum_variant_type_macro() {
        check_diagnostics(
            r#"
macro_rules! Type {
    () => { u32 };
}
enum Foo {
    Bar(Type![])
}
impl Foo {
    fn new() {
        Foo::Bar(0);
        Foo::Bar(0, 1);
              //^^^^^^ error: expected 1 argument, found 2
        Foo::Bar();
              //^^ error: expected 1 argument, found 0
    }
}
        "#,
        );
    }

    #[test]
    fn varargs() {
        check_diagnostics(
            r#"
extern "C" {
    fn fixed(fixed: u8);
    fn varargs(fixed: u8, ...);
    fn varargs2(...);
}

fn f() {
    unsafe {
        fixed(0);
        fixed(0, 1);
           //^^^^^^ error: expected 1 argument, found 2
        varargs(0);
        varargs(0, 1);
        varargs2();
        varargs2(0);
        varargs2(0, 1);
    }
}
        "#,
        )
    }

    #[test]
    fn arg_count_lambda() {
        check_diagnostics(
            r#"
fn main() {
    let f = |()| ();
    f();
   //^^ error: expected 1 argument, found 0
    f(());
    f((), ());
   //^^^^^^^^ error: expected 1 argument, found 2
}
"#,
        )
    }

    #[test]
    fn cfgd_out_call_arguments() {
        check_diagnostics(
            r#"
struct C(#[cfg(FALSE)] ());
impl C {
    fn new() -> Self {
        Self(
            #[cfg(FALSE)]
            (),
        )
    }

    fn method(&self) {}
}

fn main() {
    C::new().method(#[cfg(FALSE)] 0);
}
            "#,
        );
    }

    #[test]
    fn cfgd_out_fn_params() {
        check_diagnostics(
            r#"
fn foo(#[cfg(NEVER)] x: ()) {}

struct S;

impl S {
    fn method(#[cfg(NEVER)] self) {}
    fn method2(#[cfg(NEVER)] self, arg: u8) {}
    fn method3(self, #[cfg(NEVER)] arg: u8) {}
}

extern "C" {
    fn fixed(fixed: u8, #[cfg(NEVER)] ...);
    fn varargs(#[cfg(not(NEVER))] ...);
}

fn main() {
    foo();
    S::method();
    S::method2(0);
    S::method3(S);
    S.method3();
    unsafe {
        fixed(0);
        varargs(1, 2, 3);
    }
}
            "#,
        )
    }
}
<|endoftext|>


<commit_before>//! The module contains implementations of the transport layer functionality
//! that HTTP/2 requires. It exposes APIs that allow the HTTP/2 connection to
//! use the transport layer without requiring it to know which exact
//! implementation they are using (i.e. a clear-text TCP connection, a TLS
//! protected connection, or even a mock implementation).

use std::io;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::net::Shutdown;
use openssl::ssl::SslStream;

/// A trait that any struct that wants to provide the transport layer for
/// HTTP/2 needs to implement.
///
/// It provides default implementations for some convenience methods, backed
/// by the `Read` and `Write` implementations.
pub trait TransportStream: Read + Write {
    /// A convenience method that performs as many `read` calls on the
    /// underlying `Read` implementation as it takes to fill the given buffer.
    ///
    /// The implementation simply calls the `read` in a loop until the
    /// buffer is filled or an aparent end of file is reached, upon which
    /// an error is returned.
    ///
    /// However, no particular care is taken to limit the number of loop
    /// iterations and it could theoretically be possible to end up reading
    /// a single byte at a time into a large buffer, taking a long time to
    /// return.
    ///
    /// Any errors raised by the underlying `Read` implementations are
    /// propagated.
    ///
    /// When an error is raised, the given buffer is only partially filled,
    /// but there is no way to know how many bytes were actually written to
    /// the underlying buffer, which means that, effectively, all read bytes
    /// are lost on any error.
    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
        let mut total = 0;
        while total < buf.len() {
            let read = try!(self.read(&mut buf[total..]));
            if read == 0 {
                // We consider this an unexpected end of file and return an
                // error since we were unable to read the minimum amount of
                // bytes.
                return Err(io::Error::new(io::ErrorKind::Other,
                                          "Not enough bytes"));
            }
            total += read;
        }

        Ok(())
    }

    /// Attempts to split the `TransportStream` instance into a new independently
    /// owned handle to the same underlying stream.
    fn try_split(&self) -> Result<Self, io::Error>;

    /// Attempts to shutdown both ends of the transport stream.
    ///
    /// If successful, all handles to the stream created by the `try_split` operation will start
    /// receiving an error for any IO operations.
    fn close(&self) -> Result<(), io::Error>;
}

impl TransportStream for TcpStream {
    fn try_split(&self) -> Result<TcpStream, io::Error> {
        self.try_clone()
    }

    fn close(&self) -> Result<(), io::Error> {
        self.shutdown(Shutdown::Both)
    }
}

impl TransportStream for SslStream<TcpStream> {
    fn try_split(&self) -> Result<SslStream<TcpStream>, io::Error> {
        self.try_clone()
    }

    fn close(&self) -> Result<(), io::Error> {
        self.get_ref().shutdown(Shutdown::Both)
    }
}
<commit_msg>http/transport.rs: Update module-level docs<commit_after>//! The module contains implementations of the transport layer functionality
//! that HTTP/2 requires. It exposes APIs that allow the HTTP/2 connection to
//! use the transport layer without requiring it to know which exact
//! implementation they are using (e.g. a clear-text TCP connection, a TLS
//! protected connection, or even a mock implementation).
//!
//! The types provided here are purely for convenience in being able to easily
//! plug in the native Rust socket IO primitives into the HTTP/2 connection API
//! without having to write too much boilerplate around them.

use std::io;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::net::Shutdown;
use openssl::ssl::SslStream;

/// A trait that any struct that wants to provide the transport layer for
/// HTTP/2 needs to implement.
///
/// It provides default implementations for some convenience methods, backed
/// by the `Read` and `Write` implementations.
pub trait TransportStream: Read + Write {
    /// A convenience method that performs as many `read` calls on the
    /// underlying `Read` implementation as it takes to fill the given buffer.
    ///
    /// The implementation simply calls the `read` in a loop until the
    /// buffer is filled or an aparent end of file is reached, upon which
    /// an error is returned.
    ///
    /// However, no particular care is taken to limit the number of loop
    /// iterations and it could theoretically be possible to end up reading
    /// a single byte at a time into a large buffer, taking a long time to
    /// return.
    ///
    /// Any errors raised by the underlying `Read` implementations are
    /// propagated.
    ///
    /// When an error is raised, the given buffer is only partially filled,
    /// but there is no way to know how many bytes were actually written to
    /// the underlying buffer, which means that, effectively, all read bytes
    /// are lost on any error.
    fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> {
        let mut total = 0;
        while total < buf.len() {
            let read = try!(self.read(&mut buf[total..]));
            if read == 0 {
                // We consider this an unexpected end of file and return an
                // error since we were unable to read the minimum amount of
                // bytes.
                return Err(io::Error::new(io::ErrorKind::Other,
                                          "Not enough bytes"));
            }
            total += read;
        }

        Ok(())
    }

    /// Attempts to split the `TransportStream` instance into a new independently
    /// owned handle to the same underlying stream.
    fn try_split(&self) -> Result<Self, io::Error>;

    /// Attempts to shutdown both ends of the transport stream.
    ///
    /// If successful, all handles to the stream created by the `try_split` operation will start
    /// receiving an error for any IO operations.
    fn close(&self) -> Result<(), io::Error>;
}

impl TransportStream for TcpStream {
    fn try_split(&self) -> Result<TcpStream, io::Error> {
        self.try_clone()
    }

    fn close(&self) -> Result<(), io::Error> {
        self.shutdown(Shutdown::Both)
    }
}

impl TransportStream for SslStream<TcpStream> {
    fn try_split(&self) -> Result<SslStream<TcpStream>, io::Error> {
        self.try_clone()
    }

    fn close(&self) -> Result<(), io::Error> {
        self.get_ref().shutdown(Shutdown::Both)
    }
}
<|endoftext|>