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
use crate::binary_merge::MergeOperation;
use crate::merge_state::VecMergeState;
use crate::vec_map::VecMap;
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::ops::Index;

#[derive(Hash, Debug, Clone, Eq, PartialEq, Default)]
pub struct TotalArrayMap<K, V>(VecMap<K, V>, V);

impl<K, V: Eq> TotalArrayMap<K, V> {
    pub fn new(map: VecMap<K, V>, default: V) -> Self {
        let mut entries = map;
        // ensure canonical representation!
        entries.retain(|(_, v)| *v != default);
        Self(entries, default)
    }
}

impl<K, V> TotalArrayMap<K, V> {
    pub fn constant(value: V) -> Self {
        Self(VecMap::default(), value)
    }

    pub fn as_slice(&self) -> &[(K, V)] {
        self.0.as_slice()
    }
}

struct CombineOp<'a, F, V> {
    f: F,
    a_default: &'a V,
    b_default: &'a V,
    r_default: &'a V,
}

/// a fast combine op is an op where we know that the default for both a and b is the neutral element of the operation
struct FastCombineOp<'a, F, V> {
    f: F,
    r_default: &'a V,
}

type PairMergeState<'a, K, V> = VecMergeState<'a, (K, V), (K, V), (K, V)>;

impl<'a, K: Ord + Clone, V: Eq, F: Fn(&V, &V) -> V>
    MergeOperation<(K, V), (K, V), PairMergeState<'a, K, V>> for CombineOp<'a, F, V>
{
    fn cmp(&self, a: &(K, V), b: &(K, V)) -> Ordering {
        a.0.cmp(&b.0)
    }
    fn from_a(&self, m: &mut PairMergeState<'a, K, V>, n: usize) {
        for _ in 0..n {
            if let Some((k, a)) = m.a.next() {
                let result = (self.f)(a, self.b_default);
                if result != *self.r_default {
                    m.r.push((k.clone(), result))
                }
            }
        }
    }
    fn from_b(&self, m: &mut PairMergeState<'a, K, V>, n: usize) {
        for _ in 0..n {
            if let Some((k, b)) = m.b.next() {
                let result = (self.f)(self.a_default, b);
                if result != *self.r_default {
                    m.r.push((k.clone(), result))
                }
            }
        }
    }
    fn collision(&self, m: &mut PairMergeState<'a, K, V>) {
        if let Some((k, a)) = m.a.next() {
            if let Some((_, b)) = m.b.next() {
                let result = (self.f)(a, b);
                if result != *self.r_default {
                    m.r.push((k.clone(), result))
                }
            }
        }
    }
}

impl<'a, K: Ord + Clone, V: Eq + Clone, F: Fn(&V, &V) -> V>
    MergeOperation<(K, V), (K, V), PairMergeState<'a, K, V>> for FastCombineOp<'a, F, V>
{
    fn cmp(&self, a: &(K, V), b: &(K, V)) -> Ordering {
        a.0.cmp(&b.0)
    }
    fn from_a(&self, m: &mut PairMergeState<'a, K, V>, n: usize) {
        for _ in 0..n {
            if let Some((k, a)) = m.a.next() {
                m.r.push((k.clone(), a.clone()));
            }
        }
    }
    fn from_b(&self, m: &mut PairMergeState<'a, K, V>, n: usize) {
        for _ in 0..n {
            if let Some((k, b)) = m.b.next() {
                m.r.push((k.clone(), b.clone()));
            }
        }
    }
    fn collision(&self, m: &mut PairMergeState<'a, K, V>) {
        if let Some((k, a)) = m.a.next() {
            if let Some((_, b)) = m.b.next() {
                let result = (self.f)(a, b);
                if result != *self.r_default {
                    m.r.push((k.clone(), result))
                }
            }
        }
    }
}

impl<K: Ord + Clone, V: Eq> TotalArrayMap<K, V> {
    pub fn combine<F: Fn(&V, &V) -> V>(&self, that: &Self, f: F) -> Self {
        let r_default = f(&self.1, &that.1);
        let op = CombineOp {
            f,
            a_default: &self.1,
            b_default: &that.1,
            r_default: &r_default,
        };
        let r = VecMergeState::merge(self.as_slice(), that.as_slice(), op);
        Self(VecMap::from_sorted_vec(r), r_default)
    }
}

impl<K: Ord + Clone, V: Ord + Clone> TotalArrayMap<K, V> {
    pub fn supremum(&self, that: &Self) -> Self {
        self.combine(that, |a, b| if a > b { a.clone() } else { b.clone() })
    }
    pub fn infimum(&self, that: &Self) -> Self {
        self.combine(that, |a, b| if a < b { a.clone() } else { b.clone() })
    }
}

/// not sure if I can even use fast_combine in rust
#[allow(dead_code)]
impl<K: Ord + Clone, V: Eq + Clone> TotalArrayMap<K, V> {
    pub(crate) fn fast_combine<F: Fn(&V, &V) -> V>(
        &self,
        that: &TotalArrayMap<K, V>,
        f: F,
    ) -> TotalArrayMap<K, V> {
        let r_default = f(&self.1, &that.1);
        let op = FastCombineOp {
            f,
            r_default: &r_default,
        };
        let r = VecMergeState::merge(self.as_slice(), that.as_slice(), op);
        Self(VecMap::from_sorted_vec(r), r_default)
    }
}

impl<K: Clone, V: Eq> TotalArrayMap<K, V> {
    pub fn map_values<W: Eq, F: Fn(&V) -> W>(&self, f: F) -> TotalArrayMap<K, W> {
        let default = f(&self.1);
        let elements: Vec<(K, W)> = self
            .0
            .iter()
            .filter_map(|entry| {
                let w = f(&entry.1);
                if w != default {
                    Some((entry.0.clone(), w))
                } else {
                    None
                }
            })
            .collect();
        TotalArrayMap(VecMap::from_sorted_vec(elements), default)
    }
}

impl<K: Ord, Q: ?Sized, V> Index<&Q> for TotalArrayMap<K, V>
where
    K: Borrow<Q>,
    Q: Ord,
{
    type Output = V;

    fn index(&self, key: &Q) -> &V {
        self.0.get(key).unwrap_or(&self.1)
    }
}

mod alga_instances {
    use super::*;
    use alga::general::*;

    impl<K: Ord + Clone, V: AbstractMagma<Additive> + Eq> AbstractMagma<Additive>
        for TotalArrayMap<K, V>
    {
        fn operate(&self, that: &Self) -> Self {
            self.combine(that, V::operate)
        }
    }

    impl<K, V: Identity<Additive>> Identity<Additive> for TotalArrayMap<K, V> {
        fn identity() -> Self {
            TotalArrayMap::constant(V::identity())
        }
    }

    impl<K: Clone, V: TwoSidedInverse<Additive> + Eq> TwoSidedInverse<Additive>
        for TotalArrayMap<K, V>
    {
        fn two_sided_inverse(&self) -> Self {
            self.map_values(V::two_sided_inverse)
        }
    }

    #[rustfmt::skip] impl<K: Ord + Clone, V: AbstractSemigroup<Additive> + Eq> AbstractSemigroup<Additive> for TotalArrayMap<K, V> {}
    #[rustfmt::skip] impl<K: Ord + Clone, V: AbstractMonoid<Additive> + Eq> AbstractMonoid<Additive> for TotalArrayMap<K, V> {}
    #[rustfmt::skip] impl<K: Ord + Clone, V: AbstractQuasigroup<Additive> + Eq> AbstractQuasigroup<Additive> for TotalArrayMap<K, V> {}
    #[rustfmt::skip] impl<K: Ord + Clone, V: AbstractLoop<Additive> + Eq> AbstractLoop<Additive> for TotalArrayMap<K, V> {}
    #[rustfmt::skip] impl<K: Ord + Clone, V: AbstractGroup<Additive> + Eq> AbstractGroup<Additive> for TotalArrayMap<K, V> {}
    #[rustfmt::skip] impl<K: Ord + Clone, V: AbstractGroupAbelian<Additive> + Eq> AbstractGroupAbelian<Additive> for TotalArrayMap<K, V> {}

    impl<K: Ord + Clone, V: AbstractMagma<Multiplicative> + Eq> AbstractMagma<Multiplicative>
        for TotalArrayMap<K, V>
    {
        fn operate(&self, that: &Self) -> Self {
            self.combine(that, V::operate)
        }
    }

    impl<K, V: Identity<Multiplicative>> Identity<Multiplicative> for TotalArrayMap<K, V> {
        fn identity() -> Self {
            TotalArrayMap::constant(V::identity())
        }
    }

    impl<K: Clone, V: TwoSidedInverse<Multiplicative> + Eq> TwoSidedInverse<Multiplicative>
        for TotalArrayMap<K, V>
    {
        fn two_sided_inverse(&self) -> Self {
            self.map_values(V::two_sided_inverse)
        }
    }

    #[rustfmt::skip] impl<K: Ord + Clone, V: AbstractSemigroup<Multiplicative> + Eq> AbstractSemigroup<Multiplicative> for TotalArrayMap<K, V> {}
    #[rustfmt::skip] impl<K: Ord + Clone, V: AbstractMonoid<Multiplicative> + Eq> AbstractMonoid<Multiplicative> for TotalArrayMap<K, V> {}
    #[rustfmt::skip] impl<K: Ord + Clone, V: AbstractQuasigroup<Multiplicative> + Eq> AbstractQuasigroup<Multiplicative> for TotalArrayMap<K, V> {}
    #[rustfmt::skip] impl<K: Ord + Clone, V: AbstractLoop<Multiplicative> + Eq> AbstractLoop<Multiplicative> for TotalArrayMap<K, V> {}
    #[rustfmt::skip] impl<K: Ord + Clone, V: AbstractGroup<Multiplicative> + Eq> AbstractGroup<Multiplicative> for TotalArrayMap<K, V> {}
}

// we don't implement IndexMut since that would allow changing a value to the default and all sorts of other nasty things!
#[cfg(test)]
mod tests {
    use super::*;
    use alga::general::*;
    use quickcheck::*;
    use std::collections::{BTreeMap, BTreeSet};

    type Ref = (BTreeMap<i32, i32>, i32);
    type Test = TotalArrayMap<i32, i32>;

    fn from_ref(r: Ref) -> Test {
        let (elements, default) = r;
        Test::new(elements.clone().into(), default)
    }

    impl<K: Arbitrary + Ord, V: Arbitrary + Eq> Arbitrary for TotalArrayMap<K, V> {
        fn arbitrary<G: Gen>(g: &mut G) -> Self {
            TotalArrayMap::new(Arbitrary::arbitrary(g), Arbitrary::arbitrary(g))
        }
    }

    fn combine_reference<F: Fn(i32, i32) -> i32>(a: &Ref, b: &Ref, f: F) -> Ref {
        let (a, ad) = a.clone();
        let (b, bd) = b.clone();
        let rd = f(ad, bd);
        let mut r: BTreeMap<i32, i32> = BTreeMap::default();
        let mut keys: BTreeSet<i32> = BTreeSet::new();
        keys.extend(a.keys());
        keys.extend(b.keys());
        for key in keys {
            let value = f(*a.get(&key).unwrap_or(&ad), *b.get(&key).unwrap_or(&bd));
            r.insert(key, value);
        }
        (r, rd)
    }

    quickcheck! {

        fn index(a: Ref, key: i32) -> bool {
            let x = from_ref(a.clone());
            let (elements, default) = a;
            let expected = elements.get(&key).cloned().unwrap_or(default);
            let actual = x[&key];
            expected == actual
        }

        fn supremum(a: Ref, b: Ref) -> bool {
            let expected = from_ref(combine_reference(&a, &b, |a, b| std::cmp::max(a, b)));
            let a1 = from_ref(a.clone());
            let b1 = from_ref(b.clone());
            let actual = a1.supremum(&b1);
            expected == actual
        }

        fn infimum(a: Ref, b: Ref) -> bool {
            let expected = from_ref(combine_reference(&a, &b, |a, b| std::cmp::min(a, b)));
            let a1 = from_ref(a.clone());
            let b1 = from_ref(b.clone());
            let actual = a1.infimum(&b1);
            expected == actual
        }

        fn prop_is_associative_additive(args: (Test, Test, Test)) -> bool {
            AbstractSemigroup::<Additive>::prop_is_associative(args)
        }

        fn prop_operating_identity_element_is_noop_additive(args: (Test, )) -> bool {
            AbstractMonoid::<Additive>::prop_operating_identity_element_is_noop(args)
        }

        fn prop_is_commutative(args: (Test, Test)) -> bool {
            AbstractGroupAbelian::<Additive>::prop_is_commutative(args)
        }
    }
}