Skip to content

Commit 45f14a8

Browse files
committed
refactor len and contains to iterate instead of recurse
1 parent 070c83d commit 45f14a8

File tree

1 file changed

+16
-40
lines changed

1 file changed

+16
-40
lines changed

src/librustc_data_structures/tiny_list.rs

+16-40
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ pub struct TinyList<T: PartialEq> {
2020
}
2121

2222
impl<T: PartialEq> TinyList<T> {
23-
2423
#[inline]
2524
pub fn new() -> TinyList<T> {
2625
TinyList {
@@ -60,20 +59,24 @@ impl<T: PartialEq> TinyList<T> {
6059

6160
#[inline]
6261
pub fn contains(&self, data: &T) -> bool {
63-
if let Some(ref head) = self.head {
64-
head.contains(data)
65-
} else {
66-
false
62+
let mut elem = self.head.as_ref();
63+
while let Some(ref e) = elem {
64+
if &e.data == data {
65+
return true;
66+
}
67+
elem = e.next.as_ref().map(|e| &**e);
6768
}
69+
false
6870
}
6971

7072
#[inline]
7173
pub fn len(&self) -> usize {
72-
if let Some(ref head) = self.head {
73-
head.len()
74-
} else {
75-
0
74+
let (mut elem, mut count) = (self.head.as_ref(), 0);
75+
while let Some(ref e) = elem {
76+
count += 1;
77+
elem = e.next.as_ref().map(|e| &**e);
7678
}
79+
count
7780
}
7881
}
7982

@@ -84,40 +87,13 @@ struct Element<T: PartialEq> {
8487
}
8588

8689
impl<T: PartialEq> Element<T> {
87-
8890
fn remove_next(&mut self, data: &T) -> bool {
89-
let new_next = if let Some(ref mut next) = self.next {
90-
if next.data != *data {
91-
return next.remove_next(data)
92-
} else {
93-
next.next.take()
94-
}
95-
} else {
96-
return false
91+
let new_next = match self.next {
92+
Some(ref mut next) if next.data == *data => next.next.take(),
93+
Some(ref mut next) => return next.remove_next(data),
94+
None => return false,
9795
};
98-
9996
self.next = new_next;
100-
10197
true
10298
}
103-
104-
fn len(&self) -> usize {
105-
if let Some(ref next) = self.next {
106-
1 + next.len()
107-
} else {
108-
1
109-
}
110-
}
111-
112-
fn contains(&self, data: &T) -> bool {
113-
if self.data == *data {
114-
return true
115-
}
116-
117-
if let Some(ref next) = self.next {
118-
next.contains(data)
119-
} else {
120-
false
121-
}
122-
}
12399
}

0 commit comments

Comments
 (0)