]> git.lizzy.rs Git - rust.git/commitdiff
auto merge of #8308 : blake2-ppc/rust/str-slice-bytes, r=alexcrichton
authorbors <bors@rust-lang.org>
Tue, 6 Aug 2013 12:26:01 +0000 (05:26 -0700)
committerbors <bors@rust-lang.org>
Tue, 6 Aug 2013 12:26:01 +0000 (05:26 -0700)
`fn slice_bytes` is marked unsafe since it allows violating the valid
string encoding property; but the function did also allow extending the
lifetime of the slice by mistake, since it's returning `&str`.

Use the annotation `slice_bytes<'a>(&'a str, ...) -> &'a str` so
that all uses of `slice_bytes` are region checked correctly.

132 files changed:
src/compiletest/compiletest.rs
src/compiletest/runtest.rs
src/libextra/arena.rs
src/libextra/base64.rs
src/libextra/bitv.rs
src/libextra/enum_set.rs [new file with mode: 0644]
src/libextra/extra.rs
src/libextra/fileinput.rs
src/libextra/getopts.rs
src/libextra/num/bigint.rs
src/libextra/ringbuf.rs
src/libextra/semver.rs
src/libextra/smallintmap.rs
src/libextra/test.rs
src/libextra/url.rs
src/librustc/back/link.rs
src/librustc/back/passes.rs
src/librustc/driver/driver.rs
src/librustc/front/test.rs
src/librustc/metadata/tyencode.rs
src/librustc/middle/astencode.rs
src/librustc/middle/borrowck/check_loans.rs
src/librustc/middle/check_loop.rs
src/librustc/middle/check_match.rs
src/librustc/middle/const_eval.rs
src/librustc/middle/kind.rs
src/librustc/middle/privacy.rs
src/librustc/middle/resolve.rs
src/librustc/middle/trans/_match.rs
src/librustc/middle/trans/adt.rs
src/librustc/middle/trans/base.rs
src/librustc/middle/trans/build.rs
src/librustc/middle/trans/cabi.rs
src/librustc/middle/trans/closure.rs
src/librustc/middle/trans/common.rs
src/librustc/middle/trans/controlflow.rs
src/librustc/middle/trans/debuginfo.rs
src/librustc/middle/trans/foreign.rs
src/librustc/middle/trans/glue.rs
src/librustc/middle/trans/monomorphize.rs
src/librustc/middle/trans/reflect.rs
src/librustc/middle/trans/type_of.rs
src/librustc/middle/ty.rs
src/librustc/middle/typeck/astconv.rs
src/librustc/middle/typeck/check/_match.rs
src/librustc/middle/typeck/check/method.rs
src/librustc/middle/typeck/check/mod.rs
src/librustc/middle/typeck/infer/glb.rs
src/librustc/middle/typeck/mod.rs
src/librustc/middle/typeck/rscope.rs
src/librustc/rustc.rs
src/librustc/util/enum_set.rs [deleted file]
src/librustc/util/ppaux.rs
src/librustdoc/attr_pass.rs
src/librustdoc/config.rs
src/librustdoc/desc_to_brief_pass.rs
src/librustdoc/doc.rs
src/librustdoc/markdown_index_pass.rs
src/librustdoc/markdown_pass.rs
src/librustdoc/sectionalize_pass.rs
src/librustdoc/tystr_pass.rs
src/librusti/rusti.rs
src/librustpkg/rustpkg.rs
src/librustpkg/util.rs
src/libstd/at_vec.rs
src/libstd/either.rs
src/libstd/hashmap.rs
src/libstd/io.rs
src/libstd/iterator.rs
src/libstd/local_data.rs
src/libstd/num/strconv.rs
src/libstd/num/uint.rs
src/libstd/option.rs
src/libstd/os.rs
src/libstd/ptr.rs
src/libstd/rand.rs
src/libstd/result.rs
src/libstd/rt/io/flate.rs
src/libstd/rt/io/mod.rs
src/libstd/rt/mod.rs
src/libstd/rt/task.rs
src/libstd/rt/test.rs
src/libstd/rt/util.rs
src/libstd/rt/uv/net.rs
src/libstd/rt/uv/uvio.rs
src/libstd/str.rs
src/libstd/task/mod.rs
src/libstd/trie.rs
src/libstd/vec.rs
src/libsyntax/abi.rs
src/libsyntax/ast.rs
src/libsyntax/attr.rs
src/libsyntax/codemap.rs
src/libsyntax/ext/base.rs
src/libsyntax/ext/deriving/generic.rs
src/libsyntax/ext/expand.rs
src/libsyntax/ext/source_util.rs
src/libsyntax/parse/parser.rs
src/libsyntax/print/pprust.rs
src/test/bench/core-map.rs
src/test/bench/core-set.rs
src/test/bench/core-uint-to-str.rs
src/test/bench/graph500-bfs.rs
src/test/bench/msgsend-pipes-shared.rs
src/test/bench/msgsend-pipes.rs
src/test/bench/msgsend-ring-mutex-arcs.rs
src/test/bench/msgsend-ring-rw-arcs.rs
src/test/bench/shootout-ackermann.rs
src/test/bench/shootout-binarytrees.rs
src/test/bench/shootout-chameneos-redux.rs
src/test/bench/shootout-fannkuch-redux.rs
src/test/bench/shootout-fasta-redux.rs
src/test/bench/shootout-fasta.rs
src/test/bench/shootout-fibo.rs
src/test/bench/shootout-mandelbrot.rs
src/test/bench/shootout-nbody.rs
src/test/bench/shootout-pfib.rs
src/test/bench/shootout-spectralnorm.rs
src/test/bench/shootout-threadring.rs
src/test/bench/std-smallintmap.rs
src/test/bench/sudoku.rs
src/test/bench/task-perf-jargon-metal-smoke.rs
src/test/bench/task-perf-linked-failure.rs
src/test/bench/task-perf-spawnalot.rs
src/test/compile-fail/arc-rw-read-mode-shouldnt-escape.rs
src/test/compile-fail/arc-rw-write-mode-shouldnt-escape.rs
src/test/run-fail/result-get-fail.rs
src/test/run-pass/borrowck-wg-borrow-mut-to-imm.rs
src/test/run-pass/borrowed-ptr-pattern-option.rs
src/test/run-pass/option_addition.rs
src/test/run-pass/placement-new-arena.rs
src/test/run-pass/region-dependent-addr-of.rs

index b01de242590d0e9e580343d6c39d391c2055c271..094d176980b81d2ebafae44bcb9787cac23dc044 100644 (file)
@@ -131,7 +131,7 @@ fn opt_path(m: &getopts::Matches, nm: &str) -> Path {
         ratchet_noise_percent:
             getopts::opt_maybe_str(matches,
                                    "ratchet-noise-percent").map(|s|
-                                                                f64::from_str(*s).get()),
+                                                                f64::from_str(*s).unwrap()),
         runtool: getopts::opt_maybe_str(matches, "runtool"),
         rustcflags: getopts::opt_maybe_str(matches, "rustcflags"),
         jit: getopts::opt_present(matches, "jit"),
@@ -267,7 +267,7 @@ pub fn is_test(config: &config, testfile: &Path) -> bool {
           _ => ~[~".rc", ~".rs"]
         };
     let invalid_prefixes = ~[~".", ~"#", ~"~"];
-    let name = testfile.filename().get();
+    let name = testfile.filename().unwrap();
 
     let mut valid = false;
 
@@ -300,7 +300,7 @@ pub fn make_test_name(config: &config, testfile: &Path) -> test::TestName {
     fn shorten(path: &Path) -> ~str {
         let filename = path.filename();
         let dir = path.pop().filename();
-        fmt!("%s/%s", dir.get_or_default(~""), filename.get_or_default(~""))
+        fmt!("%s/%s", dir.unwrap_or_default(~""), filename.unwrap_or_default(~""))
     }
 
     test::DynTestName(fmt!("[%s] %s",
index 74b4a1de5e0d13aecca9d2a0ea4c8261d050d6d0..5c1cc78d678f361f1525226fbcb8e1bf7f807f34 100644 (file)
@@ -145,7 +145,7 @@ fn run_pretty_test(config: &config, props: &TestProps, testfile: &Path) {
     let rounds =
         match props.pp_exact { Some(_) => 1, None => 2 };
 
-    let mut srcs = ~[io::read_whole_file_str(testfile).get()];
+    let mut srcs = ~[io::read_whole_file_str(testfile).unwrap()];
 
     let mut round = 0;
     while round < rounds {
@@ -166,7 +166,7 @@ fn run_pretty_test(config: &config, props: &TestProps, testfile: &Path) {
         match props.pp_exact {
           Some(ref file) => {
             let filepath = testfile.dir_path().push_rel(file);
-            io::read_whole_file_str(&filepath).get()
+            io::read_whole_file_str(&filepath).unwrap()
           }
           None => { srcs[srcs.len() - 2u].clone() }
         };
@@ -448,7 +448,7 @@ fn scan_until_char(haystack: &str, needle: char, idx: &mut uint) -> bool {
     if opt.is_none() {
         return false;
     }
-    *idx = opt.get();
+    *idx = opt.unwrap();
     return true;
 }
 
@@ -709,7 +709,7 @@ fn aux_output_dir_name(config: &config, testfile: &Path) -> Path {
 }
 
 fn output_testname(testfile: &Path) -> Path {
-    Path(testfile.filestem().get())
+    Path(testfile.filestem().unwrap())
 }
 
 fn output_base_name(config: &config, testfile: &Path) -> Path {
@@ -878,7 +878,7 @@ fn append_suffix_to_stem(p: &Path, suffix: &str) -> Path {
     if suffix.len() == 0 {
         (*p).clone()
     } else {
-        let stem = p.filestem().get();
+        let stem = p.filestem().unwrap();
         p.with_filestem(stem + "-" + suffix)
     }
 }
@@ -938,7 +938,7 @@ fn disassemble_extract(config: &config, _props: &TestProps,
 
 
 fn count_extracted_lines(p: &Path) -> uint {
-    let x = io::read_whole_file_str(&p.with_filetype("ll")).get();
+    let x = io::read_whole_file_str(&p.with_filetype("ll")).unwrap();
     x.line_iter().len_()
 }
 
index 47b64d76951683087cd3e91666c78e4b8821477d..ae4356eb4baccb163c586078b047c7bf8c26ccaf 100644 (file)
@@ -67,17 +67,16 @@ pub struct Arena {
     priv chunks: @mut MutList<Chunk>,
 }
 
-#[unsafe_destructor]
-impl Drop for Arena {
-    fn drop(&self) {
-        unsafe {
-            destroy_chunk(&self.head);
-            do self.chunks.each |chunk| {
-                if !chunk.is_pod {
-                    destroy_chunk(chunk);
-                }
-                true
-            };
+impl Arena {
+    pub fn new() -> Arena {
+        Arena::new_with_size(32u)
+    }
+
+    pub fn new_with_size(initial_size: uint) -> Arena {
+        Arena {
+            head: chunk(initial_size, false),
+            pod_head: chunk(initial_size, true),
+            chunks: @mut MutNil,
         }
     }
 }
@@ -92,18 +91,21 @@ fn chunk(size: uint, is_pod: bool) -> Chunk {
     }
 }
 
-pub fn arena_with_size(initial_size: uint) -> Arena {
-    Arena {
-        head: chunk(initial_size, false),
-        pod_head: chunk(initial_size, true),
-        chunks: @mut MutNil,
+#[unsafe_destructor]
+impl Drop for Arena {
+    fn drop(&self) {
+        unsafe {
+            destroy_chunk(&self.head);
+            do self.chunks.each |chunk| {
+                if !chunk.is_pod {
+                    destroy_chunk(chunk);
+                }
+                true
+            };
+        }
     }
 }
 
-pub fn Arena() -> Arena {
-    arena_with_size(32u)
-}
-
 #[inline]
 fn round_up_to(base: uint, align: uint) -> uint {
     (base + (align - 1)) & !(align - 1)
@@ -276,7 +278,7 @@ pub fn alloc<'a, T>(&'a self, op: &fn() -> T) -> &'a T {
 
 #[test]
 fn test_arena_destructors() {
-    let arena = Arena();
+    let arena = Arena::new();
     for i in range(0u, 10) {
         // Arena allocate something with drop glue to make sure it
         // doesn't leak.
@@ -291,7 +293,7 @@ fn test_arena_destructors() {
 #[should_fail]
 #[ignore(cfg(windows))]
 fn test_arena_destructors_fail() {
-    let arena = Arena();
+    let arena = Arena::new();
     // Put some stuff in the arena.
     for i in range(0u, 10) {
         // Arena allocate something with drop glue to make sure it
index f2cbcf86935e7256c99a33cc095bbcaa16843cb6..550b891a4db16c22356d20be362f55ca7b06e6cb 100644 (file)
@@ -322,24 +322,24 @@ fn test_to_base64_url_safe() {
 
     #[test]
     fn test_from_base64_basic() {
-        assert_eq!("".from_base64().get(), "".as_bytes().to_owned());
-        assert_eq!("Zg==".from_base64().get(), "f".as_bytes().to_owned());
-        assert_eq!("Zm8=".from_base64().get(), "fo".as_bytes().to_owned());
-        assert_eq!("Zm9v".from_base64().get(), "foo".as_bytes().to_owned());
-        assert_eq!("Zm9vYg==".from_base64().get(), "foob".as_bytes().to_owned());
-        assert_eq!("Zm9vYmE=".from_base64().get(), "fooba".as_bytes().to_owned());
-        assert_eq!("Zm9vYmFy".from_base64().get(), "foobar".as_bytes().to_owned());
+        assert_eq!("".from_base64().unwrap(), "".as_bytes().to_owned());
+        assert_eq!("Zg==".from_base64().unwrap(), "f".as_bytes().to_owned());
+        assert_eq!("Zm8=".from_base64().unwrap(), "fo".as_bytes().to_owned());
+        assert_eq!("Zm9v".from_base64().unwrap(), "foo".as_bytes().to_owned());
+        assert_eq!("Zm9vYg==".from_base64().unwrap(), "foob".as_bytes().to_owned());
+        assert_eq!("Zm9vYmE=".from_base64().unwrap(), "fooba".as_bytes().to_owned());
+        assert_eq!("Zm9vYmFy".from_base64().unwrap(), "foobar".as_bytes().to_owned());
     }
 
     #[test]
     fn test_from_base64_newlines() {
-        assert_eq!("Zm9v\r\nYmFy".from_base64().get(),
+        assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap(),
                    "foobar".as_bytes().to_owned());
     }
 
     #[test]
     fn test_from_base64_urlsafe() {
-        assert_eq!("-_8".from_base64().get(), "+/8=".from_base64().get());
+        assert_eq!("-_8".from_base64().unwrap(), "+/8=".from_base64().unwrap());
     }
 
     #[test]
@@ -364,7 +364,7 @@ fn test_base64_random() {
                     push(random());
                 }
             };
-            assert_eq!(v.to_base64(STANDARD).from_base64().get(), v);
+            assert_eq!(v.to_base64(STANDARD).from_base64().unwrap(), v);
         }
     }
 
index bf618d7bd3a6ff1065f5e28c138beca29c7d0cde..6dedd9ee4dd266f95da9777cf67bd7737e8edc18 100644 (file)
@@ -13,7 +13,7 @@
 
 use std::cmp;
 use std::iterator::RandomAccessIterator;
-use std::iterator::{Invert, Enumerate};
+use std::iterator::{Invert, Enumerate, Repeat, Map, Zip};
 use std::num;
 use std::ops;
 use std::uint;
@@ -206,14 +206,13 @@ pub fn set(&mut self, i: uint, x: bool) {
     #[inline]
     pub fn equals(&self, b: &BigBitv, nbits: uint) -> bool {
         let len = b.storage.len();
-        do uint::iterate(0, len) |i| {
+        for i in range(0, len) {
             let mask = big_mask(nbits, i);
             if mask & self.storage[i] != mask & b.storage[i] {
-                false
-            } else {
-                true
+                return false;
             }
         }
+        true
     }
 }
 
@@ -864,13 +863,12 @@ impl BitvSet {
     /// w1, w2) where the bit location is the number of bits offset so far,
     /// and w1/w2 are the words coming from the two vectors self, other.
     fn common_iter<'a>(&'a self, other: &'a BitvSet)
-        -> MapE<(uint,&uint),(uint,uint,uint), &'a ~[uint],Enumerate<vec::VecIterator<'a,uint>>> {
-        let min = num::min(self.bitv.storage.len(),
-                            other.bitv.storage.len());
-        MapE{iter: self.bitv.storage.slice(0, min).iter().enumerate(),
-             env: &other.bitv.storage,
-             f: |(i, &w): (uint, &uint), o_store| (i * uint::bits, w, o_store[i])
-        }
+        -> Map<'static, ((uint, &'a uint), &'a ~[uint]), (uint, uint, uint),
+               Zip<Enumerate<vec::VecIterator<'a, uint>>, Repeat<&'a ~[uint]>>> {
+        let min = num::min(self.bitv.storage.len(), other.bitv.storage.len());
+        self.bitv.storage.slice(0, min).iter().enumerate()
+            .zip(Repeat::new(&other.bitv.storage))
+            .transform(|((i, &w), o_store)| (i * uint::bits, w, o_store[i]))
     }
 
     /// Visits each word in self or other that extends beyond the other. This
@@ -881,45 +879,21 @@ fn common_iter<'a>(&'a self, other: &'a BitvSet)
     /// is true if the word comes from 'self', and false if it comes from
     /// 'other'.
     fn outlier_iter<'a>(&'a self, other: &'a BitvSet)
-        -> MapE<(uint, &uint),(bool, uint, uint), uint, Enumerate<vec::VecIterator<'a, uint>>> {
-        let len1 = self.bitv.storage.len();
-        let len2 = other.bitv.storage.len();
-        let min = num::min(len1, len2);
-
-        if min < len1 {
-            MapE{iter: self.bitv.storage.slice(min, len1).iter().enumerate(),
-                 env: min,
-                 f: |(i, &w): (uint, &uint), min| (true, (i + min) * uint::bits, w)
-            }
+        -> Map<'static, ((uint, &'a uint), uint), (bool, uint, uint),
+               Zip<Enumerate<vec::VecIterator<'a, uint>>, Repeat<uint>>> {
+        let slen = self.bitv.storage.len();
+        let olen = other.bitv.storage.len();
+
+        if olen < slen {
+            self.bitv.storage.slice_from(olen).iter().enumerate()
+                .zip(Repeat::new(olen))
+                .transform(|((i, &w), min)| (true, (i + min) * uint::bits, w))
         } else {
-            MapE{iter: other.bitv.storage.slice(min, len2).iter().enumerate(),
-                 env: min,
-                 f: |(i, &w): (uint, &uint), min| (false, (i + min) * uint::bits, w)
-            }
-        }
-    }
-}
-
-/// Like iterator::Map with explicit env capture
-struct MapE<A, B, Env, I> {
-    priv env: Env,
-    priv f: &'static fn(A, Env) -> B,
-    priv iter: I,
-}
-
-impl<'self, A, B, Env: Clone, I: Iterator<A>> Iterator<B> for MapE<A, B, Env, I> {
-    #[inline]
-    fn next(&mut self) -> Option<B> {
-        match self.iter.next() {
-            Some(elt) => Some((self.f)(elt, self.env.clone())),
-            None => None
+            other.bitv.storage.slice_from(slen).iter().enumerate()
+                .zip(Repeat::new(slen))
+                .transform(|((i, &w), min)| (false, (i + min) * uint::bits, w))
         }
     }
-
-    #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) {
-        self.iter.size_hint()
-    }
 }
 
 pub struct BitvSetIterator<'self> {
diff --git a/src/libextra/enum_set.rs b/src/libextra/enum_set.rs
new file mode 100644 (file)
index 0000000..25501fa
--- /dev/null
@@ -0,0 +1,288 @@
+// Copyright 2012 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 <LICENSE-APACHE or
+// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
+// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
+// option. This file may not be copied, modified, or distributed
+// except according to those terms.
+
+use std::iterator::Iterator;
+
+#[deriving(Clone, Eq, IterBytes, ToStr)]
+/// A specialized Set implementation to use enum types.
+pub struct EnumSet<E> {
+    // We must maintain the invariant that no bits are set
+    // for which no variant exists
+    priv bits: uint
+}
+
+/// An iterface for casting C-like enum to uint and back.
+pub trait CLike {
+    /// Converts C-like enum to uint.
+    pub fn to_uint(&self) -> uint;
+    /// Converts uint to C-like enum.
+    pub fn from_uint(uint) -> Self;
+}
+
+fn bit<E:CLike>(e: E) -> uint {
+    1 << e.to_uint()
+}
+
+impl<E:CLike> EnumSet<E> {
+    /// Returns an empty EnumSet.
+    pub fn empty() -> EnumSet<E> {
+        EnumSet {bits: 0}
+    }
+
+    /// Returns true if an EnumSet is empty.
+    pub fn is_empty(&self) -> bool {
+        self.bits == 0
+    }
+
+    /// Returns true if an EnumSet contains any enum of a given EnumSet
+    pub fn intersects(&self, e: EnumSet<E>) -> bool {
+        (self.bits & e.bits) != 0
+    }
+
+    /// Returns an intersection of both EnumSets.
+    pub fn intersection(&self, e: EnumSet<E>) -> EnumSet<E> {
+        EnumSet {bits: self.bits & e.bits}
+    }
+
+    /// Returns true if a given EnumSet is included in an EnumSet.
+    pub fn contains(&self, e: EnumSet<E>) -> bool {
+        (self.bits & e.bits) == e.bits
+    }
+
+    /// Returns a union of both EnumSets.
+    pub fn union(&self, e: EnumSet<E>) -> EnumSet<E> {
+        EnumSet {bits: self.bits | e.bits}
+    }
+
+    /// Add an enum to an EnumSet
+    pub fn add(&mut self, e: E) {
+        self.bits |= bit(e);
+    }
+
+    /// Returns true if an EnumSet contains a given enum
+    pub fn contains_elem(&self, e: E) -> bool {
+        (self.bits & bit(e)) != 0
+    }
+
+    /// Returns an iterator over an EnumSet
+    pub fn iter(&self) -> EnumSetIterator<E> {
+        EnumSetIterator::new(self.bits)
+    }
+}
+
+impl<E:CLike> Sub<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
+    fn sub(&self, e: &EnumSet<E>) -> EnumSet<E> {
+        EnumSet {bits: self.bits & !e.bits}
+    }
+}
+
+impl<E:CLike> BitOr<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
+    fn bitor(&self, e: &EnumSet<E>) -> EnumSet<E> {
+        EnumSet {bits: self.bits | e.bits}
+    }
+}
+
+impl<E:CLike> BitAnd<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
+    fn bitand(&self, e: &EnumSet<E>) -> EnumSet<E> {
+        EnumSet {bits: self.bits & e.bits}
+    }
+}
+
+/// An iterator over an EnumSet
+pub struct EnumSetIterator<E> {
+    priv index: uint,
+    priv bits: uint,
+}
+
+impl<E:CLike> EnumSetIterator<E> {
+    fn new(bits: uint) -> EnumSetIterator<E> {
+        EnumSetIterator { index: 0, bits: bits }
+    }
+}
+
+impl<E:CLike> Iterator<E> for EnumSetIterator<E> {
+    fn next(&mut self) -> Option<E> {
+        if (self.bits == 0) {
+            return None;
+        }
+
+        while (self.bits & 1) == 0 {
+            self.index += 1;
+            self.bits >>= 1;
+        }
+        let elem = CLike::from_uint(self.index);
+        self.index += 1;
+        self.bits >>= 1;
+        Some(elem)
+    }
+
+    fn size_hint(&self) -> (uint, Option<uint>) {
+        let exact = self.bits.population_count();
+        (exact, Some(exact))
+    }
+}
+
+#[cfg(test)]
+mod test {
+
+    use std::cast;
+
+    use enum_set::*;
+
+    #[deriving(Eq)]
+    enum Foo {
+        A, B, C
+    }
+
+    impl CLike for Foo {
+        pub fn to_uint(&self) -> uint {
+            *self as uint
+        }
+
+        pub fn from_uint(v: uint) -> Foo {
+            unsafe { cast::transmute(v) }
+        }
+    }
+
+    #[test]
+    fn test_empty() {
+        let e: EnumSet<Foo> = EnumSet::empty();
+        assert!(e.is_empty());
+    }
+
+    ///////////////////////////////////////////////////////////////////////////
+    // intersect
+
+    #[test]
+    fn test_two_empties_do_not_intersect() {
+        let e1: EnumSet<Foo> = EnumSet::empty();
+        let e2: EnumSet<Foo> = EnumSet::empty();
+        assert!(!e1.intersects(e2));
+    }
+
+    #[test]
+    fn test_empty_does_not_intersect_with_full() {
+        let e1: EnumSet<Foo> = EnumSet::empty();
+
+        let mut e2: EnumSet<Foo> = EnumSet::empty();
+        e2.add(A);
+        e2.add(B);
+        e2.add(C);
+
+        assert!(!e1.intersects(e2));
+    }
+
+    #[test]
+    fn test_disjoint_intersects() {
+        let mut e1: EnumSet<Foo> = EnumSet::empty();
+        e1.add(A);
+
+        let mut e2: EnumSet<Foo> = EnumSet::empty();
+        e2.add(B);
+
+        assert!(!e1.intersects(e2));
+    }
+
+    #[test]
+    fn test_overlapping_intersects() {
+        let mut e1: EnumSet<Foo> = EnumSet::empty();
+        e1.add(A);
+
+        let mut e2: EnumSet<Foo> = EnumSet::empty();
+        e2.add(A);
+        e2.add(B);
+
+        assert!(e1.intersects(e2));
+    }
+
+    ///////////////////////////////////////////////////////////////////////////
+    // contains and contains_elem
+
+    #[test]
+    fn test_contains() {
+        let mut e1: EnumSet<Foo> = EnumSet::empty();
+        e1.add(A);
+
+        let mut e2: EnumSet<Foo> = EnumSet::empty();
+        e2.add(A);
+        e2.add(B);
+
+        assert!(!e1.contains(e2));
+        assert!(e2.contains(e1));
+    }
+
+    #[test]
+    fn test_contains_elem() {
+        let mut e1: EnumSet<Foo> = EnumSet::empty();
+        e1.add(A);
+        assert!(e1.contains_elem(A));
+        assert!(!e1.contains_elem(B));
+        assert!(!e1.contains_elem(C));
+
+        e1.add(A);
+        e1.add(B);
+        assert!(e1.contains_elem(A));
+        assert!(e1.contains_elem(B));
+        assert!(!e1.contains_elem(C));
+    }
+
+    ///////////////////////////////////////////////////////////////////////////
+    // iter
+
+    #[test]
+    fn test_iterator() {
+        let mut e1: EnumSet<Foo> = EnumSet::empty();
+
+        let elems: ~[Foo] = e1.iter().collect();
+        assert_eq!(~[], elems)
+
+        e1.add(A);
+        let elems: ~[Foo] = e1.iter().collect();
+        assert_eq!(~[A], elems)
+
+        e1.add(C);
+        let elems: ~[Foo] = e1.iter().collect();
+        assert_eq!(~[A,C], elems)
+
+        e1.add(C);
+        let elems: ~[Foo] = e1.iter().collect();
+        assert_eq!(~[A,C], elems)
+
+        e1.add(B);
+        let elems: ~[Foo] = e1.iter().collect();
+        assert_eq!(~[A,B,C], elems)
+    }
+
+    ///////////////////////////////////////////////////////////////////////////
+    // operators
+
+    #[test]
+    fn test_operators() {
+        let mut e1: EnumSet<Foo> = EnumSet::empty();
+        e1.add(A);
+        e1.add(C);
+
+        let mut e2: EnumSet<Foo> = EnumSet::empty();
+        e2.add(B);
+        e2.add(C);
+
+        let e_union = e1 | e2;
+        let elems: ~[Foo] = e_union.iter().collect();
+        assert_eq!(~[A,B,C], elems)
+
+        let e_intersection = e1 & e2;
+        let elems: ~[Foo] = e_intersection.iter().collect();
+        assert_eq!(~[C], elems)
+
+        let e_subtract = e1 - e2;
+        let elems: ~[Foo] = e_subtract.iter().collect();
+        assert_eq!(~[A], elems)
+    }
+}
index e6134bb340cd8c45b708ab71d6f3539b45b4061d..58929778a59e20f6afb11105979894b771755207 100644 (file)
@@ -91,6 +91,7 @@
 pub mod base64;
 pub mod rl;
 pub mod workcache;
+pub mod enum_set;
 #[path="num/bigint.rs"]
 pub mod bigint;
 #[path="num/rational.rs"]
index a161989c3751623b1ddd5ea982130c7ae9c20f01..7a36b25eac57a53b32bb877c21e69bb60e97c109 100644 (file)
@@ -526,8 +526,8 @@ fn test_input_vec_state() {
 
         do input_vec_state(filenames) |line, state| {
             let nums: ~[&str] = line.split_iter(' ').collect();
-            let file_num = uint::from_str(nums[0]).get();
-            let line_num = uint::from_str(nums[1]).get();
+            let file_num = uint::from_str(nums[0]).unwrap();
+            let line_num = uint::from_str(nums[1]).unwrap();
             assert_eq!(line_num, state.line_num_file);
             assert_eq!(file_num * 3 + line_num, state.line_num);
             true
index b9ee38317f3210356fd9549c71ef96b3d51ffcb5..15aac8ef47c9e660dd59ac98ab0e947f0951b1c9 100644 (file)
@@ -196,7 +196,7 @@ fn find_opt(opts: &[Opt], nm: Name) -> Option<uint> {
  * The type returned when the command line does not conform to the
  * expected format. Pass this value to <fail_str> to get an error message.
  */
-#[deriving(Clone, Eq)]
+#[deriving(Clone, Eq, ToStr)]
 pub enum Fail_ {
     ArgumentMissing(~str),
     UnrecognizedOption(~str),
@@ -288,7 +288,7 @@ pub fn getopts(args: &[~str], opts: &[Opt]) -> Result {
                       None => {
                         let arg_follows =
                             last_valid_opt_id.is_some() &&
-                            match opts[last_valid_opt_id.get()]
+                            match opts[last_valid_opt_id.unwrap()]
                               .hasarg {
 
                               Yes | Maybe => true,
@@ -322,7 +322,7 @@ pub fn getopts(args: &[~str], opts: &[Opt]) -> Result {
                   }
                   Maybe => {
                     if !i_arg.is_none() {
-                        vals[optid].push(Val((i_arg.clone()).get()));
+                        vals[optid].push(Val((i_arg.clone()).unwrap()));
                     } else if name_pos < names.len() ||
                                   i + 1 == l || is_arg(args[i + 1]) {
                         vals[optid].push(Given);
@@ -330,7 +330,7 @@ pub fn getopts(args: &[~str], opts: &[Opt]) -> Result {
                   }
                   Yes => {
                     if !i_arg.is_none() {
-                        vals[optid].push(Val(i_arg.clone().get()));
+                        vals[optid].push(Val(i_arg.clone().unwrap()));
                     } else if i + 1 == l {
                         return Err(ArgumentMissing(name_str(nm)));
                     } else { i += 1; vals[optid].push(Val(args[i].clone())); }
index ab843fe65464bd599f6f812f713d25ef32ce747e..bced00902c95f5abdcc62dee20adb3b42f14d372 100644 (file)
@@ -1510,11 +1510,11 @@ fn check(a: uint, b: uint, c: uint) {
 
     #[test]
     fn test_is_even() {
-        assert!(FromStr::from_str::<BigUint>("1").get().is_odd());
-        assert!(FromStr::from_str::<BigUint>("2").get().is_even());
-        assert!(FromStr::from_str::<BigUint>("1000").get().is_even());
-        assert!(FromStr::from_str::<BigUint>("1000000000000000000000").get().is_even());
-        assert!(FromStr::from_str::<BigUint>("1000000000000000000001").get().is_odd());
+        assert!(FromStr::from_str::<BigUint>("1").unwrap().is_odd());
+        assert!(FromStr::from_str::<BigUint>("2").unwrap().is_even());
+        assert!(FromStr::from_str::<BigUint>("1000").unwrap().is_even());
+        assert!(FromStr::from_str::<BigUint>("1000000000000000000000").unwrap().is_even());
+        assert!(FromStr::from_str::<BigUint>("1000000000000000000001").unwrap().is_odd());
         assert!((BigUint::from_uint(1) << 64).is_even());
         assert!(((BigUint::from_uint(1) << 64) + BigUint::from_uint(1)).is_odd());
     }
@@ -1595,7 +1595,7 @@ fn test_from_str_radix() {
             let &(ref n, ref rs) = num_pair;
             for str_pair in rs.iter() {
                 let &(ref radix, ref str) = str_pair;
-                assert_eq!(n, &FromStrRadix::from_str_radix(*str, *radix).get());
+                assert_eq!(n, &FromStrRadix::from_str_radix(*str, *radix).unwrap());
             }
         }
 
index 89d23191a7634331bf95fa976995425d9b14a053..9833bd5d1cbf2cebe758fe7213832681d2bba76c 100644 (file)
@@ -437,12 +437,12 @@ fn test_parameterized<T:Clone + Eq>(a: T, b: T, c: T, d: T) {
         assert_eq!(deq.len(), 3);
         deq.push_back(d.clone());
         assert_eq!(deq.len(), 4);
-        assert_eq!((*deq.front().get()).clone(), b.clone());
-        assert_eq!((*deq.back().get()).clone(), d.clone());
-        assert_eq!(deq.pop_front().get(), b.clone());
-        assert_eq!(deq.pop_back().get(), d.clone());
-        assert_eq!(deq.pop_back().get(), c.clone());
-        assert_eq!(deq.pop_back().get(), a.clone());
+        assert_eq!((*deq.front().unwrap()).clone(), b.clone());
+        assert_eq!((*deq.back().unwrap()).clone(), d.clone());
+        assert_eq!(deq.pop_front().unwrap(), b.clone());
+        assert_eq!(deq.pop_back().unwrap(), d.clone());
+        assert_eq!(deq.pop_back().unwrap(), c.clone());
+        assert_eq!(deq.pop_back().unwrap(), a.clone());
         assert_eq!(deq.len(), 0);
         deq.push_back(c.clone());
         assert_eq!(deq.len(), 1);
index 8c298a7373d96a71eb919a6eed3b5f33ab96fd01..b0f89e219d8d8aa81d06240a04aaa853dae5e0b0 100644 (file)
@@ -386,8 +386,8 @@ fn test_spec_order() {
               "1.0.0"];
     let mut i = 1;
     while i < vs.len() {
-        let a = parse(vs[i-1]).get();
-        let b = parse(vs[i]).get();
+        let a = parse(vs[i-1]).unwrap();
+        let b = parse(vs[i]).unwrap();
         assert!(a < b);
         i += 1;
     }
index 52e6c1fcc1c90400d6e4aea17ea3056bcd3ac05f..3f62317eb8908ca7b083f91b7edfee1e0b08af3c 100644 (file)
@@ -366,9 +366,9 @@ fn addMoreToCount_simple(v0: uint, v1: uint) -> uint {
         map.update_with_key(3, 2, addMoreToCount);
 
         // check the total counts
-        assert_eq!(map.find(&3).get(), &10);
-        assert_eq!(map.find(&5).get(), &3);
-        assert_eq!(map.find(&9).get(), &1);
+        assert_eq!(map.find(&3).unwrap(), &10);
+        assert_eq!(map.find(&5).unwrap(), &3);
+        assert_eq!(map.find(&9).unwrap(), &1);
 
         // sadly, no sevens were counted
         assert!(map.find(&7).is_none());
index 02481693eb9713e0c34de059e9490e30838332c5..e87be1462267468dc8cc3b6772c41b191da6895e 100644 (file)
@@ -247,9 +247,8 @@ pub fn parse_opts(args: &[~str]) -> OptRes {
     let ratchet_metrics = getopts::opt_maybe_str(&matches, "ratchet-metrics");
     let ratchet_metrics = ratchet_metrics.map(|s| Path(*s));
 
-    let ratchet_noise_percent =
-        getopts::opt_maybe_str(&matches, "ratchet-noise-percent");
-    let ratchet_noise_percent = ratchet_noise_percent.map(|s| f64::from_str(*s).get());
+    let ratchet_noise_percent = getopts::opt_maybe_str(&matches, "ratchet-noise-percent");
+    let ratchet_noise_percent = ratchet_noise_percent.map(|s| f64::from_str(*s).unwrap());
 
     let save_metrics = getopts::opt_maybe_str(&matches, "save-metrics");
     let save_metrics = save_metrics.map(|s| Path(*s));
@@ -631,8 +630,8 @@ fn dummy() {}
         st.write_failures();
     };
 
-    let apos = s.find_str("a").get();
-    let bpos = s.find_str("b").get();
+    let apos = s.find_str("a").unwrap();
+    let bpos = s.find_str("b").unwrap();
     assert!(apos < bpos);
 }
 
@@ -868,7 +867,7 @@ pub fn new() -> MetricMap {
     pub fn load(p: &Path) -> MetricMap {
         assert!(os::path_exists(p));
         let f = io::file_reader(p).unwrap();
-        let mut decoder = json::Decoder(json::from_reader(f).get());
+        let mut decoder = json::Decoder(json::from_reader(f).unwrap());
         MetricMap(Decodable::decode(&mut decoder))
     }
 
@@ -1207,7 +1206,7 @@ fn first_free_arg_should_be_a_filter() {
           either::Left(o) => o,
           _ => fail!("Malformed arg in first_free_arg_should_be_a_filter")
         };
-        assert!("filter" == opts.filter.clone().get());
+        assert!("filter" == opts.filter.clone().unwrap());
     }
 
     #[test]
@@ -1346,28 +1345,28 @@ pub fn test_metricmap_compare() {
 
         let diff1 = m2.compare_to_old(&m1, None);
 
-        assert_eq!(*(diff1.find(&~"in-both-noise").get()), LikelyNoise);
-        assert_eq!(*(diff1.find(&~"in-first-noise").get()), MetricRemoved);
-        assert_eq!(*(diff1.find(&~"in-second-noise").get()), MetricAdded);
-        assert_eq!(*(diff1.find(&~"in-both-want-downwards-but-regressed").get()),
+        assert_eq!(*(diff1.find(&~"in-both-noise").unwrap()), LikelyNoise);
+        assert_eq!(*(diff1.find(&~"in-first-noise").unwrap()), MetricRemoved);
+        assert_eq!(*(diff1.find(&~"in-second-noise").unwrap()), MetricAdded);
+        assert_eq!(*(diff1.find(&~"in-both-want-downwards-but-regressed").unwrap()),
                    Regression(100.0));
-        assert_eq!(*(diff1.find(&~"in-both-want-downwards-and-improved").get()),
+        assert_eq!(*(diff1.find(&~"in-both-want-downwards-and-improved").unwrap()),
                    Improvement(50.0));
-        assert_eq!(*(diff1.find(&~"in-both-want-upwards-but-regressed").get()),
+        assert_eq!(*(diff1.find(&~"in-both-want-upwards-but-regressed").unwrap()),
                    Regression(50.0));
-        assert_eq!(*(diff1.find(&~"in-both-want-upwards-and-improved").get()),
+        assert_eq!(*(diff1.find(&~"in-both-want-upwards-and-improved").unwrap()),
                    Improvement(100.0));
         assert_eq!(diff1.len(), 7);
 
         let diff2 = m2.compare_to_old(&m1, Some(200.0));
 
-        assert_eq!(*(diff2.find(&~"in-both-noise").get()), LikelyNoise);
-        assert_eq!(*(diff2.find(&~"in-first-noise").get()), MetricRemoved);
-        assert_eq!(*(diff2.find(&~"in-second-noise").get()), MetricAdded);
-        assert_eq!(*(diff2.find(&~"in-both-want-downwards-but-regressed").get()), LikelyNoise);
-        assert_eq!(*(diff2.find(&~"in-both-want-downwards-and-improved").get()), LikelyNoise);
-        assert_eq!(*(diff2.find(&~"in-both-want-upwards-but-regressed").get()), LikelyNoise);
-        assert_eq!(*(diff2.find(&~"in-both-want-upwards-and-improved").get()), LikelyNoise);
+        assert_eq!(*(diff2.find(&~"in-both-noise").unwrap()), LikelyNoise);
+        assert_eq!(*(diff2.find(&~"in-first-noise").unwrap()), MetricRemoved);
+        assert_eq!(*(diff2.find(&~"in-second-noise").unwrap()), MetricAdded);
+        assert_eq!(*(diff2.find(&~"in-both-want-downwards-but-regressed").unwrap()), LikelyNoise);
+        assert_eq!(*(diff2.find(&~"in-both-want-downwards-and-improved").unwrap()), LikelyNoise);
+        assert_eq!(*(diff2.find(&~"in-both-want-upwards-but-regressed").unwrap()), LikelyNoise);
+        assert_eq!(*(diff2.find(&~"in-both-want-upwards-and-improved").unwrap()), LikelyNoise);
         assert_eq!(diff2.len(), 7);
     }
 
@@ -1391,28 +1390,28 @@ pub fn ratchet_test() {
         let (diff1, ok1) = m2.ratchet(&pth, None);
         assert_eq!(ok1, false);
         assert_eq!(diff1.len(), 2);
-        assert_eq!(*(diff1.find(&~"runtime").get()), Regression(10.0));
-        assert_eq!(*(diff1.find(&~"throughput").get()), LikelyNoise);
+        assert_eq!(*(diff1.find(&~"runtime").unwrap()), Regression(10.0));
+        assert_eq!(*(diff1.find(&~"throughput").unwrap()), LikelyNoise);
 
         // Check that it was not rewritten.
         let m3 = MetricMap::load(&pth);
         assert_eq!(m3.len(), 2);
-        assert_eq!(*(m3.find(&~"runtime").get()), Metric { value: 1000.0, noise: 2.0 });
-        assert_eq!(*(m3.find(&~"throughput").get()), Metric { value: 50.0, noise: 2.0 });
+        assert_eq!(*(m3.find(&~"runtime").unwrap()), Metric { value: 1000.0, noise: 2.0 });
+        assert_eq!(*(m3.find(&~"throughput").unwrap()), Metric { value: 50.0, noise: 2.0 });
 
         // Ask for a ratchet with an explicit noise-percentage override,
         // that should advance.
         let (diff2, ok2) = m2.ratchet(&pth, Some(10.0));
         assert_eq!(ok2, true);
         assert_eq!(diff2.len(), 2);
-        assert_eq!(*(diff2.find(&~"runtime").get()), LikelyNoise);
-        assert_eq!(*(diff2.find(&~"throughput").get()), LikelyNoise);
+        assert_eq!(*(diff2.find(&~"runtime").unwrap()), LikelyNoise);
+        assert_eq!(*(diff2.find(&~"throughput").unwrap()), LikelyNoise);
 
         // Check that it was rewritten.
         let m4 = MetricMap::load(&pth);
         assert_eq!(m4.len(), 2);
-        assert_eq!(*(m4.find(&~"runtime").get()), Metric { value: 1100.0, noise: 2.0 });
-        assert_eq!(*(m4.find(&~"throughput").get()), Metric { value: 50.0, noise: 2.0 });
+        assert_eq!(*(m4.find(&~"runtime").unwrap()), Metric { value: 1100.0, noise: 2.0 });
+        assert_eq!(*(m4.find(&~"throughput").unwrap()), Metric { value: 50.0, noise: 2.0 });
 
         os::remove_dir_recursive(&dpth);
     }
index 523c3521f866519fa2c8e188fe5752f9b2bbebb1..581bdf2a294dbd6e1f1562b7492a5ba362e60f06 100644 (file)
@@ -134,7 +134,7 @@ fn decode_inner(s: &str, full_url: bool) -> ~str {
             match rdr.read_char() {
               '%' => {
                 let bytes = rdr.read_bytes(2u);
-                let ch = uint::parse_bytes(bytes, 16u).get() as char;
+                let ch = uint::parse_bytes(bytes, 16u).unwrap() as char;
 
                 if full_url {
                     // Only decode some characters:
@@ -257,7 +257,7 @@ pub fn decode_form_urlencoded(s: &[u8]) -> HashMap<~str, ~[~str]> {
                     let ch = match ch {
                         '%' => {
                             let bytes = rdr.read_bytes(2u);
-                            uint::parse_bytes(bytes, 16u).get() as char
+                            uint::parse_bytes(bytes, 16u).unwrap() as char
                         }
                         '+' => ' ',
                         ch => ch
index f066ede65f976c8af7de89fa5f2122230b9561c6..637ea159d79d012880d7ffe1e527a2616810cd19 100644 (file)
@@ -912,7 +912,7 @@ fn unlib(config: @session::config, stem: ~str) -> ~str {
         }
         let dir = cratepath.dirname();
         if dir != ~"" { args.push(~"-L" + dir); }
-        let libarg = unlib(sess.targ_cfg, cratepath.filestem().get());
+        let libarg = unlib(sess.targ_cfg, cratepath.filestem().unwrap());
         args.push(~"-l" + libarg);
     }
 
@@ -950,7 +950,7 @@ fn unlib(config: @session::config, stem: ~str) -> ~str {
         // be rpathed
         if sess.targ_cfg.os == session::os_macos {
             args.push(~"-Wl,-install_name,@rpath/"
-                      + output.filename().get());
+                      + output.filename().unwrap());
         }
     }
 
index b77ed10c21ba4e3b5abe4cefea307125ac0bc81c..35d070baa9bace971854c8a4c18faf73b79f0b86 100644 (file)
@@ -319,7 +319,7 @@ fn passes_exist() {
         if !pass.is_some() {
             failed.push(name);
         } else {
-            unsafe { llvm::LLVMDestroyPass(pass.get()) }
+            unsafe { llvm::LLVMDestroyPass(pass.unwrap()) }
         }
     }
     for &(name,_) in transform_passes.iter() {
@@ -327,7 +327,7 @@ fn passes_exist() {
         if !pass.is_some() {
             failed.push(name);
         } else {
-            unsafe { llvm::LLVMDestroyPass(pass.get()) }
+            unsafe { llvm::LLVMDestroyPass(pass.unwrap()) }
         }
     }
     for &(name,_) in utility_passes.iter() {
@@ -335,7 +335,7 @@ fn passes_exist() {
         if !pass.is_some() {
             failed.push(name);
         } else {
-            unsafe { llvm::LLVMDestroyPass(pass.get()) }
+            unsafe { llvm::LLVMDestroyPass(pass.unwrap()) }
         }
     }
 
index ea679d19f73b84edea738fed068e6748b38abd6d..356820f8267fe990eb76bbaec7781ea56fc422bd 100644 (file)
@@ -922,7 +922,7 @@ pub fn build_output_filenames(input: &input,
           };
 
           let mut stem = match *input {
-              file_input(ref ifile) => (*ifile).filestem().get().to_managed(),
+              file_input(ref ifile) => (*ifile).filestem().unwrap().to_managed(),
               str_input(_) => @"rust_out"
           };
 
index 8ca68251cb8910265e3b0fa7f22e271908188cc7..d2d2a8b4be99d984f4c06c04f6b80ef3598a0418 100644 (file)
@@ -308,7 +308,7 @@ pub fn main() {
             #[main];
             extra::test::test_main_static(::std::os::args(), TESTS);
         }
-    )).get();
+    )).unwrap();
 
     let testmod = ast::_mod {
         view_items: view_items,
@@ -366,7 +366,7 @@ fn mk_tests(cx: &TestCtxt) -> @ast::item {
         pub static TESTS : &'static [self::extra::test::TestDescAndFn] =
             $test_descs
         ;
-    )).get()
+    )).unwrap()
 }
 
 fn is_extra(cx: &TestCtxt) -> bool {
index ec50f564385c3a9d3f777d0f9073f2f785deef79..ffd79433b76930fe7186c138a71fdaaed995436a 100644 (file)
@@ -413,15 +413,14 @@ fn enc_fn_sig(w: @io::Writer, cx: @ctxt, fsig: &ty::FnSig) {
 }
 
 fn enc_bounds(w: @io::Writer, cx: @ctxt, bs: &ty::ParamBounds) {
-    do bs.builtin_bounds.each |bound| {
+    for bound in bs.builtin_bounds.iter() {
         match bound {
             ty::BoundSend => w.write_char('S'),
             ty::BoundFreeze => w.write_char('K'),
             ty::BoundStatic => w.write_char('O'),
             ty::BoundSized => w.write_char('Z'),
         }
-        true
-    };
+    }
 
     for &tp in bs.trait_bounds.iter() {
         w.write_char('I');
index 34f4425a871ddbe7ed2503b9d2f896c617928b9a..b909f70440a8258031011ac11d0bf8024a2d4eda 100644 (file)
@@ -328,7 +328,7 @@ fn drop_nested_items(blk: &ast::Block, fld: @fold::ast_fold) -> ast::Block {
 
     match *ii {
         //hack: we're not dropping items
-        ast::ii_item(i) => ast::ii_item(fld.fold_item(i).get()),
+        ast::ii_item(i) => ast::ii_item(fld.fold_item(i).unwrap()),
         ast::ii_method(d, is_provided, m) =>
           ast::ii_method(d, is_provided, fld.fold_method(m)),
         ast::ii_foreign(i) => ast::ii_foreign(fld.fold_foreign_item(i))
@@ -350,7 +350,7 @@ fn renumber_ast(xcx: @ExtendedDecodeContext, ii: ast::inlined_item)
     });
 
     match ii {
-        ast::ii_item(i) => ast::ii_item(fld.fold_item(i).get()),
+        ast::ii_item(i) => ast::ii_item(fld.fold_item(i).unwrap()),
         ast::ii_method(d, is_provided, m) =>
           ast::ii_method(xcx.tr_def_id(d), is_provided, fld.fold_method(m)),
         ast::ii_foreign(i) => ast::ii_foreign(fld.fold_foreign_item(i)),
@@ -1275,7 +1275,7 @@ fn mk_ctxt() -> @fake_ext_ctxt {
 fn roundtrip(in_item: Option<@ast::item>) {
     use std::io;
 
-    let in_item = in_item.get();
+    let in_item = in_item.unwrap();
     let bytes = do io::with_bytes_writer |wr| {
         let mut ebml_w = writer::Encoder(wr);
         encode_item_ast(&mut ebml_w, in_item);
@@ -1321,13 +1321,13 @@ fn new_int_alist<B>() -> alist<int, B> {
             fn eq_int(a: int, b: int) -> bool { a == b }
             return alist {eq_fn: eq_int, data: ~[]};
         }
-    ).get());
+    ).unwrap());
     let item_out = simplify_ast(&item_in);
     let item_exp = ast::ii_item(quote_item!(
         fn new_int_alist<B>() -> alist<int, B> {
             return alist {eq_fn: eq_int, data: ~[]};
         }
-    ).get());
+    ).unwrap());
     match (item_out, item_exp) {
       (ast::ii_item(item_out), ast::ii_item(item_exp)) => {
         assert!(pprust::item_to_str(item_out,
index 646840f1e306361c535ac52145440b06b0d691fb..c3bb2000447f7fe6ae8f17694282738d72753b04 100644 (file)
@@ -307,7 +307,7 @@ pub fn check_assignment(&self, expr: @ast::expr) {
         // if they cannot already have been assigned
         if self.is_local_variable(cmt) {
             assert!(cmt.mutbl.is_immutable()); // no "const" locals
-            let lp = opt_loan_path(cmt).get();
+            let lp = opt_loan_path(cmt).unwrap();
             do self.move_data.each_assignment_of(expr.id, lp) |assign| {
                 self.bccx.report_reassigned_immutable_variable(
                     expr.span,
index fb12f97c50cb0156e25425ee174e8565d5470f98..cbd1d3cd9ad81ee4cdf05c982ebb1d2827f06ea4 100644 (file)
@@ -52,7 +52,7 @@ pub fn check_crate(tcx: ty::ctxt, crate: &Crate) {
               }
               expr_again(_) => {
                 if !cx.in_loop {
-                    tcx.sess.span_err(e.span, "`again` outside of loop");
+                    tcx.sess.span_err(e.span, "`loop` outside of loop");
                 }
               }
               expr_ret(oe) => {
index 4de096428f26ff4f806047bafaa379fe2697ab4b..1b420b9c06a55b60a758d3dfb6f76b311573ef6f 100644 (file)
@@ -109,7 +109,7 @@ pub fn check_arms(cx: &MatchCheckCtxt, arms: &[arm]) {
             let pat_matches_nan: &fn(@pat) -> bool = |p| {
                 match cx.tcx.def_map.find(&p.id) {
                     Some(&def_static(did, false)) => {
-                        let const_expr = lookup_const_by_id(cx.tcx, did).get();
+                        let const_expr = lookup_const_by_id(cx.tcx, did).unwrap();
                         match eval_const_expr(cx.tcx, const_expr) {
                             const_float(f) if f.is_NaN() => true,
                             _ => false
@@ -304,7 +304,7 @@ pub fn is_useful_specialized(cx: &MatchCheckCtxt,
                           -> useful {
     let ms = m.iter().filter_map(|r| specialize(cx, *r, &ctor, arity, lty)).collect::<matrix>();
     let could_be_useful = is_useful(
-        cx, &ms, specialize(cx, v, &ctor, arity, lty).get());
+        cx, &ms, specialize(cx, v, &ctor, arity, lty).unwrap());
     match could_be_useful {
       useful_ => useful(lty, ctor),
       ref u => *u,
@@ -319,7 +319,7 @@ pub fn pat_ctor_id(cx: &MatchCheckCtxt, p: @pat) -> Option<ctor> {
         match cx.tcx.def_map.find(&pat.id) {
           Some(&def_variant(_, id)) => Some(variant(id)),
           Some(&def_static(did, false)) => {
-            let const_expr = lookup_const_by_id(cx.tcx, did).get();
+            let const_expr = lookup_const_by_id(cx.tcx, did).unwrap();
             Some(val(eval_const_expr(cx.tcx, const_expr)))
           }
           _ => None
@@ -515,7 +515,7 @@ pub fn specialize(cx: &MatchCheckCtxt,
                     }
                     Some(&def_static(did, _)) => {
                         let const_expr =
-                            lookup_const_by_id(cx.tcx, did).get();
+                            lookup_const_by_id(cx.tcx, did).unwrap();
                         let e_v = eval_const_expr(cx.tcx, const_expr);
                         let match_ = match *ctor_id {
                             val(ref v) => {
@@ -565,7 +565,7 @@ pub fn specialize(cx: &MatchCheckCtxt,
                 match cx.tcx.def_map.get_copy(&pat_id) {
                     def_static(did, _) => {
                         let const_expr =
-                            lookup_const_by_id(cx.tcx, did).get();
+                            lookup_const_by_id(cx.tcx, did).unwrap();
                         let e_v = eval_const_expr(cx.tcx, const_expr);
                         let match_ = match *ctor_id {
                             val(ref v) =>
@@ -867,7 +867,7 @@ pub fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
                 "cannot bind by-move and by-ref \
                  in the same pattern");
             tcx.sess.span_note(
-                by_ref_span.get(),
+                by_ref_span.unwrap(),
                 "by-ref binding occurs here");
         }
     };
index 330e44893f04a733d137714bc0819cef65396943..77e81709a03d73370f51043a5a45ba9bc08840c4 100644 (file)
@@ -466,9 +466,9 @@ pub fn lit_to_const(lit: &lit) -> const_val {
       lit_int(n, _) => const_int(n),
       lit_uint(n, _) => const_uint(n),
       lit_int_unsuffixed(n) => const_int(n),
-      lit_float(n, _) => const_float(float::from_str(n).get() as f64),
+      lit_float(n, _) => const_float(float::from_str(n).unwrap() as f64),
       lit_float_unsuffixed(n) =>
-        const_float(float::from_str(n).get() as f64),
+        const_float(float::from_str(n).unwrap() as f64),
       lit_nil => const_int(0i64),
       lit_bool(b) => const_bool(b)
     }
index 3bdf0c0f6dcb84c32db21792a769cb9c923b17a4..84eb371d7b34ac49a51b99bbde139804bd918fbc 100644 (file)
@@ -338,12 +338,11 @@ pub fn check_builtin_bounds(cx: Context, ty: ty::t, bounds: ty::BuiltinBounds,
 {
     let kind = ty::type_contents(cx.tcx, ty);
     let mut missing = ty::EmptyBuiltinBounds();
-    do bounds.each |bound| {
+    for bound in bounds.iter() {
         if !kind.meets_bound(cx.tcx, bound) {
             missing.add(bound);
         }
-        true
-    };
+    }
     if !missing.is_empty() {
         any_missing(missing);
     }
index 76d1d0b05ffbc62364479d2433f295f6f2710828..9ffeb99ac3559bf7bf82810e3b7abba8579173c4 100644 (file)
@@ -225,7 +225,7 @@ pub fn check_crate<'mm>(tcx: ty::ctxt,
         // the default implementation.
         // Having to do this this is really unfortunate.
         let method_id = ty::method(tcx, method_id).provided_source
-            .get_or_default(method_id);
+            .unwrap_or_default(method_id);
 
         if method_id.crate == LOCAL_CRATE {
             let is_private = method_is_private(span, method_id.node);
index 60ecff39d8554baa1597e657794e9196272e248b..625dcd5d9cc49d1a5adb75fea9bd225e150c1cff 100644 (file)
@@ -1726,7 +1726,7 @@ pub fn build_reduced_graph_for_external_crate(@mut self,
         let mut modules = HashMap::new();
 
         // Create all the items reachable by paths.
-        do each_path(self.session.cstore, root.def_id.get().crate)
+        do each_path(self.session.cstore, root.def_id.unwrap().crate)
                 |path_string, def_like, visibility| {
 
             debug!("(building reduced graph for external crate) found path \
@@ -2350,7 +2350,7 @@ fn get_binding(this: @mut Resolver,
         match type_result {
             BoundResult(target_module, name_bindings) => {
                 debug!("(resolving single import) found type target: %?",
-                        name_bindings.type_def.get().type_def);
+                        name_bindings.type_def.unwrap().type_def);
                 import_resolution.type_target =
                     Some(Target(target_module, name_bindings));
                 import_resolution.type_id = directive.id;
@@ -3097,7 +3097,7 @@ pub fn report_unresolved_imports(@mut self, module_: @mut Module) {
         let imports: &mut ~[@ImportDirective] = &mut *module_.imports;
         let import_count = imports.len();
         if index != import_count {
-            let sn = self.session.codemap.span_to_snippet(imports[index].span);
+            let sn = self.session.codemap.span_to_snippet(imports[index].span).unwrap();
             if sn.contains("::") {
                 self.session.span_err(imports[index].span, "unresolved import");
             } else {
index 725beee6604e7d8e92a813fa18f7556e5f264e4c..d77cebbf23e0be8b1c05eed1ed0bfb0b85d68836 100644 (file)
@@ -210,7 +210,7 @@ pub fn opt_eq(tcx: ty::ctxt, a: &Opt, b: &Opt) -> bool {
                         ExprLit(existing_a_expr) => a_expr = existing_a_expr,
                             ConstLit(a_const) => {
                                 let e = const_eval::lookup_const_by_id(tcx, a_const);
-                                a_expr = e.get();
+                                a_expr = e.unwrap();
                             }
                         UnitLikeStructLit(_) => {
                             fail!("UnitLikeStructLit should have been handled \
@@ -223,7 +223,7 @@ pub fn opt_eq(tcx: ty::ctxt, a: &Opt, b: &Opt) -> bool {
                         ExprLit(existing_b_expr) => b_expr = existing_b_expr,
                             ConstLit(b_const) => {
                                 let e = const_eval::lookup_const_by_id(tcx, b_const);
-                                b_expr = e.get();
+                                b_expr = e.unwrap();
                             }
                         UnitLikeStructLit(_) => {
                             fail!("UnitLikeStructLit should have been handled \
@@ -922,7 +922,7 @@ pub fn extract_vec_elems(bcx: @mut Block,
         }
     };
     if slice.is_some() {
-        let n = slice.get();
+        let n = slice.unwrap();
         let slice_offset = Mul(bcx, vt.llunit_size,
             C_int(bcx.ccx(), n as int)
         );
@@ -1280,7 +1280,7 @@ pub fn compile_submatch(bcx: @mut Block,
     let _icx = push_ctxt("match::compile_submatch");
     let mut bcx = bcx;
     if m.len() == 0u {
-        Br(bcx, chk.get()());
+        Br(bcx, chk.unwrap()());
         return;
     }
     if m[0].pats.len() == 0u {
index fad5b9ec73b0f40525ff083b519e457756f463d1..2eb9841c6c7577411454205a0a9f8c0e8bcec754 100644 (file)
@@ -260,7 +260,7 @@ fn generic_fields_of(cx: &mut CrateContext, r: &Repr, sizing: bool) -> ~[Type] {
                     most_aligned = Some(st);
                 }
             }
-            let most_aligned = most_aligned.get();
+            let most_aligned = most_aligned.unwrap();
             let padding = largest_size - most_aligned.size;
 
             struct_llfields(cx, most_aligned, sizing)
index 0a28da5f88a7ce0fa575e7927cc18ab9c71b336c..3fc6dbca9647533ec6a1f3f5ea6b604198381d41 100644 (file)
@@ -1321,7 +1321,7 @@ pub fn cleanup_and_leave(bcx: @mut Block,
     }
     match leave {
       Some(target) => Br(bcx, target),
-      None => { Resume(bcx, Load(bcx, bcx.fcx.personality.get())); }
+      None => { Resume(bcx, Load(bcx, bcx.fcx.personality.unwrap())); }
     }
 }
 
@@ -1529,7 +1529,7 @@ pub fn alloca_maybe_zeroed(cx: @mut Block, ty: Type, name: &str, zero: bool) ->
     let p = Alloca(cx, ty, name);
     if zero {
         let b = cx.fcx.ccx.builder();
-        b.position_before(cx.fcx.alloca_insert_pt.get());
+        b.position_before(cx.fcx.alloca_insert_pt.unwrap());
         memzero(&b, p, ty);
     }
     p
@@ -1575,7 +1575,7 @@ pub fn make_return_pointer(fcx: @mut FunctionContext, output_type: ty::t) -> Val
             llvm::LLVMGetParam(fcx.llfn, 0)
         } else {
             let lloutputtype = type_of::type_of(fcx.ccx, output_type);
-            let bcx = fcx.entry_bcx.get();
+            let bcx = fcx.entry_bcx.unwrap();
             Alloca(bcx, lloutputtype, "__make_return_pointer")
         }
     }
@@ -1793,7 +1793,7 @@ pub fn finish_fn(fcx: @mut FunctionContext, last_bcx: @mut Block) {
 pub fn build_return_block(fcx: &FunctionContext, ret_cx: @mut Block) {
     // Return the value if this function immediate; otherwise, return void.
     if fcx.llretptr.is_some() && fcx.has_immediate_return_value {
-        Ret(ret_cx, Load(ret_cx, fcx.llretptr.get()))
+        Ret(ret_cx, Load(ret_cx, fcx.llretptr.unwrap()))
     } else {
         RetVoid(ret_cx)
     }
@@ -1843,7 +1843,7 @@ pub fn trans_closure(ccx: @mut CrateContext,
 
     // Create the first basic block in the function and keep a handle on it to
     //  pass to finish_fn later.
-    let bcx_top = fcx.entry_bcx.get();
+    let bcx_top = fcx.entry_bcx.unwrap();
     let mut bcx = bcx_top;
     let block_ty = node_id_type(bcx, body.id);
 
@@ -1861,7 +1861,7 @@ pub fn trans_closure(ccx: @mut CrateContext,
     {
         bcx = controlflow::trans_block(bcx, body, expr::Ignore);
     } else {
-        let dest = expr::SaveIn(fcx.llretptr.get());
+        let dest = expr::SaveIn(fcx.llretptr.unwrap());
         bcx = controlflow::trans_block(bcx, body, dest);
     }
 
@@ -2055,18 +2055,18 @@ pub fn trans_enum_variant_or_tuple_like_struct<A:IdAndTy>(
 
     let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
 
-    let bcx = fcx.entry_bcx.get();
+    let bcx = fcx.entry_bcx.unwrap();
     let arg_tys = ty::ty_fn_args(ctor_ty);
 
     insert_synthetic_type_entries(bcx, fn_args, arg_tys);
     let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
 
     let repr = adt::represent_type(ccx, result_ty);
-    adt::trans_start_init(bcx, repr, fcx.llretptr.get(), disr);
+    adt::trans_start_init(bcx, repr, fcx.llretptr.unwrap(), disr);
     for (i, fn_arg) in fn_args.iter().enumerate() {
         let lldestptr = adt::trans_field_ptr(bcx,
                                              repr,
-                                             fcx.llretptr.get(),
+                                             fcx.llretptr.unwrap(),
                                              disr,
                                              i);
         let llarg = fcx.llargs.get_copy(&fn_arg.pat.id);
@@ -2293,7 +2293,7 @@ fn create_main(ccx: @mut CrateContext, main_llfn: ValueRef) -> ValueRef {
         // be updated if this assertion starts to fail.
         assert!(fcx.has_immediate_return_value);
 
-        let bcx = fcx.entry_bcx.get();
+        let bcx = fcx.entry_bcx.unwrap();
         // Call main.
         let llenvarg = unsafe {
             let env_arg = fcx.env_arg_pos();
@@ -2782,7 +2782,7 @@ pub fn create_module_map(ccx: &mut CrateContext) -> ValueRef {
     }
 
     for key in keys.iter() {
-        let val = *ccx.module_data.find_equiv(key).get();
+        let val = *ccx.module_data.find_equiv(key).unwrap();
         let s_const = C_cstr(ccx, *key);
         let s_ptr = p2i(ccx, s_const);
         let v_ptr = p2i(ccx, val);
index 07b774105bbde7b8cbf021b65dd9afc37d4e2d16..c8e2a17c3b5f1bd93bc81448101c31e08a0404fb 100644 (file)
@@ -319,7 +319,7 @@ pub fn Alloca(cx: @mut Block, Ty: Type, name: &str) -> ValueRef {
     unsafe {
         if cx.unreachable { return llvm::LLVMGetUndef(Ty.ptr_to().to_ref()); }
         let b = cx.fcx.ccx.builder();
-        b.position_before(cx.fcx.alloca_insert_pt.get());
+        b.position_before(cx.fcx.alloca_insert_pt.unwrap());
         b.alloca(Ty, name)
     }
 }
@@ -328,7 +328,7 @@ pub fn ArrayAlloca(cx: @mut Block, Ty: Type, Val: ValueRef) -> ValueRef {
     unsafe {
         if cx.unreachable { return llvm::LLVMGetUndef(Ty.ptr_to().to_ref()); }
         let b = cx.fcx.ccx.builder();
-        b.position_before(cx.fcx.alloca_insert_pt.get());
+        b.position_before(cx.fcx.alloca_insert_pt.unwrap());
         b.array_alloca(Ty, Val)
     }
 }
index 3a6577e28b7cceb37c392667de0c107902b335d3..895bea715c964e73713dcc086f491d9516cabdc6 100644 (file)
@@ -169,7 +169,7 @@ pub fn build_wrap_ret(&self, bcx: @mut Block, arg_tys: &[Type], llargbundle: Val
             } else {
                 Load(bcx, llretval)
             };
-            let llretptr = BitCast(bcx, bcx.fcx.llretptr.get(), self.ret_ty.ty.ptr_to());
+            let llretptr = BitCast(bcx, bcx.fcx.llretptr.unwrap(), self.ret_ty.ty.ptr_to());
             Store(bcx, llretval, llretptr);
         }
     }
index ae3b773af0b63f8488669c1029346087d35f3c1f..602d33a197e29bfc536639d370372d07185a52a1 100644 (file)
@@ -330,7 +330,7 @@ pub fn load_environment(fcx: @mut FunctionContext,
         return;
     }
 
-    let bcx = fcx.entry_bcx.get();
+    let bcx = fcx.entry_bcx.unwrap();
 
     // Load a pointer to the closure data, skipping over the box header:
     let llcdata = opaque_box_body(bcx, cdata_ty, fcx.llenv);
@@ -443,7 +443,7 @@ pub fn trans_expr_fn(bcx: @mut Block,
                               if is_loop_body.is_some() {
                                   Store(bcx,
                                         C_bool(true),
-                                        bcx.fcx.llretptr.get());
+                                        bcx.fcx.llretptr.unwrap());
                               }
                           });
             rslt(bcx, llbox)
index 527706be6c1f75a3e3a4960e72543f26437f3c19..f303e7b82759769696c95b0c9856d28c89cf0341 100644 (file)
@@ -251,7 +251,7 @@ pub fn env_arg_pos(&self) -> uint {
 
     pub fn cleanup(&mut self) {
         unsafe {
-            llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt.get());
+            llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt.unwrap());
         }
         // Remove the cycle between fcx and bcx, so memory can be freed
         self.entry_bcx = None;
@@ -262,7 +262,7 @@ pub fn get_llreturn(&mut self) -> BasicBlockRef {
             self.llreturn = Some(base::mk_return_basic_block(self.llfn));
         }
 
-        self.llreturn.get()
+        self.llreturn.unwrap()
     }
 }
 
index 4fa64b4130aa9901fc39ece115e5443667814dd7..823b1e0645cbcccc3a52dd5b3d52ef01f57705de 100644 (file)
@@ -314,7 +314,7 @@ pub fn trans_break_cont(bcx: @mut Block,
                     Some(bcx) => bcx,
                         // This is a return from a loop body block
                         None => {
-                            Store(bcx, C_bool(!to_end), bcx.fcx.llretptr.get());
+                            Store(bcx, C_bool(!to_end), bcx.fcx.llretptr.unwrap());
                             cleanup_and_leave(bcx, None, Some(bcx.fcx.get_llreturn()));
                             Unreachable(bcx);
                             return bcx;
@@ -346,7 +346,7 @@ pub fn trans_ret(bcx: @mut Block, e: Option<@ast::expr>) -> @mut Block {
         // to false, return flag to true, and then store the value in the
         // parent's retptr.
         Store(bcx, C_bool(true), flagptr);
-        Store(bcx, C_bool(false), bcx.fcx.llretptr.get());
+        Store(bcx, C_bool(false), bcx.fcx.llretptr.unwrap());
         expr::SaveIn(match e {
           Some(x) => PointerCast(bcx, retptr,
                                  type_of(bcx.ccx(), expr_ty(bcx, x)).ptr_to()),
index e31a27a4c6ca0a035e2dcf9e2e158833e6bf13f8..624704c2c686c540c4457df43a9a9ab57be13154 100644 (file)
@@ -485,8 +485,8 @@ fn lexical_block_metadata(bcx: @mut Block) -> DILexicalBlock {
         }
     }
 
-    let span = bcx.node_info.get().span;
-    let id = bcx.node_info.get().id;
+    let span = bcx.node_info.unwrap().span;
+    let id = bcx.node_info.unwrap().id;
 
     // Check whether we already have a cache entry for this node id
     match dbg_cx(cx).created_blocks.find(&id) {
index 20c8e69129d74d1fce99d300e55c3a706062bbe1..6d5934592ebcb71f28f7271549533d134c27e959 100644 (file)
@@ -149,7 +149,7 @@ fn build_shim_fn_(ccx: @mut CrateContext,
 
     // Declare the body of the shim function:
     let fcx = new_fn_ctxt(ccx, ~[], llshimfn, tys.fn_sig.output, None);
-    let bcx = fcx.entry_bcx.get();
+    let bcx = fcx.entry_bcx.unwrap();
 
     let llargbundle = get_param(llshimfn, 0u);
     let llargvals = arg_builder(bcx, tys, llargbundle);
@@ -190,7 +190,7 @@ fn build_wrap_fn_(ccx: @mut CrateContext,
                   ret_builder: wrap_ret_builder) {
     let _icx = push_ctxt("foreign::build_wrap_fn_");
     let fcx = new_fn_ctxt(ccx, ~[], llwrapfn, tys.fn_sig.output, None);
-    let bcx = fcx.entry_bcx.get();
+    let bcx = fcx.entry_bcx.unwrap();
 
     // Patch up the return type if it's not immediate and we're returning via
     // the C ABI.
@@ -226,7 +226,7 @@ fn build_wrap_fn_(ccx: @mut CrateContext,
     } else {
         // Cast if we have to...
         // XXX: This is ugly.
-        let llretptr = BitCast(return_context, fcx.llretptr.get(), return_type.ptr_to());
+        let llretptr = BitCast(return_context, fcx.llretptr.unwrap(), return_type.ptr_to());
         Ret(return_context, Load(return_context, llretptr));
     }
     fcx.cleanup();
@@ -421,7 +421,7 @@ fn build_direct_fn(ccx: @mut CrateContext,
         debug!("build_direct_fn(%s)", link_name(ccx, item));
 
         let fcx = new_fn_ctxt(ccx, ~[], decl, tys.fn_sig.output, None);
-        let bcx = fcx.entry_bcx.get();
+        let bcx = fcx.entry_bcx.unwrap();
         let llbasefn = base_fn(ccx, link_name(ccx, item), tys, cc);
         let ty = ty::lookup_item_type(ccx.tcx,
                                       ast_util::local_def(item.id)).ty;
@@ -431,7 +431,7 @@ fn build_direct_fn(ccx: @mut CrateContext,
         });
         let retval = Call(bcx, llbasefn, args);
         if !ty::type_is_nil(ret_ty) && !ty::type_is_bot(ret_ty) {
-            Store(bcx, retval, fcx.llretptr.get());
+            Store(bcx, retval, fcx.llretptr.unwrap());
         }
         finish_fn(fcx, bcx);
     }
@@ -446,7 +446,7 @@ fn build_fast_ffi_fn(ccx: @mut CrateContext,
         debug!("build_fast_ffi_fn(%s)", link_name(ccx, item));
 
         let fcx = new_fn_ctxt(ccx, ~[], decl, tys.fn_sig.output, None);
-        let bcx = fcx.entry_bcx.get();
+        let bcx = fcx.entry_bcx.unwrap();
         let llbasefn = base_fn(ccx, link_name(ccx, item), tys, cc);
         set_no_inline(fcx.llfn);
         set_fixed_stack_segment(fcx.llfn);
@@ -458,7 +458,7 @@ fn build_fast_ffi_fn(ccx: @mut CrateContext,
         });
         let retval = Call(bcx, llbasefn, args);
         if !ty::type_is_nil(ret_ty) && !ty::type_is_bot(ret_ty) {
-            Store(bcx, retval, fcx.llretptr.get());
+            Store(bcx, retval, fcx.llretptr.unwrap());
         }
         finish_fn(fcx, bcx);
     }
@@ -618,7 +618,7 @@ fn count_zeros_intrinsic(bcx: @mut Block, name: &'static str) {
         set_fixed_stack_segment(fcx.llfn);
     }
 
-    let mut bcx = fcx.entry_bcx.get();
+    let mut bcx = fcx.entry_bcx.unwrap();
     let first_real_arg = fcx.arg_pos(0u);
 
     let nm = ccx.sess.str_of(item.ident);
@@ -775,7 +775,7 @@ fn count_zeros_intrinsic(bcx: @mut Block, name: &'static str) {
             let in_type_size = machine::llbitsize_of_real(ccx, llintype);
             let out_type_size = machine::llbitsize_of_real(ccx, llouttype);
             if in_type_size != out_type_size {
-                let sp = match ccx.tcx.items.get_copy(&ref_id.get()) {
+                let sp = match ccx.tcx.items.get_copy(&ref_id.unwrap()) {
                     ast_map::node_expr(e) => e.span,
                     _ => fail!("transmute has non-expr arg"),
                 };
@@ -816,7 +816,7 @@ fn count_zeros_intrinsic(bcx: @mut Block, name: &'static str) {
                     // NB: Do not use a Load and Store here. This causes massive
                     // code bloat when `transmute` is used on large structural
                     // types.
-                    let lldestptr = fcx.llretptr.get();
+                    let lldestptr = fcx.llretptr.unwrap();
                     let lldestptr = PointerCast(bcx, lldestptr, Type::i8p());
                     let llsrcptr = PointerCast(bcx, llsrcval, Type::i8p());
 
index 659f56b355e790c1bf81a1bdbaed02989842506f..948c9ceef8e6182da8188e5f6eb048ef556647cc 100644 (file)
@@ -311,7 +311,7 @@ pub fn call_tydesc_glue_full(bcx: @mut Block,
     let llrawptr = if static_ti.is_none() || static_glue_fn.is_none() {
         PointerCast(bcx, v, Type::i8p())
     } else {
-        let ty = static_ti.get().ty;
+        let ty = static_ti.unwrap().ty;
         let simpl = simplified_glue_type(ccx.tcx, field, ty);
         if simpl != ty {
             PointerCast(bcx, v, type_of(ccx, simpl).ptr_to())
@@ -708,7 +708,7 @@ pub fn make_generic_glue_inner(ccx: @mut CrateContext,
     // llfn is expected be declared to take a parameter of the appropriate
     // type, so we don't need to explicitly cast the function parameter.
 
-    let bcx = fcx.entry_bcx.get();
+    let bcx = fcx.entry_bcx.unwrap();
     let rawptr0_arg = fcx.arg_pos(0u);
     let llrawptr0 = unsafe { llvm::LLVMGetParam(llfn, rawptr0_arg as c_uint) };
     let bcx = helper(bcx, llrawptr0, t);
index 6fd47436fd8849d25dabfd0e3b5c72258f853d8e..5f8837b538cdfbd8b0b9992fc47c26713c21696a 100644 (file)
@@ -180,7 +180,7 @@ pub fn monomorphic_fn(ccx: @mut CrateContext,
             let idx = psubsts.tys.len() - num_method_ty_params;
             let substs =
                 (psubsts.tys.slice(0, idx) +
-                 &[psubsts.self_ty.get()] +
+                 &[psubsts.self_ty.unwrap()] +
                  psubsts.tys.tailn(idx));
             debug!("static default: changed substitution to %s",
                    substs.repr(ccx.tcx));
@@ -245,7 +245,7 @@ pub fn monomorphic_fn(ccx: @mut CrateContext,
       }
       ast_map::node_variant(ref v, enum_item, _) => {
         let tvs = ty::enum_variants(ccx.tcx, local_def(enum_item.id));
-        let this_tv = *tvs.iter().find_(|tv| { tv.id.node == fn_id.node}).get();
+        let this_tv = *tvs.iter().find_(|tv| { tv.id.node == fn_id.node}).unwrap();
         let d = mk_lldecl();
         set_inline_hint(d);
         match v.node.kind {
index e4259c80720e672401c7e586755b537820b253a0..609aad0bc201cc514aef7e5f533a7b5c7b5d52af 100644 (file)
@@ -303,10 +303,10 @@ pub fn visit_ty(&mut self, t: ty::t) {
                     //
                     llvm::LLVMGetParam(llfdecl, fcx.arg_pos(0u) as c_uint)
                 };
-                let mut bcx = fcx.entry_bcx.get();
+                let mut bcx = fcx.entry_bcx.unwrap();
                 let arg = BitCast(bcx, arg, llptrty);
                 let ret = adt::trans_get_discr(bcx, repr, arg);
-                Store(bcx, ret, fcx.llretptr.get());
+                Store(bcx, ret, fcx.llretptr.unwrap());
                 match fcx.llreturn {
                     Some(llreturn) => cleanup_and_Br(bcx, bcx, llreturn),
                     None => bcx = cleanup_block(bcx, Some(bcx.llbb))
index b743f2e9401575cc30d353298873433a6229293b..6a382cc1a5d1cc82b6682d6fc34a32683c5509c2 100644 (file)
@@ -239,7 +239,7 @@ pub fn type_of(cx: &mut CrateContext, t: ty::t) -> Type {
 
       ty::ty_estr(ty::vstore_slice(_)) => {
           // This means we get a nicer name in the output
-          cx.tn.find_type("str_slice").get()
+          cx.tn.find_type("str_slice").unwrap()
       }
 
       ty::ty_estr(ty::vstore_fixed(n)) => {
index 29b975cdf99f8908a49ababec5b18eaf5a68374a..a53bdff85f9dc2cb4903f2ef47d67b2b69969ce0 100644 (file)
@@ -25,7 +25,6 @@
 use util::ppaux::{trait_store_to_str, ty_to_str, vstore_to_str};
 use util::ppaux::{Repr, UserString};
 use util::common::{indenter};
-use util::enum_set::{EnumSet, CLike};
 
 use std::cast;
 use std::cmp;
@@ -33,6 +32,7 @@
 use std::ops;
 use std::ptr::to_unsafe_ptr;
 use std::to_bytes;
+use std::to_str::ToStr;
 use std::u32;
 use std::vec;
 use syntax::ast::*;
@@ -47,6 +47,7 @@
 use syntax::opt_vec;
 use syntax::abi::AbiSet;
 use syntax;
+use extra::enum_set::{EnumSet, CLike};
 
 pub static INITIAL_DISCRIMINANT_VALUE: uint = 0;
 
@@ -116,7 +117,7 @@ pub struct mt {
     mutbl: ast::mutability,
 }
 
-#[deriving(Clone, Eq, Encodable, Decodable, IterBytes)]
+#[deriving(Clone, Eq, Encodable, Decodable, IterBytes, ToStr)]
 pub enum vstore {
     vstore_fixed(uint),
     vstore_uniq,
@@ -124,7 +125,7 @@ pub enum vstore {
     vstore_slice(Region)
 }
 
-#[deriving(Clone, Eq, IterBytes, Encodable, Decodable)]
+#[deriving(Clone, Eq, IterBytes, Encodable, Decodable, ToStr)]
 pub enum TraitStore {
     BoxTraitStore,              // @Trait
     UniqTraitStore,             // ~Trait
@@ -350,6 +351,12 @@ pub struct t_box_ {
 enum t_opaque {}
 pub type t = *t_opaque;
 
+impl ToStr for t {
+    fn to_str(&self) -> ~str {
+        ~"*t_opaque"
+    }
+}
+
 pub fn get(t: t) -> t_box {
     unsafe {
         let t2: t_box = cast::transmute(t);
@@ -410,7 +417,7 @@ pub struct param_ty {
 }
 
 /// Representation of regions:
-#[deriving(Clone, Eq, IterBytes, Encodable, Decodable)]
+#[deriving(Clone, Eq, IterBytes, Encodable, Decodable, ToStr)]
 pub enum Region {
     /// Bound regions are found (primarily) in function types.  They indicate
     /// region parameters that have yet to be replaced with actual regions
@@ -456,13 +463,13 @@ pub fn is_bound(&self) -> bool {
     }
 }
 
-#[deriving(Clone, Eq, IterBytes, Encodable, Decodable)]
+#[deriving(Clone, Eq, IterBytes, Encodable, Decodable, ToStr)]
 pub struct FreeRegion {
     scope_id: NodeId,
     bound_region: bound_region
 }
 
-#[deriving(Clone, Eq, IterBytes, Encodable, Decodable)]
+#[deriving(Clone, Eq, IterBytes, Encodable, Decodable, ToStr)]
 pub enum bound_region {
     /// The self region for structs, impls (&T in a type defn or &'self T)
     br_self,
@@ -620,19 +627,22 @@ pub enum IntVarValue {
     UintType(ast::uint_ty),
 }
 
-#[deriving(Clone)]
+#[deriving(Clone, ToStr)]
 pub enum terr_vstore_kind {
-    terr_vec, terr_str, terr_fn, terr_trait
+    terr_vec,
+    terr_str,
+    terr_fn,
+    terr_trait
 }
 
-#[deriving(Clone)]
+#[deriving(Clone, ToStr)]
 pub struct expected_found<T> {
     expected: T,
     found: T
 }
 
 // Data structures used in type unification
-#[deriving(Clone)]
+#[deriving(Clone, ToStr)]
 pub enum type_err {
     terr_mismatch,
     terr_purity_mismatch(expected_found<purity>),
@@ -674,7 +684,7 @@ pub struct ParamBounds {
 
 pub type BuiltinBounds = EnumSet<BuiltinBound>;
 
-#[deriving(Clone, Eq, IterBytes)]
+#[deriving(Clone, Eq, IterBytes, ToStr)]
 pub enum BuiltinBound {
     BoundStatic,
     BoundSend,
@@ -725,7 +735,7 @@ pub enum InferTy {
     FloatVar(FloatVid)
 }
 
-#[deriving(Clone, Encodable, Decodable, IterBytes)]
+#[deriving(Clone, Encodable, Decodable, IterBytes, ToStr)]
 pub enum InferRegion {
     ReVar(RegionVid),
     ReSkolemized(uint, bound_region)
@@ -2277,7 +2287,7 @@ fn trait_contents(store: TraitStore, mutbl: ast::mutability,
         // This is like with typarams below, but less "pessimistic" and also
         // dependent on the trait store.
         let mut bt = TC_NONE;
-        do (AllBuiltinBounds() - bounds).each |bound| {
+        for bound in (AllBuiltinBounds() - bounds).iter() {
             bt = bt + match bound {
                 BoundStatic if bounds.contains_elem(BoundSend)
                             => TC_NONE, // Send bound implies static bound.
@@ -2286,8 +2296,7 @@ fn trait_contents(store: TraitStore, mutbl: ast::mutability,
                 BoundFreeze => TC_MUTABLE,
                 BoundSized  => TC_NONE, // don't care if interior is sized
             };
-            true
-        };
+        }
         st + mt + bt
     }
 
@@ -2298,7 +2307,7 @@ fn type_param_def_to_contents(cx: ctxt,
         let _i = indenter();
 
         let mut tc = TC_ALL;
-        do type_param_def.bounds.builtin_bounds.each |bound| {
+        for bound in type_param_def.bounds.builtin_bounds.iter() {
             debug!("tc = %s, bound = %?", tc.to_str(), bound);
             tc = tc - match bound {
                 BoundStatic => TypeContents::nonstatic(cx),
@@ -2307,8 +2316,7 @@ fn type_param_def_to_contents(cx: ctxt,
                 // The dynamic-size bit can be removed at pointer-level, etc.
                 BoundSized => TypeContents::dynamically_sized(cx),
             };
-            true
-        };
+        }
 
         debug!("result = %s", tc.to_str());
         return tc;
index ebf9d0944c9fbb8335d9ccdbd43ff948555fdd0c..53853e4fe1a78be01dedd8e7e1256cb521214e7b 100644 (file)
@@ -531,7 +531,7 @@ pub fn ty_of_arg<AC:AstConv,
                  expected_ty: Option<ty::t>)
                  -> ty::t {
     match a.ty.node {
-        ast::ty_infer if expected_ty.is_some() => expected_ty.get(),
+        ast::ty_infer if expected_ty.is_some() => expected_ty.unwrap(),
         ast::ty_infer => this.ty_infer(a.ty.span),
         _ => ast_ty_to_ty(this, rscope, &a.ty),
     }
@@ -587,7 +587,7 @@ pub fn ty_of_method<AC:AstConv,RS:region_scope + Clone + 'static>(
     };
     let (a, b) = ty_of_method_or_bare_fn(
         this, rscope, purity, AbiSet::Rust(), lifetimes, Some(&self_info), decl);
-    (a.get(), b)
+    (a.unwrap(), b)
 }
 
 pub fn ty_of_bare_fn<AC:AstConv,RS:region_scope + Clone + 'static>(
@@ -735,7 +735,7 @@ pub fn ty_of_closure<AC:AstConv,RS:region_scope + Clone + 'static>(
 
     let expected_ret_ty = expected_sig.map(|e| e.output);
     let output_ty = match decl.output.node {
-        ast::ty_infer if expected_ret_ty.is_some() => expected_ret_ty.get(),
+        ast::ty_infer if expected_ret_ty.is_some() => expected_ret_ty.unwrap(),
         ast::ty_infer => this.ty_infer(decl.output.span),
         _ => ast_ty_to_ty(this, &rb, &decl.output)
     };
index 842bbff41e065689914c5617b8b2bbeabc31c8d6..7caed39060159bd2c1d321c9466a1a9b20ba5a1d 100644 (file)
@@ -166,7 +166,7 @@ pub fn check_pat_variant(pcx: &pat_ctxt, pat: @ast::pat, path: &ast::Path,
                     fcx.write_error(pat.id);
                     kind_name = "[error]";
                     arg_types = (*subpats).clone()
-                                          .get_or_default(~[])
+                                          .unwrap_or_default(~[])
                                           .map(|_| ty::mk_err());
                 }
             }
@@ -209,7 +209,7 @@ pub fn check_pat_variant(pcx: &pat_ctxt, pat: @ast::pat, path: &ast::Path,
             fcx.write_error(pat.id);
             kind_name = "[error]";
             arg_types = (*subpats).clone()
-                                  .get_or_default(~[])
+                                  .unwrap_or_default(~[])
                                   .map(|_| ty::mk_err());
         }
     }
index 209f636ddc238d588f867b3cb233306f8f61c319..e1e7d10db0abd5ba07481b5a9d505e08f8221319 100644 (file)
@@ -854,7 +854,7 @@ pub fn confirm_candidate(&self, rcvr_ty: ty::t, candidate: &Candidate)
                         // like &'a Self.  We then perform a
                         // substitution which will replace Self with
                         // @Trait.
-                        let t = candidate.method_ty.transformed_self_ty.get();
+                        let t = candidate.method_ty.transformed_self_ty.unwrap();
                         ty::subst(tcx, &candidate.rcvr_substs, t)
                     }
                     _ => {
@@ -863,7 +863,7 @@ pub fn confirm_candidate(&self, rcvr_ty: ty::t, candidate: &Candidate)
                 }
             }
             _ => {
-                let t = candidate.method_ty.transformed_self_ty.get();
+                let t = candidate.method_ty.transformed_self_ty.unwrap();
                 ty::subst(tcx, &candidate.rcvr_substs, t)
             }
         };
@@ -922,7 +922,7 @@ pub fn confirm_candidate(&self, rcvr_ty: ty::t, candidate: &Candidate)
                 tcx, @Nil, Some(transformed_self_ty), &bare_fn_ty.sig,
                 |br| self.fcx.infcx().next_region_var(
                     infer::BoundRegionInFnCall(self.expr.span, br)));
-        let transformed_self_ty = opt_transformed_self_ty.get();
+        let transformed_self_ty = opt_transformed_self_ty.unwrap();
         let fty = ty::mk_bare_fn(tcx, ty::BareFnTy {
             sig: fn_sig,
             purity: bare_fn_ty.purity,
index 7f486f77447cb8c6c6d32c3d1370611c75e2c5e7..ea8a11fc7b3821b425f4ee3fac59c6927a712bb6 100644 (file)
@@ -365,7 +365,7 @@ pub fn check_fn(ccx: @mut CrateCtxt,
                                                  bound_region: br}));
         let opt_self_info =
             opt_self_info.map(
-                |si| SelfInfo {self_ty: opt_self_ty.get(), ..*si});
+                |si| SelfInfo {self_ty: opt_self_ty.unwrap(), ..*si});
         (isr, opt_self_info, fn_sig)
     };
 
@@ -2449,7 +2449,7 @@ fn check_struct_enum_variant(fcx: @mut FnCtxt,
                                            expected,
                                            |x| Some((*x).clone()));
         let inner_ty = match expected_sty {
-            Some(ty::ty_closure(_)) => expected.get(),
+            Some(ty::ty_closure(_)) => expected.unwrap(),
             _ => match expected {
                 Some(expected_t) => {
                     fcx.type_error_message(expr.span, |actual| {
index b9a62acd0bd879f21d7344b620b6262da850c7bf..f05388344bc7129914c230f0fa922af9dc2b8c07 100644 (file)
@@ -253,7 +253,7 @@ fn generalize_region(this: &Glb,
 
             if a_r.is_some() && b_r.is_some() && only_new_vars {
                 // Related to exactly one bound variable from each fn:
-                return rev_lookup(this, a_isr, a_r.get());
+                return rev_lookup(this, a_isr, a_r.unwrap());
             } else if a_r.is_none() && b_r.is_none() {
                 // Not related to bound variables from either fn:
                 return r0;
index e6c27fc8f836d1ee5db0a598ae661a551a939885..b1356ffb2d5e943632dd9d6a47f0b9966bb9ba52 100644 (file)
@@ -295,7 +295,7 @@ trait get_and_find_region {
 
 impl get_and_find_region for isr_alist {
     pub fn get(&self, br: ty::bound_region) -> ty::Region {
-        self.find(br).get()
+        self.find(br).unwrap()
     }
 
     pub fn find(&self, br: ty::bound_region) -> Option<ty::Region> {
index e2b25a67c3ddeb3d24d75df9570205d1534f8ec2..bbcf42b1c5d321b600eb4a1be6fa0f7411990c5b 100644 (file)
@@ -18,6 +18,7 @@
 use syntax::opt_vec;
 use syntax::parse::token::special_idents;
 
+#[deriving(ToStr)]
 pub struct RegionError {
     msg: ~str,
     replacement: ty::Region
index c48b30e81416439ad86c9e9217e8bfb10f43ee5a..46414a7a5e23e0cc13e0e886d94db7c872a2c20c 100644 (file)
@@ -96,7 +96,6 @@ pub mod back {
 pub mod util {
     pub mod common;
     pub mod ppaux;
-    pub mod enum_set;
 }
 
 pub mod lib {
diff --git a/src/librustc/util/enum_set.rs b/src/librustc/util/enum_set.rs
deleted file mode 100644 (file)
index 2466c37..0000000
+++ /dev/null
@@ -1,318 +0,0 @@
-// Copyright 2012 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 <LICENSE-APACHE or
-// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
-// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
-// option. This file may not be copied, modified, or distributed
-// except according to those terms.
-
-use std::iterator::Iterator;
-
-#[deriving(Clone, Eq, IterBytes)]
-pub struct EnumSet<E> {
-    // We must maintain the invariant that no bits are set
-    // for which no variant exists
-    priv bits: uint
-}
-
-pub trait CLike {
-    pub fn to_uint(&self) -> uint;
-    pub fn from_uint(uint) -> Self;
-}
-
-fn bit<E:CLike>(e: E) -> uint {
-    1 << e.to_uint()
-}
-
-impl<E:CLike> EnumSet<E> {
-    pub fn empty() -> EnumSet<E> {
-        EnumSet {bits: 0}
-    }
-
-    pub fn is_empty(&self) -> bool {
-        self.bits == 0
-    }
-
-    pub fn intersects(&self, e: EnumSet<E>) -> bool {
-        (self.bits & e.bits) != 0
-    }
-
-    pub fn intersection(&self, e: EnumSet<E>) -> EnumSet<E> {
-        EnumSet {bits: self.bits & e.bits}
-    }
-
-    pub fn contains(&self, e: EnumSet<E>) -> bool {
-        (self.bits & e.bits) == e.bits
-    }
-
-    pub fn union(&self, e: EnumSet<E>) -> EnumSet<E> {
-        EnumSet {bits: self.bits | e.bits}
-    }
-
-    pub fn add(&mut self, e: E) {
-        self.bits |= bit(e);
-    }
-
-    pub fn contains_elem(&self, e: E) -> bool {
-        (self.bits & bit(e)) != 0
-    }
-
-    pub fn each(&self, f: &fn(E) -> bool) -> bool {
-        let mut bits = self.bits;
-        let mut index = 0;
-        while bits != 0 {
-            if (bits & 1) != 0 {
-                let e = CLike::from_uint(index);
-                if !f(e) {
-                    return false;
-                }
-            }
-            index += 1;
-            bits >>= 1;
-        }
-        return true;
-    }
-
-    pub fn iter(&self) -> EnumSetIterator<E> {
-        EnumSetIterator::new(self.bits)
-    }
-}
-
-impl<E:CLike> Sub<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
-    fn sub(&self, e: &EnumSet<E>) -> EnumSet<E> {
-        EnumSet {bits: self.bits & !e.bits}
-    }
-}
-
-impl<E:CLike> BitOr<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
-    fn bitor(&self, e: &EnumSet<E>) -> EnumSet<E> {
-        EnumSet {bits: self.bits | e.bits}
-    }
-}
-
-impl<E:CLike> BitAnd<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
-    fn bitand(&self, e: &EnumSet<E>) -> EnumSet<E> {
-        EnumSet {bits: self.bits & e.bits}
-    }
-}
-
-pub struct EnumSetIterator<E> {
-    priv index: uint,
-    priv bits: uint,
-}
-
-impl<E:CLike> EnumSetIterator<E> {
-    fn new(bits: uint) -> EnumSetIterator<E> {
-        EnumSetIterator { index: 0, bits: bits }
-    }
-}
-
-impl<E:CLike> Iterator<E> for EnumSetIterator<E> {
-    fn next(&mut self) -> Option<E> {
-        if (self.bits == 0) {
-            return None;
-        }
-
-        while (self.bits & 1) == 0 {
-            self.index += 1;
-            self.bits >>= 1;
-        }
-        let elem = CLike::from_uint(self.index);
-        self.index += 1;
-        self.bits >>= 1;
-        Some(elem)
-    }
-
-    fn size_hint(&self) -> (uint, Option<uint>) {
-        let exact = self.bits.population_count();
-        (exact, Some(exact))
-    }
-}
-
-#[cfg(test)]
-mod test {
-
-    use std::cast;
-
-    use util::enum_set::*;
-
-    #[deriving(Eq)]
-    enum Foo {
-        A, B, C
-    }
-
-    impl CLike for Foo {
-        pub fn to_uint(&self) -> uint {
-            *self as uint
-        }
-
-        pub fn from_uint(v: uint) -> Foo {
-            unsafe { cast::transmute(v) }
-        }
-    }
-
-    #[test]
-    fn test_empty() {
-        let e: EnumSet<Foo> = EnumSet::empty();
-        assert!(e.is_empty());
-    }
-
-    ///////////////////////////////////////////////////////////////////////////
-    // intersect
-
-    #[test]
-    fn test_two_empties_do_not_intersect() {
-        let e1: EnumSet<Foo> = EnumSet::empty();
-        let e2: EnumSet<Foo> = EnumSet::empty();
-        assert!(!e1.intersects(e2));
-    }
-
-    #[test]
-    fn test_empty_does_not_intersect_with_full() {
-        let e1: EnumSet<Foo> = EnumSet::empty();
-
-        let mut e2: EnumSet<Foo> = EnumSet::empty();
-        e2.add(A);
-        e2.add(B);
-        e2.add(C);
-
-        assert!(!e1.intersects(e2));
-    }
-
-    #[test]
-    fn test_disjoint_intersects() {
-        let mut e1: EnumSet<Foo> = EnumSet::empty();
-        e1.add(A);
-
-        let mut e2: EnumSet<Foo> = EnumSet::empty();
-        e2.add(B);
-
-        assert!(!e1.intersects(e2));
-    }
-
-    #[test]
-    fn test_overlapping_intersects() {
-        let mut e1: EnumSet<Foo> = EnumSet::empty();
-        e1.add(A);
-
-        let mut e2: EnumSet<Foo> = EnumSet::empty();
-        e2.add(A);
-        e2.add(B);
-
-        assert!(e1.intersects(e2));
-    }
-
-    ///////////////////////////////////////////////////////////////////////////
-    // contains and contains_elem
-
-    #[test]
-    fn test_contains() {
-        let mut e1: EnumSet<Foo> = EnumSet::empty();
-        e1.add(A);
-
-        let mut e2: EnumSet<Foo> = EnumSet::empty();
-        e2.add(A);
-        e2.add(B);
-
-        assert!(!e1.contains(e2));
-        assert!(e2.contains(e1));
-    }
-
-    #[test]
-    fn test_contains_elem() {
-        let mut e1: EnumSet<Foo> = EnumSet::empty();
-        e1.add(A);
-        assert!(e1.contains_elem(A));
-        assert!(!e1.contains_elem(B));
-        assert!(!e1.contains_elem(C));
-
-        e1.add(A);
-        e1.add(B);
-        assert!(e1.contains_elem(A));
-        assert!(e1.contains_elem(B));
-        assert!(!e1.contains_elem(C));
-    }
-
-    ///////////////////////////////////////////////////////////////////////////
-    // iter / each
-
-    #[test]
-    fn test_iterator() {
-        let mut e1: EnumSet<Foo> = EnumSet::empty();
-
-        let elems: ~[Foo] = e1.iter().collect();
-        assert_eq!(~[], elems)
-
-        e1.add(A);
-        let elems: ~[Foo] = e1.iter().collect();
-        assert_eq!(~[A], elems)
-
-        e1.add(C);
-        let elems: ~[Foo] = e1.iter().collect();
-        assert_eq!(~[A,C], elems)
-
-        e1.add(C);
-        let elems: ~[Foo] = e1.iter().collect();
-        assert_eq!(~[A,C], elems)
-
-        e1.add(B);
-        let elems: ~[Foo] = e1.iter().collect();
-        assert_eq!(~[A,B,C], elems)
-    }
-
-    #[test]
-    fn test_each() {
-        let mut e1: EnumSet<Foo> = EnumSet::empty();
-
-        assert_eq!(~[], collect(e1))
-
-        e1.add(A);
-        assert_eq!(~[A], collect(e1))
-
-        e1.add(C);
-        assert_eq!(~[A,C], collect(e1))
-
-        e1.add(C);
-        assert_eq!(~[A,C], collect(e1))
-
-        e1.add(B);
-        assert_eq!(~[A,B,C], collect(e1))
-    }
-
-    fn collect(e: EnumSet<Foo>) -> ~[Foo] {
-        let mut elems = ~[];
-        e.each(|elem| {
-           elems.push(elem);
-           true
-        });
-        elems
-    }
-
-    ///////////////////////////////////////////////////////////////////////////
-    // operators
-
-    #[test]
-    fn test_operators() {
-        let mut e1: EnumSet<Foo> = EnumSet::empty();
-        e1.add(A);
-        e1.add(C);
-
-        let mut e2: EnumSet<Foo> = EnumSet::empty();
-        e2.add(B);
-        e2.add(C);
-
-        let e_union = e1 | e2;
-        let elems: ~[Foo] = e_union.iter().collect();
-        assert_eq!(~[A,B,C], elems)
-
-        let e_intersection = e1 & e2;
-        let elems: ~[Foo] = e_intersection.iter().collect();
-        assert_eq!(~[C], elems)
-
-        let e_subtract = e1 - e2;
-        let elems: ~[Foo] = e_subtract.iter().collect();
-        assert_eq!(~[A], elems)
-    }
-}
index 8f0dd51457074c23bdd2e2a7cb219e4f8cd40301..8329ad2cdf1de34ca864f5919f6681ed36b90ecf 100644 (file)
@@ -589,15 +589,14 @@ fn repr(&self, tcx: ctxt) -> ~str {
 impl Repr for ty::ParamBounds {
     fn repr(&self, tcx: ctxt) -> ~str {
         let mut res = ~[];
-        do self.builtin_bounds.each |b| {
+        for b in self.builtin_bounds.iter() {
             res.push(match b {
                 ty::BoundStatic => ~"'static",
                 ty::BoundSend => ~"Send",
                 ty::BoundFreeze => ~"Freeze",
                 ty::BoundSized => ~"Sized",
             });
-            true
-        };
+        }
         for t in self.trait_bounds.iter() {
             res.push(t.repr(tcx));
         }
@@ -833,10 +832,9 @@ impl UserString for ty::BuiltinBounds {
     fn user_string(&self, tcx: ctxt) -> ~str {
         if self.is_empty() { ~"<no-bounds>" } else {
             let mut result = ~[];
-            do self.each |bb| {
+            for bb in self.iter() {
                 result.push(bb.user_string(tcx));
-                true
-            };
+            }
             result.connect("+")
         }
     }
index b189bd2bc2dcdf5ff8dec5537d6888c525d54319..a1cb81f4503579eae39d6c34a9f13c9728dbbfcd 100644 (file)
@@ -68,7 +68,7 @@ fn fold_crate(
     doc::CrateDoc {
         topmod: doc::ModDoc {
             item: doc::ItemDoc {
-                name: attrs.name.clone().get_or_default(doc.topmod.name_()),
+                name: attrs.name.clone().unwrap_or_default(doc.topmod.name_()),
                 .. doc.topmod.item.clone()
             },
             .. doc.topmod.clone()
@@ -135,7 +135,7 @@ fn fold_enum(
                             let ast_variant =
                                 (*enum_definition.variants.iter().find_(|v| {
                                     to_str(v.node.name) == variant.name
-                                }).get()).clone();
+                                }).unwrap()).clone();
 
                             attr_parser::parse_desc(
                                 ast_variant.node.attrs.clone())
index f287e17880bb333419cb4b69dd2c2f69e77e2fd9..d387bbea592d36374231a4e59a4572d00d177fef 100644 (file)
@@ -142,7 +142,7 @@ fn config_from_opts(
         let output_dir = getopts::opt_maybe_str(matches, opt_output_dir());
         let output_dir = output_dir.map(|s| Path(*s));
         result::Ok(Config {
-            output_dir: output_dir.get_or_default(config.output_dir.clone()),
+            output_dir: output_dir.unwrap_or_default(config.output_dir.clone()),
             .. config
         })
     };
@@ -273,20 +273,20 @@ fn should_error_with_no_pandoc() {
     #[test]
     fn should_error_with_no_crates() {
         let config = parse_config([~"rustdoc"]);
-        assert!(config.get_err() == ~"no crates specified");
+        assert!(config.unwrap_err() == ~"no crates specified");
     }
 
     #[test]
     fn should_error_with_multiple_crates() {
         let config =
             parse_config([~"rustdoc", ~"crate1.rc", ~"crate2.rc"]);
-        assert!(config.get_err() == ~"multiple crates specified");
+        assert!(config.unwrap_err() == ~"multiple crates specified");
     }
 
     #[test]
     fn should_set_output_dir_to_cwd_if_not_provided() {
         let config = parse_config([~"rustdoc", ~"crate.rc"]);
-        assert!(config.get().output_dir == Path("."));
+        assert!(config.unwrap().output_dir == Path("."));
     }
 
     #[test]
@@ -294,13 +294,13 @@ fn should_set_output_dir_if_provided() {
         let config = parse_config([
             ~"rustdoc", ~"crate.rc", ~"--output-dir", ~"snuggles"
         ]);
-        assert!(config.get().output_dir == Path("snuggles"));
+        assert!(config.unwrap().output_dir == Path("snuggles"));
     }
 
     #[test]
     fn should_set_output_format_to_pandoc_html_if_not_provided() {
         let config = parse_config([~"rustdoc", ~"crate.rc"]);
-        assert!(config.get().output_format == PandocHtml);
+        assert!(config.unwrap().output_format == PandocHtml);
     }
 
     #[test]
@@ -308,7 +308,7 @@ fn should_set_output_format_to_markdown_if_requested() {
         let config = parse_config([
             ~"rustdoc", ~"crate.rc", ~"--output-format", ~"markdown"
         ]);
-        assert!(config.get().output_format == Markdown);
+        assert!(config.unwrap().output_format == Markdown);
     }
 
     #[test]
@@ -316,7 +316,7 @@ fn should_set_output_format_to_pandoc_html_if_requested() {
         let config = parse_config([
             ~"rustdoc", ~"crate.rc", ~"--output-format", ~"html"
         ]);
-        assert!(config.get().output_format == PandocHtml);
+        assert!(config.unwrap().output_format == PandocHtml);
     }
 
     #[test]
@@ -324,13 +324,13 @@ fn should_error_on_bogus_format() {
         let config = parse_config([
             ~"rustdoc", ~"crate.rc", ~"--output-format", ~"bogus"
         ]);
-        assert!(config.get_err() == ~"unknown output format 'bogus'");
+        assert!(config.unwrap_err() == ~"unknown output format 'bogus'");
     }
 
     #[test]
     fn should_set_output_style_to_doc_per_mod_by_default() {
         let config = parse_config([~"rustdoc", ~"crate.rc"]);
-        assert!(config.get().output_style == DocPerMod);
+        assert!(config.unwrap().output_style == DocPerMod);
     }
 
     #[test]
@@ -338,7 +338,7 @@ fn should_set_output_style_to_one_doc_if_requested() {
         let config = parse_config([
             ~"rustdoc", ~"crate.rc", ~"--output-style", ~"doc-per-crate"
         ]);
-        assert!(config.get().output_style == DocPerCrate);
+        assert!(config.unwrap().output_style == DocPerCrate);
     }
 
     #[test]
@@ -346,7 +346,7 @@ fn should_set_output_style_to_doc_per_mod_if_requested() {
         let config = parse_config([
             ~"rustdoc", ~"crate.rc", ~"--output-style", ~"doc-per-mod"
         ]);
-        assert!(config.get().output_style == DocPerMod);
+        assert!(config.unwrap().output_style == DocPerMod);
     }
 
     #[test]
@@ -354,7 +354,7 @@ fn should_error_on_bogus_output_style() {
         let config = parse_config([
             ~"rustdoc", ~"crate.rc", ~"--output-style", ~"bogus"
         ]);
-        assert!(config.get_err() == ~"unknown output style 'bogus'");
+        assert!(config.unwrap_err() == ~"unknown output style 'bogus'");
     }
 
     #[test]
@@ -362,12 +362,12 @@ fn should_set_pandoc_command_if_requested() {
         let config = parse_config([
             ~"rustdoc", ~"crate.rc", ~"--pandoc-cmd", ~"panda-bear-doc"
         ]);
-        assert!(config.get().pandoc_cmd == Some(~"panda-bear-doc"));
+        assert!(config.unwrap().pandoc_cmd == Some(~"panda-bear-doc"));
     }
 
     #[test]
     fn should_set_pandoc_command_when_using_pandoc() {
         let config = parse_config([~"rustdoc", ~"crate.rc"]);
-        assert!(config.get().pandoc_cmd == Some(~"pandoc"));
+        assert!(config.unwrap().pandoc_cmd == Some(~"pandoc"));
     }
 }
index 9e1dffb989b0017e7d6e2111c7d2389cea9f76b0..9f8041712eaecdb12d38bb0843ec7edbe675e9c2 100644 (file)
@@ -83,7 +83,7 @@ pub fn extract(desc: Option<~str>) -> Option<~str> {
         return None
     }
 
-    parse_desc(desc.clone().get())
+    parse_desc(desc.clone().unwrap())
 }
 
 fn parse_desc(desc: ~str) -> Option<~str> {
index cca898feba2b2d49d106a758bffb3dc20e83cc5b..d24fd1f5bfe54fb59cc90ecb61fc482976938154 100644 (file)
@@ -176,7 +176,7 @@ pub fn CrateDoc(&self) -> CrateDoc {
               doc::CratePage(doc) => Some(doc),
               _ => None
             }
-        }).get()
+        }).unwrap()
     }
 
     pub fn cratemod(&self) -> ModDoc {
index 2c6312e01b205e988f6c576b4a86857ea3d0b796..90634770a501eaa0b8869a48ff3aa10bcab69be3 100644 (file)
@@ -223,13 +223,13 @@ fn should_index_mod_contents() {
             config::DocPerCrate,
             ~"mod a { } fn b() { }"
         );
-        assert!(doc.cratemod().index.get().entries[0] == doc::IndexEntry {
+        assert!(doc.cratemod().index.unwrap().entries[0] == doc::IndexEntry {
             kind: ~"Module",
             name: ~"a",
             brief: None,
             link: ~"#module-a"
         });
-        assert!(doc.cratemod().index.get().entries[1] == doc::IndexEntry {
+        assert!(doc.cratemod().index.unwrap().entries[1] == doc::IndexEntry {
             kind: ~"Function",
             name: ~"b",
             brief: None,
@@ -243,13 +243,13 @@ fn should_index_mod_contents_multi_page() {
             config::DocPerMod,
             ~"mod a { } fn b() { }"
         );
-        assert_eq!(doc.cratemod().index.get().entries[0], doc::IndexEntry {
+        assert_eq!(doc.cratemod().index.unwrap().entries[0], doc::IndexEntry {
             kind: ~"Module",
             name: ~"a",
             brief: None,
             link: ~"a.html"
         });
-        assert_eq!(doc.cratemod().index.get().entries[1], doc::IndexEntry {
+        assert_eq!(doc.cratemod().index.unwrap().entries[1], doc::IndexEntry {
             kind: ~"Function",
             name: ~"b",
             brief: None,
@@ -263,7 +263,7 @@ fn should_add_brief_desc_to_index() {
             config::DocPerMod,
             ~"#[doc = \"test\"] mod a { }"
         );
-        assert_eq!(doc.cratemod().index.get().entries[0].brief, Some(~"test"));
+        assert_eq!(doc.cratemod().index.unwrap().entries[0].brief, Some(~"test"));
     }
 
     #[test]
@@ -273,7 +273,7 @@ fn should_index_foreign_mod_contents() {
             ~"extern { fn b(); }"
         );
         // hidden __std_macros module at the start.
-        assert_eq!(doc.cratemod().nmods()[0].index.get().entries[0],
+        assert_eq!(doc.cratemod().nmods()[0].index.unwrap().entries[0],
                    doc::IndexEntry {
                        kind: ~"Function",
                        name: ~"b",
index 0dbd29df48b631814a328d0e71164f6e10f26a86..85c360a9e0dfdd8153fa103791365235687276f3 100644 (file)
@@ -617,10 +617,10 @@ mod c {
               fn d() { }"
         );
 
-        let idx_a = markdown.find_str("# Module `a`").get();
-        let idx_b = markdown.find_str("## Function `b`").get();
-        let idx_c = markdown.find_str("# Module `c`").get();
-        let idx_d = markdown.find_str("## Function `d`").get();
+        let idx_a = markdown.find_str("# Module `a`").unwrap();
+        let idx_b = markdown.find_str("## Function `b`").unwrap();
+        let idx_c = markdown.find_str("# Module `c`").unwrap();
+        let idx_d = markdown.find_str("## Function `d`").unwrap();
 
         assert!(idx_b < idx_d);
         assert!(idx_d < idx_a);
index 4cd442bb95147db53f6951fa2e74f8fe45ae9b39..20f3ff3e98d4871b0ec72d4bf7a865c22d55b6f0 100644 (file)
@@ -218,8 +218,8 @@ fn should_remove_section_text_from_main_desc() {
               Body\"]\
               mod a {
 }");
-        assert!(!doc.cratemod().mods()[0].desc().get().contains("Header"));
-        assert!(!doc.cratemod().mods()[0].desc().get().contains("Body"));
+        assert!(!doc.cratemod().mods()[0].desc().unwrap().contains("Header"));
+        assert!(!doc.cratemod().mods()[0].desc().unwrap().contains("Body"));
     }
 
     #[test]
index abfc3517d60ebf7dc46b4a0cf905f674ab238d4e..684b4e9d198d4d1551e05418143f33b469485ce5 100644 (file)
@@ -135,7 +135,7 @@ fn fold_enum(
                             let ast_variant =
                                 (*do enum_definition.variants.iter().find_ |v| {
                                 to_str(v.node.name) == variant.name
-                            }.get()).clone();
+                            }.unwrap()).clone();
 
                             pprust::variant_to_str(
                                 &ast_variant, extract::interner())
@@ -443,7 +443,7 @@ fn should_add_type_signatures() {
     #[test]
     fn should_add_struct_defs() {
         let doc = mk_doc(~"struct S { field: () }");
-        assert!(doc.cratemod().structs()[0].sig.get().contains(
+        assert!(doc.cratemod().structs()[0].sig.unwrap().contains(
             "struct S {"));
     }
 
@@ -451,6 +451,6 @@ fn should_add_struct_defs() {
     fn should_not_serialize_struct_attrs() {
         // All we care about are the fields
         let doc = mk_doc(~"#[wut] struct S { field: () }");
-        assert!(!doc.cratemod().structs()[0].sig.get().contains("wut"));
+        assert!(!doc.cratemod().structs()[0].sig.unwrap().contains("wut"));
     }
 }
index 568a691290c88d34fbff024759c3b872af705abc..5d5518997f68f0252ab8e9c3acd276c0dec417f7 100644 (file)
@@ -322,14 +322,14 @@ fn compile_crate(src_filename: ~str, binary: ~str) -> Option<bool> {
             // instead we guess which file is the library by matching
             // the prefix and suffix of out_filename to files in the
             // directory.
-            let file_str = file.filename().get();
-            file_str.starts_with(outputs.out_filename.filestem().get())
-                && file_str.ends_with(outputs.out_filename.filetype().get())
+            let file_str = file.filename().unwrap();
+            file_str.starts_with(outputs.out_filename.filestem().unwrap())
+                && file_str.ends_with(outputs.out_filename.filetype().unwrap())
         };
         match maybe_lib_path {
             Some(lib_path) => {
-                let (src_mtime, _) = src_path.get_mtime().get();
-                let (lib_mtime, _) = lib_path.get_mtime().get();
+                let (src_mtime, _) = src_path.get_mtime().unwrap();
+                let (lib_mtime, _) = lib_path.get_mtime().unwrap();
                 if lib_mtime >= src_mtime {
                     should_compile = false;
                 }
index 4d6033de54de4bb2c3be9f9ad3dc70e409a650a2..fa03a5bbfc2fbf70eb47beea86951ae38971edd4 100644 (file)
@@ -102,7 +102,7 @@ fn parse<'a>(script: Path, workspace: &Path, id: &'a PkgId) -> PkgScript<'a> {
     debug!("pkgscript parse: %?", os::self_exe_path());
         let options = @session::options {
             binary: binary,
-            maybe_sysroot: Some(@os::self_exe_path().get().pop()),
+            maybe_sysroot: Some(@os::self_exe_path().unwrap().pop()),
             crate_type: session::bin_crate,
             .. (*session::basic_options()).clone()
         };
@@ -535,7 +535,7 @@ pub fn main() {
  * in is the working directory.
  */
 pub fn work_dir() -> Path {
-    os::self_exe_path().get()
+    os::self_exe_path().unwrap()
 }
 
 /**
index 361981289d3cef4c84be40d7304b17977d8e9d0b..81b47d6a16c0ad8ec9640ed6d988b88364a62a3b 100644 (file)
@@ -195,7 +195,7 @@ pub fn compile_input(ctxt: &Ctx,
                           }
                           + flags
                           + cfgs.flat_map(|c| { ~[~"--cfg", (*c).clone()] }),
-                          driver::optgroups()).get();
+                          driver::optgroups()).unwrap();
     let options = @session::options {
         crate_type: crate_type,
         optimize: if opt { session::Aggressive } else { session::No },
index 4ece53d0e7f529423827d4d13ec653696c32a82f..a84f3137bbd5bfb022f2ac93a6982472c59b3064 100644 (file)
@@ -78,10 +78,8 @@ pub fn build<A>(builder: &fn(push: &fn(v: A))) -> @[A] {
  *             onto the vector being constructed.
  */
 #[inline]
-pub fn build_sized_opt<A>(size: Option<uint>,
-                          builder: &fn(push: &fn(v: A)))
-                       -> @[A] {
-    build_sized(size.get_or_default(4), builder)
+pub fn build_sized_opt<A>(size: Option<uint>, builder: &fn(push: &fn(v: A))) -> @[A] {
+    build_sized(size.unwrap_or_default(4), builder)
 }
 
 // Appending
index 6bdc45d72042a7d9a589530b25458e679eee531d..cfaef550c6fa74072a2cd64413d7aa612e044a06 100644 (file)
 use vec;
 use vec::{OwnedVector, ImmutableVector};
 
-/// The either type
+/// `Either` is a type that represents one of two alternatives
 #[deriving(Clone, Eq)]
-pub enum Either<T, U> {
-    Left(T),
-    Right(U)
+pub enum Either<L, R> {
+    Left(L),
+    Right(R)
 }
 
-/// Applies a function based on the given either value
-///
-/// If `value` is left(T) then `f_left` is applied to its contents, if
-/// `value` is right(U) then `f_right` is applied to its contents, and the
-/// result is returned.
-#[inline]
-pub fn either<T, U, V>(f_left: &fn(&T) -> V,
-                       f_right: &fn(&U) -> V, value: &Either<T, U>) -> V {
-    match *value {
-        Left(ref l) => f_left(l),
-        Right(ref r) => f_right(r)
+impl<L, R> Either<L, R> {
+    /// Applies a function based on the given either value
+    ///
+    /// If `value` is `Left(L)` then `f_left` is applied to its contents, if
+    /// `value` is `Right(R)` then `f_right` is applied to its contents, and the
+    /// result is returned.
+    #[inline]
+    pub fn either<T>(&self, f_left: &fn(&L) -> T, f_right: &fn(&R) -> T) -> T {
+        match *self {
+            Left(ref l) => f_left(l),
+            Right(ref r) => f_right(r)
+        }
+    }
+
+    /// Flips between left and right of a given `Either`
+    #[inline]
+    pub fn flip(self) -> Either<R, L> {
+        match self {
+            Right(r) => Left(r),
+            Left(l) => Right(l)
+        }
+    }
+
+    /// Converts a `Either` to a `Result`
+    ///
+    /// Converts an `Either` type to a `Result` type, making the "right" choice
+    /// an `Ok` result, and the "left" choice a `Err`
+    #[inline]
+    pub fn to_result(self) -> Result<R, L> {
+        match self {
+            Right(r) => result::Ok(r),
+            Left(l) => result::Err(l)
+        }
+    }
+
+    /// Checks whether the given value is a `Left`
+    #[inline]
+    pub fn is_left(&self) -> bool {
+        match *self {
+            Left(_) => true,
+            _ => false
+        }
+    }
+
+    /// Checks whether the given value is a `Right`
+    #[inline]
+    pub fn is_right(&self) -> bool {
+        match *self {
+            Right(_) => true,
+            _ => false
+        }
+    }
+
+    /// Retrieves the value from a `Left`.
+    /// Fails with a specified reason if the `Either` is `Right`.
+    #[inline]
+    pub fn expect_left(self, reason: &str) -> L {
+        match self {
+            Left(x) => x,
+            Right(_) => fail!(reason.to_owned())
+        }
+    }
+
+    /// Retrieves the value from a `Left`. Fails if the `Either` is `Right`.
+    #[inline]
+    pub fn unwrap_left(self) -> L {
+        self.expect_left("called Either::unwrap_left()` on `Right` value")
+    }
+
+    /// Retrieves the value from a `Right`.
+    /// Fails with a specified reason if the `Either` is `Left`.
+    #[inline]
+    pub fn expect_right(self, reason: &str) -> R {
+        match self {
+            Right(x) => x,
+            Left(_) => fail!(reason.to_owned())
+        }
+    }
+
+    /// Retrieves the value from a `Right`. Fails if the `Either` is `Left`.
+    #[inline]
+    pub fn unwrap_right(self) -> R {
+        self.expect_right("called Either::unwrap_right()` on `Left` value")
     }
 }
 
+// FIXME: #8228 Replaceable by an external iterator?
 /// Extracts from a vector of either all the left values
-pub fn lefts<T:Clone,U>(eithers: &[Either<T, U>]) -> ~[T] {
+pub fn lefts<L: Clone, R>(eithers: &[Either<L, R>]) -> ~[L] {
     do vec::build_sized(eithers.len()) |push| {
         for elt in eithers.iter() {
             match *elt {
@@ -56,8 +129,9 @@ pub fn lefts<T:Clone,U>(eithers: &[Either<T, U>]) -> ~[T] {
     }
 }
 
+// FIXME: #8228 Replaceable by an external iterator?
 /// Extracts from a vector of either all the right values
-pub fn rights<T, U: Clone>(eithers: &[Either<T, U>]) -> ~[U] {
+pub fn rights<L, R: Clone>(eithers: &[Either<L, R>]) -> ~[R] {
     do vec::build_sized(eithers.len()) |push| {
         for elt in eithers.iter() {
             match *elt {
@@ -68,13 +142,14 @@ pub fn rights<T, U: Clone>(eithers: &[Either<T, U>]) -> ~[U] {
     }
 }
 
+// FIXME: #8228 Replaceable by an external iterator?
 /// Extracts from a vector of either all the left values and right values
 ///
 /// Returns a structure containing a vector of left values and a vector of
 /// right values.
-pub fn partition<T, U>(eithers: ~[Either<T, U>]) -> (~[T], ~[U]) {
-    let mut lefts: ~[T] = ~[];
-    let mut rights: ~[U] = ~[];
+pub fn partition<L, R>(eithers: ~[Either<L, R>]) -> (~[L], ~[R]) {
+    let mut lefts: ~[L] = ~[];
+    let mut rights: ~[R] = ~[];
     for elt in eithers.consume_iter() {
         match elt {
             Left(l) => lefts.push(l),
@@ -84,196 +159,101 @@ pub fn partition<T, U>(eithers: ~[Either<T, U>]) -> (~[T], ~[U]) {
     return (lefts, rights);
 }
 
-/// Flips between left and right of a given either
-#[inline]
-pub fn flip<T, U>(eith: Either<T, U>) -> Either<U, T> {
-    match eith {
-        Right(r) => Left(r),
-        Left(l) => Right(l)
-    }
-}
+#[cfg(test)]
+mod tests {
+    use super::*;
 
-/// Converts either::t to a result::t
-///
-/// Converts an `either` type to a `result` type, making the "right" choice
-/// an ok result, and the "left" choice a fail
-#[inline]
-pub fn to_result<T, U>(eith: Either<T, U>) -> Result<U, T> {
-    match eith {
-        Right(r) => result::Ok(r),
-        Left(l) => result::Err(l)
+    #[test]
+    fn test_either_left() {
+        let val = Left(10);
+        fn f_left(x: &int) -> bool { *x == 10 }
+        fn f_right(_x: &uint) -> bool { false }
+        assert!(val.either(f_left, f_right));
     }
-}
 
-/// Checks whether the given value is a left
-#[inline]
-pub fn is_left<T, U>(eith: &Either<T, U>) -> bool {
-    match *eith {
-        Left(_) => true,
-        _ => false
+    #[test]
+    fn test_either_right() {
+        let val = Right(10u);
+        fn f_left(_x: &int) -> bool { false }
+        fn f_right(x: &uint) -> bool { *x == 10u }
+        assert!(val.either(f_left, f_right));
     }
-}
 
-/// Checks whether the given value is a right
-#[inline]
-pub fn is_right<T, U>(eith: &Either<T, U>) -> bool {
-    match *eith {
-        Right(_) => true,
-        _ => false
+    #[test]
+    fn test_lefts() {
+        let input = ~[Left(10), Right(11), Left(12), Right(13), Left(14)];
+        let result = lefts(input);
+        assert_eq!(result, ~[10, 12, 14]);
     }
-}
 
-/// Retrieves the value in the left branch.
-/// Fails with a specified reason if the either is Right.
-#[inline]
-pub fn expect_left<T,U>(eith: Either<T,U>, reason: &str) -> T {
-    match eith {
-        Left(x) => x,
-        Right(_) => fail!(reason.to_owned())
+    #[test]
+    fn test_lefts_none() {
+        let input: ~[Either<int, int>] = ~[Right(10), Right(10)];
+        let result = lefts(input);
+        assert_eq!(result.len(), 0u);
     }
-}
 
-/// Retrieves the value in the left branch. Fails if the either is Right.
-#[inline]
-pub fn unwrap_left<T,U>(eith: Either<T,U>) -> T {
-    expect_left(eith, "either::unwrap_left Right")
-}
-
-/// Retrieves the value in the right branch.
-/// Fails with a specified reason if the either is Left.
-#[inline]
-pub fn expect_right<T,U>(eith: Either<T,U>, reason: &str) -> U {
-    match eith {
-        Right(x) => x,
-        Left(_) => fail!(reason.to_owned())
+    #[test]
+    fn test_lefts_empty() {
+        let input: ~[Either<int, int>] = ~[];
+        let result = lefts(input);
+        assert_eq!(result.len(), 0u);
     }
-}
 
-/// Retrieves the value in the right branch. Fails if the either is Left.
-pub fn unwrap_right<T,U>(eith: Either<T,U>) -> U {
-    expect_right(eith, "either::unwrap_right Left")
-}
-
-impl<T, U> Either<T, U> {
-    #[inline]
-    pub fn either<V>(&self, f_left: &fn(&T) -> V, f_right: &fn(&U) -> V) -> V {
-        either(f_left, f_right, self)
+    #[test]
+    fn test_rights() {
+        let input = ~[Left(10), Right(11), Left(12), Right(13), Left(14)];
+        let result = rights(input);
+        assert_eq!(result, ~[11, 13]);
     }
 
-    #[inline]
-    pub fn flip(self) -> Either<U, T> { flip(self) }
-
-    #[inline]
-    pub fn to_result(self) -> Result<U, T> { to_result(self) }
-
-    #[inline]
-    pub fn is_left(&self) -> bool { is_left(self) }
-
-    #[inline]
-    pub fn is_right(&self) -> bool { is_right(self) }
-
-    #[inline]
-    pub fn expect_left(self, reason: &str) -> T { expect_left(self, reason) }
-
-    #[inline]
-    pub fn unwrap_left(self) -> T { unwrap_left(self) }
-
-    #[inline]
-    pub fn expect_right(self, reason: &str) -> U { expect_right(self, reason) }
-
-    #[inline]
-    pub fn unwrap_right(self) -> U { unwrap_right(self) }
-}
-
-#[test]
-fn test_either_left() {
-    let val = Left(10);
-    fn f_left(x: &int) -> bool { *x == 10 }
-    fn f_right(_x: &uint) -> bool { false }
-    assert!((either(f_left, f_right, &val)));
-}
-
-#[test]
-fn test_either_right() {
-    let val = Right(10u);
-    fn f_left(_x: &int) -> bool { false }
-    fn f_right(x: &uint) -> bool { *x == 10u }
-    assert!((either(f_left, f_right, &val)));
-}
-
-#[test]
-fn test_lefts() {
-    let input = ~[Left(10), Right(11), Left(12), Right(13), Left(14)];
-    let result = lefts(input);
-    assert_eq!(result, ~[10, 12, 14]);
-}
-
-#[test]
-fn test_lefts_none() {
-    let input: ~[Either<int, int>] = ~[Right(10), Right(10)];
-    let result = lefts(input);
-    assert_eq!(result.len(), 0u);
-}
-
-#[test]
-fn test_lefts_empty() {
-    let input: ~[Either<int, int>] = ~[];
-    let result = lefts(input);
-    assert_eq!(result.len(), 0u);
-}
-
-#[test]
-fn test_rights() {
-    let input = ~[Left(10), Right(11), Left(12), Right(13), Left(14)];
-    let result = rights(input);
-    assert_eq!(result, ~[11, 13]);
-}
+    #[test]
+    fn test_rights_none() {
+        let input: ~[Either<int, int>] = ~[Left(10), Left(10)];
+        let result = rights(input);
+        assert_eq!(result.len(), 0u);
+    }
 
-#[test]
-fn test_rights_none() {
-    let input: ~[Either<int, int>] = ~[Left(10), Left(10)];
-    let result = rights(input);
-    assert_eq!(result.len(), 0u);
-}
+    #[test]
+    fn test_rights_empty() {
+        let input: ~[Either<int, int>] = ~[];
+        let result = rights(input);
+        assert_eq!(result.len(), 0u);
+    }
 
-#[test]
-fn test_rights_empty() {
-    let input: ~[Either<int, int>] = ~[];
-    let result = rights(input);
-    assert_eq!(result.len(), 0u);
-}
+    #[test]
+    fn test_partition() {
+        let input = ~[Left(10), Right(11), Left(12), Right(13), Left(14)];
+        let (lefts, rights) = partition(input);
+        assert_eq!(lefts[0], 10);
+        assert_eq!(lefts[1], 12);
+        assert_eq!(lefts[2], 14);
+        assert_eq!(rights[0], 11);
+        assert_eq!(rights[1], 13);
+    }
 
-#[test]
-fn test_partition() {
-    let input = ~[Left(10), Right(11), Left(12), Right(13), Left(14)];
-    let (lefts, rights) = partition(input);
-    assert_eq!(lefts[0], 10);
-    assert_eq!(lefts[1], 12);
-    assert_eq!(lefts[2], 14);
-    assert_eq!(rights[0], 11);
-    assert_eq!(rights[1], 13);
-}
+    #[test]
+    fn test_partition_no_lefts() {
+        let input: ~[Either<int, int>] = ~[Right(10), Right(11)];
+        let (lefts, rights) = partition(input);
+        assert_eq!(lefts.len(), 0u);
+        assert_eq!(rights.len(), 2u);
+    }
 
-#[test]
-fn test_partition_no_lefts() {
-    let input: ~[Either<int, int>] = ~[Right(10), Right(11)];
-    let (lefts, rights) = partition(input);
-    assert_eq!(lefts.len(), 0u);
-    assert_eq!(rights.len(), 2u);
-}
+    #[test]
+    fn test_partition_no_rights() {
+        let input: ~[Either<int, int>] = ~[Left(10), Left(11)];
+        let (lefts, rights) = partition(input);
+        assert_eq!(lefts.len(), 2u);
+        assert_eq!(rights.len(), 0u);
+    }
 
-#[test]
-fn test_partition_no_rights() {
-    let input: ~[Either<int, int>] = ~[Left(10), Left(11)];
-    let (lefts, rights) = partition(input);
-    assert_eq!(lefts.len(), 2u);
-    assert_eq!(rights.len(), 0u);
-}
+    #[test]
+    fn test_partition_empty() {
+        let input: ~[Either<int, int>] = ~[];
+        let (lefts, rights) = partition(input);
+        assert_eq!(lefts.len(), 0u);
+        assert_eq!(rights.len(), 0u);
+    }
 
-#[test]
-fn test_partition_empty() {
-    let input: ~[Either<int, int>] = ~[];
-    let (lefts, rights) = partition(input);
-    assert_eq!(lefts.len(), 0u);
-    assert_eq!(rights.len(), 0u);
 }
index 658f854c50d81ea80a9716ff9b2937add905e7db..fbc471c0ae05d4b289235134ec8366d040459437 100644 (file)
@@ -19,7 +19,8 @@
 use clone::Clone;
 use cmp::{Eq, Equiv};
 use hash::Hash;
-use iterator::{Iterator, IteratorUtil, FromIterator, Extendable, Chain, range};
+use iterator::{Iterator, IteratorUtil, FromIterator, Extendable, range};
+use iterator::{FilterMap, Chain, Repeat, Zip};
 use num;
 use option::{None, Option, Some};
 use rand::RngUtil;
@@ -712,10 +713,12 @@ pub fn consume(self) -> HashSetConsumeIterator<T> {
     }
 
     /// Visit the values representing the difference
-    pub fn difference_iter<'a>(&'a self, other: &'a HashSet<T>)
-        -> SetAlgebraIter<'a, T> {
-        EnvFilterIterator{iter: self.iter(), env: other,
-                          filter: |elt, other| !other.contains(elt) }
+    pub fn difference_iter<'a>(&'a self, other: &'a HashSet<T>) -> SetAlgebraIter<'a, T> {
+        Repeat::new(other)
+            .zip(self.iter())
+            .filter_map(|(other, elt)| {
+                if !other.contains(elt) { Some(elt) } else { None }
+            })
     }
 
     /// Visit the values representing the symmetric difference
@@ -727,8 +730,11 @@ pub fn symmetric_difference_iter<'a>(&'a self, other: &'a HashSet<T>)
     /// Visit the values representing the intersection
     pub fn intersection_iter<'a>(&'a self, other: &'a HashSet<T>)
         -> SetAlgebraIter<'a, T> {
-        EnvFilterIterator{iter: self.iter(), env: other,
-                          filter: |elt, other| other.contains(elt) }
+        Repeat::new(other)
+            .zip(self.iter())
+            .filter_map(|(other, elt)| {
+                if other.contains(elt) { Some(elt) } else { None }
+            })
     }
 
     /// Visit the values representing the union
@@ -756,38 +762,12 @@ fn extend(&mut self, iter: &mut T) {
     }
 }
 
-// FIXME #7814: use std::iterator::FilterIterator
-/// Building block for Set operation iterators
-pub struct EnvFilterIterator<A, Env, I> {
-    priv env: Env,
-    priv filter: &'static fn(&A, Env) -> bool,
-    priv iter: I,
-}
-
-impl<'self, A, Env: Clone, I: Iterator<&'self A>> Iterator<&'self A>
-        for EnvFilterIterator<A, Env, I> {
-    #[inline]
-    fn next(&mut self) -> Option<&'self A> {
-        loop {
-            match self.iter.next() {
-                Some(elt) => if (self.filter)(elt, self.env.clone()) {
-                    return Some(elt)
-                },
-                None => return None,
-            }
-        }
-    }
-
-    #[inline]
-    fn size_hint(&self) -> (uint, Option<uint>) {
-        let (_, upper) = self.iter.size_hint();
-        (0, upper)
-    }
-}
-
+// `Repeat` is used to feed the filter closure an explicit capture
+// of a reference to the other set
 /// Set operations iterator
 pub type SetAlgebraIter<'self, T> =
-    EnvFilterIterator<T, &'self HashSet<T>, HashSetIterator<'self, T>>;
+    FilterMap<'static,(&'self HashSet<T>, &'self T), &'self T,
+              Zip<Repeat<&'self HashSet<T>>,HashSetIterator<'self,T>>>;
 
 
 #[cfg(test)]
index f750f3f3195e7157901ea67316de27da945b8352..55e60f03ea9c694f6126780a90ee3f951e0e69e4 100644 (file)
@@ -1041,7 +1041,7 @@ pub fn stdin() -> @Reader {
 
 pub fn file_reader(path: &Path) -> Result<@Reader, ~str> {
     let f = do path.to_str().as_c_str |pathbuf| {
-        do "r".as_c_str |modebuf| {
+        do "rb".as_c_str |modebuf| {
             unsafe { libc::fopen(pathbuf, modebuf as *libc::c_char) }
         }
     };
index 0769aa6a7646478303936748307dc2ab682038fe..56a0dca56679ccf3a34d89038944614d0c497263 100644 (file)
@@ -82,6 +82,17 @@ pub trait DoubleEndedIteratorUtil {
 /// In the future these will be default methods instead of a utility trait.
 impl<A, T: DoubleEndedIterator<A>> DoubleEndedIteratorUtil for T {
     /// Flip the direction of the iterator
+    ///
+    /// The inverted iterator flips the ends on an iterator that can already
+    /// be iterated from the front and from the back.
+    ///
+    ///
+    /// If the iterator also implements RandomAccessIterator, the inverted
+    /// iterator is also random access, with the indices starting at the back
+    /// of the original iterator.
+    ///
+    /// Note: Random access with inverted indices still only applies to the first
+    /// `uint::max_value` elements of the original iterator.
     #[inline]
     fn invert(self) -> Invert<T> {
         Invert{iter: self}
@@ -106,6 +117,16 @@ impl<A, T: DoubleEndedIterator<A>> DoubleEndedIterator<A> for Invert<T> {
     fn next_back(&mut self) -> Option<A> { self.iter.next() }
 }
 
+impl<A, T: DoubleEndedIterator<A> + RandomAccessIterator<A>> RandomAccessIterator<A>
+    for Invert<T> {
+    #[inline]
+    fn indexable(&self) -> uint { self.iter.indexable() }
+    #[inline]
+    fn idx(&self, index: uint) -> Option<A> {
+        self.iter.idx(self.indexable() - index - 1)
+    }
+}
+
 /// Iterator adaptors provided for every `Iterator` implementation. The adaptor objects are also
 /// implementations of the `Iterator` trait.
 ///
@@ -1555,6 +1576,39 @@ fn size_hint(&self) -> (uint, Option<uint>) {
     }
 }
 
+/// An iterator that repeats an element endlessly
+#[deriving(Clone, DeepClone)]
+pub struct Repeat<A> {
+    priv element: A
+}
+
+impl<A: Clone> Repeat<A> {
+    /// Create a new `Repeat` that enlessly repeats the element `elt`.
+    #[inline]
+    pub fn new(elt: A) -> Repeat<A> {
+        Repeat{element: elt}
+    }
+}
+
+impl<A: Clone> Iterator<A> for Repeat<A> {
+    #[inline]
+    fn next(&mut self) -> Option<A> { self.idx(0) }
+    #[inline]
+    fn size_hint(&self) -> (uint, Option<uint>) { (uint::max_value, None) }
+}
+
+impl<A: Clone> DoubleEndedIterator<A> for Repeat<A> {
+    #[inline]
+    fn next_back(&mut self) -> Option<A> { self.idx(0) }
+}
+
+impl<A: Clone> RandomAccessIterator<A> for Repeat<A> {
+    #[inline]
+    fn indexable(&self) -> uint { uint::max_value }
+    #[inline]
+    fn idx(&self, _: uint) -> Option<A> { Some(self.element.clone()) }
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -2017,6 +2071,17 @@ fn test_random_access_enumerate() {
         check_randacc_iter(xs.iter().enumerate(), xs.len());
     }
 
+    #[test]
+    fn test_random_access_invert() {
+        let xs = [1, 2, 3, 4, 5];
+        check_randacc_iter(xs.iter().invert(), xs.len());
+        let mut it = xs.iter().invert();
+        it.next();
+        it.next_back();
+        it.next();
+        check_randacc_iter(it, xs.len() - 3);
+    }
+
     #[test]
     fn test_random_access_zip() {
         let xs = [1, 2, 3, 4, 5];
index 537289c8dd6c2f9bded558498515d9c393e3b2b9..c2a60e1c0e9c01891dd97a56a2abb09c80bf06d2 100644 (file)
@@ -112,14 +112,14 @@ fn test_tls_multitask() {
         // TLS shouldn't carry over.
         assert!(get(my_key, |k| k.map(|&k| *k)).is_none());
         set(my_key, @~"child data");
-        assert!(*(get(my_key, |k| k.map(|&k| *k)).get()) ==
+        assert!(*(get(my_key, |k| k.map(|&k| *k)).unwrap()) ==
                 ~"child data");
         // should be cleaned up for us
     }
     // Must work multiple times
-    assert!(*(get(my_key, |k| k.map(|&k| *k)).get()) == ~"parent data");
-    assert!(*(get(my_key, |k| k.map(|&k| *k)).get()) == ~"parent data");
-    assert!(*(get(my_key, |k| k.map(|&k| *k)).get()) == ~"parent data");
+    assert!(*(get(my_key, |k| k.map(|&k| *k)).unwrap()) == ~"parent data");
+    assert!(*(get(my_key, |k| k.map(|&k| *k)).unwrap()) == ~"parent data");
+    assert!(*(get(my_key, |k| k.map(|&k| *k)).unwrap()) == ~"parent data");
 }
 
 #[test]
@@ -127,14 +127,14 @@ fn test_tls_overwrite() {
     static my_key: Key<@~str> = &Key;
     set(my_key, @~"first data");
     set(my_key, @~"next data"); // Shouldn't leak.
-    assert!(*(get(my_key, |k| k.map(|&k| *k)).get()) == ~"next data");
+    assert!(*(get(my_key, |k| k.map(|&k| *k)).unwrap()) == ~"next data");
 }
 
 #[test]
 fn test_tls_pop() {
     static my_key: Key<@~str> = &Key;
     set(my_key, @~"weasel");
-    assert!(*(pop(my_key).get()) == ~"weasel");
+    assert!(*(pop(my_key).unwrap()) == ~"weasel");
     // Pop must remove the data from the map.
     assert!(pop(my_key).is_none());
 }
@@ -155,7 +155,7 @@ fn test_tls_modify() {
             None                 => fail!("missing value")
         }
     });
-    assert!(*(pop(my_key).get()) == ~"next data");
+    assert!(*(pop(my_key).unwrap()) == ~"next data");
 }
 
 #[test]
index 722af828d5c115a5e08784f2da9593772cde3913..7ab3c81b61f7abd4e134e8f66ecafbff0187bf26 100644 (file)
@@ -726,4 +726,4 @@ fn float_to_str_rand(bh: &mut BenchHarness) {
             float::to_str(rng.gen());
         }
     }
-}
\ No newline at end of file
+}
index 275a72d6ecc051089a58c182dd099fd87e578769..86bc98e53fcb6605cca989137c733653f47326df 100644 (file)
@@ -70,30 +70,6 @@ pub fn div_round(x: uint, y: uint) -> uint {
 ///
 pub fn div_floor(x: uint, y: uint) -> uint { return x / y; }
 
-///
-/// Iterate over the range [`lo`..`hi`), or stop when requested
-///
-/// # Arguments
-///
-/// * lo - The integer at which to start the loop (included)
-/// * hi - The integer at which to stop the loop (excluded)
-/// * it - A block to execute with each consecutive integer of the range.
-///        Return `true` to continue, `false` to stop.
-///
-/// # Return value
-///
-/// `true` If execution proceeded correctly, `false` if it was interrupted,
-/// that is if `it` returned `false` at any point.
-///
-pub fn iterate(lo: uint, hi: uint, it: &fn(uint) -> bool) -> bool {
-    let mut i = lo;
-    while i < hi {
-        if (!it(i)) { return false; }
-        i += 1u;
-    }
-    return true;
-}
-
 impl iter::Times for uint {
     #[inline]
     ///
index 417251d3740e6575016d0ae9934eca1d69553ca1..ea1bddcdb4b9d60aba0138494219519e120d5317 100644 (file)
@@ -47,7 +47,8 @@
 use util;
 use num::Zero;
 use iterator::Iterator;
-use str::StrSlice;
+use str::{StrSlice, OwnedStr};
+use to_str::ToStr;
 use clone::DeepClone;
 
 /// The option type
@@ -85,22 +86,37 @@ fn gt(&self, other: &Option<T>) -> bool {
     }
 }
 
-impl<T:Clone+Add<T,T>> Add<Option<T>, Option<T>> for Option<T> {
+impl<T: Add<T, T>> Add<Option<T>, Option<T>> for Option<T> {
     #[inline]
     fn add(&self, other: &Option<T>) -> Option<T> {
         match (&*self, &*other) {
             (&None, &None) => None,
-            (_, &None) => (*self).clone(),
-            (&None, _) => (*other).clone(),
+            (_, &None) => None,
+            (&None, _) => None,
             (&Some(ref lhs), &Some(ref rhs)) => Some(*lhs + *rhs)
         }
     }
 }
 
+// FIXME: #8242 implementing manually because deriving doesn't work for some reason
+impl<T: ToStr> ToStr for Option<T> {
+    fn to_str(&self) -> ~str {
+        match *self {
+            Some(ref x) => {
+                let mut s = ~"Some(";
+                s.push_str(x.to_str());
+                s.push_str(")");
+                s
+            }
+            None => ~"None"
+        }
+    }
+}
+
 impl<T> Option<T> {
     /// Return an iterator over the possibly contained value
     #[inline]
-    pub fn iter<'r>(&'r self) -> OptionIterator<'r, T> {
+    pub fn iter<'r>(&'r self) -> OptionIterator<&'r T> {
         match *self {
             Some(ref x) => OptionIterator{opt: Some(x)},
             None => OptionIterator{opt: None}
@@ -109,13 +125,19 @@ pub fn iter<'r>(&'r self) -> OptionIterator<'r, T> {
 
     /// Return a mutable iterator over the possibly contained value
     #[inline]
-    pub fn mut_iter<'r>(&'r mut self) -> OptionMutIterator<'r, T> {
+    pub fn mut_iter<'r>(&'r mut self) -> OptionIterator<&'r mut T> {
         match *self {
-            Some(ref mut x) => OptionMutIterator{opt: Some(x)},
-            None => OptionMutIterator{opt: None}
+            Some(ref mut x) => OptionIterator{opt: Some(x)},
+            None => OptionIterator{opt: None}
         }
     }
 
+    /// Return a consuming iterator over the possibly contained value
+    #[inline]
+    pub fn consume(self) -> OptionIterator<T> {
+        OptionIterator{opt: self}
+    }
+
     /// Returns true if the option equals `None`
     #[inline]
     pub fn is_none(&self) -> bool {
@@ -148,8 +170,7 @@ pub fn or(self, optb: Option<T>) -> Option<T> {
     /// Update an optional value by optionally running its content by reference
     /// through a function that returns an option.
     #[inline]
-    pub fn chain_ref<'a, U>(&'a self, f: &fn(x: &'a T) -> Option<U>)
-                            -> Option<U> {
+    pub fn chain_ref<'a, U>(&'a self, f: &fn(x: &'a T) -> Option<U>) -> Option<U> {
         match *self {
             Some(ref x) => f(x),
             None => None
@@ -159,8 +180,7 @@ pub fn chain_ref<'a, U>(&'a self, f: &fn(x: &'a T) -> Option<U>)
     /// Update an optional value by optionally running its content by mut reference
     /// through a function that returns an option.
     #[inline]
-    pub fn chain_mut_ref<'a, U>(&'a mut self, f: &fn(x: &'a mut T) -> Option<U>)
-                                -> Option<U> {
+    pub fn chain_mut_ref<'a, U>(&'a mut self, f: &fn(x: &'a mut T) -> Option<U>) -> Option<U> {
         match *self {
             Some(ref mut x) => f(x),
             None => None
@@ -256,132 +276,105 @@ pub fn mutate_default(&mut self, def: T, f: &fn(T) -> T) -> bool {
         }
     }
 
-    /**
-    Gets an immutable reference to the value inside an option.
-
-    # Failure
-
-    Fails if the value equals `None`
-
-    # Safety note
-
-    In general, because this function may fail, its use is discouraged
-    (calling `get` on `None` is akin to dereferencing a null pointer).
-    Instead, prefer to use pattern matching and handle the `None`
-    case explicitly.
-     */
+    /// Gets an immutable reference to the value inside an option.
+    ///
+    /// # Failure
+    ///
+    /// Fails if the value equals `None`
+    ///
+    /// # Safety note
+    ///
+    /// In general, because this function may fail, its use is discouraged
+    /// (calling `get` on `None` is akin to dereferencing a null pointer).
+    /// Instead, prefer to use pattern matching and handle the `None`
+    /// case explicitly.
     #[inline]
     pub fn get_ref<'a>(&'a self) -> &'a T {
         match *self {
-          Some(ref x) => x,
-          None => fail!("option::get_ref `None`"),
+            Some(ref x) => x,
+            None => fail!("called `Option::get_ref()` on a `None` value"),
         }
     }
 
-    /**
-    Gets a mutable reference to the value inside an option.
-
-    # Failure
-
-    Fails if the value equals `None`
-
-    # Safety note
-
-    In general, because this function may fail, its use is discouraged
-    (calling `get` on `None` is akin to dereferencing a null pointer).
-    Instead, prefer to use pattern matching and handle the `None`
-    case explicitly.
-     */
+    /// Gets a mutable reference to the value inside an option.
+    ///
+    /// # Failure
+    ///
+    /// Fails if the value equals `None`
+    ///
+    /// # Safety note
+    ///
+    /// In general, because this function may fail, its use is discouraged
+    /// (calling `get` on `None` is akin to dereferencing a null pointer).
+    /// Instead, prefer to use pattern matching and handle the `None`
+    /// case explicitly.
     #[inline]
     pub fn get_mut_ref<'a>(&'a mut self) -> &'a mut T {
         match *self {
-          Some(ref mut x) => x,
-          None => fail!("option::get_mut_ref `None`"),
+            Some(ref mut x) => x,
+            None => fail!("called `Option::get_mut_ref()` on a `None` value"),
         }
     }
 
+    /// Moves a value out of an option type and returns it.
+    ///
+    /// Useful primarily for getting strings, vectors and unique pointers out
+    /// of option types without copying them.
+    ///
+    /// # Failure
+    ///
+    /// Fails if the value equals `None`.
+    ///
+    /// # Safety note
+    ///
+    /// In general, because this function may fail, its use is discouraged.
+    /// Instead, prefer to use pattern matching and handle the `None`
+    /// case explicitly.
     #[inline]
     pub fn unwrap(self) -> T {
-        /*!
-        Moves a value out of an option type and returns it.
-
-        Useful primarily for getting strings, vectors and unique pointers out
-        of option types without copying them.
-
-        # Failure
-
-        Fails if the value equals `None`.
-
-        # Safety note
-
-        In general, because this function may fail, its use is discouraged.
-        Instead, prefer to use pattern matching and handle the `None`
-        case explicitly.
-         */
         match self {
-          Some(x) => x,
-          None => fail!("option::unwrap `None`"),
+            Some(x) => x,
+            None => fail!("called `Option::unwrap()` on a `None` value"),
         }
     }
 
-    /**
-     * The option dance. Moves a value out of an option type and returns it,
-     * replacing the original with `None`.
-     *
-     * # Failure
-     *
-     * Fails if the value equals `None`.
-     */
+    /// The option dance. Moves a value out of an option type and returns it,
+    /// replacing the original with `None`.
+    ///
+    /// # Failure
+    ///
+    /// Fails if the value equals `None`.
     #[inline]
     pub fn take_unwrap(&mut self) -> T {
-        if self.is_none() { fail!("option::take_unwrap `None`") }
+        if self.is_none() {
+            fail!("called `Option::take_unwrap()` on a `None` value")
+        }
         self.take().unwrap()
     }
 
-    /**
-     * Gets the value out of an option, printing a specified message on
-     * failure
-     *
-     * # Failure
-     *
-     * Fails if the value equals `None`
-     */
+    ///  Gets the value out of an option, printing a specified message on
+    ///  failure
+    ///
+    ///  # Failure
+    ///
+    ///  Fails if the value equals `None`
     #[inline]
     pub fn expect(self, reason: &str) -> T {
         match self {
-          Some(val) => val,
-          None => fail!(reason.to_owned()),
+            Some(val) => val,
+            None => fail!(reason.to_owned()),
         }
     }
 
-    /**
-    Gets the value out of an option
-
-    # Failure
-
-    Fails if the value equals `None`
-
-    # Safety note
-
-    In general, because this function may fail, its use is discouraged
-    (calling `get` on `None` is akin to dereferencing a null pointer).
-    Instead, prefer to use pattern matching and handle the `None`
-    case explicitly.
-    */
+    /// Returns the contained value or a default
     #[inline]
-    pub fn get(self) -> T {
+    pub fn unwrap_or_default(self, def: T) -> T {
         match self {
-          Some(x) => return x,
-          None => fail!("option::get `None`")
+            Some(x) => x,
+            None => def
         }
     }
 
-    /// Returns the contained value or a default
-    #[inline]
-    pub fn get_or_default(self, def: T) -> T {
-        match self { Some(x) => x, None => def }
-    }
-
     /// Applies a function zero or more times until the result is `None`.
     #[inline]
     pub fn while_some(self, blk: &fn(v: T) -> Option<T>) {
@@ -395,12 +388,21 @@ pub fn while_some(self, blk: &fn(v: T) -> Option<T>) {
 impl<T:Zero> Option<T> {
     /// Returns the contained value or zero (for this type)
     #[inline]
-    pub fn get_or_zero(self) -> T {
+    pub fn unwrap_or_zero(self) -> T {
         match self {
             Some(x) => x,
             None => Zero::zero()
         }
     }
+
+    /// Returns self or `Some(zero)` (for this type)
+    #[inline]
+    pub fn or_zero(self) -> Option<T> {
+        match self {
+            None => Some(Zero::zero()),
+            x => x
+        }
+    }
 }
 
 impl<T> Zero for Option<T> {
@@ -408,34 +410,18 @@ fn zero() -> Option<T> { None }
     fn is_zero(&self) -> bool { self.is_none() }
 }
 
-/// Immutable iterator over an `Option<A>`
-pub struct OptionIterator<'self, A> {
-    priv opt: Option<&'self A>
+/// An iterator that yields either one or zero elements
+pub struct OptionIterator<A> {
+    priv opt: Option<A>
 }
 
-impl<'self, A> Iterator<&'self A> for OptionIterator<'self, A> {
-    fn next(&mut self) -> Option<&'self A> {
-        util::replace(&mut self.opt, None)
-    }
-
-    fn size_hint(&self) -> (uint, Option<uint>) {
-        match self.opt {
-            Some(_) => (1, Some(1)),
-            None => (0, Some(0)),
-        }
-    }
-}
-
-/// Mutable iterator over an `Option<A>`
-pub struct OptionMutIterator<'self, A> {
-    priv opt: Option<&'self mut A>
-}
-
-impl<'self, A> Iterator<&'self mut A> for OptionMutIterator<'self, A> {
-    fn next(&mut self) -> Option<&'self mut A> {
-        util::replace(&mut self.opt, None)
+impl<A> Iterator<A> for OptionIterator<A> {
+    #[inline]
+    fn next(&mut self) -> Option<A> {
+        self.opt.take()
     }
 
+    #[inline]
     fn size_hint(&self) -> (uint, Option<uint>) {
         match self.opt {
             Some(_) => (1, Some(1)),
@@ -450,7 +436,7 @@ mod tests {
     use util;
 
     #[test]
-    fn test_unwrap_ptr() {
+    fn test_get_ptr() {
         unsafe {
             let x = ~0;
             let addr_x: *int = ::cast::transmute(&*x);
@@ -462,7 +448,7 @@ fn test_unwrap_ptr() {
     }
 
     #[test]
-    fn test_unwrap_str() {
+    fn test_get_str() {
         let x = ~"test";
         let addr_x = x.as_imm_buf(|buf, _len| buf);
         let opt = Some(x);
@@ -472,7 +458,7 @@ fn test_unwrap_str() {
     }
 
     #[test]
-    fn test_unwrap_resource() {
+    fn test_get_resource() {
         struct R {
            i: @mut int,
         }
@@ -530,18 +516,18 @@ fn test_option_while_some() {
     }
 
     #[test]
-    fn test_get_or_zero() {
+    fn test_unwrap_or_zero() {
         let some_stuff = Some(42);
-        assert_eq!(some_stuff.get_or_zero(), 42);
+        assert_eq!(some_stuff.unwrap_or_zero(), 42);
         let no_stuff: Option<int> = None;
-        assert_eq!(no_stuff.get_or_zero(), 0);
+        assert_eq!(no_stuff.unwrap_or_zero(), 0);
     }
 
     #[test]
     fn test_filtered() {
         let some_stuff = Some(42);
         let modified_stuff = some_stuff.filtered(|&x| {x < 10});
-        assert_eq!(some_stuff.get(), 42);
+        assert_eq!(some_stuff.unwrap(), 42);
         assert!(modified_stuff.is_none());
     }
 
index 2d0b7d4f849d7be254a0ece13fc60100ef12a548..b0e1f35b4a018a6c8237b29b7ca4b06c15741306 100644 (file)
@@ -571,7 +571,7 @@ fn getenv_nonempty(v: &str) -> Option<Path> {
 
     #[cfg(unix)]
     fn lookup() -> Path {
-        getenv_nonempty("TMPDIR").get_or_default(Path("/tmp"))
+        getenv_nonempty("TMPDIR").unwrap_or_default(Path("/tmp"))
     }
 
     #[cfg(windows)]
@@ -579,7 +579,7 @@ fn lookup() -> Path {
         getenv_nonempty("TMP").or(
             getenv_nonempty("TEMP").or(
                 getenv_nonempty("USERPROFILE").or(
-                   getenv_nonempty("WINDIR")))).get_or_default(Path("C:\\Windows"))
+                   getenv_nonempty("WINDIR")))).unwrap_or_default(Path("C:\\Windows"))
     }
 }
 
@@ -1782,7 +1782,7 @@ fn test_getenv_big() {
     fn test_self_exe_path() {
         let path = os::self_exe_path();
         assert!(path.is_some());
-        let path = path.get();
+        let path = path.unwrap();
         debug!(path.clone());
 
         // Hard to test this function
index 55c18faf83deeb5a9eed4044d551907ccfa36fe3..dfd11f9227d413e5b37725b91a34e54d024f3eea 100644 (file)
@@ -12,6 +12,7 @@
 
 use cast;
 use clone::Clone;
+use iterator::{range, Iterator};
 use option::{Option, Some, None};
 use unstable::intrinsics;
 use util::swap;
@@ -20,7 +21,6 @@
 #[cfg(not(test))] use num::Int;
 
 #[cfg(not(test))] use cmp::{Eq, Ord};
-use uint;
 
 /// Calculate the offset from a pointer
 #[inline]
@@ -240,11 +240,10 @@ pub unsafe fn array_each_with_len<T>(arr: **T, len: uint, cb: &fn(*T)) {
         fail!("ptr::array_each_with_len failure: arr input is null pointer");
     }
     //let start_ptr = *arr;
-    uint::iterate(0, len, |e| {
+    for e in range(0, len) {
         let n = offset(arr, e as int);
         cb(*n);
-        true
-    });
+    }
     debug!("array_each_with_len: after iterate");
 }
 
index b7d72c11ff7a888a564376f09df1f3473c1e2ba7..4ef524d77152bb224021d3ef7dc3b8a8e253906c 100644 (file)
@@ -533,7 +533,7 @@ fn gen_bytes(&mut self, len: uint) -> ~[u8] {
 
     /// Choose an item randomly, failing if values is empty
     fn choose<T:Clone>(&mut self, values: &[T]) -> T {
-        self.choose_option(values).get()
+        self.choose_option(values).unwrap()
     }
 
     /// Choose Some(item) randomly, returning None if values is empty
@@ -549,7 +549,7 @@ fn choose_option<T:Clone>(&mut self, values: &[T]) -> Option<T> {
      * the weights is 0
      */
     fn choose_weighted<T:Clone>(&mut self, v: &[Weighted<T>]) -> T {
-        self.choose_weighted_option(v).get()
+        self.choose_weighted_option(v).unwrap()
     }
 
     /**
index 7a578465841bba26920f521dcd805320cd054450..91f42edf0aecd46e33efafc41fa7fccf43032be4 100644 (file)
 use cmp::Eq;
 use either;
 use iterator::Iterator;
-use option::{None, Option, Some};
+use option::{None, Option, Some, OptionIterator};
 use vec;
 use vec::{OwnedVector, ImmutableVector};
 use container::Container;
-
-/// The result type
+use to_str::ToStr;
+use str::StrSlice;
+
+/// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
+///
+/// In order to provide informative error messages, `E` is reqired to implement `ToStr`.
+/// It is further recommended for `E` to be a descriptive error type, eg a `enum` for
+/// all possible errors cases.
 #[deriving(Clone, Eq)]
-pub enum Result<T, U> {
+pub enum Result<T, E> {
     /// Contains the successful result value
     Ok(T),
     /// Contains the error value
-    Err(U)
+    Err(E)
 }
 
-impl<T, E> Result<T, E> {
-    /**
-     * Convert to the `either` type
-     *
-     * `Ok` result variants are converted to `either::Right` variants, `Err`
-     * result variants are converted to `either::Left`.
-     */
+impl<T, E: ToStr> Result<T, E> {
+    /// Convert to the `either` type
+    ///
+    /// `Ok` result variants are converted to `either::Right` variants, `Err`
+    /// result variants are converted to `either::Left`.
     #[inline]
     pub fn to_either(self)-> either::Either<E, T>{
         match self {
@@ -45,18 +49,16 @@ pub fn to_either(self)-> either::Either<E, T>{
         }
     }
 
-    /**
-     * Get a reference to the value out of a successful result
-     *
-     * # Failure
-     *
-     * If the result is an error
-     */
+    /// Get a reference to the value out of a successful result
+    ///
+    /// # Failure
+    ///
+    /// If the result is an error
     #[inline]
     pub fn get_ref<'a>(&'a self) -> &'a T {
         match *self {
             Ok(ref t) => t,
-            Err(ref e) => fail!("get_ref called on `Err` result: %?", *e),
+            Err(ref e) => fail!("called `Result::get_ref()` on `Err` value: %s", e.to_str()),
         }
     }
 
@@ -75,76 +77,90 @@ pub fn is_err(&self) -> bool {
         !self.is_ok()
     }
 
-    /**
-     * Call a method based on a previous result
-     *
-     * If `self` is `Ok` then the value is extracted and passed to `op`
-     * whereupon `op`s result is returned. if `self` is `Err` then it is
-     * immediately returned. This function can be used to compose the results
-     * of two functions.
-     *
-     * Example:
-     *
-     *     do read_file(file).iter |buf| {
-     *         print_buf(buf)
-     *     }
-     */
+    /// Call a method based on a previous result
+    ///
+    /// If `self` is `Ok` then the value is extracted and passed to `op`
+    /// whereupon `op`s result is returned. if `self` is `Err` then it is
+    /// immediately returned. This function can be used to compose the results
+    /// of two functions.
+    ///
+    /// Example:
+    ///
+    ///     for buf in read_file(file) {
+    ///         print_buf(buf)
+    ///     }
     #[inline]
-    pub fn iter(&self, f: &fn(&T)) {
+    pub fn iter<'r>(&'r self) -> OptionIterator<&'r T> {
         match *self {
-            Ok(ref t) => f(t),
-            Err(_) => (),
-        }
+            Ok(ref t) => Some(t),
+            Err(*) => None,
+        }.consume()
     }
 
-    /**
-     * Call a method based on a previous result
-     *
-     * If `self` is `Err` then the value is extracted and passed to `op`
-     * whereupon `op`s result is returned. if `self` is `Ok` then it is
-     * immediately returned.  This function can be used to pass through a
-     * successful result while handling an error.
-     */
+    /// Call a method based on a previous result
+    ///
+    /// If `self` is `Err` then the value is extracted and passed to `op`
+    /// whereupon `op`s result is returned. if `self` is `Ok` then it is
+    /// immediately returned.  This function can be used to pass through a
+    /// successful result while handling an error.
     #[inline]
-    pub fn iter_err(&self, f: &fn(&E)) {
+    pub fn iter_err<'r>(&'r self) -> OptionIterator<&'r E> {
         match *self {
-            Ok(_) => (),
-            Err(ref e) => f(e),
-        }
+            Ok(*) => None,
+            Err(ref t) => Some(t),
+        }.consume()
     }
 
-    /// Unwraps a result, assuming it is an `Ok(T)`
+    /// Unwraps a result, yielding the content of an `Ok`.
+    /// Fails if the value is a `Err` with an error message derived
+    /// from `E`'s `ToStr` implementation.
     #[inline]
     pub fn unwrap(self) -> T {
         match self {
             Ok(t) => t,
-            Err(_) => fail!("unwrap called on an `Err` result"),
+            Err(e) => fail!("called `Result::unwrap()` on `Err` value: %s", e.to_str()),
         }
     }
 
-    /// Unwraps a result, assuming it is an `Err(U)`
+    /// Unwraps a result, yielding the content of an `Err`.
+    /// Fails if the value is a `Ok`.
     #[inline]
     pub fn unwrap_err(self) -> E {
+        self.expect_err("called `Result::unwrap_err()` on `Ok` value")
+    }
+
+    /// Unwraps a result, yielding the content of an `Ok`.
+    /// Fails if the value is a `Err` with a custom failure message.
+    #[inline]
+    pub fn expect(self, reason: &str) -> T {
+        match self {
+            Ok(t) => t,
+            Err(_) => fail!(reason.to_owned()),
+        }
+    }
+
+    /// Unwraps a result, yielding the content of an `Err`
+    /// Fails if the value is a `Ok` with a custom failure message.
+    #[inline]
+    pub fn expect_err(self, reason: &str) -> E {
         match self {
             Err(e) => e,
-            Ok(_) => fail!("unwrap called on an `Ok` result"),
+            Ok(_) => fail!(reason.to_owned()),
         }
     }
 
-    /**
-     * Call a method based on a previous result
-     *
-     * If `self` is `Ok` then the value is extracted and passed to `op`
-     * whereupon `op`s result is returned. if `self` is `Err` then it is
-     * immediately returned. This function can be used to compose the results
-     * of two functions.
-     *
-     * Example:
-     *
-     *     let res = do read_file(file) |buf| {
-     *         Ok(parse_bytes(buf))
-     *     };
-     */
+    /// Call a method based on a previous result
+    ///
+    /// If `self` is `Ok` then the value is extracted and passed to `op`
+    /// whereupon `op`s result is returned. if `self` is `Err` then it is
+    /// immediately returned. This function can be used to compose the results
+    /// of two functions.
+    ///
+    /// Example:
+    ///
+    ///     let res = do read_file(file) |buf| {
+    ///         Ok(parse_bytes(buf))
+    ///     };
     #[inline]
     pub fn chain<U>(self, op: &fn(T) -> Result<U, E>) -> Result<U, E> {
         match self {
@@ -153,14 +169,12 @@ pub fn chain<U>(self, op: &fn(T) -> Result<U, E>) -> Result<U, E> {
         }
     }
 
-    /**
-     * Call a function based on a previous result
-     *
-     * If `self` is `Err` then the value is extracted and passed to `op`
-     * whereupon `op`s result is returned. if `self` is `Ok` then it is
-     * immediately returned.  This function can be used to pass through a
-     * successful result while handling an error.
-     */
+    /// Call a function based on a previous result
+    ///
+    /// If `self` is `Err` then the value is extracted and passed to `op`
+    /// whereupon `op`s result is returned. if `self` is `Ok` then it is
+    /// immediately returned.  This function can be used to pass through a
+    /// successful result while handling an error.
     #[inline]
     pub fn chain_err<F>(self, op: &fn(E) -> Result<T, F>) -> Result<T, F> {
         match self {
@@ -170,32 +184,15 @@ pub fn chain_err<F>(self, op: &fn(E) -> Result<T, F>) -> Result<T, F> {
     }
 }
 
-impl<T: Clone, E> Result<T, E> {
-    /**
-     * Get the value out of a successful result
-     *
-     * # Failure
-     *
-     * If the result is an error
-     */
-    #[inline]
-    pub fn get(&self) -> T {
-        match *self {
-            Ok(ref t) => t.clone(),
-            Err(ref e) => fail!("get called on `Err` result: %?", *e),
-        }
-    }
-
-    /**
-     * Call a method based on a previous result
-     *
-     * If `self` is `Err` then the value is extracted and passed to `op`
-     * whereupon `op`s result is wrapped in an `Err` and returned. if `self` is
-     * `Ok` then it is immediately returned.  This function can be used to pass
-     * through a successful result while handling an error.
-     */
+impl<T: Clone, E: ToStr> Result<T, E> {
+    /// Call a method based on a previous result
+    ///
+    /// If `self` is `Err` then the value is extracted and passed to `op`
+    /// whereupon `op`s result is wrapped in an `Err` and returned. if `self` is
+    /// `Ok` then it is immediately returned.  This function can be used to pass
+    /// through a successful result while handling an error.
     #[inline]
-    pub fn map_err<F:Clone>(&self, op: &fn(&E) -> F) -> Result<T,F> {
+    pub fn map_err<F: Clone>(&self, op: &fn(&E) -> F) -> Result<T,F> {
         match *self {
             Ok(ref t) => Ok(t.clone()),
             Err(ref e) => Err(op(e))
@@ -203,62 +200,57 @@ pub fn map_err<F:Clone>(&self, op: &fn(&E) -> F) -> Result<T,F> {
     }
 }
 
-impl<T, E: Clone> Result<T, E> {
-    /**
-     * Get the value out of an error result
-     *
-     * # Failure
-     *
-     * If the result is not an error
-     */
+impl<T, E: Clone + ToStr> Result<T, E> {
+    /// Call a method based on a previous result
+    ///
+    /// If `self` is `Ok` then the value is extracted and passed to `op`
+    /// whereupon `op`s result is wrapped in `Ok` and returned. if `self` is
+    /// `Err` then it is immediately returned.  This function can be used to
+    /// compose the results of two functions.
+    ///
+    /// Example:
+    ///
+    ///     let res = do read_file(file).map |buf| {
+    ///         parse_bytes(buf)
+    ///     };
     #[inline]
-    pub fn get_err(&self) -> E {
+    pub fn map<U>(&self, op: &fn(&T) -> U) -> Result<U,E> {
         match *self {
-            Err(ref e) => e.clone(),
-            Ok(_) => fail!("get_err called on `Ok` result")
+            Ok(ref t) => Ok(op(t)),
+            Err(ref e) => Err(e.clone())
         }
     }
+}
 
-    /**
-     * Call a method based on a previous result
-     *
-     * If `self` is `Ok` then the value is extracted and passed to `op`
-     * whereupon `op`s result is wrapped in `Ok` and returned. if `self` is
-     * `Err` then it is immediately returned.  This function can be used to
-     * compose the results of two functions.
-     *
-     * Example:
-     *
-     *     let res = do read_file(file).map |buf| {
-     *         parse_bytes(buf)
-     *     };
-     */
-    #[inline]
-    pub fn map<U:Clone>(&self, op: &fn(&T) -> U) -> Result<U,E> {
-        match *self {
-            Ok(ref t) => Ok(op(t)),
-            Err(ref e) => Err(e.clone())
+#[inline]
+#[allow(missing_doc)]
+pub fn map_opt<T, U: ToStr, V>(o_t: &Option<T>,
+                               op: &fn(&T) -> Result<V,U>) -> Result<Option<V>,U> {
+    match *o_t {
+        None => Ok(None),
+        Some(ref t) => match op(t) {
+            Ok(v) => Ok(Some(v)),
+            Err(e) => Err(e)
         }
     }
 }
 
-/**
- * Maps each element in the vector `ts` using the operation `op`.  Should an
- * error occur, no further mappings are performed and the error is returned.
- * Should no error occur, a vector containing the result of each map is
- * returned.
- *
- * Here is an example which increments every integer in a vector,
- * checking for overflow:
- *
- *     fn inc_conditionally(x: uint) -> result<uint,str> {
- *         if x == uint::max_value { return Err("overflow"); }
- *         else { return Ok(x+1u); }
- *     }
- *     map(~[1u, 2u, 3u], inc_conditionally).chain {|incd|
- *         assert!(incd == ~[2u, 3u, 4u]);
- *     }
- */
+// FIXME: #8228 Replaceable by an external iterator?
+/// Maps each element in the vector `ts` using the operation `op`.  Should an
+/// error occur, no further mappings are performed and the error is returned.
+/// Should no error occur, a vector containing the result of each map is
+/// returned.
+///
+/// Here is an example which increments every integer in a vector,
+/// checking for overflow:
+///
+///     fn inc_conditionally(x: uint) -> result<uint,str> {
+///         if x == uint::max_value { return Err("overflow"); }
+///         else { return Ok(x+1u); }
+///     }
+///     map(~[1u, 2u, 3u], inc_conditionally).chain {|incd|
+///         assert!(incd == ~[2u, 3u, 4u]);
+///     }
 #[inline]
 pub fn map_vec<T,U,V>(ts: &[T], op: &fn(&T) -> Result<V,U>)
                       -> Result<~[V],U> {
@@ -272,36 +264,17 @@ pub fn map_vec<T,U,V>(ts: &[T], op: &fn(&T) -> Result<V,U>)
     return Ok(vs);
 }
 
+// FIXME: #8228 Replaceable by an external iterator?
+/// Same as map, but it operates over two parallel vectors.
+///
+/// A precondition is used here to ensure that the vectors are the same
+/// length.  While we do not often use preconditions in the standard
+/// library, a precondition is used here because result::t is generally
+/// used in 'careful' code contexts where it is both appropriate and easy
+/// to accommodate an error like the vectors being of different lengths.
 #[inline]
-#[allow(missing_doc)]
-pub fn map_opt<T,
-               U,
-               V>(
-               o_t: &Option<T>,
-               op: &fn(&T) -> Result<V,U>)
-               -> Result<Option<V>,U> {
-    match *o_t {
-        None => Ok(None),
-        Some(ref t) => match op(t) {
-            Ok(v) => Ok(Some(v)),
-            Err(e) => Err(e)
-        }
-    }
-}
-
-/**
- * Same as map, but it operates over two parallel vectors.
- *
- * A precondition is used here to ensure that the vectors are the same
- * length.  While we do not often use preconditions in the standard
- * library, a precondition is used here because result::t is generally
- * used in 'careful' code contexts where it is both appropriate and easy
- * to accommodate an error like the vectors being of different lengths.
- */
-#[inline]
-pub fn map_vec2<S,T,U,V>(ss: &[S], ts: &[T],
-                op: &fn(&S,&T) -> Result<V,U>) -> Result<~[V],U> {
-
+pub fn map_vec2<S, T, U: ToStr, V>(ss: &[S], ts: &[T],
+                                   op: &fn(&S,&T) -> Result<V,U>) -> Result<~[V],U> {
     assert!(vec::same_length(ss, ts));
     let n = ts.len();
     let mut vs = vec::with_capacity(n);
@@ -316,15 +289,13 @@ pub fn map_vec2<S,T,U,V>(ss: &[S], ts: &[T],
     return Ok(vs);
 }
 
-/**
- * Applies op to the pairwise elements from `ss` and `ts`, aborting on
- * error.  This could be implemented using `map_zip()` but it is more efficient
- * on its own as no result vector is built.
- */
+// FIXME: #8228 Replaceable by an external iterator?
+/// Applies op to the pairwise elements from `ss` and `ts`, aborting on
+/// error.  This could be implemented using `map_zip()` but it is more efficient
+/// on its own as no result vector is built.
 #[inline]
-pub fn iter_vec2<S,T,U>(ss: &[S], ts: &[T],
-                         op: &fn(&S,&T) -> Result<(),U>) -> Result<(),U> {
-
+pub fn iter_vec2<S, T, U: ToStr>(ss: &[S], ts: &[T],
+                                 op: &fn(&S,&T) -> Result<(),U>) -> Result<(),U> {
     assert!(vec::same_length(ss, ts));
     let n = ts.len();
     let mut i = 0u;
@@ -353,32 +324,36 @@ pub fn op3() -> Result<int, ~str> { Err(~"sadface") }
 
     #[test]
     pub fn chain_success() {
-        assert_eq!(op1().chain(op2).get(), 667u);
+        assert_eq!(op1().chain(op2).unwrap(), 667u);
     }
 
     #[test]
     pub fn chain_failure() {
-        assert_eq!(op3().chain( op2).get_err(), ~"sadface");
+        assert_eq!(op3().chain( op2).unwrap_err(), ~"sadface");
     }
 
     #[test]
     pub fn test_impl_iter() {
         let mut valid = false;
-        Ok::<~str, ~str>(~"a").iter(|_x| valid = true);
+        let okval = Ok::<~str, ~str>(~"a");
+        do okval.iter().next().map |_| { valid = true; };
         assert!(valid);
 
-        Err::<~str, ~str>(~"b").iter(|_x| valid = false);
+        let errval = Err::<~str, ~str>(~"b");
+        do errval.iter().next().map |_| { valid = false; };
         assert!(valid);
     }
 
     #[test]
     pub fn test_impl_iter_err() {
         let mut valid = true;
-        Ok::<~str, ~str>(~"a").iter_err(|_x| valid = false);
+        let okval = Ok::<~str, ~str>(~"a");
+        do okval.iter_err().next().map |_| { valid = false };
         assert!(valid);
 
         valid = false;
-        Err::<~str, ~str>(~"b").iter_err(|_x| valid = true);
+        let errval = Err::<~str, ~str>(~"b");
+        do errval.iter_err().next().map |_| { valid = true };
         assert!(valid);
     }
 
index e57b80658eef2ec377a4b561bb06673947a64cbc..bea62f7e28c193a8b3ef1116de78f2bd8ab250c3 100644 (file)
@@ -115,7 +115,7 @@ fn smoke_test() {
         let mem_reader = MemReader::new(buf);
         let mut inflate_reader = InflateReader::new(mem_reader);
         let mut out_bytes = [0, .. 100];
-        let bytes_read = inflate_reader.read(out_bytes).get();
+        let bytes_read = inflate_reader.read(out_bytes).unwrap();
         assert_eq!(bytes_read, in_bytes.len());
         let out_msg = str::from_bytes(out_bytes);
         assert!(in_msg == out_msg);
index 838c2d86c9fa267607df1002b342cd8e33dbf1bf..c980dc9d73efdc6546cf216b0368de4e5eb7e845 100644 (file)
 */
 
 use prelude::*;
+use to_str::ToStr;
+use str::{StrSlice, OwnedStr};
 
 // Reexports
 pub use self::stdio::stdin;
@@ -334,6 +336,20 @@ pub struct IoError {
     detail: Option<~str>
 }
 
+// FIXME: #8242 implementing manually because deriving doesn't work for some reason
+impl ToStr for IoError {
+    fn to_str(&self) -> ~str {
+        let mut s = ~"IoError { kind: ";
+        s.push_str(self.kind.to_str());
+        s.push_str(", desc: ");
+        s.push_str(self.desc);
+        s.push_str(", detail: ");
+        s.push_str(self.detail.to_str());
+        s.push_str(" }");
+        s
+    }
+}
+
 #[deriving(Eq)]
 pub enum IoErrorKind {
     PreviousIoError,
@@ -348,6 +364,24 @@ pub enum IoErrorKind {
     BrokenPipe
 }
 
+// FIXME: #8242 implementing manually because deriving doesn't work for some reason
+impl ToStr for IoErrorKind {
+    fn to_str(&self) -> ~str {
+        match *self {
+            PreviousIoError => ~"PreviousIoError",
+            OtherIoError => ~"OtherIoError",
+            EndOfFile => ~"EndOfFile",
+            FileNotFound => ~"FileNotFound",
+            PermissionDenied => ~"PermissionDenied",
+            ConnectionFailed => ~"ConnectionFailed",
+            Closed => ~"Closed",
+            ConnectionRefused => ~"ConnectionRefused",
+            ConnectionReset => ~"ConnectionReset",
+            BrokenPipe => ~"BrokenPipe"
+        }
+    }
+}
+
 // XXX: Can't put doc comments on macros
 // Raised by `I/O` operations on error.
 condition! {
@@ -505,4 +539,4 @@ pub fn placeholder_error() -> IoError {
         desc: "Placeholder error. You shouldn't be seeing this",
         detail: None
     }
-}
\ No newline at end of file
+}
index 33e83fd9040412936dc0d28db05a3d7709f6e22a..760ca8a9adadcbae741cce4423728ffd6ea3e75e 100644 (file)
@@ -365,7 +365,7 @@ fn run_(main: ~fn(), use_main_sched: bool) -> int {
 
         rtdebug!("about to create the main scheduler task");
 
-        let mut main_sched = main_sched.get();
+        let mut main_sched = main_sched.unwrap();
 
         let home = Sched(main_sched.make_handle());
         let mut main_task = ~Task::new_root_homed(&mut main_sched.stack_pool,
index cb949edd7bb4a76e1ca00e02e12baa9bfd1a8ceb..4c5e4bdc3c1d9b8b984642686428527ec1f40d38 100644 (file)
@@ -465,10 +465,10 @@ fn tls() {
         do run_in_newsched_task() {
             static key: local_data::Key<@~str> = &local_data::Key;
             local_data::set(key, @~"data");
-            assert!(*local_data::get(key, |k| k.map(|&k| *k)).get() == ~"data");
+            assert!(*local_data::get(key, |k| k.map(|&k| *k)).unwrap() == ~"data");
             static key2: local_data::Key<@~str> = &local_data::Key;
             local_data::set(key2, @~"data");
-            assert!(*local_data::get(key2, |k| k.map(|&k| *k)).get() == ~"data");
+            assert!(*local_data::get(key2, |k| k.map(|&k| *k)).unwrap() == ~"data");
         }
     }
 
index 2427da01a0c1c700e966eeaf90843668e25853df..8b5215ae9694aedc4d0549b1c8f184e14d00edb5 100644 (file)
@@ -154,7 +154,7 @@ pub fn run_in_mt_newsched_task(f: ~fn()) {
 
     do run_in_bare_thread {
         let nthreads = match os::getenv("RUST_RT_TEST_THREADS") {
-            Some(nstr) => FromStr::from_str(nstr).get(),
+            Some(nstr) => FromStr::from_str(nstr).unwrap(),
             None => {
                 // Using more threads than cores in test code
                 // to force the OS to preempt them frequently.
@@ -362,7 +362,7 @@ pub fn stress_factor() -> uint {
     use os::getenv;
 
     match getenv("RUST_RT_STRESS") {
-        Some(val) => uint::from_str(val).get(),
+        Some(val) => uint::from_str(val).unwrap(),
         None => 1
     }
 }
index a1169954688b097356aeeefdabd39ce00be43f3e..40e5c8d4bf1a088d7d470e768f35a61c1afd4645 100644 (file)
@@ -31,7 +31,7 @@ pub fn num_cpus() -> uint {
 /// either `RUST_THREADS` or `num_cpus`.
 pub fn default_sched_threads() -> uint {
     match os::getenv("RUST_THREADS") {
-        Some(nstr) => FromStr::from_str(nstr).get(),
+        Some(nstr) => FromStr::from_str(nstr).unwrap(),
         None => num_cpus()
     }
 }
@@ -118,4 +118,4 @@ pub fn get_exit_status() -> int {
     extern {
         fn rust_get_exit_status_newrt() -> libc::uintptr_t;
     }
-}
\ No newline at end of file
+}
index 67d3bbef8a9c6880eb4094b62732f2ca21422a89..fd3042899f6bca5e28dadc366b1ed0e0208ea8d3 100644 (file)
@@ -108,7 +108,7 @@ fn uv_socket_addr_as_socket_addr<T>(addr: UvSocketAddr, f: &fn(SocketAddr) -> T)
                             "" => ~[],
                             // IPv4-Mapped/Compatible IPv6 Address?
                             s if s.find('.').is_some() => {
-                                let i = s.rfind(':').get_or_default(-1);
+                                let i = s.rfind(':').unwrap_or_default(-1);
 
                                 let b = s.slice(i + 1, s.len()); // the ipv4 part
 
@@ -614,7 +614,7 @@ fn connect_close_ip4() {
             do tcp_watcher.connect(addr) |stream_watcher, status| {
                 rtdebug!("tcp_watcher.connect!");
                 assert!(status.is_some());
-                assert_eq!(status.get().name(), ~"ECONNREFUSED");
+                assert_eq!(status.unwrap().name(), ~"ECONNREFUSED");
                 stream_watcher.close(||());
             }
             loop_.run();
@@ -632,7 +632,7 @@ fn connect_close_ip6() {
             do tcp_watcher.connect(addr) |stream_watcher, status| {
                 rtdebug!("tcp_watcher.connect!");
                 assert!(status.is_some());
-                assert_eq!(status.get().name(), ~"ECONNREFUSED");
+                assert_eq!(status.unwrap().name(), ~"ECONNREFUSED");
                 stream_watcher.close(||());
             }
             loop_.run();
index 85cf660a5f1aaded24bd731907a919dc6374ab0e..70a397199ab7ce5b159e82f93f04618ae0a6d47b 100644 (file)
@@ -278,7 +278,7 @@ fn tcp_connect(&mut self, addr: SocketAddr) -> Result<~RtioTcpStreamObject, IoEr
                     rtdebug!("status is some");
                     let task_cell = Cell::new(task_cell.take());
                     do stream_watcher.close {
-                        let res = Err(uv_error_to_io_error(status.get()));
+                        let res = Err(uv_error_to_io_error(status.unwrap()));
                         unsafe { (*result_cell_ptr).put_back(res); }
                         let scheduler = Local::take::<Scheduler>();
                         scheduler.resume_blocked_task_immediately(task_cell.take());
index f1a44c4b386396146ef8ec9c0c5f5803857922f0..b4057b85cbfef5cbfae74b54555c359c3e9f5376 100644 (file)
@@ -58,7 +58,7 @@ pub fn from_bytes(vv: &[u8]) -> ~str {
     use str::not_utf8::cond;
 
     if !is_utf8(vv) {
-        let first_bad_byte = *vv.iter().find_(|&b| !is_utf8([*b])).get();
+        let first_bad_byte = *vv.iter().find_(|&b| !is_utf8([*b])).unwrap();
         cond.raise(fmt!("from_bytes: input is not UTF-8; first bad byte is %u",
                         first_bad_byte as uint))
     } else {
@@ -75,7 +75,7 @@ pub fn from_bytes_owned(vv: ~[u8]) -> ~str {
     use str::not_utf8::cond;
 
     if !is_utf8(vv) {
-        let first_bad_byte = *vv.iter().find_(|&b| !is_utf8([*b])).get();
+        let first_bad_byte = *vv.iter().find_(|&b| !is_utf8([*b])).unwrap();
         cond.raise(fmt!("from_bytes: input is not UTF-8; first bad byte is %u",
                         first_bad_byte as uint))
     } else {
@@ -902,7 +902,7 @@ pub unsafe fn push_byte(s: &mut ~str, b: u8) {
         let new_len = s.len() + 1;
         s.reserve_at_least(new_len);
         do s.as_mut_buf |buf, len| {
-            *ptr::mut_offset(buf, len as int) = b;
+            *ptr::mut_offset(buf, (len-1) as int) = b;
         }
         set_len(&mut *s, new_len);
     }
@@ -2825,6 +2825,13 @@ fn test_is_whitespace() {
         assert!(!"   _   ".is_whitespace());
     }
 
+    #[test]
+    fn test_push_byte() {
+        let mut s = ~"ABC";
+        unsafe{raw::push_byte(&mut s, 'D' as u8)};
+        assert_eq!(s, ~"ABCD");
+    }
+
     #[test]
     fn test_shift_byte() {
         let mut s = ~"ABC";
index f7a943f8d2fdf0c0b4bd961f188fe9e52eb61c62..225a4b8cfd294eacb0fddb4ad2b5058b5dd0edab 100644 (file)
@@ -926,7 +926,7 @@ fn test_named_task() {
         t.name(~"ada lovelace");
         do t.spawn {
             do with_task_name |name| {
-                assert!(name.get() == "ada lovelace");
+                assert!(name.unwrap() == "ada lovelace");
             }
         }
     }
index 679d36b87f18e0c2ea883467d4010dceb9d3fad2..6f61d29780f044307d048aff29d1ae0de826a547 100644 (file)
@@ -14,6 +14,7 @@
 use iterator::{IteratorUtil, FromIterator, Extendable};
 use uint;
 use util::{swap, replace};
+use vec;
 
 // FIXME: #5244: need to manually update the TrieNode constructor
 static SHIFT: uint = 4;
@@ -146,6 +147,15 @@ pub fn each_key_reverse(&self, f: &fn(&uint) -> bool) -> bool {
     pub fn each_value_reverse(&self, f: &fn(&T) -> bool) -> bool {
         self.each_reverse(|_, v| f(v))
     }
+
+    /// Get an iterator over the key-value pairs in the map
+    pub fn iter<'a>(&'a self) -> TrieMapIterator<'a, T> {
+        TrieMapIterator {
+            stack: ~[self.root.children.iter()],
+            remaining_min: self.length,
+            remaining_max: self.length
+        }
+    }
 }
 
 impl<T, Iter: Iterator<(uint, T)>> FromIterator<(uint, T), Iter> for TrieMap<T> {
@@ -217,6 +227,12 @@ pub fn each(&self, f: &fn(&uint) -> bool) -> bool { self.map.each_key(f) }
     pub fn each_reverse(&self, f: &fn(&uint) -> bool) -> bool {
         self.map.each_key_reverse(f)
     }
+
+    /// Get an iterator over the values in the set
+    #[inline]
+    pub fn iter<'a>(&'a self) -> TrieSetIterator<'a> {
+        TrieSetIterator{iter: self.map.iter()}
+    }
 }
 
 impl<Iter: Iterator<uint>> FromIterator<uint, Iter> for TrieSet {
@@ -366,6 +382,61 @@ fn remove<T>(count: &mut uint, child: &mut Child<T>, key: uint,
     return ret;
 }
 
+/// Forward iterator over a map
+pub struct TrieMapIterator<'self, T> {
+    priv stack: ~[vec::VecIterator<'self, Child<T>>],
+    priv remaining_min: uint,
+    priv remaining_max: uint
+}
+
+impl<'self, T> Iterator<(uint, &'self T)> for TrieMapIterator<'self, T> {
+    fn next(&mut self) -> Option<(uint, &'self T)> {
+        while !self.stack.is_empty() {
+            match self.stack[self.stack.len() - 1].next() {
+                None => {
+                    self.stack.pop();
+                }
+                Some(ref child) => {
+                    match **child {
+                        Internal(ref node) => {
+                            self.stack.push(node.children.iter());
+                        }
+                        External(key, ref value) => {
+                            self.remaining_max -= 1;
+                            if self.remaining_min > 0 {
+                                self.remaining_min -= 1;
+                            }
+                            return Some((key, value));
+                        }
+                        Nothing => {}
+                    }
+                }
+            }
+        }
+        return None;
+    }
+
+    #[inline]
+    fn size_hint(&self) -> (uint, Option<uint>) {
+        (self.remaining_min, Some(self.remaining_max))
+    }
+}
+
+/// Forward iterator over a set
+pub struct TrieSetIterator<'self> {
+    priv iter: TrieMapIterator<'self, ()>
+}
+
+impl<'self> Iterator<uint> for TrieSetIterator<'self> {
+    fn next(&mut self) -> Option<uint> {
+        do self.iter.next().map |&(key, _)| { key }
+    }
+
+    fn size_hint(&self) -> (uint, Option<uint>) {
+        self.iter.size_hint()
+    }
+}
+
 #[cfg(test)]
 pub fn check_integrity<T>(trie: &TrieNode<T>) {
     assert!(trie.count != 0);
@@ -553,6 +624,29 @@ fn test_from_iter() {
             assert_eq!(map.find(&k), Some(&v));
         }
     }
+
+    #[test]
+    fn test_iteration() {
+        let empty_map : TrieMap<uint> = TrieMap::new();
+        assert_eq!(empty_map.iter().next(), None);
+
+        let first = uint::max_value - 10000;
+        let last = uint::max_value;
+
+        let mut map = TrieMap::new();
+        do uint::range_rev(last, first) |x| {
+            map.insert(x, x / 2);
+            true
+        };
+
+        let mut i = 0;
+        for (k, &v) in map.iter() {
+            assert_eq!(k, first + i);
+            assert_eq!(v, k / 2);
+            i += 1;
+        }
+        assert_eq!(i, last - first);
+    }
 }
 
 #[cfg(test)]
index f037aa2b7e789299758d38064fc52a2e2cde4cab..0259b547ab3f06040f812deaa55144fbb5bded3e 100644 (file)
@@ -195,10 +195,8 @@ pub fn build<A>(builder: &fn(push: &fn(v: A))) -> ~[A] {
  *             onto the vector being constructed.
  */
 #[inline]
-pub fn build_sized_opt<A>(size: Option<uint>,
-                          builder: &fn(push: &fn(v: A)))
-                       -> ~[A] {
-    build_sized(size.get_or_default(4), builder)
+pub fn build_sized_opt<A>(size: Option<uint>, builder: &fn(push: &fn(v: A))) -> ~[A] {
+    build_sized(size.unwrap_or_default(4), builder)
 }
 
 /// An iterator over the slices of a vector separated by elements that
@@ -481,6 +479,7 @@ pub fn each_permutation<T:Clone>(values: &[T], fun: &fn(perm : &[T]) -> bool) ->
 
 /// An iterator over the (overlapping) slices of length `size` within
 /// a vector.
+#[deriving(Clone)]
 pub struct WindowIter<'self, T> {
     priv v: &'self [T],
     priv size: uint
@@ -500,6 +499,10 @@ fn next(&mut self) -> Option<&'self [T]> {
 
 /// An iterator over a vector in (non-overlapping) chunks (`size`
 /// elements at a time).
+///
+/// When the vector len is not evenly divided by the chunk size,
+/// the last slice of the iteration will be the remainer.
+#[deriving(Clone)]
 pub struct ChunkIter<'self, T> {
     priv v: &'self [T],
     priv size: uint
@@ -507,16 +510,49 @@ pub struct ChunkIter<'self, T> {
 
 impl<'self, T> Iterator<&'self [T]> for ChunkIter<'self, T> {
     fn next(&mut self) -> Option<&'self [T]> {
-        if self.size == 0 {
+        if self.v.len() == 0 {
             None
-        } else if self.size >= self.v.len() {
-            // finished
-            self.size = 0;
-            Some(self.v)
         } else {
-            let ret = Some(self.v.slice(0, self.size));
-            self.v = self.v.slice(self.size, self.v.len());
-            ret
+            let chunksz = cmp::min(self.v.len(), self.size);
+            let (fst, snd) = (self.v.slice_to(chunksz),
+                              self.v.slice_from(chunksz));
+            self.v = snd;
+            Some(fst)
+        }
+    }
+}
+
+impl<'self, T> DoubleEndedIterator<&'self [T]> for ChunkIter<'self, T> {
+    fn next_back(&mut self) -> Option<&'self [T]> {
+        if self.v.len() == 0 {
+            None
+        } else {
+            let remainder = self.v.len() % self.size;
+            let chunksz = if remainder != 0 { remainder } else { self.size };
+            let (fst, snd) = (self.v.slice_to(self.v.len() - chunksz),
+                              self.v.slice_from(self.v.len() - chunksz));
+            self.v = fst;
+            Some(snd)
+        }
+    }
+}
+
+impl<'self, T> RandomAccessIterator<&'self [T]> for ChunkIter<'self, T> {
+    #[inline]
+    fn indexable(&self) -> uint {
+        self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
+    }
+
+    #[inline]
+    fn idx(&self, index: uint) -> Option<&'self [T]> {
+        if index < self.indexable() {
+            let lo = index * self.size;
+            let mut hi = lo + self.size;
+            if hi < lo || hi > self.v.len() { hi = self.v.len(); }
+
+            Some(self.v.slice(lo, hi))
+        } else {
+            None
         }
     }
 }
@@ -3380,6 +3416,14 @@ fn test_chunk_iterator() {
         assert_eq!(v.chunk_iter(2).collect::<~[&[int]]>(), ~[&[1i,2], &[3,4], &[5]]);
         assert_eq!(v.chunk_iter(3).collect::<~[&[int]]>(), ~[&[1i,2,3], &[4,5]]);
         assert_eq!(v.chunk_iter(6).collect::<~[&[int]]>(), ~[&[1i,2,3,4,5]]);
+
+        assert_eq!(v.chunk_iter(2).invert().collect::<~[&[int]]>(), ~[&[5i], &[3,4], &[1,2]]);
+        let it = v.chunk_iter(2);
+        assert_eq!(it.indexable(), 3);
+        assert_eq!(it.idx(0).unwrap(), &[1,2]);
+        assert_eq!(it.idx(1).unwrap(), &[3,4]);
+        assert_eq!(it.idx(2).unwrap(), &[5]);
+        assert_eq!(it.idx(3), None);
     }
 
     #[test]
index e6bbd45dae770b9e8e6aa4842d06647de3b105e1..883020e637a1b80bf81886c75c18e0af663504fd 100644 (file)
@@ -280,13 +280,13 @@ fn to_str(&self) -> ~str {
 #[test]
 fn lookup_Rust() {
     let abi = lookup("Rust");
-    assert!(abi.is_some() && abi.get().data().name == "Rust");
+    assert!(abi.is_some() && abi.unwrap().data().name == "Rust");
 }
 
 #[test]
 fn lookup_cdecl() {
     let abi = lookup("cdecl");
-    assert!(abi.is_some() && abi.get().data().name == "cdecl");
+    assert!(abi.is_some() && abi.unwrap().data().name == "cdecl");
 }
 
 #[test]
index cf7a1e51798ac56ee3499dab5dfded7b797894e9..435be3c71af6f08d1fc57d644341a354cb86ddb9 100644 (file)
@@ -24,7 +24,7 @@
 // table) and a SyntaxContext to track renaming and
 // macro expansion per Flatt et al., "Macros
 // That Work Together"
-#[deriving(Clone, Eq, IterBytes)]
+#[deriving(Clone, Eq, IterBytes, ToStr)]
 pub struct ident { name: Name, ctxt: SyntaxContext }
 
 /// Construct an identifier with the given name and an empty context:
@@ -121,7 +121,7 @@ pub struct Path {
 
 pub type NodeId = int;
 
-#[deriving(Clone, Eq, Encodable, Decodable, IterBytes)]
+#[deriving(Clone, Eq, Encodable, Decodable, IterBytes, ToStr)]
 pub struct def_id {
     crate: CrateNum,
     node: NodeId,
index d1ddebfc347af259d797786a605358876f5ac7c3..d39cb2f507ca957ae57d1ec7d45332487ddcfd88 100644 (file)
@@ -114,7 +114,7 @@ pub fn meta(&self) -> @MetaItem {
     /// non-sugared doc attributes.)
     pub fn desugar_doc(&self) -> Attribute {
         if self.node.is_sugared_doc {
-            let comment = self.value_str().get();
+            let comment = self.value_str().unwrap();
             let meta = mk_name_value_item_str(@"doc",
                                               strip_doc_comment_decoration(comment).to_managed());
             mk_attr(meta)
index 0da424ce54cddb2b75e7b11578cbef7f570add25..8c70f128d9a09b82408950f3bba087b3189b7d5c 100644 (file)
@@ -369,12 +369,19 @@ pub fn span_to_lines(&self, sp: span) -> @FileLines {
         return @FileLines {file: lo.file, lines: lines};
     }
 
-    pub fn span_to_snippet(&self, sp: span) -> ~str {
+    pub fn span_to_snippet(&self, sp: span) -> Option<~str> {
         let begin = self.lookup_byte_offset(sp.lo);
         let end = self.lookup_byte_offset(sp.hi);
-        assert_eq!(begin.fm.start_pos, end.fm.start_pos);
-        return begin.fm.src.slice(
-                          begin.pos.to_uint(), end.pos.to_uint()).to_owned();
+
+        // FIXME #8256: this used to be an assert but whatever precondition
+        // it's testing isn't true for all spans in the AST, so to allow the
+        // caller to not have to fail (and it can't catch it since the CodeMap
+        // isn't sendable), return None
+        if begin.fm.start_pos != end.fm.start_pos {
+            None
+        } else {
+            Some(begin.fm.src.slice( begin.pos.to_uint(), end.pos.to_uint()).to_owned())
+        }
     }
 
     pub fn get_filemap(&self, filename: &str) -> @FileMap {
index 1dda2493da20a86c57417fa3857fa34fefa24ff0..6ed5ca3e402a8dc4ac5e69ada83f9255c30bc75f 100644 (file)
@@ -538,20 +538,20 @@ mod test {
         m.insert (@"def",@16);
         // FIXME: #4492 (ICE)  assert_eq!(m.find(&@"abc"),Some(@15));
         //  ....               assert_eq!(m.find(&@"def"),Some(@16));
-        assert_eq!(*(m.find(&@"abc").get()),15);
-        assert_eq!(*(m.find(&@"def").get()),16);
+        assert_eq!(*(m.find(&@"abc").unwrap()),15);
+        assert_eq!(*(m.find(&@"def").unwrap()),16);
         let n = m.push_frame();
         // old bindings are still present:
-        assert_eq!(*(n.find(&@"abc").get()),15);
-        assert_eq!(*(n.find(&@"def").get()),16);
+        assert_eq!(*(n.find(&@"abc").unwrap()),15);
+        assert_eq!(*(n.find(&@"def").unwrap()),16);
         n.insert (@"def",@17);
         // n shows the new binding
-        assert_eq!(*(n.find(&@"abc").get()),15);
-        assert_eq!(*(n.find(&@"def").get()),17);
+        assert_eq!(*(n.find(&@"abc").unwrap()),15);
+        assert_eq!(*(n.find(&@"def").unwrap()),17);
         // ... but m still has the old ones
         // FIXME: #4492: assert_eq!(m.find(&@"abc"),Some(@15));
         // FIXME: #4492: assert_eq!(m.find(&@"def"),Some(@16));
-        assert_eq!(*(m.find(&@"abc").get()),15);
-        assert_eq!(*(m.find(&@"def").get()),16);
+        assert_eq!(*(m.find(&@"abc").unwrap()),15);
+        assert_eq!(*(m.find(&@"def").unwrap()),16);
     }
 }
index f5eb57c94b76f104cda5a7393e12b726c6ddeb76..fb1e6bf1913844c878d9e3a36702fcb686d61807 100644 (file)
@@ -961,7 +961,7 @@ fn create_struct_pattern(cx: @ExtCtxt,
         let field_pats = do vec::build |push| {
             for (&pat, &(id, _)) in subpats.iter().zip(ident_expr.iter()) {
                 // id is guaranteed to be Some
-                push(ast::field_pat { ident: id.get(), pat: pat })
+                push(ast::field_pat { ident: id.unwrap(), pat: pat })
             }
         };
         cx.pat_struct(span, matching_path, field_pats)
index a6c5526b5a9b4968624db792fa6f17bc06c2f1db..c7020b990bf005695341846d0b0ecd49f773fa0a 100644 (file)
@@ -1182,9 +1182,9 @@ fn renaming () {
         let a2_name = intern("a2");
         let renamer = new_ident_renamer(ast::ident{name:a_name,ctxt:empty_ctxt},
                                         a2_name);
-        let renamed_ast = fun_to_ident_folder(renamer).fold_item(item_ast).get();
+        let renamed_ast = fun_to_ident_folder(renamer).fold_item(item_ast).unwrap();
         let resolver = new_ident_resolver();
-        let resolved_ast = fun_to_ident_folder(resolver).fold_item(renamed_ast).get();
+        let resolved_ast = fun_to_ident_folder(resolver).fold_item(renamed_ast).unwrap();
         let resolved_as_str = pprust::item_to_str(resolved_ast,
                                                   get_ident_interner());
         assert_eq!(resolved_as_str,~"fn a2() -> int { let b = 13; b }");
index 626a562b92c0397e9aa78222c185b132d9fafd9a..71903b9aa0204790fca3917dc093d553a67d8117 100644 (file)
@@ -31,7 +31,7 @@ pub fn expand_line(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree])
     -> base::MacResult {
     base::check_zero_tts(cx, sp, tts, "line!");
 
-    let topmost = topmost_expn_info(cx.backtrace().get());
+    let topmost = topmost_expn_info(cx.backtrace().unwrap());
     let loc = cx.codemap().lookup_char_pos(topmost.call_site.lo);
 
     base::MRExpr(cx.expr_uint(topmost.call_site, loc.line))
@@ -42,7 +42,7 @@ pub fn expand_col(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree])
     -> base::MacResult {
     base::check_zero_tts(cx, sp, tts, "col!");
 
-    let topmost = topmost_expn_info(cx.backtrace().get());
+    let topmost = topmost_expn_info(cx.backtrace().unwrap());
     let loc = cx.codemap().lookup_char_pos(topmost.call_site.lo);
     base::MRExpr(cx.expr_uint(topmost.call_site, loc.col.to_uint()))
 }
@@ -54,7 +54,7 @@ pub fn expand_file(cx: @ExtCtxt, sp: span, tts: &[ast::token_tree])
     -> base::MacResult {
     base::check_zero_tts(cx, sp, tts, "file!");
 
-    let topmost = topmost_expn_info(cx.backtrace().get());
+    let topmost = topmost_expn_info(cx.backtrace().unwrap());
     let loc = cx.codemap().lookup_char_pos(topmost.call_site.lo);
     let filename = loc.file.name;
     base::MRExpr(cx.expr_str(topmost.call_site, filename))
index afa2e7a5e42f5da00dd09ac0bf08a06f26b8a1ce..a0932729930e3c7fcc3da3da356b6b23251b3efd 100644 (file)
@@ -691,7 +691,7 @@ pub fn parse_ty_bare_fn(&self) -> ty_ {
         */
 
         let opt_abis = self.parse_opt_abis();
-        let abis = opt_abis.get_or_default(AbiSet::Rust());
+        let abis = opt_abis.unwrap_or_default(AbiSet::Rust());
         let purity = self.parse_unsafety();
         self.expect_keyword(keywords::Fn);
         let (decl, lifetimes) = self.parse_ty_fn_decl();
@@ -3326,7 +3326,7 @@ fn parse_ty_param(&self) -> TyParam {
         let ident = self.parse_ident();
         let opt_bounds = self.parse_optional_ty_param_bounds();
         // For typarams we don't care about the difference b/w "<T>" and "<T:>".
-        let bounds = opt_bounds.get_or_default(opt_vec::Empty);
+        let bounds = opt_bounds.unwrap_or_default(opt_vec::Empty);
         ast::TyParam { ident: ident, id: self.get_id(), bounds: bounds }
     }
 
@@ -4196,7 +4196,7 @@ fn parse_item_foreign_mod(&self,
                 self.obsolete(*self.last_span, ObsoleteExternVisibility);
             }
 
-            let abis = opt_abis.get_or_default(AbiSet::C());
+            let abis = opt_abis.unwrap_or_default(AbiSet::C());
 
             let (inner, next) = self.parse_inner_attrs_and_next();
             let m = self.parse_foreign_mod_items(sort, abis, next);
@@ -4463,7 +4463,7 @@ fn parse_item_or_view_item(&self,
 
             if self.eat_keyword(keywords::Fn) {
                 // EXTERN FUNCTION ITEM
-                let abis = opt_abis.get_or_default(AbiSet::C());
+                let abis = opt_abis.unwrap_or_default(AbiSet::C());
                 let (ident, item_, extra_attrs) =
                     self.parse_item_fn(extern_fn, abis);
                 return iovi_item(self.mk_item(lo, self.last_span.hi, ident,
index 174b0f8e4517cba240162b4cfadec27f40876390..f517179f6036613e100e2ed9290820d934db96b8 100644 (file)
@@ -874,7 +874,7 @@ pub fn print_attribute(s: @ps, attr: &ast::Attribute) {
     hardbreak_if_not_bol(s);
     maybe_print_comment(s, attr.span.lo);
     if attr.node.is_sugared_doc {
-        let comment = attr.value_str().get();
+        let comment = attr.value_str().unwrap();
         word(s.s, comment);
     } else {
         word(s.s, "#[");
@@ -1085,7 +1085,7 @@ pub fn print_call_post(s: @ps,
     }
     if sugar != ast::NoSugar {
         nbsp(s);
-        match blk.get().node {
+        match blk.unwrap().node {
           // need to handle closures specifically
           ast::expr_do_body(e) => {
             end(s); // we close our head box; closure
@@ -1095,7 +1095,7 @@ pub fn print_call_post(s: @ps,
           }
           _ => {
             // not sure if this can happen.
-            print_expr(s, blk.get());
+            print_expr(s, blk.unwrap());
           }
         }
     }
@@ -1323,13 +1323,13 @@ fn print_field(s: @ps, field: &ast::Field) {
         assert!(body.stmts.is_empty());
         assert!(body.expr.is_some());
         // we extract the block, so as not to create another set of boxes
-        match body.expr.get().node {
+        match body.expr.unwrap().node {
             ast::expr_block(ref blk) => {
                 print_block_unclosed(s, blk);
             }
             _ => {
                 // this is a bare expression
-                print_expr(s, body.expr.get());
+                print_expr(s, body.expr.unwrap());
                 end(s); // need to close a box
             }
         }
index da1c3596ff6c94030711fc4ae3fe7ff663048d55..cf160ca31c6f185d3ae38b5a06ef6edda527674d 100644 (file)
@@ -100,7 +100,7 @@ fn main() {
     let args = os::args();
     let n_keys = {
         if args.len() == 2 {
-            uint::from_str(args[1]).get()
+            uint::from_str(args[1]).unwrap()
         } else {
             1000000
         }
index 2c412e2eecd807fe52ec9f4bd9c1a8bf0a3c3305..4fbe00622aa26fdded3c4d32bf8a6d4b7f0824e3 100644 (file)
@@ -159,7 +159,7 @@ fn main() {
     let args = os::args();
     let num_keys = {
         if args.len() == 2 {
-            uint::from_str(args[1]).get()
+            uint::from_str(args[1]).unwrap()
         } else {
             100 // woefully inadequate for any real measurement
         }
index 8924a9beb6e5ee8c9f449f8612342e123bb65eda..4a32fda59d81ad5cb4e15963083b73f361b97da7 100644 (file)
@@ -21,7 +21,7 @@ fn main() {
         args
     };
 
-    let n = uint::from_str(args[1]).get();
+    let n = uint::from_str(args[1]).unwrap();
 
     for i in range(0u, n) {
         let x = uint::to_str(i);
index 2557680f7b507853abac8a06fe0e1e5fa88c7218..2f4d763b84d778ab750446de95e447dd2b0cb122 100644 (file)
@@ -418,8 +418,8 @@ fn main() {
         args
     };
 
-    let scale = uint::from_str(args[1]).get();
-    let num_keys = uint::from_str(args[2]).get();
+    let scale = uint::from_str(args[1]).unwrap();
+    let num_keys = uint::from_str(args[2]).unwrap();
     let do_validate = false;
     let do_sequential = true;
 
index 186923da43b8ccad194fbfb1d3c4ab47b1d6e8b0..4e9656afb813d253c50713163bdc3cfa4f8eae7a 100644 (file)
@@ -59,8 +59,8 @@ fn run(args: &[~str]) {
 
     let to_child = SharedChan::new(to_child);
 
-    let size = uint::from_str(args[1]).get();
-    let workers = uint::from_str(args[2]).get();
+    let size = uint::from_str(args[1]).unwrap();
+    let workers = uint::from_str(args[2]).unwrap();
     let num_bytes = 100;
     let start = extra::time::precise_time_s();
     let mut worker_results = ~[];
index 05ace5fd8e6c75b75ed10c069ca0ca82d03a626f..470e23d63a514ff81f8bbd419c4b32fab03ff927 100644 (file)
@@ -53,8 +53,8 @@ fn run(args: &[~str]) {
     let (from_parent, to_child) = stream();
     let to_child = SharedChan::new(to_child);
 
-    let size = uint::from_str(args[1]).get();
-    let workers = uint::from_str(args[2]).get();
+    let size = uint::from_str(args[1]).unwrap();
+    let workers = uint::from_str(args[2]).unwrap();
     let num_bytes = 100;
     let start = extra::time::precise_time_s();
     let mut worker_results = ~[];
index 649d029e60e8b7a3c20441da9a5f1e5262e85185..7de95f4d822c54613a3f72064c3efb9b0778d02e 100644 (file)
@@ -79,8 +79,8 @@ fn main() {
         args.clone()
     };
 
-    let num_tasks = uint::from_str(args[1]).get();
-    let msg_per_task = uint::from_str(args[2]).get();
+    let num_tasks = uint::from_str(args[1]).unwrap();
+    let msg_per_task = uint::from_str(args[2]).unwrap();
 
     let (num_chan, num_port) = init();
     let num_chan = Cell::new(num_chan);
index 7f9d7aa588906b9837105a76dab73050abf64ab1..1299e863db6b3f923274740bc443b65f5b802862 100644 (file)
@@ -75,8 +75,8 @@ fn main() {
         args.clone()
     };
 
-    let num_tasks = uint::from_str(args[1]).get();
-    let msg_per_task = uint::from_str(args[2]).get();
+    let num_tasks = uint::from_str(args[1]).unwrap();
+    let msg_per_task = uint::from_str(args[2]).unwrap();
 
     let (num_chan, num_port) = init();
     let num_chan = Cell::new(num_chan);
index e06ff02a0b38f403404e78706b1e9f7046b6d0c5..e8659ba26d4bc878bd686b5f873ba7365bfe4bc8 100644 (file)
@@ -35,6 +35,6 @@ fn main() {
     } else {
         args
     };
-    let n = int::from_str(args[1]).get();
+    let n = int::from_str(args[1]).unwrap();
     printfln!("Ack(3,%d): %d\n", n, ack(3, n));
 }
index 596a5b5422a5dccbd8e12c81b3db9055bc58c767..8a2ae3e89952007903431e6484d1e70af1d7c366 100644 (file)
@@ -9,7 +9,7 @@
 // except according to those terms.
 
 extern mod extra;
-use extra::arena;
+use extra::arena::Arena;
 
 enum Tree<'self> {
     Nil,
@@ -25,7 +25,7 @@ fn item_check(t: &Tree) -> int {
     }
 }
 
-fn bottom_up_tree<'r>(arena: &'r arena::Arena, item: int, depth: int)
+fn bottom_up_tree<'r>(arena: &'r Arena, item: int, depth: int)
                    -> &'r Tree<'r> {
     if depth > 0 {
         return arena.alloc(
@@ -48,7 +48,7 @@ fn main() {
         args
     };
 
-    let n = int::from_str(args[1]).get();
+    let n = int::from_str(args[1]).unwrap();
     let min_depth = 4;
     let mut max_depth;
     if min_depth + 2 > n {
@@ -57,7 +57,7 @@ fn main() {
         max_depth = n;
     }
 
-    let stretch_arena = arena::Arena();
+    let stretch_arena = Arena::new();
     let stretch_depth = max_depth + 1;
     let stretch_tree = bottom_up_tree(&stretch_arena, 0, stretch_depth);
 
@@ -65,7 +65,7 @@ fn main() {
               stretch_depth,
               item_check(stretch_tree));
 
-    let long_lived_arena = arena::Arena();
+    let long_lived_arena = Arena::new();
     let long_lived_tree = bottom_up_tree(&long_lived_arena, 0, max_depth);
     let mut depth = min_depth;
     while depth <= max_depth {
index f48c15329463e890b854c5dd6185c49ff716a998..190ad62d6e17ff771ecb81900a8cdd2767479a3b 100644 (file)
@@ -212,7 +212,7 @@ fn main() {
         args
     };
 
-    let nn = uint::from_str(args[1]).get();
+    let nn = uint::from_str(args[1]).unwrap();
 
     print_complements();
     io::println("");
index bf942cf61a38c1bd2ebc1f52061c9540e12f612c..9d4d31b8969205a3b0b7a911dd9648897c3d8214 100644 (file)
@@ -91,6 +91,6 @@ fn fannkuch_redux(n: i32) -> i32 {
 
 #[fixed_stack_segment]
 fn main() {
-    let n: i32 = FromStr::from_str(os::args()[1]).get();
+    let n: i32 = FromStr::from_str(os::args()[1]).unwrap();
     printfln!("Pfannkuchen(%d) = %d", n as int, fannkuch_redux(n) as int);
 }
index af96170c79c8701318f62111146b95c91d8a9e71..579b88a7e0e72c0231fb22f17a8c7a407cbfb83b 100644 (file)
@@ -184,7 +184,7 @@ fn make(&mut self, n: uint) {
 
 #[fixed_stack_segment]
 fn main() {
-    let n: uint = FromStr::from_str(os::args()[1]).get();
+    let n: uint = FromStr::from_str(os::args()[1]).unwrap();
 
     unsafe {
         let mode = "w";
index 3a90c6647e08e5d732b9f8ad0ae7deee053fff51..4e2ab8b0a498dce2b444fad63f81717b4015dd48 100644 (file)
@@ -130,7 +130,7 @@ fn main() {
         io::stdout()
     };
 
-    let n = int::from_str(args[1]).get();
+    let n = int::from_str(args[1]).unwrap();
 
     let iub: ~[AminoAcids] =
         make_cumulative(~[acid('a', 27u32), acid('c', 12u32), acid('g', 12u32),
index 7b8bc31bf1c8326331e70180ac69e178b18cfa11..9c07df36eb3c1be3bf84a94a2f34dc11dd416bd4 100644 (file)
@@ -31,6 +31,6 @@ fn main() {
     } else {
         args
     };
-    let n = int::from_str(args[1]).get();
+    let n = int::from_str(args[1]).unwrap();
     printfln!("%d\n", fib(n));
 }
index 16936f6ed722d3fad5be3024ed7a75a8b33983fc..cf43f470e7177d55e2fcf77b0c57061fc03d02a7 100644 (file)
@@ -9,7 +9,7 @@
 #[fixed_stack_segment]
 fn main() {
     unsafe {
-        let w: i32 = FromStr::from_str(os::args()[1]).get();
+        let w: i32 = FromStr::from_str(os::args()[1]).unwrap();
         let h = w;
         let mut byte_acc: i8 = 0;
         let mut bit_num: i32 = 0;
index 99bd7c0f7867273873363141d474cfa6598b718a..115607d0a992c14896d3d227799dee2dbc611bbf 100644 (file)
@@ -137,7 +137,7 @@ fn offset_momentum(bodies: &mut [Planet, ..N_BODIES]) {
 }
 
 fn main() {
-    let n: i32 = FromStr::from_str(os::args()[1]).get();
+    let n: i32 = FromStr::from_str(os::args()[1]).unwrap();
     let mut bodies = BODIES;
 
     offset_momentum(&mut bodies);
index 663ebcac3340acaeeb7b3f8909e6cdb47b0fe8ab..611b11560e4ae8b0e8970b3d5a16bf73d66f9366 100644 (file)
@@ -110,7 +110,7 @@ fn main() {
     if opts.stress {
         stress(2);
     } else {
-        let max = uint::parse_bytes(args[1].as_bytes(), 10u).get() as int;
+        let max = uint::parse_bytes(args[1].as_bytes(), 10u).unwrap() as int;
 
         let num_trials = 10;
 
index e3c3c19c33bb38abc247d728db1e30b2c8655871..aef22bc2b8426f056a4047abb81092e288f9ece6 100644 (file)
@@ -52,7 +52,7 @@ fn mult_AtAv(v: &mut [f64], out: &mut [f64], tmp: &mut [f64]) {
 
 #[fixed_stack_segment]
 fn main() {
-    let n: uint = FromStr::from_str(os::args()[1]).get();
+    let n: uint = FromStr::from_str(os::args()[1]).unwrap();
     let mut u = vec::from_elem(n, 1f64);
     let mut v = u.clone();
     let mut tmp = u.clone();
index 203b9c297fa6b402d806f7719f9fa08053bf239f..ace008c1f95d2164febe6451d5d3e3d98c6f5cd5 100644 (file)
@@ -62,13 +62,13 @@ fn main() {
         os::args()
     };
     let token = if args.len() > 1u {
-        FromStr::from_str(args[1]).get()
+        FromStr::from_str(args[1]).unwrap()
     }
     else {
         1000
     };
     let n_tasks = if args.len() > 2u {
-        FromStr::from_str(args[2]).get()
+        FromStr::from_str(args[2]).unwrap()
     }
     else {
         503
index 2c2073eafea6275732530164561f4a74aaef705e..a035041a662dc73097c6a8bbd28430a6f99cc43a 100644 (file)
@@ -39,8 +39,8 @@ fn main() {
     } else {
         args
     };
-    let max = uint::from_str(args[1]).get();
-    let rep = uint::from_str(args[2]).get();
+    let max = uint::from_str(args[1]).unwrap();
+    let rep = uint::from_str(args[2]).unwrap();
 
     let mut checkf = 0.0;
     let mut appendf = 0.0;
index 49b2c32ed686717de8985ee9d8a96c56fd8fea25..675735408953403b49d6fd622a2cd906c0cd7eaa 100644 (file)
@@ -75,9 +75,9 @@ pub fn read(reader: @io::Reader) -> Sudoku {
             let comps: ~[&str] = line.trim().split_iter(',').collect();
 
             if comps.len() == 3u {
-                let row     = uint::from_str(comps[0]).get() as u8;
-                let col     = uint::from_str(comps[1]).get() as u8;
-                g[row][col] = uint::from_str(comps[2]).get() as u8;
+                let row     = uint::from_str(comps[0]).unwrap() as u8;
+                let col     = uint::from_str(comps[1]).unwrap() as u8;
+                g[row][col] = uint::from_str(comps[2]).unwrap() as u8;
             }
             else {
                 fail!("Invalid sudoku file");
index 4e27841a748505b9ca0b58c0a8c470cf9aa23748..be7f9b5f43adfc22b75ad98e0e513408d9e3fb6e 100644 (file)
@@ -52,7 +52,7 @@ fn main() {
     };
 
     let (p,c) = comm::stream();
-    child_generation(uint::from_str(args[1]).get(), c);
+    child_generation(uint::from_str(args[1]).unwrap(), c);
     if p.try_recv().is_none() {
         fail!("it happened when we slumbered");
     }
index 6ab83e5b3830b632b3d0474e5672c8ebfac0b918..95dd803af8183221f00bbc21ee6a2c56bbabd3e9 100644 (file)
@@ -71,7 +71,7 @@ fn main() {
         args.clone()
     };
 
-    let num_tasks = uint::from_str(args[1]).get();
+    let num_tasks = uint::from_str(args[1]).unwrap();
 
     // Main group #0 waits for unsupervised group #1.
     // Grandparent group #1 waits for middle group #2, then fails, killing #3.
index a152c3021331841ab19f83fa8760e5f2a1c7f914..83116ae3c87deb07df1902da9201edb1ef55ea5e 100644 (file)
@@ -31,7 +31,7 @@ fn main() {
     } else {
         args
     };
-    let n = uint::from_str(args[1]).get();
+    let n = uint::from_str(args[1]).unwrap();
     let mut i = 0u;
     while i < n { task::spawn(|| f(n) ); i += 1u; }
 }
index 451616a074f118942ce116f8490e8979c545b6a5..cb6290686816d74054a3e9923c9f4a862d628bd7 100644 (file)
@@ -17,7 +17,7 @@ fn main() {
         y = Some(x.downgrade(write_mode));
         //~^ ERROR cannot infer an appropriate lifetime
     }
-    y.get();
+    y.unwrap();
     // Adding this line causes a method unification failure instead
     // do (&option::unwrap(y)).read |state| { assert!(*state == 1); }
 }
index b6535b6189a0449cc77ab77bea55ec695ab54a2d..75e1989aff01a5ad7faf55da8087bf89bda910cb 100644 (file)
@@ -17,7 +17,7 @@ fn main() {
     do x.write_downgrade |write_mode| {
         y = Some(write_mode);
     }
-    y.get();
+    y.unwrap();
     // Adding this line causes a method unification failure instead
     // do (&option::unwrap(y)).write |state| { assert!(*state == 1); }
 }
index 782ce61cab253647286fad6fdbe021d2d6593f12..4f552bc8f4216468a8929cb78c44300bb225dcf4 100644 (file)
@@ -8,10 +8,10 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-// error-pattern:get called on `Err` result: ~"kitty"
+// error-pattern:called `Result::unwrap()` on `Err` value: kitty
 
 use std::result;
 
 fn main() {
-  error!(result::Err::<int,~str>(~"kitty").get());
+    error!(result::Err::<int,~str>(~"kitty").unwrap());
 }
index 3b18a8649eeeaac16d91727ded6bed6306ba45c6..668f602b3d35c941770d07d920c29f7c04bdab7a 100644 (file)
@@ -1,5 +1,5 @@
 fn g(x: &Option<int>) {
-    println(x.get().to_str());
+    println(x.unwrap().to_str());
 }
 
 fn f(x: &mut Option<int>) {
index 4775e5fe0a80ee47988b8c4f951add5ebf2eb75f..9f17b9d7f95b5811ed82a74dd3cae7b2ac877317 100644 (file)
@@ -19,5 +19,5 @@ fn select<'r>(x: &'r Option<int>, y: &'r Option<int>) -> &'r Option<int> {
 pub fn main() {
     let x = None;
     let y = Some(3);
-    assert_eq!(select(&x, &y).get(), 3);
+    assert_eq!(select(&x, &y).unwrap(), 3);
 }
index fe39d1b11d3b8d1194eb4c18f1ca999dbbc7b757..8af173150a06dceee7c93cddfbf1485c2ce9964d 100644 (file)
@@ -9,29 +9,17 @@
 // except according to those terms.
 
 pub fn main() {
-    let foo = 1;
-    let bar = 2;
+    let foo: int = 1;
+    let bar: int = 2;
     let foobar = foo + bar;
 
-    let nope = optint(0) + optint(0);
-    let somefoo = optint(foo) + optint(0);
-    let somebar = optint(bar) + optint(0);
-    let somefoobar = optint(foo) + optint(bar);
+    let nope = None::<int> + None::<int>;
+    let somefoo = Some(foo) + None::<int>;
+    let somebar = None::<int> + Some(bar);
+    let somefoobar = Some(foo) + Some(bar);
 
-    match nope {
-        None => (),
-        Some(foo) => fail!("expected None, but found %?", foo)
-    }
-    assert_eq!(foo, somefoo.get());
-    assert_eq!(bar, somebar.get());
-    assert_eq!(foobar, somefoobar.get());
-}
-
-fn optint(input: int) -> Option<int> {
-    if input == 0 {
-        return None;
-    }
-    else {
-        return Some(input);
-    }
+    assert_eq!(nope, None::<int>);
+    assert_eq!(somefoo, None::<int>);
+    assert_eq!(somebar, None::<int>);
+    assert_eq!(foobar, somefoobar.unwrap());
 }
index 9500f83b76b09132b6ea729b5a6758640c0219a6..f2063b583e4f9b0cf6b7f7a0874dc1a8276a5e27 100644 (file)
 // except according to those terms.
 
 extern mod extra;
-use extra::arena;
+use extra::arena::Arena;
 
 pub fn main() {
-    let mut arena = arena::Arena();
+    let mut arena = Arena::new();
     let p = &mut arena;
     let x = p.alloc(|| 4u);
     printf!("%u", *x);
index ac2fc2eda23cf61575d972dad82c0a08eba95c06..f5eb04dd83bfe3774c0466e33fd2820fdb9aac53 100644 (file)
@@ -105,13 +105,13 @@ pub fn main() {
     assert_eq!(*p, a.value.v5.f);
 
     let p = get_v6_a(&a, 1);
-    assert_eq!(*p, a.value.v6.get().f);
+    assert_eq!(*p, a.value.v6.unwrap().f);
 
     let p = get_v6_b(&a, 1);
-    assert_eq!(*p, a.value.v6.get().f);
+    assert_eq!(*p, a.value.v6.unwrap().f);
 
     let p = get_v6_c(&a, 1);
-    assert_eq!(*p, a.value.v6.get().f);
+    assert_eq!(*p, a.value.v6.unwrap().f);
 
     let p = get_v5_ref(&a, 1);
     assert_eq!(*p, a.value.v5.f);