Skip to content

Prefer is_empty to len() #23682

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 16, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/compiletest/compiletest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ pub fn make_metrics_test_closure(config: &Config, testfile: &Path) -> test::Test
fn extract_gdb_version(full_version_line: Option<String>) -> Option<String> {
match full_version_line {
Some(ref full_version_line)
if full_version_line.trim().len() > 0 => {
if !full_version_line.trim().is_empty() => {
let full_version_line = full_version_line.trim();

// used to be a regex "(^|[^0-9])([0-9]\.[0-9])([^0-9]|$)"
Expand Down Expand Up @@ -408,7 +408,7 @@ fn extract_lldb_version(full_version_line: Option<String>) -> Option<String> {

match full_version_line {
Some(ref full_version_line)
if full_version_line.trim().len() > 0 => {
if !full_version_line.trim().is_empty() => {
let full_version_line = full_version_line.trim();

for (pos, l) in full_version_line.char_indices() {
Expand All @@ -426,7 +426,7 @@ fn extract_lldb_version(full_version_line: Option<String>) -> Option<String> {
let vers = full_version_line[pos + 5..].chars().take_while(|c| {
c.is_digit(10)
}).collect::<String>();
if vers.len() > 0 { return Some(vers) }
if !vers.is_empty() { return Some(vers) }
}
println!("Could not extract LLDB version from line '{}'",
full_version_line);
Expand Down
4 changes: 2 additions & 2 deletions src/compiletest/runtest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -864,7 +864,7 @@ fn check_debugger_output(debugger_run_result: &ProcRes, check_lines: &[String])
}
first = false;
}
if !failed && rest.len() == 0 {
if !failed && rest.is_empty() {
i += 1;
}
if i == num_check_lines {
Expand Down Expand Up @@ -1662,7 +1662,7 @@ fn _arm_push_aux_shared_library(config: &Config, testfile: &Path) {
// codegen tests (vs. clang)

fn append_suffix_to_stem(p: &Path, suffix: &str) -> PathBuf {
if suffix.len() == 0 {
if suffix.is_empty() {
p.to_path_buf()
} else {
let mut stem = p.file_stem().unwrap().to_os_string();
Expand Down
2 changes: 1 addition & 1 deletion src/doc/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -3788,7 +3788,7 @@ its type parameters are types:

```ignore
fn map<A: Clone, B: Clone>(f: |A| -> B, xs: &[A]) -> Vec<B> {
if xs.len() == 0 {
if xs.is_empty() {
return vec![];
}
let first: B = f(xs[0].clone());
Expand Down
2 changes: 1 addition & 1 deletion src/libcollections/btree/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -692,7 +692,7 @@ mod stack {
// We've reached the root, so no matter what, we're done. We manually
// access the root via the tree itself to avoid creating any dangling
// pointers.
if self.map.root.len() == 0 && !self.map.root.is_leaf() {
if self.map.root.is_empty() && !self.map.root.is_leaf() {
// We've emptied out the root, so make its only child the new root.
// If it's a leaf, we just let it become empty.
self.map.depth -= 1;
Expand Down
7 changes: 5 additions & 2 deletions src/libcollections/btree/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,9 @@ impl <K, V> Node<K, V> {
self._len
}

/// Does the node not contain any key-value pairs
pub fn is_empty(&self) -> bool { self.len() == 0 }

/// How many key-value pairs the node can fit
pub fn capacity(&self) -> usize {
self._capacity
Expand Down Expand Up @@ -1097,7 +1100,7 @@ impl<K, V> Node<K, V> {
/// When a node has no keys or values and only a single edge, extract that edge.
pub fn hoist_lone_child(&mut self) {
// Necessary for correctness, but in a private module
debug_assert!(self.len() == 0);
debug_assert!(self.is_empty());
debug_assert!(!self.is_leaf());

unsafe {
Expand Down Expand Up @@ -1225,7 +1228,7 @@ impl<K, V> Node<K, V> {
/// because we have one too many, and our parent now has one too few
fn split(&mut self) -> (K, V, Node<K, V>) {
// Necessary for correctness, but in a private function
debug_assert!(self.len() > 0);
debug_assert!(!self.is_empty());

let mut right = if self.is_leaf() {
Node::new_leaf(self.capacity())
Expand Down
4 changes: 2 additions & 2 deletions src/libcore/char.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ impl CharExt for char {
#[inline]
pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> Option<usize> {
// Marked #[inline] to allow llvm optimizing it away
if code < MAX_ONE_B && dst.len() >= 1 {
if code < MAX_ONE_B && !dst.is_empty() {
dst[0] = code as u8;
Some(1)
} else if code < MAX_TWO_B && dst.len() >= 2 {
Expand Down Expand Up @@ -258,7 +258,7 @@ pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> Option<usize> {
#[inline]
pub fn encode_utf16_raw(mut ch: u32, dst: &mut [u16]) -> Option<usize> {
// Marked #[inline] to allow llvm optimizing it away
if (ch & 0xFFFF) == ch && dst.len() >= 1 {
if (ch & 0xFFFF) == ch && !dst.is_empty() {
// The BMP falls through (assuming non-surrogate, as it should)
dst[0] = ch as u16;
Some(1)
Expand Down
18 changes: 9 additions & 9 deletions src/libcore/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ impl<T> SliceExt for [T] {

#[inline]
fn first(&self) -> Option<&T> {
if self.len() == 0 { None } else { Some(&self[0]) }
if self.is_empty() { None } else { Some(&self[0]) }
}

#[inline]
Expand All @@ -217,7 +217,7 @@ impl<T> SliceExt for [T] {

#[inline]
fn last(&self) -> Option<&T> {
if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
if self.is_empty() { None } else { Some(&self[self.len() - 1]) }
}

#[inline]
Expand Down Expand Up @@ -296,7 +296,7 @@ impl<T> SliceExt for [T] {

#[inline]
fn first_mut(&mut self) -> Option<&mut T> {
if self.len() == 0 { None } else { Some(&mut self[0]) }
if self.is_empty() { None } else { Some(&mut self[0]) }
}

#[inline]
Expand Down Expand Up @@ -1306,7 +1306,7 @@ impl<'a, T> Iterator for Chunks<'a, T> {

#[inline]
fn next(&mut self) -> Option<&'a [T]> {
if self.v.len() == 0 {
if self.v.is_empty() {
None
} else {
let chunksz = cmp::min(self.v.len(), self.size);
Expand All @@ -1318,7 +1318,7 @@ impl<'a, T> Iterator for Chunks<'a, T> {

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
if self.v.len() == 0 {
if self.v.is_empty() {
(0, Some(0))
} else {
let n = self.v.len() / self.size;
Expand All @@ -1333,7 +1333,7 @@ impl<'a, T> Iterator for Chunks<'a, T> {
impl<'a, T> DoubleEndedIterator for Chunks<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<&'a [T]> {
if self.v.len() == 0 {
if self.v.is_empty() {
None
} else {
let remainder = self.v.len() % self.size;
Expand Down Expand Up @@ -1384,7 +1384,7 @@ impl<'a, T> Iterator for ChunksMut<'a, T> {

#[inline]
fn next(&mut self) -> Option<&'a mut [T]> {
if self.v.len() == 0 {
if self.v.is_empty() {
None
} else {
let sz = cmp::min(self.v.len(), self.chunk_size);
Expand All @@ -1397,7 +1397,7 @@ impl<'a, T> Iterator for ChunksMut<'a, T> {

#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
if self.v.len() == 0 {
if self.v.is_empty() {
(0, Some(0))
} else {
let n = self.v.len() / self.chunk_size;
Expand All @@ -1412,7 +1412,7 @@ impl<'a, T> Iterator for ChunksMut<'a, T> {
impl<'a, T> DoubleEndedIterator for ChunksMut<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<&'a mut [T]> {
if self.v.len() == 0 {
if self.v.is_empty() {
None
} else {
let remainder = self.v.len() % self.chunk_size;
Expand Down
2 changes: 1 addition & 1 deletion src/libcore/str/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1119,7 +1119,7 @@ enum OldSearcher {
impl OldSearcher {
#[allow(dead_code)]
fn new(haystack: &[u8], needle: &[u8]) -> OldSearcher {
if needle.len() == 0 {
if needle.is_empty() {
// Handle specially
unimplemented!()
// FIXME: Tune this.
Expand Down
2 changes: 1 addition & 1 deletion src/libcore/str/pattern.rs
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@ fn str_search_step<F, G>(mut m: &mut StrSearcher,
{
if m.state.done() {
SearchStep::Done
} else if m.needle.len() == 0 && m.start <= m.end {
} else if m.needle.is_empty() && m.start <= m.end {
// Case for needle == ""
if let State::Reject(a, b) = m.state.take() {
SearchStep::Reject(a, b)
Expand Down
4 changes: 2 additions & 2 deletions src/libfmt_macros/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ impl<'a> Parser<'a> {
None => {
let tmp = self.cur.clone();
match self.word() {
word if word.len() > 0 => {
word if !word.is_empty() => {
if self.consume('$') {
CountIsName(word)
} else {
Expand Down Expand Up @@ -463,7 +463,7 @@ mod tests {
fn musterr(s: &str) {
let mut p = Parser::new(s);
p.next();
assert!(p.errors.len() != 0);
assert!(!p.errors.is_empty());
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion src/libgetopts/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -804,7 +804,7 @@ fn format_option(opt: &OptGroup) -> String {
}

// Use short_name is possible, but fallback to long_name.
if opt.short_name.len() > 0 {
if !opt.short_name.is_empty() {
line.push('-');
line.push_str(&opt.short_name[..]);
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/liblog/directive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub fn parse_logging_spec(spec: &str) -> (Vec<LogDirective>, Option<String>) {
return (dirs, None);
}
mods.map(|m| { for s in m.split(',') {
if s.len() == 0 { continue }
if s.is_empty() { continue }
let mut parts = s.split('=');
let (log_level, name) = match (parts.next(), parts.next().map(|s| s.trim()), parts.next()) {
(Some(part0), None, None) => {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/metadata/creader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ pub fn validate_crate_name(sess: Option<&Session>, s: &str, sp: Option<Span>) {
(None, Some(sess)) => sess.err(s),
}
};
if s.len() == 0 {
if s.is_empty() {
say("crate name must not be empty");
}
for c in s.chars() {
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/metadata/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -767,7 +767,7 @@ pub fn get_enum_variants<'tcx>(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::Nod
get_type(cdata, field_ty.id.node, tcx).ty
})
.collect();
let arg_names = if arg_names.len() == 0 { None } else { Some(arg_names) };
let arg_names = if arg_names.is_empty() { None } else { Some(arg_names) };

(None, arg_tys, arg_names)
}
Expand Down Expand Up @@ -1383,7 +1383,7 @@ pub fn get_dylib_dependency_formats(cdata: Cmd)

debug!("found dylib deps: {}", formats.as_str_slice());
for spec in formats.as_str_slice().split(',') {
if spec.len() == 0 { continue }
if spec.is_empty() { continue }
let cnum = spec.split(':').nth(0).unwrap();
let link = spec.split(':').nth(1).unwrap();
let cnum: ast::CrateNum = cnum.parse().unwrap();
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/metadata/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,7 @@ fn each_auxiliary_node_id<F>(item: &ast::Item, callback: F) -> bool where
ast::ItemStruct(ref struct_def, _) => {
// If this is a newtype struct, return the constructor.
match struct_def.ctor_id {
Some(ctor_id) if struct_def.fields.len() > 0 &&
Some(ctor_id) if !struct_def.fields.is_empty() &&
struct_def.fields[0].node.kind.is_unnamed() => {
continue_ = callback(ctor_id);
}
Expand Down Expand Up @@ -1751,7 +1751,7 @@ fn encode_codemap(ecx: &EncodeContext, rbml_w: &mut Encoder) {

for filemap in &codemap.files.borrow()[..] {

if filemap.lines.borrow().len() == 0 || filemap.is_imported() {
if filemap.lines.borrow().is_empty() || filemap.is_imported() {
// No need to export empty filemaps, as they can't contain spans
// that need translation.
// Also no need to re-export imported filemaps, as any downstream
Expand Down
14 changes: 7 additions & 7 deletions src/librustc/metadata/loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,13 +307,13 @@ impl<'a> Context<'a> {
}

pub fn report_load_errs(&mut self) {
let message = if self.rejected_via_hash.len() > 0 {
let message = if !self.rejected_via_hash.is_empty() {
format!("found possibly newer version of crate `{}`",
self.ident)
} else if self.rejected_via_triple.len() > 0 {
} else if !self.rejected_via_triple.is_empty() {
format!("couldn't find crate `{}` with expected target triple {}",
self.ident, self.triple)
} else if self.rejected_via_kind.len() > 0 {
} else if !self.rejected_via_kind.is_empty() {
format!("found staticlib `{}` instead of rlib or dylib", self.ident)
} else {
format!("can't find crate for `{}`", self.ident)
Expand All @@ -325,15 +325,15 @@ impl<'a> Context<'a> {
};
self.sess.span_err(self.span, &message[..]);

if self.rejected_via_triple.len() > 0 {
if !self.rejected_via_triple.is_empty() {
let mismatches = self.rejected_via_triple.iter();
for (i, &CrateMismatch{ ref path, ref got }) in mismatches.enumerate() {
self.sess.fileline_note(self.span,
&format!("crate `{}`, path #{}, triple {}: {}",
self.ident, i+1, got, path.display()));
}
}
if self.rejected_via_hash.len() > 0 {
if !self.rejected_via_hash.is_empty() {
self.sess.span_note(self.span, "perhaps this crate needs \
to be recompiled?");
let mismatches = self.rejected_via_hash.iter();
Expand All @@ -353,7 +353,7 @@ impl<'a> Context<'a> {
}
}
}
if self.rejected_via_kind.len() > 0 {
if !self.rejected_via_kind.is_empty() {
self.sess.fileline_help(self.span, "please recompile this crate using \
--crate-type lib");
let mismatches = self.rejected_via_kind.iter();
Expand Down Expand Up @@ -517,7 +517,7 @@ impl<'a> Context<'a> {
// library's metadata sections. In theory we should
// read both, but reading dylib metadata is quite
// slow.
if m.len() == 0 {
if m.is_empty() {
return None
} else if m.len() == 1 {
return Some(m.into_iter().next().unwrap())
Expand Down
8 changes: 4 additions & 4 deletions src/librustc/middle/check_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ fn check_for_bindings_named_the_same_as_variants(cx: &MatchCheckCtxt, pat: &Pat)
if let Some(DefLocal(_)) = def {
if ty::enum_variants(cx.tcx, def_id).iter().any(|variant|
token::get_name(variant.name) == token::get_name(ident.node.name)
&& variant.args.len() == 0
&& variant.args.is_empty()
) {
span_warn!(cx.tcx.sess, p.span, E0170,
"pattern binding `{}` is named the same as one \
Expand Down Expand Up @@ -636,19 +636,19 @@ fn is_useful(cx: &MatchCheckCtxt,
-> Usefulness {
let &Matrix(ref rows) = matrix;
debug!("{:?}", matrix);
if rows.len() == 0 {
if rows.is_empty() {
return match witness {
ConstructWitness => UsefulWithWitness(vec!()),
LeaveOutWitness => Useful
};
}
if rows[0].len() == 0 {
if rows[0].is_empty() {
return NotUseful;
}
assert!(rows.iter().all(|r| r.len() == v.len()));
let real_pat = match rows.iter().find(|r| (*r)[0].id != DUMMY_NODE_ID) {
Some(r) => raw_pat(r[0]),
None if v.len() == 0 => return NotUseful,
None if v.is_empty() => return NotUseful,
None => v[0]
};
let left_ty = if real_pat.id == DUMMY_NODE_ID {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/dead.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {

fn mark_live_symbols(&mut self) {
let mut scanned = HashSet::new();
while self.worklist.len() > 0 {
while !self.worklist.is_empty() {
let id = self.worklist.pop().unwrap();
if scanned.contains(&id) {
continue
Expand Down
Loading