1 #region Copyright notice and license 2 // Protocol Buffers - Google's data interchange format 3 // Copyright 2015 Google Inc. All rights reserved. 4 // https://developers.google.com/protocol-buffers/ 5 // 6 // Redistribution and use in source and binary forms, with or without 7 // modification, are permitted provided that the following conditions are 8 // met: 9 // 10 // * Redistributions of source code must retain the above copyright 11 // notice, this list of conditions and the following disclaimer. 12 // * Redistributions in binary form must reproduce the above 13 // copyright notice, this list of conditions and the following disclaimer 14 // in the documentation and/or other materials provided with the 15 // distribution. 16 // * Neither the name of Google Inc. nor the names of its 17 // contributors may be used to endorse or promote products derived from 18 // this software without specific prior written permission. 19 // 20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 #endregion 32 33 using System; 34 using System.Globalization; 35 using System.Text; 36 37 namespace Google.Protobuf.WellKnownTypes 38 { 39 // Manually-written partial class for the Duration well-known type, 40 // providing a conversion to TimeSpan and convenience operators. 41 public partial class Duration : ICustomDiagnosticMessage 42 { 43 /// <summary> 44 /// The number of nanoseconds in a second. 45 /// </summary> 46 public const int NanosecondsPerSecond = 1000000000; 47 /// <summary> 48 /// The number of nanoseconds in a BCL tick (as used by <see cref="TimeSpan"/> and <see cref="DateTime"/>). 49 /// </summary> 50 public const int NanosecondsPerTick = 100; 51 52 /// <summary> 53 /// The maximum permitted number of seconds. 54 /// </summary> 55 public const long MaxSeconds = 315576000000L; 56 57 /// <summary> 58 /// The minimum permitted number of seconds. 59 /// </summary> 60 public const long MinSeconds = -315576000000L; 61 62 internal const int MaxNanoseconds = NanosecondsPerSecond - 1; 63 internal const int MinNanoseconds = -NanosecondsPerSecond + 1; 64 IsNormalized(long seconds, int nanoseconds)65 internal static bool IsNormalized(long seconds, int nanoseconds) 66 { 67 // Simple boundaries 68 if (seconds < MinSeconds || seconds > MaxSeconds || 69 nanoseconds < MinNanoseconds || nanoseconds > MaxNanoseconds) 70 { 71 return false; 72 } 73 // We only have a problem is one is strictly negative and the other is 74 // strictly positive. 75 return Math.Sign(seconds) * Math.Sign(nanoseconds) != -1; 76 } 77 78 /// <summary> 79 /// Converts this <see cref="Duration"/> to a <see cref="TimeSpan"/>. 80 /// </summary> 81 /// <remarks>If the duration is not a precise number of ticks, it is truncated towards 0.</remarks> 82 /// <returns>The value of this duration, as a <c>TimeSpan</c>.</returns> 83 /// <exception cref="InvalidOperationException">This value isn't a valid normalized duration, as 84 /// described in the documentation.</exception> ToTimeSpan()85 public TimeSpan ToTimeSpan() 86 { 87 checked 88 { 89 if (!IsNormalized(Seconds, Nanos)) 90 { 91 throw new InvalidOperationException("Duration was not a valid normalized duration"); 92 } 93 long ticks = Seconds * TimeSpan.TicksPerSecond + Nanos / NanosecondsPerTick; 94 return TimeSpan.FromTicks(ticks); 95 } 96 } 97 98 /// <summary> 99 /// Converts the given <see cref="TimeSpan"/> to a <see cref="Duration"/>. 100 /// </summary> 101 /// <param name="timeSpan">The <c>TimeSpan</c> to convert.</param> 102 /// <returns>The value of the given <c>TimeSpan</c>, as a <c>Duration</c>.</returns> FromTimeSpan(TimeSpan timeSpan)103 public static Duration FromTimeSpan(TimeSpan timeSpan) 104 { 105 checked 106 { 107 long ticks = timeSpan.Ticks; 108 long seconds = ticks / TimeSpan.TicksPerSecond; 109 int nanos = (int) (ticks % TimeSpan.TicksPerSecond) * NanosecondsPerTick; 110 return new Duration { Seconds = seconds, Nanos = nanos }; 111 } 112 } 113 114 /// <summary> 115 /// Returns the result of negating the duration. For example, the negation of 5 minutes is -5 minutes. 116 /// </summary> 117 /// <param name="value">The duration to negate. Must not be null.</param> 118 /// <returns>The negated value of this duration.</returns> operator -(Duration value)119 public static Duration operator -(Duration value) 120 { 121 ProtoPreconditions.CheckNotNull(value, "value"); 122 checked 123 { 124 return Normalize(-value.Seconds, -value.Nanos); 125 } 126 } 127 128 /// <summary> 129 /// Adds the two specified <see cref="Duration"/> values together. 130 /// </summary> 131 /// <param name="lhs">The first value to add. Must not be null.</param> 132 /// <param name="rhs">The second value to add. Must not be null.</param> 133 /// <returns></returns> operator +(Duration lhs, Duration rhs)134 public static Duration operator +(Duration lhs, Duration rhs) 135 { 136 ProtoPreconditions.CheckNotNull(lhs, "lhs"); 137 ProtoPreconditions.CheckNotNull(rhs, "rhs"); 138 checked 139 { 140 return Normalize(lhs.Seconds + rhs.Seconds, lhs.Nanos + rhs.Nanos); 141 } 142 } 143 144 /// <summary> 145 /// Subtracts one <see cref="Duration"/> from another. 146 /// </summary> 147 /// <param name="lhs">The duration to subtract from. Must not be null.</param> 148 /// <param name="rhs">The duration to subtract. Must not be null.</param> 149 /// <returns>The difference between the two specified durations.</returns> operator -(Duration lhs, Duration rhs)150 public static Duration operator -(Duration lhs, Duration rhs) 151 { 152 ProtoPreconditions.CheckNotNull(lhs, "lhs"); 153 ProtoPreconditions.CheckNotNull(rhs, "rhs"); 154 checked 155 { 156 return Normalize(lhs.Seconds - rhs.Seconds, lhs.Nanos - rhs.Nanos); 157 } 158 } 159 160 /// <summary> 161 /// Creates a duration with the normalized values from the given number of seconds and 162 /// nanoseconds, conforming with the description in the proto file. 163 /// </summary> Normalize(long seconds, int nanoseconds)164 internal static Duration Normalize(long seconds, int nanoseconds) 165 { 166 // Ensure that nanoseconds is in the range (-1,000,000,000, +1,000,000,000) 167 int extraSeconds = nanoseconds / NanosecondsPerSecond; 168 seconds += extraSeconds; 169 nanoseconds -= extraSeconds * NanosecondsPerSecond; 170 171 // Now make sure that Sign(seconds) == Sign(nanoseconds) if Sign(seconds) != 0. 172 if (seconds < 0 && nanoseconds > 0) 173 { 174 seconds += 1; 175 nanoseconds -= NanosecondsPerSecond; 176 } 177 else if (seconds > 0 && nanoseconds < 0) 178 { 179 seconds -= 1; 180 nanoseconds += NanosecondsPerSecond; 181 } 182 return new Duration { Seconds = seconds, Nanos = nanoseconds }; 183 } 184 185 /// <summary> 186 /// Converts a duration specified in seconds/nanoseconds to a string. 187 /// </summary> 188 /// <remarks> 189 /// If the value is a normalized duration in the range described in <c>duration.proto</c>, 190 /// <paramref name="diagnosticOnly"/> is ignored. Otherwise, if the parameter is <c>true</c>, 191 /// a JSON object with a warning is returned; if it is <c>false</c>, an <see cref="InvalidOperationException"/> is thrown. 192 /// </remarks> 193 /// <param name="seconds">Seconds portion of the duration.</param> 194 /// <param name="nanoseconds">Nanoseconds portion of the duration.</param> 195 /// <param name="diagnosticOnly">Determines the handling of non-normalized values</param> 196 /// <exception cref="InvalidOperationException">The represented duration is invalid, and <paramref name="diagnosticOnly"/> is <c>false</c>.</exception> ToJson(long seconds, int nanoseconds, bool diagnosticOnly)197 internal static string ToJson(long seconds, int nanoseconds, bool diagnosticOnly) 198 { 199 if (IsNormalized(seconds, nanoseconds)) 200 { 201 var builder = new StringBuilder(); 202 builder.Append('"'); 203 // The seconds part will normally provide the minus sign if we need it, but not if it's 0... 204 if (seconds == 0 && nanoseconds < 0) 205 { 206 builder.Append('-'); 207 } 208 209 builder.Append(seconds.ToString("d", CultureInfo.InvariantCulture)); 210 AppendNanoseconds(builder, Math.Abs(nanoseconds)); 211 builder.Append("s\""); 212 return builder.ToString(); 213 } 214 if (diagnosticOnly) 215 { 216 // Note: the double braces here are escaping for braces in format strings. 217 return string.Format(CultureInfo.InvariantCulture, 218 "{{ \"@warning\": \"Invalid Duration\", \"seconds\": \"{0}\", \"nanos\": {1} }}", 219 seconds, 220 nanoseconds); 221 } 222 else 223 { 224 throw new InvalidOperationException("Non-normalized duration value"); 225 } 226 } 227 228 /// <summary> 229 /// Returns a string representation of this <see cref="Duration"/> for diagnostic purposes. 230 /// </summary> 231 /// <remarks> 232 /// Normally the returned value will be a JSON string value (including leading and trailing quotes) but 233 /// when the value is non-normalized or out of range, a JSON object representation will be returned 234 /// instead, including a warning. This is to avoid exceptions being thrown when trying to 235 /// diagnose problems - the regular JSON formatter will still throw an exception for non-normalized 236 /// values. 237 /// </remarks> 238 /// <returns>A string representation of this value.</returns> ToDiagnosticString()239 public string ToDiagnosticString() 240 { 241 return ToJson(Seconds, Nanos, true); 242 } 243 244 /// <summary> 245 /// Appends a number of nanoseconds to a StringBuilder. Either 0 digits are added (in which 246 /// case no "." is appended), or 3 6 or 9 digits. This is internal for use in Timestamp as well 247 /// as Duration. 248 /// </summary> AppendNanoseconds(StringBuilder builder, int nanos)249 internal static void AppendNanoseconds(StringBuilder builder, int nanos) 250 { 251 if (nanos != 0) 252 { 253 builder.Append('.'); 254 // Output to 3, 6 or 9 digits. 255 if (nanos % 1000000 == 0) 256 { 257 builder.Append((nanos / 1000000).ToString("d3", CultureInfo.InvariantCulture)); 258 } 259 else if (nanos % 1000 == 0) 260 { 261 builder.Append((nanos / 1000).ToString("d6", CultureInfo.InvariantCulture)); 262 } 263 else 264 { 265 builder.Append(nanos.ToString("d9", CultureInfo.InvariantCulture)); 266 } 267 } 268 } 269 } 270 } 271