1
Fork 0

don't use Result::ok just to be able to use unwrap/unwrap_or

This commit is contained in:
Oliver Schneider 2015-03-20 08:19:13 +01:00
parent 0084f92302
commit b4a1e59146
21 changed files with 62 additions and 53 deletions

View file

@ -78,7 +78,7 @@
//! let bad_result: Result<int, int> = bad_result.or_else(|i| Ok(11)); //! let bad_result: Result<int, int> = bad_result.or_else(|i| Ok(11));
//! //!
//! // Consume the result and return the contents with `unwrap`. //! // Consume the result and return the contents with `unwrap`.
//! let final_awesome_result = good_result.ok().unwrap(); //! let final_awesome_result = good_result.unwrap();
//! ``` //! ```
//! //!
//! # Results must be used //! # Results must be used
@ -460,7 +460,7 @@ impl<T, E> Result<T, E> {
/// line.trim_right().parse::<int>().unwrap_or(0) /// line.trim_right().parse::<int>().unwrap_or(0)
/// }); /// });
/// // Add the value if there were no errors, otherwise add 0 /// // Add the value if there were no errors, otherwise add 0
/// sum += val.ok().unwrap_or(0); /// sum += val.unwrap_or(0);
/// } /// }
/// ///
/// assert!(sum == 10); /// assert!(sum == 10);

View file

@ -43,6 +43,7 @@ use std::io::SeekFrom;
use std::io::prelude::*; use std::io::prelude::*;
use std::num::FromPrimitive; use std::num::FromPrimitive;
use std::rc::Rc; use std::rc::Rc;
use std::fmt::Debug;
use rbml::reader; use rbml::reader;
use rbml::writer::Encoder; use rbml::writer::Encoder;
@ -298,9 +299,11 @@ trait def_id_encoder_helpers {
fn emit_def_id(&mut self, did: ast::DefId); fn emit_def_id(&mut self, did: ast::DefId);
} }
impl<S:serialize::Encoder> def_id_encoder_helpers for S { impl<S:serialize::Encoder> def_id_encoder_helpers for S
where <S as serialize::serialize::Encoder>::Error: Debug
{
fn emit_def_id(&mut self, did: ast::DefId) { fn emit_def_id(&mut self, did: ast::DefId) {
did.encode(self).ok().unwrap() did.encode(self).unwrap()
} }
} }
@ -310,15 +313,18 @@ trait def_id_decoder_helpers {
cdata: &cstore::crate_metadata) -> ast::DefId; cdata: &cstore::crate_metadata) -> ast::DefId;
} }
impl<D:serialize::Decoder> def_id_decoder_helpers for D { impl<D:serialize::Decoder> def_id_decoder_helpers for D
where <D as serialize::serialize::Decoder>::Error: Debug
{
fn read_def_id(&mut self, dcx: &DecodeContext) -> ast::DefId { fn read_def_id(&mut self, dcx: &DecodeContext) -> ast::DefId {
let did: ast::DefId = Decodable::decode(self).ok().unwrap(); let did: ast::DefId = Decodable::decode(self).unwrap();
did.tr(dcx) did.tr(dcx)
} }
fn read_def_id_nodcx(&mut self, fn read_def_id_nodcx(&mut self,
cdata: &cstore::crate_metadata) -> ast::DefId { cdata: &cstore::crate_metadata)
let did: ast::DefId = Decodable::decode(self).ok().unwrap(); -> ast::DefId {
let did: ast::DefId = Decodable::decode(self).unwrap();
decoder::translate_def_id(cdata, did) decoder::translate_def_id(cdata, did)
} }
} }
@ -1769,7 +1775,7 @@ impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> {
fn read_closure_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>) fn read_closure_kind<'b, 'c>(&mut self, _dcx: &DecodeContext<'b, 'c, 'tcx>)
-> ty::ClosureKind -> ty::ClosureKind
{ {
Decodable::decode(self).ok().unwrap() Decodable::decode(self).unwrap()
} }
fn read_closure_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>) fn read_closure_ty<'b, 'c>(&mut self, dcx: &DecodeContext<'b, 'c, 'tcx>)

View file

@ -54,10 +54,10 @@ fn replace_newline_with_backslash_l(s: String) -> String {
} }
impl<'a, 'ast> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a, 'ast> { impl<'a, 'ast> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a, 'ast> {
fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new(&self.name[..]).ok().unwrap() } fn graph_id(&'a self) -> dot::Id<'a> { dot::Id::new(&self.name[..]).unwrap() }
fn node_id(&'a self, &(i,_): &Node<'a>) -> dot::Id<'a> { fn node_id(&'a self, &(i,_): &Node<'a>) -> dot::Id<'a> {
dot::Id::new(format!("N{}", i.node_id())).ok().unwrap() dot::Id::new(format!("N{}", i.node_id())).unwrap()
} }
fn node_label(&'a self, &(i, n): &Node<'a>) -> dot::LabelText<'a> { fn node_label(&'a self, &(i, n): &Node<'a>) -> dot::LabelText<'a> {

View file

@ -69,13 +69,13 @@ pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a,
return; return;
} }
let requested_output = env::var("RUST_REGION_GRAPH").ok(); let requested_output = env::var("RUST_REGION_GRAPH");
debug!("requested_output: {:?} requested_node: {:?}", debug!("requested_output: {:?} requested_node: {:?}",
requested_output, requested_node); requested_output, requested_node);
let output_path = { let output_path = {
let output_template = match requested_output { let output_template = match requested_output {
Some(ref s) if &**s == "help" => { Ok(ref s) if &**s == "help" => {
static PRINTED_YET: AtomicBool = ATOMIC_BOOL_INIT; static PRINTED_YET: AtomicBool = ATOMIC_BOOL_INIT;
if !PRINTED_YET.load(Ordering::SeqCst) { if !PRINTED_YET.load(Ordering::SeqCst) {
print_help_message(); print_help_message();
@ -84,8 +84,8 @@ pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a,
return; return;
} }
Some(other_path) => other_path, Ok(other_path) => other_path,
None => "/tmp/constraints.node%.dot".to_string(), Err(_) => "/tmp/constraints.node%.dot".to_string(),
}; };
if output_template.len() == 0 { if output_template.len() == 0 {
@ -171,7 +171,7 @@ impl<'a, 'tcx> ConstraintGraph<'a, 'tcx> {
impl<'a, 'tcx> dot::Labeller<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { impl<'a, 'tcx> dot::Labeller<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> {
fn graph_id(&self) -> dot::Id { fn graph_id(&self) -> dot::Id {
dot::Id::new(&*self.graph_name).ok().unwrap() dot::Id::new(&*self.graph_name).unwrap()
} }
fn node_id(&self, n: &Node) -> dot::Id { fn node_id(&self, n: &Node) -> dot::Id {
let node_id = match self.node_ids.get(n) { let node_id = match self.node_ids.get(n) {

View file

@ -491,7 +491,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for StaticInitializerCtxt<'a, 'tcx> {
if let ast::ExprAddrOf(mutbl, ref base) = ex.node { if let ast::ExprAddrOf(mutbl, ref base) = ex.node {
let param_env = ty::empty_parameter_environment(self.bccx.tcx); let param_env = ty::empty_parameter_environment(self.bccx.tcx);
let mc = mc::MemCategorizationContext::new(&param_env); let mc = mc::MemCategorizationContext::new(&param_env);
let base_cmt = mc.cat_expr(&**base).ok().unwrap(); let base_cmt = mc.cat_expr(&**base).unwrap();
let borrow_kind = ty::BorrowKind::from_mutbl(mutbl); let borrow_kind = ty::BorrowKind::from_mutbl(mutbl);
// Check that we don't allow borrows of unsafe static items. // Check that we don't allow borrows of unsafe static items.
if check_aliasability(self.bccx, ex.span, euv::AddrOf, if check_aliasability(self.bccx, ex.span, euv::AddrOf,

View file

@ -1532,7 +1532,7 @@ mod tests {
#[test] #[test]
fn binary_file() { fn binary_file() {
let mut bytes = [0; 1024]; let mut bytes = [0; 1024];
StdRng::new().ok().unwrap().fill_bytes(&mut bytes); StdRng::new().unwrap().fill_bytes(&mut bytes);
let tmpdir = tmpdir(); let tmpdir = tmpdir();

View file

@ -277,7 +277,7 @@ mod tests {
fn read_to_end() { fn read_to_end() {
let mut reader = Cursor::new(vec!(0, 1, 2, 3, 4, 5, 6, 7)); let mut reader = Cursor::new(vec!(0, 1, 2, 3, 4, 5, 6, 7));
let mut v = Vec::new(); let mut v = Vec::new();
reader.read_to_end(&mut v).ok().unwrap(); reader.read_to_end(&mut v).unwrap();
assert_eq!(v, [0, 1, 2, 3, 4, 5, 6, 7]); assert_eq!(v, [0, 1, 2, 3, 4, 5, 6, 7]);
} }

View file

@ -617,7 +617,7 @@ mod tests {
unique_local: bool, global: bool, unique_local: bool, global: bool,
u_link_local: bool, u_site_local: bool, u_global: bool, u_link_local: bool, u_site_local: bool, u_global: bool,
m_scope: Option<Ipv6MulticastScope>) { m_scope: Option<Ipv6MulticastScope>) {
let ip: Ipv6Addr = str_addr.parse().ok().unwrap(); let ip: Ipv6Addr = str_addr.parse().unwrap();
assert_eq!(str_addr, ip.to_string()); assert_eq!(str_addr, ip.to_string());
assert_eq!(ip.is_unspecified(), unspec); assert_eq!(ip.is_unspecified(), unspec);

View file

@ -1608,7 +1608,7 @@ mod test {
use rand::{StdRng, Rng}; use rand::{StdRng, Rng};
let mut bytes = [0; 1024]; let mut bytes = [0; 1024];
StdRng::new().ok().unwrap().fill_bytes(&mut bytes); StdRng::new().unwrap().fill_bytes(&mut bytes);
let tmpdir = tmpdir(); let tmpdir = tmpdir();

View file

@ -592,7 +592,7 @@ impl<T: Send> Sender<T> {
// asleep (we're looking at it), so the receiver // asleep (we're looking at it), so the receiver
// can't go away. // can't go away.
(*a.get()).send(t).ok().unwrap(); (*a.get()).send(t).ok().unwrap();
token.signal(); token.signal();
(a, Ok(())) (a, Ok(()))
} }
} }

View file

@ -454,7 +454,7 @@ fn output(w: &mut Write, idx: int, addr: *mut libc::c_void,
#[allow(dead_code)] #[allow(dead_code)]
fn output_fileline(w: &mut Write, file: &[u8], line: libc::c_int, fn output_fileline(w: &mut Write, file: &[u8], line: libc::c_int,
more: bool) -> io::Result<()> { more: bool) -> io::Result<()> {
let file = str::from_utf8(file).ok().unwrap_or("<unknown>"); let file = str::from_utf8(file).unwrap_or("<unknown>");
// prior line: " ##: {:2$} - func" // prior line: " ##: {:2$} - func"
try!(write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH)); try!(write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH));
if more { if more {

View file

@ -391,7 +391,7 @@ mod tests {
let mut reader = FileDesc::new(reader, true); let mut reader = FileDesc::new(reader, true);
let mut writer = FileDesc::new(writer, true); let mut writer = FileDesc::new(writer, true);
writer.write(b"test").ok().unwrap(); writer.write(b"test").unwrap();
let mut buf = [0; 4]; let mut buf = [0; 4];
match reader.read(&mut buf) { match reader.read(&mut buf) {
Ok(4) => { Ok(4) => {

View file

@ -23,7 +23,7 @@ pub fn new() -> (signal, signal) {
} }
pub fn signal(fd: libc::c_int) { pub fn signal(fd: libc::c_int) {
FileDesc::new(fd, false).write(&[0]).ok().unwrap(); FileDesc::new(fd, false).write(&[0]).unwrap();
} }
pub fn close(fd: libc::c_int) { pub fn close(fd: libc::c_int) {

View file

@ -197,7 +197,7 @@ fn helper(input: libc::c_int, messages: Receiver<Req>, _: ()) {
// drain the file descriptor // drain the file descriptor
let mut buf = [0]; let mut buf = [0];
assert_eq!(fd.read(&mut buf).ok().unwrap(), 1); assert_eq!(fd.read(&mut buf).unwrap(), 1);
} }
-1 if os::errno() == libc::EINTR as i32 => {} -1 if os::errno() == libc::EINTR as i32 => {}

View file

@ -757,10 +757,10 @@ impl UnixAcceptor {
impl Clone for UnixAcceptor { impl Clone for UnixAcceptor {
fn clone(&self) -> UnixAcceptor { fn clone(&self) -> UnixAcceptor {
let name = to_utf16(&self.listener.name).ok().unwrap(); let name = to_utf16(&self.listener.name).unwrap();
UnixAcceptor { UnixAcceptor {
inner: self.inner.clone(), inner: self.inner.clone(),
event: Event::new(true, false).ok().unwrap(), event: Event::new(true, false).unwrap(),
deadline: 0, deadline: 0,
listener: UnixListener { listener: UnixListener {
name: self.listener.name.clone(), name: self.listener.name.clone(),

View file

@ -869,7 +869,7 @@ mod test {
Err(e) => { Err(e) => {
type T = &'static str; type T = &'static str;
assert!(e.is::<T>()); assert!(e.is::<T>());
assert_eq!(*e.downcast::<T>().ok().unwrap(), "static string"); assert_eq!(*e.downcast::<T>().unwrap(), "static string");
} }
Ok(()) => panic!() Ok(()) => panic!()
} }
@ -883,7 +883,7 @@ mod test {
Err(e) => { Err(e) => {
type T = String; type T = String;
assert!(e.is::<T>()); assert!(e.is::<T>());
assert_eq!(*e.downcast::<T>().ok().unwrap(), "owned string".to_string()); assert_eq!(*e.downcast::<T>().unwrap(), "owned string".to_string());
} }
Ok(()) => panic!() Ok(()) => panic!()
} }
@ -897,9 +897,9 @@ mod test {
Err(e) => { Err(e) => {
type T = Box<Any + Send>; type T = Box<Any + Send>;
assert!(e.is::<T>()); assert!(e.is::<T>());
let any = e.downcast::<T>().ok().unwrap(); let any = e.downcast::<T>().unwrap();
assert!(any.is::<u16>()); assert!(any.is::<u16>());
assert_eq!(*any.downcast::<u16>().ok().unwrap(), 413); assert_eq!(*any.downcast::<u16>().unwrap(), 413);
} }
Ok(()) => panic!() Ok(()) => panic!()
} }

View file

@ -64,7 +64,7 @@
//! fn encode(&self, s: &mut S) -> Result<(), E> { //! fn encode(&self, s: &mut S) -> Result<(), E> {
//! s.emit_struct("Spanned", 2, |this| { //! s.emit_struct("Spanned", 2, |this| {
//! this.emit_struct_field("node", 0, |this| self.node.encode(this)) //! this.emit_struct_field("node", 0, |this| self.node.encode(this))
//! .ok().unwrap(); //! .unwrap();
//! this.emit_struct_field("span", 1, |this| self.span.encode(this)) //! this.emit_struct_field("span", 1, |this| self.span.encode(this))
//! }) //! })
//! } //! }
@ -79,9 +79,9 @@
//! d.read_struct("Spanned", 2, |this| { //! d.read_struct("Spanned", 2, |this| {
//! Ok(Spanned { //! Ok(Spanned {
//! node: this.read_struct_field("node", 0, |this| Decodable::decode(this)) //! node: this.read_struct_field("node", 0, |this| Decodable::decode(this))
//! .ok().unwrap(), //! .unwrap(),
//! span: this.read_struct_field("span", 1, |this| Decodable::decode(this)) //! span: this.read_struct_field("span", 1, |this| Decodable::decode(this))
//! .ok().unwrap(), //! .unwrap(),
//! }) //! })
//! }) //! })
//! } //! }

View file

@ -623,7 +623,7 @@ impl<'a> StringReader<'a> {
// find the integer representing the name // find the integer representing the name
self.scan_digits(base); self.scan_digits(base);
let encoded_name : u32 = self.with_str_from(start_bpos, |s| { let encoded_name : u32 = self.with_str_from(start_bpos, |s| {
num::from_str_radix(s, 10).ok().unwrap_or_else(|| { num::from_str_radix(s, 10).unwrap_or_else(|_| {
panic!("expected digits representing a name, got {:?}, {}, range [{:?},{:?}]", panic!("expected digits representing a name, got {:?}, {}, range [{:?},{:?}]",
s, whence, start_bpos, self.last_pos); s, whence, start_bpos, self.last_pos);
}) })
@ -641,7 +641,7 @@ impl<'a> StringReader<'a> {
let start_bpos = self.last_pos; let start_bpos = self.last_pos;
self.scan_digits(base); self.scan_digits(base);
let encoded_ctxt : ast::SyntaxContext = self.with_str_from(start_bpos, |s| { let encoded_ctxt : ast::SyntaxContext = self.with_str_from(start_bpos, |s| {
num::from_str_radix(s, 10).ok().unwrap_or_else(|| { num::from_str_radix(s, 10).unwrap_or_else(|_| {
panic!("expected digits representing a ctxt, got {:?}, {}", s, whence); panic!("expected digits representing a ctxt, got {:?}, {}", s, whence);
}) })
}); });

View file

@ -181,21 +181,24 @@ impl<T: Write+Send+'static> TerminfoTerminal<T> {
} }
}; };
let entry = open(&term[..]); let mut file = match open(&term[..]) {
if entry.is_err() { Ok(f) => f,
if env::var("MSYSCON").ok().map_or(false, |s| { Err(err) => return match env::var("MSYSCON") {
"mintty.exe" == s Ok(ref val) if &val[..] == "mintty.exe" => {
}) { // msys terminal
// msys terminal Some(box TerminfoTerminal{
return Some(box TerminfoTerminal {out: out, out: out,
ti: msys_terminfo(), ti: msys_terminfo(),
num_colors: 8} as Box<Terminal<T>+Send>); num_colors: 8,
} } as Box<Terminal<T>+Send>)
debug!("error finding terminfo entry: {:?}", entry.err().unwrap()); },
return None; _ => {
} debug!("error finding terminfo entry: {:?}", err);
None
},
},
};
let mut file = entry.unwrap();
let ti = parse(&mut file, false); let ti = parse(&mut file, false);
if ti.is_err() { if ti.is_err() {
debug!("error parsing terminfo entry: {:?}", ti.err().unwrap()); debug!("error parsing terminfo entry: {:?}", ti.err().unwrap());

View file

@ -12,7 +12,7 @@ use std::thread;
pub fn main() { pub fn main() {
let t = thread::spawn(move|| child((10, 20, 30, 40, 50, 60, 70, 80, 90)) ); let t = thread::spawn(move|| child((10, 20, 30, 40, 50, 60, 70, 80, 90)) );
t.join().ok().unwrap(); t.join().ok().unwrap(); // forget Err value, since it doesn't implement Debug
} }
fn child(args: (int, int, int, int, int, int, int, int, int)) { fn child(args: (int, int, int, int, int, int, int, int, int)) {

View file

@ -26,6 +26,6 @@ pub fn main() {
let _b = Foo; let _b = Foo;
}).join(); }).join();
let s = x.err().unwrap().downcast::<&'static str>().ok().unwrap(); let s = x.err().unwrap().downcast::<&'static str>().unwrap();
assert_eq!(&**s, "This panic should happen."); assert_eq!(&**s, "This panic should happen.");
} }