1//! A type that can be treated as a difference.
2//!
3//! Differential dataflow most commonly tracks the counts associated with records in a multiset, but it
4//! generalizes to tracking any map from the records to an Abelian group. The most common generalization
5//! is when we maintain both a count and another accumulation, for example height. The differential
6//! dataflow collections would then track for each record the total of counts and heights, which allows
7//! us to track something like the average.
89/// A type that can be an additive identity for all `Semigroup` implementations.
10///
11/// This method is extracted from `Semigroup` to avoid ambiguity when used.
12/// It refers exclusively to the type itself, and whether it will act as the identity
13/// in the course of `Semigroup<Self>::plus_equals()`.
14pub trait IsZero {
15/// Returns true if the element is the additive identity.
16 ///
17 /// This is primarily used by differential dataflow to know when it is safe to delete an update.
18 /// When a difference accumulates to zero, the difference has no effect on any accumulation and can
19 /// be removed.
20 ///
21 /// A semigroup is not obligated to have a zero element, and this method could always return
22 /// false in such a setting.
23fn is_zero(&self) -> bool;
24}
2526/// A type with addition and a test for zero.
27///
28/// These traits are currently the minimal requirements for a type to be a "difference" in differential
29/// dataflow. Addition allows differential dataflow to compact multiple updates to the same data, and
30/// the test for zero allows differential dataflow to retire updates that have no effect. There is no
31/// requirement that the test for zero ever return true, and the zero value does not need to inhabit the
32/// type.
33///
34/// There is a light presumption of commutativity here, in that while we will largely perform addition
35/// in order of timestamps, for many types of timestamps there is no total order and consequently no
36/// obvious order to respect. Non-commutative semigroups should be used with care.
37pub trait Semigroup<Rhs: ?Sized = Self> : Clone + IsZero {
38/// The method of `std::ops::AddAssign`, for types that do not implement `AddAssign`.
39fn plus_equals(&mut self, rhs: &Rhs);
40}
4142// Blanket implementation to support GATs of the form `&'a Diff`.
43impl<'a, S, T: Semigroup<S>> Semigroup<&'a S> for T {
44fn plus_equals(&mut self, rhs: &&'a S) {
45self.plus_equals(&**rhs);
46 }
47}
4849/// A semigroup with an explicit zero element.
50pub trait Monoid : Semigroup {
51/// A zero element under the semigroup addition operator.
52fn zero() -> Self;
53}
5455/// A `Monoid` with negation.
56///
57/// This trait extends the requirements of `Semigroup` to include a negation operator.
58/// Several differential dataflow operators require negation in order to retract prior outputs, but
59/// not quite as many as you might imagine.
60pub trait Abelian : Monoid {
61/// The method of `std::ops::Neg`, for types that do not implement `Neg`.
62fn negate(&mut self);
63}
6465/// A replacement for `std::ops::Mul` for types that do not implement it.
66pub trait Multiply<Rhs = Self> {
67/// Output type per the `Mul` trait.
68type Output;
69/// Core method per the `Mul` trait.
70fn multiply(self, rhs: &Rhs) -> Self::Output;
71}
7273/// Implementation for built-in signed integers.
74macro_rules! builtin_implementation {
75 ($t:ty) => {
76impl IsZero for $t {
77#[inline] fn is_zero(&self) -> bool { self == &0 }
78 }
79impl Semigroup for $t {
80#[inline] fn plus_equals(&mut self, rhs: &Self) { *self += rhs; }
81 }
8283impl Monoid for $t {
84#[inline] fn zero() -> Self { 0 }
85 }
8687impl Multiply<Self> for $t {
88type Output = Self;
89fn multiply(self, rhs: &Self) -> Self { self * rhs}
90 }
91 };
92}
9394macro_rules! builtin_abelian_implementation {
95 ($t:ty) => {
96impl Abelian for $t {
97#[inline] fn negate(&mut self) { *self = -*self; }
98 }
99 };
100}
101102builtin_implementation!(i8);
103builtin_implementation!(i16);
104builtin_implementation!(i32);
105builtin_implementation!(i64);
106builtin_implementation!(i128);
107builtin_implementation!(isize);
108builtin_implementation!(u8);
109builtin_implementation!(u16);
110builtin_implementation!(u32);
111builtin_implementation!(u64);
112builtin_implementation!(u128);
113builtin_implementation!(usize);
114115builtin_abelian_implementation!(i8);
116builtin_abelian_implementation!(i16);
117builtin_abelian_implementation!(i32);
118builtin_abelian_implementation!(i64);
119builtin_abelian_implementation!(i128);
120builtin_abelian_implementation!(isize);
121122/// Implementations for wrapping signed integers, which have a different zero.
123macro_rules! wrapping_implementation {
124 ($t:ty) => {
125impl IsZero for $t {
126#[inline] fn is_zero(&self) -> bool { self == &std::num::Wrapping(0) }
127 }
128impl Semigroup for $t {
129#[inline] fn plus_equals(&mut self, rhs: &Self) { *self += rhs; }
130 }
131132impl Monoid for $t {
133#[inline] fn zero() -> Self { std::num::Wrapping(0) }
134 }
135136impl Abelian for $t {
137#[inline] fn negate(&mut self) { *self = -*self; }
138 }
139140impl Multiply<Self> for $t {
141type Output = Self;
142fn multiply(self, rhs: &Self) -> Self { self * rhs}
143 }
144 };
145}
146147wrapping_implementation!(std::num::Wrapping<i8>);
148wrapping_implementation!(std::num::Wrapping<i16>);
149wrapping_implementation!(std::num::Wrapping<i32>);
150wrapping_implementation!(std::num::Wrapping<i64>);
151wrapping_implementation!(std::num::Wrapping<i128>);
152wrapping_implementation!(std::num::Wrapping<isize>);
153154155pub use self::present::Present;
156mod present {
157use serde::{Deserialize, Serialize};
158159/// A zero-sized difference that indicates the presence of a record.
160 ///
161 /// This difference type has no negation, and present records cannot be retracted.
162 /// Addition and multiplication maintain presence, and zero does not inhabit the type.
163 ///
164 /// The primary feature of this type is that it has zero size, which reduces the overhead
165 /// of differential dataflow's representations for settings where collections either do
166 /// not change, or for which records are only added (for example, derived facts in Datalog).
167#[derive(Copy, Ord, PartialOrd, Eq, PartialEq, Debug, Clone, Serialize, Deserialize, Hash)]
168pub struct Present;
169170impl<T: Clone> super::Multiply<T> for Present {
171type Output = T;
172fn multiply(self, rhs: &T) -> T {
173 rhs.clone()
174 }
175 }
176177impl super::IsZero for Present {
178fn is_zero(&self) -> bool { false }
179 }
180181impl super::Semigroup for Present {
182fn plus_equals(&mut self, _rhs: &Self) { }
183 }
184}
185186// Pair implementations.
187mod tuples {
188189use super::{IsZero, Semigroup, Monoid, Abelian, Multiply};
190191/// Implementations for tuples. The two arguments must have the same length.
192macro_rules! tuple_implementation {
193 ( ($($name:ident)*), ($($name2:ident)*) ) => (
194195impl<$($name: IsZero),*> IsZero for ($($name,)*) {
196#[allow(unused_mut)]
197 #[allow(non_snake_case)]
198 #[inline] fn is_zero(&self) -> bool {
199let mut zero = true;
200let ($(ref $name,)*) = *self;
201 $( zero &= $name.is_zero(); )*
202 zero
203 }
204 }
205206impl<$($name: Semigroup),*> Semigroup for ($($name,)*) {
207#[allow(non_snake_case)]
208 #[inline] fn plus_equals(&mut self, rhs: &Self) {
209let ($(ref mut $name,)*) = *self;
210let ($(ref $name2,)*) = *rhs;
211 $($name.plus_equals($name2);)*
212 }
213 }
214215impl<$($name: Monoid),*> Monoid for ($($name,)*) {
216#[allow(non_snake_case)]
217 #[inline] fn zero() -> Self {
218 ( $($name::zero(), )* )
219 }
220 }
221222impl<$($name: Abelian),*> Abelian for ($($name,)*) {
223#[allow(non_snake_case)]
224 #[inline] fn negate(&mut self) {
225let ($(ref mut $name,)*) = self;
226 $($name.negate();)*
227 }
228 }
229230impl<T, $($name: Multiply<T>),*> Multiply<T> for ($($name,)*) {
231type Output = ($(<$name as Multiply<T>>::Output,)*);
232#[allow(unused_variables)]
233 #[allow(non_snake_case)]
234 #[inline] fn multiply(self, rhs: &T) -> Self::Output {
235let ($($name,)*) = self;
236 ( $($name.multiply(rhs), )* )
237 }
238 }
239 )
240 }
241242tuple_implementation!((), ());
243tuple_implementation!((A1), (A2));
244tuple_implementation!((A1 B1), (A2 B2));
245tuple_implementation!((A1 B1 C1), (A2 B2 C2));
246tuple_implementation!((A1 B1 C1 D1), (A2 B2 C2 D2));
247}
248249// Vector implementations
250mod vector {
251252use super::{IsZero, Semigroup, Monoid, Abelian, Multiply};
253254impl<R: IsZero> IsZero for Vec<R> {
255fn is_zero(&self) -> bool {
256self.iter().all(|x| x.is_zero())
257 }
258 }
259260impl<R: Semigroup> Semigroup for Vec<R> {
261fn plus_equals(&mut self, rhs: &Self) {
262self.plus_equals(&rhs[..])
263 }
264 }
265266impl<R: Semigroup> Semigroup<[R]> for Vec<R> {
267fn plus_equals(&mut self, rhs: &[R]) {
268// Apply all updates to existing elements
269for (index, update) in rhs.iter().enumerate().take(self.len()) {
270self[index].plus_equals(update);
271 }
272273// Clone leftover elements from `rhs`
274while self.len() < rhs.len() {
275let element = &rhs[self.len()];
276self.push(element.clone());
277 }
278 }
279 }
280281#[cfg(test)]
282mod tests {
283use crate::difference::Semigroup;
284285#[test]
286fn test_semigroup_vec() {
287let mut a = vec![1,2,3];
288 a.plus_equals([1,1,1,1].as_slice());
289assert_eq!(vec![2,3,4,1], a);
290 }
291 }
292293impl<R: Monoid> Monoid for Vec<R> {
294fn zero() -> Self {
295Self::new()
296 }
297 }
298299impl<R: Abelian> Abelian for Vec<R> {
300fn negate(&mut self) {
301for update in self.iter_mut() {
302 update.negate();
303 }
304 }
305 }
306307impl<T, R: Multiply<T>> Multiply<T> for Vec<R> {
308type Output = Vec<<R as Multiply<T>>::Output>;
309fn multiply(self, rhs: &T) -> Self::Output {
310self.into_iter()
311 .map(|x| x.multiply(rhs))
312 .collect()
313 }
314 }
315}