summaryrefslogtreecommitdiff
path: root/src/sys/time.rs
blob: fbe17c4988ad4c8fbee99cc290b542199b70111b (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
use std::{fmt, ops};
use std::num::Int;
use std::i64;
use libc::{time_t, suseconds_t};

#[repr(C)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub struct TimeVal {
    pub tv_sec: time_t,
    pub tv_usec: suseconds_t,
}

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

const MIN: TimeVal = TimeVal {
    tv_sec: -(i64::MAX / MICROS_PER_SEC - 1),
    tv_usec: (-(MICROS_PER_SEC - 1)) as suseconds_t,
};

const MAX: TimeVal = TimeVal {
    tv_sec: i64::MAX / MICROS_PER_SEC - 1,
    tv_usec: (MICROS_PER_SEC - 1) as suseconds_t,
};

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 {
        let ret = TimeVal { tv_sec: seconds, tv_usec: 0 };
        assert!(ret >= MIN && ret <= MAX, "TimeVal out of bounds");
        ret
    }

    #[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]
    #[unstable(feature = "std_misc")]
    pub fn microseconds(microseconds: i64) -> TimeVal {
        let (secs, micros) = div_mod_floor_64(microseconds, MICROS_PER_SEC);
        let ret = TimeVal { tv_sec: secs, tv_usec: micros as suseconds_t };
        assert!(ret >= MIN && ret <= MAX, "TimeVal out of bounds");
        ret
    }

    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
        } else {
            self.tv_sec
        }
    }

    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
        }
    }
}

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");
    }
}