pyth-lazer-protocol 0.40.0

Pyth Lazer SDK - protocol types.
Documentation
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
#[cfg(test)]
mod tests;

use {
    anyhow::Context,
    protobuf::{
        well_known_types::{
            duration::Duration as ProtobufDuration, timestamp::Timestamp as ProtobufTimestamp,
        },
        MessageField,
    },
    serde::{Deserialize, Serialize},
    std::time::{Duration, SystemTime},
};

/// Unix timestamp with microsecond resolution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[repr(transparent)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct TimestampUs(u64);

#[cfg_attr(feature = "mry", mry::mry)]
impl TimestampUs {
    pub fn now() -> Self {
        SystemTime::now().try_into().expect("invalid system time")
    }
}

impl TimestampUs {
    pub const UNIX_EPOCH: Self = Self(0);
    pub const MAX: Self = Self(u64::MAX);

    #[inline]
    pub const fn from_micros(micros: u64) -> Self {
        Self(micros)
    }

    #[inline]
    pub const fn as_micros(self) -> u64 {
        self.0
    }

    #[inline]
    pub fn as_nanos(self) -> u128 {
        // never overflows
        u128::from(self.0) * 1000
    }

    #[inline]
    pub fn as_nanos_i128(self) -> i128 {
        // never overflows
        i128::from(self.0) * 1000
    }

    #[inline]
    pub fn from_nanos(nanos: u128) -> anyhow::Result<Self> {
        let micros = nanos
            .checked_div(1000)
            .context("nanos.checked_div(1000) failed")?;
        Ok(Self::from_micros(micros.try_into()?))
    }

    #[inline]
    pub fn from_nanos_i128(nanos: i128) -> anyhow::Result<Self> {
        let micros = nanos
            .checked_div(1000)
            .context("nanos.checked_div(1000) failed")?;
        Ok(Self::from_micros(micros.try_into()?))
    }

    #[inline]
    pub fn as_millis(self) -> u64 {
        self.0 / 1000
    }

    #[inline]
    pub fn from_millis(millis: u64) -> anyhow::Result<Self> {
        let micros = millis
            .checked_mul(1000)
            .context("millis.checked_mul(1000) failed")?;
        Ok(Self::from_micros(micros))
    }

    #[inline]
    pub fn as_secs(self) -> u64 {
        self.0 / 1_000_000
    }

    #[inline]
    pub fn from_secs(secs: u64) -> anyhow::Result<Self> {
        let micros = secs
            .checked_mul(1_000_000)
            .context("secs.checked_mul(1_000_000) failed")?;
        Ok(Self::from_micros(micros))
    }

    #[inline]
    pub fn duration_since(self, other: Self) -> anyhow::Result<DurationUs> {
        Ok(DurationUs(
            self.0
                .checked_sub(other.0)
                .context("timestamp.checked_sub(duration) failed")?,
        ))
    }

    #[inline]
    pub fn saturating_duration_since(self, other: Self) -> DurationUs {
        DurationUs(self.0.saturating_sub(other.0))
    }

    #[inline]
    pub fn elapsed(self) -> anyhow::Result<DurationUs> {
        Self::now().duration_since(self)
    }

    #[inline]
    pub fn saturating_elapsed(self) -> DurationUs {
        Self::now().saturating_duration_since(self)
    }

    #[inline]
    pub fn saturating_add(self, duration: DurationUs) -> TimestampUs {
        TimestampUs(self.0.saturating_add(duration.0))
    }

    #[inline]
    pub fn saturating_sub(self, duration: DurationUs) -> TimestampUs {
        TimestampUs(self.0.saturating_sub(duration.0))
    }

    #[inline]
    pub fn is_multiple_of(self, duration: DurationUs) -> bool {
        match self.0.checked_rem(duration.0) {
            Some(rem) => rem == 0,
            None => true,
        }
    }

    /// Calculates the smallest value greater than or equal to self that is a multiple of `duration`.
    #[inline]
    pub fn next_multiple_of(self, duration: DurationUs) -> anyhow::Result<TimestampUs> {
        // Copy implementation from std source to support older Rust.
        #[inline]
        fn checked_next_multiple_of(lhs: u64, rhs: u64) -> Option<u64> {
            match lhs.checked_rem(rhs)? {
                0 => Some(lhs),
                // rhs - r cannot overflow because r is smaller than rhs
                r => lhs.checked_add(rhs - r),
            }
        }

        Ok(TimestampUs(
            checked_next_multiple_of(self.0, duration.0)
                .context("checked_next_multiple_of failed")?,
        ))
    }

    /// Calculates the smallest value less than or equal to self that is a multiple of `duration`.
    #[inline]
    pub fn previous_multiple_of(self, duration: DurationUs) -> anyhow::Result<TimestampUs> {
        Ok(TimestampUs(
            self.0
                .checked_div(duration.0)
                .context("checked_div failed")?
                .checked_mul(duration.0)
                .context("checked_mul failed")?,
        ))
    }

    #[inline]
    pub fn checked_add(self, duration: DurationUs) -> anyhow::Result<Self> {
        Ok(TimestampUs(
            self.0
                .checked_add(duration.0)
                .context("checked_add failed")?,
        ))
    }

    #[inline]
    pub fn checked_sub(self, duration: DurationUs) -> anyhow::Result<Self> {
        Ok(TimestampUs(
            self.0
                .checked_sub(duration.0)
                .context("checked_sub failed")?,
        ))
    }
}

impl TryFrom<ProtobufTimestamp> for TimestampUs {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(timestamp: ProtobufTimestamp) -> anyhow::Result<Self> {
        TryFrom::<&ProtobufTimestamp>::try_from(&timestamp)
    }
}

impl TryFrom<&ProtobufTimestamp> for TimestampUs {
    type Error = anyhow::Error;

    fn try_from(timestamp: &ProtobufTimestamp) -> anyhow::Result<Self> {
        let seconds_in_micros: u64 = timestamp
            .seconds
            .checked_mul(1_000_000)
            .context("checked_mul failed")?
            .try_into()?;
        let nanos_in_micros: u64 = timestamp
            .nanos
            .checked_div(1_000)
            .context("checked_div failed")?
            .try_into()?;
        Ok(TimestampUs(
            seconds_in_micros
                .checked_add(nanos_in_micros)
                .context("checked_add failed")?,
        ))
    }
}

impl From<TimestampUs> for ProtobufTimestamp {
    fn from(timestamp: TimestampUs) -> Self {
        // u64 to i64 after this division can never overflow because the value cannot be too big
        ProtobufTimestamp {
            #[allow(clippy::cast_possible_wrap)]
            seconds: (timestamp.0 / 1_000_000) as i64,
            // never fails, never overflows
            nanos: (timestamp.0 % 1_000_000) as i32 * 1000,
            special_fields: Default::default(),
        }
    }
}

impl From<TimestampUs> for MessageField<ProtobufTimestamp> {
    #[inline]
    fn from(value: TimestampUs) -> Self {
        MessageField::some(value.into())
    }
}

impl TryFrom<SystemTime> for TimestampUs {
    type Error = anyhow::Error;

    fn try_from(value: SystemTime) -> Result<Self, Self::Error> {
        let value = value
            .duration_since(SystemTime::UNIX_EPOCH)
            .context("invalid system time")?
            .as_micros()
            .try_into()?;
        Ok(Self(value))
    }
}

impl TryFrom<TimestampUs> for SystemTime {
    type Error = anyhow::Error;

    fn try_from(value: TimestampUs) -> Result<Self, Self::Error> {
        SystemTime::UNIX_EPOCH
            .checked_add(Duration::from_micros(value.as_micros()))
            .context("checked_add failed")
    }
}

impl TryFrom<&chrono::DateTime<chrono::Utc>> for TimestampUs {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(value: &chrono::DateTime<chrono::Utc>) -> Result<Self, Self::Error> {
        Ok(Self(value.timestamp_micros().try_into()?))
    }
}

impl TryFrom<chrono::DateTime<chrono::Utc>> for TimestampUs {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(value: chrono::DateTime<chrono::Utc>) -> Result<Self, Self::Error> {
        TryFrom::<&chrono::DateTime<chrono::Utc>>::try_from(&value)
    }
}

impl TryFrom<TimestampUs> for chrono::DateTime<chrono::Utc> {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(value: TimestampUs) -> Result<Self, Self::Error> {
        chrono::DateTime::<chrono::Utc>::from_timestamp_micros(value.as_micros().try_into()?)
            .with_context(|| format!("cannot convert timestamp to datetime: {value:?}"))
    }
}

/// Non-negative duration with microsecond resolution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
pub struct DurationUs(u64);

impl DurationUs {
    pub const ZERO: Self = Self(0);

    #[inline]
    pub const fn from_micros(micros: u64) -> Self {
        Self(micros)
    }

    #[inline]
    pub const fn as_micros(self) -> u64 {
        self.0
    }

    #[inline]
    pub fn as_nanos(self) -> u128 {
        // never overflows
        u128::from(self.0) * 1000
    }

    #[inline]
    pub fn as_nanos_i128(self) -> i128 {
        // never overflows
        i128::from(self.0) * 1000
    }

    #[inline]
    pub fn from_nanos(nanos: u128) -> anyhow::Result<Self> {
        let micros = nanos.checked_div(1000).context("checked_div failed")?;
        Ok(Self::from_micros(micros.try_into()?))
    }

    #[inline]
    pub fn as_millis(self) -> u64 {
        self.0 / 1000
    }

    #[inline]
    pub const fn from_millis_u32(millis: u32) -> Self {
        // never overflows
        Self((millis as u64) * 1_000)
    }

    #[inline]
    pub fn from_millis(millis: u64) -> anyhow::Result<Self> {
        let micros = millis
            .checked_mul(1000)
            .context("millis.checked_mul(1000) failed")?;
        Ok(Self::from_micros(micros))
    }

    #[inline]
    pub fn as_secs(self) -> u64 {
        self.0 / 1_000_000
    }

    #[inline]
    pub const fn from_secs_u32(secs: u32) -> Self {
        // never overflows
        Self((secs as u64) * 1_000_000)
    }

    #[inline]
    pub fn from_secs(secs: u64) -> anyhow::Result<Self> {
        let micros = secs
            .checked_mul(1_000_000)
            .context("secs.checked_mul(1_000_000) failed")?;
        Ok(Self::from_micros(micros))
    }

    #[inline]
    pub const fn from_days_u16(days: u16) -> Self {
        // never overflows
        Self((days as u64) * 24 * 3600 * 1_000_000)
    }

    #[inline]
    pub fn is_multiple_of(self, other: DurationUs) -> bool {
        match self.0.checked_rem(other.0) {
            Some(rem) => rem == 0,
            None => true,
        }
    }

    #[inline]
    pub const fn is_zero(self) -> bool {
        self.0 == 0
    }

    #[inline]
    pub const fn is_positive(self) -> bool {
        self.0 > 0
    }

    #[inline]
    pub fn checked_add(self, other: DurationUs) -> anyhow::Result<Self> {
        Ok(DurationUs(
            self.0.checked_add(other.0).context("checked_add failed")?,
        ))
    }

    #[inline]
    pub fn checked_sub(self, other: DurationUs) -> anyhow::Result<Self> {
        Ok(DurationUs(
            self.0.checked_sub(other.0).context("checked_sub failed")?,
        ))
    }

    #[inline]
    pub fn checked_mul(self, n: u64) -> anyhow::Result<DurationUs> {
        Ok(DurationUs(
            self.0.checked_mul(n).context("checked_mul failed")?,
        ))
    }

    #[inline]
    pub fn checked_div(self, n: u64) -> anyhow::Result<DurationUs> {
        Ok(DurationUs(
            self.0.checked_div(n).context("checked_div failed")?,
        ))
    }
}

impl From<DurationUs> for Duration {
    #[inline]
    fn from(value: DurationUs) -> Self {
        Duration::from_micros(value.as_micros())
    }
}

impl TryFrom<Duration> for DurationUs {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(value: Duration) -> Result<Self, Self::Error> {
        Ok(Self(value.as_micros().try_into()?))
    }
}

impl TryFrom<ProtobufDuration> for DurationUs {
    type Error = anyhow::Error;

    #[inline]
    fn try_from(duration: ProtobufDuration) -> anyhow::Result<Self> {
        TryFrom::<&ProtobufDuration>::try_from(&duration)
    }
}

impl TryFrom<&ProtobufDuration> for DurationUs {
    type Error = anyhow::Error;

    fn try_from(duration: &ProtobufDuration) -> anyhow::Result<Self> {
        let seconds_in_micros: u64 = duration
            .seconds
            .checked_mul(1_000_000)
            .context("checked_mul failed")?
            .try_into()?;
        let nanos_in_micros: u64 = duration
            .nanos
            .checked_div(1_000)
            .context("nanos.checked_div(1_000) failed")?
            .try_into()?;
        Ok(DurationUs(
            seconds_in_micros
                .checked_add(nanos_in_micros)
                .context("checked_add failed")?,
        ))
    }
}

impl From<DurationUs> for ProtobufDuration {
    fn from(duration: DurationUs) -> Self {
        ProtobufDuration {
            // u64 to i64 after this division can never overflow because the value cannot be too big
            #[allow(clippy::cast_possible_wrap)]
            seconds: (duration.0 / 1_000_000) as i64,
            // never fails, never overflows
            nanos: (duration.0 % 1_000_000) as i32 * 1000,
            special_fields: Default::default(),
        }
    }
}

pub mod duration_us_serde_humantime {
    use std::time::Duration;

    use serde::{de::Error, Deserialize, Serialize};

    use crate::time::DurationUs;

    pub fn serialize<S>(value: &DurationUs, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        humantime_serde::Serde::from(Duration::from(*value)).serialize(serializer)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<DurationUs, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = humantime_serde::Serde::<Duration>::deserialize(deserializer)?;
        value.into_inner().try_into().map_err(D::Error::custom)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "utoipa", schema(as = String, example = "fixed_rate@200ms"))]
pub struct FixedRate {
    rate: DurationUs,
}

impl FixedRate {
    pub const RATE_50_MS: Self = Self {
        rate: DurationUs::from_millis_u32(50),
    };
    pub const RATE_200_MS: Self = Self {
        rate: DurationUs::from_millis_u32(200),
    };
    pub const RATE_1000_MS: Self = Self {
        rate: DurationUs::from_millis_u32(1000),
    };

    // Assumptions (tested below):
    // - Values are sorted.
    // - 1 second contains a whole number of each interval.
    // - all intervals are divisable by the smallest interval.
    pub const ALL: [Self; 3] = [Self::RATE_50_MS, Self::RATE_200_MS, Self::RATE_1000_MS];
    pub const MIN: Self = Self::ALL[0];

    pub fn from_millis(millis: u32) -> Option<Self> {
        Self::ALL
            .into_iter()
            .find(|v| v.rate.as_millis() == u64::from(millis))
    }

    pub fn duration(self) -> DurationUs {
        self.rate
    }
}

impl TryFrom<DurationUs> for FixedRate {
    type Error = anyhow::Error;

    fn try_from(value: DurationUs) -> Result<Self, Self::Error> {
        Self::ALL
            .into_iter()
            .find(|v| v.rate == value)
            .with_context(|| format!("unsupported rate: {value:?}"))
    }
}

impl TryFrom<&ProtobufDuration> for FixedRate {
    type Error = anyhow::Error;

    fn try_from(value: &ProtobufDuration) -> Result<Self, Self::Error> {
        let duration = DurationUs::try_from(value)?;
        Self::try_from(duration)
    }
}

impl TryFrom<ProtobufDuration> for FixedRate {
    type Error = anyhow::Error;

    fn try_from(duration: ProtobufDuration) -> anyhow::Result<Self> {
        TryFrom::<&ProtobufDuration>::try_from(&duration)
    }
}

impl From<FixedRate> for DurationUs {
    fn from(value: FixedRate) -> Self {
        value.rate
    }
}

impl From<FixedRate> for ProtobufDuration {
    fn from(value: FixedRate) -> Self {
        value.rate.into()
    }
}

#[test]
fn fixed_rate_values() {
    assert!(
        FixedRate::ALL.windows(2).all(|w| w[0] < w[1]),
        "values must be unique and sorted"
    );
    for value in FixedRate::ALL {
        assert_eq!(
            1_000_000 % value.duration().as_micros(),
            0,
            "1 s must contain whole number of intervals"
        );
        assert_eq!(
            value.duration().as_micros() % FixedRate::MIN.duration().as_micros(),
            0,
            "the interval's borders must be a subset of the minimal interval's borders"
        );
    }
}