<commit_before>pub mod village_manager;

use self::village_manager::*;
use village::*;
use village::resource::*;
use village_mind::*;
use village_mind::trade_request::*;
use std::cell::RefCell;
use std::rc::Rc;
use std::collections::HashMap;

#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum PriceDirection {
    Upward,
    Downward,
    Equilibrium,
}

pub struct Simulation {
    village_managers: Vec<VillageManager>,
    pub prices: HashMap<ResourceType, u32>,
    pub price_directions: HashMap<ResourceType, PriceDirection>,
}

impl Simulation {
    pub fn new() -> Simulation {

        let mut simulation = Simulation {
            village_managers: vec!(),
            prices: HashMap::new(),
            price_directions: HashMap::new(),
        };

        //for each resource (other than gold), put the starting price at one gold
        for resource_type in ResourceType::iterator() {
            if *resource_type != ResourceType::Gold {
                simulation.prices.insert(*resource_type, 5);
                simulation.price_directions.insert(*resource_type, PriceDirection::Equilibrium);
            }
        }
        simulation
    }

    pub fn add_village(&mut self, village: Village) {
        let villageRC = Rc::new(RefCell::new(village));
        let village_manager = VillageManager {
            village: villageRC.clone(),
            village_mind: VillageMind::new(villageRC.clone()),
        };

        self.village_managers.push(village_manager);
    }

    pub fn village_managers(&self) -> &Vec<VillageManager> {
        &self.village_managers
    }

    pub fn simulate(&mut self) {
        // update the villages and village minds with the new information
        for vm in self.village_managers.iter_mut() {
            vm.village.borrow_mut().simulate();
            vm.village_mind.manage_village();
        }

        // do the trading phase until no more trade request are given
        let mut trading = true;
        let mut trade_requests : Vec<TradeRequest> = Vec::new();

        while trading {
            trade_requests.clear();

            for mut vm in self.village_managers.iter_mut() {
                trade_requests.append(&mut vm.village_mind.trade());
            }

            if trade_requests.len() == 0 {
                trading = false;
            }
        }

        // update village minds
        for vm in self.village_managers.iter_mut() {
            vm.village_mind.manage_village();
        }
    }

    pub fn handleTrades(&mut self, trade_requests: &mut Vec<TradeRequest>) {
        // see if this is an initial trading session (all prices are at equilibrium), or we are in a current trading session
        let mut initial_trade_session = true;
        for price_direction in self.price_directions.values() {
            if *price_direction != PriceDirection::Equilibrium {
                initial_trade_session = false;
                break;
            }
        }

        // get the trade request for each resource type minus gold
        for resource_type in ResourceType::iterator().filter(|r| **r != ResourceType::Gold) {
            // get the total number of buys and sells requested for a resource at the current price
            let mut buys = 0;
            let mut sells = 0;
            for trade_request in trade_requests.iter_mut().filter(|t| t.resource_type == *resource_type) {
                if trade_request.trade_type == TradeType::Buy {
                    buys += trade_request.request_amount;
                } else {
                    sells += trade_request.request_amount;
                }
            }

            // if number of buys and sells are equal consider the price at equilibrium and fulfill the trade requests
            if buys == sells {
                for trade_request in trade_requests.iter_mut().filter(|t| t.resource_type == *resource_type) {
                    trade_request.fulfilled_amount = trade_request.request_amount;
                }
                self.price_directions.insert(*resource_type, PriceDirection::Equilibrium);
            }
            else if buys > sells {
                if initial_trade_session {
                    // In the initial trade session, if the number of buyers are greater then sellers
                    // the price direction will be upward and the price will increase
                    self.price_directions.insert(*resource_type, PriceDirection::Upward);
                    let price = self.prices.get_mut(resource_type).unwrap();
                    *price += 1;
                }
                else if *self.price_directions.get(resource_type).unwrap() == PriceDirection::Downward {
                    // if the price direction of the resource is downward, we now have more buyers then sellers and found an acceptable equilibrium price
                    // first fulfill all sell request
                    for trade_request in trade_requests.iter_mut().filter(|t| t.resource_type == *resource_type && t.trade_type == TradeType::Sell) {
                        trade_request.fulfilled_amount = trade_request.request_amount;
                    }
                    // iterate through all buy request until we run out of the resource to sell
                    let mut buy_requests : Vec<&mut TradeRequest> = trade_requests.iter_mut()
                        .filter(|t| t.resource_type == *resource_type && t.trade_type == TradeType::Buy)
                        .collect();
                    while sells > 0 {
                        for buy_request in buy_requests.iter_mut() {
                            buy_request.fulfilled_amount += 1;
                            sells -= 1;
                            if sells <= 0 {break;}
                        }
                    }

                    self.price_directions.insert(*resource_type, PriceDirection::Equilibrium);
                }

            }
            // if the number of sellers are greater then the number of buyers, the price direction will be downward and the price will decrease
            else {
                self.price_directions.insert(*resource_type, PriceDirection::Downward);
                let price = self.prices.get_mut(resource_type).unwrap();
                *price -= 1;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use village::*;
    use village_mind::*;
    use simulation::*;
    use village::resource::*;
    use village_mind::trade_request::*;

    fn default_village() -> Village {
        Village::new(|w: &worker::Worker| false)
    }

    #[test]
    fn add_village() {
        let mut simulation = Simulation::new();
        simulation.add_village(default_village());

        assert_eq!(1, simulation.village_managers().len());
    }

    #[test]
    fn initial_resource_prices() {
        let mut simulation = Simulation::new();

        assert_eq!(5, *simulation.prices.get(&ResourceType::Food).unwrap());
    }

    #[test]
    fn initial_price_directions() {
        let mut simulation = Simulation::new();

        assert_eq!(PriceDirection::Equilibrium, *simulation.price_directions.get(&ResourceType::Food).unwrap());
    }

    #[test]
    fn handle_trades_basic_sell_and_buy() {
        let mut simulation = Simulation::new();
        let mut trade_requests : Vec<TradeRequest> = Vec::new();
        trade_requests.push(TradeRequest::new(TradeType::Buy, 1, ResourceType::Food));
        trade_requests.push(TradeRequest::new(TradeType::Sell, 1, ResourceType::Food));
        simulation.handleTrades(&mut trade_requests);

        assert_eq!(1, trade_requests.get(0).unwrap().fulfilled_amount);
        assert_eq!(1, trade_requests.get(1).unwrap().fulfilled_amount);
        assert_eq!(PriceDirection::Equilibrium, *simulation.price_directions.get(&ResourceType::Food).unwrap());
    }

    #[test]
    fn handle_trades_upward_price() {
        let mut simulation = Simulation::new();
        let mut trade_requests : Vec<TradeRequest> = Vec::new();
        trade_requests.push(TradeRequest::new(TradeType::Buy, 1, ResourceType::Food));
        simulation.handleTrades(&mut trade_requests);

        assert_eq!(0, trade_requests.get(0).unwrap().fulfilled_amount);
        assert_eq!(PriceDirection::Upward, *simulation.price_directions.get(&ResourceType::Food).unwrap());
        assert_eq!(6, *simulation.prices.get(&ResourceType::Food).unwrap());
    }

    #[test]
    fn handle_trades_downward_price() {
        let mut simulation = Simulation::new();
        let mut trade_requests : Vec<TradeRequest> = Vec::new();
        trade_requests.push(TradeRequest::new(TradeType::Sell, 1, ResourceType::Food));
        simulation.handleTrades(&mut trade_requests);

        assert_eq!(0, trade_requests.get(0).unwrap().fulfilled_amount);
        assert_eq!(PriceDirection::Downward, *simulation.price_directions.get(&ResourceType::Food).unwrap());
        assert_eq!(4, *simulation.prices.get(&ResourceType::Food).unwrap());
    }

    #[test]
    fn handles_trades_multiple_rounds_downward() {
        let mut simulation = Simulation::new();
        let mut trade_requests : Vec<TradeRequest> = Vec::new();
        trade_requests.push(TradeRequest::new(TradeType::Sell, 1, ResourceType::Food));
        simulation.handleTrades(&mut trade_requests);
        simulation.handleTrades(&mut trade_requests);
        simulation.handleTrades(&mut trade_requests);

        trade_requests.push(TradeRequest::new(TradeType::Buy, 5, ResourceType::Food));
        simulation.handleTrades(&mut trade_requests);

        assert_eq!(1, trade_requests.get(0).unwrap().fulfilled_amount);
        assert_eq!(1, trade_requests.get(1).unwrap().fulfilled_amount);
        assert_eq!(PriceDirection::Equilibrium, *simulation.price_directions.get(&ResourceType::Food).unwrap());
        assert_eq!(2, *simulation.prices.get(&ResourceType::Food).unwrap());
    }
}<commit_msg>Finished Current Trading Features<commit_after>pub mod village_manager;

use self::village_manager::*;
use village::*;
use village::resource::*;
use village_mind::*;
use village_mind::trade_request::*;
use std::cell::RefCell;
use std::rc::Rc;
use std::collections::HashMap;

#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub enum PriceDirection {
    Upward,
    Downward,
    Equilibrium,
}

pub struct Simulation {
    village_managers: Vec<VillageManager>,
    pub prices: HashMap<ResourceType, u32>,
    pub price_directions: HashMap<ResourceType, PriceDirection>,
}

impl Simulation {
    pub fn new() -> Simulation {

        let mut simulation = Simulation {
            village_managers: vec!(),
            prices: HashMap::new(),
            price_directions: HashMap::new(),
        };

        //for each resource (other than gold), put the starting price at one gold
        for resource_type in ResourceType::iterator() {
            if *resource_type != ResourceType::Gold {
                simulation.prices.insert(*resource_type, 5);
                simulation.price_directions.insert(*resource_type, PriceDirection::Equilibrium);
            }
        }
        simulation
    }

    pub fn add_village(&mut self, village: Village) {
        let villageRC = Rc::new(RefCell::new(village));
        let village_manager = VillageManager {
            village: villageRC.clone(),
            village_mind: VillageMind::new(villageRC.clone()),
        };

        self.village_managers.push(village_manager);
    }

    pub fn village_managers(&self) -> &Vec<VillageManager> {
        &self.village_managers
    }

    pub fn simulate(&mut self) {
        // update the villages and village minds with the new information
        for vm in self.village_managers.iter_mut() {
            vm.village.borrow_mut().simulate();
            vm.village_mind.manage_village();
        }

        // do the trading phase until no more trade request are given
        let mut trading = true;
        let mut trade_requests : Vec<TradeRequest> = Vec::new();

        while trading {
            trade_requests.clear();

            for mut vm in self.village_managers.iter_mut() {
                trade_requests.append(&mut vm.village_mind.trade());
            }

            if trade_requests.len() == 0 {
                trading = false;
            }
        }

        // update village minds
        for vm in self.village_managers.iter_mut() {
            vm.village_mind.manage_village();
        }
    }

    pub fn handleTrades(&mut self, trade_requests: &mut Vec<TradeRequest>) {
        // get the trade request for each resource type minus gold
        for resource_type in ResourceType::iterator().filter(|r| **r != ResourceType::Gold) {
            // get the total number of buys and sells requested for a resource at the current price
            let mut buys = 0;
            let mut sells = 0;
            for trade_request in trade_requests.iter_mut().filter(|t| t.resource_type == *resource_type) {
                if trade_request.trade_type == TradeType::Buy {
                    buys += trade_request.request_amount;
                } else {
                    sells += trade_request.request_amount;
                }
            }

            // if number of buys and sells are equal consider the price at equilibrium and fulfill the trade requests
            if buys == sells {
                for trade_request in trade_requests.iter_mut().filter(|t| t.resource_type == *resource_type) {
                    trade_request.fulfilled_amount = trade_request.request_amount;
                }
                self.price_directions.insert(*resource_type, PriceDirection::Equilibrium);
            }
            else if buys > sells {
                let price_direction = *self.price_directions.get(resource_type).unwrap();
                if price_direction == PriceDirection::Equilibrium || price_direction == PriceDirection::Upward {
                    // The price direction is already upwards or at equilibrium
                    // thus the price direction will be upward and the price will increase
                    self.price_directions.insert(*resource_type, PriceDirection::Upward);
                    let price = self.prices.get_mut(resource_type).unwrap();
                    *price += 1;
                } else { // price direction is Downward
                    // we now have more buyers then sellers and found an acceptable equilibrium price
                    // first fulfill all sell request
                    for trade_request in trade_requests.iter_mut().filter(|t| t.resource_type == *resource_type && t.trade_type == TradeType::Sell) {
                        trade_request.fulfilled_amount = trade_request.request_amount;
                    }
                    // iterate through all buy request until we run out of the resource to sell
                    let mut buy_requests: Vec<&mut TradeRequest> = trade_requests.iter_mut()
                        .filter(|t| t.resource_type == *resource_type && t.trade_type == TradeType::Buy)
                        .collect();
                    while sells > 0 {
                        for buy_request in buy_requests.iter_mut() {
                            buy_request.fulfilled_amount += 1;
                            sells -= 1;
                            if sells <= 0 { break; }
                        }
                    }

                    self.price_directions.insert(*resource_type, PriceDirection::Equilibrium);
                }
            } else { //more sellers then buyers
                let price_direction = *self.price_directions.get(resource_type).unwrap();
                if (price_direction == PriceDirection::Equilibrium || price_direction == PriceDirection::Downward) && *self.prices.get_mut(resource_type).unwrap() > 1 {
                    // The price direction is already downwards or at equilibrium
                    // thus the price direction will be downward and the price will increase
                    self.price_directions.insert(*resource_type, PriceDirection::Downward);
                    let price = self.prices.get_mut(resource_type).unwrap();
                    *price -= 1;
                } else { //price direction is Upward or the price is 1
                    // we now have more sellers then buyers and found an acceptable equilibrium price
                    for buy_request in trade_requests.iter_mut().filter(|t| t.resource_type == *resource_type && t.trade_type == TradeType::Buy) {
                        buy_request.fulfilled_amount = buy_request.request_amount;
                    }

                    // iterate through all sell request until we run out of buyers
                    let mut sell_requests : Vec<&mut TradeRequest> = trade_requests.iter_mut()
                        .filter(|t| t.resource_type == *resource_type && t.trade_type == TradeType::Sell)
                        .collect();
                    while buys > 0 {
                        for sell_request in sell_requests.iter_mut() {
                            sell_request.fulfilled_amount += 1;
                            buys -= 1;
                            if buys <= 0 {break;}
                        }
                    }

                    self.price_directions.insert(*resource_type, PriceDirection::Equilibrium);
                }

            }
        }
    }
}

#[cfg(test)]
mod tests {
    use village::*;
    use village_mind::*;
    use simulation::*;
    use village::resource::*;
    use village_mind::trade_request::*;

    fn default_village() -> Village {
        Village::new(|w: &worker::Worker| false)
    }

    #[test]
    fn add_village() {
        let mut simulation = Simulation::new();
        simulation.add_village(default_village());

        assert_eq!(1, simulation.village_managers().len());
    }

    #[test]
    fn initial_resource_prices() {
        let mut simulation = Simulation::new();

        assert_eq!(5, *simulation.prices.get(&ResourceType::Food).unwrap());
    }

    #[test]
    fn initial_price_directions() {
        let mut simulation = Simulation::new();

        assert_eq!(PriceDirection::Equilibrium, *simulation.price_directions.get(&ResourceType::Food).unwrap());
    }

    #[test]
    fn handle_trades_basic_sell_and_buy() {
        let mut simulation = Simulation::new();
        let mut trade_requests : Vec<TradeRequest> = Vec::new();
        trade_requests.push(TradeRequest::new(TradeType::Buy, 1, ResourceType::Food));
        trade_requests.push(TradeRequest::new(TradeType::Sell, 1, ResourceType::Food));
        simulation.handleTrades(&mut trade_requests);

        assert_eq!(1, trade_requests.get(0).unwrap().fulfilled_amount);
        assert_eq!(1, trade_requests.get(1).unwrap().fulfilled_amount);
        assert_eq!(PriceDirection::Equilibrium, *simulation.price_directions.get(&ResourceType::Food).unwrap());
    }

    #[test]
    fn handle_trades_upward_price() {
        let mut simulation = Simulation::new();
        let mut trade_requests : Vec<TradeRequest> = Vec::new();
        trade_requests.push(TradeRequest::new(TradeType::Buy, 1, ResourceType::Food));
        simulation.handleTrades(&mut trade_requests);

        assert_eq!(0, trade_requests.get(0).unwrap().fulfilled_amount);
        assert_eq!(PriceDirection::Upward, *simulation.price_directions.get(&ResourceType::Food).unwrap());
        assert_eq!(6, *simulation.prices.get(&ResourceType::Food).unwrap());
    }

    #[test]
    fn handle_trades_downward_price() {
        let mut simulation = Simulation::new();
        let mut trade_requests : Vec<TradeRequest> = Vec::new();
        trade_requests.push(TradeRequest::new(TradeType::Sell, 1, ResourceType::Food));
        simulation.handleTrades(&mut trade_requests);

        assert_eq!(0, trade_requests.get(0).unwrap().fulfilled_amount);
        assert_eq!(PriceDirection::Downward, *simulation.price_directions.get(&ResourceType::Food).unwrap());
        assert_eq!(4, *simulation.prices.get(&ResourceType::Food).unwrap());
    }

    #[test]
    fn handle_trades_multiple_rounds_downward() {
        let mut simulation = Simulation::new();
        let mut trade_requests : Vec<TradeRequest> = Vec::new();
        trade_requests.push(TradeRequest::new(TradeType::Sell, 1, ResourceType::Food));
        simulation.handleTrades(&mut trade_requests);
        simulation.handleTrades(&mut trade_requests);
        simulation.handleTrades(&mut trade_requests);

        trade_requests.push(TradeRequest::new(TradeType::Buy, 5, ResourceType::Food));
        simulation.handleTrades(&mut trade_requests);

        assert_eq!(1, trade_requests.get(0).unwrap().fulfilled_amount);
        assert_eq!(1, trade_requests.get(1).unwrap().fulfilled_amount);
        assert_eq!(PriceDirection::Equilibrium, *simulation.price_directions.get(&ResourceType::Food).unwrap());
        assert_eq!(2, *simulation.prices.get(&ResourceType::Food).unwrap());
    }

    #[test]
    fn handle_trades_multiple_rounds_upward() {
        let mut simulation = Simulation::new();
        let mut trade_requests : Vec<TradeRequest> = Vec::new();
        trade_requests.push(TradeRequest::new(TradeType::Buy, 1, ResourceType::Food));
        simulation.handleTrades(&mut trade_requests);
        simulation.handleTrades(&mut trade_requests);
        simulation.handleTrades(&mut trade_requests);

        trade_requests.push(TradeRequest::new(TradeType::Sell, 5, ResourceType::Food));
        simulation.handleTrades(&mut trade_requests);

        assert_eq!(1, trade_requests.get(0).unwrap().fulfilled_amount);
        assert_eq!(1, trade_requests.get(1).unwrap().fulfilled_amount);
        assert_eq!(PriceDirection::Equilibrium, *simulation.price_directions.get(&ResourceType::Food).unwrap());
        assert_eq!(8, *simulation.prices.get(&ResourceType::Food).unwrap());
    }

    #[test]
    fn handle_trades_price_minimum() {
        let mut simulation = Simulation::new();
        let mut trade_requests : Vec<TradeRequest> = Vec::new();
        trade_requests.push(TradeRequest::new(TradeType::Sell, 2, ResourceType::Food));
        simulation.handleTrades(&mut trade_requests);
        simulation.handleTrades(&mut trade_requests);
        simulation.handleTrades(&mut trade_requests);
        simulation.handleTrades(&mut trade_requests);
        trade_requests.push(TradeRequest::new(TradeType::Buy, 1, ResourceType::Food));
        simulation.handleTrades(&mut trade_requests);

        assert_eq!(1, trade_requests.get(0).unwrap().fulfilled_amount);
        assert_eq!(1, trade_requests.get(1).unwrap().fulfilled_amount);
        assert_eq!(PriceDirection::Equilibrium, *simulation.price_directions.get(&ResourceType::Food).unwrap());
        assert_eq!(1, *simulation.prices.get(&ResourceType::Food).unwrap());
    }
}<|endoftext|>


<commit_before>//! Module containing bindings to the `rand` library.

extern crate rand;
extern crate rand_xorshift;

use self::rand::{Rng, SeedableRng};

use crate::vm::{
    self,
    api::{RuntimeResult, IO},
    thread::Thread,
    types::VmInt,
    ExternModule,
};

#[derive(Clone, Debug, Userdata, Trace, VmType)]
#[gluon(vm_type = "std.random.XorShiftRng")]
#[gluon(crate_name = "::vm")]
#[gluon_trace(skip)]
struct XorShiftRng(self::rand_xorshift::XorShiftRng);

field_decl! { value, gen }

fn next_int(_: ()) -> IO<VmInt> {
    IO::Value(rand::thread_rng().gen())
}

fn next_float(_: ()) -> IO<f64> {
    IO::Value(rand::thread_rng().gen())
}

fn gen_int_range(low: VmInt, high: VmInt) -> IO<VmInt> {
    IO::Value(rand::thread_rng().gen_range(low, high))
}

type RngNext<G> = record_type! {
    value => VmInt,
    gen => G
};

fn xor_shift_new(seed: &[u8]) -> RuntimeResult<XorShiftRng, String> {
    if seed.len() == 16 {
        let seed = unsafe { *(seed.as_ptr() as *const [u8; 16]) };
        RuntimeResult::Return(XorShiftRng(self::rand_xorshift::XorShiftRng::from_seed(
            seed,
        )))
    } else {
        RuntimeResult::Panic("Expected xorshift seed to have 4 elements".to_string())
    }
}

fn xor_shift_next(gen: &XorShiftRng) -> RngNext<XorShiftRng> {
    let mut gen = gen.clone();
    record_no_decl! {
        value => gen.0.gen(),
        gen => gen
    }
}

mod std {
    pub mod random {
        pub use crate::std_lib::random as prim;
    }
}

pub fn load(vm: &Thread) -> vm::Result<ExternModule> {
    vm.register_type::<XorShiftRng>("std.random.XorShiftRng", &[])?;

    ExternModule::new(
        vm,
        record! {
            type std::random::XorShiftRng => XorShiftRng,
            next_int => primitive!(1, std::random::prim::next_int),
            next_float => primitive!(1, std::random::prim::next_float),
            gen_int_range => primitive!(2, std::random::prim::gen_int_range),
            xor_shift_new => primitive!(1, std::random::prim::xor_shift_new),
            xor_shift_next => primitive!(1, std::random::prim::xor_shift_next)
        },
    )
}
<commit_msg>fix: xor_shift_new inconsistent description<commit_after>//! Module containing bindings to the `rand` library.

extern crate rand;
extern crate rand_xorshift;

use self::rand::{Rng, SeedableRng};

use crate::vm::{
    self,
    api::{RuntimeResult, IO},
    thread::Thread,
    types::VmInt,
    ExternModule,
};

#[derive(Clone, Debug, Userdata, Trace, VmType)]
#[gluon(vm_type = "std.random.XorShiftRng")]
#[gluon(crate_name = "::vm")]
#[gluon_trace(skip)]
struct XorShiftRng(self::rand_xorshift::XorShiftRng);

field_decl! { value, gen }

fn next_int(_: ()) -> IO<VmInt> {
    IO::Value(rand::thread_rng().gen())
}

fn next_float(_: ()) -> IO<f64> {
    IO::Value(rand::thread_rng().gen())
}

fn gen_int_range(low: VmInt, high: VmInt) -> IO<VmInt> {
    IO::Value(rand::thread_rng().gen_range(low, high))
}

type RngNext<G> = record_type! {
    value => VmInt,
    gen => G
};

fn xor_shift_new(seed: &[u8]) -> RuntimeResult<XorShiftRng, String> {
    if seed.len() == 16 {
        let seed = unsafe { *(seed.as_ptr() as *const [u8; 16]) };
        RuntimeResult::Return(XorShiftRng(self::rand_xorshift::XorShiftRng::from_seed(
            seed,
        )))
    } else {
        RuntimeResult::Panic("Expected xorshift seed to have 16 elements".to_string())
    }
}

fn xor_shift_next(gen: &XorShiftRng) -> RngNext<XorShiftRng> {
    let mut gen = gen.clone();
    record_no_decl! {
        value => gen.0.gen(),
        gen => gen
    }
}

mod std {
    pub mod random {
        pub use crate::std_lib::random as prim;
    }
}

pub fn load(vm: &Thread) -> vm::Result<ExternModule> {
    vm.register_type::<XorShiftRng>("std.random.XorShiftRng", &[])?;

    ExternModule::new(
        vm,
        record! {
            type std::random::XorShiftRng => XorShiftRng,
            next_int => primitive!(1, std::random::prim::next_int),
            next_float => primitive!(1, std::random::prim::next_float),
            gen_int_range => primitive!(2, std::random::prim::gen_int_range),
            xor_shift_new => primitive!(1, std::random::prim::xor_shift_new),
            xor_shift_next => primitive!(1, std::random::prim::xor_shift_next)
        },
    )
}
<|endoftext|>


<commit_before>use rustc::dep_graph::{DepGraphQuery, DepNode};
use rustc::hir::def_id::DefId;
use rustc_data_structures::fnv::FnvHashMap;
use rustc_data_structures::graph::{DepthFirstTraversal, INCOMING, NodeIndex};

use super::hash::*;

/// A data-structure that makes it easy to enumerate the hashable
/// predecessors of any given dep-node.
pub struct Predecessors<'query> {
    // - Keys: dep-nodes that may have work-products, output meta-data
    //   nodes.
    // - Values: transitive predecessors of the key that are hashable
    //   (e.g., HIR nodes, input meta-data nodes)
    pub inputs: FnvHashMap<&'query DepNode<DefId>, Vec<&'query DepNode<DefId>>>,

    // - Keys: some hashable node
    // - Values: the hash thereof
    pub hashes: FnvHashMap<&'query DepNode<DefId>, u64>,
}

impl<'q> Predecessors<'q> {
    pub fn new(query: &'q DepGraphQuery<DefId>, hcx: &mut HashContext) -> Self {
        // Find nodes for which we want to know the full set of preds
        let mut dfs = DepthFirstTraversal::new(&query.graph, INCOMING);
        let all_nodes = query.graph.all_nodes();
        let tcx = hcx.tcx;

        let inputs: FnvHashMap<_, _> = all_nodes.iter()
            .enumerate()
            .filter(|&(_, node)| match node.data {
                DepNode::WorkProduct(_) => true,
                DepNode::MetaData(ref def_id) => def_id.is_local(),

                // if -Z query-dep-graph is passed, save more extended data
                // to enable better unit testing
                DepNode::TypeckItemBody(_) |
                DepNode::TransCrateItem(_) => tcx.sess.opts.debugging_opts.query_dep_graph,

                _ => false,
            })
            .map(|(node_index, node)| {
                dfs.reset(NodeIndex(node_index));
                let inputs: Vec<_> = dfs.by_ref()
                    .map(|i| &all_nodes[i.node_id()].data)
                    .filter(|d| HashContext::is_hashable(d))
                    .collect();
                (&node.data, inputs)
            })
            .collect();

        let mut hashes = FnvHashMap();
        for input in inputs.values().flat_map(|v| v.iter().cloned()) {
            hashes.entry(input)
                  .or_insert_with(|| hcx.hash(input).unwrap().1);
        }

        Predecessors {
            inputs: inputs,
            hashes: hashes,
        }
    }
}
<commit_msg>fix license<commit_after>// Copyright 2012-2015 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 rustc::dep_graph::{DepGraphQuery, DepNode};
use rustc::hir::def_id::DefId;
use rustc_data_structures::fnv::FnvHashMap;
use rustc_data_structures::graph::{DepthFirstTraversal, INCOMING, NodeIndex};

use super::hash::*;

/// A data-structure that makes it easy to enumerate the hashable
/// predecessors of any given dep-node.
pub struct Predecessors<'query> {
    // - Keys: dep-nodes that may have work-products, output meta-data
    //   nodes.
    // - Values: transitive predecessors of the key that are hashable
    //   (e.g., HIR nodes, input meta-data nodes)
    pub inputs: FnvHashMap<&'query DepNode<DefId>, Vec<&'query DepNode<DefId>>>,

    // - Keys: some hashable node
    // - Values: the hash thereof
    pub hashes: FnvHashMap<&'query DepNode<DefId>, u64>,
}

impl<'q> Predecessors<'q> {
    pub fn new(query: &'q DepGraphQuery<DefId>, hcx: &mut HashContext) -> Self {
        // Find nodes for which we want to know the full set of preds
        let mut dfs = DepthFirstTraversal::new(&query.graph, INCOMING);
        let all_nodes = query.graph.all_nodes();
        let tcx = hcx.tcx;

        let inputs: FnvHashMap<_, _> = all_nodes.iter()
            .enumerate()
            .filter(|&(_, node)| match node.data {
                DepNode::WorkProduct(_) => true,
                DepNode::MetaData(ref def_id) => def_id.is_local(),

                // if -Z query-dep-graph is passed, save more extended data
                // to enable better unit testing
                DepNode::TypeckItemBody(_) |
                DepNode::TransCrateItem(_) => tcx.sess.opts.debugging_opts.query_dep_graph,

                _ => false,
            })
            .map(|(node_index, node)| {
                dfs.reset(NodeIndex(node_index));
                let inputs: Vec<_> = dfs.by_ref()
                    .map(|i| &all_nodes[i.node_id()].data)
                    .filter(|d| HashContext::is_hashable(d))
                    .collect();
                (&node.data, inputs)
            })
            .collect();

        let mut hashes = FnvHashMap();
        for input in inputs.values().flat_map(|v| v.iter().cloned()) {
            hashes.entry(input)
                  .or_insert_with(|| hcx.hash(input).unwrap().1);
        }

        Predecessors {
            inputs: inputs,
            hashes: hashes,
        }
    }
}
<|endoftext|>


<commit_before>use std::cell::Cell;
use std::ops::Deref;

use wayland_client::cursor::{is_available, CursorTheme, load_theme};
use wayland_client::protocol::{wl_compositor,wl_shm,wl_surface,wl_pointer};

pub struct ThemedPointer {
    pointer: wl_pointer::WlPointer,
    surface: wl_surface::WlSurface,
    theme: CursorTheme,
    last_serial: Cell<u32>,
}

impl ThemedPointer {
    pub fn load(pointer: wl_pointer::WlPointer, name: Option<&str>,
                compositor: &wl_compositor::WlCompositor, shm: &wl_shm::WlShm)
        -> Result<ThemedPointer, wl_pointer::WlPointer>
    {
        if !is_available() { return Err(pointer) }

        let theme = load_theme(name, 16, shm);
        let surface = compositor.create_surface().expect("Compositor cannot be destroyed");

        Ok(ThemedPointer {
            pointer: pointer,
            surface: surface,
            theme: theme,
            last_serial: Cell::new(0)
        })
    }

    pub fn set_cursor(&self, name: &str, serial: Option<u32>) {
        let cursor = if let Some(c) = self.theme.get_cursor(name) { c } else { return };
        let buffer = if let Some(b) = cursor.frame_buffer(0) { b } else { return };
        let (w, h, hx, hy) = cursor.frame_info(0)
                                   .map(|(w,h,hx,hy,_)| (w as i32, h as i32, hx as i32, hy as i32))
                                   .unwrap_or((0,0, 0, 0));

        if let Some(s) = serial { self.last_serial.set(s); }

        self.surface.attach(Some(&buffer), 0, 0);
        self.surface.damage_buffer(0,0,w,h);
        self.surface.commit();
        self.pointer.set_cursor(self.last_serial.get(), Some(&self.surface), hx, hy);
    }
}

impl Deref for ThemedPointer {
    type Target = wl_pointer::WlPointer;
    fn deref(&self) -> &wl_pointer::WlPointer {
        &self.pointer
    }
}
<commit_msg>Don't call damage_buffer on <= v3 wl_surfaces.<commit_after>use std::cell::Cell;
use std::ops::Deref;

use wayland_client::Proxy;
use wayland_client::cursor::{is_available, CursorTheme, load_theme};
use wayland_client::protocol::{wl_compositor,wl_shm,wl_surface,wl_pointer};

pub struct ThemedPointer {
    pointer: wl_pointer::WlPointer,
    surface: wl_surface::WlSurface,
    theme: CursorTheme,
    last_serial: Cell<u32>,
}

impl ThemedPointer {
    pub fn load(pointer: wl_pointer::WlPointer, name: Option<&str>,
                compositor: &wl_compositor::WlCompositor, shm: &wl_shm::WlShm)
        -> Result<ThemedPointer, wl_pointer::WlPointer>
    {
        if !is_available() { return Err(pointer) }

        let theme = load_theme(name, 16, shm);
        let surface = compositor.create_surface().expect("Compositor cannot be destroyed");

        Ok(ThemedPointer {
            pointer: pointer,
            surface: surface,
            theme: theme,
            last_serial: Cell::new(0)
        })
    }

    pub fn set_cursor(&self, name: &str, serial: Option<u32>) {
        let cursor = if let Some(c) = self.theme.get_cursor(name) { c } else { return };
        let buffer = if let Some(b) = cursor.frame_buffer(0) { b } else { return };
        let (w, h, hx, hy) = cursor.frame_info(0)
                                   .map(|(w,h,hx,hy,_)| (w as i32, h as i32, hx as i32, hy as i32))
                                   .unwrap_or((0,0, 0, 0));

        if let Some(s) = serial { self.last_serial.set(s); }

        self.surface.attach(Some(&buffer), 0, 0);
        if self.surface.version() >= 4 {
            self.surface.damage_buffer(0,0,w,h);
        } else {
            // surface is old and does not support damage_buffer, so we damage
            // in surface coordinates and hope it is not rescaled
            self.surface.damage(0,0,w,h);
        }
        self.surface.commit();
        self.pointer.set_cursor(self.last_serial.get(), Some(&self.surface), hx, hy);
    }
}

impl Deref for ThemedPointer {
    type Target = wl_pointer::WlPointer;
    fn deref(&self) -> &wl_pointer::WlPointer {
        &self.pointer
    }
}
<|endoftext|>


<commit_before>use std::fs::File;
use std::io::Read;
use whisper;

const HEADER_SIZE: usize = 16;
const ARCHIVE_INFO_SIZE: usize = 12;

#[derive(PartialEq,Debug)]
pub struct Header{
    pub metadata: whisper::metadata::Metadata,
    pub archive_infos: Vec<whisper::archive_info::ArchiveInfo>
}

// TODO change to result type
pub fn read_header(mut file: File) -> Header{
    let header_buffer = &mut[0u8; HEADER_SIZE];
    let metadata_read_result = file.read(header_buffer);

    match metadata_read_result {
        Ok(bytes_read) => {
            if bytes_read != HEADER_SIZE {
                panic!("could not read enough bytes!")
            }

            let metadata = whisper::metadata::slice_to_metadata(header_buffer);

            let mut archive_infos = vec![];

            for archive_index in 0..metadata.archive_count {
            let archive_info_buffer = &mut[0u8; ARCHIVE_INFO_SIZE];
            let archive_read_result = file.read(archive_info_buffer);
            match archive_read_result {
                Ok(bytes_read) => {
                    if bytes_read != ARCHIVE_INFO_SIZE {
                        panic!("could not read enough bytes!")
                    }

                    let archive_info = whisper::archive_info::slice_to_archive_info(archive_info_buffer);
                    archive_infos.push(archive_info);
                }
                Err(_) => {
                    println!("sup");
                }
            }

            println!("archive_index: {}", archive_index);
            }

            let header = Header {
                metadata: metadata,
                archive_infos: archive_infos
            };
            header
        }
        Err(e) => {
            panic!("got err {}", e);
        }
    }
}
<commit_msg>Test fixture file<commit_after>use std::fs::File;
use std::io::Read;
use whisper;

const HEADER_SIZE: usize = 16;
const ARCHIVE_INFO_SIZE: usize = 12;

#[derive(PartialEq,Debug)]
pub struct Header{
    pub metadata: whisper::metadata::Metadata,
    pub archive_infos: Vec<whisper::archive_info::ArchiveInfo>
}

// TODO change to result type
pub fn read_header(mut file: File) -> Header{
    let header_buffer = &mut[0u8; HEADER_SIZE];
    let metadata_read_result = file.read(header_buffer);

    match metadata_read_result {
        Ok(bytes_read) => {
            if bytes_read != HEADER_SIZE {
                panic!("could not read enough bytes!")
            }

            let metadata = whisper::metadata::slice_to_metadata(header_buffer);

            let mut archive_infos = vec![];

            for archive_index in 0..metadata.archive_count {
            let archive_info_buffer = &mut[0u8; ARCHIVE_INFO_SIZE];
            let archive_read_result = file.read(archive_info_buffer);
            match archive_read_result {
                Ok(bytes_read) => {
                    if bytes_read != ARCHIVE_INFO_SIZE {
                        panic!("could not read enough bytes!")
                    }

                    let archive_info = whisper::archive_info::slice_to_archive_info(archive_info_buffer);
                    archive_infos.push(archive_info);
                }
                Err(_) => {
                    println!("sup");
                }
            }

            println!("archive_index: {}", archive_index);
            }

            let header = Header {
                metadata: metadata,
                archive_infos: archive_infos
            };
            header
        }
        Err(e) => {
            panic!("got err {}", e);
        }
    }
}

#[test]
fn parses_60_1440() {
    let path = "./test/fixtures/60-1440.wsp";
    let open_result = whisper::file::open(path);

    let expected = Header {
        metadata: whisper::metadata::Metadata {
            aggregation_type: whisper::metadata::AggregationType::Average,
            max_retention: 86400,
            x_files_factor: 1056964608,
            archive_count: 1
        },
        archive_infos: vec![
            whisper::archive_info::ArchiveInfo {
                offset: 28,
                seconds_per_point: 60,
                points: 1440
            }
        ]
    };

    match open_result {
        Ok(f) => {
            let header = whisper::header::read_header(f);
            assert_eq!(header, expected)
        }
        Err(_) => {
            assert!(false)
        }
    }
}
<|endoftext|>


<commit_before>#![deny(missing_docs)]
#![deny(missing_copy_implementations)]

//! Window abstraction

extern crate libc;
extern crate input;
extern crate shader_version;

use shader_version::OpenGL;
use input::Input;

/// The type of an OpenGL function address.
pub type ProcAddress = *const libc::c_void;

/// Size in pixels.
#[derive(Copy, Clone)]
pub struct Size {
    /// The width in pixels.
    pub width: u32,
    /// The height in pixels.
    pub height: u32,
}

impl From<[u32; 2]> for Size {
    #[inline(always)]
    fn from(value: [u32; 2]) -> Size {
        Size { width: value[0], height: value[1] }
    }
}

impl From<(u32, u32)> for Size {
    #[inline(always)]
    fn from(value: (u32, u32)) -> Size {
        Size { width: value.0, height: value.1 }
    }
}

/// Required to use the event loop.
pub trait Window {
    /// The event type emitted by `poll_event`
    type Event;

    /// Returns true if window should close.
    fn should_close(&self) -> bool;

    /// Gets the size of the window in user coordinates.
    fn size(&self) -> Size;

    /// Swaps render buffers.
    fn swap_buffers(&mut self);

    /// Polls event from window.
    fn poll_event(&mut self) -> Option<Self::Event>;

    /// Gets draw size of the window.
    /// This is equal to the size of the frame buffer of the inner window,
    /// excluding the title bar and borders.
    fn draw_size(&self) -> Size;
}

/// Implemented by fully supported window back-ends.
pub trait AdvancedWindow: Window + Sized {
    /// Gets a copy of the title of the window.
    fn get_title(&self) -> String;

    /// Sets the title of the window.
    fn set_title(&mut self, value: String);

    /// Sets title on window.
    fn title(mut self, value: String) -> Self {
        self.set_title(value);
        self
    }

    /// Gets whether to exit when pressing esc.
    fn get_exit_on_esc(&self) -> bool;

    /// Sets whether to exit when pressing esc.
    fn set_exit_on_esc(&mut self, value: bool);

    /// Sets whether to exit when pressing esc.
    fn exit_on_esc(mut self, value: bool) -> Self {
        self.set_exit_on_esc(value);
        self
    }

    /// Sets whether to capture/grab cursor.
    /// This is used to lock and hide cursor to the window,
    /// for example in a first-person shooter game.
    fn set_capture_cursor(&mut self, value: bool);

    /// Sets whether to capture/grab cursor (see `set_capture_cursor`).
    fn capture_cursor(mut self, value: bool) -> Self {
        self.set_capture_cursor(value);
        self
    }
}

/// Trait for OpenGL specific operations.
pub trait OpenGLWindow: Window {
    /// Returns the address of an OpenGL function if it exist, else returns null pointer.
    fn get_proc_address(&mut self, proc_name: &str) -> ProcAddress;

    /// Returns true if this context is the current context.
    fn is_current(&self) -> bool;

    /// Make this context current.
    fn make_current(&mut self);
}

/// Settings for window behavior.
pub struct WindowSettings {
    /// Title of the window.
    title: String,
    /// The size of the window.
    size: Size,
    /// Number samples per pixel (anti-aliasing).
    samples: u8,
    /// If true, the window is fullscreen.
    fullscreen: bool,
    /// If true, exit when pressing Esc.
    exit_on_esc: bool,
    /// If true, enable vsync.
    vsync: bool,
    /// An optional OpenGL version.
    opengl: Option<OpenGL>,
}

impl WindowSettings {
    /// Creates window settings with defaults.
    /// - samples: 0
    /// - fullscreen: false
    /// - exit_on_esc: false
    pub fn new<T: Into<String>, S: Into<Size>>(
        title: T, size: S) -> WindowSettings
    {
        WindowSettings {
            title: title.into(),
            size: size.into(),
            samples: 0,
            fullscreen: false,
            exit_on_esc: false,
            vsync: false,
            opengl: None,
        }
    }

    /// Gets title.
    pub fn get_title(&self) -> String { self.title.clone() }

    /// Sets title.
    pub fn title(mut self, value: String) -> Self {
        self.title = value;
        self
    }

    /// Gets size.
    pub fn get_size(&self) -> Size { self.size }

    /// Sets size.
    pub fn size(mut self, value: Size) -> Self {
        self.size = value;
        self
    }

    /// Gets fullscreen.
    pub fn get_fullscreen(&self) -> bool { self.fullscreen }

    /// Sets fullscreen.
    pub fn fullscreen(mut self, value: bool) -> Self {
        self.fullscreen = value;
        self
    }

    /// Gets exit on esc.
    pub fn get_exit_on_esc(&self) -> bool { self.exit_on_esc }

    /// Sets exit on esc.
    pub fn exit_on_esc(mut self, value: bool) -> Self {
        self.exit_on_esc = value;
        self
    }

    /// Gets samples.
    pub fn get_samples(&self) -> u8 { self.samples }

    /// Sets samples.
    pub fn samples(mut self, value: u8) -> Self {
        self.samples = value;
        self
    }

    /// Gets vsync.
    pub fn get_vsync(&self) -> bool { self.vsync }

    /// Sets vsync.
    pub fn vsync(mut self, value: bool) -> Self {
        self.vsync = value;
        self
    }

    /// Gets opengl.
    pub fn get_maybe_opengl(&self) -> Option<OpenGL> { self.opengl }

    /// Sets opengl.
    pub fn maybe_opengl(mut self, value: Option<OpenGL>) -> Self {
        self.opengl = value;
        self
    }

    /// Sets opengl.
    pub fn opengl(mut self, value: OpenGL) -> Self {
        self.opengl = Some(value);
        self
    }
}

/// An implementation of Window that runs without a window at all.
pub struct NoWindow {
    should_close: bool,
    title: String,
    size: Size
}

impl NoWindow {
    /// Returns a new `NoWindow`.
    pub fn new(settings: WindowSettings) -> NoWindow {
        NoWindow {
            should_close: false,
            title: settings.title,
            size: settings.size,
        }
    }
}

impl From<WindowSettings> for NoWindow {
    fn from(settings: WindowSettings) -> NoWindow {
        NoWindow::new(settings)
    }
}

impl Window for NoWindow {
    type Event = Input;
    fn should_close(&self) -> bool { self.should_close }
    fn size(&self) -> Size { self.size }
    fn swap_buffers(&mut self) {}
    fn poll_event(&mut self) -> Option<Input> { None }
    fn draw_size(&self) -> Size { self.size() }
}

impl AdvancedWindow for NoWindow {
    fn get_title(&self) -> String { self.title.clone() }
    fn set_title(&mut self, value: String) { self.title = value; }
    fn get_exit_on_esc(&self) -> bool { false }
    fn set_exit_on_esc(&mut self, _value: bool) {}
    fn set_capture_cursor(&mut self, _value: bool) {}
}
<commit_msg>Added set_should_close to the window trait & the NoWindow implementation for closing the window programmatically  (issue #944).<commit_after>#![deny(missing_docs)]
#![deny(missing_copy_implementations)]

//! Window abstraction

extern crate libc;
extern crate input;
extern crate shader_version;

use shader_version::OpenGL;
use input::Input;

/// The type of an OpenGL function address.
pub type ProcAddress = *const libc::c_void;

/// Size in pixels.
#[derive(Copy, Clone)]
pub struct Size {
    /// The width in pixels.
    pub width: u32,
    /// The height in pixels.
    pub height: u32,
}

impl From<[u32; 2]> for Size {
    #[inline(always)]
    fn from(value: [u32; 2]) -> Size {
        Size { width: value[0], height: value[1] }
    }
}

impl From<(u32, u32)> for Size {
    #[inline(always)]
    fn from(value: (u32, u32)) -> Size {
        Size { width: value.0, height: value.1 }
    }
}

/// Required to use the event loop.
pub trait Window {
    /// The event type emitted by `poll_event`
    type Event;

    /// Tells the window to close or stay open.
    fn set_should_close(&mut self, value: bool);

    /// Returns true if window should close.
    fn should_close(&self) -> bool;

    /// Gets the size of the window in user coordinates.
    fn size(&self) -> Size;

    /// Swaps render buffers.
    fn swap_buffers(&mut self);

    /// Polls event from window.
    fn poll_event(&mut self) -> Option<Self::Event>;

    /// Gets draw size of the window.
    /// This is equal to the size of the frame buffer of the inner window,
    /// excluding the title bar and borders.
    fn draw_size(&self) -> Size;
}

/// Implemented by fully supported window back-ends.
pub trait AdvancedWindow: Window + Sized {
    /// Gets a copy of the title of the window.
    fn get_title(&self) -> String;

    /// Sets the title of the window.
    fn set_title(&mut self, value: String);

    /// Sets title on window.
    fn title(mut self, value: String) -> Self {
        self.set_title(value);
        self
    }

    /// Gets whether to exit when pressing esc.
    fn get_exit_on_esc(&self) -> bool;

    /// Sets whether to exit when pressing esc.
    fn set_exit_on_esc(&mut self, value: bool);

    /// Sets whether to exit when pressing esc.
    fn exit_on_esc(mut self, value: bool) -> Self {
        self.set_exit_on_esc(value);
        self
    }

    /// Sets whether to capture/grab cursor.
    /// This is used to lock and hide cursor to the window,
    /// for example in a first-person shooter game.
    fn set_capture_cursor(&mut self, value: bool);

    /// Sets whether to capture/grab cursor (see `set_capture_cursor`).
    fn capture_cursor(mut self, value: bool) -> Self {
        self.set_capture_cursor(value);
        self
    }
}

/// Trait for OpenGL specific operations.
pub trait OpenGLWindow: Window {
    /// Returns the address of an OpenGL function if it exist, else returns null pointer.
    fn get_proc_address(&mut self, proc_name: &str) -> ProcAddress;

    /// Returns true if this context is the current context.
    fn is_current(&self) -> bool;

    /// Make this context current.
    fn make_current(&mut self);
}

/// Settings for window behavior.
pub struct WindowSettings {
    /// Title of the window.
    title: String,
    /// The size of the window.
    size: Size,
    /// Number samples per pixel (anti-aliasing).
    samples: u8,
    /// If true, the window is fullscreen.
    fullscreen: bool,
    /// If true, exit when pressing Esc.
    exit_on_esc: bool,
    /// If true, enable vsync.
    vsync: bool,
    /// An optional OpenGL version.
    opengl: Option<OpenGL>,
}

impl WindowSettings {
    /// Creates window settings with defaults.
    /// - samples: 0
    /// - fullscreen: false
    /// - exit_on_esc: false
    pub fn new<T: Into<String>, S: Into<Size>>(
        title: T, size: S) -> WindowSettings
    {
        WindowSettings {
            title: title.into(),
            size: size.into(),
            samples: 0,
            fullscreen: false,
            exit_on_esc: false,
            vsync: false,
            opengl: None,
        }
    }

    /// Gets title.
    pub fn get_title(&self) -> String { self.title.clone() }

    /// Sets title.
    pub fn title(mut self, value: String) -> Self {
        self.title = value;
        self
    }

    /// Gets size.
    pub fn get_size(&self) -> Size { self.size }

    /// Sets size.
    pub fn size(mut self, value: Size) -> Self {
        self.size = value;
        self
    }

    /// Gets fullscreen.
    pub fn get_fullscreen(&self) -> bool { self.fullscreen }

    /// Sets fullscreen.
    pub fn fullscreen(mut self, value: bool) -> Self {
        self.fullscreen = value;
        self
    }

    /// Gets exit on esc.
    pub fn get_exit_on_esc(&self) -> bool { self.exit_on_esc }

    /// Sets exit on esc.
    pub fn exit_on_esc(mut self, value: bool) -> Self {
        self.exit_on_esc = value;
        self
    }

    /// Gets samples.
    pub fn get_samples(&self) -> u8 { self.samples }

    /// Sets samples.
    pub fn samples(mut self, value: u8) -> Self {
        self.samples = value;
        self
    }

    /// Gets vsync.
    pub fn get_vsync(&self) -> bool { self.vsync }

    /// Sets vsync.
    pub fn vsync(mut self, value: bool) -> Self {
        self.vsync = value;
        self
    }

    /// Gets opengl.
    pub fn get_maybe_opengl(&self) -> Option<OpenGL> { self.opengl }

    /// Sets opengl.
    pub fn maybe_opengl(mut self, value: Option<OpenGL>) -> Self {
        self.opengl = value;
        self
    }

    /// Sets opengl.
    pub fn opengl(mut self, value: OpenGL) -> Self {
        self.opengl = Some(value);
        self
    }
}

/// An implementation of Window that runs without a window at all.
pub struct NoWindow {
    should_close: bool,
    title: String,
    size: Size
}

impl NoWindow {
    /// Returns a new `NoWindow`.
    pub fn new(settings: WindowSettings) -> NoWindow {
        NoWindow {
            should_close: false,
            title: settings.title,
            size: settings.size,
        }
    }
}

impl From<WindowSettings> for NoWindow {
    fn from(settings: WindowSettings) -> NoWindow {
        NoWindow::new(settings)
    }
}

impl Window for NoWindow {
    type Event = Input;
    fn should_close(&self) -> bool { self.should_close }
    fn set_should_close(&mut self, value: bool) { self.should_close = value; }
    fn size(&self) -> Size { self.size }
    fn swap_buffers(&mut self) {}
    fn poll_event(&mut self) -> Option<Input> { None }
    fn draw_size(&self) -> Size { self.size() }
}

impl AdvancedWindow for NoWindow {
    fn get_title(&self) -> String { self.title.clone() }
    fn set_title(&mut self, value: String) { self.title = value; }
    fn get_exit_on_esc(&self) -> bool { false }
    fn set_exit_on_esc(&mut self, _value: bool) {}
    fn set_capture_cursor(&mut self, _value: bool) {}
}
<|endoftext|>


<commit_before>use ::DeterministicRandomId;

use std::hash::Hash;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::io::{Read, Write};
use std::any::Any;
use std::fmt::{self, Debug};
use std::collections::BTreeSet;
use std::mem;
use std::cell::RefCell;
use std::marker::PhantomData;

use super::super::api::*;
use implementation_support::common::{split_off_greater_set};

#[derive (Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Debug)]
struct GetValue;
impl StewardData for GetValue{}

#[derive (Clone, Serialize, Deserialize, Debug)]
struct SimpleTimeline <Data: StewardData, B: Basics> {
  // Hacky workaround for https://github.com/rust-lang/rust/issues/41617 (see https://github.com/serde-rs/serde/issues/943)
  #[serde(deserialize_with = "::serde::Deserialize::deserialize")]
  changes: Vec<(DynamicEventHandle <B>, Option <Data>)>,
  #[serde(deserialize_with = "::serde::Deserialize::deserialize")]
  other_dependent_events: RefCell<BTreeSet<DynamicEventHandle<B>>>,
}

impl <Data: StewardData, B: Basics> SimpleTimeline <Data, B> {
  fn new ()->Self {
    SimpleTimeline {
      changes: Vec::new(),
      other_dependent_events: RefCell::new (BTreeSet::new()),
    }
  }

  fn invalidate_after <Steward: TimeSteward <Basics = B>, Accessor: InvalidationAccessor<Steward = Steward>> (&self, time: &ExtendedTime <B>, accessor: & Accessor) {
    let mut dependencies = self.other_dependent_events.borrow_mut();
    let removed = split_off_greater_set (&mut *dependencies, time);
    for event in removed {
      accessor.invalidate_dynamic(&event);
    }
    for change in self.changes.iter().rev() {
      let event = &change.0;
      if event.time() <= time {
        break
      }
      accessor.invalidate_dynamic(&event);
    }
  }

  fn remove_from (&mut self, time: &ExtendedTime <B>) {
    while let Some (change) = self.changes.pop() {
      if change.0.time() <= time {
        self.changes.push (change);
        break
      }
    }
  }
}

impl <Data: StewardData, B: Basics> DataTimeline for SimpleTimeline <Data, B> {
  type Basics = B;

  fn clone_for_snapshot (&self, time: &ExtendedTime <Self::Basics>)->Self {
    let slice = match self.changes.binary_search_by_key (&time, | change | change.0.time()) {
      Ok(index) => &self.changes [index.saturating_sub (1).. index+1],
      Err (index) => &self.changes [index.saturating_sub (1)..index],
    };
    SimpleTimeline {
      changes: slice.to_vec(),
      other_dependent_events: RefCell::new (BTreeSet::new()),
    }
  }

  fn forget_before (&mut self, time: &ExtendedTime <Self::Basics>) {
    let mut dependencies = self.other_dependent_events.borrow_mut();
    let retained = dependencies.split_off (time);
    mem::replace (&mut*dependencies, retained);
  }
}
impl <Data: StewardData, B: Basics> DataTimelineQueriableWith<GetValue> for SimpleTimeline <Data, B> {
  type QueryResult = Option <(ExtendedTime <B>, Option <Data>)>;

  fn query (&self, query: &GetValue, time: &ExtendedTime <Self::Basics>, offset: QueryOffset)->Self::QueryResult {
    let previous_change_index = match self.changes.binary_search_by_key (&time, | change | change.0.time()) {
      Ok(index) => match offset {QueryOffset::After => index, QueryOffset::Before => index.wrapping_sub (1)},
      Err (index) => index.wrapping_sub (1),
    };
    self.changes.get (previous_change_index).map (| change | (change.0.time().clone(), change.1.clone()))
  }
}

fn query_simple_timeline <Data: StewardData, Steward: TimeSteward, Accessor: EventAccessor <Steward = Steward>> (accessor: & Accessor, handle: & DataTimelineHandle <SimpleTimeline <Data, Steward::Basics>>, offset: QueryOffset)->Option <(ExtendedTime <Steward::Basics>, Option <Data>)> {
  accessor.modify (handle, move |timeline| {
    let mut dependencies = timeline.other_dependent_events.borrow_mut();
    dependencies.insert (accessor.handle().clone().erase_type());
  });
  accessor.query (handle, &GetValue, offset)
}
fn modify_simple_timeline <Data: StewardData, Steward: TimeSteward, Accessor: EventAccessor <Steward = Steward>> (accessor: & Accessor, handle: & DataTimelineHandle <SimpleTimeline <Data, Steward::Basics>>, modification: Option <Data>) {
  if let Some((time, data)) = accessor.query (handle, &GetValue, QueryOffset::After) {
    if &time == accessor.now() && data == modification {
      return
    }
  }
  accessor.invalidate (&| invalidator | {
    invalidator.peek(handle).invalidate_after (accessor.now(), invalidator);
  });
  accessor.modify (handle, move |timeline| {
    timeline.remove_from (accessor.now());
    timeline.changes.push ((accessor.handle().clone().erase_type(), modification));
  });
}
fn unmodify_simple_timeline <Data: StewardData, Steward: TimeSteward, Accessor: EventAccessor <Steward = Steward>> (accessor: & Accessor, handle: & DataTimelineHandle <SimpleTimeline <Data, Steward::Basics>>) {
  if let Some((time, data)) = accessor.query (handle, &GetValue, QueryOffset::After) { if &time == accessor.now() {
    accessor.invalidate (&| invalidator | {
      invalidator.peek(handle).invalidate_after (accessor.now(), invalidator);
    });
    accessor.modify (handle, move |timeline| {
      timeline.remove_from (accessor.now());
    });
  }}
}

<commit_msg>Automatic_tracking now compiles!<commit_after>use ::DeterministicRandomId;

use std::hash::Hash;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::io::{Read, Write};
use std::any::Any;
use std::fmt::{self, Debug};
use std::collections::BTreeSet;
use std::mem;
use std::cell::RefCell;
use std::marker::PhantomData;

use super::super::api::*;
use implementation_support::common::{split_off_greater_set};

#[derive (Copy, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Debug)]
struct GetValue;
impl StewardData for GetValue{}

#[derive (Clone, Serialize, Deserialize, Debug)]
struct SimpleTimeline <Data: StewardData, B: Basics> {
  // Hacky workaround for https://github.com/rust-lang/rust/issues/41617 (see https://github.com/serde-rs/serde/issues/943)
  #[serde(deserialize_with = "::serde::Deserialize::deserialize")]
  changes: Vec<(DynamicEventHandle <B>, Option <Data>)>,
  #[serde(deserialize_with = "::serde::Deserialize::deserialize")]
  other_dependent_events: RefCell<BTreeSet<DynamicEventHandle<B>>>,
}

impl <Data: StewardData, B: Basics> SimpleTimeline <Data, B> {
  fn new ()->Self {
    SimpleTimeline {
      changes: Vec::new(),
      other_dependent_events: RefCell::new (BTreeSet::new()),
    }
  }

  fn invalidate_after <Steward: TimeSteward <Basics = B>, Accessor: InvalidationAccessor<Steward = Steward>> (&self, time: &ExtendedTime <B>, accessor: & Accessor) {
    let mut dependencies = self.other_dependent_events.borrow_mut();
    let removed = split_off_greater_set (&mut *dependencies, time);
    for event in removed {
      accessor.invalidate_dynamic(&event);
    }
    for change in self.changes.iter().rev() {
      let event = &change.0;
      if event.time() <= time {
        break
      }
      accessor.invalidate_dynamic(&event);
    }
  }

  fn remove_from (&mut self, time: &ExtendedTime <B>) {
    while let Some (change) = self.changes.pop() {
      if change.0.time() <= time {
        self.changes.push (change);
        break
      }
    }
  }
}

impl <Data: StewardData, B: Basics> DataTimeline for SimpleTimeline <Data, B> {
  type Basics = B;

  fn clone_for_snapshot (&self, time: &ExtendedTime <Self::Basics>)->Self {
    let slice = match self.changes.binary_search_by_key (&time, | change | change.0.time()) {
      Ok(index) => &self.changes [index.saturating_sub (1).. index+1],
      Err (index) => &self.changes [index.saturating_sub (1)..index],
    };
    SimpleTimeline {
      changes: slice.to_vec(),
      other_dependent_events: RefCell::new (BTreeSet::new()),
    }
  }

  fn forget_before (&mut self, time: &ExtendedTime <Self::Basics>) {
    let mut dependencies = self.other_dependent_events.borrow_mut();
    let retained = dependencies.split_off (time);
    mem::replace (&mut*dependencies, retained);
  }
}
impl <Data: StewardData, B: Basics> DataTimelineQueriableWith<GetValue> for SimpleTimeline <Data, B> {
  type QueryResult = Option <(ExtendedTime <B>, Option <Data>)>;

  fn query (&self, query: &GetValue, time: &ExtendedTime <Self::Basics>, offset: QueryOffset)->Self::QueryResult {
    let previous_change_index = match self.changes.binary_search_by_key (&time, | change | change.0.time()) {
      Ok(index) => match offset {QueryOffset::After => index, QueryOffset::Before => index.wrapping_sub (1)},
      Err (index) => index.wrapping_sub (1),
    };
    self.changes.get (previous_change_index).map (| change | (change.0.time().clone(), change.1.clone()))
  }
}

fn query_simple_timeline <Data: StewardData, Steward: TimeSteward, Accessor: EventAccessor <Steward = Steward>> (accessor: & Accessor, handle: & DataTimelineHandle <SimpleTimeline <Data, Steward::Basics>>, offset: QueryOffset)->Option <(ExtendedTime <Steward::Basics>, Option <Data>)> {
  accessor.modify (handle, move |timeline| {
    let mut dependencies = timeline.other_dependent_events.borrow_mut();
    dependencies.insert (accessor.handle().clone().erase_type());
  });
  accessor.query (handle, &GetValue, offset)
}
fn modify_simple_timeline <Data: StewardData, Steward: TimeSteward, Accessor: EventAccessor <Steward = Steward>> (accessor: & Accessor, handle: & DataTimelineHandle <SimpleTimeline <Data, Steward::Basics>>, modification: Option <Data>) {
  if let Some((time, data)) = accessor.query (handle, &GetValue, QueryOffset::After) {
    if &time == accessor.now() && data == modification {
      return
    }
  }
  accessor.invalidate (| invalidator | {
    invalidator.peek(handle).invalidate_after (accessor.now(), invalidator);
  });
  accessor.modify (handle, move |timeline| {
    timeline.remove_from (accessor.now());
    timeline.changes.push ((accessor.handle().clone().erase_type(), modification));
  });
}
fn unmodify_simple_timeline <Data: StewardData, Steward: TimeSteward, Accessor: EventAccessor <Steward = Steward>> (accessor: & Accessor, handle: & DataTimelineHandle <SimpleTimeline <Data, Steward::Basics>>) {
  if let Some((time, data)) = accessor.query (handle, &GetValue, QueryOffset::After) { if &time == accessor.now() {
    accessor.invalidate (| invalidator | {
      invalidator.peek(handle).invalidate_after (accessor.now(), invalidator);
    });
    accessor.modify (handle, move |timeline| {
      timeline.remove_from (accessor.now());
    });
  }}
}

<|endoftext|>


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

use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct MempoolConfig {
    pub broadcast_transactions: bool,
    pub capacity: usize,
    pub capacity_per_user: usize,
    pub max_broadcasts_per_peer: usize,
    pub shared_mempool_backoff_interval_ms: u64,
    pub shared_mempool_batch_size: usize,
    pub shared_mempool_max_concurrent_inbound_syncs: usize,
    pub shared_mempool_min_broadcast_recipient_count: Option<usize>,
    pub shared_mempool_tick_interval_ms: u64,
    pub system_transaction_timeout_secs: u64,
    pub system_transaction_gc_interval_ms: u64,
}

impl Default for MempoolConfig {
    fn default() -> MempoolConfig {
        MempoolConfig {
            broadcast_transactions: true,
            shared_mempool_tick_interval_ms: 50,
            shared_mempool_backoff_interval_ms: 30_000,
            shared_mempool_batch_size: 100,
            shared_mempool_max_concurrent_inbound_syncs: 100,
            shared_mempool_min_broadcast_recipient_count: None,
            max_broadcasts_per_peer: 25,
            capacity: 1_000_000,
            capacity_per_user: 100,
            system_transaction_timeout_secs: 86400,
            system_transaction_gc_interval_ms: 180_000,
        }
    }
}
<commit_msg>[mempool] remove unused config field 'broadcast_transactions'<commit_after>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct MempoolConfig {
    pub capacity: usize,
    pub capacity_per_user: usize,
    pub max_broadcasts_per_peer: usize,
    pub shared_mempool_backoff_interval_ms: u64,
    pub shared_mempool_batch_size: usize,
    pub shared_mempool_max_concurrent_inbound_syncs: usize,
    pub shared_mempool_min_broadcast_recipient_count: Option<usize>,
    pub shared_mempool_tick_interval_ms: u64,
    pub system_transaction_timeout_secs: u64,
    pub system_transaction_gc_interval_ms: u64,
}

impl Default for MempoolConfig {
    fn default() -> MempoolConfig {
        MempoolConfig {
            shared_mempool_tick_interval_ms: 50,
            shared_mempool_backoff_interval_ms: 30_000,
            shared_mempool_batch_size: 100,
            shared_mempool_max_concurrent_inbound_syncs: 100,
            shared_mempool_min_broadcast_recipient_count: None,
            max_broadcasts_per_peer: 25,
            capacity: 1_000_000,
            capacity_per_user: 100,
            system_transaction_timeout_secs: 86400,
            system_transaction_gc_interval_ms: 180_000,
        }
    }
}
<|endoftext|>


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

use collections::String;
use collections::Vec;

use drivers::pio::Pio8;

use graphics::color::Color;
use graphics::display::Display;
use graphics::point::Point;
use graphics::size::Size;

const BLACK: Color = Color::new(0, 0, 0);
const RED: Color = Color::new(194, 54, 33);
const GREEN: Color = Color::new(37, 188, 36);
const YELLOW: Color = Color::new(173, 173, 39);
const BLUE: Color = Color::new(73, 46, 225);
const MAGENTA: Color = Color::new(211, 56, 211);
const CYAN: Color = Color::new(51, 187, 200);
const WHITE: Color = Color::new(203, 204, 205);

pub struct Console {
    pub display: Box<Display>,
    pub point: Point,
    pub foreground: Color,
    pub background: Color,
    pub instant: bool,
    pub draw: bool,
    pub redraw: bool,
    pub command: Option<String>,
    pub escape: bool,
    pub escape_sequence: bool,
    pub sequence: Vec<String>,
}

impl Console {
    pub fn new() -> Console {
        Console {
            display: unsafe { Display::root() },
            point: Point::new(0, 0),
            foreground: WHITE,
            background: BLACK,
            instant: true,
            draw: false,
            redraw: true,
            command: None,
            escape: false,
            escape_sequence: false,
            sequence: Vec::new(),
        }
    }

    pub fn code(&mut self, c: char) {
        if self.escape_sequence {
            if c >= '0' && c <= '9' {
                // Add a number to the sequence list
                if let Some(mut value) = self.sequence.last_mut() {
                    value.push(c);
                }
            } else if c == ';' {
                // Split sequence into list
                self.sequence.push(String::new());
            } else if c == 'm' {
                // Display attributes
                for value in self.sequence.iter() {
                    if value == "0" {
                        // Reset all
                        self.foreground = WHITE;
                        self.background = BLACK;
                    } else if value == "30" {
                        self.foreground = BLACK;
                    } else if value == "31" {
                        self.foreground = RED;
                    } else if value == "32" {
                        self.foreground = GREEN;
                    } else if value == "33" {
                        self.foreground = YELLOW;
                    } else if value == "34" {
                        self.foreground = BLUE;
                    } else if value == "35" {
                        self.foreground = MAGENTA;
                    } else if value == "36" {
                        self.foreground = CYAN;
                    } else if value == "37" {
                        self.foreground = WHITE;
                    } else if value == "40" {
                        self.background = BLACK;
                    } else if value == "41" {
                        self.background = RED;
                    } else if value == "42" {
                        self.background = GREEN;
                    } else if value == "43" {
                        self.background = YELLOW;
                    } else if value == "44" {
                        self.background = BLUE;
                    } else if value == "45" {
                        self.background = MAGENTA;
                    } else if value == "46" {
                        self.background = CYAN;
                    } else if value == "47" {
                        self.background = WHITE;
                    }
                }

                self.escape_sequence = false;
            } else {
                self.escape_sequence = false;
            }

            if !self.escape_sequence {
                self.sequence.clear();
                self.escape = false;
            }
        } else if c == '[' {
            // Control sequence initiator

            self.escape_sequence = true;
            self.sequence.push(String::new());
        } else if c == 'c' {
            // Reset
            self.point.x = 0;
            self.point.y = 0;
            self.foreground = WHITE;
            self.background = BLACK;
            self.display.set(self.background);
            self.redraw = true;

            self.escape = false;
        } else {
            // Unknown escape character

            self.escape = false;
        }
    }

    pub fn character(&mut self, c: char) {
        self.display.rect(self.point, Size::new(8, 16), self.background);
        if c == '\x1B' {
            self.escape = true;
        } else if c == '\n' {
            self.point.x = 0;
            self.point.y += 16;
        } else if c == '\x08' {
            self.point.x -= 8;
            if self.point.x < 0 {
                self.point.x = 0
            }
            self.display.rect(self.point, Size::new(8, 16), self.background);
        } else {
            self.display.char(self.point, c, self.foreground);
            self.point.x += 8;
        }
        if self.point.x >= self.display.width as isize {
            self.point.x = 0;
            self.point.y += 16;
        }
        while self.point.y + 16 > self.display.height as isize {
            self.display.scroll(16);
            self.point.y -= 16;
        }
        self.display.rect(self.point, Size::new(8, 16), self.foreground);
        self.redraw = true;
    }

    pub fn write(&mut self, bytes: &[u8]) {
        let serial_status = Pio8::new(0x3F8 + 5);
        let mut serial_data = Pio8::new(0x3F8);

        for byte in bytes.iter() {
            let c = *byte as char;

            if self.escape {
                self.code(c);
            } else {
                self.character(c);
            }

            unsafe {
                while serial_status.read() & 0x20 == 0 {}
                serial_data.write(*byte);

                if *byte == 8 {
                    while serial_status.read() & 0x20 == 0 {}
                    serial_data.write(0x20);

                    while serial_status.read() & 0x20 == 0 {}
                    serial_data.write(8);
                }
            }
        }
        // If contexts disabled, probably booting up
        if self.instant && self.draw && self.redraw {
            self.redraw = false;
            self.display.flip();
        }
    }
}
<commit_msg>Add tab<commit_after>use alloc::boxed::Box;

use collections::String;
use collections::Vec;

use drivers::pio::Pio8;

use graphics::color::Color;
use graphics::display::Display;
use graphics::point::Point;
use graphics::size::Size;

const BLACK: Color = Color::new(0, 0, 0);
const RED: Color = Color::new(194, 54, 33);
const GREEN: Color = Color::new(37, 188, 36);
const YELLOW: Color = Color::new(173, 173, 39);
const BLUE: Color = Color::new(73, 46, 225);
const MAGENTA: Color = Color::new(211, 56, 211);
const CYAN: Color = Color::new(51, 187, 200);
const WHITE: Color = Color::new(203, 204, 205);

pub struct Console {
    pub display: Box<Display>,
    pub point: Point,
    pub foreground: Color,
    pub background: Color,
    pub instant: bool,
    pub draw: bool,
    pub redraw: bool,
    pub command: Option<String>,
    pub escape: bool,
    pub escape_sequence: bool,
    pub sequence: Vec<String>,
}

impl Console {
    pub fn new() -> Console {
        Console {
            display: unsafe { Display::root() },
            point: Point::new(0, 0),
            foreground: WHITE,
            background: BLACK,
            instant: true,
            draw: false,
            redraw: true,
            command: None,
            escape: false,
            escape_sequence: false,
            sequence: Vec::new(),
        }
    }

    pub fn code(&mut self, c: char) {
        if self.escape_sequence {
            if c >= '0' && c <= '9' {
                // Add a number to the sequence list
                if let Some(mut value) = self.sequence.last_mut() {
                    value.push(c);
                }
            } else if c == ';' {
                // Split sequence into list
                self.sequence.push(String::new());
            } else if c == 'm' {
                // Display attributes
                for value in self.sequence.iter() {
                    if value == "0" {
                        // Reset all
                        self.foreground = WHITE;
                        self.background = BLACK;
                    } else if value == "30" {
                        self.foreground = BLACK;
                    } else if value == "31" {
                        self.foreground = RED;
                    } else if value == "32" {
                        self.foreground = GREEN;
                    } else if value == "33" {
                        self.foreground = YELLOW;
                    } else if value == "34" {
                        self.foreground = BLUE;
                    } else if value == "35" {
                        self.foreground = MAGENTA;
                    } else if value == "36" {
                        self.foreground = CYAN;
                    } else if value == "37" {
                        self.foreground = WHITE;
                    } else if value == "40" {
                        self.background = BLACK;
                    } else if value == "41" {
                        self.background = RED;
                    } else if value == "42" {
                        self.background = GREEN;
                    } else if value == "43" {
                        self.background = YELLOW;
                    } else if value == "44" {
                        self.background = BLUE;
                    } else if value == "45" {
                        self.background = MAGENTA;
                    } else if value == "46" {
                        self.background = CYAN;
                    } else if value == "47" {
                        self.background = WHITE;
                    }
                }

                self.escape_sequence = false;
            } else {
                self.escape_sequence = false;
            }

            if !self.escape_sequence {
                self.sequence.clear();
                self.escape = false;
            }
        } else if c == '[' {
            // Control sequence initiator

            self.escape_sequence = true;
            self.sequence.push(String::new());
        } else if c == 'c' {
            // Reset
            self.point.x = 0;
            self.point.y = 0;
            self.foreground = WHITE;
            self.background = BLACK;
            self.display.set(self.background);
            self.redraw = true;

            self.escape = false;
        } else {
            // Unknown escape character

            self.escape = false;
        }
    }

    pub fn character(&mut self, c: char) {
        self.display.rect(self.point, Size::new(8, 16), self.background);
        if c == '\x1B' {
            self.escape = true;
        } else if c == '\n' {
            self.point.x = 0;
            self.point.y += 16;
        } else if c == '\t' {
            self.point.x = ((self.point.x / 64) + 1) * 64;
        } else if c == '\x08' {
            self.point.x -= 8;
            if self.point.x < 0 {
                self.point.x = 0
            }
            self.display.rect(self.point, Size::new(8, 16), self.background);
        } else {
            self.display.char(self.point, c, self.foreground);
            self.point.x += 8;
        }
        if self.point.x >= self.display.width as isize {
            self.point.x = 0;
            self.point.y += 16;
        }
        while self.point.y + 16 > self.display.height as isize {
            self.display.scroll(16);
            self.point.y -= 16;
        }
        self.display.rect(self.point, Size::new(8, 16), self.foreground);
        self.redraw = true;
    }

    pub fn write(&mut self, bytes: &[u8]) {
        let serial_status = Pio8::new(0x3F8 + 5);
        let mut serial_data = Pio8::new(0x3F8);

        for byte in bytes.iter() {
            let c = *byte as char;

            if self.escape {
                self.code(c);
            } else {
                self.character(c);
            }

            unsafe {
                while serial_status.read() & 0x20 == 0 {}
                serial_data.write(*byte);

                if *byte == 8 {
                    while serial_status.read() & 0x20 == 0 {}
                    serial_data.write(0x20);

                    while serial_status.read() & 0x20 == 0 {}
                    serial_data.write(8);
                }
            }
        }
        // If contexts disabled, probably booting up
        if self.instant && self.draw && self.redraw {
            self.redraw = false;
            self.display.flip();
        }
    }
}
<|endoftext|>


<commit_before>use models::*;

pub fn print_headline_with_author(item:&HnItem, index:&i32) {
    let s = create_headline_with_author(item, index).unwrap(); // Not handling errs
    println!("{}", s);
}

fn create_headline_with_author(item:&HnItem, index:&i32) -> Result<String,String> {
    match item.title {
        Some(ref title) => Ok(format!("[{}] {} ~{}", &index, &item.title.as_ref().unwrap(), &item.by)),
        None => Err(String::from("Not headline"))
    }
}<commit_msg>Made cli prints for headlines similar width<commit_after>use models::*;

pub fn print_headline_with_author(item: &HnItem, index: &i32) {
    let s = create_headline_with_author(item, index).unwrap(); // Not handling errs
    println!("{}", s);
}

fn create_headline_with_author(item: &HnItem, index: &i32) -> Result<String, String> {
    match item.title {
        Some(ref title) => {
            let s = format!("[{:3}] {:80} ~ {}",
                            &index,
                            &item.title.as_ref().unwrap(),
                            &item.by);
            Ok(s)

        }
        None => Err(String::from("Not headline")),
    }
}<|endoftext|>


<commit_before>extern crate base64;
extern crate md5;

use std::io::Write;

use attohttpc::header::HeaderName;

use crate::bucket::Bucket;
use crate::command::Command;
use crate::error::S3Error;
use bytes::Bytes;
use std::collections::HashMap;
use time::OffsetDateTime;

use crate::command::HttpMethod;
use crate::request::{Request, ResponseData};

// Temporary structure for making a request
pub struct AttoRequest<'a> {
    pub bucket: &'a Bucket,
    pub path: &'a str,
    pub command: Command<'a>,
    pub datetime: OffsetDateTime,
    pub sync: bool,
}

impl<'a> Request for AttoRequest<'a> {
    type Response = attohttpc::Response;
    type HeaderMap = attohttpc::header::HeaderMap;

    fn datetime(&self) -> OffsetDateTime {
        self.datetime
    }

    fn bucket(&self) -> Bucket {
        self.bucket.clone()
    }

    fn command(&self) -> Command {
        self.command.clone()
    }

    fn path(&self) -> String {
        self.path.to_string()
    }

    fn response(&self) -> Result<Self::Response, S3Error> {
        // Build headers
        let headers = match self.headers() {
            Ok(headers) => headers,
            Err(e) => return Err(e),
        };

        let mut session = attohttpc::Session::new();

        for (name, value) in headers.iter() {
            session.header(HeaderName::from_bytes(name.as_ref()).unwrap(), value);
        }

        if let Some(timeout) = self.bucket.request_timeout {
            session.timeout(timeout)
        }

        let request = match self.command.http_verb() {
            HttpMethod::Get => session.get(self.url()),
            HttpMethod::Delete => session.delete(self.url()),
            HttpMethod::Put => session.put(self.url()),
            HttpMethod::Post => session.post(self.url()),
            HttpMethod::Head => session.head(self.url()),
        };

        let response = request.bytes(&self.request_body()).send()?;

        if cfg!(feature = "fail-on-err") && !response.status().is_success() {
            let status = response.status().as_u16();
            let text = response.text()?;
            return Err(S3Error::Http(status, text));
        }

        Ok(response)
    }

    fn response_data(&self, etag: bool) -> Result<ResponseData, S3Error> {
        let response = self.response()?;
        let status_code = response.status().as_u16();

        let response_headers = response
            .headers()
            .iter()
            .map(|(k, v)| {
                (
                    k.to_string(),
                    v.to_str()
                        .unwrap_or("could-not-decode-header-value")
                        .to_string(),
                )
            })
            .collect::<HashMap<String, String>>();

        let body_vec = if etag {
            if let Some(etag) = response.headers().get("ETag") {
                Bytes::from(etag.to_str()?.to_string())
            } else {
                Bytes::from("")
            }
        } else {
            Bytes::from(response.bytes()?)
        };
        Ok(ResponseData::new(body_vec, status_code, response_headers))
    }

    fn response_data_to_writer<T: Write>(&self, writer: &mut T) -> Result<u16, S3Error> {
        let response = self.response()?;

        let status_code = response.status();
        let stream = response.bytes()?;

        writer.write_all(&stream)?;

        Ok(status_code.as_u16())
    }

    fn response_header(&self) -> Result<(Self::HeaderMap, u16), S3Error> {
        let response = self.response()?;
        let status_code = response.status().as_u16();
        let headers = response.headers().clone();
        Ok((headers, status_code))
    }
}

impl<'a> AttoRequest<'a> {
    pub fn new<'b>(
        bucket: &'b Bucket,
        path: &'b str,
        command: Command<'b>,
    ) -> Result<AttoRequest<'b>, S3Error> {
        bucket.credentials_refresh()?;
        Ok(AttoRequest {
            bucket,
            path,
            command,
            datetime: OffsetDateTime::now_utc(),
            sync: false,
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::bucket::Bucket;
    use crate::command::Command;
    use crate::request::blocking::AttoRequest;
    use crate::request::Request;
    use anyhow::Result;
    use awscreds::Credentials;

    // Fake keys - otherwise using Credentials::default will use actual user
    // credentials if they exist.
    fn fake_credentials() -> Credentials {
        let access_key = "AKIAIOSFODNN7EXAMPLE";
        let secert_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY";
        Credentials::new(Some(access_key), Some(secert_key), None, None, None).unwrap()
    }

    #[test]
    fn url_uses_https_by_default() -> Result<()> {
        let region = "custom-region".parse()?;
        let bucket = Bucket::new("my-first-bucket", region, fake_credentials())?;
        let path = "/my-first/path";
        let request = AttoRequest::new(&bucket, path, Command::GetObject).unwrap();

        assert_eq!(request.url().scheme(), "https");

        let headers = request.headers().unwrap();
        let host = headers.get("Host").unwrap();

        assert_eq!(*host, "my-first-bucket.custom-region".to_string());
        Ok(())
    }

    #[test]
    fn url_uses_https_by_default_path_style() -> Result<()> {
        let region = "custom-region".parse()?;
        let mut bucket = Bucket::new("my-first-bucket", region, fake_credentials())?;
        bucket.with_path_style();
        let path = "/my-first/path";
        let request = AttoRequest::new(&bucket, path, Command::GetObject).unwrap();

        assert_eq!(request.url().scheme(), "https");

        let headers = request.headers().unwrap();
        let host = headers.get("Host").unwrap();

        assert_eq!(*host, "custom-region".to_string());
        Ok(())
    }

    #[test]
    fn url_uses_scheme_from_custom_region_if_defined() -> Result<()> {
        let region = "http://custom-region".parse()?;
        let bucket = Bucket::new("my-second-bucket", region, fake_credentials())?;
        let path = "/my-second/path";
        let request = AttoRequest::new(&bucket, path, Command::GetObject).unwrap();

        assert_eq!(request.url().scheme(), "http");

        let headers = request.headers().unwrap();
        let host = headers.get("Host").unwrap();
        assert_eq!(*host, "my-second-bucket.custom-region".to_string());
        Ok(())
    }

    #[test]
    fn url_uses_scheme_from_custom_region_if_defined_with_path_style() -> Result<()> {
        let region = "http://custom-region".parse()?;
        let mut bucket = Bucket::new("my-second-bucket", region, fake_credentials())?;
        bucket.with_path_style();
        let path = "/my-second/path";
        let request = AttoRequest::new(&bucket, path, Command::GetObject).unwrap();

        assert_eq!(request.url().scheme(), "http");

        let headers = request.headers().unwrap();
        let host = headers.get("Host").unwrap();
        assert_eq!(*host, "custom-region".to_string());

        Ok(())
    }
}
<commit_msg>Stream sync get object responses (#301)<commit_after>extern crate base64;
extern crate md5;

use std::io;
use std::io::Write;

use attohttpc::header::HeaderName;

use crate::bucket::Bucket;
use crate::command::Command;
use crate::error::S3Error;
use bytes::Bytes;
use std::collections::HashMap;
use time::OffsetDateTime;

use crate::command::HttpMethod;
use crate::request::{Request, ResponseData};

// Temporary structure for making a request
pub struct AttoRequest<'a> {
    pub bucket: &'a Bucket,
    pub path: &'a str,
    pub command: Command<'a>,
    pub datetime: OffsetDateTime,
    pub sync: bool,
}

impl<'a> Request for AttoRequest<'a> {
    type Response = attohttpc::Response;
    type HeaderMap = attohttpc::header::HeaderMap;

    fn datetime(&self) -> OffsetDateTime {
        self.datetime
    }

    fn bucket(&self) -> Bucket {
        self.bucket.clone()
    }

    fn command(&self) -> Command {
        self.command.clone()
    }

    fn path(&self) -> String {
        self.path.to_string()
    }

    fn response(&self) -> Result<Self::Response, S3Error> {
        // Build headers
        let headers = match self.headers() {
            Ok(headers) => headers,
            Err(e) => return Err(e),
        };

        let mut session = attohttpc::Session::new();

        for (name, value) in headers.iter() {
            session.header(HeaderName::from_bytes(name.as_ref()).unwrap(), value);
        }

        if let Some(timeout) = self.bucket.request_timeout {
            session.timeout(timeout)
        }

        let request = match self.command.http_verb() {
            HttpMethod::Get => session.get(self.url()),
            HttpMethod::Delete => session.delete(self.url()),
            HttpMethod::Put => session.put(self.url()),
            HttpMethod::Post => session.post(self.url()),
            HttpMethod::Head => session.head(self.url()),
        };

        let response = request.bytes(&self.request_body()).send()?;

        if cfg!(feature = "fail-on-err") && !response.status().is_success() {
            let status = response.status().as_u16();
            let text = response.text()?;
            return Err(S3Error::Http(status, text));
        }

        Ok(response)
    }

    fn response_data(&self, etag: bool) -> Result<ResponseData, S3Error> {
        let response = self.response()?;
        let status_code = response.status().as_u16();

        let response_headers = response
            .headers()
            .iter()
            .map(|(k, v)| {
                (
                    k.to_string(),
                    v.to_str()
                        .unwrap_or("could-not-decode-header-value")
                        .to_string(),
                )
            })
            .collect::<HashMap<String, String>>();

        let body_vec = if etag {
            if let Some(etag) = response.headers().get("ETag") {
                Bytes::from(etag.to_str()?.to_string())
            } else {
                Bytes::from("")
            }
        } else {
            Bytes::from(response.bytes()?)
        };
        Ok(ResponseData::new(body_vec, status_code, response_headers))
    }

    fn response_data_to_writer<T: Write>(&self, writer: &mut T) -> Result<u16, S3Error> {
        let mut response = self.response()?;

        let status_code = response.status();
        io::copy(&mut response, writer)?;

        Ok(status_code.as_u16())
    }

    fn response_header(&self) -> Result<(Self::HeaderMap, u16), S3Error> {
        let response = self.response()?;
        let status_code = response.status().as_u16();
        let headers = response.headers().clone();
        Ok((headers, status_code))
    }
}

impl<'a> AttoRequest<'a> {
    pub fn new<'b>(
        bucket: &'b Bucket,
        path: &'b str,
        command: Command<'b>,
    ) -> Result<AttoRequest<'b>, S3Error> {
        bucket.credentials_refresh()?;
        Ok(AttoRequest {
            bucket,
            path,
            command,
            datetime: OffsetDateTime::now_utc(),
            sync: false,
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::bucket::Bucket;
    use crate::command::Command;
    use crate::request::blocking::AttoRequest;
    use crate::request::Request;
    use anyhow::Result;
    use awscreds::Credentials;

    // Fake keys - otherwise using Credentials::default will use actual user
    // credentials if they exist.
    fn fake_credentials() -> Credentials {
        let access_key = "AKIAIOSFODNN7EXAMPLE";
        let secert_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY";
        Credentials::new(Some(access_key), Some(secert_key), None, None, None).unwrap()
    }

    #[test]
    fn url_uses_https_by_default() -> Result<()> {
        let region = "custom-region".parse()?;
        let bucket = Bucket::new("my-first-bucket", region, fake_credentials())?;
        let path = "/my-first/path";
        let request = AttoRequest::new(&bucket, path, Command::GetObject).unwrap();

        assert_eq!(request.url().scheme(), "https");

        let headers = request.headers().unwrap();
        let host = headers.get("Host").unwrap();

        assert_eq!(*host, "my-first-bucket.custom-region".to_string());
        Ok(())
    }

    #[test]
    fn url_uses_https_by_default_path_style() -> Result<()> {
        let region = "custom-region".parse()?;
        let mut bucket = Bucket::new("my-first-bucket", region, fake_credentials())?;
        bucket.with_path_style();
        let path = "/my-first/path";
        let request = AttoRequest::new(&bucket, path, Command::GetObject).unwrap();

        assert_eq!(request.url().scheme(), "https");

        let headers = request.headers().unwrap();
        let host = headers.get("Host").unwrap();

        assert_eq!(*host, "custom-region".to_string());
        Ok(())
    }

    #[test]
    fn url_uses_scheme_from_custom_region_if_defined() -> Result<()> {
        let region = "http://custom-region".parse()?;
        let bucket = Bucket::new("my-second-bucket", region, fake_credentials())?;
        let path = "/my-second/path";
        let request = AttoRequest::new(&bucket, path, Command::GetObject).unwrap();

        assert_eq!(request.url().scheme(), "http");

        let headers = request.headers().unwrap();
        let host = headers.get("Host").unwrap();
        assert_eq!(*host, "my-second-bucket.custom-region".to_string());
        Ok(())
    }

    #[test]
    fn url_uses_scheme_from_custom_region_if_defined_with_path_style() -> Result<()> {
        let region = "http://custom-region".parse()?;
        let mut bucket = Bucket::new("my-second-bucket", region, fake_credentials())?;
        bucket.with_path_style();
        let path = "/my-second/path";
        let request = AttoRequest::new(&bucket, path, Command::GetObject).unwrap();

        assert_eq!(request.url().scheme(), "http");

        let headers = request.headers().unwrap();
        let host = headers.get("Host").unwrap();
        assert_eq!(*host, "custom-region".to_string());

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