Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Use Try syntax for Option in place of macros or match
  • Loading branch information
mbrubeck committed Dec 9, 2017
1 parent c7b6d82 commit 3024c14
Show file tree
Hide file tree
Showing 28 changed files with 92 additions and 230 deletions.
46 changes: 9 additions & 37 deletions src/liballoc/allocator.rs
Expand Up @@ -217,14 +217,8 @@ impl Layout {
/// On arithmetic overflow, returns `None`.
#[inline]
pub fn repeat(&self, n: usize) -> Option<(Self, usize)> {
let padded_size = match self.size.checked_add(self.padding_needed_for(self.align)) {
None => return None,
Some(padded_size) => padded_size,
};
let alloc_size = match padded_size.checked_mul(n) {
None => return None,
Some(alloc_size) => alloc_size,
};
let padded_size = self.size.checked_add(self.padding_needed_for(self.align))?;
let alloc_size = padded_size.checked_mul(n)?;

// We can assume that `self.align` is a power-of-two that does
// not exceed 2<sup>31</sup>. Furthermore, `alloc_size` has already been
Expand All @@ -246,26 +240,14 @@ impl Layout {
/// On arithmetic overflow, returns `None`.
pub fn extend(&self, next: Self) -> Option<(Self, usize)> {
let new_align = cmp::max(self.align, next.align);
let realigned = match Layout::from_size_align(self.size, new_align) {
None => return None,
Some(l) => l,
};
let realigned = Layout::from_size_align(self.size, new_align)?;

let pad = realigned.padding_needed_for(next.align);

let offset = match self.size.checked_add(pad) {
None => return None,
Some(offset) => offset,
};
let new_size = match offset.checked_add(next.size) {
None => return None,
Some(new_size) => new_size,
};
let offset = self.size.checked_add(pad)?;
let new_size = offset.checked_add(next.size)?;

let layout = match Layout::from_size_align(new_size, new_align) {
None => return None,
Some(l) => l,
};
let layout = Layout::from_size_align(new_size, new_align)?;
Some((layout, offset))
}

Expand All @@ -282,11 +264,7 @@ impl Layout {
///
/// On arithmetic overflow, returns `None`.
pub fn repeat_packed(&self, n: usize) -> Option<Self> {
let size = match self.size().checked_mul(n) {
None => return None,
Some(scaled) => scaled,
};

let size = self.size().checked_mul(n)?;
Layout::from_size_align(size, self.align)
}

Expand All @@ -306,14 +284,8 @@ impl Layout {
///
/// On arithmetic overflow, returns `None`.
pub fn extend_packed(&self, next: Self) -> Option<(Self, usize)> {
let new_size = match self.size().checked_add(next.size()) {
None => return None,
Some(new_size) => new_size,
};
let layout = match Layout::from_size_align(new_size, self.align) {
None => return None,
Some(l) => l,
};
let new_size = self.size().checked_add(next.size())?;
let layout = Layout::from_size_align(new_size, self.align)?;
Some((layout, self.size()))
}

Expand Down
14 changes: 4 additions & 10 deletions src/liballoc/btree/set.rs
Expand Up @@ -1067,21 +1067,15 @@ impl<'a, T: Ord> Iterator for Intersection<'a, T> {

fn next(&mut self) -> Option<&'a T> {
loop {
let o_cmp = match (self.a.peek(), self.b.peek()) {
(None, _) => None,
(_, None) => None,
(Some(a1), Some(b1)) => Some(a1.cmp(b1)),
};
match o_cmp {
None => return None,
Some(Less) => {
match Ord::cmp(self.a.peek()?, self.b.peek()?) {
Less => {
self.a.next();
}
Some(Equal) => {
Equal => {
self.b.next();
return self.a.next();
}
Some(Greater) => {
Greater => {
self.b.next();
}
}
Expand Down
5 changes: 1 addition & 4 deletions src/liballoc/string.rs
Expand Up @@ -1044,10 +1044,7 @@ impl String {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn pop(&mut self) -> Option<char> {
let ch = match self.chars().rev().next() {
Some(ch) => ch,
None => return None,
};
let ch = self.chars().rev().next()?;
let newlen = self.len() - ch.len_utf8();
unsafe {
self.vec.set_len(newlen);
Expand Down
5 changes: 1 addition & 4 deletions src/liballoc/vec.rs
Expand Up @@ -1423,10 +1423,7 @@ impl<T: PartialEq> Vec<T> {
/// ```
#[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
pub fn remove_item(&mut self, item: &T) -> Option<T> {
let pos = match self.iter().position(|x| *x == *item) {
Some(x) => x,
None => return None,
};
let pos = self.iter().position(|x| *x == *item)?;
Some(self.remove(pos))
}
}
Expand Down
9 changes: 4 additions & 5 deletions src/libcore/str/mod.rs
Expand Up @@ -494,11 +494,10 @@ fn unwrap_or_0(opt: Option<&u8>) -> u8 {
#[inline]
pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
// Decode UTF-8
let x = match bytes.next() {
None => return None,
Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32),
Some(&next_byte) => next_byte,
};
let x = *bytes.next()?;
if x < 128 {
return Some(x as u32)
}

// Multibyte case follows
// Decode from a byte combination out of: [[[x y] z] w]
Expand Down
5 changes: 2 additions & 3 deletions src/librustc/hir/map/mod.rs
Expand Up @@ -978,9 +978,8 @@ impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
// chain, then returns `None`.
fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
loop {
match map.find(id) {
None => return None,
Some(NodeItem(item)) if item_is_mod(&item) =>
match map.find(id)? {
NodeItem(item) if item_is_mod(&item) =>
return Some((id, item.name)),
_ => {}
}
Expand Down
6 changes: 2 additions & 4 deletions src/librustc/infer/error_reporting/util.rs
Expand Up @@ -91,10 +91,8 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
.iter()
.enumerate()
.filter_map(|(index, arg)| {
let ty = match tables.borrow().node_id_to_type_opt(arg.hir_id) {
Some(v) => v,
None => return None, // sometimes the tables are not yet populated
};
// May return None; sometimes the tables are not yet populated.
let ty = tables.borrow().node_id_to_type_opt(arg.hir_id)?;
let mut found_anon_region = false;
let new_arg_ty = self.tcx
.fold_regions(&ty, &mut false, |r, _| if *r == *anon_region {
Expand Down
7 changes: 1 addition & 6 deletions src/librustc/ty/util.rs
Expand Up @@ -439,12 +439,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
}
});

let dtor_did = match dtor_did {
Some(dtor) => dtor,
None => return None,
};

Some(ty::Destructor { did: dtor_did })
Some(ty::Destructor { did: dtor_did? })
}

/// Return the set of types that are required to be alive in
Expand Down
14 changes: 4 additions & 10 deletions src/librustc/util/common.rs
Expand Up @@ -215,24 +215,18 @@ pub fn record_time<T, F>(accu: &Cell<Duration>, f: F) -> T where
rv
}

// Like std::macros::try!, but for Option<>.
#[cfg(unix)]
macro_rules! option_try(
($e:expr) => (match $e { Some(e) => e, None => return None })
);

// Memory reporting
#[cfg(unix)]
fn get_resident() -> Option<usize> {
use std::fs::File;
use std::io::Read;

let field = 1;
let mut f = option_try!(File::open("/proc/self/statm").ok());
let mut f = File::open("/proc/self/statm").ok()?;
let mut contents = String::new();
option_try!(f.read_to_string(&mut contents).ok());
let s = option_try!(contents.split_whitespace().nth(field));
let npages = option_try!(s.parse::<usize>().ok());
f.read_to_string(&mut contents).ok()?;
let s = contents.split_whitespace().nth(field)?;
let npages = s.parse::<usize>().ok()?;
Some(npages * 4096)
}

Expand Down
6 changes: 2 additions & 4 deletions src/librustc_data_structures/indexed_set.rs
Expand Up @@ -291,10 +291,8 @@ impl<'a, T: Idx> Iterator for Iter<'a, T> {
}
}

match self.iter.next() {
Some((i, word)) => self.cur = Some((*word, word_bits * i)),
None => return None,
}
let (i, word) = self.iter.next()?;
self.cur = Some((*word, word_bits * i));
}
}
}
5 changes: 1 addition & 4 deletions src/librustc_metadata/creader.rs
Expand Up @@ -385,10 +385,7 @@ impl<'a> CrateLoader<'a> {
}

fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
let library = match locate_ctxt.maybe_load_library_crate() {
Some(lib) => lib,
None => return None,
};
let library = locate_ctxt.maybe_load_library_crate()?;

// In the case that we're loading a crate, but not matching
// against a hash, we could load a crate which has the same hash
Expand Down
5 changes: 1 addition & 4 deletions src/librustc_mir/borrow_check/mod.rs
Expand Up @@ -1982,10 +1982,7 @@ mod prefixes {
impl<'cx, 'gcx, 'tcx> Iterator for Prefixes<'cx, 'gcx, 'tcx> {
type Item = &'cx Place<'tcx>;
fn next(&mut self) -> Option<Self::Item> {
let mut cursor = match self.next {
None => return None,
Some(place) => place,
};
let mut cursor = self.next?;

// Post-processing `place`: Enqueue any remaining
// work. Also, `place` may not be a prefix itself, but
Expand Down
5 changes: 1 addition & 4 deletions src/librustc_trans/back/archive.rs
Expand Up @@ -120,10 +120,7 @@ impl<'a> ArchiveBuilder<'a> {
if let Some(ref a) = self.src_archive {
return a.as_ref()
}
let src = match self.config.src {
Some(ref src) => src,
None => return None,
};
let src = self.config.src.as_ref()?;
self.src_archive = Some(ArchiveRO::open(src).ok());
self.src_archive.as_ref().unwrap().as_ref()
}
Expand Down
11 changes: 3 additions & 8 deletions src/librustc_typeck/check/autoderef.rs
Expand Up @@ -79,10 +79,8 @@ impl<'a, 'gcx, 'tcx> Iterator for Autoderef<'a, 'gcx, 'tcx> {
let (kind, new_ty) = if let Some(mt) = self.cur_ty.builtin_deref(false, NoPreference) {
(AutoderefKind::Builtin, mt.ty)
} else {
match self.overloaded_deref_ty(self.cur_ty) {
Some(ty) => (AutoderefKind::Overloaded, ty),
_ => return None,
}
let ty = self.overloaded_deref_ty(self.cur_ty)?;
(AutoderefKind::Overloaded, ty)
};

if new_ty.references_error() {
Expand All @@ -108,10 +106,7 @@ impl<'a, 'gcx, 'tcx> Autoderef<'a, 'gcx, 'tcx> {

// <cur_ty as Deref>
let trait_ref = TraitRef {
def_id: match tcx.lang_items().deref_trait() {
Some(f) => f,
None => return None,
},
def_id: tcx.lang_items().deref_trait()?,
substs: tcx.mk_substs_trait(self.cur_ty, &[]),
};

Expand Down
16 changes: 7 additions & 9 deletions src/librustdoc/html/format.rs
Expand Up @@ -425,15 +425,13 @@ pub fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
Some(&(ref fqp, shortty)) => {
(fqp, shortty, repeat("../").take(loc.len()).collect())
}
None => match cache.external_paths.get(&did) {
Some(&(ref fqp, shortty)) => {
(fqp, shortty, match cache.extern_locations[&did.krate] {
(.., render::Remote(ref s)) => s.to_string(),
(.., render::Local) => repeat("../").take(loc.len()).collect(),
(.., render::Unknown) => return None,
})
}
None => return None,
None => {
let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
(fqp, shortty, match cache.extern_locations[&did.krate] {
(.., render::Remote(ref s)) => s.to_string(),
(.., render::Local) => repeat("../").take(loc.len()).collect(),
(.., render::Unknown) => return None,
})
}
};
for component in &fqp[..fqp.len() - 1] {
Expand Down
7 changes: 2 additions & 5 deletions src/librustdoc/html/render.rs
Expand Up @@ -1672,11 +1672,8 @@ impl<'a> Item<'a> {
let mut path = String::new();
let (krate, path) = if self.item.def_id.is_local() {
let path = PathBuf::from(&self.item.source.filename);
if let Some(path) = self.cx.shared.local_sources.get(&path) {
(&self.cx.shared.layout.krate, path)
} else {
return None;
}
let path = self.cx.shared.local_sources.get(&path)?;
(&self.cx.shared.layout.krate, path)
} else {
// Macros from other libraries get special filenames which we can
// safely ignore.
Expand Down
5 changes: 1 addition & 4 deletions src/libserialize/json.rs
Expand Up @@ -1052,10 +1052,7 @@ impl Json {
pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{
let mut target = self;
for key in keys {
match target.find(*key) {
Some(t) => { target = t; },
None => return None
}
target = target.find(*key)?;
}
Some(target)
}
Expand Down
20 changes: 6 additions & 14 deletions src/libstd/collections/hash/set.rs
Expand Up @@ -1152,13 +1152,9 @@ impl<'a, T, S> Iterator for Intersection<'a, T, S>

fn next(&mut self) -> Option<&'a T> {
loop {
match self.iter.next() {
None => return None,
Some(elt) => {
if self.other.contains(elt) {
return Some(elt);
}
}
let elt = self.iter.next()?;
if self.other.contains(elt) {
return Some(elt);
}
}
}
Expand Down Expand Up @@ -1202,13 +1198,9 @@ impl<'a, T, S> Iterator for Difference<'a, T, S>

fn next(&mut self) -> Option<&'a T> {
loop {
match self.iter.next() {
None => return None,
Some(elt) => {
if !self.other.contains(elt) {
return Some(elt);
}
}
let elt = self.iter.next()?;
if !self.other.contains(elt) {
return Some(elt);
}
}
}
Expand Down
7 changes: 3 additions & 4 deletions src/libstd/io/mod.rs
Expand Up @@ -2019,10 +2019,9 @@ impl<R: Read> Iterator for Chars<R> {
type Item = result::Result<char, CharsError>;

fn next(&mut self) -> Option<result::Result<char, CharsError>> {
let first_byte = match read_one_byte(&mut self.inner) {
None => return None,
Some(Ok(b)) => b,
Some(Err(e)) => return Some(Err(CharsError::Other(e))),
let first_byte = match read_one_byte(&mut self.inner)? {
Ok(b) => b,
Err(e) => return Some(Err(CharsError::Other(e))),
};
let width = core_str::utf8_char_width(first_byte);
if width == 1 { return Some(Ok(first_byte as char)) }
Expand Down
6 changes: 1 addition & 5 deletions src/libstd/net/parser.rs
Expand Up @@ -170,11 +170,7 @@ impl<'a> Parser<'a> {
return None;
}

let octet = self.read_number(10, 3, 0x100).map(|n| n as u8);
match octet {
Some(d) => bs[i] = d,
None => return None,
};
bs[i] = self.read_number(10, 3, 0x100).map(|n| n as u8)?;
i += 1;
}
Some(Ipv4Addr::new(bs[0], bs[1], bs[2], bs[3]))
Expand Down

0 comments on commit 3024c14

Please sign in to comment.