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
use std::ops::Neg;
use crate::*;
use crate::iter::TimeUnion;


/// A union of [`TimeSpan`] (aliased to [`TimeSet<TimeValue>`])
pub type TimeSpans = TimeSet<TimeValue>;

/// A union of [`TimeSlot`] (aliased to [`TimeSet<Timestamp>`])
pub type TimeSlots = TimeSet<Timestamp>;

/// # A union of time intervals
///
/// This is the more generic structure to keep a set of time points.
/// It could be empty, convex or defined by pieces.
///
/// The inner list of time intervals is chronological sorted
/// and all the inner intervals are disjoint. If, when added,
/// two intervals overlaps, then they are merged.
#[derive(Clone, Eq, Hash)]
pub struct TimeSet<T:TimePoint>(pub(crate) Vec<TimeInterval<T>>);


impl<T:TimePoint> TimeSet<T>
{
    /// The full interval `]-oo,+oo[`
    ///
    /// Returns a timeset composed of the full interval `]-oo,+oo[`
    #[inline]
    pub fn all() -> Self { Self(vec![TimeInterval::all()]) }

    /// A convex interval `[a,b]`
    ///
    /// Returns a timeset composed of one convex interval.
    #[inline]
    pub fn convex(lower: T, upper: T) -> Self
    {
        let tw = TimeInterval::new(lower, upper);
        if tw.is_empty() { Self::empty() } else { Self(vec![tw]) }
    }

    /// A singleton `{t}`
    ///
    /// Retuns a timeset composed of the convex interval `[t,t]`
    #[inline]
    pub fn singleton(t: T) -> Self {
        Self(vec![TimeInterval::singleton(t)])
    }

    /// The empty set
    #[inline]
    pub fn empty() -> Self { Self(vec![]) }

    #[inline]
    pub fn shrink_to_fit(&mut self) { self.0.shrink_to_fit() }
}



impl<T:TimePoint> TimeBounds for TimeSet<T>
{
    type TimePoint = T;

    #[inline]
    fn is_empty(&self) -> bool { self.0.is_empty() }

    #[inline]
    fn is_singleton(&self) -> bool {
        (self.0.len() == 1) && unsafe { self.0.get_unchecked(0).is_singleton() }
    }

    #[inline]
    fn is_bounded(&self) -> bool {
        self.is_low_bounded() && self.is_up_bounded()
    }

    #[inline]
    fn is_low_bounded(&self) -> bool {
        self.0.first().map(|s| s.is_low_bounded()).unwrap_or(false)
    }

    #[inline]
    fn is_up_bounded(&self) -> bool {
        self.0.last().map(|s| s.is_up_bounded()).unwrap_or(false)
    }

    #[inline]
    fn lower_bound(&self) -> Self::TimePoint {
        self.0.first()
            .map(|i| i.lower_bound())
            .unwrap_or(Self::TimePoint::INFINITE)
    }

    #[inline]
    fn upper_bound(&self) -> Self::TimePoint {
        self.0.last()
            .map(|i| i.upper_bound())
            .unwrap_or(-Self::TimePoint::INFINITE)
    }
}


impl<T:TimePoint> TimeWindow for TimeSet<T>
{
    #[inline]
    fn convex_count(&self) -> usize { self.0.len() }

    type ConvexIter = crate::iter::intoiter::IntoConvexIter<T,std::vec::IntoIter<TimeInterval<T>>>;

    fn iter(&self) -> Self::ConvexIter {
        crate::iter::intoiter::IntoConvexIter(self.0.clone().into_iter())
    }
}

impl<T:TimePoint> Neg for TimeSet<T>
{
    type Output = Self;
    #[inline] fn neg(self) -> Self {
        // negate each intervals AND reverse the list
        Self(self.0.iter().rev().map(|&t| -t).collect())
    }
}

impl<T:TimePoint> FromIterator<TimeInterval<T>> for TimeSet<T>
{
    fn from_iter<I: IntoIterator<Item=TimeInterval<T>>>(iter: I) -> Self
    {
        let mut iter = iter.into_iter()
            .filter(|i| !i.is_empty());

        match iter.next() {
            None => Self::empty(),
            Some(i) => {
                iter.fold(i.into(), |mut r,i| {
                    // very most of the time, time iterators are chronologically sorted
                    // if the gap is more than one tick, just add the new convex at the end
                    if i.lower_bound() > r.upper_bound().just_after() {
                        r.0.push(i.into()); r
                    } else {
                        // todo: could be improved
                        r.into_iter().union(i).collect()
                    }
                })
            }
        }
    }
}


impl<T:TimePoint> FromIterator<TimeSet<T>> for TimeSet<T>
{
    fn from_iter<I: IntoIterator<Item=TimeSet<T>>>(iter: I) -> Self
    {
        iter.into_iter()
            .reduce(|r,s| r|s)
            .unwrap_or(TimeSet::empty())
    }
}


impl<T,TW> From<TW> for TimeSet<T>
    where
        T:TimePoint,
        TW:TimeConvex<TimePoint=T>
{
    #[inline] fn from(tw: TW) -> Self
    {
        if tw.is_empty() {
            TimeSet::empty()
        } else {
            Self(vec![TimeInterval { lower: tw.lower_bound(), upper: tw.upper_bound()}])
        }
    }
}