summaryrefslogtreecommitdiff
path: root/src/sys/time.rs
blob: 8340c9d0a4ff667bb402fa474357da86073713b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
use std::{cmp, fmt, ops};
use libc::{time_t, suseconds_t, timeval};

#[repr(C)]
#[derive(Clone, Copy)]
pub struct TimeVal(timeval);

const MICROS_PER_SEC: i64 = 1_000_000;
const SECS_PER_MINUTE: i64 = 60;
const SECS_PER_HOUR: i64 = 3600;

#[cfg(target_pointer_width = "64")]
const MAX_SECONDS: i64 = (::std::i64::MAX / MICROS_PER_SEC) - 1;

#[cfg(target_pointer_width = "32")]
const MAX_SECONDS: i64 = ::std::isize::MAX as i64;

const MIN_SECONDS: i64 = -MAX_SECONDS;

impl fmt::Debug for TimeVal {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        fmt.debug_struct("TimeVal")
            .field("tv_sec", &self.tv_sec())
            .field("tv_usec", &self.tv_usec())
            .finish()
    }
}

impl cmp::PartialEq for TimeVal {
    // The implementation of cmp is simplified by assuming that the struct is
    // normalized.  That is, tv_usec must always be within [0, 1_000_000)
    fn eq(&self, other: &TimeVal) -> bool {
        self.tv_sec() == other.tv_sec() && self.tv_usec() == other.tv_usec()
    }
}

impl cmp::Eq for TimeVal {}

impl cmp::Ord for TimeVal {
    // The implementation of cmp is simplified by assuming that the struct is
    // normalized.  That is, tv_usec must always be within [0, 1_000_000)
    fn cmp(&self, other: &TimeVal) -> cmp::Ordering {
        if self.tv_sec() == other.tv_sec() {
            self.tv_sec().cmp(&other.tv_sec())
        } else {
            self.tv_usec().cmp(&other.tv_usec())
        }
    }
}

impl cmp::PartialOrd for TimeVal {
    fn partial_cmp(&self, other: &TimeVal) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl TimeVal {
    #[inline]
    pub fn zero() -> TimeVal {
        TimeVal::microseconds(0)
    }

    #[inline]
    pub fn hours(hours: i64) -> TimeVal {
        let secs = hours.checked_mul(SECS_PER_HOUR)
            .expect("TimeVal::hours ouf of bounds");

        TimeVal::seconds(secs)
    }

    #[inline]
    pub fn minutes(minutes: i64) -> TimeVal {
        let secs = minutes.checked_mul(SECS_PER_MINUTE)
            .expect("TimeVal::minutes out of bounds");

        TimeVal::seconds(secs)
    }

    #[inline]
    pub fn seconds(seconds: i64) -> TimeVal {
        assert!(seconds >= MIN_SECONDS && seconds <= MAX_SECONDS, "TimeVal out of bounds; seconds={}", seconds);
        TimeVal(timeval {tv_sec: seconds as time_t, tv_usec: 0 })
    }

    #[inline]
    pub fn milliseconds(milliseconds: i64) -> TimeVal {
        let microseconds = milliseconds.checked_mul(1_000)
            .expect("TimeVal::milliseconds out of bounds");

        TimeVal::microseconds(microseconds)
    }

    /// Makes a new `TimeVal` with given number of microseconds.
    #[inline]
    pub fn microseconds(microseconds: i64) -> TimeVal {
        let (secs, micros) = div_mod_floor_64(microseconds, MICROS_PER_SEC);
        assert!(secs >= MIN_SECONDS && secs <= MAX_SECONDS, "TimeVal out of bounds");
        TimeVal(timeval {tv_sec: secs as time_t,
                           tv_usec: micros as suseconds_t })
    }

    pub fn num_hours(&self) -> i64 {
        self.num_seconds() / 3600
    }

    pub fn num_minutes(&self) -> i64 {
        self.num_seconds() / 60
    }

    pub fn num_seconds(&self) -> i64 {
        if self.tv_sec() < 0 && self.tv_usec() > 0 {
            (self.tv_sec() + 1) as i64
        } else {
            self.tv_sec() as i64
        }
    }

    pub fn num_milliseconds(&self) -> i64 {
        self.num_microseconds() / 1_000
    }

    pub fn num_microseconds(&self) -> i64 {
        let secs = self.num_seconds() * 1_000_000;
        let usec = self.micros_mod_sec();
        secs + usec as i64
    }

    fn micros_mod_sec(&self) -> suseconds_t {
        if self.tv_sec() < 0 && self.tv_usec() > 0 {
            self.tv_usec() - MICROS_PER_SEC as suseconds_t
        } else {
            self.tv_usec()
        }
    }

    pub fn timeval(&self) -> timeval{
        self.0
    }

    pub fn tv_sec(&self) -> time_t {
        self.0.tv_sec
    }

    pub fn tv_usec(&self) -> suseconds_t {
        self.0.tv_usec
    }
}

impl ops::Neg for TimeVal {
    type Output = TimeVal;

    fn neg(self) -> TimeVal {
        TimeVal::microseconds(-self.num_microseconds())
    }
}

impl ops::Add for TimeVal {
    type Output = TimeVal;

    fn add(self, rhs: TimeVal) -> TimeVal {
        TimeVal::microseconds(
            self.num_microseconds() + rhs.num_microseconds())
    }
}

impl ops::Sub for TimeVal {
    type Output = TimeVal;

    fn sub(self, rhs: TimeVal) -> TimeVal {
        TimeVal::microseconds(
            self.num_microseconds() - rhs.num_microseconds())
    }
}

impl ops::Mul<i32> for TimeVal {
    type Output = TimeVal;

    fn mul(self, rhs: i32) -> TimeVal {
        let usec = self.num_microseconds().checked_mul(rhs as i64)
            .expect("TimeVal multiply out of bounds");

        TimeVal::microseconds(usec)
    }
}

impl ops::Div<i32> for TimeVal {
    type Output = TimeVal;

    fn div(self, rhs: i32) -> TimeVal {
        let usec = self.num_microseconds() / rhs as i64;
        TimeVal::microseconds(usec)
    }
}

impl fmt::Display for TimeVal {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let (abs, sign) = if self.tv_sec() < 0 {
            (-*self, "-")
        } else {
            (*self, "")
        };

        let sec = abs.tv_sec();

        try!(write!(f, "{}", sign));

        if abs.tv_usec() == 0 {
            if abs.tv_sec() == 1 {
                try!(write!(f, "{} second", sec));
            } else {
                try!(write!(f, "{} seconds", sec));
            }
        } else if abs.tv_usec() % 1000 == 0 {
            try!(write!(f, "{}.{:03} seconds", sec, abs.tv_usec() / 1000));
        } else {
            try!(write!(f, "{}.{:06} seconds", sec, abs.tv_usec()));
        }

        Ok(())
    }
}

#[inline]
fn div_mod_floor_64(this: i64, other: i64) -> (i64, i64) {
    (div_floor_64(this, other), mod_floor_64(this, other))
}

#[inline]
fn div_floor_64(this: i64, other: i64) -> i64 {
    match div_rem_64(this, other) {
        (d, r) if (r > 0 && other < 0)
               || (r < 0 && other > 0) => d - 1,
        (d, _)                         => d,
    }
}

#[inline]
fn mod_floor_64(this: i64, other: i64) -> i64 {
    match this % other {
        r if (r > 0 && other < 0)
          || (r < 0 && other > 0) => r + other,
        r                         => r,
    }
}

#[inline]
fn div_rem_64(this: i64, other: i64) -> (i64, i64) {
    (this / other, this % other)
}

#[cfg(test)]
mod test {
    use super::TimeVal;

    #[test]
    pub fn test_time_val() {
        assert!(TimeVal::seconds(1) != TimeVal::zero());
        assert_eq!(TimeVal::seconds(1) + TimeVal::seconds(2), TimeVal::seconds(3));
        assert_eq!(TimeVal::minutes(3) + TimeVal::seconds(2),
                   TimeVal::seconds(182));
    }

    #[test]
    pub fn test_time_val_neg() {
        let a = TimeVal::seconds(1) + TimeVal::microseconds(123);
        let b = TimeVal::seconds(-1) + TimeVal::microseconds(-123);

        assert_eq!(a, -b);
    }

    #[test]
    pub fn test_time_val_fmt() {
        assert_eq!(TimeVal::zero().to_string(), "0 seconds");
        assert_eq!(TimeVal::seconds(42).to_string(), "42 seconds");
        assert_eq!(TimeVal::milliseconds(42).to_string(), "0.042 seconds");
        assert_eq!(TimeVal::microseconds(42).to_string(), "0.000042 seconds");
        assert_eq!(TimeVal::seconds(-86401).to_string(), "-86401 seconds");
    }
}