braid-core 0.1.4

Unified Braid Protocol implementation in Rust, including Braid-HTTP, Antimatter CRDT, and BraidFS.
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
use std::ops::{Deref, DerefMut, Range};

pub trait HasLength {
    /// The number of child items in the entry. This is indexed with the size used in truncate.
    fn len(&self) -> usize;

    #[inline]
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<V> HasLength for &V where V: HasLength {
    fn len(&self) -> usize { (*self).len() }
}

pub trait SplitableSpanHelpers: Clone {
    /// Split the entry, returning the part of the entry which was jettisoned. After truncating at
    /// `pos`, self.len() == `pos` and the returned value contains the rest of the items.
    ///
    /// ```ignore
    /// let initial_len = entry.len();
    /// let rest = entry.truncate(truncate_at);
    /// assert!(initial_len == truncate_at + rest.len());
    /// ```
    ///
    /// `at` parameter must strictly obey *0 < at < entry.len()*
    fn truncate_h(&mut self, at: usize) -> Self;

    /// The inverse of truncate. This method mutably truncates an item, keeping all content from
    /// at..item.len() and returning the item range from 0..at.
    #[inline(always)]
    fn truncate_keeping_right_h(&mut self, at: usize) -> Self {
        let mut other = self.clone();
        *self = other.truncate_h(at);
        other
    }

    fn split(mut self, at: usize) -> (Self, Self) {
        let remainder = self.truncate_h(at);
        (self, remainder)
    }
}

impl<T: SplitableSpanHelpers> SplitableSpanCtx for T {
    type Ctx = ();

    fn truncate_ctx(&mut self, at: usize, _ctx: &Self::Ctx) -> Self {
        self.truncate_h(at)
        // SplitableSpanHelpers::truncate(self, at)
        // <self as SplitableSpanHelpers>::truncate(self, at)
    }
}

pub trait SplitableSpanCtx: Clone {
    type Ctx: ?Sized;

    /// Split the entry, returning the part of the entry which was jettisoned. After truncating at
    /// `pos`, self.len() == `pos` and the returned value contains the rest of the items.
    ///
    /// ```ignore
    /// let initial_len = entry.len();
    /// let rest = entry.truncate(truncate_at);
    /// assert!(initial_len == truncate_at + rest.len());
    /// ```
    ///
    /// `at` parameter must strictly obey *0 < at < entry.len()*
    fn truncate_ctx(&mut self, at: usize, ctx: &Self::Ctx) -> Self;

    /// The inverse of truncate. This method mutably truncates an item, keeping all content from
    /// at..item.len() and returning the item range from 0..at.
    #[inline(always)]
    fn truncate_keeping_right_ctx(&mut self, at: usize, ctx: &Self::Ctx) -> Self {
        let mut other = self.clone();
        *self = other.truncate_ctx(at, ctx);
        other
    }

    fn split_ctx(mut self, at: usize, ctx: &Self::Ctx) -> (Self, Self) {
        let remainder = self.truncate_ctx(at, ctx);
        (self, remainder)
    }
}

// Do not implement this directly.
pub trait SplitableSpan: SplitableSpanCtx<Ctx=()> {
    /// Split the entry, returning the part of the entry which was jettisoned. After truncating at
    /// `pos`, self.len() == `pos` and the returned value contains the rest of the items.
    ///
    /// ```ignore
    /// let initial_len = entry.len();
    /// let rest = entry.truncate(truncate_at);
    /// assert!(initial_len == truncate_at + rest.len());
    /// ```
    ///
    /// `at` parameter must strictly obey *0 < at < entry.len()*
    fn truncate(&mut self, at: usize) -> Self {
        self.truncate_ctx(at, &())
    }

    /// The inverse of truncate. This method mutably truncates an item, keeping all content from
    /// at..item.len() and returning the item range from 0..at.
    #[inline(always)]
    fn truncate_keeping_right(&mut self, at: usize) -> Self {
        self.truncate_keeping_right_ctx(at, &())
    }

    fn split_h(mut self, at: usize) -> (Self, Self) {
        let remainder = self.truncate_ctx(at, &());
        (self, remainder)
    }
}

impl<T: SplitableSpanCtx<Ctx=()>> SplitableSpan for T {}

// This is a bit of a hack. This wrapper trait lets us use regular splitablespan methods in lots of
// situations.
#[derive(Debug)]
pub struct WithCtx<'a, T: SplitableSpanCtx + Clone>(pub T, pub &'a T::Ctx);

impl<'a, T: SplitableSpanCtx + Clone> Deref for WithCtx<'a, T> {
    type Target = T;

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

impl<'a, T: SplitableSpanCtx + Clone> DerefMut for WithCtx<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<'a, T: SplitableSpanCtx + Clone> WithCtx<'a, T> {
    pub fn new(t: T, ctx: &'a T::Ctx) -> Self {
        Self(t, ctx)
    }

    pub fn to_inner(self) -> T {
        self.0
    }
}

impl<'a, T: SplitableSpanCtx + Clone> Clone for WithCtx<'a, T> {
    fn clone(&self) -> Self {
        WithCtx(self.0.clone(), self.1)
    }
}

impl<'a, T: SplitableSpanCtx> SplitableSpanCtx for WithCtx<'a, T> {
    type Ctx = ();

    fn truncate_ctx(&mut self, at: usize, _ctx: &Self::Ctx) -> Self {
        WithCtx(self.0.truncate_ctx(at, self.1), self.1)
    }

    fn truncate_keeping_right_ctx(&mut self, at: usize, _ctx: &Self::Ctx) -> Self {
        WithCtx(self.0.truncate_keeping_right_ctx(at, self.1), self.1)
    }
}

impl<'a, T: SplitableSpanCtx + HasLength> HasLength for WithCtx<'a, T> {
    fn len(&self) -> usize {
        self.0.len()
    }
}

// struct WithoutCtx<T: SplitableSpanCtx<Ctx=()>>(T);


// impl<T: SplitableSpanCtx<Ctx=()>> SplitableSpan for T {
//     fn truncate(&mut self, at: usize) -> Self {
//         self.truncate_ctx(at, &())
//     }
//
//     fn truncate_keeping_right(&mut self, at: usize) -> Self {
//         self.truncate_keeping_right_ctx(at, &())
//     }
//
//     fn split(self, at: usize) -> (Self, Self) {
//         self.split_ctx(at, &())
//     }
// }

pub trait TrimCtx: SplitableSpanCtx + HasLength {
    /// Trim self to at most `at` items. Remainder (if any) is returned.
    #[inline]
    fn trim_ctx(&mut self, at: usize, ctx: &Self::Ctx) -> Option<Self> {
        if at >= self.len() {
            None
        } else {
            Some(self.truncate_ctx(at, ctx))
        }
    }
}

impl<T: SplitableSpanCtx + HasLength> TrimCtx for T {}

pub trait Trim: SplitableSpan + HasLength {
    #[inline]
    fn trim(&mut self, at: usize) -> Option<Self> {
        self.trim_ctx(at, &())
    }
}

impl<T: SplitableSpan + HasLength> Trim for T {}


/// TODO: This could almost always be written to just take a T rather than needing Option.
pub struct Shatter<T>(Option<T>);

impl<T: SplitableSpan + HasLength> Iterator for Shatter<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        let Some(val) = self.0.as_mut() else { return None; };

        if val.len() > 1 {
            Some(val.truncate_keeping_right(1))
        } else {
            self.0.take()
        }
    }
}

/// Iterate over the individual elements of a given item.
pub fn shatter<T: SplitableSpan + HasLength>(item: T) -> Shatter<T> {
    Shatter(Some(item))
}

pub trait MergableSpan: Clone {
    /// See if the other item can be appended to self. `can_append` will always be called
    /// immediately before `append`.
    fn can_append(&self, other: &Self) -> bool;

    /// Merge the passed item into self. Essentially, self = self + other.
    ///
    /// The other item *must* be a valid target for merging
    /// (as per can_append(), above).
    fn append(&mut self, other: Self);

    /// Append an item at the start of this item. self = other + self.
    ///
    /// This item must be a valid append target for other. That is, `other.can_append(self)` must
    /// be true for this method to be called.
    #[inline(always)]
    fn prepend(&mut self, mut other: Self) {
        other.append(self.clone());
        *self = other;
    }
}

/// An entry is expected to contain multiple items.
///
/// A SplitableSpan is a range entry. That is, an entry which contains a compact run of many
/// entries internally.
pub trait SplitAndJoinSpan: HasLength + SplitableSpan + MergableSpan {}
impl<T: HasLength + SplitableSpan + MergableSpan> SplitAndJoinSpan for T {}

pub trait SplitAndJoinSpanCtx: HasLength + SplitableSpanCtx + MergableSpan {}
impl<T: HasLength + SplitableSpanCtx + MergableSpan> SplitAndJoinSpanCtx for T {}

/// A SplitableSpan wrapper for any single item.
#[derive(Copy, Clone, Hash, Debug, PartialEq, Eq, Default)]
pub struct Single<T>(pub T);

/// A splitablespan in reverse. This is useful for making lists in descending order.
#[derive(Copy, Clone, Hash, Debug, PartialEq, Eq, Default)]
pub struct ReverseSpan<S>(pub S);

impl<T> HasLength for Single<T> {
    fn len(&self) -> usize { 1 }
}
impl<T: Clone> SplitableSpanHelpers for Single<T> {
    // This is a valid impl because truncate can never be called for single items.
    fn truncate_h(&mut self, _at: usize) -> Self { panic!("Cannot truncate single sized item"); }
}
impl<T: Clone> MergableSpan for Single<T> {
    fn can_append(&self, _other: &Self) -> bool { false }
    fn append(&mut self, _other: Self) { panic!("Cannot append to single sized item"); }
}

// impl<T: HasRleKey> HasRleKey for ReverseSpan<T> {
//     // You might think we need to reverse this or something, but I don't think thats generally true.
//     fn rle_key(&self) -> usize {
//         self.0.rle_key()
//     }
// }
impl<S: HasLength> HasLength for ReverseSpan<S> {
    fn len(&self) -> usize { self.0.len() }
}
impl<S: SplitableSpanCtx<Ctx=()>> SplitableSpanHelpers for ReverseSpan<S> {
    fn truncate_h(&mut self, at: usize) -> Self {
        ReverseSpan(self.0.truncate_keeping_right(at))
    }
    fn truncate_keeping_right_h(&mut self, at: usize) -> Self {
        ReverseSpan(self.0.truncate(at))
    }
}
impl<S: MergableSpan> MergableSpan for ReverseSpan<S> {
    fn can_append(&self, other: &Self) -> bool { other.0.can_append(&self.0) }
    fn append(&mut self, other: Self) { self.0.prepend(other.0); }
    fn prepend(&mut self, other: Self) { self.0.append(other.0); }
}

impl<A, B> MergableSpan for (A, B) where A: MergableSpan, B: MergableSpan {
    fn can_append(&self, other: &Self) -> bool {
        self.0.can_append(&other.0) && self.1.can_append(&other.1)
    }

    fn append(&mut self, other: Self) {
        self.0.append(other.0);
        self.1.append(other.1);
    }
}

impl<A, B> HasLength for (A, B) where A: HasLength {
    fn len(&self) -> usize {
        // debug_assert_eq!(self.0.len(), self.1.len());
        self.0.len()
    }
}

impl<A, B> SplitableSpanHelpers for (A, B) where A: SplitableSpan, B: SplitableSpan {
    fn truncate_h(&mut self, at: usize) -> Self {
        (self.0.truncate(at), self.1.truncate(at))
    }
}

// impl<A, B> SplitableSpanCtx for (A, B) where A: SplitableSpanCtx, B: SplitableSpanCtx, A::Ctx: Sized, B::Ctx: Sized {
//     type Ctx = (A::Ctx, B::Ctx);
//
//     fn truncate_ctx(&mut self, at: usize, ctx: &Self::Ctx) -> Self {
//         (self.0.truncate_ctx(at, &ctx.0), self.1.truncate_ctx(at, &ctx.1))
//     }
// }


// impl<T, E> SplitableSpan for Result<T, E> where T: SplitableSpan + Clone, E: Clone {
//     fn truncate(&mut self, at: usize) -> Self {
//         match self {
//             Ok(v) => Result::Ok(v.truncate(at)),
//             Err(e) => Result::Err(e.clone())
//         }
//     }
// }

impl<T, E> SplitableSpanCtx for Result<T, E> where T: SplitableSpanCtx + Clone, E: Clone {
    type Ctx = T::Ctx;

    fn truncate_ctx(&mut self, at: usize, ctx: &Self::Ctx) -> Self {
        match self {
            Ok(v) => Result::Ok(v.truncate_ctx(at, ctx)),
            Err(e) => Result::Err(e.clone())
        }
    }
}

impl<T, E> HasLength for Result<T, E> where T: HasLength, Result<T, E>: Clone {
    fn len(&self) -> usize {
        match self {
            Ok(val) => val.len(),
            Err(_) => 1
        }
    }
}

impl<V> SplitableSpanHelpers for Option<V> where V: SplitableSpan {
    fn truncate_h(&mut self, at: usize) -> Self {
        self.as_mut().map(|v| v.truncate(at))
        // match self {
        //     None => None,
        //     Some(v) => Some(v.truncate(at))
        // }
    }
}

// This will implement SplitableSpan for u8, u16, u32, u64, u128, usize
// impl<T: Add<Output=T> + Sub + Copy + Eq> SplitableSpan for Range<T>
// where usize: From<<T as Sub>::Output>, T: From<usize>
// {
//     fn len(&self) -> usize {
//         (self.end - self.start).into()
//     }
//
//     fn truncate(&mut self, at: usize) -> Self {
//         let old_end = self.end;
//         self.end = self.start + at.into();
//         Self { start: self.end, end: old_end }
//     }
//
//     fn can_append(&self, other: &Self) -> bool {
//         self.end == other.start
//     }
//
//     fn append(&mut self, other: Self) {
//         self.end = other.end;
//     }
// }

// Implement me for all numeric types!
impl HasLength for Range<u32> {
    fn len(&self) -> usize { (self.end - self.start) as _ }
}
// impl HasLength for Range<usize> {
//     fn len(&self) -> usize { (self.end - self.start) as _ }
// }

impl SplitableSpanHelpers for Range<u32> {
    // This is a valid impl because truncate can never be called for single items.
    fn truncate_h(&mut self, at: usize) -> Self {
        let old_end = self.end;
        self.end = self.start + at as u32;
        Self { start: self.end, end: old_end }
    }
}
impl MergableSpan for Range<u32> {
    fn can_append(&self, other: &Self) -> bool {
        self.end == other.start
    }

    fn append(&mut self, other: Self) {
        self.end = other.end;
    }
}

impl SplitableSpanHelpers for Range<usize> {
    // This is a valid impl because truncate can never be called for single items.
    fn truncate_h(&mut self, at: usize) -> Self {
        let old_end = self.end;
        self.end = self.start + at;
        Self { start: self.end, end: old_end }
    }
}
impl MergableSpan for Range<usize> {
    fn can_append(&self, other: &Self) -> bool {
        self.end == other.start
    }

    fn append(&mut self, other: Self) {
        self.end = other.end;
    }
}

/// Simple test helper to verify an implementation of SplitableSpan is valid and meets expected
/// constraints.
///
/// Use this to test splitablespan implementations in tests.
// #[cfg(test)]
pub fn test_splitable_methods_valid<E: SplitAndJoinSpan + std::fmt::Debug + Clone + Eq>(entry: E) {
    test_splitable_methods_valid_ctx(entry, &());
}

pub fn test_splitable_methods_valid_ctx<E: SplitAndJoinSpanCtx + std::fmt::Debug + Clone + Eq>(entry: E, ctx: &E::Ctx) {
    assert!(entry.len() >= 2, "Call this with a larger entry");
    // dbg!(&entry);

    for i in 1..entry.len() {
        // Split here and make sure we get the expected results.
        let mut start = entry.clone();
        let end = start.truncate_ctx(i, ctx);
        // dbg!(&start, &end);

        assert_eq!(start.len(), i);
        assert_eq!(end.len(), entry.len() - i);

        // dbg!(&start, &end);
        assert!(start.can_append(&end));

        let mut merge_append = start.clone();

        // dbg!(&start, &end);
        merge_append.append(end.clone());
        // dbg!(&merge_append);
        assert_eq!(merge_append, entry);

        let mut merge_prepend = end.clone();
        merge_prepend.prepend(start.clone());
        assert_eq!(merge_prepend, entry);

        // Split using truncate_keeping_right. We should get the same behaviour.
        let mut end2 = entry.clone();
        let start2 = end2.truncate_keeping_right_ctx(i, ctx);
        assert_eq!(end2, end);
        assert_eq!(start2, start);
    }
}

#[cfg(test)]
mod test {
    use crate::vendor::rle::*;
    use crate::vendor::rle::rlerun::{RleDRun, RleRun};

    #[test]
    fn test_rle_run() {
        assert!(!RleRun { val: 10, len: 5 }.can_append(&RleRun { val: 20, len: 5 }));
        assert!(RleRun { val: 10, len: 5 }.can_append(&RleRun { val: 10, len: 15 }));

        test_splitable_methods_valid(RleRun { val: 12, len: 5 });
    }

    #[test]
    fn test_rle_distinct() {
        assert!(RleDRun::new(0..10, 'x').can_append(&RleDRun::new(10..20, 'x')));
        assert!(!RleDRun::new(0..10, 'x').can_append(&RleDRun::new(10..20, 'y')));
        assert!(!RleDRun::new(0..10, 'x').can_append(&RleDRun::new(11..20, 'x')));

        test_splitable_methods_valid(RleDRun::new(0..10, 'x'));
    }

    #[test]
    fn splitable_range() {
        test_splitable_methods_valid(0..10);
        test_splitable_methods_valid(0u32..10u32);
    }
}