1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use std::collections::BTreeMap;
use std::io::Read;
use std::ops::{Deref, DerefMut};
use tikv_util::codec::number::{self, NumberEncoder};
use tikv_util::codec::Result;
#[derive(Clone, Debug, Default)]
pub struct IndexHandle {
pub size: u64,
pub offset: u64,
}
#[derive(Debug, Default)]
pub struct IndexHandles(BTreeMap<Vec<u8>, IndexHandle>);
impl Deref for IndexHandles {
type Target = BTreeMap<Vec<u8>, IndexHandle>;
fn deref(&self) -> &BTreeMap<Vec<u8>, IndexHandle> {
&self.0
}
}
impl DerefMut for IndexHandles {
fn deref_mut(&mut self) -> &mut BTreeMap<Vec<u8>, IndexHandle> {
&mut self.0
}
}
impl IndexHandles {
pub fn new() -> IndexHandles {
IndexHandles(BTreeMap::new())
}
pub fn into_map(self) -> BTreeMap<Vec<u8>, IndexHandle> {
self.0
}
pub fn add(&mut self, key: Vec<u8>, index_handle: IndexHandle) {
self.0.insert(key, index_handle);
}
pub fn encode(&self) -> Vec<u8> {
let mut buf = Vec::with_capacity(1024);
for (k, v) in &self.0 {
buf.encode_u64(k.len() as u64).unwrap();
buf.extend(k);
buf.encode_u64(v.size).unwrap();
buf.encode_u64(v.offset).unwrap();
}
buf
}
pub fn decode(mut buf: &[u8]) -> Result<IndexHandles> {
let mut res = BTreeMap::new();
while !buf.is_empty() {
let klen = number::decode_u64(&mut buf)?;
let mut k = vec![0; klen as usize];
buf.read_exact(&mut k)?;
let v = IndexHandle {
size: number::decode_u64(&mut buf)?,
offset: number::decode_u64(&mut buf)?,
};
res.insert(k, v);
}
Ok(IndexHandles(res))
}
}
pub trait DecodeProperties {
fn decode(&self, k: &str) -> Result<&[u8]>;
fn decode_u64(&self, k: &str) -> Result<u64> {
let mut buf = self.decode(k)?;
number::decode_u64(&mut buf)
}
fn decode_handles(&self, k: &str) -> Result<IndexHandles> {
let buf = self.decode(k)?;
IndexHandles::decode(buf)
}
}