1
Fork 0

Use Try syntax for Option in place of macros or match

This commit is contained in:
Matt Brubeck 2017-12-08 17:32:04 -08:00
parent c7b6d8263b
commit 3024c1434a
28 changed files with 92 additions and 230 deletions

View file

@ -217,14 +217,8 @@ impl Layout {
/// On arithmetic overflow, returns `None`. /// On arithmetic overflow, returns `None`.
#[inline] #[inline]
pub fn repeat(&self, n: usize) -> Option<(Self, usize)> { pub fn repeat(&self, n: usize) -> Option<(Self, usize)> {
let padded_size = match self.size.checked_add(self.padding_needed_for(self.align)) { let padded_size = self.size.checked_add(self.padding_needed_for(self.align))?;
None => return None, let alloc_size = padded_size.checked_mul(n)?;
Some(padded_size) => padded_size,
};
let alloc_size = match padded_size.checked_mul(n) {
None => return None,
Some(alloc_size) => alloc_size,
};
// We can assume that `self.align` is a power-of-two that does // 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 // not exceed 2<sup>31</sup>. Furthermore, `alloc_size` has already been
@ -246,26 +240,14 @@ impl Layout {
/// On arithmetic overflow, returns `None`. /// On arithmetic overflow, returns `None`.
pub fn extend(&self, next: Self) -> Option<(Self, usize)> { pub fn extend(&self, next: Self) -> Option<(Self, usize)> {
let new_align = cmp::max(self.align, next.align); let new_align = cmp::max(self.align, next.align);
let realigned = match Layout::from_size_align(self.size, new_align) { let realigned = Layout::from_size_align(self.size, new_align)?;
None => return None,
Some(l) => l,
};
let pad = realigned.padding_needed_for(next.align); let pad = realigned.padding_needed_for(next.align);
let offset = match self.size.checked_add(pad) { let offset = self.size.checked_add(pad)?;
None => return None, let new_size = offset.checked_add(next.size)?;
Some(offset) => offset,
};
let new_size = match offset.checked_add(next.size) {
None => return None,
Some(new_size) => new_size,
};
let layout = match Layout::from_size_align(new_size, new_align) { let layout = Layout::from_size_align(new_size, new_align)?;
None => return None,
Some(l) => l,
};
Some((layout, offset)) Some((layout, offset))
} }
@ -282,11 +264,7 @@ impl Layout {
/// ///
/// On arithmetic overflow, returns `None`. /// On arithmetic overflow, returns `None`.
pub fn repeat_packed(&self, n: usize) -> Option<Self> { pub fn repeat_packed(&self, n: usize) -> Option<Self> {
let size = match self.size().checked_mul(n) { let size = self.size().checked_mul(n)?;
None => return None,
Some(scaled) => scaled,
};
Layout::from_size_align(size, self.align) Layout::from_size_align(size, self.align)
} }
@ -306,14 +284,8 @@ impl Layout {
/// ///
/// On arithmetic overflow, returns `None`. /// On arithmetic overflow, returns `None`.
pub fn extend_packed(&self, next: Self) -> Option<(Self, usize)> { pub fn extend_packed(&self, next: Self) -> Option<(Self, usize)> {
let new_size = match self.size().checked_add(next.size()) { let new_size = self.size().checked_add(next.size())?;
None => return None, let layout = Layout::from_size_align(new_size, self.align)?;
Some(new_size) => new_size,
};
let layout = match Layout::from_size_align(new_size, self.align) {
None => return None,
Some(l) => l,
};
Some((layout, self.size())) 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> { fn next(&mut self) -> Option<&'a T> {
loop { loop {
let o_cmp = match (self.a.peek(), self.b.peek()) { match Ord::cmp(self.a.peek()?, self.b.peek()?) {
(None, _) => None, Less => {
(_, None) => None,
(Some(a1), Some(b1)) => Some(a1.cmp(b1)),
};
match o_cmp {
None => return None,
Some(Less) => {
self.a.next(); self.a.next();
} }
Some(Equal) => { Equal => {
self.b.next(); self.b.next();
return self.a.next(); return self.a.next();
} }
Some(Greater) => { Greater => {
self.b.next(); self.b.next();
} }
} }

View file

@ -1044,10 +1044,7 @@ impl String {
#[inline] #[inline]
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub fn pop(&mut self) -> Option<char> { pub fn pop(&mut self) -> Option<char> {
let ch = match self.chars().rev().next() { let ch = self.chars().rev().next()?;
Some(ch) => ch,
None => return None,
};
let newlen = self.len() - ch.len_utf8(); let newlen = self.len() - ch.len_utf8();
unsafe { unsafe {
self.vec.set_len(newlen); 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")] #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
pub fn remove_item(&mut self, item: &T) -> Option<T> { pub fn remove_item(&mut self, item: &T) -> Option<T> {
let pos = match self.iter().position(|x| *x == *item) { let pos = self.iter().position(|x| *x == *item)?;
Some(x) => x,
None => return None,
};
Some(self.remove(pos)) Some(self.remove(pos))
} }
} }

View file

@ -494,11 +494,10 @@ fn unwrap_or_0(opt: Option<&u8>) -> u8 {
#[inline] #[inline]
pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> { pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
// Decode UTF-8 // Decode UTF-8
let x = match bytes.next() { let x = *bytes.next()?;
None => return None, if x < 128 {
Some(&next_byte) if next_byte < 128 => return Some(next_byte as u32), return Some(x as u32)
Some(&next_byte) => next_byte, }
};
// Multibyte case follows // Multibyte case follows
// Decode from a byte combination out of: [[[x y] z] w] // 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`. // chain, then returns `None`.
fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> { fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
loop { loop {
match map.find(id) { match map.find(id)? {
None => return None, NodeItem(item) if item_is_mod(&item) =>
Some(NodeItem(item)) if item_is_mod(&item) =>
return Some((id, item.name)), return Some((id, item.name)),
_ => {} _ => {}
} }

View file

@ -91,10 +91,8 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
.iter() .iter()
.enumerate() .enumerate()
.filter_map(|(index, arg)| { .filter_map(|(index, arg)| {
let ty = match tables.borrow().node_id_to_type_opt(arg.hir_id) { // May return None; sometimes the tables are not yet populated.
Some(v) => v, let ty = tables.borrow().node_id_to_type_opt(arg.hir_id)?;
None => return None, // sometimes the tables are not yet populated
};
let mut found_anon_region = false; let mut found_anon_region = false;
let new_arg_ty = self.tcx let new_arg_ty = self.tcx
.fold_regions(&ty, &mut false, |r, _| if *r == *anon_region { .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(ty::Destructor { did: dtor_did? })
Some(dtor) => dtor,
None => return None,
};
Some(ty::Destructor { did: dtor_did })
} }
/// Return the set of types that are required to be alive in /// 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 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 // Memory reporting
#[cfg(unix)] #[cfg(unix)]
fn get_resident() -> Option<usize> { fn get_resident() -> Option<usize> {
@ -228,11 +222,11 @@ fn get_resident() -> Option<usize> {
use std::io::Read; use std::io::Read;
let field = 1; 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(); let mut contents = String::new();
option_try!(f.read_to_string(&mut contents).ok()); f.read_to_string(&mut contents).ok()?;
let s = option_try!(contents.split_whitespace().nth(field)); let s = contents.split_whitespace().nth(field)?;
let npages = option_try!(s.parse::<usize>().ok()); let npages = s.parse::<usize>().ok()?;
Some(npages * 4096) Some(npages * 4096)
} }

View file

@ -291,10 +291,8 @@ impl<'a, T: Idx> Iterator for Iter<'a, T> {
} }
} }
match self.iter.next() { let (i, word) = self.iter.next()?;
Some((i, word)) => self.cur = Some((*word, word_bits * i)), self.cur = Some((*word, word_bits * i));
None => return None,
}
} }
} }
} }

View file

@ -385,10 +385,7 @@ impl<'a> CrateLoader<'a> {
} }
fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> { fn load(&mut self, locate_ctxt: &mut locator::Context) -> Option<LoadResult> {
let library = match locate_ctxt.maybe_load_library_crate() { let library = locate_ctxt.maybe_load_library_crate()?;
Some(lib) => lib,
None => return None,
};
// In the case that we're loading a crate, but not matching // 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 // 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> { impl<'cx, 'gcx, 'tcx> Iterator for Prefixes<'cx, 'gcx, 'tcx> {
type Item = &'cx Place<'tcx>; type Item = &'cx Place<'tcx>;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
let mut cursor = match self.next { let mut cursor = self.next?;
None => return None,
Some(place) => place,
};
// Post-processing `place`: Enqueue any remaining // Post-processing `place`: Enqueue any remaining
// work. Also, `place` may not be a prefix itself, but // 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 { if let Some(ref a) = self.src_archive {
return a.as_ref() return a.as_ref()
} }
let src = match self.config.src { let src = self.config.src.as_ref()?;
Some(ref src) => src,
None => return None,
};
self.src_archive = Some(ArchiveRO::open(src).ok()); self.src_archive = Some(ArchiveRO::open(src).ok());
self.src_archive.as_ref().unwrap().as_ref() 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) { let (kind, new_ty) = if let Some(mt) = self.cur_ty.builtin_deref(false, NoPreference) {
(AutoderefKind::Builtin, mt.ty) (AutoderefKind::Builtin, mt.ty)
} else { } else {
match self.overloaded_deref_ty(self.cur_ty) { let ty = self.overloaded_deref_ty(self.cur_ty)?;
Some(ty) => (AutoderefKind::Overloaded, ty), (AutoderefKind::Overloaded, ty)
_ => return None,
}
}; };
if new_ty.references_error() { if new_ty.references_error() {
@ -108,10 +106,7 @@ impl<'a, 'gcx, 'tcx> Autoderef<'a, 'gcx, 'tcx> {
// <cur_ty as Deref> // <cur_ty as Deref>
let trait_ref = TraitRef { let trait_ref = TraitRef {
def_id: match tcx.lang_items().deref_trait() { def_id: tcx.lang_items().deref_trait()?,
Some(f) => f,
None => return None,
},
substs: tcx.mk_substs_trait(self.cur_ty, &[]), 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)) => { Some(&(ref fqp, shortty)) => {
(fqp, shortty, repeat("../").take(loc.len()).collect()) (fqp, shortty, repeat("../").take(loc.len()).collect())
} }
None => match cache.external_paths.get(&did) { None => {
Some(&(ref fqp, shortty)) => { let &(ref fqp, shortty) = cache.external_paths.get(&did)?;
(fqp, shortty, match cache.extern_locations[&did.krate] { (fqp, shortty, match cache.extern_locations[&did.krate] {
(.., render::Remote(ref s)) => s.to_string(), (.., render::Remote(ref s)) => s.to_string(),
(.., render::Local) => repeat("../").take(loc.len()).collect(), (.., render::Local) => repeat("../").take(loc.len()).collect(),
(.., render::Unknown) => return None, (.., render::Unknown) => return None,
}) })
} }
None => return None,
}
}; };
for component in &fqp[..fqp.len() - 1] { for component in &fqp[..fqp.len() - 1] {
url.push_str(component); url.push_str(component);

View file

@ -1672,11 +1672,8 @@ impl<'a> Item<'a> {
let mut path = String::new(); let mut path = String::new();
let (krate, path) = if self.item.def_id.is_local() { let (krate, path) = if self.item.def_id.is_local() {
let path = PathBuf::from(&self.item.source.filename); 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) (&self.cx.shared.layout.krate, path)
} else {
return None;
}
} else { } else {
// Macros from other libraries get special filenames which we can // Macros from other libraries get special filenames which we can
// safely ignore. // safely ignore.

View file

@ -1052,10 +1052,7 @@ impl Json {
pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{ pub fn find_path<'a>(&'a self, keys: &[&str]) -> Option<&'a Json>{
let mut target = self; let mut target = self;
for key in keys { for key in keys {
match target.find(*key) { target = target.find(*key)?;
Some(t) => { target = t; },
None => return None
}
} }
Some(target) 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> { fn next(&mut self) -> Option<&'a T> {
loop { loop {
match self.iter.next() { let elt = self.iter.next()?;
None => return None,
Some(elt) => {
if self.other.contains(elt) { if self.other.contains(elt) {
return Some(elt); return Some(elt);
} }
} }
} }
}
}
fn size_hint(&self) -> (usize, Option<usize>) { fn size_hint(&self) -> (usize, Option<usize>) {
let (_, upper) = self.iter.size_hint(); 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> { fn next(&mut self) -> Option<&'a T> {
loop { loop {
match self.iter.next() { let elt = self.iter.next()?;
None => return None,
Some(elt) => {
if !self.other.contains(elt) { if !self.other.contains(elt) {
return Some(elt); return Some(elt);
} }
} }
} }
}
}
fn size_hint(&self) -> (usize, Option<usize>) { fn size_hint(&self) -> (usize, Option<usize>) {
let (_, upper) = self.iter.size_hint(); 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>; type Item = result::Result<char, CharsError>;
fn next(&mut self) -> Option<result::Result<char, CharsError>> { fn next(&mut self) -> Option<result::Result<char, CharsError>> {
let first_byte = match read_one_byte(&mut self.inner) { let first_byte = match read_one_byte(&mut self.inner)? {
None => return None, Ok(b) => b,
Some(Ok(b)) => b, Err(e) => return Some(Err(CharsError::Other(e))),
Some(Err(e)) => return Some(Err(CharsError::Other(e))),
}; };
let width = core_str::utf8_char_width(first_byte); let width = core_str::utf8_char_width(first_byte);
if width == 1 { return Some(Ok(first_byte as char)) } if width == 1 { return Some(Ok(first_byte as char)) }

View file

@ -170,11 +170,7 @@ impl<'a> Parser<'a> {
return None; return None;
} }
let octet = self.read_number(10, 3, 0x100).map(|n| n as u8); bs[i] = self.read_number(10, 3, 0x100).map(|n| n as u8)?;
match octet {
Some(d) => bs[i] = d,
None => return None,
};
i += 1; i += 1;
} }
Some(Ipv4Addr::new(bs[0], bs[1], bs[2], bs[3])) 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> { pub unsafe fn init() -> Option<usize> {
let psize = os::page_size(); let psize = os::page_size();
let mut stackaddr = match get_stack_start() { let mut stackaddr = get_stack_start()?;
Some(addr) => addr,
None => return None,
};
// Ensure stackaddr is page aligned! A parent process might // Ensure stackaddr is page aligned! A parent process might
// have reset RLIMIT_STACK to be non-page aligned. The // 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> { fn next(&mut self) -> Option<SocketAddr> {
loop { loop {
unsafe { unsafe {
let cur = match self.cur.as_ref() { let cur = self.cur.as_ref()?;
None => return None,
Some(c) => c,
};
self.cur = cur.ai_next; self.cur = cur.ai_next;
match sockaddr_to_addr(mem::transmute(cur.ai_addr), match sockaddr_to_addr(mem::transmute(cur.ai_addr),
cur.ai_addrlen as usize) cur.ai_addrlen as usize)

View file

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

View file

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

View file

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

View file

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

View file

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