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
//! Module defining the Window and its operations

use core::fmt::Debug;
use core::marker::PhantomData;

use crate::time::{TimeUnit, UnitNumber};
use crate::window::window_types::WindowType;

pub mod window_types {
    //!  Module for the `WindowType` trait

    use core::fmt::Debug;

    use crate::seal::Seal;
    use crate::window::{Demand, Overlap, Supply};

    /// Marker Trait for Window Types
    pub trait WindowType: Seal + Debug {}

    impl WindowType for Supply {}

    impl WindowType for Demand {}

    impl<P: WindowType, Q: WindowType> WindowType for Overlap<P, Q> {}
}

mod window_end;

pub use window_end::WindowEnd;

/// Type representing a Window based on the papers Definition 1.
///
/// With an extra Type Parameter to indicate the Window type
// Not Copy to prevent accidental errors due to implicit copy
#[derive(Debug, Hash, Eq)]
pub struct Window<T> {
    /// The Start point of the Window
    pub start: TimeUnit,
    /// The End Point of the Window
    pub end: WindowEnd,
    /// The Kind of the Window
    window_type: PhantomData<T>,
}

impl<W> PartialEq for Window<W> {
    fn eq(&self, other: &Self) -> bool {
        self.start == other.start && self.end == other.end
    }
}

impl<T> Clone for Window<T> {
    fn clone(&self) -> Self {
        Window {
            start: self.start,
            end: self.end,
            window_type: PhantomData,
        }
    }
}

impl<T> Window<T> {
    /// Create a new Window
    #[must_use]
    pub fn new<I: Into<TimeUnit>, E: Into<WindowEnd>>(start: I, end: E) -> Self {
        Window {
            start: start.into(),
            end: end.into(),
            window_type: PhantomData,
        }
    }

    /// Create a new empty Window
    #[must_use]
    pub const fn empty() -> Self {
        Window {
            start: TimeUnit::ZERO,
            end: WindowEnd::Finite(TimeUnit::ZERO),
            window_type: PhantomData,
        }
    }

    /// Calculate the window length as defined in Definition 1. of the paper
    #[must_use]
    pub fn length(&self) -> WindowEnd {
        match self.end {
            WindowEnd::Finite(end) => {
                let end = if self.start < end {
                    end - self.start
                } else {
                    TimeUnit::ZERO
                };
                WindowEnd::Finite(end)
            }
            WindowEnd::Infinite => WindowEnd::Infinite,
        }
    }

    /// Calculate the overlap (Ω) of two windows as defined in Definition 2. of the paper
    #[must_use]
    pub fn overlaps(&self, other: &Self) -> bool {
        !(self.end < other.start || other.end < self.start)
    }

    /// Determine if two windows are adjacent, a special case of overlapping
    ///
    /// Used by `AggregationIterator` to take advantage of the relaxed invariant of `CurveIterator` as opposed to `Curve`
    #[must_use]
    pub fn adjacent(&self, other: &Self) -> bool {
        self.end == other.start || self.start == other.end
    }

    /// Calculate the Window delta as defined in Definition 6. of the paper
    #[must_use]
    pub fn delta<Q: WindowType>(supply: &Self, demand: &Window<Q>) -> WindowDeltaResult<T, Q>
    where
        T: WindowType,
    {
        if supply.end < demand.start {
            WindowDeltaResult {
                remaining_supply_head: supply.clone(),
                remaining_supply_tail: Window::empty(),
                overlap: Window::empty(),
                remaining_demand: demand.clone(),
            }
        } else {
            let overlap_start = TimeUnit::max(supply.start, demand.start);
            let overlap_end: WindowEnd =
                overlap_start + WindowEnd::min(demand.length(), supply.end - overlap_start);
            let overlap = Window::new(overlap_start, overlap_end);

            let remaining_demand = match overlap.length() {
                WindowEnd::Finite(length) => Window::new(demand.start + length, demand.end),
                WindowEnd::Infinite => {
                    // Infinite supply satisfies infinite demand, no demand left

                    Window::empty()
                }
            };

            let remaining_supply_head = Window::new(supply.start, overlap.start);
            let remaining_supply_tail = match overlap.end {
                WindowEnd::Finite(overlap_end) => Window::new(overlap_end, supply.end),
                WindowEnd::Infinite => {
                    // Infinite supply satisfies infinite demand, no tail supply left
                    Window::empty()
                }
            };

            WindowDeltaResult {
                remaining_supply_head,
                remaining_supply_tail,
                overlap,
                remaining_demand,
            }
        }
    }

    /// Whether the window is empty/has a length of 0
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.length() == TimeUnit::ZERO
    }

    /// Calculate the Budget Group that the window falls into
    /// given a splitting interval
    ///
    /// See Section 6.2 §3
    #[must_use]
    pub fn budget_group(&self, interval: TimeUnit) -> UnitNumber {
        self.start / interval
    }

    /// Calculate the aggregation (⊕) of two windows as defined in Definition 4. of the paper
    #[must_use]
    pub fn aggregate(&self, other: &Self) -> Option<Self> {
        // only defined for overlapping windows, return None when not overlapping
        self.overlaps(other).then(|| {
            let start = TimeUnit::min(self.start, other.start);
            let end = start + self.length() + other.length();
            Window::new(start, end)
        })
    }

    pub fn reclassify<R>(self) -> Window<R> {
        Window {
            start: self.start,
            end: self.end,
            window_type: PhantomData,
        }
    }
}

/// The Return Type for the [`Window::delta`] calculation
#[derive(Debug, Eq, PartialEq)] // Eq for tests
pub struct WindowDeltaResult<P: WindowType, Q: WindowType> {
    /// The unused supply at the start of the original supply window
    pub remaining_supply_head: Window<P>,
    /// The unused supply at the end of the original supply window
    pub remaining_supply_tail: Window<P>,
    /// The Windows Overlap
    pub overlap: Window<Overlap<P, Q>>,
    /// The unfulfilled "demand"
    pub remaining_demand: Window<Q>,
}

/// Marker Type for Window, indicating a Supply Window
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Supply;

/// Marker Type for Window, indicating Demand
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Demand;

/// Marker Type for Window,indicating an Overlap between Supply and Demand
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Overlap<P, Q>(PhantomData<(P, Q)>);