infinitree/fields/
serialized.rs

1use super::{
2    depth::{Depth, Snapshot},
3    Load, LocalField, Store,
4};
5use crate::{
6    index::{FieldReader, FieldWriter, Transaction},
7    object::{self, AEADReader, Pool},
8};
9use parking_lot::RwLock;
10use serde::{de::DeserializeOwned, Serialize};
11use std::{
12    ops::{Deref, DerefMut},
13    sync::Arc,
14};
15
16/// Allows using any serializable type as a member of the index
17///
18/// This implementation is super simplistic, and will not optimize for
19/// best performance. If you want something fancy, you are very likely
20/// to want to implement your own serialization.
21#[derive(Default)]
22pub struct Serialized<T>(Arc<RwLock<T>>);
23
24impl<T> Clone for Serialized<T> {
25    fn clone(&self) -> Self {
26        Serialized(self.0.clone())
27    }
28}
29
30impl<T> Serialized<T> {
31    pub fn read(&self) -> impl Deref<Target = T> + '_ {
32        self.0.read()
33    }
34
35    pub fn write(&self) -> impl DerefMut<Target = T> + '_ {
36        self.0.write()
37    }
38}
39
40impl<T> From<T> for Serialized<T>
41where
42    T: Serialize + DeserializeOwned + Sync,
43{
44    fn from(original: T) -> Self {
45        Serialized(Arc::new(original.into()))
46    }
47}
48
49impl<T> Store for LocalField<Serialized<T>>
50where
51    T: Serialize + Sync,
52{
53    #[inline(always)]
54    fn store(&mut self, mut transaction: &mut dyn Transaction, _object: &mut dyn object::Writer) {
55        transaction.write_next(&*self.field.read());
56    }
57}
58
59impl<T> Load for LocalField<Serialized<T>>
60where
61    T: DeserializeOwned,
62{
63    fn load(&mut self, pool: Pool<AEADReader>, transaction_list: crate::index::TransactionList) {
64        for mut transaction in Snapshot::resolve(pool, transaction_list) {
65            *self.field.write() = transaction.read_next().unwrap();
66        }
67    }
68}
69
70#[cfg(test)]
71mod test {
72    use super::Serialized;
73    use crate::fields::{LocalField, Strategy};
74
75    #[test]
76    fn strategy_local_field() {
77        let store = Serialized::from(123456789);
78        let load = Serialized::default();
79
80        crate::index::test::store_then_load(
81            LocalField::for_field(&store),
82            LocalField::for_field(&load),
83        );
84
85        assert_eq!(*store.read(), *load.read());
86        assert_eq!(*load.read(), 123456789);
87    }
88}