gstreamer/format/
mod.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3// rustdoc-stripper-ignore-next
4//! This module gathers GStreamer's formatted value concepts together.
5//!
6//! GStreamer uses formatted values to differentiate value units in some APIs.
7//! In C this is done by qualifying an integer value by a companion enum
8//! [`GstFormat`]. In Rust, most APIs can use a specific type for each format.
9//! Each format type embeds the actual value using the new type pattern.
10//!
11//! # Specific Formatted Values
12//!
13//! Examples of specific formatted values include [`ClockTime`], [`Buffers`], etc.
14//! These types represent both the quantity and the unit making it possible for Rust
15//! to perform runtime and, to a certain extent, compile time invariants enforcement.
16//!
17//! Specific formatted values are also guaranteed to always represent a valid value.
18//! For instance:
19//!
20//! - [`Percent`] only allows values in the integer range [0, 1_000_000] or
21//!   float range [0.0, 1.0].
22//! - [`ClockTime`] can use all `u64` values except `u64::MAX` which is reserved by
23//!   the C constant `GST_CLOCK_TIME_NONE`.
24//!
25//! ## Examples
26//!
27//! ### Querying the pipeline for a time position
28//!
29//! ```
30//! # use gstreamer as gst;
31//! # use gst::prelude::ElementExtManual;
32//! # gst::init();
33//! # let pipeline = gst::Pipeline::new();
34//! let res = pipeline.query_position::<gst::ClockTime>();
35//! ```
36//!
37//! ## Seeking to a specific time position
38//!
39//! ```
40//! # use gstreamer as gst;
41//! # use gst::{format::prelude::*, prelude::ElementExtManual};
42//! # gst::init();
43//! # let pipeline = gst::Pipeline::new();
44//! # let seek_flags = gst::SeekFlags::FLUSH | gst::SeekFlags::KEY_UNIT;
45//! let seek_pos = gst::ClockTime::from_seconds(10);
46//! let res = pipeline.seek_simple(seek_flags, seek_pos);
47//! ```
48//!
49//! ### Downcasting a `Segment` for specific formatted value use
50//!
51//! ```
52//! # use gstreamer as gst;
53//! # use gst::format::FormattedValue;
54//! # gst::init();
55//! # let segment = gst::FormattedSegment::<gst::ClockTime>::new().upcast();
56//! // Downcasting the generic `segment` for `gst::ClockTime` use.
57//! let time_segment = segment.downcast_ref::<gst::ClockTime>().expect("time segment");
58//! // Setters and getters conform to `gst::ClockTime`.
59//! // This is enforced at compilation time.
60//! let start = time_segment.start();
61//! assert_eq!(start.format(), gst::Format::Time);
62//! ```
63//!
64//! ### Building a specific formatted value
65//!
66//! ```
67//! # use gstreamer as gst;
68//! use gst::prelude::*;
69//! use gst::format::{Buffers, Bytes, ClockTime, Default, Percent};
70//!
71//! // Specific formatted values implement the faillible `try_from` constructor:
72//! let default = Default::try_from(42).unwrap();
73//! assert_eq!(*default, 42);
74//! assert_eq!(Default::try_from(42), Ok(default));
75//! assert_eq!(Default::try_from(42).ok(), Some(default));
76//!
77//! // `ClockTime` provides specific `const` constructors,
78//! // which can panic if the requested value is out of range.
79//! let time = ClockTime::from_nseconds(45_834_908_569_837);
80//! let time = ClockTime::from_seconds(20);
81//!
82//! // Other formatted values also come with (panicking) `const` constructors:
83//! let buffers_nb = Buffers::from_u64(512);
84//! let received = Bytes::from_u64(64);
85//! let quantity = Default::from_u64(42);
86//!
87//! // `Bytes` can be built from an `usize` too (not `const`):
88//! let sample_size = Bytes::from_usize([0u8; 4].len());
89//!
90//! // This can be convenient (not `const`):
91//! assert_eq!(
92//!     7.seconds() + 250.mseconds(),
93//!     ClockTime::from_nseconds(7_250_000_000),
94//! );
95//!
96//! // Those too (not `const`):
97//! assert_eq!(512.buffers(), Buffers::from_u64(512));
98//! assert_eq!(64.bytes(), Bytes::from_u64(64));
99//! assert_eq!(42.default_format(), Default::from_u64(42));
100//!
101//! // The `ZERO` and `NONE` constants can come in handy sometimes:
102//! assert_eq!(*Buffers::ZERO, 0);
103//! assert!(ClockTime::NONE.is_none());
104//!
105//! // Specific formatted values provide the constant `ONE` value:
106//! assert_eq!(*Buffers::ONE, 1);
107//!
108//! // `Bytes` also comes with usual multipliers (not `const`):
109//! assert_eq!(*(512.kibibytes()), 512 * 1024);
110//! assert_eq!(*(8.mebibytes()), 8 * 1024 * 1024);
111//! assert_eq!(*(4.gibibytes()), 4 * 1024 * 1024 * 1024);
112//!
113//! // ... and the matching constants:
114//! assert_eq!(512 * Bytes::KiB, 512.kibibytes());
115//!
116//! // `Percent` can be built from a percent integer value:
117//! let a_quarter = 25.percent();
118//! assert_eq!(a_quarter.percent(), 25);
119//! assert_eq!(a_quarter.ppm(), 250000);
120//! assert_eq!(a_quarter.ratio(), 0.25);
121//! // ... from a floating point ratio:
122//! let a_quarter_from_ratio = 0.25.percent_ratio();
123//! assert_eq!(a_quarter, a_quarter_from_ratio);
124//! // ... from a part per million integer value:
125//! let a_quarter_from_ppm = (25 * 10_000).ppm();
126//! assert_eq!(a_quarter, a_quarter_from_ppm);
127//! // ... `MAX` which represents 100%:
128//! assert_eq!(Percent::MAX / 4, a_quarter);
129//! // ... `ONE` which is 1%:
130//! assert_eq!(25 * Percent::ONE, a_quarter);
131//! // ... and `SCALE` which is 1% in ppm:
132//! assert_eq!(Percent::SCALE, 10_000.ppm());
133//! ```
134//!
135//! ### Displaying a formatted value
136//!
137//! Formatted values implement the [`Display`] trait which allows getting
138//! human readable representations.
139//!
140//! ```
141//! # use gstreamer as gst;
142//! # use gst::prelude::*;
143//! let time = 45_834_908_569_837.nseconds();
144//!
145//! assert_eq!(format!("{time}"), "12:43:54.908569837");
146//! assert_eq!(format!("{time:.0}"), "12:43:54");
147//!
148//! let percent = 0.1234.percent_ratio();
149//! assert_eq!(format!("{percent}"), "12.34 %");
150//! assert_eq!(format!("{percent:5.1}"), " 12.3 %");
151//! ```
152//!
153//! ## Some operations available on specific formatted values
154//!
155//! ```
156//! # use gstreamer as gst;
157//! # use gst::prelude::*;
158//! let cur_pos = gst::ClockTime::ZERO;
159//!
160//! // All four arithmetic operations can be used:
161//! let fwd = cur_pos + 2.seconds() / 3 - 5.mseconds();
162//!
163//! // Examples of operations which make sure not to overflow:
164//! let bwd = cur_pos.saturating_sub(2.seconds());
165//! let further = cur_pos.checked_mul(2).expect("Overflowed");
166//!
167//! // Specific formatted values can be compared:
168//! assert!(fwd > bwd);
169//! assert_ne!(fwd, cur_pos);
170//!
171//! # fn next() -> gst::ClockTime { gst::ClockTime::ZERO };
172//! // Use `gst::ClockTime::MAX` for the maximum valid value:
173//! let mut min_pos = gst::ClockTime::MAX;
174//! for _ in 0..4 {
175//!     min_pos = min_pos.min(next());
176//! }
177//!
178//! // And `gst::ClockTime::ZERO` for the minimum value:
179//! let mut max_pos = gst::ClockTime::ZERO;
180//! for _ in 0..4 {
181//!     max_pos = max_pos.max(next());
182//! }
183//!
184//! // Specific formatted values implement the `MulDiv` trait:
185//! # use gst::prelude::MulDiv;
186//! # let (samples, rate) = (1024u64, 48_000u64);
187//! let duration = samples
188//!     .mul_div_round(*gst::ClockTime::SECOND, rate)
189//!     .map(gst::ClockTime::from_nseconds);
190//! ```
191//!
192//! ## Types in operations
193//!
194//! Additions and substractions are available with the specific formatted value type
195//! as both left and right hand side operands.
196//!
197//! On the other hand, multiplications are only available with plain integers.
198//! This is because multiplying a `ClockTime` by a `ClockTime` would result in
199//! `ClockTime²`, whereas a `u64 * ClockTime` (or `ClockTime * u64`) still
200//! results in `ClockTime`.
201//!
202//! Divisions are available with both the specific formatted value and plain
203//! integers as right hand side operands. The difference is that
204//! `ClockTime / ClockTime` results in `u64` and `ClockTime / u64` results in
205//! `ClockTime`.
206//!
207//! # Optional specific formatted values
208//!
209//! Optional specific formatted values are represented as a standard Rust
210//! `Option<F>`. This departs from the C APIs which use a sentinel that must
211//! be checked in order to figure out whether the value is defined.
212//!
213//! Besides giving access to the usual `Option` features, this ensures the APIs
214//! enforce mandatory or optional variants whenever possible.
215//!
216//! Note: for each specific formatted value `F`, the constant `F::NONE` is defined
217//! as a shortcut for `Option::<F>::None`. For `gst::ClockTime`, this constant is
218//! equivalent to the C constant `GST_CLOCK_TIME_NONE`.
219//!
220//! ## Examples
221//!
222//! ### Building a seek `Event` with undefined `stop` time
223//!
224//! ```
225//! # use gstreamer as gst;
226//! # use gst::format::prelude::*;
227//! # gst::init();
228//! # let seek_flags = gst::SeekFlags::FLUSH | gst::SeekFlags::KEY_UNIT;
229//! let seek_evt = gst::event::Seek::new(
230//!     1.0f64,
231//!     seek_flags,
232//!     gst::SeekType::Set,
233//!     10.seconds(),         // start at 10s
234//!     gst::SeekType::Set,
235//!     gst::ClockTime::NONE, // stop is undefined
236//! );
237//! ```
238//!
239//! ### Displaying an optional formatted value
240//!
241//! Optional formatted values can take advantage of the [`Display`] implementation
242//! of the base specific formatted value. We have to workaround the [orphan rule]
243//! that forbids the implementation of [`Display`] for `Option<FormattedValue>`
244//! though. This is why displaying an optional formatted value necessitates calling
245//! [`display()`].
246//!
247//! ```
248//! # use gstreamer as gst;
249//! # use gst::prelude::*;
250//! let opt_time = Some(45_834_908_569_837.nseconds());
251//!
252//! assert_eq!(format!("{}", opt_time.display()), "12:43:54.908569837");
253//! assert_eq!(format!("{:.0}", opt_time.display()), "12:43:54");
254//! assert_eq!(format!("{:.0}", gst::ClockTime::NONE.display()), "--:--:--");
255//! ```
256//!
257//! ### Some operations available on optional formatted values
258//!
259//! ```
260//! # use gstreamer as gst;
261//! # use gst::prelude::*;
262//! let pts = Some(gst::ClockTime::ZERO);
263//! assert!(pts.is_some());
264//!
265//! // All four arithmetic operations can be used. Ex.:
266//! let fwd = pts.opt_add(2.seconds());
267//! // `pts` is defined, so `fwd` will contain the addition result in `Some`,
268//! assert!(fwd.is_some());
269//! // otherwise `fwd` would be `None`.
270//!
271//! // Examples of operations which make sure not to overflow:
272//! let bwd = pts.opt_saturating_sub(2.seconds());
273//! let further = pts.opt_checked_mul(2).expect("Overflowed");
274//!
275//! // Optional specific formatted values can be compared:
276//! assert_eq!(fwd.opt_gt(bwd), Some(true));
277//! assert_ne!(fwd, pts);
278//! assert_eq!(fwd.opt_min(bwd), bwd);
279//!
280//! // Optional specific formatted values operations also apply to non-optional values:
281//! assert_eq!(fwd.opt_lt(gst::ClockTime::SECOND), Some(false));
282//! assert_eq!(gst::ClockTime::SECOND.opt_lt(fwd), Some(true));
283//!
284//! // Comparing a defined values to an undefined value results in `None`:
285//! assert_eq!(bwd.opt_gt(gst::ClockTime::NONE), None);
286//! assert_eq!(gst::ClockTime::ZERO.opt_lt(gst::ClockTime::NONE), None);
287//! ```
288//!
289//! # Signed formatted values
290//!
291//! Some APIs can return a signed formatted value. See [`Segment::to_running_time_full`]
292//! for an example. In Rust, we use the [`Signed`] enum wrapper around the actual
293//! formatted value.
294//!
295//! For each signed specific formatted value `F`, the constants `F::MIN_SIGNED` and
296//! `F::MAX_SIGNED` represent the minimum and maximum signed values for `F`.
297//!
298//! ## Examples
299//!
300//! ### Handling a signed formatted value
301//!
302//! ```
303//! # use gstreamer as gst;
304//! # use gst::prelude::*;
305//! # gst::init();
306//! # let segment = gst::FormattedSegment::<gst::ClockTime>::new();
307//! use gst::Signed::*;
308//! match segment.to_running_time_full(2.seconds()) {
309//!     Some(Positive(pos_rtime)) => println!("positive rtime {pos_rtime}"),
310//!     Some(Negative(neg_rtime)) => println!("negative rtime {neg_rtime}"),
311//!     None => println!("undefined rtime"),
312//! }
313//! ```
314//!
315//! ### Converting a formatted value into a signed formatted value
316//!
317//! ```
318//! # use gstreamer as gst;
319//! # use gst::prelude::*;
320//! let step = 10.mseconds();
321//!
322//! let positive_step = step.into_positive();
323//! assert!(positive_step.is_positive());
324//!
325//! let negative_step = step.into_negative();
326//! assert!(negative_step.is_negative());
327//! ```
328//!
329//! ### Handling one sign only
330//!
331//! ```
332//! # use gstreamer as gst;
333//! # use gst::prelude::*;
334//! # struct NegativeError;
335//! let pos_step = 10.mseconds().into_positive();
336//! assert!(pos_step.is_positive());
337//!
338//! let abs_step_or_panic = pos_step.positive().expect("positive");
339//! let abs_step_or_zero = pos_step.positive().unwrap_or(gst::ClockTime::ZERO);
340//!
341//! let abs_step_or_err = pos_step.positive_or(NegativeError);
342//! let abs_step_or_else_err = pos_step.positive_or_else(|step| {
343//!     println!("{step} is negative");
344//!     NegativeError
345//! });
346//! ```
347//!
348//! ### Displaying a signed formatted value
349//!
350//! ```
351//! # use gstreamer as gst;
352//! # use gst::prelude::*;
353//! # gst::init();
354//! # let mut segment = gst::FormattedSegment::<gst::ClockTime>::new();
355//! # segment.set_start(10.seconds());
356//! let start = segment.start().unwrap();
357//! assert_eq!(format!("{start:.0}"), "0:00:10");
358//!
359//! let p_rtime = segment.to_running_time_full(20.seconds());
360//! // Use `display()` with optional signed values.
361//! assert_eq!(format!("{:.0}", p_rtime.display()), "+0:00:10");
362//!
363//! let p_rtime = segment.to_running_time_full(gst::ClockTime::ZERO);
364//! assert_eq!(format!("{:.0}", p_rtime.display()), "-0:00:10");
365//!
366//! let p_rtime = segment.to_running_time_full(gst::ClockTime::NONE);
367//! assert_eq!(format!("{:.0}", p_rtime.display()), "--:--:--");
368//! ```
369//!
370//! ## Some operations available for signed formatted values
371//!
372//! All the operations available for formatted values can be used with
373//! signed formatted values.
374//!
375//! ```
376//! # use gstreamer as gst;
377//! # use gst::prelude::*;
378//! let p_one_sec = gst::ClockTime::SECOND.into_positive();
379//! let p_two_sec = 2.seconds().into_positive();
380//! let n_one_sec = gst::ClockTime::SECOND.into_negative();
381//!
382//! assert_eq!(p_one_sec + p_one_sec, p_two_sec);
383//! assert_eq!(p_two_sec - p_one_sec, p_one_sec);
384//! assert_eq!(gst::ClockTime::ZERO - p_one_sec, n_one_sec);
385//! assert_eq!(p_one_sec * 2u64, p_two_sec);
386//! assert_eq!(n_one_sec * -1i64, p_one_sec);
387//! assert_eq!(p_two_sec / 2u64, p_one_sec);
388//! assert_eq!(p_two_sec / p_one_sec, 2);
389//!
390//! // Examples of operations which make sure not to overflow:
391//! assert_eq!(p_one_sec.saturating_sub(p_two_sec), n_one_sec);
392//! assert_eq!(p_one_sec.checked_mul(2), Some(p_two_sec));
393//!
394//! // Signed formatted values can be compared:
395//! assert!(p_one_sec > n_one_sec);
396//!
397//! # fn next() -> gst::Signed<gst::ClockTime> { gst::ClockTime::ZERO.into_positive() };
398//! // Use `gst::ClockTime::MAX_SIGNED` for the maximum valid signed value:
399//! let mut min_signed_pos = gst::ClockTime::MAX_SIGNED;
400//! for _ in 0..4 {
401//!     min_signed_pos = min_signed_pos.min(next());
402//! }
403//!
404//! // And `gst::ClockTime::MIN_SIGNED` for the minimum valid signed value:
405//! let mut max_signed_pos = gst::ClockTime::MIN_SIGNED;
406//! for _ in 0..4 {
407//!     max_signed_pos = max_signed_pos.max(next());
408//! }
409//!
410//! // Signed formatted values implement the `MulDiv` trait:
411//! # use gst::prelude::*;
412//! # let rate = 48_000u64;
413//! let samples = 1024.default_format().into_negative();
414//! let duration = samples
415//!     .mul_div_round(*gst::ClockTime::SECOND, rate)
416//!     .map(|signed_default| {
417//!         let signed_u64 = signed_default.into_inner_signed();
418//!         gst::Signed::<gst::ClockTime>::from_nseconds(signed_u64)
419//!     })
420//!     .unwrap();
421//! assert!(duration.is_negative());
422//! ```
423//!
424//! ### Some operations available for optional signed formatted values
425//!
426//! All the operations available for optional formatted values can be used
427//! with signed formatted values.
428//!
429//! ```
430//! # use gstreamer as gst;
431//! # use gst::prelude::*;
432//! let p_one_sec = 1.seconds().into_positive();
433//! let p_two_sec = 2.seconds().into_positive();
434//! let n_one_sec = 1.seconds().into_negative();
435//!
436//! // Signed `ClockTime` addition with optional and non-optional operands.
437//! assert_eq!(Some(p_one_sec).opt_add(p_one_sec), Some(p_two_sec));
438//! assert_eq!(p_two_sec.opt_add(Some(n_one_sec)), Some(p_one_sec));
439//!
440//! // This can also be used with unsigned formatted values.
441//! assert_eq!(Some(p_one_sec).opt_add(gst::ClockTime::SECOND), Some(p_two_sec));
442//!
443//! // Etc...
444//! ```
445//!
446//! # Generic Formatted Values
447//!
448//! Sometimes, generic code can't assume a specific format will be used. For such
449//! use cases, the [`GenericFormattedValue`] enum makes it possible to select
450//! the appropriate behaviour at runtime.
451//!
452//! Most variants embed an optional specific formatted value.
453//!
454//! ## Example
455//!
456//! ### Generic handling of the position from a `SegmentDone` event
457//!
458//! ```
459//! # use gstreamer as gst;
460//! # use gst::prelude::*;
461//! # gst::init();
462//! # let event = gst::event::SegmentDone::new(512.buffers());
463//! if let gst::EventView::SegmentDone(seg_done_evt) = event.view() {
464//!     use gst::GenericFormattedValue::*;
465//!     match seg_done_evt.get() {
466//!         Buffers(buffers) => println!("Segment done @ {}", buffers.display()),
467//!         Bytes(bytes) => println!("Segment done @ {}", bytes.display()),
468//!         Time(time) => println!("Segment done @ {}", time.display()),
469//!         other => println!("Unexpected format for Segment done position {other:?}"),
470//!     }
471//! }
472//! ```
473//!
474//! [`GstFormat`]: https://gstreamer.freedesktop.org/documentation/gstreamer/gstformat.html?gi-language=c
475//! [`ClockTime`]: struct.ClockTime.html
476//! [`Buffers`]: struct.Buffers.html
477//! [`Percent`]: struct.Percent.html
478//! [`Display`]: https://doc.rust-lang.org/std/fmt/trait.Display.html
479//! [`display()`]: ../prelude/trait.Displayable.html
480//! [orphan rule]: https://doc.rust-lang.org/book/ch10-02-traits.html?highlight=orphan#implementing-a-trait-on-a-type
481//! [`Segment::to_running_time_full`]: ../struct.FormattedSegment.html#method.to_running_time_full
482//! [`Signed`]: enum.Signed.html
483//! [`GenericFormattedValue`]: generic/enum.GenericFormattedValue.html
484
485use thiserror::Error;
486
487#[macro_use]
488mod macros;
489
490mod clock_time;
491pub use clock_time::*;
492#[cfg(feature = "serde")]
493mod clock_time_serde;
494
495mod compatible;
496pub use compatible::*;
497
498#[cfg(feature = "serde")]
499mod format_serde;
500
501mod generic;
502pub use generic::*;
503
504mod signed;
505pub use signed::*;
506
507mod specific;
508pub use specific::*;
509
510mod undefined;
511pub use undefined::*;
512
513pub mod prelude {
514    pub use super::{
515        BuffersFormatConstructor, BytesFormatConstructor, DefaultFormatConstructor, FormattedValue,
516        FormattedValueNoneBuilder, NoneSignedBuilder, OtherFormatConstructor,
517        PercentFormatFloatConstructor, PercentFormatIntegerConstructor, TimeFormatConstructor,
518        UndefinedFormatConstructor, UnsignedIntoSigned,
519    };
520}
521
522use crate::Format;
523
524#[derive(Clone, Copy, Debug, PartialEq, Eq, Error)]
525#[error("invalid formatted value format {:?}", .0)]
526pub struct FormattedValueError(Format);
527
528pub trait FormattedValue: Copy + Clone + Sized + Into<GenericFormattedValue> + 'static {
529    // rustdoc-stripper-ignore-next
530    /// Type which allows building a `FormattedValue` of this format from any raw value.
531    type FullRange: FormattedValueFullRange + From<Self>;
532
533    #[doc(alias = "get_default_format")]
534    fn default_format() -> Format;
535
536    #[doc(alias = "get_format")]
537    fn format(&self) -> Format;
538
539    // rustdoc-stripper-ignore-next
540    /// Returns `true` if this `FormattedValue` represents a defined value.
541    fn is_some(&self) -> bool;
542
543    // rustdoc-stripper-ignore-next
544    /// Returns `true` if this `FormattedValue` represents an undefined value.
545    fn is_none(&self) -> bool {
546        !self.is_some()
547    }
548
549    unsafe fn into_raw_value(self) -> i64;
550}
551
552// rustdoc-stripper-ignore-next
553/// A [`FormattedValue`] which can be built from any raw value.
554///
555/// # Examples:
556///
557/// - `GenericFormattedValue` is the `FormattedValueFullRange` type for `GenericFormattedValue`.
558/// - `Undefined` is the `FormattedValueFullRange` type for `Undefined`.
559/// - `Option<Percent>` is the `FormattedValueFullRange` type for `Percent`.
560pub trait FormattedValueFullRange: FormattedValue + TryFrom<GenericFormattedValue> {
561    unsafe fn from_raw(format: Format, value: i64) -> Self;
562}
563
564// rustdoc-stripper-ignore-next
565/// A trait implemented on the intrinsic type of a `FormattedValue`.
566///
567/// # Examples
568///
569/// - `GenericFormattedValue` is the intrinsic type for `GenericFormattedValue`.
570/// - `Undefined` is the intrinsic type for `Undefined`.
571/// - `Bytes` is the intrinsic type for `Option<Bytes>`.
572pub trait FormattedValueIntrinsic: FormattedValue {}
573
574pub trait FormattedValueNoneBuilder: FormattedValueFullRange {
575    // rustdoc-stripper-ignore-next
576    /// Returns the `None` value for `Self` as a `FullRange` if such a value can be represented.
577    ///
578    /// - For `SpecificFormattedValue`s, this results in `Option::<FormattedValueIntrinsic>::None`.
579    /// - For `GenericFormattedValue`, this can only be obtained using [`Self::none_for_format`]
580    ///   because the `None` is an inner value of some of the variants.
581    ///
582    /// # Panics
583    ///
584    /// Panics if `Self` is `GenericFormattedValue` in which case, the `Format` must be known.
585    fn none() -> Self;
586
587    // rustdoc-stripper-ignore-next
588    /// Returns the `None` value for `Self` if such a value can be represented.
589    ///
590    /// - For `SpecificFormattedValue`s, this is the same as `Self::none()`
591    ///   if the `format` matches the `SpecificFormattedValue`'s format.
592    /// - For `GenericFormattedValue` this is the variant for the specified `format`,
593    ///   initialized with `None` as a value, if the `format` can represent that value.
594    ///
595    /// # Panics
596    ///
597    /// Panics if `None` can't be represented by `Self` for `format` or by the requested
598    /// `GenericFormattedValue` variant.
599    #[track_caller]
600    #[inline]
601    fn none_for_format(format: Format) -> Self {
602        skip_assert_initialized!();
603        // This is the default impl. `GenericFormattedValue` must override.
604        if Self::default_format() != format {
605            panic!(
606                "Expected: {:?}, requested {format:?}",
607                Self::default_format()
608            );
609        }
610
611        Self::none()
612    }
613}
614
615use std::fmt;
616impl fmt::Display for Format {
617    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
618        match self {
619            Self::Undefined => f.write_str("undefined"),
620            Self::Default => f.write_str("default"),
621            Self::Bytes => f.write_str("bytes"),
622            Self::Time => f.write_str("time"),
623            Self::Buffers => f.write_str("buffers"),
624            Self::Percent => f.write_str("%"),
625            Self::__Unknown(format) => write!(f, "(format: {format})"),
626        }
627    }
628}
629
630#[cfg(test)]
631mod tests {
632    use super::*;
633    use crate::utils::Displayable;
634
635    fn with_compatible_formats<V1, V2>(
636        arg1: V1,
637        arg2: V2,
638    ) -> Result<V2::Original, FormattedValueError>
639    where
640        V1: FormattedValue,
641        V2: CompatibleFormattedValue<V1>,
642    {
643        skip_assert_initialized!();
644        arg2.try_into_checked(arg1)
645    }
646
647    #[test]
648    fn compatible() {
649        assert_eq!(
650            with_compatible_formats(ClockTime::ZERO, ClockTime::ZERO),
651            Ok(ClockTime::ZERO),
652        );
653        assert_eq!(
654            with_compatible_formats(ClockTime::ZERO, ClockTime::NONE),
655            Ok(ClockTime::NONE),
656        );
657        assert_eq!(
658            with_compatible_formats(ClockTime::NONE, ClockTime::ZERO),
659            Ok(ClockTime::ZERO),
660        );
661        assert_eq!(
662            with_compatible_formats(
663                ClockTime::ZERO,
664                GenericFormattedValue::Time(Some(ClockTime::ZERO)),
665            ),
666            Ok(GenericFormattedValue::Time(Some(ClockTime::ZERO))),
667        );
668        assert_eq!(
669            with_compatible_formats(
670                GenericFormattedValue::Time(Some(ClockTime::ZERO)),
671                ClockTime::NONE,
672            ),
673            Ok(ClockTime::NONE),
674        );
675    }
676
677    #[test]
678    fn incompatible() {
679        with_compatible_formats(
680            ClockTime::ZERO,
681            GenericFormattedValue::Buffers(Some(42.buffers())),
682        )
683        .unwrap_err();
684        with_compatible_formats(
685            GenericFormattedValue::Buffers(Some(42.buffers())),
686            ClockTime::NONE,
687        )
688        .unwrap_err();
689    }
690
691    fn with_compatible_explicit<T, V>(arg: V, f: Format) -> Result<V::Original, FormattedValueError>
692    where
693        T: FormattedValue,
694        V: CompatibleFormattedValue<T>,
695    {
696        skip_assert_initialized!();
697        arg.try_into_checked_explicit(f)
698    }
699
700    #[test]
701    fn compatible_explicit() {
702        assert_eq!(
703            with_compatible_explicit::<ClockTime, _>(ClockTime::ZERO, Format::Time),
704            Ok(ClockTime::ZERO),
705        );
706        assert_eq!(
707            with_compatible_explicit::<ClockTime, _>(ClockTime::NONE, Format::Time),
708            Ok(ClockTime::NONE),
709        );
710        assert_eq!(
711            with_compatible_explicit::<ClockTime, _>(ClockTime::ZERO, Format::Time),
712            Ok(ClockTime::ZERO),
713        );
714        assert_eq!(
715            with_compatible_explicit::<ClockTime, _>(
716                GenericFormattedValue::Time(None),
717                Format::Time
718            ),
719            Ok(GenericFormattedValue::Time(None)),
720        );
721        assert_eq!(
722            with_compatible_explicit::<GenericFormattedValue, _>(ClockTime::NONE, Format::Time),
723            Ok(ClockTime::NONE),
724        );
725    }
726
727    #[test]
728    fn incompatible_explicit() {
729        with_compatible_explicit::<Buffers, _>(GenericFormattedValue::Time(None), Format::Buffers)
730            .unwrap_err();
731        with_compatible_explicit::<GenericFormattedValue, _>(Buffers::ZERO, Format::Time)
732            .unwrap_err();
733        with_compatible_explicit::<GenericFormattedValue, _>(
734            GenericFormattedValue::Time(None),
735            Format::Buffers,
736        )
737        .unwrap_err();
738    }
739
740    #[test]
741    fn none_builder() {
742        let ct_none: Option<ClockTime> = Option::<ClockTime>::none();
743        assert!(ct_none.is_none());
744
745        let ct_none: Option<ClockTime> = Option::<ClockTime>::none_for_format(Format::Time);
746        assert!(ct_none.is_none());
747
748        let gen_ct_none: GenericFormattedValue =
749            GenericFormattedValue::none_for_format(Format::Time);
750        assert!(gen_ct_none.is_none());
751
752        assert!(ClockTime::ZERO.is_some());
753        assert!(!ClockTime::ZERO.is_none());
754    }
755
756    #[test]
757    #[should_panic]
758    fn none_for_inconsistent_format() {
759        let _ = Option::<ClockTime>::none_for_format(Format::Percent);
760    }
761
762    #[test]
763    #[should_panic]
764    fn none_for_unsupported_format() {
765        let _ = GenericFormattedValue::none_for_format(Format::Undefined);
766    }
767
768    #[test]
769    fn none_signed_builder() {
770        let ct_none: Option<Signed<ClockTime>> = Option::<ClockTime>::none_signed();
771        assert!(ct_none.is_none());
772
773        let ct_none: Option<Signed<ClockTime>> =
774            Option::<ClockTime>::none_signed_for_format(Format::Time);
775        assert!(ct_none.is_none());
776
777        let gen_ct_none: GenericSignedFormattedValue =
778            GenericFormattedValue::none_signed_for_format(Format::Time);
779        assert!(gen_ct_none.abs().is_none());
780    }
781
782    #[test]
783    fn signed_optional() {
784        let ct_1 = Some(ClockTime::SECOND);
785
786        let signed = ct_1.into_positive().unwrap();
787        assert_eq!(signed, Signed::Positive(ClockTime::SECOND));
788        assert!(signed.is_positive());
789        assert_eq!(signed.positive_or(()).unwrap(), ClockTime::SECOND);
790        assert_eq!(signed.positive_or_else(|_| ()).unwrap(), ClockTime::SECOND);
791        signed.negative_or(()).unwrap_err();
792        assert_eq!(
793            signed.negative_or_else(|val| val).unwrap_err(),
794            ClockTime::SECOND
795        );
796
797        let signed = ct_1.into_negative().unwrap();
798        assert_eq!(signed, Signed::Negative(ClockTime::SECOND));
799        assert!(signed.is_negative());
800        assert_eq!(signed.negative_or(()).unwrap(), ClockTime::SECOND);
801        assert_eq!(signed.negative_or_else(|_| ()).unwrap(), ClockTime::SECOND);
802        signed.positive_or(()).unwrap_err();
803        assert_eq!(
804            signed.positive_or_else(|val| val).unwrap_err(),
805            ClockTime::SECOND
806        );
807
808        let ct_none = ClockTime::NONE;
809        assert!(ct_none.into_positive().is_none());
810        assert!(ct_none.into_negative().is_none());
811    }
812
813    #[test]
814    fn signed_mandatory() {
815        let ct_1 = ClockTime::SECOND;
816
817        let signed = ct_1.into_positive();
818        assert_eq!(signed, Signed::Positive(ct_1));
819        assert!(signed.is_positive());
820        assert_eq!(signed.positive(), Some(ct_1));
821        assert!(!signed.is_negative());
822        assert!(signed.negative().is_none());
823        assert_eq!(signed.signum(), 1);
824
825        let signed = ct_1.into_negative();
826        assert_eq!(signed, Signed::Negative(ct_1));
827        assert!(signed.is_negative());
828        assert_eq!(signed.negative(), Some(ct_1));
829        assert!(!signed.is_positive());
830        assert!(signed.positive().is_none());
831        assert_eq!(signed.signum(), -1);
832
833        let signed = Default::ONE.into_positive();
834        assert_eq!(signed, Signed::Positive(Default::ONE));
835        assert!(signed.is_positive());
836        assert_eq!(signed.positive(), Some(Default::ONE));
837        assert!(!signed.is_negative());
838        assert!(signed.negative().is_none());
839        assert_eq!(signed.signum(), 1);
840
841        let signed = Default::ONE.into_negative();
842        assert_eq!(signed, Signed::Negative(Default::ONE));
843        assert!(signed.is_negative());
844        assert_eq!(signed.negative(), Some(Default::ONE));
845        assert!(!signed.is_positive());
846        assert!(signed.positive().is_none());
847        assert_eq!(signed.signum(), -1);
848
849        let ct_zero = ClockTime::ZERO;
850        let p_ct_zero = ct_zero.into_positive();
851        assert!(p_ct_zero.is_positive());
852        assert!(!p_ct_zero.is_negative());
853        assert_eq!(p_ct_zero.signum(), 0);
854        let n_ct_zero = ct_zero.into_negative();
855        assert!(n_ct_zero.is_negative());
856        assert!(!n_ct_zero.is_positive());
857        assert_eq!(n_ct_zero.signum(), 0);
858    }
859
860    #[test]
861    fn signed_generic() {
862        let ct_1 = GenericFormattedValue::Time(Some(ClockTime::SECOND));
863        assert!(ct_1.is_some());
864
865        let signed = ct_1.into_positive();
866        assert_eq!(
867            signed,
868            GenericSignedFormattedValue::Time(Some(Signed::Positive(ClockTime::SECOND))),
869        );
870        assert_eq!(signed.is_positive(), Some(true));
871        assert_eq!(signed.is_negative(), Some(false));
872        assert_eq!(signed.signum(), Some(1));
873
874        let signed = ct_1.into_negative();
875        assert_eq!(
876            signed,
877            GenericSignedFormattedValue::Time(Some(Signed::Negative(ClockTime::SECOND))),
878        );
879        assert_eq!(signed.is_negative(), Some(true));
880        assert_eq!(signed.is_positive(), Some(false));
881        assert_eq!(signed.signum(), Some(-1));
882
883        let ct_none = GenericFormattedValue::Time(ClockTime::NONE);
884        assert!(ct_none.is_none());
885
886        let signed = ct_none.into_positive();
887        assert_eq!(signed, GenericSignedFormattedValue::Time(None),);
888        assert!(signed.is_positive().is_none());
889        assert!(signed.is_negative().is_none());
890        assert!(signed.signum().is_none());
891
892        let signed = ct_none.into_negative();
893        assert_eq!(signed, GenericSignedFormattedValue::Time(None),);
894        assert!(signed.is_negative().is_none());
895        assert!(signed.is_positive().is_none());
896        assert!(signed.signum().is_none());
897
898        let ct_zero = GenericFormattedValue::Time(Some(ClockTime::ZERO));
899        assert!(ct_zero.is_some());
900
901        let signed = ct_zero.into_positive();
902        assert_eq!(
903            signed,
904            GenericSignedFormattedValue::Time(Some(Signed::Positive(ClockTime::ZERO))),
905        );
906        assert_eq!(signed.is_positive(), Some(true));
907        assert_eq!(signed.is_negative(), Some(false));
908        assert_eq!(signed.signum(), Some(0));
909    }
910
911    #[test]
912    fn signed_roundtrip() {
913        let ct_1 = Some(ClockTime::SECOND);
914        let raw_ct_1 = unsafe { ct_1.into_raw_value() };
915
916        let signed = unsafe { Option::<ClockTime>::from_raw(Format::Time, raw_ct_1) }
917            .into_signed(1)
918            .unwrap();
919        assert_eq!(signed, Signed::Positive(ClockTime::SECOND));
920        assert!(signed.is_positive());
921
922        let signed = unsafe { Option::<ClockTime>::from_raw(Format::Time, raw_ct_1) }
923            .into_signed(-1)
924            .unwrap();
925        assert_eq!(signed, Signed::Negative(ClockTime::SECOND));
926        assert!(signed.is_negative());
927
928        let ct_none = ClockTime::NONE;
929        let raw_ct_none = unsafe { ct_none.into_raw_value() };
930
931        let signed =
932            unsafe { Option::<ClockTime>::from_raw(Format::Time, raw_ct_none) }.into_signed(1);
933        assert!(signed.is_none());
934
935        let signed =
936            unsafe { Option::<ClockTime>::from_raw(Format::Time, raw_ct_none) }.into_signed(-1);
937        assert!(signed.is_none());
938    }
939
940    #[test]
941    fn display_new_types() {
942        let bytes = 42.bytes();
943        assert_eq!(&format!("{bytes}"), "42 bytes");
944        assert_eq!(&format!("{}", bytes.display()), "42 bytes");
945
946        assert_eq!(&format!("{}", Some(bytes).display()), "42 bytes");
947        assert_eq!(&format!("{}", Bytes::NONE.display()), "undef. bytes");
948
949        let gv_1 = GenericFormattedValue::Percent(Some(42.percent()));
950        assert_eq!(&format!("{gv_1}"), "42 %");
951        assert_eq!(
952            &format!("{}", GenericFormattedValue::Percent(None)),
953            "undef. %"
954        );
955
956        let percent = Percent::try_from(0.1234).unwrap();
957        assert_eq!(&format!("{percent}"), "12.34 %");
958        assert_eq!(&format!("{percent:5.1}"), " 12.3 %");
959
960        let other: Other = 42.try_into().unwrap();
961        assert_eq!(&format!("{other}"), "42");
962
963        let g_other = GenericFormattedValue::new(Format::__Unknown(128), 42);
964        assert_eq!(&format!("{g_other}"), "42 (format: 128)");
965        assert_eq!(&format!("{}", g_other.display()), "42 (format: 128)");
966
967        let g_other_none = GenericFormattedValue::Other(Format::__Unknown(128), None);
968        assert_eq!(&format!("{g_other_none}"), "undef. (format: 128)");
969        assert_eq!(
970            &format!("{}", g_other_none.display()),
971            "undef. (format: 128)"
972        );
973    }
974
975    #[test]
976    fn display_signed() {
977        let bytes_42 = 42.bytes();
978        let p_bytes = bytes_42.into_positive();
979        assert_eq!(&format!("{p_bytes}"), "+42 bytes");
980        assert_eq!(&format!("{}", p_bytes.display()), "+42 bytes");
981
982        let some_p_bytes = Some(p_bytes);
983        assert_eq!(&format!("{}", some_p_bytes.display()), "+42 bytes");
984
985        let p_some_bytes = Signed::Positive(Some(bytes_42));
986        assert_eq!(&format!("{}", p_some_bytes.display()), "+42 bytes");
987
988        let n_bytes = bytes_42.into_negative();
989        assert_eq!(&format!("{n_bytes}"), "-42 bytes");
990        assert_eq!(&format!("{}", n_bytes.display()), "-42 bytes");
991
992        let some_n_bytes = Some(n_bytes);
993        assert_eq!(&format!("{}", some_n_bytes.display()), "-42 bytes");
994
995        let n_some_bytes = Signed::Negative(Some(bytes_42));
996        assert_eq!(&format!("{}", n_some_bytes.display()), "-42 bytes");
997
998        let p_none_bytes = Signed::Positive(Bytes::NONE);
999        assert_eq!(&format!("{}", p_none_bytes.display()), "undef. bytes");
1000        let n_none_bytes = Signed::Negative(Bytes::NONE);
1001        assert_eq!(&format!("{}", n_none_bytes.display()), "undef. bytes");
1002
1003        let none_s_bytes = Option::<Signed<Bytes>>::None;
1004        assert_eq!(&format!("{}", none_s_bytes.display()), "undef. bytes");
1005
1006        let ct_1 = 45_834_908_569_837 * ClockTime::NSECOND;
1007        assert_eq!(&format!("{ct_1}"), "12:43:54.908569837");
1008        assert_eq!(&format!("{}", ct_1.display()), "12:43:54.908569837");
1009
1010        let g_ct_1 = GenericFormattedValue::Time(Some(ct_1));
1011        assert_eq!(&format!("{g_ct_1}"), "12:43:54.908569837");
1012        assert_eq!(&format!("{}", g_ct_1.display()), "12:43:54.908569837");
1013
1014        let p_g_ct1 = g_ct_1.into_positive();
1015        assert_eq!(&format!("{p_g_ct1}"), "+12:43:54.908569837");
1016        assert_eq!(&format!("{}", p_g_ct1.display()), "+12:43:54.908569837");
1017
1018        let n_g_ct1 = g_ct_1.into_negative();
1019        assert_eq!(&format!("{n_g_ct1}"), "-12:43:54.908569837");
1020        assert_eq!(&format!("{}", n_g_ct1.display()), "-12:43:54.908569837");
1021    }
1022}