libpulse_binding/time/
convert.rs

1// Copyright 2017 Lyndon Brown
2//
3// This file is part of the PulseAudio Rust language binding.
4//
5// Licensed under the MIT license or the Apache license (version 2.0), at your option. You may not
6// copy, modify, or distribute this file except in compliance with said license. You can find copies
7// of these licenses either in the LICENSE-MIT and LICENSE-APACHE files, or alternatively at
8// <http://opensource.org/licenses/MIT> and <http://www.apache.org/licenses/LICENSE-2.0>
9// respectively.
10//
11// Portions of documentation are copied from the LGPL 2.1+ licensed PulseAudio C headers on a
12// fair-use basis, as discussed in the overall project readme (available in the git repository).
13
14//! Implementation of conversions between the types.
15
16use super::*;
17
18// To `MicroSeconds`
19
20impl TryFrom<Duration> for MicroSeconds {
21    type Error = ();
22
23    #[inline]
24    fn try_from(t: Duration) -> Result<Self, Self::Error> {
25        let secs_as_micros = t.as_secs().checked_mul(MICROS_PER_SEC).ok_or(())?;
26        let total_micros = secs_as_micros.checked_add(t.subsec_micros() as u64).ok_or(())?;
27        Ok(MicroSeconds(total_micros))
28    }
29}
30
31impl From<Timeval> for MicroSeconds {
32    #[inline]
33    fn from(t: Timeval) -> Self {
34        MicroSeconds(unsafe { capi::pa_timeval_load(&t.0) })
35    }
36}
37
38// To `Duration`
39
40impl From<MicroSeconds> for Duration {
41    #[inline]
42    fn from(t: MicroSeconds) -> Self {
43        Duration::from_micros(t.0)
44    }
45}
46
47impl From<Timeval> for Duration {
48    #[inline]
49    fn from(t: Timeval) -> Self {
50        Duration::from_micros((MicroSeconds::from(t)).0)
51    }
52}
53
54// To `Timeval`
55
56impl From<MicroSeconds> for Timeval {
57    #[inline]
58    fn from(t: MicroSeconds) -> Self {
59        let secs = (t.0 / MICROS_PER_SEC) as super::timeval::TvSecs;
60        let micros = (t.0 % MICROS_PER_SEC) as super::timeval::TvUsecs;
61        Timeval::new(secs, micros)
62    }
63}
64
65impl From<Duration> for Timeval {
66    #[inline]
67    fn from(t: Duration) -> Self {
68        let secs = t.as_secs() as super::timeval::TvSecs;
69        let micros = t.subsec_micros() as super::timeval::TvUsecs;
70        Timeval::new(secs, micros)
71    }
72}
73
74#[test]
75fn tests() {
76    let micro = MicroSeconds(2_700_000);
77    let duration = Duration::from_micros(2_700_000);
78    let timeval = Timeval::new(2, 700_000);
79
80    assert_eq!(MicroSeconds::try_from(duration).unwrap(), micro);
81    assert_eq!(MicroSeconds::from(timeval), micro);
82
83    assert_eq!(Duration::from(micro), duration);
84    assert_eq!(Duration::from(timeval), duration);
85
86    assert_eq!(Timeval::from(micro), timeval);
87    assert_eq!(Timeval::from(duration), timeval);
88}