1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.system;
18 
19 import libcore.util.NonNull;
20 import libcore.util.Objects;
21 
22 /**
23  * Corresponds to C's {@code struct timeval} from {@code sys/time.h}.
24  */
25 public final class StructTimeval {
26     /** Seconds. */
27     public final long tv_sec;
28 
29     /** Microseconds. */
30     public final long tv_usec;
31 
StructTimeval(long tv_sec, long tv_usec)32     private StructTimeval(long tv_sec, long tv_usec) {
33         this.tv_sec = tv_sec;
34         this.tv_usec = tv_usec;
35         if (tv_usec < 0 || tv_usec > 999_999) {
36             throw new IllegalArgumentException(
37                     "tv_usec value " + tv_usec + " is not in [0, 999999]");
38         }
39     }
40 
fromMillis(long millis)41     public static @NonNull StructTimeval fromMillis(long millis) {
42         // tv_sec can be positive or negative. tv_usec can only be positive. Negative numbers are
43         // represented by rounding down to the nearest whole second <= the one we need
44         // (i.e. floor()) and adding the necessary micro seconds.
45         long tv_sec = millis / 1000;
46         long tv_usec = (millis - (tv_sec * 1000)) * 1000;
47         if (millis < 0) {
48             tv_sec -= 1;
49             tv_usec += 1_000_000;
50         }
51         return new StructTimeval(tv_sec, tv_usec);
52     }
53 
toMillis()54     public long toMillis() {
55         return (tv_sec * 1000) + (tv_usec / 1000);
56     }
57 
58     @Override
toString()59     public String toString() {
60         return Objects.toString(this);
61     }
62 
63     @Override
equals(Object o)64     public boolean equals(Object o) {
65         if (this == o) {
66             return true;
67         }
68         if (o == null || getClass() != o.getClass()) {
69             return false;
70         }
71         StructTimeval that = (StructTimeval) o;
72         return tv_sec == that.tv_sec &&
73                 tv_usec == that.tv_usec;
74     }
75 
76     @Override
hashCode()77     public int hashCode() {
78         return java.util.Objects.hash(tv_sec, tv_usec);
79     }
80 }
81