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
use_prelude!();
use std::{borrow::BorrowMut, time::SystemTime};

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

use super::type_traits::MutableValue;
use crate::error::{DittoError, ErrorKind};

// Similar to an ObjC Extension, DittoDocument can be implemented
// for a number of opaque types (usually various smart pointers)
pub trait DittoDocument {
    /// Returns the ID of the document
    fn id(&self) -> DocumentId;
    /// Renders the document as a CBOR value
    fn to_cbor(&self) -> Result<serde_cbor::Value, DittoError>;

    /// Returns the value at a given path in the document
    /// The parameter `V` represents the type expected at the given path.
    /// Note however that other peers may have changed this type and
    /// deserialization may fail. In this case provide a general type like
    /// `serde_cbor::Value`
    fn get<V: DeserializeOwned>(&self, path: &str) -> Result<V, DittoError>;

    /// Decodes a document into a user-provided type provided that type
    /// implements `serde::Deserialize`
    /// Note that this is a snapshot of the current state of the Document, which
    /// may be later modified by other peers
    fn typed<T: DeserializeOwned>(&self) -> Result<T, DittoError>;
}

pub trait DittoMutDocument: DittoDocument {
    /// Returns the value at a given path in the mutable document
    /// The parameter `V` represents the type expected at the given path.
    /// Note however that other peers may have changed this type and
    /// deserialization may fail.
    // FIXME(Daniel): does this apply in this case ??
    // In this case provide a general type like `serde_cbor::Value`
    fn get_mut<V: MutableValue>(&mut self, path: &str) -> Result<V, DittoError>;

    /// Assigns a some serializable value to the document at the given path *and
    /// removes any other information present at that path*
    /// If the path does not exist it will be created.
    fn set<V: Serialize>(&mut self, path: &str, val: V) -> Result<(), DittoError>;

    /// Sets the value at the provided path and marks it as the default,
    /// indicating other peers in the network are expected to overwrite it.
    fn set_as_default<V: Serialize>(&mut self, path: &str, val: V) -> Result<(), DittoError>;

    /// Given a `path` to an array inside a document, appends value to the
    /// array. An error will be returned if the path does not in fact point
    /// to an array.
    fn push<V: Serialize>(&mut self, path: &str, val: V) -> Result<(), DittoError>;

    /// Removes and returns the last item at a path within a document if that
    /// path is to an array.
    fn pop<T>(&mut self, path: &str) -> Result<T, DittoError>
    where
        T: DeserializeOwned;

    /// Inserts a `value` at the provided path and *will not remove other
    /// descendant items at that path.
    fn insert<V: Serialize>(&mut self, path: &str, val: V) -> Result<(), DittoError>;

    /// Remove the value from a document at a given path
    fn remove(&mut self, path: &str) -> Result<(), DittoError>;

    /// Increment (+/-) a field previously transformed into a Counter by
    /// `amount`.
    fn increment(&mut self, path: &str, amount: f64) -> Result<(), DittoError>;
}

// impl DittoDocument for ffi_sdk::DocumentRef { // a Box<Document>
impl<T: Borrow<ffi_sdk::Document>> DittoDocument for T {
    fn id(&self) -> DocumentId {
        let id_slice = unsafe { ffi_sdk::ditto_document_id(self.borrow()) };
        let id = id_slice.as_slice().to_vec().into();
        unsafe {
            ffi_sdk::ditto_c_bytes_free(id_slice);
        }
        id
    }

    fn to_cbor(&self) -> Result<serde_cbor::Value, DittoError> {
        let c_bytes = unsafe { ffi_sdk::ditto_document_cbor(self.borrow()) };
        let result = serde_cbor::from_slice(c_bytes.as_slice())
            .map_err(|e| DittoError::new(ErrorKind::InvalidInput, e));
        unsafe {
            ffi_sdk::ditto_c_bytes_free(c_bytes);
        }
        result
    }

    fn get<V: DeserializeOwned>(&self, key: &str) -> Result<V, DittoError> {
        use ffi_sdk::PathAccessorType;
        let c_key = char_p::new(key);
        let c_val = unsafe {
            ffi_sdk::ditto_document_get_cbor_with_path_type(
                self.borrow(),
                c_key.as_ref(),
                PathAccessorType::Any,
            )
        };
        c_val
            .ok_or(ErrorKind::NonExtant)
            .and_then(|x| -> Result<V, _> {
                let result = serde_cbor::from_slice(x.as_slice())
                    .map_err(|e| DittoError::new(ErrorKind::InvalidInput, e));
                unsafe {
                    ffi_sdk::ditto_c_bytes_free(x);
                }
                result
            })
    }

    fn typed<V: DeserializeOwned>(&self) -> Result<V, DittoError> {
        let c_bytes = unsafe { ffi_sdk::ditto_document_cbor(self.borrow()) };
        let result = serde_cbor::from_slice::<V>(c_bytes.as_slice())
            .map_err(|e| DittoError::new(ErrorKind::InvalidInput, e));
        unsafe {
            ffi_sdk::ditto_c_bytes_free(c_bytes);
        }
        result
    }
}

impl<T: BorrowMut<ffi_sdk::Document>> DittoMutDocument for T {
    /// Retrieve the mutable version of any ditto mutable explicit type
    fn get_mut<V: MutableValue>(&mut self, path: &str) -> Result<V> {
        let base_value: V::BaseType = self.get(path)?;
        let doc = self.borrow_mut();
        let c_key = char_p::new(path);
        V::mutable_version(base_value, doc, c_key)
    }

    fn set<V: Serialize>(&mut self, path: &str, val: V) -> Result<(), DittoError> {
        let c_str = char_p::new(path);
        let cbor: Vec<u8> =
            serde_cbor::to_vec(&val).map_err(|e| DittoError::new(ErrorKind::InvalidInput, e))?;
        let status = unsafe {
            ffi_sdk::ditto_document_set_cbor(
                self.borrow_mut(),
                c_str.as_ref(),
                cbor.as_slice().into(),
                true, // Make a path if not present
            )
        };
        if status != 0 {
            Err(DittoError::from_ffi(ErrorKind::InvalidInput))
        } else {
            Ok(())
        }
    }

    fn set_as_default<V: Serialize>(&mut self, path: &str, val: V) -> Result<(), DittoError> {
        let c_str = char_p::new(path);
        let cbor: Vec<u8> =
            serde_cbor::to_vec(&val).map_err(|e| DittoError::new(ErrorKind::InvalidInput, e))?;

        // This should be reasonably stable for this application, otherwise we can
        // upgrade to the chrono library
        // Note the underlying impl is platform specific
        let timestamp = match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
            Ok(n) => n.as_secs(),
            Err(e) => return Err(DittoError::new(ErrorKind::Internal, e)),
        };
        let status = unsafe {
            ffi_sdk::ditto_document_set_cbor_with_timestamp(
                self.borrow_mut(),
                c_str.as_ref(),
                cbor.as_slice().into(),
                true, // Make a path if not present
                timestamp as u32,
            )
        };
        if status != 0 {
            Err(DittoError::from_ffi(ErrorKind::InvalidInput))
        } else {
            Ok(())
        }
    }

    fn push<V: Serialize>(&mut self, path: &str, value: V) -> Result<(), DittoError> {
        let c_str = char_p::new(path);
        let cbor: Vec<u8> =
            serde_cbor::to_vec(&value).map_err(|e| DittoError::new(ErrorKind::InvalidInput, e))?;
        let status = unsafe {
            ffi_sdk::ditto_document_push_cbor(
                self.borrow_mut(),
                c_str.as_ref(),
                cbor.as_slice().into(),
            )
        };
        if status != 0 {
            Err(DittoError::from_ffi(ErrorKind::InvalidInput))
        } else {
            Ok(())
        }
    }

    fn pop<V: DeserializeOwned>(&mut self, path: &str) -> Result<V, DittoError> {
        let c_str = char_p::new(path);
        let cbor = {
            use ::safer_ffi::prelude::{AsOut, ManuallyDropMut};
            let mut slot: c_slice::Box<u8> = Default::default();
            let out_cbor: Out<c_slice::Box<u8>> = slot.manually_drop_mut().as_out();
            let status = unsafe {
                ffi_sdk::ditto_document_pop_cbor(self.borrow_mut(), c_str.as_ref(), out_cbor)
            };
            if status != 0 {
                return Err(DittoError::from_ffi(ErrorKind::InvalidInput));
            }
            slot
        };

        let result = serde_cbor::from_slice::<V>(cbor.as_slice())
            .map_err(|e| DittoError::new(ErrorKind::InvalidInput, e));
        unsafe {
            ffi_sdk::ditto_c_bytes_free(cbor);
        }
        result
    }

    fn insert<V: Serialize>(&mut self, path: &str, value: V) -> Result<(), DittoError> {
        let c_str = char_p::new(path);
        let cbor: Vec<u8> =
            serde_cbor::to_vec(&value).map_err(|e| DittoError::new(ErrorKind::InvalidInput, e))?;
        let status = unsafe {
            ffi_sdk::ditto_document_insert_cbor(
                self.borrow_mut(),
                c_str.as_ref(),
                cbor.as_slice().into(),
            )
        };
        if status != 0 {
            Err(DittoError::from_ffi(ErrorKind::InvalidInput))
        } else {
            Ok(())
        }
    }

    fn remove(&mut self, path: &str) -> Result<(), DittoError> {
        let pointer = char_p::new(path);
        let status = unsafe { ffi_sdk::ditto_document_remove(self.borrow_mut(), pointer.as_ref()) };
        if status != 0 {
            Err(DittoError::from_ffi(ErrorKind::InvalidInput))
        } else {
            Ok(())
        }
    }

    fn increment(&mut self, path: &str, amount: f64) -> Result<(), DittoError> {
        let pointer = char_p::new(path);

        let status = unsafe {
            ffi_sdk::ditto_document_increment_counter(self.borrow_mut(), pointer.as_ref(), amount)
        };
        if status != 0 {
            Err(DittoError::from_ffi(ErrorKind::InvalidInput))
        } else {
            Ok(())
        }
    }
}