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 if (tv_sec * 1000 > millis) { 47 --tv_sec; 48 } 49 long tv_usec = (millis - (tv_sec * 1000)) * 1000; 50 return new StructTimeval(tv_sec, tv_usec); 51 } 52 toMillis()53 public long toMillis() { 54 return (tv_sec * 1000) + (tv_usec / 1000); 55 } 56 57 @Override toString()58 public String toString() { 59 return Objects.toString(this); 60 } 61 62 @Override equals(Object o)63 public boolean equals(Object o) { 64 if (this == o) { 65 return true; 66 } 67 if (o == null || getClass() != o.getClass()) { 68 return false; 69 } 70 StructTimeval that = (StructTimeval) o; 71 return tv_sec == that.tv_sec && 72 tv_usec == that.tv_usec; 73 } 74 75 @Override hashCode()76 public int hashCode() { 77 return java.util.Objects.hash(tv_sec, tv_usec); 78 } 79 } 80