<commit_before>#![allow(dead_code)]
use std::io::Result as IoResult;
use std::result::Result;
use std::iter::{Iterator, IntoIterator};
use std::collections::HashMap;
use std::collections::hash_map;
use std::vec::Vec;
use std::cmp::{Eq, PartialEq};
use std::hash::{Hash, Hasher};

pub type Pixels = usize;
pub type FileName = String;
pub type FilePath = String;

#[derive(Clone, Eq, PartialEq, Hash)]
pub enum ResolutionUnits {
    PixelsPerInch,
    PixelsPerCentimeter,
}

#[derive(Clone, Eq, PartialEq, Hash)]
pub enum Direction {
    Horizontal,
    Vertical,
}

#[derive(Clone, Eq, PartialEq, Hash)]
pub enum ImageFileFormat {
    TIFF,
    PNG,
    JPEG,
    UNKNOWN,
}

#[derive(Clone, Eq, PartialEq, Hash)]
struct ImageDimensions {
    x_pixels: Pixels,
    y_pixels: Pixels,
}

impl ImageDimensions {
    fn new(x: Pixels, y: Pixels) -> ImageDimensions {
        ImageDimensions {
            x_pixels: x,
            y_pixels: y,
        }
    }
}

#[derive(Clone, Eq, PartialEq, Hash)]
pub struct ImageResolution {
    amount: Pixels,
    units: ResolutionUnits,
}

impl ImageResolution {
    fn new(amount: usize, units: ResolutionUnits) -> ImageResolution {
        ImageResolution {
            amount: amount,
            units: units,
        }
    }
}

#[derive(Clone)]
pub enum PageOps {
    Identify(FilePath),
    Rescale(Pixels, Direction),
    ExpandLeftEdge(Pixels),
    ExpandRightEdge(Pixels),
    ExpandTopEdge(Pixels),
    ExpandBottomEdge(Pixels),
    TrimLeftEdge(Pixels),
    TrimRightEdge(Pixels),
    TrimTopEdge(Pixels),
    TrimBottomEdge(Pixels),
    SetResolution(ImageResolution),
}

pub trait ElementaryPageOperations {
    fn identify(path: FilePath)                -> IoResult<String>;
    fn rescale(amount: Pixels, dir: Direction) -> IoResult<String>;
    fn expand_left_edge(amount: Pixels)        -> IoResult<String>;
    fn expand_right_edge(amount: Pixels)       -> IoResult<String>;
    fn expand_top_edge(amount: Pixels)         -> IoResult<String>;
    fn expand_bottom_edge(amount: Pixels)      -> IoResult<String>;
    fn trim_left_edge(amount: Pixels)          -> IoResult<String>;
    fn trim_right_edge(amount: Pixels)         -> IoResult<String>;
    fn trim_top_edge(amount: Pixels)           -> IoResult<String>;
    fn trim_bottom_edge(amount: Pixels)        -> IoResult<String>;
    fn set_resolution(res: ImageResolution)    -> IoResult<String>;
}

trait RunOperation<OpTrait, OtherOp> {
    fn run_operation(op: OtherOp) -> IoResult<String>;
}

impl<Op> RunOperation<Op, PageOps> for Op where Op: ElementaryPageOperations {
    fn run_operation(page_op: PageOps) -> IoResult<String> {
        match page_op {
            PageOps::Identify(path)           => Op::identify(path),
            PageOps::Rescale(amount, dir)     => Op::rescale(amount, dir),
            PageOps::ExpandLeftEdge(amount)   => Op::expand_left_edge(amount),
            PageOps::ExpandRightEdge(amount)  => Op::expand_right_edge(amount),
            PageOps::ExpandTopEdge(amount)    => Op::expand_top_edge(amount),
            PageOps::ExpandBottomEdge(amount) => Op::expand_bottom_edge(amount),
            PageOps::TrimLeftEdge(amount)     => Op::trim_left_edge(amount),
            PageOps::TrimRightEdge(amount)    => Op::trim_right_edge(amount),
            PageOps::TrimTopEdge(amount)      => Op::trim_top_edge(amount),
            PageOps::TrimBottomEdge(amount)   => Op::trim_bottom_edge(amount),
            PageOps::SetResolution(res)       => Op::set_resolution(res),
        }
    }
}

#[derive(Clone)]
struct CompoundPageOperation {
    page_name: FileName,
    page_path: FilePath,
    ops: Option<Vec<PageOps>>,
}

impl CompoundPageOperation {
    fn new(page_name: FileName, page_path: FilePath, ops: &[PageOps]) -> CompoundPageOperation {

        if ops.is_empty() {
            return CompoundPageOperation {
                page_name: page_name,
                page_path: page_path,
                ops: None,
            };
        }

        let mut vec = Vec::new();
        for op in ops.iter() {
            vec.push(op.clone());
        }

        CompoundPageOperation {
            page_name: page_name,
            page_path: page_path,
            ops: Some(vec),
        }
    }

    fn make_noop() -> CompoundPageOperation {
        CompoundPageOperation {
            page_name: String::from(""),
            page_path: String::from(""),
            ops: None,
        }
    }

    fn is_noop(&self) -> bool {
        match self.ops {
            Some(ref vec) => vec.is_empty(),
            None          => true,
        }
    }

    fn run_operation<Op>(&self) -> IoResult<String>
        where Op: ElementaryPageOperations {

        match self.ops {

            None      => {
                Ok(String::from("No Operation"))
            }
            Some(ref vec) => {
                if self.is_noop() {
                    // Should not happen.
                    unreachable!();
                    //return Ok(String::from("No Operation"));
                }

                let mut result = Ok(String::from(""));
                for op in vec.iter() {
                    let res = Op::run_operation(op.clone());
                    match res {
                        Ok(s) => {
                            continue;
                        }
                        Err(e) => {
                            result = Err(e);
                            break;
                        }
                    }
                }
                result
            }
        }
    }

}

#[derive(Clone)]
enum CompoundPageOps {
    AnOp(CompoundPageOperation),
    NoOp(CompoundPageOperation),
}

impl CompoundPageOps {
    fn new(page_name: FileName, page_path: FilePath, ops: &[PageOps]) -> CompoundPageOps {
        if ops.is_empty() {
            return CompoundPageOps::NoOp(CompoundPageOperation::new(page_name, page_path, ops));
        }

        CompoundPageOps::AnOp(CompoundPageOperation::new(page_name, page_path, ops))
    }
}

#[derive(Clone, Eq)]
struct Page {
    file_name: FileName,
    file_extension: ImageFileFormat,
    file_path: FilePath,
    dimensions: ImageDimensions,
    resolution: ImageResolution,
}

impl Page {
    fn new  (
            file_name: FileName,
            file_extension: ImageFileFormat,
            file_path: FilePath,
            dimensions: ImageDimensions,
            resolution: ImageResolution
            ) -> Page
    {
        Page {
            file_name: file_name,
            file_extension: file_extension,
            file_path: file_path,
            dimensions: dimensions,
            resolution: resolution,
        }
    }
}

impl PartialEq for Page {
    fn eq(&self, other: &Page) -> bool {
            self.file_name      == other.file_name
        &&  self.file_extension == other.file_extension
        &&  self.file_path      == other.file_path
        &&  self.dimensions     == other.dimensions
        &&  self.resolution     == other.resolution
    }
}

impl Hash for Page {
    fn hash<H>(&self, state: &mut H)
        where H: Hasher {

        self.file_name.hash(state);
        self.file_extension.hash(state);
        self.file_path.hash(state);
        self.dimensions.hash(state);
        self.resolution.hash(state);
    }
}

struct OperationSchedule {
    schedule: HashMap<Page, CompoundPageOperation>,
}

struct OperationResults {
    results: Vec<IoResult<String>>,
}

impl OperationResults {
    fn new(vec: Vec<IoResult<String>>) -> Self {
        OperationResults {
            results: vec,
        }
    }
}

#[derive(Clone, Eq, PartialEq)]
enum OperationScheduleError {
    LengthMismatch,
}

impl OperationSchedule {
    fn new() -> Self {
        OperationSchedule {
            schedule: HashMap::new(),
        }
    }

    fn add_operation(&mut self, page: Page, op: CompoundPageOperation) {
        self.schedule.insert(page, op);
    }

    fn build_schedule(pages: &[Page], ops: &[CompoundPageOperation]) -> Result<Self, OperationScheduleError> {
        if pages.len() == ops.len() {

            let mut schedule = OperationSchedule::new();

            for page_number in 0..pages.len() {
                schedule.add_operation(pages[page_number].clone(), ops[page_number].clone());
            }

            Ok(schedule)

        } else {
            Err(OperationScheduleError::LengthMismatch)
        }

    }

    fn iter(&self) -> OpSchedIter {
        OpSchedIter {
            inner: self.schedule.iter()
        }
    }

    fn run_operation<Op>(&self) -> OperationResults
        where Op: ElementaryPageOperations {

        let mut results = Vec::new();

        for (page, op) in self {
            let result = op.run_operation::<Op>();
            results.push(result);
        }

        OperationResults::new(results)
    }

}

struct OpSchedIter<'a> {
    inner:  hash_map::Iter<'a, Page, CompoundPageOperation>
}

impl<'a> Iterator for OpSchedIter<'a> {
    type Item = (&'a Page, &'a CompoundPageOperation);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

}

impl<'a> IntoIterator for &'a OperationSchedule {
    type Item = (&'a Page, &'a CompoundPageOperation);
    type IntoIter = OpSchedIter<'a>;

    fn into_iter(self) -> OpSchedIter<'a> {
        self.iter()
    }
}

struct OpSchedIntoIter {
    inner: hash_map::IntoIter<Page, CompoundPageOperation>,
}

impl IntoIterator for OperationSchedule {
    type Item = (Page, CompoundPageOperation);
    type IntoIter = OpSchedIntoIter;

    fn into_iter(self) -> OpSchedIntoIter {
        OpSchedIntoIter {
            inner: self.schedule.into_iter()
        }
    }
}

impl Iterator for OpSchedIntoIter {
    type Item = (Page, CompoundPageOperation);

    fn next(&mut self) -> Option<(Page, CompoundPageOperation)> {
        self.inner.next()
    }
}
<commit_msg>Update OperationResults.<commit_after>#![allow(dead_code)]
use std::io::Result as IoResult;
use std::result::Result;
use std::iter::{Iterator, IntoIterator};
use std::collections::HashMap;
use std::collections::hash_map;
use std::vec::Vec;
use std::cmp::{Eq, PartialEq};
use std::hash::{Hash, Hasher};

pub type Pixels = usize;
pub type FileName = String;
pub type FilePath = String;

#[derive(Clone, Eq, PartialEq, Hash)]
pub enum ResolutionUnits {
    PixelsPerInch,
    PixelsPerCentimeter,
}

#[derive(Clone, Eq, PartialEq, Hash)]
pub enum Direction {
    Horizontal,
    Vertical,
}

#[derive(Clone, Eq, PartialEq, Hash)]
pub enum ImageFileFormat {
    TIFF,
    PNG,
    JPEG,
    UNKNOWN,
}

#[derive(Clone, Eq, PartialEq, Hash)]
struct ImageDimensions {
    x_pixels: Pixels,
    y_pixels: Pixels,
}

impl ImageDimensions {
    fn new(x: Pixels, y: Pixels) -> ImageDimensions {
        ImageDimensions {
            x_pixels: x,
            y_pixels: y,
        }
    }
}

#[derive(Clone, Eq, PartialEq, Hash)]
pub struct ImageResolution {
    amount: Pixels,
    units: ResolutionUnits,
}

impl ImageResolution {
    fn new(amount: usize, units: ResolutionUnits) -> ImageResolution {
        ImageResolution {
            amount: amount,
            units: units,
        }
    }
}

#[derive(Clone)]
pub enum PageOps {
    Identify(FilePath),
    Rescale(Pixels, Direction),
    ExpandLeftEdge(Pixels),
    ExpandRightEdge(Pixels),
    ExpandTopEdge(Pixels),
    ExpandBottomEdge(Pixels),
    TrimLeftEdge(Pixels),
    TrimRightEdge(Pixels),
    TrimTopEdge(Pixels),
    TrimBottomEdge(Pixels),
    SetResolution(ImageResolution),
}

pub trait ElementaryPageOperations {
    fn identify(path: FilePath)                -> IoResult<String>;
    fn rescale(amount: Pixels, dir: Direction) -> IoResult<String>;
    fn expand_left_edge(amount: Pixels)        -> IoResult<String>;
    fn expand_right_edge(amount: Pixels)       -> IoResult<String>;
    fn expand_top_edge(amount: Pixels)         -> IoResult<String>;
    fn expand_bottom_edge(amount: Pixels)      -> IoResult<String>;
    fn trim_left_edge(amount: Pixels)          -> IoResult<String>;
    fn trim_right_edge(amount: Pixels)         -> IoResult<String>;
    fn trim_top_edge(amount: Pixels)           -> IoResult<String>;
    fn trim_bottom_edge(amount: Pixels)        -> IoResult<String>;
    fn set_resolution(res: ImageResolution)    -> IoResult<String>;
}

trait RunOperation<OpTrait, OtherOp> {
    fn run_operation(op: OtherOp) -> IoResult<String>;
}

impl<Op> RunOperation<Op, PageOps> for Op where Op: ElementaryPageOperations {
    fn run_operation(page_op: PageOps) -> IoResult<String> {
        match page_op {
            PageOps::Identify(path)           => Op::identify(path),
            PageOps::Rescale(amount, dir)     => Op::rescale(amount, dir),
            PageOps::ExpandLeftEdge(amount)   => Op::expand_left_edge(amount),
            PageOps::ExpandRightEdge(amount)  => Op::expand_right_edge(amount),
            PageOps::ExpandTopEdge(amount)    => Op::expand_top_edge(amount),
            PageOps::ExpandBottomEdge(amount) => Op::expand_bottom_edge(amount),
            PageOps::TrimLeftEdge(amount)     => Op::trim_left_edge(amount),
            PageOps::TrimRightEdge(amount)    => Op::trim_right_edge(amount),
            PageOps::TrimTopEdge(amount)      => Op::trim_top_edge(amount),
            PageOps::TrimBottomEdge(amount)   => Op::trim_bottom_edge(amount),
            PageOps::SetResolution(res)       => Op::set_resolution(res),
        }
    }
}

#[derive(Clone)]
struct CompoundPageOperation {
    page_name: FileName,
    page_path: FilePath,
    ops: Option<Vec<PageOps>>,
}

impl CompoundPageOperation {
    fn new(page_name: FileName, page_path: FilePath, ops: &[PageOps]) -> CompoundPageOperation {

        if ops.is_empty() {
            return CompoundPageOperation {
                page_name: page_name,
                page_path: page_path,
                ops: None,
            };
        }

        let mut vec = Vec::new();
        for op in ops.iter() {
            vec.push(op.clone());
        }

        CompoundPageOperation {
            page_name: page_name,
            page_path: page_path,
            ops: Some(vec),
        }
    }

    fn make_noop() -> CompoundPageOperation {
        CompoundPageOperation {
            page_name: String::from(""),
            page_path: String::from(""),
            ops: None,
        }
    }

    fn is_noop(&self) -> bool {
        match self.ops {
            Some(ref vec) => vec.is_empty(),
            None          => true,
        }
    }

    fn run_operation<Op>(&self) -> IoResult<String>
        where Op: ElementaryPageOperations {

        match self.ops {

            None      => {
                Ok(String::from("No Operation"))
            }
            Some(ref vec) => {
                if self.is_noop() {
                    // Should not happen.
                    unreachable!();
                    //return Ok(String::from("No Operation"));
                }

                let mut result = Ok(String::from(""));
                for op in vec.iter() {
                    let res = Op::run_operation(op.clone());
                    match res {
                        Ok(s) => {
                            continue;
                        }
                        Err(e) => {
                            result = Err(e);
                            break;
                        }
                    }
                }
                result
            }
        }
    }

}

#[derive(Clone)]
enum CompoundPageOps {
    AnOp(CompoundPageOperation),
    NoOp(CompoundPageOperation),
}

impl CompoundPageOps {
    fn new(page_name: FileName, page_path: FilePath, ops: &[PageOps]) -> CompoundPageOps {
        if ops.is_empty() {
            return CompoundPageOps::NoOp(CompoundPageOperation::new(page_name, page_path, ops));
        }

        CompoundPageOps::AnOp(CompoundPageOperation::new(page_name, page_path, ops))
    }
}

#[derive(Clone, Eq)]
struct Page {
    file_name: FileName,
    file_extension: ImageFileFormat,
    file_path: FilePath,
    dimensions: ImageDimensions,
    resolution: ImageResolution,
}

impl Page {
    fn new  (
            file_name: FileName,
            file_extension: ImageFileFormat,
            file_path: FilePath,
            dimensions: ImageDimensions,
            resolution: ImageResolution
            ) -> Page
    {
        Page {
            file_name: file_name,
            file_extension: file_extension,
            file_path: file_path,
            dimensions: dimensions,
            resolution: resolution,
        }
    }
}

impl PartialEq for Page {
    fn eq(&self, other: &Page) -> bool {
            self.file_name      == other.file_name
        &&  self.file_extension == other.file_extension
        &&  self.file_path      == other.file_path
        &&  self.dimensions     == other.dimensions
        &&  self.resolution     == other.resolution
    }
}

impl Hash for Page {
    fn hash<H>(&self, state: &mut H) where H: Hasher {

        self.file_name.hash(state);
        self.file_extension.hash(state);
        self.file_path.hash(state);
        self.dimensions.hash(state);
        self.resolution.hash(state);
    }
}

type OperationResult = IoResult<String>;

struct OperationResults {
    results: Vec<OperationResult>,
}

impl OperationResults {
    fn new() -> OperationResults {
        OperationResults {
            results: Vec::new(),
        }
    }

    fn append(&mut self, result: OperationResult) {
        self.results.push(result);
    }

    fn append_vec(&mut self, other: &mut Vec<OperationResult>) {
        self.results.append(other);
    }

}

struct OperationSchedule {
    schedule: HashMap<Page, CompoundPageOperation>,
}

#[derive(Clone, Eq, PartialEq)]
enum OperationScheduleError {
    LengthMismatch,
}

impl OperationSchedule {
    fn new() -> OperationSchedule {
        OperationSchedule {
            schedule: HashMap::new(),
        }
    }

    fn add_operation(&mut self, page: Page, op: CompoundPageOperation) {
        self.schedule.insert(page, op);
    }

    fn build_schedule(pages: &[Page], ops: &[CompoundPageOperation]) -> Result<Self, OperationScheduleError> {
        if pages.len() == ops.len() {

            let mut schedule = OperationSchedule::new();

            for page_number in 0..pages.len() {
                schedule.add_operation(pages[page_number].clone(), ops[page_number].clone());
            }

            Ok(schedule)

        } else {
            Err(OperationScheduleError::LengthMismatch)
        }

    }

    fn iter(&self) -> OpSchedIter {
        OpSchedIter {
            inner: self.schedule.iter()
        }
    }

    fn run_operation<Op>(&self) -> OperationResults
        where Op: ElementaryPageOperations {

        let mut results = OperationResults::new();

        for (page, op) in self {
            let result = op.run_operation::<Op>();
            results.append(result);
        }

        results
    }

}

struct OpSchedIter<'a> {
    inner:  hash_map::Iter<'a, Page, CompoundPageOperation>
}

impl<'a> Iterator for OpSchedIter<'a> {
    type Item = (&'a Page, &'a CompoundPageOperation);

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }

}

impl<'a> IntoIterator for &'a OperationSchedule {
    type Item = (&'a Page, &'a CompoundPageOperation);
    type IntoIter = OpSchedIter<'a>;

    fn into_iter(self) -> OpSchedIter<'a> {
        self.iter()
    }
}

struct OpSchedIntoIter {
    inner: hash_map::IntoIter<Page, CompoundPageOperation>,
}

impl IntoIterator for OperationSchedule {
    type Item = (Page, CompoundPageOperation);
    type IntoIter = OpSchedIntoIter;

    fn into_iter(self) -> OpSchedIntoIter {
        OpSchedIntoIter {
            inner: self.schedule.into_iter()
        }
    }
}

impl Iterator for OpSchedIntoIter {
    type Item = (Page, CompoundPageOperation);

    fn next(&mut self) -> Option<(Page, CompoundPageOperation)> {
        self.inner.next()
    }
}
<|endoftext|>


<commit_before>use hyper::client::{Client, Response};
use hyper::method::Method;

use std::process::{Child, Command, Stdio};
use std::thread;
use std::io::Read;
use std::sync::Mutex;
use std::env;

struct Bomb(Child);

// Don't leak child processes!
impl Drop for Bomb {
    fn drop(&mut self) {
        match self.0.kill() {
            Ok(()) => {},
            Err(e) => panic!("Leaking child process: {:?}", e)
        }

        if thread::panicking() {
            let mut s = String::new();
            let stdout = self.0.stdout.as_mut().unwrap();
            stdout.read_to_string(&mut s).unwrap();

            println!("Unparsed Stdout:\n{}", s);
        }
    }
}

pub fn response_for_post(url: &str, body: &str) -> Response {
    Client::new()
           .post(url)
           .body(body)
           .send()
           .unwrap()
}

pub fn response_for_method(method: Method, url: &str) -> Response {
    Client::new()
           .request(method, url)
           .send()
           .unwrap()
}

pub fn response_for(url: &str) -> Response {
    response_for_method(Method::Get, url)
}

pub fn read_body_to_string(res: &mut Response) -> String {
    let mut s = String::new();
    res.read_to_string(&mut s).unwrap();
    s
}

pub fn read_url(url: &str) -> String {
    let mut res = response_for(url);
    read_body_to_string(&mut res)
}

pub fn run_example<F>(name: &str, f: F)
where F: FnOnce(u16) {
    cargo_build(name);

    let command = format!("target/debug/examples/{}", name);
    let child = Command::new(&command)
                        .env("NICKEL_TEST_HARNESS", "1")
                        .stdout(Stdio::piped())
                        .spawn()
                        .unwrap();

    let mut bomb = Bomb(child);
    let port = parse_port(&mut bomb);

    f(port);
}

// We cannot use `cargo run --example foo` as when a test fails
// we can only send SIGKILL, which cargo doesn't propogate to the
// child process. Rust currently doesn't seem to give us a way to
// use SIGTERM.
//
// We do a full build call rather than just checking if the executable
// exists, as the dependancies may have changed and then a user running
// `cargo test --test foo` to run the integration tests only will not
// pick up the changes.
fn cargo_build(name: &str) {
    // Don't let cargo build in parallel, it can cause unnecessary test failures
    // https://github.com/rust-lang/cargo/issues/354
    //
    // NOTE: important to assign to variable or it'll drop instantly.
    let _lock = BUILD_LOCK.lock();

    let mut command = Command::new("cargo");

    command.env("NICKEL_TEST_HARNESS", "1")
           .stdout(Stdio::piped())
           .arg("build")
           .arg("--example")
           .arg(name);

    // support for features passed in the env (as we do on travis)
    if let Some(arg) = env::var("FEATURES").ok() {
        for feature_arg in arg.split_whitespace() {
            command.arg(feature_arg);
        }
    }

    let mut child = command.spawn().unwrap();
    child.wait().unwrap();
}

lazy_static! {
    static ref BUILD_LOCK : Mutex<()> = Mutex::new(());
}

fn parse_port(&mut Bomb(ref mut process): &mut Bomb) -> u16 {
    // stdout doesn't implement BufRead... *shrug*
    let stdout = process.stdout.as_mut().unwrap();

    let mut line = String::new();

    for c in stdout.bytes().map(|b| b.unwrap() as char) {
        if c == '\n' {
            // Check if it's the line we want
            if line.starts_with("Listening") {
                break
            } else {
                println!("Skipping Stdout line: {:?}", line);
                line.clear();
            }
        } else {
            line.push(c)
        }
    }

    let port = {
        let s = line.rsplitn(2, ':').next().unwrap();
        match s.parse() {
            Ok(port) => port,
            Err(e) => panic!("Failed to parse port from: {:?} : {:?}", line, e)
        }
    };

    println!("Parsed: port={} from {:?}", port, line);
    port
}
<commit_msg>Added files via upload<commit_after>

pub fn run_example  ()  {

println!("NN: ");

}

<|endoftext|>


<commit_before>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::{
    peer_manager::{PeerManager, PeerScoreUpdateType},
    PeerId,
};
use channel;
use network::validator_network::StateSynchronizerSender;
use std::collections::HashMap;

#[test]
fn test_peer_manager() {
    let peers = vec![
        PeerId::random(),
        PeerId::random(),
        PeerId::random(),
        PeerId::random(),
    ];
    let mut peer_manager = PeerManager::new(peers.clone());
    let (network_reqs_tx, _) = channel::new_test(8);
    let sender = StateSynchronizerSender::new(network_reqs_tx);
    for peer_id in peers.clone() {
        peer_manager.enable_peer(peer_id, sender.clone());
    }

    for _ in 0..50 {
        peer_manager.update_score(&peers[0], PeerScoreUpdateType::InvalidChunk);
    }

    let mut pick_counts = HashMap::new();
    for _ in 0..1000 {
        let (picked_peer_id, _) = peer_manager.pick_peer().unwrap();
        let counter = pick_counts.entry(picked_peer_id).or_insert(0);
        *counter += 1;
    }

    assert!(pick_counts.get(&peers[0]).unwrap() < pick_counts.get(&peers[1]).unwrap());
    assert!(pick_counts.get(&peers[0]).unwrap() < pick_counts.get(&peers[2]).unwrap());
    assert!(pick_counts.get(&peers[0]).unwrap() < pick_counts.get(&peers[3]).unwrap());
}

#[test]
fn test_remove_requests() {
    let peers = vec![PeerId::random(), PeerId::random()];
    let mut peer_manager = PeerManager::new(peers.clone());

    peer_manager.process_request(1, peers[0]);
    peer_manager.process_request(3, peers[1]);
    peer_manager.process_request(5, peers[0]);
    peer_manager.process_request(10, peers[0]);
    peer_manager.process_request(12, peers[1]);

    peer_manager.remove_requests(5);

    assert!(!peer_manager.has_requested(1, peers[0]));
    assert!(!peer_manager.has_requested(3, peers[1]));
    assert!(!peer_manager.has_requested(5, peers[0]));
    assert!(peer_manager.has_requested(10, peers[0]));
    assert!(peer_manager.has_requested(12, peers[1]));
}
<commit_msg>[state-sync] Fixing flaky peer manager test<commit_after>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::{
    peer_manager::{PeerManager, PeerScoreUpdateType},
    PeerId,
};
use channel;
use network::validator_network::StateSynchronizerSender;
use std::collections::HashMap;

#[test]
fn test_peer_manager() {
    let peers = vec![
        PeerId::random(),
        PeerId::random(),
        PeerId::random(),
        PeerId::random(),
    ];
    let mut peer_manager = PeerManager::new(peers.clone());
    let (network_reqs_tx, _) = channel::new_test(8);
    let sender = StateSynchronizerSender::new(network_reqs_tx);
    for peer_id in peers.clone() {
        peer_manager.enable_peer(peer_id, sender.clone());
    }

    for _ in 0..50 {
        peer_manager.update_score(&peers[0], PeerScoreUpdateType::InvalidChunk);
    }

    let mut pick_counts = HashMap::new();
    for _ in 0..1000 {
        let (picked_peer_id, _) = peer_manager.pick_peer().unwrap();
        let counter = pick_counts.entry(picked_peer_id).or_insert(0);
        *counter += 1;
    }

    // unwrap_or needed because the peer with bad score may never be picked, and may be
    // missing from pick_counts
    assert!(pick_counts.get(&peers[0]).unwrap_or(&0) < pick_counts.get(&peers[1]).unwrap());
    assert!(pick_counts.get(&peers[0]).unwrap_or(&0) < pick_counts.get(&peers[2]).unwrap());
    assert!(pick_counts.get(&peers[0]).unwrap_or(&0) < pick_counts.get(&peers[3]).unwrap());
}

#[test]
fn test_remove_requests() {
    let peers = vec![PeerId::random(), PeerId::random()];
    let mut peer_manager = PeerManager::new(peers.clone());

    peer_manager.process_request(1, peers[0]);
    peer_manager.process_request(3, peers[1]);
    peer_manager.process_request(5, peers[0]);
    peer_manager.process_request(10, peers[0]);
    peer_manager.process_request(12, peers[1]);

    peer_manager.remove_requests(5);

    assert!(!peer_manager.has_requested(1, peers[0]));
    assert!(!peer_manager.has_requested(3, peers[1]));
    assert!(!peer_manager.has_requested(5, peers[0]));
    assert!(peer_manager.has_requested(10, peers[0]));
    assert!(peer_manager.has_requested(12, peers[1]));
}
<|endoftext|>


<commit_before>//! Signature verification support for Rustup.

// TODO: Determine whether we want external keyring support

use std::io::Read;

use anyhow::Result;

use sequoia_openpgp::{
    parse::{stream::*, Parse},
    policy, Cert, KeyHandle,
};

use crate::config::PgpPublicKey;

/// Returns the index of the cert in `certs` that verifies a
/// signature.
///
/// Ignores any signatures that are bad for any reason.  If no
/// signature could be verified, returns `None`.
// XXX: This is a bit of an odd policy.  Shouldn't we fail if we
// encounter a single bad signature (bad as in checksum doesn't check
// out, not bad as in we don't have the key)?
pub(crate) fn verify_signature<T: Read + Send + Sync>(
    content: T,
    signature: &str,
    certs: &[PgpPublicKey],
) -> Result<Option<usize>> {
    let p = policy::StandardPolicy::new();
    let helper = Helper::new(certs);
    let mut v = DetachedVerifierBuilder::from_reader(signature.as_bytes())?
        .with_policy(&p, None, helper)?;
    v.verify_reader(content)?;
    Ok(v.into_helper().index)
}

struct Helper<'a> {
    certs: &'a [PgpPublicKey],
    // The index of the cert in certs that successfully verified a
    // signature.
    index: Option<usize>,
}

impl<'a> Helper<'a> {
    fn new(certs: &'a [PgpPublicKey]) -> Self {
        Helper { certs, index: None }
    }
}

impl VerificationHelper for Helper<'_> {
    fn get_certs(&mut self, _: &[KeyHandle]) -> anyhow::Result<Vec<Cert>> {
        Ok(self.certs.iter().map(|c| c.cert().clone()).collect())
    }

    fn check(&mut self, structure: MessageStructure<'_>) -> anyhow::Result<()> {
        for layer in structure.into_iter() {
            match layer {
                MessageLayer::SignatureGroup { results } => {
                    for result in results {
                        match result {
                            Ok(GoodChecksum { ka, .. }) => {
                                // A good signature!  Find the index
                                // of the singer key and return
                                // success.
                                self.index = self.certs.iter().position(|c| c.cert() == ka.cert());
                                assert!(self.index.is_some());
                                return Ok(());
                            }
                            _ => {
                                // We ignore any errors.
                            }
                        }
                    }
                }
                MessageLayer::Compression { .. } => {
                    unreachable!("we're verifying detached signatures")
                }
                MessageLayer::Encryption { .. } => {
                    unreachable!("we're verifying detached signatures")
                }
            }
        }

        Ok(())
    }
}
<commit_msg>Make single_match clippy happy<commit_after>//! Signature verification support for Rustup.

// TODO: Determine whether we want external keyring support

use std::io::Read;

use anyhow::Result;

use sequoia_openpgp::{
    parse::{stream::*, Parse},
    policy, Cert, KeyHandle,
};

use crate::config::PgpPublicKey;

/// Returns the index of the cert in `certs` that verifies a
/// signature.
///
/// Ignores any signatures that are bad for any reason.  If no
/// signature could be verified, returns `None`.
// XXX: This is a bit of an odd policy.  Shouldn't we fail if we
// encounter a single bad signature (bad as in checksum doesn't check
// out, not bad as in we don't have the key)?
pub(crate) fn verify_signature<T: Read + Send + Sync>(
    content: T,
    signature: &str,
    certs: &[PgpPublicKey],
) -> Result<Option<usize>> {
    let p = policy::StandardPolicy::new();
    let helper = Helper::new(certs);
    let mut v = DetachedVerifierBuilder::from_reader(signature.as_bytes())?
        .with_policy(&p, None, helper)?;
    v.verify_reader(content)?;
    Ok(v.into_helper().index)
}

struct Helper<'a> {
    certs: &'a [PgpPublicKey],
    // The index of the cert in certs that successfully verified a
    // signature.
    index: Option<usize>,
}

impl<'a> Helper<'a> {
    fn new(certs: &'a [PgpPublicKey]) -> Self {
        Helper { certs, index: None }
    }
}

impl VerificationHelper for Helper<'_> {
    fn get_certs(&mut self, _: &[KeyHandle]) -> anyhow::Result<Vec<Cert>> {
        Ok(self.certs.iter().map(|c| c.cert().clone()).collect())
    }

    fn check(&mut self, structure: MessageStructure<'_>) -> anyhow::Result<()> {
        for layer in structure.into_iter() {
            match layer {
                MessageLayer::SignatureGroup { results } => {
                    // We ignore any errors for now.
                    for GoodChecksum { ka, .. } in results.into_iter().flatten() {
                        // A good signature!  Find the index
                        // of the signer key and return
                        // success.
                        self.index = self.certs.iter().position(|c| c.cert() == ka.cert());
                        assert!(self.index.is_some());
                    }
                }
                MessageLayer::Compression { .. } => {
                    unreachable!("we're verifying detached signatures")
                }
                MessageLayer::Encryption { .. } => {
                    unreachable!("we're verifying detached signatures")
                }
            }
        }

        Ok(())
    }
}
<|endoftext|>


<commit_before>use super::schema::*;
use diesel::*;

#[test]
fn boxed_queries_can_be_executed() {
    let connection = connection_with_sean_and_tess_in_users_table();
    insert(&NewUser::new("Jim", None)).into(users::table)
        .execute(&connection).unwrap();
    let query_which_fails_unless_all_segments_are_applied =
        users::table
            .select(users::name)
            .filter(users::name.ne("jim"))
            .order(users::name.desc())
            .limit(1)
            .offset(1)
            .into_boxed();

    let expected_data = vec!["Sean".to_string()];
    let data = query_which_fails_unless_all_segments_are_applied.load(&connection);
    assert_eq!(Ok(expected_data), data);
}

#[test]
fn boxed_queries_can_differ_conditionally() {
    let connection = connection_with_sean_and_tess_in_users_table();
    insert(&NewUser::new("Jim", None)).into(users::table)
        .execute(&connection).unwrap();

    enum Query { All, Ordered, One };
    let source = |query| {
        match query {
            Query::All => users::table.into_boxed(),
            Query::Ordered =>
                users::table
                    .order(users::name.desc())
                    .into_boxed(),
            Query::One =>
                users::table
                    .filter(users::name.ne("jim"))
                    .order(users::name.desc())
                    .limit(1)
                    .offset(1)
                    .into_boxed(),
        }
    };
    let sean = find_user_by_name("Sean", &connection);
    let tess = find_user_by_name("Tess", &connection);
    let jim = find_user_by_name("Jim", &connection);

    let all = source(Query::All).load(&connection);
    let expected_data = vec![sean.clone(), tess.clone(), jim.clone()];
    assert_eq!(Ok(expected_data), all);

    let ordered = source(Query::Ordered).load(&connection);
    let expected_data = vec![tess.clone(), sean.clone(), jim.clone()];
    assert_eq!(Ok(expected_data), ordered);

    let one = source(Query::One).load(&connection);
    let expected_data = vec![sean.clone()];
    assert_eq!(Ok(expected_data), one);
}

#[test]
fn boxed_queries_implement_select_dsl() {
    let connection = connection_with_sean_and_tess_in_users_table();
    let data = users::table.into_boxed().select(users::name)
        .load::<String>(&connection);
    assert_eq!(Ok(vec!["Sean".into(), "Tess".into()]), data);
}

#[test]
fn boxed_queries_implement_filter_dsl() {
    let connection = connection_with_sean_and_tess_in_users_table();
    insert(&NewUser::new("Shane", None)).into(users::table)
        .execute(&connection).unwrap();
    let data = users::table.into_boxed()
        .select(users::name)
        .filter(users::name.ne("Sean"))
        .filter(users::name.like("S%"))
        .load(&connection);
    assert_eq!(Ok(vec![String::from("Shane")]), data);
}

#[test]
fn boxed_queries_implement_limit_dsl() {
    let connection = connection_with_sean_and_tess_in_users_table();
    let data = users::table.into_boxed().limit(1).load(&connection);
    let expected_data = vec![find_user_by_name("Sean", &connection)];
    assert_eq!(Ok(expected_data), data);
}

#[test]
fn boxed_queries_implement_offset_dsl() {
    let connection = connection_with_sean_and_tess_in_users_table();
    let data = users::table.into_boxed().offset(1).load(&connection);
    let expected_data = vec![find_user_by_name("Tess", &connection)];
    assert_eq!(Ok(expected_data), data);
}

#[test]
fn boxed_queries_implement_order_dsl() {
    let connection = connection_with_sean_and_tess_in_users_table();
    let data = users::table.into_boxed().order(users::name.desc())
        .load(&connection);
    let expected_data = vec![
        find_user_by_name("Tess", &connection),
        find_user_by_name("Sean", &connection),
    ];
    assert_eq!(Ok(expected_data), data);
}
<commit_msg>Fix failing tests<commit_after>use super::schema::*;
use diesel::*;

#[test]
fn boxed_queries_can_be_executed() {
    let connection = connection_with_sean_and_tess_in_users_table();
    insert(&NewUser::new("Jim", None)).into(users::table)
        .execute(&connection).unwrap();
    let query_which_fails_unless_all_segments_are_applied =
        users::table
            .select(users::name)
            .filter(users::name.ne("jim"))
            .order(users::name.desc())
            .limit(1)
            .offset(1)
            .into_boxed();

    let expected_data = vec!["Sean".to_string()];
    let data = query_which_fails_unless_all_segments_are_applied.load(&connection);
    assert_eq!(Ok(expected_data), data);
}

#[test]
fn boxed_queries_can_differ_conditionally() {
    let connection = connection_with_sean_and_tess_in_users_table();
    insert(&NewUser::new("Jim", None)).into(users::table)
        .execute(&connection).unwrap();

    enum Query { All, Ordered, One };
    let source = |query| {
        match query {
            Query::All => users::table.into_boxed(),
            Query::Ordered =>
                users::table
                    .order(users::name.desc())
                    .into_boxed(),
            Query::One =>
                users::table
                    .filter(users::name.ne("jim"))
                    .order(users::name.desc())
                    .limit(1)
                    .offset(1)
                    .into_boxed(),
        }
    };
    let sean = find_user_by_name("Sean", &connection);
    let tess = find_user_by_name("Tess", &connection);
    let jim = find_user_by_name("Jim", &connection);

    let all = source(Query::All).load(&connection);
    let expected_data = vec![sean.clone(), tess.clone(), jim.clone()];
    assert_eq!(Ok(expected_data), all);

    let ordered = source(Query::Ordered).load(&connection);
    let expected_data = vec![tess.clone(), sean.clone(), jim.clone()];
    assert_eq!(Ok(expected_data), ordered);

    let one = source(Query::One).load(&connection);
    let expected_data = vec![sean.clone()];
    assert_eq!(Ok(expected_data), one);
}

#[test]
fn boxed_queries_implement_select_dsl() {
    let connection = connection_with_sean_and_tess_in_users_table();
    let data = users::table.into_boxed().select(users::name)
        .load::<String>(&connection);
    assert_eq!(Ok(vec!["Sean".into(), "Tess".into()]), data);
}

#[test]
fn boxed_queries_implement_filter_dsl() {
    let connection = connection_with_sean_and_tess_in_users_table();
    insert(&NewUser::new("Shane", None)).into(users::table)
        .execute(&connection).unwrap();
    let data = users::table.into_boxed()
        .select(users::name)
        .filter(users::name.ne("Sean"))
        .filter(users::name.like("S%"))
        .load(&connection);
    assert_eq!(Ok(vec![String::from("Shane")]), data);
}

#[test]
fn boxed_queries_implement_limit_dsl() {
    let connection = connection_with_sean_and_tess_in_users_table();
    let data = users::table.into_boxed().limit(1).load(&connection);
    let expected_data = vec![find_user_by_name("Sean", &connection)];
    assert_eq!(Ok(expected_data), data);
}

#[test]
fn boxed_queries_implement_offset_dsl() {
    let connection = connection_with_sean_and_tess_in_users_table();
    let data = users::table.into_boxed()
        .limit(1)
        .offset(1)
        .load(&connection);
    let expected_data = vec![find_user_by_name("Tess", &connection)];
    assert_eq!(Ok(expected_data), data);
}

#[test]
fn boxed_queries_implement_order_dsl() {
    let connection = connection_with_sean_and_tess_in_users_table();
    let data = users::table.into_boxed().order(users::name.desc())
        .load(&connection);
    let expected_data = vec![
        find_user_by_name("Tess", &connection),
        find_user_by_name("Sean", &connection),
    ];
    assert_eq!(Ok(expected_data), data);
}
<|endoftext|>


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

#![unstable(feature = "futures_api",
            reason = "futures in libcore are unstable",
            issue = "50547")]

use fmt;
use future::{FutureObj, LocalFutureObj};

/// A task executor.
///
/// A *task* is a `()`-producing async value that runs at the top level, and will
/// be `poll`ed until completion. It's also the unit at which wake-up
/// notifications occur. Executors, such as thread pools, allow tasks to be
/// spawned and are responsible for putting tasks onto ready queues when
/// they are woken up, and polling them when they are ready.
pub trait Executor {
    /// Spawn the given task, polling it until completion.
    ///
    /// # Errors
    ///
    /// The executor may be unable to spawn tasks, either because it has
    /// been shut down or is resource-constrained.
    fn spawn_obj(&mut self, task: FutureObj<'static, ()>) -> Result<(), SpawnObjError>;

    /// Determine whether the executor is able to spawn new tasks.
    ///
    /// # Returns
    ///
    /// An `Ok` return means the executor is *likely* (but not guaranteed)
    /// to accept a subsequent spawn attempt. Likewise, an `Err` return
    /// means that `spawn` is likely, but not guaranteed, to yield an error.
    #[inline]
    fn status(&self) -> Result<(), SpawnErrorKind> {
        Ok(())
    }
}

/// Provides the reason that an executor was unable to spawn.
pub struct SpawnErrorKind {
    _hidden: (),
}

impl fmt::Debug for SpawnErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("SpawnErrorKind")
            .field(&"shutdown")
            .finish()
    }
}

impl SpawnErrorKind {
    /// Spawning is failing because the executor has been shut down.
    pub fn shutdown() -> SpawnErrorKind {
        SpawnErrorKind { _hidden: () }
    }

    /// Check whether this error is the `shutdown` error.
    pub fn is_shutdown(&self) -> bool {
        true
    }
}

/// The result of a failed spawn
#[derive(Debug)]
pub struct SpawnObjError {
    /// The kind of error
    pub kind: SpawnErrorKind,

    /// The task for which spawning was attempted
    pub task: FutureObj<'static, ()>,
}

/// The result of a failed spawn
#[derive(Debug)]
pub struct SpawnLocalObjError {
    /// The kind of error
    pub kind: SpawnErrorKind,

    /// The task for which spawning was attempted
    pub task: LocalFutureObj<'static, ()>,
}
<commit_msg>Rollup merge of #52610 - MajorBreakfast:task-terminology, r=cramertj<commit_after>// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

#![unstable(feature = "futures_api",
            reason = "futures in libcore are unstable",
            issue = "50547")]

use fmt;
use future::{FutureObj, LocalFutureObj};

/// A task executor.
///
/// Futures are polled until completion by tasks, a kind of lightweight
/// "thread". A *task executor* is responsible for the creation of these tasks
/// and the coordination of their execution on real operating system threads. In
/// particular, whenever a task signals that it can make further progress via a
/// wake-up notification, it is the responsibility of the task executor to put
/// the task into a queue to continue executing it, i.e. polling the future in
/// it, later.
pub trait Executor {
    /// Spawns a new task with the given future. The future will be polled until
    /// completion.
    ///
    /// # Errors
    ///
    /// The executor may be unable to spawn tasks, either because it has
    /// been shut down or is resource-constrained.
    fn spawn_obj(
        &mut self,
        future: FutureObj<'static, ()>,
    ) -> Result<(), SpawnObjError>;

    /// Determines whether the executor is able to spawn new tasks.
    ///
    /// # Returns
    ///
    /// An `Ok` return means the executor is *likely* (but not guaranteed)
    /// to accept a subsequent spawn attempt. Likewise, an `Err` return
    /// means that `spawn` is likely, but not guaranteed, to yield an error.
    #[inline]
    fn status(&self) -> Result<(), SpawnErrorKind> {
        Ok(())
    }
}

/// Provides the reason that an executor was unable to spawn.
pub struct SpawnErrorKind {
    _hidden: (),
}

impl fmt::Debug for SpawnErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("SpawnErrorKind")
            .field(&"shutdown")
            .finish()
    }
}

impl SpawnErrorKind {
    /// Spawning is failing because the executor has been shut down.
    pub fn shutdown() -> SpawnErrorKind {
        SpawnErrorKind { _hidden: () }
    }

    /// Check whether this error is the `shutdown` error.
    pub fn is_shutdown(&self) -> bool {
        true
    }
}

/// The result of a failed spawn
#[derive(Debug)]
pub struct SpawnObjError {
    /// The kind of error
    pub kind: SpawnErrorKind,

    /// The future for which spawning inside a task was attempted
    pub future: FutureObj<'static, ()>,
}

/// The result of a failed spawn
#[derive(Debug)]
pub struct SpawnLocalObjError {
    /// The kind of error
    pub kind: SpawnErrorKind,

    /// The future for which spawning inside a task was attempted
    pub future: LocalFutureObj<'static, ()>,
}
<|endoftext|>


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

use libc::{c_char, c_int};
use libc;
use std::mem;
use std::ptr::{null, mut_null};
use std::rt::rtio;
use std::rt::rtio::IoError;

use super::net;

pub struct GetAddrInfoRequest;

impl GetAddrInfoRequest {
    pub fn run(host: Option<&str>, servname: Option<&str>,
               hint: Option<rtio::AddrinfoHint>)
        -> Result<Vec<rtio::AddrinfoInfo>, IoError>
    {
        assert!(host.is_some() || servname.is_some());

        let c_host = host.map(|x| x.to_c_str());
        let c_serv = servname.map(|x| x.to_c_str());

        let hint = hint.map(|hint| {
            libc::addrinfo {
                ai_flags: hint.flags as c_int,
                ai_family: hint.family as c_int,
                ai_socktype: 0,
                ai_protocol: 0,
                ai_addrlen: 0,
                ai_canonname: mut_null(),
                ai_addr: mut_null(),
                ai_next: mut_null()
            }
        });

        let hint_ptr = hint.as_ref().map_or(null(), |x| {
            x as *const libc::addrinfo
        });
        let mut res = mut_null();

        // Make the call
        let s = unsafe {
            let ch = if c_host.is_none() { null() } else { c_host.unwrap().as_ptr() };
            let cs = if c_serv.is_none() { null() } else { c_serv.unwrap().as_ptr() };
            getaddrinfo(ch, cs, hint_ptr, &mut res)
        };

        // Error?
        if s != 0 {
            return Err(get_error(s));
        }

        // Collect all the results we found
        let mut addrs = Vec::new();
        let mut rp = res;
        while rp.is_not_null() {
            unsafe {
                let addr = match net::sockaddr_to_addr(mem::transmute((*rp).ai_addr),
                                                       (*rp).ai_addrlen as uint) {
                    Ok(a) => a,
                    Err(e) => return Err(e)
                };
                addrs.push(rtio::AddrinfoInfo {
                    address: addr,
                    family: (*rp).ai_family as uint,
                    socktype: 0,
                    protocol: 0,
                    flags: (*rp).ai_flags as uint
                });

                rp = (*rp).ai_next as *mut libc::addrinfo;
            }
        }

        unsafe { freeaddrinfo(res); }

        Ok(addrs)
    }
}

extern "system" {
    fn getaddrinfo(node: *const c_char, service: *const c_char,
                   hints: *const libc::addrinfo,
                   res: *mut *mut libc::addrinfo) -> c_int;
    fn freeaddrinfo(res: *mut libc::addrinfo);
    #[cfg(not(windows))]
    fn gai_strerror(errcode: c_int) -> *const c_char;
}

#[cfg(windows)]
fn get_error(_: c_int) -> IoError {
    net::last_error()
}

#[cfg(not(windows))]
fn get_error(s: c_int) -> IoError {
    use std::c_str::CString;

    let err_str = unsafe {
        CString::new(gai_strerror(s), false).as_str().unwrap().to_string()
    };
    IoError {
        code: s as uint,
        extra: 0,
        detail: Some(err_str),
    }
}
<commit_msg>Test fixes from the rollup<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use libc::{c_char, c_int};
use libc;
use std::mem;
use std::ptr::{null, mut_null};
use std::rt::rtio;
use std::rt::rtio::IoError;

use super::net;

pub struct GetAddrInfoRequest;

impl GetAddrInfoRequest {
    pub fn run(host: Option<&str>, servname: Option<&str>,
               hint: Option<rtio::AddrinfoHint>)
        -> Result<Vec<rtio::AddrinfoInfo>, IoError>
    {
        assert!(host.is_some() || servname.is_some());

        let c_host = host.map(|x| x.to_c_str());
        let c_host = c_host.as_ref().map(|x| x.as_ptr()).unwrap_or(null());
        let c_serv = servname.map(|x| x.to_c_str());
        let c_serv = c_serv.as_ref().map(|x| x.as_ptr()).unwrap_or(null());

        let hint = hint.map(|hint| {
            libc::addrinfo {
                ai_flags: hint.flags as c_int,
                ai_family: hint.family as c_int,
                ai_socktype: 0,
                ai_protocol: 0,
                ai_addrlen: 0,
                ai_canonname: mut_null(),
                ai_addr: mut_null(),
                ai_next: mut_null()
            }
        });

        let hint_ptr = hint.as_ref().map_or(null(), |x| {
            x as *const libc::addrinfo
        });
        let mut res = mut_null();

        // Make the call
        let s = unsafe {
            getaddrinfo(c_host, c_serv, hint_ptr, &mut res)
        };

        // Error?
        if s != 0 {
            return Err(get_error(s));
        }

        // Collect all the results we found
        let mut addrs = Vec::new();
        let mut rp = res;
        while rp.is_not_null() {
            unsafe {
                let addr = match net::sockaddr_to_addr(mem::transmute((*rp).ai_addr),
                                                       (*rp).ai_addrlen as uint) {
                    Ok(a) => a,
                    Err(e) => return Err(e)
                };
                addrs.push(rtio::AddrinfoInfo {
                    address: addr,
                    family: (*rp).ai_family as uint,
                    socktype: 0,
                    protocol: 0,
                    flags: (*rp).ai_flags as uint
                });

                rp = (*rp).ai_next as *mut libc::addrinfo;
            }
        }

        unsafe { freeaddrinfo(res); }

        Ok(addrs)
    }
}

extern "system" {
    fn getaddrinfo(node: *const c_char, service: *const c_char,
                   hints: *const libc::addrinfo,
                   res: *mut *mut libc::addrinfo) -> c_int;
    fn freeaddrinfo(res: *mut libc::addrinfo);
    #[cfg(not(windows))]
    fn gai_strerror(errcode: c_int) -> *const c_char;
}

#[cfg(windows)]
fn get_error(_: c_int) -> IoError {
    net::last_error()
}

#[cfg(not(windows))]
fn get_error(s: c_int) -> IoError {
    use std::c_str::CString;

    let err_str = unsafe {
        CString::new(gai_strerror(s), false).as_str().unwrap().to_string()
    };
    IoError {
        code: s as uint,
        extra: 0,
        detail: Some(err_str),
    }
}
<|endoftext|>


<commit_before>//  rpc-perf - RPC Performance Testing
//  Copyright 2015 Twitter, Inc
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

#![crate_type = "lib"]

extern crate mpmc;
extern crate pad;
extern crate rand;
extern crate ratelimit;
extern crate rpcperf_request as request;
extern crate shuteye;
extern crate time;

const ONE_SECOND: u64 = 1_000_000_000;
pub const BUCKET_SIZE: usize = 10_000;

use mpmc::Queue as BoundedQueue;
use pad::{PadStr, Alignment};
use rand::{thread_rng, Rng};
use ratelimit::Ratelimit;
use request::{echo, memcache, ping, redis, thrift};
use std::str;
use request::thrift::*;

#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Protocol {
    Echo,
    Memcache,
    Ping,
    Redis,
    Thrift,
    Unknown,
}

impl Protocol {
    pub fn new(protocol: &str) -> Result<Protocol, &'static str> {
        match &*protocol {
            "echo" => Ok(Protocol::Echo),
            "memcache" => Ok(Protocol::Memcache),
            "ping" => Ok(Protocol::Ping),
            "redis" => Ok(Protocol::Redis),
            "thrift" => Ok(Protocol::Thrift),
            _ => Err("unknown protocol"),
        }
    }
}

pub fn rate_to_interval(rate: u64) -> u64 {
    if rate == 0 {
        return 0;
    }
    let interval = ONE_SECOND / rate;
    if interval < 1 {
        return 0;
    }
    interval
}

fn random_string(size: usize) -> String {
    thread_rng().gen_ascii_chars().take(size).collect()
}

fn seeded_string(size: usize, seed: usize) -> String {
    let s = format!("{}", seed);
    s.pad(size, '0', Alignment::Right, true)
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Type {
    Stop,
    Void,
    Bool,
    Byte,
    Double,
    Int16,
    Int32,
    Int64,
    String,
    Struct,
    Map,
    Set,
    List(String),
    None,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Style {
    Random,
    Static,
}

#[derive(Clone, Debug)]
pub struct Parameter {
    pub id: Option<i16>,
    pub ptype: Type,
    pub seed: usize,
    pub size: usize,
    pub style: Style,
    pub regenerate: bool,
    pub value: Value,
}

#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    Stop,
    Void,
    Bool(bool),
    Byte(u8),
    Double(f64),
    Int16(i16),
    Int32(i32),
    Int64(i64),
    String(String),
    Struct,
    Map,
    Set,
    List(String, i32),
    None,
}

impl Default for Value {
    fn default() -> Value {
        Value::None
    }
}

impl Default for Parameter {
    fn default() -> Parameter {
        Parameter {
            id: None,
            ptype: Type::None,
            seed: 0,
            size: 1,
            style: Style::Static,
            regenerate: false,
            value: Default::default(),
        }
    }
}

pub enum Preparation {
    Flush,
    Hit,
}

pub struct Workload {
    protocol: Protocol,
    command: String,
    rate: u64,
    ratelimit: Ratelimit,
    queue: BoundedQueue<Vec<u8>>,
    parameters: Vec<Parameter>,
    values: Vec<Vec<u8>>,
}

impl Workload {
    pub fn new(protocol: Protocol,
               command: String,
               rate: Option<u64>,
               queue: BoundedQueue<Vec<u8>>)
               -> Result<Workload, &'static str> {
        let r = rate.unwrap_or(0);
        let i = rate_to_interval(r);
        let ratelimit = match Ratelimit::new(BUCKET_SIZE, time::precise_time_ns(), i, 1) {
            Some(r) => r,
            None => {
                return Err("Ratelimit initialization failed!");
            }
        };
        Ok(Workload {
            protocol: protocol,
            command: command,
            rate: rate.unwrap_or(0),
            ratelimit: ratelimit,
            queue: queue,
            parameters: Vec::<Parameter>::new(),
            values: Vec::<Vec<u8>>::new(),
        })
    }

    fn generate_values(&mut self, force: bool) {
        for i in 0..self.parameters.len() {
            match self.parameters[i].style {
                Style::Random => {
                    if self.parameters[i].regenerate || force {
                        self.parameters[i].value = match self.parameters[i].ptype {
                            Type::Stop => Value::Stop,
                            Type::Void => Value::Void,
                            Type::Bool => Value::Bool(rand::random::<bool>()),
                            Type::Int16 => Value::Int16(rand::random::<i16>()),
                            Type::Int32 => Value::Int32(rand::random::<i32>()),
                            Type::Int64 => Value::Int64(rand::random::<i64>()),
                            Type::Struct => Value::Struct,
                            Type::String => Value::String(random_string(self.parameters[i].size)),
                            _ => {
                                self.values[i] = random_string(self.parameters[i].size)
                                                     .into_bytes();
                                Value::None
                            }
                        }
                    }
                }
                Style::Static => {
                    self.parameters[i].value = match self.parameters[i].ptype.clone() {
                        Type::Int16 => Value::Int16(self.parameters[i].seed as i16),
                        Type::Int32 => Value::Int32(self.parameters[i].seed as i32),
                        Type::Int64 => Value::Int64(self.parameters[i].seed as i64),
                        Type::List(ttype) => Value::List(ttype.clone(), self.parameters[i].seed as i32),
                        Type::Stop => Value::Stop,
                        Type::Struct => Value::Struct,
                        _ => {
                            self.values[i] = seeded_string(self.parameters[i].size,
                                                           self.parameters[i].seed)
                                                 .into_bytes();
                            Value::None
                        }
                    }
                }
            }
        }
    }

    pub fn add_param(&mut self, parameter: Parameter) {
        self.parameters.push(parameter);
        self.values.push(Vec::<u8>::new());
    }

    pub fn prepare(&mut self, preparation: Preparation) {
        match preparation {
            Preparation::Flush => {
                match self.protocol {
                    Protocol::Memcache => {
                        let _ = self.queue.push(memcache::flush_all().into_bytes());
                    }
                    Protocol::Redis => {
                        let _ = self.queue.push(redis::flushall().into_bytes());
                    }
                    _ => {}
                }
            }
            Preparation::Hit => {
                match &*self.command {
                    "get" => {
                        match self.protocol {
                            Protocol::Memcache => {
                                if self.values.len() < 2 {
                                    self.values.push(Default::default());
                                }
                                let _ = self.queue
                                            .push(memcache::set(str::from_utf8(&*self.values[0])
                                                                    .unwrap(),
                                                                str::from_utf8(&*self.values[1])
                                                                    .unwrap(),
                                                                None,
                                                                None)
                                                      .into_bytes());
                            }
                            Protocol::Redis => {
                                let _ = self.queue.push(redis::flushall().into_bytes());
                            }
                            _ => {}
                        }
                    }
                    _ => {}
                }
            }
        }
    }

    pub fn run(&mut self) {
        self.generate_values(true);
        loop {
            if self.rate != 0 {
                self.ratelimit.block(1);
            }
            self.generate_values(false);

            let query = match self.protocol {
                Protocol::Echo => {
                    match &*self.command {
                        "echo" => echo::echo(&*self.values[0]),
                        _ => {
                            panic!("unknown command: {} for protocol: {:?}",
                                   self.command,
                                   self.protocol);
                        }
                    }
                }
                Protocol::Memcache => {
                    match &*self.command {
                        "set" => {
                            memcache::set(str::from_utf8(&*self.values[0]).unwrap(),
                                          str::from_utf8(&*self.values[1]).unwrap(),
                                          None,
                                          None)
                                .into_bytes()
                        }
                        "get" => {
                            memcache::get(str::from_utf8(&*self.values[0]).unwrap()).into_bytes()
                        }
                        "gets" => {
                            memcache::gets(str::from_utf8(&*self.values[0]).unwrap()).into_bytes()
                        }
                        "add" => {
                            memcache::add(str::from_utf8(&*self.values[0]).unwrap(),
                                          str::from_utf8(&*self.values[1]).unwrap(),
                                          None,
                                          None)
                                .into_bytes()
                        }
                        _ => {
                            panic!("unknown command: {} for protocol: {:?}",
                                   self.command,
                                   self.protocol);
                        }
                    }
                }
                Protocol::Ping => {
                    match &*self.command {
                        "ping" => ping::ping().into_bytes(),
                        _ => {
                            panic!("unknown command: {} for protocol: {:?}",
                                   self.command,
                                   self.protocol);
                        }
                    }
                }
                Protocol::Redis => {
                    match &*self.command {
                        "set" => {
                            redis::set(str::from_utf8(&*self.values[0]).unwrap(),
                                       str::from_utf8(&*self.values[1]).unwrap())
                                .into_bytes()
                        }
                        "get" => redis::get(str::from_utf8(&*self.values[0]).unwrap()).into_bytes(),
                        "hset" => {
                            redis::hset(str::from_utf8(&*self.values[0]).unwrap(),
                                        str::from_utf8(&*self.values[1]).unwrap(),
                                        str::from_utf8(&*self.values[2]).unwrap())
                                .into_bytes()
                        }
                        "hget" => {
                            redis::hget(str::from_utf8(&*self.values[0]).unwrap(),
                                        str::from_utf8(&*self.values[1]).unwrap())
                                .into_bytes()
                        }
                        _ => {
                            panic!("unknown command: {} for protocol: {:?}",
                                   self.command,
                                   self.protocol);
                        }
                    }
                }
                Protocol::Thrift => {
                    match &*self.command {
                        "ping" => thrift::ping(),
                        _ => {
                            let mut thrift = thrift::ThriftRequest::default();
                            thrift.method = &self.command;
                            for p in &self.parameters {
                                match p.value {
                                    Value::Stop => {
                                        thrift.payload.push(ThriftType::Stop)
                                    }
                                    Value::Void => {
                                        thrift.payload.push(ThriftType::Void)
                                    }
                                    Value::Bool(v) => {
                                        thrift.payload.push(ThriftType::Bool(p.id, v))
                                    }
                                    Value::Byte(v) => {
                                        thrift.payload.push(ThriftType::Byte(p.id, v))
                                    }
                                    Value::Int16(v) => {
                                        thrift.payload.push(ThriftType::Int16(p.id, v))
                                    }
                                    Value::Int32(v) => {
                                        thrift.payload.push(ThriftType::Int32(p.id, v))
                                    }
                                    Value::Int64(v) => {
                                        thrift.payload.push(ThriftType::Int64(p.id, v))
                                    }
                                    Value::String(ref v) => {
                                        thrift.payload.push(ThriftType::String(p.id, v))
                                    }
                                    Value::Struct => {
                                        thrift.payload.push(ThriftType::Struct(p.id.unwrap()))
                                    }
                                    Value::List(ref ttype, length) => {
                                        thrift.payload.push(ThriftType::List(p.id.unwrap(), ttype, length))
                                    }
                                    _ => {}
                                }
                            }
                            thrift::generic(thrift)
                        }
                    }
                }
                _ => {
                    panic!("unsupported protocol");
                }
            };
            let _ = self.queue.push(query);
        }
    }
}
<commit_msg>Reduce indent by using if/else on low cardenality matches<commit_after>//  rpc-perf - RPC Performance Testing
//  Copyright 2015 Twitter, Inc
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.

#![crate_type = "lib"]

extern crate mpmc;
extern crate pad;
extern crate rand;
extern crate ratelimit;
extern crate rpcperf_request as request;
extern crate shuteye;
extern crate time;

const ONE_SECOND: u64 = 1_000_000_000;
pub const BUCKET_SIZE: usize = 10_000;

use mpmc::Queue as BoundedQueue;
use pad::{PadStr, Alignment};
use rand::{thread_rng, Rng};
use ratelimit::Ratelimit;
use request::{echo, memcache, ping, redis, thrift};
use std::str;
use request::thrift::*;

#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Protocol {
    Echo,
    Memcache,
    Ping,
    Redis,
    Thrift,
    Unknown,
}

impl Protocol {
    pub fn new(protocol: &str) -> Result<Protocol, &'static str> {
        match &*protocol {
            "echo" => Ok(Protocol::Echo),
            "memcache" => Ok(Protocol::Memcache),
            "ping" => Ok(Protocol::Ping),
            "redis" => Ok(Protocol::Redis),
            "thrift" => Ok(Protocol::Thrift),
            _ => Err("unknown protocol"),
        }
    }
}

pub fn rate_to_interval(rate: u64) -> u64 {
    if rate == 0 {
        return 0;
    }
    let interval = ONE_SECOND / rate;
    if interval < 1 {
        return 0;
    }
    interval
}

fn random_string(size: usize) -> String {
    thread_rng().gen_ascii_chars().take(size).collect()
}

fn seeded_string(size: usize, seed: usize) -> String {
    let s = format!("{}", seed);
    s.pad(size, '0', Alignment::Right, true)
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Type {
    Stop,
    Void,
    Bool,
    Byte,
    Double,
    Int16,
    Int32,
    Int64,
    String,
    Struct,
    Map,
    Set,
    List(String),
    None,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Style {
    Random,
    Static,
}

#[derive(Clone, Debug)]
pub struct Parameter {
    pub id: Option<i16>,
    pub ptype: Type,
    pub seed: usize,
    pub size: usize,
    pub style: Style,
    pub regenerate: bool,
    pub value: Value,
}

#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    Stop,
    Void,
    Bool(bool),
    Byte(u8),
    Double(f64),
    Int16(i16),
    Int32(i32),
    Int64(i64),
    String(String),
    Struct,
    Map,
    Set,
    List(String, i32),
    None,
}

impl Default for Value {
    fn default() -> Value {
        Value::None
    }
}

impl Default for Parameter {
    fn default() -> Parameter {
        Parameter {
            id: None,
            ptype: Type::None,
            seed: 0,
            size: 1,
            style: Style::Static,
            regenerate: false,
            value: Default::default(),
        }
    }
}

pub enum Preparation {
    Flush,
    Hit,
}

pub struct Workload {
    protocol: Protocol,
    command: String,
    rate: u64,
    ratelimit: Ratelimit,
    queue: BoundedQueue<Vec<u8>>,
    parameters: Vec<Parameter>,
    values: Vec<Vec<u8>>,
}

impl Workload {
    pub fn new(protocol: Protocol,
               command: String,
               rate: Option<u64>,
               queue: BoundedQueue<Vec<u8>>)
               -> Result<Workload, &'static str> {
        let r = rate.unwrap_or(0);
        let i = rate_to_interval(r);
        let ratelimit = match Ratelimit::new(BUCKET_SIZE, time::precise_time_ns(), i, 1) {
            Some(r) => r,
            None => {
                return Err("Ratelimit initialization failed!");
            }
        };
        Ok(Workload {
            protocol: protocol,
            command: command,
            rate: rate.unwrap_or(0),
            ratelimit: ratelimit,
            queue: queue,
            parameters: Vec::<Parameter>::new(),
            values: Vec::<Vec<u8>>::new(),
        })
    }

    fn generate_values(&mut self, force: bool) {
        for i in 0..self.parameters.len() {
            match self.parameters[i].style {
                Style::Random => {
                    if self.parameters[i].regenerate || force {
                        self.parameters[i].value = match self.parameters[i].ptype {
                            Type::Stop => Value::Stop,
                            Type::Void => Value::Void,
                            Type::Bool => Value::Bool(rand::random::<bool>()),
                            Type::Int16 => Value::Int16(rand::random::<i16>()),
                            Type::Int32 => Value::Int32(rand::random::<i32>()),
                            Type::Int64 => Value::Int64(rand::random::<i64>()),
                            Type::Struct => Value::Struct,
                            Type::String => Value::String(random_string(self.parameters[i].size)),
                            _ => {
                                self.values[i] = random_string(self.parameters[i].size)
                                                     .into_bytes();
                                Value::None
                            }
                        }
                    }
                }
                Style::Static => {
                    self.parameters[i].value = match self.parameters[i].ptype.clone() {
                        Type::Int16 => Value::Int16(self.parameters[i].seed as i16),
                        Type::Int32 => Value::Int32(self.parameters[i].seed as i32),
                        Type::Int64 => Value::Int64(self.parameters[i].seed as i64),
                        Type::List(ttype) => {
                            Value::List(ttype.clone(), self.parameters[i].seed as i32)
                        }
                        Type::Stop => Value::Stop,
                        Type::Struct => Value::Struct,
                        _ => {
                            self.values[i] = seeded_string(self.parameters[i].size,
                                                           self.parameters[i].seed)
                                                 .into_bytes();
                            Value::None
                        }
                    }
                }
            }
        }
    }

    pub fn add_param(&mut self, parameter: Parameter) {
        self.parameters.push(parameter);
        self.values.push(Vec::<u8>::new());
    }

    pub fn prepare(&mut self, preparation: Preparation) {
        match preparation {
            Preparation::Flush => {
                if self.protocol == Protocol::Memcache {
                    let _ = self.queue.push(memcache::flush_all().into_bytes());
                } else if self.protocol == Protocol::Redis {
                    let _ = self.queue.push(redis::flushall().into_bytes());
                }
            }
            Preparation::Hit => {
                if &*self.command == "get" {
                    if self.protocol == Protocol::Memcache {
                        if self.values.len() < 2 {
                            self.values.push(Default::default());
                        }
                        let bytes = memcache::set(str::from_utf8(&*self.values[0]).unwrap(),
                                                  str::from_utf8(&*self.values[1]).unwrap(),
                                                  None,
                                                  None);
                        let _ = self.queue.push(bytes.into_bytes());
                    } else if self.protocol == Protocol::Redis {
                        let _ = self.queue.push(redis::flushall().into_bytes());
                    }
                }
            }
        }
    }

    pub fn run(&mut self) {
        self.generate_values(true);
        loop {
            if self.rate != 0 {
                self.ratelimit.block(1);
            }
            self.generate_values(false);

            let query = match self.protocol {
                Protocol::Echo => {
                    if "echo" == &*self.command {
                        echo::echo(&*self.values[0])
                    } else {
                        panic!("unknown command: {} for protocol: {:?}",
                               self.command,
                               self.protocol);
                    }
                }
                Protocol::Memcache => {
                    match &*self.command {
                        "set" => {
                            memcache::set(str::from_utf8(&*self.values[0]).unwrap(),
                                          str::from_utf8(&*self.values[1]).unwrap(),
                                          None,
                                          None)
                                .into_bytes()
                        }
                        "get" => {
                            memcache::get(str::from_utf8(&*self.values[0]).unwrap()).into_bytes()
                        }
                        "gets" => {
                            memcache::gets(str::from_utf8(&*self.values[0]).unwrap()).into_bytes()
                        }
                        "add" => {
                            memcache::add(str::from_utf8(&*self.values[0]).unwrap(),
                                          str::from_utf8(&*self.values[1]).unwrap(),
                                          None,
                                          None)
                                .into_bytes()
                        }
                        _ => {
                            panic!("unknown command: {} for protocol: {:?}",
                                   self.command,
                                   self.protocol);
                        }
                    }
                }
                Protocol::Ping => {
                    if "ping" == &*self.command {
                        ping::ping().into_bytes()
                    } else {
                        panic!("unknown command: {} for protocol: {:?}",
                               self.command,
                               self.protocol);
                    }
                }
                Protocol::Redis => {
                    match &*self.command {
                        "set" => {
                            redis::set(str::from_utf8(&*self.values[0]).unwrap(),
                                       str::from_utf8(&*self.values[1]).unwrap())
                                .into_bytes()
                        }
                        "get" => redis::get(str::from_utf8(&*self.values[0]).unwrap()).into_bytes(),
                        "hset" => {
                            redis::hset(str::from_utf8(&*self.values[0]).unwrap(),
                                        str::from_utf8(&*self.values[1]).unwrap(),
                                        str::from_utf8(&*self.values[2]).unwrap())
                                .into_bytes()
                        }
                        "hget" => {
                            redis::hget(str::from_utf8(&*self.values[0]).unwrap(),
                                        str::from_utf8(&*self.values[1]).unwrap())
                                .into_bytes()
                        }
                        _ => {
                            panic!("unknown command: {} for protocol: {:?}",
                                   self.command,
                                   self.protocol);
                        }
                    }
                }
                Protocol::Thrift => {
                    if "ping" == &*self.command {
                        thrift::ping()
                    } else {
                        let mut thrift = thrift::ThriftRequest::default();
                        thrift.method = &self.command;
                        for p in &self.parameters {
                            match p.value {
                                Value::Stop => thrift.payload.push(ThriftType::Stop),
                                Value::Void => thrift.payload.push(ThriftType::Void),
                                Value::Bool(v) => thrift.payload.push(ThriftType::Bool(p.id, v)),
                                Value::Byte(v) => thrift.payload.push(ThriftType::Byte(p.id, v)),
                                Value::Int16(v) => thrift.payload.push(ThriftType::Int16(p.id, v)),
                                Value::Int32(v) => thrift.payload.push(ThriftType::Int32(p.id, v)),
                                Value::Int64(v) => thrift.payload.push(ThriftType::Int64(p.id, v)),
                                Value::String(ref v) => {
                                    thrift.payload.push(ThriftType::String(p.id, v))
                                }
                                Value::Struct => {
                                    thrift.payload.push(ThriftType::Struct(p.id.unwrap()))
                                }
                                Value::List(ref ttype, length) => {
                                    thrift.payload
                                          .push(ThriftType::List(p.id.unwrap(), ttype, length))
                                }
                                _ => {}
                            }
                        }
                        thrift::generic(thrift)
                    }
                }
                _ => {
                    panic!("unsupported protocol");
                }
            };
            let _ = self.queue.push(query);
        }
    }
}
<|endoftext|>


<commit_before>extern crate core;

use core::num::FromPrimitive;
use core::fmt;

#[derive(Copy)]
#[derive(Show)]
#[derive(FromPrimitive)]
enum Direction {
    SpinUp = 0x1,
    SpinDown = 0x2,
    SpinSuper = 0x3,
}

impl fmt::String for Direction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let r = match self {
            &Direction::SpinUp => "SpinUp",
            &Direction::SpinDown => "SpinDown",
            &Direction::SpinSuper => "SpinSuper"
        };
        write!(f, "{}", r)
    }
}

struct Pair<T> {
    lhs: T,
    rhs: T
}

struct Particle {
    spin: Direction
}

impl Particle {
    fn new_pair () -> Pair<Particle> {
        let d1 = FromPrimitive::from_u8(0x3).expect("unknown direction");
        let d2 = FromPrimitive::from_u8(0x3).expect("unknown direction");
        let p1 = Particle{spin: d1};
        let p2 = Particle{spin: d2};

        return Pair{lhs:p1, rhs: p2};
    }
}

fn main () {

    let particles = Particle::new_pair();

    println!("lhs.spin {}", particles.lhs.spin);
}
<commit_msg>remove useless numeric values of spin<commit_after>extern crate core;

use core::num::FromPrimitive;
use core::fmt;

#[derive(Copy)]
#[derive(Show)]
enum Direction {
    SpinUp,
    SpinDown,
    SpinSuper,
}

impl fmt::String for Direction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let r = match self {
            &Direction::SpinUp => "SpinUp",
            &Direction::SpinDown => "SpinDown",
            &Direction::SpinSuper => "SpinSuper"
        };
        write!(f, "{}", r)
    }
}

struct Pair<T> {
    lhs: T,
    rhs: T
}

struct Particle {
    spin: Direction
}

impl Particle {
    fn new_pair () -> Pair<Particle> {
        let d1 = Direction::SpinSuper;
        let d2 =  Direction::SpinSuper;
        let p1 = Particle{spin: d1};
        let p2 = Particle{spin: d2};

        return Pair{lhs:p1, rhs: p2};
    }
}

fn main () {

    let particles = Particle::new_pair();

    println!("lhs.spin {}", particles.lhs.spin);
}
<|endoftext|>


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

//! Traits for conversions between types.
//!
//! The traits in this module provide a general way to talk about
//! conversions from one type to another. They follow the standard
//! Rust conventions of `as`/`to`/`into`/`from`.

#![stable(feature = "rust1", since = "1.0.0")]

use marker::Sized;

/// A cheap, reference-to-reference conversion.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRef<T: ?Sized> {
    /// Perform the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn as_ref(&self) -> &T;
}

/// A cheap, mutable reference-to-mutable reference conversion.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsMut<T: ?Sized> {
    /// Perform the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn as_mut(&mut self) -> &mut T;
}

/// A conversion that consumes `self`, which may or may not be
/// expensive.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Into<T>: Sized {
    /// Perform the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn into(self) -> T;
}

/// Construct `Self` via a conversion.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait From<T> {
    /// Perform the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn from(T) -> Self;
}

////////////////////////////////////////////////////////////////////////////////
// GENERIC IMPLS
////////////////////////////////////////////////////////////////////////////////

// As lifts over &
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U> {
    fn as_ref(&self) -> &U {
        <T as AsRef<U>>::as_ref(*self)
    }
}

// As lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U> {
    fn as_ref(&self) -> &U {
        <T as AsRef<U>>::as_ref(*self)
    }
}

// FIXME (#23442): replace the above impls for &/&mut with the following more general one:
// // As lifts over Deref
// impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
//     fn as_ref(&self) -> &U {
//         self.deref().as_ref()
//     }
// }

// AsMut lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U> {
    fn as_mut(&mut self) -> &mut U {
        (*self).as_mut()
    }
}

// FIXME (#23442): replace the above impl for &mut with the following more general one:
// // AsMut lifts over DerefMut
// impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
//     fn as_mut(&mut self) -> &mut U {
//         self.deref_mut().as_mut()
//     }
// }

// From implies Into
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, U> Into<U> for T where U: From<T> {
    fn into(self) -> U {
        U::from(self)
    }
}

// From (and thus Into) is reflexive
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> From<T> for T {
    fn from(t: T) -> T { t }
}

////////////////////////////////////////////////////////////////////////////////
// CONCRETE IMPLS
////////////////////////////////////////////////////////////////////////////////

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsRef<[T]> for [T] {
    fn as_ref(&self) -> &[T] {
        self
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsMut<[T]> for [T] {
    fn as_mut(&mut self) -> &mut [T] {
        self
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<str> for str {
    fn as_ref(&self) -> &str {
        self
    }
}
<commit_msg>Auto merge of #24067 - apasel422:patch-1, r=Gankro<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Traits for conversions between types.
//!
//! The traits in this module provide a general way to talk about
//! conversions from one type to another. They follow the standard
//! Rust conventions of `as`/`to`/`into`/`from`.

#![stable(feature = "rust1", since = "1.0.0")]

use marker::Sized;

/// A cheap, reference-to-reference conversion.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRef<T: ?Sized> {
    /// Performs the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn as_ref(&self) -> &T;
}

/// A cheap, mutable reference-to-mutable reference conversion.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsMut<T: ?Sized> {
    /// Performs the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn as_mut(&mut self) -> &mut T;
}

/// A conversion that consumes `self`, which may or may not be
/// expensive.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Into<T>: Sized {
    /// Performs the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn into(self) -> T;
}

/// Construct `Self` via a conversion.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait From<T> {
    /// Performs the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn from(T) -> Self;
}

////////////////////////////////////////////////////////////////////////////////
// GENERIC IMPLS
////////////////////////////////////////////////////////////////////////////////

// As lifts over &
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U> {
    fn as_ref(&self) -> &U {
        <T as AsRef<U>>::as_ref(*self)
    }
}

// As lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U> {
    fn as_ref(&self) -> &U {
        <T as AsRef<U>>::as_ref(*self)
    }
}

// FIXME (#23442): replace the above impls for &/&mut with the following more general one:
// // As lifts over Deref
// impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
//     fn as_ref(&self) -> &U {
//         self.deref().as_ref()
//     }
// }

// AsMut lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U> {
    fn as_mut(&mut self) -> &mut U {
        (*self).as_mut()
    }
}

// FIXME (#23442): replace the above impl for &mut with the following more general one:
// // AsMut lifts over DerefMut
// impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
//     fn as_mut(&mut self) -> &mut U {
//         self.deref_mut().as_mut()
//     }
// }

// From implies Into
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, U> Into<U> for T where U: From<T> {
    fn into(self) -> U {
        U::from(self)
    }
}

// From (and thus Into) is reflexive
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> From<T> for T {
    fn from(t: T) -> T { t }
}

////////////////////////////////////////////////////////////////////////////////
// CONCRETE IMPLS
////////////////////////////////////////////////////////////////////////////////

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsRef<[T]> for [T] {
    fn as_ref(&self) -> &[T] {
        self
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsMut<[T]> for [T] {
    fn as_mut(&mut self) -> &mut [T] {
        self
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<str> for str {
    fn as_ref(&self) -> &str {
        self
    }
}
<|endoftext|>