json0-rs 0.1.0

JSON0 OT implement in rust.
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
use std::rc::Rc;

use crate::common::Validation;
use crate::error::Result;
use crate::json::Appliable;
use crate::operation::{Operation, OperationComponent, Operator};
use crate::path::{Path, PathElement};
use crate::sub_type::SubTypeFunctionsHolder;

fn is_equivalent_to_noop(op: &OperationComponent) -> bool {
    match &op.operator {
        Operator::Noop() => true,
        Operator::SubType(_, _, _) => false,
        Operator::ListInsert(_)
        | Operator::ListDelete(_)
        | Operator::ObjectInsert(_)
        | Operator::ObjectDelete(_) => false,
        Operator::ListReplace(new_v, old_v) | Operator::ObjectReplace(new_v, old_v) => {
            new_v.eq(old_v)
        }
        Operator::ListMove(lm) => op
            .path
            .last()
            .map(|p| p == &PathElement::Index(*lm))
            .unwrap_or(false),
    }
}

fn is_same_operand(op_a: &OperationComponent, op_b: &OperationComponent) -> bool {
    if let Operator::SubType(_, _, _) = op_a.operator {
        return false;
    }

    if let Operator::SubType(_, _, _) = op_b.operator {
        return false;
    }

    op_a.path.len() == op_b.path.len()
}

#[derive(PartialEq)]
pub enum TransformSide {
    LEFT,
    RIGHT,
}

pub struct Transformer {}

impl Transformer {
    pub fn new(_: Rc<SubTypeFunctionsHolder>) -> Transformer {
        Transformer {}
    }

    pub fn transform(
        &self,
        operation: &Operation,
        base_operation: &Operation,
    ) -> Result<(Operation, Operation)> {
        if base_operation.is_empty() {
            return Ok((operation.clone(), Operation::empty_operation()));
        }

        operation.validates()?;
        base_operation.validates()?;

        if operation.len() == 1 && base_operation.len() == 1 {
            let a = self.transform_component(
                operation.get(0).unwrap().clone(),
                base_operation.get(0).unwrap(),
                TransformSide::LEFT,
            )?;
            let b = self.transform_component(
                base_operation.get(0).unwrap().clone(),
                operation.get(0).unwrap(),
                TransformSide::RIGHT,
            )?;

            return Ok((a.into(), b.into()));
        }

        self.transform_matrix(operation.clone(), base_operation.clone())
    }

    fn transform_matrix(
        &self,
        operation: Operation,
        base_operation: Operation,
    ) -> Result<(Operation, Operation)> {
        if operation.is_empty() || base_operation.is_empty() {
            return Ok((operation, base_operation));
        }

        let mut out_b = vec![];
        let mut ops = operation;
        for base_op in base_operation {
            let (a, b) = self.transform_multi(ops, base_op)?;
            ops = a;

            if let Some(o) = b {
                out_b.push(o);
            }
        }

        Ok((ops, out_b.into()))
    }

    fn transform_multi(
        &self,
        operation: Operation,
        base_op: OperationComponent,
    ) -> Result<(Operation, Option<OperationComponent>)> {
        let mut out: Vec<OperationComponent> = vec![];

        let mut base = base_op.not_noop();
        for op in operation {
            match base {
                Some(b) => {
                    let backup = op.clone();
                    let mut a = self.transform_component(op, &b, TransformSide::LEFT)?;
                    let mut b = self.transform_component(b, &backup, TransformSide::RIGHT)?;
                    assert!(b.len() == 1);
                    base = b.pop();

                    out.append(&mut a);
                }
                None => {
                    out.push(op.clone());
                    continue;
                }
            }
        }

        Ok((out.into(), base))
    }

    fn transform_component(
        &self,
        new_op: OperationComponent,
        base_op: &OperationComponent,
        side: TransformSide,
    ) -> Result<Vec<OperationComponent>> {
        let mut new_op = new_op;
        if is_equivalent_to_noop(&new_op) || is_equivalent_to_noop(base_op) {
            return Ok(vec![new_op]);
        }

        let max_common_path = base_op.path.max_common_path(&new_op.path);
        let new_operate_path_len = new_op.operate_path_len();
        let base_operate_path_len = base_op.operate_path_len();

        if max_common_path.len() < new_operate_path_len
            && max_common_path.len() < base_operate_path_len
        {
            // common path must be equal to new_op's or base_op's operate path
            // or base_op and new_op is operating on orthogonal value
            // they don't need transform
            return Ok(vec![new_op]);
        }

        // such as:
        // new_op, base_op
        // [p1,p2,p3], [p1,p2,p4,p5]
        // [p1,p2,p3], [p1,p2,p3,p5]
        if base_operate_path_len > new_operate_path_len {
            // if base_op's path is longger and contains new_op's path, new_op should include base_op's effect
            if new_op.path.is_prefix_of(&base_op.path) {
                self.consume(&mut new_op, &max_common_path, base_op)?;
            }
            return Ok(vec![new_op]);
        }

        // from here, base_op's path is shorter or equal to new_op, such as:
        // new_op, base_op
        // [p1,p2,p3], [p1,p2,p3]. same operand and base_op is prefix of new_op
        // [p1,p2,p4], [p1,p2,p3]. same operand
        // [p1,p2,p3,p4,..], [p1,p2,p3], base_op is prefix of new_op
        // [p1,p2,p4,p5,..], [p1,p2,p3]
        let same_operand = is_same_operand(base_op, &new_op);
        let base_op_is_prefix = base_op.path.is_prefix_of(&new_op.path);
        match &base_op.operator {
            Operator::SubType(base_sub_type, base_op_operand, base_f) => {
                if let Operator::SubType(new_op_subtype, new_op_operand, _) = &new_op.operator {
                    if base_sub_type.eq(new_op_subtype) {
                        return base_f
                            .transform(new_op_operand, base_op_operand, side)?
                            .into_iter()
                            .map(|new_operand| {
                                OperationComponent::new(
                                    base_op.path.clone(),
                                    Operator::SubType(
                                        base_sub_type.clone(),
                                        new_operand,
                                        base_f.box_clone(),
                                    ),
                                )
                            })
                            .collect::<Result<Vec<OperationComponent>>>();
                    }
                }
            }
            Operator::ListReplace(li_v, _) => {
                if base_op_is_prefix {
                    if !same_operand {
                        return Ok(vec![]);
                    }
                    if let Operator::ListReplace(new_li, _) = &new_op.operator {
                        if side == TransformSide::LEFT {
                            return Ok(vec![OperationComponent::new(
                                new_op.path,
                                Operator::ListReplace(new_li.clone(), li_v.clone()),
                            )?]);
                        } else {
                            return Ok(vec![]);
                        }
                    }
                    if let Operator::ListDelete(_) = &new_op.operator {
                        return Ok(vec![]);
                    }
                }
            }
            Operator::ListInsert(_) => {
                if let Operator::ListInsert(_) = &new_op.operator {
                    if same_operand && base_op_is_prefix {
                        if side == TransformSide::RIGHT {
                            new_op.path.increase_index(base_operate_path_len);
                        }
                        return Ok(vec![new_op]);
                    }
                }

                if base_op
                    .path
                    .get(base_operate_path_len)
                    .and_then(|p1| new_op.path.get(base_operate_path_len).map(|p2| p1 <= p2))
                    .unwrap_or(false)
                {
                    new_op.path.increase_index(base_operate_path_len);
                }

                if let Operator::ListMove(lm) = &mut new_op.operator {
                    if same_operand
                        && base_op
                            .path
                            .get(base_operate_path_len)
                            .map(|p| p <= &PathElement::Index(*lm))
                            .unwrap_or(false)
                    {
                        new_op.operator = Operator::ListMove(*lm + 1);
                    }
                }
            }
            Operator::ListDelete(_) => {
                let base_op_operate_path = base_op.path.get(base_operate_path_len).unwrap();
                let new_op_operate_path = new_op.path.get(base_operate_path_len).unwrap();
                if let Operator::ListMove(lm) = new_op.operator {
                    if same_operand {
                        if base_op_is_prefix {
                            // base_op deleted the thing we're trying to move
                            return Ok(vec![]);
                        }
                        let to = lm.into();
                        if base_op_operate_path < &to
                            || (base_op_operate_path.eq(&to) && new_op_operate_path < &to)
                        {
                            new_op.operator = Operator::ListMove(lm - 1);
                        }
                    }
                }

                if base_op_operate_path < new_op_operate_path {
                    new_op.path.decrease_index(base_operate_path_len);
                } else if base_op_is_prefix {
                    if !same_operand {
                        // we're below the deleted element, so -> noop
                        return Ok(vec![]);
                    }
                    if let Operator::ListDelete(_) = new_op.operator {
                        // we're trying to delete the same element, -> noop
                        return Ok(vec![]);
                    }
                    if let Operator::ListReplace(li, _) = new_op.operator {
                        // we're replacing, they're deleting. we become an insert.
                        return Ok(vec![OperationComponent::new(
                            new_op.path.clone(),
                            Operator::ListInsert(li.clone()),
                        )?]);
                    }
                }
            }
            Operator::ObjectReplace(oi, _) => {
                if base_op_is_prefix {
                    if !same_operand {
                        return Ok(vec![]);
                    }

                    match &new_op.operator {
                        Operator::ObjectReplace(new_oi, _) | Operator::ObjectInsert(new_oi) => {
                            if side == TransformSide::RIGHT {
                                return Ok(vec![]);
                            }
                            return Ok(vec![OperationComponent {
                                path: new_op.path.clone(),
                                operator: Operator::ObjectReplace(new_oi.clone(), oi.clone()),
                            }]);
                        }
                        _ => {
                            return Ok(vec![]);
                        }
                    }
                }
            }
            Operator::ObjectInsert(base_oi) => {
                if base_op_is_prefix {
                    if let Operator::ObjectReplace(new_oi, _) | Operator::ObjectInsert(new_oi) =
                        &new_op.operator
                    {
                        if side == TransformSide::LEFT {
                            if same_operand {
                                return Ok(vec![OperationComponent {
                                    path: base_op.path.clone(),
                                    operator: Operator::ObjectReplace(
                                        new_oi.clone(),
                                        base_oi.clone(),
                                    ),
                                }]);
                            }
                            // Here, we are different from original json0
                            // eg: new_op = [{"p": ["p1", "p2"],"oi": "v1"}], base_op = [{"p": ["p1"],"oi": "v2"}]
                            // after execution of these op, the result should be {"p1":{"p2":"v1"}}, so new_op after left transform
                            // is [{"p": ["p1"],"od": "v2"}, {"p": ["p1", "p2"],"oi": "v1"}]
                            // but original json0 is [{"p": ["p1", "p2"],"od": "v2"}, {"p": ["p1", "p2"],"oi": "v1"}]
                            // the problem of original json0 is "v2" inserted by base_op is under path p1, not [p1, p2]
                            return Ok(vec![
                                OperationComponent {
                                    path: base_op.path.clone(),
                                    operator: Operator::ObjectDelete(base_oi.clone()),
                                },
                                new_op,
                            ]);
                        } else {
                            return Ok(vec![]);
                        }
                    } else if let Operator::ObjectDelete(_) = &new_op.operator {
                        if side == TransformSide::RIGHT {
                            return Ok(vec![]);
                        }
                    }
                }
            }
            Operator::ObjectDelete(_) => {
                if base_op_is_prefix {
                    if !same_operand {
                        return Ok(vec![]);
                    }
                    if let Operator::ObjectReplace(new_oi, _) | Operator::ObjectInsert(new_oi) =
                        &new_op.operator
                    {
                        if side == TransformSide::LEFT {
                            return Ok(vec![OperationComponent {
                                path: new_op.path.clone(),
                                operator: Operator::ObjectInsert(new_oi.clone()),
                            }]);
                        } else {
                            return Ok(vec![]);
                        }
                    } else {
                        return Ok(vec![]);
                    }
                }
            }
            Operator::ListMove(lm) => {
                if same_operand {
                    match &mut new_op.operator {
                        Operator::ListMove(new_op_lm) => {
                            let other_from = base_op.path.get(new_operate_path_len).unwrap();
                            let other_to = PathElement::Index(*lm);

                            if other_from == &other_to {
                                return Ok(vec![new_op]);
                            }

                            let from = new_op.path.get(new_operate_path_len).unwrap().clone();
                            let to: PathElement = PathElement::Index(*new_op_lm);

                            if &from == other_from {
                                if to == other_to {
                                    // already moved to where we want
                                    return Ok(vec![]);
                                }
                                if side == TransformSide::LEFT {
                                    new_op.path.replace(base_operate_path_len, other_to.clone());
                                    if from == to {
                                        new_op.operator = base_op.operator.clone();
                                    }
                                } else {
                                    return Ok(vec![]);
                                }
                            } else {
                                let mut n_lm = *new_op_lm;
                                if &from > other_from {
                                    new_op.path.decrease_index(base_operate_path_len);
                                }
                                if from > other_to {
                                    new_op.path.increase_index(base_operate_path_len);
                                } else if from == other_to && other_from > &other_to {
                                    new_op.path.increase_index(base_operate_path_len);
                                    if from == to {
                                        n_lm += 1;
                                    }
                                }
                                if &to > other_from || (&to == other_from && to > from) {
                                    n_lm -= 1;
                                }
                                if to > other_to {
                                    n_lm += 1;
                                } else if to == other_to {
                                    if (&other_to > other_from && to > from)
                                        || (&other_to < other_from && to < from)
                                    {
                                        if side == TransformSide::RIGHT {
                                            n_lm += 1;
                                        }
                                    } else if to > from {
                                        n_lm += 1;
                                    } else if &to == other_from {
                                        n_lm -= 1;
                                    }
                                }
                                new_op.operator = Operator::ListMove(n_lm);
                            }
                            return Ok(vec![new_op]);
                        }
                        Operator::ListInsert(_) => {
                            let operate_index = base_operate_path_len;
                            let from = base_op.path.get(operate_index).unwrap();
                            let to = *lm;
                            let p = new_op.path.get(operate_index).unwrap().clone();
                            if &p > from {
                                new_op.path.decrease_index(operate_index);
                            }
                            if p > PathElement::Index(to) {
                                new_op.path.increase_index(operate_index);
                            }
                            return Ok(vec![new_op]);
                        }
                        _ => {}
                    }
                }
                let from = base_op.path.get(base_operate_path_len).unwrap();
                let to = PathElement::Index(*lm);
                let p = new_op.path.get(base_operate_path_len).unwrap().clone();
                if &p == from {
                    new_op.path.replace(base_operate_path_len, to.clone());
                } else {
                    if &p > from {
                        new_op.path.decrease_index(base_operate_path_len);
                    }
                    if p > to || (p == to && from > &to) {
                        new_op.path.increase_index(base_operate_path_len);
                    }
                }
            }
            _ => {}
        }

        Ok(vec![new_op])
    }

    pub fn consume(
        &self,
        op: &mut OperationComponent,
        common_path: &Path,
        other: &OperationComponent,
    ) -> Result<()> {
        match &mut op.operator {
            Operator::ListDelete(v)
            | Operator::ListReplace(_, v)
            | Operator::ObjectDelete(v)
            | Operator::ObjectReplace(_, v) => {
                let (_, p2) = other.path.split_at(common_path.len());
                // v maybe cannot apply other.operator
                // if that happen we do not consume other just leave origin op
                _ = v.apply(p2, other.operator.clone());
            }
            _ => {}
        }
        Ok(())
    }
}