<commit_before>use std::rc::{self, Rc};
use std::sync::{self, Arc};

/// Trait for generalizing downgrading a strong reference to a weak reference.
pub trait Downgrade
where
    Self: Sized,
{
    /// Weak reference type.
    type Weak;

    /// Downgrade to a weak reference.
    fn downgrade(&self) -> Self::Weak;
}

/// Trait for generalizing upgrading a weak reference to a strong reference.
pub trait Upgrade
where
    Self: Sized,
{
    /// Strong reference type.
    type Strong;

    /// Try upgrading a weak reference to a strong reference.
    fn upgrade(&self) -> Option<Self::Strong>;
}

impl<T: Downgrade + crate::ObjectType> Upgrade for crate::WeakRef<T> {
    type Strong = T;

    fn upgrade(&self) -> Option<Self::Strong> {
        self.upgrade()
    }
}

impl<T> Downgrade for Arc<T> {
    type Weak = sync::Weak<T>;

    fn downgrade(&self) -> Self::Weak {
        Arc::downgrade(self)
    }
}

impl<T> Upgrade for sync::Weak<T> {
    type Strong = Arc<T>;

    fn upgrade(&self) -> Option<Self::Strong> {
        self.upgrade()
    }
}

impl<T> Downgrade for Rc<T> {
    type Weak = rc::Weak<T>;

    fn downgrade(&self) -> Self::Weak {
        Rc::downgrade(self)
    }
}

impl<T> Upgrade for rc::Weak<T> {
    type Strong = Rc<T>;

    fn upgrade(&self) -> Option<Self::Strong> {
        self.upgrade()
    }
}

#[doc(hidden)]
#[macro_export]
macro_rules! to_type_before {
    (_) => ();
    (self) => (
        compile_error!("Can't use `self` as variable name for the `clone!` macro. Try storing it in a temporary variable.");
    );
    (@weak self) => (
        compile_error!("Can't use `self` as variable name for the `clone!` macro. Try storing it in a temporary variable.");
    );
    (@strong self) => (
        compile_error!("Can't use `self` as variable name for the `clone!` macro. Try storing it in a temporary variable.");
    );
    ($variable:ident) => (
        compile_error!("You need to specify if this is a weak or a strong clone.");
    );
    (@strong $variable:ident) => (
        let $variable = $variable.clone();
    );
    (@weak $variable:ident) => (
        let $variable = $crate::clone::Downgrade::downgrade(&$variable);
    );
    (@ $keyword:ident $variable:ident) => (
        compile_error!("Unknown keyword, only `weak` and `strong` are allowed");
    );
}

#[doc(hidden)]
#[macro_export]
macro_rules! to_type_after {
    (@weak self, $return_value:expr) => {};
    (@strong self, $return_value:expr) => {};
    (@default-panic, @weak $variable:ident) => {
        let $variable = match $crate::clone::Upgrade::upgrade(&$variable) {
            Some(val) => val,
            None => panic!("failed to upgrade {}", stringify!($variable)),
        };
    };
    (@default-panic, @strong $variable:ident) => {};
    (@weak $variable:ident , $return_value:expr) => {
        let $variable = match $crate::clone::Upgrade::upgrade(&$variable) {
            Some(val) => val,
            None => return ($return_value)(),
        };
    };
    (@strong $variable:ident , $return_value:expr) => {};
    (@ $keyword:ident $variable:ident, $return_value:expr) => {};
}

#[doc(hidden)]
#[macro_export]
macro_rules! to_return_value {
    () => {
        ()
    };
    ($value:expr) => {
        $value
    };
}

/// Macro for passing variables as strong or weak references into a closure.
///
/// This macro can be useful in combination with closures, e.g. signal handlers, to reduce the
/// boilerplate required for passing strong or weak references into the closure. It will
/// automatically create the new reference and pass it with the same name into the closure.
///
/// If upgrading the weak reference to a strong reference inside the closure is failing, the
/// closure is immediately returning an optional default return value. If none is provided, `()` is
/// returned.
///
/// ### Passing a strong reference
///
/// ```
/// use glib::clone;
/// use std::rc::Rc;
///
/// let v = Rc::new(1);
/// let closure = clone!(@strong v => move |x| {
///     println!("v: {}, x: {}", v, x);
/// });
///
/// closure(2);
/// ```
///
/// ### Passing a strong and weak reference
///
/// ```
/// use glib::clone;
/// use std::rc::Rc;
///
/// let v = Rc::new(1);
/// let u = Rc::new(2);
/// let closure = clone!(@strong v, @weak u => move |x| {
///     println!("v: {}, u: {}, x: {}", v, u, x);
/// });
///
/// closure(3);
/// ```
///
/// ### Providing a default return value if upgrading a weak reference fails
///
/// You can do it in two different ways:
///
/// Either by providing the value yourself using `@default-return`:
///
/// ```
/// use glib::clone;
/// use std::rc::Rc;
///
/// let v = Rc::new(1);
/// let closure = clone!(@weak v => @default-return false, move |x| {
///     println!("v: {}, x: {}", v, x);
///     true
/// });
///
/// // Drop value so that the weak reference can't be upgraded.
/// drop(v);
///
/// assert_eq!(closure(2), false);
/// ```
///
/// Or by using `@default-panic` (if the value fails to get upgraded, it'll panic):
///
/// ```run_fail
/// # use glib::clone;
/// # use std::rc::Rc;
/// # let v = Rc::new(1);
/// let closure = clone!(@weak v => @default-panic, move |x| {
///     println!("v: {}, x: {}", v, x);
///     true
/// });
/// # drop(v);
/// # assert_eq!(closure(2), false);
/// ```
///
/// ### Errors
///
/// Here is a list of errors you might encounter:
///
/// **Missing `@weak` or `@strong`**:
///
/// ```compile_fail
/// # use glib::clone;
/// # use std::rc::Rc;
/// let v = Rc::new(1);
///
/// let closure = clone!(v => move |x| {
///     println!("v: {}, x: {}", v, x);
/// });
/// ```
///
/// **Passing `self` as an argument**:
///
/// ```compile_fail
/// # use glib::clone;
/// # use std::rc::Rc;
/// struct Foo;
///
/// impl Foo {
///     fn foo(&self) {
///         let v = Rc::new(1);
///
///         let closure = clone!(@strong self => move |x| {
///             println!("v: {}, x: {}", v, x);
///         });
///     }
/// }
#[macro_export]
macro_rules! clone {
    ($($(@ $strength:ident)? $variables:ident),+ => @default-panic, move || $body:block ) => (
        {
            $( $crate::to_type_before!($(@ $strength)? $variables); )*
            move || {
                $( $crate::to_type_after!(@default-panic, $(@ $strength)? $variables );)*
                $body
            }
        }
    );
    ($($(@ $strength:ident)? $variables:ident),+ => $(@default-return $return_value:expr,)? move || $body:block ) => (
        {
            $( $crate::to_type_before!($(@ $strength)? $variables); )*
            move || {
                let return_value = || $crate::to_return_value!($($return_value)?);
                $( $crate::to_type_after!($(@ $strength)? $variables, return_value );)*
                $body
            }
        }
    );
    ($($(@ $strength:ident)? $variables:ident),+ => @default-panic, move | $($pattern:pat),* | $body:block ) => (
        {
            $( $crate::to_type_before!($(@ $strength)? $variables); )*
            move |$($pattern),*| {
                $( $crate::to_type_after!(@default-panic, $(@ $strength)? $variables );)*
                $body
            }
        }
    );
    ($($(@ $strength:ident)? $variables:ident),+ => $(@default-return $return_value:expr,)? move | $($pattern:pat),* | $body:block ) => (
        {
            $( $crate::to_type_before!($(@ $strength)? $variables); )*
            move |$($pattern),*| {
                let return_value = || $crate::to_return_value!($($return_value)?);
                $( $crate::to_type_after!($(@ $strength)? $variables, return_value );)*
                $body
            }
        }
    );
}
<commit_msg>Add compile_error! to clone! for passing arbitrary expressions, e.g. field accesses<commit_after>use std::rc::{self, Rc};
use std::sync::{self, Arc};

/// Trait for generalizing downgrading a strong reference to a weak reference.
pub trait Downgrade
where
    Self: Sized,
{
    /// Weak reference type.
    type Weak;

    /// Downgrade to a weak reference.
    fn downgrade(&self) -> Self::Weak;
}

/// Trait for generalizing upgrading a weak reference to a strong reference.
pub trait Upgrade
where
    Self: Sized,
{
    /// Strong reference type.
    type Strong;

    /// Try upgrading a weak reference to a strong reference.
    fn upgrade(&self) -> Option<Self::Strong>;
}

impl<T: Downgrade + crate::ObjectType> Upgrade for crate::WeakRef<T> {
    type Strong = T;

    fn upgrade(&self) -> Option<Self::Strong> {
        self.upgrade()
    }
}

impl<T> Downgrade for Arc<T> {
    type Weak = sync::Weak<T>;

    fn downgrade(&self) -> Self::Weak {
        Arc::downgrade(self)
    }
}

impl<T> Upgrade for sync::Weak<T> {
    type Strong = Arc<T>;

    fn upgrade(&self) -> Option<Self::Strong> {
        self.upgrade()
    }
}

impl<T> Downgrade for Rc<T> {
    type Weak = rc::Weak<T>;

    fn downgrade(&self) -> Self::Weak {
        Rc::downgrade(self)
    }
}

impl<T> Upgrade for rc::Weak<T> {
    type Strong = Rc<T>;

    fn upgrade(&self) -> Option<Self::Strong> {
        self.upgrade()
    }
}

#[doc(hidden)]
#[macro_export]
macro_rules! to_type_before {
    (_) => ();
    ($variable:ident) => (
        compile_error!("You need to specify if this is a weak or a strong clone.");
    );
    (@strong $variable:ident) => (
        let $variable = $variable.clone();
    );
    (@weak $variable:ident) => (
        let $variable = $crate::clone::Downgrade::downgrade(&$variable);
    );
    (@ $keyword:ident $variable:ident) => (
        compile_error!("Unknown keyword, only `weak` and `strong` are allowed");
    );
}

#[doc(hidden)]
#[macro_export]
macro_rules! to_type_after {
    (@weak self, $return_value:expr) => {};
    (@strong self, $return_value:expr) => {};
    (@default-panic, @weak $variable:ident) => {
        let $variable = match $crate::clone::Upgrade::upgrade(&$variable) {
            Some(val) => val,
            None => panic!("failed to upgrade {}", stringify!($variable)),
        };
    };
    (@default-panic, @strong $variable:ident) => {};
    (@weak $variable:ident , $return_value:expr) => {
        let $variable = match $crate::clone::Upgrade::upgrade(&$variable) {
            Some(val) => val,
            None => return ($return_value)(),
        };
    };
    (@strong $variable:ident , $return_value:expr) => {};
    (@ $keyword:ident $variable:ident, $return_value:expr) => {};
}

#[doc(hidden)]
#[macro_export]
macro_rules! to_return_value {
    () => {
        ()
    };
    ($value:expr) => {
        $value
    };
}

/// Macro for passing variables as strong or weak references into a closure.
///
/// This macro can be useful in combination with closures, e.g. signal handlers, to reduce the
/// boilerplate required for passing strong or weak references into the closure. It will
/// automatically create the new reference and pass it with the same name into the closure.
///
/// If upgrading the weak reference to a strong reference inside the closure is failing, the
/// closure is immediately returning an optional default return value. If none is provided, `()` is
/// returned.
///
/// ### Passing a strong reference
///
/// ```
/// use glib::clone;
/// use std::rc::Rc;
///
/// let v = Rc::new(1);
/// let closure = clone!(@strong v => move |x| {
///     println!("v: {}, x: {}", v, x);
/// });
///
/// closure(2);
/// ```
///
/// ### Passing a strong and weak reference
///
/// ```
/// use glib::clone;
/// use std::rc::Rc;
///
/// let v = Rc::new(1);
/// let u = Rc::new(2);
/// let closure = clone!(@strong v, @weak u => move |x| {
///     println!("v: {}, u: {}, x: {}", v, u, x);
/// });
///
/// closure(3);
/// ```
///
/// ### Providing a default return value if upgrading a weak reference fails
///
/// You can do it in two different ways:
///
/// Either by providing the value yourself using `@default-return`:
///
/// ```
/// use glib::clone;
/// use std::rc::Rc;
///
/// let v = Rc::new(1);
/// let closure = clone!(@weak v => @default-return false, move |x| {
///     println!("v: {}, x: {}", v, x);
///     true
/// });
///
/// // Drop value so that the weak reference can't be upgraded.
/// drop(v);
///
/// assert_eq!(closure(2), false);
/// ```
///
/// Or by using `@default-panic` (if the value fails to get upgraded, it'll panic):
///
/// ```run_fail
/// # use glib::clone;
/// # use std::rc::Rc;
/// # let v = Rc::new(1);
/// let closure = clone!(@weak v => @default-panic, move |x| {
///     println!("v: {}, x: {}", v, x);
///     true
/// });
/// # drop(v);
/// # assert_eq!(closure(2), false);
/// ```
///
/// ### Errors
///
/// Here is a list of errors you might encounter:
///
/// **Missing `@weak` or `@strong`**:
///
/// ```compile_fail
/// # use glib::clone;
/// # use std::rc::Rc;
/// let v = Rc::new(1);
///
/// let closure = clone!(v => move |x| {
///     println!("v: {}, x: {}", v, x);
/// });
/// ```
///
/// **Passing `self` as an argument**:
///
/// ```compile_fail
/// # use glib::clone;
/// # use std::rc::Rc;
/// struct Foo;
///
/// impl Foo {
///     fn foo(&self) {
///         let v = Rc::new(1);
///
///         let closure = clone!(@strong self => move |x| {
///             println!("v: {}, x: {}", v, x);
///         });
///     }
/// }
#[macro_export]
macro_rules! clone {
    ($($(@ $strength:ident)? self),+ => $($_:tt)* ) => (
        compile_error!("Can't use `self` as variable name. Try storing it in a temporary variable.");
    );
    ($($(@ $strength:ident)? $variables:ident),+ => @default-panic, move || $body:block ) => (
        {
            $( $crate::to_type_before!($(@ $strength)? $variables); )*
            move || {
                $( $crate::to_type_after!(@default-panic, $(@ $strength)? $variables );)*
                $body
            }
        }
    );
    ($($(@ $strength:ident)? $variables:ident),+ => $(@default-return $return_value:expr,)? move || $body:block ) => (
        {
            $( $crate::to_type_before!($(@ $strength)? $variables); )*
            move || {
                let return_value = || $crate::to_return_value!($($return_value)?);
                $( $crate::to_type_after!($(@ $strength)? $variables, return_value );)*
                $body
            }
        }
    );
    ($($(@ $strength:ident)? $variables:ident),+ => @default-panic, move | $($pattern:pat),* | $body:block ) => (
        {
            $( $crate::to_type_before!($(@ $strength)? $variables); )*
            move |$($pattern),*| {
                $( $crate::to_type_after!(@default-panic, $(@ $strength)? $variables );)*
                $body
            }
        }
    );
    ($($(@ $strength:ident)? $variables:ident),+ => $(@default-return $return_value:expr,)? move | $($pattern:pat),* | $body:block ) => (
        {
            $( $crate::to_type_before!($(@ $strength)? $variables); )*
            move |$($pattern),*| {
                let return_value = || $crate::to_return_value!($($return_value)?);
                $( $crate::to_type_after!($(@ $strength)? $variables, return_value );)*
                $body
            }
        }
    );
    ($($(@ $strength:ident)? $variables:expr),+ => $($_:tt)* ) => (
        compile_error!("Variables need to be valid identifiers, e.g. field accesses are not allowed");
    );
}
<|endoftext|>


<commit_before>extern crate sorting;

const TO_SORT_I8:  [i8;  16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const TO_SORT_I16: [i16; 16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const TO_SORT_I32: [i32; 16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const TO_SORT_I64: [i64; 16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const TO_SORT_U8:  [u8;  16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const TO_SORT_U16: [u16; 16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const TO_SORT_U32: [u32; 16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const TO_SORT_U64: [u64; 16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const SORTED_IND_INT:  [usize; 16] = [3, 4, 15, 2, 8, 13, 5, 1, 0, 7, 6, 9, 10, 14, 11, 12];

const TO_SORT_F32: [f32; 16] = [6.0,   5.0,  3.0,  1.0,  2.4, 4.0, 10.0, 7.0,
                                3.42, 32.2, 44.2, 56.3, 67.9, 3.2, 44.2, 2.0];
const TO_SORT_F64: [f64; 16] = [6.0,   5.0,  3.0,  1.0,  2.4, 4.0, 10.0, 7.0,
                                3.42, 32.2, 44.2, 56.3, 67.9, 3.2, 44.2, 2.0];
// NOTE: The order is different for the floats because of the fractional parts. For example,
//       "2.0" comes before "2.4", while in the integer arrays it was "2" vs "2". Since the
//       algorithms are stable, the floating points vector will get a different sorting sequence.
const SORTED_IND_FLOAT: [usize; 16] = [3, 15, 4, 2, 13, 8, 5, 1, 0, 7, 6, 9, 10, 14, 11, 12];

/// Verify order of input vector as sorted by indices.
///
/// # Details
///
/// This function takes as arguments a vector of data and a vector representing the indices of the
/// first vector making it sorted.
///
/// The elements of the sorted vector are compared to the next ones to make sure they are less
/// or equal.
///
/// # Panics
///
/// The sorting of the data vector is enforced using `assert!()`.
///
/// # Examples
///
/// ```
/// let data: Vec<i32> = vec![4, 2, 3, 1];
/// let sorted_indices: Vec<usize> = vec![3, 1, 2, 0];
/// verify_sorting(&data, &sorted_indices);
/// ```
///
fn verify_sorting<T: PartialOrd>(array: &Vec<T>, sorted_indices: &Vec<usize>) {
    let n = array.len();
    assert_eq!(n , sorted_indices.len());

    if !array.is_empty() {
        for i in 0..n-1 {
            assert!(array[sorted_indices[i]] <= array[sorted_indices[i+1]]);
        }
    }
}

/// Call the specified sorting function on an empty vector of specific type.
///
/// # Details
///
/// This function takes as arguments a pointer to a sorting function acting and call
/// it on an empty vector of type T. The call should succeed and the index vector should
/// be empty as well.
///
/// # Panics
///
/// The emptiness of the sorted list is enforced using `assert!()`.
///
/// # Examples
///
/// ```
/// test_empty_vec::<i8>(sorting::simplesorts::insertion::sort);
/// ```
///
fn test_empty_vec<T: PartialOrd>(sorting_fct: fn(&Vec<T>) -> Vec<usize>) {
    let to_sort: Vec<T> = vec![];
    let sorted_indices = sorting_fct(&to_sort);
    assert_eq!(sorted_indices, vec![]);
    assert!(sorted_indices.is_empty());
}

/// Call the specified sorting function on an specific vector of floats and validate the output.
///
/// # Details
///
/// This function takes as arguments:
///    1. An immutable vector of floats, to be sorted;
///    2. An immutable vector of indices as the reference to compare with;
///    3. A function pointer to be called on the first vector.
///
/// # Panics
///
/// This calls the function `verify_sorting()` which will assert if the result is not in order.
/// It also compares the resulting indices with expected values using asserts.
///
/// # Examples
///
/// ```
/// let to_sort: Vec<f32> = vec![6.0,   5.0,  3.0,  1.0,  2.4, 4.0, 10.0, 7.0,
///                              3.42, 32.2, 44.2, 56.3, 67.9, 3.2, 44.2, 2.0];
///
/// let known_sorted_indices = vec![3, 15, 4, 2, 13, 8, 5, 1, 0, 7, 6, 9, 10, 14, 11, 12];
///
/// test_sort_vec_float::<f32>(&to_sort, &known_sorted_indices,
///                            sorting::simplesorts::insertion::sort);
/// ```
///
fn test_sort_vec_float<T: PartialOrd>(to_sort: &Vec<T>, expected_indices: &Vec<usize>,
                                      sorting_fct: fn(&Vec<T>) -> Vec<usize>) {
    let sorted_indices = sorting_fct(&to_sort);

    verify_sorting(&to_sort, &sorted_indices);

    assert_eq!(sorted_indices.len(), expected_indices.len());

    for i in 0..to_sort.len() {
        assert_eq!(sorted_indices[i], expected_indices[i]);
    }
}

/// Validate against empty vector (i8).
#[test]
fn simple_insertion_empty_vec_i8() {
    test_empty_vec::<i8>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (i32).
#[test]
fn simple_insertion_empty_vec_i16() {
    test_empty_vec::<i16>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (i32).
#[test]
fn simple_insertion_empty_vec_i32() {
    test_empty_vec::<i32>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (i64).
#[test]
fn simple_insertion_empty_vec_i64() {
    test_empty_vec::<i64>(sorting::simplesorts::insertion::sort);
}

/// Validate against empty vector (u8).
#[test]
fn simple_insertion_empty_vec_u8() {
    test_empty_vec::<u8>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (u32).
#[test]
fn simple_insertion_empty_vec_u16() {
    test_empty_vec::<u16>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (u32).
#[test]
fn simple_insertion_empty_vec_u32() {
    test_empty_vec::<u32>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (u64).
#[test]
fn simple_insertion_empty_vec_u64() {
    test_empty_vec::<u64>(sorting::simplesorts::insertion::sort);
}

/// Validate against empty vector (isize).
#[test]
fn simple_insertion_empty_vec_isize() {
    test_empty_vec::<isize>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (usize).
#[test]
fn simple_insertion_empty_vec_usize() {
    test_empty_vec::<usize>(sorting::simplesorts::insertion::sort);
}

/// Validate against empty vector (f32).
#[test]
fn simple_insertion_empty_vec_f32() {
    test_empty_vec::<f32>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (f64).
#[test]
fn simple_insertion_empty_vec_f64() {
    test_empty_vec::<f64>(sorting::simplesorts::insertion::sort);
}

/// Validate sorting a vector of single precision values (i8).
#[test]
fn simple_insertion_vec_i8() {
    let to_sort: Vec<_> = From::from(&TO_SORT_I8[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<i8>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}
/// Validate sorting a vector of single precision values (i16).
#[test]
fn simple_insertion_vec_i16() {
    let to_sort: Vec<_> = From::from(&TO_SORT_I16[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<i16>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}
/// Validate sorting a vector of single precision values (i32).
#[test]
fn simple_insertion_vec_i32() {
    let to_sort: Vec<_> = From::from(&TO_SORT_I32[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<i32>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}
/// Validate sorting a vector of single precision values (i64).
#[test]
fn simple_insertion_vec_i64() {
    let to_sort: Vec<_> = From::from(&TO_SORT_I64[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<i64>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}

/// Validate sorting a vector of single precision values (u8).
#[test]
fn simple_insertion_vec_u8() {
    let to_sort: Vec<_> = From::from(&TO_SORT_U8[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<u8>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}
/// Validate sorting a vector of single precision values (u16).
#[test]
fn simple_insertion_vec_u16() {
    let to_sort: Vec<_> = From::from(&TO_SORT_U16[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<u16>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}
/// Validate sorting a vector of single precision values (u32).
#[test]
fn simple_insertion_vec_u32() {
    let to_sort: Vec<_> = From::from(&TO_SORT_U32[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<u32>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}
/// Validate sorting a vector of single precision values (u64).
#[test]
fn simple_insertion_vec_u64() {
    let to_sort: Vec<_> = From::from(&TO_SORT_U64[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<u64>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}

/// Validate sorting a vector of single precision values (f32).
#[test]
fn simple_insertion_vec_f32() {
    let to_sort: Vec<_> = From::from(&TO_SORT_F32[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_FLOAT[..]);

    test_sort_vec_float::<f32>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}

/// Validate sorting a vector of double precision values (f64).
#[test]
fn simple_insertion_vec_f64() {
    let to_sort: Vec<_> = From::from(&TO_SORT_F64[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_FLOAT[..]);

    test_sort_vec_float::<f64>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}
<commit_msg>New function to verify input vector as being sorted.<commit_after>extern crate sorting;

const TO_SORT_I8:  [i8;  16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const TO_SORT_I16: [i16; 16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const TO_SORT_I32: [i32; 16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const TO_SORT_I64: [i64; 16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const TO_SORT_U8:  [u8;  16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const TO_SORT_U16: [u16; 16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const TO_SORT_U32: [u32; 16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const TO_SORT_U64: [u64; 16] = [6,  5,  3,  1,  2, 4, 10, 7, 3, 32, 44, 56, 67, 3, 44, 2];
const SORTED_IND_INT:  [usize; 16] = [3, 4, 15, 2, 8, 13, 5, 1, 0, 7, 6, 9, 10, 14, 11, 12];

const TO_SORT_F32: [f32; 16] = [6.0,   5.0,  3.0,  1.0,  2.4, 4.0, 10.0, 7.0,
                                3.42, 32.2, 44.2, 56.3, 67.9, 3.2, 44.2, 2.0];
const TO_SORT_F64: [f64; 16] = [6.0,   5.0,  3.0,  1.0,  2.4, 4.0, 10.0, 7.0,
                                3.42, 32.2, 44.2, 56.3, 67.9, 3.2, 44.2, 2.0];
// NOTE: The order is different for the floats because of the fractional parts. For example,
//       "2.0" comes before "2.4", while in the integer arrays it was "2" vs "2". Since the
//       algorithms are stable, the floating points vector will get a different sorting sequence.
const SORTED_IND_FLOAT: [usize; 16] = [3, 15, 4, 2, 13, 8, 5, 1, 0, 7, 6, 9, 10, 14, 11, 12];

/// Verify input vector as being sorted.
///
/// # Details
///
/// This function takes as arguments a vector of data that must be verified to be sorted.
///
/// The elements of the sorted vector are compared to the next ones to make sure they are less
/// or equal.
///
/// # Panics
///
/// The sorting of the data vector is enforced using `assert!()`.
///
/// # Examples
///
/// ```
/// let data: Vec<i32> = vec![1, 2, 3, 4];
/// verify_sorting(&data);
/// ```
///
fn verify_sorted<T: PartialOrd>(array: &Vec<T>) {
    let n = array.len();
    if !array.is_empty() {
        for i in 0..n-1 {
            assert!(array[i] <= array[i+1]);
        }
    }
}

/// Verify order of input vector as sorted by indices.
///
/// # Details
///
/// This function takes as arguments a vector of data and a vector representing the indices of the
/// first vector making it sorted.
///
/// The elements of the sorted vector are compared to the next ones to make sure they are less
/// or equal.
///
/// # Panics
///
/// The sorting of the data vector is enforced using `assert!()`.
///
/// # Examples
///
/// ```
/// let data: Vec<i32> = vec![4, 2, 3, 1];
/// let sorted_indices: Vec<usize> = vec![3, 1, 2, 0];
/// verify_sorting(&data, &sorted_indices);
/// ```
///
fn verify_sorting<T: PartialOrd>(array: &Vec<T>, sorted_indices: &Vec<usize>) {
    let n = array.len();
    assert_eq!(n , sorted_indices.len());

    if !array.is_empty() {
        for i in 0..n-1 {
            assert!(array[sorted_indices[i]] <= array[sorted_indices[i+1]]);
        }
    }
}

/// Call the specified sorting function on an empty vector of specific type.
///
/// # Details
///
/// This function takes as arguments a pointer to a sorting function acting and call
/// it on an empty vector of type T. The call should succeed and the index vector should
/// be empty as well.
///
/// # Panics
///
/// The emptiness of the sorted list is enforced using `assert!()`.
///
/// # Examples
///
/// ```
/// test_empty_vec::<i8>(sorting::simplesorts::insertion::sort);
/// ```
///
fn test_empty_vec<T: PartialOrd>(sorting_fct: fn(&Vec<T>) -> Vec<usize>) {
    let to_sort: Vec<T> = vec![];
    let sorted_indices = sorting_fct(&to_sort);
    assert_eq!(sorted_indices, vec![]);
    assert!(sorted_indices.is_empty());
}

/// Call the specified sorting function on an specific vector of floats and validate the output.
///
/// # Details
///
/// This function takes as arguments:
///    1. An immutable vector of floats, to be sorted;
///    2. An immutable vector of indices as the reference to compare with;
///    3. A function pointer to be called on the first vector.
///
/// # Panics
///
/// This calls the function `verify_sorting()` which will assert if the result is not in order.
/// It also compares the resulting indices with expected values using asserts.
///
/// # Examples
///
/// ```
/// let to_sort: Vec<f32> = vec![6.0,   5.0,  3.0,  1.0,  2.4, 4.0, 10.0, 7.0,
///                              3.42, 32.2, 44.2, 56.3, 67.9, 3.2, 44.2, 2.0];
///
/// let known_sorted_indices = vec![3, 15, 4, 2, 13, 8, 5, 1, 0, 7, 6, 9, 10, 14, 11, 12];
///
/// test_sort_vec_float::<f32>(&to_sort, &known_sorted_indices,
///                            sorting::simplesorts::insertion::sort);
/// ```
///
fn test_sort_vec_float<T: PartialOrd>(to_sort: &Vec<T>, expected_indices: &Vec<usize>,
                                      sorting_fct: fn(&Vec<T>) -> Vec<usize>) {
    let sorted_indices = sorting_fct(&to_sort);

    verify_sorting(&to_sort, &sorted_indices);

    assert_eq!(sorted_indices.len(), expected_indices.len());

    for i in 0..to_sort.len() {
        assert_eq!(sorted_indices[i], expected_indices[i]);
    }
}

/// Validate against empty vector (i8).
#[test]
fn simple_insertion_empty_vec_i8() {
    test_empty_vec::<i8>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (i32).
#[test]
fn simple_insertion_empty_vec_i16() {
    test_empty_vec::<i16>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (i32).
#[test]
fn simple_insertion_empty_vec_i32() {
    test_empty_vec::<i32>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (i64).
#[test]
fn simple_insertion_empty_vec_i64() {
    test_empty_vec::<i64>(sorting::simplesorts::insertion::sort);
}

/// Validate against empty vector (u8).
#[test]
fn simple_insertion_empty_vec_u8() {
    test_empty_vec::<u8>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (u32).
#[test]
fn simple_insertion_empty_vec_u16() {
    test_empty_vec::<u16>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (u32).
#[test]
fn simple_insertion_empty_vec_u32() {
    test_empty_vec::<u32>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (u64).
#[test]
fn simple_insertion_empty_vec_u64() {
    test_empty_vec::<u64>(sorting::simplesorts::insertion::sort);
}

/// Validate against empty vector (isize).
#[test]
fn simple_insertion_empty_vec_isize() {
    test_empty_vec::<isize>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (usize).
#[test]
fn simple_insertion_empty_vec_usize() {
    test_empty_vec::<usize>(sorting::simplesorts::insertion::sort);
}

/// Validate against empty vector (f32).
#[test]
fn simple_insertion_empty_vec_f32() {
    test_empty_vec::<f32>(sorting::simplesorts::insertion::sort);
}
/// Validate against empty vector (f64).
#[test]
fn simple_insertion_empty_vec_f64() {
    test_empty_vec::<f64>(sorting::simplesorts::insertion::sort);
}

/// Validate sorting a vector of single precision values (i8).
#[test]
fn simple_insertion_vec_i8() {
    let to_sort: Vec<_> = From::from(&TO_SORT_I8[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<i8>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}
/// Validate sorting a vector of single precision values (i16).
#[test]
fn simple_insertion_vec_i16() {
    let to_sort: Vec<_> = From::from(&TO_SORT_I16[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<i16>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}
/// Validate sorting a vector of single precision values (i32).
#[test]
fn simple_insertion_vec_i32() {
    let to_sort: Vec<_> = From::from(&TO_SORT_I32[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<i32>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}
/// Validate sorting a vector of single precision values (i64).
#[test]
fn simple_insertion_vec_i64() {
    let to_sort: Vec<_> = From::from(&TO_SORT_I64[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<i64>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}

/// Validate sorting a vector of single precision values (u8).
#[test]
fn simple_insertion_vec_u8() {
    let to_sort: Vec<_> = From::from(&TO_SORT_U8[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<u8>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}
/// Validate sorting a vector of single precision values (u16).
#[test]
fn simple_insertion_vec_u16() {
    let to_sort: Vec<_> = From::from(&TO_SORT_U16[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<u16>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}
/// Validate sorting a vector of single precision values (u32).
#[test]
fn simple_insertion_vec_u32() {
    let to_sort: Vec<_> = From::from(&TO_SORT_U32[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<u32>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}
/// Validate sorting a vector of single precision values (u64).
#[test]
fn simple_insertion_vec_u64() {
    let to_sort: Vec<_> = From::from(&TO_SORT_U64[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_INT[..]);

    test_sort_vec_float::<u64>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}

/// Validate sorting a vector of single precision values (f32).
#[test]
fn simple_insertion_vec_f32() {
    let to_sort: Vec<_> = From::from(&TO_SORT_F32[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_FLOAT[..]);

    test_sort_vec_float::<f32>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}

/// Validate sorting a vector of double precision values (f64).
#[test]
fn simple_insertion_vec_f64() {
    let to_sort: Vec<_> = From::from(&TO_SORT_F64[..]);
    let known_sorted_indices: Vec<usize> = From::from(&SORTED_IND_FLOAT[..]);

    test_sort_vec_float::<f64>(&to_sort, &known_sorted_indices,
                               sorting::simplesorts::insertion::sort);
}
<|endoftext|>


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

extern crate magick_rust;

use magick_rust::{MagickWand, magick_wand_genesis};
use magick_rust::filters::{FilterType};

use std::error::Error;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::sync::{Once, ONCE_INIT};

// Used to make sure MagickWand is initialized exactly once. Note that we
// do not bother shutting down, we simply exit when the tests are done.
static START: Once = ONCE_INIT;

#[test]
fn test_new_drop() {
    START.call_once(|| {
        magick_wand_genesis();
    });
    MagickWand::new();
}

#[test]
fn test_resize_image() {
    START.call_once(|| {
        magick_wand_genesis();
    });
    let wand = MagickWand::new();
    assert!(wand.read_image("tests/data/IMG_5745.JPG").is_ok());
    assert_eq!(512, wand.get_image_width());
    assert_eq!(384, wand.get_image_height());
    let halfwidth = match wand.get_image_width() {
        1 => 1,
        width => width / 2
    };
    let halfheight = match wand.get_image_height() {
        1 => 1,
        height => height / 2
    };
    wand.resize_image(halfwidth, halfheight, FilterType::LanczosFilter, 1.0);
    assert_eq!(256, wand.get_image_width());
    assert_eq!(192, wand.get_image_height());
}

#[test]
fn test_read_from_blob() {
    START.call_once(|| {
        magick_wand_genesis();
    });
    let wand = MagickWand::new();

    let path = Path::new("tests/data/IMG_5745.JPG");
    let mut file = match File::open(&path) {
        Err(why) => panic!("couldn't open file: {}", Error::description(&why)),
        Ok(file) => file
    };
    let mut data: Vec<u8> = Vec::new();
    match file.read_to_end(&mut data) {
        Err(why) => panic!("couldn't read file: {}", Error::description(&why)),
        Ok(_) => ()
    };
    assert!(wand.read_image_blob(data).is_ok());
    assert_eq!(512, wand.get_image_width());
    assert_eq!(384, wand.get_image_height());
}

#[test]
fn test_write_to_blob() {
    START.call_once(|| {
        magick_wand_genesis();
    });
    let wand = MagickWand::new();
    assert!(wand.read_image("tests/data/IMG_5745.JPG").is_ok());
    assert_eq!(512, wand.get_image_width());
    assert_eq!(384, wand.get_image_height());
    let blob = wand.write_image_blob("jpeg").unwrap();
    assert_eq!(104061, blob.len());
    // should be able to read it back again
    assert!(wand.read_image_blob(blob).is_ok());
    assert_eq!(512, wand.get_image_width());
    assert_eq!(384, wand.get_image_height());
}

#[test]
fn test_fit() {
    START.call_once(|| {
        magick_wand_genesis();
    });
    let wand = MagickWand::new();
    assert!(wand.read_image("tests/data/IMG_5745.JPG").is_ok());
    assert_eq!(512, wand.get_image_width());
    assert_eq!(384, wand.get_image_height());
    wand.fit(240, 240);
    assert_eq!(240, wand.get_image_width());
    assert_eq!(180, wand.get_image_height());
}

#[test]
fn test_get_image_property() {
    START.call_once(|| {
        magick_wand_genesis();
    });
    let wand = MagickWand::new();
    assert!(wand.read_image("tests/data/IMG_5745.JPG").is_ok());
    // retrieve a property we know exists
    let found_value = wand.get_image_property("exif:DateTimeOriginal");
    assert!(found_value.is_ok());
    assert_eq!("2014:04:23 13:33:08", found_value.unwrap());
    // retrieve a property that does not exist
    let missing_value = wand.get_image_property("exif:Foobar");
    assert!(missing_value.is_err());
    assert_eq!("missing property", missing_value.unwrap_err());
}
<commit_msg>Use cfg! so test passes on FreeBSD<commit_after>/*
 * Copyright 2015 Nathan Fiedler
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

extern crate magick_rust;

use magick_rust::{MagickWand, magick_wand_genesis};
use magick_rust::filters::{FilterType};

use std::error::Error;
use std::fs::File;
use std::io::Read;
use std::path::Path;
use std::sync::{Once, ONCE_INIT};

// Used to make sure MagickWand is initialized exactly once. Note that we
// do not bother shutting down, we simply exit when the tests are done.
static START: Once = ONCE_INIT;

#[test]
fn test_new_drop() {
    START.call_once(|| {
        magick_wand_genesis();
    });
    MagickWand::new();
}

#[test]
fn test_resize_image() {
    START.call_once(|| {
        magick_wand_genesis();
    });
    let wand = MagickWand::new();
    assert!(wand.read_image("tests/data/IMG_5745.JPG").is_ok());
    assert_eq!(512, wand.get_image_width());
    assert_eq!(384, wand.get_image_height());
    let halfwidth = match wand.get_image_width() {
        1 => 1,
        width => width / 2
    };
    let halfheight = match wand.get_image_height() {
        1 => 1,
        height => height / 2
    };
    wand.resize_image(halfwidth, halfheight, FilterType::LanczosFilter, 1.0);
    assert_eq!(256, wand.get_image_width());
    assert_eq!(192, wand.get_image_height());
}

#[test]
fn test_read_from_blob() {
    START.call_once(|| {
        magick_wand_genesis();
    });
    let wand = MagickWand::new();

    let path = Path::new("tests/data/IMG_5745.JPG");
    let mut file = match File::open(&path) {
        Err(why) => panic!("couldn't open file: {}", Error::description(&why)),
        Ok(file) => file
    };
    let mut data: Vec<u8> = Vec::new();
    match file.read_to_end(&mut data) {
        Err(why) => panic!("couldn't read file: {}", Error::description(&why)),
        Ok(_) => ()
    };
    assert!(wand.read_image_blob(data).is_ok());
    assert_eq!(512, wand.get_image_width());
    assert_eq!(384, wand.get_image_height());
}

#[test]
fn test_write_to_blob() {
    START.call_once(|| {
        magick_wand_genesis();
    });
    let wand = MagickWand::new();
    assert!(wand.read_image("tests/data/IMG_5745.JPG").is_ok());
    assert_eq!(512, wand.get_image_width());
    assert_eq!(384, wand.get_image_height());
    let blob = wand.write_image_blob("jpeg").unwrap();
    if cfg!(target_os = "freebsd") {
        // yeah, don't know why...
        assert_eq!(104060, blob.len());
    } else {
        assert_eq!(104061, blob.len());
    }
    // should be able to read it back again
    assert!(wand.read_image_blob(blob).is_ok());
    assert_eq!(512, wand.get_image_width());
    assert_eq!(384, wand.get_image_height());
}

#[test]
fn test_fit() {
    START.call_once(|| {
        magick_wand_genesis();
    });
    let wand = MagickWand::new();
    assert!(wand.read_image("tests/data/IMG_5745.JPG").is_ok());
    assert_eq!(512, wand.get_image_width());
    assert_eq!(384, wand.get_image_height());
    wand.fit(240, 240);
    assert_eq!(240, wand.get_image_width());
    assert_eq!(180, wand.get_image_height());
}

#[test]
fn test_get_image_property() {
    START.call_once(|| {
        magick_wand_genesis();
    });
    let wand = MagickWand::new();
    assert!(wand.read_image("tests/data/IMG_5745.JPG").is_ok());
    // retrieve a property we know exists
    let found_value = wand.get_image_property("exif:DateTimeOriginal");
    assert!(found_value.is_ok());
    assert_eq!("2014:04:23 13:33:08", found_value.unwrap());
    // retrieve a property that does not exist
    let missing_value = wand.get_image_property("exif:Foobar");
    assert!(missing_value.is_err());
    assert_eq!("missing property", missing_value.unwrap_err());
}
<|endoftext|>


<commit_before>extern crate pinyin;

struct TestCase {
    args: pinyin::Args,
    result: Vec<Vec<String>>,
    lazy_result: Vec<String>,
}

impl TestCase {
    pub fn new(args: pinyin::Args, result: Vec<Vec<String>>, lazy_result: Vec<String>) -> TestCase {
        TestCase {
            args,
            result,
            lazy_result,
        }
    }
}

#[test]
fn test_pinyin() {
    let hans = "中国人";
    let test_data = vec![
        TestCase::new(
            pinyin::Args::new(),
            vec![
                vec!["zhong".to_string()],
                vec!["guo".to_string()],
                vec!["ren".to_string()],
            ],
            vec!["zhong".to_string(), "guo".to_string(), "ren".to_string()],
        ),
        TestCase::new(
            pinyin::Args {
                style: pinyin::Style::Normal,
                heteronym: false,
            },
            vec![
                vec!["zhong".to_string()],
                vec!["guo".to_string()],
                vec!["ren".to_string()],
            ],
            vec!["zhong".to_string(), "guo".to_string(), "ren".to_string()],
        ),
        TestCase::new(
            pinyin::Args {
                style: pinyin::Style::Tone,
                heteronym: false,
            },
            vec![
                vec!["zhōng".to_string()],
                vec!["guó".to_string()],
                vec!["rén".to_string()],
            ],
            vec!["zhōng".to_string(), "guó".to_string(), "rén".to_string()],
        ),
        TestCase::new(
            pinyin::Args {
                style: pinyin::Style::Tone2,
                heteronym: false,
            },
            vec![
                vec!["zho1ng".to_string()],
                vec!["guo2".to_string()],
                vec!["re2n".to_string()],
            ],
            vec!["zho1ng".to_string(), "guo2".to_string(), "re2n".to_string()],
        ),
        TestCase::new(
            pinyin::Args {
                style: pinyin::Style::Initials,
                heteronym: false,
            },
            vec![
                vec!["zh".to_string()],
                vec!["g".to_string()],
                vec!["r".to_string()],
            ],
            vec!["zh".to_string(), "g".to_string(), "r".to_string()],
        ),
        TestCase::new(
            pinyin::Args {
                style: pinyin::Style::FirstLetter,
                heteronym: false,
            },
            vec![
                vec!["z".to_string()],
                vec!["g".to_string()],
                vec!["r".to_string()],
            ],
            vec!["z".to_string(), "g".to_string(), "r".to_string()],
        ),
        TestCase::new(
            pinyin::Args {
                style: pinyin::Style::Finals,
                heteronym: false,
            },
            vec![
                vec!["ong".to_string()],
                vec!["uo".to_string()],
                vec!["en".to_string()],
            ],
            vec!["ong".to_string(), "uo".to_string(), "en".to_string()],
        ),
        TestCase::new(
            pinyin::Args {
                style: pinyin::Style::FinalsTone,
                heteronym: false,
            },
            vec![
                vec!["ōng".to_string()],
                vec!["uó".to_string()],
                vec!["én".to_string()],
            ],
            vec!["ōng".to_string(), "uó".to_string(), "én".to_string()],
        ),
        TestCase::new(
            pinyin::Args {
                style: pinyin::Style::FinalsTone2,
                heteronym: false,
            },
            vec![
                vec!["o1ng".to_string()],
                vec!["uo2".to_string()],
                vec!["e2n".to_string()],
            ],
            vec!["o1ng".to_string(), "uo2".to_string(), "e2n".to_string()],
        ),
        TestCase::new(
            pinyin::Args {
                style: pinyin::Style::Normal,
                heteronym: true,
            },
            vec![
                vec!["zhong".to_string(), "zhong".to_string()],
                vec!["guo".to_string()],
                vec!["ren".to_string()],
            ],
            vec!["zhong".to_string(), "guo".to_string(), "ren".to_string()],
        ),
    ];
    for data in &test_data {
        assert_eq!(data.result, pinyin::pinyin(hans, &data.args));
        assert_eq!(data.lazy_result, pinyin::lazy_pinyin(hans, &data.args));
    }
}

#[test]
fn test_non_chinese_pinyin() {
    let hans = "中国人abc你好";
    let expect = vec![
        vec!["zhong".to_string()],
        vec!["guo".to_string()],
        vec!["ren".to_string()],
        vec![],
        vec![],
        vec![],
        vec!["ni".to_string()],
        vec!["hao".to_string()],
    ];
    let result = pinyin::pinyin(hans, &pinyin::Args::new());
    assert_eq!(expect, result);
}

#[test]
fn test_non_chinese_lazy_pinyin() {
    let hans = "中国人abc你好";
    let expect = vec![
        "zhong".to_string(),
        "guo".to_string(),
        "ren".to_string(),
        "ni".to_string(),
        "hao".to_string(),
    ];
    let result = pinyin::lazy_pinyin(hans, &pinyin::Args::new());
    assert_eq!(expect, result);
}

#[test]
fn test_new_args() {
    let args = pinyin::Args::new();
    assert_eq!(pinyin::Style::Normal, args.style);
    assert_eq!(false, args.heteronym);
}
<commit_msg>add more tests<commit_after>extern crate pinyin;

struct TestCase {
    hans: String,
    args: pinyin::Args,
    result: Vec<Vec<String>>,
    lazy_result: Vec<String>,
}

impl TestCase {
    pub fn new(
        hans: String,
        args: pinyin::Args,
        result: Vec<Vec<String>>,
        lazy_result: Vec<String>,
    ) -> TestCase {
        TestCase {
            hans,
            args,
            result,
            lazy_result,
        }
    }
}

#[test]
fn test_pinyin() {
    let test_data = vec![
        TestCase::new(
            "中国人".to_string(),
            pinyin::Args::new(),
            vec![
                vec!["zhong".to_string()],
                vec!["guo".to_string()],
                vec!["ren".to_string()],
            ],
            vec!["zhong".to_string(), "guo".to_string(), "ren".to_string()],
        ),
        TestCase::new(
            "中国人".to_string(),
            pinyin::Args {
                style: pinyin::Style::Normal,
                heteronym: false,
            },
            vec![
                vec!["zhong".to_string()],
                vec!["guo".to_string()],
                vec!["ren".to_string()],
            ],
            vec!["zhong".to_string(), "guo".to_string(), "ren".to_string()],
        ),
        TestCase::new(
            "中国人".to_string(),
            pinyin::Args {
                style: pinyin::Style::Tone,
                heteronym: false,
            },
            vec![
                vec!["zhōng".to_string()],
                vec!["guó".to_string()],
                vec!["rén".to_string()],
            ],
            vec!["zhōng".to_string(), "guó".to_string(), "rén".to_string()],
        ),
        TestCase::new(
            "中国人".to_string(),
            pinyin::Args {
                style: pinyin::Style::Tone2,
                heteronym: false,
            },
            vec![
                vec!["zho1ng".to_string()],
                vec!["guo2".to_string()],
                vec!["re2n".to_string()],
            ],
            vec!["zho1ng".to_string(), "guo2".to_string(), "re2n".to_string()],
        ),
        TestCase::new(
            "中国人".to_string(),
            pinyin::Args {
                style: pinyin::Style::Initials,
                heteronym: false,
            },
            vec![
                vec!["zh".to_string()],
                vec!["g".to_string()],
                vec!["r".to_string()],
            ],
            vec!["zh".to_string(), "g".to_string(), "r".to_string()],
        ),
        TestCase::new(
            "中国人".to_string(),
            pinyin::Args {
                style: pinyin::Style::FirstLetter,
                heteronym: false,
            },
            vec![
                vec!["z".to_string()],
                vec!["g".to_string()],
                vec!["r".to_string()],
            ],
            vec!["z".to_string(), "g".to_string(), "r".to_string()],
        ),
        TestCase::new(
            "中国人".to_string(),
            pinyin::Args {
                style: pinyin::Style::Finals,
                heteronym: false,
            },
            vec![
                vec!["ong".to_string()],
                vec!["uo".to_string()],
                vec!["en".to_string()],
            ],
            vec!["ong".to_string(), "uo".to_string(), "en".to_string()],
        ),
        TestCase::new(
            "中国人".to_string(),
            pinyin::Args {
                style: pinyin::Style::FinalsTone,
                heteronym: false,
            },
            vec![
                vec!["ōng".to_string()],
                vec!["uó".to_string()],
                vec!["én".to_string()],
            ],
            vec!["ōng".to_string(), "uó".to_string(), "én".to_string()],
        ),
        TestCase::new(
            "中国人".to_string(),
            pinyin::Args {
                style: pinyin::Style::FinalsTone2,
                heteronym: false,
            },
            vec![
                vec!["o1ng".to_string()],
                vec!["uo2".to_string()],
                vec!["e2n".to_string()],
            ],
            vec!["o1ng".to_string(), "uo2".to_string(), "e2n".to_string()],
        ),
        TestCase::new(
            "中国人".to_string(),
            pinyin::Args {
                style: pinyin::Style::Normal,
                heteronym: true,
            },
            vec![
                vec!["zhong".to_string(), "zhong".to_string()],
                vec!["guo".to_string()],
                vec!["ren".to_string()],
            ],
            vec!["zhong".to_string(), "guo".to_string(), "ren".to_string()],
        ),
    ];
    for data in &test_data {
        assert_eq!(data.result, pinyin::pinyin(&data.hans, &data.args));
        assert_eq!(
            data.lazy_result,
            pinyin::lazy_pinyin(&data.hans, &data.args)
        );
    }
}

#[test]
fn test_non_chinese_pinyin() {
    let hans = "中国人abc你好";
    let expect = vec![
        vec!["zhong".to_string()],
        vec!["guo".to_string()],
        vec!["ren".to_string()],
        vec![],
        vec![],
        vec![],
        vec!["ni".to_string()],
        vec!["hao".to_string()],
    ];
    let result = pinyin::pinyin(hans, &pinyin::Args::new());
    assert_eq!(expect, result);
}

#[test]
fn test_non_chinese_lazy_pinyin() {
    let hans = "中国人abc你好";
    let expect = vec![
        "zhong".to_string(),
        "guo".to_string(),
        "ren".to_string(),
        "ni".to_string(),
        "hao".to_string(),
    ];
    let result = pinyin::lazy_pinyin(hans, &pinyin::Args::new());
    assert_eq!(expect, result);
}

#[test]
fn test_new_args() {
    let args = pinyin::Args::new();
    assert_eq!(pinyin::Style::Normal, args.style);
    assert_eq!(false, args.heteronym);
}

#[test]
fn test_no_initial() {
    let hans = "安";
    let expect = vec!["an".to_string()];
    let result = pinyin::lazy_pinyin(hans, &pinyin::Args::new());
    assert_eq!(expect, result);
}

#[test]
fn test_no_phonetic_symbol() {
    let hans = "啊";
    let expect = vec!["a".to_string()];
    let result = pinyin::lazy_pinyin(hans, &pinyin::Args::new());
    assert_eq!(expect, result);
}
<|endoftext|>


<commit_before>extern crate musicbrainz;
use musicbrainz::*;

#[test]
fn test_artist_equal() {
    let a = artist::Artist::new(
        Uuid::nil(),
        String::from("insert name here"),
        String::new(),
        enums::PersonType::Other,
        Vec::new(),
        Vec::new()
    );

    let b = artist::Artist::new(
        Uuid::nil(),
        String::from("insert name here"),
        String::from("gender"),
        enums::PersonType::Other,
        vec![String::from("tags")],
        Vec::new(),
    );

    assert_eq!(a, b);
}<commit_msg>Add artist inequality test<commit_after>extern crate musicbrainz;
use musicbrainz::*;

#[test]
fn test_artist_equal() {
    let a = artist::Artist::new(
        Uuid::nil(),
        String::from("insert name here"),
        String::new(),
        enums::PersonType::Other,
        Vec::new(),
        Vec::new()
    );

    let b = artist::Artist::new(
        Uuid::nil(),
        String::from("insert name here"),
        String::from("gender"),
        enums::PersonType::Other,
        vec![String::from("tags")],
        Vec::new(),
    );

    assert_eq!(a, b);
}

#[test]
#[should_panic]
fn test_artist_not_equal() {
    let a = artist::Artist::new(
        Uuid::nil(),
        String::from("foo"),
        String::new(),
        enums::PersonType::Other,
        Vec::new(),
        Vec::new()
    );

    let b = artist::Artist::new(
        Uuid::nil(),
        String::from("bar"),
        String::from("gender"),
        enums::PersonType::Other,
        vec![String::from("tags")],
        Vec::new(),
    );

    assert_eq!(a, b);
}<|endoftext|>


<commit_before>extern crate codespawn;

#[test]
fn check_from_xml() {
    let raw_code = codespawn::from_xml("examples/sample.xml").unwrap();

    for c in raw_code.configs.iter() {
        println!("{}", c.1);
    }

    println!("{}", raw_code);
    println!("{}", raw_code.to_cpp());
    println!("{}", raw_code.to_rust());

    // save to .rst file instead of .rs so that subsequent test don't get confused
    let _ = raw_code.to_rust().to_file("tests/sample.rst");
    let _ = raw_code.to_cpp().to_file("tests/sample.cpp");
}

#[test]
fn check_from_json() {
    let raw_code = codespawn::from_json("examples/sample.json").unwrap();

    for c in raw_code.configs.iter() {
        println!("{}", c.1);
    }

    println!("{}", raw_code);
    println!("{}", raw_code.to_cpp());
    println!("{}", raw_code.to_rust());

    // save to .rst file instead of .rs so that subsequent test don't get confused
    let _ = raw_code.to_rust().to_file("tests/sample.rst");
    let _ = raw_code.to_cpp().to_file("tests/sample.cpp");
}

#[test]
fn check_simple_json() {
    let raw_code = codespawn::from_json_str("{\"config\": [\"tests/dummy_cfg.json\", \"examples/config.json\"],\"var\":[{\"void*\":\"void_ptr\"},{\"int\":\"some_number\"}]}").unwrap();
    let _ = raw_code.to_cpp();
    let _ = raw_code.to_rust();
}

#[test]
#[should_panic]
fn check_from_xml_fail() {
    let _ = codespawn::from_xml("foobar").unwrap(); }

#[test]
#[should_panic]
fn check_from_json_fail() {
    let _ = codespawn::from_json("foobar").unwrap(); }

#[test]
#[should_panic]
fn check_from_xml_fail_cfg() {
    let _ = codespawn::from_xml_str("<config name=\"foobar\"/><var name=\"x\" type=\"int\"/>").unwrap(); }

#[test]
#[should_panic]
fn check_from_json_fail_cfg() {
    let _ = codespawn::from_json_str("{\"config\": \"foobar\", \"var\": {\"name\": \"x\", \"type\":\"int\" }}").unwrap(); }

#[test]
#[should_panic]
fn check_from_xml_fail_malformed() {
    let _ = codespawn::from_xml_str("<config name=\"foobar\"/>var name=\"x\" type=\"int\"/>").unwrap(); }

#[test]
#[should_panic]
fn check_from_json_fail_malformed() {
    let _ = codespawn::from_json_str("{\"config\": \"examples/config.json\" \"var\": {\"name\": \"x\", \"type\":\"int\" }}").unwrap(); }

#[test]
#[should_panic]
fn check_from_xml_fail_enum() {
    let rc = codespawn::from_xml_str("<enum name=\"Foo\"><func name=\"x\" type=\"int\"/></enum>").unwrap();
    rc.to_rust().to_string(); }

#[test]
#[should_panic]
fn check_from_json_fail_enum() {
    let rc = codespawn::from_json_str("{\"enum\":{ \"name\":\"Foo\",\"func\": { \"name\":\"x\",\"type\":\"int\"}}}").unwrap();
    rc.to_cpp().to_string(); }

#[test]
#[should_panic]
fn check_from_xml_fail_func() {
    let rc = codespawn::from_xml_str("<func name=\"x\" type=\"int\"><enum name=\"Foo\"></enum></func>").unwrap();
    rc.to_rust().to_string(); }

#[test]
#[should_panic]
fn check_from_json_fail_func() {
    let rc = codespawn::from_json_str("{\"func\": {\"name\":\"x\",\"type\":\"int\",\"enum\": {\"name\":\"Foo\"}}}").unwrap();
    rc.to_cpp().to_string(); }

#[test]
#[should_panic]
fn check_from_xml_fail_bitflags() {
    let rc = codespawn::from_xml_str("<struct name=\"Foo\"><bitflags name=\"x\" type=\"int\"><enum></enum></bitflags></struct>").unwrap();
    rc.to_rust().to_string(); }

#[test]
#[should_panic]
fn check_from_json_fail_bitflags() {
    let rc = codespawn::from_json_str("{\"struct\":{ \"name\":\"Foo\",\"bitflags\": { \"name\":\"x\",\"type\":\"int\", \"enum\": { \"name\": \"foonum\" }}}}").unwrap();
    rc.to_rust().to_string(); }

#[test]
#[should_panic]
fn check_from_xml_fail_malformed_cfg() {
    let _ = codespawn::from_xml_str("<config name=\"tests/malformed_cfg.xml\"/><var name=\"x\" type=\"int\"/>").unwrap(); }

#[test]
#[should_panic]
fn check_write_file() {
    let raw_code = codespawn::from_xml("examples/sample.xml").unwrap();
    raw_code.to_cpp().to_file("").unwrap(); }
<commit_msg>added more test cases<commit_after>extern crate codespawn;

#[test]
fn check_from_xml() {
    let raw_code = codespawn::from_xml("examples/sample.xml").unwrap();

    for c in raw_code.configs.iter() {
        println!("{}", c.1);
    }

    println!("{}", raw_code);
    println!("{}", raw_code.to_cpp());
    println!("{}", raw_code.to_rust());

    // save to .rst file instead of .rs so that subsequent test don't get confused
    let _ = raw_code.to_rust().to_file("tests/sample.rst");
    let _ = raw_code.to_cpp().to_file("tests/sample.cpp");
}

#[test]
fn check_from_json() {
    let raw_code = codespawn::from_json("examples/sample.json").unwrap();

    for c in raw_code.configs.iter() {
        println!("{}", c.1);
    }

    println!("{}", raw_code);
    println!("{}", raw_code.to_cpp());
    println!("{}", raw_code.to_rust());

    // save to .rst file instead of .rs so that subsequent test don't get confused
    let _ = raw_code.to_rust().to_file("tests/sample.rst");
    let _ = raw_code.to_cpp().to_file("tests/sample.cpp");
}

#[test]
fn check_simple_json() {
    let raw_code = codespawn::from_json_str("{\"config\": [\"tests/dummy_cfg.json\", \"examples/config.json\"],\"var\":[{\"void*\":\"void_ptr\"},{\"int\":\"some_number\"}]}").unwrap();
    let _ = raw_code.to_cpp();
    let _ = raw_code.to_rust();
}

#[test]
#[should_panic]
fn check_from_xml_fail() {
    let _ = codespawn::from_xml("foobar").unwrap_or_else(|e| { panic!("{}", e);}); }

#[test]
#[should_panic]
fn check_from_json_fail() {
    let _ = codespawn::from_json("foobar").unwrap_or_else(|e| { panic!("{}", e);}); }

#[test]
#[should_panic]
fn check_from_xml_fail_cfg() {
    let _ = codespawn::from_xml_str("<config name=\"foobar\"/><var name=\"x\" type=\"int\"/>").unwrap_or_else(|e| { panic!("{}", e);}); }

#[test]
#[should_panic]
fn check_from_json_fail_cfg() {
    let _ = codespawn::from_json_str("{\"config\": \"foobar\", \"var\": {\"name\": \"x\", \"type\":\"int\" }}").unwrap(); }

#[test]
#[should_panic]
fn check_from_xml_fail_malformed() {
    let _ = codespawn::from_xml_str("<config name=\"foobar\"/>var name=\"x\" type=\"int\"/>").unwrap_or_else(|e| { panic!("{}", e);}); }

#[test]
#[should_panic]
fn check_from_json_fail_malformed() {
    let _ = codespawn::from_json_str("{\"config\": \"examples/config.json\" \"var\": {\"name\": \"x\", \"type\":\"int\" }}").unwrap_or_else(|e| { panic!("{}", e);}); }

#[test]
#[should_panic]
fn check_from_xml_fail_enum() {
    let rc = codespawn::from_xml_str("<enum name=\"Foo\"><func name=\"x\" type=\"int\"/></enum>").unwrap_or_else(|e| { panic!("{}", e);});
    rc.to_rust().to_string(); }

#[test]
#[should_panic]
fn check_from_json_fail_enum() {
    let rc = codespawn::from_json_str("{\"enum\":{ \"name\":\"Foo\",\"func\": { \"name\":\"x\",\"type\":\"int\"}}}").unwrap_or_else(|e| { panic!("{}", e);});
    rc.to_cpp().to_string(); }

#[test]
#[should_panic]
fn check_from_xml_fail_func() {
    let rc = codespawn::from_xml_str("<func name=\"x\" type=\"int\"><enum name=\"Foo\"></enum></func>").unwrap_or_else(|e| { panic!("{}", e);});
    rc.to_rust().to_string(); }

#[test]
#[should_panic]
fn check_from_json_fail_func() {
    let rc = codespawn::from_json_str("{\"func\": {\"name\":\"x\",\"type\":\"int\",\"enum\": {\"name\":\"Foo\"}}}").unwrap_or_else(|e| { panic!("{}", e);});
    rc.to_cpp().to_string(); }

#[test]
#[should_panic]
fn check_from_xml_fail_bitflags() {
    let rc = codespawn::from_xml_str("<struct name=\"Foo\"><bitflags name=\"x\" type=\"int\"><enum></enum></bitflags></struct>").unwrap_or_else(|e| { panic!("{}", e);});
    rc.to_rust().to_string(); }

#[test]
#[should_panic]
fn check_from_json_fail_bitflags() {
    let rc = codespawn::from_json_str("{\"struct\":{ \"name\":\"Foo\",\"bitflags\": { \"name\":\"x\",\"type\":\"int\", \"enum\": { \"name\": \"foonum\" }}}}").unwrap_or_else(|e| { panic!("{}", e);});
    rc.to_rust().to_string(); }

#[test]
#[should_panic]
fn check_from_xml_fail_malformed_cfg() {
    let _ = codespawn::from_xml_str("<config name=\"tests/malformed_cfg.xml\"/><var name=\"x\" type=\"int\"/>").unwrap_or_else(|e| { panic!("{}", e);}); }

#[test]
#[should_panic]
fn check_write_file() {
    let raw_code = codespawn::from_xml("examples/sample.xml").unwrap();
    raw_code.to_cpp().to_file("").unwrap_or_else(|e| { panic!("{}", e);}); }
<|endoftext|>


<commit_before><commit_msg>setting up toy graphs<commit_after>extern crate thunderdome;

#[cfg(test)]
mod helpers {
    use thunderdome::graph::Graph;

    fn toy_graph_friends() -> Box<Graph> {
        let mut g = Graph::new();
        let mut v1 = g.add_vertex();
        g
    }

}
<|endoftext|>


<commit_before>use collections::string::String;

use vec4;
use num::Num;
use regex::Regex;

#[inline(always)]
fn to_256_str<T: Num>(value: T) -> String {
    (value * T::from_usize(255usize)).round().to_string()
}

#[inline(always)]
pub fn to_rgb<T: Num>(out: [T; 4]) -> String {
    concat_string!("rgb(", &to_256_str(out[0]), ", ", &to_256_str(out[1]), ", ", &to_256_str(out[2]), ")")
}
#[test]
fn test_to_rgb() {
    assert_eq!(&to_rgb([1.0, 0.5, 0.0, 1.0]), "rgb(255, 128, 0)")
}

#[inline(always)]
pub fn to_rgba<T: Num>(out: [T; 4]) -> String {
    concat_string!("rgba(", &to_256_str(out[0]), ", ", &to_256_str(out[1]), ", ", &to_256_str(out[2]), ", ", &(out[3].to_string()), ")")
}
#[test]
fn test_to_rgba() {
    assert_eq!(&to_rgba([1.0, 0.5, 0.0, 1.0]), "rgba(255, 128, 0, 1)")
}

#[inline(always)]
fn to_number<T: Num>(value: &str) -> T {
    T::from_f64(value.parse::<f64>().unwrap())
}

#[inline(always)]
fn to_256<T: Num>(value: &str) -> T {
    to_number::<T>(value).min(T::from_usize(255usize)) / T::from_usize(255usize)
}

#[inline(always)]
pub fn from_rgba<T: Num>(out: &mut [T; 4], string: String) -> &mut [T; 4] {
    let re = Regex::new(r"^rgba\((?:\s+)?(\d+),(?:\s+)?(\d+),(?:\s+)?(\d+),(?:\s+)?((?:\.)?\d+(?:\.\d+)?)\)$").unwrap();

    match re.captures(&string) {
        Some(matches) => {
            out[0] = to_256(matches.get(1).unwrap().as_str());
            out[1] = to_256(matches.get(2).unwrap().as_str());
            out[2] = to_256(matches.get(3).unwrap().as_str());
            out[3] = to_number::<T>(
                matches.get(4).unwrap().as_str()
            ).min(T::from_usize(1usize));
        },
        None => {
            vec4::set(out, T::zero(), T::zero(), T::zero(), T::one());
        },
    }
    out
}
#[test]
fn test_from_rgba() {
    let mut v = [0.0, 0.0, 0.0, 1.0];
    from_rgba(&mut v, String::from("rgba( 255, 128, 0, 1)"));
    assert_eq!(v, [1.0, 128.0 / 255.0, 0.0, 1.0])
}

#[inline(always)]
pub fn from_rgb<T: Num>(out: &mut [T; 4], string: String) -> &mut [T; 4] {
    let re = Regex::new(r"^rgb\((?:\s+)?(\d+),(?:\s+)?(\d+),(?:\s+)?(\d+)\)$").unwrap();

    match re.captures(&string) {
        Some(matches) => {
            out[0] = to_256(matches.get(1).unwrap().as_str());
            out[1] = to_256(matches.get(2).unwrap().as_str());
            out[2] = to_256(matches.get(3).unwrap().as_str());
            out[3] = T::one();
        },
        None => {
            vec4::set(out, T::zero(), T::zero(), T::zero(), T::one());
        },
    }

    out
}
#[test]
fn test_from_rgb() {
    let mut v = [0.0, 0.0, 0.0, 1.0];
    from_rgb(&mut v, String::from("rgb( 255, 128, 0)"));
    assert_eq!(v, [1.0, 128.0 / 255.0, 0.0, 1.0])
}
<commit_msg>clean up<commit_after>use collections::string::String;

use vec4;
use num::Num;
use regex::Regex;

#[inline(always)]
fn to_256_str<T: Num>(value: T) -> String {
    (value * T::from_usize(255usize)).round().to_string()
}

#[inline(always)]
pub fn to_rgb<T: Num>(out: [T; 4]) -> String {
    concat_string!("rgb(", &to_256_str(out[0]), ", ", &to_256_str(out[1]), ", ", &to_256_str(out[2]), ")")
}
#[test]
fn test_to_rgb() {
    assert_eq!(&to_rgb([1.0, 0.5, 0.0, 1.0]), "rgb(255, 128, 0)")
}

#[inline(always)]
pub fn to_rgba<T: Num>(out: [T; 4]) -> String {
    concat_string!("rgba(", &to_256_str(out[0]), ", ", &to_256_str(out[1]), ", ", &to_256_str(out[2]), ", ", &(out[3].to_string()), ")")
}
#[test]
fn test_to_rgba() {
    assert_eq!(&to_rgba([1.0, 0.5, 0.0, 1.0]), "rgba(255, 128, 0, 1)")
}

#[inline(always)]
fn to_number<T: Num>(value: &str) -> T {
    T::from_f64(value.parse::<f64>().unwrap())
}

#[inline(always)]
fn to_256<T: Num>(value: &str) -> T {
    to_number::<T>(value).min(T::from_usize(255usize)) / T::from_usize(255usize)
}

#[inline(always)]
pub fn from_rgba<T: Num>(out: &mut [T; 4], string: String) -> &mut [T; 4] {
    let re = Regex::new(r"^rgba\((?:\s+)?(\d+),(?:\s+)?(\d+),(?:\s+)?(\d+),(?:\s+)?((?:\.)?\d+(?:\.\d+)?)\)$").unwrap();

    match re.captures(&string) {
        Some(matches) => {
            out[0] = to_256(matches.get(1).unwrap().as_str());
            out[1] = to_256(matches.get(2).unwrap().as_str());
            out[2] = to_256(matches.get(3).unwrap().as_str());
            out[3] = to_number::<T>(
                matches.get(4).unwrap().as_str()
            ).min(T::from_usize(1usize));
        },
        None => {
            vec4::set(out, T::zero(), T::zero(), T::zero(), T::one());
        },
    }
    out
}
#[test]
fn test_from_rgba() {
    let mut v = [0.0, 0.0, 0.0, 1.0];

    from_rgba(&mut v, String::from("rgba( 255, 128, 0, 1)"));
    assert_eq!(v, [1.0, 128.0 / 255.0, 0.0, 1.0]);

    from_rgba(&mut v, String::from("rgba(0, 0, 0, 1)"));
    assert_eq!(v, [0.0, 0.0, 0.0, 1.0]);
}

#[inline(always)]
pub fn from_rgb<T: Num>(out: &mut [T; 4], string: String) -> &mut [T; 4] {
    let re = Regex::new(r"^rgb\((?:\s+)?(\d+),(?:\s+)?(\d+),(?:\s+)?(\d+)\)$").unwrap();

    match re.captures(&string) {
        Some(matches) => {
            out[0] = to_256(matches.get(1).unwrap().as_str());
            out[1] = to_256(matches.get(2).unwrap().as_str());
            out[2] = to_256(matches.get(3).unwrap().as_str());
            out[3] = T::one();
        },
        None => {
            vec4::set(out, T::zero(), T::zero(), T::zero(), T::one());
        },
    }

    out
}
#[test]
fn test_from_rgb() {
    let mut v = [0.0, 0.0, 0.0, 1.0];

    from_rgb(&mut v, String::from("rgb( 255, 128, 0)"));
    assert_eq!(v, [1.0, 128.0 / 255.0, 0.0, 1.0]);

    from_rgb(&mut v, String::from("rgb(0, 0, 0)"));
    assert_eq!(v, [0.0, 0.0, 0.0, 1.0]);
}
<|endoftext|>


<commit_before>#![feature(collections)]

extern crate macaroons;
pub use macaroons::token::{Token, Tag};
pub use macaroons::caveat::{Caveat, Predicate};

const EXAMPLE_KEY: &'static str = "this is our super secret key; only we should know it";
const EXAMPLE_ID:  &'static str = "we used our secret key";
const EXAMPLE_URI: &'static str = "http://mybank/";

#[test]
fn empty_macaroon_signature() {
  let key        = String::from_str(EXAMPLE_KEY).into_bytes();
  let identifier = String::from_str(EXAMPLE_ID).into_bytes();
  let location   = String::from_str(EXAMPLE_URI).into_bytes();

  let token = Token::new(key, identifier, location);

  let expected_tag = [0xe3,0xd9,0xe0,0x29,0x08,0x52,0x6c,0x4c
                     ,0x00,0x39,0xae,0x15,0x11,0x41,0x15,0xd9
                     ,0x7f,0xdd,0x68,0xbf,0x2b,0xa3,0x79,0xb3
                     ,0x42,0xaa,0xf0,0xf6,0x17,0xd0,0x55,0x2f];

  let Tag(actual_tag) = token.tag;
  assert_eq!(expected_tag, actual_tag)
}

#[test]
fn signature_with_first_party_caveat() {
  let key        = String::from_str(EXAMPLE_KEY).into_bytes();
  let identifier = String::from_str(EXAMPLE_ID).into_bytes();
  let location   = String::from_str(EXAMPLE_URI).into_bytes();

  let token     = Token::new(key, identifier, location);
  let predicate = String::from_str("test = caveat").into_bytes();
  let new_token = token.add_caveat(Caveat::new(Predicate(predicate)));

  let expected_tag = [0x19,0x7b,0xac,0x7a,0x04,0x4a,0xf3,0x33
                     ,0x32,0x86,0x5b,0x92,0x66,0xe2,0x6d,0x49
                     ,0x3b,0xdd,0x66,0x8a,0x66,0x0e,0x44,0xd8
                     ,0x8c,0xe1,0xa9,0x98,0xc2,0x3d,0xbd,0x67];

  let Tag(actual_tag) = new_token.tag;
  assert_eq!(expected_tag, actual_tag)
}
<commit_msg>Factor example byte vectors into functions<commit_after>#![feature(collections)]

extern crate macaroons;
pub use macaroons::token::{Token, Tag};
pub use macaroons::caveat::{Caveat, Predicate};

const EXAMPLE_KEY: &'static str = "this is our super secret key; only we should know it";
const EXAMPLE_ID:  &'static str = "we used our secret key";
const EXAMPLE_URI: &'static str = "http://mybank/";

fn example_key() -> Vec<u8> {
  String::from_str(EXAMPLE_KEY).into_bytes()
}

fn example_id() -> Vec<u8> {
  String::from_str(EXAMPLE_ID).into_bytes()
}

fn example_uri() -> Vec<u8> {
  String::from_str(EXAMPLE_URI).into_bytes()
}

#[test]
fn empty_macaroon_signature() {
  let token = Token::new(example_key(), example_id(), example_uri());

  let expected_tag = [0xe3,0xd9,0xe0,0x29,0x08,0x52,0x6c,0x4c
                     ,0x00,0x39,0xae,0x15,0x11,0x41,0x15,0xd9
                     ,0x7f,0xdd,0x68,0xbf,0x2b,0xa3,0x79,0xb3
                     ,0x42,0xaa,0xf0,0xf6,0x17,0xd0,0x55,0x2f];

  let Tag(actual_tag) = token.tag;
  assert_eq!(expected_tag, actual_tag)
}

#[test]
fn signature_with_first_party_caveat() {
  let token = Token::new(example_key(), example_id(), example_uri());
  let predicate = String::from_str("test = caveat").into_bytes();
  let new_token = token.add_caveat(Caveat::new(Predicate(predicate)));

  let expected_tag = [0x19,0x7b,0xac,0x7a,0x04,0x4a,0xf3,0x33
                     ,0x32,0x86,0x5b,0x92,0x66,0xe2,0x6d,0x49
                     ,0x3b,0xdd,0x66,0x8a,0x66,0x0e,0x44,0xd8
                     ,0x8c,0xe1,0xa9,0x98,0xc2,0x3d,0xbd,0x67];

  let Tag(actual_tag) = new_token.tag;
  assert_eq!(expected_tag, actual_tag)
}
<|endoftext|>


<commit_before>extern crate digits;
use digits::{BaseCustom,Digits};

#[test]
fn it_can_return_string_result() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let num = Digits::new(&base10, "12345".to_string());
  assert_eq!(num.to_s(), "12345");
  assert_eq!(num.to_string(), "12345");
  let s: String = num.into();
  assert_eq!(s, "12345");
}

#[test]
fn it_can_add() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let num1 = Digits::new_one(&base10);
  assert_eq!(num1.clone().add(num1).to_s(), "2");
}

#[test]
fn it_can_give_length() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let num1 = Digits::new(&base10, "1111111".to_string());
  assert_eq!(num1.length(), 7);
}

#[test]
fn it_can_add_with_carry_over() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let num13 = Digits::new(&base10, "13".to_string());
  let num29 = Digits::new(&base10, "29".to_string());
  assert_eq!(num13.clone().add(num29).to_s(), "42");
}

#[test]
fn it_can_add_with_multiple_carry_over() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let numa = Digits::new(&base10, "999".to_string());
  let numb = Digits::new(&base10, "999".to_string());
  assert_eq!(numa.clone().add(numb).to_s(), "1998");
}

#[test]
fn it_can_go_beyond_u64_max() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let num_u64_max = Digits::new(&base10, "18446744073709551615".to_string());
  let one = Digits::new(&base10, "1".to_string());
  assert_eq!(num_u64_max.clone().add(one).to_s(), "18446744073709551616");
}

// #[test]
// Fn it_can_pow_beyond_u64_max() {
//   let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
//   let mut num_u64_max = Digits::new(&base10, "18446744073709551615".to_string());
//   let two = num_u64_max.propagate("2".to_string());
//   assert_eq!(num_u64_max.pow(two).to_s(), "340282366920938463426481119284349108225");
// }

#[test]
fn it_can_provide_zero() {
  let base3 = BaseCustom::<char>::new("ABC".chars().collect());
  let num = Digits::new(&base3, "BA".to_string());
  assert_eq!(num.zero().pinky(), 'A');
  let zero = Digits::new_zero(&base3);
  assert_eq!(zero.pinky(), 'A');
}

#[test]
fn it_can_provide_one() {
  let base3 = BaseCustom::<char>::new("ABC".chars().collect());
  let num = Digits::new(&base3, "BA".to_string());
  assert_eq!(num.one().pinky(), 'B');
  let one = Digits::new_one(&base3);
  assert_eq!(one.pinky(), 'B');
}

#[test]
fn it_can_prove_zero() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let one = Digits::new_one(&base10);
  assert_eq!(one.is_zero(), false);
  let zero = Digits::new(&base10, "0000".to_string());
  assert_eq!(zero.is_zero(), true);
  let thousand = Digits::new(&base10, "01000".to_string());
  assert_eq!(thousand.is_zero(), false);
}

#[test]
fn eleven_times_one_with_mul_method() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let one = Digits::new_one(&base10);
  let mut eleven = one.propagate("11".to_string());
  assert_eq!(eleven.mul(one).to_s(), "11");
}

#[test]
fn one_times_eleven_with_mul_method() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let mut one = Digits::new_one(&base10);
  let eleven = one.propagate("11".to_string());
  assert_eq!(one.mul(eleven).to_s(), "11");
}

#[test]
fn cdlxxxii_times_xxxviii_with_mul_method() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let mut cdlxxxii = Digits::new(&base10, "482".to_string());
  let xxxviii = cdlxxxii.propagate("38".to_string());
  assert_eq!(cdlxxxii.mul(xxxviii).to_s(), "18316");
}

#[test]
fn it_multiplies_powers_of_with_pow() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let mut ten = Digits::new(&base10, "10".to_string());
  let two = ten.propagate("2".to_string());
  assert_eq!(ten.pow(two).to_s(), "100");
  let two = ten.propagate("2".to_string());
  assert_eq!(ten.pow(two).to_s(), "10000");
}

#[test]
fn it_succs() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let mut nine = Digits::new(&base10, "9".to_string());
  assert_eq!(nine.succ().to_s(), "10");
  assert_eq!(nine.succ().to_s(), "11");
  assert_eq!(nine.succ().to_s(), "12");
}

#[test]
fn it_preds_till_zero() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let mut ten = Digits::new(&base10, "10".to_string());
  assert_eq!(ten.pred_till_zero().to_s(), "9");
  assert_eq!(ten.pred_till_zero().to_s(), "8");
  assert_eq!(ten.pred_till_zero().to_s(), "7");
  assert_eq!(ten.pred_till_zero().to_s(), "6");
  assert_eq!(ten.pred_till_zero().to_s(), "5");
  assert_eq!(ten.pred_till_zero().to_s(), "4");
  assert_eq!(ten.pred_till_zero().to_s(), "3");
  assert_eq!(ten.pred_till_zero().to_s(), "2");
  assert_eq!(ten.pred_till_zero().to_s(), "1");
  assert_eq!(ten.pred_till_zero().to_s(), "0");
  assert_eq!(ten.pred_till_zero().to_s(), "0");
}
<commit_msg>case incorrect in comment<commit_after>extern crate digits;
use digits::{BaseCustom,Digits};

#[test]
fn it_can_return_string_result() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let num = Digits::new(&base10, "12345".to_string());
  assert_eq!(num.to_s(), "12345");
  assert_eq!(num.to_string(), "12345");
  let s: String = num.into();
  assert_eq!(s, "12345");
}

#[test]
fn it_can_add() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let num1 = Digits::new_one(&base10);
  assert_eq!(num1.clone().add(num1).to_s(), "2");
}

#[test]
fn it_can_give_length() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let num1 = Digits::new(&base10, "1111111".to_string());
  assert_eq!(num1.length(), 7);
}

#[test]
fn it_can_add_with_carry_over() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let num13 = Digits::new(&base10, "13".to_string());
  let num29 = Digits::new(&base10, "29".to_string());
  assert_eq!(num13.clone().add(num29).to_s(), "42");
}

#[test]
fn it_can_add_with_multiple_carry_over() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let numa = Digits::new(&base10, "999".to_string());
  let numb = Digits::new(&base10, "999".to_string());
  assert_eq!(numa.clone().add(numb).to_s(), "1998");
}

#[test]
fn it_can_go_beyond_u64_max() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let num_u64_max = Digits::new(&base10, "18446744073709551615".to_string());
  let one = Digits::new(&base10, "1".to_string());
  assert_eq!(num_u64_max.clone().add(one).to_s(), "18446744073709551616");
}

// #[test]
// fn it_can_pow_beyond_u64_max() {
//   let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
//   let mut num_u64_max = Digits::new(&base10, "18446744073709551615".to_string());
//   let two = num_u64_max.propagate("2".to_string());
//   assert_eq!(num_u64_max.pow(two).to_s(), "340282366920938463426481119284349108225");
// }

#[test]
fn it_can_provide_zero() {
  let base3 = BaseCustom::<char>::new("ABC".chars().collect());
  let num = Digits::new(&base3, "BA".to_string());
  assert_eq!(num.zero().pinky(), 'A');
  let zero = Digits::new_zero(&base3);
  assert_eq!(zero.pinky(), 'A');
}

#[test]
fn it_can_provide_one() {
  let base3 = BaseCustom::<char>::new("ABC".chars().collect());
  let num = Digits::new(&base3, "BA".to_string());
  assert_eq!(num.one().pinky(), 'B');
  let one = Digits::new_one(&base3);
  assert_eq!(one.pinky(), 'B');
}

#[test]
fn it_can_prove_zero() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let one = Digits::new_one(&base10);
  assert_eq!(one.is_zero(), false);
  let zero = Digits::new(&base10, "0000".to_string());
  assert_eq!(zero.is_zero(), true);
  let thousand = Digits::new(&base10, "01000".to_string());
  assert_eq!(thousand.is_zero(), false);
}

#[test]
fn eleven_times_one_with_mul_method() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let one = Digits::new_one(&base10);
  let mut eleven = one.propagate("11".to_string());
  assert_eq!(eleven.mul(one).to_s(), "11");
}

#[test]
fn one_times_eleven_with_mul_method() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let mut one = Digits::new_one(&base10);
  let eleven = one.propagate("11".to_string());
  assert_eq!(one.mul(eleven).to_s(), "11");
}

#[test]
fn cdlxxxii_times_xxxviii_with_mul_method() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let mut cdlxxxii = Digits::new(&base10, "482".to_string());
  let xxxviii = cdlxxxii.propagate("38".to_string());
  assert_eq!(cdlxxxii.mul(xxxviii).to_s(), "18316");
}

#[test]
fn it_multiplies_powers_of_with_pow() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let mut ten = Digits::new(&base10, "10".to_string());
  let two = ten.propagate("2".to_string());
  assert_eq!(ten.pow(two).to_s(), "100");
  let two = ten.propagate("2".to_string());
  assert_eq!(ten.pow(two).to_s(), "10000");
}

#[test]
fn it_succs() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let mut nine = Digits::new(&base10, "9".to_string());
  assert_eq!(nine.succ().to_s(), "10");
  assert_eq!(nine.succ().to_s(), "11");
  assert_eq!(nine.succ().to_s(), "12");
}

#[test]
fn it_preds_till_zero() {
  let base10 = BaseCustom::<char>::new("0123456789".chars().collect());
  let mut ten = Digits::new(&base10, "10".to_string());
  assert_eq!(ten.pred_till_zero().to_s(), "9");
  assert_eq!(ten.pred_till_zero().to_s(), "8");
  assert_eq!(ten.pred_till_zero().to_s(), "7");
  assert_eq!(ten.pred_till_zero().to_s(), "6");
  assert_eq!(ten.pred_till_zero().to_s(), "5");
  assert_eq!(ten.pred_till_zero().to_s(), "4");
  assert_eq!(ten.pred_till_zero().to_s(), "3");
  assert_eq!(ten.pred_till_zero().to_s(), "2");
  assert_eq!(ten.pred_till_zero().to_s(), "1");
  assert_eq!(ten.pred_till_zero().to_s(), "0");
  assert_eq!(ten.pred_till_zero().to_s(), "0");
}
<|endoftext|>


<commit_before>extern crate bk_tree;

use bk_tree::{BKNode, BKTree};
use bk_tree::metrics::levenshtein;

#[test]
fn node_construct() {
    let node: BKNode<&str> = BKNode::new("foo");
    assert_eq!(node.key, "foo");
    assert!(node.children.is_empty());
}

#[test]
fn tree_construct() {
    let tree: BKTree<&str> = BKTree::new(levenshtein);
    assert!(tree.root.is_none());
}

#[test]
fn tree_add() {
    let mut tree: BKTree<&str> = BKTree::new(levenshtein);
    tree.add("foo");
    match tree.root {
        Some(ref root) => {
            assert_eq!(root.key, "foo");
        },
        None => { assert!(false); }
    }
    tree.add("fop");
    println!("foo fop {}", levenshtein("foo", "fop"));
    assert_eq!(tree.root.unwrap().children.get(&1).unwrap().key, "fop");
}

#[test]
fn tree_find() {
    /*
     * This example tree is from
     * https://nullwords.wordpress.com/2013/03/13/the-bk-tree-a-data-structure-for-spell-checking/
     */
    let mut tree: BKTree<&str> = BKTree::new(levenshtein);
    tree.add("book");
    tree.add("books");
    tree.add("cake");
    tree.add("boo");
    tree.add("cape");
    tree.add("boon");
    tree.add("cook");
    tree.add("cart");
    assert_eq!(tree.find("caqe", 1), vec!["cake", "cape"]);
    assert_eq!(tree.find("cape", 1), vec!["cake", "cape"]);
    assert_eq!(tree.find("book", 1), vec!["book", "books", "boo", "boon", "cook"]);
    assert_eq!(tree.find("book", 0), vec!["book"]);
    assert!(tree.find("foobar", 1).is_empty());
}
<commit_msg>Fix tests to check that the vectors are same unordered<commit_after>extern crate bk_tree;

use std::fmt::Debug;

use bk_tree::{BKNode, BKTree};
use bk_tree::metrics::levenshtein;

fn assert_eq_sorted<T>(left: Vec<T>, right: Vec<T>) where T: Ord + Clone + Debug {
    let mut left_mut = left.to_vec();
    let mut right_mut = right.to_vec();

    left_mut.sort();
    right_mut.sort();

    assert_eq!(left_mut, right_mut);
}

#[test]
fn node_construct() {
    let node: BKNode<&str> = BKNode::new("foo");
    assert_eq!(node.key, "foo");
    assert!(node.children.is_empty());
}

#[test]
fn tree_construct() {
    let tree: BKTree<&str> = BKTree::new(levenshtein);
    assert!(tree.root.is_none());
}

#[test]
fn tree_add() {
    let mut tree: BKTree<&str> = BKTree::new(levenshtein);
    tree.add("foo");
    match tree.root {
        Some(ref root) => {
            assert_eq!(root.key, "foo");
        },
        None => { assert!(false); }
    }
    tree.add("fop");
    println!("foo fop {}", levenshtein("foo", "fop"));
    assert_eq!(tree.root.unwrap().children.get(&1).unwrap().key, "fop");
}

#[test]
fn tree_find() {
    /*
     * This example tree is from
     * https://nullwords.wordpress.com/2013/03/13/the-bk-tree-a-data-structure-for-spell-checking/
     */
    let mut tree: BKTree<&str> = BKTree::new(levenshtein);
    tree.add("book");
    tree.add("books");
    tree.add("cake");
    tree.add("boo");
    tree.add("cape");
    tree.add("boon");
    tree.add("cook");
    tree.add("cart");
    assert_eq_sorted(tree.find("caqe", 1), vec!["cake", "cape"]);
    assert_eq_sorted(tree.find("cape", 1), vec!["cake", "cape"]);
    assert_eq_sorted(tree.find("book", 1), vec!["book", "books", "boo", "boon", "cook"]);
    assert_eq_sorted(tree.find("book", 0), vec!["book"]);
    assert!(tree.find("foobar", 1).is_empty());
}
<|endoftext|>