Skip to main content

gstreamer/format/
specific.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use glib::translate::{FromGlib, GlibNoneError, IntoGlib, OptionIntoGlib, TryFromGlib};
4
5use super::{
6    Format, FormattedValue, FormattedValueError, FormattedValueFullRange, FormattedValueIntrinsic,
7    FormattedValueNoneBuilder, GenericFormattedValue,
8};
9use crate::ffi;
10
11pub trait SpecificFormattedValue: FormattedValue {}
12
13pub trait SpecificFormattedValueFullRange: FormattedValueFullRange {}
14
15// rustdoc-stripper-ignore-next
16/// A trait implemented on the intrinsic type of a `SpecificFormattedValue`.
17///
18/// # Examples
19///
20/// - `Undefined` is the intrinsic type for `Undefined`.
21/// - `Bytes` is the intrinsic type for `Option<Bytes>`.
22pub trait SpecificFormattedValueIntrinsic: TryFromGlib<i64> + FormattedValueIntrinsic {}
23
24// rustdoc-stripper-ignore-next
25/// A Buffer quantity
26///
27/// Some functions enforce format specific quantities. This type can be used when
28/// Buffer counts are expected. It comes with functions to perform computations without the
29/// need to retrieve the inner integer.
30///
31/// # Examples
32///
33/// ```rust
34/// # use gstreamer::{prelude::*, format::Buffers};
35/// // Regular constructors (can be used in `const` contexts)
36/// const FORTY_TWO_BUFFERS: Buffers = Buffers::from_u64(42);
37/// let two_buffers = Buffers::from_u64(2);
38///
39/// // All four arithmetic operations
40/// let limit = (FORTY_TWO_BUFFERS + two_buffers) * 2 / 3;
41///
42/// // Comparisons
43/// if limit > Buffers::ZERO {
44///     println!("Greater");
45/// }
46/// ```
47///
48/// See [the documentation of the `format` module] for more examples.
49///
50/// [the documentation of the `format` module]: ./index.html
51#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Debug, Default)]
52pub struct Buffers(u64);
53impl Buffers {
54    #[doc(alias = "GST_BUFFER_OFFSET_NONE")]
55    pub const OFFSET_NONE: u64 = ffi::GST_BUFFER_OFFSET_NONE;
56    pub const MAX: Self = Self(Self::OFFSET_NONE - 1);
57}
58
59impl Buffers {
60    // rustdoc-stripper-ignore-next
61    /// Builds a new `Buffers` formatted value with the provided buffers count.
62    ///
63    /// # Panics
64    ///
65    /// Panics if the provided count equals `u64::MAX`,
66    /// which is reserved for `None` in C.
67    #[track_caller]
68    #[inline]
69    pub const fn from_u64(buffers: u64) -> Self {
70        if buffers == ffi::GST_BUFFER_OFFSET_NONE {
71            panic!("`Buffers` value out of range");
72        }
73
74        Buffers(buffers)
75    }
76
77    // rustdoc-stripper-ignore-next
78    /// Builds a new `Buffers` formatted value with the provided buffers count.
79    ///
80    /// # Panics
81    ///
82    /// Panics if the provided count equals `u64::MAX`,
83    /// which is reserved for `None` in C.
84    #[track_caller]
85    #[inline]
86    pub fn from_usize(buffers: usize) -> Self {
87        Buffers::from_u64(buffers.try_into().unwrap())
88    }
89}
90
91impl_common_ops_for_newtype_uint!(Buffers, u64);
92impl_signed_div_mul!(Buffers, u64);
93impl_signed_int_into_signed!(Buffers, u64);
94impl_format_value_traits!(Buffers, Buffers, Buffers, u64);
95option_glib_newtype_from_to!(Buffers, Buffers::OFFSET_NONE);
96glib_newtype_display!(Buffers, DisplayableOptionBuffers, Format::Buffers);
97
98impl TryFrom<Buffers> for usize {
99    type Error = std::num::TryFromIntError;
100
101    fn try_from(value: Buffers) -> Result<Self, Self::Error> {
102        value.0.try_into()
103    }
104}
105
106// FIXME `functions in traits cannot be const` (rustc 1.64.0)
107// rustdoc-stripper-ignore-next
108/// `Buffers` formatted value constructor trait.
109pub trait BuffersFormatConstructor {
110    // rustdoc-stripper-ignore-next
111    /// Builds a `Buffers` formatted value from `self`.
112    fn buffers(self) -> Buffers;
113}
114
115impl BuffersFormatConstructor for u64 {
116    #[track_caller]
117    #[inline]
118    fn buffers(self) -> Buffers {
119        Buffers::from_u64(self)
120    }
121}
122
123// rustdoc-stripper-ignore-next
124/// A Byte quantity
125///
126/// Some functions enforce format specific quantities. This type can be used when
127/// Bytes are expected. It comes with functions to perform computations without the
128/// need to retrieve the inner integer.
129///
130/// # Examples
131///
132/// ```rust
133/// # use gstreamer::{prelude::*, format::Bytes};
134/// // Regular constructors (can be used in `const` contexts)
135/// const FORTY_TWO_BYTES: Bytes = Bytes::from_bytes(42);
136/// const TWO_K: Bytes = Bytes::from_kibibytes(2);
137/// let three_m = Bytes::from_mebibytes(3);
138/// let four_g = Bytes::from_gibibytes(4);
139///
140/// // Convenience constructors (not `const`)
141/// let forty_two_bytes = 42.bytes();
142/// let two_k = 2.kibibytes();
143/// let three_m = 3.mebibytes();
144/// let four_g = 4.gibibytes();
145///
146/// // All four arithmetic operations
147/// let limit = (2.kibibytes() + 512.bytes()) * 2 / 3;
148///
149/// // Comparisons
150/// if limit > Bytes::KiB {
151///     println!("Greater");
152/// }
153/// ```
154///
155/// See [the documentation of the `format` module] for more examples.
156///
157/// [the documentation of the `format` module]: ./index.html
158#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Debug, Default)]
159pub struct Bytes(u64);
160impl Bytes {
161    // rustdoc-stripper-ignore-next
162    /// 1 kibibyte (1024).
163    #[allow(non_upper_case_globals)]
164    pub const KiB: Self = Self(1024);
165    // rustdoc-stripper-ignore-next
166    /// 1 mebibyte (1024 * 1024).
167    #[allow(non_upper_case_globals)]
168    pub const MiB: Self = Self(1024 * 1024);
169    // rustdoc-stripper-ignore-next
170    /// 1 gibibyte (1024 * 1024 * 1024).
171    #[allow(non_upper_case_globals)]
172    pub const GiB: Self = Self(1024 * 1024 * 1024);
173    pub const MAX: Self = Self(u64::MAX - 1);
174}
175
176impl Bytes {
177    // rustdoc-stripper-ignore-next
178    /// Builds a new `Bytes` formatted value with the provided bytes count.
179    ///
180    /// # Panics
181    ///
182    /// Panics if the provided count equals `u64::MAX`,
183    /// which is reserved for `None` in C.
184    #[track_caller]
185    #[inline]
186    pub const fn from_bytes(bytes: u64) -> Self {
187        Bytes::from_u64(bytes)
188    }
189
190    // rustdoc-stripper-ignore-next
191    /// Builds a new `Bytes` formatted value with the provided kibibytes (1024) count.
192    ///
193    /// # Panics
194    ///
195    /// Panics if the resulting count equals `u64::MAX`,
196    /// which is reserved for `None` in C.
197    #[track_caller]
198    #[inline]
199    pub const fn from_kibibytes(kibibytes: u64) -> Self {
200        Bytes::from_u64(kibibytes * 1024)
201    }
202
203    // rustdoc-stripper-ignore-next
204    /// Builds a new `Bytes` formatted value with the provided mebibytes (1024 * 1024) count.
205    ///
206    /// # Panics
207    ///
208    /// Panics if the resulting count equals `u64::MAX`,
209    /// which is reserved for `None` in C.
210    #[track_caller]
211    #[inline]
212    pub const fn from_mebibytes(mebibytes: u64) -> Self {
213        Bytes::from_u64(mebibytes * 1024 * 1024)
214    }
215
216    // rustdoc-stripper-ignore-next
217    /// Builds a new `Bytes` formatted value with the provided gibibytes (1024 * 1024 * 1024) count.
218    ///
219    /// # Panics
220    ///
221    /// Panics if the resulting count equals `u64::MAX`,
222    /// which is reserved for `None` in C.
223    #[track_caller]
224    #[inline]
225    pub const fn from_gibibytes(gibibytes: u64) -> Self {
226        Bytes::from_u64(gibibytes * 1024 * 1024 * 1024)
227    }
228
229    // rustdoc-stripper-ignore-next
230    /// Builds a new `Bytes` formatted value with the provided bytes count.
231    ///
232    /// # Panics
233    ///
234    /// Panics if the provided count equals `u64::MAX`,
235    /// which is reserved for `None` in C.
236    #[track_caller]
237    #[inline]
238    pub const fn from_u64(bytes: u64) -> Self {
239        if bytes == u64::MAX {
240            panic!("`Bytes` value out of range");
241        }
242
243        Bytes(bytes)
244    }
245
246    // rustdoc-stripper-ignore-next
247    /// Builds a new `Bytes` formatted value with the provided bytes count.
248    ///
249    /// # Panics
250    ///
251    /// Panics if the provided count equals `u64::MAX`,
252    /// which is reserved for `None` in C.
253    #[track_caller]
254    #[inline]
255    pub fn from_usize(bytes: usize) -> Self {
256        // FIXME can't use `try_into` in `const` (rustc 1.64.0)
257        Bytes::from_u64(bytes.try_into().unwrap())
258    }
259}
260
261impl_common_ops_for_newtype_uint!(Bytes, u64);
262impl_signed_div_mul!(Bytes, u64);
263impl_signed_int_into_signed!(Bytes, u64);
264impl_format_value_traits!(Bytes, Bytes, Bytes, u64);
265option_glib_newtype_from_to!(Bytes, u64::MAX);
266glib_newtype_display!(Bytes, DisplayableOptionBytes, Format::Bytes);
267
268impl TryFrom<Bytes> for usize {
269    type Error = std::num::TryFromIntError;
270
271    fn try_from(value: Bytes) -> Result<Self, Self::Error> {
272        value.0.try_into()
273    }
274}
275
276// FIXME `functions in traits cannot be const` (rustc 1.64.0)
277// rustdoc-stripper-ignore-next
278/// `Bytes` formatted value constructor trait.
279///
280/// These constructors use the [unambiguous conventions] for byte units.
281///
282/// [unambiguous conventions]: https://en.wikipedia.org/wiki/Byte#Multiple-byte_units
283pub trait BytesFormatConstructor {
284    // rustdoc-stripper-ignore-next
285    /// Builds a `Bytes` formatted value from `self`.
286    fn bytes(self) -> Bytes;
287
288    // rustdoc-stripper-ignore-next
289    /// Builds a `Bytes` formatted value from `self` interpreted as kibibytes (1024).
290    fn kibibytes(self) -> Bytes;
291
292    // rustdoc-stripper-ignore-next
293    /// Builds a `Bytes` formatted value from `self` interpreted as mebibytes (1024²).
294    fn mebibytes(self) -> Bytes;
295
296    // rustdoc-stripper-ignore-next
297    /// Builds a `Bytes` formatted value from `self` interpreted as gibibytes (1024³).
298    fn gibibytes(self) -> Bytes;
299}
300
301impl BytesFormatConstructor for u64 {
302    #[track_caller]
303    #[inline]
304    fn bytes(self) -> Bytes {
305        Bytes::from_u64(self)
306    }
307
308    #[track_caller]
309    #[inline]
310    fn kibibytes(self) -> Bytes {
311        Bytes::from_u64(self * 1024)
312    }
313
314    #[track_caller]
315    #[inline]
316    fn mebibytes(self) -> Bytes {
317        Bytes::from_u64(self * 1024 * 1024)
318    }
319
320    #[track_caller]
321    #[inline]
322    fn gibibytes(self) -> Bytes {
323        Bytes::from_u64(self * 1024 * 1024 * 1024)
324    }
325}
326
327// rustdoc-stripper-ignore-next
328/// A unit-less quantity
329///
330/// Some functions enforce format specific quantities. This type can be used when
331/// a `Default` format is expected. It comes with functions to perform computations without the
332/// need to retrieve the inner integer.
333///
334/// # Examples
335///
336/// ```rust
337/// # use gstreamer::{prelude::*, format::Default};
338/// // Regular constructors (can be used in `const` contexts)
339/// const FORTY_TWO: Default = Default::from_u64(42);
340/// let two = Default::from_u64(2);
341///
342/// // All four arithmetic operations
343/// let limit = (FORTY_TWO + two) * 2 / 3;
344///
345/// // Comparisons
346/// if limit > Default::ZERO {
347///     println!("Greater");
348/// }
349/// ```
350///
351/// See [the documentation of the `format` module] for more examples.
352///
353/// [the documentation of the `format` module]: ./index.html
354#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Debug, Default)]
355pub struct Default(u64);
356impl Default {
357    pub const MAX: Self = Self(u64::MAX - 1);
358}
359
360impl Default {
361    // rustdoc-stripper-ignore-next
362    /// Builds a new `Default` formatted value with the provided quantity.
363    ///
364    /// # Panics
365    ///
366    /// Panics if the provided quantity equals `u64::MAX`,
367    /// which is reserved for `None` in C.
368    #[track_caller]
369    #[inline]
370    pub const fn from_u64(quantity: u64) -> Self {
371        if quantity == u64::MAX {
372            panic!("`Default` value out of range");
373        }
374
375        Default(quantity)
376    }
377
378    // rustdoc-stripper-ignore-next
379    /// Builds a new `Default` formatted value with the provided quantity.
380    ///
381    /// # Panics
382    ///
383    /// Panics if the provided quantity equals `u64::MAX`,
384    /// which is reserved for `None` in C.
385    #[track_caller]
386    #[inline]
387    pub fn from_usize(quantity: usize) -> Self {
388        // FIXME can't use `try_into` in `const` (rustc 1.64.0)
389        Default::from_u64(quantity.try_into().unwrap())
390    }
391}
392
393impl_common_ops_for_newtype_uint!(Default, u64);
394impl_signed_div_mul!(Default, u64);
395impl_signed_int_into_signed!(Default, u64);
396impl_format_value_traits!(Default, Default, Default, u64);
397option_glib_newtype_from_to!(Default, u64::MAX);
398glib_newtype_display!(Default, DisplayableOptionDefault, Format::Default);
399
400impl TryFrom<Default> for usize {
401    type Error = std::num::TryFromIntError;
402
403    fn try_from(value: Default) -> Result<Self, Self::Error> {
404        value.0.try_into()
405    }
406}
407
408// FIXME `functions in traits cannot be const` (rustc 1.64.0)
409// rustdoc-stripper-ignore-next
410/// `Default` formatted value constructor trait.
411pub trait DefaultFormatConstructor {
412    // rustdoc-stripper-ignore-next
413    /// Builds a `Default` formatted value from `self`.
414    fn default_format(self) -> Default;
415}
416
417impl DefaultFormatConstructor for u64 {
418    #[track_caller]
419    #[inline]
420    fn default_format(self) -> Default {
421        Default::from_u64(self)
422    }
423}
424
425pub type Time = super::ClockTime;
426
427// rustdoc-stripper-ignore-next
428/// A Percent quantity
429///
430/// Some functions enforce format specific quantities. This type can be used when
431/// a Percent is expected. It comes with functions to perform computations without the
432/// need to retrieve the inner integer.
433///
434/// # Examples
435///
436/// ```rust
437/// # use gstreamer::{prelude::*, format::Percent};
438/// // Regular constructors (can be used in `const` contexts)
439/// const FORTY_TWO_PERCENT: Percent = Percent::from_percent(42);
440/// const TWO_PPM: Percent = Percent::from_ppm(2);
441/// let half = Percent::from_ratio(0.5);
442///
443/// // All four arithmetic operations
444/// let limit = (FORTY_TWO_PERCENT + TWO_PPM) * 2 / 3;
445///
446/// // Comparisons
447/// if limit > half {
448///     println!("Greater");
449/// }
450/// ```
451///
452/// See [the documentation of the `format` module] for more examples.
453///
454/// [the documentation of the `format` module]: ./index.html
455#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy, Debug, Default)]
456pub struct Percent(u32);
457impl Percent {
458    #[doc(alias = "GST_FORMAT_PERCENT_MAX")]
459    pub const MAX: Self = Self(ffi::GST_FORMAT_PERCENT_MAX as u32);
460    #[doc(alias = "GST_FORMAT_PERCENT_SCALE")]
461    pub const SCALE: Self = Self(ffi::GST_FORMAT_PERCENT_SCALE as u32);
462
463    // rustdoc-stripper-ignore-next
464    /// Builds a new `Percent` with the provided percent value.
465    ///
466    /// # Panics
467    ///
468    /// Panics if the provided value is larger than 100.
469    #[track_caller]
470    #[inline]
471    pub const fn from_percent(percent: u32) -> Self {
472        if percent > 100 {
473            panic!("`Percent` value out of range");
474        }
475
476        Percent(ffi::GST_FORMAT_PERCENT_SCALE as u32 * percent)
477    }
478
479    // rustdoc-stripper-ignore-next
480    /// Builds a new `Percent` with the provided parts per million value.
481    ///
482    /// # Panics
483    ///
484    /// Panics if the provided value is larger than [`Self::MAX`].
485    #[track_caller]
486    #[inline]
487    pub const fn from_ppm(ppm: u32) -> Self {
488        if ppm > ffi::GST_FORMAT_PERCENT_MAX as u32 {
489            panic!("`Percent` ppm value out of range");
490        }
491
492        Percent(ppm)
493    }
494
495    // rustdoc-stripper-ignore-next
496    /// Builds a new `Percent` with the provided ratio.
497    ///
498    /// # Panics
499    ///
500    /// Panics if the provided radio is out of the range [0.0, 1.0].
501    #[track_caller]
502    #[inline]
503    pub fn from_ratio(ratio: f32) -> Self {
504        // FIXME floating point arithmetic is not allowed in constant functions (rustc 1.64.0)
505        Percent::try_from(ratio).expect("`Percent` ratio out of range")
506    }
507
508    // rustdoc-stripper-ignore-next
509    /// The percent value in the range [0, 100].
510    #[track_caller]
511    #[inline]
512    pub fn percent(&self) -> u32 {
513        self.0 / ffi::GST_FORMAT_PERCENT_SCALE as u32
514    }
515
516    // rustdoc-stripper-ignore-next
517    /// The per million value in the range [0, 1_000_000].
518    #[track_caller]
519    #[inline]
520    pub fn ppm(&self) -> u32 {
521        self.0
522    }
523
524    // rustdoc-stripper-ignore-next
525    /// The ratio value in the range [0.0, 1.0].
526    #[track_caller]
527    #[inline]
528    pub fn ratio(&self) -> f32 {
529        self.0 as f32 / ffi::GST_FORMAT_PERCENT_MAX as f32
530    }
531}
532
533impl_common_ops_for_newtype_uint!(Percent, u32, one: ffi::GST_FORMAT_PERCENT_SCALE as u32);
534impl_signed_div_mul!(Percent, u32);
535impl_signed_int_into_signed!(Percent, u32);
536
537impl FormattedValue for Option<Percent> {
538    type FullRange = Option<Percent>;
539
540    #[inline]
541    fn default_format() -> Format {
542        Format::Percent
543    }
544
545    #[inline]
546    fn format(&self) -> Format {
547        Format::Percent
548    }
549
550    #[inline]
551    fn is_some(&self) -> bool {
552        Option::is_some(self)
553    }
554
555    #[inline]
556    unsafe fn into_raw_value(self) -> i64 {
557        self.map_or(-1, |v| v.0 as i64)
558    }
559}
560
561impl FormattedValueFullRange for Option<Percent> {
562    #[inline]
563    unsafe fn from_raw(format: Format, value: i64) -> Self {
564        unsafe {
565            debug_assert_eq!(format, Format::Percent);
566            Percent::try_from_glib(value).ok()
567        }
568    }
569}
570
571impl From<Option<Percent>> for GenericFormattedValue {
572    #[inline]
573    fn from(v: Option<Percent>) -> Self {
574        skip_assert_initialized!();
575        GenericFormattedValue::Percent(v)
576    }
577}
578
579impl From<Percent> for GenericFormattedValue {
580    #[inline]
581    fn from(v: Percent) -> Self {
582        skip_assert_initialized!();
583        GenericFormattedValue::Percent(Some(v))
584    }
585}
586
587impl FormattedValue for Percent {
588    type FullRange = Option<Percent>;
589
590    #[inline]
591    fn default_format() -> Format {
592        Format::Percent
593    }
594
595    #[inline]
596    fn format(&self) -> Format {
597        Format::Percent
598    }
599
600    #[inline]
601    fn is_some(&self) -> bool {
602        true
603    }
604
605    #[inline]
606    unsafe fn into_raw_value(self) -> i64 {
607        self.0 as i64
608    }
609}
610
611impl TryFrom<u64> for Percent {
612    type Error = GlibNoneError;
613
614    #[inline]
615    fn try_from(v: u64) -> Result<Percent, GlibNoneError> {
616        skip_assert_initialized!();
617        unsafe { Self::try_from_glib(v as i64) }
618    }
619}
620
621impl TryFromGlib<i64> for Percent {
622    type Error = GlibNoneError;
623    #[inline]
624    unsafe fn try_from_glib(value: i64) -> Result<Self, Self::Error> {
625        skip_assert_initialized!();
626        if value < 0 || value > ffi::GST_FORMAT_PERCENT_MAX {
627            Err(GlibNoneError)
628        } else {
629            Ok(Percent(value as u32))
630        }
631    }
632}
633
634impl TryFrom<u32> for Percent {
635    type Error = FormattedValueError;
636
637    #[inline]
638    fn try_from(value: u32) -> Result<Self, Self::Error> {
639        skip_assert_initialized!();
640        if value > ffi::GST_FORMAT_PERCENT_MAX as u32 {
641            Err(FormattedValueError(Format::Percent))
642        } else {
643            Ok(Percent(value))
644        }
645    }
646}
647
648impl TryFrom<GenericFormattedValue> for Option<Percent> {
649    type Error = FormattedValueError;
650
651    #[inline]
652    fn try_from(v: GenericFormattedValue) -> Result<Option<Percent>, Self::Error> {
653        skip_assert_initialized!();
654        if let GenericFormattedValue::Percent(v) = v {
655            Ok(v)
656        } else {
657            Err(FormattedValueError(v.format()))
658        }
659    }
660}
661
662impl FormattedValueIntrinsic for Percent {}
663impl SpecificFormattedValue for Option<Percent> {}
664impl SpecificFormattedValueFullRange for Option<Percent> {}
665impl SpecificFormattedValueIntrinsic for Percent {}
666impl FormattedValueNoneBuilder for Option<Percent> {
667    #[inline]
668    fn none() -> Option<Percent> {
669        None
670    }
671}
672
673#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
674#[error("value out of range")]
675pub struct TryPercentFromFloatError(());
676
677impl TryFrom<f64> for Percent {
678    type Error = TryPercentFromFloatError;
679
680    #[inline]
681    fn try_from(v: f64) -> Result<Self, Self::Error> {
682        skip_assert_initialized!();
683        if v < 0.0 || v > 1.0 {
684            Err(TryPercentFromFloatError(()))
685        } else {
686            Ok(Percent(
687                (v * ffi::GST_FORMAT_PERCENT_MAX as f64).round() as u32
688            ))
689        }
690    }
691}
692
693impl TryFrom<f32> for Percent {
694    type Error = TryPercentFromFloatError;
695
696    #[inline]
697    fn try_from(v: f32) -> Result<Self, Self::Error> {
698        skip_assert_initialized!();
699        if v < 0.0 || v > 1.0 {
700            Err(TryPercentFromFloatError(()))
701        } else {
702            Ok(Percent(
703                (v * ffi::GST_FORMAT_PERCENT_MAX as f32).round() as u32
704            ))
705        }
706    }
707}
708
709// FIXME `functions in traits cannot be const` (rustc 1.64.0)
710// rustdoc-stripper-ignore-next
711/// `Percent` formatted value from integer constructor trait.
712pub trait PercentFormatIntegerConstructor {
713    // rustdoc-stripper-ignore-next
714    /// Builds a `Percent` formatted value from `self` interpreted as a percent.
715    fn percent(self) -> Percent;
716
717    // rustdoc-stripper-ignore-next
718    /// Builds a `Percent` formatted value from `self` interpreted as parts per million.
719    fn ppm(self) -> Percent;
720}
721
722impl PercentFormatIntegerConstructor for u32 {
723    #[track_caller]
724    #[inline]
725    fn percent(self) -> Percent {
726        Percent::from_percent(self)
727    }
728
729    #[track_caller]
730    #[inline]
731    fn ppm(self) -> Percent {
732        Percent::from_ppm(self)
733    }
734}
735
736// FIXME `functions in traits cannot be const` (rustc 1.64.0)
737// rustdoc-stripper-ignore-next
738/// `Percent` formatted value from float constructor trait.
739pub trait PercentFormatFloatConstructor {
740    // rustdoc-stripper-ignore-next
741    /// Builds a `Percent` formatted value from `self` interpreted as a ratio.
742    fn percent_ratio(self) -> Percent;
743}
744
745impl PercentFormatFloatConstructor for f32 {
746    #[track_caller]
747    #[inline]
748    fn percent_ratio(self) -> Percent {
749        Percent::try_from(self).unwrap()
750    }
751}
752
753impl std::fmt::Display for Percent {
754    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
755        std::fmt::Display::fmt(&(self.0 as f32 / (*Percent::SCALE) as f32), f)?;
756        f.write_str(" %")
757    }
758}
759
760impl crate::utils::Displayable for Percent {
761    type DisplayImpl = Self;
762    fn display(self) -> Self {
763        self
764    }
765}
766pub struct DisplayableOptionPercent(Option<Percent>);
767
768impl std::fmt::Display for DisplayableOptionPercent {
769    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
770        if let Some(val) = self.0.as_ref() {
771            std::fmt::Display::fmt(val, f)
772        } else {
773            f.write_str("undef. %")
774        }
775    }
776}
777
778impl crate::utils::Displayable for Option<Percent> {
779    type DisplayImpl = DisplayableOptionPercent;
780    fn display(self) -> Self::DisplayImpl {
781        DisplayableOptionPercent(self)
782    }
783}