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
use core::ops::Deref;

use ::serde::{de::DeserializeOwned, Deserialize, Serialize};

use crate::error::{DittoError, ErrorKind};

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

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
#[serde(from = "Vec<serde_json::Value>")]
#[serde(into = "DittoRgaStoredFormat")]
/// Represents a CRDT Replicated Growable Array (RGA).
///
/// RGAs are deprecated and you should instead use a `DittoRegister` containing
/// an array.
pub struct DittoRga {
    pub value: Vec<serde_json::Value>,
}

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

impl From<DittoRga> for DittoRgaStoredFormat {
    fn from(DittoRga { value }: DittoRga) -> DittoRgaStoredFormat {
        Self {
            _value: value,
            _type: ::ffi_sdk::DittoCrdtType::Rga as u64,
        }
    }
}

/// Deref to access vector features
impl Deref for DittoRga {
    type Target = Vec<serde_json::Value>;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl DittoRga {
    /// Retrieve value at given index.
    /// The operation may fail if the content of the Rga can not be serialized into T
    pub fn get<T: DeserializeOwned>(&self, index: usize) -> Result<T, DittoError> {
        self.value
            .get(index)
            .ok_or_else(|| {
                DittoError::from_str(ErrorKind::InvalidInput, "Provided index to not exists")
            })
            .and_then(|v| serde_json::from_value(v.clone()).map_err(|json_err| json_err.into()))
    }
}