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.protobuf.util.Timestamps.MICROS_PER_SECOND; 34 import static com.google.protobuf.util.Timestamps.MILLIS_PER_SECOND; 35 import static com.google.protobuf.util.Timestamps.NANOS_PER_MICROSECOND; 36 import static com.google.protobuf.util.Timestamps.NANOS_PER_MILLISECOND; 37 import static com.google.protobuf.util.Timestamps.NANOS_PER_SECOND; 38 39 import com.google.protobuf.Duration; 40 41 import java.text.ParseException; 42 43 /** 44 * Utilities to help create/manipulate {@code protobuf/duration.proto}. 45 */ 46 public final class Durations { 47 static final long DURATION_SECONDS_MIN = -315576000000L; 48 static final long DURATION_SECONDS_MAX = 315576000000L; 49 50 // TODO(kak): Do we want to expose Duration constants for MAX/MIN? 51 Durations()52 private Durations() {} 53 54 /** 55 * Returns true if the given {@link Duration} is valid. The {@code seconds} value must be in the 56 * range [-315,576,000,000, +315,576,000,000]. The {@code nanos} value must be in the range 57 * [-999,999,999, +999,999,999]. 58 * 59 * <p>Note: Durations less than one second are represented with a 0 {@code seconds} field and a 60 * positive or negative {@code nanos} field. For durations of one second or more, a non-zero value 61 * for the {@code nanos} field must be of the same sign as the {@code seconds} field. 62 */ isValid(Duration duration)63 public static boolean isValid(Duration duration) { 64 return isValid(duration.getSeconds(), duration.getNanos()); 65 } 66 67 /** 68 * Returns true if the given number of seconds and nanos is a valid {@link Duration}. The 69 * {@code seconds} value must be in the range [-315,576,000,000, +315,576,000,000]. The 70 * {@code nanos} value must be in the range [-999,999,999, +999,999,999]. 71 * 72 * <p>Note: Durations less than one second are represented with a 0 {@code seconds} field and a 73 * positive or negative {@code nanos} field. For durations of one second or more, a non-zero value 74 * for the {@code nanos} field must be of the same sign as the {@code seconds} field. 75 */ isValid(long seconds, long nanos)76 public static boolean isValid(long seconds, long nanos) { 77 if (seconds < DURATION_SECONDS_MIN || seconds > DURATION_SECONDS_MAX) { 78 return false; 79 } 80 if (nanos < -999999999L || nanos >= NANOS_PER_SECOND) { 81 return false; 82 } 83 if (seconds < 0 || nanos < 0) { 84 if (seconds > 0 || nanos > 0) { 85 return false; 86 } 87 } 88 return true; 89 } 90 91 /** 92 * Throws an {@link IllegalArgumentException} if the given seconds/nanos are not 93 * a valid {@link Duration}. 94 */ checkValid(long seconds, int nanos)95 private static void checkValid(long seconds, int nanos) { 96 if (!isValid(seconds, nanos)) { 97 throw new IllegalArgumentException(String.format( 98 "Duration is not valid. See proto definition for valid values. " 99 + "Seconds (%s) must be in range [-315,576,000,000, +315,576,000,000]." 100 + "Nanos (%s) must be in range [-999,999,999, +999,999,999]. " 101 + "Nanos must have the same sign as seconds", seconds, nanos)); 102 } 103 } 104 105 /** 106 * Convert Duration to string format. The string format will contains 3, 6, 107 * or 9 fractional digits depending on the precision required to represent 108 * the exact Duration value. For example: "1s", "1.010s", "1.000000100s", 109 * "-3.100s" The range that can be represented by Duration is from 110 * -315,576,000,000 to +315,576,000,000 inclusive (in seconds). 111 * 112 * @return The string representation of the given duration. 113 * @throws IllegalArgumentException if the given duration is not in the valid 114 * range. 115 */ toString(Duration duration)116 public static String toString(Duration duration) { 117 long seconds = duration.getSeconds(); 118 int nanos = duration.getNanos(); 119 checkValid(seconds, nanos); 120 121 StringBuilder result = new StringBuilder(); 122 if (seconds < 0 || nanos < 0) { 123 result.append("-"); 124 seconds = -seconds; 125 nanos = -nanos; 126 } 127 result.append(seconds); 128 if (nanos != 0) { 129 result.append("."); 130 result.append(Timestamps.formatNanos(nanos)); 131 } 132 result.append("s"); 133 return result.toString(); 134 } 135 136 /** 137 * Parse from a string to produce a duration. 138 * 139 * @return A Duration parsed from the string. 140 * @throws ParseException if parsing fails. 141 */ parse(String value)142 public static Duration parse(String value) throws ParseException { 143 // Must ended with "s". 144 if (value.isEmpty() || value.charAt(value.length() - 1) != 's') { 145 throw new ParseException("Invalid duration string: " + value, 0); 146 } 147 boolean negative = false; 148 if (value.charAt(0) == '-') { 149 negative = true; 150 value = value.substring(1); 151 } 152 String secondValue = value.substring(0, value.length() - 1); 153 String nanoValue = ""; 154 int pointPosition = secondValue.indexOf('.'); 155 if (pointPosition != -1) { 156 nanoValue = secondValue.substring(pointPosition + 1); 157 secondValue = secondValue.substring(0, pointPosition); 158 } 159 long seconds = Long.parseLong(secondValue); 160 int nanos = nanoValue.isEmpty() ? 0 : Timestamps.parseNanos(nanoValue); 161 if (seconds < 0) { 162 throw new ParseException("Invalid duration string: " + value, 0); 163 } 164 if (negative) { 165 seconds = -seconds; 166 nanos = -nanos; 167 } 168 try { 169 return normalizedDuration(seconds, nanos); 170 } catch (IllegalArgumentException e) { 171 throw new ParseException("Duration value is out of range.", 0); 172 } 173 } 174 175 /** 176 * Create a Duration from the number of milliseconds. 177 */ fromMillis(long milliseconds)178 public static Duration fromMillis(long milliseconds) { 179 return normalizedDuration( 180 milliseconds / MILLIS_PER_SECOND, 181 (int) (milliseconds % MILLIS_PER_SECOND * NANOS_PER_MILLISECOND)); 182 } 183 184 /** 185 * Convert a Duration to the number of milliseconds.The result will be 186 * rounded towards 0 to the nearest millisecond. E.g., if the duration 187 * represents -1 nanosecond, it will be rounded to 0. 188 */ toMillis(Duration duration)189 public static long toMillis(Duration duration) { 190 return duration.getSeconds() * MILLIS_PER_SECOND + duration.getNanos() / NANOS_PER_MILLISECOND; 191 } 192 193 /** 194 * Create a Duration from the number of microseconds. 195 */ fromMicros(long microseconds)196 public static Duration fromMicros(long microseconds) { 197 return normalizedDuration( 198 microseconds / MICROS_PER_SECOND, 199 (int) (microseconds % MICROS_PER_SECOND * NANOS_PER_MICROSECOND)); 200 } 201 202 /** 203 * Convert a Duration to the number of microseconds.The result will be 204 * rounded towards 0 to the nearest microseconds. E.g., if the duration 205 * represents -1 nanosecond, it will be rounded to 0. 206 */ toMicros(Duration duration)207 public static long toMicros(Duration duration) { 208 return duration.getSeconds() * MICROS_PER_SECOND + duration.getNanos() / NANOS_PER_MICROSECOND; 209 } 210 211 /** 212 * Create a Duration from the number of nanoseconds. 213 */ fromNanos(long nanoseconds)214 public static Duration fromNanos(long nanoseconds) { 215 return normalizedDuration( 216 nanoseconds / NANOS_PER_SECOND, (int) (nanoseconds % NANOS_PER_SECOND)); 217 } 218 219 /** 220 * Convert a Duration to the number of nanoseconds. 221 */ toNanos(Duration duration)222 public static long toNanos(Duration duration) { 223 return duration.getSeconds() * NANOS_PER_SECOND + duration.getNanos(); 224 } 225 226 /** 227 * Add two durations. 228 */ add(Duration d1, Duration d2)229 public static Duration add(Duration d1, Duration d2) { 230 return normalizedDuration(d1.getSeconds() + d2.getSeconds(), d1.getNanos() + d2.getNanos()); 231 } 232 233 /** 234 * Subtract a duration from another. 235 */ subtract(Duration d1, Duration d2)236 public static Duration subtract(Duration d1, Duration d2) { 237 return normalizedDuration(d1.getSeconds() - d2.getSeconds(), d1.getNanos() - d2.getNanos()); 238 } 239 normalizedDuration(long seconds, int nanos)240 static Duration normalizedDuration(long seconds, int nanos) { 241 if (nanos <= -NANOS_PER_SECOND || nanos >= NANOS_PER_SECOND) { 242 seconds += nanos / NANOS_PER_SECOND; 243 nanos %= NANOS_PER_SECOND; 244 } 245 if (seconds > 0 && nanos < 0) { 246 nanos += NANOS_PER_SECOND; 247 seconds -= 1; 248 } 249 if (seconds < 0 && nanos > 0) { 250 nanos -= NANOS_PER_SECOND; 251 seconds += 1; 252 } 253 checkValid(seconds, nanos); 254 return Duration.newBuilder().setSeconds(seconds).setNanos(nanos).build(); 255 } 256 } 257