Skip to content

Commit 8a32676

Browse files
author
blake2-ppc
committed
deque: Move the shorter part when growing
The deque is split at the marker lo, or logical index 0. Move the shortest part (split by lo) when growing. This way add_front is just as fast as add_back, on average.
1 parent 75015c3 commit 8a32676

File tree

1 file changed

+25
-7
lines changed

1 file changed

+25
-7
lines changed

src/libextra/deque.rs

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ impl<T> Deque<T> {
108108
/// Prepend an element to the deque
109109
pub fn add_front(&mut self, t: T) {
110110
if self.nelts == self.elts.len() {
111-
grow(self.nelts, self.lo, &mut self.elts);
111+
grow(self.nelts, &mut self.lo, &mut self.elts);
112112
}
113113
if self.lo == 0u {
114114
self.lo = self.elts.len() - 1u;
@@ -120,7 +120,7 @@ impl<T> Deque<T> {
120120
/// Append an element to the deque
121121
pub fn add_back(&mut self, t: T) {
122122
if self.nelts == self.elts.len() {
123-
grow(self.nelts, self.lo, &mut self.elts);
123+
grow(self.nelts, &mut self.lo, &mut self.elts);
124124
}
125125
let hi = self.raw_index(self.nelts);
126126
self.elts[hi] = Some(t);
@@ -230,18 +230,36 @@ iterator!{impl DequeMutRevIterator -> &'self mut T, get_mut_ref, -1}
230230

231231
/// Grow is only called on full elts, so nelts is also len(elts), unlike
232232
/// elsewhere.
233-
fn grow<T>(nelts: uint, lo: uint, elts: &mut ~[Option<T>]) {
233+
fn grow<T>(nelts: uint, loptr: &mut uint, elts: &mut ~[Option<T>]) {
234234
assert_eq!(nelts, elts.len());
235-
let newlen = elts.capacity() * 2;
235+
let lo = *loptr;
236+
let newlen = nelts * 2;
236237
elts.reserve(newlen);
237238

238239
/* fill with None */
239240
for uint::range(elts.len(), elts.capacity()) |_| {
240241
elts.push(None);
241242
}
242-
/* move the former wraparound to the new half */
243-
for uint::range(0, lo) |i| {
244-
elts.swap(i, nelts + i);
243+
244+
/*
245+
Move the shortest half into the newly reserved area.
246+
lo ---->|
247+
nelts ----------->|
248+
[o o o|o o o o o]
249+
A [. . .|o o o o o o o o|. . . . .]
250+
B [o o o|. . . . . . . .|o o o o o]
251+
*/
252+
253+
assert!(newlen - nelts/2 >= nelts);
254+
if lo <= (nelts - lo) { // A
255+
for uint::range(0, lo) |i| {
256+
elts.swap(i, nelts + i);
257+
}
258+
} else { // B
259+
for uint::range(lo, nelts) |i| {
260+
elts.swap(i, newlen - nelts + i);
261+
}
262+
*loptr += newlen - nelts;
245263
}
246264
}
247265

0 commit comments

Comments
 (0)