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
use_prelude!();
use super::DittoRegister;

/// Represents a mutable CRDT register that can be updated while updating a
/// document.
///
/// This class can't be instantiated directly. It's returned from the
/// `get_mut` method of DittoMutDocument.
pub struct DittoMutableRegister {
    document: *mut ffi_sdk::Document,
    path: char_p::Box,
    register: DittoRegister,
}

impl MutableValue for DittoMutableRegister {
    type BaseType = DittoRegister;
    fn mutable_version(
        base: Self::BaseType,
        document: &mut ffi_sdk::Document,
        path: char_p::Box,
    ) -> Result<Self> {
        Ok(Self {
            register: base,
            document,
            path,
        })
    }
}

impl DittoMutableRegister {
    /// Set content of the register to a new value.
    pub fn set<T: Serialize>(&mut self, value: T) -> Result<(), DittoError> {
        let path = self.path.clone();
        let document = self.document;
        // needed to get a ref mut to the document pointer
        unsafe {
            document.as_mut().unwrap().set(path.to_str(), &value)?;
        }

        let register = DittoRegister::new(value)?;
        self.register = register;
        Ok(())
    }

    /// 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> {
        self.register.value()
    }
}