colla 0.2.0

Operational Transformation library for nested documents with text and rich-text
Documentation
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! Immutable Value types and Snapshot lookup.

use std::collections::BTreeMap;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::sync::Arc;

use crate::error::{CodecError, ValueError};
use crate::input_limits::InputLimits;
use crate::path::{Path, PathSeg};
use crate::richtext::RichText;

/// A finite, canonical `f64` value.
///
/// NaN and infinities are rejected, and negative zero is normalized to
/// positive zero so equality and canonical encoding remain deterministic.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FiniteF64(u64);

impl FiniteF64 {
    /// Creates a canonical finite float.
    pub fn new(value: f64) -> Result<Self, ValueError> {
        if !value.is_finite() {
            return Err(ValueError::NonFiniteFloat);
        }
        let canonical = if value == 0.0 { 0.0 } else { value };
        Ok(Self(canonical.to_bits()))
    }

    /// Returns the represented floating-point value.
    pub fn get(self) -> f64 {
        f64::from_bits(self.0)
    }
}

impl fmt::Debug for FiniteF64 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.get().fmt(f)
    }
}

/// Collaborative text addressed by Unicode scalar positions.
///
/// Unlike an atomic String Value, Text supports character-level OT.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Text(Arc<str>);

impl Text {
    /// Creates collaborative text from UTF-8 content.
    pub fn new(value: impl Into<String>) -> Self {
        Self(Arc::from(value.into()))
    }

    /// Returns the UTF-8 text content.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Returns the Unicode scalar length.
    pub fn len(&self) -> usize {
        self.0.chars().count()
    }

    /// Returns whether the text contains no Unicode scalars.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// An immutable ordered collection of Values.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct List(Arc<Vec<Value>>);

impl List {
    /// Creates a List from its elements.
    pub fn new(values: Vec<Value>) -> Self {
        Self(Arc::new(values))
    }

    /// Returns all elements as a borrowed slice.
    pub fn as_slice(&self) -> &[Value] {
        &self.0
    }

    /// Returns the number of elements.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns whether the List contains no elements.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the element at `index`, if present.
    pub fn get(&self, index: usize) -> Option<&Value> {
        self.0.get(index)
    }
}

/// An immutable map from unique string keys to Values.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Map(Arc<BTreeMap<String, Value>>);

impl Hash for Map {
    fn hash<H: Hasher>(&self, state: &mut H) {
        for (key, value) in self.0.iter() {
            key.hash(state);
            value.hash(state);
        }
    }
}

impl Map {
    /// Creates a Map and rejects duplicate keys.
    pub fn from_entries<I, K>(entries: I) -> Result<Self, ValueError>
    where
        I: IntoIterator<Item = (K, Value)>,
        K: Into<String>,
    {
        let mut map = BTreeMap::new();
        for (key, value) in entries {
            let key = key.into();
            if map.insert(key.clone(), value).is_some() {
                return Err(ValueError::DuplicateKey(key));
            }
        }
        Ok(Self(Arc::new(map)))
    }

    pub(crate) fn from_btree(map: BTreeMap<String, Value>) -> Self {
        Self(Arc::new(map))
    }

    /// Returns the Value associated with `key`, if present.
    pub fn get(&self, key: &str) -> Option<&Value> {
        self.0.get(key)
    }

    /// Iterates entries in canonical key order.
    pub fn iter(&self) -> impl Iterator<Item = (&String, &Value)> {
        self.0.iter()
    }

    /// Returns the number of entries.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns whether the Map contains no entries.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub(crate) fn to_btree(&self) -> BTreeMap<String, Value> {
        self.0.as_ref().clone()
    }
}

/// The closed set of Value type discriminants.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ValueType {
    /// Null.
    Null,
    /// Boolean.
    Bool,
    /// Signed 64-bit integer.
    Int,
    /// Finite IEEE-754 `f64`.
    Float,
    /// Atomic UTF-8 string.
    String,
    /// Collaborative text.
    Text,
    /// Collaborative rich text.
    RichText,
    /// Ordered Value list.
    List,
    /// String-keyed Value map.
    Map,
}

/// The closed recursive content model stored by [`Value`].
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ValueKind {
    /// Null value.
    Null,
    /// Boolean value.
    Bool(bool),
    /// Signed 64-bit integer value.
    Int(i64),
    /// Canonical finite floating-point value.
    Float(FiniteF64),
    /// Atomic UTF-8 string value.
    String(Arc<str>),
    /// Collaborative text value.
    Text(Text),
    /// Collaborative RichText value.
    RichText(RichText),
    /// Ordered List value.
    List(List),
    /// String-keyed Map value.
    Map(Map),
}

/// An immutable, structurally shared Core Value.
///
/// A Value may be used as a complete Snapshot or nested inside another Value.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct Value(Arc<ValueKind>);

impl fmt::Debug for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl Value {
    /// Creates Null.
    pub fn null() -> Self {
        Self(Arc::new(ValueKind::Null))
    }
    /// Creates a Bool.
    pub fn bool(value: bool) -> Self {
        Self(Arc::new(ValueKind::Bool(value)))
    }
    /// Creates an Int.
    pub fn int(value: i64) -> Self {
        Self(Arc::new(ValueKind::Int(value)))
    }
    /// Creates a Float, rejecting NaN and infinities.
    pub fn float(value: f64) -> Result<Self, ValueError> {
        Ok(Self(Arc::new(ValueKind::Float(FiniteF64::new(value)?))))
    }
    /// Creates a Float from an already validated finite value.
    pub fn finite_float(value: FiniteF64) -> Self {
        Self(Arc::new(ValueKind::Float(value)))
    }
    /// Creates an atomic String.
    pub fn string(value: impl Into<String>) -> Self {
        Self(Arc::new(ValueKind::String(Arc::from(value.into()))))
    }
    /// Creates collaborative Text.
    pub fn text(value: impl Into<String>) -> Self {
        Self(Arc::new(ValueKind::Text(Text::new(value))))
    }
    /// Creates a RichText Value.
    pub fn rich_text(value: RichText) -> Self {
        Self(Arc::new(ValueKind::RichText(value)))
    }
    /// Creates a List from an iterator of Values.
    pub fn list<I>(values: I) -> Self
    where
        I: IntoIterator<Item = Value>,
    {
        Self(Arc::new(ValueKind::List(List::new(
            values.into_iter().collect(),
        ))))
    }
    /// Creates a Map and rejects duplicate keys.
    pub fn map<I, K>(entries: I) -> Result<Self, ValueError>
    where
        I: IntoIterator<Item = (K, Value)>,
        K: Into<String>,
    {
        Ok(Self(Arc::new(ValueKind::Map(Map::from_entries(entries)?))))
    }
    pub(crate) fn from_kind(kind: ValueKind) -> Self {
        Self(Arc::new(kind))
    }

    /// Returns the concrete content kind.
    pub fn kind(&self) -> &ValueKind {
        &self.0
    }
    /// Returns the content type discriminant.
    pub fn value_type(&self) -> ValueType {
        match self.kind() {
            ValueKind::Null => ValueType::Null,
            ValueKind::Bool(_) => ValueType::Bool,
            ValueKind::Int(_) => ValueType::Int,
            ValueKind::Float(_) => ValueType::Float,
            ValueKind::String(_) => ValueType::String,
            ValueKind::Text(_) => ValueType::Text,
            ValueKind::RichText(_) => ValueType::RichText,
            ValueKind::List(_) => ValueType::List,
            ValueKind::Map(_) => ValueType::Map,
        }
    }

    /// Borrows the contained Map, if this Value is a Map.
    pub fn as_map(&self) -> Option<&Map> {
        if let ValueKind::Map(v) = self.kind() {
            Some(v)
        } else {
            None
        }
    }
    /// Borrows the contained List, if this Value is a List.
    pub fn as_list(&self) -> Option<&List> {
        if let ValueKind::List(v) = self.kind() {
            Some(v)
        } else {
            None
        }
    }
    /// Borrows the contained Text, if this Value is Text.
    pub fn as_text(&self) -> Option<&Text> {
        if let ValueKind::Text(v) = self.kind() {
            Some(v)
        } else {
            None
        }
    }
    /// Borrows the contained RichText, if this Value is RichText.
    pub fn as_rich_text(&self) -> Option<&RichText> {
        if let ValueKind::RichText(v) = self.kind() {
            Some(v)
        } else {
            None
        }
    }
    /// Returns the contained integer, if this Value is an Int.
    pub fn as_int(&self) -> Option<i64> {
        if let ValueKind::Int(v) = self.kind() {
            Some(*v)
        } else {
            None
        }
    }

    /// Resolves a Snapshot-relative Path and borrows the target Value.
    ///
    /// Paths navigate Map keys and List indexes only and are not part of a
    /// Change's canonical representation.
    pub fn get(&self, path: &Path) -> Option<&Value> {
        let mut current = self;
        for segment in path.segments() {
            current = match (current.kind(), segment) {
                (ValueKind::Map(map), PathSeg::Key(key)) => map.get(key)?,
                (ValueKind::List(list), PathSeg::Index(index)) => list.get(*index)?,
                _ => return None,
            };
        }
        Some(current)
    }

    pub(crate) fn check_input_limits(&self, limits: &InputLimits) -> Result<(), CodecError> {
        let mut stack = vec![(self, 1usize)];
        let mut nodes = 0usize;
        while let Some((value, depth)) = stack.pop() {
            nodes += 1;
            if nodes > limits.max_value_nodes {
                return Err(CodecError::LimitExceeded {
                    name: "value nodes",
                    actual: nodes,
                    limit: limits.max_value_nodes,
                });
            }
            if depth > limits.max_depth {
                return Err(CodecError::LimitExceeded {
                    name: "value depth",
                    actual: depth,
                    limit: limits.max_depth,
                });
            }
            match value.kind() {
                ValueKind::String(s) => {
                    check_len("string bytes", s.len(), limits.max_string_bytes)?
                }
                ValueKind::Text(t) => {
                    check_len("text bytes", t.as_str().len(), limits.max_string_bytes)?
                }
                ValueKind::List(list) => {
                    check_len("container length", list.len(), limits.max_container_len)?;
                    for child in list.as_slice().iter().rev() {
                        stack.push((child, depth + 1));
                    }
                }
                ValueKind::Map(map) => {
                    check_len("container length", map.len(), limits.max_container_len)?;
                    for (key, child) in map.iter() {
                        check_len("string bytes", key.len(), limits.max_string_bytes)?;
                        stack.push((child, depth + 1));
                    }
                }
                ValueKind::RichText(rich) => {
                    check_len(
                        "container length",
                        rich.span_count(),
                        limits.max_container_len,
                    )?;
                    check_len("sequence length", rich.len(), limits.max_sequence_len)?;
                    for span in rich.iter_spans().rev() {
                        match span.content() {
                            crate::richtext::RichContent::Text(text) => {
                                check_len(
                                    "string bytes",
                                    text.as_str().len(),
                                    limits.max_string_bytes,
                                )?;
                            }
                            crate::richtext::RichContent::Embed(child) => {
                                stack.push((child, depth + 1));
                            }
                        }
                        check_len(
                            "container length",
                            span.attrs().len(),
                            limits.max_container_len,
                        )?;
                        for (key, value) in span.attrs().iter() {
                            check_len("string bytes", key.len(), limits.max_string_bytes)?;
                            if let crate::AttrValue::String(value) = value {
                                check_len("string bytes", value.len(), limits.max_string_bytes)?;
                            }
                        }
                    }
                }
                _ => {}
            }
        }
        Ok(())
    }
}

fn check_len(name: &'static str, actual: usize, limit: usize) -> Result<(), CodecError> {
    if actual > limit {
        Err(CodecError::LimitExceeded {
            name,
            actual,
            limit,
        })
    } else {
        Ok(())
    }
}