OLD | NEW |
(Empty) | |
| 1 // Protocol Buffers - Google's data interchange format |
| 2 // Copyright 2008 Google Inc. All rights reserved. |
| 3 // https://developers.google.com/protocol-buffers/ |
| 4 // |
| 5 // Redistribution and use in source and binary forms, with or without |
| 6 // modification, are permitted provided that the following conditions are |
| 7 // met: |
| 8 // |
| 9 // * Redistributions of source code must retain the above copyright |
| 10 // notice, this list of conditions and the following disclaimer. |
| 11 // * Redistributions in binary form must reproduce the above |
| 12 // copyright notice, this list of conditions and the following disclaimer |
| 13 // in the documentation and/or other materials provided with the |
| 14 // distribution. |
| 15 // * Neither the name of Google Inc. nor the names of its |
| 16 // contributors may be used to endorse or promote products derived from |
| 17 // this software without specific prior written permission. |
| 18 // |
| 19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
| 21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
| 22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
| 23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
| 24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
| 25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
| 26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
| 27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
| 28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 30 |
| 31 package com.google.protobuf.util; |
| 32 |
| 33 import static com.google.common.base.Preconditions.checkArgument; |
| 34 import static com.google.common.math.IntMath.checkedAdd; |
| 35 import static com.google.common.math.IntMath.checkedSubtract; |
| 36 import static com.google.common.math.LongMath.checkedAdd; |
| 37 import static com.google.common.math.LongMath.checkedMultiply; |
| 38 import static com.google.common.math.LongMath.checkedSubtract; |
| 39 import static com.google.protobuf.util.Timestamps.MICROS_PER_SECOND; |
| 40 import static com.google.protobuf.util.Timestamps.MILLIS_PER_SECOND; |
| 41 import static com.google.protobuf.util.Timestamps.NANOS_PER_MICROSECOND; |
| 42 import static com.google.protobuf.util.Timestamps.NANOS_PER_MILLISECOND; |
| 43 import static com.google.protobuf.util.Timestamps.NANOS_PER_SECOND; |
| 44 |
| 45 import com.google.protobuf.Duration; |
| 46 import java.text.ParseException; |
| 47 import java.util.Comparator; |
| 48 |
| 49 /** |
| 50 * Utilities to help create/manipulate {@code protobuf/duration.proto}. All oper
ations throw an |
| 51 * {@link IllegalArgumentException} if the input(s) are not {@linkplain #isValid
(Duration) valid}. |
| 52 */ |
| 53 public final class Durations { |
| 54 static final long DURATION_SECONDS_MIN = -315576000000L; |
| 55 static final long DURATION_SECONDS_MAX = 315576000000L; |
| 56 |
| 57 /** A constant holding the minimum valid {@link Duration}, approximately {@cod
e -10,000} years. */ |
| 58 public static final Duration MIN_VALUE = |
| 59 Duration.newBuilder().setSeconds(DURATION_SECONDS_MIN).setNanos(-999999999
).build(); |
| 60 |
| 61 /** A constant holding the maximum valid {@link Duration}, approximately {@cod
e +10,000} years. */ |
| 62 public static final Duration MAX_VALUE = |
| 63 Duration.newBuilder().setSeconds(DURATION_SECONDS_MAX).setNanos(999999999)
.build(); |
| 64 |
| 65 private Durations() {} |
| 66 |
| 67 private static final Comparator<Duration> COMPARATOR = |
| 68 new Comparator<Duration>() { |
| 69 @Override |
| 70 public int compare(Duration d1, Duration d2) { |
| 71 checkValid(d1); |
| 72 checkValid(d2); |
| 73 int secDiff = Long.compare(d1.getSeconds(), d2.getSeconds()); |
| 74 return (secDiff != 0) ? secDiff : Integer.compare(d1.getNanos(), d2.ge
tNanos()); |
| 75 } |
| 76 }; |
| 77 |
| 78 /** |
| 79 * Returns a {@link Comparator} for {@link Duration}s which sorts in increasin
g chronological |
| 80 * order. Nulls and invalid {@link Duration}s are not allowed (see {@link #isV
alid}). |
| 81 */ |
| 82 public static Comparator<Duration> comparator() { |
| 83 return COMPARATOR; |
| 84 } |
| 85 |
| 86 /** |
| 87 * Returns true if the given {@link Duration} is valid. The {@code seconds} va
lue must be in the |
| 88 * range [-315,576,000,000, +315,576,000,000]. The {@code nanos} value must be
in the range |
| 89 * [-999,999,999, +999,999,999]. |
| 90 * |
| 91 * <p><b>Note:</b> Durations less than one second are represented with a 0 {@c
ode seconds} field |
| 92 * and a positive or negative {@code nanos} field. For durations of one second
or more, a non-zero |
| 93 * value for the {@code nanos} field must be of the same sign as the {@code se
conds} field. |
| 94 */ |
| 95 public static boolean isValid(Duration duration) { |
| 96 return isValid(duration.getSeconds(), duration.getNanos()); |
| 97 } |
| 98 |
| 99 /** |
| 100 * Returns true if the given number of seconds and nanos is a valid {@link Dur
ation}. The {@code |
| 101 * seconds} value must be in the range [-315,576,000,000, +315,576,000,000]. T
he {@code nanos} |
| 102 * value must be in the range [-999,999,999, +999,999,999]. |
| 103 * |
| 104 * <p><b>Note:</b> Durations less than one second are represented with a 0 {@c
ode seconds} field |
| 105 * and a positive or negative {@code nanos} field. For durations of one second
or more, a non-zero |
| 106 * value for the {@code nanos} field must be of the same sign as the {@code se
conds} field. |
| 107 */ |
| 108 public static boolean isValid(long seconds, int nanos) { |
| 109 if (seconds < DURATION_SECONDS_MIN || seconds > DURATION_SECONDS_MAX) { |
| 110 return false; |
| 111 } |
| 112 if (nanos < -999999999L || nanos >= NANOS_PER_SECOND) { |
| 113 return false; |
| 114 } |
| 115 if (seconds < 0 || nanos < 0) { |
| 116 if (seconds > 0 || nanos > 0) { |
| 117 return false; |
| 118 } |
| 119 } |
| 120 return true; |
| 121 } |
| 122 |
| 123 /** Throws an {@link IllegalArgumentException} if the given {@link Duration} i
s not valid. */ |
| 124 public static Duration checkValid(Duration duration) { |
| 125 long seconds = duration.getSeconds(); |
| 126 int nanos = duration.getNanos(); |
| 127 checkArgument( |
| 128 isValid(seconds, nanos), |
| 129 "Duration is not valid. See proto definition for valid values. " |
| 130 + "Seconds (%s) must be in range [-315,576,000,000, +315,576,000,000
]. " |
| 131 + "Nanos (%s) must be in range [-999,999,999, +999,999,999]. " |
| 132 + "Nanos must have the same sign as seconds", |
| 133 seconds, |
| 134 nanos); |
| 135 return duration; |
| 136 } |
| 137 |
| 138 /** |
| 139 * Convert Duration to string format. The string format will contains 3, 6, or
9 fractional digits |
| 140 * depending on the precision required to represent the exact Duration value.
For example: "1s", |
| 141 * "1.010s", "1.000000100s", "-3.100s" The range that can be represented by Du
ration is from |
| 142 * -315,576,000,000 to +315,576,000,000 inclusive (in seconds). |
| 143 * |
| 144 * @return The string representation of the given duration. |
| 145 * @throws IllegalArgumentException if the given duration is not in the valid
range. |
| 146 */ |
| 147 public static String toString(Duration duration) { |
| 148 checkValid(duration); |
| 149 |
| 150 long seconds = duration.getSeconds(); |
| 151 int nanos = duration.getNanos(); |
| 152 |
| 153 StringBuilder result = new StringBuilder(); |
| 154 if (seconds < 0 || nanos < 0) { |
| 155 result.append("-"); |
| 156 seconds = -seconds; |
| 157 nanos = -nanos; |
| 158 } |
| 159 result.append(seconds); |
| 160 if (nanos != 0) { |
| 161 result.append("."); |
| 162 result.append(Timestamps.formatNanos(nanos)); |
| 163 } |
| 164 result.append("s"); |
| 165 return result.toString(); |
| 166 } |
| 167 |
| 168 /** |
| 169 * Parse from a string to produce a duration. |
| 170 * |
| 171 * @return A Duration parsed from the string. |
| 172 * @throws ParseException if parsing fails. |
| 173 */ |
| 174 public static Duration parse(String value) throws ParseException { |
| 175 // Must ended with "s". |
| 176 if (value.isEmpty() || value.charAt(value.length() - 1) != 's') { |
| 177 throw new ParseException("Invalid duration string: " + value, 0); |
| 178 } |
| 179 boolean negative = false; |
| 180 if (value.charAt(0) == '-') { |
| 181 negative = true; |
| 182 value = value.substring(1); |
| 183 } |
| 184 String secondValue = value.substring(0, value.length() - 1); |
| 185 String nanoValue = ""; |
| 186 int pointPosition = secondValue.indexOf('.'); |
| 187 if (pointPosition != -1) { |
| 188 nanoValue = secondValue.substring(pointPosition + 1); |
| 189 secondValue = secondValue.substring(0, pointPosition); |
| 190 } |
| 191 long seconds = Long.parseLong(secondValue); |
| 192 int nanos = nanoValue.isEmpty() ? 0 : Timestamps.parseNanos(nanoValue); |
| 193 if (seconds < 0) { |
| 194 throw new ParseException("Invalid duration string: " + value, 0); |
| 195 } |
| 196 if (negative) { |
| 197 seconds = -seconds; |
| 198 nanos = -nanos; |
| 199 } |
| 200 try { |
| 201 return normalizedDuration(seconds, nanos); |
| 202 } catch (IllegalArgumentException e) { |
| 203 throw new ParseException("Duration value is out of range.", 0); |
| 204 } |
| 205 } |
| 206 |
| 207 /** Create a Duration from the number of seconds. */ |
| 208 public static Duration fromSeconds(long seconds) { |
| 209 return normalizedDuration(seconds, 0); |
| 210 } |
| 211 |
| 212 /** |
| 213 * Convert a Duration to the number of seconds. The result will be rounded tow
ards 0 to the |
| 214 * nearest second. E.g., if the duration represents -1 nanosecond, it will be
rounded to 0. |
| 215 */ |
| 216 public static long toSeconds(Duration duration) { |
| 217 return checkValid(duration).getSeconds(); |
| 218 } |
| 219 |
| 220 /** Create a Duration from the number of milliseconds. */ |
| 221 public static Duration fromMillis(long milliseconds) { |
| 222 return normalizedDuration( |
| 223 milliseconds / MILLIS_PER_SECOND, |
| 224 (int) (milliseconds % MILLIS_PER_SECOND * NANOS_PER_MILLISECOND)); |
| 225 } |
| 226 |
| 227 /** |
| 228 * Convert a Duration to the number of milliseconds. The result will be rounde
d towards 0 to the |
| 229 * nearest millisecond. E.g., if the duration represents -1 nanosecond, it wil
l be rounded to 0. |
| 230 */ |
| 231 public static long toMillis(Duration duration) { |
| 232 checkValid(duration); |
| 233 return checkedAdd( |
| 234 checkedMultiply(duration.getSeconds(), MILLIS_PER_SECOND), |
| 235 duration.getNanos() / NANOS_PER_MILLISECOND); |
| 236 } |
| 237 |
| 238 /** Create a Duration from the number of microseconds. */ |
| 239 public static Duration fromMicros(long microseconds) { |
| 240 return normalizedDuration( |
| 241 microseconds / MICROS_PER_SECOND, |
| 242 (int) (microseconds % MICROS_PER_SECOND * NANOS_PER_MICROSECOND)); |
| 243 } |
| 244 |
| 245 /** |
| 246 * Convert a Duration to the number of microseconds. The result will be rounde
d towards 0 to the |
| 247 * nearest microseconds. E.g., if the duration represents -1 nanosecond, it wi
ll be rounded to 0. |
| 248 */ |
| 249 public static long toMicros(Duration duration) { |
| 250 checkValid(duration); |
| 251 return checkedAdd( |
| 252 checkedMultiply(duration.getSeconds(), MICROS_PER_SECOND), |
| 253 duration.getNanos() / NANOS_PER_MICROSECOND); |
| 254 } |
| 255 |
| 256 /** Create a Duration from the number of nanoseconds. */ |
| 257 public static Duration fromNanos(long nanoseconds) { |
| 258 return normalizedDuration( |
| 259 nanoseconds / NANOS_PER_SECOND, (int) (nanoseconds % NANOS_PER_SECOND)); |
| 260 } |
| 261 |
| 262 /** Convert a Duration to the number of nanoseconds. */ |
| 263 public static long toNanos(Duration duration) { |
| 264 checkValid(duration); |
| 265 return checkedAdd( |
| 266 checkedMultiply(duration.getSeconds(), NANOS_PER_SECOND), duration.getNa
nos()); |
| 267 } |
| 268 |
| 269 /** Add two durations. */ |
| 270 public static Duration add(Duration d1, Duration d2) { |
| 271 checkValid(d1); |
| 272 checkValid(d2); |
| 273 return normalizedDuration( |
| 274 checkedAdd(d1.getSeconds(), d2.getSeconds()), checkedAdd(d1.getNanos(),
d2.getNanos())); |
| 275 } |
| 276 |
| 277 /** Subtract a duration from another. */ |
| 278 public static Duration subtract(Duration d1, Duration d2) { |
| 279 checkValid(d1); |
| 280 checkValid(d2); |
| 281 return normalizedDuration( |
| 282 checkedSubtract(d1.getSeconds(), d2.getSeconds()), |
| 283 checkedSubtract(d1.getNanos(), d2.getNanos())); |
| 284 } |
| 285 |
| 286 static Duration normalizedDuration(long seconds, int nanos) { |
| 287 if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) { |
| 288 seconds = checkedAdd(seconds, nanos / NANOS_PER_SECOND); |
| 289 nanos %= NANOS_PER_SECOND; |
| 290 } |
| 291 if (seconds > 0 && nanos < 0) { |
| 292 nanos += NANOS_PER_SECOND; // no overflow since nanos is negative (and we'
re adding) |
| 293 seconds--; // no overflow since seconds is positive (and we're decrementin
g) |
| 294 } |
| 295 if (seconds < 0 && nanos > 0) { |
| 296 nanos -= NANOS_PER_SECOND; // no overflow since nanos is positive (and we'
re subtracting) |
| 297 seconds++; // no overflow since seconds is negative (and we're incrementin
g) |
| 298 } |
| 299 Duration duration = Duration.newBuilder().setSeconds(seconds).setNanos(nanos
).build(); |
| 300 return checkValid(duration); |
| 301 } |
| 302 } |
OLD | NEW |