Auto merge of #46602 - mbrubeck:try, r=kennytm

Replace option_try macros and match with ? operator

None
This commit is contained in:
bors 2017-12-10 00:57:40 +00:00
commit c89e206eed
28 changed files with 92 additions and 230 deletions

View File

@ -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
@ -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))
}
@ -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)
}
@ -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()))
}

View File

@ -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();
}
}

View File

@ -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);

View File

@ -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))
}
}

View File

@ -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]

View File

@ -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)),
_ => {}
}

View File

@ -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 {

View File

@ -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

View File

@ -215,12 +215,6 @@ 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> {
@ -228,11 +222,11 @@ fn get_resident() -> Option<usize> {
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)
}

View File

@ -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));
}
}
}

View File

@ -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

View File

@ -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

View File

@ -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()
}

View File

@ -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() {
@ -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, &[]),
};

View File

@ -425,16 +425,14 @@ 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)) => {
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,
})
}
None => return None,
}
};
for component in &fqp[..fqp.len() - 1] {
url.push_str(component);

View File

@ -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) {
let path = self.cx.shared.local_sources.get(&path)?;
(&self.cx.shared.layout.krate, path)
} else {
return None;
}
} else {
// Macros from other libraries get special filenames which we can
// safely ignore.

View File

@ -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)
}

View File

@ -1152,16 +1152,12 @@ 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) => {
let elt = self.iter.next()?;
if self.other.contains(elt) {
return Some(elt);
}
}
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (_, upper) = self.iter.size_hint();
@ -1202,16 +1198,12 @@ 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) => {
let elt = self.iter.next()?;
if !self.other.contains(elt) {
return Some(elt);
}
}
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let (_, upper) = self.iter.size_hint();

View File

@ -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)) }

View File

@ -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]))

View File

@ -255,10 +255,7 @@ pub mod guard {
pub unsafe fn init() -> Option<usize> {
let psize = os::page_size();
let mut stackaddr = match get_stack_start() {
Some(addr) => addr,
None => return None,
};
let mut stackaddr = get_stack_start()?;
// Ensure stackaddr is page aligned! A parent process might
// have reset RLIMIT_STACK to be non-page aligned. The

View File

@ -136,10 +136,7 @@ impl Iterator for LookupHost {
fn next(&mut self) -> Option<SocketAddr> {
loop {
unsafe {
let cur = match self.cur.as_ref() {
None => return None,
Some(c) => c,
};
let cur = self.cur.as_ref()?;
self.cur = cur.ai_next;
match sockaddr_to_addr(mem::transmute(cur.ai_addr),
cur.ai_addrlen as usize)

View File

@ -578,10 +578,7 @@ impl Wtf8 {
fn next_surrogate(&self, mut pos: usize) -> Option<(usize, u16)> {
let mut iter = self.bytes[pos..].iter();
loop {
let b = match iter.next() {
None => return None,
Some(&b) => b,
};
let b = *iter.next()?;
if b < 0x80 {
pos += 1;
} else if b < 0xE0 {

View File

@ -1528,12 +1528,7 @@ impl<I: Iterator<Item = u16>> Iterator for DecodeUtf16<I> {
fn next(&mut self) -> Option<Result<char, DecodeUtf16Error>> {
let u = match self.buf.take() {
Some(buf) => buf,
None => {
match self.iter.next() {
Some(u) => u,
None => return None,
}
}
None => self.iter.next()?
};
if u < 0xD800 || 0xDFFF < u {

View File

@ -1123,10 +1123,7 @@ impl MetaItem {
_ => return None,
};
let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi());
let node = match MetaItemKind::from_tokens(tokens) {
Some(node) => node,
_ => return None,
};
let node = MetaItemKind::from_tokens(tokens)?;
let hi = match node {
MetaItemKind::NameValue(ref lit) => lit.span.hi(),
MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(span.hi()),
@ -1182,10 +1179,8 @@ impl MetaItemKind {
let mut tokens = delimited.into_trees().peekable();
let mut result = Vec::new();
while let Some(..) = tokens.peek() {
match NestedMetaItemKind::from_tokens(&mut tokens) {
Some(item) => result.push(respan(item.span(), item)),
None => return None,
}
let item = NestedMetaItemKind::from_tokens(&mut tokens)?;
result.push(respan(item.span(), item));
match tokens.next() {
None | Some(TokenTree::Token(_, Token::Comma)) => {}
_ => return None,

View File

@ -620,10 +620,7 @@ fn prepend_attrs(sess: &ParseSess,
span: syntax_pos::Span)
-> Option<tokenstream::TokenStream>
{
let tokens = match tokens {
Some(tokens) => tokens,
None => return None,
};
let tokens = tokens?;
if attrs.len() == 0 {
return Some(tokens.clone())
}

View File

@ -8,15 +8,6 @@
// option. This file may not be copied, modified, or distributed
// except according to those terms.
macro_rules! try_opt {
($e:expr) => {
match $e {
Some(v) => v,
None => return None,
}
};
}
pub mod printf {
use super::strcursor::StrCursor as Cur;
@ -173,7 +164,7 @@ pub mod printf {
s.push_str("{");
if let Some(arg) = self.parameter {
try_opt!(write!(s, "{}", try_opt!(arg.checked_sub(1))).ok());
write!(s, "{}", arg.checked_sub(1)?).ok()?;
}
if has_options {
@ -203,12 +194,12 @@ pub mod printf {
}
if let Some(width) = width {
try_opt!(width.translate(&mut s).ok());
width.translate(&mut s).ok()?;
}
if let Some(precision) = precision {
s.push_str(".");
try_opt!(precision.translate(&mut s).ok());
precision.translate(&mut s).ok()?;
}
if let Some(type_) = type_ {
@ -277,13 +268,9 @@ pub mod printf {
impl<'a> Iterator for Substitutions<'a> {
type Item = Substitution<'a>;
fn next(&mut self) -> Option<Self::Item> {
match parse_next_substitution(self.s) {
Some((sub, tail)) => {
let (sub, tail) = parse_next_substitution(self.s)?;
self.s = tail;
Some(sub)
},
None => None,
}
}
}
@ -303,11 +290,10 @@ pub mod printf {
use self::State::*;
let at = {
let start = try_opt!(s.find('%'));
match s[start+1..].chars().next() {
Some('%') => return Some((Substitution::Escape, &s[start+2..])),
Some(_) => {/* fall-through */},
None => return None,
let start = s.find('%')?;
match s[start+1..].chars().next()? {
'%' => return Some((Substitution::Escape, &s[start+2..])),
_ => {/* fall-through */},
}
Cur::new_at_start(&s[start..])
@ -335,16 +321,16 @@ pub mod printf {
// Used to establish the full span at the end.
let start = at;
// The current position within the string.
let mut at = try_opt!(at.at_next_cp());
let mut at = at.at_next_cp()?;
// `c` is the next codepoint, `next` is a cursor after it.
let (mut c, mut next) = try_opt!(at.next_cp());
let (mut c, mut next) = at.next_cp()?;
// Update `at`, `c`, and `next`, exiting if we're out of input.
macro_rules! move_to {
($cur:expr) => {
{
at = $cur;
let (c_, next_) = try_opt!(at.next_cp());
let (c_, next_) = at.next_cp()?;
c = c_;
next = next_;
}
@ -801,32 +787,28 @@ pub mod shell {
/// Parse the next substitution from the input string.
pub fn parse_next_substitution(s: &str) -> Option<(Substitution, &str)> {
let at = {
let start = try_opt!(s.find('$'));
match s[start+1..].chars().next() {
Some('$') => return Some((Substitution::Escape, &s[start+2..])),
Some(c @ '0' ... '9') => {
let start = s.find('$')?;
match s[start+1..].chars().next()? {
'$' => return Some((Substitution::Escape, &s[start+2..])),
c @ '0' ... '9' => {
let n = (c as u8) - b'0';
return Some((Substitution::Ordinal(n), &s[start+2..]));
},
Some(_) => {/* fall-through */},
None => return None,
_ => {/* fall-through */},
}
Cur::new_at_start(&s[start..])
};
let at = try_opt!(at.at_next_cp());
match at.next_cp() {
Some((c, inner)) => {
let at = at.at_next_cp()?;
let (c, inner) = at.next_cp()?;
if !is_ident_head(c) {
None
} else {
let end = at_next_cp_while(inner, is_ident_tail);
Some((Substitution::Name(at.slice_between(end).unwrap()), end.slice_after()))
}
},
_ => None
}
}
fn at_next_cp_while<F>(mut cur: Cur, mut pred: F) -> Cur
@ -946,10 +928,7 @@ mod strcursor {
}
pub fn next_cp(mut self) -> Option<(char, StrCursor<'a>)> {
let cp = match self.cp_after() {
Some(cp) => cp,
None => return None,
};
let cp = self.cp_after()?;
self.seek_right(cp.len_utf8());
Some((cp, self))
}

View File

@ -20,10 +20,7 @@ use std::path::PathBuf;
#[allow(deprecated)]
pub fn get_dbpath_for_term(term: &str) -> Option<PathBuf> {
let mut dirs_to_search = Vec::new();
let first_char = match term.chars().next() {
Some(c) => c,
None => return None,
};
let first_char = term.chars().next()?;
// Find search directory
if let Some(dir) = env::var_os("TERMINFO") {