grafton_ndi/rejected.rs
1use std::fmt;
2
3use crate::Error;
4
5/// A failed operation that hands back the value it would have consumed.
6///
7/// Operations that take ownership of a value the caller cannot recreate — a
8/// receiver, a sender, a frame, a registration — return this on failure, so
9/// the caller keeps the value and can use it, retry, or drop it deliberately.
10///
11/// `Rejected<T>` converts into [`Error`] (dropping the value), so `?` works in
12/// a function that returns [`crate::Result`].
13///
14/// # Examples
15///
16/// ```no_run
17/// use grafton_ndi::{
18/// discovery_server::{AdvertiserOptions, SendAdvertisement, SendAdvertiser},
19/// Sender, SenderOptions, Ndi,
20/// };
21///
22/// # fn main() -> Result<(), grafton_ndi::Error> {
23/// let ndi = Ndi::new()?;
24/// let server = AdvertiserOptions::default().servers(["127.0.0.1"]);
25/// let mut studio = SendAdvertiser::new(&ndi, &server)?;
26/// let mut backup = SendAdvertiser::new(&ndi, &server)?;
27/// let sender = Sender::new(&ndi, &SenderOptions::new("Camera 1"))?;
28/// let registration = studio.register(&sender, &SendAdvertisement::default())?;
29///
30/// // Only the advertiser that issued a registration can remove it. Another
31/// // one hands it back with the reason instead of consuming it.
32/// let rejected = backup.unregister(registration).unwrap_err();
33/// println!("still registered: {rejected}");
34/// studio.unregister(rejected.into_inner())?;
35/// # Ok(())
36/// # }
37/// ```
38pub struct Rejected<T> {
39 error: Error,
40 // Boxed so that a failure stays as small as an `Error` whatever the value
41 // (an owned frame is hundreds of bytes); only a rejection allocates.
42 value: Box<T>,
43}
44
45impl<T> Rejected<T> {
46 pub(crate) fn new(error: Error, value: T) -> Self {
47 Self {
48 error,
49 value: Box::new(value),
50 }
51 }
52
53 /// Why the operation failed.
54 pub fn error(&self) -> &Error {
55 &self.error
56 }
57
58 /// The value the operation did not consume.
59 pub fn into_inner(self) -> T {
60 *self.value
61 }
62
63 /// The reason, discarding the value.
64 pub fn into_error(self) -> Error {
65 self.error
66 }
67
68 /// The reason and the value.
69 pub fn into_parts(self) -> (Error, T) {
70 (self.error, *self.value)
71 }
72
73 /// Replace the returned value, keeping the reason.
74 #[cfg(feature = "advanced")]
75 pub(crate) fn map<U>(self, value: impl FnOnce(T) -> U) -> Rejected<U> {
76 Rejected::new(self.error, value(*self.value))
77 }
78}
79
80// The value is often a native object with no useful `Debug` output, and none
81// is required of it: only its type is shown.
82impl<T> fmt::Debug for Rejected<T> {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 f.debug_struct("Rejected")
85 .field("error", &self.error)
86 .field("value", &std::any::type_name::<T>())
87 .finish()
88 }
89}
90
91impl<T> fmt::Display for Rejected<T> {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 self.error.fmt(f)
94 }
95}
96
97// Transparent: the message and the source are those of the reason.
98impl<T> std::error::Error for Rejected<T> {
99 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
100 std::error::Error::source(&self.error)
101 }
102}
103
104impl<T> From<Rejected<T>> for Error {
105 fn from(rejected: Rejected<T>) -> Self {
106 rejected.error
107 }
108}
109
110#[cfg(test)]
111mod tests {
112 use super::*;
113
114 #[test]
115 fn returns_the_value_and_converts_to_the_reason() {
116 let rejected = Rejected::new(
117 Error::InvalidFrame(crate::FrameDefect::NullVideoData),
118 vec![1u8, 2],
119 );
120 assert_eq!(rejected.to_string(), rejected.error().to_string());
121 assert!(format!("{rejected:?}").contains("Vec<u8>"));
122
123 let (error, value) = rejected.into_parts();
124 assert!(matches!(error, Error::InvalidFrame(_)));
125 assert_eq!(value, [1, 2]);
126
127 fn through_question_mark() -> crate::Result<()> {
128 Err(Rejected::new(
129 Error::InvalidFrame(crate::FrameDefect::NullVideoData),
130 (),
131 ))?
132 }
133 assert!(matches!(
134 through_question_mark(),
135 Err(Error::InvalidFrame(_))
136 ));
137 }
138}