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
use ::serde::{de::DeserializeOwned, Deserialize, Serialize};

use crate::error::DittoError;

#[derive(Serialize, Deserialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct DittoRegisterStoredFormat {
    _value: serde_json::Value,
    #[serde(rename = "_ditto_internal_type_jkb12973t4b")]
    _type: u64,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(from = "serde_json::Value")]
#[serde(into = "DittoRegisterStoredFormat")]
/// Represents a CRDT register that can be upserted as part of a document or
/// assigned to a property during an update of a document.
pub struct DittoRegister {
    pub value: serde_json::Value,
}

impl From<serde_json::Value> for DittoRegister {
    fn from(value: serde_json::Value) -> DittoRegister {
        DittoRegister { value }
    }
}

impl From<DittoRegister> for DittoRegisterStoredFormat {
    fn from(DittoRegister { value }: DittoRegister) -> DittoRegisterStoredFormat {
        Self {
            _value: value,
            _type: ::ffi_sdk::DittoCrdtType::Register as u64,
        }
    }
}

impl DittoRegister {
    /// Create a new register with the provided value
    pub fn new<T: Serialize>(value: T) -> Result<Self, DittoError> {
        let value = serde_json::to_value(value)?;
        Ok(Self { value })
    }

    /// Access to the value within the register.
    /// The operation may fail if the content of the register can not be serialized into T
    pub fn value<T: DeserializeOwned>(&self) -> Result<T, DittoError> {
        serde_json::from_value(self.value.clone()).map_err(|json_err| json_err.into())
    }
}