1/*
2 * Copyright (C) 2017 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
17package android.system;
18
19import libcore.util.Objects;;
20
21/**
22 * Corresponds to C's {@code struct timespec} from {@code <time.h>}.
23 */
24public final class StructTimespec implements Comparable<StructTimespec> {
25    /** Seconds part of time of last data modification. */
26    public final long tv_sec; /*time_t*/
27
28    /** Nanoseconds (values are [0, 999999999]). */
29    public final long tv_nsec;
30
31    public StructTimespec(long tv_sec, long tv_nsec) {
32        this.tv_sec = tv_sec;
33        this.tv_nsec = tv_nsec;
34        if (tv_nsec < 0 || tv_nsec > 999_999_999) {
35            throw new IllegalArgumentException(
36                    "tv_nsec value " + tv_nsec + " is not in [0, 999999999]");
37        }
38    }
39
40    @Override
41    public int compareTo(StructTimespec other) {
42        if (tv_sec > other.tv_sec) {
43            return 1;
44        }
45        if (tv_sec < other.tv_sec) {
46            return -1;
47        }
48        if (tv_nsec > other.tv_nsec) {
49            return 1;
50        }
51        if (tv_nsec < other.tv_nsec) {
52            return -1;
53        }
54        return 0;
55    }
56
57    @Override
58    public boolean equals(Object o) {
59        if (this == o) return true;
60        if (o == null || getClass() != o.getClass()) return false;
61
62        StructTimespec that = (StructTimespec) o;
63
64        if (tv_sec != that.tv_sec) return false;
65        return tv_nsec == that.tv_nsec;
66    }
67
68    @Override
69    public int hashCode() {
70        int result = (int) (tv_sec ^ (tv_sec >>> 32));
71        result = 31 * result + (int) (tv_nsec ^ (tv_nsec >>> 32));
72        return result;
73    }
74
75    @Override
76    public String toString() {
77        return Objects.toString(this);
78    }
79}
80