From dd43dcca8c3a0af761ae981edcadd7e78e875fe8 Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Wed, 20 Jan 2016 18:43:00 +0000 Subject: Ensure that FieldMask, Timestamp and Duration ToString() calls don't throw The usage of ICustomDiagnosticMessage here is non-essential - ToDiagnosticString doesn't actually get called by ToString() in this case, due to JsonFormatter code. It was intended to make it clearer that it *did* have a custom format... but then arguably I should do the same for Value, Struct, Any etc. Moving some of the code out of JsonFormatter and into Duration/Timestamp/FieldMask likewise feels somewhat nice, somewhat nasty... basically there are JSON-specific bits of formatting, but also domain-specific bits of computation. Thoughts welcome. --- .../WellKnownTypes/TimestampPartial.cs | 70 +++++++++++++++++++--- 1 file changed, 63 insertions(+), 7 deletions(-) (limited to 'csharp/src/Google.Protobuf/WellKnownTypes/TimestampPartial.cs') diff --git a/csharp/src/Google.Protobuf/WellKnownTypes/TimestampPartial.cs b/csharp/src/Google.Protobuf/WellKnownTypes/TimestampPartial.cs index 7c50a3d7..86998e27 100644 --- a/csharp/src/Google.Protobuf/WellKnownTypes/TimestampPartial.cs +++ b/csharp/src/Google.Protobuf/WellKnownTypes/TimestampPartial.cs @@ -31,10 +31,12 @@ #endregion using System; +using System.Globalization; +using System.Text; namespace Google.Protobuf.WellKnownTypes { - public partial class Timestamp + public partial class Timestamp : ICustomDiagnosticMessage { private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // Constants determined programmatically, but then hard-coded so they can be constant expressions. @@ -43,11 +45,11 @@ namespace Google.Protobuf.WellKnownTypes internal const long UnixSecondsAtBclMinValue = -BclSecondsAtUnixEpoch; internal const int MaxNanos = Duration.NanosecondsPerSecond - 1; - private bool IsNormalized => - Nanos >= 0 && - Nanos <= MaxNanos && - Seconds >= UnixSecondsAtBclMinValue && - Seconds <= UnixSecondsAtBclMaxValue; + private static bool IsNormalized(long seconds, int nanoseconds) => + nanoseconds >= 0 && + nanoseconds <= MaxNanos && + seconds >= UnixSecondsAtBclMinValue && + seconds <= UnixSecondsAtBclMaxValue; /// /// Returns the difference between one and another, as a . @@ -111,7 +113,7 @@ namespace Google.Protobuf.WellKnownTypes /// incorrectly normalized or is outside the valid range. public DateTime ToDateTime() { - if (!IsNormalized) + if (!IsNormalized(Seconds, Nanos)) { throw new InvalidOperationException(@"Timestamp contains invalid values: Seconds={Seconds}; Nanos={Nanos}"); } @@ -181,5 +183,59 @@ namespace Google.Protobuf.WellKnownTypes } return new Timestamp { Seconds = seconds, Nanos = nanoseconds }; } + + /// + /// Converts a timestamp specified in seconds/nanoseconds to a string. + /// + /// + /// If the value is a normalized duration in the range described in timestamp.proto, + /// is ignored. Otherwise, if the parameter is true, + /// a JSON object with a warning is returned; if it is false, an is thrown. + /// + /// Seconds portion of the duration. + /// Nanoseconds portion of the duration. + /// Determines the handling of non-normalized values + /// The represented duration is invalid, and is false. + internal static string ToJson(long seconds, int nanoseconds, bool diagnosticOnly) + { + if (IsNormalized(seconds, nanoseconds)) + { + // Use .NET's formatting for the value down to the second, including an opening double quote (as it's a string value) + DateTime dateTime = UnixEpoch.AddSeconds(seconds); + var builder = new StringBuilder(); + builder.Append('"'); + builder.Append(dateTime.ToString("yyyy'-'MM'-'dd'T'HH:mm:ss", CultureInfo.InvariantCulture)); + Duration.AppendNanoseconds(builder, nanoseconds); + builder.Append("Z\""); + return builder.ToString(); + } + if (diagnosticOnly) + { + return string.Format(CultureInfo.InvariantCulture, + "{{ \"@warning\": \"Invalid Timestamp\", \"seconds\": \"{0}\", \"nanos\": {1} }}", + seconds, + nanoseconds); + } + else + { + throw new InvalidOperationException("Non-normalized timestamp value"); + } + } + + /// + /// Returns a string representation of this for diagnostic purposes. + /// + /// + /// Normally the returned value will be a JSON string value (including leading and trailing quotes) but + /// when the value is non-normalized or out of range, a JSON object representation will be returned + /// instead, including a warning. This is to avoid exceptions being thrown when trying to + /// diagnose problems - the regular JSON formatter will still throw an exception for non-normalized + /// values. + /// + /// A string representation of this value. + public string ToDiagnosticString() + { + return ToJson(Seconds, Nanos, true); + } } } -- cgit v1.2.3