<commit_before>//! Composable primitives for asynchronous computations
//!
//! The async module contains utilities for managing asynchronous computations.
//! These utilities are primarily based around `Future` and `Stream` types as
//! well as functions that allow composing computations on these types.
//!
//! ## Future
//!
//! A `Future` is a proxy representing the result of a computation which may
//! not be complete.  The computation may be running concurrently in another
//! thread or may be triggered upon completion of an asynchronous callback. One
//! way to think of a `Future` is as a `Result` where the value is
//! asynchronously computed.
//!
//! For example:
//!
//! ```
//! use eventual::*;
//!
//! // Run a computation in another thread
//! let future1 = Future::spawn(|| {
//!     // Represents an expensive computation, but for now just return a
//!     // number
//!     42
//! });
//!
//! // Run another computation
//! let future2 = Future::spawn(|| {
//!     // Another expensive computation
//!     18
//! });
//!
//! let res = join((
//!         future1.map(|v| v * 2),
//!         future2.map(|v| v + 5)))
//!     .and_then(|(v1, v2)| Ok(v1 - v2))
//!     .await().unwrap();
//!
//! assert_eq!(61, res);
//!
//! ```
//!
//! ## Stream
//!
//! A `Stream` is like a `Future`, except that instead of representing a single
//! value, it represents a sequence of values.
//!

#![crate_name = "eventual"]

extern crate syncbox;
extern crate time;

#[macro_use]
extern crate log;

pub use self::future::{Future, Complete};
pub use self::join::{join, Join};
pub use self::receipt::Receipt;
pub use self::select::{select, Select};
pub use self::sequence::sequence;
pub use self::stream::{Stream, StreamIter, Sender, BusySender};
pub use self::timer::Timer;

use std::fmt;

// ## TODO
//
// * Switch generics to where clauses
//   - rust-lang/rust#20300 (T::Foo resolution)
//
// * Allow Async::or & Async::or_else to change the error type
//
// * Improve performance / reduce allocations

mod core;
mod future;
mod join;
mod process;
mod receipt;
mod select;
mod sequence;
mod stream;
mod timer;

/// A value representing an asynchronous computation
pub trait Async : Send + 'static + Sized {
    type Value: Send + 'static;
    type Error: Send + 'static;
    type Cancel: Cancel<Self>;

    /// Returns true if `expect` will succeed.
    fn is_ready(&self) -> bool;

    /// Returns true if the async value is ready and has failed
    fn is_err(&self) -> bool;

    /// Get the underlying value if present
    fn poll(self) -> Result<AsyncResult<Self::Value, Self::Error>, Self>;

    /// Get the underlying value if present, panic otherwise
    fn expect(self) -> AsyncResult<Self::Value, Self::Error> {
        if let Ok(v) = self.poll() {
            return v;
        }

        panic!("the async value is not ready");
    }

    /// Invokes the given function when the Async instance is ready to be
    /// consumed.
    fn ready<F>(self, f: F) -> Self::Cancel where F: FnOnce(Self) + Send + 'static;

    /// Invoke the callback with the resolved `Async` result.
    fn receive<F>(self, f: F)
            where F: FnOnce(AsyncResult<Self::Value, Self::Error>) + Send + 'static {
        self.ready(move |async| {
            match async.poll() {
                Ok(res) => f(res),
                Err(_) => panic!("ready callback invoked but is not actually ready"),
            }
        });
    }

    /// Blocks the thread until the async value is complete and returns the
    /// result.
    fn await(self) -> AsyncResult<Self::Value, Self::Error> {
        use std::sync::mpsc::channel;

        let (tx, rx) = channel();

        self.receive(move |res| tx.send(res).ok().expect("receiver thread died"));
        rx.recv().ok().expect("async disappeared without a trace")
    }

    /// Trigger the computation without waiting for the result
    fn fire(self) {
        self.receive(drop)
    }

    /*
     *
     * ===== Computation Builders =====
     *
     */

    /// This method returns a future whose completion value depends on the
    /// completion value of the original future.
    ///
    /// If the original future completes with an error, the future returned by
    /// this method completes with that error.
    ///
    /// If the original future completes successfully, the future returned by
    /// this method completes with the completion value of `next`.
    fn and<U: Async<Error=Self::Error>>(self, next: U) -> Future<U::Value, Self::Error> {
        self.and_then(move |_| next)
    }

    /// This method returns a future whose completion value depends on the
    /// completion value of the original future.
    ///
    /// If the original future completes with an error, the future returned by
    /// this method completes with that error.
    ///
    /// If the original future completes successfully, the callback to this
    /// method is called with the value, and the callback returns a new future.
    /// The future returned by this method then completes with the completion
    /// value of that returned future.
    ///
    /// ```
    /// use eventual::*;
    ///
    /// let f = Future::of(1337);
    ///
    /// f.and_then(|v| {
    ///     assert_eq!(v, 1337);
    ///     Ok(1007)
    /// }).and_then(|v| {
    ///     assert_eq!(v, 1007)
    /// }).await();
    ///
    /// let e = Future::<(), &'static str>::error("failed");
    ///
    /// e.and_then(|v| {
    ///     panic!("unreachable");
    ///     Ok(())
    /// }).await();
    /// ```
    fn and_then<F, U: Async<Error=Self::Error>>(self, f: F) -> Future<U::Value, Self::Error>
            where F: FnOnce(Self::Value) -> U + Send + 'static,
                  U::Value: Send + 'static {
        let (complete, ret) = Future::pair();

        complete.receive(move |c| {
            if let Ok(complete) = c {
                self.receive(move |res| {
                    match res {
                        Ok(v) => {
                            f(v).receive(move |res| {
                                match res {
                                    Ok(u) => complete.complete(u),
                                    Err(AsyncError::Failed(e)) => complete.fail(e),
                                    _ => {}
                                }
                            });
                        }
                        Err(AsyncError::Failed(e)) => complete.fail(e),
                        _ => {}
                    }
                });
            }
        });

        ret
    }

    /// This method returns a future whose completion value depends on the
    /// completion value of the original future.
    ///
    /// If the original future completes successfully, the future returned by
    /// this method will complete with that value.
    ///
    /// If the original future completes with an error, the future returned by
    /// this method will complete with the completion value of the `alt` future
    /// passed in. That can be either a success or error.
    fn or<A>(self, alt: A) -> Future<Self::Value, A::Error>
            where A: Async<Value=Self::Value> {
        self.or_else(move |_| alt)
    }

    /// This method returns a future whose completion value depends on the
    /// completion value of the original future.
    ///
    /// If the original future completes successfully, the future returned by
    /// this method will complete with that value.
    ///
    /// If the original future completes with an error, this method will invoke
    /// the callback passed to the method, which should return a future. The
    /// future returned by this method will complete with the completion value
    /// of that future. That can be either a success or error.
    fn or_else<F, A>(self, f: F) -> Future<Self::Value, A::Error>
            where F: FnOnce(Self::Error) -> A + Send + 'static,
                  A: Async<Value=Self::Value> {

        let (complete, ret) = Future::pair();

        complete.receive(move |c| {
            if let Ok(complete) = c {
                self.receive(move |res| {
                    match res {
                        Ok(v) => complete.complete(v),
                        Err(AsyncError::Failed(e)) => {
                            f(e).receive(move |res| {
                                match res {
                                    Ok(v) => complete.complete(v),
                                    Err(AsyncError::Failed(e)) => complete.fail(e),
                                    _ => {}
                                }
                            });
                        }
                        Err(AsyncError::Aborted) => drop(complete),
                    }
                });
            }
        });

        ret
    }
}

pub trait Pair {
    type Tx;

    fn pair() -> (Self::Tx, Self);
}

pub trait Cancel<A: Send + 'static> : Send + 'static {
    fn cancel(self) -> Option<A>;
}

/*
 *
 * ===== Async implementations =====
 *
 */

impl<T: Send + 'static, E: Send + 'static> Async for Result<T, E> {
    type Value = T;
    type Error = E;
    type Cancel = Option<Result<T, E>>;

    fn is_ready(&self) -> bool {
        true
    }

    fn is_err(&self) -> bool {
        self.is_err()
    }

    fn poll(self) -> Result<AsyncResult<T, E>, Result<T, E>> {
        Ok(self.await())
    }

    fn ready<F: FnOnce(Result<T, E>) + Send + 'static>(self, f: F) -> Option<Result<T, E>> {
        f(self);
        None
    }

    fn await(self) -> AsyncResult<T, E> {
        self.map_err(|e| AsyncError::Failed(e))
    }
}

impl<A: Send + 'static> Cancel<A> for Option<A> {
    fn cancel(self) -> Option<A> {
        self
    }
}

/*
 *
 * ===== Async implementations =====
 *
 */

macro_rules! async_impl_body {
    ($ty:ty) => (
        fn is_ready(&self) -> bool {
            true
        }

        fn is_err(&self) -> bool {
            false
        }

        fn poll(self) -> Result<AsyncResult<$ty, ()>, $ty> {
            Ok(Ok(self))
        }

        fn ready<F: FnOnce($ty) + Send + 'static>(self, f: F) -> Option<$ty> {
            f(self);
            None
        }

        fn await(self) -> AsyncResult<$ty, ()> {
            Ok(self)
        }
    );
}

macro_rules! async_impl {
    ($ty:ty) => (
        impl Async for $ty {
            type Value  = $ty;
            type Error  = ();
            type Cancel = Option<$ty>;

            async_impl_body!($ty);
        }
    );

    ($ty:ty, $($rest:tt),*) => (
        async_impl!($ty);
        async_impl!($($rest),*);
    );
}

// For now, implement on as many concrete types as possible. One day, Rust will
// support specialization (hopefully) and this won't be necessary.
async_impl!(
    (), bool, String,
    u8, u16, u32, u64, usize,
    i8, i16, i32, i64, isize);

impl<E: Send + 'static> Async for Vec<E> {
    type Value = Vec<E>;
    type Error = ();
    type Cancel = Option<Vec<E>>;

    async_impl_body!(Vec<E>);
}

/*
 *
 * ===== AsyncResult =====
 *
 */

pub type AsyncResult<T, E> = Result<T, AsyncError<E>>;

#[derive(Eq, PartialEq)]
pub enum AsyncError<E: Send + 'static> {
    Failed(E),
    Aborted,
}

impl<E: Send + 'static> AsyncError<E> {
    pub fn failed(err: E) -> AsyncError<E> {
        AsyncError::Failed(err)
    }

    pub fn aborted() -> AsyncError<E> {
        AsyncError::Aborted
    }

    pub fn is_aborted(&self) -> bool {
        match *self {
            AsyncError::Aborted => true,
            _ => false,
        }
    }

    pub fn is_failed(&self) -> bool {
        match *self {
            AsyncError::Failed(..) => true,
            _ => false,
        }
    }

    pub fn unwrap(self) -> E {
        match self {
            AsyncError::Failed(err) => err,
            AsyncError::Aborted => panic!("unwrapping a cancellation error"),
        }
    }

    pub fn take(self) -> Option<E> {
        match self {
            AsyncError::Failed(err) => Some(err),
            _ => None,
        }
    }
}

impl<E: Send + 'static + fmt::Debug> fmt::Debug for AsyncError<E> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            AsyncError::Failed(ref e) => write!(fmt, "AsyncError::Failed({:?})", e),
            AsyncError::Aborted => write!(fmt, "AsyncError::Aborted"),
        }
    }
}

/*
 *
 * ===== BoxedReceive =====
 *
 */

// Needed to allow virtual dispatch to Receive
trait BoxedReceive<T> : Send + 'static {
    fn receive_boxed(self: Box<Self>, val: T);
}

impl<F: FnOnce(T) + Send + 'static, T> BoxedReceive<T> for F {
    fn receive_boxed(self: Box<F>, val: T) {
        (*self)(val)
    }
}
<commit_msg>Remove Async impls for std types except for Result and ()<commit_after>//! Composable primitives for asynchronous computations
//!
//! The async module contains utilities for managing asynchronous computations.
//! These utilities are primarily based around `Future` and `Stream` types as
//! well as functions that allow composing computations on these types.
//!
//! ## Future
//!
//! A `Future` is a proxy representing the result of a computation which may
//! not be complete.  The computation may be running concurrently in another
//! thread or may be triggered upon completion of an asynchronous callback. One
//! way to think of a `Future` is as a `Result` where the value is
//! asynchronously computed.
//!
//! For example:
//!
//! ```
//! use eventual::*;
//!
//! // Run a computation in another thread
//! let future1 = Future::spawn(|| {
//!     // Represents an expensive computation, but for now just return a
//!     // number
//!     42
//! });
//!
//! // Run another computation
//! let future2 = Future::spawn(|| {
//!     // Another expensive computation
//!     18
//! });
//!
//! let res = join((
//!         future1.map(|v| v * 2),
//!         future2.map(|v| v + 5)))
//!     .and_then(|(v1, v2)| Ok(v1 - v2))
//!     .await().unwrap();
//!
//! assert_eq!(61, res);
//!
//! ```
//!
//! ## Stream
//!
//! A `Stream` is like a `Future`, except that instead of representing a single
//! value, it represents a sequence of values.
//!

#![crate_name = "eventual"]

extern crate syncbox;
extern crate time;

#[macro_use]
extern crate log;

pub use self::future::{Future, Complete};
pub use self::join::{join, Join};
pub use self::receipt::Receipt;
pub use self::select::{select, Select};
pub use self::sequence::sequence;
pub use self::stream::{Stream, StreamIter, Sender, BusySender};
pub use self::timer::Timer;

use std::fmt;

// ## TODO
//
// * Switch generics to where clauses
//   - rust-lang/rust#20300 (T::Foo resolution)
//
// * Allow Async::or & Async::or_else to change the error type
//
// * Improve performance / reduce allocations

mod core;
mod future;
mod join;
mod process;
mod receipt;
mod select;
mod sequence;
mod stream;
mod timer;

/// A value representing an asynchronous computation
pub trait Async : Send + 'static + Sized {
    type Value: Send + 'static;
    type Error: Send + 'static;
    type Cancel: Cancel<Self>;

    /// Returns true if `expect` will succeed.
    fn is_ready(&self) -> bool;

    /// Returns true if the async value is ready and has failed
    fn is_err(&self) -> bool;

    /// Get the underlying value if present
    fn poll(self) -> Result<AsyncResult<Self::Value, Self::Error>, Self>;

    /// Get the underlying value if present, panic otherwise
    fn expect(self) -> AsyncResult<Self::Value, Self::Error> {
        if let Ok(v) = self.poll() {
            return v;
        }

        panic!("the async value is not ready");
    }

    /// Invokes the given function when the Async instance is ready to be
    /// consumed.
    fn ready<F>(self, f: F) -> Self::Cancel where F: FnOnce(Self) + Send + 'static;

    /// Invoke the callback with the resolved `Async` result.
    fn receive<F>(self, f: F)
            where F: FnOnce(AsyncResult<Self::Value, Self::Error>) + Send + 'static {
        self.ready(move |async| {
            match async.poll() {
                Ok(res) => f(res),
                Err(_) => panic!("ready callback invoked but is not actually ready"),
            }
        });
    }

    /// Blocks the thread until the async value is complete and returns the
    /// result.
    fn await(self) -> AsyncResult<Self::Value, Self::Error> {
        use std::sync::mpsc::channel;

        let (tx, rx) = channel();

        self.receive(move |res| tx.send(res).ok().expect("receiver thread died"));
        rx.recv().ok().expect("async disappeared without a trace")
    }

    /// Trigger the computation without waiting for the result
    fn fire(self) {
        self.receive(drop)
    }

    /*
     *
     * ===== Computation Builders =====
     *
     */

    /// This method returns a future whose completion value depends on the
    /// completion value of the original future.
    ///
    /// If the original future completes with an error, the future returned by
    /// this method completes with that error.
    ///
    /// If the original future completes successfully, the future returned by
    /// this method completes with the completion value of `next`.
    fn and<U: Async<Error=Self::Error>>(self, next: U) -> Future<U::Value, Self::Error> {
        self.and_then(move |_| next)
    }

    /// This method returns a future whose completion value depends on the
    /// completion value of the original future.
    ///
    /// If the original future completes with an error, the future returned by
    /// this method completes with that error.
    ///
    /// If the original future completes successfully, the callback to this
    /// method is called with the value, and the callback returns a new future.
    /// The future returned by this method then completes with the completion
    /// value of that returned future.
    ///
    /// ```
    /// use eventual::*;
    ///
    /// let f = Future::of(1337);
    ///
    /// f.and_then(|v| {
    ///     assert_eq!(v, 1337);
    ///     Ok(1007)
    /// }).and_then(|v| {
    ///     assert_eq!(v, 1007)
    /// }).await();
    ///
    /// let e = Future::<(), &'static str>::error("failed");
    ///
    /// e.and_then(|v| {
    ///     panic!("unreachable");
    ///     Ok(())
    /// }).await();
    /// ```
    fn and_then<F, U: Async<Error=Self::Error>>(self, f: F) -> Future<U::Value, Self::Error>
            where F: FnOnce(Self::Value) -> U + Send + 'static,
                  U::Value: Send + 'static {
        let (complete, ret) = Future::pair();

        complete.receive(move |c| {
            if let Ok(complete) = c {
                self.receive(move |res| {
                    match res {
                        Ok(v) => {
                            f(v).receive(move |res| {
                                match res {
                                    Ok(u) => complete.complete(u),
                                    Err(AsyncError::Failed(e)) => complete.fail(e),
                                    _ => {}
                                }
                            });
                        }
                        Err(AsyncError::Failed(e)) => complete.fail(e),
                        _ => {}
                    }
                });
            }
        });

        ret
    }

    /// This method returns a future whose completion value depends on the
    /// completion value of the original future.
    ///
    /// If the original future completes successfully, the future returned by
    /// this method will complete with that value.
    ///
    /// If the original future completes with an error, the future returned by
    /// this method will complete with the completion value of the `alt` future
    /// passed in. That can be either a success or error.
    fn or<A>(self, alt: A) -> Future<Self::Value, A::Error>
            where A: Async<Value=Self::Value> {
        self.or_else(move |_| alt)
    }

    /// This method returns a future whose completion value depends on the
    /// completion value of the original future.
    ///
    /// If the original future completes successfully, the future returned by
    /// this method will complete with that value.
    ///
    /// If the original future completes with an error, this method will invoke
    /// the callback passed to the method, which should return a future. The
    /// future returned by this method will complete with the completion value
    /// of that future. That can be either a success or error.
    fn or_else<F, A>(self, f: F) -> Future<Self::Value, A::Error>
            where F: FnOnce(Self::Error) -> A + Send + 'static,
                  A: Async<Value=Self::Value> {

        let (complete, ret) = Future::pair();

        complete.receive(move |c| {
            if let Ok(complete) = c {
                self.receive(move |res| {
                    match res {
                        Ok(v) => complete.complete(v),
                        Err(AsyncError::Failed(e)) => {
                            f(e).receive(move |res| {
                                match res {
                                    Ok(v) => complete.complete(v),
                                    Err(AsyncError::Failed(e)) => complete.fail(e),
                                    _ => {}
                                }
                            });
                        }
                        Err(AsyncError::Aborted) => drop(complete),
                    }
                });
            }
        });

        ret
    }
}

pub trait Pair {
    type Tx;

    fn pair() -> (Self::Tx, Self);
}

pub trait Cancel<A: Send + 'static> : Send + 'static {
    fn cancel(self) -> Option<A>;
}

/*
 *
 * ===== Async implementations =====
 *
 */

impl<T: Send + 'static, E: Send + 'static> Async for Result<T, E> {
    type Value = T;
    type Error = E;
    type Cancel = Option<Result<T, E>>;

    fn is_ready(&self) -> bool {
        true
    }

    fn is_err(&self) -> bool {
        self.is_err()
    }

    fn poll(self) -> Result<AsyncResult<T, E>, Result<T, E>> {
        Ok(self.await())
    }

    fn ready<F: FnOnce(Result<T, E>) + Send + 'static>(self, f: F) -> Option<Result<T, E>> {
        f(self);
        None
    }

    fn await(self) -> AsyncResult<T, E> {
        self.map_err(|e| AsyncError::Failed(e))
    }
}

impl<A: Send + 'static> Cancel<A> for Option<A> {
    fn cancel(self) -> Option<A> {
        self
    }
}

/// Convenience implementation for (), to ease use of side-effecting functions returning unit
impl Async for () {
    type Value  = ();
    type Error  = ();
    type Cancel = Option<()>;

    fn is_ready(&self) -> bool {
        true
    }

    fn is_err(&self) -> bool {
        false
    }

    fn poll(self) -> Result<AsyncResult<(), ()>, ()> {
        Ok(Ok(self))
    }

    fn ready<F: FnOnce(()) + Send + 'static>(self, f: F) -> Option<()> {
        f(self);
        None
    }

    fn await(self) -> AsyncResult<(), ()> {
         Ok(self)
    }
}

/*
 *
 * ===== AsyncResult =====
 *
 */

pub type AsyncResult<T, E> = Result<T, AsyncError<E>>;

#[derive(Eq, PartialEq)]
pub enum AsyncError<E: Send + 'static> {
    Failed(E),
    Aborted,
}

impl<E: Send + 'static> AsyncError<E> {
    pub fn failed(err: E) -> AsyncError<E> {
        AsyncError::Failed(err)
    }

    pub fn aborted() -> AsyncError<E> {
        AsyncError::Aborted
    }

    pub fn is_aborted(&self) -> bool {
        match *self {
            AsyncError::Aborted => true,
            _ => false,
        }
    }

    pub fn is_failed(&self) -> bool {
        match *self {
            AsyncError::Failed(..) => true,
            _ => false,
        }
    }

    pub fn unwrap(self) -> E {
        match self {
            AsyncError::Failed(err) => err,
            AsyncError::Aborted => panic!("unwrapping a cancellation error"),
        }
    }

    pub fn take(self) -> Option<E> {
        match self {
            AsyncError::Failed(err) => Some(err),
            _ => None,
        }
    }
}

impl<E: Send + 'static + fmt::Debug> fmt::Debug for AsyncError<E> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            AsyncError::Failed(ref e) => write!(fmt, "AsyncError::Failed({:?})", e),
            AsyncError::Aborted => write!(fmt, "AsyncError::Aborted"),
        }
    }
}

/*
 *
 * ===== BoxedReceive =====
 *
 */

// Needed to allow virtual dispatch to Receive
trait BoxedReceive<T> : Send + 'static {
    fn receive_boxed(self: Box<Self>, val: T);
}

impl<F: FnOnce(T) + Send + 'static, T> BoxedReceive<T> for F {
    fn receive_boxed(self: Box<F>, val: T) {
        (*self)(val)
    }
}
<|endoftext|>


<commit_before>pub mod aes;

pub fn ecb_encrypt(key: &[u8], data: &[u8]) -> Vec<u8> {
    let ekey = aes::expand_key(key);
    let mut output = Vec::new();
    for block in data.chunks(16) {
        if block.len() != 16 { panic!("Size must be multiple of 16 bytes"); }
        let encrypted = aes::encrypt(&ekey, block);
        output.extend(encrypted.iter().cloned());
    }
    output
}

pub fn ecb_decrypt(key: &[u8], data: &[u8]) -> Vec<u8> {
    let ekey = aes::expand_key(key);
    let mut output = Vec::new();
    for block in data.chunks(16) {
        if block.len() != 16 { panic!("Size must be multiple of 16 bytes"); }
        let decrypted = aes::decrypt(&ekey, block);
        output.extend(decrypted.iter().cloned());
    }
    output
}

#[test]
fn ecb_test() {
    let data = [1; 128];
    let key = [2; 16];
    let encrypted = ecb_encrypt(&key, &data);
    let decrypted = ecb_decrypt(&key, &encrypted);
    assert_eq!(&data[..], &decrypted[..]);
}

pub fn cbc_encrypt(key: &[u8], data: &[u8], iv: &[u8]) -> Vec<u8> {
    let ekey = aes::expand_key(key);
    let mut output = Vec::new();
    let mut previous = [0; 16];
    for i in 0..16 { previous[i] = iv[i]; }
    for block in data.chunks(16) {
        if block.len() != 16 { panic!("Size must be multiple of 16 bytes"); }
        for i in 0..16 {
            previous[i] ^= block[i];
        }
        let encrypted = aes::encrypt(&ekey, &previous);
        previous = encrypted;
        output.extend(encrypted.iter().cloned());
    }
    output
}

pub fn cbc_decrypt(key: &[u8], data: &[u8], iv: &[u8]) -> Vec<u8> {
    let ekey = aes::expand_key(key);
    let mut output = Vec::new();
    let mut previous = [0; 16];
    for i in 0..16 { previous[i] = iv[i]; }
    for block in data.chunks(16) {
        if block.len() != 16 { panic!("Size must be multiple of 16 bytes"); }
        let mut decrypted = aes::decrypt(&ekey, block);
        for i in 0..16 {
            decrypted[i] ^= previous[i];
            previous[i] = block[i];
        }
        output.extend(decrypted.iter().cloned());
    }
    output
}

#[test]
fn cbc_test() {
    let data = [3; 128];
    let key = [4; 16];
    let iv = [5; 16];
    let encrypted = cbc_encrypt(&key, &data, &iv);
    let decrypted = cbc_decrypt(&key, &encrypted, &iv);
    assert_eq!(&data[..], &decrypted[..]);
}

<commit_msg>Added simple padding function<commit_after>pub mod aes;

pub fn ecb_encrypt(key: &[u8], data: &[u8]) -> Vec<u8> {
    let ekey = aes::expand_key(key);
    let mut output = Vec::new();
    for block in data.chunks(16) {
        if block.len() != 16 { panic!("Size must be multiple of 16 bytes"); }
        let encrypted = aes::encrypt(&ekey, block);
        output.extend(encrypted.iter().cloned());
    }
    output
}

pub fn ecb_decrypt(key: &[u8], data: &[u8]) -> Vec<u8> {
    let ekey = aes::expand_key(key);
    let mut output = Vec::new();
    for block in data.chunks(16) {
        if block.len() != 16 { panic!("Size must be multiple of 16 bytes"); }
        let decrypted = aes::decrypt(&ekey, block);
        output.extend(decrypted.iter().cloned());
    }
    output
}

#[test]
fn ecb_test() {
    let data = [1; 128];
    let key = [2; 16];
    let encrypted = ecb_encrypt(&key, &data);
    let decrypted = ecb_decrypt(&key, &encrypted);
    assert_eq!(&data[..], &decrypted[..]);
}

pub fn cbc_encrypt(key: &[u8], data: &[u8], iv: &[u8]) -> Vec<u8> {
    let ekey = aes::expand_key(key);
    let mut output = Vec::new();
    let mut previous = [0; 16];
    for i in 0..16 { previous[i] = iv[i]; }
    for block in data.chunks(16) {
        if block.len() != 16 { panic!("Size must be multiple of 16 bytes"); }
        for i in 0..16 {
            previous[i] ^= block[i];
        }
        let encrypted = aes::encrypt(&ekey, &previous);
        previous = encrypted;
        output.extend(encrypted.iter().cloned());
    }
    output
}

pub fn cbc_decrypt(key: &[u8], data: &[u8], iv: &[u8]) -> Vec<u8> {
    let ekey = aes::expand_key(key);
    let mut output = Vec::new();
    let mut previous = [0; 16];
    for i in 0..16 { previous[i] = iv[i]; }
    for block in data.chunks(16) {
        if block.len() != 16 { panic!("Size must be multiple of 16 bytes"); }
        let mut decrypted = aes::decrypt(&ekey, block);
        for i in 0..16 {
            decrypted[i] ^= previous[i];
            previous[i] = block[i];
        }
        output.extend(decrypted.iter().cloned());
    }
    output
}

#[test]
fn cbc_test() {
    let data = [3; 128];
    let key = [4; 16];
    let iv = [5; 16];
    let encrypted = cbc_encrypt(&key, &data, &iv);
    let decrypted = cbc_decrypt(&key, &encrypted, &iv);
    assert_eq!(&data[..], &decrypted[..]);
}

pub fn pad(data: &[u8]) -> Vec<u8> {
    let length = data.len();
    let target = length - length % 16 + 16;
    let padding = target - length;
    let mut output = data.to_vec();
    for _ in 0..padding {
        output.push(padding as u8);
    }
    output
}

#[test]
fn pad_test() {
    let data = [7;11];
    let padded = pad(&data);
    assert_eq!([7,7,7,7,7,7,7,7,7,7,7,5,5,5,5,5], padded[..]);
    let data2 = [4;16];
    let padded2 = pad(&data2);
    assert_eq!([4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16], padded2[..]);
    // ^ allowing for no padding at all creates ambiguity if the unpadded data has an ending that
    // looks like it could be padding so we pad for a full block
}
<|endoftext|>


<commit_before>// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

//! A library providing high-level abstractions for event loop concurrency,
//! heavily borrowing ideas from [KJ](https://capnproto.org/cxxrpc.html#kj-concurrency-framework).
//! Allows for coordination of asynchronous tasks using [promises](struct.Promise.html) as
//! a basic building block.

extern crate mio;
extern crate nix;

use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::result::Result;
use private::{promise_node, Event, BoolEvent, PromiseAndFulfillerHub,
              EVENT_LOOP, with_current_event_loop, PromiseNode};

pub mod io;

mod private;
mod handle_table;

pub struct Forced;

/// A computation that might eventually resolve to a value of type `T` or to an error
//  of type `E`.
pub struct Promise<T, E> where T: 'static, E: 'static {
    node: Box<PromiseNode<T, E>>,
}

impl <T, E> Promise <T, E> {
    /// Chains further computation to be executed once the promise resolves.
    /// When the promise is fulfilled or rejected, invokes `func` on its result.
    ///
    /// If the returned promise is dropped before the chained computation runs, the chained
    /// computation will be cancelled.
    ///
    /// Always returns immediately, even if the promise is already resolved. The earliest that
    /// `func` might be invoked is during the next `turn()` of the event loop.
    pub fn then_else<F, R, E1>(self, func: F) -> Promise<R, E1>
        where F: 'static,
              F: FnOnce(Result<T, E>) -> Result<Promise<R, E1>, E1>,
              R: 'static
    {
        let intermediate = Box::new(promise_node::Transform::new(self.node, func));
        Promise { node: Box::new(promise_node::Chain::new(intermediate)) }
    }

    /// Calls `then_else()` with a default error handler that simply propagates all errors.
    pub fn then<F, R>(self, func: F) -> Promise<R, E>
        where F: 'static,
              F: FnOnce(T) -> Result<Promise<R, E>, E>,
              R: 'static,
    {
        self.then_else(|r| { match r { Ok(v) => func(v), Err(e) => Err(e) } })
    }

    /// Like then_else() but for a `func` that returns a direct value rather than a promise.
    pub fn map_else<F, R, E1>(self, func: F) -> Promise<R, E1>
        where F: 'static,
              F: FnOnce(Result<T, E>) -> Result<R, E1>,
              R: 'static,
              E1: 'static
    {
        Promise { node: Box::new(promise_node::Transform::new(self.node, func)) }
    }

    /// Calls `map_else()` with a default error handler that simple propagates all errors.
    pub fn map<F, R>(self, func: F) -> Promise<R, E>
        where F: 'static,
              F: FnOnce(T) -> Result<R, E>,
              R: 'static
    {
        self.map_else(|r| { match r { Ok(v) => func(v), Err(e) =>  Err(e) } } )
    }

    /// Transforms the error branch of the promise.
    pub fn map_err<E1, F>(self, func: F) -> Promise<T, E1>
        where F: 'static,
              F: FnOnce(E) -> E1
    {
        self.map_else(|r| { match r { Ok(v) => Ok(v), Err(e) =>  Err(func(e)) } } )
    }

    /// Maps errors into a more general type.
    pub fn lift<E1>(self) -> Promise<T, E1> where E: Into<E1> {
        self.map_err(|e| e.into())
    }

    /// Cancels the promise, returning its value if it has already been fulfilled. If the promise has not
    /// already been fulfilled, the result must be an Err.
    pub fn force(self) -> Result<T, E> {
        self.node.force()
    }

    /// Returns a new promise that resolves when either `self` or `other` resolves. The promise that
    /// doesn't resolve first is cancelled.
    pub fn exclusive_join(self, other: Promise<T, E>) -> Promise<T, E> {
        Promise { node: Box::new(private::promise_node::ExclusiveJoin::new(self.node, other.node)) }
    }

    /// Creates a new promise that has already been fulfilled.
    pub fn fulfilled(value: T) -> Promise<T, E> {
        Promise { node: Box::new(promise_node::Immediate::new(Ok(value))) }
    }

    /// Creates a new promise that has already been rejected with the given error.
    pub fn rejected(error: E) -> Promise<T, E> {
        Promise { node: Box::new(promise_node::Immediate::new(Err(error))) }
    }

    /// Runs the event loop until the promise is fulfilled.
    ///
    /// The `WaitScope` argument ensures that `wait()` can only be called at the top level of a program.
    /// Waiting within event callbacks is disallowed.
    pub fn wait(mut self, _wait_scope: &WaitScope) -> Result<T, E> {
        with_current_event_loop(move |event_loop| {
            let fired = ::std::rc::Rc::new(::std::cell::Cell::new(false));
            let done_event = BoolEvent::new(fired.clone());
            let (handle, _dropper) = private::EventHandle::new();
            handle.set(Box::new(done_event));
            self.node.on_ready(handle);

            //event_loop.running = true;

            while !fired.get() {
                if !event_loop.turn() {
                    // No events in the queue.
                    event_loop.event_port.borrow_mut().wait();
                }
            }

            self.node.get()
        })
    }
}

/// A scope in which asynchronous programming can occur. Corresponds to the top level scope
/// of some event loop.
pub struct WaitScope(::std::marker::PhantomData<*mut u8>); // impl !Sync for WaitScope {}

/// Interface between an `EventLoop` and events originating from outside of the loop's thread.
trait EventPort {
    /// Waits for an external event to arrive, sleeping if necessary.
    /// Returns true if wake() has been called from another thread.
    fn wait(&mut self) -> bool;

    /// Checks whether any external events have arrived, but does not sleep.
    /// Returns true if wake() has been called from another thread.
    fn poll(&mut self) -> bool;

    /// Called to notify the `EventPort` when the `EventLoop` has work to do; specifically when it
    /// transitions from empty -> runnable or runnable -> empty. This is typically useful when
    /// integrating with an external event loop; if the loop is currently runnable then you should
    /// arrange to call run() on it soon. The default implementation does nothing.
    fn set_runnable(&mut self, _runnable: bool) { }

    fn wake(&mut self) { unimplemented!(); }
}

/// A queue of events being executed in a loop on a single thread.
pub struct EventLoop {
//    daemons: TaskSetImpl,
    event_port: RefCell<io::MioEventPort>,
    _running: bool,
    _last_runnable_state: bool,
    events: RefCell<handle_table::HandleTable<private::EventNode>>,
    head: private::EventHandle,
    tail: Cell<private::EventHandle>,
    depth_first_insertion_point: Cell<private::EventHandle>,
}

impl EventLoop {
    /// Creates an event loop for the current thread, panicking if one already exists. Runs the given
    /// closure and then drops the event loop.
    pub fn top_level<F>(main: F) -> Result<(), Box<::std::error::Error>>
        where F: FnOnce(&WaitScope) -> Result<(), Box<::std::error::Error>>
    {
        let mut events = handle_table::HandleTable::<private::EventNode>::new();
        let dummy = private::EventNode { event: None, next: None, prev: None };
        let head_handle = private::EventHandle(events.push(dummy));

        EVENT_LOOP.with(move |maybe_event_loop| {
            let event_loop = EventLoop {
                event_port: RefCell::new(io::MioEventPort::new().unwrap()),
                _running: false,
                _last_runnable_state: false,
                events: RefCell::new(events),
                head: head_handle,
                tail: Cell::new(head_handle),
                depth_first_insertion_point: Cell::new(head_handle), // insert after this node
            };

            assert!(maybe_event_loop.borrow().is_none());
            *maybe_event_loop.borrow_mut() = Some(event_loop);
        });
        let wait_scope = WaitScope(::std::marker::PhantomData );

        let result = main(&wait_scope);

        EVENT_LOOP.with(move |maybe_event_loop| {
            *maybe_event_loop.borrow_mut() = None;
        });

        return result;
    }

    fn arm_depth_first(&self, event_handle: private::EventHandle) {

        let insertion_node_next = self.events.borrow()[self.depth_first_insertion_point.get().0].next;

        match insertion_node_next {
            Some(next_handle) => {
                self.events.borrow_mut()[next_handle.0].prev = Some(event_handle);
                self.events.borrow_mut()[event_handle.0].next = Some(next_handle);
            }
            None => {
                self.tail.set(event_handle);
            }
        }

        self.events.borrow_mut()[event_handle.0].prev = Some(self.depth_first_insertion_point.get());
        self.events.borrow_mut()[self.depth_first_insertion_point.get().0].next = Some(event_handle);
        self.depth_first_insertion_point.set(event_handle);
    }

    fn arm_breadth_first(&self, event_handle: private::EventHandle) {
        let events = &mut *self.events.borrow_mut();
        events[self.tail.get().0].next = Some(event_handle);
        events[event_handle.0].prev = Some(self.tail.get());
        self.tail.set(event_handle);
    }

    /// Runs the event loop for `max_turn_count` turns or until there is nothing left to be done,
    /// whichever comes first. This never calls the `EventPort`'s `sleep()` or `poll()`. It will
    /// call the `EventPort`'s `set_runnable(false)` if the queue becomes empty.
    fn _run(&mut self, max_turn_count: u32) {
        self._running = true;

        for _ in 0..max_turn_count {
            if !self.turn() {
                break;
            }
        }
    }

    /// Runs the event loop for a single step.
    fn turn(&self) -> bool {

        let event_handle = match self.events.borrow()[self.head.0].next {
            None => return false,
            Some(event_handle) => { event_handle }
        };
        self.depth_first_insertion_point.set(event_handle);

        let mut event = ::std::mem::replace(&mut self.events.borrow_mut()[event_handle.0].event, None)
            .expect("No event to fire?");
        let _dropper = event.fire();

        let maybe_next = self.events.borrow()[event_handle.0].next;
        self.events.borrow_mut()[self.head.0].next = maybe_next;
        match maybe_next {
            Some(e) => {
                self.events.borrow_mut()[e.0].prev = Some(self.head);
            }
            None => {}
        }

        self.events.borrow_mut()[event_handle.0].next = None;
        self.events.borrow_mut()[event_handle.0].prev = None;

        if self.tail.get() == event_handle {
            self.tail.set(self.head);
        }

        self.depth_first_insertion_point.set(self.head);
        return true;
    }
}

/// A callback that can be used to fulfill or reject a promise.
pub trait PromiseFulfiller<T, E> where T: 'static, E: 'static, E: From<Forced> {
    fn fulfill(self: Box<Self>, value: T);
    fn reject(self: Box<Self>, error: E);
}

/// Creates a new promise/fulfiller pair.
pub fn new_promise_and_fulfiller<T, E>() -> (Promise<T, E>, Box<PromiseFulfiller<T, E>>)
    where T: 'static,
          E: 'static + From<Forced>
{
    let result = ::std::rc::Rc::new(::std::cell::RefCell::new(PromiseAndFulfillerHub::new()));
    let result_promise: Promise<T, E> = Promise { node: Box::new(result.clone())};
    (result_promise, Box::new(result))
}

/// Holds a collection of `Promise<()>`s and ensures that each executes to completion.
/// Destroying a TaskSet automatically cancels all of its unfinished promises.
pub struct TaskSet {
    task_set_impl: Rc<RefCell<private::TaskSetImpl>>,
}

impl TaskSet {
    pub fn new(error_handler: Box<ErrorHandler>) -> TaskSet {
        TaskSet { task_set_impl : Rc::new(RefCell::new(private::TaskSetImpl::new(error_handler))) }
    }

    pub fn add(&mut self, promise: Promise<(), Box<::std::error::Error>>) {
        private::TaskSetImpl::add(self.task_set_impl.clone(), promise.node);
    }
}

/// A callback to be invoked when a task in a `TaskSet` fails.
pub trait ErrorHandler {
    fn task_failed(&mut self, error: Box<::std::error::Error>);
}

/// Transforms a vector of promises into a promise for a vector.
pub fn join_promises<T, E>(promises: Vec<Promise<T, E>>) -> Promise<Vec<T>, E>
{
    let nodes = promises.into_iter().map(|p| { p.node }).collect();
    Promise { node: Box::new(private::promise_node::ArrayJoin::new(nodes)) }
}

impl From<Forced> for ::std::io::Error {
    fn from(_: Forced) -> ::std::io::Error {
        ::std::io::Error::new(::std::io::ErrorKind::Other, "forced unfulfilled promise")
    }
}

impl From<Forced> for Box<::std::error::Error> {
    fn from(_: Forced) -> Box<::std::error::Error> {
        ::std::io::Error::new(::std::io::ErrorKind::Other, "forced unfulfilled promise").into()
    }
}
<commit_msg>fix typo<commit_after>// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

//! A library providing high-level abstractions for event loop concurrency,
//! heavily borrowing ideas from [KJ](https://capnproto.org/cxxrpc.html#kj-concurrency-framework).
//! Allows for coordination of asynchronous tasks using [promises](struct.Promise.html) as
//! a basic building block.

extern crate mio;
extern crate nix;

use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::result::Result;
use private::{promise_node, Event, BoolEvent, PromiseAndFulfillerHub,
              EVENT_LOOP, with_current_event_loop, PromiseNode};

pub mod io;

mod private;
mod handle_table;

pub struct Forced;

/// A computation that might eventually resolve to a value of type `T` or to an error
///  of type `E`.
pub struct Promise<T, E> where T: 'static, E: 'static {
    node: Box<PromiseNode<T, E>>,
}

impl <T, E> Promise <T, E> {
    /// Chains further computation to be executed once the promise resolves.
    /// When the promise is fulfilled or rejected, invokes `func` on its result.
    ///
    /// If the returned promise is dropped before the chained computation runs, the chained
    /// computation will be cancelled.
    ///
    /// Always returns immediately, even if the promise is already resolved. The earliest that
    /// `func` might be invoked is during the next `turn()` of the event loop.
    pub fn then_else<F, R, E1>(self, func: F) -> Promise<R, E1>
        where F: 'static,
              F: FnOnce(Result<T, E>) -> Result<Promise<R, E1>, E1>,
              R: 'static
    {
        let intermediate = Box::new(promise_node::Transform::new(self.node, func));
        Promise { node: Box::new(promise_node::Chain::new(intermediate)) }
    }

    /// Calls `then_else()` with a default error handler that simply propagates all errors.
    pub fn then<F, R>(self, func: F) -> Promise<R, E>
        where F: 'static,
              F: FnOnce(T) -> Result<Promise<R, E>, E>,
              R: 'static,
    {
        self.then_else(|r| { match r { Ok(v) => func(v), Err(e) => Err(e) } })
    }

    /// Like then_else() but for a `func` that returns a direct value rather than a promise.
    pub fn map_else<F, R, E1>(self, func: F) -> Promise<R, E1>
        where F: 'static,
              F: FnOnce(Result<T, E>) -> Result<R, E1>,
              R: 'static,
              E1: 'static
    {
        Promise { node: Box::new(promise_node::Transform::new(self.node, func)) }
    }

    /// Calls `map_else()` with a default error handler that simple propagates all errors.
    pub fn map<F, R>(self, func: F) -> Promise<R, E>
        where F: 'static,
              F: FnOnce(T) -> Result<R, E>,
              R: 'static
    {
        self.map_else(|r| { match r { Ok(v) => func(v), Err(e) =>  Err(e) } } )
    }

    /// Transforms the error branch of the promise.
    pub fn map_err<E1, F>(self, func: F) -> Promise<T, E1>
        where F: 'static,
              F: FnOnce(E) -> E1
    {
        self.map_else(|r| { match r { Ok(v) => Ok(v), Err(e) =>  Err(func(e)) } } )
    }

    /// Maps errors into a more general type.
    pub fn lift<E1>(self) -> Promise<T, E1> where E: Into<E1> {
        self.map_err(|e| e.into())
    }

    /// Cancels the promise, returning its value if it has already been fulfilled. If the promise has not
    /// already been fulfilled, the result must be an Err.
    pub fn force(self) -> Result<T, E> {
        self.node.force()
    }

    /// Returns a new promise that resolves when either `self` or `other` resolves. The promise that
    /// doesn't resolve first is cancelled.
    pub fn exclusive_join(self, other: Promise<T, E>) -> Promise<T, E> {
        Promise { node: Box::new(private::promise_node::ExclusiveJoin::new(self.node, other.node)) }
    }

    /// Creates a new promise that has already been fulfilled.
    pub fn fulfilled(value: T) -> Promise<T, E> {
        Promise { node: Box::new(promise_node::Immediate::new(Ok(value))) }
    }

    /// Creates a new promise that has already been rejected with the given error.
    pub fn rejected(error: E) -> Promise<T, E> {
        Promise { node: Box::new(promise_node::Immediate::new(Err(error))) }
    }

    /// Runs the event loop until the promise is fulfilled.
    ///
    /// The `WaitScope` argument ensures that `wait()` can only be called at the top level of a program.
    /// Waiting within event callbacks is disallowed.
    pub fn wait(mut self, _wait_scope: &WaitScope) -> Result<T, E> {
        with_current_event_loop(move |event_loop| {
            let fired = ::std::rc::Rc::new(::std::cell::Cell::new(false));
            let done_event = BoolEvent::new(fired.clone());
            let (handle, _dropper) = private::EventHandle::new();
            handle.set(Box::new(done_event));
            self.node.on_ready(handle);

            //event_loop.running = true;

            while !fired.get() {
                if !event_loop.turn() {
                    // No events in the queue.
                    event_loop.event_port.borrow_mut().wait();
                }
            }

            self.node.get()
        })
    }
}

/// A scope in which asynchronous programming can occur. Corresponds to the top level scope
/// of some event loop.
pub struct WaitScope(::std::marker::PhantomData<*mut u8>); // impl !Sync for WaitScope {}

/// Interface between an `EventLoop` and events originating from outside of the loop's thread.
trait EventPort {
    /// Waits for an external event to arrive, sleeping if necessary.
    /// Returns true if wake() has been called from another thread.
    fn wait(&mut self) -> bool;

    /// Checks whether any external events have arrived, but does not sleep.
    /// Returns true if wake() has been called from another thread.
    fn poll(&mut self) -> bool;

    /// Called to notify the `EventPort` when the `EventLoop` has work to do; specifically when it
    /// transitions from empty -> runnable or runnable -> empty. This is typically useful when
    /// integrating with an external event loop; if the loop is currently runnable then you should
    /// arrange to call run() on it soon. The default implementation does nothing.
    fn set_runnable(&mut self, _runnable: bool) { }

    fn wake(&mut self) { unimplemented!(); }
}

/// A queue of events being executed in a loop on a single thread.
pub struct EventLoop {
//    daemons: TaskSetImpl,
    event_port: RefCell<io::MioEventPort>,
    _running: bool,
    _last_runnable_state: bool,
    events: RefCell<handle_table::HandleTable<private::EventNode>>,
    head: private::EventHandle,
    tail: Cell<private::EventHandle>,
    depth_first_insertion_point: Cell<private::EventHandle>,
}

impl EventLoop {
    /// Creates an event loop for the current thread, panicking if one already exists. Runs the given
    /// closure and then drops the event loop.
    pub fn top_level<F>(main: F) -> Result<(), Box<::std::error::Error>>
        where F: FnOnce(&WaitScope) -> Result<(), Box<::std::error::Error>>
    {
        let mut events = handle_table::HandleTable::<private::EventNode>::new();
        let dummy = private::EventNode { event: None, next: None, prev: None };
        let head_handle = private::EventHandle(events.push(dummy));

        EVENT_LOOP.with(move |maybe_event_loop| {
            let event_loop = EventLoop {
                event_port: RefCell::new(io::MioEventPort::new().unwrap()),
                _running: false,
                _last_runnable_state: false,
                events: RefCell::new(events),
                head: head_handle,
                tail: Cell::new(head_handle),
                depth_first_insertion_point: Cell::new(head_handle), // insert after this node
            };

            assert!(maybe_event_loop.borrow().is_none());
            *maybe_event_loop.borrow_mut() = Some(event_loop);
        });
        let wait_scope = WaitScope(::std::marker::PhantomData );

        let result = main(&wait_scope);

        EVENT_LOOP.with(move |maybe_event_loop| {
            *maybe_event_loop.borrow_mut() = None;
        });

        return result;
    }

    fn arm_depth_first(&self, event_handle: private::EventHandle) {

        let insertion_node_next = self.events.borrow()[self.depth_first_insertion_point.get().0].next;

        match insertion_node_next {
            Some(next_handle) => {
                self.events.borrow_mut()[next_handle.0].prev = Some(event_handle);
                self.events.borrow_mut()[event_handle.0].next = Some(next_handle);
            }
            None => {
                self.tail.set(event_handle);
            }
        }

        self.events.borrow_mut()[event_handle.0].prev = Some(self.depth_first_insertion_point.get());
        self.events.borrow_mut()[self.depth_first_insertion_point.get().0].next = Some(event_handle);
        self.depth_first_insertion_point.set(event_handle);
    }

    fn arm_breadth_first(&self, event_handle: private::EventHandle) {
        let events = &mut *self.events.borrow_mut();
        events[self.tail.get().0].next = Some(event_handle);
        events[event_handle.0].prev = Some(self.tail.get());
        self.tail.set(event_handle);
    }

    /// Runs the event loop for `max_turn_count` turns or until there is nothing left to be done,
    /// whichever comes first. This never calls the `EventPort`'s `sleep()` or `poll()`. It will
    /// call the `EventPort`'s `set_runnable(false)` if the queue becomes empty.
    fn _run(&mut self, max_turn_count: u32) {
        self._running = true;

        for _ in 0..max_turn_count {
            if !self.turn() {
                break;
            }
        }
    }

    /// Runs the event loop for a single step.
    fn turn(&self) -> bool {

        let event_handle = match self.events.borrow()[self.head.0].next {
            None => return false,
            Some(event_handle) => { event_handle }
        };
        self.depth_first_insertion_point.set(event_handle);

        let mut event = ::std::mem::replace(&mut self.events.borrow_mut()[event_handle.0].event, None)
            .expect("No event to fire?");
        let _dropper = event.fire();

        let maybe_next = self.events.borrow()[event_handle.0].next;
        self.events.borrow_mut()[self.head.0].next = maybe_next;
        match maybe_next {
            Some(e) => {
                self.events.borrow_mut()[e.0].prev = Some(self.head);
            }
            None => {}
        }

        self.events.borrow_mut()[event_handle.0].next = None;
        self.events.borrow_mut()[event_handle.0].prev = None;

        if self.tail.get() == event_handle {
            self.tail.set(self.head);
        }

        self.depth_first_insertion_point.set(self.head);
        return true;
    }
}

/// A callback that can be used to fulfill or reject a promise.
pub trait PromiseFulfiller<T, E> where T: 'static, E: 'static, E: From<Forced> {
    fn fulfill(self: Box<Self>, value: T);
    fn reject(self: Box<Self>, error: E);
}

/// Creates a new promise/fulfiller pair.
pub fn new_promise_and_fulfiller<T, E>() -> (Promise<T, E>, Box<PromiseFulfiller<T, E>>)
    where T: 'static,
          E: 'static + From<Forced>
{
    let result = ::std::rc::Rc::new(::std::cell::RefCell::new(PromiseAndFulfillerHub::new()));
    let result_promise: Promise<T, E> = Promise { node: Box::new(result.clone())};
    (result_promise, Box::new(result))
}

/// Holds a collection of `Promise<()>`s and ensures that each executes to completion.
/// Destroying a TaskSet automatically cancels all of its unfinished promises.
pub struct TaskSet {
    task_set_impl: Rc<RefCell<private::TaskSetImpl>>,
}

impl TaskSet {
    pub fn new(error_handler: Box<ErrorHandler>) -> TaskSet {
        TaskSet { task_set_impl : Rc::new(RefCell::new(private::TaskSetImpl::new(error_handler))) }
    }

    pub fn add(&mut self, promise: Promise<(), Box<::std::error::Error>>) {
        private::TaskSetImpl::add(self.task_set_impl.clone(), promise.node);
    }
}

/// A callback to be invoked when a task in a `TaskSet` fails.
pub trait ErrorHandler {
    fn task_failed(&mut self, error: Box<::std::error::Error>);
}

/// Transforms a vector of promises into a promise for a vector.
pub fn join_promises<T, E>(promises: Vec<Promise<T, E>>) -> Promise<Vec<T>, E>
{
    let nodes = promises.into_iter().map(|p| { p.node }).collect();
    Promise { node: Box::new(private::promise_node::ArrayJoin::new(nodes)) }
}

impl From<Forced> for ::std::io::Error {
    fn from(_: Forced) -> ::std::io::Error {
        ::std::io::Error::new(::std::io::ErrorKind::Other, "forced unfulfilled promise")
    }
}

impl From<Forced> for Box<::std::error::Error> {
    fn from(_: Forced) -> Box<::std::error::Error> {
        ::std::io::Error::new(::std::io::ErrorKind::Other, "forced unfulfilled promise").into()
    }
}
<|endoftext|>


<commit_before>#![feature(box_syntax)]
#![feature(zero_one)]

pub mod expr;

use std::fmt;
use expr::NumType;

pub use expr::{Expr, Condition, ExprError};

/// Used to name symbols and variables.
pub trait Alphabet: fmt::Display + fmt::Debug + Eq + PartialEq + Clone {}

impl Alphabet for &'static str {}
impl Alphabet for char {}

/// A symbol whose arguments are all constant values.
#[derive(Clone, Eq, PartialEq)]
pub struct ConstSymbol<A: Alphabet, T: NumType> {
    pub symbol: A,
    pub args: Vec<T>,
}

impl<A:Alphabet, T:NumType> ConstSymbol<A, T> {
    pub fn new(symbol: A) -> ConstSymbol<A, T> {
        ConstSymbol {
            symbol: symbol,
            args: vec![],
        }
    }

    pub fn new_parametric(symbol: A, args: Vec<T>) -> ConstSymbol<A, T> {
        ConstSymbol {
            symbol: symbol,
            args: args,
        }
    }
}

impl<A:Alphabet, T:NumType> fmt::Debug for ConstSymbol<A, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "({}", self.symbol));
        for arg in self.args.iter() {
            try!(write!(f, " {:?}", arg));
        }

        write!(f, ")")
    }
}

/// A symbol (may contain non-constant expressions)
#[derive(Clone)]
pub struct Symbol<A: Alphabet, T: NumType> {
    symbol: A,
    exprs: Vec<Expr<T>>,
}

impl<A:Alphabet, T:NumType> fmt::Debug for Symbol<A, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "({}", self.symbol));
        for expr in self.exprs.iter() {
            try!(write!(f, " {:?}", expr));
        }

        write!(f, ")")
    }
}

impl<A:Alphabet, T:NumType> Symbol<A, T> {
    pub fn new(symbol: A) -> Symbol<A, T> {
        Symbol {
            symbol: symbol,
            exprs: vec![],
        }
    }

    pub fn new_parametric(symbol: A, exprs: Vec<Expr<T>>) -> Symbol<A, T> {
        Symbol {
            symbol: symbol,
            exprs: exprs,
        }
    }

    pub fn evaluate(&self, args: &[T]) -> Result<ConstSymbol<A, T>, ExprError> {
        let mut values = Vec::with_capacity(self.exprs.len());
        for expr in self.exprs.iter() {
            values.push(try!(expr.evaluate(args)));
        }
        assert!(values.len() == self.exprs.len());
        Ok(ConstSymbol {
            symbol: self.symbol.clone(),
            args: values,
        })
    }
}

/// A list of constant Symbols.
#[derive(Eq, PartialEq)]
pub struct ConstSymbolString<A: Alphabet, T: NumType>(pub Vec<ConstSymbol<A, T>>);

impl<A:Alphabet, T: NumType> fmt::Debug for ConstSymbolString<A, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for (i, sym) in self.0.iter().enumerate() {
            if i > 0 {
                try!(write!(f, " "));
            }
            try!(write!(f, "{:?}", sym));
        }
        Ok(())
    }
}

/// A list of Symbols.
pub struct SymbolString<A: Alphabet, T: NumType>(pub Vec<Symbol<A, T>>);

impl<A:Alphabet, T: NumType> fmt::Debug for SymbolString<A, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for (i, sym) in self.0.iter().enumerate() {
            if i > 0 {
                try!(write!(f, " "));
            }
            try!(write!(f, "{:?}", sym));
        }
        Ok(())
    }
}

impl<A:Alphabet, T:NumType> SymbolString<A, T> {
    pub fn evaluate(&self, args: &[T]) -> Result<ConstSymbolString<A, T>, ExprError> {
        let mut csyms = Vec::with_capacity(self.0.len());
        for sym in self.0.iter() {
            csyms.push(try!(sym.evaluate(args)));
        }
        assert!(csyms.len() == self.0.len());
        Ok(ConstSymbolString(csyms))
    }
}

#[derive(Debug)]
pub struct Rule<A: Alphabet, T: NumType> {
    pub symbol: A,
    pub condition: Condition<T>,
    pub successor: SymbolString<A, T>,
}

#[derive(Debug, Eq, PartialEq)]
pub enum RuleError {
    SymbolMismatch,
    ConditionFalse,
    ConditionFailed,
    ExprFailed(ExprError),
}

impl<A:Alphabet, T:NumType> Rule<A, T> {
    pub fn new(symbol: A, successor: SymbolString<A, T>) -> Rule<A, T> {
        Rule {
            symbol: symbol,
            condition: Condition::True,
            successor: successor,
        }
    }

    pub fn new_conditional(symbol: A,
                           successor: SymbolString<A, T>,
                           condition: Condition<T>)
                           -> Rule<A, T> {
        Rule {
            symbol: symbol,
            condition: condition,
            successor: successor,
        }
    }

    /// Apply the rule to the given constant symbol and if possible, produce
    /// a successor.
    pub fn apply(&self, csym: &ConstSymbol<A, T>) -> Result<ConstSymbolString<A, T>, RuleError> {
        if csym.symbol == self.symbol {
            match self.condition.evaluate(&csym.args) {
                Ok(true) => {
                    match self.successor.evaluate(&csym.args) {
                        Ok(csymstr) => Ok(csymstr),
                        Err(e) => Err(RuleError::ExprFailed(e)),
                    }
                }
                Ok(false) => {
                    Err(RuleError::ConditionFalse)
                }
                _ => {
                    Err(RuleError::ConditionFailed)
                }
            }
        } else {
            Err(RuleError::SymbolMismatch)
        }
    }
}

#[test]
fn test_rule_apply() {
    let p = Symbol::new_parametric("P", vec![Expr::Const(123u32)]);
    let rule = Rule::new("A", Condition::True, SymbolString(vec![p.clone()]));
    assert_eq!(Err(RuleError::SymbolMismatch),
               rule.apply(&ConstSymbol::new("P")));
    assert_eq!(Ok(ConstSymbolString(vec![ConstSymbol::new_parametric("P", vec![123u32])])),
               rule.apply(&ConstSymbol::new("A")));

    let rule = Rule::new("A", Condition::False, SymbolString(vec![p.clone()]));
    assert_eq!(Err(RuleError::ConditionFalse),
               rule.apply(&ConstSymbol::new("A")));
}

#[derive(Debug)]
pub struct System<A: Alphabet, T: NumType> {
    rules: Vec<Rule<A, T>>,
}

impl<A:Alphabet, T:NumType> System<A, T> {
    pub fn new() -> System<A, T> {
        System { rules: vec![] }
    }

    pub fn add_rule(&mut self, rule: Rule<A, T>) {
        self.rules.push(rule);
    }

    /// Apply first matching rule and return expanded successor.
    fn apply_first_rule(&self, csym: &ConstSymbol<A, T>) -> Option<ConstSymbolString<A, T>> {
        for rule in self.rules.iter() {
            if let Ok(successor) = rule.apply(csym) {
                return Some(successor);
            }
        }
        return None;
    }

    /// Apply in parallel the first matching rule to each symbol in the string.
    /// Returns the total number of rule applications.
    pub fn develop_step(&self,
                        axiom: &ConstSymbolString<A, T>)
                        -> (ConstSymbolString<A, T>, usize) {
        let mut expanded = Vec::new();
        let mut rule_applications = 0;

        for csym in axiom.0.iter() {
            match self.apply_first_rule(csym) {
                Some(successor) => {
                    expanded.extend(successor.0);
                    rule_applications += 1;
                    // XXX: Count rule applications of the matching rule.
                }
                None => {
                    expanded.push(csym.clone());
                }
            }
        }

        (ConstSymbolString(expanded), rule_applications)
    }

    /// Develop the system starting with `axiom` up to `max_iterations`. Return iteration count.
    pub fn develop(&self,
                   axiom: ConstSymbolString<A, T>,
                   max_iterations: usize)
                   -> (ConstSymbolString<A, T>, usize) {
        let mut current = axiom;

        for iter in 0..max_iterations {
            let (next, rule_applications) = self.develop_step(&current);
            if rule_applications == 0 {
                return (current, iter);
            }
            current = next;
        }
        return (current, max_iterations);
    }
}
<commit_msg>Fix tests<commit_after>#![feature(box_syntax)]
#![feature(zero_one)]

pub mod expr;

use std::fmt;
use expr::NumType;

pub use expr::{Expr, Condition, ExprError};

/// Used to name symbols and variables.
pub trait Alphabet: fmt::Display + fmt::Debug + Eq + PartialEq + Clone {}

impl Alphabet for &'static str {}
impl Alphabet for char {}

/// A symbol whose arguments are all constant values.
#[derive(Clone, Eq, PartialEq)]
pub struct ConstSymbol<A: Alphabet, T: NumType> {
    pub symbol: A,
    pub args: Vec<T>,
}

impl<A:Alphabet, T:NumType> ConstSymbol<A, T> {
    pub fn new(symbol: A) -> ConstSymbol<A, T> {
        ConstSymbol {
            symbol: symbol,
            args: vec![],
        }
    }

    pub fn new_parametric(symbol: A, args: Vec<T>) -> ConstSymbol<A, T> {
        ConstSymbol {
            symbol: symbol,
            args: args,
        }
    }
}

impl<A:Alphabet, T:NumType> fmt::Debug for ConstSymbol<A, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "({}", self.symbol));
        for arg in self.args.iter() {
            try!(write!(f, " {:?}", arg));
        }

        write!(f, ")")
    }
}

/// A symbol (may contain non-constant expressions)
#[derive(Clone)]
pub struct Symbol<A: Alphabet, T: NumType> {
    symbol: A,
    exprs: Vec<Expr<T>>,
}

impl<A:Alphabet, T:NumType> fmt::Debug for Symbol<A, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(f, "({}", self.symbol));
        for expr in self.exprs.iter() {
            try!(write!(f, " {:?}", expr));
        }

        write!(f, ")")
    }
}

impl<A:Alphabet, T:NumType> Symbol<A, T> {
    pub fn new(symbol: A) -> Symbol<A, T> {
        Symbol {
            symbol: symbol,
            exprs: vec![],
        }
    }

    pub fn new_parametric(symbol: A, exprs: Vec<Expr<T>>) -> Symbol<A, T> {
        Symbol {
            symbol: symbol,
            exprs: exprs,
        }
    }

    pub fn evaluate(&self, args: &[T]) -> Result<ConstSymbol<A, T>, ExprError> {
        let mut values = Vec::with_capacity(self.exprs.len());
        for expr in self.exprs.iter() {
            values.push(try!(expr.evaluate(args)));
        }
        assert!(values.len() == self.exprs.len());
        Ok(ConstSymbol {
            symbol: self.symbol.clone(),
            args: values,
        })
    }
}

/// A list of constant Symbols.
#[derive(Eq, PartialEq)]
pub struct ConstSymbolString<A: Alphabet, T: NumType>(pub Vec<ConstSymbol<A, T>>);

impl<A:Alphabet, T: NumType> fmt::Debug for ConstSymbolString<A, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for (i, sym) in self.0.iter().enumerate() {
            if i > 0 {
                try!(write!(f, " "));
            }
            try!(write!(f, "{:?}", sym));
        }
        Ok(())
    }
}

/// A list of Symbols.
pub struct SymbolString<A: Alphabet, T: NumType>(pub Vec<Symbol<A, T>>);

impl<A:Alphabet, T: NumType> fmt::Debug for SymbolString<A, T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for (i, sym) in self.0.iter().enumerate() {
            if i > 0 {
                try!(write!(f, " "));
            }
            try!(write!(f, "{:?}", sym));
        }
        Ok(())
    }
}

impl<A:Alphabet, T:NumType> SymbolString<A, T> {
    pub fn evaluate(&self, args: &[T]) -> Result<ConstSymbolString<A, T>, ExprError> {
        let mut csyms = Vec::with_capacity(self.0.len());
        for sym in self.0.iter() {
            csyms.push(try!(sym.evaluate(args)));
        }
        assert!(csyms.len() == self.0.len());
        Ok(ConstSymbolString(csyms))
    }
}

#[derive(Debug)]
pub struct Rule<A: Alphabet, T: NumType> {
    pub symbol: A,
    pub condition: Condition<T>,
    pub successor: SymbolString<A, T>,
}

#[derive(Debug, Eq, PartialEq)]
pub enum RuleError {
    SymbolMismatch,
    ConditionFalse,
    ConditionFailed,
    ExprFailed(ExprError),
}

impl<A:Alphabet, T:NumType> Rule<A, T> {
    pub fn new(symbol: A, successor: SymbolString<A, T>) -> Rule<A, T> {
        Rule {
            symbol: symbol,
            condition: Condition::True,
            successor: successor,
        }
    }

    pub fn new_conditional(symbol: A,
                           successor: SymbolString<A, T>,
                           condition: Condition<T>)
                           -> Rule<A, T> {
        Rule {
            symbol: symbol,
            condition: condition,
            successor: successor,
        }
    }

    /// Apply the rule to the given constant symbol and if possible, produce
    /// a successor.
    pub fn apply(&self, csym: &ConstSymbol<A, T>) -> Result<ConstSymbolString<A, T>, RuleError> {
        if csym.symbol == self.symbol {
            match self.condition.evaluate(&csym.args) {
                Ok(true) => {
                    match self.successor.evaluate(&csym.args) {
                        Ok(csymstr) => Ok(csymstr),
                        Err(e) => Err(RuleError::ExprFailed(e)),
                    }
                }
                Ok(false) => {
                    Err(RuleError::ConditionFalse)
                }
                _ => {
                    Err(RuleError::ConditionFailed)
                }
            }
        } else {
            Err(RuleError::SymbolMismatch)
        }
    }
}

#[test]
fn test_rule_apply() {
    let p = Symbol::new_parametric("P", vec![Expr::Const(123u32)]);
    let rule = Rule::new("A", SymbolString(vec![p.clone()]));
    assert_eq!(Err(RuleError::SymbolMismatch),
               rule.apply(&ConstSymbol::new("P")));
    assert_eq!(Ok(ConstSymbolString(vec![ConstSymbol::new_parametric("P", vec![123u32])])),
               rule.apply(&ConstSymbol::new("A")));

    let rule = Rule::new_conditional("A", SymbolString(vec![p.clone()]), Condition::False);
    assert_eq!(Err(RuleError::ConditionFalse),
               rule.apply(&ConstSymbol::new("A")));
}

#[derive(Debug)]
pub struct System<A: Alphabet, T: NumType> {
    rules: Vec<Rule<A, T>>,
}

impl<A:Alphabet, T:NumType> System<A, T> {
    pub fn new() -> System<A, T> {
        System { rules: vec![] }
    }

    pub fn add_rule(&mut self, rule: Rule<A, T>) {
        self.rules.push(rule);
    }

    /// Apply first matching rule and return expanded successor.
    fn apply_first_rule(&self, csym: &ConstSymbol<A, T>) -> Option<ConstSymbolString<A, T>> {
        for rule in self.rules.iter() {
            if let Ok(successor) = rule.apply(csym) {
                return Some(successor);
            }
        }
        return None;
    }

    /// Apply in parallel the first matching rule to each symbol in the string.
    /// Returns the total number of rule applications.
    pub fn develop_step(&self,
                        axiom: &ConstSymbolString<A, T>)
                        -> (ConstSymbolString<A, T>, usize) {
        let mut expanded = Vec::new();
        let mut rule_applications = 0;

        for csym in axiom.0.iter() {
            match self.apply_first_rule(csym) {
                Some(successor) => {
                    expanded.extend(successor.0);
                    rule_applications += 1;
                    // XXX: Count rule applications of the matching rule.
                }
                None => {
                    expanded.push(csym.clone());
                }
            }
        }

        (ConstSymbolString(expanded), rule_applications)
    }

    /// Develop the system starting with `axiom` up to `max_iterations`. Return iteration count.
    pub fn develop(&self,
                   axiom: ConstSymbolString<A, T>,
                   max_iterations: usize)
                   -> (ConstSymbolString<A, T>, usize) {
        let mut current = axiom;

        for iter in 0..max_iterations {
            let (next, rule_applications) = self.develop_step(&current);
            if rule_applications == 0 {
                return (current, iter);
            }
            current = next;
        }
        return (current, max_iterations);
    }
}
<|endoftext|>


<commit_before>#![feature(test)]

use std::mem;
use std::ops::Deref;

mod voxel_bounds;

pub use voxel_bounds::*;

#[derive(Debug)]
pub struct VoxelTree<T> {
  /// The log_2 of the tree's size.
  lg_size: u8,
  /// Force the top level to always be branches;
  /// it saves a branch in the grow logic.
  contents: Branches<T>,
}

#[derive(Debug)]
#[repr(C)]
pub struct Branches<T> {
  // xyz ordering

  lll: TreeBody<T>,
  llh: TreeBody<T>,
  lhl: TreeBody<T>,
  lhh: TreeBody<T>,
  hll: TreeBody<T>,
  hlh: TreeBody<T>,
  hhl: TreeBody<T>,
  hhh: TreeBody<T>,
}

impl<T> Branches<T> {
  pub fn empty() -> Branches<T> {
    Branches {
      lll: TreeBody::Empty,
      llh: TreeBody::Empty,
      lhl: TreeBody::Empty,
      lhh: TreeBody::Empty,
      hll: TreeBody::Empty,
      hlh: TreeBody::Empty,
      hhl: TreeBody::Empty,
      hhh: TreeBody::Empty,
    }
  }
}

/// The main, recursive, tree-y part of the `VoxelTree`.
#[derive(Debug)]
pub enum TreeBody<T> {
  Empty,
  Leaf(T),
  Branch(Box<Branches<T>>),
}

impl<T> VoxelTree<T> {
  pub fn new() -> VoxelTree<T> {
    VoxelTree {
      lg_size: 0,
      contents: Branches::empty(),
    }
  }

  /// Is this voxel (non-strictly) within an origin-centered voxel with
  /// size `2^lg_size`?
  pub fn contains_bounds(&self, voxel: VoxelBounds) -> bool {
    if voxel.lg_size < 0 {
      return true
    }

    let high = (1 << self.lg_size) >> voxel.lg_size;
    let low = -high;

    // TODO: Should these be strict?
    if voxel.x <= low || voxel.y <= low || voxel.z <= low {
      return false
    }

    true
    && (voxel.x + 1) <= high
    && (voxel.y + 1) <= high
    && (voxel.z + 1) <= high
  }

  #[inline(always)]
  fn get_branch<'a, ChooseBranch>(
    branches: &'a Branches<T>,
    mut choose_branch: ChooseBranch,
    x: i32, y: i32, z: i32,
  ) -> &'a TreeBody<T>
    where ChooseBranch: FnMut(i32) -> bool,
  {
    // TODO: Make this branch-free by constructing the bools into an offset.
    match (choose_branch(x), choose_branch(y), choose_branch(z)) {
      (false, false, false) => &branches.lll,
      (false, false, true ) => &branches.llh,
      (false, true , false) => &branches.lhl,
      (false, true , true ) => &branches.lhh,
      (true , false, false) => &branches.hll,
      (true , false, true ) => &branches.hlh,
      (true , true , false) => &branches.hhl,
      (true , true , true ) => &branches.hhh,
    }
  }

  #[inline(always)]
  fn get_branch_mut<'a, ChooseBranch>(
    branches: &'a mut Branches<T>,
    mut choose_branch: ChooseBranch,
    x: i32, y: i32, z: i32,
  ) -> &'a mut TreeBody<T>
    where ChooseBranch: FnMut(i32) -> bool,
  {
    // TODO: Make this branch-free by constructing the bools into an offset.
    match (choose_branch(x), choose_branch(y), choose_branch(z)) {
      (false, false, false) => &mut branches.lll,
      (false, false, true ) => &mut branches.llh,
      (false, true , false) => &mut branches.lhl,
      (false, true , true ) => &mut branches.lhh,
      (true , false, false) => &mut branches.hll,
      (true , false, true ) => &mut branches.hlh,
      (true , true , false) => &mut branches.hhl,
      (true , true , true ) => &mut branches.hhh,
    }
  }

  /// Ensure that this tree can hold the provided voxel.
  pub fn grow_to_hold(&mut self, voxel: VoxelBounds) {
    while !self.contains_bounds(voxel) {
      // Double the bounds in every direction.
      self.lg_size += 1;

      // Pull out `self.contents` so we can move out of it.
      let contents = mem::replace(&mut self.contents, Branches::empty());

      // We re-construct the tree with bounds twice the size (but still centered
      // around the origin) by deconstructing the top level of branches,
      // creating a new doubly-sized top level, and moving the old branches back
      // in as the new top level's children. e.g. in 2D:
      //
      //                      ---------------------------
      //                      |     |     |0|     |     |
      //                      |     |     |0|     |     |
      // ---------------      ------------|0|------------
      // |  1  |0|  2  |      |     |  1  |0|  2  |     |
      // |     |0|     |      |     |     |0|     |     |
      // |------0------|      |------------0------------|
      // 000000000000000  ==> |0000000000000000000000000|
      // |------0------|      |------------0------------|
      // |     |0|     |      |     |     |0|     |     |
      // |  3  |0|  4  |      |     |  3  |0|  4  |     |
      // ---------------      |------------0------------|
      //                      |     |     |0|     |     |
      //                      |     |     |0|     |     |
      //                      ---------------------------

      macro_rules! at(
        ($c_idx:ident, $b_idx:ident) => {{
          let mut branches = Branches::empty();
          branches.$b_idx = contents.$c_idx;
          TreeBody::Branch(Box::new(branches))
        }}
      );

      self.contents =
        Branches {
          lll: at!(lll, hhh),
          llh: at!(llh, hhl),
          lhl: at!(lhl, hlh),
          lhh: at!(lhh, hll),
          hll: at!(hll, lhh),
          hlh: at!(hlh, lhl),
          hhl: at!(hhl, llh),
          hhh: at!(hhh, lll),
        };
    }
  }

  fn find_mask(&self, voxel: VoxelBounds) -> i32 {
    // When we compare the voxel position to octree bounds to choose subtrees
    // for insertion, we'll be comparing voxel position to values of 2^n and
    // -2^n, so we can just use the position bits to branch directly.
    // This actually works for negative values too, without much wrestling:
    // we need to branch on the sign bit up front, but after that, two's
    // complement magic means the branching on bits works regardless of sign.

    let mut mask = (1 << self.lg_size) >> 1;

    // Shift everything by the voxel's lg_size, so we can compare the mask to 0
    // to know whether we're done.
    if voxel.lg_size >= 0 {
      mask = mask >> voxel.lg_size;
    } else {
      // TODO: Check for overflow.
      mask = mask << -voxel.lg_size;
    }

    mask
  }

  fn mut_find<'a, Step, E>(
    &'a mut self,
    voxel: VoxelBounds,
    mut step: Step,
  ) -> Result<&'a mut TreeBody<T>, E> where
    Step: FnMut(&'a mut TreeBody<T>) -> Result<&'a mut Branches<T>, E>,
  {
    let mut mask = self.find_mask(voxel);
    let mut branches = &mut self.contents;

    macro_rules! iter(
      ($mask:expr, $step:block) => {{
        let branches_temp = branches;
        let branch = VoxelTree::get_branch_mut(branches_temp, $mask, voxel.x, voxel.y, voxel.z);

        $step;
        // We've reached the voxel.
        if mask == 0 {
          return Ok(branch)
        }

        branches = try!(step(branch));
      }}
    );

    iter!(|x| x >= 0, {});

    loop {
      iter!(
        |x| { (x & mask) != 0 },
        // Branch through half this size next time.
        { mask = mask >> 1; }
      );
    }
  }

  fn find<'a, Step, E>(
    &'a self,
    voxel: VoxelBounds,
    mut step: Step,
  ) -> Result<&'a TreeBody<T>, E> where
    Step: FnMut(&'a TreeBody<T>) -> Result<&'a Branches<T>, E>,
  {
    let mut mask = self.find_mask(voxel);
    let mut branches = &self.contents;

    macro_rules! iter(
      ($mask:expr, $step:block) => {{
        let branches_temp = branches;
        let branch = VoxelTree::get_branch(branches_temp, $mask, voxel.x, voxel.y, voxel.z);

        $step;
        // We've reached the voxel.
        if mask == 0 {
          return Ok(branch)
        }

        branches = try!(step(branch));
      }}
    );

    iter!(|x| x >= 0, {});

    loop {
      iter!(
        |x| { (x & mask) != 0 },
        // Branch through half this size next time.
        { mask = mask >> 1; }
      );
    }
  }

  /// Find a voxel inside this tree.
  /// If it doesn't exist, it will be created as empty.
  pub fn get_mut_or_create<'a>(&'a mut self, voxel: VoxelBounds) -> &'a mut TreeBody<T> {
    self.grow_to_hold(voxel);
    let branch: Result<_, ()> =
      self.mut_find(voxel, |branch| { Ok(VoxelTree::get_mut_or_create_step(branch)) });
    branch.unwrap()
  }

  fn get_mut_or_create_step<'a>(
    branch: &'a mut TreeBody<T>,
  ) -> &'a mut Branches<T> {
    // "Step down" the tree.
    match *branch {
      // Branches; we can go straight to the branching logic.
      TreeBody::Branch(ref mut b) => b,

      // Otherwise, keep going, but we need to insert a voxel inside the
      // space occupied by the current branch.

      TreeBody::Empty => {
        // Replace this branch with 8 empty sub-branches - who's gonna notice?
        *branch = TreeBody::Branch(Box::new(Branches::empty()));

        match *branch {
          TreeBody::Branch(ref mut b) => b,
          _ => unreachable!(),
        }
      },
      TreeBody::Leaf(_) => {
        // Erase this leaf and replace it with 8 empty sub-branches.
        // This behavior is pretty debatable, but we need to do something,
        // and it's easier to debug accidentally replacing a big chunk
        // with a smaller one than to debug a nop.
        *branch = TreeBody::Branch(Box::new(Branches::empty()));

        match *branch {
          TreeBody::Branch(ref mut b) => b,
          _ => unreachable!(),
        }
      },
    }
  }

  /// Find a voxel inside this tree.
  pub fn get<'a>(&'a self, voxel: VoxelBounds) -> Option<&'a T> {
    if !self.contains_bounds(voxel) {
      return None
    }

    let get_step = |branch| {
      match branch {
        &TreeBody::Branch(ref branches) => Ok(branches.deref()),
        _ => Err(()),
      }
    };

    match self.find(voxel, get_step) {
      Ok(&TreeBody::Leaf(ref t)) => Some(t),
      _ => None,
    }
  }
}

#[cfg(test)]
mod tests {
  extern crate test;

  use super::{VoxelBounds, VoxelTree, TreeBody};

  #[test]
  fn simple_test() {
    let mut tree: VoxelTree<i32> = VoxelTree::new();
    *tree.get_mut_or_create(VoxelBounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
    *tree.get_mut_or_create(VoxelBounds::new(8, -8, 4, 0)) = TreeBody::Leaf(2);
    *tree.get_mut_or_create(VoxelBounds::new(2, 0, 4, 4)) = TreeBody::Leaf(3);
    *tree.get_mut_or_create(VoxelBounds::new(9, 0, 16, 2)) = TreeBody::Leaf(4);
    *tree.get_mut_or_create(VoxelBounds::new(9, 0, 16, 2)) = TreeBody::Leaf(5);

    assert_eq!(tree.get(VoxelBounds::new(1, 1, 1, 0)), Some(&1));
    assert_eq!(tree.get(VoxelBounds::new(8, -8, 4, 0)), Some(&2));
    assert_eq!(tree.get(VoxelBounds::new(9, 0, 16, 2)), Some(&5));

    assert_eq!(tree.get(VoxelBounds::new(2, 0, 4, 4)), None);
  }

  #[test]
  fn wrong_voxel_size_is_not_found() {
    let mut tree: VoxelTree<i32> = VoxelTree::new();
    *tree.get_mut_or_create(VoxelBounds::new(4, 4, -4, 1)) = TreeBody::Leaf(1);
    assert_eq!(tree.get(VoxelBounds::new(4, 4, -4, 0)), None);
    assert_eq!(tree.get(VoxelBounds::new(4, 4, -4, 2)), None);
  }

  #[test]
  fn grow_is_transparent() {
    let mut tree: VoxelTree<i32> = VoxelTree::new();
    *tree.get_mut_or_create(VoxelBounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
    tree.grow_to_hold(VoxelBounds::new(0, 0, 0, 1));
    tree.grow_to_hold(VoxelBounds::new(0, 0, 0, 2));
    tree.grow_to_hold(VoxelBounds::new(-32, 32, -128, 3));

    assert_eq!(tree.get(VoxelBounds::new(1, 1, 1, 0)), Some(&1));
  }

  #[bench]
  fn simple_inserts(bencher: &mut test::Bencher) {
    bencher.iter(|| {
      let mut tree: VoxelTree<i32> = VoxelTree::new();
      tree.grow_to_hold(VoxelBounds::new(0, 0, 0, 30));

      for i in -10..10 {
        *tree.get_mut_or_create(VoxelBounds::new(i, i, i, 0)) = TreeBody::Leaf(0);
      }

      test::black_box(tree);
    });
  }
}
<commit_msg>Fix benches.<commit_after>#![feature(test)]

use std::mem;
use std::ops::Deref;

mod voxel_bounds;

pub use voxel_bounds::*;

#[derive(Debug)]
pub struct VoxelTree<T> {
  /// The log_2 of the tree's size.
  lg_size: u8,
  /// Force the top level to always be branches;
  /// it saves a branch in the grow logic.
  contents: Branches<T>,
}

#[derive(Debug)]
#[repr(C)]
pub struct Branches<T> {
  // xyz ordering

  lll: TreeBody<T>,
  llh: TreeBody<T>,
  lhl: TreeBody<T>,
  lhh: TreeBody<T>,
  hll: TreeBody<T>,
  hlh: TreeBody<T>,
  hhl: TreeBody<T>,
  hhh: TreeBody<T>,
}

impl<T> Branches<T> {
  pub fn empty() -> Branches<T> {
    Branches {
      lll: TreeBody::Empty,
      llh: TreeBody::Empty,
      lhl: TreeBody::Empty,
      lhh: TreeBody::Empty,
      hll: TreeBody::Empty,
      hlh: TreeBody::Empty,
      hhl: TreeBody::Empty,
      hhh: TreeBody::Empty,
    }
  }
}

/// The main, recursive, tree-y part of the `VoxelTree`.
#[derive(Debug)]
pub enum TreeBody<T> {
  Empty,
  Leaf(T),
  Branch(Box<Branches<T>>),
}

impl<T> VoxelTree<T> {
  pub fn new() -> VoxelTree<T> {
    VoxelTree {
      lg_size: 0,
      contents: Branches::empty(),
    }
  }

  /// Is this voxel (non-strictly) within an origin-centered voxel with
  /// size `2^lg_size`?
  pub fn contains_bounds(&self, voxel: VoxelBounds) -> bool {
    if voxel.lg_size < 0 {
      return true
    }

    let high = (1 << self.lg_size) >> voxel.lg_size;
    let low = -high;

    // TODO: Should these be strict?
    if voxel.x <= low || voxel.y <= low || voxel.z <= low {
      return false
    }

    true
    && (voxel.x + 1) <= high
    && (voxel.y + 1) <= high
    && (voxel.z + 1) <= high
  }

  #[inline(always)]
  fn get_branch<'a, ChooseBranch>(
    branches: &'a Branches<T>,
    mut choose_branch: ChooseBranch,
    x: i32, y: i32, z: i32,
  ) -> &'a TreeBody<T>
    where ChooseBranch: FnMut(i32) -> bool,
  {
    // TODO: Make this branch-free by constructing the bools into an offset.
    match (choose_branch(x), choose_branch(y), choose_branch(z)) {
      (false, false, false) => &branches.lll,
      (false, false, true ) => &branches.llh,
      (false, true , false) => &branches.lhl,
      (false, true , true ) => &branches.lhh,
      (true , false, false) => &branches.hll,
      (true , false, true ) => &branches.hlh,
      (true , true , false) => &branches.hhl,
      (true , true , true ) => &branches.hhh,
    }
  }

  #[inline(always)]
  fn get_branch_mut<'a, ChooseBranch>(
    branches: &'a mut Branches<T>,
    mut choose_branch: ChooseBranch,
    x: i32, y: i32, z: i32,
  ) -> &'a mut TreeBody<T>
    where ChooseBranch: FnMut(i32) -> bool,
  {
    // TODO: Make this branch-free by constructing the bools into an offset.
    match (choose_branch(x), choose_branch(y), choose_branch(z)) {
      (false, false, false) => &mut branches.lll,
      (false, false, true ) => &mut branches.llh,
      (false, true , false) => &mut branches.lhl,
      (false, true , true ) => &mut branches.lhh,
      (true , false, false) => &mut branches.hll,
      (true , false, true ) => &mut branches.hlh,
      (true , true , false) => &mut branches.hhl,
      (true , true , true ) => &mut branches.hhh,
    }
  }

  /// Ensure that this tree can hold the provided voxel.
  pub fn grow_to_hold(&mut self, voxel: VoxelBounds) {
    while !self.contains_bounds(voxel) {
      // Double the bounds in every direction.
      self.lg_size += 1;

      // Pull out `self.contents` so we can move out of it.
      let contents = mem::replace(&mut self.contents, Branches::empty());

      // We re-construct the tree with bounds twice the size (but still centered
      // around the origin) by deconstructing the top level of branches,
      // creating a new doubly-sized top level, and moving the old branches back
      // in as the new top level's children. e.g. in 2D:
      //
      //                      ---------------------------
      //                      |     |     |0|     |     |
      //                      |     |     |0|     |     |
      // ---------------      ------------|0|------------
      // |  1  |0|  2  |      |     |  1  |0|  2  |     |
      // |     |0|     |      |     |     |0|     |     |
      // |------0------|      |------------0------------|
      // 000000000000000  ==> |0000000000000000000000000|
      // |------0------|      |------------0------------|
      // |     |0|     |      |     |     |0|     |     |
      // |  3  |0|  4  |      |     |  3  |0|  4  |     |
      // ---------------      |------------0------------|
      //                      |     |     |0|     |     |
      //                      |     |     |0|     |     |
      //                      ---------------------------

      macro_rules! at(
        ($c_idx:ident, $b_idx:ident) => {{
          let mut branches = Branches::empty();
          branches.$b_idx = contents.$c_idx;
          TreeBody::Branch(Box::new(branches))
        }}
      );

      self.contents =
        Branches {
          lll: at!(lll, hhh),
          llh: at!(llh, hhl),
          lhl: at!(lhl, hlh),
          lhh: at!(lhh, hll),
          hll: at!(hll, lhh),
          hlh: at!(hlh, lhl),
          hhl: at!(hhl, llh),
          hhh: at!(hhh, lll),
        };
    }
  }

  fn find_mask(&self, voxel: VoxelBounds) -> i32 {
    // When we compare the voxel position to octree bounds to choose subtrees
    // for insertion, we'll be comparing voxel position to values of 2^n and
    // -2^n, so we can just use the position bits to branch directly.
    // This actually works for negative values too, without much wrestling:
    // we need to branch on the sign bit up front, but after that, two's
    // complement magic means the branching on bits works regardless of sign.

    let mut mask = (1 << self.lg_size) >> 1;

    // Shift everything by the voxel's lg_size, so we can compare the mask to 0
    // to know whether we're done.
    if voxel.lg_size >= 0 {
      mask = mask >> voxel.lg_size;
    } else {
      // TODO: Check for overflow.
      mask = mask << -voxel.lg_size;
    }

    mask
  }

  fn mut_find<'a, Step, E>(
    &'a mut self,
    voxel: VoxelBounds,
    mut step: Step,
  ) -> Result<&'a mut TreeBody<T>, E> where
    Step: FnMut(&'a mut TreeBody<T>) -> Result<&'a mut Branches<T>, E>,
  {
    let mut mask = self.find_mask(voxel);
    let mut branches = &mut self.contents;

    macro_rules! iter(
      ($mask:expr, $step:block) => {{
        let branches_temp = branches;
        let branch = VoxelTree::get_branch_mut(branches_temp, $mask, voxel.x, voxel.y, voxel.z);

        $step;
        // We've reached the voxel.
        if mask == 0 {
          return Ok(branch)
        }

        branches = try!(step(branch));
      }}
    );

    iter!(|x| x >= 0, {});

    loop {
      iter!(
        |x| { (x & mask) != 0 },
        // Branch through half this size next time.
        { mask = mask >> 1; }
      );
    }
  }

  fn find<'a, Step, E>(
    &'a self,
    voxel: VoxelBounds,
    mut step: Step,
  ) -> Result<&'a TreeBody<T>, E> where
    Step: FnMut(&'a TreeBody<T>) -> Result<&'a Branches<T>, E>,
  {
    let mut mask = self.find_mask(voxel);
    let mut branches = &self.contents;

    macro_rules! iter(
      ($mask:expr, $step:block) => {{
        let branches_temp = branches;
        let branch = VoxelTree::get_branch(branches_temp, $mask, voxel.x, voxel.y, voxel.z);

        $step;
        // We've reached the voxel.
        if mask == 0 {
          return Ok(branch)
        }

        branches = try!(step(branch));
      }}
    );

    iter!(|x| x >= 0, {});

    loop {
      iter!(
        |x| { (x & mask) != 0 },
        // Branch through half this size next time.
        { mask = mask >> 1; }
      );
    }
  }

  /// Find a voxel inside this tree.
  /// If it doesn't exist, it will be created as empty.
  pub fn get_mut_or_create<'a>(&'a mut self, voxel: VoxelBounds) -> &'a mut TreeBody<T> {
    self.grow_to_hold(voxel);
    let branch: Result<_, ()> =
      self.mut_find(voxel, |branch| { Ok(VoxelTree::get_mut_or_create_step(branch)) });
    branch.unwrap()
  }

  fn get_mut_or_create_step<'a>(
    branch: &'a mut TreeBody<T>,
  ) -> &'a mut Branches<T> {
    // "Step down" the tree.
    match *branch {
      // Branches; we can go straight to the branching logic.
      TreeBody::Branch(ref mut b) => b,

      // Otherwise, keep going, but we need to insert a voxel inside the
      // space occupied by the current branch.

      TreeBody::Empty => {
        // Replace this branch with 8 empty sub-branches - who's gonna notice?
        *branch = TreeBody::Branch(Box::new(Branches::empty()));

        match *branch {
          TreeBody::Branch(ref mut b) => b,
          _ => unreachable!(),
        }
      },
      TreeBody::Leaf(_) => {
        // Erase this leaf and replace it with 8 empty sub-branches.
        // This behavior is pretty debatable, but we need to do something,
        // and it's easier to debug accidentally replacing a big chunk
        // with a smaller one than to debug a nop.
        *branch = TreeBody::Branch(Box::new(Branches::empty()));

        match *branch {
          TreeBody::Branch(ref mut b) => b,
          _ => unreachable!(),
        }
      },
    }
  }

  /// Find a voxel inside this tree.
  pub fn get<'a>(&'a self, voxel: VoxelBounds) -> Option<&'a T> {
    if !self.contains_bounds(voxel) {
      return None
    }

    let get_step = |branch| {
      match branch {
        &TreeBody::Branch(ref branches) => Ok(branches.deref()),
        _ => Err(()),
      }
    };

    match self.find(voxel, get_step) {
      Ok(&TreeBody::Leaf(ref t)) => Some(t),
      _ => None,
    }
  }
}

#[cfg(test)]
mod tests {
  extern crate test;

  use super::{VoxelBounds, VoxelTree, TreeBody};

  #[test]
  fn simple_test() {
    let mut tree: VoxelTree<i32> = VoxelTree::new();
    *tree.get_mut_or_create(VoxelBounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
    *tree.get_mut_or_create(VoxelBounds::new(8, -8, 4, 0)) = TreeBody::Leaf(2);
    *tree.get_mut_or_create(VoxelBounds::new(2, 0, 4, 4)) = TreeBody::Leaf(3);
    *tree.get_mut_or_create(VoxelBounds::new(9, 0, 16, 2)) = TreeBody::Leaf(4);
    *tree.get_mut_or_create(VoxelBounds::new(9, 0, 16, 2)) = TreeBody::Leaf(5);

    assert_eq!(tree.get(VoxelBounds::new(1, 1, 1, 0)), Some(&1));
    assert_eq!(tree.get(VoxelBounds::new(8, -8, 4, 0)), Some(&2));
    assert_eq!(tree.get(VoxelBounds::new(9, 0, 16, 2)), Some(&5));

    assert_eq!(tree.get(VoxelBounds::new(2, 0, 4, 4)), None);
  }

  #[test]
  fn wrong_voxel_size_is_not_found() {
    let mut tree: VoxelTree<i32> = VoxelTree::new();
    *tree.get_mut_or_create(VoxelBounds::new(4, 4, -4, 1)) = TreeBody::Leaf(1);
    assert_eq!(tree.get(VoxelBounds::new(4, 4, -4, 0)), None);
    assert_eq!(tree.get(VoxelBounds::new(4, 4, -4, 2)), None);
  }

  #[test]
  fn grow_is_transparent() {
    let mut tree: VoxelTree<i32> = VoxelTree::new();
    *tree.get_mut_or_create(VoxelBounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
    tree.grow_to_hold(VoxelBounds::new(0, 0, 0, 1));
    tree.grow_to_hold(VoxelBounds::new(0, 0, 0, 2));
    tree.grow_to_hold(VoxelBounds::new(-32, 32, -128, 3));

    assert_eq!(tree.get(VoxelBounds::new(1, 1, 1, 0)), Some(&1));
  }

  #[bench]
  fn simple_inserts(bencher: &mut test::Bencher) {
    let mut tree: VoxelTree<i32> = VoxelTree::new();
    tree.grow_to_hold(VoxelBounds::new(0, 0, 0, 30));
    bencher.iter(|| {
      *tree.get_mut_or_create(VoxelBounds::new(0, 0, 0, 0)) = TreeBody::Leaf(0);
    });
    test::black_box(tree);
  }
}
<|endoftext|>