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
/*!
Types and traits for functionally describing mutation of immutable maps
*/
use super::*;
use std::marker::PhantomData;

/// A mutation to perform at a single key-value pair
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Mutation<K, V> {
    /// Leave the entry alone
    Null,
    /// Remove the entry
    Remove,
    /// Replace *only a nonexisting* entry with another value
    Insert(K, V),
    /// Replace *only an existing* entry with another value
    Update(V),
}

impl<K, V> Mutation<K, V> {
    /// Transform an action into the appropriate action for a potentially empty entry
    ///
    /// A user usually does not need to worry about this, as it is done automatically with the result of the `mutate` function
    pub fn normalize(self, is_empty: bool) -> Mutation<K, V> {
        use Mutation::*;
        match (self, is_empty) {
            (Null, _) | (Remove, true) | (Update(_), true) | (Insert(_, _), false) => Null,
            (mutation, _) => mutation,
        }
    }
    /// Check whether an action is null
    pub fn is_null(&self) -> bool {
        matches!(self, Mutation::Null)
    }
}

/// Specially optimized mutators on a single map
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, PartialOrd, Ord)]
pub enum UnaryMutatorKind {
    /// The null mutator, i.e. leave the map alone
    Null,
    /// The deletion mutator, i.e. completely delete the map
    Delete,
    /// A general value mutator
    General,
}

/// A unary value transformer, leaving keys intact
pub trait UnaryTransformer<K, I, O> {
    /// Transform a value from the input type to the output type, or delete it
    fn transform(&mut self, key: &K, value: &I) -> Option<O>;
}

/// A unary mutator, leaving keys and value *types* intact
pub trait UnaryMutator<K, V>: UnaryTransformer<K, V, V> {
    /// The kind of this mutation, if it can be specially optimized
    #[inline(always)]
    fn kind(&mut self) -> UnaryMutatorKind {
        UnaryMutatorKind::General
    }
    /// Mutate a value: should be the same as `transform`, except sometimes returning `UnaryResult::Old`
    /// when the output would be equal to the input
    #[inline(always)]
    fn mutate(&mut self, key: &K, value: &V) -> UnaryResult<Option<V>> {
        UnaryResult::New(self.transform(key, value))
    }
}

/// The null mutator
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct NullMutator;

impl<K, V: Clone> UnaryTransformer<K, V, V> for NullMutator {
    #[inline(always)]
    fn transform(&mut self, _key: &K, value: &V) -> Option<V> {
        Some(value.clone())
    }
}

impl<K, V: Clone> UnaryMutator<K, V> for NullMutator {
    #[inline(always)]
    fn kind(&mut self) -> UnaryMutatorKind {
        UnaryMutatorKind::Null
    }
    #[inline(always)]
    fn mutate(&mut self, _key: &K, _value: &V) -> UnaryResult<Option<V>> {
        UnaryResult::Old
    }
}

/// The deletion mutator
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct DeleteMutator;

impl<K, I, O> UnaryTransformer<K, I, O> for DeleteMutator {
    #[inline(always)]
    fn transform(&mut self, _key: &K, _value: &I) -> Option<O> {
        None
    }
}

impl<K, V> UnaryMutator<K, V> for DeleteMutator {
    #[inline(always)]
    fn kind(&mut self) -> UnaryMutatorKind {
        UnaryMutatorKind::Delete
    }
}

/// The `FilterMap` operation
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct FilterMap<F, K, I, O> {
    /// The underlying function used
    pub func: F,
    key_type: PhantomData<K>,
    input_type: PhantomData<I>,
    output_type: PhantomData<O>,
}

impl<F, K, I, O> FilterMap<F, K, I, Option<O>> {
    /// Create a new `FilterMap` operation
    pub fn new(func: F) -> FilterMap<F, K, I, Option<O>>
    where
        F: FnMut(&K, &I) -> Option<O>,
    {
        FilterMap {
            func,
            key_type: PhantomData,
            input_type: PhantomData,
            output_type: PhantomData,
        }
    }
}

impl<F, K, V> FilterMap<F, K, V, UnaryResult<Option<V>>> {
    /// Create a new, annotated `FilterMap` mutator
    pub fn annotated(func: F) -> FilterMap<F, K, V, UnaryResult<Option<V>>>
    where
        F: FnMut(&K, &V) -> UnaryResult<Option<V>>,
    {
        FilterMap {
            func,
            key_type: PhantomData,
            input_type: PhantomData,
            output_type: PhantomData,
        }
    }
}

impl<F, K, I, O> UnaryTransformer<K, I, O> for FilterMap<F, K, I, Option<O>>
where
    F: FnMut(&K, &I) -> Option<O>,
{
    #[inline(always)]
    fn transform(&mut self, key: &K, value: &I) -> Option<O> {
        (self.func)(key, value)
    }
}

impl<F, K, V> UnaryTransformer<K, V, V> for FilterMap<F, K, V, UnaryResult<Option<V>>>
where
    F: FnMut(&K, &V) -> UnaryResult<Option<V>>,
    V: Clone,
{
    #[inline(always)]
    fn transform(&mut self, key: &K, value: &V) -> Option<V> {
        match (self.func)(key, value) {
            UnaryResult::Old => Some(value.clone()),
            UnaryResult::New(n) => n,
        }
    }
}

impl<F, K, V> UnaryMutator<K, V> for FilterMap<F, K, V, Option<V>>
where
    F: FnMut(&K, &V) -> Option<V>,
{
    #[inline(always)]
    fn kind(&mut self) -> UnaryMutatorKind {
        UnaryMutatorKind::General
    }
}

impl<F, K, V> UnaryMutator<K, V> for FilterMap<F, K, V, UnaryResult<Option<V>>>
where
    V: Clone,
    F: FnMut(&K, &V) -> UnaryResult<Option<V>>,
{
    #[inline(always)]
    fn kind(&mut self) -> UnaryMutatorKind {
        UnaryMutatorKind::General
    }
    #[inline(always)]
    fn mutate(&mut self, key: &K, value: &V) -> UnaryResult<Option<V>> {
        (self.func)(key, value)
    }
}

/// Specially optimized mutators on a binary map
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum BinaryMutatorKind {
    /// An idempotent mutator, i.e. if the left and right maps are the same, the result is the same as them
    Idempotent,
    /// A (weakly) nilpotent mutator, i.e. if the left and right maps are the same, the result is the empty map
    Nilpotent,
    /// A mutator which always picks the left tree
    Left,
    /// A mutator which always picks the right tree
    Right,
    /// A mutator which picks either the left or right tree, whichever is convenient
    Ambi,
    /// A general binary mutator
    General,
}

/// A binary value transformer, leaving keys intact
pub trait BinaryTransformer<K, L, R, O> {
    /// Transform a value pair from the input types to the output type
    fn transform_bin(&mut self, key: &K, left: &L, right: &R) -> Option<O>;
}

/// A binary mutator, leaving keys and value *types* intact
pub trait BinaryMutator<K, V>: BinaryTransformer<K, V, V, V> {
    /// The kind of this mutator, if it can be specially optimized
    #[inline(always)]
    fn kind(&mut self) -> BinaryMutatorKind {
        BinaryMutatorKind::General
    }
    /// Mutate a value: should be the same as `transform_bin`, except sometimes returning `UnaryResult::Left/Right`
    /// when the output would be equal to the input
    #[inline(always)]
    fn mutate_bin(&mut self, key: &K, left: &V, right: &V) -> BinaryResult<Option<V>> {
        BinaryResult::New(self.transform_bin(key, left, right))
    }
}

/// A left-agreement mutator: if the left and right maps are equal, the result is the left, otherwise, a deletion is performed
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct LeftAgreeMutator;

impl<K, L, R> BinaryTransformer<K, L, R, L> for LeftAgreeMutator
where
    L: PartialEq<R> + Clone,
{
    fn transform_bin(&mut self, _key: &K, left: &L, right: &R) -> Option<L> {
        if left == right {
            Some(left.clone())
        } else {
            None
        }
    }
}

impl<K, V> BinaryMutator<K, V> for LeftAgreeMutator
where
    V: PartialEq + Clone,
{
    #[inline(always)]
    fn kind(&mut self) -> BinaryMutatorKind {
        BinaryMutatorKind::Idempotent
    }
    #[inline(always)]
    fn mutate_bin(&mut self, _key: &K, left: &V, right: &V) -> BinaryResult<Option<V>> {
        if left == right {
            BinaryResult::Left
        } else {
            BinaryResult::New(None)
        }
    }
}

/// A right-agreement mutator: if the left and right maps are equal, the result is the right, otherwise, a deletion is performed
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct RightAgreeMutator;

impl<K, L, R> BinaryTransformer<K, L, R, R> for RightAgreeMutator
where
    R: PartialEq<L> + Clone,
{
    fn transform_bin(&mut self, _key: &K, left: &L, right: &R) -> Option<R> {
        if right == left {
            Some(right.clone())
        } else {
            None
        }
    }
}

impl<K, V> BinaryMutator<K, V> for RightAgreeMutator
where
    V: PartialEq + Clone,
{
    #[inline(always)]
    fn kind(&mut self) -> BinaryMutatorKind {
        BinaryMutatorKind::Idempotent
    }
    #[inline(always)]
    fn mutate_bin(&mut self, _key: &K, left: &V, right: &V) -> BinaryResult<Option<V>> {
        if right == left {
            BinaryResult::Right
        } else {
            BinaryResult::New(None)
        }
    }
}

impl<K, L, R, O> BinaryTransformer<K, L, R, O> for DeleteMutator {
    #[inline(always)]
    fn transform_bin(&mut self, _key: &K, _left: &L, _right: &R) -> Option<O> {
        None
    }
}

impl<K, V> BinaryMutator<K, V> for DeleteMutator
where
    V: Clone,
{
    #[inline(always)]
    fn kind(&mut self) -> BinaryMutatorKind {
        BinaryMutatorKind::Nilpotent
    }
}

/// A mutator which always takes the left tree
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct LeftMutator;

impl<K, L, R> BinaryTransformer<K, L, R, L> for LeftMutator
where
    L: Clone,
{
    #[inline(always)]
    fn transform_bin(&mut self, _key: &K, left: &L, _right: &R) -> Option<L> {
        Some(left.clone())
    }
}

impl<K, V> BinaryMutator<K, V> for LeftMutator
where
    V: Clone,
{
    #[inline(always)]
    fn kind(&mut self) -> BinaryMutatorKind {
        BinaryMutatorKind::Left
    }
    #[inline(always)]
    fn mutate_bin(&mut self, _key: &K, _left: &V, _right: &V) -> BinaryResult<Option<V>> {
        BinaryResult::Left
    }
}

/// A mutator which always takes the right tree
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct RightMutator;

impl<K, L, R> BinaryTransformer<K, L, R, R> for RightMutator
where
    R: Clone,
{
    fn transform_bin(&mut self, _key: &K, _left: &L, right: &R) -> Option<R> {
        Some(right.clone())
    }
}

impl<K, V> BinaryMutator<K, V> for RightMutator
where
    V: Clone,
{
    #[inline(always)]
    fn kind(&mut self) -> BinaryMutatorKind {
        BinaryMutatorKind::Right
    }
    #[inline(always)]
    fn mutate_bin(&mut self, _key: &K, _left: &V, _right: &V) -> BinaryResult<Option<V>> {
        BinaryResult::Right
    }
}

/// A mutator which picks either the left or the right tree, whichever is convenient.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct AmbiMutator;

impl<K, L, R> BinaryTransformer<K, L, R, L> for AmbiMutator
where
    L: Clone,
{
    fn transform_bin(&mut self, _key: &K, left: &L, _right: &R) -> Option<L> {
        Some(left.clone())
    }
}

impl<K, V> BinaryMutator<K, V> for AmbiMutator
where
    V: Clone,
{
    #[inline(always)]
    fn kind(&mut self) -> BinaryMutatorKind {
        BinaryMutatorKind::Ambi
    }
    #[inline(always)]
    fn mutate_bin(&mut self, _key: &K, _left: &V, _right: &V) -> BinaryResult<Option<V>> {
        BinaryResult::Ambi
    }
}

/// A binary mutation whose parameters are swapped
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, RefCast)]
#[repr(transparent)]
pub struct Swapped<B>(pub B);

impl<B, K, L, R, O> BinaryTransformer<K, L, R, O> for Swapped<B>
where
    B: BinaryTransformer<K, R, L, O>,
{
    fn transform_bin(&mut self, key: &K, left: &L, right: &R) -> Option<O> {
        self.0.transform_bin(key, right, left)
    }
}

impl<B, K, V> BinaryMutator<K, V> for Swapped<B>
where
    B: BinaryMutator<K, V>,
{
    #[inline(always)]
    fn kind(&mut self) -> BinaryMutatorKind {
        self.0.kind()
    }
    #[inline(always)]
    fn mutate_bin(&mut self, key: &K, left: &V, right: &V) -> BinaryResult<Option<V>> {
        self.0.mutate_bin(key, left, right).swap_sides()
    }
}