Skip to content

Instantly share code, notes, and snippets.

@niamster
Created May 3, 2017 00:34
Show Gist options
  • Save niamster/e753cf062c85d54de1a59060f1302216 to your computer and use it in GitHub Desktop.
Save niamster/e753cf062c85d54de1a59060f1302216 to your computer and use it in GitHub Desktop.
BTreeMap range test for woodpecker
use std::collections::BTreeMap;
use std::collections::Bound::Included;
static mut INC: i32 = 0;
fn inc() -> i32 {
unsafe {
INC += 1;
INC
}
}
fn find(map: &BTreeMap<&str, i32>, module: &str) -> Option<String> {
let top = module.split("::").nth(0).or(Some(module)).unwrap();
let mut range = map.range::<str, _>((Included(top), Included(module)));
let last = range.next_back();
if last.is_none() {
return None;
}
let (last, _) = last.unwrap();
if module.starts_with(last) {
return Some(last.to_string());
}
let first = range.next();
if first.is_none() {
return None;
}
let (first, _) = first.unwrap();
Some(first.to_string())
}
fn main() {
let mut map = BTreeMap::new();
let keys = vec![
"a",
"a::b",
"a::b::c",
"a::c::c",
"b",
"b::b",
"b::c::c",
"c",
"c::b",
"c::b::c",
"c::c::c",
];
for key in keys {
map.insert(key, inc());
}
println!("{:#?}", map);
println!("");
for module in &["b", "b::b", "b::b::c", "b::a", "b::c", "b::c::c", "d"] {
println!(">> Looking for '{}', found {:?}", module, find(&map, module));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment