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
// Copyright 2019 DFINITY
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::amount::Amount;
use crate::displayer::{DisplayProxy, DisplayerOf};
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::ops::{Add, AddAssign, Div, Mul, MulAssign, Sub, SubAssign};

/// `Instant<Unit>` provides a type-safe way to keep absolute time of
/// some events, expressed in `Unit`s (CPU ticks, seconds from epoch,
/// years from birth, etc).
///
/// You can compare instants:
///
/// ```
/// use phantom_newtype::Instant;
///
/// enum SecondsFromEpoch {}
/// type UnixTime = Instant<SecondsFromEpoch, i64>;
///
/// assert_eq!(true, UnixTime::from(3) < UnixTime::from(5));
/// assert_eq!(false, UnixTime::from(3) > UnixTime::from(5));
/// assert_eq!(true, UnixTime::from(3) != UnixTime::from(5));
/// assert_eq!(true, UnixTime::from(5) == UnixTime::from(5));
/// assert_eq!(false, UnixTime::from(5) != UnixTime::from(5));
///
/// assert_eq!(vec![UnixTime::from(3), UnixTime::from(5)].iter().max().unwrap(),
///            &UnixTime::from(5));
/// ```
///
/// Instants support basic arithmetics, you can:
/// * Subtract an instant from another instant to get amount of units between them.
/// * Add/subtract amount of units to/from an instant to get another instant.
///
/// ```
/// use phantom_newtype::{Amount, Instant};
///
/// enum SecondsFromEpoch {}
///
/// type UnixTime = Instant<SecondsFromEpoch, i64>;
/// type TimeDiff = Amount<SecondsFromEpoch, i64>;
///
/// let epoch = UnixTime::from(0);
/// let some_date = UnixTime::from(123456789);
/// let diff = TimeDiff::from(123456789);
///
/// assert_eq!(some_date - epoch, diff);
/// assert_eq!(some_date - diff, epoch);
/// assert_eq!(epoch + diff, some_date);
/// ```
///
/// Direct multiplication of instants is not supported, however, you
/// can scale them by a scalar or divide to get a scalar back:
///
/// ```
/// use phantom_newtype::Instant;
///
/// enum SecondsFromEpoch {}
/// type UnixTime = Instant<SecondsFromEpoch, i64>;
///
/// let x = UnixTime::from(123456);
/// assert_eq!(x * 3, UnixTime::from(3 * 123456));
/// assert_eq!(1, x / x);
/// assert_eq!(3, (x * 3) / x);
/// ```
///
/// Note that the unit is only available at compile time, thus using
/// `Instant` instead of `u64` doesn't incur any runtime penalty:
///
/// ```
/// use phantom_newtype::Instant;
///
/// enum SecondsFromEpoch {}
///
/// let ms = Instant::<SecondsFromEpoch, u64>::from(10);
/// assert_eq!(std::mem::size_of_val(&ms), std::mem::size_of::<u64>());
/// ```
///
/// Instants can be serialized and deserialized with `serde`. Serialized
/// forms of `Instant<Unit, Repr>` and `Repr` are identical.
///
/// ```
/// #[cfg(feature = "serde")] {
/// use phantom_newtype::Instant;
/// use serde::{Serialize, Deserialize};
/// use serde_json;
///
/// enum SecondsFromEpoch {}
/// type UnixTime = Instant<SecondsFromEpoch, i64>;
///
/// let repr: u64 = 123456;
/// let time = UnixTime::from(repr);
/// assert_eq!(serde_json::to_string(&time).unwrap(), serde_json::to_string(&repr).unwrap());
///
/// let copy: UnitTime = serde_json::from_str(&serde_json::to_string(&time).unwrap()).unwrap();
/// assert_eq!(copy, time);
/// }
/// ```
///
/// You can also declare constants of `Instant<Unit, Repr>` using `new`
/// function:
/// ```
/// use phantom_newtype::Instant;
///
/// enum SecondsFromEpoch {}
/// type UnixTime = Instant<SecondsFromEpoch, u64>;
///
/// const EPOCH: UnixTime = UnixTime::new(0);
/// ```
///
/// Instants can be sent between threads if the `Repr` allows it, no
/// matter which `Unit` is used.
///
/// ```
/// use phantom_newtype::Instant;
///
/// type Cell = std::cell::RefCell<i64>;
/// type CellInstant = Instant<Cell, i64>;
/// const I: CellInstant = CellInstant::new(1234);
///
/// let instant_from_thread = std::thread::spawn(|| &I).join().unwrap();
/// assert_eq!(I, *instant_from_thread);
/// ```
pub struct Instant<Unit, Repr>(Repr, PhantomData<std::sync::Mutex<Unit>>);

impl<Unit, Repr: Copy> Instant<Unit, Repr> {
    /// Returns the wrapped value.
    ///
    /// ```
    /// use phantom_newtype::Instant;
    ///
    /// enum Apples {}
    ///
    /// let three_apples = Instant::<Apples, u64>::from(3);
    /// assert_eq!(9, (three_apples * 3).get());
    /// ```
    pub fn get(&self) -> Repr {
        self.0
    }
}

impl<Unit, Repr> Instant<Unit, Repr> {
    /// `new` is a synonym for `from` that can be evaluated in
    /// compile time. The main use-case of this functions is defining
    /// constants.
    pub const fn new(repr: Repr) -> Instant<Unit, Repr> {
        Instant(repr, PhantomData)
    }
}

impl<Unit: Default, Repr: Copy> Instant<Unit, Repr> {
    /// Provides a useful shortcut to access units of an instant if
    /// they implement the `Default` trait:
    ///
    /// ```
    /// use phantom_newtype::Instant;
    ///
    /// #[derive(Debug, Default)]
    /// struct SecondsFromEpoch;
    /// let when = Instant::<SecondsFromEpoch, i64>::from(5);
    ///
    /// assert_eq!("5 SecondsFromEpoch", format!("{} {:?}", when, when.unit()));
    /// ```
    pub fn unit(&self) -> Unit {
        Default::default()
    }
}

impl<Unit, Repr> Instant<Unit, Repr>
where
    Unit: DisplayerOf<Instant<Unit, Repr>>,
{
    /// `display` provides a machanism to implement a custom display
    /// for phantom types.
    ///
    /// ```
    /// use phantom_newtype::{Instant, DisplayerOf};
    /// use std::fmt;
    ///
    /// struct YearUnit;
    /// type YearAD = Instant<YearUnit, u64>;
    ///
    /// impl DisplayerOf<YearAD> for YearUnit {
    ///   fn display(year: &YearAD, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    ///     write!(f, "{} AD", year.get())
    ///   }
    /// }
    ///
    /// assert_eq!(format!("{}", YearAD::from(1221).display()), "1221 AD");
    /// ```
    pub fn display(&self) -> DisplayProxy<'_, Self, Unit> {
        DisplayProxy::new(self)
    }
}

impl<Unit, Repr: Copy> From<Repr> for Instant<Unit, Repr> {
    fn from(repr: Repr) -> Self {
        Self::new(repr)
    }
}

impl<Unit, Repr: Copy> Clone for Instant<Unit, Repr> {
    fn clone(&self) -> Self {
        Instant(self.0, PhantomData)
    }
}

impl<Unit, Repr: Copy> Copy for Instant<Unit, Repr> {}

impl<Unit, Repr: PartialEq> PartialEq for Instant<Unit, Repr> {
    fn eq(&self, rhs: &Self) -> bool {
        self.0.eq(&rhs.0)
    }
}

impl<Unit, Repr: Eq> Eq for Instant<Unit, Repr> {}

impl<Unit, Repr: PartialOrd> PartialOrd for Instant<Unit, Repr> {
    fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
        self.0.partial_cmp(&rhs.0)
    }
}

impl<Unit, Repr: Ord> Ord for Instant<Unit, Repr> {
    fn cmp(&self, rhs: &Self) -> Ordering {
        self.0.cmp(&rhs.0)
    }
}

impl<Unit, Repr: Hash> Hash for Instant<Unit, Repr> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.hash(state)
    }
}

impl<Unit, Repr, Repr2> Add<Amount<Unit, Repr2>> for Instant<Unit, Repr>
where
    Repr: AddAssign<Repr2> + Copy,
    Repr2: Copy,
{
    type Output = Self;
    fn add(mut self, rhs: Amount<Unit, Repr2>) -> Self {
        self.add_assign(rhs);
        self
    }
}

impl<Unit, Repr, Repr2> AddAssign<Amount<Unit, Repr2>> for Instant<Unit, Repr>
where
    Repr: AddAssign<Repr2> + Copy,
    Repr2: Copy,
{
    fn add_assign(&mut self, rhs: Amount<Unit, Repr2>) {
        self.0 += rhs.get()
    }
}

impl<Unit, Repr, Repr2> SubAssign<Amount<Unit, Repr2>> for Instant<Unit, Repr>
where
    Repr: SubAssign<Repr2> + Copy,
    Repr2: Copy,
{
    fn sub_assign(&mut self, rhs: Amount<Unit, Repr2>) {
        self.0 -= rhs.get()
    }
}

impl<Unit, Repr> Sub for Instant<Unit, Repr>
where
    Repr: Sub + Copy,
{
    type Output = Amount<Unit, <Repr as Sub>::Output>;

    fn sub(self, rhs: Self) -> Self::Output {
        Amount::<Unit, <Repr as Sub>::Output>::new(self.0 - rhs.0)
    }
}

impl<Unit, Repr, Repr2> Sub<Amount<Unit, Repr2>> for Instant<Unit, Repr>
where
    Repr: SubAssign<Repr2> + Copy,
    Repr2: Copy,
{
    type Output = Self;

    fn sub(mut self, rhs: Amount<Unit, Repr2>) -> Self {
        self.sub_assign(rhs);
        self
    }
}

impl<Unit, Repr> MulAssign<Repr> for Instant<Unit, Repr>
where
    Repr: MulAssign + Copy,
{
    fn mul_assign(&mut self, rhs: Repr) {
        self.0 *= rhs;
    }
}

impl<Unit, Repr> Mul<Repr> for Instant<Unit, Repr>
where
    Repr: MulAssign + Copy,
{
    type Output = Self;

    fn mul(mut self, rhs: Repr) -> Self {
        self.mul_assign(rhs);
        self
    }
}

impl<Unit, Repr> Div<Self> for Instant<Unit, Repr>
where
    Repr: Div<Repr> + Copy,
{
    type Output = <Repr as Div>::Output;

    fn div(self, rhs: Self) -> Self::Output {
        self.0.div(rhs.0)
    }
}

impl<Unit, Repr> fmt::Debug for Instant<Unit, Repr>
where
    Repr: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl<Unit, Repr> fmt::Display for Instant<Unit, Repr>
where
    Repr: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[cfg(feature = "serde")]
impl<Unit, Repr: Serialize> Serialize for Instant<Unit, Repr> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.0.serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'de, Unit, Repr> Deserialize<'de> for Instant<Unit, Repr>
where
    Repr: Deserialize<'de>,
{
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Repr::deserialize(deserializer).map(Instant::<Unit, Repr>::new)
    }
}

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

    #[test]
    fn test_complex_instant_arithmetics() {
        enum Seconds {}
        enum UTC {}

        type Timestamp = Instant<Seconds, i64>;
        type TsDiff = Amount<Seconds, i64>;
        type Date = Instant<UTC, Timestamp>;

        let epoch = Date::new(Timestamp::new(0));
        let date = Date::new(Timestamp::new(123456789));
        let span = Amount::<UTC, TsDiff>::new(TsDiff::from(123456789));

        assert_eq!(date - epoch, span);
        assert_eq!(date - span, epoch);
        assert_eq!(epoch + span, date);
    }
}