From 1ed646eaf7d09455a086afa11bcd83a7d2a6b0f4 Mon Sep 17 00:00:00 2001 From: Steven Fackler Date: Sat, 28 Jun 2014 13:57:36 -0700 Subject: [PATCH] Extract tests from libcore to a separate crate Libcore's test infrastructure is complicated by the fact that many lang items are defined in the crate. The current approach (realcore/realstd imports) is hacky and hard to work with (tests inside of core::cmp haven't been run for months!). Moving tests to a separate crate does mean that they can only test the public API of libcore, but I don't feel that that is too much of an issue. The only tests that I had to get rid of were some checking the various numeric formatters, but those are also exercised through normal format! calls in other tests. --- mk/tests.mk | 9 +- src/liballoc/owned.rs | 48 ++ src/libcore/any.rs | 176 ------ src/libcore/atomics.rs | 94 ---- src/libcore/cell.rs | 129 ----- src/libcore/char.rs | 202 ------- src/libcore/clone.rs | 60 -- src/libcore/cmp.rs | 64 --- src/libcore/failure.rs | 4 +- src/libcore/finally.rs | 52 -- src/libcore/fmt/mod.rs | 25 - src/libcore/fmt/num.rs | 280 ---------- src/libcore/intrinsics.rs | 9 - src/libcore/iter.rs | 865 +---------------------------- src/libcore/lib.rs | 29 +- src/libcore/macros.rs | 10 - src/libcore/mem.rs | 179 ------ src/libcore/num/int_macros.rs | 148 ----- src/libcore/num/mod.rs | 16 - src/libcore/num/uint_macros.rs | 107 ---- src/libcore/ops.rs | 37 -- src/libcore/option.rs | 288 ---------- src/libcore/ptr.rs | 269 +-------- src/libcore/raw.rs | 29 - src/libcore/result.rs | 163 ------ src/libcore/slice.rs | 4 - src/libcore/str.rs | 12 - src/libcore/tuple.rs | 99 +--- src/libcoretest/any.rs | 131 +++++ src/libcoretest/atomics.rs | 83 +++ src/libcoretest/cell.rs | 129 +++++ src/libcoretest/char.rs | 202 +++++++ src/libcoretest/clone.rs | 39 ++ src/libcoretest/cmp.rs | 69 +++ src/libcoretest/finally.rs | 59 ++ src/libcoretest/fmt/mod.rs | 11 + src/libcoretest/fmt/num.rs | 234 ++++++++ src/libcoretest/iter.rs | 835 ++++++++++++++++++++++++++++ src/libcoretest/lib.rs | 31 ++ src/libcoretest/mem.rs | 173 ++++++ src/libcoretest/num/i16.rs | 11 + src/libcoretest/num/i32.rs | 11 + src/libcoretest/num/i64.rs | 11 + src/libcoretest/num/i8.rs | 11 + src/libcoretest/num/int.rs | 11 + src/libcoretest/num/int_macros.rs | 160 ++++++ src/libcoretest/num/mod.rs | 39 ++ src/libcoretest/num/u16.rs | 11 + src/libcoretest/num/u32.rs | 11 + src/libcoretest/num/u64.rs | 11 + src/libcoretest/num/u8.rs | 11 + src/libcoretest/num/uint.rs | 11 + src/libcoretest/num/uint_macros.rs | 118 ++++ src/libcoretest/ops.rs | 29 + src/libcoretest/option.rs | 278 +++++++++ src/libcoretest/ptr.rs | 255 +++++++++ src/libcoretest/raw.rs | 35 ++ src/libcoretest/result.rs | 161 ++++++ src/libcoretest/tuple.rs | 92 +++ src/libstd/gc.rs | 7 + 60 files changed, 3348 insertions(+), 3339 deletions(-) create mode 100644 src/libcoretest/any.rs create mode 100644 src/libcoretest/atomics.rs create mode 100644 src/libcoretest/cell.rs create mode 100644 src/libcoretest/char.rs create mode 100644 src/libcoretest/clone.rs create mode 100644 src/libcoretest/cmp.rs create mode 100644 src/libcoretest/finally.rs create mode 100644 src/libcoretest/fmt/mod.rs create mode 100644 src/libcoretest/fmt/num.rs create mode 100644 src/libcoretest/iter.rs create mode 100644 src/libcoretest/lib.rs create mode 100644 src/libcoretest/mem.rs create mode 100644 src/libcoretest/num/i16.rs create mode 100644 src/libcoretest/num/i32.rs create mode 100644 src/libcoretest/num/i64.rs create mode 100644 src/libcoretest/num/i8.rs create mode 100644 src/libcoretest/num/int.rs create mode 100644 src/libcoretest/num/int_macros.rs create mode 100644 src/libcoretest/num/mod.rs create mode 100644 src/libcoretest/num/u16.rs create mode 100644 src/libcoretest/num/u32.rs create mode 100644 src/libcoretest/num/u64.rs create mode 100644 src/libcoretest/num/u8.rs create mode 100644 src/libcoretest/num/uint.rs create mode 100644 src/libcoretest/num/uint_macros.rs create mode 100644 src/libcoretest/ops.rs create mode 100644 src/libcoretest/option.rs create mode 100644 src/libcoretest/ptr.rs create mode 100644 src/libcoretest/raw.rs create mode 100644 src/libcoretest/result.rs create mode 100644 src/libcoretest/tuple.rs diff --git a/mk/tests.mk b/mk/tests.mk index 1989d6ef86797..44bedde99ccff 100644 --- a/mk/tests.mk +++ b/mk/tests.mk @@ -14,7 +14,12 @@ ###################################################################### # The names of crates that must be tested -TEST_TARGET_CRATES = $(TARGET_CRATES) + +# libcore tests are in a separate crate +DEPS_coretest := +$(eval $(call RUST_CRATE,coretest)) + +TEST_TARGET_CRATES = $(filter-out core,$(TARGET_CRATES)) coretest TEST_DOC_CRATES = $(DOC_CRATES) TEST_HOST_CRATES = $(HOST_CRATES) TEST_CRATES = $(TEST_TARGET_CRATES) $(TEST_HOST_CRATES) @@ -172,7 +177,7 @@ check-notidy: cleantmptestlogs cleantestlibs all check-stage2 $(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log check-lite: cleantestlibs cleantmptestlogs \ - $(foreach crate,$(TARGET_CRATES),check-stage2-$(crate)) \ + $(foreach crate,$(TEST_TARGET_CRATES),check-stage2-$(crate)) \ check-stage2-rpass \ check-stage2-rfail check-stage2-cfail check-stage2-rmake $(Q)$(CFG_PYTHON) $(S)src/etc/check-summary.py tmp/*.log diff --git a/src/liballoc/owned.rs b/src/liballoc/owned.rs index 589adbd41d04e..33afa806f4e39 100644 --- a/src/liballoc/owned.rs +++ b/src/liballoc/owned.rs @@ -146,3 +146,51 @@ impl fmt::Show for Box { f.pad("Box") } } + +#[cfg(test)] +mod test { + #[test] + fn test_owned_clone() { + let a = box 5i; + let b: Box = a.clone(); + assert!(a == b); + } + + #[test] + fn any_move() { + let a = box 8u as Box; + let b = box Test as Box; + + match a.move::() { + Ok(a) => { assert!(a == box 8u); } + Err(..) => fail!() + } + match b.move::() { + Ok(a) => { assert!(a == box Test); } + Err(..) => fail!() + } + + let a = box 8u as Box; + let b = box Test as Box; + + assert!(a.move::>().is_err()); + assert!(b.move::>().is_err()); + } + + #[test] + fn test_show() { + let a = box 8u as Box; + let b = box Test as Box; + let a_str = a.to_str(); + let b_str = b.to_str(); + assert_eq!(a_str.as_slice(), "Box"); + assert_eq!(b_str.as_slice(), "Box"); + + let a = &8u as &Any; + let b = &Test as &Any; + let s = format!("{}", a); + assert_eq!(s.as_slice(), "&Any"); + let s = format!("{}", b); + assert_eq!(s.as_slice(), "&Any"); + } +} diff --git a/src/libcore/any.rs b/src/libcore/any.rs index 4a35dde08eb5c..8021fa50d8f46 100644 --- a/src/libcore/any.rs +++ b/src/libcore/any.rs @@ -115,179 +115,3 @@ impl<'a> AnyMutRefExt<'a> for &'a mut Any { } } } - -#[cfg(test)] -mod tests { - use prelude::*; - use super::*; - use realstd::owned::{Box, AnyOwnExt}; - use realstd::str::Str; - - #[deriving(PartialEq, Show)] - struct Test; - - static TEST: &'static str = "Test"; - - #[test] - fn any_referenced() { - let (a, b, c) = (&5u as &Any, &TEST as &Any, &Test as &Any); - - assert!(a.is::()); - assert!(!b.is::()); - assert!(!c.is::()); - - assert!(!a.is::<&'static str>()); - assert!(b.is::<&'static str>()); - assert!(!c.is::<&'static str>()); - - assert!(!a.is::()); - assert!(!b.is::()); - assert!(c.is::()); - } - - #[test] - fn any_owning() { - let (a, b, c) = (box 5u as Box, box TEST as Box, box Test as Box); - - assert!(a.is::()); - assert!(!b.is::()); - assert!(!c.is::()); - - assert!(!a.is::<&'static str>()); - assert!(b.is::<&'static str>()); - assert!(!c.is::<&'static str>()); - - assert!(!a.is::()); - assert!(!b.is::()); - assert!(c.is::()); - } - - #[test] - fn any_as_ref() { - let a = &5u as &Any; - - match a.as_ref::() { - Some(&5) => {} - x => fail!("Unexpected value {}", x) - } - - match a.as_ref::() { - None => {} - x => fail!("Unexpected value {}", x) - } - } - - #[test] - fn any_as_mut() { - let mut a = 5u; - let mut b = box 7u; - - let a_r = &mut a as &mut Any; - let tmp: &mut uint = &mut *b; - let b_r = tmp as &mut Any; - - match a_r.as_mut::() { - Some(x) => { - assert_eq!(*x, 5u); - *x = 612; - } - x => fail!("Unexpected value {}", x) - } - - match b_r.as_mut::() { - Some(x) => { - assert_eq!(*x, 7u); - *x = 413; - } - x => fail!("Unexpected value {}", x) - } - - match a_r.as_mut::() { - None => (), - x => fail!("Unexpected value {}", x) - } - - match b_r.as_mut::() { - None => (), - x => fail!("Unexpected value {}", x) - } - - match a_r.as_mut::() { - Some(&612) => {} - x => fail!("Unexpected value {}", x) - } - - match b_r.as_mut::() { - Some(&413) => {} - x => fail!("Unexpected value {}", x) - } - } - - #[test] - fn any_move() { - use realstd::any::Any; - use realstd::result::{Ok, Err}; - let a = box 8u as Box; - let b = box Test as Box; - - match a.move::() { - Ok(a) => { assert!(a == box 8u); } - Err(..) => fail!() - } - match b.move::() { - Ok(a) => { assert!(a == box Test); } - Err(..) => fail!() - } - - let a = box 8u as Box; - let b = box Test as Box; - - assert!(a.move::>().is_err()); - assert!(b.move::>().is_err()); - } - - #[test] - fn test_show() { - use realstd::to_str::ToStr; - let a = box 8u as Box<::realstd::any::Any>; - let b = box Test as Box<::realstd::any::Any>; - let a_str = a.to_str(); - let b_str = b.to_str(); - assert_eq!(a_str.as_slice(), "Box"); - assert_eq!(b_str.as_slice(), "Box"); - - let a = &8u as &Any; - let b = &Test as &Any; - let s = format!("{}", a); - assert_eq!(s.as_slice(), "&Any"); - let s = format!("{}", b); - assert_eq!(s.as_slice(), "&Any"); - } - - #[test] - fn any_fixed_vec() { - let test = [0u, ..8]; - let test = &test as &Any; - assert!(test.is::<[uint, ..8]>()); - assert!(!test.is::<[uint, ..10]>()); - } -} - -#[cfg(test)] -mod bench { - extern crate test; - - use any::{Any, AnyRefExt}; - use option::Some; - use self::test::Bencher; - - #[bench] - fn bench_as_ref(b: &mut Bencher) { - b.iter(|| { - let mut x = 0i; - let mut y = &mut x as &mut Any; - test::black_box(&mut y); - test::black_box(y.as_ref::() == Some(&0)); - }); - } -} diff --git a/src/libcore/atomics.rs b/src/libcore/atomics.rs index 13979bb648fda..971799acc7862 100644 --- a/src/libcore/atomics.rs +++ b/src/libcore/atomics.rs @@ -693,97 +693,3 @@ pub fn fence(order: Ordering) { } } } - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn bool_() { - let a = AtomicBool::new(false); - assert_eq!(a.compare_and_swap(false, true, SeqCst), false); - assert_eq!(a.compare_and_swap(false, true, SeqCst), true); - - a.store(false, SeqCst); - assert_eq!(a.compare_and_swap(false, true, SeqCst), false); - } - - #[test] - fn bool_and() { - let a = AtomicBool::new(true); - assert_eq!(a.fetch_and(false, SeqCst),true); - assert_eq!(a.load(SeqCst),false); - } - - #[test] - fn uint_and() { - let x = AtomicUint::new(0xf731); - assert_eq!(x.fetch_and(0x137f, SeqCst), 0xf731); - assert_eq!(x.load(SeqCst), 0xf731 & 0x137f); - } - - #[test] - fn uint_or() { - let x = AtomicUint::new(0xf731); - assert_eq!(x.fetch_or(0x137f, SeqCst), 0xf731); - assert_eq!(x.load(SeqCst), 0xf731 | 0x137f); - } - - #[test] - fn uint_xor() { - let x = AtomicUint::new(0xf731); - assert_eq!(x.fetch_xor(0x137f, SeqCst), 0xf731); - assert_eq!(x.load(SeqCst), 0xf731 ^ 0x137f); - } - - #[test] - fn int_and() { - let x = AtomicInt::new(0xf731); - assert_eq!(x.fetch_and(0x137f, SeqCst), 0xf731); - assert_eq!(x.load(SeqCst), 0xf731 & 0x137f); - } - - #[test] - fn int_or() { - let x = AtomicInt::new(0xf731); - assert_eq!(x.fetch_or(0x137f, SeqCst), 0xf731); - assert_eq!(x.load(SeqCst), 0xf731 | 0x137f); - } - - #[test] - fn int_xor() { - let x = AtomicInt::new(0xf731); - assert_eq!(x.fetch_xor(0x137f, SeqCst), 0xf731); - assert_eq!(x.load(SeqCst), 0xf731 ^ 0x137f); - } - - static mut S_BOOL : AtomicBool = INIT_ATOMIC_BOOL; - static mut S_INT : AtomicInt = INIT_ATOMIC_INT; - static mut S_UINT : AtomicUint = INIT_ATOMIC_UINT; - - #[test] - fn static_init() { - unsafe { - assert!(!S_BOOL.load(SeqCst)); - assert!(S_INT.load(SeqCst) == 0); - assert!(S_UINT.load(SeqCst) == 0); - } - } - - #[test] - fn different_sizes() { - unsafe { - let mut slot = 0u16; - assert_eq!(super::atomic_swap(&mut slot, 1, SeqCst), 0); - - let mut slot = 0u8; - assert_eq!(super::atomic_compare_and_swap(&mut slot, 1, 2, SeqCst), 0); - - let slot = 0u32; - assert_eq!(super::atomic_load(&slot, SeqCst), 0); - - let mut slot = 0u64; - super::atomic_store(&mut slot, 2, SeqCst); - } - } -} diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs index 8cd65c4f56466..355ee7c7a16f0 100644 --- a/src/libcore/cell.rs +++ b/src/libcore/cell.rs @@ -383,132 +383,3 @@ impl<'b, T> DerefMut for RefMut<'b, T> { unsafe { &mut *self._parent.value.get() } } } - -#[cfg(test)] -mod test { - use super::*; - use mem::drop; - - #[test] - fn smoketest_cell() { - let x = Cell::new(10i); - assert!(x == Cell::new(10)); - assert!(x.get() == 10); - x.set(20); - assert!(x == Cell::new(20)); - assert!(x.get() == 20); - - let y = Cell::new((30i, 40i)); - assert!(y == Cell::new((30, 40))); - assert!(y.get() == (30, 40)); - } - - #[test] - fn cell_has_sensible_show() { - use str::StrSlice; - use realstd::str::Str; - - let x = Cell::new("foo bar"); - assert!(format!("{}", x).as_slice().contains(x.get())); - - x.set("baz qux"); - assert!(format!("{}", x).as_slice().contains(x.get())); - } - - #[test] - fn ref_and_refmut_have_sensible_show() { - use str::StrSlice; - use realstd::str::Str; - - let refcell = RefCell::new("foo"); - - let refcell_refmut = refcell.borrow_mut(); - assert!(format!("{}", refcell_refmut).as_slice().contains("foo")); - drop(refcell_refmut); - - let refcell_ref = refcell.borrow(); - assert!(format!("{}", refcell_ref).as_slice().contains("foo")); - drop(refcell_ref); - } - - #[test] - fn double_imm_borrow() { - let x = RefCell::new(0i); - let _b1 = x.borrow(); - x.borrow(); - } - - #[test] - fn no_mut_then_imm_borrow() { - let x = RefCell::new(0i); - let _b1 = x.borrow_mut(); - assert!(x.try_borrow().is_none()); - } - - #[test] - fn no_imm_then_borrow_mut() { - let x = RefCell::new(0i); - let _b1 = x.borrow(); - assert!(x.try_borrow_mut().is_none()); - } - - #[test] - fn no_double_borrow_mut() { - let x = RefCell::new(0i); - let _b1 = x.borrow_mut(); - assert!(x.try_borrow_mut().is_none()); - } - - #[test] - fn imm_release_borrow_mut() { - let x = RefCell::new(0i); - { - let _b1 = x.borrow(); - } - x.borrow_mut(); - } - - #[test] - fn mut_release_borrow_mut() { - let x = RefCell::new(0i); - { - let _b1 = x.borrow_mut(); - } - x.borrow(); - } - - #[test] - fn double_borrow_single_release_no_borrow_mut() { - let x = RefCell::new(0i); - let _b1 = x.borrow(); - { - let _b2 = x.borrow(); - } - assert!(x.try_borrow_mut().is_none()); - } - - #[test] - #[should_fail] - fn discard_doesnt_unborrow() { - let x = RefCell::new(0i); - let _b = x.borrow(); - let _ = _b; - let _b = x.borrow_mut(); - } - - #[test] - #[allow(experimental)] - fn clone_ref_updates_flag() { - let x = RefCell::new(0i); - { - let b1 = x.borrow(); - assert!(x.try_borrow_mut().is_none()); - { - let _b2 = clone_ref(&b1); - assert!(x.try_borrow_mut().is_none()); - } - assert!(x.try_borrow_mut().is_none()); - } - assert!(x.try_borrow_mut().is_some()); - } -} diff --git a/src/libcore/char.rs b/src/libcore/char.rs index c188ec75ddd09..da67772d0f122 100644 --- a/src/libcore/char.rs +++ b/src/libcore/char.rs @@ -602,205 +602,3 @@ impl Char for char { } -#[cfg(test)] -mod test { - use super::{escape_unicode, escape_default}; - - use char::Char; - use slice::ImmutableVector; - use option::{Some, None}; - use realstd::string::String; - use realstd::str::Str; - - #[test] - fn test_is_lowercase() { - assert!('a'.is_lowercase()); - assert!('ö'.is_lowercase()); - assert!('ß'.is_lowercase()); - assert!(!'Ü'.is_lowercase()); - assert!(!'P'.is_lowercase()); - } - - #[test] - fn test_is_uppercase() { - assert!(!'h'.is_uppercase()); - assert!(!'ä'.is_uppercase()); - assert!(!'ß'.is_uppercase()); - assert!('Ö'.is_uppercase()); - assert!('T'.is_uppercase()); - } - - #[test] - fn test_is_whitespace() { - assert!(' '.is_whitespace()); - assert!('\u2007'.is_whitespace()); - assert!('\t'.is_whitespace()); - assert!('\n'.is_whitespace()); - assert!(!'a'.is_whitespace()); - assert!(!'_'.is_whitespace()); - assert!(!'\u0000'.is_whitespace()); - } - - #[test] - fn test_to_digit() { - assert_eq!('0'.to_digit(10u), Some(0u)); - assert_eq!('1'.to_digit(2u), Some(1u)); - assert_eq!('2'.to_digit(3u), Some(2u)); - assert_eq!('9'.to_digit(10u), Some(9u)); - assert_eq!('a'.to_digit(16u), Some(10u)); - assert_eq!('A'.to_digit(16u), Some(10u)); - assert_eq!('b'.to_digit(16u), Some(11u)); - assert_eq!('B'.to_digit(16u), Some(11u)); - assert_eq!('z'.to_digit(36u), Some(35u)); - assert_eq!('Z'.to_digit(36u), Some(35u)); - assert_eq!(' '.to_digit(10u), None); - assert_eq!('$'.to_digit(36u), None); - } - - #[test] - fn test_to_lowercase() { - assert_eq!('A'.to_lowercase(), 'a'); - assert_eq!('Ö'.to_lowercase(), 'ö'); - assert_eq!('ß'.to_lowercase(), 'ß'); - assert_eq!('Ü'.to_lowercase(), 'ü'); - assert_eq!('💩'.to_lowercase(), '💩'); - assert_eq!('Σ'.to_lowercase(), 'σ'); - assert_eq!('Τ'.to_lowercase(), 'τ'); - assert_eq!('Ι'.to_lowercase(), 'ι'); - assert_eq!('Γ'.to_lowercase(), 'γ'); - assert_eq!('Μ'.to_lowercase(), 'μ'); - assert_eq!('Α'.to_lowercase(), 'α'); - assert_eq!('Σ'.to_lowercase(), 'σ'); - } - - #[test] - fn test_to_uppercase() { - assert_eq!('a'.to_uppercase(), 'A'); - assert_eq!('ö'.to_uppercase(), 'Ö'); - assert_eq!('ß'.to_uppercase(), 'ß'); // not ẞ: Latin capital letter sharp s - assert_eq!('ü'.to_uppercase(), 'Ü'); - assert_eq!('💩'.to_uppercase(), '💩'); - - assert_eq!('σ'.to_uppercase(), 'Σ'); - assert_eq!('τ'.to_uppercase(), 'Τ'); - assert_eq!('ι'.to_uppercase(), 'Ι'); - assert_eq!('γ'.to_uppercase(), 'Γ'); - assert_eq!('μ'.to_uppercase(), 'Μ'); - assert_eq!('α'.to_uppercase(), 'Α'); - assert_eq!('ς'.to_uppercase(), 'Σ'); - } - - #[test] - fn test_is_control() { - assert!('\u0000'.is_control()); - assert!('\u0003'.is_control()); - assert!('\u0006'.is_control()); - assert!('\u0009'.is_control()); - assert!('\u007f'.is_control()); - assert!('\u0092'.is_control()); - assert!(!'\u0020'.is_control()); - assert!(!'\u0055'.is_control()); - assert!(!'\u0068'.is_control()); - } - - #[test] - fn test_is_digit() { - assert!('2'.is_digit()); - assert!('7'.is_digit()); - assert!(!'c'.is_digit()); - assert!(!'i'.is_digit()); - assert!(!'z'.is_digit()); - assert!(!'Q'.is_digit()); - } - - #[test] - fn test_escape_default() { - fn string(c: char) -> String { - let mut result = String::new(); - escape_default(c, |c| { result.push_char(c); }); - return result; - } - let s = string('\n'); - assert_eq!(s.as_slice(), "\\n"); - let s = string('\r'); - assert_eq!(s.as_slice(), "\\r"); - let s = string('\''); - assert_eq!(s.as_slice(), "\\'"); - let s = string('"'); - assert_eq!(s.as_slice(), "\\\""); - let s = string(' '); - assert_eq!(s.as_slice(), " "); - let s = string('a'); - assert_eq!(s.as_slice(), "a"); - let s = string('~'); - assert_eq!(s.as_slice(), "~"); - let s = string('\x00'); - assert_eq!(s.as_slice(), "\\x00"); - let s = string('\x1f'); - assert_eq!(s.as_slice(), "\\x1f"); - let s = string('\x7f'); - assert_eq!(s.as_slice(), "\\x7f"); - let s = string('\xff'); - assert_eq!(s.as_slice(), "\\xff"); - let s = string('\u011b'); - assert_eq!(s.as_slice(), "\\u011b"); - let s = string('\U0001d4b6'); - assert_eq!(s.as_slice(), "\\U0001d4b6"); - } - - #[test] - fn test_escape_unicode() { - fn string(c: char) -> String { - let mut result = String::new(); - escape_unicode(c, |c| { result.push_char(c); }); - return result; - } - let s = string('\x00'); - assert_eq!(s.as_slice(), "\\x00"); - let s = string('\n'); - assert_eq!(s.as_slice(), "\\x0a"); - let s = string(' '); - assert_eq!(s.as_slice(), "\\x20"); - let s = string('a'); - assert_eq!(s.as_slice(), "\\x61"); - let s = string('\u011b'); - assert_eq!(s.as_slice(), "\\u011b"); - let s = string('\U0001d4b6'); - assert_eq!(s.as_slice(), "\\U0001d4b6"); - } - - #[test] - fn test_to_str() { - use realstd::to_str::ToStr; - let s = 't'.to_str(); - assert_eq!(s.as_slice(), "t"); - } - - #[test] - fn test_encode_utf8() { - fn check(input: char, expect: &[u8]) { - let mut buf = [0u8, ..4]; - let n = input.encode_utf8(buf /* as mut slice! */); - assert_eq!(buf.slice_to(n), expect); - } - - check('x', [0x78]); - check('\u00e9', [0xc3, 0xa9]); - check('\ua66e', [0xea, 0x99, 0xae]); - check('\U0001f4a9', [0xf0, 0x9f, 0x92, 0xa9]); - } - - #[test] - fn test_encode_utf16() { - fn check(input: char, expect: &[u16]) { - let mut buf = [0u16, ..2]; - let n = input.encode_utf16(buf /* as mut slice! */); - assert_eq!(buf.slice_to(n), expect); - } - - check('x', [0x0078]); - check('\u00e9', [0x00e9]); - check('\ua66e', [0xa66e]); - check('\U0001f4a9', [0xd83d, 0xdca9]); - } -} diff --git a/src/libcore/clone.rs b/src/libcore/clone.rs index 04f01db314797..247f63115a783 100644 --- a/src/libcore/clone.rs +++ b/src/libcore/clone.rs @@ -110,63 +110,3 @@ extern_fn_clone!(A, B, C, D, E, F) extern_fn_clone!(A, B, C, D, E, F, G) extern_fn_clone!(A, B, C, D, E, F, G, H) -#[cfg(test)] -mod test { - use prelude::*; - use realstd::owned::Box; - use realstd::gc::{Gc, GC}; - - fn realclone(t: &T) -> T { - use realstd::clone::Clone; - t.clone() - } - - fn realclone_from(t1: &mut T, t2: &T) { - use realstd::clone::Clone; - t1.clone_from(t2) - } - - #[test] - fn test_owned_clone() { - let a = box 5i; - let b: Box = realclone(&a); - assert!(a == b); - } - - #[test] - fn test_managed_clone() { - let a = box(GC) 5i; - let b: Gc = realclone(&a); - assert!(a == b); - } - - #[test] - fn test_borrowed_clone() { - let x = 5i; - let y: &int = &x; - let z: &int = (&y).clone(); - assert_eq!(*z, 5); - } - - #[test] - fn test_clone_from() { - let a = box 5i; - let mut b = box 10i; - realclone_from(&mut b, &a); - assert_eq!(*b, 5); - } - - #[test] - fn test_extern_fn_clone() { - trait Empty {} - impl Empty for int {} - - fn test_fn_a() -> f64 { 1.0 } - fn test_fn_b(x: T) -> T { x } - fn test_fn_c(_: int, _: f64, _: int, _: int, _: int) {} - - let _ = test_fn_a.clone(); - let _ = test_fn_b::.clone(); - let _ = test_fn_c.clone(); - } -} diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index 197997507a6c6..a29aba6df980e 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -192,7 +192,6 @@ pub fn max(v1: T, v2: T) -> T { } // Implementation of PartialEq, Eq, PartialOrd and Ord for primitive types -#[cfg(not(test))] mod impls { use cmp::{PartialOrd, Ord, PartialEq, Eq, Ordering, Less, Greater, Equal}; @@ -327,66 +326,3 @@ mod impls { } impl<'a, T: Eq> Eq for &'a mut T {} } - -#[cfg(test)] -mod test { - use super::lexical_ordering; - - #[test] - fn test_int_totalord() { - assert_eq!(5u.cmp(&10), Less); - assert_eq!(10u.cmp(&5), Greater); - assert_eq!(5u.cmp(&5), Equal); - assert_eq!((-5u).cmp(&12), Less); - assert_eq!(12u.cmp(-5), Greater); - } - - #[test] - fn test_mut_int_totalord() { - assert_eq!((&mut 5u).cmp(&10), Less); - assert_eq!((&mut 10u).cmp(&5), Greater); - assert_eq!((&mut 5u).cmp(&5), Equal); - assert_eq!((&mut -5u).cmp(&12), Less); - assert_eq!((&mut 12u).cmp(-5), Greater); - } - - #[test] - fn test_ordering_order() { - assert!(Less < Equal); - assert_eq!(Greater.cmp(&Less), Greater); - } - - #[test] - fn test_lexical_ordering() { - fn t(o1: Ordering, o2: Ordering, e: Ordering) { - assert_eq!(lexical_ordering(o1, o2), e); - } - - let xs = [Less, Equal, Greater]; - for &o in xs.iter() { - t(Less, o, Less); - t(Equal, o, o); - t(Greater, o, Greater); - } - } - - #[test] - fn test_user_defined_eq() { - // Our type. - struct SketchyNum { - num : int - } - - // Our implementation of `PartialEq` to support `==` and `!=`. - impl PartialEq for SketchyNum { - // Our custom eq allows numbers which are near each other to be equal! :D - fn eq(&self, other: &SketchyNum) -> bool { - (self.num - other.num).abs() < 5 - } - } - - // Now these binary operators will work when applied! - assert!(SketchyNum {num: 37} == SketchyNum {num: 34}); - assert!(SketchyNum {num: 25} != SketchyNum {num: 57}); - } -} diff --git a/src/libcore/failure.rs b/src/libcore/failure.rs index c64bd6201faf3..4bc39db8ecf09 100644 --- a/src/libcore/failure.rs +++ b/src/libcore/failure.rs @@ -31,11 +31,10 @@ #![allow(dead_code, missing_doc)] use fmt; -#[cfg(not(test))] use intrinsics; +use intrinsics; #[cold] #[inline(never)] // this is the slow path, always #[lang="fail_"] -#[cfg(not(test))] fn fail_(expr: &'static str, file: &'static str, line: uint) -> ! { format_args!(|args| -> () { begin_unwind(args, file, line); @@ -46,7 +45,6 @@ fn fail_(expr: &'static str, file: &'static str, line: uint) -> ! { #[cold] #[lang="fail_bounds_check"] -#[cfg(not(test))] fn fail_bounds_check(file: &'static str, line: uint, index: uint, len: uint) -> ! { format_args!(|args| -> () { diff --git a/src/libcore/finally.rs b/src/libcore/finally.rs index ab151460537af..514b3f90df7c0 100644 --- a/src/libcore/finally.rs +++ b/src/libcore/finally.rs @@ -115,55 +115,3 @@ impl<'a,A> Drop for Finallyalizer<'a,A> { } } -#[cfg(test)] -mod test { - use super::{try_finally, Finally}; - use realstd::task::failing; - - #[test] - fn test_success() { - let mut i = 0i; - try_finally( - &mut i, (), - |i, ()| { - *i = 10; - }, - |i| { - assert!(!failing()); - assert_eq!(*i, 10); - *i = 20; - }); - assert_eq!(i, 20); - } - - #[test] - #[should_fail] - fn test_fail() { - let mut i = 0i; - try_finally( - &mut i, (), - |i, ()| { - *i = 10; - fail!(); - }, - |i| { - assert!(failing()); - assert_eq!(*i, 10); - }) - } - - #[test] - fn test_retval() { - let mut closure: || -> int = || 10; - let i = closure.finally(|| { }); - assert_eq!(i, 10); - } - - #[test] - fn test_compact() { - fn do_some_fallible_work() {} - fn but_always_run_this_function() { } - let mut f = do_some_fallible_work; - f.finally(but_always_run_this_function); - } -} diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index 1096758a22d96..ff7d7827fbb8e 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -496,31 +496,6 @@ pub fn argument<'a, T>(f: extern "Rust" fn(&T, &mut Formatter) -> Result, } } -#[cfg(test)] -pub fn format(args: &Arguments) -> ::realstd::string::String { - use str; - use realstd::io::MemWriter; - - fn mywrite(t: &mut T, b: &[u8]) { - use realstd::io::Writer; - let _ = t.write(b); - } - - impl FormatWriter for MemWriter { - fn write(&mut self, bytes: &[u8]) -> Result { - mywrite(self, bytes); - Ok(()) - } - } - - let mut i = MemWriter::new(); - let _ = write(&mut i, args); - - let mut result = ::realstd::string::String::new(); - result.push_str(str::from_utf8(i.get_ref()).unwrap()); - result -} - /// When the compiler determines that the type of an argument *must* be a string /// (such as for select), then it invokes this method. #[doc(hidden)] #[inline] diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs index d3edfd42febfd..d52791f6b0ea2 100644 --- a/src/libcore/fmt/num.rs +++ b/src/libcore/fmt/num.rs @@ -188,283 +188,3 @@ integer!(i8, u8) integer!(i16, u16) integer!(i32, u32) integer!(i64, u64) - -#[cfg(test)] -mod tests { - use fmt::radix; - use super::{Binary, Octal, Decimal, LowerHex, UpperHex}; - use super::{GenericRadix, Radix}; - use realstd::str::Str; - - #[test] - fn test_radix_base() { - assert_eq!(Binary.base(), 2); - assert_eq!(Octal.base(), 8); - assert_eq!(Decimal.base(), 10); - assert_eq!(LowerHex.base(), 16); - assert_eq!(UpperHex.base(), 16); - assert_eq!(Radix { base: 36 }.base(), 36); - } - - #[test] - fn test_radix_prefix() { - assert_eq!(Binary.prefix(), "0b"); - assert_eq!(Octal.prefix(), "0o"); - assert_eq!(Decimal.prefix(), ""); - assert_eq!(LowerHex.prefix(), "0x"); - assert_eq!(UpperHex.prefix(), "0x"); - assert_eq!(Radix { base: 36 }.prefix(), ""); - } - - #[test] - fn test_radix_digit() { - assert_eq!(Binary.digit(0), '0' as u8); - assert_eq!(Binary.digit(2), '2' as u8); - assert_eq!(Octal.digit(0), '0' as u8); - assert_eq!(Octal.digit(7), '7' as u8); - assert_eq!(Decimal.digit(0), '0' as u8); - assert_eq!(Decimal.digit(9), '9' as u8); - assert_eq!(LowerHex.digit(0), '0' as u8); - assert_eq!(LowerHex.digit(10), 'a' as u8); - assert_eq!(LowerHex.digit(15), 'f' as u8); - assert_eq!(UpperHex.digit(0), '0' as u8); - assert_eq!(UpperHex.digit(10), 'A' as u8); - assert_eq!(UpperHex.digit(15), 'F' as u8); - assert_eq!(Radix { base: 36 }.digit(0), '0' as u8); - assert_eq!(Radix { base: 36 }.digit(15), 'f' as u8); - assert_eq!(Radix { base: 36 }.digit(35), 'z' as u8); - } - - #[test] - #[should_fail] - fn test_hex_radix_digit_overflow() { - let _ = LowerHex.digit(16); - } - - #[test] - fn test_format_int() { - // Formatting integers should select the right implementation based off - // the type of the argument. Also, hex/octal/binary should be defined - // for integers, but they shouldn't emit the negative sign. - assert!(format!("{}", 1i).as_slice() == "1"); - assert!(format!("{}", 1i8).as_slice() == "1"); - assert!(format!("{}", 1i16).as_slice() == "1"); - assert!(format!("{}", 1i32).as_slice() == "1"); - assert!(format!("{}", 1i64).as_slice() == "1"); - assert!(format!("{:d}", -1i).as_slice() == "-1"); - assert!(format!("{:d}", -1i8).as_slice() == "-1"); - assert!(format!("{:d}", -1i16).as_slice() == "-1"); - assert!(format!("{:d}", -1i32).as_slice() == "-1"); - assert!(format!("{:d}", -1i64).as_slice() == "-1"); - assert!(format!("{:t}", 1i).as_slice() == "1"); - assert!(format!("{:t}", 1i8).as_slice() == "1"); - assert!(format!("{:t}", 1i16).as_slice() == "1"); - assert!(format!("{:t}", 1i32).as_slice() == "1"); - assert!(format!("{:t}", 1i64).as_slice() == "1"); - assert!(format!("{:x}", 1i).as_slice() == "1"); - assert!(format!("{:x}", 1i8).as_slice() == "1"); - assert!(format!("{:x}", 1i16).as_slice() == "1"); - assert!(format!("{:x}", 1i32).as_slice() == "1"); - assert!(format!("{:x}", 1i64).as_slice() == "1"); - assert!(format!("{:X}", 1i).as_slice() == "1"); - assert!(format!("{:X}", 1i8).as_slice() == "1"); - assert!(format!("{:X}", 1i16).as_slice() == "1"); - assert!(format!("{:X}", 1i32).as_slice() == "1"); - assert!(format!("{:X}", 1i64).as_slice() == "1"); - assert!(format!("{:o}", 1i).as_slice() == "1"); - assert!(format!("{:o}", 1i8).as_slice() == "1"); - assert!(format!("{:o}", 1i16).as_slice() == "1"); - assert!(format!("{:o}", 1i32).as_slice() == "1"); - assert!(format!("{:o}", 1i64).as_slice() == "1"); - - assert!(format!("{}", 1u).as_slice() == "1"); - assert!(format!("{}", 1u8).as_slice() == "1"); - assert!(format!("{}", 1u16).as_slice() == "1"); - assert!(format!("{}", 1u32).as_slice() == "1"); - assert!(format!("{}", 1u64).as_slice() == "1"); - assert!(format!("{:u}", 1u).as_slice() == "1"); - assert!(format!("{:u}", 1u8).as_slice() == "1"); - assert!(format!("{:u}", 1u16).as_slice() == "1"); - assert!(format!("{:u}", 1u32).as_slice() == "1"); - assert!(format!("{:u}", 1u64).as_slice() == "1"); - assert!(format!("{:t}", 1u).as_slice() == "1"); - assert!(format!("{:t}", 1u8).as_slice() == "1"); - assert!(format!("{:t}", 1u16).as_slice() == "1"); - assert!(format!("{:t}", 1u32).as_slice() == "1"); - assert!(format!("{:t}", 1u64).as_slice() == "1"); - assert!(format!("{:x}", 1u).as_slice() == "1"); - assert!(format!("{:x}", 1u8).as_slice() == "1"); - assert!(format!("{:x}", 1u16).as_slice() == "1"); - assert!(format!("{:x}", 1u32).as_slice() == "1"); - assert!(format!("{:x}", 1u64).as_slice() == "1"); - assert!(format!("{:X}", 1u).as_slice() == "1"); - assert!(format!("{:X}", 1u8).as_slice() == "1"); - assert!(format!("{:X}", 1u16).as_slice() == "1"); - assert!(format!("{:X}", 1u32).as_slice() == "1"); - assert!(format!("{:X}", 1u64).as_slice() == "1"); - assert!(format!("{:o}", 1u).as_slice() == "1"); - assert!(format!("{:o}", 1u8).as_slice() == "1"); - assert!(format!("{:o}", 1u16).as_slice() == "1"); - assert!(format!("{:o}", 1u32).as_slice() == "1"); - assert!(format!("{:o}", 1u64).as_slice() == "1"); - - // Test a larger number - assert!(format!("{:t}", 55i).as_slice() == "110111"); - assert!(format!("{:o}", 55i).as_slice() == "67"); - assert!(format!("{:d}", 55i).as_slice() == "55"); - assert!(format!("{:x}", 55i).as_slice() == "37"); - assert!(format!("{:X}", 55i).as_slice() == "37"); - } - - #[test] - fn test_format_int_zero() { - assert!(format!("{}", 0i).as_slice() == "0"); - assert!(format!("{:d}", 0i).as_slice() == "0"); - assert!(format!("{:t}", 0i).as_slice() == "0"); - assert!(format!("{:o}", 0i).as_slice() == "0"); - assert!(format!("{:x}", 0i).as_slice() == "0"); - assert!(format!("{:X}", 0i).as_slice() == "0"); - - assert!(format!("{}", 0u).as_slice() == "0"); - assert!(format!("{:u}", 0u).as_slice() == "0"); - assert!(format!("{:t}", 0u).as_slice() == "0"); - assert!(format!("{:o}", 0u).as_slice() == "0"); - assert!(format!("{:x}", 0u).as_slice() == "0"); - assert!(format!("{:X}", 0u).as_slice() == "0"); - } - - #[test] - fn test_format_int_flags() { - assert!(format!("{:3d}", 1i).as_slice() == " 1"); - assert!(format!("{:>3d}", 1i).as_slice() == " 1"); - assert!(format!("{:>+3d}", 1i).as_slice() == " +1"); - assert!(format!("{:<3d}", 1i).as_slice() == "1 "); - assert!(format!("{:#d}", 1i).as_slice() == "1"); - assert!(format!("{:#x}", 10i).as_slice() == "0xa"); - assert!(format!("{:#X}", 10i).as_slice() == "0xA"); - assert!(format!("{:#5x}", 10i).as_slice() == " 0xa"); - assert!(format!("{:#o}", 10i).as_slice() == "0o12"); - assert!(format!("{:08x}", 10i).as_slice() == "0000000a"); - assert!(format!("{:8x}", 10i).as_slice() == " a"); - assert!(format!("{:<8x}", 10i).as_slice() == "a "); - assert!(format!("{:>8x}", 10i).as_slice() == " a"); - assert!(format!("{:#08x}", 10i).as_slice() == "0x00000a"); - assert!(format!("{:08d}", -10i).as_slice() == "-0000010"); - assert!(format!("{:x}", -1u8).as_slice() == "ff"); - assert!(format!("{:X}", -1u8).as_slice() == "FF"); - assert!(format!("{:t}", -1u8).as_slice() == "11111111"); - assert!(format!("{:o}", -1u8).as_slice() == "377"); - assert!(format!("{:#x}", -1u8).as_slice() == "0xff"); - assert!(format!("{:#X}", -1u8).as_slice() == "0xFF"); - assert!(format!("{:#t}", -1u8).as_slice() == "0b11111111"); - assert!(format!("{:#o}", -1u8).as_slice() == "0o377"); - } - - #[test] - fn test_format_int_sign_padding() { - assert!(format!("{:+5d}", 1i).as_slice() == " +1"); - assert!(format!("{:+5d}", -1i).as_slice() == " -1"); - assert!(format!("{:05d}", 1i).as_slice() == "00001"); - assert!(format!("{:05d}", -1i).as_slice() == "-0001"); - assert!(format!("{:+05d}", 1i).as_slice() == "+0001"); - assert!(format!("{:+05d}", -1i).as_slice() == "-0001"); - } - - #[test] - fn test_format_int_twos_complement() { - use {i8, i16, i32, i64}; - assert!(format!("{}", i8::MIN).as_slice() == "-128"); - assert!(format!("{}", i16::MIN).as_slice() == "-32768"); - assert!(format!("{}", i32::MIN).as_slice() == "-2147483648"); - assert!(format!("{}", i64::MIN).as_slice() == "-9223372036854775808"); - } - - #[test] - fn test_format_radix() { - assert!(format!("{:04}", radix(3i, 2)).as_slice() == "0011"); - assert!(format!("{}", radix(55i, 36)).as_slice() == "1j"); - } - - #[test] - #[should_fail] - fn test_radix_base_too_large() { - let _ = radix(55i, 37); - } -} - -#[cfg(test)] -mod bench { - extern crate test; - - mod uint { - use super::test::Bencher; - use fmt::radix; - use realstd::rand::{weak_rng, Rng}; - - #[bench] - fn format_bin(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:t}", rng.gen::()); }) - } - - #[bench] - fn format_oct(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:o}", rng.gen::()); }) - } - - #[bench] - fn format_dec(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:u}", rng.gen::()); }) - } - - #[bench] - fn format_hex(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:x}", rng.gen::()); }) - } - - #[bench] - fn format_base_36(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{}", radix(rng.gen::(), 36)); }) - } - } - - mod int { - use super::test::Bencher; - use fmt::radix; - use realstd::rand::{weak_rng, Rng}; - - #[bench] - fn format_bin(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:t}", rng.gen::()); }) - } - - #[bench] - fn format_oct(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:o}", rng.gen::()); }) - } - - #[bench] - fn format_dec(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:d}", rng.gen::()); }) - } - - #[bench] - fn format_hex(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{:x}", rng.gen::()); }) - } - - #[bench] - fn format_base_36(b: &mut Bencher) { - let mut rng = weak_rng(); - b.iter(|| { format!("{}", radix(rng.gen::(), 36)); }) - } - } -} diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs index fd06ae95f1b7f..161dd7cef7e13 100644 --- a/src/libcore/intrinsics.rs +++ b/src/libcore/intrinsics.rs @@ -44,14 +44,9 @@ A quick refresher on memory ordering: #![experimental] #![allow(missing_doc)] -// This is needed to prevent duplicate lang item definitions. -#[cfg(test)] -pub use realcore::intrinsics::{TyDesc, Opaque, TyVisitor, TypeId}; - pub type GlueFn = extern "Rust" fn(*const i8); #[lang="ty_desc"] -#[cfg(not(test))] pub struct TyDesc { // sizeof(T) pub size: uint, @@ -70,13 +65,11 @@ pub struct TyDesc { } #[lang="opaque"] -#[cfg(not(test))] pub enum Opaque { } pub type Disr = u64; #[lang="ty_visitor"] -#[cfg(not(test))] pub trait TyVisitor { fn visit_bot(&mut self) -> bool; fn visit_nil(&mut self) -> bool; @@ -564,12 +557,10 @@ extern "rust-intrinsic" { #[lang="type_id"] // This needs to be kept in lockstep with the code in trans/intrinsic.rs and // middle/lang_items.rs #[deriving(PartialEq, Eq, Show)] -#[cfg(not(test))] pub struct TypeId { t: u64, } -#[cfg(not(test))] impl TypeId { /// Returns the `TypeId` of the type this generic function has been instantiated with pub fn of() -> TypeId { diff --git a/src/libcore/iter.rs b/src/libcore/iter.rs index c041ef5706ba2..1445376d7db21 100644 --- a/src/libcore/iter.rs +++ b/src/libcore/iter.rs @@ -2281,868 +2281,5 @@ pub mod order { } } } - - #[test] - fn test_lt() { - use slice::ImmutableVector; - - let empty: [int, ..0] = []; - let xs = [1i,2,3]; - let ys = [1i,2,0]; - - assert!(!lt(xs.iter(), ys.iter())); - assert!(!le(xs.iter(), ys.iter())); - assert!( gt(xs.iter(), ys.iter())); - assert!( ge(xs.iter(), ys.iter())); - - assert!( lt(ys.iter(), xs.iter())); - assert!( le(ys.iter(), xs.iter())); - assert!(!gt(ys.iter(), xs.iter())); - assert!(!ge(ys.iter(), xs.iter())); - - assert!( lt(empty.iter(), xs.iter())); - assert!( le(empty.iter(), xs.iter())); - assert!(!gt(empty.iter(), xs.iter())); - assert!(!ge(empty.iter(), xs.iter())); - - // Sequence with NaN - let u = [1.0f64, 2.0]; - let v = [0.0f64/0.0, 3.0]; - - assert!(!lt(u.iter(), v.iter())); - assert!(!le(u.iter(), v.iter())); - assert!(!gt(u.iter(), v.iter())); - assert!(!ge(u.iter(), v.iter())); - - let a = [0.0f64/0.0]; - let b = [1.0f64]; - let c = [2.0f64]; - - assert!(lt(a.iter(), b.iter()) == (a[0] < b[0])); - assert!(le(a.iter(), b.iter()) == (a[0] <= b[0])); - assert!(gt(a.iter(), b.iter()) == (a[0] > b[0])); - assert!(ge(a.iter(), b.iter()) == (a[0] >= b[0])); - - assert!(lt(c.iter(), b.iter()) == (c[0] < b[0])); - assert!(le(c.iter(), b.iter()) == (c[0] <= b[0])); - assert!(gt(c.iter(), b.iter()) == (c[0] > b[0])); - assert!(ge(c.iter(), b.iter()) == (c[0] >= b[0])); - } - - #[test] - fn test_multi_iter() { - use slice::ImmutableVector; - use iter::DoubleEndedIterator; - let xs = [1i,2,3,4]; - let ys = [4i,3,2,1]; - assert!(eq(xs.iter(), ys.iter().rev())); - assert!(lt(xs.iter(), xs.iter().skip(2))); - } -} - -#[cfg(test)] -mod tests { - use prelude::*; - use iter::*; - use num; - use realstd::vec::Vec; - use realstd::slice::Vector; - use realstd::gc::GC; - - use cmp; - use realstd::owned::Box; - use uint; - - impl FromIterator for Vec { - fn from_iter>(mut iterator: I) -> Vec { - let mut v = Vec::new(); - for e in iterator { - v.push(e); - } - return v; - } - } - - impl<'a, T> Iterator<&'a T> for ::realcore::slice::Items<'a, T> { - fn next(&mut self) -> Option<&'a T> { - use RealSome = realcore::option::Some; - use RealNone = realcore::option::None; - fn mynext>(i: &mut I) - -> ::realcore::option::Option - { - use realcore::iter::Iterator; - i.next() - } - match mynext(self) { - RealSome(t) => Some(t), - RealNone => None, - } - } - } - - #[test] - fn test_counter_from_iter() { - let it = count(0i, 5).take(10); - let xs: Vec = FromIterator::from_iter(it); - assert!(xs == vec![0, 5, 10, 15, 20, 25, 30, 35, 40, 45]); - } - - #[test] - fn test_iterator_chain() { - let xs = [0u, 1, 2, 3, 4, 5]; - let ys = [30u, 40, 50, 60]; - let expected = [0, 1, 2, 3, 4, 5, 30, 40, 50, 60]; - let mut it = xs.iter().chain(ys.iter()); - let mut i = 0; - for &x in it { - assert_eq!(x, expected[i]); - i += 1; - } - assert_eq!(i, expected.len()); - - let ys = count(30u, 10).take(4); - let mut it = xs.iter().map(|&x| x).chain(ys); - let mut i = 0; - for x in it { - assert_eq!(x, expected[i]); - i += 1; - } - assert_eq!(i, expected.len()); - } - - #[test] - fn test_filter_map() { - let mut it = count(0u, 1u).take(10) - .filter_map(|x| if x % 2 == 0 { Some(x*x) } else { None }); - assert!(it.collect::>() == vec![0*0, 2*2, 4*4, 6*6, 8*8]); - } - - #[test] - fn test_iterator_enumerate() { - let xs = [0u, 1, 2, 3, 4, 5]; - let mut it = xs.iter().enumerate(); - for (i, &x) in it { - assert_eq!(i, x); - } - } - - #[test] - fn test_iterator_peekable() { - let xs = vec![0u, 1, 2, 3, 4, 5]; - let mut it = xs.iter().map(|&x|x).peekable(); - assert_eq!(it.peek().unwrap(), &0); - assert_eq!(it.next().unwrap(), 0); - assert_eq!(it.next().unwrap(), 1); - assert_eq!(it.next().unwrap(), 2); - assert_eq!(it.peek().unwrap(), &3); - assert_eq!(it.peek().unwrap(), &3); - assert_eq!(it.next().unwrap(), 3); - assert_eq!(it.next().unwrap(), 4); - assert_eq!(it.peek().unwrap(), &5); - assert_eq!(it.next().unwrap(), 5); - assert!(it.peek().is_none()); - assert!(it.next().is_none()); - } - - #[test] - fn test_iterator_take_while() { - let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19]; - let ys = [0u, 1, 2, 3, 5, 13]; - let mut it = xs.iter().take_while(|&x| *x < 15u); - let mut i = 0; - for &x in it { - assert_eq!(x, ys[i]); - i += 1; - } - assert_eq!(i, ys.len()); - } - - #[test] - fn test_iterator_skip_while() { - let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19]; - let ys = [15, 16, 17, 19]; - let mut it = xs.iter().skip_while(|&x| *x < 15u); - let mut i = 0; - for &x in it { - assert_eq!(x, ys[i]); - i += 1; - } - assert_eq!(i, ys.len()); - } - - #[test] - fn test_iterator_skip() { - let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19, 20, 30]; - let ys = [13, 15, 16, 17, 19, 20, 30]; - let mut it = xs.iter().skip(5); - let mut i = 0; - for &x in it { - assert_eq!(x, ys[i]); - i += 1; - } - assert_eq!(i, ys.len()); - } - - #[test] - fn test_iterator_take() { - let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19]; - let ys = [0u, 1, 2, 3, 5]; - let mut it = xs.iter().take(5); - let mut i = 0; - for &x in it { - assert_eq!(x, ys[i]); - i += 1; - } - assert_eq!(i, ys.len()); - } - - #[test] - fn test_iterator_scan() { - // test the type inference - fn add(old: &mut int, new: &uint) -> Option { - *old += *new as int; - Some(*old as f64) - } - let xs = [0u, 1, 2, 3, 4]; - let ys = [0f64, 1.0, 3.0, 6.0, 10.0]; - - let mut it = xs.iter().scan(0, add); - let mut i = 0; - for x in it { - assert_eq!(x, ys[i]); - i += 1; - } - assert_eq!(i, ys.len()); - } - - #[test] - fn test_iterator_flat_map() { - let xs = [0u, 3, 6]; - let ys = [0u, 1, 2, 3, 4, 5, 6, 7, 8]; - let mut it = xs.iter().flat_map(|&x| count(x, 1).take(3)); - let mut i = 0; - for x in it { - assert_eq!(x, ys[i]); - i += 1; - } - assert_eq!(i, ys.len()); - } - - #[test] - fn test_inspect() { - let xs = [1u, 2, 3, 4]; - let mut n = 0; - - let ys = xs.iter() - .map(|&x| x) - .inspect(|_| n += 1) - .collect::>(); - - assert_eq!(n, xs.len()); - assert_eq!(xs.as_slice(), ys.as_slice()); - } - - #[test] - fn test_unfoldr() { - fn count(st: &mut uint) -> Option { - if *st < 10 { - let ret = Some(*st); - *st += 1; - ret - } else { - None - } - } - - let mut it = Unfold::new(0, count); - let mut i = 0; - for counted in it { - assert_eq!(counted, i); - i += 1; - } - assert_eq!(i, 10); - } - - #[test] - fn test_cycle() { - let cycle_len = 3; - let it = count(0u, 1).take(cycle_len).cycle(); - assert_eq!(it.size_hint(), (uint::MAX, None)); - for (i, x) in it.take(100).enumerate() { - assert_eq!(i % cycle_len, x); - } - - let mut it = count(0u, 1).take(0).cycle(); - assert_eq!(it.size_hint(), (0, Some(0))); - assert_eq!(it.next(), None); - } - - #[test] - fn test_iterator_nth() { - let v = &[0i, 1, 2, 3, 4]; - for i in range(0u, v.len()) { - assert_eq!(v.iter().nth(i).unwrap(), &v[i]); - } - } - - #[test] - fn test_iterator_last() { - let v = &[0i, 1, 2, 3, 4]; - assert_eq!(v.iter().last().unwrap(), &4); - assert_eq!(v.slice(0, 1).iter().last().unwrap(), &0); - } - - #[test] - fn test_iterator_len() { - let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.slice(0, 4).iter().count(), 4); - assert_eq!(v.slice(0, 10).iter().count(), 10); - assert_eq!(v.slice(0, 0).iter().count(), 0); - } - - #[test] - fn test_iterator_sum() { - let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.slice(0, 4).iter().map(|&x| x).sum(), 6); - assert_eq!(v.iter().map(|&x| x).sum(), 55); - assert_eq!(v.slice(0, 0).iter().map(|&x| x).sum(), 0); - } - - #[test] - fn test_iterator_product() { - let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.slice(0, 4).iter().map(|&x| x).product(), 0); - assert_eq!(v.slice(1, 5).iter().map(|&x| x).product(), 24); - assert_eq!(v.slice(0, 0).iter().map(|&x| x).product(), 1); - } - - #[test] - fn test_iterator_max() { - let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.slice(0, 4).iter().map(|&x| x).max(), Some(3)); - assert_eq!(v.iter().map(|&x| x).max(), Some(10)); - assert_eq!(v.slice(0, 0).iter().map(|&x| x).max(), None); - } - - #[test] - fn test_iterator_min() { - let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.slice(0, 4).iter().map(|&x| x).min(), Some(0)); - assert_eq!(v.iter().map(|&x| x).min(), Some(0)); - assert_eq!(v.slice(0, 0).iter().map(|&x| x).min(), None); - } - - #[test] - fn test_iterator_size_hint() { - let c = count(0i, 1); - let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9]; - let v2 = &[10i, 11, 12]; - let vi = v.iter(); - - assert_eq!(c.size_hint(), (uint::MAX, None)); - assert_eq!(vi.size_hint(), (10, Some(10))); - - assert_eq!(c.take(5).size_hint(), (5, Some(5))); - assert_eq!(c.skip(5).size_hint().val1(), None); - assert_eq!(c.take_while(|_| false).size_hint(), (0, None)); - assert_eq!(c.skip_while(|_| false).size_hint(), (0, None)); - assert_eq!(c.enumerate().size_hint(), (uint::MAX, None)); - assert_eq!(c.chain(vi.map(|&i| i)).size_hint(), (uint::MAX, None)); - assert_eq!(c.zip(vi).size_hint(), (10, Some(10))); - assert_eq!(c.scan(0i, |_,_| Some(0i)).size_hint(), (0, None)); - assert_eq!(c.filter(|_| false).size_hint(), (0, None)); - assert_eq!(c.map(|_| 0i).size_hint(), (uint::MAX, None)); - assert_eq!(c.filter_map(|_| Some(0i)).size_hint(), (0, None)); - - assert_eq!(vi.take(5).size_hint(), (5, Some(5))); - assert_eq!(vi.take(12).size_hint(), (10, Some(10))); - assert_eq!(vi.skip(3).size_hint(), (7, Some(7))); - assert_eq!(vi.skip(12).size_hint(), (0, Some(0))); - assert_eq!(vi.take_while(|_| false).size_hint(), (0, Some(10))); - assert_eq!(vi.skip_while(|_| false).size_hint(), (0, Some(10))); - assert_eq!(vi.enumerate().size_hint(), (10, Some(10))); - assert_eq!(vi.chain(v2.iter()).size_hint(), (13, Some(13))); - assert_eq!(vi.zip(v2.iter()).size_hint(), (3, Some(3))); - assert_eq!(vi.scan(0i, |_,_| Some(0i)).size_hint(), (0, Some(10))); - assert_eq!(vi.filter(|_| false).size_hint(), (0, Some(10))); - assert_eq!(vi.map(|i| i+1).size_hint(), (10, Some(10))); - assert_eq!(vi.filter_map(|_| Some(0i)).size_hint(), (0, Some(10))); - } - - #[test] - fn test_collect() { - let a = vec![1i, 2, 3, 4, 5]; - let b: Vec = a.iter().map(|&x| x).collect(); - assert!(a == b); - } - - #[test] - fn test_all() { - let v: Box<&[int]> = box &[1i, 2, 3, 4, 5]; - assert!(v.iter().all(|&x| x < 10)); - assert!(!v.iter().all(|&x| x % 2 == 0)); - assert!(!v.iter().all(|&x| x > 100)); - assert!(v.slice(0, 0).iter().all(|_| fail!())); - } - - #[test] - fn test_any() { - let v: Box<&[int]> = box &[1i, 2, 3, 4, 5]; - assert!(v.iter().any(|&x| x < 10)); - assert!(v.iter().any(|&x| x % 2 == 0)); - assert!(!v.iter().any(|&x| x > 100)); - assert!(!v.slice(0, 0).iter().any(|_| fail!())); - } - - #[test] - fn test_find() { - let v: &[int] = &[1i, 3, 9, 27, 103, 14, 11]; - assert_eq!(*v.iter().find(|x| *x & 1 == 0).unwrap(), 14); - assert_eq!(*v.iter().find(|x| *x % 3 == 0).unwrap(), 3); - assert!(v.iter().find(|x| *x % 12 == 0).is_none()); - } - - #[test] - fn test_position() { - let v = &[1i, 3, 9, 27, 103, 14, 11]; - assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5); - assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1); - assert!(v.iter().position(|x| *x % 12 == 0).is_none()); - } - - #[test] - fn test_count() { - let xs = &[1i, 2, 2, 1, 5, 9, 0, 2]; - assert_eq!(xs.iter().filter(|x| **x == 2).count(), 3); - assert_eq!(xs.iter().filter(|x| **x == 5).count(), 1); - assert_eq!(xs.iter().filter(|x| **x == 95).count(), 0); - } - - #[test] - fn test_max_by() { - let xs: &[int] = &[-3i, 0, 1, 5, -10]; - assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10); - } - - #[test] - fn test_min_by() { - let xs: &[int] = &[-3i, 0, 1, 5, -10]; - assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0); - } - - #[test] - fn test_by_ref() { - let mut xs = range(0i, 10); - // sum the first five values - let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b); - assert_eq!(partial_sum, 10); - assert_eq!(xs.next(), Some(5)); - } - - #[test] - fn test_rev() { - let xs = [2i, 4, 6, 8, 10, 12, 14, 16]; - let mut it = xs.iter(); - it.next(); - it.next(); - assert!(it.rev().map(|&x| x).collect::>() == - vec![16, 14, 12, 10, 8, 6]); - } - - #[test] - fn test_double_ended_map() { - let xs = [1i, 2, 3, 4, 5, 6]; - let mut it = xs.iter().map(|&x| x * -1); - assert_eq!(it.next(), Some(-1)); - assert_eq!(it.next(), Some(-2)); - assert_eq!(it.next_back(), Some(-6)); - assert_eq!(it.next_back(), Some(-5)); - assert_eq!(it.next(), Some(-3)); - assert_eq!(it.next_back(), Some(-4)); - assert_eq!(it.next(), None); - } - - #[test] - fn test_double_ended_enumerate() { - let xs = [1i, 2, 3, 4, 5, 6]; - let mut it = xs.iter().map(|&x| x).enumerate(); - assert_eq!(it.next(), Some((0, 1))); - assert_eq!(it.next(), Some((1, 2))); - assert_eq!(it.next_back(), Some((5, 6))); - assert_eq!(it.next_back(), Some((4, 5))); - assert_eq!(it.next_back(), Some((3, 4))); - assert_eq!(it.next_back(), Some((2, 3))); - assert_eq!(it.next(), None); - } - - #[test] - fn test_double_ended_zip() { - let xs = [1i, 2, 3, 4, 5, 6]; - let ys = [1i, 2, 3, 7]; - let a = xs.iter().map(|&x| x); - let b = ys.iter().map(|&x| x); - let mut it = a.zip(b); - assert_eq!(it.next(), Some((1, 1))); - assert_eq!(it.next(), Some((2, 2))); - assert_eq!(it.next_back(), Some((4, 7))); - assert_eq!(it.next_back(), Some((3, 3))); - assert_eq!(it.next(), None); - } - - #[test] - fn test_double_ended_filter() { - let xs = [1i, 2, 3, 4, 5, 6]; - let mut it = xs.iter().filter(|&x| *x & 1 == 0); - assert_eq!(it.next_back().unwrap(), &6); - assert_eq!(it.next_back().unwrap(), &4); - assert_eq!(it.next().unwrap(), &2); - assert_eq!(it.next_back(), None); - } - - #[test] - fn test_double_ended_filter_map() { - let xs = [1i, 2, 3, 4, 5, 6]; - let mut it = xs.iter().filter_map(|&x| if x & 1 == 0 { Some(x * 2) } else { None }); - assert_eq!(it.next_back().unwrap(), 12); - assert_eq!(it.next_back().unwrap(), 8); - assert_eq!(it.next().unwrap(), 4); - assert_eq!(it.next_back(), None); - } - - #[test] - fn test_double_ended_chain() { - let xs = [1i, 2, 3, 4, 5]; - let ys = [7i, 9, 11]; - let mut it = xs.iter().chain(ys.iter()).rev(); - assert_eq!(it.next().unwrap(), &11) - assert_eq!(it.next().unwrap(), &9) - assert_eq!(it.next_back().unwrap(), &1) - assert_eq!(it.next_back().unwrap(), &2) - assert_eq!(it.next_back().unwrap(), &3) - assert_eq!(it.next_back().unwrap(), &4) - assert_eq!(it.next_back().unwrap(), &5) - assert_eq!(it.next_back().unwrap(), &7) - assert_eq!(it.next_back(), None) - } - - #[test] - fn test_rposition() { - fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' } - fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' } - let v = [(0i, 'a'), (1, 'b'), (2, 'c'), (3, 'b')]; - - assert_eq!(v.iter().rposition(f), Some(3u)); - assert!(v.iter().rposition(g).is_none()); - } - - #[test] - #[should_fail] - fn test_rposition_fail() { - let v = [(box 0i, box(GC) 0i), (box 0i, box(GC) 0i), - (box 0i, box(GC) 0i), (box 0i, box(GC) 0i)]; - let mut i = 0i; - v.iter().rposition(|_elt| { - if i == 2 { - fail!() - } - i += 1; - false - }); - } - - - #[cfg(test)] - fn check_randacc_iter>(a: T, len: uint) - { - let mut b = a.clone(); - assert_eq!(len, b.indexable()); - let mut n = 0u; - for (i, elt) in a.enumerate() { - assert!(Some(elt) == b.idx(i)); - n += 1; - } - assert_eq!(n, len); - assert!(None == b.idx(n)); - // call recursively to check after picking off an element - if len > 0 { - b.next(); - check_randacc_iter(b, len-1); - } - } - - - #[test] - fn test_double_ended_flat_map() { - let u = [0u,1]; - let v = [5u,6,7,8]; - let mut it = u.iter().flat_map(|x| v.slice(*x, v.len()).iter()); - assert_eq!(it.next_back().unwrap(), &8); - assert_eq!(it.next().unwrap(), &5); - assert_eq!(it.next_back().unwrap(), &7); - assert_eq!(it.next_back().unwrap(), &6); - assert_eq!(it.next_back().unwrap(), &8); - assert_eq!(it.next().unwrap(), &6); - assert_eq!(it.next_back().unwrap(), &7); - assert_eq!(it.next_back(), None); - assert_eq!(it.next(), None); - assert_eq!(it.next_back(), None); - } - - #[test] - fn test_random_access_chain() { - let xs = [1i, 2, 3, 4, 5]; - let ys = [7i, 9, 11]; - let mut it = xs.iter().chain(ys.iter()); - assert_eq!(it.idx(0).unwrap(), &1); - assert_eq!(it.idx(5).unwrap(), &7); - assert_eq!(it.idx(7).unwrap(), &11); - assert!(it.idx(8).is_none()); - - it.next(); - it.next(); - it.next_back(); - - assert_eq!(it.idx(0).unwrap(), &3); - assert_eq!(it.idx(4).unwrap(), &9); - assert!(it.idx(6).is_none()); - - check_randacc_iter(it, xs.len() + ys.len() - 3); - } - - #[test] - fn test_random_access_enumerate() { - let xs = [1i, 2, 3, 4, 5]; - check_randacc_iter(xs.iter().enumerate(), xs.len()); - } - - #[test] - fn test_random_access_rev() { - let xs = [1i, 2, 3, 4, 5]; - check_randacc_iter(xs.iter().rev(), xs.len()); - let mut it = xs.iter().rev(); - it.next(); - it.next_back(); - it.next(); - check_randacc_iter(it, xs.len() - 3); - } - - #[test] - fn test_random_access_zip() { - let xs = [1i, 2, 3, 4, 5]; - let ys = [7i, 9, 11]; - check_randacc_iter(xs.iter().zip(ys.iter()), cmp::min(xs.len(), ys.len())); - } - - #[test] - fn test_random_access_take() { - let xs = [1i, 2, 3, 4, 5]; - let empty: &[int] = []; - check_randacc_iter(xs.iter().take(3), 3); - check_randacc_iter(xs.iter().take(20), xs.len()); - check_randacc_iter(xs.iter().take(0), 0); - check_randacc_iter(empty.iter().take(2), 0); - } - - #[test] - fn test_random_access_skip() { - let xs = [1i, 2, 3, 4, 5]; - let empty: &[int] = []; - check_randacc_iter(xs.iter().skip(2), xs.len() - 2); - check_randacc_iter(empty.iter().skip(2), 0); - } - - #[test] - fn test_random_access_inspect() { - let xs = [1i, 2, 3, 4, 5]; - - // test .map and .inspect that don't implement Clone - let mut it = xs.iter().inspect(|_| {}); - assert_eq!(xs.len(), it.indexable()); - for (i, elt) in xs.iter().enumerate() { - assert_eq!(Some(elt), it.idx(i)); - } - - } - - #[test] - fn test_random_access_map() { - let xs = [1i, 2, 3, 4, 5]; - - let mut it = xs.iter().map(|x| *x); - assert_eq!(xs.len(), it.indexable()); - for (i, elt) in xs.iter().enumerate() { - assert_eq!(Some(*elt), it.idx(i)); - } - } - - #[test] - fn test_random_access_cycle() { - let xs = [1i, 2, 3, 4, 5]; - let empty: &[int] = []; - check_randacc_iter(xs.iter().cycle().take(27), 27); - check_randacc_iter(empty.iter().cycle(), 0); - } - - #[test] - fn test_double_ended_range() { - assert!(range(11i, 14).rev().collect::>() == vec![13i, 12, 11]); - for _ in range(10i, 0).rev() { - fail!("unreachable"); - } - - assert!(range(11u, 14).rev().collect::>() == vec![13u, 12, 11]); - for _ in range(10u, 0).rev() { - fail!("unreachable"); - } - } - - #[test] - fn test_range() { - /// A mock type to check Range when ToPrimitive returns None - struct Foo; - - impl ToPrimitive for Foo { - fn to_i64(&self) -> Option { None } - fn to_u64(&self) -> Option { None } - } - - impl Add for Foo { - fn add(&self, _: &Foo) -> Foo { - Foo - } - } - - impl PartialEq for Foo { - fn eq(&self, _: &Foo) -> bool { - true - } - } - - impl PartialOrd for Foo { - fn lt(&self, _: &Foo) -> bool { - false - } - } - - impl Clone for Foo { - fn clone(&self) -> Foo { - Foo - } - } - - impl Mul for Foo { - fn mul(&self, _: &Foo) -> Foo { - Foo - } - } - - impl num::One for Foo { - fn one() -> Foo { - Foo - } - } - - assert!(range(0i, 5).collect::>() == vec![0i, 1, 2, 3, 4]); - assert!(range(-10i, -1).collect::>() == - vec![-10, -9, -8, -7, -6, -5, -4, -3, -2]); - assert!(range(0i, 5).rev().collect::>() == vec![4, 3, 2, 1, 0]); - assert_eq!(range(200i, -5).count(), 0); - assert_eq!(range(200i, -5).rev().count(), 0); - assert_eq!(range(200i, 200).count(), 0); - assert_eq!(range(200i, 200).rev().count(), 0); - - assert_eq!(range(0i, 100).size_hint(), (100, Some(100))); - // this test is only meaningful when sizeof uint < sizeof u64 - assert_eq!(range(uint::MAX - 1, uint::MAX).size_hint(), (1, Some(1))); - assert_eq!(range(-10i, -1).size_hint(), (9, Some(9))); - assert_eq!(range(Foo, Foo).size_hint(), (0, None)); - } - - #[test] - fn test_range_inclusive() { - assert!(range_inclusive(0i, 5).collect::>() == - vec![0i, 1, 2, 3, 4, 5]); - assert!(range_inclusive(0i, 5).rev().collect::>() == - vec![5i, 4, 3, 2, 1, 0]); - assert_eq!(range_inclusive(200i, -5).count(), 0); - assert_eq!(range_inclusive(200i, -5).rev().count(), 0); - assert!(range_inclusive(200i, 200).collect::>() == vec![200]); - assert!(range_inclusive(200i, 200).rev().collect::>() == vec![200]); - } - - #[test] - fn test_range_step() { - assert!(range_step(0i, 20, 5).collect::>() == - vec![0, 5, 10, 15]); - assert!(range_step(20i, 0, -5).collect::>() == - vec![20, 15, 10, 5]); - assert!(range_step(20i, 0, -6).collect::>() == - vec![20, 14, 8, 2]); - assert!(range_step(200u8, 255, 50).collect::>() == - vec![200u8, 250]); - assert!(range_step(200i, -5, 1).collect::>() == vec![]); - assert!(range_step(200i, 200, 1).collect::>() == vec![]); - } - - #[test] - fn test_range_step_inclusive() { - assert!(range_step_inclusive(0i, 20, 5).collect::>() == - vec![0, 5, 10, 15, 20]); - assert!(range_step_inclusive(20i, 0, -5).collect::>() == - vec![20, 15, 10, 5, 0]); - assert!(range_step_inclusive(20i, 0, -6).collect::>() == - vec![20, 14, 8, 2]); - assert!(range_step_inclusive(200u8, 255, 50).collect::>() == - vec![200u8, 250]); - assert!(range_step_inclusive(200i, -5, 1).collect::>() == - vec![]); - assert!(range_step_inclusive(200i, 200, 1).collect::>() == - vec![200]); - } - - #[test] - fn test_reverse() { - let mut ys = [1i, 2, 3, 4, 5]; - ys.mut_iter().reverse_(); - assert!(ys == [5, 4, 3, 2, 1]); - } - - #[test] - fn test_peekable_is_empty() { - let a = [1i]; - let mut it = a.iter().peekable(); - assert!( !it.is_empty() ); - it.next(); - assert!( it.is_empty() ); - } - - #[test] - fn test_min_max() { - let v: [int, ..0] = []; - assert_eq!(v.iter().min_max(), NoElements); - - let v = [1i]; - assert!(v.iter().min_max() == OneElement(&1)); - - let v = [1i, 2, 3, 4, 5]; - assert!(v.iter().min_max() == MinMax(&1, &5)); - - let v = [1i, 2, 3, 4, 5, 6]; - assert!(v.iter().min_max() == MinMax(&1, &6)); - - let v = [1i, 1, 1, 1]; - assert!(v.iter().min_max() == MinMax(&1, &1)); - } - - #[test] - fn test_min_max_result() { - let r: MinMaxResult = NoElements; - assert_eq!(r.into_option(), None) - - let r = OneElement(1i); - assert_eq!(r.into_option(), Some((1,1))); - - let r = MinMax(1i,2); - assert_eq!(r.into_option(), Some((1,2))); - } } + diff --git a/src/libcore/lib.rs b/src/libcore/lib.rs index 4dc45ceeb85ad..385a33fb92a4c 100644 --- a/src/libcore/lib.rs +++ b/src/libcore/lib.rs @@ -43,7 +43,9 @@ //! the failure message, the file at which failure was invoked, and the line. //! It is up to consumers of this core library to define this failure //! function; it is only required to never return. -//! + +// Since libcore defines many fundamental lang items, all tests live in a +// separate crate, libcoretest, to avoid bizarre issues. #![crate_id = "core#0.11.0-pre"] #![experimental] @@ -59,16 +61,6 @@ #![feature(simd, unsafe_destructor)] #![deny(missing_doc)] -#[cfg(test)] extern crate realcore = "core"; -#[cfg(test)] extern crate libc; -#[cfg(test)] extern crate native; -#[cfg(test)] extern crate realstd = "std"; - -#[cfg(test)] pub use cmp = realcore::cmp; -#[cfg(test)] pub use kinds = realcore::kinds; -#[cfg(test)] pub use ops = realcore::ops; -#[cfg(test)] pub use ty = realcore::ty; - mod macros; #[path = "num/float_macros.rs"] mod float_macros; @@ -104,10 +96,10 @@ pub mod ptr; /* Core language traits */ -#[cfg(not(test))] pub mod kinds; -#[cfg(not(test))] pub mod ops; -#[cfg(not(test))] pub mod ty; -#[cfg(not(test))] pub mod cmp; +pub mod kinds; +pub mod ops; +pub mod ty; +pub mod cmp; pub mod clone; pub mod default; pub mod collections; @@ -144,11 +136,4 @@ mod std { pub use kinds; pub use option; pub use fmt; - - #[cfg(test)] pub use realstd::rt; // needed for fail!() - // #[cfg(test)] pub use realstd::option; // needed for fail!() - // #[cfg(test)] pub use realstd::fmt; // needed for fail!() - #[cfg(test)] pub use realstd::os; // needed for tests - #[cfg(test)] pub use realstd::slice; // needed for tests - #[cfg(test)] pub use realstd::vec; // needed for vec![] } diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs index a62bc10d8abc6..93c838198c559 100644 --- a/src/libcore/macros.rs +++ b/src/libcore/macros.rs @@ -112,16 +112,6 @@ macro_rules! writeln( ) ) -#[cfg(test)] -macro_rules! vec( ($($e:expr),*) => ({ - let mut _v = ::std::vec::Vec::new(); - $(_v.push($e);)* - _v -}) ) - -#[cfg(test)] -macro_rules! format( ($($arg:tt)*) => (format_args!(::fmt::format, $($arg)*)) ) - /// Write some formatted data into a stream. /// /// Identical to the macro in `std::macros` diff --git a/src/libcore/mem.rs b/src/libcore/mem.rs index 39ec830179cb5..06e28816c1cd5 100644 --- a/src/libcore/mem.rs +++ b/src/libcore/mem.rs @@ -382,182 +382,3 @@ pub unsafe fn copy_mut_lifetime<'a, S, T>(_ptr: &'a mut S, ptr: &mut T) -> &'a mut T { transmute(ptr) } - -#[cfg(test)] -mod tests { - use mem::*; - use option::{Some,None}; - use realstd::str::StrAllocating; - use realstd::owned::Box; - use realstd::vec::Vec; - use raw; - - #[test] - fn size_of_basic() { - assert_eq!(size_of::(), 1u); - assert_eq!(size_of::(), 2u); - assert_eq!(size_of::(), 4u); - assert_eq!(size_of::(), 8u); - } - - #[test] - #[cfg(target_arch = "x86")] - #[cfg(target_arch = "arm")] - #[cfg(target_arch = "mips")] - #[cfg(target_arch = "mipsel")] - fn size_of_32() { - assert_eq!(size_of::(), 4u); - assert_eq!(size_of::<*const uint>(), 4u); - } - - #[test] - #[cfg(target_arch = "x86_64")] - fn size_of_64() { - assert_eq!(size_of::(), 8u); - assert_eq!(size_of::<*const uint>(), 8u); - } - - #[test] - fn size_of_val_basic() { - assert_eq!(size_of_val(&1u8), 1); - assert_eq!(size_of_val(&1u16), 2); - assert_eq!(size_of_val(&1u32), 4); - assert_eq!(size_of_val(&1u64), 8); - } - - #[test] - fn align_of_basic() { - assert_eq!(align_of::(), 1u); - assert_eq!(align_of::(), 2u); - assert_eq!(align_of::(), 4u); - } - - #[test] - #[cfg(target_arch = "x86")] - #[cfg(target_arch = "arm")] - #[cfg(target_arch = "mips")] - #[cfg(target_arch = "mipsel")] - fn align_of_32() { - assert_eq!(align_of::(), 4u); - assert_eq!(align_of::<*const uint>(), 4u); - } - - #[test] - #[cfg(target_arch = "x86_64")] - fn align_of_64() { - assert_eq!(align_of::(), 8u); - assert_eq!(align_of::<*const uint>(), 8u); - } - - #[test] - fn align_of_val_basic() { - assert_eq!(align_of_val(&1u8), 1u); - assert_eq!(align_of_val(&1u16), 2u); - assert_eq!(align_of_val(&1u32), 4u); - } - - #[test] - fn test_swap() { - let mut x = 31337i; - let mut y = 42i; - swap(&mut x, &mut y); - assert_eq!(x, 42); - assert_eq!(y, 31337); - } - - #[test] - fn test_replace() { - let mut x = Some("test".to_string()); - let y = replace(&mut x, None); - assert!(x.is_none()); - assert!(y.is_some()); - } - - #[test] - fn test_transmute_copy() { - assert_eq!(1u, unsafe { ::mem::transmute_copy(&1i) }); - } - - #[test] - fn test_transmute() { - trait Foo {} - impl Foo for int {} - - let a = box 100i as Box; - unsafe { - let x: raw::TraitObject = transmute(a); - assert!(*(x.data as *const int) == 100); - let _x: Box = transmute(x); - } - - unsafe { - assert!(Vec::from_slice([76u8]) == transmute("L".to_string())); - } - } -} - -// FIXME #13642 (these benchmarks should be in another place) -/// Completely miscellaneous language-construct benchmarks. -#[cfg(test)] -mod bench { - extern crate test; - use self::test::Bencher; - use option::{Some,None}; - - // Static/dynamic method dispatch - - struct Struct { - field: int - } - - trait Trait { - fn method(&self) -> int; - } - - impl Trait for Struct { - fn method(&self) -> int { - self.field - } - } - - #[bench] - fn trait_vtable_method_call(b: &mut Bencher) { - let s = Struct { field: 10 }; - let t = &s as &Trait; - b.iter(|| { - t.method() - }); - } - - #[bench] - fn trait_static_method_call(b: &mut Bencher) { - let s = Struct { field: 10 }; - b.iter(|| { - s.method() - }); - } - - // Overhead of various match forms - - #[bench] - fn match_option_some(b: &mut Bencher) { - let x = Some(10i); - b.iter(|| { - match x { - Some(y) => y, - None => 11 - } - }); - } - - #[bench] - fn match_vec_pattern(b: &mut Bencher) { - let x = [1i,2,3,4,5,6]; - b.iter(|| { - match x { - [1,2,3,..] => 10i, - _ => 11i, - } - }); - } -} diff --git a/src/libcore/num/int_macros.rs b/src/libcore/num/int_macros.rs index ef10c9abe1141..ff0494725f849 100644 --- a/src/libcore/num/int_macros.rs +++ b/src/libcore/num/int_macros.rs @@ -32,152 +32,4 @@ pub static MIN: $T = (-1 as $T) << (BITS - 1); #[unstable] pub static MAX: $T = !MIN; -#[cfg(test)] -mod tests { - use prelude::*; - use super::*; - - use int; - use num; - use num::CheckedDiv; - - #[test] - fn test_overflows() { - assert!(MAX > 0); - assert!(MIN <= 0); - assert!(MIN + MAX + 1 == 0); - } - - #[test] - fn test_num() { - num::test_num(10 as $T, 2 as $T); - } - - #[test] - pub fn test_abs() { - assert!((1 as $T).abs() == 1 as $T); - assert!((0 as $T).abs() == 0 as $T); - assert!((-1 as $T).abs() == 1 as $T); - } - - #[test] - fn test_abs_sub() { - assert!((-1 as $T).abs_sub(&(1 as $T)) == 0 as $T); - assert!((1 as $T).abs_sub(&(1 as $T)) == 0 as $T); - assert!((1 as $T).abs_sub(&(0 as $T)) == 1 as $T); - assert!((1 as $T).abs_sub(&(-1 as $T)) == 2 as $T); - } - - #[test] - fn test_signum() { - assert!((1 as $T).signum() == 1 as $T); - assert!((0 as $T).signum() == 0 as $T); - assert!((-0 as $T).signum() == 0 as $T); - assert!((-1 as $T).signum() == -1 as $T); - } - - #[test] - fn test_is_positive() { - assert!((1 as $T).is_positive()); - assert!(!(0 as $T).is_positive()); - assert!(!(-0 as $T).is_positive()); - assert!(!(-1 as $T).is_positive()); - } - - #[test] - fn test_is_negative() { - assert!(!(1 as $T).is_negative()); - assert!(!(0 as $T).is_negative()); - assert!(!(-0 as $T).is_negative()); - assert!((-1 as $T).is_negative()); - } - - #[test] - fn test_bitwise_operators() { - assert!(0b1110 as $T == (0b1100 as $T).bitor(&(0b1010 as $T))); - assert!(0b1000 as $T == (0b1100 as $T).bitand(&(0b1010 as $T))); - assert!(0b0110 as $T == (0b1100 as $T).bitxor(&(0b1010 as $T))); - assert!(0b1110 as $T == (0b0111 as $T).shl(&(1 as $T))); - assert!(0b0111 as $T == (0b1110 as $T).shr(&(1 as $T))); - assert!(-(0b11 as $T) - (1 as $T) == (0b11 as $T).not()); - } - - static A: $T = 0b0101100; - static B: $T = 0b0100001; - static C: $T = 0b1111001; - - static _0: $T = 0; - static _1: $T = !0; - - #[test] - fn test_count_ones() { - assert!(A.count_ones() == 3); - assert!(B.count_ones() == 2); - assert!(C.count_ones() == 5); - } - - #[test] - fn test_count_zeros() { - assert!(A.count_zeros() == BITS as $T - 3); - assert!(B.count_zeros() == BITS as $T - 2); - assert!(C.count_zeros() == BITS as $T - 5); - } - - #[test] - fn test_rotate() { - assert_eq!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); - assert_eq!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); - assert_eq!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); - - // Rotating these should make no difference - // - // We test using 124 bits because to ensure that overlong bit shifts do - // not cause undefined behaviour. See #10183. - assert_eq!(_0.rotate_left(124), _0); - assert_eq!(_1.rotate_left(124), _1); - assert_eq!(_0.rotate_right(124), _0); - assert_eq!(_1.rotate_right(124), _1); - } - - #[test] - fn test_swap_bytes() { - assert_eq!(A.swap_bytes().swap_bytes(), A); - assert_eq!(B.swap_bytes().swap_bytes(), B); - assert_eq!(C.swap_bytes().swap_bytes(), C); - - // Swapping these should make no difference - assert_eq!(_0.swap_bytes(), _0); - assert_eq!(_1.swap_bytes(), _1); - } - - #[test] - fn test_le() { - assert_eq!(Int::from_le(A.to_le()), A); - assert_eq!(Int::from_le(B.to_le()), B); - assert_eq!(Int::from_le(C.to_le()), C); - assert_eq!(Int::from_le(_0), _0); - assert_eq!(Int::from_le(_1), _1); - assert_eq!(_0.to_le(), _0); - assert_eq!(_1.to_le(), _1); - } - - #[test] - fn test_be() { - assert_eq!(Int::from_be(A.to_be()), A); - assert_eq!(Int::from_be(B.to_be()), B); - assert_eq!(Int::from_be(C.to_be()), C); - assert_eq!(Int::from_be(_0), _0); - assert_eq!(Int::from_be(_1), _1); - assert_eq!(_0.to_be(), _0); - assert_eq!(_1.to_be(), _1); - } - - #[test] - fn test_signed_checked_div() { - assert!(10i.checked_div(&2) == Some(5)); - assert!(5i.checked_div(&0) == None); - assert!(int::MIN.checked_div(&-1) == None); - } -} - )) diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index 512c107b930b6..b32e4167da1d4 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -1375,22 +1375,6 @@ macro_rules! checkeddiv_uint_impl( checkeddiv_uint_impl!(uint u8 u16 u32 u64) -/// Helper function for testing numeric operations -#[cfg(test)] -pub fn test_num(ten: T, two: T) { - assert_eq!(ten.add(&two), cast(12i).unwrap()); - assert_eq!(ten.sub(&two), cast(8i).unwrap()); - assert_eq!(ten.mul(&two), cast(20i).unwrap()); - assert_eq!(ten.div(&two), cast(5i).unwrap()); - assert_eq!(ten.rem(&two), cast(0i).unwrap()); - - assert_eq!(ten.add(&two), ten + two); - assert_eq!(ten.sub(&two), ten - two); - assert_eq!(ten.mul(&two), ten * two); - assert_eq!(ten.div(&two), ten / two); - assert_eq!(ten.rem(&two), ten % two); -} - /// Used for representing the classification of floating point numbers #[deriving(PartialEq, Show)] pub enum FPCategory { diff --git a/src/libcore/num/uint_macros.rs b/src/libcore/num/uint_macros.rs index 5828697ddad50..b0c570af04ac0 100644 --- a/src/libcore/num/uint_macros.rs +++ b/src/libcore/num/uint_macros.rs @@ -23,111 +23,4 @@ pub static MIN: $T = 0 as $T; #[unstable] pub static MAX: $T = 0 as $T - 1 as $T; -#[cfg(test)] -mod tests { - use prelude::*; - use super::*; - - use num; - use num::CheckedDiv; - - #[test] - fn test_overflows() { - assert!(MAX > 0); - assert!(MIN <= 0); - assert!(MIN + MAX + 1 == 0); - } - - #[test] - fn test_num() { - num::test_num(10 as $T, 2 as $T); - } - - #[test] - fn test_bitwise_operators() { - assert!(0b1110 as $T == (0b1100 as $T).bitor(&(0b1010 as $T))); - assert!(0b1000 as $T == (0b1100 as $T).bitand(&(0b1010 as $T))); - assert!(0b0110 as $T == (0b1100 as $T).bitxor(&(0b1010 as $T))); - assert!(0b1110 as $T == (0b0111 as $T).shl(&(1 as $T))); - assert!(0b0111 as $T == (0b1110 as $T).shr(&(1 as $T))); - assert!(MAX - (0b1011 as $T) == (0b1011 as $T).not()); - } - - static A: $T = 0b0101100; - static B: $T = 0b0100001; - static C: $T = 0b1111001; - - static _0: $T = 0; - static _1: $T = !0; - - #[test] - fn test_count_ones() { - assert!(A.count_ones() == 3); - assert!(B.count_ones() == 2); - assert!(C.count_ones() == 5); - } - - #[test] - fn test_count_zeros() { - assert!(A.count_zeros() == BITS as $T - 3); - assert!(B.count_zeros() == BITS as $T - 2); - assert!(C.count_zeros() == BITS as $T - 5); - } - - #[test] - fn test_rotate() { - assert_eq!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); - assert_eq!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); - assert_eq!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); - - // Rotating these should make no difference - // - // We test using 124 bits because to ensure that overlong bit shifts do - // not cause undefined behaviour. See #10183. - assert_eq!(_0.rotate_left(124), _0); - assert_eq!(_1.rotate_left(124), _1); - assert_eq!(_0.rotate_right(124), _0); - assert_eq!(_1.rotate_right(124), _1); - } - - #[test] - fn test_swap_bytes() { - assert_eq!(A.swap_bytes().swap_bytes(), A); - assert_eq!(B.swap_bytes().swap_bytes(), B); - assert_eq!(C.swap_bytes().swap_bytes(), C); - - // Swapping these should make no difference - assert_eq!(_0.swap_bytes(), _0); - assert_eq!(_1.swap_bytes(), _1); - } - - #[test] - fn test_le() { - assert_eq!(Int::from_le(A.to_le()), A); - assert_eq!(Int::from_le(B.to_le()), B); - assert_eq!(Int::from_le(C.to_le()), C); - assert_eq!(Int::from_le(_0), _0); - assert_eq!(Int::from_le(_1), _1); - assert_eq!(_0.to_le(), _0); - assert_eq!(_1.to_le(), _1); - } - - #[test] - fn test_be() { - assert_eq!(Int::from_be(A.to_be()), A); - assert_eq!(Int::from_be(B.to_be()), B); - assert_eq!(Int::from_be(C.to_be()), C); - assert_eq!(Int::from_be(_0), _0); - assert_eq!(Int::from_be(_1), _1); - assert_eq!(_0.to_be(), _0); - assert_eq!(_1.to_be(), _1); - } - - #[test] - fn test_unsigned_checked_div() { - assert!(10u.checked_div(&2) == Some(5)); - assert!(5u.checked_div(&0) == None); - } -} - )) diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index afa08f04cb203..d42c09b8163dd 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -117,7 +117,6 @@ pub trait Add { macro_rules! add_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl Add<$t, $t> for $t { #[inline] fn add(&self, other: &$t) -> $t { (*self) + (*other) } @@ -159,7 +158,6 @@ pub trait Sub { macro_rules! sub_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl Sub<$t, $t> for $t { #[inline] fn sub(&self, other: &$t) -> $t { (*self) - (*other) } @@ -201,7 +199,6 @@ pub trait Mul { macro_rules! mul_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl Mul<$t, $t> for $t { #[inline] fn mul(&self, other: &$t) -> $t { (*self) * (*other) } @@ -243,7 +240,6 @@ pub trait Div { macro_rules! div_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl Div<$t, $t> for $t { #[inline] fn div(&self, other: &$t) -> $t { (*self) / (*other) } @@ -285,7 +281,6 @@ pub trait Rem { macro_rules! rem_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl Rem<$t, $t> for $t { #[inline] fn rem(&self, other: &$t) -> $t { (*self) % (*other) } @@ -295,7 +290,6 @@ macro_rules! rem_impl( macro_rules! rem_float_impl( ($t:ty, $fmod:ident) => { - #[cfg(not(test))] impl Rem<$t, $t> for $t { #[inline] fn rem(&self, other: &$t) -> $t { @@ -342,7 +336,6 @@ pub trait Neg { macro_rules! neg_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl Neg<$t> for $t { #[inline] fn neg(&self) -> $t { -*self } @@ -352,7 +345,6 @@ macro_rules! neg_impl( macro_rules! neg_uint_impl( ($t:ty, $t_signed:ty) => { - #[cfg(not(test))] impl Neg<$t> for $t { #[inline] fn neg(&self) -> $t { -(*self as $t_signed) as $t } @@ -402,7 +394,6 @@ pub trait Not { macro_rules! not_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl Not<$t> for $t { #[inline] fn not(&self) -> $t { !*self } @@ -444,7 +435,6 @@ pub trait BitAnd { macro_rules! bitand_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl BitAnd<$t, $t> for $t { #[inline] fn bitand(&self, rhs: &$t) -> $t { (*self) & (*rhs) } @@ -486,7 +476,6 @@ pub trait BitOr { macro_rules! bitor_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl BitOr<$t,$t> for $t { #[inline] fn bitor(&self, rhs: &$t) -> $t { (*self) | (*rhs) } @@ -528,7 +517,6 @@ pub trait BitXor { macro_rules! bitxor_impl( ($($t:ty)*) => ($( - #[cfg(not(test))] impl BitXor<$t, $t> for $t { #[inline] fn bitxor(&self, other: &$t) -> $t { (*self) ^ (*other) } @@ -746,28 +734,3 @@ pub trait FnOnce { /// This is called when the call operator is used. fn call_once(self, args: Args) -> Result; } - -#[cfg(test)] -mod bench { - extern crate test; - use self::test::Bencher; - use ops::Drop; - - // Overhead of dtors - - struct HasDtor { - x: int - } - - impl Drop for HasDtor { - fn drop(&mut self) { - } - } - - #[bench] - fn alloc_obj_with_dtor(b: &mut Bencher) { - b.iter(|| { - HasDtor { x : 10 }; - }) - } -} diff --git a/src/libcore/option.rs b/src/libcore/option.rs index 949e6a5b9a072..c0d04ee0b95fd 100644 --- a/src/libcore/option.rs +++ b/src/libcore/option.rs @@ -606,291 +606,3 @@ pub fn collect>, V: FromIterator>(iter: Iter) -> Some(v) } } - -///////////////////////////////////////////////////////////////////////////// -// Tests -///////////////////////////////////////////////////////////////////////////// - -#[cfg(test)] -mod tests { - use realstd::vec::Vec; - use realstd::string::String; - use option::collect; - use prelude::*; - use realstd::str::{Str, StrAllocating}; - use iter::range; - - use str::StrSlice; - use kinds::marker; - use slice::ImmutableVector; - - #[test] - fn test_get_ptr() { - unsafe { - let x = box 0i; - let addr_x: *const int = ::mem::transmute(&*x); - let opt = Some(x); - let y = opt.unwrap(); - let addr_y: *const int = ::mem::transmute(&*y); - assert_eq!(addr_x, addr_y); - } - } - - #[test] - fn test_get_str() { - let x = "test".to_string(); - let addr_x = x.as_slice().as_ptr(); - let opt = Some(x); - let y = opt.unwrap(); - let addr_y = y.as_slice().as_ptr(); - assert_eq!(addr_x, addr_y); - } - - #[test] - fn test_get_resource() { - use realstd::rc::Rc; - use cell::RefCell; - - struct R { - i: Rc>, - } - - #[unsafe_destructor] - impl ::ops::Drop for R { - fn drop(&mut self) { - let ii = &*self.i; - let i = *ii.borrow(); - *ii.borrow_mut() = i + 1; - } - } - - fn r(i: Rc>) -> R { - R { - i: i - } - } - - fn realclone(t: &T) -> T { - use realstd::clone::Clone; - t.clone() - } - - let i = Rc::new(RefCell::new(0i)); - { - let x = r(realclone(&i)); - let opt = Some(x); - let _y = opt.unwrap(); - } - assert_eq!(*i.borrow(), 1); - } - - #[test] - fn test_option_dance() { - let x = Some(()); - let mut y = Some(5i); - let mut y2 = 0; - for _x in x.iter() { - y2 = y.take_unwrap(); - } - assert_eq!(y2, 5); - assert!(y.is_none()); - } - - #[test] #[should_fail] - fn test_option_too_much_dance() { - let mut y = Some(marker::NoCopy); - let _y2 = y.take_unwrap(); - let _y3 = y.take_unwrap(); - } - - #[test] - fn test_and() { - let x: Option = Some(1i); - assert_eq!(x.and(Some(2i)), Some(2)); - assert_eq!(x.and(None::), None); - - let x: Option = None; - assert_eq!(x.and(Some(2i)), None); - assert_eq!(x.and(None::), None); - } - - #[test] - fn test_and_then() { - let x: Option = Some(1); - assert_eq!(x.and_then(|x| Some(x + 1)), Some(2)); - assert_eq!(x.and_then(|_| None::), None); - - let x: Option = None; - assert_eq!(x.and_then(|x| Some(x + 1)), None); - assert_eq!(x.and_then(|_| None::), None); - } - - #[test] - fn test_or() { - let x: Option = Some(1); - assert_eq!(x.or(Some(2)), Some(1)); - assert_eq!(x.or(None), Some(1)); - - let x: Option = None; - assert_eq!(x.or(Some(2)), Some(2)); - assert_eq!(x.or(None), None); - } - - #[test] - fn test_or_else() { - let x: Option = Some(1); - assert_eq!(x.or_else(|| Some(2)), Some(1)); - assert_eq!(x.or_else(|| None), Some(1)); - - let x: Option = None; - assert_eq!(x.or_else(|| Some(2)), Some(2)); - assert_eq!(x.or_else(|| None), None); - } - - #[test] - fn test_option_while_some() { - let mut i = 0i; - Some(10i).while_some(|j| { - i += 1; - if j > 0 { - Some(j-1) - } else { - None - } - }); - assert_eq!(i, 11); - } - - #[test] - fn test_unwrap() { - assert_eq!(Some(1i).unwrap(), 1); - let s = Some("hello".to_string()).unwrap(); - assert_eq!(s.as_slice(), "hello"); - } - - #[test] - #[should_fail] - fn test_unwrap_fail1() { - let x: Option = None; - x.unwrap(); - } - - #[test] - #[should_fail] - fn test_unwrap_fail2() { - let x: Option = None; - x.unwrap(); - } - - #[test] - fn test_unwrap_or() { - let x: Option = Some(1); - assert_eq!(x.unwrap_or(2), 1); - - let x: Option = None; - assert_eq!(x.unwrap_or(2), 2); - } - - #[test] - fn test_unwrap_or_else() { - let x: Option = Some(1); - assert_eq!(x.unwrap_or_else(|| 2), 1); - - let x: Option = None; - assert_eq!(x.unwrap_or_else(|| 2), 2); - } - - #[test] - fn test_filtered() { - let some_stuff = Some(42i); - let modified_stuff = some_stuff.filtered(|&x| {x < 10}); - assert_eq!(some_stuff.unwrap(), 42); - assert!(modified_stuff.is_none()); - } - - #[test] - fn test_iter() { - let val = 5i; - - let x = Some(val); - let mut it = x.iter(); - - assert_eq!(it.size_hint(), (1, Some(1))); - assert_eq!(it.next(), Some(&val)); - assert_eq!(it.size_hint(), (0, Some(0))); - assert!(it.next().is_none()); - } - - #[test] - fn test_mut_iter() { - let val = 5i; - let new_val = 11i; - - let mut x = Some(val); - { - let mut it = x.mut_iter(); - - assert_eq!(it.size_hint(), (1, Some(1))); - - match it.next() { - Some(interior) => { - assert_eq!(*interior, val); - *interior = new_val; - } - None => assert!(false), - } - - assert_eq!(it.size_hint(), (0, Some(0))); - assert!(it.next().is_none()); - } - assert_eq!(x, Some(new_val)); - } - - #[test] - fn test_ord() { - let small = Some(1.0f64); - let big = Some(5.0f64); - let nan = Some(0.0f64/0.0); - assert!(!(nan < big)); - assert!(!(nan > big)); - assert!(small < big); - assert!(None < big); - assert!(big > None); - } - - #[test] - fn test_mutate() { - let mut x = Some(3i); - assert!(x.mutate(|i| i+1)); - assert_eq!(x, Some(4i)); - assert!(x.mutate_or_set(0, |i| i+1)); - assert_eq!(x, Some(5i)); - x = None; - assert!(!x.mutate(|i| i+1)); - assert_eq!(x, None); - assert!(!x.mutate_or_set(0i, |i| i+1)); - assert_eq!(x, Some(0i)); - } - - #[test] - fn test_collect() { - let v: Option> = collect(range(0i, 0) - .map(|_| Some(0i))); - assert!(v == Some(vec![])); - - let v: Option> = collect(range(0i, 3) - .map(|x| Some(x))); - assert!(v == Some(vec![0, 1, 2])); - - let v: Option> = collect(range(0i, 3) - .map(|x| if x > 1 { None } else { Some(x) })); - assert!(v == None); - - // test that it does not take more elements than it needs - let mut functions = [|| Some(()), || None, || fail!()]; - - let v: Option> = collect(functions.mut_iter().map(|f| (*f)())); - - assert!(v == None); - } -} diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index 5d1f099040919..cecc6bab683f5 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -1,4 +1,4 @@ -// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT +// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // @@ -93,7 +93,7 @@ use intrinsics; use iter::{range, Iterator}; use option::{Some, None, Option}; -#[cfg(not(test))] use cmp::{PartialEq, Eq, PartialOrd, Equiv}; +use cmp::{PartialEq, Eq, PartialOrd, Equiv}; /// Create a null pointer. /// @@ -404,7 +404,6 @@ impl RawPtr for *mut T { } // Equality for pointers -#[cfg(not(test))] impl PartialEq for *const T { #[inline] fn eq(&self, other: &*const T) -> bool { @@ -414,10 +413,8 @@ impl PartialEq for *const T { fn ne(&self, other: &*const T) -> bool { !self.eq(other) } } -#[cfg(not(test))] impl Eq for *const T {} -#[cfg(not(test))] impl PartialEq for *mut T { #[inline] fn eq(&self, other: &*mut T) -> bool { @@ -427,18 +424,15 @@ impl PartialEq for *mut T { fn ne(&self, other: &*mut T) -> bool { !self.eq(other) } } -#[cfg(not(test))] impl Eq for *mut T {} // Equivalence for pointers -#[cfg(not(test))] impl Equiv<*mut T> for *const T { fn equiv(&self, other: &*mut T) -> bool { self.to_uint() == other.to_uint() } } -#[cfg(not(test))] impl Equiv<*const T> for *mut T { fn equiv(&self, other: &*const T) -> bool { self.to_uint() == other.to_uint() @@ -460,7 +454,6 @@ impl Clone for *mut T { } // Equality for extern "C" fn pointers -#[cfg(not(test))] mod externfnpointers { use mem; use cmp::PartialEq; @@ -494,270 +487,12 @@ mod externfnpointers { } // Comparison for pointers -#[cfg(not(test))] impl PartialOrd for *const T { #[inline] fn lt(&self, other: &*const T) -> bool { *self < *other } } -#[cfg(not(test))] impl PartialOrd for *mut T { #[inline] fn lt(&self, other: &*mut T) -> bool { *self < *other } } - -#[cfg(test)] -#[allow(deprecated, experimental)] -pub mod test { - use super::*; - use prelude::*; - - use realstd::c_str::ToCStr; - use mem; - use libc; - use realstd::str; - use realstd::str::Str; - use realstd::vec::Vec; - use realstd::collections::Collection; - use slice::{ImmutableVector, MutableVector}; - - #[test] - fn test() { - unsafe { - struct Pair { - fst: int, - snd: int - }; - let mut p = Pair {fst: 10, snd: 20}; - let pptr: *mut Pair = &mut p; - let iptr: *mut int = mem::transmute(pptr); - assert_eq!(*iptr, 10); - *iptr = 30; - assert_eq!(*iptr, 30); - assert_eq!(p.fst, 30); - - *pptr = Pair {fst: 50, snd: 60}; - assert_eq!(*iptr, 50); - assert_eq!(p.fst, 50); - assert_eq!(p.snd, 60); - - let v0 = vec![32000u16, 32001u16, 32002u16]; - let mut v1 = vec![0u16, 0u16, 0u16]; - - copy_memory(v1.as_mut_ptr().offset(1), - v0.as_ptr().offset(1), 1); - assert!((*v1.get(0) == 0u16 && - *v1.get(1) == 32001u16 && - *v1.get(2) == 0u16)); - copy_memory(v1.as_mut_ptr(), - v0.as_ptr().offset(2), 1); - assert!((*v1.get(0) == 32002u16 && - *v1.get(1) == 32001u16 && - *v1.get(2) == 0u16)); - copy_memory(v1.as_mut_ptr().offset(2), - v0.as_ptr(), 1u); - assert!((*v1.get(0) == 32002u16 && - *v1.get(1) == 32001u16 && - *v1.get(2) == 32000u16)); - } - } - - #[test] - fn test_position() { - use libc::c_char; - - "hello".with_c_str(|p| { - unsafe { - assert!(2u == position(p, |c| *c == 'l' as c_char)); - assert!(4u == position(p, |c| *c == 'o' as c_char)); - assert!(5u == position(p, |c| *c == 0 as c_char)); - } - }) - } - - #[test] - fn test_buf_len() { - "hello".with_c_str(|p0| { - "there".with_c_str(|p1| { - "thing".with_c_str(|p2| { - let v = vec![p0, p1, p2, null()]; - unsafe { - assert_eq!(buf_len(v.as_ptr()), 3u); - } - }) - }) - }) - } - - #[test] - fn test_is_null() { - let p: *const int = null(); - assert!(p.is_null()); - assert!(!p.is_not_null()); - - let q = unsafe { p.offset(1) }; - assert!(!q.is_null()); - assert!(q.is_not_null()); - - let mp: *mut int = mut_null(); - assert!(mp.is_null()); - assert!(!mp.is_not_null()); - - let mq = unsafe { mp.offset(1) }; - assert!(!mq.is_null()); - assert!(mq.is_not_null()); - } - - #[test] - fn test_to_option() { - unsafe { - let p: *const int = null(); - assert_eq!(p.to_option(), None); - - let q: *const int = &2; - assert_eq!(q.to_option().unwrap(), &2); - - let p: *mut int = mut_null(); - assert_eq!(p.to_option(), None); - - let q: *mut int = &mut 2; - assert_eq!(q.to_option().unwrap(), &2); - } - } - - #[test] - fn test_ptr_addition() { - unsafe { - let xs = Vec::from_elem(16, 5i); - let mut ptr = xs.as_ptr(); - let end = ptr.offset(16); - - while ptr < end { - assert_eq!(*ptr, 5); - ptr = ptr.offset(1); - } - - let mut xs_mut = xs; - let mut m_ptr = xs_mut.as_mut_ptr(); - let m_end = m_ptr.offset(16); - - while m_ptr < m_end { - *m_ptr += 5; - m_ptr = m_ptr.offset(1); - } - - assert!(xs_mut == Vec::from_elem(16, 10i)); - } - } - - #[test] - fn test_ptr_subtraction() { - unsafe { - let xs = vec![0,1,2,3,4,5,6,7,8,9]; - let mut idx = 9i8; - let ptr = xs.as_ptr(); - - while idx >= 0i8 { - assert_eq!(*(ptr.offset(idx as int)), idx as int); - idx = idx - 1i8; - } - - let mut xs_mut = xs; - let m_start = xs_mut.as_mut_ptr(); - let mut m_ptr = m_start.offset(9); - - while m_ptr >= m_start { - *m_ptr += *m_ptr; - m_ptr = m_ptr.offset(-1); - } - - assert!(xs_mut == vec![0,2,4,6,8,10,12,14,16,18]); - } - } - - #[test] - fn test_ptr_array_each_with_len() { - unsafe { - let one = "oneOne".to_c_str(); - let two = "twoTwo".to_c_str(); - let three = "threeThree".to_c_str(); - let arr = vec![ - one.as_ptr(), - two.as_ptr(), - three.as_ptr() - ]; - let expected_arr = [ - one, two, three - ]; - - let mut ctr = 0; - let mut iteration_count = 0; - array_each_with_len(arr.as_ptr(), arr.len(), |e| { - let actual = str::raw::from_c_str(e); - let expected = str::raw::from_c_str(expected_arr[ctr].as_ptr()); - assert_eq!(actual.as_slice(), expected.as_slice()); - ctr += 1; - iteration_count += 1; - }); - assert_eq!(iteration_count, 3u); - } - } - - #[test] - fn test_ptr_array_each() { - unsafe { - let one = "oneOne".to_c_str(); - let two = "twoTwo".to_c_str(); - let three = "threeThree".to_c_str(); - let arr = vec![ - one.as_ptr(), - two.as_ptr(), - three.as_ptr(), - // fake a null terminator - null() - ]; - let expected_arr = [ - one, two, three - ]; - - let arr_ptr = arr.as_ptr(); - let mut ctr = 0u; - let mut iteration_count = 0u; - array_each(arr_ptr, |e| { - let actual = str::raw::from_c_str(e); - let expected = str::raw::from_c_str(expected_arr[ctr].as_ptr()); - assert_eq!(actual.as_slice(), expected.as_slice()); - ctr += 1; - iteration_count += 1; - }); - assert_eq!(iteration_count, 3); - } - } - - #[test] - #[should_fail] - fn test_ptr_array_each_with_len_null_ptr() { - unsafe { - array_each_with_len(0 as *const *const libc::c_char, 1, |e| { - str::raw::from_c_str(e); - }); - } - } - #[test] - #[should_fail] - fn test_ptr_array_each_null_ptr() { - unsafe { - array_each(0 as *const *const libc::c_char, |e| { - str::raw::from_c_str(e); - }); - } - } - - #[test] - fn test_set_memory() { - let mut xs = [0u8, ..20]; - let ptr = xs.as_mut_ptr(); - unsafe { set_memory(ptr, 5u8, xs.len()); } - assert!(xs == [5u8, ..20]); - } -} diff --git a/src/libcore/raw.rs b/src/libcore/raw.rs index f32e6bd9c7cc5..da9fab0fc6f50 100644 --- a/src/libcore/raw.rs +++ b/src/libcore/raw.rs @@ -70,32 +70,3 @@ pub trait Repr { impl<'a, T> Repr> for &'a [T] {} impl<'a> Repr> for &'a str {} -#[cfg(test)] -mod tests { - use super::*; - - use mem; - - #[test] - fn synthesize_closure() { - unsafe { - let x = 10; - let f: |int| -> int = |y| x + y; - - assert_eq!(f(20), 30); - - let original_closure: Closure = mem::transmute(f); - - let actual_function_pointer = original_closure.code; - let environment = original_closure.env; - - let new_closure = Closure { - code: actual_function_pointer, - env: environment - }; - - let new_f: |int| -> int = mem::transmute(new_closure); - assert_eq!(new_f(20), 30); - } - } -} diff --git a/src/libcore/result.rs b/src/libcore/result.rs index 6c163b7919920..a104d20f4e5aa 100644 --- a/src/libcore/result.rs +++ b/src/libcore/result.rs @@ -635,166 +635,3 @@ pub fn fold>>(iterator: Iter) -> Result<(),E> { fold(iterator, (), |_, _| ()) } - -///////////////////////////////////////////////////////////////////////////// -// Tests -///////////////////////////////////////////////////////////////////////////// - -#[cfg(test)] -mod tests { - use realstd::vec::Vec; - - use result::{collect, fold, fold_}; - use prelude::*; - use realstd::str::Str; - use iter::range; - - pub fn op1() -> Result { Ok(666) } - pub fn op2() -> Result { Err("sadface") } - - #[test] - pub fn test_and() { - assert_eq!(op1().and(Ok(667i)).unwrap(), 667); - assert_eq!(op1().and(Err::<(), &'static str>("bad")).unwrap_err(), - "bad"); - - assert_eq!(op2().and(Ok(667i)).unwrap_err(), "sadface"); - assert_eq!(op2().and(Err::<(),&'static str>("bad")).unwrap_err(), - "sadface"); - } - - #[test] - pub fn test_and_then() { - assert_eq!(op1().and_then(|i| Ok::(i + 1)).unwrap(), 667); - assert_eq!(op1().and_then(|_| Err::("bad")).unwrap_err(), - "bad"); - - assert_eq!(op2().and_then(|i| Ok::(i + 1)).unwrap_err(), - "sadface"); - assert_eq!(op2().and_then(|_| Err::("bad")).unwrap_err(), - "sadface"); - } - - #[test] - pub fn test_or() { - assert_eq!(op1().or(Ok(667)).unwrap(), 666); - assert_eq!(op1().or(Err("bad")).unwrap(), 666); - - assert_eq!(op2().or(Ok(667)).unwrap(), 667); - assert_eq!(op2().or(Err("bad")).unwrap_err(), "bad"); - } - - #[test] - pub fn test_or_else() { - assert_eq!(op1().or_else(|_| Ok::(667)).unwrap(), 666); - assert_eq!(op1().or_else(|e| Err::(e)).unwrap(), 666); - - assert_eq!(op2().or_else(|_| Ok::(667)).unwrap(), 667); - assert_eq!(op2().or_else(|e| Err::(e)).unwrap_err(), - "sadface"); - } - - #[test] - pub fn test_impl_map() { - assert!(Ok::(1).map(|x| x + 1) == Ok(2)); - assert!(Err::(1).map(|x| x + 1) == Err(1)); - } - - #[test] - pub fn test_impl_map_err() { - assert!(Ok::(1).map_err(|x| x + 1) == Ok(1)); - assert!(Err::(1).map_err(|x| x + 1) == Err(2)); - } - - #[test] - fn test_collect() { - let v: Result, ()> = collect(range(0i, 0).map(|_| Ok::(0))); - assert!(v == Ok(vec![])); - - let v: Result, ()> = collect(range(0i, 3).map(|x| Ok::(x))); - assert!(v == Ok(vec![0, 1, 2])); - - let v: Result, int> = collect(range(0i, 3) - .map(|x| if x > 1 { Err(x) } else { Ok(x) })); - assert!(v == Err(2)); - - // test that it does not take more elements than it needs - let mut functions = [|| Ok(()), || Err(1i), || fail!()]; - - let v: Result, int> = collect(functions.mut_iter().map(|f| (*f)())); - assert!(v == Err(1)); - } - - #[test] - fn test_fold() { - assert_eq!(fold_(range(0i, 0) - .map(|_| Ok::<(), ()>(()))), - Ok(())); - assert_eq!(fold(range(0i, 3) - .map(|x| Ok::(x)), - 0, |a, b| a + b), - Ok(3)); - assert_eq!(fold_(range(0i, 3) - .map(|x| if x > 1 { Err(x) } else { Ok(()) })), - Err(2)); - - // test that it does not take more elements than it needs - let mut functions = [|| Ok(()), || Err(1i), || fail!()]; - - assert_eq!(fold_(functions.mut_iter() - .map(|f| (*f)())), - Err(1)); - } - - #[test] - pub fn test_fmt_default() { - let ok: Result = Ok(100); - let err: Result = Err("Err"); - - let s = format!("{}", ok); - assert_eq!(s.as_slice(), "Ok(100)"); - let s = format!("{}", err); - assert_eq!(s.as_slice(), "Err(Err)"); - } - - #[test] - pub fn test_unwrap_or() { - let ok: Result = Ok(100i); - let ok_err: Result = Err("Err"); - - assert_eq!(ok.unwrap_or(50), 100); - assert_eq!(ok_err.unwrap_or(50), 50); - } - - #[test] - pub fn test_unwrap_or_else() { - fn handler(msg: &'static str) -> int { - if msg == "I got this." { - 50i - } else { - fail!("BadBad") - } - } - - let ok: Result = Ok(100); - let ok_err: Result = Err("I got this."); - - assert_eq!(ok.unwrap_or_else(handler), 100); - assert_eq!(ok_err.unwrap_or_else(handler), 50); - } - - #[test] - #[should_fail] - pub fn test_unwrap_or_else_failure() { - fn handler(msg: &'static str) -> int { - if msg == "I got this." { - 50i - } else { - fail!("BadBad") - } - } - - let bad_err: Result = Err("Unrecoverable mess."); - let _ : int = bad_err.unwrap_or_else(handler); - } -} diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index fea7986eee595..6340633410374 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -246,7 +246,6 @@ impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> { // Equality -#[cfg(not(test))] #[allow(missing_doc)] pub mod traits { use super::*; @@ -298,9 +297,6 @@ pub mod traits { } } -#[cfg(test)] -pub mod traits {} - /// Any vector that can be represented as a slice. pub trait Vector { /// Work with `self` as a slice. diff --git a/src/libcore/str.rs b/src/libcore/str.rs index 0d4b5f590742b..21de4cdf59fb1 100644 --- a/src/libcore/str.rs +++ b/src/libcore/str.rs @@ -579,20 +579,12 @@ fn eq_slice_(a: &str, b: &str) -> bool { /// Bytewise slice equality /// NOTE: This function is (ab)used in rustc::middle::trans::_match /// to compare &[u8] byte slices that are not necessarily valid UTF-8. -#[cfg(not(test))] #[lang="str_eq"] #[inline] pub fn eq_slice(a: &str, b: &str) -> bool { eq_slice_(a, b) } -/// Bytewise slice equality -#[cfg(test)] -#[inline] -pub fn eq_slice(a: &str, b: &str) -> bool { - eq_slice_(a, b) -} - /* Section: Misc */ @@ -934,7 +926,6 @@ pub mod raw { Section: Trait implementations */ -#[cfg(not(test))] #[allow(missing_doc)] pub mod traits { use cmp::{Ord, Ordering, Less, Equal, Greater, PartialEq, PartialOrd, Equiv, Eq}; @@ -980,9 +971,6 @@ pub mod traits { } } -#[cfg(test)] -pub mod traits {} - /// Any string that can be represented as a slice pub trait Str { /// Work with `self` as a slice. diff --git a/src/libcore/tuple.rs b/src/libcore/tuple.rs index 3508da5d51628..f44bce3354712 100644 --- a/src/libcore/tuple.rs +++ b/src/libcore/tuple.rs @@ -62,8 +62,8 @@ #![doc(primitive = "tuple")] use clone::Clone; -#[cfg(not(test))] use cmp::*; -#[cfg(not(test))] use default::Default; +use cmp::*; +use default::Default; // macro for implementing n-ary tuple functions and operations macro_rules! tuple_impls { @@ -111,7 +111,6 @@ macro_rules! tuple_impls { } } - #[cfg(not(test))] impl<$($T:PartialEq),+> PartialEq for ($($T,)+) { #[inline] fn eq(&self, other: &($($T,)+)) -> bool { @@ -123,10 +122,8 @@ macro_rules! tuple_impls { } } - #[cfg(not(test))] impl<$($T:Eq),+> Eq for ($($T,)+) {} - #[cfg(not(test))] impl<$($T:PartialOrd + PartialEq),+> PartialOrd for ($($T,)+) { #[inline] fn lt(&self, other: &($($T,)+)) -> bool { @@ -146,7 +143,6 @@ macro_rules! tuple_impls { } } - #[cfg(not(test))] impl<$($T:Ord),+> Ord for ($($T,)+) { #[inline] fn cmp(&self, other: &($($T,)+)) -> Ordering { @@ -154,7 +150,6 @@ macro_rules! tuple_impls { } } - #[cfg(not(test))] impl<$($T:Default),+> Default for ($($T,)+) { #[inline] fn default() -> ($($T,)+) { @@ -292,93 +287,3 @@ tuple_impls! { } } -#[cfg(test)] -mod tests { - use super::*; - use clone::Clone; - use cmp::*; - use realstd::str::Str; - - #[test] - fn test_clone() { - let a = (1i, "2"); - let b = a.clone(); - assert_eq!(a, b); - } - - #[test] - fn test_getters() { - macro_rules! test_getter( - ($x:expr, $valN:ident, $refN:ident, $mutN:ident, - $init:expr, $incr:expr, $result:expr) => ({ - assert_eq!($x.$valN(), $init); - assert_eq!(*$x.$refN(), $init); - *$x.$mutN() += $incr; - assert_eq!(*$x.$refN(), $result); - }) - ) - let mut x = (0u8, 1u16, 2u32, 3u64, 4u, 5i8, 6i16, 7i32, 8i64, 9i, 10f32, 11f64); - test_getter!(x, val0, ref0, mut0, 0, 1, 1); - test_getter!(x, val1, ref1, mut1, 1, 1, 2); - test_getter!(x, val2, ref2, mut2, 2, 1, 3); - test_getter!(x, val3, ref3, mut3, 3, 1, 4); - test_getter!(x, val4, ref4, mut4, 4, 1, 5); - test_getter!(x, val5, ref5, mut5, 5, 1, 6); - test_getter!(x, val6, ref6, mut6, 6, 1, 7); - test_getter!(x, val7, ref7, mut7, 7, 1, 8); - test_getter!(x, val8, ref8, mut8, 8, 1, 9); - test_getter!(x, val9, ref9, mut9, 9, 1, 10); - test_getter!(x, val10, ref10, mut10, 10.0, 1.0, 11.0); - test_getter!(x, val11, ref11, mut11, 11.0, 1.0, 12.0); - } - - #[test] - fn test_tuple_cmp() { - let (small, big) = ((1u, 2u, 3u), (3u, 2u, 1u)); - - let nan = 0.0f64/0.0; - - // PartialEq - assert_eq!(small, small); - assert_eq!(big, big); - assert!(small != big); - assert!(big != small); - - // PartialOrd - assert!(small < big); - assert!(!(small < small)); - assert!(!(big < small)); - assert!(!(big < big)); - - assert!(small <= small); - assert!(big <= big); - - assert!(big > small); - assert!(small >= small); - assert!(big >= small); - assert!(big >= big); - - assert!(!((1.0f64, 2.0f64) < (nan, 3.0))); - assert!(!((1.0f64, 2.0f64) <= (nan, 3.0))); - assert!(!((1.0f64, 2.0f64) > (nan, 3.0))); - assert!(!((1.0f64, 2.0f64) >= (nan, 3.0))); - assert!(((1.0f64, 2.0f64) < (2.0, nan))); - assert!(!((2.0f64, 2.0f64) < (2.0, nan))); - - // Ord - assert!(small.cmp(&small) == Equal); - assert!(big.cmp(&big) == Equal); - assert!(small.cmp(&big) == Less); - assert!(big.cmp(&small) == Greater); - } - - #[test] - fn test_show() { - let s = format!("{}", (1i,)); - assert_eq!(s.as_slice(), "(1,)"); - let s = format!("{}", (1i, true)); - assert_eq!(s.as_slice(), "(1, true)"); - let s = format!("{}", (1i, "hi", true)); - assert_eq!(s.as_slice(), "(1, hi, true)"); - } -} diff --git a/src/libcoretest/any.rs b/src/libcoretest/any.rs new file mode 100644 index 0000000000000..fae4a26cd3863 --- /dev/null +++ b/src/libcoretest/any.rs @@ -0,0 +1,131 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +use core::any::*; +use test::Bencher; +use test; + +#[deriving(PartialEq, Show)] +struct Test; + +static TEST: &'static str = "Test"; + +#[test] +fn any_referenced() { + let (a, b, c) = (&5u as &Any, &TEST as &Any, &Test as &Any); + + assert!(a.is::()); + assert!(!b.is::()); + assert!(!c.is::()); + + assert!(!a.is::<&'static str>()); + assert!(b.is::<&'static str>()); + assert!(!c.is::<&'static str>()); + + assert!(!a.is::()); + assert!(!b.is::()); + assert!(c.is::()); +} + +#[test] +fn any_owning() { + let (a, b, c) = (box 5u as Box, box TEST as Box, box Test as Box); + + assert!(a.is::()); + assert!(!b.is::()); + assert!(!c.is::()); + + assert!(!a.is::<&'static str>()); + assert!(b.is::<&'static str>()); + assert!(!c.is::<&'static str>()); + + assert!(!a.is::()); + assert!(!b.is::()); + assert!(c.is::()); +} + +#[test] +fn any_as_ref() { + let a = &5u as &Any; + + match a.as_ref::() { + Some(&5) => {} + x => fail!("Unexpected value {}", x) + } + + match a.as_ref::() { + None => {} + x => fail!("Unexpected value {}", x) + } +} + +#[test] +fn any_as_mut() { + let mut a = 5u; + let mut b = box 7u; + + let a_r = &mut a as &mut Any; + let tmp: &mut uint = &mut *b; + let b_r = tmp as &mut Any; + + match a_r.as_mut::() { + Some(x) => { + assert_eq!(*x, 5u); + *x = 612; + } + x => fail!("Unexpected value {}", x) + } + + match b_r.as_mut::() { + Some(x) => { + assert_eq!(*x, 7u); + *x = 413; + } + x => fail!("Unexpected value {}", x) + } + + match a_r.as_mut::() { + None => (), + x => fail!("Unexpected value {}", x) + } + + match b_r.as_mut::() { + None => (), + x => fail!("Unexpected value {}", x) + } + + match a_r.as_mut::() { + Some(&612) => {} + x => fail!("Unexpected value {}", x) + } + + match b_r.as_mut::() { + Some(&413) => {} + x => fail!("Unexpected value {}", x) + } +} + +#[test] +fn any_fixed_vec() { + let test = [0u, ..8]; + let test = &test as &Any; + assert!(test.is::<[uint, ..8]>()); + assert!(!test.is::<[uint, ..10]>()); +} + + +#[bench] +fn bench_as_ref(b: &mut Bencher) { + b.iter(|| { + let mut x = 0i; + let mut y = &mut x as &mut Any; + test::black_box(&mut y); + test::black_box(y.as_ref::() == Some(&0)); + }); +} diff --git a/src/libcoretest/atomics.rs b/src/libcoretest/atomics.rs new file mode 100644 index 0000000000000..3f960ae1f267f --- /dev/null +++ b/src/libcoretest/atomics.rs @@ -0,0 +1,83 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::atomics::*; + +#[test] +fn bool_() { + let a = AtomicBool::new(false); + assert_eq!(a.compare_and_swap(false, true, SeqCst), false); + assert_eq!(a.compare_and_swap(false, true, SeqCst), true); + + a.store(false, SeqCst); + assert_eq!(a.compare_and_swap(false, true, SeqCst), false); +} + +#[test] +fn bool_and() { + let a = AtomicBool::new(true); + assert_eq!(a.fetch_and(false, SeqCst),true); + assert_eq!(a.load(SeqCst),false); +} + +#[test] +fn uint_and() { + let x = AtomicUint::new(0xf731); + assert_eq!(x.fetch_and(0x137f, SeqCst), 0xf731); + assert_eq!(x.load(SeqCst), 0xf731 & 0x137f); +} + +#[test] +fn uint_or() { + let x = AtomicUint::new(0xf731); + assert_eq!(x.fetch_or(0x137f, SeqCst), 0xf731); + assert_eq!(x.load(SeqCst), 0xf731 | 0x137f); +} + +#[test] +fn uint_xor() { + let x = AtomicUint::new(0xf731); + assert_eq!(x.fetch_xor(0x137f, SeqCst), 0xf731); + assert_eq!(x.load(SeqCst), 0xf731 ^ 0x137f); +} + +#[test] +fn int_and() { + let x = AtomicInt::new(0xf731); + assert_eq!(x.fetch_and(0x137f, SeqCst), 0xf731); + assert_eq!(x.load(SeqCst), 0xf731 & 0x137f); +} + +#[test] +fn int_or() { + let x = AtomicInt::new(0xf731); + assert_eq!(x.fetch_or(0x137f, SeqCst), 0xf731); + assert_eq!(x.load(SeqCst), 0xf731 | 0x137f); +} + +#[test] +fn int_xor() { + let x = AtomicInt::new(0xf731); + assert_eq!(x.fetch_xor(0x137f, SeqCst), 0xf731); + assert_eq!(x.load(SeqCst), 0xf731 ^ 0x137f); +} + +static mut S_BOOL : AtomicBool = INIT_ATOMIC_BOOL; +static mut S_INT : AtomicInt = INIT_ATOMIC_INT; +static mut S_UINT : AtomicUint = INIT_ATOMIC_UINT; + +#[test] +fn static_init() { + unsafe { + assert!(!S_BOOL.load(SeqCst)); + assert!(S_INT.load(SeqCst) == 0); + assert!(S_UINT.load(SeqCst) == 0); + } +} diff --git a/src/libcoretest/cell.rs b/src/libcoretest/cell.rs new file mode 100644 index 0000000000000..b3ae110363cb5 --- /dev/null +++ b/src/libcoretest/cell.rs @@ -0,0 +1,129 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::cell::*; +use std::mem::drop; + +#[test] +fn smoketest_cell() { + let x = Cell::new(10i); + assert!(x == Cell::new(10)); + assert!(x.get() == 10); + x.set(20); + assert!(x == Cell::new(20)); + assert!(x.get() == 20); + + let y = Cell::new((30i, 40i)); + assert!(y == Cell::new((30, 40))); + assert!(y.get() == (30, 40)); +} + +#[test] +fn cell_has_sensible_show() { + let x = Cell::new("foo bar"); + assert!(format!("{}", x).as_slice().contains(x.get())); + + x.set("baz qux"); + assert!(format!("{}", x).as_slice().contains(x.get())); +} + +#[test] +fn ref_and_refmut_have_sensible_show() { + let refcell = RefCell::new("foo"); + + let refcell_refmut = refcell.borrow_mut(); + assert!(format!("{}", refcell_refmut).as_slice().contains("foo")); + drop(refcell_refmut); + + let refcell_ref = refcell.borrow(); + assert!(format!("{}", refcell_ref).as_slice().contains("foo")); + drop(refcell_ref); +} + +#[test] +fn double_imm_borrow() { + let x = RefCell::new(0i); + let _b1 = x.borrow(); + x.borrow(); +} + +#[test] +fn no_mut_then_imm_borrow() { + let x = RefCell::new(0i); + let _b1 = x.borrow_mut(); + assert!(x.try_borrow().is_none()); +} + +#[test] +fn no_imm_then_borrow_mut() { + let x = RefCell::new(0i); + let _b1 = x.borrow(); + assert!(x.try_borrow_mut().is_none()); +} + +#[test] +fn no_double_borrow_mut() { + let x = RefCell::new(0i); + let _b1 = x.borrow_mut(); + assert!(x.try_borrow_mut().is_none()); +} + +#[test] +fn imm_release_borrow_mut() { + let x = RefCell::new(0i); + { + let _b1 = x.borrow(); + } + x.borrow_mut(); +} + +#[test] +fn mut_release_borrow_mut() { + let x = RefCell::new(0i); + { + let _b1 = x.borrow_mut(); + } + x.borrow(); +} + +#[test] +fn double_borrow_single_release_no_borrow_mut() { + let x = RefCell::new(0i); + let _b1 = x.borrow(); + { + let _b2 = x.borrow(); + } + assert!(x.try_borrow_mut().is_none()); +} + +#[test] +#[should_fail] +fn discard_doesnt_unborrow() { + let x = RefCell::new(0i); + let _b = x.borrow(); + let _ = _b; + let _b = x.borrow_mut(); +} + +#[test] +#[allow(experimental)] +fn clone_ref_updates_flag() { + let x = RefCell::new(0i); + { + let b1 = x.borrow(); + assert!(x.try_borrow_mut().is_none()); + { + let _b2 = clone_ref(&b1); + assert!(x.try_borrow_mut().is_none()); + } + assert!(x.try_borrow_mut().is_none()); + } + assert!(x.try_borrow_mut().is_some()); +} diff --git a/src/libcoretest/char.rs b/src/libcoretest/char.rs new file mode 100644 index 0000000000000..852edd90b0f3f --- /dev/null +++ b/src/libcoretest/char.rs @@ -0,0 +1,202 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::char::{escape_unicode, escape_default}; + +#[test] +fn test_is_lowercase() { + assert!('a'.is_lowercase()); + assert!('ö'.is_lowercase()); + assert!('ß'.is_lowercase()); + assert!(!'Ü'.is_lowercase()); + assert!(!'P'.is_lowercase()); +} + +#[test] +fn test_is_uppercase() { + assert!(!'h'.is_uppercase()); + assert!(!'ä'.is_uppercase()); + assert!(!'ß'.is_uppercase()); + assert!('Ö'.is_uppercase()); + assert!('T'.is_uppercase()); +} + +#[test] +fn test_is_whitespace() { + assert!(' '.is_whitespace()); + assert!('\u2007'.is_whitespace()); + assert!('\t'.is_whitespace()); + assert!('\n'.is_whitespace()); + assert!(!'a'.is_whitespace()); + assert!(!'_'.is_whitespace()); + assert!(!'\u0000'.is_whitespace()); +} + +#[test] +fn test_to_digit() { + assert_eq!('0'.to_digit(10u), Some(0u)); + assert_eq!('1'.to_digit(2u), Some(1u)); + assert_eq!('2'.to_digit(3u), Some(2u)); + assert_eq!('9'.to_digit(10u), Some(9u)); + assert_eq!('a'.to_digit(16u), Some(10u)); + assert_eq!('A'.to_digit(16u), Some(10u)); + assert_eq!('b'.to_digit(16u), Some(11u)); + assert_eq!('B'.to_digit(16u), Some(11u)); + assert_eq!('z'.to_digit(36u), Some(35u)); + assert_eq!('Z'.to_digit(36u), Some(35u)); + assert_eq!(' '.to_digit(10u), None); + assert_eq!('$'.to_digit(36u), None); +} + +#[test] +fn test_to_lowercase() { + assert_eq!('A'.to_lowercase(), 'a'); + assert_eq!('Ö'.to_lowercase(), 'ö'); + assert_eq!('ß'.to_lowercase(), 'ß'); + assert_eq!('Ü'.to_lowercase(), 'ü'); + assert_eq!('💩'.to_lowercase(), '💩'); + assert_eq!('Σ'.to_lowercase(), 'σ'); + assert_eq!('Τ'.to_lowercase(), 'τ'); + assert_eq!('Ι'.to_lowercase(), 'ι'); + assert_eq!('Γ'.to_lowercase(), 'γ'); + assert_eq!('Μ'.to_lowercase(), 'μ'); + assert_eq!('Α'.to_lowercase(), 'α'); + assert_eq!('Σ'.to_lowercase(), 'σ'); +} + +#[test] +fn test_to_uppercase() { + assert_eq!('a'.to_uppercase(), 'A'); + assert_eq!('ö'.to_uppercase(), 'Ö'); + assert_eq!('ß'.to_uppercase(), 'ß'); // not ẞ: Latin capital letter sharp s + assert_eq!('ü'.to_uppercase(), 'Ü'); + assert_eq!('💩'.to_uppercase(), '💩'); + + assert_eq!('σ'.to_uppercase(), 'Σ'); + assert_eq!('τ'.to_uppercase(), 'Τ'); + assert_eq!('ι'.to_uppercase(), 'Ι'); + assert_eq!('γ'.to_uppercase(), 'Γ'); + assert_eq!('μ'.to_uppercase(), 'Μ'); + assert_eq!('α'.to_uppercase(), 'Α'); + assert_eq!('ς'.to_uppercase(), 'Σ'); +} + +#[test] +fn test_is_control() { + assert!('\u0000'.is_control()); + assert!('\u0003'.is_control()); + assert!('\u0006'.is_control()); + assert!('\u0009'.is_control()); + assert!('\u007f'.is_control()); + assert!('\u0092'.is_control()); + assert!(!'\u0020'.is_control()); + assert!(!'\u0055'.is_control()); + assert!(!'\u0068'.is_control()); +} + +#[test] +fn test_is_digit() { + assert!('2'.is_digit()); + assert!('7'.is_digit()); + assert!(!'c'.is_digit()); + assert!(!'i'.is_digit()); + assert!(!'z'.is_digit()); + assert!(!'Q'.is_digit()); +} + +#[test] +fn test_escape_default() { + fn string(c: char) -> String { + let mut result = String::new(); + escape_default(c, |c| { result.push_char(c); }); + return result; + } + let s = string('\n'); + assert_eq!(s.as_slice(), "\\n"); + let s = string('\r'); + assert_eq!(s.as_slice(), "\\r"); + let s = string('\''); + assert_eq!(s.as_slice(), "\\'"); + let s = string('"'); + assert_eq!(s.as_slice(), "\\\""); + let s = string(' '); + assert_eq!(s.as_slice(), " "); + let s = string('a'); + assert_eq!(s.as_slice(), "a"); + let s = string('~'); + assert_eq!(s.as_slice(), "~"); + let s = string('\x00'); + assert_eq!(s.as_slice(), "\\x00"); + let s = string('\x1f'); + assert_eq!(s.as_slice(), "\\x1f"); + let s = string('\x7f'); + assert_eq!(s.as_slice(), "\\x7f"); + let s = string('\xff'); + assert_eq!(s.as_slice(), "\\xff"); + let s = string('\u011b'); + assert_eq!(s.as_slice(), "\\u011b"); + let s = string('\U0001d4b6'); + assert_eq!(s.as_slice(), "\\U0001d4b6"); +} + +#[test] +fn test_escape_unicode() { + fn string(c: char) -> String { + let mut result = String::new(); + escape_unicode(c, |c| { result.push_char(c); }); + return result; + } + let s = string('\x00'); + assert_eq!(s.as_slice(), "\\x00"); + let s = string('\n'); + assert_eq!(s.as_slice(), "\\x0a"); + let s = string(' '); + assert_eq!(s.as_slice(), "\\x20"); + let s = string('a'); + assert_eq!(s.as_slice(), "\\x61"); + let s = string('\u011b'); + assert_eq!(s.as_slice(), "\\u011b"); + let s = string('\U0001d4b6'); + assert_eq!(s.as_slice(), "\\U0001d4b6"); +} + +#[test] +fn test_to_str() { + let s = 't'.to_str(); + assert_eq!(s.as_slice(), "t"); +} + +#[test] +fn test_encode_utf8() { + fn check(input: char, expect: &[u8]) { + let mut buf = [0u8, ..4]; + let n = input.encode_utf8(buf /* as mut slice! */); + assert_eq!(buf.slice_to(n), expect); + } + + check('x', [0x78]); + check('\u00e9', [0xc3, 0xa9]); + check('\ua66e', [0xea, 0x99, 0xae]); + check('\U0001f4a9', [0xf0, 0x9f, 0x92, 0xa9]); +} + +#[test] +fn test_encode_utf16() { + fn check(input: char, expect: &[u16]) { + let mut buf = [0u16, ..2]; + let n = input.encode_utf16(buf /* as mut slice! */); + assert_eq!(buf.slice_to(n), expect); + } + + check('x', [0x0078]); + check('\u00e9', [0x00e9]); + check('\ua66e', [0xa66e]); + check('\U0001f4a9', [0xd83d, 0xdca9]); +} diff --git a/src/libcoretest/clone.rs b/src/libcoretest/clone.rs new file mode 100644 index 0000000000000..67c30d945d497 --- /dev/null +++ b/src/libcoretest/clone.rs @@ -0,0 +1,39 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[test] +fn test_borrowed_clone() { + let x = 5i; + let y: &int = &x; + let z: &int = (&y).clone(); + assert_eq!(*z, 5); +} + +#[test] +fn test_clone_from() { + let a = box 5i; + let mut b = box 10i; + b.clone_from(&a); + assert_eq!(*b, 5); +} + +#[test] +fn test_extern_fn_clone() { + trait Empty {} + impl Empty for int {} + + fn test_fn_a() -> f64 { 1.0 } + fn test_fn_b(x: T) -> T { x } + fn test_fn_c(_: int, _: f64, _: int, _: int, _: int) {} + + let _ = test_fn_a.clone(); + let _ = test_fn_b::.clone(); + let _ = test_fn_c.clone(); +} diff --git a/src/libcoretest/cmp.rs b/src/libcoretest/cmp.rs new file mode 100644 index 0000000000000..88e944be3e860 --- /dev/null +++ b/src/libcoretest/cmp.rs @@ -0,0 +1,69 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::cmp::lexical_ordering; + +#[test] +fn test_int_totalord() { + assert_eq!(5i.cmp(&10), Less); + assert_eq!(10i.cmp(&5), Greater); + assert_eq!(5i.cmp(&5), Equal); + assert_eq!((-5i).cmp(&12), Less); + assert_eq!(12i.cmp(&-5), Greater); +} + +#[test] +fn test_mut_int_totalord() { + assert_eq!((&mut 5i).cmp(&&mut 10), Less); + assert_eq!((&mut 10i).cmp(&&mut 5), Greater); + assert_eq!((&mut 5i).cmp(&&mut 5), Equal); + assert_eq!((&mut -5i).cmp(&&mut 12), Less); + assert_eq!((&mut 12i).cmp(&&mut -5), Greater); +} + +#[test] +fn test_ordering_order() { + assert!(Less < Equal); + assert_eq!(Greater.cmp(&Less), Greater); +} + +#[test] +fn test_lexical_ordering() { + fn t(o1: Ordering, o2: Ordering, e: Ordering) { + assert_eq!(lexical_ordering(o1, o2), e); + } + + let xs = [Less, Equal, Greater]; + for &o in xs.iter() { + t(Less, o, Less); + t(Equal, o, o); + t(Greater, o, Greater); + } +} + +#[test] +fn test_user_defined_eq() { + // Our type. + struct SketchyNum { + num : int + } + + // Our implementation of `PartialEq` to support `==` and `!=`. + impl PartialEq for SketchyNum { + // Our custom eq allows numbers which are near each other to be equal! :D + fn eq(&self, other: &SketchyNum) -> bool { + (self.num - other.num).abs() < 5 + } + } + + // Now these binary operators will work when applied! + assert!(SketchyNum {num: 37} == SketchyNum {num: 34}); + assert!(SketchyNum {num: 25} != SketchyNum {num: 57}); +} diff --git a/src/libcoretest/finally.rs b/src/libcoretest/finally.rs new file mode 100644 index 0000000000000..5da004086d27f --- /dev/null +++ b/src/libcoretest/finally.rs @@ -0,0 +1,59 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::finally::{try_finally, Finally}; +use std::task::failing; + +#[test] +fn test_success() { + let mut i = 0i; + try_finally( + &mut i, (), + |i, ()| { + *i = 10; + }, + |i| { + assert!(!failing()); + assert_eq!(*i, 10); + *i = 20; + }); + assert_eq!(i, 20); +} + +#[test] +#[should_fail] +fn test_fail() { + let mut i = 0i; + try_finally( + &mut i, (), + |i, ()| { + *i = 10; + fail!(); + }, + |i| { + assert!(failing()); + assert_eq!(*i, 10); + }) +} + +#[test] +fn test_retval() { + let mut closure: || -> int = || 10; + let i = closure.finally(|| { }); + assert_eq!(i, 10); +} + +#[test] +fn test_compact() { + fn do_some_fallible_work() {} + fn but_always_run_this_function() { } + let mut f = do_some_fallible_work; + f.finally(but_always_run_this_function); +} diff --git a/src/libcoretest/fmt/mod.rs b/src/libcoretest/fmt/mod.rs new file mode 100644 index 0000000000000..9fc09b3124ef3 --- /dev/null +++ b/src/libcoretest/fmt/mod.rs @@ -0,0 +1,11 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +mod num; diff --git a/src/libcoretest/fmt/num.rs b/src/libcoretest/fmt/num.rs new file mode 100644 index 0000000000000..baef7e3a11e85 --- /dev/null +++ b/src/libcoretest/fmt/num.rs @@ -0,0 +1,234 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +#![allow(unsigned_negate)] + +use core::fmt::radix; + +#[test] +fn test_format_int() { + // Formatting integers should select the right implementation based off + // the type of the argument. Also, hex/octal/binary should be defined + // for integers, but they shouldn't emit the negative sign. + assert!(format!("{}", 1i).as_slice() == "1"); + assert!(format!("{}", 1i8).as_slice() == "1"); + assert!(format!("{}", 1i16).as_slice() == "1"); + assert!(format!("{}", 1i32).as_slice() == "1"); + assert!(format!("{}", 1i64).as_slice() == "1"); + assert!(format!("{:d}", -1i).as_slice() == "-1"); + assert!(format!("{:d}", -1i8).as_slice() == "-1"); + assert!(format!("{:d}", -1i16).as_slice() == "-1"); + assert!(format!("{:d}", -1i32).as_slice() == "-1"); + assert!(format!("{:d}", -1i64).as_slice() == "-1"); + assert!(format!("{:t}", 1i).as_slice() == "1"); + assert!(format!("{:t}", 1i8).as_slice() == "1"); + assert!(format!("{:t}", 1i16).as_slice() == "1"); + assert!(format!("{:t}", 1i32).as_slice() == "1"); + assert!(format!("{:t}", 1i64).as_slice() == "1"); + assert!(format!("{:x}", 1i).as_slice() == "1"); + assert!(format!("{:x}", 1i8).as_slice() == "1"); + assert!(format!("{:x}", 1i16).as_slice() == "1"); + assert!(format!("{:x}", 1i32).as_slice() == "1"); + assert!(format!("{:x}", 1i64).as_slice() == "1"); + assert!(format!("{:X}", 1i).as_slice() == "1"); + assert!(format!("{:X}", 1i8).as_slice() == "1"); + assert!(format!("{:X}", 1i16).as_slice() == "1"); + assert!(format!("{:X}", 1i32).as_slice() == "1"); + assert!(format!("{:X}", 1i64).as_slice() == "1"); + assert!(format!("{:o}", 1i).as_slice() == "1"); + assert!(format!("{:o}", 1i8).as_slice() == "1"); + assert!(format!("{:o}", 1i16).as_slice() == "1"); + assert!(format!("{:o}", 1i32).as_slice() == "1"); + assert!(format!("{:o}", 1i64).as_slice() == "1"); + + assert!(format!("{}", 1u).as_slice() == "1"); + assert!(format!("{}", 1u8).as_slice() == "1"); + assert!(format!("{}", 1u16).as_slice() == "1"); + assert!(format!("{}", 1u32).as_slice() == "1"); + assert!(format!("{}", 1u64).as_slice() == "1"); + assert!(format!("{:u}", 1u).as_slice() == "1"); + assert!(format!("{:u}", 1u8).as_slice() == "1"); + assert!(format!("{:u}", 1u16).as_slice() == "1"); + assert!(format!("{:u}", 1u32).as_slice() == "1"); + assert!(format!("{:u}", 1u64).as_slice() == "1"); + assert!(format!("{:t}", 1u).as_slice() == "1"); + assert!(format!("{:t}", 1u8).as_slice() == "1"); + assert!(format!("{:t}", 1u16).as_slice() == "1"); + assert!(format!("{:t}", 1u32).as_slice() == "1"); + assert!(format!("{:t}", 1u64).as_slice() == "1"); + assert!(format!("{:x}", 1u).as_slice() == "1"); + assert!(format!("{:x}", 1u8).as_slice() == "1"); + assert!(format!("{:x}", 1u16).as_slice() == "1"); + assert!(format!("{:x}", 1u32).as_slice() == "1"); + assert!(format!("{:x}", 1u64).as_slice() == "1"); + assert!(format!("{:X}", 1u).as_slice() == "1"); + assert!(format!("{:X}", 1u8).as_slice() == "1"); + assert!(format!("{:X}", 1u16).as_slice() == "1"); + assert!(format!("{:X}", 1u32).as_slice() == "1"); + assert!(format!("{:X}", 1u64).as_slice() == "1"); + assert!(format!("{:o}", 1u).as_slice() == "1"); + assert!(format!("{:o}", 1u8).as_slice() == "1"); + assert!(format!("{:o}", 1u16).as_slice() == "1"); + assert!(format!("{:o}", 1u32).as_slice() == "1"); + assert!(format!("{:o}", 1u64).as_slice() == "1"); + + // Test a larger number + assert!(format!("{:t}", 55i).as_slice() == "110111"); + assert!(format!("{:o}", 55i).as_slice() == "67"); + assert!(format!("{:d}", 55i).as_slice() == "55"); + assert!(format!("{:x}", 55i).as_slice() == "37"); + assert!(format!("{:X}", 55i).as_slice() == "37"); +} + +#[test] +fn test_format_int_zero() { + assert!(format!("{}", 0i).as_slice() == "0"); + assert!(format!("{:d}", 0i).as_slice() == "0"); + assert!(format!("{:t}", 0i).as_slice() == "0"); + assert!(format!("{:o}", 0i).as_slice() == "0"); + assert!(format!("{:x}", 0i).as_slice() == "0"); + assert!(format!("{:X}", 0i).as_slice() == "0"); + + assert!(format!("{}", 0u).as_slice() == "0"); + assert!(format!("{:u}", 0u).as_slice() == "0"); + assert!(format!("{:t}", 0u).as_slice() == "0"); + assert!(format!("{:o}", 0u).as_slice() == "0"); + assert!(format!("{:x}", 0u).as_slice() == "0"); + assert!(format!("{:X}", 0u).as_slice() == "0"); +} + +#[test] +fn test_format_int_flags() { + assert!(format!("{:3d}", 1i).as_slice() == " 1"); + assert!(format!("{:>3d}", 1i).as_slice() == " 1"); + assert!(format!("{:>+3d}", 1i).as_slice() == " +1"); + assert!(format!("{:<3d}", 1i).as_slice() == "1 "); + assert!(format!("{:#d}", 1i).as_slice() == "1"); + assert!(format!("{:#x}", 10i).as_slice() == "0xa"); + assert!(format!("{:#X}", 10i).as_slice() == "0xA"); + assert!(format!("{:#5x}", 10i).as_slice() == " 0xa"); + assert!(format!("{:#o}", 10i).as_slice() == "0o12"); + assert!(format!("{:08x}", 10i).as_slice() == "0000000a"); + assert!(format!("{:8x}", 10i).as_slice() == " a"); + assert!(format!("{:<8x}", 10i).as_slice() == "a "); + assert!(format!("{:>8x}", 10i).as_slice() == " a"); + assert!(format!("{:#08x}", 10i).as_slice() == "0x00000a"); + assert!(format!("{:08d}", -10i).as_slice() == "-0000010"); + assert!(format!("{:x}", -1u8).as_slice() == "ff"); + assert!(format!("{:X}", -1u8).as_slice() == "FF"); + assert!(format!("{:t}", -1u8).as_slice() == "11111111"); + assert!(format!("{:o}", -1u8).as_slice() == "377"); + assert!(format!("{:#x}", -1u8).as_slice() == "0xff"); + assert!(format!("{:#X}", -1u8).as_slice() == "0xFF"); + assert!(format!("{:#t}", -1u8).as_slice() == "0b11111111"); + assert!(format!("{:#o}", -1u8).as_slice() == "0o377"); +} + +#[test] +fn test_format_int_sign_padding() { + assert!(format!("{:+5d}", 1i).as_slice() == " +1"); + assert!(format!("{:+5d}", -1i).as_slice() == " -1"); + assert!(format!("{:05d}", 1i).as_slice() == "00001"); + assert!(format!("{:05d}", -1i).as_slice() == "-0001"); + assert!(format!("{:+05d}", 1i).as_slice() == "+0001"); + assert!(format!("{:+05d}", -1i).as_slice() == "-0001"); +} + +#[test] +fn test_format_int_twos_complement() { + use core::{i8, i16, i32, i64}; + assert!(format!("{}", i8::MIN).as_slice() == "-128"); + assert!(format!("{}", i16::MIN).as_slice() == "-32768"); + assert!(format!("{}", i32::MIN).as_slice() == "-2147483648"); + assert!(format!("{}", i64::MIN).as_slice() == "-9223372036854775808"); +} + +#[test] +fn test_format_radix() { + assert!(format!("{:04}", radix(3i, 2)).as_slice() == "0011"); + assert!(format!("{}", radix(55i, 36)).as_slice() == "1j"); +} + +#[test] +#[should_fail] +fn test_radix_base_too_large() { + let _ = radix(55i, 37); +} + +mod uint { + use test::Bencher; + use core::fmt::radix; + use std::rand::{weak_rng, Rng}; + + #[bench] + fn format_bin(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:t}", rng.gen::()); }) + } + + #[bench] + fn format_oct(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:o}", rng.gen::()); }) + } + + #[bench] + fn format_dec(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:u}", rng.gen::()); }) + } + + #[bench] + fn format_hex(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:x}", rng.gen::()); }) + } + + #[bench] + fn format_base_36(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{}", radix(rng.gen::(), 36)); }) + } +} + +mod int { + use test::Bencher; + use core::fmt::radix; + use std::rand::{weak_rng, Rng}; + + #[bench] + fn format_bin(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:t}", rng.gen::()); }) + } + + #[bench] + fn format_oct(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:o}", rng.gen::()); }) + } + + #[bench] + fn format_dec(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:d}", rng.gen::()); }) + } + + #[bench] + fn format_hex(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:x}", rng.gen::()); }) + } + + #[bench] + fn format_base_36(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{}", radix(rng.gen::(), 36)); }) + } +} diff --git a/src/libcoretest/iter.rs b/src/libcoretest/iter.rs new file mode 100644 index 0000000000000..bc55b17b3467f --- /dev/null +++ b/src/libcoretest/iter.rs @@ -0,0 +1,835 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::iter::*; +use core::iter::order::*; +use core::uint; +use core::cmp; +use core::num; + +#[test] +fn test_lt() { + let empty: [int, ..0] = []; + let xs = [1i,2,3]; + let ys = [1i,2,0]; + + assert!(!lt(xs.iter(), ys.iter())); + assert!(!le(xs.iter(), ys.iter())); + assert!( gt(xs.iter(), ys.iter())); + assert!( ge(xs.iter(), ys.iter())); + + assert!( lt(ys.iter(), xs.iter())); + assert!( le(ys.iter(), xs.iter())); + assert!(!gt(ys.iter(), xs.iter())); + assert!(!ge(ys.iter(), xs.iter())); + + assert!( lt(empty.iter(), xs.iter())); + assert!( le(empty.iter(), xs.iter())); + assert!(!gt(empty.iter(), xs.iter())); + assert!(!ge(empty.iter(), xs.iter())); + + // Sequence with NaN + let u = [1.0f64, 2.0]; + let v = [0.0f64/0.0, 3.0]; + + assert!(!lt(u.iter(), v.iter())); + assert!(!le(u.iter(), v.iter())); + assert!(!gt(u.iter(), v.iter())); + assert!(!ge(u.iter(), v.iter())); + + let a = [0.0f64/0.0]; + let b = [1.0f64]; + let c = [2.0f64]; + + assert!(lt(a.iter(), b.iter()) == (a[0] < b[0])); + assert!(le(a.iter(), b.iter()) == (a[0] <= b[0])); + assert!(gt(a.iter(), b.iter()) == (a[0] > b[0])); + assert!(ge(a.iter(), b.iter()) == (a[0] >= b[0])); + + assert!(lt(c.iter(), b.iter()) == (c[0] < b[0])); + assert!(le(c.iter(), b.iter()) == (c[0] <= b[0])); + assert!(gt(c.iter(), b.iter()) == (c[0] > b[0])); + assert!(ge(c.iter(), b.iter()) == (c[0] >= b[0])); +} + +#[test] +fn test_multi_iter() { + let xs = [1i,2,3,4]; + let ys = [4i,3,2,1]; + assert!(eq(xs.iter(), ys.iter().rev())); + assert!(lt(xs.iter(), xs.iter().skip(2))); +} + +#[test] +fn test_counter_from_iter() { + let it = count(0i, 5).take(10); + let xs: Vec = FromIterator::from_iter(it); + assert!(xs == vec![0, 5, 10, 15, 20, 25, 30, 35, 40, 45]); +} + +#[test] +fn test_iterator_chain() { + let xs = [0u, 1, 2, 3, 4, 5]; + let ys = [30u, 40, 50, 60]; + let expected = [0, 1, 2, 3, 4, 5, 30, 40, 50, 60]; + let mut it = xs.iter().chain(ys.iter()); + let mut i = 0; + for &x in it { + assert_eq!(x, expected[i]); + i += 1; + } + assert_eq!(i, expected.len()); + + let ys = count(30u, 10).take(4); + let mut it = xs.iter().map(|&x| x).chain(ys); + let mut i = 0; + for x in it { + assert_eq!(x, expected[i]); + i += 1; + } + assert_eq!(i, expected.len()); +} + +#[test] +fn test_filter_map() { + let mut it = count(0u, 1u).take(10) + .filter_map(|x| if x % 2 == 0 { Some(x*x) } else { None }); + assert!(it.collect::>() == vec![0*0, 2*2, 4*4, 6*6, 8*8]); +} + +#[test] +fn test_iterator_enumerate() { + let xs = [0u, 1, 2, 3, 4, 5]; + let mut it = xs.iter().enumerate(); + for (i, &x) in it { + assert_eq!(i, x); + } +} + +#[test] +fn test_iterator_peekable() { + let xs = vec![0u, 1, 2, 3, 4, 5]; + let mut it = xs.iter().map(|&x|x).peekable(); + assert_eq!(it.peek().unwrap(), &0); + assert_eq!(it.next().unwrap(), 0); + assert_eq!(it.next().unwrap(), 1); + assert_eq!(it.next().unwrap(), 2); + assert_eq!(it.peek().unwrap(), &3); + assert_eq!(it.peek().unwrap(), &3); + assert_eq!(it.next().unwrap(), 3); + assert_eq!(it.next().unwrap(), 4); + assert_eq!(it.peek().unwrap(), &5); + assert_eq!(it.next().unwrap(), 5); + assert!(it.peek().is_none()); + assert!(it.next().is_none()); +} + +#[test] +fn test_iterator_take_while() { + let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19]; + let ys = [0u, 1, 2, 3, 5, 13]; + let mut it = xs.iter().take_while(|&x| *x < 15u); + let mut i = 0; + for &x in it { + assert_eq!(x, ys[i]); + i += 1; + } + assert_eq!(i, ys.len()); +} + +#[test] +fn test_iterator_skip_while() { + let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19]; + let ys = [15, 16, 17, 19]; + let mut it = xs.iter().skip_while(|&x| *x < 15u); + let mut i = 0; + for &x in it { + assert_eq!(x, ys[i]); + i += 1; + } + assert_eq!(i, ys.len()); +} + +#[test] +fn test_iterator_skip() { + let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19, 20, 30]; + let ys = [13, 15, 16, 17, 19, 20, 30]; + let mut it = xs.iter().skip(5); + let mut i = 0; + for &x in it { + assert_eq!(x, ys[i]); + i += 1; + } + assert_eq!(i, ys.len()); +} + +#[test] +fn test_iterator_take() { + let xs = [0u, 1, 2, 3, 5, 13, 15, 16, 17, 19]; + let ys = [0u, 1, 2, 3, 5]; + let mut it = xs.iter().take(5); + let mut i = 0; + for &x in it { + assert_eq!(x, ys[i]); + i += 1; + } + assert_eq!(i, ys.len()); +} + +#[test] +fn test_iterator_scan() { + // test the type inference + fn add(old: &mut int, new: &uint) -> Option { + *old += *new as int; + Some(*old as f64) + } + let xs = [0u, 1, 2, 3, 4]; + let ys = [0f64, 1.0, 3.0, 6.0, 10.0]; + + let mut it = xs.iter().scan(0, add); + let mut i = 0; + for x in it { + assert_eq!(x, ys[i]); + i += 1; + } + assert_eq!(i, ys.len()); +} + +#[test] +fn test_iterator_flat_map() { + let xs = [0u, 3, 6]; + let ys = [0u, 1, 2, 3, 4, 5, 6, 7, 8]; + let mut it = xs.iter().flat_map(|&x| count(x, 1).take(3)); + let mut i = 0; + for x in it { + assert_eq!(x, ys[i]); + i += 1; + } + assert_eq!(i, ys.len()); +} + +#[test] +fn test_inspect() { + let xs = [1u, 2, 3, 4]; + let mut n = 0; + + let ys = xs.iter() + .map(|&x| x) + .inspect(|_| n += 1) + .collect::>(); + + assert_eq!(n, xs.len()); + assert_eq!(xs.as_slice(), ys.as_slice()); +} + +#[test] +fn test_unfoldr() { + fn count(st: &mut uint) -> Option { + if *st < 10 { + let ret = Some(*st); + *st += 1; + ret + } else { + None + } + } + + let mut it = Unfold::new(0, count); + let mut i = 0; + for counted in it { + assert_eq!(counted, i); + i += 1; + } + assert_eq!(i, 10); +} + +#[test] +fn test_cycle() { + let cycle_len = 3; + let it = count(0u, 1).take(cycle_len).cycle(); + assert_eq!(it.size_hint(), (uint::MAX, None)); + for (i, x) in it.take(100).enumerate() { + assert_eq!(i % cycle_len, x); + } + + let mut it = count(0u, 1).take(0).cycle(); + assert_eq!(it.size_hint(), (0, Some(0))); + assert_eq!(it.next(), None); +} + +#[test] +fn test_iterator_nth() { + let v = &[0i, 1, 2, 3, 4]; + for i in range(0u, v.len()) { + assert_eq!(v.iter().nth(i).unwrap(), &v[i]); + } +} + +#[test] +fn test_iterator_last() { + let v = &[0i, 1, 2, 3, 4]; + assert_eq!(v.iter().last().unwrap(), &4); + assert_eq!(v.slice(0, 1).iter().last().unwrap(), &0); +} + +#[test] +fn test_iterator_len() { + let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + assert_eq!(v.slice(0, 4).iter().count(), 4); + assert_eq!(v.slice(0, 10).iter().count(), 10); + assert_eq!(v.slice(0, 0).iter().count(), 0); +} + +#[test] +fn test_iterator_sum() { + let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + assert_eq!(v.slice(0, 4).iter().map(|&x| x).sum(), 6); + assert_eq!(v.iter().map(|&x| x).sum(), 55); + assert_eq!(v.slice(0, 0).iter().map(|&x| x).sum(), 0); +} + +#[test] +fn test_iterator_product() { + let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + assert_eq!(v.slice(0, 4).iter().map(|&x| x).product(), 0); + assert_eq!(v.slice(1, 5).iter().map(|&x| x).product(), 24); + assert_eq!(v.slice(0, 0).iter().map(|&x| x).product(), 1); +} + +#[test] +fn test_iterator_max() { + let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + assert_eq!(v.slice(0, 4).iter().map(|&x| x).max(), Some(3)); + assert_eq!(v.iter().map(|&x| x).max(), Some(10)); + assert_eq!(v.slice(0, 0).iter().map(|&x| x).max(), None); +} + +#[test] +fn test_iterator_min() { + let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + assert_eq!(v.slice(0, 4).iter().map(|&x| x).min(), Some(0)); + assert_eq!(v.iter().map(|&x| x).min(), Some(0)); + assert_eq!(v.slice(0, 0).iter().map(|&x| x).min(), None); +} + +#[test] +fn test_iterator_size_hint() { + let c = count(0i, 1); + let v = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + let v2 = &[10i, 11, 12]; + let vi = v.iter(); + + assert_eq!(c.size_hint(), (uint::MAX, None)); + assert_eq!(vi.size_hint(), (10, Some(10))); + + assert_eq!(c.take(5).size_hint(), (5, Some(5))); + assert_eq!(c.skip(5).size_hint().val1(), None); + assert_eq!(c.take_while(|_| false).size_hint(), (0, None)); + assert_eq!(c.skip_while(|_| false).size_hint(), (0, None)); + assert_eq!(c.enumerate().size_hint(), (uint::MAX, None)); + assert_eq!(c.chain(vi.map(|&i| i)).size_hint(), (uint::MAX, None)); + assert_eq!(c.zip(vi).size_hint(), (10, Some(10))); + assert_eq!(c.scan(0i, |_,_| Some(0i)).size_hint(), (0, None)); + assert_eq!(c.filter(|_| false).size_hint(), (0, None)); + assert_eq!(c.map(|_| 0i).size_hint(), (uint::MAX, None)); + assert_eq!(c.filter_map(|_| Some(0i)).size_hint(), (0, None)); + + assert_eq!(vi.take(5).size_hint(), (5, Some(5))); + assert_eq!(vi.take(12).size_hint(), (10, Some(10))); + assert_eq!(vi.skip(3).size_hint(), (7, Some(7))); + assert_eq!(vi.skip(12).size_hint(), (0, Some(0))); + assert_eq!(vi.take_while(|_| false).size_hint(), (0, Some(10))); + assert_eq!(vi.skip_while(|_| false).size_hint(), (0, Some(10))); + assert_eq!(vi.enumerate().size_hint(), (10, Some(10))); + assert_eq!(vi.chain(v2.iter()).size_hint(), (13, Some(13))); + assert_eq!(vi.zip(v2.iter()).size_hint(), (3, Some(3))); + assert_eq!(vi.scan(0i, |_,_| Some(0i)).size_hint(), (0, Some(10))); + assert_eq!(vi.filter(|_| false).size_hint(), (0, Some(10))); + assert_eq!(vi.map(|i| i+1).size_hint(), (10, Some(10))); + assert_eq!(vi.filter_map(|_| Some(0i)).size_hint(), (0, Some(10))); +} + +#[test] +fn test_collect() { + let a = vec![1i, 2, 3, 4, 5]; + let b: Vec = a.iter().map(|&x| x).collect(); + assert!(a == b); +} + +#[test] +fn test_all() { + let v: Box<&[int]> = box &[1i, 2, 3, 4, 5]; + assert!(v.iter().all(|&x| x < 10)); + assert!(!v.iter().all(|&x| x % 2 == 0)); + assert!(!v.iter().all(|&x| x > 100)); + assert!(v.slice(0, 0).iter().all(|_| fail!())); +} + +#[test] +fn test_any() { + let v: Box<&[int]> = box &[1i, 2, 3, 4, 5]; + assert!(v.iter().any(|&x| x < 10)); + assert!(v.iter().any(|&x| x % 2 == 0)); + assert!(!v.iter().any(|&x| x > 100)); + assert!(!v.slice(0, 0).iter().any(|_| fail!())); +} + +#[test] +fn test_find() { + let v: &[int] = &[1i, 3, 9, 27, 103, 14, 11]; + assert_eq!(*v.iter().find(|x| *x & 1 == 0).unwrap(), 14); + assert_eq!(*v.iter().find(|x| *x % 3 == 0).unwrap(), 3); + assert!(v.iter().find(|x| *x % 12 == 0).is_none()); +} + +#[test] +fn test_position() { + let v = &[1i, 3, 9, 27, 103, 14, 11]; + assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5); + assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1); + assert!(v.iter().position(|x| *x % 12 == 0).is_none()); +} + +#[test] +fn test_count() { + let xs = &[1i, 2, 2, 1, 5, 9, 0, 2]; + assert_eq!(xs.iter().filter(|x| **x == 2).count(), 3); + assert_eq!(xs.iter().filter(|x| **x == 5).count(), 1); + assert_eq!(xs.iter().filter(|x| **x == 95).count(), 0); +} + +#[test] +fn test_max_by() { + let xs: &[int] = &[-3i, 0, 1, 5, -10]; + assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10); +} + +#[test] +fn test_min_by() { + let xs: &[int] = &[-3i, 0, 1, 5, -10]; + assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0); +} + +#[test] +fn test_by_ref() { + let mut xs = range(0i, 10); + // sum the first five values + let partial_sum = xs.by_ref().take(5).fold(0, |a, b| a + b); + assert_eq!(partial_sum, 10); + assert_eq!(xs.next(), Some(5)); +} + +#[test] +fn test_rev() { + let xs = [2i, 4, 6, 8, 10, 12, 14, 16]; + let mut it = xs.iter(); + it.next(); + it.next(); + assert!(it.rev().map(|&x| x).collect::>() == + vec![16, 14, 12, 10, 8, 6]); +} + +#[test] +fn test_double_ended_map() { + let xs = [1i, 2, 3, 4, 5, 6]; + let mut it = xs.iter().map(|&x| x * -1); + assert_eq!(it.next(), Some(-1)); + assert_eq!(it.next(), Some(-2)); + assert_eq!(it.next_back(), Some(-6)); + assert_eq!(it.next_back(), Some(-5)); + assert_eq!(it.next(), Some(-3)); + assert_eq!(it.next_back(), Some(-4)); + assert_eq!(it.next(), None); +} + +#[test] +fn test_double_ended_enumerate() { + let xs = [1i, 2, 3, 4, 5, 6]; + let mut it = xs.iter().map(|&x| x).enumerate(); + assert_eq!(it.next(), Some((0, 1))); + assert_eq!(it.next(), Some((1, 2))); + assert_eq!(it.next_back(), Some((5, 6))); + assert_eq!(it.next_back(), Some((4, 5))); + assert_eq!(it.next_back(), Some((3, 4))); + assert_eq!(it.next_back(), Some((2, 3))); + assert_eq!(it.next(), None); +} + +#[test] +fn test_double_ended_zip() { + let xs = [1i, 2, 3, 4, 5, 6]; + let ys = [1i, 2, 3, 7]; + let a = xs.iter().map(|&x| x); + let b = ys.iter().map(|&x| x); + let mut it = a.zip(b); + assert_eq!(it.next(), Some((1, 1))); + assert_eq!(it.next(), Some((2, 2))); + assert_eq!(it.next_back(), Some((4, 7))); + assert_eq!(it.next_back(), Some((3, 3))); + assert_eq!(it.next(), None); +} + +#[test] +fn test_double_ended_filter() { + let xs = [1i, 2, 3, 4, 5, 6]; + let mut it = xs.iter().filter(|&x| *x & 1 == 0); + assert_eq!(it.next_back().unwrap(), &6); + assert_eq!(it.next_back().unwrap(), &4); + assert_eq!(it.next().unwrap(), &2); + assert_eq!(it.next_back(), None); +} + +#[test] +fn test_double_ended_filter_map() { + let xs = [1i, 2, 3, 4, 5, 6]; + let mut it = xs.iter().filter_map(|&x| if x & 1 == 0 { Some(x * 2) } else { None }); + assert_eq!(it.next_back().unwrap(), 12); + assert_eq!(it.next_back().unwrap(), 8); + assert_eq!(it.next().unwrap(), 4); + assert_eq!(it.next_back(), None); +} + +#[test] +fn test_double_ended_chain() { + let xs = [1i, 2, 3, 4, 5]; + let ys = [7i, 9, 11]; + let mut it = xs.iter().chain(ys.iter()).rev(); + assert_eq!(it.next().unwrap(), &11) + assert_eq!(it.next().unwrap(), &9) + assert_eq!(it.next_back().unwrap(), &1) + assert_eq!(it.next_back().unwrap(), &2) + assert_eq!(it.next_back().unwrap(), &3) + assert_eq!(it.next_back().unwrap(), &4) + assert_eq!(it.next_back().unwrap(), &5) + assert_eq!(it.next_back().unwrap(), &7) + assert_eq!(it.next_back(), None) +} + +#[test] +fn test_rposition() { + fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' } + fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' } + let v = [(0i, 'a'), (1, 'b'), (2, 'c'), (3, 'b')]; + + assert_eq!(v.iter().rposition(f), Some(3u)); + assert!(v.iter().rposition(g).is_none()); +} + +#[test] +#[should_fail] +fn test_rposition_fail() { + use std::gc::GC; + let v = [(box 0i, box(GC) 0i), (box 0i, box(GC) 0i), + (box 0i, box(GC) 0i), (box 0i, box(GC) 0i)]; + let mut i = 0i; + v.iter().rposition(|_elt| { + if i == 2 { + fail!() + } + i += 1; + false + }); +} + + +#[cfg(test)] +fn check_randacc_iter>(a: T, len: uint) +{ + let mut b = a.clone(); + assert_eq!(len, b.indexable()); + let mut n = 0u; + for (i, elt) in a.enumerate() { + assert!(Some(elt) == b.idx(i)); + n += 1; + } + assert_eq!(n, len); + assert!(None == b.idx(n)); + // call recursively to check after picking off an element + if len > 0 { + b.next(); + check_randacc_iter(b, len-1); + } +} + + +#[test] +fn test_double_ended_flat_map() { + let u = [0u,1]; + let v = [5u,6,7,8]; + let mut it = u.iter().flat_map(|x| v.slice(*x, v.len()).iter()); + assert_eq!(it.next_back().unwrap(), &8); + assert_eq!(it.next().unwrap(), &5); + assert_eq!(it.next_back().unwrap(), &7); + assert_eq!(it.next_back().unwrap(), &6); + assert_eq!(it.next_back().unwrap(), &8); + assert_eq!(it.next().unwrap(), &6); + assert_eq!(it.next_back().unwrap(), &7); + assert_eq!(it.next_back(), None); + assert_eq!(it.next(), None); + assert_eq!(it.next_back(), None); +} + +#[test] +fn test_random_access_chain() { + let xs = [1i, 2, 3, 4, 5]; + let ys = [7i, 9, 11]; + let mut it = xs.iter().chain(ys.iter()); + assert_eq!(it.idx(0).unwrap(), &1); + assert_eq!(it.idx(5).unwrap(), &7); + assert_eq!(it.idx(7).unwrap(), &11); + assert!(it.idx(8).is_none()); + + it.next(); + it.next(); + it.next_back(); + + assert_eq!(it.idx(0).unwrap(), &3); + assert_eq!(it.idx(4).unwrap(), &9); + assert!(it.idx(6).is_none()); + + check_randacc_iter(it, xs.len() + ys.len() - 3); +} + +#[test] +fn test_random_access_enumerate() { + let xs = [1i, 2, 3, 4, 5]; + check_randacc_iter(xs.iter().enumerate(), xs.len()); +} + +#[test] +fn test_random_access_rev() { + let xs = [1i, 2, 3, 4, 5]; + check_randacc_iter(xs.iter().rev(), xs.len()); + let mut it = xs.iter().rev(); + it.next(); + it.next_back(); + it.next(); + check_randacc_iter(it, xs.len() - 3); +} + +#[test] +fn test_random_access_zip() { + let xs = [1i, 2, 3, 4, 5]; + let ys = [7i, 9, 11]; + check_randacc_iter(xs.iter().zip(ys.iter()), cmp::min(xs.len(), ys.len())); +} + +#[test] +fn test_random_access_take() { + let xs = [1i, 2, 3, 4, 5]; + let empty: &[int] = []; + check_randacc_iter(xs.iter().take(3), 3); + check_randacc_iter(xs.iter().take(20), xs.len()); + check_randacc_iter(xs.iter().take(0), 0); + check_randacc_iter(empty.iter().take(2), 0); +} + +#[test] +fn test_random_access_skip() { + let xs = [1i, 2, 3, 4, 5]; + let empty: &[int] = []; + check_randacc_iter(xs.iter().skip(2), xs.len() - 2); + check_randacc_iter(empty.iter().skip(2), 0); +} + +#[test] +fn test_random_access_inspect() { + let xs = [1i, 2, 3, 4, 5]; + + // test .map and .inspect that don't implement Clone + let mut it = xs.iter().inspect(|_| {}); + assert_eq!(xs.len(), it.indexable()); + for (i, elt) in xs.iter().enumerate() { + assert_eq!(Some(elt), it.idx(i)); + } + +} + +#[test] +fn test_random_access_map() { + let xs = [1i, 2, 3, 4, 5]; + + let mut it = xs.iter().map(|x| *x); + assert_eq!(xs.len(), it.indexable()); + for (i, elt) in xs.iter().enumerate() { + assert_eq!(Some(*elt), it.idx(i)); + } +} + +#[test] +fn test_random_access_cycle() { + let xs = [1i, 2, 3, 4, 5]; + let empty: &[int] = []; + check_randacc_iter(xs.iter().cycle().take(27), 27); + check_randacc_iter(empty.iter().cycle(), 0); +} + +#[test] +fn test_double_ended_range() { + assert!(range(11i, 14).rev().collect::>() == vec![13i, 12, 11]); + for _ in range(10i, 0).rev() { + fail!("unreachable"); + } + + assert!(range(11u, 14).rev().collect::>() == vec![13u, 12, 11]); + for _ in range(10u, 0).rev() { + fail!("unreachable"); + } +} + +#[test] +fn test_range() { + /// A mock type to check Range when ToPrimitive returns None + struct Foo; + + impl ToPrimitive for Foo { + fn to_i64(&self) -> Option { None } + fn to_u64(&self) -> Option { None } + } + + impl Add for Foo { + fn add(&self, _: &Foo) -> Foo { + Foo + } + } + + impl PartialEq for Foo { + fn eq(&self, _: &Foo) -> bool { + true + } + } + + impl PartialOrd for Foo { + fn lt(&self, _: &Foo) -> bool { + false + } + } + + impl Clone for Foo { + fn clone(&self) -> Foo { + Foo + } + } + + impl Mul for Foo { + fn mul(&self, _: &Foo) -> Foo { + Foo + } + } + + impl num::One for Foo { + fn one() -> Foo { + Foo + } + } + + assert!(range(0i, 5).collect::>() == vec![0i, 1, 2, 3, 4]); + assert!(range(-10i, -1).collect::>() == + vec![-10, -9, -8, -7, -6, -5, -4, -3, -2]); + assert!(range(0i, 5).rev().collect::>() == vec![4, 3, 2, 1, 0]); + assert_eq!(range(200i, -5).count(), 0); + assert_eq!(range(200i, -5).rev().count(), 0); + assert_eq!(range(200i, 200).count(), 0); + assert_eq!(range(200i, 200).rev().count(), 0); + + assert_eq!(range(0i, 100).size_hint(), (100, Some(100))); + // this test is only meaningful when sizeof uint < sizeof u64 + assert_eq!(range(uint::MAX - 1, uint::MAX).size_hint(), (1, Some(1))); + assert_eq!(range(-10i, -1).size_hint(), (9, Some(9))); + assert_eq!(range(Foo, Foo).size_hint(), (0, None)); +} + +#[test] +fn test_range_inclusive() { + assert!(range_inclusive(0i, 5).collect::>() == + vec![0i, 1, 2, 3, 4, 5]); + assert!(range_inclusive(0i, 5).rev().collect::>() == + vec![5i, 4, 3, 2, 1, 0]); + assert_eq!(range_inclusive(200i, -5).count(), 0); + assert_eq!(range_inclusive(200i, -5).rev().count(), 0); + assert!(range_inclusive(200i, 200).collect::>() == vec![200]); + assert!(range_inclusive(200i, 200).rev().collect::>() == vec![200]); +} + +#[test] +fn test_range_step() { + assert!(range_step(0i, 20, 5).collect::>() == + vec![0, 5, 10, 15]); + assert!(range_step(20i, 0, -5).collect::>() == + vec![20, 15, 10, 5]); + assert!(range_step(20i, 0, -6).collect::>() == + vec![20, 14, 8, 2]); + assert!(range_step(200u8, 255, 50).collect::>() == + vec![200u8, 250]); + assert!(range_step(200i, -5, 1).collect::>() == vec![]); + assert!(range_step(200i, 200, 1).collect::>() == vec![]); +} + +#[test] +fn test_range_step_inclusive() { + assert!(range_step_inclusive(0i, 20, 5).collect::>() == + vec![0, 5, 10, 15, 20]); + assert!(range_step_inclusive(20i, 0, -5).collect::>() == + vec![20, 15, 10, 5, 0]); + assert!(range_step_inclusive(20i, 0, -6).collect::>() == + vec![20, 14, 8, 2]); + assert!(range_step_inclusive(200u8, 255, 50).collect::>() == + vec![200u8, 250]); + assert!(range_step_inclusive(200i, -5, 1).collect::>() == + vec![]); + assert!(range_step_inclusive(200i, 200, 1).collect::>() == + vec![200]); +} + +#[test] +fn test_reverse() { + let mut ys = [1i, 2, 3, 4, 5]; + ys.mut_iter().reverse_(); + assert!(ys == [5, 4, 3, 2, 1]); +} + +#[test] +fn test_peekable_is_empty() { + let a = [1i]; + let mut it = a.iter().peekable(); + assert!( !it.is_empty() ); + it.next(); + assert!( it.is_empty() ); +} + +#[test] +fn test_min_max() { + let v: [int, ..0] = []; + assert_eq!(v.iter().min_max(), NoElements); + + let v = [1i]; + assert!(v.iter().min_max() == OneElement(&1)); + + let v = [1i, 2, 3, 4, 5]; + assert!(v.iter().min_max() == MinMax(&1, &5)); + + let v = [1i, 2, 3, 4, 5, 6]; + assert!(v.iter().min_max() == MinMax(&1, &6)); + + let v = [1i, 1, 1, 1]; + assert!(v.iter().min_max() == MinMax(&1, &1)); +} + +#[test] +fn test_min_max_result() { + let r: MinMaxResult = NoElements; + assert_eq!(r.into_option(), None) + + let r = OneElement(1i); + assert_eq!(r.into_option(), Some((1,1))); + + let r = MinMax(1i,2); + assert_eq!(r.into_option(), Some((1,2))); +} diff --git a/src/libcoretest/lib.rs b/src/libcoretest/lib.rs new file mode 100644 index 0000000000000..3a3cac542c91b --- /dev/null +++ b/src/libcoretest/lib.rs @@ -0,0 +1,31 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +#![feature(globs, unsafe_destructor, macro_rules)] + +extern crate core; +extern crate test; +extern crate libc; + +mod any; +mod atomics; +mod cell; +mod char; +mod cmp; +mod finally; +mod fmt; +mod iter; +mod mem; +mod num; +mod ops; +mod option; +mod ptr; +mod raw; +mod result; +mod tuple; diff --git a/src/libcoretest/mem.rs b/src/libcoretest/mem.rs new file mode 100644 index 0000000000000..fde640158f51e --- /dev/null +++ b/src/libcoretest/mem.rs @@ -0,0 +1,173 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +use core::mem::*; +use test::Bencher; + +#[test] +fn size_of_basic() { + assert_eq!(size_of::(), 1u); + assert_eq!(size_of::(), 2u); + assert_eq!(size_of::(), 4u); + assert_eq!(size_of::(), 8u); +} + +#[test] +#[cfg(target_arch = "x86")] +#[cfg(target_arch = "arm")] +#[cfg(target_arch = "mips")] +#[cfg(target_arch = "mipsel")] +fn size_of_32() { + assert_eq!(size_of::(), 4u); + assert_eq!(size_of::<*const uint>(), 4u); +} + +#[test] +#[cfg(target_arch = "x86_64")] +fn size_of_64() { + assert_eq!(size_of::(), 8u); + assert_eq!(size_of::<*const uint>(), 8u); +} + +#[test] +fn size_of_val_basic() { + assert_eq!(size_of_val(&1u8), 1); + assert_eq!(size_of_val(&1u16), 2); + assert_eq!(size_of_val(&1u32), 4); + assert_eq!(size_of_val(&1u64), 8); +} + +#[test] +fn align_of_basic() { + assert_eq!(align_of::(), 1u); + assert_eq!(align_of::(), 2u); + assert_eq!(align_of::(), 4u); +} + +#[test] +#[cfg(target_arch = "x86")] +#[cfg(target_arch = "arm")] +#[cfg(target_arch = "mips")] +#[cfg(target_arch = "mipsel")] +fn align_of_32() { + assert_eq!(align_of::(), 4u); + assert_eq!(align_of::<*const uint>(), 4u); +} + +#[test] +#[cfg(target_arch = "x86_64")] +fn align_of_64() { + assert_eq!(align_of::(), 8u); + assert_eq!(align_of::<*const uint>(), 8u); +} + +#[test] +fn align_of_val_basic() { + assert_eq!(align_of_val(&1u8), 1u); + assert_eq!(align_of_val(&1u16), 2u); + assert_eq!(align_of_val(&1u32), 4u); +} + +#[test] +fn test_swap() { + let mut x = 31337i; + let mut y = 42i; + swap(&mut x, &mut y); + assert_eq!(x, 42); + assert_eq!(y, 31337); +} + +#[test] +fn test_replace() { + let mut x = Some("test".to_string()); + let y = replace(&mut x, None); + assert!(x.is_none()); + assert!(y.is_some()); +} + +#[test] +fn test_transmute_copy() { + assert_eq!(1u, unsafe { transmute_copy(&1i) }); +} + +#[test] +fn test_transmute() { + trait Foo {} + impl Foo for int {} + + let a = box 100i as Box; + unsafe { + let x: ::core::raw::TraitObject = transmute(a); + assert!(*(x.data as *const int) == 100); + let _x: Box = transmute(x); + } + + unsafe { + assert!(Vec::from_slice([76u8]) == transmute("L".to_string())); + } +} + +// FIXME #13642 (these benchmarks should be in another place) +/// Completely miscellaneous language-construct benchmarks. +// Static/dynamic method dispatch + +struct Struct { + field: int +} + +trait Trait { + fn method(&self) -> int; +} + +impl Trait for Struct { + fn method(&self) -> int { + self.field + } +} + +#[bench] +fn trait_vtable_method_call(b: &mut Bencher) { + let s = Struct { field: 10 }; + let t = &s as &Trait; + b.iter(|| { + t.method() + }); +} + +#[bench] +fn trait_static_method_call(b: &mut Bencher) { + let s = Struct { field: 10 }; + b.iter(|| { + s.method() + }); +} + +// Overhead of various match forms + +#[bench] +fn match_option_some(b: &mut Bencher) { + let x = Some(10i); + b.iter(|| { + match x { + Some(y) => y, + None => 11 + } + }); +} + +#[bench] +fn match_vec_pattern(b: &mut Bencher) { + let x = [1i,2,3,4,5,6]; + b.iter(|| { + match x { + [1,2,3,..] => 10i, + _ => 11i, + } + }); +} diff --git a/src/libcoretest/num/i16.rs b/src/libcoretest/num/i16.rs new file mode 100644 index 0000000000000..f3c2d67cdeb1b --- /dev/null +++ b/src/libcoretest/num/i16.rs @@ -0,0 +1,11 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +int_module!(i16, i16) diff --git a/src/libcoretest/num/i32.rs b/src/libcoretest/num/i32.rs new file mode 100644 index 0000000000000..7232fc7505df9 --- /dev/null +++ b/src/libcoretest/num/i32.rs @@ -0,0 +1,11 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +int_module!(i32, i32) diff --git a/src/libcoretest/num/i64.rs b/src/libcoretest/num/i64.rs new file mode 100644 index 0000000000000..075b8448f3529 --- /dev/null +++ b/src/libcoretest/num/i64.rs @@ -0,0 +1,11 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +int_module!(i64, i64) diff --git a/src/libcoretest/num/i8.rs b/src/libcoretest/num/i8.rs new file mode 100644 index 0000000000000..9e0439f281889 --- /dev/null +++ b/src/libcoretest/num/i8.rs @@ -0,0 +1,11 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +int_module!(i8, i8) diff --git a/src/libcoretest/num/int.rs b/src/libcoretest/num/int.rs new file mode 100644 index 0000000000000..f01ec3f0310a3 --- /dev/null +++ b/src/libcoretest/num/int.rs @@ -0,0 +1,11 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +int_module!(int, int) diff --git a/src/libcoretest/num/int_macros.rs b/src/libcoretest/num/int_macros.rs new file mode 100644 index 0000000000000..940b036ca907b --- /dev/null +++ b/src/libcoretest/num/int_macros.rs @@ -0,0 +1,160 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![macro_escape] + +macro_rules! int_module (($T:ty, $T_i:ident) => ( +#[cfg(test)] +mod tests { + use core::$T_i::*; + use core::int; + use num; + use core::num::CheckedDiv; + + #[test] + fn test_overflows() { + assert!(MAX > 0); + assert!(MIN <= 0); + assert!(MIN + MAX + 1 == 0); + } + + #[test] + fn test_num() { + num::test_num(10 as $T, 2 as $T); + } + + #[test] + pub fn test_abs() { + assert!((1 as $T).abs() == 1 as $T); + assert!((0 as $T).abs() == 0 as $T); + assert!((-1 as $T).abs() == 1 as $T); + } + + #[test] + fn test_abs_sub() { + assert!((-1 as $T).abs_sub(&(1 as $T)) == 0 as $T); + assert!((1 as $T).abs_sub(&(1 as $T)) == 0 as $T); + assert!((1 as $T).abs_sub(&(0 as $T)) == 1 as $T); + assert!((1 as $T).abs_sub(&(-1 as $T)) == 2 as $T); + } + + #[test] + fn test_signum() { + assert!((1 as $T).signum() == 1 as $T); + assert!((0 as $T).signum() == 0 as $T); + assert!((-0 as $T).signum() == 0 as $T); + assert!((-1 as $T).signum() == -1 as $T); + } + + #[test] + fn test_is_positive() { + assert!((1 as $T).is_positive()); + assert!(!(0 as $T).is_positive()); + assert!(!(-0 as $T).is_positive()); + assert!(!(-1 as $T).is_positive()); + } + + #[test] + fn test_is_negative() { + assert!(!(1 as $T).is_negative()); + assert!(!(0 as $T).is_negative()); + assert!(!(-0 as $T).is_negative()); + assert!((-1 as $T).is_negative()); + } + + #[test] + fn test_bitwise_operators() { + assert!(0b1110 as $T == (0b1100 as $T).bitor(&(0b1010 as $T))); + assert!(0b1000 as $T == (0b1100 as $T).bitand(&(0b1010 as $T))); + assert!(0b0110 as $T == (0b1100 as $T).bitxor(&(0b1010 as $T))); + assert!(0b1110 as $T == (0b0111 as $T).shl(&(1 as $T))); + assert!(0b0111 as $T == (0b1110 as $T).shr(&(1 as $T))); + assert!(-(0b11 as $T) - (1 as $T) == (0b11 as $T).not()); + } + + static A: $T = 0b0101100; + static B: $T = 0b0100001; + static C: $T = 0b1111001; + + static _0: $T = 0; + static _1: $T = !0; + + #[test] + fn test_count_ones() { + assert!(A.count_ones() == 3); + assert!(B.count_ones() == 2); + assert!(C.count_ones() == 5); + } + + #[test] + fn test_count_zeros() { + assert!(A.count_zeros() == BITS as $T - 3); + assert!(B.count_zeros() == BITS as $T - 2); + assert!(C.count_zeros() == BITS as $T - 5); + } + + #[test] + fn test_rotate() { + assert_eq!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); + assert_eq!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); + assert_eq!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); + + // Rotating these should make no difference + // + // We test using 124 bits because to ensure that overlong bit shifts do + // not cause undefined behaviour. See #10183. + assert_eq!(_0.rotate_left(124), _0); + assert_eq!(_1.rotate_left(124), _1); + assert_eq!(_0.rotate_right(124), _0); + assert_eq!(_1.rotate_right(124), _1); + } + + #[test] + fn test_swap_bytes() { + assert_eq!(A.swap_bytes().swap_bytes(), A); + assert_eq!(B.swap_bytes().swap_bytes(), B); + assert_eq!(C.swap_bytes().swap_bytes(), C); + + // Swapping these should make no difference + assert_eq!(_0.swap_bytes(), _0); + assert_eq!(_1.swap_bytes(), _1); + } + + #[test] + fn test_le() { + assert_eq!(Int::from_le(A.to_le()), A); + assert_eq!(Int::from_le(B.to_le()), B); + assert_eq!(Int::from_le(C.to_le()), C); + assert_eq!(Int::from_le(_0), _0); + assert_eq!(Int::from_le(_1), _1); + assert_eq!(_0.to_le(), _0); + assert_eq!(_1.to_le(), _1); + } + + #[test] + fn test_be() { + assert_eq!(Int::from_be(A.to_be()), A); + assert_eq!(Int::from_be(B.to_be()), B); + assert_eq!(Int::from_be(C.to_be()), C); + assert_eq!(Int::from_be(_0), _0); + assert_eq!(Int::from_be(_1), _1); + assert_eq!(_0.to_be(), _0); + assert_eq!(_1.to_be(), _1); + } + + #[test] + fn test_signed_checked_div() { + assert!(10i.checked_div(&2) == Some(5)); + assert!(5i.checked_div(&0) == None); + assert!(int::MIN.checked_div(&-1) == None); + } +} + +)) diff --git a/src/libcoretest/num/mod.rs b/src/libcoretest/num/mod.rs new file mode 100644 index 0000000000000..8bb238c0b66e8 --- /dev/null +++ b/src/libcoretest/num/mod.rs @@ -0,0 +1,39 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::num::cast; + +mod int_macros; +mod i8; +mod i16; +mod i32; +mod i64; +mod int; +mod uint_macros; +mod u8; +mod u16; +mod u32; +mod u64; +mod uint; + +/// Helper function for testing numeric operations +pub fn test_num(ten: T, two: T) { + assert_eq!(ten.add(&two), cast(12i).unwrap()); + assert_eq!(ten.sub(&two), cast(8i).unwrap()); + assert_eq!(ten.mul(&two), cast(20i).unwrap()); + assert_eq!(ten.div(&two), cast(5i).unwrap()); + assert_eq!(ten.rem(&two), cast(0i).unwrap()); + + assert_eq!(ten.add(&two), ten + two); + assert_eq!(ten.sub(&two), ten - two); + assert_eq!(ten.mul(&two), ten * two); + assert_eq!(ten.div(&two), ten / two); + assert_eq!(ten.rem(&two), ten % two); +} diff --git a/src/libcoretest/num/u16.rs b/src/libcoretest/num/u16.rs new file mode 100644 index 0000000000000..d6aa647667804 --- /dev/null +++ b/src/libcoretest/num/u16.rs @@ -0,0 +1,11 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +uint_module!(u16, u16) diff --git a/src/libcoretest/num/u32.rs b/src/libcoretest/num/u32.rs new file mode 100644 index 0000000000000..218e79df5aece --- /dev/null +++ b/src/libcoretest/num/u32.rs @@ -0,0 +1,11 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +uint_module!(u32, u32) diff --git a/src/libcoretest/num/u64.rs b/src/libcoretest/num/u64.rs new file mode 100644 index 0000000000000..f78d4813503e7 --- /dev/null +++ b/src/libcoretest/num/u64.rs @@ -0,0 +1,11 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +uint_module!(u64, u64) diff --git a/src/libcoretest/num/u8.rs b/src/libcoretest/num/u8.rs new file mode 100644 index 0000000000000..bb08072320b70 --- /dev/null +++ b/src/libcoretest/num/u8.rs @@ -0,0 +1,11 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +uint_module!(u8, u8) diff --git a/src/libcoretest/num/uint.rs b/src/libcoretest/num/uint.rs new file mode 100644 index 0000000000000..0db865f4cde7a --- /dev/null +++ b/src/libcoretest/num/uint.rs @@ -0,0 +1,11 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +uint_module!(uint, uint) diff --git a/src/libcoretest/num/uint_macros.rs b/src/libcoretest/num/uint_macros.rs new file mode 100644 index 0000000000000..2272af67daf85 --- /dev/null +++ b/src/libcoretest/num/uint_macros.rs @@ -0,0 +1,118 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#![macro_escape] + +macro_rules! uint_module (($T:ty, $T_i:ident) => ( +#[cfg(test)] +mod tests { + use core::$T_i::*; + use num; + use core::num::CheckedDiv; + + #[test] + fn test_overflows() { + assert!(MAX > 0); + assert!(MIN <= 0); + assert!(MIN + MAX + 1 == 0); + } + + #[test] + fn test_num() { + num::test_num(10 as $T, 2 as $T); + } + + #[test] + fn test_bitwise_operators() { + assert!(0b1110 as $T == (0b1100 as $T).bitor(&(0b1010 as $T))); + assert!(0b1000 as $T == (0b1100 as $T).bitand(&(0b1010 as $T))); + assert!(0b0110 as $T == (0b1100 as $T).bitxor(&(0b1010 as $T))); + assert!(0b1110 as $T == (0b0111 as $T).shl(&(1 as $T))); + assert!(0b0111 as $T == (0b1110 as $T).shr(&(1 as $T))); + assert!(MAX - (0b1011 as $T) == (0b1011 as $T).not()); + } + + static A: $T = 0b0101100; + static B: $T = 0b0100001; + static C: $T = 0b1111001; + + static _0: $T = 0; + static _1: $T = !0; + + #[test] + fn test_count_ones() { + assert!(A.count_ones() == 3); + assert!(B.count_ones() == 2); + assert!(C.count_ones() == 5); + } + + #[test] + fn test_count_zeros() { + assert!(A.count_zeros() == BITS as $T - 3); + assert!(B.count_zeros() == BITS as $T - 2); + assert!(C.count_zeros() == BITS as $T - 5); + } + + #[test] + fn test_rotate() { + assert_eq!(A.rotate_left(6).rotate_right(2).rotate_right(4), A); + assert_eq!(B.rotate_left(3).rotate_left(2).rotate_right(5), B); + assert_eq!(C.rotate_left(6).rotate_right(2).rotate_right(4), C); + + // Rotating these should make no difference + // + // We test using 124 bits because to ensure that overlong bit shifts do + // not cause undefined behaviour. See #10183. + assert_eq!(_0.rotate_left(124), _0); + assert_eq!(_1.rotate_left(124), _1); + assert_eq!(_0.rotate_right(124), _0); + assert_eq!(_1.rotate_right(124), _1); + } + + #[test] + fn test_swap_bytes() { + assert_eq!(A.swap_bytes().swap_bytes(), A); + assert_eq!(B.swap_bytes().swap_bytes(), B); + assert_eq!(C.swap_bytes().swap_bytes(), C); + + // Swapping these should make no difference + assert_eq!(_0.swap_bytes(), _0); + assert_eq!(_1.swap_bytes(), _1); + } + + #[test] + fn test_le() { + assert_eq!(Int::from_le(A.to_le()), A); + assert_eq!(Int::from_le(B.to_le()), B); + assert_eq!(Int::from_le(C.to_le()), C); + assert_eq!(Int::from_le(_0), _0); + assert_eq!(Int::from_le(_1), _1); + assert_eq!(_0.to_le(), _0); + assert_eq!(_1.to_le(), _1); + } + + #[test] + fn test_be() { + assert_eq!(Int::from_be(A.to_be()), A); + assert_eq!(Int::from_be(B.to_be()), B); + assert_eq!(Int::from_be(C.to_be()), C); + assert_eq!(Int::from_be(_0), _0); + assert_eq!(Int::from_be(_1), _1); + assert_eq!(_0.to_be(), _0); + assert_eq!(_1.to_be(), _1); + } + + #[test] + fn test_unsigned_checked_div() { + assert!(10u.checked_div(&2) == Some(5)); + assert!(5u.checked_div(&0) == None); + } +} +)) diff --git a/src/libcoretest/ops.rs b/src/libcoretest/ops.rs new file mode 100644 index 0000000000000..447fd1c699d3d --- /dev/null +++ b/src/libcoretest/ops.rs @@ -0,0 +1,29 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use test::Bencher; + +// Overhead of dtors + +struct HasDtor { + _x: int +} + +impl Drop for HasDtor { + fn drop(&mut self) { + } +} + +#[bench] +fn alloc_obj_with_dtor(b: &mut Bencher) { + b.iter(|| { + HasDtor { _x : 10 }; + }) +} diff --git a/src/libcoretest/option.rs b/src/libcoretest/option.rs new file mode 100644 index 0000000000000..776637f3be97d --- /dev/null +++ b/src/libcoretest/option.rs @@ -0,0 +1,278 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::option::*; +use core::kinds::marker; +use core::mem; + +#[test] +fn test_get_ptr() { + unsafe { + let x = box 0i; + let addr_x: *const int = mem::transmute(&*x); + let opt = Some(x); + let y = opt.unwrap(); + let addr_y: *const int = mem::transmute(&*y); + assert_eq!(addr_x, addr_y); + } +} + +#[test] +fn test_get_str() { + let x = "test".to_string(); + let addr_x = x.as_slice().as_ptr(); + let opt = Some(x); + let y = opt.unwrap(); + let addr_y = y.as_slice().as_ptr(); + assert_eq!(addr_x, addr_y); +} + +#[test] +fn test_get_resource() { + use std::rc::Rc; + use core::cell::RefCell; + + struct R { + i: Rc>, + } + + #[unsafe_destructor] + impl Drop for R { + fn drop(&mut self) { + let ii = &*self.i; + let i = *ii.borrow(); + *ii.borrow_mut() = i + 1; + } + } + + fn r(i: Rc>) -> R { + R { + i: i + } + } + + let i = Rc::new(RefCell::new(0i)); + { + let x = r(i.clone()); + let opt = Some(x); + let _y = opt.unwrap(); + } + assert_eq!(*i.borrow(), 1); +} + +#[test] +fn test_option_dance() { + let x = Some(()); + let mut y = Some(5i); + let mut y2 = 0; + for _x in x.iter() { + y2 = y.take_unwrap(); + } + assert_eq!(y2, 5); + assert!(y.is_none()); +} + +#[test] #[should_fail] +fn test_option_too_much_dance() { + let mut y = Some(marker::NoCopy); + let _y2 = y.take_unwrap(); + let _y3 = y.take_unwrap(); +} + +#[test] +fn test_and() { + let x: Option = Some(1i); + assert_eq!(x.and(Some(2i)), Some(2)); + assert_eq!(x.and(None::), None); + + let x: Option = None; + assert_eq!(x.and(Some(2i)), None); + assert_eq!(x.and(None::), None); +} + +#[test] +fn test_and_then() { + let x: Option = Some(1); + assert_eq!(x.and_then(|x| Some(x + 1)), Some(2)); + assert_eq!(x.and_then(|_| None::), None); + + let x: Option = None; + assert_eq!(x.and_then(|x| Some(x + 1)), None); + assert_eq!(x.and_then(|_| None::), None); +} + +#[test] +fn test_or() { + let x: Option = Some(1); + assert_eq!(x.or(Some(2)), Some(1)); + assert_eq!(x.or(None), Some(1)); + + let x: Option = None; + assert_eq!(x.or(Some(2)), Some(2)); + assert_eq!(x.or(None), None); +} + +#[test] +fn test_or_else() { + let x: Option = Some(1); + assert_eq!(x.or_else(|| Some(2)), Some(1)); + assert_eq!(x.or_else(|| None), Some(1)); + + let x: Option = None; + assert_eq!(x.or_else(|| Some(2)), Some(2)); + assert_eq!(x.or_else(|| None), None); +} + +#[test] +fn test_option_while_some() { + let mut i = 0i; + Some(10i).while_some(|j| { + i += 1; + if j > 0 { + Some(j-1) + } else { + None + } + }); + assert_eq!(i, 11); +} + +#[test] +fn test_unwrap() { + assert_eq!(Some(1i).unwrap(), 1); + let s = Some("hello".to_string()).unwrap(); + assert_eq!(s.as_slice(), "hello"); +} + +#[test] +#[should_fail] +fn test_unwrap_fail1() { + let x: Option = None; + x.unwrap(); +} + +#[test] +#[should_fail] +fn test_unwrap_fail2() { + let x: Option = None; + x.unwrap(); +} + +#[test] +fn test_unwrap_or() { + let x: Option = Some(1); + assert_eq!(x.unwrap_or(2), 1); + + let x: Option = None; + assert_eq!(x.unwrap_or(2), 2); +} + +#[test] +fn test_unwrap_or_else() { + let x: Option = Some(1); + assert_eq!(x.unwrap_or_else(|| 2), 1); + + let x: Option = None; + assert_eq!(x.unwrap_or_else(|| 2), 2); +} + +#[test] +fn test_filtered() { + let some_stuff = Some(42i); + let modified_stuff = some_stuff.filtered(|&x| {x < 10}); + assert_eq!(some_stuff.unwrap(), 42); + assert!(modified_stuff.is_none()); +} + +#[test] +fn test_iter() { + let val = 5i; + + let x = Some(val); + let mut it = x.iter(); + + assert_eq!(it.size_hint(), (1, Some(1))); + assert_eq!(it.next(), Some(&val)); + assert_eq!(it.size_hint(), (0, Some(0))); + assert!(it.next().is_none()); +} + +#[test] +fn test_mut_iter() { + let val = 5i; + let new_val = 11i; + + let mut x = Some(val); + { + let mut it = x.mut_iter(); + + assert_eq!(it.size_hint(), (1, Some(1))); + + match it.next() { + Some(interior) => { + assert_eq!(*interior, val); + *interior = new_val; + } + None => assert!(false), + } + + assert_eq!(it.size_hint(), (0, Some(0))); + assert!(it.next().is_none()); + } + assert_eq!(x, Some(new_val)); +} + +#[test] +fn test_ord() { + let small = Some(1.0f64); + let big = Some(5.0f64); + let nan = Some(0.0f64/0.0); + assert!(!(nan < big)); + assert!(!(nan > big)); + assert!(small < big); + assert!(None < big); + assert!(big > None); +} + +#[test] +fn test_mutate() { + let mut x = Some(3i); + assert!(x.mutate(|i| i+1)); + assert_eq!(x, Some(4i)); + assert!(x.mutate_or_set(0, |i| i+1)); + assert_eq!(x, Some(5i)); + x = None; + assert!(!x.mutate(|i| i+1)); + assert_eq!(x, None); + assert!(!x.mutate_or_set(0i, |i| i+1)); + assert_eq!(x, Some(0i)); +} + +#[test] +fn test_collect() { + let v: Option> = collect(range(0i, 0) + .map(|_| Some(0i))); + assert!(v == Some(vec![])); + + let v: Option> = collect(range(0i, 3) + .map(|x| Some(x))); + assert!(v == Some(vec![0, 1, 2])); + + let v: Option> = collect(range(0i, 3) + .map(|x| if x > 1 { None } else { Some(x) })); + assert!(v == None); + + // test that it does not take more elements than it needs + let mut functions = [|| Some(()), || None, || fail!()]; + + let v: Option> = collect(functions.mut_iter().map(|f| (*f)())); + + assert!(v == None); +} diff --git a/src/libcoretest/ptr.rs b/src/libcoretest/ptr.rs new file mode 100644 index 0000000000000..2a4ef5e275d20 --- /dev/null +++ b/src/libcoretest/ptr.rs @@ -0,0 +1,255 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. +#![allow(deprecated)] +use core::ptr::*; +use libc::c_char; +use core::mem; +use std::str; +use libc; + +#[test] +fn test() { + unsafe { + struct Pair { + fst: int, + snd: int + }; + let mut p = Pair {fst: 10, snd: 20}; + let pptr: *mut Pair = &mut p; + let iptr: *mut int = mem::transmute(pptr); + assert_eq!(*iptr, 10); + *iptr = 30; + assert_eq!(*iptr, 30); + assert_eq!(p.fst, 30); + + *pptr = Pair {fst: 50, snd: 60}; + assert_eq!(*iptr, 50); + assert_eq!(p.fst, 50); + assert_eq!(p.snd, 60); + + let v0 = vec![32000u16, 32001u16, 32002u16]; + let mut v1 = vec![0u16, 0u16, 0u16]; + + copy_memory(v1.as_mut_ptr().offset(1), + v0.as_ptr().offset(1), 1); + assert!((*v1.get(0) == 0u16 && + *v1.get(1) == 32001u16 && + *v1.get(2) == 0u16)); + copy_memory(v1.as_mut_ptr(), + v0.as_ptr().offset(2), 1); + assert!((*v1.get(0) == 32002u16 && + *v1.get(1) == 32001u16 && + *v1.get(2) == 0u16)); + copy_memory(v1.as_mut_ptr().offset(2), + v0.as_ptr(), 1u); + assert!((*v1.get(0) == 32002u16 && + *v1.get(1) == 32001u16 && + *v1.get(2) == 32000u16)); + } +} + +#[test] +fn test_position() { + use libc::c_char; + + "hello".with_c_str(|p| { + unsafe { + assert!(2u == position(p, |c| *c == 'l' as c_char)); + assert!(4u == position(p, |c| *c == 'o' as c_char)); + assert!(5u == position(p, |c| *c == 0 as c_char)); + } + }) +} + +#[test] +fn test_buf_len() { + "hello".with_c_str(|p0| { + "there".with_c_str(|p1| { + "thing".with_c_str(|p2| { + let v = vec![p0, p1, p2, null()]; + unsafe { + assert_eq!(buf_len(v.as_ptr()), 3u); + } + }) + }) + }) +} + +#[test] +fn test_is_null() { + let p: *const int = null(); + assert!(p.is_null()); + assert!(!p.is_not_null()); + + let q = unsafe { p.offset(1) }; + assert!(!q.is_null()); + assert!(q.is_not_null()); + + let mp: *mut int = mut_null(); + assert!(mp.is_null()); + assert!(!mp.is_not_null()); + + let mq = unsafe { mp.offset(1) }; + assert!(!mq.is_null()); + assert!(mq.is_not_null()); +} + +#[test] +fn test_to_option() { + unsafe { + let p: *const int = null(); + assert_eq!(p.to_option(), None); + + let q: *const int = &2; + assert_eq!(q.to_option().unwrap(), &2); + + let p: *mut int = mut_null(); + assert_eq!(p.to_option(), None); + + let q: *mut int = &mut 2; + assert_eq!(q.to_option().unwrap(), &2); + } +} + +#[test] +fn test_ptr_addition() { + unsafe { + let xs = Vec::from_elem(16, 5i); + let mut ptr = xs.as_ptr(); + let end = ptr.offset(16); + + while ptr < end { + assert_eq!(*ptr, 5); + ptr = ptr.offset(1); + } + + let mut xs_mut = xs; + let mut m_ptr = xs_mut.as_mut_ptr(); + let m_end = m_ptr.offset(16); + + while m_ptr < m_end { + *m_ptr += 5; + m_ptr = m_ptr.offset(1); + } + + assert!(xs_mut == Vec::from_elem(16, 10i)); + } +} + +#[test] +fn test_ptr_subtraction() { + unsafe { + let xs = vec![0,1,2,3,4,5,6,7,8,9]; + let mut idx = 9i8; + let ptr = xs.as_ptr(); + + while idx >= 0i8 { + assert_eq!(*(ptr.offset(idx as int)), idx as int); + idx = idx - 1i8; + } + + let mut xs_mut = xs; + let m_start = xs_mut.as_mut_ptr(); + let mut m_ptr = m_start.offset(9); + + while m_ptr >= m_start { + *m_ptr += *m_ptr; + m_ptr = m_ptr.offset(-1); + } + + assert!(xs_mut == vec![0,2,4,6,8,10,12,14,16,18]); + } +} + +#[test] +fn test_ptr_array_each_with_len() { + unsafe { + let one = "oneOne".to_c_str(); + let two = "twoTwo".to_c_str(); + let three = "threeThree".to_c_str(); + let arr = vec![ + one.as_ptr(), + two.as_ptr(), + three.as_ptr() + ]; + let expected_arr = [ + one, two, three + ]; + + let mut ctr = 0; + let mut iteration_count = 0; + array_each_with_len(arr.as_ptr(), arr.len(), |e| { + let actual = str::raw::from_c_str(e); + let expected = str::raw::from_c_str(expected_arr[ctr].as_ptr()); + assert_eq!(actual.as_slice(), expected.as_slice()); + ctr += 1; + iteration_count += 1; + }); + assert_eq!(iteration_count, 3u); + } +} + +#[test] +fn test_ptr_array_each() { + unsafe { + let one = "oneOne".to_c_str(); + let two = "twoTwo".to_c_str(); + let three = "threeThree".to_c_str(); + let arr = vec![ + one.as_ptr(), + two.as_ptr(), + three.as_ptr(), + // fake a null terminator + null() + ]; + let expected_arr = [ + one, two, three + ]; + + let arr_ptr = arr.as_ptr(); + let mut ctr = 0u; + let mut iteration_count = 0u; + array_each(arr_ptr, |e| { + let actual = str::raw::from_c_str(e); + let expected = str::raw::from_c_str(expected_arr[ctr].as_ptr()); + assert_eq!(actual.as_slice(), expected.as_slice()); + ctr += 1; + iteration_count += 1; + }); + assert_eq!(iteration_count, 3); + } +} + +#[test] +#[should_fail] +fn test_ptr_array_each_with_len_null_ptr() { + unsafe { + array_each_with_len(0 as *const *const libc::c_char, 1, |e| { + str::raw::from_c_str(e); + }); + } +} +#[test] +#[should_fail] +fn test_ptr_array_each_null_ptr() { + unsafe { + array_each(0 as *const *const libc::c_char, |e| { + str::raw::from_c_str(e); + }); + } +} + +#[test] +fn test_set_memory() { + let mut xs = [0u8, ..20]; + let ptr = xs.as_mut_ptr(); + unsafe { set_memory(ptr, 5u8, xs.len()); } + assert!(xs == [5u8, ..20]); +} diff --git a/src/libcoretest/raw.rs b/src/libcoretest/raw.rs new file mode 100644 index 0000000000000..f2c23c7c77327 --- /dev/null +++ b/src/libcoretest/raw.rs @@ -0,0 +1,35 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::raw::*; +use core::mem; + +#[test] +fn synthesize_closure() { + unsafe { + let x = 10; + let f: |int| -> int = |y| x + y; + + assert_eq!(f(20), 30); + + let original_closure: Closure = mem::transmute(f); + + let actual_function_pointer = original_closure.code; + let environment = original_closure.env; + + let new_closure = Closure { + code: actual_function_pointer, + env: environment + }; + + let new_f: |int| -> int = mem::transmute(new_closure); + assert_eq!(new_f(20), 30); + } +} diff --git a/src/libcoretest/result.rs b/src/libcoretest/result.rs new file mode 100644 index 0000000000000..7c7e0a542cd87 --- /dev/null +++ b/src/libcoretest/result.rs @@ -0,0 +1,161 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use core::result::{collect, fold, fold_}; +use core::iter::range; + +pub fn op1() -> Result { Ok(666) } +pub fn op2() -> Result { Err("sadface") } + +#[test] +pub fn test_and() { + assert_eq!(op1().and(Ok(667i)).unwrap(), 667); + assert_eq!(op1().and(Err::<(), &'static str>("bad")).unwrap_err(), + "bad"); + + assert_eq!(op2().and(Ok(667i)).unwrap_err(), "sadface"); + assert_eq!(op2().and(Err::<(),&'static str>("bad")).unwrap_err(), + "sadface"); +} + +#[test] +pub fn test_and_then() { + assert_eq!(op1().and_then(|i| Ok::(i + 1)).unwrap(), 667); + assert_eq!(op1().and_then(|_| Err::("bad")).unwrap_err(), + "bad"); + + assert_eq!(op2().and_then(|i| Ok::(i + 1)).unwrap_err(), + "sadface"); + assert_eq!(op2().and_then(|_| Err::("bad")).unwrap_err(), + "sadface"); +} + +#[test] +pub fn test_or() { + assert_eq!(op1().or(Ok(667)).unwrap(), 666); + assert_eq!(op1().or(Err("bad")).unwrap(), 666); + + assert_eq!(op2().or(Ok(667)).unwrap(), 667); + assert_eq!(op2().or(Err("bad")).unwrap_err(), "bad"); +} + +#[test] +pub fn test_or_else() { + assert_eq!(op1().or_else(|_| Ok::(667)).unwrap(), 666); + assert_eq!(op1().or_else(|e| Err::(e)).unwrap(), 666); + + assert_eq!(op2().or_else(|_| Ok::(667)).unwrap(), 667); + assert_eq!(op2().or_else(|e| Err::(e)).unwrap_err(), + "sadface"); +} + +#[test] +pub fn test_impl_map() { + assert!(Ok::(1).map(|x| x + 1) == Ok(2)); + assert!(Err::(1).map(|x| x + 1) == Err(1)); +} + +#[test] +pub fn test_impl_map_err() { + assert!(Ok::(1).map_err(|x| x + 1) == Ok(1)); + assert!(Err::(1).map_err(|x| x + 1) == Err(2)); +} + +#[test] +fn test_collect() { + let v: Result, ()> = collect(range(0i, 0).map(|_| Ok::(0))); + assert!(v == Ok(vec![])); + + let v: Result, ()> = collect(range(0i, 3).map(|x| Ok::(x))); + assert!(v == Ok(vec![0, 1, 2])); + + let v: Result, int> = collect(range(0i, 3) + .map(|x| if x > 1 { Err(x) } else { Ok(x) })); + assert!(v == Err(2)); + + // test that it does not take more elements than it needs + let mut functions = [|| Ok(()), || Err(1i), || fail!()]; + + let v: Result, int> = collect(functions.mut_iter().map(|f| (*f)())); + assert!(v == Err(1)); +} + +#[test] +fn test_fold() { + assert_eq!(fold_(range(0i, 0) + .map(|_| Ok::<(), ()>(()))), + Ok(())); + assert_eq!(fold(range(0i, 3) + .map(|x| Ok::(x)), + 0, |a, b| a + b), + Ok(3)); + assert_eq!(fold_(range(0i, 3) + .map(|x| if x > 1 { Err(x) } else { Ok(()) })), + Err(2)); + + // test that it does not take more elements than it needs + let mut functions = [|| Ok(()), || Err(1i), || fail!()]; + + assert_eq!(fold_(functions.mut_iter() + .map(|f| (*f)())), + Err(1)); +} + +#[test] +pub fn test_fmt_default() { + let ok: Result = Ok(100); + let err: Result = Err("Err"); + + let s = format!("{}", ok); + assert_eq!(s.as_slice(), "Ok(100)"); + let s = format!("{}", err); + assert_eq!(s.as_slice(), "Err(Err)"); +} + +#[test] +pub fn test_unwrap_or() { + let ok: Result = Ok(100i); + let ok_err: Result = Err("Err"); + + assert_eq!(ok.unwrap_or(50), 100); + assert_eq!(ok_err.unwrap_or(50), 50); +} + +#[test] +pub fn test_unwrap_or_else() { + fn handler(msg: &'static str) -> int { + if msg == "I got this." { + 50i + } else { + fail!("BadBad") + } + } + + let ok: Result = Ok(100); + let ok_err: Result = Err("I got this."); + + assert_eq!(ok.unwrap_or_else(handler), 100); + assert_eq!(ok_err.unwrap_or_else(handler), 50); +} + +#[test] +#[should_fail] +pub fn test_unwrap_or_else_failure() { + fn handler(msg: &'static str) -> int { + if msg == "I got this." { + 50i + } else { + fail!("BadBad") + } + } + + let bad_err: Result = Err("Unrecoverable mess."); + let _ : int = bad_err.unwrap_or_else(handler); +} diff --git a/src/libcoretest/tuple.rs b/src/libcoretest/tuple.rs new file mode 100644 index 0000000000000..be71e42ae9ad6 --- /dev/null +++ b/src/libcoretest/tuple.rs @@ -0,0 +1,92 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#[test] +fn test_clone() { + let a = (1i, "2"); + let b = a.clone(); + assert_eq!(a, b); +} + +#[test] +fn test_getters() { + macro_rules! test_getter( + ($x:expr, $valN:ident, $refN:ident, $mutN:ident, + $init:expr, $incr:expr, $result:expr) => ({ + assert_eq!($x.$valN(), $init); + assert_eq!(*$x.$refN(), $init); + *$x.$mutN() += $incr; + assert_eq!(*$x.$refN(), $result); + }) + ) + let mut x = (0u8, 1u16, 2u32, 3u64, 4u, 5i8, 6i16, 7i32, 8i64, 9i, 10f32, 11f64); + test_getter!(x, val0, ref0, mut0, 0, 1, 1); + test_getter!(x, val1, ref1, mut1, 1, 1, 2); + test_getter!(x, val2, ref2, mut2, 2, 1, 3); + test_getter!(x, val3, ref3, mut3, 3, 1, 4); + test_getter!(x, val4, ref4, mut4, 4, 1, 5); + test_getter!(x, val5, ref5, mut5, 5, 1, 6); + test_getter!(x, val6, ref6, mut6, 6, 1, 7); + test_getter!(x, val7, ref7, mut7, 7, 1, 8); + test_getter!(x, val8, ref8, mut8, 8, 1, 9); + test_getter!(x, val9, ref9, mut9, 9, 1, 10); + test_getter!(x, val10, ref10, mut10, 10.0, 1.0, 11.0); + test_getter!(x, val11, ref11, mut11, 11.0, 1.0, 12.0); +} + +#[test] +fn test_tuple_cmp() { + let (small, big) = ((1u, 2u, 3u), (3u, 2u, 1u)); + + let nan = 0.0f64/0.0; + + // PartialEq + assert_eq!(small, small); + assert_eq!(big, big); + assert!(small != big); + assert!(big != small); + + // PartialOrd + assert!(small < big); + assert!(!(small < small)); + assert!(!(big < small)); + assert!(!(big < big)); + + assert!(small <= small); + assert!(big <= big); + + assert!(big > small); + assert!(small >= small); + assert!(big >= small); + assert!(big >= big); + + assert!(!((1.0f64, 2.0f64) < (nan, 3.0))); + assert!(!((1.0f64, 2.0f64) <= (nan, 3.0))); + assert!(!((1.0f64, 2.0f64) > (nan, 3.0))); + assert!(!((1.0f64, 2.0f64) >= (nan, 3.0))); + assert!(((1.0f64, 2.0f64) < (2.0, nan))); + assert!(!((2.0f64, 2.0f64) < (2.0, nan))); + + // Ord + assert!(small.cmp(&small) == Equal); + assert!(big.cmp(&big) == Equal); + assert!(small.cmp(&big) == Less); + assert!(big.cmp(&small) == Greater); +} + +#[test] +fn test_show() { + let s = format!("{}", (1i,)); + assert_eq!(s.as_slice(), "(1,)"); + let s = format!("{}", (1i, true)); + assert_eq!(s.as_slice(), "(1, true)"); + let s = format!("{}", (1i, "hi", true)); + assert_eq!(s.as_slice(), "(1, hi, true)"); +} diff --git a/src/libstd/gc.rs b/src/libstd/gc.rs index 363c577563e8c..44988a23070d7 100644 --- a/src/libstd/gc.rs +++ b/src/libstd/gc.rs @@ -103,6 +103,13 @@ mod tests { use super::*; use cell::RefCell; + #[test] + fn test_managed_clone() { + let a = box(GC) 5i; + let b: Gc = a.clone(); + assert!(a == b); + } + #[test] fn test_clone() { let x = Gc::new(RefCell::new(5));