Skip to content

Commit 8299f3a

Browse files
ericktbrson
authored andcommitted
libcore: add send_map::with_find_ref and with_get_ref.
1 parent 35a418e commit 8299f3a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/libcore/send_map.rs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ trait SendMap<K:Eq Hash, V: Copy> {
2222
fn each_value_ref(&self, blk: fn(v: &V) -> bool);
2323
fn find(&const self, k: &K) -> Option<V>;
2424
fn get(&const self, k: &K) -> V;
25+
fn with_find_ref<T>(&const self, k: &K, blk: fn(Option<&V>) -> T) -> T;
26+
fn with_get_ref<T>(&const self, k: &K, blk: fn(v: &V) -> T) -> T;
2527
}
2628

2729
/// Open addressing with linear probing.
@@ -290,6 +292,27 @@ mod linear {
290292
}
291293
*/
292294

295+
fn with_find_ref<T>(&self, k: &K, blk: fn(Option<&V>) -> T) -> T {
296+
match self.bucket_for_key(self.buckets, k) {
297+
FoundEntry(idx) => {
298+
match self.buckets[idx] {
299+
Some(bkt) => blk(Some(&bkt.value)),
300+
None => fail ~"LinearMap::find: internal logic error"
301+
}
302+
}
303+
TableFull | FoundHole(_) => blk(None),
304+
}
305+
}
306+
307+
fn with_get_ref<T>(&self, k: &K, blk: fn(v: &V) -> T) -> T {
308+
do self.with_find_ref(k) |v| {
309+
match v {
310+
Some(v) => blk(v),
311+
None => fail fmt!("No entry found for key: %?", k),
312+
}
313+
}
314+
}
315+
293316
fn each_ref(&self, blk: fn(k: &K, v: &V) -> bool) {
294317
for vec::each(self.buckets) |slot| {
295318
let mut broke = false;
@@ -426,4 +449,12 @@ mod test {
426449
}
427450
assert observed == 0xFFFF_FFFF;
428451
}
452+
453+
#[test]
454+
fn with_find_ref() {
455+
let mut m = ~LinearMap();
456+
m.with_find_ref(&1, |v| assert v.is_none());
457+
m.insert(1, 2);
458+
m.with_find_ref(&1, |v| assert *v.get() == 2);
459+
}
429460
}

0 commit comments

Comments
 (0)