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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
use std::fmt::{self, Write};
use std::ops::Deref;
use crate::buffer::{BufReader, BufWriter, DecodeError};
use crate::hash::hash_bytes;
#[derive(Debug, Copy, Clone, PartialEq, Ord, PartialOrd, Eq, Hash)]
pub enum DataKey {
Data(InlineData),
Hash(super::Hash),
}
const MAX_INLINE: usize = 31;
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InlineData {
len: u8,
buf: [u8; MAX_INLINE],
}
impl InlineData {
#[inline]
pub fn from_bytes(b: &[u8]) -> Option<Self> {
let mut buf = [0; MAX_INLINE];
let sub_buf = buf.get_mut(..b.len())?;
sub_buf.copy_from_slice(b);
Some(Self {
len: b.len() as u8,
buf,
})
}
}
impl Deref for InlineData {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.buf[..self.len as usize]
}
}
impl fmt::Debug for InlineData {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_char('"')?;
fmt::Display::fmt(&(**self).escape_ascii(), f)?;
f.write_char('"')
}
}
const IS_HASH_BIT: u8 = 0b1000_0000;
impl DataKey {
pub fn from_data(data: impl AsRef<[u8]>) -> Self {
let data = data.as_ref();
match InlineData::from_bytes(data) {
Some(data) => DataKey::Data(data),
None => DataKey::Hash(hash_bytes(data)),
}
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut data_key_summary = Vec::new();
self.encode(&mut data_key_summary);
data_key_summary
}
pub fn decode<'a>(bytes: &mut impl BufReader<'a>) -> Result<Self, DecodeError> {
let header = bytes.get_u8()?;
let is_hash = (header & IS_HASH_BIT) != 0;
if is_hash {
if header != IS_HASH_BIT {
return Err(DecodeError::InvalidTag);
}
let hash = super::hash::Hash {
data: bytes.get_array()?,
};
Ok(Self::Hash(hash))
} else {
let len = header;
if len as usize > MAX_INLINE {
return Err(DecodeError::BufferLength);
}
let mut buf = [0; MAX_INLINE];
let data = bytes.get_slice(len as usize)?;
buf[..len as usize].copy_from_slice(data);
Ok(Self::Data(InlineData { len, buf }))
}
}
pub fn encode(&self, bytes: &mut impl BufWriter) {
let (header, data) = match self {
DataKey::Data(data) => (data.len, &**data),
DataKey::Hash(hash) => (IS_HASH_BIT, &hash.data[..]),
};
bytes.put_u8(header);
bytes.put_slice(data);
}
}
pub trait ToDataKey {
fn to_data_key(&self) -> DataKey;
}
impl ToDataKey for crate::TypeValue {
fn to_data_key(&self) -> DataKey {
let mut bytes = Vec::new();
self.encode(&mut bytes);
DataKey::from_data(&bytes)
}
}
impl ToDataKey for crate::TupleValue {
fn to_data_key(&self) -> DataKey {
let mut bytes = Vec::new();
self.encode(&mut bytes);
DataKey::from_data(&bytes)
}
}