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

/// Extended PCG generators utilize a simple method to dramatically extend the
/// period of the genrators. In addition to extending the period of the
/// generator it ensures that the generators have K-dimensional
/// equidistribution. This means that the generator will produce every possible
/// K-tuple uniformly.
///
/// These generators require `K*sizeof(Isize)` extra bytes to provide their
/// equidistribution.
///
/// These extended generators are currently in a beta state. They are
/// implemented according to my understanding of the generator extension
/// technique presented in the PCG paper.
/// You can use these generators if you want, and if you would like to help
/// me review the code and determine if my implementation is correct that would
/// be wonderful.
pub mod extsizes;

pub use self::extsizes::*;

use extprim::u128::u128;
use rand::{Rng, Rand, SeedableRng};
use std::marker::PhantomData;
use super::PcgEngine;
use super::numops::*;
use super::stream::*;
use super::outputmix::*;
use super::multiplier::*;
use num_traits::Zero;

/// An extended PCG generator. These generators provide K-dimensional
/// equidistribution. Where K is specified by the value of the Size parameter
/// which must be an ExtSize type.
pub struct ExtPcg<Itype, Xtype,
    StreamMix: Stream<Itype>,
    MulMix: Multiplier<Itype>,
    OutMix: OutputMixin<Itype, Xtype>,
    Size: ExtSize>
{
    pcg : PcgEngine<Itype, Xtype, StreamMix, MulMix, OutMix>,
    ext : Vec<Xtype>,
    _size : PhantomData<Size>,
}

impl<Itype, Xtype, StreamMix, MulMix, OutMix, Size>
    ExtPcg<Itype, Xtype, StreamMix, MulMix, OutMix, Size>
    where
    Itype: Zero,
    Xtype: PcgOps + BitSize + Rand,
    StreamMix: Stream<Itype>,
    MulMix: Multiplier<Itype>,
    OutMix: OutputMixin<Itype, Xtype>,
    Size: ExtSize,
    PcgEngine<Itype, Xtype, StreamMix, MulMix, OutMix>: Rng
{

    /// Create a new ExtPcg from an existing PCG. This will consume
    /// Size random values to initialize the extension array.
    pub fn from_pcg(pcg: PcgEngine<Itype, Xtype, StreamMix, MulMix, OutMix>) ->
        ExtPcg<Itype, Xtype, StreamMix, MulMix, OutMix, Size> {
            let mut pcg = pcg;

            //Create the starting extension array
            let mut ext = Vec::new();
            for _ in 0..Size::ext_size() {
                ext.push(pcg.gen());
            }

            ExtPcg {
                pcg : pcg,
                ext : ext,
                _size : PhantomData::<Size>,
            }
    }

    /// Create a new unseeded ExtPcg.
    pub fn new_unseeded() -> ExtPcg<Itype, Xtype, StreamMix, MulMix, OutMix, Size>
    {
        let pcg = PcgEngine::<Itype, Xtype, StreamMix, MulMix, OutMix>::new_unseeded();
        Self::from_pcg(pcg)
    }
}

impl<Itype, StreamMix, MulMix, OutMix, Size> Rng for
    ExtPcg<Itype, u32, StreamMix, MulMix, OutMix, Size>
    where Itype: PcgOps + AsUsize + BitSize + AsSmaller<u32> + Clone,
    StreamMix: Stream<Itype>,
    MulMix: Multiplier<Itype>,
    OutMix: OutputMixin<Itype, u32>,
    Size: ExtSize {

    #[inline]
    fn next_u32(&mut self) -> u32 {
        let oldstate = self.pcg.state.clone();
        self.pcg.state = self.pcg.stream_mix.increment().wrap_add(oldstate.wrap_mul(MulMix::multiplier()));

        let mask = 2usize.pow(Size::ext_bits() as u32)-1;
        let pick = self.pcg.state.as_usize() & mask;

        let ext_val = self.ext[pick];
        self.ext[pick] = self.ext[pick] + 1;
        OutMix::output(oldstate) ^ ext_val
    }
}

impl<Itype, StreamMix, MulMix, OutMix, Size> Rng for
    ExtPcg<Itype, u64, StreamMix, MulMix, OutMix, Size>
    where Itype: PcgOps + AsUsize + BitSize + AsSmaller<u64> + Clone,
    StreamMix: Stream<Itype>,
    MulMix: Multiplier<Itype>,
    OutMix: OutputMixin<Itype, u64>,
    Size: ExtSize {

    #[inline]
    fn next_u32(&mut self) -> u32 {
        self.next_u64() as u32
    }

    #[inline]
    fn next_u64(&mut self) -> u64 {
        let oldstate = self.pcg.state.clone();
        self.pcg.state = self.pcg.stream_mix.increment().wrap_add(oldstate.wrap_mul(MulMix::multiplier()));

        let mask = 2usize.pow(Size::ext_bits() as u32)-1;
        let pick = self.pcg.state.as_usize() & mask;

        let ext_val = self.ext[pick];
        self.ext[pick] = self.ext[pick] + 1;
        OutMix::output(oldstate) ^ ext_val
    }
}

pub type SetseqXshRr6432ext<Size> = ExtPcg<u64, u32, SpecificSeqStream<u64>, DefaultMultiplier, XshRrMixin, Size>;
pub type SetseqXshRr12832ext<Size> = ExtPcg<u128, u32, SpecificSeqStream<u128>, DefaultMultiplier, XshRrMixin, Size>;
pub type SetseqXshRr12864ext<Size> = ExtPcg<u128, u64, SpecificSeqStream<u128>, DefaultMultiplier, XshRrMixin, Size>;

/// The extended version of the Pcg32 generator
pub type Pcg32Ext<Size> = SetseqXshRr6432ext<Size>;
/// The extended version of the Pcg32L generator
pub type Pcg32LExt<Size> = SetseqXshRr12832ext<Size>;
/// The extended version of the Pcg64 generator
pub type Pcg64Ext<Size> = SetseqXshRr12864ext<Size>;

//
// Seeding for the ExtPcgs
//

//These generics get pretty insane
impl<Itype, Xtype, StreamMix, MulMix, OutMix, Size> SeedableRng<Itype> for ExtPcg<Itype, Xtype, StreamMix, MulMix, OutMix, Size>
    where
    Itype: Zero,
    Xtype: PcgOps + BitSize + Rand,
    StreamMix: Stream<Itype>,
    MulMix: Multiplier<Itype>,
    OutMix: OutputMixin<Itype, Xtype>,
    Size: ExtSize, ExtPcg<Itype, Xtype, StreamMix, MulMix, OutMix, Size> : Rng,
    PcgEngine<Itype, Xtype, StreamMix, MulMix, OutMix> : Rng + SeedableRng<Itype>

{
    fn reseed(&mut self, seed: Itype) {
        //Update the PCG
        self.pcg.reseed(seed);

        //Update the extension array
        for i in 0..Size::ext_size() {
            self.ext[i] = self.pcg.gen();
        }
    }

    fn from_seed(seed: Itype) -> Self {
        let pcg = PcgEngine::from_seed(seed);
        ExtPcg::from_pcg(pcg)
    }
}

impl<Itype, Xtype,MulMix, OutMix, Size> SeedableRng<[Itype; 2]> for ExtPcg<Itype, Xtype, SpecificSeqStream<Itype>, MulMix, OutMix, Size>
    where
    Itype: Zero,
    Xtype: PcgOps + BitSize + Rand,
    SpecificSeqStream<Itype>: Stream<Itype>,
    MulMix: Multiplier<Itype>,
    OutMix: OutputMixin<Itype, Xtype>,
    Size: ExtSize, ExtPcg<Itype, Xtype, SpecificSeqStream<Itype>, MulMix, OutMix, Size> : Rng,
    PcgEngine<Itype, Xtype, SpecificSeqStream<Itype>, MulMix, OutMix> : Rng + SeedableRng<[Itype; 2]>

{
    fn reseed(&mut self, seed: [Itype; 2]) {
        //Update the PCG
        self.pcg.reseed(seed);

        //Update the extension array
        for i in 0..Size::ext_size() {
            self.ext[i] = self.pcg.gen();
        }
    }

    fn from_seed(seed: [Itype; 2]) -> Self {
        let pcg = PcgEngine::from_seed(seed);
        ExtPcg::from_pcg(pcg)
    }
}

impl<Xtype, StreamMix, MulMix, OutMix, Size> SeedableRng<[u64; 2]> for ExtPcg<u128, Xtype, StreamMix, MulMix, OutMix, Size>
    where
    u128: PcgOps + BitSize + Clone + AsSmaller<Xtype>,
    Xtype: PcgOps + BitSize + Rand,
    StreamMix: Stream<u128>,
    MulMix: Multiplier<u128>,
    OutMix: OutputMixin<u128, Xtype>,
    Size: ExtSize, ExtPcg<u128, Xtype, StreamMix, MulMix, OutMix, Size> : Rng,
    PcgEngine<u128, Xtype, StreamMix, MulMix, OutMix> : Rng + SeedableRng<[u64; 2]>

{
    fn reseed(&mut self, seed: [u64; 2]) {
        //Update the PCG
        self.pcg.reseed(seed);

        //Update the extension array
        for i in 0..Size::ext_size() {
            self.ext[i] = self.pcg.gen();
        }
    }

    fn from_seed(seed: [u64; 2]) -> Self {
        let pcg = PcgEngine::from_seed(seed);
        ExtPcg::from_pcg(pcg)
    }
}

impl<Xtype,MulMix, OutMix, Size> SeedableRng<[u64; 4]> for ExtPcg<u128, Xtype, SpecificSeqStream<u128>, MulMix, OutMix, Size>
    where
    u128: AsSmaller<Xtype>,
    Xtype: PcgOps + BitSize + Rand,
    SpecificSeqStream<u128>: Stream<u128>,
    MulMix: Multiplier<u128>,
    OutMix: OutputMixin<u128, Xtype>,
    Size: ExtSize, ExtPcg<u128, Xtype, SpecificSeqStream<u128>, MulMix, OutMix, Size> : Rng,
    PcgEngine<u128, Xtype, SpecificSeqStream<u128>, MulMix, OutMix> : Rng + SeedableRng<[u64; 4]>

{
    fn reseed(&mut self, seed: [u64; 4]) {
        //Update the PCG
        self.pcg.reseed(seed);

        //Update the extension array
        for i in 0..Size::ext_size() {
            self.ext[i] = self.pcg.gen();
        }
    }

    fn from_seed(seed: [u64; 4]) -> Self {
        let pcg = PcgEngine::from_seed(seed);
        ExtPcg::from_pcg(pcg)
    }
}
<commit_msg>Relaxed constraints<commit_after>/*
 * PCG Random Number Generation for Rust
 *
 * Copyright 2015 John Brooks <robojeb@robojeb.xyz>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

/// Extended PCG generators utilize a simple method to dramatically extend the
/// period of the genrators. In addition to extending the period of the
/// generator it ensures that the generators have K-dimensional
/// equidistribution. This means that the generator will produce every possible
/// K-tuple uniformly.
///
/// These generators require `K*sizeof(Isize)` extra bytes to provide their
/// equidistribution.
///
/// These extended generators are currently in a beta state. They are
/// implemented according to my understanding of the generator extension
/// technique presented in the PCG paper.
/// You can use these generators if you want, and if you would like to help
/// me review the code and determine if my implementation is correct that would
/// be wonderful.
pub mod extsizes;

pub use self::extsizes::*;

use extprim::u128::u128;
use rand::{Rng, Rand, SeedableRng};
use std::marker::PhantomData;
use super::PcgEngine;
use super::numops::*;
use super::stream::*;
use super::outputmix::*;
use super::multiplier::*;
use num_traits::Zero;

/// An extended PCG generator. These generators provide K-dimensional
/// equidistribution. Where K is specified by the value of the Size parameter
/// which must be an ExtSize type.
pub struct ExtPcg<Itype, Xtype,
    StreamMix: Stream<Itype>,
    MulMix: Multiplier<Itype>,
    OutMix: OutputMixin<Itype, Xtype>,
    Size: ExtSize>
{
    pcg : PcgEngine<Itype, Xtype, StreamMix, MulMix, OutMix>,
    ext : Vec<Xtype>,
    _size : PhantomData<Size>,
}

impl<Itype, Xtype, StreamMix, MulMix, OutMix, Size>
    ExtPcg<Itype, Xtype, StreamMix, MulMix, OutMix, Size>
    where
    Itype: Zero,
    Xtype: PcgOps + BitSize + Rand,
    StreamMix: Stream<Itype>,
    MulMix: Multiplier<Itype>,
    OutMix: OutputMixin<Itype, Xtype>,
    Size: ExtSize,
    PcgEngine<Itype, Xtype, StreamMix, MulMix, OutMix>: Rng
{

    /// Create a new ExtPcg from an existing PCG. This will consume
    /// Size random values to initialize the extension array.
    pub fn from_pcg(pcg: PcgEngine<Itype, Xtype, StreamMix, MulMix, OutMix>) ->
        ExtPcg<Itype, Xtype, StreamMix, MulMix, OutMix, Size> {
            let mut pcg = pcg;

            //Create the starting extension array
            let mut ext = Vec::new();
            for _ in 0..Size::ext_size() {
                ext.push(pcg.gen());
            }

            ExtPcg {
                pcg : pcg,
                ext : ext,
                _size : PhantomData::<Size>,
            }
    }

    /// Create a new unseeded ExtPcg.
    pub fn new_unseeded() -> ExtPcg<Itype, Xtype, StreamMix, MulMix, OutMix, Size>
    {
        let pcg = PcgEngine::<Itype, Xtype, StreamMix, MulMix, OutMix>::new_unseeded();
        Self::from_pcg(pcg)
    }
}

impl<Itype, StreamMix, MulMix, OutMix, Size> Rng for
    ExtPcg<Itype, u32, StreamMix, MulMix, OutMix, Size>
    where Itype: PcgOps + AsUsize + BitSize + AsSmaller<u32> + Clone,
    StreamMix: Stream<Itype>,
    MulMix: Multiplier<Itype>,
    OutMix: OutputMixin<Itype, u32>,
    Size: ExtSize {

    #[inline]
    fn next_u32(&mut self) -> u32 {
        let oldstate = self.pcg.state.clone();
        self.pcg.state = self.pcg.stream_mix.increment().wrap_add(oldstate.wrap_mul(MulMix::multiplier()));

        let mask = 2usize.pow(Size::ext_bits() as u32)-1;
        let pick = self.pcg.state.as_usize() & mask;

        let ext_val = self.ext[pick];
        self.ext[pick] = self.ext[pick] + 1;
        OutMix::output(oldstate) ^ ext_val
    }
}

impl<Itype, StreamMix, MulMix, OutMix, Size> Rng for
    ExtPcg<Itype, u64, StreamMix, MulMix, OutMix, Size>
    where Itype: PcgOps + AsUsize + BitSize + AsSmaller<u64> + Clone,
    StreamMix: Stream<Itype>,
    MulMix: Multiplier<Itype>,
    OutMix: OutputMixin<Itype, u64>,
    Size: ExtSize {

    #[inline]
    fn next_u32(&mut self) -> u32 {
        self.next_u64() as u32
    }

    #[inline]
    fn next_u64(&mut self) -> u64 {
        let oldstate = self.pcg.state.clone();
        self.pcg.state = self.pcg.stream_mix.increment().wrap_add(oldstate.wrap_mul(MulMix::multiplier()));

        let mask = 2usize.pow(Size::ext_bits() as u32)-1;
        let pick = self.pcg.state.as_usize() & mask;

        let ext_val = self.ext[pick];
        self.ext[pick] = self.ext[pick] + 1;
        OutMix::output(oldstate) ^ ext_val
    }
}

pub type SetseqXshRr6432ext<Size> = ExtPcg<u64, u32, SpecificSeqStream<u64>, DefaultMultiplier, XshRrMixin, Size>;
pub type SetseqXshRr12832ext<Size> = ExtPcg<u128, u32, SpecificSeqStream<u128>, DefaultMultiplier, XshRrMixin, Size>;
pub type SetseqXshRr12864ext<Size> = ExtPcg<u128, u64, SpecificSeqStream<u128>, DefaultMultiplier, XshRrMixin, Size>;

/// The extended version of the Pcg32 generator
pub type Pcg32Ext<Size> = SetseqXshRr6432ext<Size>;
/// The extended version of the Pcg32L generator
pub type Pcg32LExt<Size> = SetseqXshRr12832ext<Size>;
/// The extended version of the Pcg64 generator
pub type Pcg64Ext<Size> = SetseqXshRr12864ext<Size>;

//
// Seeding for the ExtPcgs
//

//These generics get pretty insane
impl<Itype, Xtype, StreamMix, MulMix, OutMix, Size> SeedableRng<Itype> for ExtPcg<Itype, Xtype, StreamMix, MulMix, OutMix, Size>
    where
    Itype: Zero,
    Xtype: PcgOps + BitSize + Rand,
    StreamMix: Stream<Itype>,
    MulMix: Multiplier<Itype>,
    OutMix: OutputMixin<Itype, Xtype>,
    Size: ExtSize, ExtPcg<Itype, Xtype, StreamMix, MulMix, OutMix, Size> : Rng,
    PcgEngine<Itype, Xtype, StreamMix, MulMix, OutMix> : Rng + SeedableRng<Itype>

{
    fn reseed(&mut self, seed: Itype) {
        //Update the PCG
        self.pcg.reseed(seed);

        //Update the extension array
        for i in 0..Size::ext_size() {
            self.ext[i] = self.pcg.gen();
        }
    }

    fn from_seed(seed: Itype) -> Self {
        let pcg = PcgEngine::from_seed(seed);
        ExtPcg::from_pcg(pcg)
    }
}

impl<Itype, Xtype,MulMix, OutMix, Size> SeedableRng<[Itype; 2]> for ExtPcg<Itype, Xtype, SpecificSeqStream<Itype>, MulMix, OutMix, Size>
    where
    Itype: Zero,
    Xtype: PcgOps + BitSize + Rand,
    SpecificSeqStream<Itype>: Stream<Itype>,
    MulMix: Multiplier<Itype>,
    OutMix: OutputMixin<Itype, Xtype>,
    Size: ExtSize, ExtPcg<Itype, Xtype, SpecificSeqStream<Itype>, MulMix, OutMix, Size> : Rng,
    PcgEngine<Itype, Xtype, SpecificSeqStream<Itype>, MulMix, OutMix> : Rng + SeedableRng<[Itype; 2]>

{
    fn reseed(&mut self, seed: [Itype; 2]) {
        //Update the PCG
        self.pcg.reseed(seed);

        //Update the extension array
        for i in 0..Size::ext_size() {
            self.ext[i] = self.pcg.gen();
        }
    }

    fn from_seed(seed: [Itype; 2]) -> Self {
        let pcg = PcgEngine::from_seed(seed);
        ExtPcg::from_pcg(pcg)
    }
}

impl<Xtype, StreamMix, MulMix, OutMix, Size> SeedableRng<[u64; 2]> for ExtPcg<u128, Xtype, StreamMix, MulMix, OutMix, Size>
    where
    Xtype: PcgOps + BitSize + Rand,
    StreamMix: Stream<u128>,
    MulMix: Multiplier<u128>,
    OutMix: OutputMixin<u128, Xtype>,
    Size: ExtSize, ExtPcg<u128, Xtype, StreamMix, MulMix, OutMix, Size> : Rng,
    PcgEngine<u128, Xtype, StreamMix, MulMix, OutMix> : Rng + SeedableRng<[u64; 2]>

{
    fn reseed(&mut self, seed: [u64; 2]) {
        //Update the PCG
        self.pcg.reseed(seed);

        //Update the extension array
        for i in 0..Size::ext_size() {
            self.ext[i] = self.pcg.gen();
        }
    }

    fn from_seed(seed: [u64; 2]) -> Self {
        let pcg = PcgEngine::from_seed(seed);
        ExtPcg::from_pcg(pcg)
    }
}

impl<Xtype,MulMix, OutMix, Size> SeedableRng<[u64; 4]> for ExtPcg<u128, Xtype, SpecificSeqStream<u128>, MulMix, OutMix, Size>
    where
    Xtype: PcgOps + BitSize + Rand,
    SpecificSeqStream<u128>: Stream<u128>,
    MulMix: Multiplier<u128>,
    OutMix: OutputMixin<u128, Xtype>,
    Size: ExtSize, ExtPcg<u128, Xtype, SpecificSeqStream<u128>, MulMix, OutMix, Size> : Rng,
    PcgEngine<u128, Xtype, SpecificSeqStream<u128>, MulMix, OutMix> : Rng + SeedableRng<[u64; 4]>

{
    fn reseed(&mut self, seed: [u64; 4]) {
        //Update the PCG
        self.pcg.reseed(seed);

        //Update the extension array
        for i in 0..Size::ext_size() {
            self.ext[i] = self.pcg.gen();
        }
    }

    fn from_seed(seed: [u64; 4]) -> Self {
        let pcg = PcgEngine::from_seed(seed);
        ExtPcg::from_pcg(pcg)
    }
}
<|endoftext|>


<commit_before>use rustc_serialize::{Decodable, Encodable};
use std::vec::Vec;
use swarm::socket::{SwarmResult, SwarmSocket};
use swarm::SwarmMsg;
use agent::SwarmAgent;
use Location;
use std::io::net::ip::{SocketAddr, ToSocketAddr};
use bincode::DecoderReader;
use bincode::EncoderWriter;
use std::io::{BufReader};
use std::io::MemWriter;

#[derive(Clone, Eq, PartialEq, Show, RustcDecodable, RustcEncodable)]
pub enum IronSwarmRPC<Loc> {
    HRTBT(SwarmAgent<Loc>),
    HRTBTACK(Vec<SwarmAgent<Loc>>),
    JOIN(SwarmAgent<Loc>),
    INFO(Loc, SwarmMsg<Loc>),
    BROADCAST(SwarmMsg<Loc>),
}

pub struct SwarmNetwork<Loc> {
    socket: SwarmSocket,
    local_agent: SwarmAgent<Loc>,
    neighbors: Vec<SwarmAgent<Loc>>
}

impl<Loc> SwarmNetwork<Loc> {
    fn new<A: ToSocketAddr>(loc: Loc, address: A) -> SwarmNetwork<Loc> {
        let mut socket = SwarmSocket::new(address);
        let addr = socket.socket_name();
        let agent = SwarmAgent::new(loc, addr);

        SwarmNetwork {
            socket: socket,
            local_agent: agent,
            neighbors: Vec::new()
        }
    }

    fn address(&mut self) -> SocketAddr {
        self.socket.socket_name()
    }

    fn update_location(&mut self, location: Loc) {
        self.local_agent.update_location(location);
    }
}

// Send RPC's.
impl<Loc: Encodable + Clone> SwarmNetwork<Loc> {
    fn send_heartbeat<A: ToSocketAddr>(&mut self, hrtbt: SwarmAgent<Loc>, dest: A) -> SwarmResult<()> {
        let rpc = IronSwarmRPC::HRTBT(hrtbt);
        self.socket.send_packet(rpc, dest)
    }

    fn send_heartbeat_ack<A: ToSocketAddr>(&mut self, neighbors: Vec<SwarmAgent<Loc>>,
                                         dest: A) -> SwarmResult<()> {
        let rpc = IronSwarmRPC::HRTBTACK(neighbors);
        self.socket.send_packet(rpc, dest)
    }

    fn send_info<A: ToSocketAddr>(&mut self, loc: Loc, msg: SwarmMsg<Loc>, dest: A) -> SwarmResult<()> {
        let rpc = IronSwarmRPC::INFO(loc, msg);
        self.socket.send_packet(rpc, dest)
    }

    fn send_broadcast<A: ToSocketAddr>(&mut self, msg: SwarmMsg<Loc>, dest: A) -> SwarmResult<()> {
        let rpc = IronSwarmRPC::BROADCAST(msg);
        self.socket.send_packet(rpc, dest)
    }

    fn send_join<A: ToSocketAddr>(&mut self, agn: SwarmAgent<Loc>, dest: A) -> SwarmResult<()> {
        let rpc = IronSwarmRPC::JOIN(agn);
        self.socket.send_packet(rpc, dest)
    }

    fn join<A: ToSocketAddr>(&mut self, address: A) {
        let agn = self.local_agent.clone();
        self.send_join(agn, address);
    }
}

// React to received RPC's.
impl<Loc: Location + Encodable + Decodable + Clone> SwarmNetwork<Loc> {
    fn next_msg(&mut self) -> SwarmResult<IronSwarmRPC<Loc>> {
        self.socket.recv_msg()
    }

    fn dispatch_rpc(&mut self) {
        let res = self.next_msg();
        let rpc = match res {
            Ok(r) => r,
            Err(e) => panic!("Could not get next_msg: {:?}", e)
        };

        match rpc {
            IronSwarmRPC::HRTBT(agn) => {}
            IronSwarmRPC::HRTBTACK(ack_vec) => {}
            IronSwarmRPC::JOIN(join_agn) => {
                self.route_join_request(join_agn)
            }
            IronSwarmRPC::INFO(loc, msg) => {}
            IronSwarmRPC::BROADCAST(msg) => {}
        }
    }

    fn find_closer_agent(&self, loc: &Loc) -> Option<SwarmAgent<Loc>> {
        self.neighbors.
            iter().
            filter(|&a| a.location().distance(loc) <
                   self.local_agent.location().distance(loc)).
            cloned().
            min_by(|a| a.location().distance(loc))
    }

    fn route_join_request(&mut self, join_agn: SwarmAgent<Loc>) {
        let closest_agent = self.find_closer_agent(join_agn.location());

        match closest_agent {
            // Send JOIN request to closest known agent.
            Some(send_agn) => {
                self.send_join(join_agn, send_agn.address());
            }
            // TODO: Already have too many neighbors
            None => {
                self.neighbors.push(join_agn);
            }
        }
    }
}

#[cfg(test)]
mod test {
    extern crate bincode;
    use std::io::net::ip::{SocketAddr, Ipv4Addr};
    use std::io::test::next_test_port;
    use agent::{SwarmAgent};
    use artifact::SwarmArtifact;
    use swarm::socket::SwarmResult;
    use swarm::SwarmMsg;
    use Location;
    use swarm::network::IronSwarmRPC;
    use super::SwarmNetwork;
    use bincode::{decode, encode};

    fn construct_artifact() -> SwarmArtifact<isize> {
        let loc = 9is;

        SwarmArtifact::new(loc)
    }

    fn construct_agent() -> SwarmAgent<isize> {
        SwarmAgent::new(9, local_socket())
    }

    fn construct_swarm_msg() -> SwarmMsg<isize> {
        SwarmMsg::new_artifact_msg(construct_agent(), construct_artifact())
    }

    fn local_socket() -> SocketAddr {
        SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: next_test_port() }
    }

    fn bincode_rpc_tester(rpc: IronSwarmRPC<isize>) {
        let orig_rpc = rpc.clone();
        let limit = bincode::SizeLimit::Infinite;
        let encoded = bincode::encode(&rpc, limit).ok().unwrap();
        let dec_rpc: IronSwarmRPC<isize> =
            bincode::decode(encoded.as_slice()).ok().unwrap();
        assert_eq!(orig_rpc, dec_rpc);
    }

    fn send_broadcast_tester(from_nework: &mut SwarmNetwork<isize>,
                           to_network: &mut SwarmNetwork<isize>) -> SwarmResult<()> {
        let msg = construct_swarm_msg();
        let exp_rpc = IronSwarmRPC::BROADCAST(msg.clone());

        try!(from_nework.send_broadcast(msg, to_network.address()));
        let recv_rpc = try!(to_network.next_msg());

        assert_eq!(exp_rpc, recv_rpc);
        Ok(())
    }

    fn next_msg_rpc_tester(from_network: &mut SwarmNetwork<isize>,
                           to_network: &mut SwarmNetwork<isize>,
                           rpc: IronSwarmRPC<isize>) -> SwarmResult<()> {
        let orig_rpc = rpc.clone();
        let net_sock = to_network.address();
        try!(from_network.socket.send_packet(rpc, net_sock));

        let dec_rpc = try!(to_network.next_msg());
        assert_eq!(orig_rpc, dec_rpc);
        Ok(())
    }

    #[test]
    fn next_msg_test() {
        let mut ack_vec = Vec::new();
        ack_vec.push(construct_agent());
        let mut from_network = SwarmNetwork::new(0is, local_socket());
        let mut to_network = SwarmNetwork::new(1is, local_socket());

        let res = next_msg_rpc_tester(&mut from_network, &mut to_network,
                                      IronSwarmRPC::HRTBT(construct_agent()));
        assert!(res.is_ok());
        let res = next_msg_rpc_tester(&mut from_network, &mut to_network,
                                      IronSwarmRPC::HRTBTACK(ack_vec));
        assert!(res.is_ok());
        let res = next_msg_rpc_tester(&mut from_network, &mut to_network,
                                      IronSwarmRPC::JOIN(construct_agent()));
        assert!(res.is_ok());
        let res = next_msg_rpc_tester(&mut from_network, &mut to_network,
                                      IronSwarmRPC::INFO(10, construct_swarm_msg()));
        assert!(res.is_ok());
        let res = next_msg_rpc_tester(&mut from_network, &mut to_network,
                                      IronSwarmRPC::BROADCAST(construct_swarm_msg()));
        assert!(res.is_ok());
    }

    #[test]
    fn bincode_test() {
        let mut ack_vec = Vec::new();
        ack_vec.push(construct_agent());

        bincode_rpc_tester(IronSwarmRPC::HRTBT(construct_agent()));
        bincode_rpc_tester(IronSwarmRPC::HRTBTACK(ack_vec));
        bincode_rpc_tester(IronSwarmRPC::JOIN(construct_agent()));
        bincode_rpc_tester(IronSwarmRPC::INFO(10, construct_swarm_msg()));
        bincode_rpc_tester(IronSwarmRPC::BROADCAST(construct_swarm_msg()));
    }

    #[test]
    fn send_rpc_test() {
        let mut network_to = SwarmNetwork::new(0is, local_socket());
        let mut network_from = SwarmNetwork::new(10is, local_socket());

        let res = send_broadcast_tester(&mut network_from, &mut network_to);
        assert!(res.is_ok());
    }

    #[test]
    fn join_self_closest_test() {
        let mut network1 = SwarmNetwork::new(0is, local_socket());
        let mut network2 = SwarmNetwork::new(10is, local_socket());
        let mut joining = SwarmNetwork::new(2is, local_socket());
        network1.neighbors.push(network2.local_agent.clone());

        joining.join(network1.address());
        network1.dispatch_rpc();

        assert_eq!(network1.neighbors.len(), 2);
    }

    #[test]
    fn join_other_closest_test() {
        let mut network1 = SwarmNetwork::new(0is, local_socket());
        let mut network2 = SwarmNetwork::new(10is, local_socket());
        let mut joining = SwarmNetwork::new(9is, local_socket());
        network1.neighbors.push(network2.local_agent.clone());

        joining.join(network1.address());
        network1.dispatch_rpc();
        network2.dispatch_rpc();

        assert_eq!(network1.neighbors.len(), 1);
        assert_eq!(network2.neighbors.len(), 1);
    }
}
<commit_msg>Implement HRTBT and HRTBTACK RPC's.<commit_after>use rustc_serialize::{Decodable, Encodable};
use std::vec::Vec;
use swarm::socket::{SwarmResult, SwarmSocket};
use swarm::SwarmMsg;
use agent::{SwarmAddr, SwarmAgent};
use Location;
use std::io::net::ip::{SocketAddr, ToSocketAddr};
use bincode::DecoderReader;
use bincode::EncoderWriter;
use std::io::{BufReader};
use std::io::MemWriter;
use std::fmt::Show;

#[derive(Clone, Eq, PartialEq, Show, RustcDecodable, RustcEncodable)]
pub enum IronSwarmRPC<Loc> {
    HRTBT(SwarmAgent<Loc>),
    HRTBTACK(Vec<SwarmAgent<Loc>>),
    JOIN(SwarmAgent<Loc>),
    INFO(Loc, SwarmMsg<Loc>),
    BROADCAST(SwarmMsg<Loc>),
}

pub struct SwarmNetwork<Loc> {
    socket: SwarmSocket,
    local_agent: SwarmAgent<Loc>,
    neighbors: Vec<SwarmAgent<Loc>>
}

impl<Loc> SwarmNetwork<Loc> {
    fn new<A: ToSocketAddr>(loc: Loc, address: A) -> SwarmNetwork<Loc> {
        let mut socket = SwarmSocket::new(address);
        let addr = socket.socket_name();
        let agent = SwarmAgent::new(loc, addr);

        SwarmNetwork {
            socket: socket,
            local_agent: agent,
            neighbors: Vec::new()
        }
    }

    fn address(&mut self) -> SocketAddr {
        self.socket.socket_name()
    }

    fn update_location(&mut self, location: Loc) {
        self.local_agent.update_location(location);
    }
}

// Send RPC's.
impl<Loc: Encodable + Clone> SwarmNetwork<Loc> {
    fn send_heartbeat<A: ToSocketAddr>(&mut self,
                                       hrtbt: SwarmAgent<Loc>,
                                       dest: A) -> SwarmResult<()> {
        let rpc = IronSwarmRPC::HRTBT(hrtbt);
        self.socket.send_packet(rpc, dest)
    }

    fn send_heartbeat_ack<A: ToSocketAddr>(&mut self,
                                           neighbors: Vec<SwarmAgent<Loc>>,
                                           dest: A) -> SwarmResult<()> {
        let rpc = IronSwarmRPC::HRTBTACK(neighbors);
        self.socket.send_packet(rpc, dest)
    }

    fn send_info<A: ToSocketAddr>(&mut self,
                                  loc: Loc,
                                  msg: SwarmMsg<Loc>,
                                  dest: A) -> SwarmResult<()> {
        let rpc = IronSwarmRPC::INFO(loc, msg);
        self.socket.send_packet(rpc, dest)
    }

    fn send_broadcast<A: ToSocketAddr>(&mut self,
                                       msg: SwarmMsg<Loc>,
                                       dest: A) -> SwarmResult<()> {
        let rpc = IronSwarmRPC::BROADCAST(msg);
        self.socket.send_packet(rpc, dest)
    }

    fn send_join<A: ToSocketAddr>(&mut self,
                                  agn: SwarmAgent<Loc>,
                                  dest: A) -> SwarmResult<()> {
        let rpc = IronSwarmRPC::JOIN(agn);
        self.socket.send_packet(rpc, dest)
    }

    fn join<A: ToSocketAddr>(&mut self, address: A) {
        let agn = self.local_agent.clone();
        self.send_join(agn, address);
    }

    fn heartbeat(&mut self) -> SwarmResult<()> {
        let addresses: Vec<SwarmAddr> = self.neighbors.iter().
            map(|n| n.address().clone()).collect();

        let agn = self.local_agent.clone();
        for dest in addresses.iter() {
            try!(self.send_heartbeat(agn.clone(), dest));
        }
        Ok(())
    }
}

// React to received RPC's.
impl<Loc: Show + Location + Encodable + Decodable + PartialEq + Clone> SwarmNetwork<Loc> {
    fn next_msg(&mut self) -> SwarmResult<IronSwarmRPC<Loc>> {
        self.socket.recv_msg()
    }

    fn dispatch_rpc(&mut self) {
        let res = self.next_msg();
        let rpc = match res {
            Ok(r) => r,
            Err(e) => panic!("Could not get next_msg: {:?}", e)
        };

        match rpc {
            IronSwarmRPC::HRTBT(agn) => {
                self.respond_to_heartbeat(agn);
            }
            IronSwarmRPC::HRTBTACK(ack_vec) => {
                let new_neighbors: Vec<SwarmAgent<Loc>> = {
                    let niter = self.neighbors.iter();
                    ack_vec.
                        into_iter().
                        filter(|n| {
                            *n != self.local_agent || niter.all(|old| *old != *n)
                        }).collect()
                };
                self.neighbors.push_all(new_neighbors.as_slice());
            }
            IronSwarmRPC::JOIN(join_agn) => {
                self.route_join_request(join_agn)
            }
            IronSwarmRPC::INFO(loc, msg) => {}
            IronSwarmRPC::BROADCAST(msg) => {}
        }
    }

    fn find_closer_agent(&self, loc: &Loc) -> Option<SwarmAgent<Loc>> {
        self.neighbors.
            iter().
            filter(|&a| a.location().distance(loc) <
                   self.local_agent.location().distance(loc)).
            cloned().
            min_by(|a| a.location().distance(loc))
    }

    fn respond_to_heartbeat(&mut self, agn: SwarmAgent<Loc>) {
        {
            let dest = agn.address();
            let neighbors = self.neighbors.clone();

            self.send_heartbeat_ack(neighbors, dest);
        }

        if self.neighbors.iter().all(|n| *n != agn) {
            self.neighbors.push(agn);
        }
    }

    fn route_join_request(&mut self, join_agn: SwarmAgent<Loc>) {
        let closest_agent = self.find_closer_agent(join_agn.location());

        match closest_agent {
            Some(send_agn) => {
                self.send_join(join_agn, send_agn.address());
            }
            // TODO: Already have too many neighbors
            None => {
                self.neighbors.push(join_agn);
            }
        }
    }
}

#[cfg(test)]
mod test {
    extern crate bincode;
    use std::io::net::ip::{SocketAddr, Ipv4Addr};
    use std::io::test::next_test_port;
    use agent::{SwarmAgent};
    use artifact::SwarmArtifact;
    use swarm::socket::SwarmResult;
    use swarm::SwarmMsg;
    use Location;
    use swarm::network::IronSwarmRPC;
    use super::SwarmNetwork;
    use bincode::{decode, encode};

    fn construct_artifact() -> SwarmArtifact<isize> {
        let loc = 9is;

        SwarmArtifact::new(loc)
    }

    fn construct_agent() -> SwarmAgent<isize> {
        SwarmAgent::new(9, local_socket())
    }

    fn construct_swarm_msg() -> SwarmMsg<isize> {
        SwarmMsg::new_artifact_msg(construct_agent(), construct_artifact())
    }

    fn local_socket() -> SocketAddr {
        SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: next_test_port() }
    }

    fn bincode_rpc_tester(rpc: IronSwarmRPC<isize>) {
        let orig_rpc = rpc.clone();
        let limit = bincode::SizeLimit::Infinite;
        let encoded = bincode::encode(&rpc, limit).ok().unwrap();
        let dec_rpc: IronSwarmRPC<isize> =
            bincode::decode(encoded.as_slice()).ok().unwrap();
        assert_eq!(orig_rpc, dec_rpc);
    }

    fn send_broadcast_tester(from_nework: &mut SwarmNetwork<isize>,
                           to_network: &mut SwarmNetwork<isize>) -> SwarmResult<()> {
        let msg = construct_swarm_msg();
        let exp_rpc = IronSwarmRPC::BROADCAST(msg.clone());

        try!(from_nework.send_broadcast(msg, to_network.address()));
        let recv_rpc = try!(to_network.next_msg());

        assert_eq!(exp_rpc, recv_rpc);
        Ok(())
    }

    fn next_msg_rpc_tester(from_network: &mut SwarmNetwork<isize>,
                           to_network: &mut SwarmNetwork<isize>,
                           rpc: IronSwarmRPC<isize>) -> SwarmResult<()> {
        let orig_rpc = rpc.clone();
        let net_sock = to_network.address();
        try!(from_network.socket.send_packet(rpc, net_sock));

        let dec_rpc = try!(to_network.next_msg());
        assert_eq!(orig_rpc, dec_rpc);
        Ok(())
    }

    #[test]
    fn next_msg_test() {
        let mut ack_vec = Vec::new();
        ack_vec.push(construct_agent());
        let mut from_network = SwarmNetwork::new(0is, local_socket());
        let mut to_network = SwarmNetwork::new(1is, local_socket());

        let res = next_msg_rpc_tester(&mut from_network, &mut to_network,
                                      IronSwarmRPC::HRTBT(construct_agent()));
        assert!(res.is_ok());
        let res = next_msg_rpc_tester(&mut from_network, &mut to_network,
                                      IronSwarmRPC::HRTBTACK(ack_vec));
        assert!(res.is_ok());
        let res = next_msg_rpc_tester(&mut from_network, &mut to_network,
                                      IronSwarmRPC::JOIN(construct_agent()));
        assert!(res.is_ok());
        let res = next_msg_rpc_tester(&mut from_network, &mut to_network,
                                      IronSwarmRPC::INFO(10, construct_swarm_msg()));
        assert!(res.is_ok());
        let res = next_msg_rpc_tester(&mut from_network, &mut to_network,
                                      IronSwarmRPC::BROADCAST(construct_swarm_msg()));
        assert!(res.is_ok());
    }

    #[test]
    fn bincode_test() {
        let mut ack_vec = Vec::new();
        ack_vec.push(construct_agent());

        bincode_rpc_tester(IronSwarmRPC::HRTBT(construct_agent()));
        bincode_rpc_tester(IronSwarmRPC::HRTBTACK(ack_vec));
        bincode_rpc_tester(IronSwarmRPC::JOIN(construct_agent()));
        bincode_rpc_tester(IronSwarmRPC::INFO(10, construct_swarm_msg()));
        bincode_rpc_tester(IronSwarmRPC::BROADCAST(construct_swarm_msg()));
    }

    #[test]
    fn send_rpc_test() {
        let mut network_to = SwarmNetwork::new(0is, local_socket());
        let mut network_from = SwarmNetwork::new(10is, local_socket());

        let res = send_broadcast_tester(&mut network_from, &mut network_to);
        assert!(res.is_ok());
    }

    #[test]
    fn join_self_closest_test() {
        let mut network1 = SwarmNetwork::new(0is, local_socket());
        let mut network2 = SwarmNetwork::new(10is, local_socket());
        let mut joining = SwarmNetwork::new(2is, local_socket());
        network1.neighbors.push(network2.local_agent.clone());

        joining.join(network1.address());
        network1.dispatch_rpc();

        assert_eq!(network1.neighbors.len(), 2);
    }

    #[test]
    fn join_other_closest_test() {
        let mut network1 = SwarmNetwork::new(0is, local_socket());
        let mut network2 = SwarmNetwork::new(10is, local_socket());
        let mut joining = SwarmNetwork::new(9is, local_socket());
        network1.neighbors.push(network2.local_agent.clone());

        joining.join(network1.address());
        network1.dispatch_rpc();
        network2.dispatch_rpc();

        assert_eq!(network1.neighbors.len(), 1);
        assert_eq!(network2.neighbors.len(), 1);
    }

    #[test]
    fn htbt_and_ack_add_neighbor_test() {
        let mut network1 = SwarmNetwork::new(0is, local_socket());
        let mut network2 = SwarmNetwork::new(10is, local_socket());
        network1.neighbors.push(network2.local_agent.clone());

        // Neighbor of ACK'd swarm agent
        let mut network3 = SwarmNetwork::new(9is, local_socket());
        network2.neighbors.push(network3.local_agent.clone());

        // New agent that is not in neighbor list.
        let mut network4 = SwarmNetwork::new(11is, local_socket());
        network4.neighbors.push(network1.local_agent.clone());

        network1.heartbeat();
        network2.dispatch_rpc();
        network1.dispatch_rpc();

        network4.heartbeat();
        network1.dispatch_rpc();

        assert_eq!(network1.neighbors.len(), 3);
    }
}
<|endoftext|>


<commit_before>// xfail-stage0
// xfail-stage1
// xfail-pretty
// error-pattern:quux
use std;
import std::str::*;
import std::uint::*;

fn nop(a: uint, b: uint) : le(a, b) { fail "quux"; }

fn main() {
    let a: uint = 5u;
    let b: uint = 4u;
    claim (le(a, b));
    nop(a, b);
}
<commit_msg>Un-xfail run-fail/fn-constraint-claim<commit_after>// xfail-pretty
// error-pattern:quux
use std;
import std::str::*;
import std::uint::*;

fn nop(a: uint, b: uint) : le(a, b) { fail "quux"; }

fn main() {
    let a: uint = 5u;
    let b: uint = 4u;
    claim (le(a, b));
    nop(a, b);
}
<|endoftext|>


<commit_before>use nom::{Err, IResult, Needed};

use std::io;
use std::io::Read;
use std::ptr;
use std::cmp;

use super::StreamProducer;

#[derive(Debug)]
pub enum ErrorKind {
  IO(io::Error),
  Incomplete(usize),
  Consumed(usize),
  Continue,
  EndOfInput,
  Unknown,
}

/// Structure that hold a slice of bytes.
pub struct ByteStream<'a> {
  offset: usize,
  bytes: &'a [u8],
}

impl<'a> ByteStream<'a> {
  /// Construct a `ByteStream` based on the passed in byte slice.
  pub fn new(bytes: &'a [u8]) -> Self {
    ByteStream {
      offset: 0,
      bytes: bytes,
    }
  }

  /// Return the number of bytes that haven't been consumed yet.
  #[inline]
  pub fn len(&self) -> usize {
    self.bytes.len() - self.offset
  }

  /// Return true if the stream contains no more bytes.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.len() == 0
  }
}

impl<'a> StreamProducer for ByteStream<'a> {
  fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>
   where F: FnOnce(&[u8]) -> IResult<&[u8], T> {
    if self.is_empty() {
      return Err(ErrorKind::EndOfInput);
    }

    match f(&self.bytes[self.offset..]) {
      IResult::Done(i, o)    => {
        self.offset += self.len() - i.len();

        Ok(o)
      }
      IResult::Incomplete(n) => {
        let mut needed = self.len();

        if let Needed::Size(size) = n {
          needed = size;
        }

        Err(ErrorKind::Incomplete(needed))
      }
      IResult::Error(_)      => Err(ErrorKind::Unknown),
    }
  }
}

// Growable buffer of bytes.
//
// Mainly used to the `ReadStream` structure but can be used seperately for
// manually filling with some `Read` source.
pub struct Buffer {
  data: Vec<u8>,
  filled: usize,
  offset: usize,
}

impl Buffer {
  // Default constructor for `Buffer`
  pub fn new() -> Self {
    Self::with_capacity(1024)
  }

  // Explicitly set the buffer capacity.
  pub fn with_capacity(capacity: usize) -> Self {
    let mut buffer = Vec::with_capacity(capacity);

    unsafe {
      buffer.set_len(capacity);
    }

    Buffer {
      data: buffer,
      filled: 0,
      offset: 0,
    }
  }

  // Return the number of read bytes that haven't been consumed yet.
  #[inline]
  pub fn len(&self) -> usize {
    self.filled - self.offset
  }

  // Return true if buffer contains no more bytes.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.len() == 0
  }

  // The set length of the unlining buffer.
  #[inline]
  pub fn capacity(&self) -> usize {
    self.data.len()
  }

  // Return a reference to the slice of unread bytes.
  pub fn as_slice(&self) -> &[u8] {
    &self.data[self.offset..self.filled]
  }

  // Fill the buffer with bytes from a `Read` source.
  pub fn fill<R: Read>(&mut self, reader: &mut R) -> io::Result<usize> {
    reader.read(&mut self.data[self.filled..]).map(|consumed| {
      self.filled += consumed;

      consumed
    })
  }

  // Resize the current buffer
  //
  // This will only allocate data when the size requests is larger than the
  // current capacity of the buffer, otherwise it moves the currently filled
  // data to the beginning of the buffer.
  pub fn resize(&mut self, size: usize) {
    if size > self.data.capacity() {
      self.data.reserve(size);

      let capacity = self.data.capacity();

      unsafe {
        self.data.set_len(capacity);
      }
    }

    if self.data.len() - self.filled < size  {
      let length  = self.filled - self.offset;
      let mut_ptr = self.data.as_mut_ptr();

      unsafe {
        let offset_ptr  = self.data.as_ptr().offset(self.offset as isize);

        ptr::copy(offset_ptr, mut_ptr, length);
      }

      self.filled -= self.offset;
      self.offset  = 0;
    }
  }

  // Move the offset by the amount of consumed bytes.
  pub fn consume(&mut self, consumed: usize) {
    self.offset += consumed;
  }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ParserState {
  Incomplete,
  EndOfInput,
}

fn fill<R: Read>(buffer: &mut Buffer, reader: &mut R, needed: usize)
                 -> io::Result<usize> {
  let mut read = 0;

  if buffer.len() < needed {
    buffer.resize(needed);

    while buffer.len() < needed {
      let size_read = try!(buffer.fill(reader));

      if size_read > 0 {
        read += size_read;
      } else {
        break;
      }
    }
  }

  Ok(read)
}

/// Structure that hold a reader for a source of bytes.
pub struct ReadStream<R: Read> {
  reader: R,
  buffer: Buffer,
  needed: usize,
  state: ParserState,
}

impl<R> ReadStream<R> where R: Read {
  /// Constructor for `ReadStream` based on a `Read` source.
  pub fn new(reader: R) -> Self {
    ReadStream {
      reader: reader,
      buffer: Buffer::new(),
      needed: 0,
      state: ParserState::Incomplete,
    }
  }

  // Fill the stream with bytes from a `Read` source.
  fn fill(&mut self) -> io::Result<usize> {
    let needed = cmp::max(1, self.needed);

    fill(&mut self.buffer, &mut self.reader, needed).map(|consumed| {
      if self.buffer.len() < needed {
        self.state = ParserState::EndOfInput;
      }

      consumed
    })
  }
}

fn from_iresult<T>(buffer: &Buffer, result: IResult<&[u8], T>)
                   -> Result<(usize, T), ErrorKind> {
  match result {
    IResult::Done(i, o)    => Ok((buffer.len() - i.len(), o)),
    IResult::Incomplete(n) => {
      let mut needed = buffer.capacity();

      if let Needed::Size(size) = n {
        needed = size;
      }

      Err(ErrorKind::Incomplete(needed))
    }
    IResult::Error(_)      => Err(ErrorKind::Unknown),
  }
}

impl<R> StreamProducer for ReadStream<R> where R: Read {
  fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>
   where F: FnOnce(&[u8]) -> IResult<&[u8], T> {
    if self.state != ParserState::EndOfInput {
      try!(self.fill().map_err(ErrorKind::IO));
    }

    let mut buffer = &mut self.buffer;

    if buffer.is_empty() {
      self.state = ParserState::EndOfInput;

      return Err(ErrorKind::EndOfInput);
    }

    let result = {
      let iresult = f(buffer.as_slice());

      from_iresult(&buffer, iresult)
    };

    match result {
      Ok((consumed, o)) => {
        buffer.consume(consumed);

        Ok(o)
      }
      Err(kind)         => {
        if let ErrorKind::Incomplete(needed) = kind {
          self.needed = needed;

          Err(ErrorKind::Continue)
        } else {
          Err(kind)
        }
      }
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use utility::StreamProducer;
  use nom::be_u32;

  #[test]
  fn test_buffer() {
    let mut buffer = Buffer::new();
    let bytes      = b"Hello World";
    let mut reader = &bytes[..];

    assert!(buffer.is_empty());
    assert_eq!(buffer.capacity(), 1024);

    let bytes_read = buffer.fill(&mut reader).unwrap_or(0);
    let bytes_len  = bytes.len();

    assert_eq!(bytes_read, bytes_len);
    assert_eq!(buffer.len(), bytes_len);
    assert_eq!(buffer.as_slice(), bytes);

    buffer.resize(512);
    assert_eq!(buffer.capacity(), 1024);
  }

  #[test]
  fn test_byte_stream() {
    let bytes      = b"Hello World";
    let mut stream = ByteStream::new(bytes);

    assert_eq!(stream.len(), bytes.len());

    let result = stream.parse(be_u32).unwrap_or(0);

    assert_eq!(result, 1214606444);
    assert_eq!(stream.len(), 7);
  }

  #[test]
  fn test_read_stream() {
    let bytes      = b"Hello World";
    let mut stream = ReadStream::new(&bytes[..]);

    let result = stream.parse(be_u32).unwrap_or(0);

    assert_eq!(result, 1214606444)
  }
}
<commit_msg>Remove enum variant for `Consumed`<commit_after>use nom::{Err, IResult, Needed};

use std::io;
use std::io::Read;
use std::ptr;
use std::cmp;

use super::StreamProducer;

#[derive(Debug)]
pub enum ErrorKind {
  IO(io::Error),
  Incomplete(usize),
  Continue,
  EndOfInput,
  Unknown,
}

/// Structure that hold a slice of bytes.
pub struct ByteStream<'a> {
  offset: usize,
  bytes: &'a [u8],
}

impl<'a> ByteStream<'a> {
  /// Construct a `ByteStream` based on the passed in byte slice.
  pub fn new(bytes: &'a [u8]) -> Self {
    ByteStream {
      offset: 0,
      bytes: bytes,
    }
  }

  /// Return the number of bytes that haven't been consumed yet.
  #[inline]
  pub fn len(&self) -> usize {
    self.bytes.len() - self.offset
  }

  /// Return true if the stream contains no more bytes.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.len() == 0
  }
}

impl<'a> StreamProducer for ByteStream<'a> {
  fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>
   where F: FnOnce(&[u8]) -> IResult<&[u8], T> {
    if self.is_empty() {
      return Err(ErrorKind::EndOfInput);
    }

    match f(&self.bytes[self.offset..]) {
      IResult::Done(i, o)    => {
        self.offset += self.len() - i.len();

        Ok(o)
      }
      IResult::Incomplete(n) => {
        let mut needed = self.len();

        if let Needed::Size(size) = n {
          needed = size;
        }

        Err(ErrorKind::Incomplete(needed))
      }
      IResult::Error(_)      => Err(ErrorKind::Unknown),
    }
  }
}

// Growable buffer of bytes.
//
// Mainly used to the `ReadStream` structure but can be used seperately for
// manually filling with some `Read` source.
pub struct Buffer {
  data: Vec<u8>,
  filled: usize,
  offset: usize,
}

impl Buffer {
  // Default constructor for `Buffer`
  pub fn new() -> Self {
    Self::with_capacity(1024)
  }

  // Explicitly set the buffer capacity.
  pub fn with_capacity(capacity: usize) -> Self {
    let mut buffer = Vec::with_capacity(capacity);

    unsafe {
      buffer.set_len(capacity);
    }

    Buffer {
      data: buffer,
      filled: 0,
      offset: 0,
    }
  }

  // Return the number of read bytes that haven't been consumed yet.
  #[inline]
  pub fn len(&self) -> usize {
    self.filled - self.offset
  }

  // Return true if buffer contains no more bytes.
  #[inline]
  pub fn is_empty(&self) -> bool {
    self.len() == 0
  }

  // The set length of the unlining buffer.
  #[inline]
  pub fn capacity(&self) -> usize {
    self.data.len()
  }

  // Return a reference to the slice of unread bytes.
  pub fn as_slice(&self) -> &[u8] {
    &self.data[self.offset..self.filled]
  }

  // Fill the buffer with bytes from a `Read` source.
  pub fn fill<R: Read>(&mut self, reader: &mut R) -> io::Result<usize> {
    reader.read(&mut self.data[self.filled..]).map(|consumed| {
      self.filled += consumed;

      consumed
    })
  }

  // Resize the current buffer
  //
  // This will only allocate data when the size requests is larger than the
  // current capacity of the buffer, otherwise it moves the currently filled
  // data to the beginning of the buffer.
  pub fn resize(&mut self, size: usize) {
    if size > self.data.capacity() {
      self.data.reserve(size);

      let capacity = self.data.capacity();

      unsafe {
        self.data.set_len(capacity);
      }
    }

    if self.data.len() - self.filled < size  {
      let length  = self.filled - self.offset;
      let mut_ptr = self.data.as_mut_ptr();

      unsafe {
        let offset_ptr  = self.data.as_ptr().offset(self.offset as isize);

        ptr::copy(offset_ptr, mut_ptr, length);
      }

      self.filled -= self.offset;
      self.offset  = 0;
    }
  }

  // Move the offset by the amount of consumed bytes.
  pub fn consume(&mut self, consumed: usize) {
    self.offset += consumed;
  }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ParserState {
  Incomplete,
  EndOfInput,
}

fn fill<R: Read>(buffer: &mut Buffer, reader: &mut R, needed: usize)
                 -> io::Result<usize> {
  let mut read = 0;

  if buffer.len() < needed {
    buffer.resize(needed);

    while buffer.len() < needed {
      let size_read = try!(buffer.fill(reader));

      if size_read > 0 {
        read += size_read;
      } else {
        break;
      }
    }
  }

  Ok(read)
}

/// Structure that hold a reader for a source of bytes.
pub struct ReadStream<R: Read> {
  reader: R,
  buffer: Buffer,
  needed: usize,
  state: ParserState,
}

impl<R> ReadStream<R> where R: Read {
  /// Constructor for `ReadStream` based on a `Read` source.
  pub fn new(reader: R) -> Self {
    ReadStream {
      reader: reader,
      buffer: Buffer::new(),
      needed: 0,
      state: ParserState::Incomplete,
    }
  }

  // Fill the stream with bytes from a `Read` source.
  fn fill(&mut self) -> io::Result<usize> {
    let needed = cmp::max(1, self.needed);

    fill(&mut self.buffer, &mut self.reader, needed).map(|consumed| {
      if self.buffer.len() < needed {
        self.state = ParserState::EndOfInput;
      }

      consumed
    })
  }
}

fn from_iresult<T>(buffer: &Buffer, result: IResult<&[u8], T>)
                   -> Result<(usize, T), ErrorKind> {
  match result {
    IResult::Done(i, o)    => Ok((buffer.len() - i.len(), o)),
    IResult::Incomplete(n) => {
      let mut needed = buffer.capacity();

      if let Needed::Size(size) = n {
        needed = size;
      }

      Err(ErrorKind::Incomplete(needed))
    }
    IResult::Error(_)      => Err(ErrorKind::Unknown),
  }
}

impl<R> StreamProducer for ReadStream<R> where R: Read {
  fn parse<F, T>(&mut self, f: F) -> Result<T, ErrorKind>
   where F: FnOnce(&[u8]) -> IResult<&[u8], T> {
    if self.state != ParserState::EndOfInput {
      try!(self.fill().map_err(ErrorKind::IO));
    }

    let mut buffer = &mut self.buffer;

    if buffer.is_empty() {
      self.state = ParserState::EndOfInput;

      return Err(ErrorKind::EndOfInput);
    }

    let result = {
      let iresult = f(buffer.as_slice());

      from_iresult(&buffer, iresult)
    };

    match result {
      Ok((consumed, o)) => {
        buffer.consume(consumed);

        Ok(o)
      }
      Err(kind)         => {
        if let ErrorKind::Incomplete(needed) = kind {
          self.needed = needed;

          Err(ErrorKind::Continue)
        } else {
          Err(kind)
        }
      }
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use utility::StreamProducer;
  use nom::be_u32;

  #[test]
  fn test_buffer() {
    let mut buffer = Buffer::new();
    let bytes      = b"Hello World";
    let mut reader = &bytes[..];

    assert!(buffer.is_empty());
    assert_eq!(buffer.capacity(), 1024);

    let bytes_read = buffer.fill(&mut reader).unwrap_or(0);
    let bytes_len  = bytes.len();

    assert_eq!(bytes_read, bytes_len);
    assert_eq!(buffer.len(), bytes_len);
    assert_eq!(buffer.as_slice(), bytes);

    buffer.resize(512);
    assert_eq!(buffer.capacity(), 1024);
  }

  #[test]
  fn test_byte_stream() {
    let bytes      = b"Hello World";
    let mut stream = ByteStream::new(bytes);

    assert_eq!(stream.len(), bytes.len());

    let result = stream.parse(be_u32).unwrap_or(0);

    assert_eq!(result, 1214606444);
    assert_eq!(stream.len(), 7);
  }

  #[test]
  fn test_read_stream() {
    let bytes      = b"Hello World";
    let mut stream = ReadStream::new(&bytes[..]);

    let result = stream.parse(be_u32).unwrap_or(0);

    assert_eq!(result, 1214606444)
  }
}
<|endoftext|>


<commit_before>//! Tests for various types of file (video, image, compressed, etc).
//!
//! Currently this is dependent on the file’s name and extension, because
//! those are the only metadata that we have access to without reading the
//! file’s contents.

use fs::File;

#[derive(Debug)]
pub struct FileExtensions;

impl FileExtensions {

    /// An “immediate” file is something that can be run or activated somehow
    /// in order to kick off the build of a project. It’s usually only present
    /// in directories full of source code.
    pub fn is_immediate(&self, file: &File) -> bool {
        file.name.starts_with("README") || file.name_is_one_of( &[
            "Makefile", "Cargo.toml", "SConstruct", "CMakeLists.txt",
            "build.gradle", "Rakefile", "Gruntfile.js",
            "Gruntfile.coffee",
        ])
    }

    pub fn is_image(&self, file: &File) -> bool {
        file.extension_is_one_of( &[
            "png", "jpeg", "jpg", "gif", "bmp", "tiff", "tif",
            "ppm", "pgm", "pbm", "pnm", "webp", "raw", "arw",
            "svg", "stl", "eps", "dvi", "ps", "cbr",
            "cbz", "xpm", "ico", "cr2",
        ])
    }

    pub fn is_video(&self, file: &File) -> bool {
        file.extension_is_one_of( &[
            "avi", "flv", "m2v", "mkv", "mov", "mp4", "mpeg",
            "mpg", "ogm", "ogv", "vob", "wmv", "webm", "m2ts",
            "ts",
        ])
    }

    pub fn is_music(&self, file: &File) -> bool {
        file.extension_is_one_of( &[
            "aac", "m4a", "mp3", "ogg", "wma", "mka", "opus",
        ])
    }

    // Lossless music, rather than any other kind of data...
    pub fn is_lossless(&self, file: &File) -> bool {
        file.extension_is_one_of( &[
            "alac", "ape", "flac", "wav",
        ])
    }

    pub fn is_crypto(&self, file: &File) -> bool {
        file.extension_is_one_of( &[
            "asc", "enc", "gpg", "pgp", "sig", "signature", "pfx", "p12",
        ])
    }

    pub fn is_document(&self, file: &File) -> bool {
        file.extension_is_one_of( &[
            "djvu", "doc", "docx", "dvi", "eml", "eps", "fotd",
            "odp", "odt", "pdf", "ppt", "pptx", "rtf",
            "xls", "xlsx",
        ])
    }

    pub fn is_compressed(&self, file: &File) -> bool {
        file.extension_is_one_of( &[
            "zip", "tar", "Z", "gz", "bz2", "a", "ar", "7z",
            "iso", "dmg", "tc", "rar", "par", "tgz",
        ])
    }

    pub fn is_temp(&self, file: &File) -> bool {
        file.name.ends_with('~')
            || (file.name.starts_with('#') && file.name.ends_with('#'))
            || file.extension_is_one_of( &[ "tmp", "swp", "swo", "swn", "bak" ])
    }

    pub fn is_compiled(&self, file: &File) -> bool {
        if file.extension_is_one_of( &[ "class", "elc", "hi", "o", "pyc" ]) {
            true
        }
        else if let Some(dir) = file.parent_dir {
            file.get_source_files().iter().any(|path| dir.contains(path))
        }
        else {
            false
        }
    }
}
<commit_msg>Add raw file type for Olympus and Nikon<commit_after>//! Tests for various types of file (video, image, compressed, etc).
//!
//! Currently this is dependent on the file’s name and extension, because
//! those are the only metadata that we have access to without reading the
//! file’s contents.

use fs::File;

#[derive(Debug)]
pub struct FileExtensions;

impl FileExtensions {

    /// An “immediate” file is something that can be run or activated somehow
    /// in order to kick off the build of a project. It’s usually only present
    /// in directories full of source code.
    pub fn is_immediate(&self, file: &File) -> bool {
        file.name.starts_with("README") || file.name_is_one_of( &[
            "Makefile", "Cargo.toml", "SConstruct", "CMakeLists.txt",
            "build.gradle", "Rakefile", "Gruntfile.js",
            "Gruntfile.coffee",
        ])
    }

    pub fn is_image(&self, file: &File) -> bool {
        file.extension_is_one_of( &[
            "png", "jpeg", "jpg", "gif", "bmp", "tiff", "tif",
            "ppm", "pgm", "pbm", "pnm", "webp", "raw", "arw",
            "svg", "stl", "eps", "dvi", "ps", "cbr",
            "cbz", "xpm", "ico", "cr2", "orf", "nef",
        ])
    }

    pub fn is_video(&self, file: &File) -> bool {
        file.extension_is_one_of( &[
            "avi", "flv", "m2v", "mkv", "mov", "mp4", "mpeg",
            "mpg", "ogm", "ogv", "vob", "wmv", "webm", "m2ts",
            "ts",
        ])
    }

    pub fn is_music(&self, file: &File) -> bool {
        file.extension_is_one_of( &[
            "aac", "m4a", "mp3", "ogg", "wma", "mka", "opus",
        ])
    }

    // Lossless music, rather than any other kind of data...
    pub fn is_lossless(&self, file: &File) -> bool {
        file.extension_is_one_of( &[
            "alac", "ape", "flac", "wav",
        ])
    }

    pub fn is_crypto(&self, file: &File) -> bool {
        file.extension_is_one_of( &[
            "asc", "enc", "gpg", "pgp", "sig", "signature", "pfx", "p12",
        ])
    }

    pub fn is_document(&self, file: &File) -> bool {
        file.extension_is_one_of( &[
            "djvu", "doc", "docx", "dvi", "eml", "eps", "fotd",
            "odp", "odt", "pdf", "ppt", "pptx", "rtf",
            "xls", "xlsx",
        ])
    }

    pub fn is_compressed(&self, file: &File) -> bool {
        file.extension_is_one_of( &[
            "zip", "tar", "Z", "gz", "bz2", "a", "ar", "7z",
            "iso", "dmg", "tc", "rar", "par", "tgz",
        ])
    }

    pub fn is_temp(&self, file: &File) -> bool {
        file.name.ends_with('~')
            || (file.name.starts_with('#') && file.name.ends_with('#'))
            || file.extension_is_one_of( &[ "tmp", "swp", "swo", "swn", "bak" ])
    }

    pub fn is_compiled(&self, file: &File) -> bool {
        if file.extension_is_one_of( &[ "class", "elc", "hi", "o", "pyc" ]) {
            true
        }
        else if let Some(dir) = file.parent_dir {
            file.get_source_files().iter().any(|path| dir.contains(path))
        }
        else {
            false
        }
    }
}
<|endoftext|>


<commit_before>// As the name implies, unsigned integers (u8, u16, u32, u64) cannot be negative
#[test]
fn unsigned_ints() {
  assert!(u8::min_value() == __);
}

// Unsigned integers can be reduced only as far as their minimum value of 0
#[test]
fn sub_unsigned_int() {
  let mut num:u8 = 10;
  num -= 10;
  assert!(num __ u8::min_value());
}

// Signed integers(i8, i16, i32, i64), on the other hand, can be negative
#[test]
fn signed_ints() {
  assert!(i8::min_value() __ 0);
}

// Signed integers can be reduced below zero, as far as their minimum value.
// hint: The maximum magnitude for a negative integer is greater than
// that of a positive integer
#[test]
fn sub_signed_int() {
  let mut num:i8 = 0;
  let negative:i8 = __;
  num += negative;
  assert!(num == i8::min_value());
}

// Addition of positive integers works much the same for signed and unsigned numbers
#[test]
fn add_numbers() {
  let mut sig:i8 = 0;
  let mut unsig:u8 = 0;
  sig += __;
  unsig += __;
  assert!(sig == i8::max_value() && unsig == u8::max_value());
}
<commit_msg>Add immutability koans to integer.rs<commit_after>// As the name implies, unsigned integers (u8, u16, u32, u64) cannot be negative
#[test]
fn unsigned_ints() {
  assert!(u8::min_value() == __);
}

// Unsigned integers can be reduced only as far as their minimum value of 0
#[test]
fn sub_unsigned_int() {
  let mut num:u8 = 10;
  num -= 10;
  assert!(num __ u8::min_value());
}

// Signed integers(i8, i16, i32, i64), on the other hand, can be negative
#[test]
fn signed_ints() {
  assert!(i8::min_value() __ 0);
}

// Signed integers can be reduced below zero, as far as their minimum value.
// hint: The maximum magnitude for a negative integer is greater than
// that of a positive integer
#[test]
fn sub_signed_int() {
  let mut num:i8 = 0;
  let negative:i8 = __;
  num += negative;
  assert!(num == i8::min_value());
}

// Addition of positive integers works much the same for signed and unsigned numbers
#[test]
fn add_numbers() {
  let mut sig:i8 = 0;
  let mut unsig:u8 = 0;
  sig += __;
  unsig += __;
  assert!(sig == i8::max_value() && unsig == u8::max_value());
}

// Like any variable in Rust, integers are immutable unless declared otherwise
#[test]
fn mutating_ints() {
  let num:i8 = 1;
  num += 2;
  assert!(num == 3);
}

// While regular immutable variables cannot be changed, mutable versions of them can be
#[test]
fn referencing_values() {
  let num:i8 = 1;
  __ = num;
  mut_num += 1;
  assert!(num != mut_num);
}
<|endoftext|>


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

use crate::StorageRead;
use crypto::{hash::CryptoHash, HashValue};
use failure::prelude::*;
use scratchpad::{AccountState, SparseMerkleTree};
use state_view::StateView;
use std::{
    cell::RefCell,
    collections::{hash_map::Entry, BTreeMap, HashMap},
    convert::TryInto,
    sync::Arc,
};
use types::{
    access_path::AccessPath,
    account_address::AccountAddress,
    proof::{verify_sparse_merkle_element, SparseMerkleProof},
    transaction::Version,
};

/// `VerifiedStateView` is like a snapshot of the global state comprised of state view at two
/// levels, persistent storage and memory.
pub struct VerifiedStateView<'a> {
    /// A gateway implementing persistent storage interface, which can be a RPC client or direct
    /// accessor.
    reader: Arc<dyn StorageRead>,

    /// The most recent version in persistent storage.
    latest_persistent_version: Option<Version>,

    /// The most recent state root hash in persistent storage.
    latest_persistent_state_root: HashValue,

    /// The in-momery version of sparse Merkle tree of which the states haven't been committed.
    speculative_state: &'a SparseMerkleTree,

    /// The cache of verified account states from `reader` and `speculative_state_view`,
    /// represented by a hashmap with an account address as key and a pair of an ordered
    /// account state map and an an optional account state proof as value. When the VM queries an
    /// `access_path`, this cache will first check whether `reader_cache` is hit. If hit, it
    /// will return the corresponding value of that `access_path`; otherwise, the account state
    /// will be loaded into the cache from scratchpad or persistent storage in order as a
    /// deserialized ordered map and then be returned. If the VM queries this account again,
    /// the cached data can be read directly without bothering storage layer. The proofs in
    /// cache are needed by ScratchPad after VM execution to construct an in-memory sparse Merkle
    /// tree.
    /// ```text
    ///                      +----------------------------+
    ///                      | In-memory SparseMerkleTree <------+
    ///                      +-------------^--------------+      |
    ///                                    |                     |
    ///                                write sets                |
    ///                                    |          cached account state map
    ///                            +-------+-------+           proof
    ///                            |      V M      |             |
    ///                            +-------^-------+             |
    ///                                    |                     |
    ///                      value of `account_address/path`     |
    ///                                    |                     |
    ///        +---------------------------+---------------------+-------+
    ///        | +-------------------------+---------------------+-----+ |
    ///        | |    account_to_btree_cache, account_to_proof_cache   | |
    ///        | +---------------^---------------------------^---------+ |
    ///        |                 |                           |           |
    ///        |     account state blob only        account state blob   |
    ///        |                 |                         proof         |
    ///        |                 |                           |           |
    ///        | +---------------+--------------+ +----------+---------+ |
    ///        | |      speculative_state       | |       reader       | |
    ///        | +------------------------------+ +--------------------+ |
    ///        +---------------------------------------------------------+
    /// ```
    account_to_btree_cache: RefCell<HashMap<AccountAddress, BTreeMap<Vec<u8>, Vec<u8>>>>,
    account_to_proof_cache: RefCell<HashMap<HashValue, SparseMerkleProof>>,
}

impl<'a> VerifiedStateView<'a> {
    /// Constructs a [`VerifiedStateView`] with persistent state view represented by
    /// `latest_persistent_state_root` plus a storage reader, and the in-memory speculative state
    /// on top of it represented by `speculative_state`.
    pub fn new(
        reader: Arc<dyn StorageRead>,
        latest_persistent_version_and_state_root: (Option<Version>, HashValue),
        speculative_state: &'a SparseMerkleTree,
    ) -> Self {
        Self {
            reader,
            latest_persistent_version: latest_persistent_version_and_state_root.0,
            // if num_elements_in_accumulator > 0 {
            //     Some(num_elements_in_accumulator - 1)
            // } else {
            //     None
            // },
            latest_persistent_state_root: latest_persistent_version_and_state_root.1,
            speculative_state,
            account_to_btree_cache: RefCell::new(HashMap::new()),
            account_to_proof_cache: RefCell::new(HashMap::new()),
        }
    }
}

impl<'a>
    Into<(
        HashMap<AccountAddress, BTreeMap<Vec<u8>, Vec<u8>>>,
        HashMap<HashValue, SparseMerkleProof>,
    )> for VerifiedStateView<'a>
{
    fn into(
        self,
    ) -> (
        HashMap<AccountAddress, BTreeMap<Vec<u8>, Vec<u8>>>,
        HashMap<HashValue, SparseMerkleProof>,
    ) {
        (
            self.account_to_btree_cache.into_inner(),
            self.account_to_proof_cache.into_inner(),
        )
    }
}

impl<'a> StateView for VerifiedStateView<'a> {
    fn get(&self, access_path: &AccessPath) -> Result<Option<Vec<u8>>> {
        let address = access_path.address;
        let path = &access_path.path;
        match self.account_to_btree_cache.borrow_mut().entry(address) {
            Entry::Occupied(occupied) => Ok(occupied.get().get(path).cloned()),
            Entry::Vacant(vacant) => {
                let address_hash = address.hash();
                let account_blob_option = match self.speculative_state.get(address_hash) {
                    AccountState::ExistsInScratchPad(blob) => Some(blob),
                    AccountState::DoesNotExist => None,
                    // No matter it is in db or unknown, we have to query from db since even the
                    // former case, we don't have the blob data but only its hash.
                    AccountState::ExistsInDB | AccountState::Unknown => {
                        let (blob, proof) = match self.latest_persistent_version {
                            Some(version) => self
                                .reader
                                .get_account_state_with_proof_by_version(address, version)?,
                            None => (None, SparseMerkleProof::new(None, vec![])),
                        };
                        verify_sparse_merkle_element(
                            self.latest_persistent_state_root,
                            address.hash(),
                            &blob,
                            &proof,
                        )
                        .map_err(|err| {
                            format_err!(
                                "Proof is invalid for address {:?} with state root hash {:?}: {}",
                                address,
                                self.latest_persistent_state_root,
                                err
                            )
                        })?;
                        assert!(self
                            .account_to_proof_cache
                            .borrow_mut()
                            .insert(address_hash, proof)
                            .is_none());
                        blob
                    }
                };
                Ok(vacant
                    .insert(
                        account_blob_option
                            .as_ref()
                            .map(TryInto::try_into)
                            .transpose()?
                            .unwrap_or_default(),
                    )
                    .get(path)
                    .cloned())
            }
        }
    }

    fn multi_get(&self, _access_paths: &[AccessPath]) -> Result<Vec<Option<Vec<u8>>>> {
        unimplemented!();
    }

    fn is_genesis(&self) -> bool {
        self.latest_persistent_version.is_none()
    }
}
<commit_msg>[state_view] remove commented code<commit_after>// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::StorageRead;
use crypto::{hash::CryptoHash, HashValue};
use failure::prelude::*;
use scratchpad::{AccountState, SparseMerkleTree};
use state_view::StateView;
use std::{
    cell::RefCell,
    collections::{hash_map::Entry, BTreeMap, HashMap},
    convert::TryInto,
    sync::Arc,
};
use types::{
    access_path::AccessPath,
    account_address::AccountAddress,
    proof::{verify_sparse_merkle_element, SparseMerkleProof},
    transaction::Version,
};

/// `VerifiedStateView` is like a snapshot of the global state comprised of state view at two
/// levels, persistent storage and memory.
pub struct VerifiedStateView<'a> {
    /// A gateway implementing persistent storage interface, which can be a RPC client or direct
    /// accessor.
    reader: Arc<dyn StorageRead>,

    /// The most recent version in persistent storage.
    latest_persistent_version: Option<Version>,

    /// The most recent state root hash in persistent storage.
    latest_persistent_state_root: HashValue,

    /// The in-momery version of sparse Merkle tree of which the states haven't been committed.
    speculative_state: &'a SparseMerkleTree,

    /// The cache of verified account states from `reader` and `speculative_state_view`,
    /// represented by a hashmap with an account address as key and a pair of an ordered
    /// account state map and an an optional account state proof as value. When the VM queries an
    /// `access_path`, this cache will first check whether `reader_cache` is hit. If hit, it
    /// will return the corresponding value of that `access_path`; otherwise, the account state
    /// will be loaded into the cache from scratchpad or persistent storage in order as a
    /// deserialized ordered map and then be returned. If the VM queries this account again,
    /// the cached data can be read directly without bothering storage layer. The proofs in
    /// cache are needed by ScratchPad after VM execution to construct an in-memory sparse Merkle
    /// tree.
    /// ```text
    ///                      +----------------------------+
    ///                      | In-memory SparseMerkleTree <------+
    ///                      +-------------^--------------+      |
    ///                                    |                     |
    ///                                write sets                |
    ///                                    |          cached account state map
    ///                            +-------+-------+           proof
    ///                            |      V M      |             |
    ///                            +-------^-------+             |
    ///                                    |                     |
    ///                      value of `account_address/path`     |
    ///                                    |                     |
    ///        +---------------------------+---------------------+-------+
    ///        | +-------------------------+---------------------+-----+ |
    ///        | |    account_to_btree_cache, account_to_proof_cache   | |
    ///        | +---------------^---------------------------^---------+ |
    ///        |                 |                           |           |
    ///        |     account state blob only        account state blob   |
    ///        |                 |                         proof         |
    ///        |                 |                           |           |
    ///        | +---------------+--------------+ +----------+---------+ |
    ///        | |      speculative_state       | |       reader       | |
    ///        | +------------------------------+ +--------------------+ |
    ///        +---------------------------------------------------------+
    /// ```
    account_to_btree_cache: RefCell<HashMap<AccountAddress, BTreeMap<Vec<u8>, Vec<u8>>>>,
    account_to_proof_cache: RefCell<HashMap<HashValue, SparseMerkleProof>>,
}

impl<'a> VerifiedStateView<'a> {
    /// Constructs a [`VerifiedStateView`] with persistent state view represented by
    /// `latest_persistent_state_root` plus a storage reader, and the in-memory speculative state
    /// on top of it represented by `speculative_state`.
    pub fn new(
        reader: Arc<dyn StorageRead>,
        latest_persistent_version_and_state_root: (Option<Version>, HashValue),
        speculative_state: &'a SparseMerkleTree,
    ) -> Self {
        Self {
            reader,
            latest_persistent_version: latest_persistent_version_and_state_root.0,
            latest_persistent_state_root: latest_persistent_version_and_state_root.1,
            speculative_state,
            account_to_btree_cache: RefCell::new(HashMap::new()),
            account_to_proof_cache: RefCell::new(HashMap::new()),
        }
    }
}

impl<'a>
    Into<(
        HashMap<AccountAddress, BTreeMap<Vec<u8>, Vec<u8>>>,
        HashMap<HashValue, SparseMerkleProof>,
    )> for VerifiedStateView<'a>
{
    fn into(
        self,
    ) -> (
        HashMap<AccountAddress, BTreeMap<Vec<u8>, Vec<u8>>>,
        HashMap<HashValue, SparseMerkleProof>,
    ) {
        (
            self.account_to_btree_cache.into_inner(),
            self.account_to_proof_cache.into_inner(),
        )
    }
}

impl<'a> StateView for VerifiedStateView<'a> {
    fn get(&self, access_path: &AccessPath) -> Result<Option<Vec<u8>>> {
        let address = access_path.address;
        let path = &access_path.path;
        match self.account_to_btree_cache.borrow_mut().entry(address) {
            Entry::Occupied(occupied) => Ok(occupied.get().get(path).cloned()),
            Entry::Vacant(vacant) => {
                let address_hash = address.hash();
                let account_blob_option = match self.speculative_state.get(address_hash) {
                    AccountState::ExistsInScratchPad(blob) => Some(blob),
                    AccountState::DoesNotExist => None,
                    // No matter it is in db or unknown, we have to query from db since even the
                    // former case, we don't have the blob data but only its hash.
                    AccountState::ExistsInDB | AccountState::Unknown => {
                        let (blob, proof) = match self.latest_persistent_version {
                            Some(version) => self
                                .reader
                                .get_account_state_with_proof_by_version(address, version)?,
                            None => (None, SparseMerkleProof::new(None, vec![])),
                        };
                        verify_sparse_merkle_element(
                            self.latest_persistent_state_root,
                            address.hash(),
                            &blob,
                            &proof,
                        )
                        .map_err(|err| {
                            format_err!(
                                "Proof is invalid for address {:?} with state root hash {:?}: {}",
                                address,
                                self.latest_persistent_state_root,
                                err
                            )
                        })?;
                        assert!(self
                            .account_to_proof_cache
                            .borrow_mut()
                            .insert(address_hash, proof)
                            .is_none());
                        blob
                    }
                };
                Ok(vacant
                    .insert(
                        account_blob_option
                            .as_ref()
                            .map(TryInto::try_into)
                            .transpose()?
                            .unwrap_or_default(),
                    )
                    .get(path)
                    .cloned())
            }
        }
    }

    fn multi_get(&self, _access_paths: &[AccessPath]) -> Result<Vec<Option<Vec<u8>>>> {
        unimplemented!();
    }

    fn is_genesis(&self) -> bool {
        self.latest_persistent_version.is_none()
    }
}
<|endoftext|>


<commit_before>use role_playing_game::*;

#[test]
fn test_reviving_dead_player() {
    let dead_player = Player {
        health: 0,
        mana: Some(0),
        level: 34,
    };
    let revived_player = dead_player
        .revive()
        .expect("reviving a dead player must return Some(player)");
    assert_eq!(revived_player.health, 100);
    assert_eq!(revived_player.mana, Some(100));
    assert_eq!(revived_player.level, dead_player.level);
}

#[test]
#[ignore]
fn test_reviving_dead_level9_player() {
    let dead_player = Player {
        health: 0,
        mana: Some(0),
        level: 9,
    };
    let revived_player = dead_player
        .revive()
        .expect("reviving a dead player must return Some(player)");
    assert_eq!(revived_player.health, 100);
    assert_eq!(revived_player.mana, None);
    assert_eq!(revived_player.level, dead_player.level);
}

#[test]
#[ignore]
fn test_reviving_dead_level10_player() {
    let dead_player = Player {
        health: 0,
        mana: Some(0),
        level: 10,
    };
    let revived_player = dead_player
        .revive()
        .expect("reviving a dead player must return Some(player)");
    assert_eq!(revived_player.health, 100);
    assert_eq!(revived_player.mana, Some(100));
    assert_eq!(revived_player.level, dead_player.level);
}

#[test]
#[ignore]
fn test_reviving_alive_player() {
    let alive_player = Player {
        health: 1,
        mana: None,
        level: 8,
    };
    assert!(alive_player.revive().is_none());
}

#[test]
#[ignore]
fn test_cast_spell_with_enough_mana() {
    const HEALTH: u32 = 99;
    const MANA: u32 = 100;
    const LEVEL: u32 = 100;
    const MANA_COST: u32 = 3;

    let mut accomplished_wizard = Player {
        health: HEALTH,
        mana: Some(MANA),
        level: LEVEL,
    };

    assert_eq!(accomplished_wizard.cast_spell(MANA_COST), MANA_COST * 2);
    assert_eq!(accomplished_wizard.health, HEALTH);
    assert_eq!(accomplished_wizard.mana, Some(MANA - MANA_COST));
    assert_eq!(accomplished_wizard.level, LEVEL);
}

#[test]
#[ignore]
fn test_cast_spell_with_insufficient_mana() {
    let mut no_mana_wizard = Player {
        health: 56,
        mana: Some(2),
        level: 22,
    };

    // we want to clone so we can compare before-and-after effects of casting the spell,
    // but we don't want to introduce that concept to the student yet, so we have to do it manually
    let clone = Player { ..no_mana_wizard };

    assert_eq!(no_mana_wizard.cast_spell(3), 0);
    assert_eq!(no_mana_wizard.health, clone.health);
    assert_eq!(no_mana_wizard.mana, clone.mana);
    assert_eq!(no_mana_wizard.level, clone.level);
}

#[test]
#[ignore]
fn test_cast_spell_with_no_mana_pool() {
    const MANA_COST: u32 = 10;

    let mut underleveled_player = Player {
        health: 87,
        mana: None,
        level: 6,
    };

    let clone = Player {
        ..underleveled_player
    };

    assert_eq!(underleveled_player.cast_spell(MANA_COST), 0);
    assert_eq!(underleveled_player.health, clone.health - MANA_COST);
    assert_eq!(underleveled_player.mana, clone.mana);
    assert_eq!(underleveled_player.level, clone.level);
}

#[test]
#[ignore]
fn test_cast_large_spell_with_no_mana_pool() {
    const MANA_COST: u32 = 30;

    let mut underleveled_player = Player {
        health: 20,
        mana: None,
        level: 6,
    };

    assert_eq!(underleveled_player.cast_spell(MANA_COST), 0);
    assert_eq!(underleveled_player.health, 0);
    assert_eq!(underleveled_player.mana, None);
    assert_eq!(underleveled_player.level, 6);
}
<commit_msg>fix test_reviving_dead_level9_player (#1402)<commit_after>use role_playing_game::*;

#[test]
fn test_reviving_dead_player() {
    let dead_player = Player {
        health: 0,
        mana: Some(0),
        level: 34,
    };
    let revived_player = dead_player
        .revive()
        .expect("reviving a dead player must return Some(player)");
    assert_eq!(revived_player.health, 100);
    assert_eq!(revived_player.mana, Some(100));
    assert_eq!(revived_player.level, dead_player.level);
}

#[test]
#[ignore]
fn test_reviving_dead_level9_player() {
    let dead_player = Player {
        health: 0,
        mana: None,
        level: 9,
    };
    let revived_player = dead_player
        .revive()
        .expect("reviving a dead player must return Some(player)");
    assert_eq!(revived_player.health, 100);
    assert_eq!(revived_player.mana, None);
    assert_eq!(revived_player.level, dead_player.level);
}

#[test]
#[ignore]
fn test_reviving_dead_level10_player() {
    let dead_player = Player {
        health: 0,
        mana: Some(0),
        level: 10,
    };
    let revived_player = dead_player
        .revive()
        .expect("reviving a dead player must return Some(player)");
    assert_eq!(revived_player.health, 100);
    assert_eq!(revived_player.mana, Some(100));
    assert_eq!(revived_player.level, dead_player.level);
}

#[test]
#[ignore]
fn test_reviving_alive_player() {
    let alive_player = Player {
        health: 1,
        mana: None,
        level: 8,
    };
    assert!(alive_player.revive().is_none());
}

#[test]
#[ignore]
fn test_cast_spell_with_enough_mana() {
    const HEALTH: u32 = 99;
    const MANA: u32 = 100;
    const LEVEL: u32 = 100;
    const MANA_COST: u32 = 3;

    let mut accomplished_wizard = Player {
        health: HEALTH,
        mana: Some(MANA),
        level: LEVEL,
    };

    assert_eq!(accomplished_wizard.cast_spell(MANA_COST), MANA_COST * 2);
    assert_eq!(accomplished_wizard.health, HEALTH);
    assert_eq!(accomplished_wizard.mana, Some(MANA - MANA_COST));
    assert_eq!(accomplished_wizard.level, LEVEL);
}

#[test]
#[ignore]
fn test_cast_spell_with_insufficient_mana() {
    let mut no_mana_wizard = Player {
        health: 56,
        mana: Some(2),
        level: 22,
    };

    // we want to clone so we can compare before-and-after effects of casting the spell,
    // but we don't want to introduce that concept to the student yet, so we have to do it manually
    let clone = Player { ..no_mana_wizard };

    assert_eq!(no_mana_wizard.cast_spell(3), 0);
    assert_eq!(no_mana_wizard.health, clone.health);
    assert_eq!(no_mana_wizard.mana, clone.mana);
    assert_eq!(no_mana_wizard.level, clone.level);
}

#[test]
#[ignore]
fn test_cast_spell_with_no_mana_pool() {
    const MANA_COST: u32 = 10;

    let mut underleveled_player = Player {
        health: 87,
        mana: None,
        level: 6,
    };

    let clone = Player {
        ..underleveled_player
    };

    assert_eq!(underleveled_player.cast_spell(MANA_COST), 0);
    assert_eq!(underleveled_player.health, clone.health - MANA_COST);
    assert_eq!(underleveled_player.mana, clone.mana);
    assert_eq!(underleveled_player.level, clone.level);
}

#[test]
#[ignore]
fn test_cast_large_spell_with_no_mana_pool() {
    const MANA_COST: u32 = 30;

    let mut underleveled_player = Player {
        health: 20,
        mana: None,
        level: 6,
    };

    assert_eq!(underleveled_player.cast_spell(MANA_COST), 0);
    assert_eq!(underleveled_player.health, 0);
    assert_eq!(underleveled_player.mana, None);
    assert_eq!(underleveled_player.level, 6);
}
<|endoftext|>