bitcode/derive/
duration.rs
1use crate::coder::{Buffer, Decoder, Encoder, Result, View};
2use crate::{Decode, Encode};
3use alloc::vec::Vec;
4use bytemuck::CheckedBitPattern;
5use core::num::NonZeroUsize;
6use core::time::Duration;
7
8#[derive(Default)]
9pub struct DurationEncoder {
10 secs: <u64 as Encode>::Encoder,
11 subsec_nanos: <u32 as Encode>::Encoder,
12}
13impl Encoder<Duration> for DurationEncoder {
14 #[inline(always)]
15 fn encode(&mut self, t: &Duration) {
16 self.secs.encode(&t.as_secs());
17 self.subsec_nanos.encode(&t.subsec_nanos());
18 }
19}
20impl Buffer for DurationEncoder {
21 fn collect_into(&mut self, out: &mut Vec<u8>) {
22 self.secs.collect_into(out);
23 self.subsec_nanos.collect_into(out);
24 }
25
26 fn reserve(&mut self, additional: NonZeroUsize) {
27 self.secs.reserve(additional);
28 self.subsec_nanos.reserve(additional);
29 }
30}
31impl Encode for Duration {
32 type Encoder = DurationEncoder;
33}
34
35#[derive(Copy, Clone)]
37#[repr(transparent)]
38struct Nanoseconds(u32);
39unsafe impl CheckedBitPattern for Nanoseconds {
41 type Bits = u32;
42 #[inline(always)]
43 fn is_valid_bit_pattern(bits: &Self::Bits) -> bool {
44 *bits < 1_000_000_000
45 }
46}
47impl<'a> Decode<'a> for Nanoseconds {
48 type Decoder = crate::int::CheckedIntDecoder<'a, Nanoseconds, u32>;
49}
50
51#[derive(Default)]
52pub struct DurationDecoder<'a> {
53 secs: <u64 as Decode<'a>>::Decoder,
54 subsec_nanos: <Nanoseconds as Decode<'a>>::Decoder,
55}
56impl<'a> View<'a> for DurationDecoder<'a> {
57 fn populate(&mut self, input: &mut &'a [u8], length: usize) -> Result<()> {
58 self.secs.populate(input, length)?;
59 self.subsec_nanos.populate(input, length)?;
60 Ok(())
61 }
62}
63impl<'a> Decoder<'a, Duration> for DurationDecoder<'a> {
64 #[inline(always)]
65 fn decode(&mut self) -> Duration {
66 let secs = self.secs.decode();
67 let Nanoseconds(subsec_nanos) = self.subsec_nanos.decode();
68 unsafe {
71 if !Nanoseconds::is_valid_bit_pattern(&subsec_nanos) {
72 core::hint::unreachable_unchecked();
73 }
74 }
75 Duration::new(secs, subsec_nanos)
76 }
77}
78impl<'a> Decode<'a> for Duration {
79 type Decoder = DurationDecoder<'a>;
80}
81
82#[cfg(test)]
83mod tests {
84 #[test]
85 fn test() {
86 assert!(crate::decode::<Duration>(&crate::encode(&(u64::MAX, 999_999_999))).is_ok());
87 assert!(crate::decode::<Duration>(&crate::encode(&(u64::MAX, 1_000_000_000))).is_err());
88 }
89
90 use alloc::vec::Vec;
91 use core::time::Duration;
92 fn bench_data() -> Vec<Duration> {
93 crate::random_data(1000)
94 .into_iter()
95 .map(|(s, n): (_, u32)| Duration::new(s, n % 1_000_000_000))
96 .collect()
97 }
98 crate::bench_encode_decode!(duration_vec: Vec<_>);
99}