moq_lite/message/
announce.rs

1use num_enum::{IntoPrimitive, TryFromPrimitive};
2
3use crate::coding::*;
4
5/// Sent by the publisher to announce the availability of a track.
6/// The payload contains the contents of the wildcard.
7#[derive(Clone, Debug, PartialEq, Eq)]
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9pub enum Announce {
10	Active { suffix: String },
11	Ended { suffix: String },
12}
13
14impl Announce {
15	pub fn suffix(&self) -> &str {
16		match self {
17			Announce::Active { suffix } => suffix,
18			Announce::Ended { suffix } => suffix,
19		}
20	}
21}
22impl Decode for Announce {
23	fn decode<R: bytes::Buf>(r: &mut R) -> Result<Self, DecodeError> {
24		Ok(match AnnounceStatus::decode(r)? {
25			AnnounceStatus::Active => Self::Active {
26				suffix: String::decode(r)?,
27			},
28			AnnounceStatus::Ended => Self::Ended {
29				suffix: String::decode(r)?,
30			},
31		})
32	}
33}
34
35impl Encode for Announce {
36	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
37		match self {
38			Self::Active { suffix } => {
39				AnnounceStatus::Active.encode(w);
40				suffix.encode(w);
41			}
42			Self::Ended { suffix } => {
43				AnnounceStatus::Ended.encode(w);
44				suffix.encode(w);
45			}
46		}
47	}
48}
49
50#[cfg(test)]
51impl Announce {
52	pub fn assert_active(&self, expected: &str) {
53		match self {
54			Announce::Active { suffix } => assert_eq!(suffix, expected),
55			_ => panic!("expected active announce"),
56		}
57	}
58
59	pub fn assert_ended(&self, expected: &str) {
60		match self {
61			Announce::Ended { suffix } => assert_eq!(suffix, expected),
62			_ => panic!("expected ended announce"),
63		}
64	}
65}
66
67/// Sent by the subscriber to request ANNOUNCE messages.
68#[derive(Clone, Debug)]
69pub struct AnnounceRequest {
70	// Request tracks with this prefix.
71	pub prefix: String,
72}
73
74impl Decode for AnnounceRequest {
75	fn decode<R: bytes::Buf>(r: &mut R) -> Result<Self, DecodeError> {
76		let prefix = String::decode(r)?;
77		Ok(Self { prefix })
78	}
79}
80
81impl Encode for AnnounceRequest {
82	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
83		self.prefix.encode(w)
84	}
85}
86
87/// Send by the publisher, used to determine the message that follows.
88#[derive(Clone, Copy, Debug, IntoPrimitive, TryFromPrimitive)]
89#[repr(u8)]
90enum AnnounceStatus {
91	Ended = 0,
92	Active = 1,
93}
94
95impl Decode for AnnounceStatus {
96	fn decode<R: bytes::Buf>(r: &mut R) -> Result<Self, DecodeError> {
97		let status = u8::decode(r)?;
98		match status {
99			0 => Ok(Self::Ended),
100			1 => Ok(Self::Active),
101			_ => Err(DecodeError::InvalidValue),
102		}
103	}
104}
105
106impl Encode for AnnounceStatus {
107	fn encode<W: bytes::BufMut>(&self, w: &mut W) {
108		(*self as u8).encode(w)
109	}
110}