Debian Codegraph @

third_party/rust/rkv/src/value.rs

raw
1 // Copyright 2018-2019 Mozilla
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not use
4 // this file except in compliance with the License. You may obtain a copy of the
5 // License at http://www.apache.org/licenses/LICENSE-2.0
6 // Unless required by applicable law or agreed to in writing, software distributed
7 // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
8 // CONDITIONS OF ANY KIND, either express or implied. See the License for the
9 // specific language governing permissions and limitations under the License.
10
11 use std::fmt;
12
13 use arrayref::array_ref;
14 use bincode::{deserialize, serialize, serialized_size};
15 use ordered_float::OrderedFloat;
16 use uuid::{Bytes, Uuid};
17
18 use crate::error::DataError;
19
20 /// We define a set of types, associated with simple integers, to annotate values stored
21 /// in LMDB. This is to avoid an accidental 'cast' from a value of one type to another.
22 /// For this reason we don't simply use `deserialize` from the `bincode` crate.
23 #[repr(u8)]
24 #[derive(Debug, PartialEq, Eq)]
25 pub enum Type {
26 Bool = 1,
27 U64 = 2,
28 I64 = 3,
29 F64 = 4,
30 Instant = 5, // Millisecond-precision timestamp.
31 Uuid = 6,
32 Str = 7,
33 Json = 8,
34 Blob = 9,
35 }
36
37 /// We use manual tagging, because <https://github.com/serde-rs/serde/issues/610>.
38 impl Type {
39 pub fn from_tag(tag: u8) -> Result<Type, DataError> {
40 #![allow(clippy::unnecessary_lazy_evaluations)]
41 Type::from_primitive(tag).ok_or_else(|| DataError::UnknownType(tag))
42 }
43
44 #[allow(clippy::wrong_self_convention)]
45 pub fn to_tag(self) -> u8 {
46 self as u8
47 }
48
49 fn from_primitive(p: u8) -> Option<Type> {
50 match p {
51 1 => Some(Type::Bool),
52 2 => Some(Type::U64),
53 3 => Some(Type::I64),
54 4 => Some(Type::F64),
55 5 => Some(Type::Instant),
56 6 => Some(Type::Uuid),
57 7 => Some(Type::Str),
58 8 => Some(Type::Json),
59 9 => Some(Type::Blob),
60 _ => None,
61 }
62 }
63 }
64
65 impl fmt::Display for Type {
66 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
67 f.write_str(match *self {
68 Type::Bool => "bool",
69 Type::U64 => "u64",
70 Type::I64 => "i64",
71 Type::F64 => "f64",
72 Type::Instant => "instant",
73 Type::Uuid => "uuid",
74 Type::Str => "str",
75 Type::Json => "json",
76 Type::Blob => "blob",
77 })
78 }
79 }
80
81 #[derive(Debug, Eq, PartialEq)]
82 pub enum Value<'v> {
83 Bool(bool),
84 U64(u64),
85 I64(i64),
86 F64(OrderedFloat<f64>),
87 Instant(i64), // Millisecond-precision timestamp.
88 Uuid(&'v Bytes),
89 Str(&'v str),
90 Json(&'v str),
91 Blob(&'v [u8]),
92 }
93
94 #[derive(Clone, Debug, PartialEq)]
95 pub enum OwnedValue {
96 Bool(bool),
97 U64(u64),
98 I64(i64),
99 F64(f64),
100 Instant(i64), // Millisecond-precision timestamp.
101 Uuid(Uuid),
102 Str(String),
103 Json(String), // TODO
104 Blob(Vec<u8>),
105 }
106
107 fn uuid(bytes: &[u8]) -> Result<Value, DataError> {
108 if bytes.len() == 16 {
109 Ok(Value::Uuid(array_ref![bytes, 0, 16]))
110 } else {
111 Err(DataError::InvalidUuid)
112 }
113 }
114
115 impl<'v> Value<'v> {
116 pub fn from_tagged_slice(slice: &'v [u8]) -> Result<Value<'v>, DataError> {
117 let (tag, data) = slice.split_first().ok_or(DataError::Empty)?;
118 let t = Type::from_tag(*tag)?;
119 Value::from_type_and_data(t, data)
120 }
121
122 fn from_type_and_data(t: Type, data: &'v [u8]) -> Result<Value<'v>, DataError> {
123 if t == Type::Uuid {
124 return deserialize(data)
125 .map_err(|e| DataError::DecodingError {
126 value_type: t,
127 err: e,
128 })
129 .map(uuid)?;
130 }
131
132 match t {
133 Type::Bool => deserialize(data).map(Value::Bool),
134 Type::U64 => deserialize(data).map(Value::U64),
135 Type::I64 => deserialize(data).map(Value::I64),
136 Type::F64 => deserialize(data).map(OrderedFloat).map(Value::F64),
137 Type::Instant => deserialize(data).map(Value::Instant),
138 Type::Str => deserialize(data).map(Value::Str),
139 Type::Json => deserialize(data).map(Value::Json),
140 Type::Blob => deserialize(data).map(Value::Blob),
141 Type::Uuid => {
142 // Processed above to avoid verbose duplication of error transforms.
143 unreachable!()
144 }
145 }
146 .map_err(|e| DataError::DecodingError {
147 value_type: t,
148 err: e,
149 })
150 }
151
152 pub fn to_bytes(&self) -> Result<Vec<u8>, DataError> {
153 match self {
154 Value::Bool(v) => serialize(&(Type::Bool.to_tag(), *v)),
155 Value::U64(v) => serialize(&(Type::U64.to_tag(), *v)),
156 Value::I64(v) => serialize(&(Type::I64.to_tag(), *v)),
157 Value::F64(v) => serialize(&(Type::F64.to_tag(), v.0)),
158 Value::Instant(v) => serialize(&(Type::Instant.to_tag(), *v)),
159 Value::Str(v) => serialize(&(Type::Str.to_tag(), v)),
160 Value::Json(v) => serialize(&(Type::Json.to_tag(), v)),
161 Value::Blob(v) => serialize(&(Type::Blob.to_tag(), v)),
162 Value::Uuid(v) => serialize(&(Type::Uuid.to_tag(), v)),
163 }
164 .map_err(DataError::EncodingError)
165 }
166
167 pub fn serialized_size(&self) -> Result<u64, DataError> {
168 match self {
169 Value::Bool(v) => serialized_size(&(Type::Bool.to_tag(), *v)),
170 Value::U64(v) => serialized_size(&(Type::U64.to_tag(), *v)),
171 Value::I64(v) => serialized_size(&(Type::I64.to_tag(), *v)),
172 Value::F64(v) => serialized_size(&(Type::F64.to_tag(), v.0)),
173 Value::Instant(v) => serialized_size(&(Type::Instant.to_tag(), *v)),
174 Value::Str(v) => serialized_size(&(Type::Str.to_tag(), v)),
175 Value::Json(v) => serialized_size(&(Type::Json.to_tag(), v)),
176 Value::Blob(v) => serialized_size(&(Type::Blob.to_tag(), v)),
177 Value::Uuid(v) => serialized_size(&(Type::Uuid.to_tag(), v)),
178 }
179 .map_err(DataError::EncodingError)
180 }
181 }
182
183 impl<'v> From<&'v Value<'v>> for OwnedValue {
184 fn from(value: &Value) -> OwnedValue {
185 match value {
186 Value::Bool(v) => OwnedValue::Bool(*v),
187 Value::U64(v) => OwnedValue::U64(*v),
188 Value::I64(v) => OwnedValue::I64(*v),
189 Value::F64(v) => OwnedValue::F64(**v),
190 Value::Instant(v) => OwnedValue::Instant(*v),
191 Value::Uuid(v) => OwnedValue::Uuid(Uuid::from_bytes(**v)),
192 Value::Str(v) => OwnedValue::Str((*v).to_string()),
193 Value::Json(v) => OwnedValue::Json((*v).to_string()),
194 Value::Blob(v) => OwnedValue::Blob(v.to_vec()),
195 }
196 }
197 }
198
199 impl<'v> From<&'v OwnedValue> for Value<'v> {
200 fn from(value: &OwnedValue) -> Value {
201 match value {
202 OwnedValue::Bool(v) => Value::Bool(*v),
203 OwnedValue::U64(v) => Value::U64(*v),
204 OwnedValue::I64(v) => Value::I64(*v),
205 OwnedValue::F64(v) => Value::F64(OrderedFloat::from(*v)),
206 OwnedValue::Instant(v) => Value::Instant(*v),
207 OwnedValue::Uuid(v) => Value::Uuid(v.as_bytes()),
208 OwnedValue::Str(v) => Value::Str(v),
209 OwnedValue::Json(v) => Value::Json(v),
210 OwnedValue::Blob(v) => Value::Blob(v),
211 }
212 }
213 }
214
215 #[cfg(test)]
216 mod tests {
217 use super::*;
218
219 #[test]
220 fn test_value_serialized_size() {
221 // | Value enum | tag: 1 byte | value_payload |
222 // |----------------------------------------------------------|
223 // | I64 | 1 | 8 |
224 // | U64 | 1 | 8 |
225 // | Bool | 1 | 1 |
226 // | Instant | 1 | 8 |
227 // | F64 | 1 | 8 |
228 // | Uuid | 1 | 16 |
229 // | Str/Blob/Json | 1 |(8: len + sizeof(payload))|
230 assert_eq!(Value::I64(-1000).serialized_size().unwrap(), 9);
231 assert_eq!(Value::U64(1000u64).serialized_size().unwrap(), 9);
232 assert_eq!(Value::Bool(true).serialized_size().unwrap(), 2);
233 assert_eq!(
234 Value::Instant(1_558_020_865_224).serialized_size().unwrap(),
235 9
236 );
237 assert_eq!(
238 Value::F64(OrderedFloat(10000.1)).serialized_size().unwrap(),
239 9
240 );
241 assert_eq!(Value::Str("hello!").serialized_size().unwrap(), 15);
242 assert_eq!(Value::Str("¡Hola").serialized_size().unwrap(), 15);
243 assert_eq!(Value::Blob(b"hello!").serialized_size().unwrap(), 15);
244 assert_eq!(
245 uuid(b"\x9f\xe2\xc4\xe9\x3f\x65\x4f\xdb\xb2\x4c\x02\xb1\x52\x59\x71\x6c")
246 .unwrap()
247 .serialized_size()
248 .unwrap(),
249 17
250 );
251 }
252 }