tinystore 0.3.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
Documentation
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! A value as its row keeps it, and the one way every type gets there.
//!
//! A type is kept by what serde says it is, so a bucket's type is given once,
//! where the bucket opens, and nothing wraps it:
//!
//! | Type                               | Row                                 | Example                      |
//! |------------------------------------|-------------------------------------|------------------------------|
//! | `()`, `None`                       | nothing                             | a set's member               |
//! | `bool`, integers that fit an `i64` | an integer                          | `true → 1`, `-7 → -7`        |
//! | `String`, `char`                   | `01`, then the text's UTF-8         | `"hé" → 01 68 c3 a9`         |
//! | serde bytes                        | `02`, then the bytes                | `Bytes([7]) → 02 07`         |
//! | structs, maps, sequences, enums    | `03`, then JSON                     | `{"user":42} → 03 7b …`      |
//! | `f64`                              | `04`, then its bits, big-endian     | `-0.0 → 04 80 00 … 00`       |
//! | `u64`                              | `05`, then 8 bytes, big-endian      | `2^63 → 05 80 00 … 00`       |
//! | `f32`                              | `06`, then its bits, big-endian     | `1.0 → 06 3f 80 00 00`       |
//!
//! A row of bytes says by its first byte what wrote it, so a value read as
//! another kind than it was written is `Corrupt` rather than a plausible wrong
//! value: text is never read from JSON, nor bytes from text. Every SDK writes
//! the same rows, so each reads the others'. A float keeps its bits, `-0`,
//! infinities and a NaN's payload included. A newtype keeps what it wraps.
//! `Vec<u8>` is a sequence to serde and becomes JSON; [`Bytes`] keeps bytes as
//! they are.

use std::fmt;

use serde::de::{self, DeserializeOwned, Visitor};
use serde::ser::{self, Impossible};
use serde::{Deserialize, Serialize};

/// The first byte of a row of bytes: the kind of value that wrote it.
const TEXT: u8 = 1;
const BYTES: u8 = 2;
const JSON: u8 = 3;
const F64: u8 = 4;
const U64: u8 = 5;
const F32: u8 = 6;

fn tagged(tag: u8, body: &[u8]) -> Raw {
    let mut row = Vec::with_capacity(body.len() + 1);
    row.push(tag);
    row.extend_from_slice(body);
    Raw::Bytes(row)
}

fn kind_of(tag: u8) -> &'static str {
    match tag {
        TEXT => "text",
        BYTES => "bytes",
        JSON => "JSON",
        F64 => "an f64",
        U64 => "a u64",
        F32 => "an f32",
        _ => "bytes of no kind",
    }
}

/// A value as its row keeps it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Raw {
    None,
    Int(i64),
    Bytes(Vec<u8>),
}

impl Raw {
    pub(crate) fn len(&self) -> usize {
        match self {
            Raw::None => 0,
            Raw::Int(_) => 8,
            Raw::Bytes(bytes) => bytes.len(),
        }
    }
}

/// A type a bucket can keep: anything serde reads and writes.
pub trait Value: Serialize + DeserializeOwned + Send + 'static {}

impl<T: Serialize + DeserializeOwned + Send + 'static> Value for T {}

/// Bytes kept as they are rather than as a JSON list of numbers.
#[derive(Clone, Default, PartialEq, Eq, Hash)]
pub struct Bytes(pub Vec<u8>);

impl fmt::Debug for Bytes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Bytes({} bytes)", self.0.len())
    }
}

impl Serialize for Bytes {
    fn serialize<S: ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_bytes(&self.0)
    }
}

impl<'de> Deserialize<'de> for Bytes {
    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_byte_buf(BytesVisitor)
    }
}

struct BytesVisitor;

impl Visitor<'_> for BytesVisitor {
    type Value = Bytes;

    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("bytes")
    }

    fn visit_bytes<E: de::Error>(self, bytes: &[u8]) -> Result<Bytes, E> {
        Ok(Bytes(bytes.to_vec()))
    }

    fn visit_byte_buf<E: de::Error>(self, bytes: Vec<u8>) -> Result<Bytes, E> {
        Ok(Bytes(bytes))
    }
}

/// Why a value could not become a row, or a row a value.
#[derive(Debug)]
pub(crate) struct Mismatch(pub(crate) String);

impl fmt::Display for Mismatch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for Mismatch {}

impl de::Error for Mismatch {
    fn custom<T: fmt::Display>(message: T) -> Self {
        Mismatch(message.to_string())
    }
}

/// The row a value is kept as.
pub(crate) fn encode<V: Serialize>(value: &V) -> Result<Raw, Mismatch> {
    match value.serialize(Probe) {
        Ok(raw) => Ok(raw),
        Err(Probed::Compound) => {
            serde_json::to_vec(value).map(|json| tagged(JSON, &json)).map_err(|error| Mismatch(error.to_string()))
        }
        Err(Probed::Failed(mismatch)) => Err(mismatch),
    }
}

/// The value a row keeps.
pub(crate) fn decode<V: DeserializeOwned>(raw: &Raw) -> Result<V, Mismatch> {
    V::deserialize(Row(raw))
}

/// A serializer that keeps a top-level primitive as a row and gives up on
/// anything compound, which then becomes JSON.
struct Probe;

/// How a probe gave up: on a compound value, or on a value serde refused.
#[derive(Debug)]
enum Probed {
    Compound,
    Failed(Mismatch),
}

impl fmt::Display for Probed {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Probed::Compound => f.write_str("a compound value"),
            Probed::Failed(mismatch) => mismatch.fmt(f),
        }
    }
}

impl std::error::Error for Probed {}

impl ser::Error for Probed {
    fn custom<T: fmt::Display>(message: T) -> Self {
        Probed::Failed(Mismatch(message.to_string()))
    }
}

macro_rules! compound {
    ($($method:ident($($arg:ty),*) -> $kind:ty;)*) => {
        $(fn $method(self, $(_: $arg),*) -> Result<$kind, Probed> {
            Err(Probed::Compound)
        })*
    };
}

impl ser::Serializer for Probe {
    type Ok = Raw;
    type Error = Probed;
    type SerializeSeq = Impossible<Raw, Probed>;
    type SerializeTuple = Impossible<Raw, Probed>;
    type SerializeTupleStruct = Impossible<Raw, Probed>;
    type SerializeTupleVariant = Impossible<Raw, Probed>;
    type SerializeMap = Impossible<Raw, Probed>;
    type SerializeStruct = Impossible<Raw, Probed>;
    type SerializeStructVariant = Impossible<Raw, Probed>;

    fn serialize_bool(self, value: bool) -> Result<Raw, Probed> {
        Ok(Raw::Int(i64::from(value)))
    }

    fn serialize_i8(self, value: i8) -> Result<Raw, Probed> {
        Ok(Raw::Int(value.into()))
    }

    fn serialize_i16(self, value: i16) -> Result<Raw, Probed> {
        Ok(Raw::Int(value.into()))
    }

    fn serialize_i32(self, value: i32) -> Result<Raw, Probed> {
        Ok(Raw::Int(value.into()))
    }

    fn serialize_i64(self, value: i64) -> Result<Raw, Probed> {
        Ok(Raw::Int(value))
    }

    fn serialize_u8(self, value: u8) -> Result<Raw, Probed> {
        Ok(Raw::Int(value.into()))
    }

    fn serialize_u16(self, value: u16) -> Result<Raw, Probed> {
        Ok(Raw::Int(value.into()))
    }

    fn serialize_u32(self, value: u32) -> Result<Raw, Probed> {
        Ok(Raw::Int(value.into()))
    }

    fn serialize_u64(self, value: u64) -> Result<Raw, Probed> {
        Ok(tagged(U64, &value.to_be_bytes()))
    }

    fn serialize_f32(self, value: f32) -> Result<Raw, Probed> {
        Ok(tagged(F32, &value.to_bits().to_be_bytes()))
    }

    fn serialize_f64(self, value: f64) -> Result<Raw, Probed> {
        Ok(tagged(F64, &value.to_bits().to_be_bytes()))
    }

    fn serialize_char(self, value: char) -> Result<Raw, Probed> {
        Ok(tagged(TEXT, value.to_string().as_bytes()))
    }

    fn serialize_str(self, value: &str) -> Result<Raw, Probed> {
        Ok(tagged(TEXT, value.as_bytes()))
    }

    fn serialize_bytes(self, value: &[u8]) -> Result<Raw, Probed> {
        Ok(tagged(BYTES, value))
    }

    fn serialize_none(self) -> Result<Raw, Probed> {
        Ok(Raw::None)
    }

    fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<Raw, Probed> {
        value.serialize(self)
    }

    fn serialize_unit(self) -> Result<Raw, Probed> {
        Ok(Raw::None)
    }

    fn serialize_unit_struct(self, _: &'static str) -> Result<Raw, Probed> {
        Ok(Raw::None)
    }

    fn serialize_newtype_struct<T: ?Sized + Serialize>(self, _: &'static str, value: &T) -> Result<Raw, Probed> {
        value.serialize(self)
    }

    fn serialize_unit_variant(self, _: &'static str, _: u32, _: &'static str) -> Result<Raw, Probed> {
        Err(Probed::Compound)
    }

    fn serialize_newtype_variant<T: ?Sized + Serialize>(
        self,
        _: &'static str,
        _: u32,
        _: &'static str,
        _: &T,
    ) -> Result<Raw, Probed> {
        Err(Probed::Compound)
    }

    compound! {
        serialize_seq(Option<usize>) -> Self::SerializeSeq;
        serialize_tuple(usize) -> Self::SerializeTuple;
        serialize_tuple_struct(&'static str, usize) -> Self::SerializeTupleStruct;
        serialize_tuple_variant(&'static str, u32, &'static str, usize) -> Self::SerializeTupleVariant;
        serialize_map(Option<usize>) -> Self::SerializeMap;
        serialize_struct(&'static str, usize) -> Self::SerializeStruct;
        serialize_struct_variant(&'static str, u32, &'static str, usize) -> Self::SerializeStructVariant;
    }
}

/// A row read back as whatever the value's type asks for. It borrows the row,
/// so text and bytes are handed to the value's type without a copy here.
struct Row<'de>(&'de Raw);

impl<'de> Row<'de> {
    /// The body of a row of bytes that `tag` wrote; one another kind wrote
    /// is refused, naming both.
    fn body(&self, tag: u8, wanted: &str) -> Result<&'de [u8], Mismatch> {
        match self.0 {
            Raw::Bytes(bytes) => match bytes.split_first() {
                Some((&first, body)) if first == tag => Ok(body),
                Some((&first, _)) => Err(Mismatch(format!("{wanted} from a row of {}", kind_of(first)))),
                None => Err(Mismatch(format!("{wanted} from a row of no bytes"))),
            },
            other => Err(Mismatch(format!("{wanted} from a row holding {}", shown(other)))),
        }
    }

    fn int(&self, wanted: &str) -> Result<i64, Mismatch> {
        match self.0 {
            Raw::Int(int) => Ok(*int),
            other => Err(Mismatch(format!("{wanted} from a row holding {}", shown(other)))),
        }
    }

    fn fixed<const N: usize>(&self, tag: u8, wanted: &str) -> Result<[u8; N], Mismatch> {
        let bytes = self.body(tag, wanted)?;
        bytes.try_into().map_err(|_| Mismatch(format!("{wanted} from {} bytes rather than {N}", bytes.len())))
    }

    fn text(&self) -> Result<&'de str, Mismatch> {
        std::str::from_utf8(self.body(TEXT, "text")?).map_err(|_| Mismatch("text that is not UTF-8".to_owned()))
    }

    /// Reads the row as JSON with `read`, refusing anything after the value.
    fn json<T>(
        &self,
        read: impl FnOnce(&mut serde_json::Deserializer<serde_json::de::SliceRead<'de>>) -> serde_json::Result<T>,
    ) -> Result<T, Mismatch> {
        let mut json = serde_json::Deserializer::from_slice(self.body(JSON, "JSON")?);
        let value = read(&mut json).map_err(|error| Mismatch(error.to_string()))?;
        json.end().map_err(|error| Mismatch(error.to_string()))?;
        Ok(value)
    }
}

fn shown(raw: &Raw) -> &'static str {
    match raw {
        Raw::None => "nothing",
        Raw::Int(_) => "an integer",
        Raw::Bytes(_) => "bytes",
    }
}

macro_rules! from_int {
    ($($method:ident,)*) => {
        $(fn $method<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
            visitor.visit_i64(self.int("an integer")?)
        })*
    };
}

macro_rules! from_json {
    ($($method:ident($($arg:ident: $ty:ty),*);)*) => {
        $(fn $method<V: Visitor<'de>>(self, $($arg: $ty,)* visitor: V) -> Result<V::Value, Mismatch> {
            self.json(|json| de::Deserializer::$method(json, $($arg,)* visitor))
        })*
    };
}

impl<'de> de::Deserializer<'de> for Row<'de> {
    type Error = Mismatch;

    fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        match self.0 {
            Raw::None => visitor.visit_unit(),
            Raw::Int(int) => visitor.visit_i64(*int),
            Raw::Bytes(bytes) => match bytes.first() {
                Some(&TEXT) => visitor.visit_borrowed_str(self.text()?),
                Some(&BYTES) => visitor.visit_borrowed_bytes(self.body(BYTES, "bytes")?),
                Some(&F64) => visitor.visit_f64(f64::from_bits(u64::from_be_bytes(self.fixed(F64, "an f64")?))),
                Some(&U64) => visitor.visit_u64(u64::from_be_bytes(self.fixed(U64, "a u64")?)),
                Some(&F32) => visitor.visit_f32(f32::from_bits(u32::from_be_bytes(self.fixed(F32, "an f32")?))),
                _ => self.json(|json| de::Deserializer::deserialize_any(json, visitor)),
            },
        }
    }

    fn deserialize_bool<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        match self.int("a bool")? {
            0 => visitor.visit_bool(false),
            1 => visitor.visit_bool(true),
            other => Err(Mismatch(format!("a bool from the integer {other}"))),
        }
    }

    from_int! {
        deserialize_i8, deserialize_i16, deserialize_i32, deserialize_i64,
        deserialize_u8, deserialize_u16, deserialize_u32,
    }

    fn deserialize_u64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_u64(u64::from_be_bytes(self.fixed(U64, "a u64")?))
    }

    fn deserialize_f32<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_f32(f32::from_bits(u32::from_be_bytes(self.fixed(F32, "an f32")?)))
    }

    fn deserialize_f64<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_f64(f64::from_bits(u64::from_be_bytes(self.fixed(F64, "an f64")?)))
    }

    fn deserialize_char<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_borrowed_str(self.text()?)
    }

    fn deserialize_str<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_borrowed_str(self.text()?)
    }

    fn deserialize_string<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_borrowed_str(self.text()?)
    }

    fn deserialize_bytes<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_borrowed_bytes(self.body(BYTES, "bytes")?)
    }

    fn deserialize_byte_buf<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_borrowed_bytes(self.body(BYTES, "bytes")?)
    }

    fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        match self.0 {
            Raw::None => visitor.visit_none(),
            _ => visitor.visit_some(self),
        }
    }

    fn deserialize_unit<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Mismatch> {
        match self.0 {
            Raw::None => visitor.visit_unit(),
            other => Err(Mismatch(format!("nothing from a row holding {}", shown(other)))),
        }
    }

    fn deserialize_unit_struct<V: Visitor<'de>>(self, _: &'static str, visitor: V) -> Result<V::Value, Mismatch> {
        self.deserialize_unit(visitor)
    }

    fn deserialize_newtype_struct<V: Visitor<'de>>(self, _: &'static str, visitor: V) -> Result<V::Value, Mismatch> {
        visitor.visit_newtype_struct(self)
    }

    from_json! {
        deserialize_seq();
        deserialize_tuple(len: usize);
        deserialize_tuple_struct(name: &'static str, len: usize);
        deserialize_map();
        deserialize_struct(name: &'static str, fields: &'static [&'static str]);
        deserialize_enum(name: &'static str, variants: &'static [&'static str]);
        deserialize_identifier();
        deserialize_ignored_any();
    }
}

#[cfg(test)]
#[path = "value_tests.rs"]
mod tests;