dhcpv6_core/
lib.rs

1// Copyright 2020 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5pub mod client;
6
7use std::fmt::Debug;
8use std::time::Duration;
9
10/// A type representing an instant in time.
11pub trait Instant: Sized + Ord + Copy + Clone + Debug + Send + Sync + 'static {
12    // Note that this trait intentionally does not have a `now` method to return
13    // the current time instant to force the platform to provide the time instant
14    // when an event is handled.
15
16    /// Returns the amount of time elapsed from another instant to this one.
17    ///
18    /// # Panics
19    ///
20    /// This function will panic if `earlier` is later than `self`.
21    fn duration_since(&self, earlier: Self) -> Duration;
22
23    /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be
24    /// represented as `Instant` (which means it's inside the bounds of the
25    /// underlying data structure), `None` otherwise.
26    fn checked_add(&self, duration: Duration) -> Option<Self>;
27}
28
29pub(crate) trait InstantExt: Instant {
30    /// Adds the duration to the instant.
31    ///
32    /// We can't do a blanket `impl<I: Instant> Add<Duration> for I` because `I`
33    /// may be foreign type and `Add` is also a foreign type. We use this ext
34    /// trait to avoid having to do `.checked_add(..).unwrap()` when we want to
35    /// add an [`Instant`] with a [`Duration`].
36    ///
37    /// # Panics
38    ///
39    /// This function may panic if the resulting point in time cannot be represented by the
40    /// underlying data structure. See [`Instant::checked_add`] for a version without panic.
41    fn add(self, duration: Duration) -> Self;
42}
43
44impl<I: Instant> InstantExt for I {
45    fn add(self, duration: Duration) -> Self {
46        self.checked_add(duration).unwrap_or_else(|| {
47            panic!("overflow when adding duration={:?} to instant={:?}", duration, self,)
48        })
49    }
50}
51
52impl Instant for std::time::Instant {
53    fn duration_since(&self, earlier: Self) -> Duration {
54        std::time::Instant::duration_since(self, earlier)
55    }
56
57    fn checked_add(&self, duration: Duration) -> Option<Self> {
58        std::time::Instant::checked_add(self, duration)
59    }
60}
61
62// The client currently supports DUID-LL and DUID-LLT with MAC addresses only
63// and DUID-UUID, the largest of which is DUID-UUID which takes up 18 bytes.
64pub type ClientDuid = arrayvec::ArrayVec<u8, 18>;