2016-10-02 02:24:53 +08:00
|
|
|
use std::vec::Vec;
|
|
|
|
use std::string::String;
|
|
|
|
use std::btree_map::BTreeMap;
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
struct Entry {
|
2016-11-24 00:28:05 +08:00
|
|
|
data: Vec<i32>,
|
2016-10-02 02:24:53 +08:00
|
|
|
borrowed: bool
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct Cache {
|
|
|
|
entries: BTreeMap<String, Entry>
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Cache {
|
|
|
|
pub fn new() -> Cache {
|
|
|
|
Cache { entries: BTreeMap::new() }
|
|
|
|
}
|
|
|
|
|
2016-11-24 00:28:05 +08:00
|
|
|
pub fn get(&mut self, key: &str) -> *const [i32] {
|
2016-10-02 02:24:53 +08:00
|
|
|
match self.entries.get_mut(key) {
|
|
|
|
None => &[],
|
|
|
|
Some(ref mut entry) => {
|
|
|
|
entry.borrowed = true;
|
|
|
|
&entry.data[..]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-24 00:28:05 +08:00
|
|
|
pub fn put(&mut self, key: &str, data: &[i32]) -> Result<(), ()> {
|
2016-10-02 02:24:53 +08:00
|
|
|
match self.entries.get_mut(key) {
|
|
|
|
None => (),
|
|
|
|
Some(ref mut entry) => {
|
|
|
|
if entry.borrowed { return Err(()) }
|
|
|
|
entry.data = Vec::from(data);
|
|
|
|
return Ok(())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
self.entries.insert(String::from(key), Entry {
|
|
|
|
data: Vec::from(data),
|
|
|
|
borrowed: false
|
|
|
|
});
|
|
|
|
Ok(())
|
|
|
|
}
|
2016-10-06 22:19:12 +08:00
|
|
|
|
|
|
|
pub unsafe fn unborrow(&mut self) {
|
|
|
|
for (_key, entry) in self.entries.iter_mut() {
|
|
|
|
entry.borrowed = false;
|
|
|
|
}
|
|
|
|
}
|
2016-10-02 02:24:53 +08:00
|
|
|
}
|