From 7fc8807145aa527b8992ee8d02d22be4c0fc9046 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marvin=20L=C3=B6bel?= Date: Fri, 2 Aug 2013 14:59:21 +0200 Subject: [PATCH] Updated std::Either and std::Result Made naming schemes consistent between Option, Result and Either Changed Options Add implementation to work like the maybe monad (return None if any of the inputs is None) Renamed Option::unwrap to Option::get and Option::take_unwrap to Option::take_get --- doc/tutorial-tasks.md | 2 +- src/compiletest/errors.rs | 2 +- src/compiletest/header.rs | 2 +- src/compiletest/runtest.rs | 2 +- src/libextra/dlist.rs | 28 +- src/libextra/fileinput.rs | 10 +- src/libextra/getopts.rs | 2 +- src/libextra/json.rs | 78 ++-- src/libextra/ringbuf.rs | 16 +- src/libextra/rl.rs | 2 +- src/libextra/smallintmap.rs | 40 +- src/libextra/sync.rs | 10 +- src/libextra/tempfile.rs | 2 +- src/libextra/term.rs | 34 +- src/libextra/terminfo/parm.rs | 36 +- src/libextra/terminfo/searcher.rs | 2 +- src/libextra/test.rs | 6 +- src/libextra/time.rs | 8 +- src/libextra/treemap.rs | 66 ++-- src/libextra/url.rs | 52 +-- src/libextra/workcache.rs | 4 +- src/librust/rust.rs | 4 +- src/librustc/back/passes.rs | 2 +- src/librustc/middle/resolve.rs | 2 +- src/librustc/middle/trans/adt.rs | 4 +- src/librustc/middle/trans/base.rs | 4 +- src/librustc/middle/trans/reflect.rs | 4 +- src/librustc/middle/ty.rs | 32 +- src/librustc/middle/typeck/rscope.rs | 1 + src/librustc/util/enum_set.rs | 2 +- src/librustdoc/page_pass.rs | 2 +- src/librustdoc/prune_private_pass.rs | 2 +- src/librustdoc/sectionalize_pass.rs | 2 +- src/librustpkg/tests.rs | 2 +- src/libstd/cell.rs | 2 +- src/libstd/comm.rs | 14 +- src/libstd/either.rs | 366 +++++++++--------- src/libstd/io.rs | 40 +- src/libstd/iterator.rs | 74 ++-- src/libstd/local_data.rs | 22 +- src/libstd/num/f32.rs | 8 +- src/libstd/num/f64.rs | 8 +- src/libstd/num/float.rs | 8 +- src/libstd/num/strconv.rs | 12 +- src/libstd/option.rs | 226 ++++++----- src/libstd/pipes.rs | 16 +- src/libstd/ptr.rs | 4 +- src/libstd/result.rs | 330 +++++++--------- src/libstd/rt/comm.rs | 6 +- src/libstd/rt/io/file.rs | 2 +- src/libstd/rt/io/mod.rs | 36 +- src/libstd/rt/io/net/ip.rs | 16 +- src/libstd/rt/io/net/tcp.rs | 8 +- src/libstd/rt/io/net/udp.rs | 4 +- src/libstd/rt/io/option.rs | 2 +- src/libstd/rt/kill.rs | 30 +- src/libstd/rt/local.rs | 4 +- src/libstd/rt/sched.rs | 12 +- src/libstd/rt/select.rs | 2 +- src/libstd/rt/task.rs | 12 +- src/libstd/rt/tube.rs | 2 +- src/libstd/rt/uv/async.rs | 2 +- src/libstd/rt/uv/idle.rs | 2 +- src/libstd/rt/uv/net.rs | 32 +- src/libstd/rt/uv/timer.rs | 2 +- src/libstd/rt/uv/uvio.rs | 56 +-- src/libstd/run.rs | 8 +- src/libstd/task/mod.rs | 6 +- src/libstd/task/spawn.rs | 7 +- src/libstd/unstable/sync.rs | 10 +- src/libstd/vec.rs | 46 +-- src/libsyntax/ast.rs | 4 +- src/test/bench/core-map.rs | 6 +- src/test/bench/core-std.rs | 2 +- src/test/bench/graph500-bfs.rs | 2 +- src/test/bench/msgsend-ring-mutex-arcs.rs | 4 +- src/test/bench/msgsend-ring-rw-arcs.rs | 4 +- src/test/bench/shootout-fasta.rs | 2 +- src/test/bench/shootout-k-nucleotide-pipes.rs | 4 +- src/test/bench/task-perf-linked-failure.rs | 2 +- .../arc-rw-cond-shouldnt-escape.rs | 2 +- .../arc-rw-state-shouldnt-escape.rs | 2 +- .../arc-rw-write-mode-cond-shouldnt-escape.rs | 2 +- .../compile-fail/sync-cond-shouldnt-escape.rs | 2 +- .../sync-rwlock-cond-shouldnt-escape.rs | 2 +- ...-rwlock-write-mode-cond-shouldnt-escape.rs | 2 +- src/test/run-fail/result-get-fail.rs | 2 +- .../class-impl-very-parameterized-trait.rs | 2 +- src/test/run-pass/issue-2718.rs | 14 +- src/test/run-pass/issue-4016.rs | 2 +- src/test/run-pass/issue-4036.rs | 2 +- src/test/run-pass/option_addition.rs | 30 +- src/test/run-pass/stat.rs | 2 +- src/test/run-pass/task-comm-12.rs | 2 +- src/test/run-pass/task-comm-9.rs | 2 +- src/test/run-pass/yield.rs | 2 +- src/test/run-pass/yield1.rs | 2 +- 97 files changed, 991 insertions(+), 1017 deletions(-) diff --git a/doc/tutorial-tasks.md b/doc/tutorial-tasks.md index 4528f3f9e15b2..eaeee4df27164 100644 --- a/doc/tutorial-tasks.md +++ b/doc/tutorial-tasks.md @@ -355,7 +355,7 @@ fn pnorm(nums: &~[float], p: uint) -> float { fn main() { let numbers = vec::from_fn(1000000, |_| rand::random::()); - println(fmt!("Inf-norm = %?", *numbers.iter().max().unwrap())); + println(fmt!("Inf-norm = %?", *numbers.iter().max().get())); let numbers_arc = Arc::new(numbers); diff --git a/src/compiletest/errors.rs b/src/compiletest/errors.rs index b044f19dcd629..780a917c019b2 100644 --- a/src/compiletest/errors.rs +++ b/src/compiletest/errors.rs @@ -15,7 +15,7 @@ pub struct ExpectedError { line: uint, kind: ~str, msg: ~str } // Load any test directives embedded in the file pub fn load_errors(testfile: &Path) -> ~[ExpectedError] { let mut error_patterns = ~[]; - let rdr = io::file_reader(testfile).unwrap(); + let rdr = io::file_reader(testfile).get(); let mut line_num = 1u; while !rdr.eof() { let ln = rdr.read_line(); diff --git a/src/compiletest/header.rs b/src/compiletest/header.rs index a07da151afc3b..8b57357631313 100644 --- a/src/compiletest/header.rs +++ b/src/compiletest/header.rs @@ -105,7 +105,7 @@ pub fn is_test_ignored(config: &config, testfile: &Path) -> bool { } fn iter_header(testfile: &Path, it: &fn(~str) -> bool) -> bool { - let rdr = io::file_reader(testfile).unwrap(); + let rdr = io::file_reader(testfile).get(); while !rdr.eof() { let ln = rdr.read_line(); diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index 970178f05fe08..4a172c9539c2f 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -696,7 +696,7 @@ fn dump_output_file(config: &config, testfile: &Path, out: &str, extension: &str) { let outfile = make_out_name(config, testfile, extension); let writer = - io::file_writer(&outfile, [io::Create, io::Truncate]).unwrap(); + io::file_writer(&outfile, [io::Create, io::Truncate]).get(); writer.write_str(out); } diff --git a/src/libextra/dlist.rs b/src/libextra/dlist.rs index 392eaf2815780..cd37687bb704f 100644 --- a/src/libextra/dlist.rs +++ b/src/libextra/dlist.rs @@ -340,7 +340,7 @@ impl DList { if take_a { it.next(); } else { - it.insert_next_node(other.pop_front_node().unwrap()); + it.insert_next_node(other.pop_front_node().get()); } } } @@ -499,7 +499,7 @@ impl<'self, A> MutDListIterator<'self, A> { None => return self.list.push_front_node(ins_node), Some(prev) => prev, }; - let node_own = prev_node.next.take_unwrap(); + let node_own = prev_node.next.take_get(); ins_node.next = link_with_prev(node_own, Rawlink::some(ins_node)); prev_node.next = link_with_prev(ins_node, Rawlink::some(prev_node)); self.list.length += 1; @@ -634,14 +634,14 @@ mod tests { n.push_front(2); n.push_front(3); { - assert_eq!(n.front().unwrap(), &3); - let x = n.front_mut().unwrap(); + assert_eq!(n.front().get(), &3); + let x = n.front_mut().get(); assert_eq!(*x, 3); *x = 0; } { - assert_eq!(n.back().unwrap(), &2); - let y = n.back_mut().unwrap(); + assert_eq!(n.back().get(), &2); + let y = n.back_mut().get(); assert_eq!(*y, 2); *y = 1; } @@ -750,7 +750,7 @@ mod tests { n.push_front(4); let mut it = n.iter(); assert_eq!(it.size_hint(), (1, Some(1))); - assert_eq!(it.next().unwrap(), &4); + assert_eq!(it.next().get(), &4); assert_eq!(it.size_hint(), (0, Some(0))); assert_eq!(it.next(), None); } @@ -778,11 +778,11 @@ mod tests { n.push_front(6); let mut it = n.iter(); assert_eq!(it.size_hint(), (3, Some(3))); - assert_eq!(it.next().unwrap(), &6); + assert_eq!(it.next().get(), &6); assert_eq!(it.size_hint(), (2, Some(2))); - assert_eq!(it.next_back().unwrap(), &4); + assert_eq!(it.next_back().get(), &4); assert_eq!(it.size_hint(), (1, Some(1))); - assert_eq!(it.next_back().unwrap(), &5); + assert_eq!(it.next_back().get(), &5); assert_eq!(it.next_back(), None); assert_eq!(it.next(), None); } @@ -798,7 +798,7 @@ mod tests { n.push_front(4); let mut it = n.rev_iter(); assert_eq!(it.size_hint(), (1, Some(1))); - assert_eq!(it.next().unwrap(), &4); + assert_eq!(it.next().get(), &4); assert_eq!(it.size_hint(), (0, Some(0))); assert_eq!(it.next(), None); } @@ -833,11 +833,11 @@ mod tests { n.push_front(6); let mut it = n.mut_iter(); assert_eq!(it.size_hint(), (3, Some(3))); - assert_eq!(*it.next().unwrap(), 6); + assert_eq!(*it.next().get(), 6); assert_eq!(it.size_hint(), (2, Some(2))); - assert_eq!(*it.next_back().unwrap(), 4); + assert_eq!(*it.next_back().get(), 4); assert_eq!(it.size_hint(), (1, Some(1))); - assert_eq!(*it.next_back().unwrap(), 5); + assert_eq!(*it.next_back().get(), 5); assert!(it.next_back().is_none()); assert!(it.next().is_none()); } diff --git a/src/libextra/fileinput.rs b/src/libextra/fileinput.rs index 2094259664cf9..cb1e713b7116c 100644 --- a/src/libextra/fileinput.rs +++ b/src/libextra/fileinput.rs @@ -224,7 +224,7 @@ impl FileInput { let path_option = self.fi.files.shift(); let file = match path_option { None => io::stdin(), - Some(ref path) => io::file_reader(path).unwrap() + Some(ref path) => io::file_reader(path).get() }; self.fi.current_reader = Some(file); @@ -417,7 +417,7 @@ mod test { use std::vec; fn make_file(path : &Path, contents: &[~str]) { - let file = io::file_writer(path, [io::Create, io::Truncate]).unwrap(); + let file = io::file_writer(path, [io::Create, io::Truncate]).get(); foreach str in contents.iter() { file.write_str(*str); @@ -565,11 +565,9 @@ mod test { let f2 = Some(Path("tmp/lib-fileinput-test-no-trailing-newline-2.tmp")); - let wr = io::file_writer(f1.get_ref(), - [io::Create, io::Truncate]).unwrap(); + let wr = io::file_writer(f1.get_ref(), [io::Create, io::Truncate]).get(); wr.write_str("1\n2"); - let wr = io::file_writer(f2.get_ref(), - [io::Create, io::Truncate]).unwrap(); + let wr = io::file_writer(f2.get_ref(), [io::Create, io::Truncate]).get(); wr.write_str("3\n4"); let mut lines = ~[]; diff --git a/src/libextra/getopts.rs b/src/libextra/getopts.rs index 31a73833e27ca..9d517165dc640 100644 --- a/src/libextra/getopts.rs +++ b/src/libextra/getopts.rs @@ -196,7 +196,7 @@ fn find_opt(opts: &[Opt], nm: Name) -> Option { * The type returned when the command line does not conform to the * expected format. Pass this value to to get an error message. */ -#[deriving(Clone, Eq)] +#[deriving(Clone, Eq, ToStr)] pub enum Fail_ { ArgumentMissing(~str), UnrecognizedOption(~str), diff --git a/src/libextra/json.rs b/src/libextra/json.rs index a9f4276e79e70..839bdf3c744a6 100644 --- a/src/libextra/json.rs +++ b/src/libextra/json.rs @@ -1511,8 +1511,8 @@ mod tests { // We can't compare the strings directly because the object fields be // printed in a different order. - assert_eq!(a.clone(), from_str(to_str(&a)).unwrap()); - assert_eq!(a.clone(), from_str(to_pretty_str(&a)).unwrap()); + assert_eq!(a.clone(), from_str(to_str(&a)).get()); + assert_eq!(a.clone(), from_str(to_pretty_str(&a)).get()); } #[test] @@ -1631,15 +1631,15 @@ mod tests { #[test] fn test_decode_identifiers() { - let mut decoder = Decoder(from_str("null").unwrap()); + let mut decoder = Decoder(from_str("null").get()); let v: () = Decodable::decode(&mut decoder); assert_eq!(v, ()); - let mut decoder = Decoder(from_str("true").unwrap()); + let mut decoder = Decoder(from_str("true").get()); let v: bool = Decodable::decode(&mut decoder); assert_eq!(v, true); - let mut decoder = Decoder(from_str("false").unwrap()); + let mut decoder = Decoder(from_str("false").get()); let v: bool = Decodable::decode(&mut decoder); assert_eq!(v, false); } @@ -1674,31 +1674,31 @@ mod tests { #[test] fn test_decode_numbers() { - let mut decoder = Decoder(from_str("3").unwrap()); + let mut decoder = Decoder(from_str("3").get()); let v: float = Decodable::decode(&mut decoder); assert_eq!(v, 3f); - let mut decoder = Decoder(from_str("3.1").unwrap()); + let mut decoder = Decoder(from_str("3.1").get()); let v: float = Decodable::decode(&mut decoder); assert_eq!(v, 3.1f); - let mut decoder = Decoder(from_str("-1.2").unwrap()); + let mut decoder = Decoder(from_str("-1.2").get()); let v: float = Decodable::decode(&mut decoder); assert_eq!(v, -1.2f); - let mut decoder = Decoder(from_str("0.4").unwrap()); + let mut decoder = Decoder(from_str("0.4").get()); let v: float = Decodable::decode(&mut decoder); assert_eq!(v, 0.4f); - let mut decoder = Decoder(from_str("0.4e5").unwrap()); + let mut decoder = Decoder(from_str("0.4e5").get()); let v: float = Decodable::decode(&mut decoder); assert_eq!(v, 0.4e5f); - let mut decoder = Decoder(from_str("0.4e15").unwrap()); + let mut decoder = Decoder(from_str("0.4e15").get()); let v: float = Decodable::decode(&mut decoder); assert_eq!(v, 0.4e15f); - let mut decoder = Decoder(from_str("0.4e-01").unwrap()); + let mut decoder = Decoder(from_str("0.4e-01").get()); let v: float = Decodable::decode(&mut decoder); assert_eq!(v, 0.4e-01f); } @@ -1726,39 +1726,39 @@ mod tests { #[test] fn test_decode_str() { - let mut decoder = Decoder(from_str("\"\"").unwrap()); + let mut decoder = Decoder(from_str("\"\"").get()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~""); - let mut decoder = Decoder(from_str("\"foo\"").unwrap()); + let mut decoder = Decoder(from_str("\"foo\"").get()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"foo"); - let mut decoder = Decoder(from_str("\"\\\"\"").unwrap()); + let mut decoder = Decoder(from_str("\"\\\"\"").get()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"\""); - let mut decoder = Decoder(from_str("\"\\b\"").unwrap()); + let mut decoder = Decoder(from_str("\"\\b\"").get()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"\x08"); - let mut decoder = Decoder(from_str("\"\\n\"").unwrap()); + let mut decoder = Decoder(from_str("\"\\n\"").get()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"\n"); - let mut decoder = Decoder(from_str("\"\\r\"").unwrap()); + let mut decoder = Decoder(from_str("\"\\r\"").get()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"\r"); - let mut decoder = Decoder(from_str("\"\\t\"").unwrap()); + let mut decoder = Decoder(from_str("\"\\t\"").get()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"\t"); - let mut decoder = Decoder(from_str("\"\\u12ab\"").unwrap()); + let mut decoder = Decoder(from_str("\"\\u12ab\"").get()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"\u12ab"); - let mut decoder = Decoder(from_str("\"\\uAB12\"").unwrap()); + let mut decoder = Decoder(from_str("\"\\uAB12\"").get()); let v: ~str = Decodable::decode(&mut decoder); assert_eq!(v, ~"\uAB12"); } @@ -1791,27 +1791,27 @@ mod tests { #[test] fn test_decode_list() { - let mut decoder = Decoder(from_str("[]").unwrap()); + let mut decoder = Decoder(from_str("[]").get()); let v: ~[()] = Decodable::decode(&mut decoder); assert_eq!(v, ~[]); - let mut decoder = Decoder(from_str("[null]").unwrap()); + let mut decoder = Decoder(from_str("[null]").get()); let v: ~[()] = Decodable::decode(&mut decoder); assert_eq!(v, ~[()]); - let mut decoder = Decoder(from_str("[true]").unwrap()); + let mut decoder = Decoder(from_str("[true]").get()); let v: ~[bool] = Decodable::decode(&mut decoder); assert_eq!(v, ~[true]); - let mut decoder = Decoder(from_str("[true]").unwrap()); + let mut decoder = Decoder(from_str("[true]").get()); let v: ~[bool] = Decodable::decode(&mut decoder); assert_eq!(v, ~[true]); - let mut decoder = Decoder(from_str("[3, 1]").unwrap()); + let mut decoder = Decoder(from_str("[3, 1]").get()); let v: ~[int] = Decodable::decode(&mut decoder); assert_eq!(v, ~[3, 1]); - let mut decoder = Decoder(from_str("[[3], [1, 2]]").unwrap()); + let mut decoder = Decoder(from_str("[[3], [1, 2]]").get()); let v: ~[~[uint]] = Decodable::decode(&mut decoder); assert_eq!(v, ~[~[3], ~[1, 2]]); } @@ -1866,21 +1866,21 @@ mod tests { col: 8u, msg: @~"EOF while parsing object"})); - assert_eq!(from_str("{}").unwrap(), mk_object([])); - assert_eq!(from_str("{\"a\": 3}").unwrap(), + assert_eq!(from_str("{}").get(), mk_object([])); + assert_eq!(from_str("{\"a\": 3}").get(), mk_object([(~"a", Number(3.0f))])); assert_eq!(from_str( - "{ \"a\": null, \"b\" : true }").unwrap(), + "{ \"a\": null, \"b\" : true }").get(), mk_object([ (~"a", Null), (~"b", Boolean(true))])); - assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").unwrap(), + assert_eq!(from_str("\n{ \"a\": null, \"b\" : true }\n").get(), mk_object([ (~"a", Null), (~"b", Boolean(true))])); assert_eq!(from_str( - "{\"a\" : 1.0 ,\"b\": [ true ]}").unwrap(), + "{\"a\" : 1.0 ,\"b\": [ true ]}").get(), mk_object([ (~"a", Number(1.0)), (~"b", List(~[Boolean(true)])) @@ -1893,7 +1893,7 @@ mod tests { "\"foo\\nbar\", " + "{ \"c\": {\"d\": null} } " + "]" + - "}").unwrap(), + "}").get(), mk_object([ (~"a", Number(1.0f)), (~"b", List(~[ @@ -1913,7 +1913,7 @@ mod tests { { \"a\": null, \"b\": 2, \"c\": [\"abc\", \"xyz\"] } ] }"; - let mut decoder = Decoder(from_str(s).unwrap()); + let mut decoder = Decoder(from_str(s).get()); let v: Outer = Decodable::decode(&mut decoder); assert_eq!( v, @@ -1927,23 +1927,23 @@ mod tests { #[test] fn test_decode_option() { - let mut decoder = Decoder(from_str("null").unwrap()); + let mut decoder = Decoder(from_str("null").get()); let value: Option<~str> = Decodable::decode(&mut decoder); assert_eq!(value, None); - let mut decoder = Decoder(from_str("\"jodhpurs\"").unwrap()); + let mut decoder = Decoder(from_str("\"jodhpurs\"").get()); let value: Option<~str> = Decodable::decode(&mut decoder); assert_eq!(value, Some(~"jodhpurs")); } #[test] fn test_decode_enum() { - let mut decoder = Decoder(from_str("\"Dog\"").unwrap()); + let mut decoder = Decoder(from_str("\"Dog\"").get()); let value: Animal = Decodable::decode(&mut decoder); assert_eq!(value, Dog); let mut decoder = - Decoder(from_str("[\"Frog\",\"Henry\",349]").unwrap()); + Decoder(from_str("[\"Frog\",\"Henry\",349]").get()); let value: Animal = Decodable::decode(&mut decoder); assert_eq!(value, Frog(~"Henry", 349)); } @@ -1951,7 +1951,7 @@ mod tests { #[test] fn test_decode_map() { let s = ~"{\"a\": \"Dog\", \"b\": [\"Frog\", \"Henry\", 349]}"; - let mut decoder = Decoder(from_str(s).unwrap()); + let mut decoder = Decoder(from_str(s).get()); let mut map: TreeMap<~str, Animal> = Decodable::decode(&mut decoder); assert_eq!(map.pop(&~"a"), Some(Dog)); diff --git a/src/libextra/ringbuf.rs b/src/libextra/ringbuf.rs index f3f34a3becc0e..f4e85557fcd61 100644 --- a/src/libextra/ringbuf.rs +++ b/src/libextra/ringbuf.rs @@ -357,9 +357,9 @@ mod tests { d.push_back(137); assert_eq!(d.len(), 4u); debug!(d.front()); - assert_eq!(*d.front().unwrap(), 42); + assert_eq!(*d.front().get(), 42); debug!(d.back()); - assert_eq!(*d.back().unwrap(), 137); + assert_eq!(*d.back().get(), 137); let mut i = d.pop_front(); debug!(i); assert_eq!(i, Some(42)); @@ -658,9 +658,9 @@ mod tests { { let mut it = d.mut_iter(); - assert_eq!(*it.next().unwrap(), 0); - assert_eq!(*it.next().unwrap(), 1); - assert_eq!(*it.next().unwrap(), 2); + assert_eq!(*it.next().get(), 0); + assert_eq!(*it.next().get(), 1); + assert_eq!(*it.next().get(), 2); assert!(it.next().is_none()); } } @@ -681,9 +681,9 @@ mod tests { { let mut it = d.mut_rev_iter(); - assert_eq!(*it.next().unwrap(), 0); - assert_eq!(*it.next().unwrap(), 1); - assert_eq!(*it.next().unwrap(), 2); + assert_eq!(*it.next().get(), 0); + assert_eq!(*it.next().get(), 1); + assert_eq!(*it.next().get(), 2); assert!(it.next().is_none()); } } diff --git a/src/libextra/rl.rs b/src/libextra/rl.rs index 8aff8d388877f..3458e4a7e7142 100644 --- a/src/libextra/rl.rs +++ b/src/libextra/rl.rs @@ -76,7 +76,7 @@ pub unsafe fn complete(cb: CompletionCb) { extern fn callback(line: *c_char, completions: *()) { do local_data::get(complete_key) |cb| { - let cb = **cb.unwrap(); + let cb = **cb.get(); unsafe { do cb(str::raw::from_c_str(line)) |suggestion| { diff --git a/src/libextra/smallintmap.rs b/src/libextra/smallintmap.rs index 8b8e3faaf9a24..93b022ccbcedc 100644 --- a/src/libextra/smallintmap.rs +++ b/src/libextra/smallintmap.rs @@ -407,15 +407,15 @@ mod test_map { let mut it = m.iter(); assert_eq!(it.size_hint(), (0, Some(11))); - assert_eq!(it.next().unwrap(), (0, &1)); + assert_eq!(it.next().get(), (0, &1)); assert_eq!(it.size_hint(), (0, Some(10))); - assert_eq!(it.next().unwrap(), (1, &2)); + assert_eq!(it.next().get(), (1, &2)); assert_eq!(it.size_hint(), (0, Some(9))); - assert_eq!(it.next().unwrap(), (3, &5)); + assert_eq!(it.next().get(), (3, &5)); assert_eq!(it.size_hint(), (0, Some(7))); - assert_eq!(it.next().unwrap(), (6, &10)); + assert_eq!(it.next().get(), (6, &10)); assert_eq!(it.size_hint(), (0, Some(4))); - assert_eq!(it.next().unwrap(), (10, &11)); + assert_eq!(it.next().get(), (10, &11)); assert_eq!(it.size_hint(), (0, Some(0))); assert!(it.next().is_none()); } @@ -451,11 +451,11 @@ mod test_map { } let mut it = m.iter(); - assert_eq!(it.next().unwrap(), (0, &1)); - assert_eq!(it.next().unwrap(), (1, &3)); - assert_eq!(it.next().unwrap(), (3, &8)); - assert_eq!(it.next().unwrap(), (6, &16)); - assert_eq!(it.next().unwrap(), (10, &21)); + assert_eq!(it.next().get(), (0, &1)); + assert_eq!(it.next().get(), (1, &3)); + assert_eq!(it.next().get(), (3, &8)); + assert_eq!(it.next().get(), (6, &16)); + assert_eq!(it.next().get(), (10, &21)); assert!(it.next().is_none()); } @@ -470,11 +470,11 @@ mod test_map { assert!(m.insert(10, 11)); let mut it = m.rev_iter(); - assert_eq!(it.next().unwrap(), (10, &11)); - assert_eq!(it.next().unwrap(), (6, &10)); - assert_eq!(it.next().unwrap(), (3, &5)); - assert_eq!(it.next().unwrap(), (1, &2)); - assert_eq!(it.next().unwrap(), (0, &1)); + assert_eq!(it.next().get(), (10, &11)); + assert_eq!(it.next().get(), (6, &10)); + assert_eq!(it.next().get(), (3, &5)); + assert_eq!(it.next().get(), (1, &2)); + assert_eq!(it.next().get(), (0, &1)); assert!(it.next().is_none()); } @@ -493,11 +493,11 @@ mod test_map { } let mut it = m.iter(); - assert_eq!(it.next().unwrap(), (0, &1)); - assert_eq!(it.next().unwrap(), (1, &3)); - assert_eq!(it.next().unwrap(), (3, &8)); - assert_eq!(it.next().unwrap(), (6, &16)); - assert_eq!(it.next().unwrap(), (10, &21)); + assert_eq!(it.next().get(), (0, &1)); + assert_eq!(it.next().get(), (1, &3)); + assert_eq!(it.next().get(), (3, &8)); + assert_eq!(it.next().get(), (6, &16)); + assert_eq!(it.next().get(), (10, &21)); assert!(it.next().is_none()); } diff --git a/src/libextra/sync.rs b/src/libextra/sync.rs index 276f9cad7c6d0..0055f5614ca50 100644 --- a/src/libextra/sync.rs +++ b/src/libextra/sync.rs @@ -111,7 +111,7 @@ impl Sem { /* do 1000.times { task::yield(); } */ // Need to wait outside the exclusive. if waiter_nobe.is_some() { - let _ = comm::recv_one(waiter_nobe.unwrap()); + let _ = comm::recv_one(waiter_nobe.get()); } } } @@ -216,7 +216,7 @@ impl<'self> Condvar<'self> { state.waiters.signal(); } // Enqueue ourself to be woken up by a signaller. - let SignalEnd = SignalEnd.take_unwrap(); + let SignalEnd = SignalEnd.take_get(); state.blocked[condvar_id].tail.send_deferred(SignalEnd); } else { out_of_bounds = Some(state.blocked.len()); @@ -235,7 +235,7 @@ impl<'self> Condvar<'self> { do (|| { unsafe { do task::rekillable { - let _ = comm::recv_one(WaitEnd.take_unwrap()); + let _ = comm::recv_one(WaitEnd.take_get()); } } }).finally { @@ -295,7 +295,7 @@ impl<'self> Condvar<'self> { } } do check_cvar_bounds(out_of_bounds, condvar_id, "cond.signal_on()") { - let queue = queue.take_unwrap(); + let queue = queue.take_get(); queue.broadcast() } } @@ -1326,7 +1326,7 @@ mod tests { do x.write_downgrade |xwrite| { let mut xopt = Some(xwrite); do y.write_downgrade |_ywrite| { - y.downgrade(xopt.take_unwrap()); + y.downgrade(xopt.take_get()); error!("oops, y.downgrade(x) should have failed!"); } } diff --git a/src/libextra/tempfile.rs b/src/libextra/tempfile.rs index 79b2600369620..0ea9a62150550 100644 --- a/src/libextra/tempfile.rs +++ b/src/libextra/tempfile.rs @@ -37,7 +37,7 @@ mod tests { #[test] fn test_mkdtemp() { - let p = mkdtemp(&Path("."), "foobar").unwrap(); + let p = mkdtemp(&Path("."), "foobar").get(); os::remove_dir(&p); assert!(p.to_str().ends_with("foobar")); } diff --git a/src/libextra/term.rs b/src/libextra/term.rs index 1cfb4f4afa627..b7c59c09f5e52 100644 --- a/src/libextra/term.rs +++ b/src/libextra/term.rs @@ -114,17 +114,17 @@ impl Terminal { return Err(~"TERM environment variable undefined"); } - let entry = open(term.unwrap()); + let entry = open(term.get()); if entry.is_err() { - return Err(entry.unwrap_err()); + return Err(entry.get_err()); } - let ti = parse(entry.unwrap(), false); + let ti = parse(entry.get(), false); if ti.is_err() { - return Err(ti.unwrap_err()); + return Err(ti.get_err()); } - let inf = ti.unwrap(); + let inf = ti.get(); let nc = if inf.strings.find_equiv(&("setaf")).is_some() && inf.strings.find_equiv(&("setab")).is_some() { inf.numbers.find_equiv(&("colors")).map_consume_default(0, |&n| n) @@ -141,13 +141,13 @@ impl Terminal { pub fn fg(&self, color: color::Color) -> bool { let color = self.dim_if_necessary(color); if self.num_colors > color { - let s = expand(*self.ti.strings.find_equiv(&("setaf")).unwrap(), + let s = expand(*self.ti.strings.find_equiv(&("setaf")).get(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { - self.out.write(s.unwrap()); + self.out.write(s.get()); return true } else { - warn!("%s", s.unwrap_err()); + warn!("%s", s.get_err()); } } false @@ -161,13 +161,13 @@ impl Terminal { pub fn bg(&self, color: color::Color) -> bool { let color = self.dim_if_necessary(color); if self.num_colors > color { - let s = expand(*self.ti.strings.find_equiv(&("setab")).unwrap(), + let s = expand(*self.ti.strings.find_equiv(&("setab")).get(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { - self.out.write(s.unwrap()); + self.out.write(s.get()); return true } else { - warn!("%s", s.unwrap_err()); + warn!("%s", s.get_err()); } } false @@ -183,12 +183,12 @@ impl Terminal { let cap = cap_for_attr(attr); let parm = self.ti.strings.find_equiv(&cap); if parm.is_some() { - let s = expand(*parm.unwrap(), [], &mut Variables::new()); + let s = expand(*parm.get(), [], &mut Variables::new()); if s.is_ok() { - self.out.write(s.unwrap()); + self.out.write(s.get()); return true } else { - warn!("%s", s.unwrap_err()); + warn!("%s", s.get_err()); } } false @@ -224,13 +224,13 @@ impl Terminal { expand(*op, [], &mut Variables::new()) }; if s.is_ok() { - self.out.write(s.unwrap()); + self.out.write(s.get()); } else if self.num_colors > 0 { - warn!("%s", s.unwrap_err()); + warn!("%s", s.get_err()); } else { // if we support attributes but not color, it would be nice to still warn!() // but it's not worth testing all known attributes just for this. - debug!("%s", s.unwrap_err()); + debug!("%s", s.get_err()); } } diff --git a/src/libextra/terminfo/parm.rs b/src/libextra/terminfo/parm.rs index 3669c1ea0a357..801a1b706441a 100644 --- a/src/libextra/terminfo/parm.rs +++ b/src/libextra/terminfo/parm.rs @@ -248,7 +248,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables) let flags = Flags::new(); let res = format(stack.pop(), FormatOp::from_char(cur), flags); if res.is_err() { return res } - output.push_all(res.unwrap()) + output.push_all(res.get()) } else { return Err(~"stack is empty") }, ':'|'#'|' '|'.'|'0'..'9' => { let mut flags = Flags::new(); @@ -343,7 +343,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables) (_,'d')|(_,'o')|(_,'x')|(_,'X')|(_,'s') => if stack.len() > 0 { let res = format(stack.pop(), FormatOp::from_char(cur), *flags); if res.is_err() { return res } - output.push_all(res.unwrap()); + output.push_all(res.get()); old_state = state; // will cause state to go to Nothing } else { return Err(~"stack is empty") }, (FormatStateFlags,'#') => { @@ -580,13 +580,13 @@ mod test { #[test] fn test_basic_setabf() { let s = bytes!("\\E[48;5;%p1%dm"); - assert_eq!(expand(s, [Number(1)], &mut Variables::new()).unwrap(), + assert_eq!(expand(s, [Number(1)], &mut Variables::new()).get(), bytes!("\\E[48;5;1m").to_owned()); } #[test] fn test_multiple_int_constants() { - assert_eq!(expand(bytes!("%{1}%{2}%d%d"), [], &mut Variables::new()).unwrap(), + assert_eq!(expand(bytes!("%{1}%{2}%d%d"), [], &mut Variables::new()).get(), bytes!("21").to_owned()); } @@ -612,7 +612,7 @@ mod test { let p = if *cap == "%s" || *cap == "%l" { String(~"foo") } else { Number(97) }; let res = expand((bytes!("%p1")).to_owned() + cap.as_bytes(), [p], vars); assert!(res.is_ok(), - "Op %s failed with 1 stack entry: %s", *cap, res.unwrap_err()); + "Op %s failed with 1 stack entry: %s", *cap, res.get_err()); } let caps = ["%+", "%-", "%*", "%/", "%m", "%&", "%|", "%A", "%O"]; foreach cap in caps.iter() { @@ -624,7 +624,7 @@ mod test { "Binop %s succeeded incorrectly with 1 stack entry", *cap); let res = expand((bytes!("%{1}%{2}")).to_owned() + cap.as_bytes(), [], vars); assert!(res.is_ok(), - "Binop %s failed with 2 stack entries: %s", *cap, res.unwrap_err()); + "Binop %s failed with 2 stack entries: %s", *cap, res.get_err()); } } @@ -639,16 +639,16 @@ mod test { foreach &(op, bs) in v.iter() { let s = fmt!("%%{1}%%{2}%%%c%%d", op); let res = expand(s.as_bytes(), [], &mut Variables::new()); - assert!(res.is_ok(), res.unwrap_err()); - assert_eq!(res.unwrap(), ~['0' as u8 + bs[0]]); + assert!(res.is_ok(), res.get_err()); + assert_eq!(res.get(), ~['0' as u8 + bs[0]]); let s = fmt!("%%{1}%%{1}%%%c%%d", op); let res = expand(s.as_bytes(), [], &mut Variables::new()); - assert!(res.is_ok(), res.unwrap_err()); - assert_eq!(res.unwrap(), ~['0' as u8 + bs[1]]); + assert!(res.is_ok(), res.get_err()); + assert_eq!(res.get(), ~['0' as u8 + bs[1]]); let s = fmt!("%%{2}%%{1}%%%c%%d", op); let res = expand(s.as_bytes(), [], &mut Variables::new()); - assert!(res.is_ok(), res.unwrap_err()); - assert_eq!(res.unwrap(), ~['0' as u8 + bs[2]]); + assert!(res.is_ok(), res.get_err()); + assert_eq!(res.get(), ~['0' as u8 + bs[2]]); } } @@ -657,14 +657,14 @@ mod test { let mut vars = Variables::new(); let s = bytes!("\\E[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m"); let res = expand(s, [Number(1)], &mut vars); - assert!(res.is_ok(), res.unwrap_err()); - assert_eq!(res.unwrap(), bytes!("\\E[31m").to_owned()); + assert!(res.is_ok(), res.get_err()); + assert_eq!(res.get(), bytes!("\\E[31m").to_owned()); let res = expand(s, [Number(8)], &mut vars); - assert!(res.is_ok(), res.unwrap_err()); - assert_eq!(res.unwrap(), bytes!("\\E[90m").to_owned()); + assert!(res.is_ok(), res.get_err()); + assert_eq!(res.get(), bytes!("\\E[90m").to_owned()); let res = expand(s, [Number(42)], &mut vars); - assert!(res.is_ok(), res.unwrap_err()); - assert_eq!(res.unwrap(), bytes!("\\E[38;5;42m").to_owned()); + assert!(res.is_ok(), res.get_err()); + assert_eq!(res.get(), bytes!("\\E[38;5;42m").to_owned()); } #[test] diff --git a/src/libextra/terminfo/searcher.rs b/src/libextra/terminfo/searcher.rs index 175cf836c477d..e6373fdcafee7 100644 --- a/src/libextra/terminfo/searcher.rs +++ b/src/libextra/terminfo/searcher.rs @@ -32,7 +32,7 @@ pub fn get_dbpath_for_term(term: &str) -> Option<~path> { Some(dir) => dirs_to_search.push(path(dir)), None => { if homedir.is_some() { - dirs_to_search.push(homedir.unwrap().push(".terminfo")); // ncurses compatability + dirs_to_search.push(homedir.get().push(".terminfo")); // ncurses compatability } match getenv("TERMINFO_DIRS") { Some(dirs) => foreach i in dirs.split_iter(':') { diff --git a/src/libextra/test.rs b/src/libextra/test.rs index fd5d3fb21b195..5e49a1dfe9fc1 100644 --- a/src/libextra/test.rs +++ b/src/libextra/test.rs @@ -803,7 +803,7 @@ pub fn run_test(force_ignore: bool, task.future_result(|r| { result_future = Some(r) }); task.spawn(testfn_cell.take()); - let task_result = result_future.unwrap().recv(); + let task_result = result_future.get().recv(); let test_result = calc_result(&desc, task_result == task::Success); monitor_ch.send((desc.clone(), test_result)); @@ -867,14 +867,14 @@ impl MetricMap { /// Load MetricDiff from a file. pub fn load(p: &Path) -> MetricMap { assert!(os::path_exists(p)); - let f = io::file_reader(p).unwrap(); + let f = io::file_reader(p).get(); let mut decoder = json::Decoder(json::from_reader(f).get()); MetricMap(Decodable::decode(&mut decoder)) } /// Write MetricDiff to a file. pub fn save(&self, p: &Path) { - let f = io::file_writer(p, [io::Create, io::Truncate]).unwrap(); + let f = io::file_writer(p, [io::Create, io::Truncate]).get(); json::to_pretty_writer(f, &self.to_json()); } diff --git a/src/libextra/time.rs b/src/libextra/time.rs index d95ac6d6c25b4..5a20054ad9fec 100644 --- a/src/libextra/time.rs +++ b/src/libextra/time.rs @@ -1127,13 +1127,13 @@ mod tests { assert!(test("6", "%w")); assert!(test("2009", "%Y")); assert!(test("09", "%y")); - assert!(strptime("UTC", "%Z").unwrap().tm_zone == + assert!(strptime("UTC", "%Z").get().tm_zone == ~"UTC"); - assert!(strptime("PST", "%Z").unwrap().tm_zone == + assert!(strptime("PST", "%Z").get().tm_zone == ~""); - assert!(strptime("-0000", "%z").unwrap().tm_gmtoff == + assert!(strptime("-0000", "%z").get().tm_gmtoff == 0); - assert!(strptime("-0800", "%z").unwrap().tm_gmtoff == + assert!(strptime("-0800", "%z").get().tm_gmtoff == 0); assert!(test("%", "%%")); diff --git a/src/libextra/treemap.rs b/src/libextra/treemap.rs index 82c7bf6caf17d..9f55f9e212b55 100644 --- a/src/libextra/treemap.rs +++ b/src/libextra/treemap.rs @@ -48,7 +48,7 @@ impl Eq for TreeMap { let mut x = self.iter(); let mut y = other.iter(); foreach _ in range(0u, self.len()) { - if x.next().unwrap() != y.next().unwrap() { + if x.next().get() != y.next().get() { return false } } @@ -66,8 +66,8 @@ fn lt(a: &TreeMap, let (a_len, b_len) = (a.len(), b.len()); foreach _ in range(0u, num::min(a_len, b_len)) { - let (key_a, value_a) = x.next().unwrap(); - let (key_b, value_b) = y.next().unwrap(); + let (key_a, value_a) = x.next().get(); + let (key_b, value_b) = y.next().get(); if *key_a < *key_b { return true; } if *key_a > *key_b { return false; } if *value_a < *value_b { return true; } @@ -355,8 +355,8 @@ impl Set for TreeSet { let mut a = x.next(); let mut b = y.next(); while a.is_some() && b.is_some() { - let a1 = a.unwrap(); - let b1 = b.unwrap(); + let a1 = a.get(); + let b1 = b.get(); match a1.cmp(b1) { Less => a = x.next(), Greater => b = y.next(), @@ -383,8 +383,8 @@ impl Set for TreeSet { return false } - let a1 = a.unwrap(); - let b1 = b.unwrap(); + let a1 = a.get(); + let b1 = b.get(); match a1.cmp(b1) { Less => (), @@ -438,11 +438,11 @@ impl TreeSet { while a.is_some() { if b.is_none() { - return f(a.unwrap()) && x.advance(f); + return f(a.get()) && x.advance(f); } - let a1 = a.unwrap(); - let b1 = b.unwrap(); + let a1 = a.get(); + let b1 = b.get(); let cmp = a1.cmp(b1); @@ -468,11 +468,11 @@ impl TreeSet { while a.is_some() { if b.is_none() { - return f(a.unwrap()) && x.advance(f); + return f(a.get()) && x.advance(f); } - let a1 = a.unwrap(); - let b1 = b.unwrap(); + let a1 = a.get(); + let b1 = b.get(); let cmp = a1.cmp(b1); @@ -500,8 +500,8 @@ impl TreeSet { let mut b = y.next(); while a.is_some() && b.is_some() { - let a1 = a.unwrap(); - let b1 = b.unwrap(); + let a1 = a.get(); + let b1 = b.get(); let cmp = a1.cmp(b1); @@ -527,11 +527,11 @@ impl TreeSet { while a.is_some() { if b.is_none() { - return f(a.unwrap()) && x.advance(f); + return f(a.get()) && x.advance(f); } - let a1 = a.unwrap(); - let b1 = b.unwrap(); + let a1 = a.get(); + let b1 = b.get(); let cmp = a1.cmp(b1); @@ -604,7 +604,7 @@ fn mutate_values<'r, K: TotalOrd, V>(node: &'r mut Option<~TreeNode>, // Remove left horizontal link by rotating right fn skew(node: &mut ~TreeNode) { if node.left.map_default(false, |x| x.level == node.level) { - let mut save = node.left.take_unwrap(); + let mut save = node.left.take_get(); swap(&mut node.left, &mut save.right); // save.right now None swap(node, &mut save); node.right = Some(save); @@ -616,7 +616,7 @@ fn skew(node: &mut ~TreeNode) { fn split(node: &mut ~TreeNode) { if node.right.map_default(false, |x| x.right.map_default(false, |y| y.level == node.level)) { - let mut save = node.right.take_unwrap(); + let mut save = node.right.take_get(); swap(&mut node.right, &mut save.left); // save.left now None save.level += 1; swap(node, &mut save); @@ -695,7 +695,7 @@ fn remove(node: &mut Option<~TreeNode>, Equal => { if save.left.is_some() { if save.right.is_some() { - let mut left = save.left.take_unwrap(); + let mut left = save.left.take_get(); if left.right.is_some() { heir_swap(save, &mut left.right); } else { @@ -705,13 +705,13 @@ fn remove(node: &mut Option<~TreeNode>, save.left = Some(left); (remove(&mut save.left, key), true) } else { - let new = save.left.take_unwrap(); + let new = save.left.take_get(); let ~TreeNode{value, _} = replace(save, new); - *save = save.left.take_unwrap(); + *save = save.left.take_get(); (Some(value), true) } } else if save.right.is_some() { - let new = save.right.take_unwrap(); + let new = save.right.take_get(); let ~TreeNode{value, _} = replace(save, new); (Some(value), true) } else { @@ -827,7 +827,7 @@ mod test_treemap { assert!(m.insert(5, 2)); assert!(m.insert(2, 9)); assert!(!m.insert(2, 11)); - assert_eq!(m.find(&2).unwrap(), &11); + assert_eq!(m.find(&2).get(), &11); } #[test] @@ -865,7 +865,7 @@ mod test_treemap { assert_eq!(ctrl.is_empty(), map.is_empty()); foreach x in ctrl.iter() { let &(ref k, ref v) = x; - assert!(map.find(k).unwrap() == v) + assert!(map.find(k).get() == v) } foreach (map_k, map_v) in map.iter() { let mut found = false; @@ -1077,11 +1077,11 @@ mod test_treemap { let m = m; let mut a = m.iter(); - assert_eq!(a.next().unwrap(), (&x1, &y1)); - assert_eq!(a.next().unwrap(), (&x2, &y2)); - assert_eq!(a.next().unwrap(), (&x3, &y3)); - assert_eq!(a.next().unwrap(), (&x4, &y4)); - assert_eq!(a.next().unwrap(), (&x5, &y5)); + assert_eq!(a.next().get(), (&x1, &y1)); + assert_eq!(a.next().get(), (&x2, &y2)); + assert_eq!(a.next().get(), (&x3, &y3)); + assert_eq!(a.next().get(), (&x4, &y4)); + assert_eq!(a.next().get(), (&x5, &y5)); assert!(a.next().is_none()); @@ -1382,10 +1382,10 @@ mod test_set { // FIXME: #5801: this needs a type hint to compile... let result: Option<(&uint, & &'static str)> = z.next(); - assert_eq!(result.unwrap(), (&5u, & &"bar")); + assert_eq!(result.get(), (&5u, & &"bar")); let result: Option<(&uint, & &'static str)> = z.next(); - assert_eq!(result.unwrap(), (&11u, & &"foo")); + assert_eq!(result.get(), (&11u, & &"foo")); let result: Option<(&uint, & &'static str)> = z.next(); assert!(result.is_none()); diff --git a/src/libextra/url.rs b/src/libextra/url.rs index 9b4bf9d0ad4d8..4dfe0c1c8478b 100644 --- a/src/libextra/url.rs +++ b/src/libextra/url.rs @@ -729,21 +729,21 @@ fn test_split_char_first() { #[test] fn test_get_authority() { let (u, h, p, r) = get_authority( - "//user:pass@rust-lang.org/something").unwrap(); + "//user:pass@rust-lang.org/something").get(); assert_eq!(u, Some(UserInfo::new(~"user", Some(~"pass")))); assert_eq!(h, ~"rust-lang.org"); assert!(p.is_none()); assert_eq!(r, ~"/something"); let (u, h, p, r) = get_authority( - "//rust-lang.org:8000?something").unwrap(); + "//rust-lang.org:8000?something").get(); assert!(u.is_none()); assert_eq!(h, ~"rust-lang.org"); assert_eq!(p, Some(~"8000")); assert_eq!(r, ~"?something"); let (u, h, p, r) = get_authority( - "//rust-lang.org#blah").unwrap(); + "//rust-lang.org#blah").get(); assert!(u.is_none()); assert_eq!(h, ~"rust-lang.org"); assert!(p.is_none()); @@ -751,17 +751,17 @@ fn test_get_authority() { // ipv6 tests let (_, h, _, _) = get_authority( - "//2001:0db8:85a3:0042:0000:8a2e:0370:7334#blah").unwrap(); + "//2001:0db8:85a3:0042:0000:8a2e:0370:7334#blah").get(); assert_eq!(h, ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334"); let (_, h, p, _) = get_authority( - "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah").unwrap(); + "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah").get(); assert_eq!(h, ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334"); assert_eq!(p, Some(~"8000")); let (u, h, p, _) = get_authority( "//us:p@2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000#blah" - ).unwrap(); + ).get(); assert_eq!(u, Some(UserInfo::new(~"us", Some(~"p")))); assert_eq!(h, ~"2001:0db8:85a3:0042:0000:8a2e:0370:7334"); assert_eq!(p, Some(~"8000")); @@ -775,21 +775,21 @@ fn test_get_authority() { "//2001:0db8:85a3:0042:0000:8a2e:0370:7334:8000:00").is_err()); // these parse as empty, because they don't start with '//' - let (_, h, _, _) = get_authority("user:pass@rust-lang").unwrap(); + let (_, h, _, _) = get_authority("user:pass@rust-lang").get(); assert_eq!(h, ~""); - let (_, h, _, _) = get_authority("rust-lang.org").unwrap(); + let (_, h, _, _) = get_authority("rust-lang.org").get(); assert_eq!(h, ~""); } #[test] fn test_get_path() { - let (p, r) = get_path("/something+%20orother", true).unwrap(); + let (p, r) = get_path("/something+%20orother", true).get(); assert_eq!(p, ~"/something+ orother"); assert_eq!(r, ~""); - let (p, r) = get_path("test@email.com#fragment", false).unwrap(); + let (p, r) = get_path("test@email.com#fragment", false).get(); assert_eq!(p, ~"test@email.com"); assert_eq!(r, ~"#fragment"); - let (p, r) = get_path("/gen/:addr=?q=v", false).unwrap(); + let (p, r) = get_path("/gen/:addr=?q=v", false).get(); assert_eq!(p, ~"/gen/:addr="); assert_eq!(r, ~"?q=v"); @@ -809,7 +809,7 @@ mod tests { let url = ~"http://user:pass@rust-lang.org/doc?s=v#something"; let up = from_str(url); - let u = up.unwrap(); + let u = up.get(); assert!(u.scheme == ~"http"); let userinfo = u.user.get_ref(); assert!(userinfo.user == ~"user"); @@ -823,7 +823,7 @@ mod tests { #[test] fn test_url_parse_host_slash() { let urlstr = ~"http://0.42.42.42/"; - let url = from_str(urlstr).unwrap(); + let url = from_str(urlstr).get(); assert!(url.host == ~"0.42.42.42"); assert!(url.path == ~"/"); } @@ -831,14 +831,14 @@ mod tests { #[test] fn test_url_with_underscores() { let urlstr = ~"http://dotcom.com/file_name.html"; - let url = from_str(urlstr).unwrap(); + let url = from_str(urlstr).get(); assert!(url.path == ~"/file_name.html"); } #[test] fn test_url_with_dashes() { let urlstr = ~"http://dotcom.com/file-name.html"; - let url = from_str(urlstr).unwrap(); + let url = from_str(urlstr).get(); assert!(url.path == ~"/file-name.html"); } @@ -856,62 +856,62 @@ mod tests { #[test] fn test_full_url_parse_and_format() { let url = ~"http://user:pass@rust-lang.org/doc?s=v#something"; - assert_eq!(from_str(url).unwrap().to_str(), url); + assert_eq!(from_str(url).get().to_str(), url); } #[test] fn test_userless_url_parse_and_format() { let url = ~"http://rust-lang.org/doc?s=v#something"; - assert_eq!(from_str(url).unwrap().to_str(), url); + assert_eq!(from_str(url).get().to_str(), url); } #[test] fn test_queryless_url_parse_and_format() { let url = ~"http://user:pass@rust-lang.org/doc#something"; - assert_eq!(from_str(url).unwrap().to_str(), url); + assert_eq!(from_str(url).get().to_str(), url); } #[test] fn test_empty_query_url_parse_and_format() { let url = ~"http://user:pass@rust-lang.org/doc?#something"; let should_be = ~"http://user:pass@rust-lang.org/doc#something"; - assert_eq!(from_str(url).unwrap().to_str(), should_be); + assert_eq!(from_str(url).get().to_str(), should_be); } #[test] fn test_fragmentless_url_parse_and_format() { let url = ~"http://user:pass@rust-lang.org/doc?q=v"; - assert_eq!(from_str(url).unwrap().to_str(), url); + assert_eq!(from_str(url).get().to_str(), url); } #[test] fn test_minimal_url_parse_and_format() { let url = ~"http://rust-lang.org/doc"; - assert_eq!(from_str(url).unwrap().to_str(), url); + assert_eq!(from_str(url).get().to_str(), url); } #[test] fn test_scheme_host_only_url_parse_and_format() { let url = ~"http://rust-lang.org"; - assert_eq!(from_str(url).unwrap().to_str(), url); + assert_eq!(from_str(url).get().to_str(), url); } #[test] fn test_pathless_url_parse_and_format() { let url = ~"http://user:pass@rust-lang.org?q=v#something"; - assert_eq!(from_str(url).unwrap().to_str(), url); + assert_eq!(from_str(url).get().to_str(), url); } #[test] fn test_scheme_host_fragment_only_url_parse_and_format() { let url = ~"http://rust-lang.org#something"; - assert_eq!(from_str(url).unwrap().to_str(), url); + assert_eq!(from_str(url).get().to_str(), url); } #[test] fn test_url_component_encoding() { let url = ~"http://rust-lang.org/doc%20uments?ba%25d%20=%23%26%2B"; - let u = from_str(url).unwrap(); + let u = from_str(url).get(); assert!(u.path == ~"/doc uments"); assert!(u.query == ~[(~"ba%d ", ~"#&+")]); } @@ -919,7 +919,7 @@ mod tests { #[test] fn test_url_without_authority() { let url = ~"mailto:test@email.com"; - assert_eq!(from_str(url).unwrap().to_str(), url); + assert_eq!(from_str(url).get().to_str(), url); } #[test] diff --git a/src/libextra/workcache.rs b/src/libextra/workcache.rs index d28407a984a01..3aefeed626f6d 100644 --- a/src/libextra/workcache.rs +++ b/src/libextra/workcache.rs @@ -206,7 +206,7 @@ fn json_encode>(t: &T) -> ~str { // FIXME(#5121) fn json_decode>(s: &str) -> T { do io::with_str_reader(s) |rdr| { - let j = json::from_reader(rdr).unwrap(); + let j = json::from_reader(rdr).get(); let mut decoder = json::Decoder(j); Decodable::decode(&mut decoder) } @@ -321,7 +321,7 @@ impl<'self> Prep<'self> { _ => { let (port, chan) = oneshot(); - let blk = bo.take_unwrap(); + let blk = bo.take_get(); let chan = Cell::new(chan); do task::spawn { diff --git a/src/librust/rust.rs b/src/librust/rust.rs index 0d2148c4a1233..f4cc1c499cd21 100644 --- a/src/librust/rust.rs +++ b/src/librust/rust.rs @@ -162,7 +162,7 @@ fn cmd_help(args: &[~str]) -> ValidUsage { fn cmd_test(args: &[~str]) -> ValidUsage { match args { [ref filename] => { - let test_exec = Path(*filename).filestem().unwrap() + "test~"; + let test_exec = Path(*filename).filestem().get() + "test~"; invoke("rustc", &[~"--test", filename.to_owned(), ~"-o", test_exec.to_owned()], rustc::main); let exit_code = run::process_status(~"./" + test_exec, []); @@ -175,7 +175,7 @@ fn cmd_test(args: &[~str]) -> ValidUsage { fn cmd_run(args: &[~str]) -> ValidUsage { match args { [ref filename, ..prog_args] => { - let exec = Path(*filename).filestem().unwrap() + "~"; + let exec = Path(*filename).filestem().get() + "~"; invoke("rustc", &[filename.to_owned(), ~"-o", exec.to_owned()], rustc::main); let exit_code = run::process_status(~"./"+exec, prog_args); diff --git a/src/librustc/back/passes.rs b/src/librustc/back/passes.rs index 831719135b13d..16b66e83bd71d 100644 --- a/src/librustc/back/passes.rs +++ b/src/librustc/back/passes.rs @@ -47,7 +47,7 @@ impl PassManager { } pub fn add_pass_from_name(&mut self, name:&str) { - let pass = create_pass(name).unwrap(); + let pass = create_pass(name).get(); self.add_pass(pass); } diff --git a/src/librustc/middle/resolve.rs b/src/librustc/middle/resolve.rs index 5a70f251aca46..45119d9154c42 100644 --- a/src/librustc/middle/resolve.rs +++ b/src/librustc/middle/resolve.rs @@ -1030,7 +1030,7 @@ impl Resolver { if (duplicate_type != NoError) { // Return an error here by looking up the namespace that // had the duplicate. - let ns = ns.unwrap(); + let ns = ns.get(); self.session.span_err(sp, fmt!("duplicate definition of %s `%s`", namespace_error_to_str(duplicate_type), diff --git a/src/librustc/middle/trans/adt.rs b/src/librustc/middle/trans/adt.rs index 6c37fd18f69e8..09e44fb663360 100644 --- a/src/librustc/middle/trans/adt.rs +++ b/src/librustc/middle/trans/adt.rs @@ -165,7 +165,7 @@ fn represent_type_uncached(cx: &mut CrateContext, t: ty::t) -> Repr { if cases.iter().all(|c| c.tys.len() == 0) { // All bodies empty -> intlike let discrs = cases.map(|c| c.discr); - return CEnum(*discrs.iter().min().unwrap(), *discrs.iter().max().unwrap()); + return CEnum(*discrs.iter().min().get(), *discrs.iter().max().get()); } if cases.len() == 1 { @@ -508,7 +508,7 @@ pub fn trans_const(ccx: &mut CrateContext, r: &Repr, discr: uint, } General(ref cases) => { let case = &cases[discr]; - let max_sz = cases.iter().transform(|x| x.size).max().unwrap(); + let max_sz = cases.iter().transform(|x| x.size).max().get(); let discr_ty = C_uint(ccx, discr); let contents = build_const_struct(ccx, case, ~[discr_ty] + vals); diff --git a/src/librustc/middle/trans/base.rs b/src/librustc/middle/trans/base.rs index e0a7cd8cc0b57..f81291e7e1a0c 100644 --- a/src/librustc/middle/trans/base.rs +++ b/src/librustc/middle/trans/base.rs @@ -94,7 +94,7 @@ static task_local_insn_key: local_data::Key<@~[&'static str]> = &local_data::Key pub fn with_insn_ctxt(blk: &fn(&[&'static str])) { let opt = local_data::get(task_local_insn_key, |k| k.map(|&k| *k)); if opt.is_some() { - blk(*opt.unwrap()); + blk(*opt.get()); } } @@ -2296,7 +2296,7 @@ pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool { // runtime rust_start function pub fn create_entry_wrapper(ccx: @mut CrateContext, _sp: span, main_llfn: ValueRef) { - let et = ccx.sess.entry_type.unwrap(); + let et = ccx.sess.entry_type.get(); if et == session::EntryMain { let llfn = create_main(ccx, main_llfn); create_entry_fn(ccx, llfn, true); diff --git a/src/librustc/middle/trans/reflect.rs b/src/librustc/middle/trans/reflect.rs index 93b2e8a6665df..fecadcd92c599 100644 --- a/src/librustc/middle/trans/reflect.rs +++ b/src/librustc/middle/trans/reflect.rs @@ -279,7 +279,7 @@ impl Reflector { let repr = adt::represent_type(bcx.ccx(), t); let variants = ty::substd_enum_variants(ccx.tcx, did, substs); let llptrty = type_of(ccx, t).ptr_to(); - let opaquety = ty::get_opaque_ty(ccx.tcx).unwrap(); + let opaquety = ty::get_opaque_ty(ccx.tcx).get(); let opaqueptrty = ty::mk_ptr(ccx.tcx, ty::mt { ty: opaquety, mutbl: ast::m_imm }); let make_get_disr = || { @@ -380,7 +380,7 @@ pub fn emit_calls_to_trait_visit_ty(bcx: @mut Block, visitor_trait_id: def_id) -> @mut Block { let final = sub_block(bcx, "final"); - let tydesc_ty = ty::get_tydesc_ty(bcx.ccx().tcx).unwrap(); + let tydesc_ty = ty::get_tydesc_ty(bcx.ccx().tcx).get(); let tydesc_ty = type_of(bcx.ccx(), tydesc_ty); let mut r = Reflector { visitor_val: visitor_val, diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index bfab8e26132e7..a2724e6882f23 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -33,6 +33,7 @@ use std::hashmap::{HashMap, HashSet}; 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::*; @@ -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 @@ impl Region { } } -#[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 { 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), @@ -674,7 +684,7 @@ pub struct ParamBounds { pub type BuiltinBounds = EnumSet; -#[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) diff --git a/src/librustc/middle/typeck/rscope.rs b/src/librustc/middle/typeck/rscope.rs index 16740d3ce4e5a..020ef30e34c58 100644 --- a/src/librustc/middle/typeck/rscope.rs +++ b/src/librustc/middle/typeck/rscope.rs @@ -18,6 +18,7 @@ use syntax::opt_vec::OptVec; use syntax::opt_vec; use syntax::parse::token::special_idents; +#[deriving(ToStr)] pub struct RegionError { msg: ~str, replacement: ty::Region diff --git a/src/librustc/util/enum_set.rs b/src/librustc/util/enum_set.rs index 2466c373f23b4..ced29f18f7f11 100644 --- a/src/librustc/util/enum_set.rs +++ b/src/librustc/util/enum_set.rs @@ -10,7 +10,7 @@ use std::iterator::Iterator; -#[deriving(Clone, Eq, IterBytes)] +#[deriving(Clone, Eq, IterBytes, ToStr)] pub struct EnumSet { // We must maintain the invariant that no bits are set // for which no variant exists diff --git a/src/librustdoc/page_pass.rs b/src/librustdoc/page_pass.rs index 82a4724496dd1..e882a22d9ed3d 100644 --- a/src/librustdoc/page_pass.rs +++ b/src/librustdoc/page_pass.rs @@ -66,7 +66,7 @@ fn make_doc_from_pages(page_port: &PagePort) -> doc::Doc { loop { let val = page_port.recv(); if val.is_some() { - pages.push(val.unwrap()); + pages.push(val.get()); } else { break; } diff --git a/src/librustdoc/prune_private_pass.rs b/src/librustdoc/prune_private_pass.rs index 6f3f91f3c65de..ffc3cdbd8ee17 100644 --- a/src/librustdoc/prune_private_pass.rs +++ b/src/librustdoc/prune_private_pass.rs @@ -85,7 +85,7 @@ fn strip_priv_methods( extract::to_str(m.ident) == method.name }; assert!(ast_method.is_some()); - let ast_method = ast_method.unwrap(); + let ast_method = ast_method.get(); match ast_method.vis { ast::public => true, ast::private => false, diff --git a/src/librustdoc/sectionalize_pass.rs b/src/librustdoc/sectionalize_pass.rs index da73027a4abc0..4c0e0d7af2aa9 100644 --- a/src/librustdoc/sectionalize_pass.rs +++ b/src/librustdoc/sectionalize_pass.rs @@ -141,7 +141,7 @@ fn sectionalize(desc: Option<~str>) -> (Option<~str>, ~[doc::Section]) { } if current_section.is_some() { - sections.push(current_section.unwrap()); + sections.push(current_section.get()); } (new_desc, sections) diff --git a/src/librustpkg/tests.rs b/src/librustpkg/tests.rs index 6b174836a68dc..6ab8547d733d3 100644 --- a/src/librustpkg/tests.rs +++ b/src/librustpkg/tests.rs @@ -72,7 +72,7 @@ fn git_repo_pkg_with_tag(a_tag: ~str) -> PkgId { } fn writeFile(file_path: &Path, contents: &str) { - let out = io::file_writer(file_path, [io::Create, io::Truncate]).unwrap(); + let out = io::file_writer(file_path, [io::Create, io::Truncate]).get(); out.write_line(contents); } diff --git a/src/libstd/cell.rs b/src/libstd/cell.rs index 5a0c781fe9a87..f602102c01cb7 100644 --- a/src/libstd/cell.rs +++ b/src/libstd/cell.rs @@ -46,7 +46,7 @@ impl Cell { fail!("attempt to take an empty cell"); } - this.value.take_unwrap() + this.value.take_get() } /// Returns the value, failing if the cell is full. diff --git a/src/libstd/comm.rs b/src/libstd/comm.rs index a0731dc3494c2..e68b2e029fc50 100644 --- a/src/libstd/comm.rs +++ b/src/libstd/comm.rs @@ -179,7 +179,7 @@ impl GenericChan for SharedChan { unsafe { let mut xx = Some(x); do chan.with_imm |chan| { - chan.send(xx.take_unwrap()) + chan.send(xx.take_get()) } } } @@ -195,7 +195,7 @@ impl GenericSmartChan for SharedChan { unsafe { let mut xx = Some(x); do chan.with_imm |chan| { - chan.try_send(xx.take_unwrap()) + chan.try_send(xx.take_get()) } } } @@ -469,7 +469,7 @@ mod pipesy { if message.is_none() { None } else { - let oneshot::send(message) = message.unwrap(); + let oneshot::send(message) = message.get(); Some(message) } } @@ -586,7 +586,7 @@ mod pipesy { fn send(&self, x: T) { unsafe { let self_endp = transmute_mut(&self.endp); - *self_endp = Some(streamp::client::data(self_endp.take_unwrap(), x)) + *self_endp = Some(streamp::client::data(self_endp.take_get(), x)) } } } @@ -596,7 +596,7 @@ mod pipesy { fn try_send(&self, x: T) -> bool { unsafe { let self_endp = transmute_mut(&self.endp); - match streamp::client::try_data(self_endp.take_unwrap(), x) { + match streamp::client::try_data(self_endp.take_get(), x) { Some(next) => { *self_endp = Some(next); true @@ -613,7 +613,7 @@ mod pipesy { unsafe { let self_endp = transmute_mut(&self.endp); let endp = self_endp.take(); - let streamp::data(x, endp) = recv(endp.unwrap()); + let streamp::data(x, endp) = recv(endp.get()); *self_endp = Some(endp); x } @@ -624,7 +624,7 @@ mod pipesy { unsafe { let self_endp = transmute_mut(&self.endp); let endp = self_endp.take(); - match try_recv(endp.unwrap()) { + match try_recv(endp.get()) { Some(streamp::data(x, endp)) => { *self_endp = Some(endp); Some(x) diff --git a/src/libstd/either.rs b/src/libstd/either.rs index d0378fa947b2b..cc17b3cef14f3 100644 --- a/src/libstd/either.rs +++ b/src/libstd/either.rs @@ -23,29 +23,102 @@ use str::StrSlice; 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 { - Left(T), - Right(U) +pub enum Either { + 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(f_left: &fn(&T) -> V, - f_right: &fn(&U) -> V, value: &Either) -> V { - match *value { - Left(ref l) => f_left(l), - Right(ref r) => f_right(r) +impl Either { + /// 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(&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 { + 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 { + 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 get_left(self) -> L { + self.expect_left("called Either::get_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 get_right(self) -> R { + self.expect_right("called Either::get_right()` on `Left` value") } } +// FIXME: #8228 Replaceable by an external iterator? /// Extracts from a vector of either all the left values -pub fn lefts(eithers: &[Either]) -> ~[T] { +pub fn lefts(eithers: &[Either]) -> ~[L] { do vec::build_sized(eithers.len()) |push| { foreach elt in eithers.iter() { match *elt { @@ -56,8 +129,9 @@ pub fn lefts(eithers: &[Either]) -> ~[T] { } } +// FIXME: #8228 Replaceable by an external iterator? /// Extracts from a vector of either all the right values -pub fn rights(eithers: &[Either]) -> ~[U] { +pub fn rights(eithers: &[Either]) -> ~[R] { do vec::build_sized(eithers.len()) |push| { foreach elt in eithers.iter() { match *elt { @@ -68,13 +142,14 @@ pub fn rights(eithers: &[Either]) -> ~[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(eithers: ~[Either]) -> (~[T], ~[U]) { - let mut lefts: ~[T] = ~[]; - let mut rights: ~[U] = ~[]; +pub fn partition(eithers: ~[Either]) -> (~[L], ~[R]) { + let mut lefts: ~[L] = ~[]; + let mut rights: ~[R] = ~[]; foreach elt in eithers.consume_iter() { match elt { Left(l) => lefts.push(l), @@ -84,196 +159,101 @@ pub fn partition(eithers: ~[Either]) -> (~[T], ~[U]) { return (lefts, rights); } -/// Flips between left and right of a given either -#[inline] -pub fn flip(eith: Either) -> Either { - 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(eith: Either) -> Result { - 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(eith: &Either) -> 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(eith: &Either) -> 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(eith: Either, reason: &str) -> T { - match eith { - Left(x) => x, - Right(_) => fail!(reason.to_owned()) + #[test] + fn test_lefts_none() { + let input: ~[Either] = ~[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(eith: Either) -> 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(eith: Either, reason: &str) -> U { - match eith { - Right(x) => x, - Left(_) => fail!(reason.to_owned()) + #[test] + fn test_lefts_empty() { + let input: ~[Either] = ~[]; + 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(eith: Either) -> U { - expect_right(eith, "either::unwrap_right Left") -} - -impl Either { - #[inline] - pub fn either(&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 { flip(self) } - - #[inline] - pub fn to_result(self) -> Result { 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] = ~[Right(10), Right(10)]; - let result = lefts(input); - assert_eq!(result.len(), 0u); -} - -#[test] -fn test_lefts_empty() { - let input: ~[Either] = ~[]; - 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] = ~[Left(10), Left(10)]; + let result = rights(input); + assert_eq!(result.len(), 0u); + } -#[test] -fn test_rights_none() { - let input: ~[Either] = ~[Left(10), Left(10)]; - let result = rights(input); - assert_eq!(result.len(), 0u); -} + #[test] + fn test_rights_empty() { + let input: ~[Either] = ~[]; + let result = rights(input); + assert_eq!(result.len(), 0u); + } -#[test] -fn test_rights_empty() { - let input: ~[Either] = ~[]; - 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] = ~[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] = ~[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] = ~[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] = ~[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] = ~[]; + let (lefts, rights) = partition(input); + assert_eq!(lefts.len(), 0u); + assert_eq!(rights.len(), 0u); + } -#[test] -fn test_partition_empty() { - let input: ~[Either] = ~[]; - let (lefts, rights) = partition(input); - assert_eq!(lefts.len(), 0u); - assert_eq!(rights.len(), 0u); } diff --git a/src/libstd/io.rs b/src/libstd/io.rs index 606c958b4085e..c2d16d28cae75 100644 --- a/src/libstd/io.rs +++ b/src/libstd/io.rs @@ -1860,10 +1860,10 @@ mod tests { ~"A hoopy frood who really knows where his towel is."; debug!(frood.clone()); { - let out = io::file_writer(tmpfile, [io::Create, io::Truncate]).unwrap(); + let out = io::file_writer(tmpfile, [io::Create, io::Truncate]).get(); out.write_str(frood); } - let inp = io::file_reader(tmpfile).unwrap(); + let inp = io::file_reader(tmpfile).get(); let frood2: ~str = inp.read_c_str(); debug!(frood2.clone()); assert_eq!(frood, frood2); @@ -1876,18 +1876,18 @@ mod tests { { // create empty, enough to reproduce a problem - io::file_writer(&path, [io::Create]).unwrap(); + io::file_writer(&path, [io::Create]).get(); } { - let file = io::file_reader(&path).unwrap(); + let file = io::file_reader(&path).get(); do file.each_byte() |_| { fail!("must be empty") }; } { - let file = io::file_reader(&path).unwrap(); + let file = io::file_reader(&path).get(); do file.each_char() |_| { fail!("must be empty") }; @@ -1986,9 +1986,9 @@ mod tests { fn test_read_buffer_too_small() { let path = &Path("tmp/lib-io-test-read-buffer-too-small.tmp"); // ensure the file exists - io::file_writer(path, [io::Create]).unwrap(); + io::file_writer(path, [io::Create]).get(); - let file = io::file_reader(path).unwrap(); + let file = io::file_reader(path).get(); let mut buf = vec::from_elem(5, 0u8); file.read(buf, 6); // this should fail because buf is too small } @@ -1997,9 +1997,9 @@ mod tests { fn test_read_buffer_big_enough() { let path = &Path("tmp/lib-io-test-read-buffer-big-enough.tmp"); // ensure the file exists - io::file_writer(path, [io::Create]).unwrap(); + io::file_writer(path, [io::Create]).get(); - let file = io::file_reader(path).unwrap(); + let file = io::file_reader(path).get(); let mut buf = vec::from_elem(5, 0u8); file.read(buf, 4); // this should succeed because buf is big enough } @@ -2007,7 +2007,7 @@ mod tests { #[test] fn test_write_empty() { let file = io::file_writer(&Path("tmp/lib-io-test-write-empty.tmp"), - [io::Create]).unwrap(); + [io::Create]).get(); file.write([]); } @@ -2053,7 +2053,7 @@ mod tests { // write the ints to the file { - let file = io::file_writer(&path, [io::Create]).unwrap(); + let file = io::file_writer(&path, [io::Create]).get(); foreach i in uints.iter() { file.write_le_u64(*i); } @@ -2061,7 +2061,7 @@ mod tests { // then read them back and check that they are the same { - let file = io::file_reader(&path).unwrap(); + let file = io::file_reader(&path).get(); foreach i in uints.iter() { assert_eq!(file.read_le_u64(), *i); } @@ -2075,7 +2075,7 @@ mod tests { // write the ints to the file { - let file = io::file_writer(&path, [io::Create]).unwrap(); + let file = io::file_writer(&path, [io::Create]).get(); foreach i in uints.iter() { file.write_be_u64(*i); } @@ -2083,7 +2083,7 @@ mod tests { // then read them back and check that they are the same { - let file = io::file_reader(&path).unwrap(); + let file = io::file_reader(&path).get(); foreach i in uints.iter() { assert_eq!(file.read_be_u64(), *i); } @@ -2097,7 +2097,7 @@ mod tests { // write the ints to the file { - let file = io::file_writer(&path, [io::Create]).unwrap(); + let file = io::file_writer(&path, [io::Create]).get(); foreach i in ints.iter() { file.write_be_i32(*i); } @@ -2105,7 +2105,7 @@ mod tests { // then read them back and check that they are the same { - let file = io::file_reader(&path).unwrap(); + let file = io::file_reader(&path).get(); foreach i in ints.iter() { // this tests that the sign extension is working // (comparing the values as i32 would not test this) @@ -2121,12 +2121,12 @@ mod tests { let buf = ~[0x41, 0x02, 0x00, 0x00]; { - let file = io::file_writer(&path, [io::Create]).unwrap(); + let file = io::file_writer(&path, [io::Create]).get(); file.write(buf); } { - let file = io::file_reader(&path).unwrap(); + let file = io::file_reader(&path).get(); let f = file.read_be_f32(); assert_eq!(f, 8.1250); } @@ -2138,13 +2138,13 @@ mod tests { let f:f32 = 8.1250; { - let file = io::file_writer(&path, [io::Create]).unwrap(); + let file = io::file_writer(&path, [io::Create]).get(); file.write_be_f32(f); file.write_le_f32(f); } { - let file = io::file_reader(&path).unwrap(); + let file = io::file_reader(&path).get(); assert_eq!(file.read_be_f32(), 8.1250); assert_eq!(file.read_le_f32(), 8.1250); } diff --git a/src/libstd/iterator.rs b/src/libstd/iterator.rs index 3b8298414843c..8ddadfe239e72 100644 --- a/src/libstd/iterator.rs +++ b/src/libstd/iterator.rs @@ -448,7 +448,7 @@ pub trait IteratorUtil { /// /// ~~~ {.rust} /// let xs = [-3, 0, 1, 5, -10]; - /// assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10); + /// assert_eq!(*xs.iter().max_by(|x| x.abs()).get(), -10); /// ~~~ fn max_by(&mut self, f: &fn(&A) -> B) -> Option; @@ -458,7 +458,7 @@ pub trait IteratorUtil { /// /// ~~~ {.rust} /// let xs = [-3, 0, 1, 5, -10]; - /// assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0); + /// assert_eq!(*xs.iter().min_by(|x| x.abs()).get(), 0); /// ~~~ fn min_by(&mut self, f: &fn(&A) -> B) -> Option; } @@ -1746,15 +1746,15 @@ mod tests { fn test_iterator_nth() { let v = &[0, 1, 2, 3, 4]; foreach i in range(0u, v.len()) { - assert_eq!(v.iter().nth(i).unwrap(), &v[i]); + assert_eq!(v.iter().nth(i).get(), &v[i]); } } #[test] fn test_iterator_last() { let v = &[0, 1, 2, 3, 4]; - assert_eq!(v.iter().last_().unwrap(), &4); - assert_eq!(v.slice(0, 1).iter().last_().unwrap(), &0); + assert_eq!(v.iter().last_().get(), &4); + assert_eq!(v.slice(0, 1).iter().last_().get(), &0); } #[test] @@ -1862,16 +1862,16 @@ mod tests { #[test] fn test_find() { let v = &[1, 3, 9, 27, 103, 14, 11]; - assert_eq!(*v.iter().find_(|x| *x & 1 == 0).unwrap(), 14); - assert_eq!(*v.iter().find_(|x| *x % 3 == 0).unwrap(), 3); + assert_eq!(*v.iter().find_(|x| *x & 1 == 0).get(), 14); + assert_eq!(*v.iter().find_(|x| *x % 3 == 0).get(), 3); assert!(v.iter().find_(|x| *x % 12 == 0).is_none()); } #[test] fn test_position() { let v = &[1, 3, 9, 27, 103, 14, 11]; - assert_eq!(v.iter().position(|x| *x & 1 == 0).unwrap(), 5); - assert_eq!(v.iter().position(|x| *x % 3 == 0).unwrap(), 1); + assert_eq!(v.iter().position(|x| *x & 1 == 0).get(), 5); + assert_eq!(v.iter().position(|x| *x % 3 == 0).get(), 1); assert!(v.iter().position(|x| *x % 12 == 0).is_none()); } @@ -1886,13 +1886,13 @@ mod tests { #[test] fn test_max_by() { let xs = [-3, 0, 1, 5, -10]; - assert_eq!(*xs.iter().max_by(|x| x.abs()).unwrap(), -10); + assert_eq!(*xs.iter().max_by(|x| x.abs()).get(), -10); } #[test] fn test_min_by() { let xs = [-3, 0, 1, 5, -10]; - assert_eq!(*xs.iter().min_by(|x| x.abs()).unwrap(), 0); + assert_eq!(*xs.iter().min_by(|x| x.abs()).get(), 0); } #[test] @@ -1921,9 +1921,9 @@ mod tests { fn test_double_ended_filter() { let xs = [1, 2, 3, 4, 5, 6]; let mut it = xs.iter().filter(|&x| *x & 1 == 0); - assert_eq!(it.next_back().unwrap(), &6); - assert_eq!(it.next_back().unwrap(), &4); - assert_eq!(it.next().unwrap(), &2); + assert_eq!(it.next_back().get(), &6); + assert_eq!(it.next_back().get(), &4); + assert_eq!(it.next().get(), &2); assert_eq!(it.next_back(), None); } @@ -1931,9 +1931,9 @@ mod tests { fn test_double_ended_filter_map() { let xs = [1, 2, 3, 4, 5, 6]; let mut it = xs.iter().filter_map(|&x| if x & 1 == 0 { Some(x * 2) } else { None }); - assert_eq!(it.next_back().unwrap(), 12); - assert_eq!(it.next_back().unwrap(), 8); - assert_eq!(it.next().unwrap(), 4); + assert_eq!(it.next_back().get(), 12); + assert_eq!(it.next_back().get(), 8); + assert_eq!(it.next().get(), 4); assert_eq!(it.next_back(), None); } @@ -1942,14 +1942,14 @@ mod tests { let xs = [1, 2, 3, 4, 5]; let ys = ~[7, 9, 11]; let mut it = xs.iter().chain_(ys.iter()).invert(); - assert_eq!(it.next().unwrap(), &11) - assert_eq!(it.next().unwrap(), &9) - assert_eq!(it.next_back().unwrap(), &1) - assert_eq!(it.next_back().unwrap(), &2) - assert_eq!(it.next_back().unwrap(), &3) - assert_eq!(it.next_back().unwrap(), &4) - assert_eq!(it.next_back().unwrap(), &5) - assert_eq!(it.next_back().unwrap(), &7) + assert_eq!(it.next().get(), &11) + assert_eq!(it.next().get(), &9) + assert_eq!(it.next_back().get(), &1) + assert_eq!(it.next_back().get(), &2) + assert_eq!(it.next_back().get(), &3) + assert_eq!(it.next_back().get(), &4) + assert_eq!(it.next_back().get(), &5) + assert_eq!(it.next_back().get(), &7) assert_eq!(it.next_back(), None) } @@ -1978,13 +1978,13 @@ mod tests { let u = [0u,1]; let v = [5,6,7,8]; let mut it = u.iter().flat_map_(|x| v.slice(*x, v.len()).iter()); - assert_eq!(it.next_back().unwrap(), &8); - assert_eq!(it.next().unwrap(), &5); - assert_eq!(it.next_back().unwrap(), &7); - assert_eq!(it.next_back().unwrap(), &6); - assert_eq!(it.next_back().unwrap(), &8); - assert_eq!(it.next().unwrap(), &6); - assert_eq!(it.next_back().unwrap(), &7); + assert_eq!(it.next_back().get(), &8); + assert_eq!(it.next().get(), &5); + assert_eq!(it.next_back().get(), &7); + assert_eq!(it.next_back().get(), &6); + assert_eq!(it.next_back().get(), &8); + assert_eq!(it.next().get(), &6); + assert_eq!(it.next_back().get(), &7); assert_eq!(it.next_back(), None); assert_eq!(it.next(), None); assert_eq!(it.next_back(), None); @@ -1995,17 +1995,17 @@ mod tests { let xs = [1, 2, 3, 4, 5]; let ys = ~[7, 9, 11]; let mut it = xs.iter().chain_(ys.iter()); - assert_eq!(it.idx(0).unwrap(), &1); - assert_eq!(it.idx(5).unwrap(), &7); - assert_eq!(it.idx(7).unwrap(), &11); + assert_eq!(it.idx(0).get(), &1); + assert_eq!(it.idx(5).get(), &7); + assert_eq!(it.idx(7).get(), &11); assert!(it.idx(8).is_none()); it.next(); it.next(); it.next_back(); - assert_eq!(it.idx(0).unwrap(), &3); - assert_eq!(it.idx(4).unwrap(), &9); + assert_eq!(it.idx(0).get(), &3); + assert_eq!(it.idx(4).get(), &9); assert!(it.idx(6).is_none()); check_randacc_iter(it, xs.len() + ys.len() - 3); diff --git a/src/libstd/local_data.rs b/src/libstd/local_data.rs index 537289c8dd6c2..3ca0730670f3e 100644 --- a/src/libstd/local_data.rs +++ b/src/libstd/local_data.rs @@ -236,15 +236,15 @@ fn test_owned() { do get(key) |v| { do get(key) |v| { do get(key) |v| { - assert_eq!(**v.unwrap(), 1); + assert_eq!(**v.get(), 1); } - assert_eq!(**v.unwrap(), 1); + assert_eq!(**v.get(), 1); } - assert_eq!(**v.unwrap(), 1); + assert_eq!(**v.get(), 1); } set(key, ~2); do get(key) |v| { - assert_eq!(**v.unwrap(), 2); + assert_eq!(**v.get(), 2); } } @@ -254,11 +254,11 @@ fn test_get_mut() { set(key, 1); do get_mut(key) |v| { - *v.unwrap() = 2; + *v.get() = 2; } do get(key) |v| { - assert_eq!(*v.unwrap(), 2); + assert_eq!(*v.get(), 2); } } @@ -275,11 +275,11 @@ fn test_same_key_type() { set(key4, 4); set(key5, 5); - get(key1, |x| assert_eq!(*x.unwrap(), 1)); - get(key2, |x| assert_eq!(*x.unwrap(), 2)); - get(key3, |x| assert_eq!(*x.unwrap(), 3)); - get(key4, |x| assert_eq!(*x.unwrap(), 4)); - get(key5, |x| assert_eq!(*x.unwrap(), 5)); + get(key1, |x| assert_eq!(*x.get(), 1)); + get(key2, |x| assert_eq!(*x.get(), 2)); + get(key3, |x| assert_eq!(*x.get(), 3)); + get(key4, |x| assert_eq!(*x.get(), 4)); + get(key5, |x| assert_eq!(*x.get(), 5)); } #[test] diff --git a/src/libstd/num/f32.rs b/src/libstd/num/f32.rs index faf9b2e2390dc..0edf7bdabed81 100644 --- a/src/libstd/num/f32.rs +++ b/src/libstd/num/f32.rs @@ -1192,8 +1192,8 @@ mod tests { fn test_ldexp() { // We have to use from_str until base-2 exponents // are supported in floating-point literals - let f1: f32 = from_str_hex("1p-123").unwrap(); - let f2: f32 = from_str_hex("1p-111").unwrap(); + let f1: f32 = from_str_hex("1p-123").get(); + let f2: f32 = from_str_hex("1p-111").get(); assert_eq!(Float::ldexp(1f32, -123), f1); assert_eq!(Float::ldexp(1f32, -111), f2); @@ -1210,8 +1210,8 @@ mod tests { fn test_frexp() { // We have to use from_str until base-2 exponents // are supported in floating-point literals - let f1: f32 = from_str_hex("1p-123").unwrap(); - let f2: f32 = from_str_hex("1p-111").unwrap(); + let f1: f32 = from_str_hex("1p-123").get(); + let f2: f32 = from_str_hex("1p-111").get(); let (x1, exp1) = f1.frexp(); let (x2, exp2) = f2.frexp(); assert_eq!((x1, exp1), (0.5f32, -122)); diff --git a/src/libstd/num/f64.rs b/src/libstd/num/f64.rs index c7db60e6fd264..b7c77972d8e5f 100644 --- a/src/libstd/num/f64.rs +++ b/src/libstd/num/f64.rs @@ -1238,8 +1238,8 @@ mod tests { fn test_ldexp() { // We have to use from_str until base-2 exponents // are supported in floating-point literals - let f1: f64 = from_str_hex("1p-123").unwrap(); - let f2: f64 = from_str_hex("1p-111").unwrap(); + let f1: f64 = from_str_hex("1p-123").get(); + let f2: f64 = from_str_hex("1p-111").get(); assert_eq!(Float::ldexp(1f64, -123), f1); assert_eq!(Float::ldexp(1f64, -111), f2); @@ -1256,8 +1256,8 @@ mod tests { fn test_frexp() { // We have to use from_str until base-2 exponents // are supported in floating-point literals - let f1: f64 = from_str_hex("1p-123").unwrap(); - let f2: f64 = from_str_hex("1p-111").unwrap(); + let f1: f64 = from_str_hex("1p-123").get(); + let f2: f64 = from_str_hex("1p-111").get(); let (x1, exp1) = f1.frexp(); let (x2, exp2) = f2.frexp(); assert_eq!((x1, exp1), (0.5f64, -122)); diff --git a/src/libstd/num/float.rs b/src/libstd/num/float.rs index 486d35620899a..d4d979b5238bc 100644 --- a/src/libstd/num/float.rs +++ b/src/libstd/num/float.rs @@ -1180,8 +1180,8 @@ mod tests { fn test_ldexp() { // We have to use from_str until base-2 exponents // are supported in floating-point literals - let f1: float = from_str_hex("1p-123").unwrap(); - let f2: float = from_str_hex("1p-111").unwrap(); + let f1: float = from_str_hex("1p-123").get(); + let f2: float = from_str_hex("1p-111").get(); assert_eq!(Float::ldexp(1f, -123), f1); assert_eq!(Float::ldexp(1f, -111), f2); @@ -1198,8 +1198,8 @@ mod tests { fn test_frexp() { // We have to use from_str until base-2 exponents // are supported in floating-point literals - let f1: float = from_str_hex("1p-123").unwrap(); - let f2: float = from_str_hex("1p-111").unwrap(); + let f1: float = from_str_hex("1p-123").get(); + let f2: float = from_str_hex("1p-111").get(); let (x1, exp1) = f1.frexp(); let (x2, exp2) = f2.frexp(); assert_eq!((x1, exp1), (0.5f, -122)); diff --git a/src/libstd/num/strconv.rs b/src/libstd/num/strconv.rs index 722af828d5c11..69214e1143874 100644 --- a/src/libstd/num/strconv.rs +++ b/src/libstd/num/strconv.rs @@ -266,8 +266,7 @@ pub fn float_to_str_bytes_common break if deccum == _0 { break; } @@ -322,8 +321,7 @@ pub fn float_to_str_bytes_common Ord for Option { } } -impl> Add, Option> for Option { +impl> Add, Option> for Option { #[inline] fn add(&self, other: &Option) -> Option { 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 ToStr for Option { + 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 Option { /// Return an iterator over the possibly contained value #[inline] @@ -148,8 +164,7 @@ impl Option { /// 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) - -> Option { + pub fn chain_ref<'a, U>(&'a self, f: &fn(x: &'a T) -> Option) -> Option { match *self { Some(ref x) => f(x), None => None @@ -159,8 +174,7 @@ impl Option { /// 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) - -> Option { + pub fn chain_mut_ref<'a, U>(&'a mut self, f: &fn(x: &'a mut T) -> Option) -> Option { match *self { Some(ref mut x) => f(x), None => None @@ -239,7 +253,7 @@ impl Option { /// Returns true if the contained value was mutated. pub fn mutate(&mut self, f: &fn(T) -> T) -> bool { if self.is_some() { - *self = Some(f(self.take_unwrap())); + *self = Some(f(self.take_get())); true } else { false } } @@ -248,7 +262,7 @@ impl Option { /// Returns true if the contained value was mutated, or false if set to the default. pub fn mutate_default(&mut self, def: T, f: &fn(T) -> T) -> bool { if self.is_some() { - *self = Some(f(self.take_unwrap())); + *self = Some(f(self.take_get())); true } else { *self = Some(def); @@ -256,130 +270,103 @@ impl Option { } } - /** - 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. - */ + pub fn get(self) -> T { match self { - Some(x) => x, - None => fail!("option::unwrap `None`"), + Some(x) => x, + None => fail!("called `Option::get()` 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`. - */ - #[inline] - pub fn take_unwrap(&mut self) -> T { - if self.is_none() { fail!("option::take_unwrap `None`") } - self.take().unwrap() - } - - /** - * Gets the value out of an option, printing a specified message on - * failure - * - * # 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 expect(self, reason: &str) -> T { - match self { - Some(val) => val, - None => fail!(reason.to_owned()), + pub fn take_get(&mut self) -> T { + if self.is_none() { + fail!("called `Option::take_get()` on a `None` value") } + self.take().get() } - /** - 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. - */ + /// Gets the value out of an option, printing a specified message on + /// failure + /// + /// # Failure + /// + /// Fails if the value equals `None` #[inline] - pub fn get(self) -> T { + pub fn expect(self, reason: &str) -> T { match self { - Some(x) => return x, - None => fail!("option::get `None`") + Some(val) => val, + None => fail!(reason.to_owned()), } } /// Returns the contained value or a default #[inline] pub fn get_or_default(self, def: T) -> T { - match self { Some(x) => x, None => def } + match self { + Some(x) => x, + None => def + } } /// Applies a function zero or more times until the result is `None`. @@ -387,7 +374,7 @@ impl Option { pub fn while_some(self, blk: &fn(v: T) -> Option) { let mut opt = self; while opt.is_some() { - opt = blk(opt.unwrap()); + opt = blk(opt.get()); } } } @@ -401,6 +388,15 @@ impl Option { None => Zero::zero() } } + + /// Returns self or `Some(zero)` (for this type) + #[inline] + pub fn or_zero(self) -> Option { + match self { + None => Some(Zero::zero()), + x => x + } + } } impl Zero for Option { @@ -450,29 +446,29 @@ mod tests { use util; #[test] - fn test_unwrap_ptr() { + fn test_get_ptr() { unsafe { let x = ~0; let addr_x: *int = ::cast::transmute(&*x); let opt = Some(x); - let y = opt.unwrap(); + let y = opt.get(); let addr_y: *int = ::cast::transmute(&*y); assert_eq!(addr_x, addr_y); } } #[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); - let y = opt.unwrap(); + let y = opt.get(); let addr_y = y.as_imm_buf(|buf, _len| buf); assert_eq!(addr_x, addr_y); } #[test] - fn test_unwrap_resource() { + fn test_get_resource() { struct R { i: @mut int, } @@ -492,7 +488,7 @@ mod tests { { let x = R(i); let opt = Some(x); - let _y = opt.unwrap(); + let _y = opt.get(); } assert_eq!(*i, 1); } @@ -503,7 +499,7 @@ mod tests { let mut y = Some(5); let mut y2 = 0; foreach _x in x.iter() { - y2 = y.take_unwrap(); + y2 = y.take_get(); } assert_eq!(y2, 5); assert!(y.is_none()); @@ -511,8 +507,8 @@ mod tests { #[test] #[should_fail] #[ignore(cfg(windows))] fn test_option_too_much_dance() { let mut y = Some(util::NonCopyable); - let _y2 = y.take_unwrap(); - let _y3 = y.take_unwrap(); + let _y2 = y.take_get(); + let _y3 = y.take_get(); } #[test] diff --git a/src/libstd/pipes.rs b/src/libstd/pipes.rs index 2819744c56036..d1aab99874702 100644 --- a/src/libstd/pipes.rs +++ b/src/libstd/pipes.rs @@ -432,7 +432,7 @@ fn try_recv_(p: &mut Packet) -> Option { Full => { let payload = p.payload.take(); p.header.state = Empty; - return Some(payload.unwrap()) + return Some(payload.get()) }, Terminated => return None, _ => {} @@ -489,7 +489,7 @@ fn try_recv_(p: &mut Packet) -> Option { } } p.header.state = Empty; - return Some(payload.unwrap()) + return Some(payload.get()) } Terminated => { // This assert detects when we've accidentally unsafely @@ -675,7 +675,7 @@ impl Drop for SendPacketBuffered { unsafe { let this: &mut SendPacketBuffered = transmute(self); if this.p != None { - sender_terminate(this.p.take_unwrap()); + sender_terminate(this.p.take_get()); } } } @@ -693,7 +693,7 @@ pub fn SendPacketBuffered(p: *mut Packet) impl SendPacketBuffered { pub fn unwrap(&mut self) -> *mut Packet { - self.p.take_unwrap() + self.p.take_get() } pub fn header(&mut self) -> *mut PacketHeader { @@ -709,7 +709,7 @@ impl SendPacketBuffered { pub fn reuse_buffer(&mut self) -> BufferResource { //error!("send reuse_buffer"); - self.buffer.take_unwrap() + self.buffer.take_get() } } @@ -732,7 +732,7 @@ impl Drop for RecvPacketBuffered { unsafe { let this: &mut RecvPacketBuffered = transmute(self); if this.p != None { - receiver_terminate(this.p.take_unwrap()) + receiver_terminate(this.p.take_get()) } } } @@ -740,11 +740,11 @@ impl Drop for RecvPacketBuffered { impl RecvPacketBuffered { pub fn unwrap(&mut self) -> *mut Packet { - self.p.take_unwrap() + self.p.take_get() } pub fn reuse_buffer(&mut self) -> BufferResource { - self.buffer.take_unwrap() + self.buffer.take_get() } } diff --git a/src/libstd/ptr.rs b/src/libstd/ptr.rs index 3af4769fcdb43..3cd8a275f6839 100644 --- a/src/libstd/ptr.rs +++ b/src/libstd/ptr.rs @@ -540,13 +540,13 @@ pub mod ptr_tests { assert_eq!(p.to_option(), None); let q: *int = &2; - assert_eq!(q.to_option().unwrap(), &2); + assert_eq!(q.to_option().get(), &2); let p: *mut int = mut_null(); assert_eq!(p.to_option(), None); let q: *mut int = &mut 2; - assert_eq!(q.to_option().unwrap(), &2); + assert_eq!(q.to_option().get(), &2); } } diff --git a/src/libstd/result.rs b/src/libstd/result.rs index 89803d022f844..926167dc31b14 100644 --- a/src/libstd/result.rs +++ b/src/libstd/result.rs @@ -20,23 +20,27 @@ use option::{None, Option, Some}; 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 { +pub enum Result { /// Contains the successful result value Ok(T), /// Contains the error value - Err(U) + Err(E) } -impl Result { - /** - * Convert to the `either` type - * - * `Ok` result variants are converted to `either::Right` variants, `Err` - * result variants are converted to `either::Left`. - */ +impl Result { + /// 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{ match self { @@ -45,18 +49,16 @@ impl Result { } } - /** - * 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,20 +77,18 @@ impl Result { !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: + /// + /// do read_file(file).iter |buf| { + /// print_buf(buf) + /// } #[inline] pub fn iter(&self, f: &fn(&T)) { match *self { @@ -97,14 +97,12 @@ impl Result { } } - /** - * 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)) { match *self { @@ -113,38 +111,56 @@ impl Result { } } - /// 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 { + pub fn get(self) -> T { match self { Ok(t) => t, - Err(_) => fail!("unwrap called on an `Err` result"), + Err(e) => fail!("called `Result::get()` 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 get_err(self) -> E { + self.expect_err("called `Result::get_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 unwrap_err(self) -> E { + 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(self, op: &fn(T) -> Result) -> Result { match self { @@ -153,14 +169,12 @@ impl Result { } } - /** - * 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(self, op: &fn(E) -> Result) -> Result { match self { @@ -170,32 +184,15 @@ impl Result { } } -impl Result { - /** - * Get the value out of a successful result - * - * # Failure - * - * If the result is an error - */ +impl Result { + /// 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 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. - */ - #[inline] - pub fn map_err(&self, op: &fn(&E) -> F) -> Result { + pub fn map_err(&self, op: &fn(&E) -> F) -> Result { match *self { Ok(ref t) => Ok(t.clone()), Err(ref e) => Err(op(e)) @@ -203,38 +200,21 @@ impl Result { } } -impl Result { - /** - * Get the value out of an error result - * - * # Failure - * - * If the result is not an error - */ - #[inline] - pub fn get_err(&self) -> E { - match *self { - Err(ref e) => e.clone(), - Ok(_) => fail!("get_err called on `Ok` result") - } - } - - /** - * 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) - * }; - */ +impl Result { + /// 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(&self, op: &fn(&T) -> U) -> Result { + pub fn map(&self, op: &fn(&T) -> U) -> Result { match *self { Ok(ref t) => Ok(op(t)), Err(ref e) => Err(e.clone()) @@ -242,44 +222,10 @@ impl Result { } } -/** - * 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 { - * 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(ts: &[T], op: &fn(&T) -> Result) - -> Result<~[V],U> { - let mut vs: ~[V] = vec::with_capacity(ts.len()); - foreach t in ts.iter() { - match op(t) { - Ok(v) => vs.push(v), - Err(u) => return Err(u) - } - } - return Ok(vs); -} - #[inline] #[allow(missing_doc)] -pub fn map_opt( - o_t: &Option, - op: &fn(&T) -> Result) - -> Result,U> { +pub fn map_opt(o_t: &Option, + op: &fn(&T) -> Result) -> Result,U> { match *o_t { None => Ok(None), Some(ref t) => match op(t) { @@ -289,19 +235,45 @@ pub fn map_opt result { +/// 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_vec2(ss: &[S], ts: &[T], - op: &fn(&S,&T) -> Result) -> Result<~[V],U> { +pub fn map_vec(ts: &[T], op: &fn(&T) -> Result) -> Result<~[V],U> { + let mut vs: ~[V] = vec::with_capacity(ts.len()); + foreach t in ts.iter() { + match op(t) { + Ok(v) => vs.push(v), + Err(u) => return Err(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] +pub fn map_vec2(ss: &[S], ts: &[T], + op: &fn(&S,&T) -> Result) -> Result<~[V],U> { assert!(vec::same_length(ss, ts)); let n = ts.len(); let mut vs = vec::with_capacity(n); @@ -316,15 +288,13 @@ pub fn map_vec2(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(ss: &[S], ts: &[T], - op: &fn(&S,&T) -> Result<(),U>) -> Result<(),U> { - +pub fn iter_vec2(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; diff --git a/src/libstd/rt/comm.rs b/src/libstd/rt/comm.rs index a060059f5fc93..8202044d37d58 100644 --- a/src/libstd/rt/comm.rs +++ b/src/libstd/rt/comm.rs @@ -556,8 +556,8 @@ impl SharedChan { unsafe { let (next_pone, next_cone) = oneshot(); let cone = (*self.next.get()).swap(~next_cone, SeqCst); - cone.unwrap().try_send_inner(StreamPayload { val: val, next: next_pone }, - do_resched) + cone.get().try_send_inner(StreamPayload { val: val, next: next_pone }, + do_resched) } } } @@ -621,7 +621,7 @@ impl GenericPort for SharedPort { unsafe { let (next_link_port, next_link_chan) = oneshot(); let link_port = (*self.next_link.get()).swap(~next_link_port, SeqCst); - let link_port = link_port.unwrap(); + let link_port = link_port.get(); let data_port = link_port.recv(); let (next_data_port, res) = match data_port.try_recv() { Some(StreamPayload { val, next }) => { diff --git a/src/libstd/rt/io/file.rs b/src/libstd/rt/io/file.rs index a99f5da032c39..940b0d9d561c7 100644 --- a/src/libstd/rt/io/file.rs +++ b/src/libstd/rt/io/file.rs @@ -74,6 +74,6 @@ impl Seek for FileStream { fn super_simple_smoke_test_lets_go_read_some_files_and_have_a_good_time() { let message = "it's alright. have a good time"; let filename = &Path("test.txt"); - let mut outstream = FileStream::open(filename, Create, Read).unwrap(); + let mut outstream = FileStream::open(filename, Create, Read).get(); outstream.write(message.as_bytes()); } diff --git a/src/libstd/rt/io/mod.rs b/src/libstd/rt/io/mod.rs index 838c2d86c9fa2..c980dc9d73efd 100644 --- a/src/libstd/rt/io/mod.rs +++ b/src/libstd/rt/io/mod.rs @@ -243,6 +243,8 @@ Out of scope */ 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 +} diff --git a/src/libstd/rt/io/net/ip.rs b/src/libstd/rt/io/net/ip.rs index 2b572574b60b2..667b99ac25c75 100644 --- a/src/libstd/rt/io/net/ip.rs +++ b/src/libstd/rt/io/net/ip.rs @@ -29,11 +29,11 @@ impl ToStr for IpAddr { // Ipv4 Compatible address Ipv6(0, 0, 0, 0, 0, 0, g, h, p) => { let a = fmt!("%04x", g as uint); - let b = FromStrRadix::from_str_radix(a.slice(2, 4), 16).unwrap(); - let a = FromStrRadix::from_str_radix(a.slice(0, 2), 16).unwrap(); + let b = FromStrRadix::from_str_radix(a.slice(2, 4), 16).get(); + let a = FromStrRadix::from_str_radix(a.slice(0, 2), 16).get(); let c = fmt!("%04x", h as uint); - let d = FromStrRadix::from_str_radix(c.slice(2, 4), 16).unwrap(); - let c = FromStrRadix::from_str_radix(c.slice(0, 2), 16).unwrap(); + let d = FromStrRadix::from_str_radix(c.slice(2, 4), 16).get(); + let c = FromStrRadix::from_str_radix(c.slice(0, 2), 16).get(); fmt!("[::%u.%u.%u.%u]:%u", a, b, c, d, p as uint) } @@ -41,11 +41,11 @@ impl ToStr for IpAddr { // Ipv4-Mapped address Ipv6(0, 0, 0, 0, 0, 1, g, h, p) => { let a = fmt!("%04x", g as uint); - let b = FromStrRadix::from_str_radix(a.slice(2, 4), 16).unwrap(); - let a = FromStrRadix::from_str_radix(a.slice(0, 2), 16).unwrap(); + let b = FromStrRadix::from_str_radix(a.slice(2, 4), 16).get(); + let a = FromStrRadix::from_str_radix(a.slice(0, 2), 16).get(); let c = fmt!("%04x", h as uint); - let d = FromStrRadix::from_str_radix(c.slice(2, 4), 16).unwrap(); - let c = FromStrRadix::from_str_radix(c.slice(0, 2), 16).unwrap(); + let d = FromStrRadix::from_str_radix(c.slice(2, 4), 16).get(); + let c = FromStrRadix::from_str_radix(c.slice(0, 2), 16).get(); fmt!("[::FFFF:%u.%u.%u.%u]:%u", a, b, c, d, p as uint) } diff --git a/src/libstd/rt/io/net/tcp.rs b/src/libstd/rt/io/net/tcp.rs index 764ef283eb88c..029275dc2ec76 100644 --- a/src/libstd/rt/io/net/tcp.rs +++ b/src/libstd/rt/io/net/tcp.rs @@ -575,13 +575,13 @@ mod test { let listener = TcpListener::bind(addr); assert!(listener.is_some()); - let mut listener = listener.unwrap(); + let mut listener = listener.get(); // Make sure socket_name gives // us the socket we binded to. let so_name = listener.socket_name(); assert!(so_name.is_some()); - assert_eq!(addr, so_name.unwrap()); + assert_eq!(addr, so_name.get()); } } @@ -600,14 +600,14 @@ mod test { let stream = TcpStream::connect(addr); assert!(stream.is_some()); - let mut stream = stream.unwrap(); + let mut stream = stream.get(); // Make sure peer_name gives us the // address/port of the peer we've // connected to. let peer_name = stream.peer_name(); assert!(peer_name.is_some()); - assert_eq!(addr, peer_name.unwrap()); + assert_eq!(addr, peer_name.get()); } } } diff --git a/src/libstd/rt/io/net/udp.rs b/src/libstd/rt/io/net/udp.rs index c04abfa899b1a..79c268f041f91 100644 --- a/src/libstd/rt/io/net/udp.rs +++ b/src/libstd/rt/io/net/udp.rs @@ -271,13 +271,13 @@ mod test { let server = UdpSocket::bind(addr); assert!(server.is_some()); - let mut server = server.unwrap(); + let mut server = server.get(); // Make sure socket_name gives // us the socket we binded to. let so_name = server.socket_name(); assert!(so_name.is_some()); - assert_eq!(addr, so_name.unwrap()); + assert_eq!(addr, so_name.get()); } } diff --git a/src/libstd/rt/io/option.rs b/src/libstd/rt/io/option.rs index 7dadc653e6cc9..33b63156c69ef 100644 --- a/src/libstd/rt/io/option.rs +++ b/src/libstd/rt/io/option.rs @@ -87,7 +87,7 @@ mod test { let mut writer: Option = Some(MemWriter::new()); writer.write([0, 1, 2]); writer.flush(); - assert_eq!(writer.unwrap().inner(), ~[0, 1, 2]); + assert_eq!(writer.get().inner(), ~[0, 1, 2]); } } diff --git a/src/libstd/rt/kill.rs b/src/libstd/rt/kill.rs index deec8dd37a600..361b97ba15b87 100644 --- a/src/libstd/rt/kill.rs +++ b/src/libstd/rt/kill.rs @@ -493,7 +493,7 @@ impl Death { do self.on_exit.take_map |on_exit| { if success { // We succeeded, but our children might not. Need to wait for them. - let mut inner = self.kill_handle.take_unwrap().unwrap(); + let mut inner = self.kill_handle.take_get().unwrap(); if inner.any_child_failed { success = false; } else { @@ -677,7 +677,7 @@ mod test { util::ignore(link); // Must have created a tombstone let mut parent_inner = parent.unwrap(); - assert!(parent_inner.child_tombstones.take_unwrap()()); + assert!(parent_inner.child_tombstones.take_get()()); assert!(parent_inner.any_child_failed == false); } } @@ -697,7 +697,7 @@ mod test { // Must have created a tombstone let mut parent_inner = parent.unwrap(); // Failure must be seen in the tombstone. - assert!(parent_inner.child_tombstones.take_unwrap()() == false); + assert!(parent_inner.child_tombstones.take_get()() == false); assert!(parent_inner.any_child_failed == false); } } @@ -716,7 +716,7 @@ mod test { util::ignore(link); // Must have created a tombstone let mut parent_inner = parent.unwrap(); - assert!(parent_inner.child_tombstones.take_unwrap()()); + assert!(parent_inner.child_tombstones.take_get()()); assert!(parent_inner.any_child_failed == false); } } @@ -738,7 +738,7 @@ mod test { // Must have created a tombstone let mut parent_inner = parent.unwrap(); // Failure must be seen in the tombstone. - assert!(parent_inner.child_tombstones.take_unwrap()() == false); + assert!(parent_inner.child_tombstones.take_get()() == false); assert!(parent_inner.any_child_failed == false); } } @@ -812,7 +812,7 @@ mod test { #[test] fn block_and_wake() { do with_test_task |mut task| { - BlockedTask::try_block(task).unwrap_right().wake().unwrap() + BlockedTask::try_block(task).get_right().wake().get() } } @@ -820,8 +820,8 @@ mod test { fn block_and_get_killed() { do with_test_task |mut task| { let mut handle = task.death.kill_handle.get_ref().clone(); - let result = BlockedTask::try_block(task).unwrap_right(); - let task = handle.kill().unwrap(); + let result = BlockedTask::try_block(task).get_right(); + let task = handle.kill().get(); assert!(result.wake().is_none()); task } @@ -832,7 +832,7 @@ mod test { do with_test_task |mut task| { let mut handle = task.death.kill_handle.get_ref().clone(); assert!(handle.kill().is_none()); - BlockedTask::try_block(task).unwrap_left() + BlockedTask::try_block(task).get_left() } } @@ -841,9 +841,9 @@ mod test { do with_test_task |mut task| { let mut handle = task.death.kill_handle.get_ref().clone(); task.death.inhibit_kill(false); - let result = BlockedTask::try_block(task).unwrap_right(); + let result = BlockedTask::try_block(task).get_right(); assert!(handle.kill().is_none()); - let mut task = result.wake().unwrap(); + let mut task = result.wake().get(); // This call wants to fail, but we can't have that happen since // we're not running in a newsched task, so we can't even use // spawntask_try. But the failing behaviour is already tested @@ -858,10 +858,10 @@ mod test { // Tests the "killable" path of casting to/from uint. do run_in_newsched_task { do with_test_task |mut task| { - let result = BlockedTask::try_block(task).unwrap_right(); + let result = BlockedTask::try_block(task).get_right(); let result = unsafe { result.cast_to_uint() }; let result = unsafe { BlockedTask::cast_from_uint(result) }; - result.wake().unwrap() + result.wake().get() } } } @@ -872,10 +872,10 @@ mod test { do run_in_newsched_task { do with_test_task |mut task| { task.death.inhibit_kill(false); - let result = BlockedTask::try_block(task).unwrap_right(); + let result = BlockedTask::try_block(task).get_right(); let result = unsafe { result.cast_to_uint() }; let result = unsafe { BlockedTask::cast_from_uint(result) }; - let mut task = result.wake().unwrap(); + let mut task = result.wake().get(); task.death.allow_kill(false); task } diff --git a/src/libstd/rt/local.rs b/src/libstd/rt/local.rs index 7ab63233cff2f..6cc1f6f5fe2e0 100644 --- a/src/libstd/rt/local.rs +++ b/src/libstd/rt/local.rs @@ -63,7 +63,7 @@ impl Local for Scheduler { } fn take() -> ~Scheduler { do Local::borrow:: |task| { - let sched = task.sched.take_unwrap(); + let sched = task.sched.take_get(); let task = task; task.sched = None; sched @@ -117,7 +117,7 @@ impl Local for IoFactoryObject { fn borrow(_f: &fn(&mut IoFactoryObject) -> T) -> T { rtabort!("unimpl") } unsafe fn unsafe_borrow() -> *mut IoFactoryObject { let sched = Local::unsafe_borrow::(); - let io: *mut IoFactoryObject = (*sched).event_loop.io().unwrap(); + let io: *mut IoFactoryObject = (*sched).event_loop.io().get(); return io; } unsafe fn try_unsafe_borrow() -> Option<*mut IoFactoryObject> { rtabort!("unimpl") } diff --git a/src/libstd/rt/sched.rs b/src/libstd/rt/sched.rs index dfe003253c2cf..c25e41711ba4e 100644 --- a/src/libstd/rt/sched.rs +++ b/src/libstd/rt/sched.rs @@ -381,7 +381,7 @@ impl Scheduler { /// Given an input Coroutine sends it back to its home scheduler. fn send_task_home(task: ~Task) { let mut task = task; - let mut home = task.take_unwrap_home(); + let mut home = task.take_get_home(); match home { Sched(ref mut home_handle) => { home_handle.send(PinnedTask(task)); @@ -418,7 +418,7 @@ impl Scheduler { match this.work_queue.pop() { Some(task) => { let mut task = task; - let home = task.take_unwrap_home(); + let home = task.take_get_home(); match home { Sched(home_handle) => { if home_handle.sched_id != this.sched_id() { @@ -455,9 +455,9 @@ impl Scheduler { // Similar to deschedule running task and then, but cannot go through // the task-blocking path. The task is already dying. let mut this = self; - let stask = this.sched_task.take_unwrap(); + let stask = this.sched_task.take_get(); do this.change_task_context(stask) |sched, mut dead_task| { - let coroutine = dead_task.coroutine.take_unwrap(); + let coroutine = dead_task.coroutine.take_get(); coroutine.recycle(&mut sched.stack_pool); } } @@ -640,7 +640,7 @@ impl Scheduler { // Trickier - we need to get the scheduler task out of self // and use it as the destination. let mut this = self; - let stask = this.sched_task.take_unwrap(); + let stask = this.sched_task.take_get(); // Otherwise this is the same as below. this.switch_running_tasks_and_then(stask, f); } @@ -693,7 +693,7 @@ impl Scheduler { pub fn run_cleanup_job(&mut self) { rtdebug!("running cleanup job"); - let cleanup_job = self.cleanup_job.take_unwrap(); + let cleanup_job = self.cleanup_job.take_get(); match cleanup_job { DoNothing => { } GiveTask(task, f) => f.to_fn()(self, task) diff --git a/src/libstd/rt/select.rs b/src/libstd/rt/select.rs index a5adb25b526a9..a3364367a5616 100644 --- a/src/libstd/rt/select.rs +++ b/src/libstd/rt/select.rs @@ -199,7 +199,7 @@ mod test { // get it back out util::swap(port.get_mut_ref(), &mut ports[index]); // NB. Not recv(), because optimistic_check randomly fails. - let (data, new_port) = port.take_unwrap().recv_ready().unwrap(); + let (data, new_port) = port.take_get().recv_ready().get(); assert!(data == 31337); port = Some(new_port); } diff --git a/src/libstd/rt/task.rs b/src/libstd/rt/task.rs index b242ee13fa668..50ee2f92195a2 100644 --- a/src/libstd/rt/task.rs +++ b/src/libstd/rt/task.rs @@ -88,7 +88,7 @@ impl Task { let f = Cell::new(f); let home = Cell::new(home); do Local::borrow:: |running_task| { - let mut sched = running_task.sched.take_unwrap(); + let mut sched = running_task.sched.take_get(); let new_task = ~running_task.new_child_homed(&mut sched.stack_pool, home.take(), f.take()); @@ -105,7 +105,7 @@ impl Task { let f = Cell::new(f); let home = Cell::new(home); do Local::borrow:: |running_task| { - let mut sched = running_task.sched.take_unwrap(); + let mut sched = running_task.sched.take_get(); let new_task = ~Task::new_root_homed(&mut sched.stack_pool, home.take(), f.take()); @@ -197,10 +197,10 @@ impl Task { } } - pub fn take_unwrap_home(&mut self) -> SchedHome { + pub fn take_get_home(&mut self) -> SchedHome { match self.task_type { GreenTask(ref mut home) => { - let out = home.take_unwrap(); + let out = home.take_get(); return *out; } SchedTask => { @@ -564,7 +564,7 @@ mod test { let mut builder = task(); builder.future_result(|r| result = Some(r)); do builder.spawn {} - assert_eq!(result.unwrap().recv(), Success); + assert_eq!(result.get().recv(), Success); result = None; let mut builder = task(); @@ -573,7 +573,7 @@ mod test { do builder.spawn { fail!(); } - assert_eq!(result.unwrap().recv(), Failure); + assert_eq!(result.get().recv(), Failure); } } } diff --git a/src/libstd/rt/tube.rs b/src/libstd/rt/tube.rs index c014d0abda2a8..28322a4936d7d 100644 --- a/src/libstd/rt/tube.rs +++ b/src/libstd/rt/tube.rs @@ -50,7 +50,7 @@ impl Tube { if (*state).blocked_task.is_some() { // There's a waiting task. Wake it up rtdebug!("waking blocked tube"); - let task = (*state).blocked_task.take_unwrap(); + let task = (*state).blocked_task.take_get(); let sched = Local::take::(); sched.resume_blocked_task_immediately(task); } diff --git a/src/libstd/rt/uv/async.rs b/src/libstd/rt/uv/async.rs index d0ca38317cbed..964732743ce11 100644 --- a/src/libstd/rt/uv/async.rs +++ b/src/libstd/rt/uv/async.rs @@ -62,7 +62,7 @@ impl AsyncWatcher { let mut watcher: AsyncWatcher = NativeHandle::from_native_handle(handle); { let data = watcher.get_watcher_data(); - data.close_cb.take_unwrap()(); + data.close_cb.take_get()(); } watcher.drop_watcher_data(); unsafe { uvll::free_handle(handle as *c_void); } diff --git a/src/libstd/rt/uv/idle.rs b/src/libstd/rt/uv/idle.rs index b73be9f7250db..f5bf39f28a599 100644 --- a/src/libstd/rt/uv/idle.rs +++ b/src/libstd/rt/uv/idle.rs @@ -73,7 +73,7 @@ impl IdleWatcher { let mut idle_watcher: IdleWatcher = NativeHandle::from_native_handle(handle); { let data = idle_watcher.get_watcher_data(); - data.close_cb.take_unwrap()(); + data.close_cb.take_get()(); } idle_watcher.drop_watcher_data(); uvll::idle_delete(handle); diff --git a/src/libstd/rt/uv/net.rs b/src/libstd/rt/uv/net.rs index 773adb3848ad1..0085b1b44aab3 100644 --- a/src/libstd/rt/uv/net.rs +++ b/src/libstd/rt/uv/net.rs @@ -99,7 +99,7 @@ fn uv_ip_as_ip(addr: UvIpAddr, f: &fn(IpAddr) -> T) -> T { UvIpv4(*) => { let ip: ~[u8] = ip_str.split_iter('.') - .transform(|s: &str| -> u8 { FromStr::from_str(s).unwrap() }) + .transform(|s: &str| -> u8 { FromStr::from_str(s).get() }) .collect(); assert_eq!(ip.len(), 4); Ipv4(ip[0], ip[1], ip[2], ip[3], ip_port) @@ -109,7 +109,7 @@ fn uv_ip_as_ip(addr: UvIpAddr, f: &fn(IpAddr) -> T) -> T { let expand_shorthand_and_convert = |s: &str| -> ~[~[u16]] { let convert_each_segment = |s: &str| -> ~[u16] { let read_hex_segment = |s: &str| -> u16 { - num::FromStrRadix::from_str_radix(s, 16u).unwrap() + num::FromStrRadix::from_str_radix(s, 16u).get() }; match s { "" => ~[], @@ -120,7 +120,7 @@ fn uv_ip_as_ip(addr: UvIpAddr, f: &fn(IpAddr) -> T) -> T { let b = s.slice(i + 1, s.len()); // the ipv4 part let h = b.split_iter('.') - .transform(|s: &str| -> u8 { FromStr::from_str(s).unwrap() }) + .transform(|s: &str| -> u8 { FromStr::from_str(s).get() }) .transform(|s: u8| -> ~str { fmt!("%02x", s as uint) }) .collect::<~[~str]>(); @@ -129,8 +129,8 @@ fn uv_ip_as_ip(addr: UvIpAddr, f: &fn(IpAddr) -> T) -> T { // first 96 bits are zero leaving 32 bits // for the ipv4 part // (i.e ::127.0.0.1 == ::7F00:1) - ~[num::FromStrRadix::from_str_radix(h[0] + h[1], 16).unwrap(), - num::FromStrRadix::from_str_radix(h[2] + h[3], 16).unwrap()] + ~[num::FromStrRadix::from_str_radix(h[0] + h[1], 16).get(), + num::FromStrRadix::from_str_radix(h[2] + h[3], 16).get()] } else { // Ipv4-Mapped Address (::FFFF:x.x.x.x) // first 80 bits are zero, followed by all ones @@ -138,8 +138,8 @@ fn uv_ip_as_ip(addr: UvIpAddr, f: &fn(IpAddr) -> T) -> T { // the ipv4 part // (i.e ::FFFF:127.0.0.1 == ::FFFF:7F00:1) ~[1, - num::FromStrRadix::from_str_radix(h[0] + h[1], 16).unwrap(), - num::FromStrRadix::from_str_radix(h[2] + h[3], 16).unwrap()] + num::FromStrRadix::from_str_radix(h[0] + h[1], 16).get(), + num::FromStrRadix::from_str_radix(h[2] + h[3], 16).get()] } }, s => s.split_iter(':').transform(read_hex_segment).collect() @@ -238,7 +238,7 @@ impl StreamWatcher { let write_request: WriteRequest = NativeHandle::from_native_handle(req); let mut stream_watcher = write_request.stream(); write_request.delete(); - let cb = stream_watcher.get_watcher_data().write_cb.take_unwrap(); + let cb = stream_watcher.get_watcher_data().write_cb.take_get(); let status = status_to_maybe_uv_error(stream_watcher, status); cb(stream_watcher, status); } @@ -262,7 +262,7 @@ impl StreamWatcher { extern fn close_cb(handle: *uvll::uv_stream_t) { let mut stream_watcher: StreamWatcher = NativeHandle::from_native_handle(handle); - stream_watcher.get_watcher_data().close_cb.take_unwrap()(); + stream_watcher.get_watcher_data().close_cb.take_get()(); stream_watcher.drop_watcher_data(); unsafe { free_handle(handle as *c_void) } } @@ -330,7 +330,7 @@ impl TcpWatcher { let connect_request: ConnectRequest = NativeHandle::from_native_handle(req); let mut stream_watcher = connect_request.stream(); connect_request.delete(); - let cb = stream_watcher.get_watcher_data().connect_cb.take_unwrap(); + let cb = stream_watcher.get_watcher_data().connect_cb.take_get(); let status = status_to_maybe_uv_error(stream_watcher, status); cb(stream_watcher, status); } @@ -465,7 +465,7 @@ impl UdpWatcher { let send_request: UdpSendRequest = NativeHandle::from_native_handle(req); let mut udp_watcher = send_request.handle(); send_request.delete(); - let cb = udp_watcher.get_watcher_data().udp_send_cb.take_unwrap(); + let cb = udp_watcher.get_watcher_data().udp_send_cb.take_get(); let status = status_to_maybe_uv_error(udp_watcher, status); cb(udp_watcher, status); } @@ -483,7 +483,7 @@ impl UdpWatcher { extern fn close_cb(handle: *uvll::uv_udp_t) { let mut udp_watcher: UdpWatcher = NativeHandle::from_native_handle(handle); - udp_watcher.get_watcher_data().close_cb.take_unwrap()(); + udp_watcher.get_watcher_data().close_cb.take_get()(); udp_watcher.drop_watcher_data(); unsafe { free_handle(handle as *c_void) } } @@ -700,7 +700,7 @@ mod test { let mut count = count_cell.take(); if status.is_none() { rtdebug!("got %d bytes", nread); - let buf = buf.unwrap(); + let buf = buf.get(); foreach byte in buf.slice(0, nread as uint).iter() { assert!(*byte == count as u8); rtdebug!("%u", *byte as uint); @@ -775,7 +775,7 @@ mod test { let mut count = count_cell.take(); if status.is_none() { rtdebug!("got %d bytes", nread); - let buf = buf.unwrap(); + let buf = buf.get(); let r = buf.slice(0, nread as uint); foreach byte in r.iter() { assert!(*byte == count as u8); @@ -847,7 +847,7 @@ mod test { let mut count = 0; rtdebug!("got %d bytes", nread); - let buf = buf.unwrap(); + let buf = buf.get(); foreach &byte in buf.slice(0, nread as uint).iter() { assert!(byte == count as u8); rtdebug!("%u", byte as uint); @@ -907,7 +907,7 @@ mod test { let mut count = 0; rtdebug!("got %d bytes", nread); - let buf = buf.unwrap(); + let buf = buf.get(); foreach &byte in buf.slice(0, nread as uint).iter() { assert!(byte == count as u8); rtdebug!("%u", byte as uint); diff --git a/src/libstd/rt/uv/timer.rs b/src/libstd/rt/uv/timer.rs index eaa5e77a6da2f..b09cfa64eb54f 100644 --- a/src/libstd/rt/uv/timer.rs +++ b/src/libstd/rt/uv/timer.rs @@ -70,7 +70,7 @@ impl TimerWatcher { let mut watcher: TimerWatcher = NativeHandle::from_native_handle(handle); { let data = watcher.get_watcher_data(); - data.close_cb.take_unwrap()(); + data.close_cb.take_get()(); } watcher.drop_watcher_data(); unsafe { diff --git a/src/libstd/rt/uv/uvio.rs b/src/libstd/rt/uv/uvio.rs index e15e3adb8c9f3..fbfcab6a84fc9 100644 --- a/src/libstd/rt/uv/uvio.rs +++ b/src/libstd/rt/uv/uvio.rs @@ -62,7 +62,7 @@ fn socket_name>(sk: SocketNameKind, if r != 0 { let status = status_to_maybe_uv_error(handle, r); - return Err(uv_error_to_io_error(status.unwrap())); + return Err(uv_error_to_io_error(status.get())); } let addr = unsafe { @@ -478,7 +478,7 @@ impl RtioTcpStream for UvTcpStream { assert!(nread >= 0); Ok(nread as uint) } else { - Err(uv_error_to_io_error(status.unwrap())) + Err(uv_error_to_io_error(status.get())) }; unsafe { (*result_cell_ptr).put_back(result); } @@ -505,7 +505,7 @@ impl RtioTcpStream for UvTcpStream { let result = if status.is_none() { Ok(()) } else { - Err(uv_error_to_io_error(status.unwrap())) + Err(uv_error_to_io_error(status.get())) }; unsafe { (*result_cell_ptr).put_back(result); } @@ -838,10 +838,10 @@ fn test_simple_tcp_server_and_client() { do spawntask { unsafe { let io = Local::unsafe_borrow::(); - let mut listener = (*io).tcp_bind(addr).unwrap(); - let mut stream = listener.accept().unwrap(); + let mut listener = (*io).tcp_bind(addr).get(); + let mut stream = listener.accept().get(); let mut buf = [0, .. 2048]; - let nread = stream.read(buf).unwrap(); + let nread = stream.read(buf).get(); assert_eq!(nread, 8); foreach i in range(0u, nread) { rtdebug!("%u", buf[i] as uint); @@ -853,7 +853,7 @@ fn test_simple_tcp_server_and_client() { do spawntask { unsafe { let io = Local::unsafe_borrow::(); - let mut stream = (*io).tcp_connect(addr).unwrap(); + let mut stream = (*io).tcp_connect(addr).get(); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); } } @@ -869,9 +869,9 @@ fn test_simple_udp_server_and_client() { do spawntask { unsafe { let io = Local::unsafe_borrow::(); - let mut server_socket = (*io).udp_bind(server_addr).unwrap(); + let mut server_socket = (*io).udp_bind(server_addr).get(); let mut buf = [0, .. 2048]; - let (nread,src) = server_socket.recvfrom(buf).unwrap(); + let (nread,src) = server_socket.recvfrom(buf).get(); assert_eq!(nread, 8); foreach i in range(0u, nread) { rtdebug!("%u", buf[i] as uint); @@ -884,7 +884,7 @@ fn test_simple_udp_server_and_client() { do spawntask { unsafe { let io = Local::unsafe_borrow::(); - let mut client_socket = (*io).udp_bind(client_addr).unwrap(); + let mut client_socket = (*io).udp_bind(client_addr).get(); client_socket.sendto([0, 1, 2, 3, 4, 5, 6, 7], server_addr); } } @@ -898,8 +898,8 @@ fn test_read_and_block() { do spawntask { let io = unsafe { Local::unsafe_borrow::() }; - let mut listener = unsafe { (*io).tcp_bind(addr).unwrap() }; - let mut stream = listener.accept().unwrap(); + let mut listener = unsafe { (*io).tcp_bind(addr).get() }; + let mut stream = listener.accept().get(); let mut buf = [0, .. 2048]; let expected = 32; @@ -907,7 +907,7 @@ fn test_read_and_block() { let mut reads = 0; while current < expected { - let nread = stream.read(buf).unwrap(); + let nread = stream.read(buf).get(); foreach i in range(0u, nread) { let val = buf[i] as uint; assert_eq!(val, current % 8); @@ -932,7 +932,7 @@ fn test_read_and_block() { do spawntask { unsafe { let io = Local::unsafe_borrow::(); - let mut stream = (*io).tcp_connect(addr).unwrap(); + let mut stream = (*io).tcp_connect(addr).get(); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); stream.write([0, 1, 2, 3, 4, 5, 6, 7]); @@ -952,8 +952,8 @@ fn test_read_read_read() { do spawntask { unsafe { let io = Local::unsafe_borrow::(); - let mut listener = (*io).tcp_bind(addr).unwrap(); - let mut stream = listener.accept().unwrap(); + let mut listener = (*io).tcp_bind(addr).get(); + let mut stream = listener.accept().get(); let buf = [1, .. 2048]; let mut total_bytes_written = 0; while total_bytes_written < MAX { @@ -966,11 +966,11 @@ fn test_read_read_read() { do spawntask { unsafe { let io = Local::unsafe_borrow::(); - let mut stream = (*io).tcp_connect(addr).unwrap(); + let mut stream = (*io).tcp_connect(addr).get(); let mut buf = [0, .. 2048]; let mut total_bytes_read = 0; while total_bytes_read < MAX { - let nread = stream.read(buf).unwrap(); + let nread = stream.read(buf).get(); rtdebug!("read %u bytes", nread as uint); total_bytes_read += nread; foreach i in range(0u, nread) { @@ -992,7 +992,7 @@ fn test_udp_twice() { do spawntask { unsafe { let io = Local::unsafe_borrow::(); - let mut client = (*io).udp_bind(client_addr).unwrap(); + let mut client = (*io).udp_bind(client_addr).get(); assert!(client.sendto([1], server_addr).is_ok()); assert!(client.sendto([2], server_addr).is_ok()); } @@ -1001,11 +1001,11 @@ fn test_udp_twice() { do spawntask { unsafe { let io = Local::unsafe_borrow::(); - let mut server = (*io).udp_bind(server_addr).unwrap(); + let mut server = (*io).udp_bind(server_addr).get(); let mut buf1 = [0]; let mut buf2 = [0]; - let (nread1, src1) = server.recvfrom(buf1).unwrap(); - let (nread2, src2) = server.recvfrom(buf2).unwrap(); + let (nread1, src1) = server.recvfrom(buf1).get(); + let (nread2, src2) = server.recvfrom(buf2).get(); assert_eq!(nread1, 1); assert_eq!(nread2, 1); assert_eq!(src1, client_addr); @@ -1029,8 +1029,8 @@ fn test_udp_many_read() { do spawntask { unsafe { let io = Local::unsafe_borrow::(); - let mut server_out = (*io).udp_bind(server_out_addr).unwrap(); - let mut server_in = (*io).udp_bind(server_in_addr).unwrap(); + let mut server_out = (*io).udp_bind(server_out_addr).get(); + let mut server_in = (*io).udp_bind(server_in_addr).get(); let msg = [1, .. 2048]; let mut total_bytes_sent = 0; let mut buf = [1]; @@ -1041,7 +1041,7 @@ fn test_udp_many_read() { // check if the client has received enough let res = server_in.recvfrom(buf); assert!(res.is_ok()); - let (nread, src) = res.unwrap(); + let (nread, src) = res.get(); assert_eq!(nread, 1); assert_eq!(src, client_out_addr); } @@ -1052,8 +1052,8 @@ fn test_udp_many_read() { do spawntask { unsafe { let io = Local::unsafe_borrow::(); - let mut client_out = (*io).udp_bind(client_out_addr).unwrap(); - let mut client_in = (*io).udp_bind(client_in_addr).unwrap(); + let mut client_out = (*io).udp_bind(client_out_addr).get(); + let mut client_in = (*io).udp_bind(client_in_addr).get(); let mut total_bytes_recv = 0; let mut buf = [0, .. 2048]; while total_bytes_recv < MAX { @@ -1062,7 +1062,7 @@ fn test_udp_many_read() { // wait for data let res = client_in.recvfrom(buf); assert!(res.is_ok()); - let (nread, src) = res.unwrap(); + let (nread, src) = res.get(); assert_eq!(src, server_out_addr); total_bytes_recv += nread; foreach i in range(0u, nread) { diff --git a/src/libstd/run.rs b/src/libstd/run.rs index 4c67d844c7e81..bc0b8bd4e0592 100644 --- a/src/libstd/run.rs +++ b/src/libstd/run.rs @@ -1241,8 +1241,8 @@ mod tests { let parent_dir = os::getcwd().normalize(); let child_dir = Path(output.trim()).normalize(); - let parent_stat = parent_dir.stat().unwrap(); - let child_stat = child_dir.stat().unwrap(); + let parent_stat = parent_dir.stat().get(); + let child_stat = child_dir.stat().get(); assert_eq!(parent_stat.st_dev, child_stat.st_dev); assert_eq!(parent_stat.st_ino, child_stat.st_ino); @@ -1258,8 +1258,8 @@ mod tests { let output = str::from_bytes(prog.finish_with_output().output); let child_dir = Path(output.trim()).normalize(); - let parent_stat = parent_dir.stat().unwrap(); - let child_stat = child_dir.stat().unwrap(); + let parent_stat = parent_dir.stat().get(); + let child_stat = child_dir.stat().get(); assert_eq!(parent_stat.st_dev, child_stat.st_dev); assert_eq!(parent_stat.st_ino, child_stat.st_ino); diff --git a/src/libstd/task/mod.rs b/src/libstd/task/mod.rs index f7a943f8d2fdf..91b34736ceadf 100644 --- a/src/libstd/task/mod.rs +++ b/src/libstd/task/mod.rs @@ -395,7 +395,7 @@ impl TaskBuilder { ch.send(f()); } - match result.unwrap().recv() { + match result.get().recv() { Success => result::Ok(po.recv()), Failure => result::Err(()) } @@ -972,7 +972,7 @@ fn test_future_result() { let mut builder = task(); builder.future_result(|r| result = Some(r)); do builder.spawn {} - assert_eq!(result.unwrap().recv(), Success); + assert_eq!(result.get().recv(), Success); result = None; let mut builder = task(); @@ -981,7 +981,7 @@ fn test_future_result() { do builder.spawn { fail!(); } - assert_eq!(result.unwrap().recv(), Failure); + assert_eq!(result.get().recv(), Failure); } #[test] #[should_fail] #[ignore(cfg(windows))] diff --git a/src/libstd/task/spawn.rs b/src/libstd/task/spawn.rs index e6f115958fd40..8ead3dfbba0fa 100644 --- a/src/libstd/task/spawn.rs +++ b/src/libstd/task/spawn.rs @@ -244,7 +244,7 @@ fn each_ancestor(list: &mut AncestorList, if coalesce_this.is_some() { // Needed coalesce. Our next ancestor becomes our old // ancestor's next ancestor. ("next = old_next->next;") - *list = coalesce_this.unwrap(); + *list = coalesce_this.get(); } return early_break; } @@ -463,8 +463,7 @@ fn kill_taskgroup(state: TaskGroupInner, me: &TaskHandle, is_main: bool) { // That's ok; only one task needs to do the dirty work. (Might also // see 'None' if Somebody already failed and we got a kill signal.) if newstate.is_some() { - let TaskGroupData { members: members, descendants: descendants } = - newstate.unwrap(); + let TaskGroupData { members: members, descendants: descendants } = newstate.get(); foreach sibling in members.consume() { // Skip self - killing ourself won't do much good. if &sibling != me { @@ -774,7 +773,7 @@ fn spawn_raw_newsched(mut opts: TaskOpts, f: ~fn()) { }; if opts.notify_chan.is_some() { - let notify_chan = opts.notify_chan.take_unwrap(); + let notify_chan = opts.notify_chan.take_get(); let notify_chan = Cell::new(notify_chan); let on_exit: ~fn(bool) = |success| { notify_chan.take().send( diff --git a/src/libstd/unstable/sync.rs b/src/libstd/unstable/sync.rs index 88c9c6ccb3aa4..8ca4bc006231c 100644 --- a/src/libstd/unstable/sync.rs +++ b/src/libstd/unstable/sync.rs @@ -141,7 +141,7 @@ impl UnsafeAtomicRcBox { // FIXME(#3224): it should be like this // let ~AtomicRcBoxData { data: user_data, _ } = data; // user_data - data.data.take_unwrap() + data.data.take_get() } else { // The *next* person who sees the refcount hit 0 will wake us. let p1 = Cell::new(p1); // argh @@ -157,7 +157,7 @@ impl UnsafeAtomicRcBox { // let ~AtomicRcBoxData { data: user_data, _ } = data; // user_data let mut data = data; - data.data.take_unwrap() + data.data.take_get() }).finally { if task::failing() { // Killed during wait. Because this might happen while @@ -200,7 +200,7 @@ impl UnsafeAtomicRcBox { // Tell this handle's destructor not to run (we are now it). this.data = ptr::mut_null(); // FIXME(#3224) as above - Right(data.data.take_unwrap()) + Right(data.data.take_get()) } else { cast::forget(data); Left(this) @@ -594,7 +594,7 @@ mod tests { } // Have to get rid of our reference before blocking. util::ignore(x); - res.unwrap().recv(); + res.get().recv(); } #[test] #[should_fail] #[ignore(cfg(windows))] @@ -610,7 +610,7 @@ mod tests { } assert!(x.unwrap() == ~~"hello"); // See #4689 for why this can't be just "res.recv()". - assert!(res.unwrap().recv() == task::Success); + assert!(res.get().recv() == task::Success); } #[test] #[ignore(cfg(windows))] diff --git a/src/libstd/vec.rs b/src/libstd/vec.rs index 1f6adaf040b7e..adadf7a64a38a 100644 --- a/src/libstd/vec.rs +++ b/src/libstd/vec.rs @@ -1983,7 +1983,7 @@ pub mod raw { let mut box = Some(val); do v.as_mut_buf |p, _len| { intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), - box.take_unwrap()); + box.take_get()); } } @@ -2423,9 +2423,9 @@ mod tests { let mut a = ~[]; assert_eq!(a.head_opt(), None); a = ~[11]; - assert_eq!(a.head_opt().unwrap(), &11); + assert_eq!(a.head_opt().get(), &11); a = ~[11, 12]; - assert_eq!(a.head_opt().unwrap(), &11); + assert_eq!(a.head_opt().get(), &11); } #[test] @@ -2513,9 +2513,9 @@ mod tests { let mut a = ~[]; assert_eq!(a.last_opt(), None); a = ~[11]; - assert_eq!(a.last_opt().unwrap(), &11); + assert_eq!(a.last_opt().get(), &11); a = ~[11, 12]; - assert_eq!(a.last_opt().unwrap(), &12); + assert_eq!(a.last_opt().get(), &12); } #[test] @@ -3169,15 +3169,15 @@ mod tests { let xs = [1, 2, 5, 10, 11]; let mut it = xs.iter(); assert_eq!(it.size_hint(), (5, Some(5))); - assert_eq!(it.next().unwrap(), &1); + assert_eq!(it.next().get(), &1); assert_eq!(it.size_hint(), (4, Some(4))); - assert_eq!(it.next().unwrap(), &2); + assert_eq!(it.next().get(), &2); assert_eq!(it.size_hint(), (3, Some(3))); - assert_eq!(it.next().unwrap(), &5); + assert_eq!(it.next().get(), &5); assert_eq!(it.size_hint(), (2, Some(2))); - assert_eq!(it.next().unwrap(), &10); + assert_eq!(it.next().get(), &10); assert_eq!(it.size_hint(), (1, Some(1))); - assert_eq!(it.next().unwrap(), &11); + assert_eq!(it.next().get(), &11); assert_eq!(it.size_hint(), (0, Some(0))); assert!(it.next().is_none()); } @@ -3189,32 +3189,32 @@ mod tests { let mut it = xs.iter(); assert_eq!(it.indexable(), 5); - assert_eq!(it.idx(0).unwrap(), &1); - assert_eq!(it.idx(2).unwrap(), &5); - assert_eq!(it.idx(4).unwrap(), &11); + assert_eq!(it.idx(0).get(), &1); + assert_eq!(it.idx(2).get(), &5); + assert_eq!(it.idx(4).get(), &11); assert!(it.idx(5).is_none()); - assert_eq!(it.next().unwrap(), &1); + assert_eq!(it.next().get(), &1); assert_eq!(it.indexable(), 4); - assert_eq!(it.idx(0).unwrap(), &2); - assert_eq!(it.idx(3).unwrap(), &11); + assert_eq!(it.idx(0).get(), &2); + assert_eq!(it.idx(3).get(), &11); assert!(it.idx(4).is_none()); - assert_eq!(it.next().unwrap(), &2); + assert_eq!(it.next().get(), &2); assert_eq!(it.indexable(), 3); - assert_eq!(it.idx(1).unwrap(), &10); + assert_eq!(it.idx(1).get(), &10); assert!(it.idx(3).is_none()); - assert_eq!(it.next().unwrap(), &5); + assert_eq!(it.next().get(), &5); assert_eq!(it.indexable(), 2); - assert_eq!(it.idx(1).unwrap(), &11); + assert_eq!(it.idx(1).get(), &11); - assert_eq!(it.next().unwrap(), &10); + assert_eq!(it.next().get(), &10); assert_eq!(it.indexable(), 1); - assert_eq!(it.idx(0).unwrap(), &11); + assert_eq!(it.idx(0).get(), &11); assert!(it.idx(1).is_none()); - assert_eq!(it.next().unwrap(), &11); + assert_eq!(it.next().get(), &11); assert_eq!(it.indexable(), 0); assert!(it.idx(0).is_none()); diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 11f2c7005bcee..6bf9ca9716a5f 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -24,7 +24,7 @@ use extra::serialize::{Encodable, Decodable, Encoder, Decoder}; // 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 type CrateNum = int; 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, diff --git a/src/test/bench/core-map.rs b/src/test/bench/core-map.rs index 10d9c1a6b9b46..eded298b20b43 100644 --- a/src/test/bench/core-map.rs +++ b/src/test/bench/core-map.rs @@ -38,7 +38,7 @@ fn ascending>(map: &mut M, n_keys: uint) { do timed("search") { foreach i in range(0u, n_keys) { - assert_eq!(map.find(&i).unwrap(), &(i + 1)); + assert_eq!(map.find(&i).get(), &(i + 1)); } } @@ -61,7 +61,7 @@ fn descending>(map: &mut M, n_keys: uint) { do timed("search") { do uint::range_rev(n_keys, 0) |i| { - assert_eq!(map.find(&i).unwrap(), &(i + 1)); + assert_eq!(map.find(&i).get(), &(i + 1)); true }; } @@ -84,7 +84,7 @@ fn vector>(map: &mut M, n_keys: uint, dist: &[uint]) { do timed("search") { foreach i in range(0u, n_keys) { - assert_eq!(map.find(&dist[i]).unwrap(), &(i + 1)); + assert_eq!(map.find(&dist[i]).get(), &(i + 1)); } } diff --git a/src/test/bench/core-std.rs b/src/test/bench/core-std.rs index 100d9d673faf7..d94de836d9b3b 100644 --- a/src/test/bench/core-std.rs +++ b/src/test/bench/core-std.rs @@ -75,7 +75,7 @@ fn read_line() { .push_rel(&Path("src/test/bench/shootout-k-nucleotide.data")); foreach _ in range(0, 3) { - let reader = io::file_reader(&path).unwrap(); + let reader = io::file_reader(&path).get(); while !reader.eof() { reader.read_line(); } diff --git a/src/test/bench/graph500-bfs.rs b/src/test/bench/graph500-bfs.rs index 10bfb4f60ed63..99924aa23e280 100644 --- a/src/test/bench/graph500-bfs.rs +++ b/src/test/bench/graph500-bfs.rs @@ -140,7 +140,7 @@ fn bfs(graph: graph, key: node_id) -> bfs_result { marks[key] = key; while !q.is_empty() { - let t = q.pop_front().unwrap(); + let t = q.pop_front().get(); do graph[t].iter().advance |k| { if marks[*k] == -1i64 { diff --git a/src/test/bench/msgsend-ring-mutex-arcs.rs b/src/test/bench/msgsend-ring-mutex-arcs.rs index 626fa25766bdb..d3f9c891bf731 100644 --- a/src/test/bench/msgsend-ring-mutex-arcs.rs +++ b/src/test/bench/msgsend-ring-mutex-arcs.rs @@ -59,8 +59,8 @@ fn thread_ring(i: uint, count: uint, num_chan: pipe, num_port: pipe) { // Send/Receive lots of messages. foreach j in range(0u, count) { //error!("task %?, iter %?", i, j); - let num_chan2 = num_chan.take_unwrap(); - let num_port2 = num_port.take_unwrap(); + let num_chan2 = num_chan.take_get(); + let num_port2 = num_port.take_get(); send(&num_chan2, i * j); num_chan = Some(num_chan2); let _n = recv(&num_port2); diff --git a/src/test/bench/msgsend-ring-rw-arcs.rs b/src/test/bench/msgsend-ring-rw-arcs.rs index 1a92b8b2fe86b..beed13147b189 100644 --- a/src/test/bench/msgsend-ring-rw-arcs.rs +++ b/src/test/bench/msgsend-ring-rw-arcs.rs @@ -55,8 +55,8 @@ fn thread_ring(i: uint, count: uint, num_chan: pipe, num_port: pipe) { // Send/Receive lots of messages. foreach j in range(0u, count) { //error!("task %?, iter %?", i, j); - let num_chan2 = num_chan.take_unwrap(); - let num_port2 = num_port.take_unwrap(); + let num_chan2 = num_chan.take_get(); + let num_port2 = num_port.take_get(); send(&num_chan2, i * j); num_chan = Some(num_chan2); let _n = recv(&num_port2); diff --git a/src/test/bench/shootout-fasta.rs b/src/test/bench/shootout-fasta.rs index 6cee2c4e5ffea..96878eb513342 100644 --- a/src/test/bench/shootout-fasta.rs +++ b/src/test/bench/shootout-fasta.rs @@ -125,7 +125,7 @@ fn main() { let writer = if os::getenv("RUST_BENCH").is_some() { io::file_writer(&Path("./shootout-fasta.data"), - [io::Truncate, io::Create]).unwrap() + [io::Truncate, io::Create]).get() } else { io::stdout() }; diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index 6c40ede76825b..0ca91ca101467 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -161,7 +161,7 @@ fn main() { // get to this massive data set, but include_bin! chokes on it (#2598) let path = Path(env!("CFG_SRC_DIR")) .push_rel(&Path("src/test/bench/shootout-k-nucleotide.data")); - io::file_reader(&path).unwrap() + io::file_reader(&path).get() } else { io::stdin() }; @@ -175,7 +175,7 @@ fn main() { let to_child = do sizes.iter().zip(streams.mut_iter()).transform |(sz, stream_ref)| { let sz = *sz; let stream = util::replace(stream_ref, None); - let (from_child_, to_parent_) = stream.unwrap(); + let (from_child_, to_parent_) = stream.get(); from_child.push(from_child_); diff --git a/src/test/bench/task-perf-linked-failure.rs b/src/test/bench/task-perf-linked-failure.rs index 6ab83e5b3830b..e88e33302cec5 100644 --- a/src/test/bench/task-perf-linked-failure.rs +++ b/src/test/bench/task-perf-linked-failure.rs @@ -57,7 +57,7 @@ fn spawn_supervised_blocking(myname: &str, f: ~fn()) { builder.supervised(); builder.spawn(f); error!("%s group waiting", myname); - let x = res.unwrap().recv(); + let x = res.get().recv(); assert_eq!(x, task::Success); } diff --git a/src/test/compile-fail/arc-rw-cond-shouldnt-escape.rs b/src/test/compile-fail/arc-rw-cond-shouldnt-escape.rs index f8a3c5c573a0d..240c8ef0b1a18 100644 --- a/src/test/compile-fail/arc-rw-cond-shouldnt-escape.rs +++ b/src/test/compile-fail/arc-rw-cond-shouldnt-escape.rs @@ -17,5 +17,5 @@ fn main() { do x.write_cond |_one, cond| { y = Some(cond); } - y.unwrap().wait(); + y.get().wait(); } diff --git a/src/test/compile-fail/arc-rw-state-shouldnt-escape.rs b/src/test/compile-fail/arc-rw-state-shouldnt-escape.rs index 44657dfd0efe6..5b077746d8db4 100644 --- a/src/test/compile-fail/arc-rw-state-shouldnt-escape.rs +++ b/src/test/compile-fail/arc-rw-state-shouldnt-escape.rs @@ -16,7 +16,7 @@ fn main() { do x.write |one| { y = Some(one); } - *y.unwrap() = 2; + *y.get() = 2; //~^ ERROR lifetime of return value does not outlive the function call //~^^ ERROR dereference of reference outside its lifetime } diff --git a/src/test/compile-fail/arc-rw-write-mode-cond-shouldnt-escape.rs b/src/test/compile-fail/arc-rw-write-mode-cond-shouldnt-escape.rs index 44ac0e722d38a..ce7d04e640c1e 100644 --- a/src/test/compile-fail/arc-rw-write-mode-cond-shouldnt-escape.rs +++ b/src/test/compile-fail/arc-rw-write-mode-cond-shouldnt-escape.rs @@ -19,5 +19,5 @@ fn main() { y = Some(cond); } } - y.unwrap().wait(); + y.get().wait(); } diff --git a/src/test/compile-fail/sync-cond-shouldnt-escape.rs b/src/test/compile-fail/sync-cond-shouldnt-escape.rs index 928953de39088..a8956b423887a 100644 --- a/src/test/compile-fail/sync-cond-shouldnt-escape.rs +++ b/src/test/compile-fail/sync-cond-shouldnt-escape.rs @@ -18,5 +18,5 @@ fn main() { do m.lock_cond |c| { cond = Some(c); } - cond.unwrap().signal(); + cond.get().signal(); } diff --git a/src/test/compile-fail/sync-rwlock-cond-shouldnt-escape.rs b/src/test/compile-fail/sync-rwlock-cond-shouldnt-escape.rs index 03779b3ffe3d1..06283aa6a85b4 100644 --- a/src/test/compile-fail/sync-rwlock-cond-shouldnt-escape.rs +++ b/src/test/compile-fail/sync-rwlock-cond-shouldnt-escape.rs @@ -17,5 +17,5 @@ fn main() { do x.write_cond |cond| { y = Some(cond); } - y.unwrap().wait(); + y.get().wait(); } diff --git a/src/test/compile-fail/sync-rwlock-write-mode-cond-shouldnt-escape.rs b/src/test/compile-fail/sync-rwlock-write-mode-cond-shouldnt-escape.rs index fab16894a655a..823569c0be683 100644 --- a/src/test/compile-fail/sync-rwlock-write-mode-cond-shouldnt-escape.rs +++ b/src/test/compile-fail/sync-rwlock-write-mode-cond-shouldnt-escape.rs @@ -19,5 +19,5 @@ fn main() { y = Some(cond); } } - y.unwrap().wait(); + y.get().wait(); } diff --git a/src/test/run-fail/result-get-fail.rs b/src/test/run-fail/result-get-fail.rs index 782ce61cab253..fa232eb0de5c0 100644 --- a/src/test/run-fail/result-get-fail.rs +++ b/src/test/run-fail/result-get-fail.rs @@ -8,7 +8,7 @@ // 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::get()` on `Err` value: kitty use std::result; diff --git a/src/test/run-pass/class-impl-very-parameterized-trait.rs b/src/test/run-pass/class-impl-very-parameterized-trait.rs index 921b35b74375b..aa7c9e562ab98 100644 --- a/src/test/run-pass/class-impl-very-parameterized-trait.rs +++ b/src/test/run-pass/class-impl-very-parameterized-trait.rs @@ -118,7 +118,7 @@ impl cat { pub fn main() { let mut nyan: cat<~str> = cat::new(0, 2, ~"nyan"); foreach _ in range(1u, 5) { nyan.speak(); } - assert!(*nyan.find(&1).unwrap() == ~"nyan"); + assert!(*nyan.find(&1).get() == ~"nyan"); assert_eq!(nyan.find(&10), None); let mut spotty: cat = cat::new(2, 57, tuxedo); foreach _ in range(0u, 6) { spotty.speak(); } diff --git a/src/test/run-pass/issue-2718.rs b/src/test/run-pass/issue-2718.rs index fbd06c5e9cea1..7e6e0e8ca6d4b 100644 --- a/src/test/run-pass/issue-2718.rs +++ b/src/test/run-pass/issue-2718.rs @@ -113,7 +113,7 @@ pub mod pipes { empty | blocked => { task::yield(); } full => { let payload = util::replace(&mut p.payload, None); - return Some(payload.unwrap()) + return Some(payload.get()) } terminated => { assert_eq!(old_state, terminated); @@ -169,7 +169,7 @@ pub mod pipes { let self_p: &mut Option<*packet> = cast::transmute(&self.p); let p = util::replace(self_p, None); - sender_terminate(p.unwrap()) + sender_terminate(p.get()) } } } @@ -177,7 +177,7 @@ pub mod pipes { impl send_packet { pub fn unwrap(&mut self) -> *packet { - util::replace(&mut self.p, None).unwrap() + util::replace(&mut self.p, None).get() } } @@ -199,7 +199,7 @@ pub mod pipes { let self_p: &mut Option<*packet> = cast::transmute(&self.p); let p = util::replace(self_p, None); - receiver_terminate(p.unwrap()) + receiver_terminate(p.get()) } } } @@ -207,7 +207,7 @@ pub mod pipes { impl recv_packet { pub fn unwrap(&mut self) -> *packet { - util::replace(&mut self.p, None).unwrap() + util::replace(&mut self.p, None).get() } } @@ -272,7 +272,7 @@ pub mod pingpong { if packet.is_none() { fail!("sender closed the connection") } - (pingpong::liberate_pong(packet.unwrap()), ()) + (pingpong::liberate_pong(packet.get()), ()) } } @@ -287,7 +287,7 @@ pub mod pingpong { if packet.is_none() { fail!("sender closed the connection") } - (pingpong::liberate_ping(packet.unwrap()), ()) + (pingpong::liberate_ping(packet.get()), ()) } pub fn do_pong(c: pong) -> ping { diff --git a/src/test/run-pass/issue-4016.rs b/src/test/run-pass/issue-4016.rs index c4178961d9e69..841f671ac73d9 100644 --- a/src/test/run-pass/issue-4016.rs +++ b/src/test/run-pass/issue-4016.rs @@ -17,7 +17,7 @@ use extra::serialize::Decodable; trait JD : Decodable { } fn exec() { - let doc = json::from_str("").unwrap(); + let doc = json::from_str("").get(); let mut decoder = json::Decoder(doc); let _v: T = Decodable::decode(&mut decoder); fail!() diff --git a/src/test/run-pass/issue-4036.rs b/src/test/run-pass/issue-4036.rs index ad82071259593..6132d9ce2175b 100644 --- a/src/test/run-pass/issue-4036.rs +++ b/src/test/run-pass/issue-4036.rs @@ -16,7 +16,7 @@ use self::extra::json; use self::extra::serialize; pub fn main() { - let json = json::from_str("[1]").unwrap(); + let json = json::from_str("[1]").get(); let mut decoder = json::Decoder(json); let _x: ~[int] = serialize::Decodable::decode(&mut decoder); } diff --git a/src/test/run-pass/option_addition.rs b/src/test/run-pass/option_addition.rs index fe39d1b11d3b8..8ca7ec9bdc791 100644 --- a/src/test/run-pass/option_addition.rs +++ b/src/test/run-pass/option_addition.rs @@ -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:: + None::; + let somefoo = Some(foo) + None::; + let somebar = None:: + 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!(nope, None::); + assert_eq!(somefoo, None::); + assert_eq!(somebar, None::); assert_eq!(foobar, somefoobar.get()); } - -fn optint(input: int) -> Option { - if input == 0 { - return None; - } - else { - return Some(input); - } -} diff --git a/src/test/run-pass/stat.rs b/src/test/run-pass/stat.rs index babf5a2fa9089..57147daf3dbc0 100644 --- a/src/test/run-pass/stat.rs +++ b/src/test/run-pass/stat.rs @@ -19,7 +19,7 @@ use std::os; use std::uint; pub fn main() { - let dir = tempfile::mkdtemp(&Path("."), "").unwrap(); + let dir = tempfile::mkdtemp(&Path("."), "").get(); let path = dir.push("file"); { diff --git a/src/test/run-pass/task-comm-12.rs b/src/test/run-pass/task-comm-12.rs index fd2e81d062e8e..2a35fb7571077 100644 --- a/src/test/run-pass/task-comm-12.rs +++ b/src/test/run-pass/task-comm-12.rs @@ -33,7 +33,7 @@ fn test00() { } // Try joining tasks that have already finished. - result.unwrap().recv(); + result.get().recv(); info!("Joined task."); } diff --git a/src/test/run-pass/task-comm-9.rs b/src/test/run-pass/task-comm-9.rs index 86e3e24a3ee23..1a2fd448d088c 100644 --- a/src/test/run-pass/task-comm-9.rs +++ b/src/test/run-pass/task-comm-9.rs @@ -42,7 +42,7 @@ fn test00() { i += 1; } - result.unwrap().recv(); + result.get().recv(); assert_eq!(sum, number_of_messages * (number_of_messages - 1) / 2); } diff --git a/src/test/run-pass/yield.rs b/src/test/run-pass/yield.rs index 8beaee83864db..bd52d494ad68c 100644 --- a/src/test/run-pass/yield.rs +++ b/src/test/run-pass/yield.rs @@ -21,7 +21,7 @@ pub fn main() { error!("2"); task::yield(); error!("3"); - result.unwrap().recv(); + result.get().recv(); } fn child() { diff --git a/src/test/run-pass/yield1.rs b/src/test/run-pass/yield1.rs index 37ec8af7e57c8..0f77ac10922e4 100644 --- a/src/test/run-pass/yield1.rs +++ b/src/test/run-pass/yield1.rs @@ -18,7 +18,7 @@ pub fn main() { builder.spawn(child); error!("1"); task::yield(); - result.unwrap().recv(); + result.get().recv(); } fn child() { error!("2"); }