dbsp/algebra/
mod.rs

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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
//! This module contains declarations of abstract algebraic concepts:
//! monoids, groups, rings, etc.

#[macro_use]
mod checked_int;
mod floats;
mod lattice;
mod order;
mod present;

pub mod zset;

pub use checked_int::CheckedInt;
pub use floats::{F32, F64};
pub use lattice::Lattice;
pub use order::{PartialOrder, TotalOrder};
pub use present::Present;
pub use zset::{
    DynZWeight, IndexedZSet, IndexedZSetReader, OrdIndexedZSet, OrdIndexedZSetFactories, OrdZSet,
    OrdZSetFactories, VecIndexedZSet, VecIndexedZSetFactories, VecZSet, VecZSetFactories, ZBatch,
    ZBatchReader, ZCursor, ZSet, ZSetReader, ZTrace, ZWeight,
};

use num::PrimInt;
use rust_decimal::{prelude::One, prelude::Zero, Decimal};
use size_of::SizeOf;
use std::{
    fmt::{Debug, Display},
    marker::PhantomData,
    num::Wrapping,
    ops::{Add, AddAssign, Mul, Neg},
    rc::Rc,
};

/// Trait for types where the minimum value is known
pub trait MinValue {
    fn min_value() -> Self;
}

/// Trait for types where the maximum value is known
pub trait MaxValue {
    fn max_value() -> Self;
}

/// Trait for integer types returning the first
/// value representable in this type which is
/// too large for the previous narrower type
pub trait FirstLargeValue {
    fn large() -> Self;
}

/// Trait for primitive integers that are unsigned
pub trait UnsignedPrimInt: PrimInt + FirstLargeValue + HasZero + Debug + Display {}

impl FirstLargeValue for u8 {
    fn large() -> Self {
        // There is no narrower unsigned type
        0x1
    }
}

impl FirstLargeValue for u16 {
    fn large() -> Self {
        0x100
    }
}

impl FirstLargeValue for u32 {
    fn large() -> Self {
        0x10000
    }
}

impl FirstLargeValue for u64 {
    fn large() -> Self {
        0x1_0000_0000
    }
}

impl FirstLargeValue for u128 {
    fn large() -> Self {
        0x1_0000_0000_0000_0000
    }
}

impl UnsignedPrimInt for u8 {}
impl UnsignedPrimInt for u16 {}
impl UnsignedPrimInt for u32 {}
impl UnsignedPrimInt for u64 {}
impl UnsignedPrimInt for u128 {}

/// Trait for primitive integers that are signed
pub trait SignedPrimInt:
    PrimInt + Neg<Output = Self> + HasZero + HasOne + Ord + Debug + Display
{
}

// For all primitive signed integers we also implement
// MinValue and MaxValue
macro_rules! make_signed {
    ($type: ty) => {
        impl MinValue for $type {
            fn min_value() -> Self {
                <$type>::MIN
            }
        }

        impl MaxValue for $type {
            fn max_value() -> Self {
                <$type>::MAX
            }
        }

        impl SignedPrimInt for $type {}
    };
}

make_signed!(i8);
make_signed!(i16);
make_signed!(i32);
make_signed!(i64);
make_signed!(i128);

/// A trait for types that have a zero value.
///
/// This is similar to the standard Zero trait, but that
/// trait depends on Add and HasZero doesn't.
pub trait HasZero {
    fn is_zero(&self) -> bool;

    fn zero() -> Self;
}

/// Implement `HasZero` for types that already implement `Zero`.
macro_rules! impl_has_zero {
    ($($type:ty),* $(,)?) => {
        $(
            impl $crate::algebra::HasZero for $type {
                #[inline]
                fn is_zero(&self) -> bool {
                    *self == 0
                }

                #[inline]
                fn zero() -> Self {
                    0
                }
            }
        )*
    };
}

impl_has_zero! {
    u8,
    i8,
    u16,
    i16,
    u32,
    i32,
    u64,
    i64,
    u128,
    i128,
    usize,
    isize,
}

impl HasZero for Decimal {
    #[inline]
    fn is_zero(&self) -> bool {
        Zero::is_zero(self)
    }

    #[inline]
    fn zero() -> Self {
        Zero::zero()
    }
}

impl<T> HasZero for Option<T> {
    #[inline]
    fn is_zero(&self) -> bool {
        self.is_none()
    }

    #[inline]
    fn zero() -> Self {
        None
    }
}

// TODO: Implement for `std::num::Saturating` once stable
impl<T> HasZero for Wrapping<T>
where
    T: HasZero,
{
    #[inline]
    fn is_zero(&self) -> bool {
        self.0.is_zero()
    }

    #[inline]
    fn zero() -> Self {
        Self(T::zero())
    }
}

/// A trait for types that have a one value.
/// This is similar to the standard One trait, but that
/// trait depends on Mul and HasOne doesn't.
pub trait HasOne {
    fn one() -> Self;
}

/// Implement `HasOne` for types that already implement `One`.
macro_rules! impl_has_one {
    ($($type:ty),* $(,)?) => {
        $(
            impl $crate::algebra::HasOne for $type {
                #[inline]
                fn one() -> Self {
                    1
                }
            }
        )*
    };
}

impl HasOne for Decimal {
    #[inline]
    fn one() -> Self {
        One::one()
    }
}

impl_has_one! {
    u8,
    i8,
    u16,
    i16,
    u32,
    i32,
    u64,
    i64,
    u128,
    i128,
    usize,
    isize,
}

impl<T> HasOne for Rc<T>
where
    T: HasOne,
{
    #[inline]
    fn one() -> Self {
        Rc::new(<T as HasOne>::one())
    }
}

/// Like the Add trait, but with arguments by reference.
pub trait AddByRef<Rhs = Self> {
    fn add_by_ref(&self, other: &Rhs) -> Self;
}

/// Implementation of AddByRef for types that have an Add.
impl<T> AddByRef for T
where
    for<'a> &'a T: Add<Output = T>,
{
    #[inline]
    fn add_by_ref(&self, other: &Self) -> Self {
        self.add(other)
    }
}

/// Like the Neg trait, but with arguments by reference.
pub trait NegByRef {
    fn neg_by_ref(&self) -> Self;
}

/// Implementation of NegByRef for types that have a Neg.
impl<T> NegByRef for T
where
    for<'a> &'a T: Neg<Output = T>,
{
    #[inline]
    fn neg_by_ref(&self) -> Self {
        self.neg()
    }
}

/// Like the AddAsssign trait, but with arguments by reference
pub trait AddAssignByRef<Rhs = Self> {
    fn add_assign_by_ref(&mut self, other: &Rhs);
}

/// Implemenation of AddAssignByRef for types that already have `AddAssign<&T>`.
impl<T> AddAssignByRef for T
where
    for<'a> T: AddAssign<&'a T>,
{
    #[inline]
    fn add_assign_by_ref(&mut self, other: &Self) {
        self.add_assign(other)
    }
}

/// Like the Mul trait, but with arguments by reference
pub trait MulByRef<Rhs = Self> {
    type Output;

    fn mul_by_ref(&self, other: &Rhs) -> Self::Output;
}

/// Implementation of MulByRef for types that already have Mul.
impl<T> MulByRef<T> for T
where
    for<'a> &'a T: Mul<Output = Self>,
{
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, other: &Self) -> Self::Output {
        self.mul(other)
    }
}

/// A type with an associative addition.
/// We trust the implementation to have an associative addition.
/// (this cannot be checked statically).
// TODO: Add a `for<'a> Add<&'a Self, Output = Self>` bound for adding an owned
// and a referenced value together
pub trait SemigroupValue: Clone + Eq + SizeOf + AddByRef + AddAssignByRef + 'static {}

impl<T> SemigroupValue for T where T: Clone + Eq + SizeOf + AddByRef + AddAssignByRef + 'static {}

/// A type with an associative addition and a zero.
pub trait MonoidValue: SemigroupValue + HasZero {}

/// Default implementation for all types that have an addition and a zero.
impl<T> MonoidValue for T where T: SemigroupValue + HasZero {}

/// A Group is a Monoid with a with negation operation.
/// We expect all our groups to be commutative.
pub trait GroupValue: MonoidValue + Neg<Output = Self> + NegByRef {}

/// Default implementation of GroupValue for all types that have the required
/// traits.
impl<T> GroupValue for T where T: MonoidValue + Neg<Output = Self> + NegByRef {}

/// A Group with a multiplication operation is a Ring.
pub trait RingValue: GroupValue + Mul<Output = Self> + MulByRef<Output = Self> + HasOne {}

/// Default implementation of RingValue for all types that have the required
/// traits.
impl<T> RingValue for T where T: GroupValue + Mul<Output = Self> + MulByRef<Output = Self> + HasOne {}

/// A ring where elements can be compared with zero
pub trait ZRingValue: RingValue {
    /// True if value is greater or equal to zero.
    fn ge0(&self) -> bool;

    /// True if value is less than or equal to zero.
    fn le0(&self) -> bool;
}

/// Default implementation of `ZRingValue` for all types that have the required
/// traits.
impl<T> ZRingValue for T
where
    T: RingValue + Ord,
{
    #[inline]
    fn ge0(&self) -> bool {
        *self >= Self::zero()
    }

    #[inline]
    fn le0(&self) -> bool {
        *self <= Self::zero()
    }
}

/// `MulByRef<isize>`

impl MulByRef<isize> for i8 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &isize) -> Self::Output {
        (*self as isize * w) as Self
    }
}

impl MulByRef<isize> for i16 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &isize) -> Self::Output {
        (*self as isize * w) as Self
    }
}

impl MulByRef<isize> for i32 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &isize) -> Self::Output {
        (*self as isize * w) as Self
    }
}

impl MulByRef<isize> for i64 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &isize) -> Self::Output {
        (*self as isize * w) as Self
    }
}

impl MulByRef<isize> for f32 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &isize) -> Self::Output {
        *self * ((*w) as f32)
    }
}

impl MulByRef<isize> for f64 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &isize) -> Self::Output {
        *self * ((*w) as f64)
    }
}

impl MulByRef<isize> for F32 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &isize) -> Self::Output {
        *self * ((*w) as f32)
    }
}

impl MulByRef<isize> for F64 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &isize) -> Self::Output {
        *self * ((*w) as f64)
    }
}

impl MulByRef<isize> for Decimal {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &isize) -> Self::Output {
        *self * Decimal::from(*w)
    }
}

/////////// `MulByRef<i64>`

impl MulByRef<i64> for i8 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i64) -> Self::Output {
        (*self as i64 * w) as Self
    }
}

impl MulByRef<i64> for i16 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i64) -> Self::Output {
        (*self as i64 * w) as Self
    }
}

impl MulByRef<i64> for i32 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i64) -> Self::Output {
        (*self as i64 * w) as Self
    }
}

impl MulByRef<i64> for isize {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i64) -> Self::Output {
        (*self as i64 * w) as Self
    }
}

impl MulByRef<i64> for f32 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i64) -> Self::Output {
        *self * ((*w) as f32)
    }
}

impl MulByRef<i64> for f64 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i64) -> Self::Output {
        *self * ((*w) as f64)
    }
}

impl MulByRef<i64> for F32 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i64) -> Self::Output {
        *self * ((*w) as f32)
    }
}

impl MulByRef<i64> for F64 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i64) -> Self::Output {
        *self * ((*w) as f64)
    }
}

impl MulByRef<i64> for Decimal {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i64) -> Self::Output {
        *self * Decimal::from(*w)
    }
}

/////////// `MulByRef<i32>`

impl MulByRef<i32> for i8 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i32) -> Self::Output {
        (*self as i32 * w) as Self
    }
}

impl MulByRef<i32> for i16 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i32) -> Self::Output {
        (*self as i32 * w) as Self
    }
}

impl MulByRef<i32> for i64 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i32) -> Self::Output {
        (*self as i32 * w) as Self
    }
}

impl MulByRef<i32> for isize {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i32) -> Self::Output {
        (*self as i32 * w) as Self
    }
}

impl MulByRef<i32> for f32 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i32) -> Self::Output {
        *self * ((*w) as f32)
    }
}

impl MulByRef<i32> for f64 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i32) -> Self::Output {
        *self * ((*w) as f64)
    }
}

impl MulByRef<i32> for F32 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i32) -> Self::Output {
        *self * ((*w) as f32)
    }
}

impl MulByRef<i32> for F64 {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i32) -> Self::Output {
        *self * ((*w) as f64)
    }
}

impl MulByRef<i32> for Decimal {
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, w: &i32) -> Self::Output {
        *self * Decimal::from(*w)
    }
}

/////////// generic implementation for Option<t>

trait OptionWeightType {}
impl OptionWeightType for isize {}
impl OptionWeightType for i8 {}
impl OptionWeightType for i16 {}
impl OptionWeightType for i32 {}
impl OptionWeightType for i64 {}
impl OptionWeightType for f32 {}
impl OptionWeightType for f64 {}
impl OptionWeightType for F32 {}
impl OptionWeightType for F64 {}
impl OptionWeightType for Decimal {}
impl OptionWeightType for Present {}

impl<T, S> MulByRef<S> for Option<T>
where
    T: MulByRef<S, Output = T>,
    S: OptionWeightType,
{
    type Output = Self;

    #[inline]
    fn mul_by_ref(&self, rhs: &S) -> Self::Output {
        self.as_ref().map(|lhs| lhs.mul_by_ref(rhs))
    }
}

/// Semigroup over values of type `V`.
///
/// This trait defines an associative binary operation
/// over values of type `V`.  Unlike [`SemigroupValue`],
/// which can only be implemented once per type, it allows
/// creating multiple semigroup structures over the same type.
/// For example, integers form semigroups with addition,
/// multiplication, min, and max operations, among others.
// TODO: add optimized methods that take arguments by value,
// and that combine more than two elements.
pub trait Semigroup<V> {
    /// Apply the semigroup operation to `left` and `right`.
    fn combine(left: &V, right: &V) -> V;

    /// Apply the semigroup operation to values of type `Option<V>`.
    ///
    /// This method defines a monoid over values of type `Option<V>` with
    /// `None` as the neutral element.  It returns:
    /// * `None`, if both arguments are `None`,
    /// * `left` (`right`), if `right` (`left`) is `None`,
    /// * `combine(left.unwrap(), right.unwrap())` otherwise.
    fn combine_opt(left: &Option<V>, right: &Option<V>) -> Option<V>
    where
        V: Clone,
    {
        if let Some(left) = left {
            if let Some(right) = right {
                Some(Self::combine(left, right))
            } else {
                Some(left.clone())
            }
        } else {
            right.clone()
        }
    }
}

/// Trait [`Semigroup`] implementation for types that
/// implement [`SemigroupValue`].
///
/// Implements `Semigroup<V>` using `V`'s natural plus
/// operation.
#[derive(Clone)]
pub struct DefaultSemigroup<V>(PhantomData<V>);

impl<V> Semigroup<V> for DefaultSemigroup<V>
where
    V: SemigroupValue,
{
    fn combine(left: &V, right: &V) -> V {
        left.add_by_ref(right)
    }
}

/// [`Semigroup`] implementation that panics with "not implemented"
/// message.
// TODO: this is a temporary thing that can be used with aggregation operators,
// which currently don't invoke the `Semigroup` trait (but this will change
// in the future).
#[derive(Clone)]
pub struct UnimplementedSemigroup<V>(PhantomData<V>);

impl<V> Semigroup<V> for UnimplementedSemigroup<V> {
    fn combine(_left: &V, _right: &V) -> V {
        unimplemented!()
    }
}

#[cfg(test)]
mod integer_ring_tests {
    use super::*;

    #[test]
    fn fixed_integer_tests() {
        assert_eq!(0, <i64 as HasZero>::zero());
        assert_eq!(1, <i64 as HasOne>::one());
        let two = <i64 as HasOne>::one().add_by_ref(&<i64 as HasOne>::one());
        assert_eq!(2, two);
        assert_eq!(-2, two.neg_by_ref());
        assert_eq!(-4, two.mul_by_ref(&two.neg_by_ref()));
    }

    #[test]
    fn fixed_isize_tests() {
        assert_eq!(0, <isize as HasZero>::zero());
        assert_eq!(1, <isize as HasOne>::one());
        let two = <isize as HasOne>::one().add_by_ref(&<isize as HasOne>::one());
        assert_eq!(2, two);
        assert_eq!(-2, two.neg_by_ref());
        assert_eq!(-4, two.mul_by_ref(&two.neg_by_ref()));
    }

    #[test]
    fn fixed_i64_tests() {
        assert_eq!(0, <i64 as HasZero>::zero());
        assert_eq!(1, <i64 as HasOne>::one());
        let two = <i64 as HasOne>::one().add_by_ref(&<i64 as HasOne>::one());
        assert_eq!(2, two);
        assert_eq!(-2, two.neg_by_ref());
        assert_eq!(-4, two.mul_by_ref(&two.neg_by_ref()));
    }
}