From 1fc485928fc7a6483b700867f1a6cb2acfa8da5d Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Fri, 15 Jan 2016 11:39:27 +0000 Subject: Fixes to JSON timestamp/duration representations --- .../WellKnownTypes/DurationPartial.cs | 23 ++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'csharp/src/Google.Protobuf/WellKnownTypes/DurationPartial.cs') diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/DurationPartial.cs b/csharp/src/Google.Protobuf/WellKnownTypes/DurationPartial.cs index 324f48fc..b8eba9d3 100644 --- a/csharp/src/Google.Protobuf/WellKnownTypes/DurationPartial.cs +++ b/csharp/src/Google.Protobuf/WellKnownTypes/DurationPartial.cs @@ -57,15 +57,38 @@ namespace Google.Protobuf.WellKnownTypes /// public const long MinSeconds = -315576000000L; + internal const int MaxNanoseconds = NanosecondsPerSecond - 1; + internal const int MinNanoseconds = -NanosecondsPerSecond + 1; + + internal static bool IsNormalized(long seconds, int nanoseconds) + { + // Simple boundaries + if (seconds < MinSeconds || seconds > MaxSeconds || + nanoseconds < MinNanoseconds || nanoseconds > MaxNanoseconds) + { + return false; + } + // We only have a problem is one is strictly negative and the other is + // strictly positive. + return Math.Sign(seconds) * Math.Sign(nanoseconds) != -1; + } + + /// /// Converts this to a . /// /// If the duration is not a precise number of ticks, it is truncated towards 0. /// The value of this duration, as a TimeSpan. + /// This value isn't a valid normalized duration, as + /// described in the documentation. public TimeSpan ToTimeSpan() { checked { + if (!IsNormalized(Seconds, Nanos)) + { + throw new InvalidOperationException("Duration was not a valid normalized duration"); + } long ticks = Seconds * TimeSpan.TicksPerSecond + Nanos / NanosecondsPerTick; return TimeSpan.FromTicks(ticks); } -- cgit v1.2.3