<commit_before>use std::marker::PhantomData;
use std::mem;
use super::traits::JpmNode;
use super::innerptr::InnerPtr;
use ::rudymap::results::InsertResult;
use ::Key;

pub struct LeafBitmap<K: Key, V> {
    array: [Option<V>; 256],
    pd: PhantomData<K>
}

impl<K: Key, V> LeafBitmap<K, V> {
    pub fn new() -> LeafBitmap<K, V> {
        LeafBitmap {
            array: unsafe { mem::zeroed() },
            pd: PhantomData
        }
    }
}

fn singleton_index(key: &[u8]) -> usize {
    debug_assert!(key.len() == 1);
    key[0] as usize
}

impl<K: Key, V> JpmNode<K, V> for LeafBitmap<K, V> {
    fn get(&self, key: &[u8]) -> Option<&V> {
        self.array[singleton_index(key)].as_ref()
    }

    fn get_mut(&mut self, key: &[u8]) -> Option<&mut V> {
        self.array[singleton_index(key)].as_mut()
    }

    fn insert(&mut self, key: &[u8], value: V) -> InsertResult<V> {
        let place = &mut self.array[singleton_index(key)];
        InsertResult::Success(mem::replace(place, Some(value)))
    }

    fn expand(self: Box<Self>, pop: usize, key: &[u8], value: V) -> InnerPtr<K, V> {
        unreachable!();
    }
}
<commit_msg>Really implement LeafBitmap<commit_after>/// # Plans
/// Current this uses raw bit operations to provide a packed representation
/// with an interface similar to [Option<T>; N]. Once integer generics land,
/// it can instead use an abstraction layer to provide operations. Hopefully
/// that can be maintained as a separate crate.

use std::marker::PhantomData;
use std::mem;
use std::ptr;
use super::traits::JpmNode;
use super::innerptr::InnerPtr;
use ::rudymap::results::InsertResult;
use ::Key;
use nodrop::NoDrop;

pub struct LeafBitmap<K: Key, V> {
    keys: [u8; 256 / 8],
    values: NoDrop<[V; 256]>,
    pd: PhantomData<K>
}

impl<K: Key, V> LeafBitmap<K, V> {
    pub fn new() -> LeafBitmap<K, V> {
        LeafBitmap {
            keys: [0; 256 / 8],
            values: unsafe { mem::zeroed() },
            pd: PhantomData
        }
    }
}

#[derive(Debug)]
enum Place {
    Occupied(usize),
    Empty(usize)
}

fn singleton_index(key: &[u8], keys: &[u8; 256 / 8]) -> Place {
    debug_assert!(key.len() == 1);
    let index = key[0] as usize;
    let occupied = keys[index / 8] & (1 << (index % 8));
    if occupied != 0 {
        Place::Occupied(index)
    } else {
        Place::Empty(index)
    }
}

impl<K: Key, V> JpmNode<K, V> for LeafBitmap<K, V> {
    fn get(&self, key: &[u8]) -> Option<&V> {
        match singleton_index(key, &self.keys) {
            Place::Occupied(index) => Some(&self.values[index]),
            Place::Empty(index) => None
        }
    }

    fn get_mut(&mut self, key: &[u8]) -> Option<&mut V> {
        match singleton_index(key, &self.keys) {
            Place::Occupied(index) => Some(&mut self.values[index]),
            Place::Empty(index) => None
        }
    }

    fn insert(&mut self, key: &[u8], value: V) -> InsertResult<V> {
        match singleton_index(key, &self.keys) {
            Place::Occupied(index) => {
                let place = &mut self.values[index];
                InsertResult::replace(place, value)
            },
            Place::Empty(index) => {
                let place = &mut self.values[index];
                self.keys[index / 8] |= 1 << (index % 8);
                unsafe {
                    ptr::write(place, value);
                }
                InsertResult::Success(None)
            }
        }
    }

    fn expand(self: Box<Self>, pop: usize, key: &[u8], value: V) -> InnerPtr<K, V> {
        unreachable!();
    }
}
<|endoftext|>


<commit_before>use super::ssz::decode::{
    decode_length,
    Decodable,
};
use super::utils::hash::canonical_hash;
use super::block::{
    MIN_SSZ_BLOCK_LENGTH,
    MAX_SSZ_BLOCK_LENGTH,
};

#[derive(Debug, PartialEq)]
pub enum BlockValidatorError {
    TooShort,
    TooLong,
    NoAttestationRecords,
    BadPowHash,
    SlotTooLow,
    SlotTooHigh,
}

const LENGTH_BYTES: usize = 4;

/// Allows for reading of block values directly from serialized
/// ssz bytes.
#[derive(Debug, PartialEq)]
pub struct SszBlock<'a> {
    ssz: &'a [u8],
    attestation_len: usize,
    pub len: usize,
}

impl<'a> SszBlock<'a> {
    pub fn from_slice(vec: &'a [u8])
        -> Result<Self, BlockValidatorError>
    {
        let ssz = &vec[..];
        let len = vec.len();
        /*
         * Ensure the SSZ is long enough to be a block.
         */
        if len < MIN_SSZ_BLOCK_LENGTH {
            return Err(BlockValidatorError::TooShort);
        }
        /*
         * Ensure the SSZ slice isn't longer than is possible for a block.
         */
        if len > MAX_SSZ_BLOCK_LENGTH {
            return Err(BlockValidatorError::TooLong);
        }
        /*
         * Determine how many bytes are used to store attestation records
         * and ensure that length is enough to store at least one attestation
         * record.
         */
        let attestation_len = decode_length(ssz, 80, LENGTH_BYTES)
            .map_err(|_| BlockValidatorError::TooShort)?;
        if len < (76 + attestation_len + 96) {
            return Err(BlockValidatorError::TooShort);
        }
        Ok(Self{
            ssz,
            attestation_len,
            len,
        })
    }

    pub fn block_hash(&self) -> Vec<u8> {
        canonical_hash(self.ssz)
    }

    pub fn parent_hash(&self) -> &[u8] {
        &self.ssz[5..37]
    }

    pub fn slot_number(&self) -> u64 {
        u64::ssz_decode(&self.ssz, 32).unwrap().0
    }

    pub fn randao_reveal(&self) -> &[u8] {
        &self.ssz[40..72]
    }

    pub fn attestations(&self) -> &[u8] {
        let start = 72 + LENGTH_BYTES;
        &self.ssz[start..(start + self.attestation_len)]
    }

    pub fn pow_chain_ref(&self) -> &[u8] {
        &self.ssz[(self.len - 96)..(self.len - 64)]
    }

    pub fn act_state_root(&self) -> &[u8] {
        &self.ssz[(self.len - 64)..(self.len - 32)]
    }

    pub fn cry_state_root(&self) -> &[u8] {
        &self.ssz[(self.len - 32)..(self.len)]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use super::super::block::Block;
    use super::super::attestation_record::AttestationRecord;
    use super::super::ssz::SszStream;

    fn get_block_ssz(b: &Block) -> Vec<u8> {
        let mut ssz_stream = SszStream::new();
        ssz_stream.append(b);
        ssz_stream.drain()
    }

    #[test]
    fn test_ssz_block_zero_attestation_records() {
        let mut b = Block::zero();
        b.attestations = vec![];
        let ssz = get_block_ssz(&b);

        assert_eq!(
            SszBlock::from_slice(&ssz[..]),
            Err(BlockValidatorError::NoAttestationRecords)
        );
    }

    #[test]
    fn test_ssz_block_single_attestation_record() {
        let mut b = Block::zero();
        b.attestations = vec![AttestationRecord::zero()];
        let ssz = get_block_ssz(&b);

        assert_eq!(
            SszBlock::from_slice(&ssz[..]),
            Err(BlockValidatorError::NoAttestationRecords)
        );
    }
}
<commit_msg>Fix SszBlock tests<commit_after>use super::ssz::decode::{
    decode_length,
    Decodable,
};
use super::utils::hash::canonical_hash;
use super::block::{
    MIN_SSZ_BLOCK_LENGTH,
    MAX_SSZ_BLOCK_LENGTH,
};

#[derive(Debug, PartialEq)]
pub enum BlockValidatorError {
    TooShort,
    TooLong,
    BadPowHash,
    SlotTooLow,
    SlotTooHigh,
}

const LENGTH_BYTES: usize = 4;

/// Allows for reading of block values directly from serialized
/// ssz bytes.
#[derive(Debug, PartialEq)]
pub struct SszBlock<'a> {
    ssz: &'a [u8],
    attestation_len: usize,
    pub len: usize,
}

impl<'a> SszBlock<'a> {
    pub fn from_slice(vec: &'a [u8])
        -> Result<Self, BlockValidatorError>
    {
        let ssz = &vec[..];
        let len = vec.len();
        /*
         * Ensure the SSZ is long enough to be a block.
         */
        if len < MIN_SSZ_BLOCK_LENGTH {
            return Err(BlockValidatorError::TooShort);
        }
        /*
         * Ensure the SSZ slice isn't longer than is possible for a block.
         */
        if len > MAX_SSZ_BLOCK_LENGTH {
            return Err(BlockValidatorError::TooLong);
        }
        /*
         * Determine how many bytes are used to store attestation records
         * and ensure that length is enough to store at least one attestation
         * record.
         */
        let attestation_len = decode_length(ssz, 80, LENGTH_BYTES)
            .map_err(|_| BlockValidatorError::TooShort)?;
        if len < (76 + attestation_len + 96) {
            return Err(BlockValidatorError::TooShort);
        }
        Ok(Self{
            ssz,
            attestation_len,
            len,
        })
    }

    pub fn block_hash(&self) -> Vec<u8> {
        canonical_hash(self.ssz)
    }

    pub fn parent_hash(&self) -> &[u8] {
        &self.ssz[5..37]
    }

    pub fn slot_number(&self) -> u64 {
        u64::ssz_decode(&self.ssz, 32).unwrap().0
    }

    pub fn randao_reveal(&self) -> &[u8] {
        &self.ssz[40..72]
    }

    pub fn attestations(&self) -> &[u8] {
        let start = 72 + LENGTH_BYTES;
        &self.ssz[start..(start + self.attestation_len)]
    }

    pub fn pow_chain_ref(&self) -> &[u8] {
        &self.ssz[(self.len - 96)..(self.len - 64)]
    }

    pub fn act_state_root(&self) -> &[u8] {
        &self.ssz[(self.len - 64)..(self.len - 32)]
    }

    pub fn cry_state_root(&self) -> &[u8] {
        &self.ssz[(self.len - 32)..(self.len)]
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use super::super::block::Block;
    use super::super::attestation_record::AttestationRecord;
    use super::super::ssz::SszStream;

    fn get_block_ssz(b: &Block) -> Vec<u8> {
        let mut ssz_stream = SszStream::new();
        ssz_stream.append(b);
        ssz_stream.drain()
    }

    #[test]
    fn test_ssz_block_zero_attestation_records() {
        let mut b = Block::zero();
        b.attestations = vec![];
        let ssz = get_block_ssz(&b);

        assert_eq!(
            SszBlock::from_slice(&ssz[..]),
            Err(BlockValidatorError::TooShort)
        );
    }

    #[test]
    fn test_ssz_block_single_attestation_record() {
        let mut b = Block::zero();
        b.attestations = vec![AttestationRecord::zero()];
        let ssz = get_block_ssz(&b);

        assert!(SszBlock::from_slice(&ssz[..]).is_ok());
    }
}
<|endoftext|>


<commit_before>extern crate find_folder;

use screen::*;
use piston_window;
use conrod;
use conrod::Widget;
use conrod::Frameable;
use conrod::color::Colorable;
use conrod::Positionable;

pub struct MainMenuScreen {
    ui: conrod::Ui<piston_window::Glyphs>,
}

impl MainMenuScreen {
    pub fn new(window: &piston_window::PistonWindow) -> MainMenuScreen {
        MainMenuScreen { ui: create_ui(&window) }
    }
}

impl Screen for MainMenuScreen {
    fn on_input(&mut self, input: &piston_window::Input, window: &piston_window::PistonWindow) -> InputResults {
        use piston_window::{Input, Button, MouseButton};

        let mut result = Vec::new();

        match input {
            &Input::Press(Button::Mouse(MouseButton::Left)) => {
                result.push(InputResult::PopScreen);
                result.push(InputResult::PushScreen(Box::new(BattleScreen::new(&window))));
            }
            _ => {}
        }

        result
    }

    fn on_draw(&mut self, args: &piston_window::RenderArgs, window: &piston_window::PistonWindow) {
        // TODO: Move Ui to some context?
        // piston_window::Glyphs
        // type Ui = conrod::Ui<Glyphs>;
        let mut ui = {
            let assets = find_folder::Search::KidsThenParents(3, 5).for_folder("assets").unwrap();
            let font_path = assets.join("NotoSans-Regular.ttf");
            let theme = conrod::Theme::default();
            let glyph_cache = piston_window::Glyphs::new(&font_path, window.factory.borrow().clone());
            conrod::Ui::new(glyph_cache.unwrap(), theme)
        };

        ui.handle_event(window);

        ui.set_widgets(|ui| {
            conrod::Canvas::new()
                .frame(200.)
                .pad(30.0)
                .color(conrod::color::rgb(0.2, 0.35, 0.45))
                .scroll_kids()
                .set(CANVAS, ui);

            conrod::Text::new("Widget Demonstration")
                .top_left_with_margins_on(CANVAS, 0.0, 350.0)
                .font_size(32)
                .color(conrod::color::rgb(0.2, 0.35, 0.45).plain_contrast())
                .set(TITLE, ui);
        });

        window.draw_2d(|context, graphics| ui.draw(context, graphics));
    }

    fn on_update(&mut self, args: &piston_window::UpdateArgs) {}
}

widget_ids! {
    CANVAS,
    TITLE,
}

fn create_ui(window: &piston_window::PistonWindow) -> conrod::Ui<piston_window::Glyphs> {
    let assets = find_folder::Search::KidsThenParents(3, 5).for_folder("assets").unwrap();
    let font_path = assets.join("NotoSans-Regular.ttf");
    let theme = conrod::Theme::default();
    let glyph_cache = piston_window::Glyphs::new(&font_path, window.factory.borrow().clone());
    conrod::Ui::new(glyph_cache.unwrap(), theme)
}
<commit_msg>Ui refactoring<commit_after>extern crate find_folder;

use screen::*;
use piston_window;
use conrod;
use conrod::Widget;
use conrod::Frameable;
use conrod::color::Colorable;
use conrod::Positionable;

pub struct MainMenuScreen {
    ui: conrod::Ui<piston_window::Glyphs>,
}

impl MainMenuScreen {
    pub fn new(window: &piston_window::PistonWindow) -> MainMenuScreen {
        MainMenuScreen { ui: create_ui(&window) }
    }
}

impl Screen for MainMenuScreen {
    fn on_input(&mut self, input: &piston_window::Input, window: &piston_window::PistonWindow) -> InputResults {
        use piston_window::{Input, Button, MouseButton};

        let mut result = Vec::new();

        match input {
            &Input::Press(Button::Mouse(MouseButton::Left)) => {
                result.push(InputResult::PopScreen);
                result.push(InputResult::PushScreen(Box::new(BattleScreen::new(&window))));
            }
            _ => {}
        }

        result
    }

    fn on_draw(&mut self, args: &piston_window::RenderArgs, window: &piston_window::PistonWindow) {
        self.ui.handle_event(window);
        self.ui.set_widgets(|ui| {
            conrod::Canvas::new()
                .frame(200.)
                .pad(30.0)
                .color(conrod::color::rgb(0.2, 0.35, 0.45))
                .scroll_kids()
                .set(CANVAS, ui);

            conrod::Text::new("Widget Demonstration")
                .top_left_with_margins_on(CANVAS, 0.0, 350.0)
                .font_size(32)
                .color(conrod::color::rgb(0.2, 0.35, 0.45).plain_contrast())
                .set(TITLE, ui);
        });

        window.draw_2d(|context, graphics| self.ui.draw(context, graphics));
    }

    fn on_update(&mut self, args: &piston_window::UpdateArgs) {}
}

widget_ids! {
    CANVAS,
    TITLE,
}

fn create_ui(window: &piston_window::PistonWindow) -> conrod::Ui<piston_window::Glyphs> {
    let assets = find_folder::Search::KidsThenParents(3, 5).for_folder("assets").unwrap();
    let font_path = assets.join("NotoSans-Regular.ttf");
    let theme = conrod::Theme::default();
    let glyph_cache = piston_window::Glyphs::new(&font_path, window.factory.borrow().clone());
    conrod::Ui::new(glyph_cache.unwrap(), theme)
}
<|endoftext|>


<commit_before>// Copyright 2015-2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>

//! `IMPL` The `glib_wrapper!` macro and miscellaneous wrapper traits.

/// Defines a wrapper type and implements the appropriate traits.
///
/// The basic syntax is
///
/// ```ignore
/// glib_wrapper! {
///     /// Documentation
///     pub struct $name($kind<$foreign>);
///
///     match fn {
///         $fn_name => /* a closure-like expression */,
///         ...
///     }
/// }
/// ```
///
/// This creates a wrapper named `$name` around the foreign type `$foreign`
/// of `$kind` (one of `Boxed`, `Shared`, `Object`) using expressions from the `match fn`
/// block to implement type-specific low-level operations (the expression
/// will be evaluated in `unsafe` context).
///
/// ### Boxed
///
/// Boxed records with single ownership.
///
/// ```ignore
/// glib_wrapper! {
///     /// Text buffer iterator
///     pub struct TextIter(Boxed<ffi::GtkTextIter>);
///
///     match fn {
///         copy => |ptr| ffi::gtk_text_iter_copy(ptr),
///         free => |ptr| ffi::gtk_text_iter_free(ptr),
///     }
/// }
/// ```
///
/// `copy`: `|*const $foreign| -> *mut $foreign` creates a copy of the value.
///
/// `free`: `|*mut $foreign|` frees the value.
///
/// `get_type`: `||` (optional) returns the `Type`, if any
///
/// ### Shared
///
/// Records with reference counted shared ownership.
///
/// ```ignore
/// glib_wrapper! {
///     /// Object holding timing information for a single frame.
///     pub struct FrameTimings(Shared<ffi::GdkFrameTimings>);
///
///     match fn {
///         ref => |ptr| ffi::gdk_frame_timings_ref(ptr),
///         unref => |ptr| ffi::gdk_frame_timings_unref(ptr),
///     }
/// }
/// ```
///
/// `ref`: `|*mut $foreign|` increases the refcount.
///
/// `unref`: `|*mut $foreign|` decreases the refcount.
///
/// `get_type`: `||` (optional) returns the `Type`, if any
///
/// ### Object
///
/// Objects -- classes and interfaces.  Note that the class name must
/// be specified after the $foreign type.
///
/// ```ignore
/// glib_wrapper! {
///     /// Object representing an input device.
///     pub struct Device(Object<ffi::GdkDevice, ffi::GdkDeviceClass>);
///
///     match fn {
///         get_type => || ffi::gdk_device_get_type(),
///     }
/// }
/// ```
///
/// ```ignore
/// glib_wrapper! {
///     /// A container with just one child.
///     pub struct Bin(Object<ffi::GtkBin, ffi::GtkBinClass>): Container, Widget, Buildable;
///
///     match fn {
///         get_type => || ffi::gtk_bin_get_type(),
///     }
/// }
/// ```
///
/// Implementing types from other crates requires specifying their FFI
/// counterparts as well:
///
/// ```ignore
/// glib_wrapper! {
///     pub struct Application(Object<ffi::GtkApplication, ffi::GtkApplicationClass>): [
///         gio::Application => gio_ffi::GApplication,
///         gio::ActionGroup => gio_ffi::GActionGroup,
///         gio::ActionMap => gio_ffi::GActionMap,
///     ];
///
///     match fn {
///         get_type => || ffi::gtk_application_get_type(),
///     }
/// }
/// ```
///
/// #### Non-derivable classes
///
/// By convention, GObject implements "final" classes, i.e. those who cannot
/// be subclassed, by exposing a public Instance struct, but no corresponding
/// Class struct.  In this case, don't specify a class name at all:
///
/// ```ignore
/// glib_wrapper! {
///     pub struct Clipboard(Object<ffi::GtkClipboard>);
///     ...
/// }
/// ```
///
/// `get_type: || -> GType` returns the type identifier of the class or interface.
#[macro_export]
macro_rules! glib_wrapper {
    // Boxed

    (
        $(#[$attr:meta])*
        pub struct $name:ident(Boxed<$ffi_name:path>);

        match fn {
            copy => |$copy_arg:ident| $copy_expr:expr,
            free => |$free_arg:ident| $free_expr:expr,
        }
    ) => {
        glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr,
            @free $free_arg $free_expr);
    };

    (
        $(#[$attr:meta])*
        pub struct $name:ident(Boxed<$ffi_name:path>);

        match fn {
            copy => |$copy_arg:ident| $copy_expr:expr,
            free => |$free_arg:ident| $free_expr:expr,
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr,
            @free $free_arg $free_expr, @get_type $get_type_expr);
    };

    // Shared

    (
        $(#[$attr:meta])*
        pub struct $name:ident(Shared<$ffi_name:path>);

        match fn {
            ref => |$ref_arg:ident| $ref_expr:expr,
            unref => |$unref_arg:ident| $unref_expr:expr,
        }
    ) => {
        glib_shared_wrapper!([$($attr)*] $name, $ffi_name, @ref $ref_arg $ref_expr,
            @unref $unref_arg $unref_expr);
    };

    (
        $(#[$attr:meta])*
        pub struct $name:ident(Shared<$ffi_name:path>);

        match fn {
            ref => |$ref_arg:ident| $ref_expr:expr,
            unref => |$unref_arg:ident| $unref_expr:expr,
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_shared_wrapper!([$($attr)*] $name, $ffi_name, @ref $ref_arg $ref_expr,
            @unref $unref_arg $unref_expr, @get_type $get_type_expr);
    };

    // Object, no class struct, no parents
    (
        $(#[$attr:meta])*
        pub struct $name:ident(Object<$ffi_name:path>);

        match fn {
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_object_wrapper!([$($attr)*] $name, $ffi_name, $crate::wrapper::Void, @get_type $get_type_expr, []);
    };

    // Object, class struct, no parents
    (
        $(#[$attr:meta])*
        pub struct $name:ident(Object<$ffi_name:path, $ffi_class_name:path>);

        match fn {
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_object_wrapper!([$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, []);
    };

    // Object, no class struct, parents in other crates
    (
        $(#[$attr:meta])*
        pub struct $name:ident(Object<$ffi_name:path>): [$($implements:tt)+];

        match fn {
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_object_wrapper!([$($attr)*] $name, $ffi_name, $crate::wrapper::Void, @get_type $get_type_expr,
            @implements $($implements)+);
    };

    // Object, class struct, parents in other crates
    (
        $(#[$attr:meta])*
        pub struct $name:ident(Object<$ffi_name:path, $ffi_class_name:path>): [$($implements:tt)+];

        match fn {
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_object_wrapper!([$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr,
            @implements $($implements)+);
    };

    // Object, no class struct, parents
    (
        $(#[$attr:meta])*
        pub struct $name:ident(Object<$ffi_name:path>): $($implements:path),+;

        match fn {
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_object_wrapper!([$($attr)*] $name, $ffi_name, $crate::wrapper::Void, @get_type $get_type_expr,
            [$($implements),+]);
    };

    // Object, class struct, parents
    (
        $(#[$attr:meta])*
        pub struct $name:ident(Object<$ffi_name:path, $ffi_class_name:path>): $($implements:path),+;

        match fn {
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_object_wrapper!([$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr,
            [$($implements),+]);
    };
}

/// Represents a pair of structures (instance, class) as exposed by descendants of GObject
pub trait Wrapper {
    /// type of the Instance structure
    type GlibType: 'static;
    /// type of the Class structure
    type GlibClassType: 'static;
}

pub trait UnsafeFrom<T> {
    unsafe fn from(t: T) -> Self;
}

// So we can refer to the empty type by a path
pub type Void = ();
<commit_msg>Clarify the documentation for glib_wrapper!()<commit_after>// Copyright 2015-2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>

//! `IMPL` The `glib_wrapper!` macro and miscellaneous wrapper traits.

/// Defines a wrapper type and implements the appropriate traits.
///
/// The basic syntax is
///
/// ```ignore
/// glib_wrapper! {
///     /// Your documentation goes here
///     pub struct $name($kind<$foreign>);
///
///     match fn {
///         $fn_name => /* a closure-like expression */,
///         ...
///     }
/// }
/// ```
///
/// This creates a wrapper named `$name` around the foreign type
/// `$foreign` of `$kind` — one of [`Boxed`][#boxed],
/// [`Shared`][#shared], or [`Object`][#object].
///
/// Inside the `match fn` block there are closure-like expressions to
/// provide ways of copying/freeing, or referencing/unreferencing the
/// value that you are wrapping.  These expressions will be evaluated
/// in an `unsafe` context, since they frequently invoke `extern`
/// functions from an FFI crate.
///
/// What follows is a description of each of the possible `$kind`:
/// [`Boxed`][#boxed], [`Shared`][#shared], and [`Object`][#object];
/// note that each supports different sets of `$fn_name` inside the
/// `match fn` block.  Also, `Object` may require you to specify
/// things like the class struct to wrap, plus any interfaces that the
/// class implements.
///
/// ### Boxed
///
/// Boxed records with single ownership.
///
/// With no registered `glib_ffi::GType`:
///
/// ```ignore
/// glib_wrapper! {
///     /// Text buffer iterator
///     pub struct TextIter(Boxed<ffi::GtkTextIter>);
///
///     match fn {
///         copy => |ptr| ffi::gtk_text_iter_copy(ptr),
///         free => |ptr| ffi::gtk_text_iter_free(ptr),
///     }
/// }
/// ```
///
/// `copy`: `|*const $foreign| -> *mut $foreign` creates a copy of the value.
///
/// `free`: `|*mut $foreign|` frees the value.
///
/// With a registered `glib_ffi::GType`:
///
/// ```ignore
/// glib_wrapper! {
///     /// Text buffer iterator
///     pub struct TextIter(Boxed<ffi::GtkTextIter>);
///
///     match fn {
///         copy     => |ptr| ffi::gtk_text_iter_copy(ptr),
///         free     => |ptr| ffi::gtk_text_iter_free(ptr),
///         get_type => ||    ffi::gtk_text_iter_get_type(),
///     }
/// }
/// ```
///
/// `get_type`: `|| -> glib_ffi::GType` (optional) returns the
/// `glib_ffi::GType` that corresponds to the foreign struct.
///
/// ### Shared
///
/// Records with reference-counted, shared ownership.
///
/// With no registered `glib_ffi::GType`:
///
/// ```ignore
/// glib_wrapper! {
///     /// Object holding timing information for a single frame.
///     pub struct FrameTimings(Shared<ffi::GdkFrameTimings>);
///
///     match fn {
///         ref   => |ptr| ffi::gdk_frame_timings_ref(ptr),
///         unref => |ptr| ffi::gdk_frame_timings_unref(ptr),
///     }
/// }
/// ```
///
/// `ref`: `|*mut $foreign|` increases the refcount.
///
/// `unref`: `|*mut $foreign|` decreases the refcount.
///
/// With a registered `glib_ffi::GType`:
///
/// ```ignore
/// glib_wrapper! {
///     /// Object holding timing information for a single frame.
///     pub struct FrameTimings(Shared<ffi::GdkFrameTimings>);
///
///     match fn {
///         ref      => |ptr| ffi::gdk_frame_timings_ref(ptr),
///         unref    => |ptr| ffi::gdk_frame_timings_unref(ptr),
///         get_type => ||    ffi::gdk_frame_timings_get_type(),
///     }
/// }
/// ```
///
/// `get_type`: `|| -> glib_ffi::GType` (optional) returns the
/// `glib_ffi::GType` that corresponds to the foreign struct.
///
/// ### Object
///
/// Objects -- classes and interfaces.  Note that the class name, if
/// available, must be specified after the $foreign type; see below
/// for [non-derivable classes][#non-derivable-classes].
///
/// The basic syntax is this:
///
/// ```ignore
/// glib_wrapper! {
///     /// Your documentation goes here
///     pub struct InstanceName(Object<ffi::InstanceStruct, ffi::ClassStruct>):
///         ParentClass, GrandparentClass, ...,
///         Interface1, Interface2, ...;
///
///     match fn {
///         get_type => || ffi::instance_get_type(),
///     }
/// }
/// ```
///
/// `get_type`: `|| -> glib_ffi::GType` returns the `glib_ffi::GType`
/// that corresponds to the foreign class.
///
/// #### All parent classes must be specified
///
/// In the example above, "`ParentClass, GrandparentClass, ...,`" is where you must specify all the
/// parent classes of the one you are wrapping.  It is not necessary to specify the uppermost
/// `GObject` or `GInitiallyUnowned` parent classes.
///
/// For example, `ffi::GtkWindowGroup` derives directly from
/// `GObject`, so it can be simply wrapped as follows:
///
/// ```ignore
/// glib_wrapper! {
///     pub struct WindowGroup(Object<ffi::GtkWindowGroup, ffi::GtkWindowGroupClass>);
///
///     match fn {
///         get_type => || ffi::gtk_window_group_get_type(),
///     }
/// }
/// ```
///
/// In contrast, `ffi::GtkButton` has a parent, grandparent, etc. classes, which must be specified:
///
/// ```ignore
/// glib_wrapper! {
///     pub struct Button(Object<ffi::GtkButton>): Bin, Container, Widget;
///         // see note on interfaces in the example below
///
///     match fn {
///         get_type => || ffi::gtk_button_get_type(),
///     }
/// }
/// ```
///
/// #### Objects which implement interfaces
///
/// The example above is incomplete, since `ffi::GtkButton` actually implements two interfaces,
/// `Buildable` and `Actionable`.  In this case, they must be specified after all the parent classes:
///
/// ```ignore
/// glib_wrapper! {
///     pub struct Button(Object<ffi::GtkButton>):
///         Bin, Container, Widget, // parent classes
///         Buildable, Actionable;  // interfaces
///
///     match fn {
///         get_type => || ffi::gtk_button_get_type(),
///     }
/// }
/// ```
///
/// #### Wrapping objects with parents/interfaces from different crates
///
/// Implementing types whose parents or interfaces come from different
/// crates requires specifying the wrapped names of the
/// parents/interfaces and their FFI counterparts as well.  Note that
/// these must be specified inside square brackets "`[]`", as
/// comma-delimited pairs like
/// "`crate_name::WrappedName => ffi_crate_name::Name`".
///
/// Here, note that the parent class for `ffi::GtkApplication` is
/// `gio::Application`, which is the Rust wrapper for
/// `gio_ffi::GApplication`.  Similarly, the `ActionGroup` and
/// `ActionMap` interfaces, and their corresponding ffi structs, come
/// from different crates.
///
/// ```ignore
/// glib_wrapper! {
///     pub struct Application(Object<ffi::GtkApplication, ffi::GtkApplicationClass>): [
///         gio::Application => gio_ffi::GApplication,
///         gio::ActionGroup => gio_ffi::GActionGroup,
///         gio::ActionMap   => gio_ffi::GActionMap,
///     ];
///
///     match fn {
///         get_type => || ffi::gtk_application_get_type(),
///     }
/// }
/// ```
///
/// #### Non-derivable classes
///
/// By convention, GObject implements "final" classes, i.e. those who
/// cannot be subclassed, by *not* exposing a public Class struct.
/// This way it is not possible to override any methods, as there are
/// no `klass.method_name` fields to overwrite.  In this case, don't
/// specify a class name at all in the `Object<>` part:
///
/// ```ignore
/// glib_wrapper! {
///     pub struct Clipboard(Object<ffi::GtkClipboard>);
///     ...
/// }
/// ```
///
/// [#boxed]: #boxed
/// [#shared]: #shared
/// [#object]: #object
/// [#non-derivable-classes]: #non-derivable-classes

#[macro_export]
macro_rules! glib_wrapper {
    // Boxed

    (
        $(#[$attr:meta])*
        pub struct $name:ident(Boxed<$ffi_name:path>);

        match fn {
            copy => |$copy_arg:ident| $copy_expr:expr,
            free => |$free_arg:ident| $free_expr:expr,
        }
    ) => {
        glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr,
            @free $free_arg $free_expr);
    };

    (
        $(#[$attr:meta])*
        pub struct $name:ident(Boxed<$ffi_name:path>);

        match fn {
            copy => |$copy_arg:ident| $copy_expr:expr,
            free => |$free_arg:ident| $free_expr:expr,
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_boxed_wrapper!([$($attr)*] $name, $ffi_name, @copy $copy_arg $copy_expr,
            @free $free_arg $free_expr, @get_type $get_type_expr);
    };

    // Shared

    (
        $(#[$attr:meta])*
        pub struct $name:ident(Shared<$ffi_name:path>);

        match fn {
            ref => |$ref_arg:ident| $ref_expr:expr,
            unref => |$unref_arg:ident| $unref_expr:expr,
        }
    ) => {
        glib_shared_wrapper!([$($attr)*] $name, $ffi_name, @ref $ref_arg $ref_expr,
            @unref $unref_arg $unref_expr);
    };

    (
        $(#[$attr:meta])*
        pub struct $name:ident(Shared<$ffi_name:path>);

        match fn {
            ref => |$ref_arg:ident| $ref_expr:expr,
            unref => |$unref_arg:ident| $unref_expr:expr,
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_shared_wrapper!([$($attr)*] $name, $ffi_name, @ref $ref_arg $ref_expr,
            @unref $unref_arg $unref_expr, @get_type $get_type_expr);
    };

    // Object, no class struct, no parents
    (
        $(#[$attr:meta])*
        pub struct $name:ident(Object<$ffi_name:path>);

        match fn {
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_object_wrapper!([$($attr)*] $name, $ffi_name, $crate::wrapper::Void, @get_type $get_type_expr, []);
    };

    // Object, class struct, no parents
    (
        $(#[$attr:meta])*
        pub struct $name:ident(Object<$ffi_name:path, $ffi_class_name:path>);

        match fn {
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_object_wrapper!([$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr, []);
    };

    // Object, no class struct, parents in other crates
    (
        $(#[$attr:meta])*
        pub struct $name:ident(Object<$ffi_name:path>): [$($implements:tt)+];

        match fn {
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_object_wrapper!([$($attr)*] $name, $ffi_name, $crate::wrapper::Void, @get_type $get_type_expr,
            @implements $($implements)+);
    };

    // Object, class struct, parents in other crates
    (
        $(#[$attr:meta])*
        pub struct $name:ident(Object<$ffi_name:path, $ffi_class_name:path>): [$($implements:tt)+];

        match fn {
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_object_wrapper!([$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr,
            @implements $($implements)+);
    };

    // Object, no class struct, parents
    (
        $(#[$attr:meta])*
        pub struct $name:ident(Object<$ffi_name:path>): $($implements:path),+;

        match fn {
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_object_wrapper!([$($attr)*] $name, $ffi_name, $crate::wrapper::Void, @get_type $get_type_expr,
            [$($implements),+]);
    };

    // Object, class struct, parents
    (
        $(#[$attr:meta])*
        pub struct $name:ident(Object<$ffi_name:path, $ffi_class_name:path>): $($implements:path),+;

        match fn {
            get_type => || $get_type_expr:expr,
        }
    ) => {
        glib_object_wrapper!([$($attr)*] $name, $ffi_name, $ffi_class_name, @get_type $get_type_expr,
            [$($implements),+]);
    };
}

/// Represents a pair of structures (instance, class) as exposed by descendants of GObject
pub trait Wrapper {
    /// type of the Instance structure
    type GlibType: 'static;
    /// type of the Class structure
    type GlibClassType: 'static;
}

pub trait UnsafeFrom<T> {
    unsafe fn from(t: T) -> Self;
}

// So we can refer to the empty type by a path
pub type Void = ();
<|endoftext|>


<commit_before>//! Module: czmq-zpoller

use {czmq_sys, Error, ErrorKind, Result, Sockish};
use std::{error, fmt, ptr};
use std::os::raw::c_int;

pub struct ZPoller {
    zpoller: *mut czmq_sys::zpoller_t,
}

unsafe impl Send for ZPoller {}

impl Drop for ZPoller {
    fn drop(&mut self) {
        unsafe { czmq_sys::zpoller_destroy(&mut self.zpoller) };
    }
}

impl ZPoller {
    pub fn new() -> Result<ZPoller> {
        // zpoller_new() can take one or more readers, though Rust
        // doesn't support variadic fns except through macros.
        let zpoller = unsafe { czmq_sys::zpoller_new(ptr::null_mut()) };

        if zpoller == ptr::null_mut() {
            return Err(Error::new(ErrorKind::NullPtr, ZPollerError::Instantiate));
        }

        Ok(ZPoller {
            zpoller: zpoller,
        })
    }

    pub fn add<S: Sockish>(&mut self, reader: &S) -> Result<()> {
        let rc = unsafe { czmq_sys::zpoller_add(self.zpoller, reader.borrow_raw()) };

        if rc == -1 {
            Err(Error::new(ErrorKind::NonZero, ZPollerError::CmdFailed))
        } else {
            Ok(())
        }
    }

    pub fn remove<S: Sockish>(&mut self, reader: &S) -> Result<()> {
        let rc = unsafe { czmq_sys::zpoller_remove(self.zpoller, reader.borrow_raw()) };

        if rc == -1 {
            Err(Error::new(ErrorKind::NonZero, ZPollerError::CmdFailed))
        } else {
            Ok(())
        }
    }

    pub fn wait<S: Sockish>(&self, timeout: Option<u32>) -> Result<Option<S>> {
        let t = match timeout {
            Some(time) => time as c_int,
            None => -1 as c_int,
        };

        let ptr = unsafe { czmq_sys::zpoller_wait(self.zpoller, t) };

        if ptr == ptr::null_mut() {
            Ok(None)
        } else {
            Ok(Some(S::from_raw(ptr, false)))
        }
    }

    pub fn expired(&self) -> bool {
        unsafe { czmq_sys::zpoller_expired(self.zpoller) == 1 }
    }

    pub fn terminated(&self) -> bool {
        unsafe { czmq_sys::zpoller_terminated(self.zpoller) == 1 }
    }

    pub fn set_nonstop(&self, nonstop: bool) {
        unsafe { czmq_sys::zpoller_set_nonstop(self.zpoller, if nonstop { 1 } else { 0 }) }
    }
}

#[derive(Debug)]
pub enum ZPollerError {
    CmdFailed,
    Instantiate,
}

impl fmt::Display for ZPollerError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ZPollerError::CmdFailed => write!(f, "ZPoller command failed"),
            ZPollerError::Instantiate => write!(f, "Could not instantiate new ZPoller struct"),
        }
    }
}

impl error::Error for ZPollerError {
    fn description(&self) -> &str {
        match *self {
            ZPollerError::CmdFailed => "ZPoller command failed",
            ZPollerError::Instantiate => "Could not instantiate new ZPoller struct",
        }
    }
}

#[cfg(test)]
mod tests {
    use {ZSock, ZSockType, ZSys};
    use super::*;

    #[test]
    fn test_new() {
        assert!(ZPoller::new().is_ok());
    }

    #[test]
    fn test_add_remove() {
        ZSys::init();

        let sock = ZSock::new(ZSockType::PAIR);
        let mut poller = ZPoller::new().unwrap();
        assert!(poller.add(&sock).is_ok());
        assert!(poller.remove(&sock).is_ok());
    }

    #[test]
    fn test_wait() {
        ZSys::init();

        let server1 = ZSock::new_rep("inproc://zpoller_test_wait1").unwrap();
        let client1 = ZSock::new_req("inproc://zpoller_test_wait1").unwrap();
        client1.send_str("moo").unwrap();

        let server2 = ZSock::new_rep("inproc://zpoller_test_wait2").unwrap();
        let client2 = ZSock::new_req("inproc://zpoller_test_wait2").unwrap();
        client2.send_str("cow").unwrap();

        let mut poller = ZPoller::new().unwrap();
        poller.add(&server1).unwrap();
        poller.add(&server2).unwrap();

        let sock: ZSock = poller.wait(Some(500)).unwrap().unwrap();
        assert_eq!(sock.endpoint().unwrap(), "inproc://zpoller_test_wait1");
        server1.recv_str().unwrap().unwrap();

        let sock: ZSock = poller.wait(Some(500)).unwrap().unwrap();
        assert_eq!(sock.endpoint().unwrap(), "inproc://zpoller_test_wait2");
        server2.recv_str().unwrap().unwrap();

        let sock: Option<ZSock> = poller.wait(Some(0)).unwrap();
        assert!(sock.is_none());
        assert!(poller.expired());
        assert!(!poller.terminated());
    }
}
<commit_msg>Removed superfluous Result from ZPoller::wait() return signature<commit_after>//! Module: czmq-zpoller

use {czmq_sys, Error, ErrorKind, Result, Sockish};
use std::{error, fmt, ptr};
use std::os::raw::c_int;

pub struct ZPoller {
    zpoller: *mut czmq_sys::zpoller_t,
}

unsafe impl Send for ZPoller {}

impl Drop for ZPoller {
    fn drop(&mut self) {
        unsafe { czmq_sys::zpoller_destroy(&mut self.zpoller) };
    }
}

impl ZPoller {
    pub fn new() -> Result<ZPoller> {
        // zpoller_new() can take one or more readers, though Rust
        // doesn't support variadic fns except through macros.
        let zpoller = unsafe { czmq_sys::zpoller_new(ptr::null_mut()) };

        if zpoller == ptr::null_mut() {
            return Err(Error::new(ErrorKind::NullPtr, ZPollerError::Instantiate));
        }

        Ok(ZPoller {
            zpoller: zpoller,
        })
    }

    pub fn add<S: Sockish>(&mut self, reader: &S) -> Result<()> {
        let rc = unsafe { czmq_sys::zpoller_add(self.zpoller, reader.borrow_raw()) };

        if rc == -1 {
            Err(Error::new(ErrorKind::NonZero, ZPollerError::CmdFailed))
        } else {
            Ok(())
        }
    }

    pub fn remove<S: Sockish>(&mut self, reader: &S) -> Result<()> {
        let rc = unsafe { czmq_sys::zpoller_remove(self.zpoller, reader.borrow_raw()) };

        if rc == -1 {
            Err(Error::new(ErrorKind::NonZero, ZPollerError::CmdFailed))
        } else {
            Ok(())
        }
    }

    pub fn wait<S: Sockish>(&self, timeout: Option<u32>) -> Option<S> {
        let t = match timeout {
            Some(time) => time as c_int,
            None => -1 as c_int,
        };

        let ptr = unsafe { czmq_sys::zpoller_wait(self.zpoller, t) };

        if ptr == ptr::null_mut() {
            None
        } else {
            Some(S::from_raw(ptr, false))
        }
    }

    pub fn expired(&self) -> bool {
        unsafe { czmq_sys::zpoller_expired(self.zpoller) == 1 }
    }

    pub fn terminated(&self) -> bool {
        unsafe { czmq_sys::zpoller_terminated(self.zpoller) == 1 }
    }

    pub fn set_nonstop(&self, nonstop: bool) {
        unsafe { czmq_sys::zpoller_set_nonstop(self.zpoller, if nonstop { 1 } else { 0 }) }
    }
}

#[derive(Debug)]
pub enum ZPollerError {
    CmdFailed,
    Instantiate,
}

impl fmt::Display for ZPollerError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ZPollerError::CmdFailed => write!(f, "ZPoller command failed"),
            ZPollerError::Instantiate => write!(f, "Could not instantiate new ZPoller struct"),
        }
    }
}

impl error::Error for ZPollerError {
    fn description(&self) -> &str {
        match *self {
            ZPollerError::CmdFailed => "ZPoller command failed",
            ZPollerError::Instantiate => "Could not instantiate new ZPoller struct",
        }
    }
}

#[cfg(test)]
mod tests {
    use {ZSock, ZSockType, ZSys};
    use super::*;

    #[test]
    fn test_new() {
        assert!(ZPoller::new().is_ok());
    }

    #[test]
    fn test_add_remove() {
        ZSys::init();

        let sock = ZSock::new(ZSockType::PAIR);
        let mut poller = ZPoller::new().unwrap();
        assert!(poller.add(&sock).is_ok());
        assert!(poller.remove(&sock).is_ok());
    }

    #[test]
    fn test_wait() {
        ZSys::init();

        let server1 = ZSock::new_rep("inproc://zpoller_test_wait1").unwrap();
        let client1 = ZSock::new_req("inproc://zpoller_test_wait1").unwrap();
        client1.send_str("moo").unwrap();

        let server2 = ZSock::new_rep("inproc://zpoller_test_wait2").unwrap();
        let client2 = ZSock::new_req("inproc://zpoller_test_wait2").unwrap();
        client2.send_str("cow").unwrap();

        let mut poller = ZPoller::new().unwrap();
        poller.add(&server1).unwrap();
        poller.add(&server2).unwrap();

        let sock: ZSock = poller.wait(Some(500)).unwrap();
        assert_eq!(sock.endpoint().unwrap(), "inproc://zpoller_test_wait1");
        server1.recv_str().unwrap().unwrap();

        let sock: ZSock = poller.wait(Some(500)).unwrap();
        assert_eq!(sock.endpoint().unwrap(), "inproc://zpoller_test_wait2");
        server2.recv_str().unwrap().unwrap();

        let sock: Option<ZSock> = poller.wait(Some(0));
        assert!(sock.is_none());
        assert!(poller.expired());
        assert!(!poller.terminated());
    }
}
<|endoftext|>


<commit_before>// run-pass

#![feature(generators)]
#![feature(destructuring_assignment)]

#![allow(non_camel_case_types)]
#![allow(dead_code)]
#![allow(unreachable_code)]
#![allow(unused_braces, unused_must_use, unused_parens)]

#![recursion_limit = "256"]

use std::cell::Cell;
use std::mem::swap;

// Just a grab bag of stuff that you wouldn't want to actually write.

fn strange() -> bool { let _x: bool = return true; }

fn funny() {
    fn f(_x: ()) { }
    f(return);
}

fn what() {
    fn the(x: &Cell<bool>) {
        return while !x.get() { x.set(true); };
    }
    let i = &Cell::new(false);
    let dont = {||the(i)};
    dont();
    assert!((i.get()));
}

fn zombiejesus() {
    loop {
        while (return) {
            if (return) {
                match (return) {
                    1 => {
                        if (return) {
                            return
                        } else {
                            return
                        }
                    }
                    _ => { return }
                };
            } else if (return) {
                return;
            }
        }
        if (return) { break; }
    }
}

fn notsure() {
    let mut _x: isize;
    let mut _y = (_x = 0) == (_x = 0);
    let mut _z = (_x = 0) < (_x = 0);
    let _a = (_x += 0) == (_x = 0);
    let _b = swap(&mut _y, &mut _z) == swap(&mut _y, &mut _z);
}

fn canttouchthis() -> usize {
    fn p() -> bool { true }
    let _a = (assert!((true)) == (assert!(p())));
    let _c = (assert!((p())) == ());
    let _b: bool = (println!("{}", 0) == (return 0));
}

fn angrydome() {
    loop { if break { } }
    let mut i = 0;
    loop { i += 1; if i == 1 { match (continue) { 1 => { }, _ => panic!("wat") } }
      break; }
}

fn evil_lincoln() { let _evil = println!("lincoln"); }

fn dots() {
    assert_eq!(String::from(".................................................."),
               format!("{:?}", .. .. .. .. .. .. .. .. .. .. .. .. ..
                               .. .. .. .. .. .. .. .. .. .. .. ..));
}

fn u8(u8: u8) {
    if u8 != 0u8 {
        assert_eq!(8u8, {
            macro_rules! u8 {
                (u8) => {
                    mod u8 {
                        pub fn u8<'u8: 'u8 + 'u8>(u8: &'u8 u8) -> &'u8 u8 {
                            "u8";
                            u8
                        }
                    }
                };
            }

            u8!(u8);
            let &u8: &u8 = u8::u8(&8u8);
            ::u8(0u8);
            u8
        });
    }
}

fn fishy() {
    assert_eq!(String::from("><>"),
               String::<>::from::<>("><>").chars::<>().rev::<>().collect::<String>());
}

fn union() {
    union union<'union> { union: &'union union<'union>, }
}

fn special_characters() {
    let val = !((|(..):(_,_),__@_|__)((&*"\\",'🤔')/**/,{})=={&[..=..][..];})//
    ;
    assert!(!val);
}

fn punch_card() -> impl std::fmt::Debug {
    ..=..=.. ..    .. .. .. ..    .. .. .. ..    .. ..=.. ..
    ..=.. ..=..    .. .. .. ..    .. .. .. ..    ..=..=..=..
    ..=.. ..=..    ..=.. ..=..    .. ..=..=..    .. ..=.. ..
    ..=..=.. ..    ..=.. ..=..    ..=.. .. ..    .. ..=.. ..
    ..=.. ..=..    ..=.. ..=..    .. ..=.. ..    .. ..=.. ..
    ..=.. ..=..    ..=.. ..=..    .. .. ..=..    .. ..=.. ..
    ..=.. ..=..    .. ..=..=..    ..=..=.. ..    .. ..=.. ..
}

fn r#match() {
    let val = match match match match match () {
        () => ()
    } {
        () => ()
    } {
        () => ()
    } {
        () => ()
    } {
        () => ()
    };
    assert_eq!(val, ());
}

fn i_yield() {
    static || {
        yield yield yield yield yield yield yield yield yield;
    };
}

fn match_nested_if() {
    let val = match () {
        () if if if if true {true} else {false} {true} else {false} {true} else {false} => true,
        _ => false,
    };
    assert!(val);
}

fn empty_tuple_assignment() {
    let val = ()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=();
    assert_eq!(val, ());
}

pub fn main() {
    strange();
    funny();
    what();
    zombiejesus();
    notsure();
    canttouchthis();
    angrydome();
    evil_lincoln();
    dots();
    u8(8u8);
    fishy();
    union();
    special_characters();
    punch_card();
    r#match();
    i_yield();
    match_nested_if();
    empty_tuple_assignment();
}
<commit_msg>Rename empty_tuple_assignment to monkey_barrel<commit_after>// run-pass

#![feature(generators)]
#![feature(destructuring_assignment)]

#![allow(non_camel_case_types)]
#![allow(dead_code)]
#![allow(unreachable_code)]
#![allow(unused_braces, unused_must_use, unused_parens)]

#![recursion_limit = "256"]

use std::cell::Cell;
use std::mem::swap;

// Just a grab bag of stuff that you wouldn't want to actually write.

fn strange() -> bool { let _x: bool = return true; }

fn funny() {
    fn f(_x: ()) { }
    f(return);
}

fn what() {
    fn the(x: &Cell<bool>) {
        return while !x.get() { x.set(true); };
    }
    let i = &Cell::new(false);
    let dont = {||the(i)};
    dont();
    assert!((i.get()));
}

fn zombiejesus() {
    loop {
        while (return) {
            if (return) {
                match (return) {
                    1 => {
                        if (return) {
                            return
                        } else {
                            return
                        }
                    }
                    _ => { return }
                };
            } else if (return) {
                return;
            }
        }
        if (return) { break; }
    }
}

fn notsure() {
    let mut _x: isize;
    let mut _y = (_x = 0) == (_x = 0);
    let mut _z = (_x = 0) < (_x = 0);
    let _a = (_x += 0) == (_x = 0);
    let _b = swap(&mut _y, &mut _z) == swap(&mut _y, &mut _z);
}

fn canttouchthis() -> usize {
    fn p() -> bool { true }
    let _a = (assert!((true)) == (assert!(p())));
    let _c = (assert!((p())) == ());
    let _b: bool = (println!("{}", 0) == (return 0));
}

fn angrydome() {
    loop { if break { } }
    let mut i = 0;
    loop { i += 1; if i == 1 { match (continue) { 1 => { }, _ => panic!("wat") } }
      break; }
}

fn evil_lincoln() { let _evil = println!("lincoln"); }

fn dots() {
    assert_eq!(String::from(".................................................."),
               format!("{:?}", .. .. .. .. .. .. .. .. .. .. .. .. ..
                               .. .. .. .. .. .. .. .. .. .. .. ..));
}

fn u8(u8: u8) {
    if u8 != 0u8 {
        assert_eq!(8u8, {
            macro_rules! u8 {
                (u8) => {
                    mod u8 {
                        pub fn u8<'u8: 'u8 + 'u8>(u8: &'u8 u8) -> &'u8 u8 {
                            "u8";
                            u8
                        }
                    }
                };
            }

            u8!(u8);
            let &u8: &u8 = u8::u8(&8u8);
            ::u8(0u8);
            u8
        });
    }
}

fn fishy() {
    assert_eq!(String::from("><>"),
               String::<>::from::<>("><>").chars::<>().rev::<>().collect::<String>());
}

fn union() {
    union union<'union> { union: &'union union<'union>, }
}

fn special_characters() {
    let val = !((|(..):(_,_),__@_|__)((&*"\\",'🤔')/**/,{})=={&[..=..][..];})//
    ;
    assert!(!val);
}

fn punch_card() -> impl std::fmt::Debug {
    ..=..=.. ..    .. .. .. ..    .. .. .. ..    .. ..=.. ..
    ..=.. ..=..    .. .. .. ..    .. .. .. ..    ..=..=..=..
    ..=.. ..=..    ..=.. ..=..    .. ..=..=..    .. ..=.. ..
    ..=..=.. ..    ..=.. ..=..    ..=.. .. ..    .. ..=.. ..
    ..=.. ..=..    ..=.. ..=..    .. ..=.. ..    .. ..=.. ..
    ..=.. ..=..    ..=.. ..=..    .. .. ..=..    .. ..=.. ..
    ..=.. ..=..    .. ..=..=..    ..=..=.. ..    .. ..=.. ..
}

fn r#match() {
    let val = match match match match match () {
        () => ()
    } {
        () => ()
    } {
        () => ()
    } {
        () => ()
    } {
        () => ()
    };
    assert_eq!(val, ());
}

fn i_yield() {
    static || {
        yield yield yield yield yield yield yield yield yield;
    };
}

fn match_nested_if() {
    let val = match () {
        () if if if if true {true} else {false} {true} else {false} {true} else {false} => true,
        _ => false,
    };
    assert!(val);
}

fn monkey_barrel() {
    let val = ()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=()=();
    assert_eq!(val, ());
}

pub fn main() {
    strange();
    funny();
    what();
    zombiejesus();
    notsure();
    canttouchthis();
    angrydome();
    evil_lincoln();
    dots();
    u8(8u8);
    fishy();
    union();
    special_characters();
    punch_card();
    r#match();
    i_yield();
    match_nested_if();
    monkey_barrel();
}
<|endoftext|>


<commit_before>use std::rc::*;
use super::treenode::*;

///
/// Trait implemented by types that can work as a tree node index
///
pub trait TreeNodeIndex {
    ///
    /// Finds the tree node corresponding to the specified index in the tree
    ///
    fn lookup_index<'a>(&'a self, parent_node: &'a TreeNode) -> Option<&Rc<TreeNode>>;
}

impl TreeNodeIndex for usize {
    ///
    /// Finds the tree node corresponding to the specified index in the tree
    ///
    fn lookup_index<'a>(&'a self, parent_node: &'a TreeNode) -> Option<&Rc<TreeNode>> {
        let mut pos = *self;
        let mut current_child = parent_node.get_child_ref().to_owned();

        loop {
            match current_child {
                None        => return None,
                Some(child) => {
                    if pos == 0 { return current_child; }

                    pos = pos-1;
                    current_child = child.get_sibling_ref().to_owned();
                }
            }
        }
    }
}

///
/// Provides the ability to reference the children of a tree node by looking up a particular index
///
pub trait TreeNodeLookup : TreeNode {
    ///
    /// Looks up a child node at a particular index (panics if the child does not exist)
    ///
    fn get_child_at<'a, TIndex: TreeNodeIndex>(&'a self, index: TIndex) -> &TreeNode where TIndex: 'a;
}

impl<T: TreeNode> TreeNodeLookup for T {
    ///
    /// Looks up a child node at a particular index (panics if the child does not exist)
    ///
    fn get_child_at<'a, TIndex: TreeNodeIndex>(&'a self, index: TIndex) -> &TreeNode where TIndex: 'a {
        let opt_node = index.lookup_index(self);
        let node_ref = opt_node.unwrap();

        &**node_ref
    }
}

/*
impl<TIndex: TreeNodeIndex> Index<TIndex> for TreeNode {
    type Output = TreeNode;

    fn index<'a>(&'a self, index: TIndex) -> &'a TreeNode {
        let opt_node = index.lookup_index(self);
        let node_ref = opt_node.unwrap();

        &**node_ref
    }
}
*/

#[cfg(test)]
mod treenode_index_tests {
    use super::super::values::*;
    use super::super::treenode::*;
    use super::super::basictree::*;
    use std::rc::*;

    #[test]
    fn can_get_first_child() {
        let mut tree = BasicTree::new("test", ());
        let first_child = Rc::new(BasicTree::new("first_child", ()));

        tree.set_child_ref(first_child);

        assert!(tree.get_child_at(0).is_some());
        assert!((tree.get_child_at(0).unwrap().get_tag()) == "child");
        assert!(tree.get_sibling_ref().is_none());
    }
}
<commit_msg>Try making lookup_index work by using a generic treenode (doesn't work, rust still moans incomprehensibly about type lifetimes)<commit_after>use std::rc::*;
use super::treenode::*;

///
/// Trait implemented by types that can work as a tree node index
///
pub trait TreeNodeIndex : Sized {
    ///
    /// Finds the tree node corresponding to the specified index in the tree
    ///
    fn lookup_index<'a, T: TreeNode>(&'a self, parent_node: &'a T) -> Option<&Rc<TreeNode>>;
}

impl TreeNodeIndex for usize {
    ///
    /// Finds the tree node corresponding to the specified index in the tree
    ///
    fn lookup_index<'a, T: TreeNode>(&'a self, parent_node: &'a T) -> Option<&Rc<TreeNode>> {
        let mut pos = *self;
        let mut current_child = parent_node.get_child_ref().to_owned();

        loop {
            match current_child {
                None        => return None,
                Some(child) => {
                    if pos == 0 { return current_child; }

                    pos = pos-1;
                    current_child = child.get_sibling_ref().to_owned();
                }
            }
        }
    }
}

///
/// Provides the ability to reference the children of a tree node by looking up a particular index
///
pub trait TreeNodeLookup : TreeNode {
    ///
    /// Looks up a child node at a particular index (panics if the child does not exist)
    ///
    fn get_child_at<TIndex: TreeNodeIndex>(&self, index: TIndex) -> &TreeNode;
}

impl<T: TreeNode> TreeNodeLookup for T {
    ///
    /// Looks up a child node at a particular index (panics if the child does not exist)
    ///
    fn get_child_at<TIndex: TreeNodeIndex>(&self, index: TIndex) -> &TreeNode {
        let opt_node = index.lookup_index(self);
        let node_ref = opt_node.unwrap();

        &**node_ref
    }
}

/*
impl<TIndex: TreeNodeIndex> Index<TIndex> for TreeNode {
    type Output = TreeNode;

    fn index<'a>(&'a self, index: TIndex) -> &'a TreeNode {
        let opt_node = index.lookup_index(self);
        let node_ref = opt_node.unwrap();

        &**node_ref
    }
}
*/

#[cfg(test)]
mod treenode_index_tests {
    use super::super::values::*;
    use super::super::treenode::*;
    use super::super::basictree::*;
    use std::rc::*;

    #[test]
    fn can_get_first_child() {
        let mut tree = BasicTree::new("test", ());
        let first_child = Rc::new(BasicTree::new("first_child", ()));

        tree.set_child_ref(first_child);

        assert!(tree.get_child_at(0).is_some());
        assert!((tree.get_child_at(0).unwrap().get_tag()) == "child");
        assert!(tree.get_sibling_ref().is_none());
    }
}
<|endoftext|>


<commit_before>use super::treenode::*;
use super::values::*;

///
/// Trait that provides some sugar functions that makes MutableTreeNode easier to use
///
pub trait MutableTreeNodeSugar : MutableTreeNode {
    ///
    /// Updates the child of this tree node
    ///
    fn set_child<TNode: ToTreeNode>(&mut self, new_node: TNode);

    ///
    /// Updates the sibling of this tree node
    ///
    fn set_sibling<TNode: ToTreeNode>(&mut self, new_node: TNode);

    ///
    /// Changes the value set for this node. Returns the same node so many nodes can be altered as part of a single statement.
    ///
    fn set_value<TValue: ToTreeValue>(&mut self, new_value: TValue);
}

impl<T: MutableTreeNode> MutableTreeNodeSugar for T {
    ///
    /// Updates the child of this tree node
    ///
    fn set_child<TNode: ToTreeNode>(&mut self, new_node: TNode) {
        self.set_child_ref(new_node.to_tree_node());
    }

    ///
    /// Updates the sibling of this tree node
    ///
    fn set_sibling<TNode: ToTreeNode>(&mut self, new_node: TNode) {
        self.set_sibling_ref(new_node.to_tree_node());
    }

    ///
    /// Changes the value set for this node. Returns the same node so many nodes can be altered as part of a single statement.
    ///
    fn set_value<TValue: ToTreeValue>(&mut self, new_value: TValue) {
        self.set_tree_value(new_value.to_tree_value());
    }
}
<commit_msg>Comment update<commit_after>use super::treenode::*;
use super::values::*;

///
/// Sugar functions for MutableTreeNode: various functions that can be implemented in terms of
/// the standard mutable tree node functions.
///
pub trait MutableTreeNodeSugar {
    ///
    /// Updates the child of this tree node
    ///
    fn set_child<TNode: ToTreeNode>(&mut self, new_node: TNode);

    ///
    /// Updates the sibling of this tree node
    ///
    fn set_sibling<TNode: ToTreeNode>(&mut self, new_node: TNode);

    ///
    /// Changes the value set for this node. Returns the same node so many nodes can be altered as part of a single statement.
    ///
    fn set_value<TValue: ToTreeValue>(&mut self, new_value: TValue);
}

impl<T: MutableTreeNode> MutableTreeNodeSugar for T {
    ///
    /// Updates the child of this tree node
    ///
    fn set_child<TNode: ToTreeNode>(&mut self, new_node: TNode) {
        self.set_child_ref(new_node.to_tree_node());
    }

    ///
    /// Updates the sibling of this tree node
    ///
    fn set_sibling<TNode: ToTreeNode>(&mut self, new_node: TNode) {
        self.set_sibling_ref(new_node.to_tree_node());
    }

    ///
    /// Changes the value set for this node. Returns the same node so many nodes can be altered as part of a single statement.
    ///
    fn set_value<TValue: ToTreeValue>(&mut self, new_value: TValue) {
        self.set_tree_value(new_value.to_tree_value());
    }
}
<|endoftext|>


<commit_before>//! Types dealing with ranges of values

extern mod extra;

use extra::time::Timespec;

/// A trait that normalizes a range bound for a type
pub trait Normalizable {
    /// Given a range bound, returns the normalized version of that bound. For
    /// discrete types such as i32, the normalized lower bound is always
    /// inclusive and the normalized upper bound is always exclusive. Other
    /// types, such as Timespec, have no normalization process so their
    /// implementation is a no-op.
    ///
    /// The logic here should match the logic performed by the equivalent
    /// Postgres type.
    fn normalize<S: BoundSided>(bound: RangeBound<S, Self>)
            -> RangeBound<S, Self>;
}

macro_rules! bounded_normalizable(
    ($t:ty) => (
        impl Normalizable for $t {
            fn normalize<S: BoundSided>(bound: RangeBound<S, $t>)
                    -> RangeBound<S, $t> {
                match BoundSided::side(None::<S>) {
                    Upper if bound.type_ == Inclusive => {
                        assert!(bound.value != Bounded::max_value());
                        RangeBound::new(bound.value + 1, Exclusive)
                    }
                    Lower if bound.type_ == Exclusive => {
                        assert!(bound.value != Bounded::max_value());
                        RangeBound::new(bound.value + 1, Inclusive)
                    }
                    _ => bound
                }
            }
        }
    )
)

bounded_normalizable!(i32)
bounded_normalizable!(i64)

impl Normalizable for Timespec {
    fn normalize<S: BoundSided>(bound: RangeBound<S, Timespec>)
            -> RangeBound<S, Timespec> {
        bound
    }
}

enum BoundSide {
    Upper,
    Lower
}

trait BoundSided {
    // param is a hack to get around lack of hints for self type
    fn side(_: Option<Self>) -> BoundSide;
}

/// A tag type representing an upper bound
#[deriving(Eq,Clone)]
pub struct UpperBound;

/// A tag type representing a lower bound
#[deriving(Eq,Clone)]
pub struct LowerBound;

impl BoundSided for UpperBound {
    fn side(_: Option<UpperBound>) -> BoundSide {
        Upper
    }
}

impl BoundSided for LowerBound {
    fn side(_: Option<LowerBound>) -> BoundSide {
        Lower
    }
}

/// The type of a range bound
#[deriving(Eq,Clone)]
pub enum BoundType {
    /// The bound includes its value
    Inclusive,
    /// The bound excludes its value
    Exclusive
}

/// Represents a one-sided bound.
///
/// The side is determined by the `S` phantom parameter.
#[deriving(Eq,Clone)]
pub struct RangeBound<S, T> {
    /// The value of the bound
    value: T,
    /// The type of the bound
    type_: BoundType
}

impl<S: BoundSided, T: Ord> Ord for RangeBound<S, T> {
    fn lt(&self, other: &RangeBound<S, T>) -> bool {
        match (BoundSided::side(None::<S>), self.type_, other.type_) {
            (Upper, Exclusive, Inclusive)
            | (Lower, Inclusive, Exclusive) => self.value <= other.value,
            _ => self.value < other.value
        }
    }
}

impl<S: BoundSided, T: Ord> RangeBound<S, T> {
    /// Constructs a new range bound
    pub fn new(value: T, type_: BoundType) -> RangeBound<S, T> {
        RangeBound { value: value, type_: type_ }
    }

    /// Determines if a value lies within the range specified by this bound.
    pub fn in_bounds(&self, value: &T) -> bool {
        match (self.type_, BoundSided::side(None::<S>)) {
            (Inclusive, Upper) if value <= &self.value => true,
            (Exclusive, Upper) if value < &self.value => true,
            (Inclusive, Lower) if value >= &self.value => true,
            (Exclusive, Lower) if value > &self.value => true,
            _ => false
        }
    }
}

/// Represents a range of values.
#[deriving(Eq,Clone)]
pub enum Range<T> {
    priv Empty,
    priv Normal(Option<RangeBound<LowerBound, T>>,
                Option<RangeBound<UpperBound, T>>)
}

impl<T: Ord+Normalizable> Range<T> {
    /// Creates a new range.
    ///
    /// If a bound is `None`, the range is unbounded in that direction.
    pub fn new(lower: Option<RangeBound<LowerBound, T>>,
               upper: Option<RangeBound<UpperBound, T>>) -> Range<T> {
        let lower = lower.map(|bound| { Normalizable::normalize(bound) });
        let upper = upper.map(|bound| { Normalizable::normalize(bound) });

        match (&lower, &upper) {
            (&Some(ref lower), &Some(ref upper)) =>
                assert!(lower.value <= upper.value),
            _ => {}
        }

        Normal(lower, upper)
    }

    /// Creates a new empty range.
    pub fn empty() -> Range<T> {
        Empty
    }

    /// Determines if this range is the empty range.
    pub fn is_empty(&self) -> bool {
        match *self {
            Empty => true,
            Normal(*) => false
        }
    }

    /// Returns the lower bound if it exists.
    pub fn lower<'a>(&'a self) -> &'a Option<RangeBound<LowerBound, T>> {
        match *self {
            Empty => &None,
            Normal(ref lower, _) => lower
        }
    }

    /// Returns the upper bound if it exists.
    pub fn upper<'a>(&'a self) -> &'a Option<RangeBound<UpperBound, T>> {
        match *self {
            Empty => &None,
            Normal(_, ref upper) => upper
        }
    }

    /// Determines if a value lies within this range.
    pub fn contains(&self, value: &T) -> bool {
        match *self {
            Empty => false,
            Normal(ref lower, ref upper) => {
                lower.as_ref().map_default(true, |b| { b.in_bounds(value) }) &&
                    upper.as_ref().map_default(true, |b| { b.in_bounds(value) })
            }
        }
    }
}

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

    #[test]
    fn test_range_bound_lower_lt() {
        fn check(val1: int, inc1: BoundType, val2: int, inc2: BoundType, expected: bool) {
            let a: RangeBound<LowerBound, int> = RangeBound::new(val1, inc1);
            let b: RangeBound<LowerBound, int> = RangeBound::new(val2, inc2);
            assert_eq!(expected, a < b);
        }

        check(1, Inclusive, 2, Exclusive, true);
        check(1, Exclusive, 2, Inclusive, true);
        check(1, Inclusive, 1, Exclusive, true);
        check(2, Inclusive, 1, Inclusive, false);
        check(2, Exclusive, 1, Exclusive, false);
        check(1, Exclusive, 1, Inclusive, false);
        check(1, Exclusive, 1, Exclusive, false);
        check(1, Inclusive, 1, Inclusive, false);
    }

    #[test]
    fn test_range_bound_upper_lt() {
        fn check(val1: int, inc1: BoundType, val2: int, inc2: BoundType, expected: bool) {
            let a: RangeBound<UpperBound, int> = RangeBound::new(val1, inc1);
            let b: RangeBound<UpperBound, int> = RangeBound::new(val2, inc2);
            assert_eq!(expected, a < b);
        }

        check(1, Inclusive, 2, Exclusive, true);
        check(1, Exclusive, 2, Exclusive, true);
        check(1, Exclusive, 1, Inclusive, true);
        check(2, Inclusive, 1, Inclusive, false);
        check(2, Exclusive, 1, Exclusive, false);
        check(1, Inclusive, 1, Exclusive, false);
        check(1, Inclusive, 1, Inclusive, false);
        check(1, Exclusive, 1, Exclusive, false);
    }

    #[test]
    fn test_range_bound_lower_in_bounds() {
        fn check(bound: int, inc: BoundType, val: int, expected: bool) {
            let b: RangeBound<LowerBound, int> = RangeBound::new(bound, inc);
            assert_eq!(expected, b.in_bounds(&val));
        }

        check(1, Inclusive, 1, true);
        check(1, Exclusive, 1, false);
        check(1, Inclusive, 2, true);
        check(1, Inclusive, 0, false);
    }

    #[test]
    fn test_range_bound_upper_in_bounds() {
        fn check(bound: int, inc: BoundType, val: int, expected: bool) {
            let b: RangeBound<UpperBound, int> = RangeBound::new(bound, inc);
            assert_eq!(expected, b.in_bounds(&val));
        }

        check(1, Inclusive, 1, true);
        check(1, Exclusive, 1, false);
        check(1, Inclusive, 2, false);
        check(1, Inclusive, 0, true);
    }

    #[test]
    fn test_range_contains() {
        let r =  Range::new(Some(RangeBound::new(1i32, Inclusive)),
                            Some(RangeBound::new(3i32, Inclusive)));
        assert!(!r.contains(&4));
        assert!(r.contains(&3));
        assert!(r.contains(&2));
        assert!(r.contains(&1));
        assert!(!r.contains(&0));

        let r =  Range::new(Some(RangeBound::new(1i32, Exclusive)),
                            Some(RangeBound::new(3i32, Exclusive)));
        assert!(!r.contains(&4));
        assert!(!r.contains(&3));
        assert!(r.contains(&2));
        assert!(!r.contains(&1));
        assert!(!r.contains(&0));

        let r = Range::new(None, Some(RangeBound::new(3i32, Inclusive)));
        assert!(!r.contains(&4));
        assert!(r.contains(&2));
        assert!(r.contains(&Bounded::min_value()));

        let r = Range::new(Some(RangeBound::new(1i32, Inclusive)), None);
        assert!(r.contains(&Bounded::max_value()));
        assert!(r.contains(&4));
        assert!(!r.contains(&0));

        let r = Range::new(None, None);
        assert!(r.contains(&Bounded::max_value()));
        assert!(r.contains(&0i32));
        assert!(r.contains(&Bounded::min_value()));
    }

    #[test]
    fn test_normalize_lower() {
        let r: RangeBound<LowerBound, i32> = RangeBound::new(10i32, Inclusive);
        assert_eq!(RangeBound::new(10i32, Inclusive), Normalizable::normalize(r));

        let r: RangeBound<LowerBound, i32> = RangeBound::new(10i32, Exclusive);
        assert_eq!(RangeBound::new(11i32, Inclusive), Normalizable::normalize(r));
    }

    #[test]
    fn test_normalize_upper() {
        let r: RangeBound<UpperBound, i32> = RangeBound::new(10i32, Inclusive);
        assert_eq!(RangeBound::new(11i32, Exclusive), Normalizable::normalize(r));

        let r: RangeBound<UpperBound, i32> = RangeBound::new(10i32, Exclusive);
        assert_eq!(RangeBound::new(10i32, Exclusive), Normalizable::normalize(r));
    }

    #[test]
    fn test_range_normalizes() {
        let r1 = Range::new(Some(RangeBound::new(10i32, Exclusive)),
                            Some(RangeBound::new(15i32, Inclusive)));
        let r2 = Range::new(Some(RangeBound::new(11i32, Inclusive)),
                            Some(RangeBound::new(16i32, Exclusive)));
        assert_eq!(r1, r2);
    }
}
<commit_msg>More Range work<commit_after>//! Types dealing with ranges of values

extern mod extra;

use std::cmp;
use extra::time::Timespec;

/// A trait that normalizes a range bound for a type
pub trait Normalizable {
    /// Given a range bound, returns the normalized version of that bound. For
    /// discrete types such as i32, the normalized lower bound is always
    /// inclusive and the normalized upper bound is always exclusive. Other
    /// types, such as Timespec, have no normalization process so their
    /// implementation is a no-op.
    ///
    /// The logic here should match the logic performed by the equivalent
    /// Postgres type.
    fn normalize<S: BoundSided>(bound: RangeBound<S, Self>)
            -> RangeBound<S, Self>;
}

macro_rules! bounded_normalizable(
    ($t:ty) => (
        impl Normalizable for $t {
            fn normalize<S: BoundSided>(bound: RangeBound<S, $t>)
                    -> RangeBound<S, $t> {
                match BoundSided::side(None::<S>) {
                    Upper if bound.type_ == Inclusive => {
                        assert!(bound.value != Bounded::max_value());
                        RangeBound::new(bound.value + 1, Exclusive)
                    }
                    Lower if bound.type_ == Exclusive => {
                        assert!(bound.value != Bounded::max_value());
                        RangeBound::new(bound.value + 1, Inclusive)
                    }
                    _ => bound
                }
            }
        }
    )
)

bounded_normalizable!(i32)
bounded_normalizable!(i64)

impl Normalizable for Timespec {
    fn normalize<S: BoundSided>(bound: RangeBound<S, Timespec>)
            -> RangeBound<S, Timespec> {
        bound
    }
}

enum BoundSide {
    Upper,
    Lower
}

trait BoundSided {
    // param is a hack to get around lack of hints for self type
    fn side(_: Option<Self>) -> BoundSide;
}

/// A tag type representing an upper bound
#[deriving(Eq,Clone)]
pub struct UpperBound;

/// A tag type representing a lower bound
#[deriving(Eq,Clone)]
pub struct LowerBound;

impl BoundSided for UpperBound {
    fn side(_: Option<UpperBound>) -> BoundSide {
        Upper
    }
}

impl BoundSided for LowerBound {
    fn side(_: Option<LowerBound>) -> BoundSide {
        Lower
    }
}

/// The type of a range bound
#[deriving(Eq,Clone)]
pub enum BoundType {
    /// The bound includes its value
    Inclusive,
    /// The bound excludes its value
    Exclusive
}

/// Represents a one-sided bound.
///
/// The side is determined by the `S` phantom parameter.
#[deriving(Eq,Clone)]
pub struct RangeBound<S, T> {
    /// The value of the bound
    value: T,
    /// The type of the bound
    type_: BoundType
}

impl<S: BoundSided, T: Ord> Ord for RangeBound<S, T> {
    fn lt(&self, other: &RangeBound<S, T>) -> bool {
        match (BoundSided::side(None::<S>), self.type_, other.type_) {
            (Upper, Exclusive, Inclusive)
            | (Lower, Inclusive, Exclusive) => self.value <= other.value,
            _ => self.value < other.value
        }
    }
}

impl<S: BoundSided, T: Ord> RangeBound<S, T> {
    /// Constructs a new range bound
    pub fn new(value: T, type_: BoundType) -> RangeBound<S, T> {
        RangeBound { value: value, type_: type_ }
    }

    /// Determines if a value lies within the range specified by this bound.
    pub fn in_bounds(&self, value: &T) -> bool {
        match (self.type_, BoundSided::side(None::<S>)) {
            (Inclusive, Upper) if value <= &self.value => true,
            (Exclusive, Upper) if value < &self.value => true,
            (Inclusive, Lower) if value >= &self.value => true,
            (Exclusive, Lower) if value > &self.value => true,
            _ => false
        }
    }
}

/// Represents a range of values.
#[deriving(Eq,Clone)]
pub enum Range<T> {
    priv Empty,
    priv Normal(Option<RangeBound<LowerBound, T>>,
                Option<RangeBound<UpperBound, T>>)
}

impl<T: Ord+Normalizable> Range<T> {
    /// Creates a new range.
    ///
    /// If a bound is `None`, the range is unbounded in that direction.
    pub fn new(lower: Option<RangeBound<LowerBound, T>>,
               upper: Option<RangeBound<UpperBound, T>>) -> Range<T> {
        let lower = lower.map(|bound| { Normalizable::normalize(bound) });
        let upper = upper.map(|bound| { Normalizable::normalize(bound) });

        match (&lower, &upper) {
            (&Some(ref lower), &Some(ref upper)) => {
                let empty = match (lower.type_, upper.type_) {
                    (Inclusive, Inclusive) => lower.value > upper.value,
                    _ => lower.value >= upper.value
                };
                if empty {
                    return Empty;
                }
            }
            _ => {}
        }

        Normal(lower, upper)
    }

    /// Creates a new empty range.
    pub fn empty() -> Range<T> {
        Empty
    }

    /// Determines if this range is the empty range.
    pub fn is_empty(&self) -> bool {
        match *self {
            Empty => true,
            Normal(*) => false
        }
    }

    /// Returns the lower bound if it exists.
    pub fn lower<'a>(&'a self) -> &'a Option<RangeBound<LowerBound, T>> {
        match *self {
            Empty => &None,
            Normal(ref lower, _) => lower
        }
    }

    /// Returns the upper bound if it exists.
    pub fn upper<'a>(&'a self) -> &'a Option<RangeBound<UpperBound, T>> {
        match *self {
            Empty => &None,
            Normal(_, ref upper) => upper
        }
    }

    /// Determines if a value lies within this range.
    pub fn contains(&self, value: &T) -> bool {
        match *self {
            Empty => false,
            Normal(ref lower, ref upper) => {
                lower.as_ref().map_default(true, |b| { b.in_bounds(value) }) &&
                    upper.as_ref().map_default(true, |b| { b.in_bounds(value) })
            }
        }
    }
}

impl<T: Ord+Normalizable+Clone> Range<T> {
    /// Returns the intersection of this range with another
    pub fn intersect(&self, other: &Range<T>) -> Range<T> {
        if self.is_empty() || other.is_empty() {
            return Range::empty();
        }

        let lower = match (self.lower(), other.lower()) {
            (&Some(ref a), &Some(ref b)) => Some(cmp::max(a, b).clone()),
            (&Some(ref a), &None) => Some(a.clone()),
            (&None, &Some(ref b)) => Some(b.clone()),
            (&None, &None) => None
        };

        let upper = match (self.upper(), other.upper()) {
            (&Some(ref a), &Some(ref b)) => Some(cmp::min(a, b).clone()),
            (&Some(ref a), &None) => Some(a.clone()),
            (&None, &Some(ref b)) => Some(b.clone()),
            (&None, &None) => None
        };

        Range::new(lower, upper)
    }
}

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

    #[test]
    fn test_range_bound_lower_lt() {
        fn check(val1: int, inc1: BoundType, val2: int, inc2: BoundType, expected: bool) {
            let a: RangeBound<LowerBound, int> = RangeBound::new(val1, inc1);
            let b: RangeBound<LowerBound, int> = RangeBound::new(val2, inc2);
            assert_eq!(expected, a < b);
        }

        check(1, Inclusive, 2, Exclusive, true);
        check(1, Exclusive, 2, Inclusive, true);
        check(1, Inclusive, 1, Exclusive, true);
        check(2, Inclusive, 1, Inclusive, false);
        check(2, Exclusive, 1, Exclusive, false);
        check(1, Exclusive, 1, Inclusive, false);
        check(1, Exclusive, 1, Exclusive, false);
        check(1, Inclusive, 1, Inclusive, false);
    }

    #[test]
    fn test_range_bound_upper_lt() {
        fn check(val1: int, inc1: BoundType, val2: int, inc2: BoundType, expected: bool) {
            let a: RangeBound<UpperBound, int> = RangeBound::new(val1, inc1);
            let b: RangeBound<UpperBound, int> = RangeBound::new(val2, inc2);
            assert_eq!(expected, a < b);
        }

        check(1, Inclusive, 2, Exclusive, true);
        check(1, Exclusive, 2, Exclusive, true);
        check(1, Exclusive, 1, Inclusive, true);
        check(2, Inclusive, 1, Inclusive, false);
        check(2, Exclusive, 1, Exclusive, false);
        check(1, Inclusive, 1, Exclusive, false);
        check(1, Inclusive, 1, Inclusive, false);
        check(1, Exclusive, 1, Exclusive, false);
    }

    #[test]
    fn test_range_bound_lower_in_bounds() {
        fn check(bound: int, inc: BoundType, val: int, expected: bool) {
            let b: RangeBound<LowerBound, int> = RangeBound::new(bound, inc);
            assert_eq!(expected, b.in_bounds(&val));
        }

        check(1, Inclusive, 1, true);
        check(1, Exclusive, 1, false);
        check(1, Inclusive, 2, true);
        check(1, Inclusive, 0, false);
    }

    #[test]
    fn test_range_bound_upper_in_bounds() {
        fn check(bound: int, inc: BoundType, val: int, expected: bool) {
            let b: RangeBound<UpperBound, int> = RangeBound::new(bound, inc);
            assert_eq!(expected, b.in_bounds(&val));
        }

        check(1, Inclusive, 1, true);
        check(1, Exclusive, 1, false);
        check(1, Inclusive, 2, false);
        check(1, Inclusive, 0, true);
    }

    #[test]
    fn test_range_contains() {
        let r =  Range::new(Some(RangeBound::new(1i32, Inclusive)),
                            Some(RangeBound::new(3i32, Inclusive)));
        assert!(!r.contains(&4));
        assert!(r.contains(&3));
        assert!(r.contains(&2));
        assert!(r.contains(&1));
        assert!(!r.contains(&0));

        let r =  Range::new(Some(RangeBound::new(1i32, Exclusive)),
                            Some(RangeBound::new(3i32, Exclusive)));
        assert!(!r.contains(&4));
        assert!(!r.contains(&3));
        assert!(r.contains(&2));
        assert!(!r.contains(&1));
        assert!(!r.contains(&0));

        let r = Range::new(None, Some(RangeBound::new(3i32, Inclusive)));
        assert!(!r.contains(&4));
        assert!(r.contains(&2));
        assert!(r.contains(&Bounded::min_value()));

        let r = Range::new(Some(RangeBound::new(1i32, Inclusive)), None);
        assert!(r.contains(&Bounded::max_value()));
        assert!(r.contains(&4));
        assert!(!r.contains(&0));

        let r = Range::new(None, None);
        assert!(r.contains(&Bounded::max_value()));
        assert!(r.contains(&0i32));
        assert!(r.contains(&Bounded::min_value()));
    }

    #[test]
    fn test_normalize_lower() {
        let r: RangeBound<LowerBound, i32> = RangeBound::new(10i32, Inclusive);
        assert_eq!(RangeBound::new(10i32, Inclusive), Normalizable::normalize(r));

        let r: RangeBound<LowerBound, i32> = RangeBound::new(10i32, Exclusive);
        assert_eq!(RangeBound::new(11i32, Inclusive), Normalizable::normalize(r));
    }

    #[test]
    fn test_normalize_upper() {
        let r: RangeBound<UpperBound, i32> = RangeBound::new(10i32, Inclusive);
        assert_eq!(RangeBound::new(11i32, Exclusive), Normalizable::normalize(r));

        let r: RangeBound<UpperBound, i32> = RangeBound::new(10i32, Exclusive);
        assert_eq!(RangeBound::new(10i32, Exclusive), Normalizable::normalize(r));
    }

    #[test]
    fn test_range_normalizes() {
        let r1 = Range::new(Some(RangeBound::new(10i32, Exclusive)),
                            Some(RangeBound::new(15i32, Inclusive)));
        let r2 = Range::new(Some(RangeBound::new(11i32, Inclusive)),
                            Some(RangeBound::new(16i32, Exclusive)));
        assert_eq!(r1, r2);
    }

    #[test]
    fn test_range_empty() {
        assert!(Range::new(Some(RangeBound::new(9i32, Exclusive)),
                           Some(RangeBound::new(10i32, Exclusive))).is_empty());
        assert!(Range::new(Some(RangeBound::new(10i32, Inclusive)),
                           Some(RangeBound::new(10i32, Exclusive))).is_empty());
        assert!(Range::new(Some(RangeBound::new(10i32, Exclusive)),
                           Some(RangeBound::new(10i32, Inclusive))).is_empty());
        assert!(Range::new(Some(RangeBound::new(10i32, Inclusive)),
                           Some(RangeBound::new(9i32, Inclusive))).is_empty());
    }

    #[test]
    fn test_intersection() {
        let r1 = Range::new(Some(RangeBound::new(10i32, Inclusive)),
                            Some(RangeBound::new(15i32, Exclusive)));
        let r2 = Range::new(Some(RangeBound::new(20i32, Exclusive)),
                            Some(RangeBound::new(25i32, Inclusive)));
        assert!(r1.intersect(&r2).is_empty());
        assert!(r2.intersect(&r1).is_empty());
        assert_eq!(r1, r1.intersect(&Range::new(None, None)));
        assert_eq!(r1, Range::new(None, None).intersect(&r1));

        let r2 = Range::new(Some(RangeBound::new(10i32, Exclusive)), None);
        let exp = Range::new(r2.lower().clone(), r1.upper().clone());
        assert_eq!(exp, r1.intersect(&r2));
        assert_eq!(exp, r2.intersect(&r1));

        let r2 = Range::new(None, Some(RangeBound::new(15i32, Inclusive)));
        assert_eq!(r1, r1.intersect(&r2));
        assert_eq!(r1, r2.intersect(&r1));

        let r2 = Range::new(Some(RangeBound::new(11i32, Inclusive)),
                            Some(RangeBound::new(14i32, Exclusive)));
        assert_eq!(r2, r1.intersect(&r2));
        assert_eq!(r2, r2.intersect(&r1));
    }
}
<|endoftext|>


<commit_before>extern crate getopts;
extern crate notify;

use self::notify::{Watcher, RecursiveMode, DebouncedEvent};
use std::sync::mpsc::channel;
use std::time::Duration;
use std::env;
use std::fs;

/// watches the debug build, restarts server on build
pub fn watcher (matches: &getopts::Matches) {
    if matches.opt_present("w") && matches.opt_present("d") {

        let stratis_path = env::var("STRATIS_DEBUG").expect("no \'STRATIS_DEBUG\' path found in environment vars");

        let (tx, rx) = channel();
        let mut w = self::notify::watcher(tx,Duration::from_secs(5)).expect("unable to create filesys watcher");

        w.watch(stratis_path.clone(),RecursiveMode::NonRecursive).expect("unable to watch directory");

        for n in rx.recv() {
            match n {
                DebouncedEvent::Write(path) => {
                    //FIXME: this simply crashes on windows
                    let r = fs::copy(path,stratis_path.clone()+"PAN_stratis.exe");
                    println!("watcher-copy:{:?}",r);
                },
                _ => {},
            }
        }

    }
}
<commit_msg>fix watcher<commit_after>extern crate getopts;
extern crate notify;

use self::notify::{Watcher, RecursiveMode, DebouncedEvent};
use std::sync::mpsc::channel;
use std::time::Duration;
use std::env;
use std::fs;

/// watches the debug build, restarts server on build
pub fn watcher (matches: &getopts::Matches) {
    if matches.opt_present("w") && matches.opt_present("d") {

        let stratis_path = env::var("STRATIS_DEBUG").expect("no \'STRATIS_DEBUG\' path found in environment vars");

        let (tx, rx) = channel();
        let mut w = self::notify::watcher(tx,Duration::from_secs(5)).expect("unable to create filesys watcher");

        w.watch(stratis_path.clone()+"\\stratis.exe",RecursiveMode::NonRecursive).expect("unable to watch directory");

        for n in rx.iter() {
            println!("event: {:?}",n);
            match n {
                DebouncedEvent::Write(path) => {
                    let r = fs::copy(path,stratis_path.clone()+"\\PAN_stratis.exe");
                    println!("watcher-copy:{:?}",r);
                },
                _ => {  },
            }
        }

    }
}
<|endoftext|>


<commit_before>fn main() {
    let m = matrix_from_vec(vec![2, -1, 5, 1, 3, 2, 2, -6, 1, 3, 3, -1, 5, -2, -3, 3], 4);
    let mm = m.solve(&vec![-3, -32, -47, 49]);
    println!("{:?}", mm);
}

#[derive(Clone)]
struct Matrix {
    elts: Vec<Vec<i64>>,
    dim: usize,
}

impl Matrix {
    // Compute determinant with the cofactor method
    // Using Gaussian elimination would have been more efficient, but it also solves the linear
    // system, so…
    fn det(&self) -> f64 {
        match self.dim {
            0 => 0.,
            1 => self.elts[0][0] as f64,
            2 => (self.elts[0][0] * self.elts[1][1] - self.elts[0][1] * self.elts[1][0]) as f64,
            d => {
                let mut acc = 0.;
                let mut coeff = 1.;
                for k in 0..d {
                    acc += coeff * self.elts[0][k] as f64 * self.comatrix(0, k).det();
                    coeff *= -1.
                }
                acc
            }
        }
    }

    // Solve linear systems using Cramer's method
    fn solve(&self, target: &Vec<i64>) -> Vec<f64> {
        let mut solution: Vec<f64> = vec![0.; self.dim];
        let denominator = self.det();
        for j in 0..self.dim {
            let mut mm = self.clone();
            for i in 0..self.dim {
                mm.elts[i][j] = target[i]
            }
            solution[j] = mm.det() / denominator
        }
        solution
    }

    // Compute a cofactor matrix for determinant computation
    fn comatrix(&self, k: usize, l: usize) -> Matrix {
        let mut v: Vec<i64> = vec![];
        for i in 0..self.dim {
            for j in 0..self.dim {
                if i != k && j != l {
                    v.push(self.elts[i][j])
                }
            }
        }
        matrix_from_vec(v, self.dim - 1)
    }
}

fn matrix_from_vec(v: Vec<i64>, dim: usize) -> Matrix {
    assert_eq!(v.len(), dim * dim);
    let mut elts = vec![vec!(0, dim); dim];
    for i in 0..dim {
        for j in 0..dim {
            elts[i][j] = v[i * dim + j]
        }
    }
    Matrix { elts, dim }
}
<commit_msg>Add tests and simplify matrix accesses<commit_after>use std::ops::{Index, IndexMut};

fn main() {
    let m = matrix(
        vec![
            2., -1., 5., 1., 3., 2., 2., -6., 1., 3., 3., -1., 5., -2., -3., 3.,
        ],
        4,
    );
    let mm = m.solve(&vec![-3., -32., -47., 49.]);
    println!("{:?}", mm);
}

#[derive(Clone)]
struct Matrix {
    elts: Vec<f64>,
    dim: usize,
}

impl Matrix {
    // Compute determinant using cofactor method
    // Using Gaussian elimination would have been more efficient, but it also solves the linear
    // system, so…
    fn det(&self) -> f64 {
        match self.dim {
            0 => 0.,
            1 => self[0][0],
            2 => self[0][0] * self[1][1] - self[0][1] * self[1][0],
            d => {
                let mut acc = 0.;
                let mut signature = 1.;
                for k in 0..d {
                    acc += signature * self[0][k] * self.comatrix(0, k).det();
                    signature *= -1.
                }
                acc
            }
        }
    }

    // Solve linear systems using Cramer's method
    fn solve(&self, target: &Vec<f64>) -> Vec<f64> {
        let mut solution: Vec<f64> = vec![0.; self.dim];
        let denominator = self.det();
        for j in 0..self.dim {
            let mut mm = self.clone();
            for i in 0..self.dim {
                mm[i][j] = target[i]
            }
            solution[j] = mm.det() / denominator
        }
        solution
    }

    // Compute the cofactor matrix for determinant computations
    fn comatrix(&self, k: usize, l: usize) -> Matrix {
        let mut v: Vec<f64> = vec![];
        for i in 0..self.dim {
            for j in 0..self.dim {
                if i != k && j != l {
                    v.push(self[i][j])
                }
            }
        }
        matrix(v, self.dim - 1)
    }
}

fn matrix(elts: Vec<f64>, dim: usize) -> Matrix {
    assert_eq!(elts.len(), dim * dim);
    Matrix { elts, dim }
}

impl Index<usize> for Matrix {
    type Output = [f64];

    fn index(&self, i: usize) -> &Self::Output {
        let m = self.dim;
        &self.elts[m * i..m * (i + 1)]
    }
}

impl IndexMut<usize> for Matrix {
    fn index_mut(&mut self, i: usize) -> &mut Self::Output {
        let m = self.dim;
        &mut self.elts[m * i..m * (i + 1)]
    }
}

#[test]
fn test_create_and_access() {
    let m = matrix(vec![1., 2., 3., 4.], 2);
    assert_eq!(m[0][0], 1.);
    assert_eq!(m[0][1], 2.);
    assert_eq!(m[1][0], 3.);
    assert_eq!(m[1][1], 4.);
}

#[test]
fn test_determinant() {
    let dim = 5;
    let mut m = matrix(vec![0.; dim * dim], dim);
    (0..dim).for_each(|i| (0..=i).for_each(|j| m[i][j] = 1.));
    assert_eq!(m.det(), 1.);
    let m = matrix(
        vec![
            1., -5., 2., 1., -5., -7., 0., 3., 0., 3., 4., 1., 41., 0., -1., 0.,
        ],
        4,
    );
    assert_eq!(m.det(), -2680.);
}

#[test]
fn test_solve() {
    let m = matrix(
        vec![
            1., -5., 2., 1., -5., -7., 0., 3., 0., 3., 4., 1., 41., 0., -1., 0.,
        ],
        4,
    );
    let b = vec![153., 219., -94., -41.];
    assert_eq!(m.solve(&b), vec![-1., -31., 0., -1.])
}
<|endoftext|>


<commit_before>
use wtest_basic::*;

#[cfg( feature = "in_wtools" )]
use wtools::string as TheModule;
#[cfg( not( feature = "in_wtools" ) )]
use wstring_tools as TheModule;

//

fn _basic()
{

  // test.case( "delimeter : "b" );
  let src = "abc def";
  let iter = TheModule::string::split()
  .src( src )
  .delimeter( "bc" )
  .form();
  // assert_eq!( iter.collect::< Vec< _ > >(), vec![ "a", "bc", " def" ] );
  assert_eq!( iter.map( | e | String::from( e ) ).collect::< Vec< _ > >(), vec![ "a", "bc", " def" ] );

}

//

test_suite!
{
  basic,
}
<commit_msg>Write test routines  `split_with_option_preserving_empty`, `split_with_option_preserving_delimeters`, `split_with_option_stripping`<commit_after>
use wtest_basic::*;

#[cfg( feature = "in_wtools" )]
use wtools::string as TheModule;
#[cfg( not( feature = "in_wtools" ) )]
use wstring_tools as TheModule;

//

fn _basic()
{

  // test.case( "delimeter : "b" );
  let src = "abc def";
  let iter = TheModule::string::split()
  .src( src )
  .delimeter( "bc" )
  .stripping( false )
  .form();
  // assert_eq!( iter.collect::< Vec< _ > >(), vec![ "a", "bc", " def" ] );
  assert_eq!( iter.map( | e | String::from( e ) ).collect::< Vec< _ > >(), vec![ "a", "bc", " def" ] );

}

//

fn _split_with_option_preserving_empty()
{
  let src = "a b c";
  let iter = TheModule::string::split()
  .src( src )
  .delimeter( " " )
  .preserving_empty( true )
  .stripping( false )
  .form();
  assert_eq!( iter.map( | e | String::from( e ) ).collect::< Vec< _ > >(), vec![ "a", " ", "b", " ", "c" ] );

  let src = "a b c";
  let iter = TheModule::string::split()
  .src( src )
  .delimeter( " " )
  .preserving_empty( false )
  .stripping( false )
  .form();
  assert_eq!( iter.map( | e | String::from( e ) ).collect::< Vec< _ > >(), vec![ "a", " ", "b", " ", "c" ] );

  /* */

  let src = "a b c";
  let iter = TheModule::string::split()
  .src( src )
  .delimeter( " " )
  .preserving_empty( true )
  .stripping( true )
  .form();
  assert_eq!( iter.map( | e | String::from( e ) ).collect::< Vec< _ > >(), vec![ "a", "", "b", "", "c" ] );

  let src = "a b c";
  let iter = TheModule::string::split()
  .src( src )
  .delimeter( " " )
  .preserving_empty( false )
  .stripping( true )
  .form();
  assert_eq!( iter.map( | e | String::from( e ) ).collect::< Vec< _ > >(), vec![ "a", "b", "c" ] );
}

//

fn _split_with_option_preserving_delimeters()
{
  let src = "a b c";
  let iter = TheModule::string::split()
  .src( src )
  .delimeter( " " )
  .preserving_delimeters( true )
  .stripping( false )
  .form();
  assert_eq!( iter.map( | e | String::from( e ) ).collect::< Vec< _ > >(), vec![ "a", " ", "b", " ", "c" ] );

  let src = "a b c";
  let iter = TheModule::string::split()
  .src( src )
  .delimeter( " " )
  .preserving_delimeters( false )
  .stripping( false )
  .form();
  assert_eq!( iter.map( | e | String::from( e ) ).collect::< Vec< _ > >(), vec![ "a", "b", "c" ] );
}

//

fn _split_with_option_stripping()
{
  let src = "a b c";
  let iter = TheModule::string::split()
  .src( src )
  .delimeter( " " )
  .stripping( true )
  .form();
  assert_eq!( iter.map( | e | String::from( e ) ).collect::< Vec< _ > >(), vec![ "a", "", "b", "", "c" ] );

  let src = "a b c";
  let iter = TheModule::string::split()
  .src( src )
  .delimeter( " " )
  .stripping( false )
  .form();
  assert_eq!( iter.map( | e | String::from( e ) ).collect::< Vec< _ > >(), vec![ "a", " ", "b", " ", "c" ] );
}

//

test_suite!
{
  basic,
  split_with_option_preserving_empty,
  split_with_option_preserving_delimeters,
  split_with_option_stripping,
}
<|endoftext|>


<commit_before>
#[ allow( unused_imports ) ]
use super::*;

//

tests_impls!
{

  #[ cfg( any( feature = "chrono", feature = "time_chrono" ) ) ]
  #[ test ]
  fn basic()
  {
    use TheModule::*;

    // test.case( "time::now" );
    let got = time::now();
    assert!( got > 0 );

    // test.case( "time::ms::now" );
    let got1 = time::now();
    let got2 = time::ms::now();
    a_id!( got1, got2 );

    // // test.case( "time::ns::now" );
    // let got1 = time::now();
    // let got2 = time::ns::now();
    // a_id!( got1, got2 / 1000000 );
    // zzz : use equal!

    // test.case( "time::s::now" );
    let got1 = time::now();
    let got2 = time::s::now();
    a_id!( got1 / 1000, got2 );
  }

}

//

tests_index!
{
  basic,
}
<commit_msg>Fix tests of module `time_tools`, add time delta to test checks<commit_after>
#[ allow( unused_imports ) ]
use super::*;

//

tests_impls!
{

  #[ cfg( any( feature = "chrono", feature = "time_chrono" ) ) ]
  fn basic()
  {
    use TheModule::*;

    // test.case( "time::now" );
    let got = time::now();
    a_true!( got > 0 );

    // test.case( "time::ms::now" );
    let got1 = time::now();
    let got2 = time::ms::now();
    a_true!( got2 - got2 <= 10 );

    // // test.case( "time::ns::now" );
    let got1 = time::now();
    let got2 = time::ns::now();
    a_true!( got2 / 1_000_000 - got1 <= 10 );
    // zzz : use equal!

    // test.case( "time::s::now" );
    let got1 = time::now();
    let got2 = time::s::now();
    a_id!( got1 / 1000, got2 );
  }

}

//

tests_index!
{
  basic,
}
<|endoftext|>