1use std::error::Error as StdError;
2use std::fmt;
3
4use rkyv::rancor::Error as RkyvError;
5use rkyv::{Archive, Deserialize, Serialize};
6use serde_json::{Map, Number, Value};
7
8const MAGIC_V1: &[u8; 6] = b"CLVCV1";
9const MAGIC_V2: &[u8; 6] = b"CLVCV2";
10const TYPE_NULL: u8 = 0;
11const TYPE_BOOL: u8 = 1;
12const TYPE_I64: u8 = 2;
13const TYPE_U64: u8 = 3;
14const TYPE_F64: u8 = 4;
15const TYPE_STRING: u8 = 5;
16const TYPE_BYTES: u8 = 6;
17const TYPE_JSON: u8 = 7;
18
19pub type ValueResult<T> = std::result::Result<T, ValueError>;
20
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub struct ValueError(String);
23
24impl ValueError {
25 fn new(message: impl Into<String>) -> Self {
26 Self(message.into())
27 }
28}
29
30impl fmt::Display for ValueError {
31 fn fmt(
32 &self,
33 f: &mut fmt::Formatter<'_>,
34 ) -> fmt::Result {
35 self.0.fmt(f)
36 }
37}
38
39impl StdError for ValueError {}
40
41#[derive(Clone, Debug, PartialEq)]
46pub enum CacheValue {
47 Null,
48 Bool(bool),
49 I64(i64),
50 U64(u64),
51 F64(f64),
52 String(String),
53 Bytes(Vec<u8>),
54 Json(CacheJson),
55}
56
57#[derive(Debug)]
64pub enum CacheValueRef<'a> {
65 Null,
66 Bool(bool),
67 I64(i64),
68 U64(u64),
69 F64(f64),
70 String(&'a str),
71 Bytes(&'a [u8]),
72 Json(&'a ArchivedCacheJson),
73 LegacyJson(CacheJson),
74}
75
76impl CacheValueRef<'_> {
77 pub fn into_owned(self) -> ValueResult<CacheValue> {
78 Ok(match self {
79 Self::Null => CacheValue::Null,
80 Self::Bool(value) => CacheValue::Bool(value),
81 Self::I64(value) => CacheValue::I64(value),
82 Self::U64(value) => CacheValue::U64(value),
83 Self::F64(value) => CacheValue::F64(value),
84 Self::String(value) => CacheValue::String(value.to_owned()),
85 Self::Bytes(value) => CacheValue::Bytes(value.to_vec()),
86 Self::Json(value) => CacheValue::Json(
87 rkyv::deserialize::<CacheJson, RkyvError>(value).map_err(
88 |error| {
89 ValueError::new(format!(
90 "cache value archive decode failed: {error}"
91 ))
92 },
93 )?,
94 ),
95 Self::LegacyJson(value) => CacheValue::Json(value),
96 })
97 }
98}
99
100#[derive(Archive, Serialize, Deserialize, Clone, Debug, PartialEq)]
106#[rkyv(derive(Debug))]
107#[rkyv(serialize_bounds(
108 __S: rkyv::ser::Writer + rkyv::ser::Allocator,
109 __S::Error: rkyv::rancor::Source,
110))]
111#[rkyv(deserialize_bounds(__D::Error: rkyv::rancor::Source))]
112#[rkyv(bytecheck(bounds(__C: rkyv::validation::ArchiveContext)))]
113pub enum CacheJson {
114 Null,
115 Bool(bool),
116 I64(i64),
117 U64(u64),
118 F64(f64),
119 String(String),
120 Array(#[rkyv(omit_bounds)] Vec<CacheJson>),
121 Object(#[rkyv(omit_bounds)] Vec<(String, CacheJson)>),
122}
123
124impl CacheJson {
125 pub fn from_json(value: Value) -> Self {
126 match value {
127 Value::Null => Self::Null,
128 Value::Bool(value) => Self::Bool(value),
129 Value::Number(value) => {
130 if let Some(value) = value.as_i64() {
131 Self::I64(value)
132 } else if let Some(value) = value.as_u64() {
133 Self::U64(value)
134 } else if let Some(value) = value.as_f64() {
135 Self::F64(value)
136 } else {
137 unreachable!(
138 "serde_json numbers are representable as i64, u64, or f64"
139 )
140 }
141 }
142 Value::String(value) => Self::String(value),
143 Value::Array(values) => {
144 Self::Array(values.into_iter().map(Self::from_json).collect())
145 }
146 Value::Object(values) => Self::Object(
147 values
148 .into_iter()
149 .map(|(key, value)| (key, Self::from_json(value)))
150 .collect(),
151 ),
152 }
153 }
154
155 pub fn to_json(&self) -> Value {
156 match self {
157 Self::Null => Value::Null,
158 Self::Bool(value) => Value::Bool(*value),
159 Self::I64(value) => Value::Number(Number::from(*value)),
160 Self::U64(value) => Value::Number(Number::from(*value)),
161 Self::F64(value) => Number::from_f64(*value)
162 .map(Value::Number)
163 .unwrap_or(Value::Null),
164 Self::String(value) => Value::String(value.clone()),
165 Self::Array(values) => {
166 Value::Array(values.iter().map(Self::to_json).collect())
167 }
168 Self::Object(values) => Value::Object(
169 values
170 .iter()
171 .map(|(key, value)| (key.clone(), value.to_json()))
172 .collect(),
173 ),
174 }
175 }
176}
177
178impl CacheValue {
179 pub fn from_json(value: Value) -> Self {
180 match value {
181 Value::Null => Self::Null,
182 Value::Bool(value) => Self::Bool(value),
183 Value::Number(value) => number_to_cache_value(value),
184 Value::String(value) => Self::String(value),
185 Value::Array(_) | Value::Object(_) => {
186 Self::Json(CacheJson::from_json(value))
187 }
188 }
189 }
190
191 pub fn to_json(&self) -> Value {
192 match self {
193 Self::Null => Value::Null,
194 Self::Bool(value) => Value::Bool(*value),
195 Self::I64(value) => Value::Number(Number::from(*value)),
196 Self::U64(value) => Value::Number(Number::from(*value)),
197 Self::F64(value) => Number::from_f64(*value)
198 .map(Value::Number)
199 .unwrap_or(Value::Null),
200 Self::String(value) => Value::String(value.clone()),
201 Self::Bytes(value) => {
202 let mut object = Map::new();
203 object.insert(
204 "type".to_string(),
205 Value::String("bytes".to_string()),
206 );
207 object.insert(
208 "value".to_string(),
209 Value::Array(
210 value
211 .iter()
212 .map(|byte| Value::Number(Number::from(*byte)))
213 .collect(),
214 ),
215 );
216 Value::Object(object)
217 }
218 Self::Json(value) => value.to_json(),
219 }
220 }
221
222 pub fn type_name(&self) -> &'static str {
223 match self {
224 Self::Null => "null",
225 Self::Bool(_) => "bool",
226 Self::I64(_) => "i64",
227 Self::U64(_) => "u64",
228 Self::F64(_) => "f64",
229 Self::String(_) => "string",
230 Self::Bytes(_) => "bytes",
231 Self::Json(_) => "json",
232 }
233 }
234
235 pub fn encode(&self) -> ValueResult<Vec<u8>> {
236 let mut out = Vec::new();
237
238 match self {
239 Self::Null => {
240 out.extend_from_slice(MAGIC_V1);
241 out.push(TYPE_NULL);
242 }
243 Self::Bool(value) => {
244 out.extend_from_slice(MAGIC_V1);
245 out.push(TYPE_BOOL);
246 out.push(u8::from(*value));
247 }
248 Self::I64(value) => {
249 out.extend_from_slice(MAGIC_V1);
250 out.push(TYPE_I64);
251 out.extend_from_slice(&value.to_le_bytes());
252 }
253 Self::U64(value) => {
254 out.extend_from_slice(MAGIC_V1);
255 out.push(TYPE_U64);
256 out.extend_from_slice(&value.to_le_bytes());
257 }
258 Self::F64(value) => {
259 out.extend_from_slice(MAGIC_V1);
260 out.push(TYPE_F64);
261 out.extend_from_slice(&value.to_le_bytes());
262 }
263 Self::String(value) => {
264 out.extend_from_slice(MAGIC_V1);
265 out.push(TYPE_STRING);
266 out.extend_from_slice(value.as_bytes());
267 }
268 Self::Bytes(value) => {
269 out.extend_from_slice(MAGIC_V1);
270 out.push(TYPE_BYTES);
271 out.extend_from_slice(value);
272 }
273 Self::Json(value) => {
274 out.extend_from_slice(MAGIC_V2);
275 out.extend_from_slice(
276 &rkyv::to_bytes::<RkyvError>(value).map_err(|error| {
277 ValueError::new(format!(
278 "cache value archive encode failed: {error}"
279 ))
280 })?,
281 );
282 }
283 }
284
285 Ok(out)
286 }
287
288 pub fn decode(bytes: &[u8]) -> ValueResult<Self> {
289 Self::view(bytes)?.into_owned()
290 }
291
292 pub fn view(bytes: &[u8]) -> ValueResult<CacheValueRef<'_>> {
298 if bytes.starts_with(MAGIC_V2) {
299 let payload = &bytes[MAGIC_V2.len()..];
300 return rkyv::access::<ArchivedCacheJson, RkyvError>(payload)
301 .map(CacheValueRef::Json)
302 .map_err(|error| {
303 ValueError::new(format!(
304 "cache value archive decode failed: {error}"
305 ))
306 });
307 }
308
309 if bytes.len() < MAGIC_V1.len() + 1 || !bytes.starts_with(MAGIC_V1) {
310 return Ok(CacheValueRef::Bytes(bytes));
311 }
312
313 let tag = bytes[MAGIC_V1.len()];
314 let payload = &bytes[MAGIC_V1.len() + 1..];
315 match tag {
316 TYPE_NULL if payload.is_empty() => Ok(CacheValueRef::Null),
317 TYPE_BOOL if payload.len() == 1 => {
318 Ok(CacheValueRef::Bool(payload[0] != 0))
319 }
320 TYPE_I64 if payload.len() == 8 => {
321 Ok(CacheValueRef::I64(i64::from_le_bytes(
322 payload.try_into().expect("checked i64 cache value length"),
323 )))
324 }
325 TYPE_U64 if payload.len() == 8 => {
326 Ok(CacheValueRef::U64(u64::from_le_bytes(
327 payload.try_into().expect("checked u64 cache value length"),
328 )))
329 }
330 TYPE_F64 if payload.len() == 8 => {
331 Ok(CacheValueRef::F64(f64::from_le_bytes(
332 payload.try_into().expect("checked f64 cache value length"),
333 )))
334 }
335 TYPE_STRING => std::str::from_utf8(payload)
336 .map(CacheValueRef::String)
337 .map_err(|error| {
338 ValueError::new(format!(
339 "cache value string decode failed: {error}"
340 ))
341 }),
342 TYPE_BYTES => Ok(CacheValueRef::Bytes(payload)),
343 TYPE_JSON => serde_json::from_slice(payload)
344 .map(CacheJson::from_json)
345 .map(CacheValueRef::LegacyJson)
346 .map_err(|error| {
347 ValueError::new(format!(
348 "legacy cache value json decode failed: {error}"
349 ))
350 }),
351 _ => Err(ValueError::new("invalid cache value envelope")),
352 }
353 }
354}
355
356fn number_to_cache_value(value: Number) -> CacheValue {
357 if let Some(value) = value.as_i64() {
358 CacheValue::I64(value)
359 } else if let Some(value) = value.as_u64() {
360 CacheValue::U64(value)
361 } else if let Some(value) = value.as_f64() {
362 CacheValue::F64(value)
363 } else {
364 CacheValue::Json(CacheJson::from_json(Value::Number(value)))
365 }
366}
367
368#[cfg(test)]
369#[path = "../tests/value.rs"]
370mod tests;