Skip to main content

moq_net/model/
timed.rs

1use bytes::Bytes;
2
3use crate::Timestamp;
4
5/// A value to publish, and optionally when it was captured.
6///
7/// `T` is the clock the time is on: a raw [`Timestamp`] by default, or whatever a higher layer
8/// maps onto one (`moq-mux` takes a [`std::time::Instant`]). Converts from a bare payload (bytes,
9/// or a `&V` to serialize), so a producer taking one still accepts the plain value, stamped when
10/// written.
11#[derive(Debug, Clone, Copy)]
12pub struct Timed<P, T = Timestamp> {
13	/// The value to publish.
14	pub value: P,
15
16	/// When the value was captured. `None` stamps it when written.
17	pub at: Option<T>,
18}
19
20impl<P, T> Timed<P, T> {
21	/// Set when the value was captured.
22	pub fn at(mut self, at: T) -> Self {
23		self.at = Some(at);
24		self
25	}
26}
27
28impl<B: Into<Bytes>, T> From<B> for Timed<Bytes, T> {
29	fn from(value: B) -> Self {
30		Self {
31			value: value.into(),
32			at: None,
33		}
34	}
35}
36
37impl<'a, V, T> From<&'a V> for Timed<&'a V, T> {
38	fn from(value: &'a V) -> Self {
39		Self { value, at: None }
40	}
41}
42
43#[cfg(test)]
44mod tests {
45	use super::*;
46
47	#[test]
48	fn a_bare_payload_converts_untimed() {
49		let timed: Timed<Bytes> = vec![1u8, 2].into();
50		assert_eq!(timed.value, Bytes::from_static(&[1, 2]));
51		assert_eq!(timed.at, None);
52
53		let stamped = Timed::from(&b"x"[..]).at(Timestamp::from_millis(5).unwrap());
54		assert_eq!(stamped.at, Some(Timestamp::from_millis(5).unwrap()));
55
56		let value = 7u32;
57		let timed: Timed<&u32, std::time::Instant> = (&value).into();
58		assert_eq!(*timed.value, 7);
59	}
60}