Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 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.Collections; |
| 35 | using System.Globalization; |
| 36 | using System.Text; |
| 37 | using Google.Protobuf.Reflection; |
| 38 | using Google.Protobuf.WellKnownTypes; |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 39 | using System.IO; |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 40 | using System.Linq; |
| 41 | using System.Collections.Generic; |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 42 | using System.Reflection; |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 43 | |
| 44 | namespace Google.Protobuf |
| 45 | { |
| 46 | /// <summary> |
| 47 | /// Reflection-based converter from messages to JSON. |
| 48 | /// </summary> |
| 49 | /// <remarks> |
| 50 | /// <para> |
| 51 | /// Instances of this class are thread-safe, with no mutable state. |
| 52 | /// </para> |
| 53 | /// <para> |
| 54 | /// This is a simple start to get JSON formatting working. As it's reflection-based, |
| 55 | /// it's not as quick as baking calls into generated messages - but is a simpler implementation. |
| 56 | /// (This code is generally not heavily optimized.) |
| 57 | /// </para> |
| 58 | /// </remarks> |
| 59 | public sealed class JsonFormatter |
| 60 | { |
| 61 | internal const string AnyTypeUrlField = "@type"; |
| 62 | internal const string AnyDiagnosticValueField = "@value"; |
| 63 | internal const string AnyWellKnownTypeValueField = "value"; |
| 64 | private const string TypeUrlPrefix = "type.googleapis.com"; |
| 65 | private const string NameValueSeparator = ": "; |
| 66 | private const string PropertySeparator = ", "; |
| 67 | |
| 68 | /// <summary> |
| 69 | /// Returns a formatter using the default settings. |
| 70 | /// </summary> |
| 71 | public static JsonFormatter Default { get; } = new JsonFormatter(Settings.Default); |
| 72 | |
| 73 | // A JSON formatter which *only* exists |
| 74 | private static readonly JsonFormatter diagnosticFormatter = new JsonFormatter(Settings.Default); |
| 75 | |
| 76 | /// <summary> |
| 77 | /// The JSON representation of the first 160 characters of Unicode. |
| 78 | /// Empty strings are replaced by the static constructor. |
| 79 | /// </summary> |
| 80 | private static readonly string[] CommonRepresentations = { |
| 81 | // C0 (ASCII and derivatives) control characters |
| 82 | "\\u0000", "\\u0001", "\\u0002", "\\u0003", // 0x00 |
| 83 | "\\u0004", "\\u0005", "\\u0006", "\\u0007", |
| 84 | "\\b", "\\t", "\\n", "\\u000b", |
| 85 | "\\f", "\\r", "\\u000e", "\\u000f", |
| 86 | "\\u0010", "\\u0011", "\\u0012", "\\u0013", // 0x10 |
| 87 | "\\u0014", "\\u0015", "\\u0016", "\\u0017", |
| 88 | "\\u0018", "\\u0019", "\\u001a", "\\u001b", |
| 89 | "\\u001c", "\\u001d", "\\u001e", "\\u001f", |
| 90 | // Escaping of " and \ are required by www.json.org string definition. |
| 91 | // Escaping of < and > are required for HTML security. |
| 92 | "", "", "\\\"", "", "", "", "", "", // 0x20 |
| 93 | "", "", "", "", "", "", "", "", |
| 94 | "", "", "", "", "", "", "", "", // 0x30 |
| 95 | "", "", "", "", "\\u003c", "", "\\u003e", "", |
| 96 | "", "", "", "", "", "", "", "", // 0x40 |
| 97 | "", "", "", "", "", "", "", "", |
| 98 | "", "", "", "", "", "", "", "", // 0x50 |
| 99 | "", "", "", "", "\\\\", "", "", "", |
| 100 | "", "", "", "", "", "", "", "", // 0x60 |
| 101 | "", "", "", "", "", "", "", "", |
| 102 | "", "", "", "", "", "", "", "", // 0x70 |
| 103 | "", "", "", "", "", "", "", "\\u007f", |
| 104 | // C1 (ISO 8859 and Unicode) extended control characters |
| 105 | "\\u0080", "\\u0081", "\\u0082", "\\u0083", // 0x80 |
| 106 | "\\u0084", "\\u0085", "\\u0086", "\\u0087", |
| 107 | "\\u0088", "\\u0089", "\\u008a", "\\u008b", |
| 108 | "\\u008c", "\\u008d", "\\u008e", "\\u008f", |
| 109 | "\\u0090", "\\u0091", "\\u0092", "\\u0093", // 0x90 |
| 110 | "\\u0094", "\\u0095", "\\u0096", "\\u0097", |
| 111 | "\\u0098", "\\u0099", "\\u009a", "\\u009b", |
| 112 | "\\u009c", "\\u009d", "\\u009e", "\\u009f" |
| 113 | }; |
| 114 | |
| 115 | static JsonFormatter() |
| 116 | { |
| 117 | for (int i = 0; i < CommonRepresentations.Length; i++) |
| 118 | { |
| 119 | if (CommonRepresentations[i] == "") |
| 120 | { |
| 121 | CommonRepresentations[i] = ((char) i).ToString(); |
| 122 | } |
| 123 | } |
| 124 | } |
| 125 | |
| 126 | private readonly Settings settings; |
| 127 | |
| 128 | private bool DiagnosticOnly => ReferenceEquals(this, diagnosticFormatter); |
| 129 | |
| 130 | /// <summary> |
| 131 | /// Creates a new formatted with the given settings. |
| 132 | /// </summary> |
| 133 | /// <param name="settings">The settings.</param> |
| 134 | public JsonFormatter(Settings settings) |
| 135 | { |
| 136 | this.settings = settings; |
| 137 | } |
| 138 | |
| 139 | /// <summary> |
| 140 | /// Formats the specified message as JSON. |
| 141 | /// </summary> |
| 142 | /// <param name="message">The message to format.</param> |
| 143 | /// <returns>The formatted message.</returns> |
| 144 | public string Format(IMessage message) |
| 145 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 146 | var writer = new StringWriter(); |
| 147 | Format(message, writer); |
| 148 | return writer.ToString(); |
| 149 | } |
| 150 | |
| 151 | /// <summary> |
| 152 | /// Formats the specified message as JSON. |
| 153 | /// </summary> |
| 154 | /// <param name="message">The message to format.</param> |
| 155 | /// <param name="writer">The TextWriter to write the formatted message to.</param> |
| 156 | /// <returns>The formatted message.</returns> |
| 157 | public void Format(IMessage message, TextWriter writer) |
| 158 | { |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 159 | ProtoPreconditions.CheckNotNull(message, nameof(message)); |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 160 | ProtoPreconditions.CheckNotNull(writer, nameof(writer)); |
| 161 | |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 162 | if (message.Descriptor.IsWellKnownType) |
| 163 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 164 | WriteWellKnownTypeValue(writer, message.Descriptor, message); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 165 | } |
| 166 | else |
| 167 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 168 | WriteMessage(writer, message); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 169 | } |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 170 | } |
| 171 | |
| 172 | /// <summary> |
| 173 | /// Converts a message to JSON for diagnostic purposes with no extra context. |
| 174 | /// </summary> |
| 175 | /// <remarks> |
| 176 | /// <para> |
| 177 | /// This differs from calling <see cref="Format(IMessage)"/> on the default JSON |
| 178 | /// formatter in its handling of <see cref="Any"/>. As no type registry is available |
| 179 | /// in <see cref="object.ToString"/> calls, the normal way of resolving the type of |
| 180 | /// an <c>Any</c> message cannot be applied. Instead, a JSON property named <c>@value</c> |
| 181 | /// is included with the base64 data from the <see cref="Any.Value"/> property of the message. |
| 182 | /// </para> |
| 183 | /// <para>The value returned by this method is only designed to be used for diagnostic |
| 184 | /// purposes. It may not be parsable by <see cref="JsonParser"/>, and may not be parsable |
| 185 | /// by other Protocol Buffer implementations.</para> |
| 186 | /// </remarks> |
| 187 | /// <param name="message">The message to format for diagnostic purposes.</param> |
| 188 | /// <returns>The diagnostic-only JSON representation of the message</returns> |
| 189 | public static string ToDiagnosticString(IMessage message) |
| 190 | { |
| 191 | ProtoPreconditions.CheckNotNull(message, nameof(message)); |
| 192 | return diagnosticFormatter.Format(message); |
| 193 | } |
| 194 | |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 195 | private void WriteMessage(TextWriter writer, IMessage message) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 196 | { |
| 197 | if (message == null) |
| 198 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 199 | WriteNull(writer); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 200 | return; |
| 201 | } |
| 202 | if (DiagnosticOnly) |
| 203 | { |
| 204 | ICustomDiagnosticMessage customDiagnosticMessage = message as ICustomDiagnosticMessage; |
| 205 | if (customDiagnosticMessage != null) |
| 206 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 207 | writer.Write(customDiagnosticMessage.ToDiagnosticString()); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 208 | return; |
| 209 | } |
| 210 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 211 | writer.Write("{ "); |
| 212 | bool writtenFields = WriteMessageFields(writer, message, false); |
| 213 | writer.Write(writtenFields ? " }" : "}"); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 214 | } |
| 215 | |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 216 | private bool WriteMessageFields(TextWriter writer, IMessage message, bool assumeFirstFieldWritten) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 217 | { |
| 218 | var fields = message.Descriptor.Fields; |
| 219 | bool first = !assumeFirstFieldWritten; |
| 220 | // First non-oneof fields |
| 221 | foreach (var field in fields.InFieldNumberOrder()) |
| 222 | { |
| 223 | var accessor = field.Accessor; |
| 224 | if (field.ContainingOneof != null && field.ContainingOneof.Accessor.GetCaseFieldDescriptor(message) != field) |
| 225 | { |
| 226 | continue; |
| 227 | } |
| 228 | // Omit default values unless we're asked to format them, or they're oneofs (where the default |
| 229 | // value is still formatted regardless, because that's how we preserve the oneof case). |
| 230 | object value = accessor.GetValue(message); |
| 231 | if (field.ContainingOneof == null && !settings.FormatDefaultValues && IsDefaultValue(accessor, value)) |
| 232 | { |
| 233 | continue; |
| 234 | } |
| 235 | |
| 236 | // Okay, all tests complete: let's write the field value... |
| 237 | if (!first) |
| 238 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 239 | writer.Write(PropertySeparator); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 240 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 241 | |
| 242 | WriteString(writer, accessor.Descriptor.JsonName); |
| 243 | writer.Write(NameValueSeparator); |
| 244 | WriteValue(writer, value); |
| 245 | |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 246 | first = false; |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 247 | } |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 248 | return !first; |
| 249 | } |
| 250 | |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 251 | // Converted from java/core/src/main/java/com/google/protobuf/Descriptors.java |
| 252 | internal static string ToJsonName(string name) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 253 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 254 | StringBuilder result = new StringBuilder(name.Length); |
| 255 | bool isNextUpperCase = false; |
| 256 | foreach (char ch in name) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 257 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 258 | if (ch == '_') |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 259 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 260 | isNextUpperCase = true; |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 261 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 262 | else if (isNextUpperCase) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 263 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 264 | result.Append(char.ToUpperInvariant(ch)); |
| 265 | isNextUpperCase = false; |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 266 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 267 | else |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 268 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 269 | result.Append(ch); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 270 | } |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 271 | } |
| 272 | return result.ToString(); |
| 273 | } |
| 274 | |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 275 | private static void WriteNull(TextWriter writer) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 276 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 277 | writer.Write("null"); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 278 | } |
| 279 | |
| 280 | private static bool IsDefaultValue(IFieldAccessor accessor, object value) |
| 281 | { |
| 282 | if (accessor.Descriptor.IsMap) |
| 283 | { |
| 284 | IDictionary dictionary = (IDictionary) value; |
| 285 | return dictionary.Count == 0; |
| 286 | } |
| 287 | if (accessor.Descriptor.IsRepeated) |
| 288 | { |
| 289 | IList list = (IList) value; |
| 290 | return list.Count == 0; |
| 291 | } |
| 292 | switch (accessor.Descriptor.FieldType) |
| 293 | { |
| 294 | case FieldType.Bool: |
| 295 | return (bool) value == false; |
| 296 | case FieldType.Bytes: |
| 297 | return (ByteString) value == ByteString.Empty; |
| 298 | case FieldType.String: |
| 299 | return (string) value == ""; |
| 300 | case FieldType.Double: |
| 301 | return (double) value == 0.0; |
| 302 | case FieldType.SInt32: |
| 303 | case FieldType.Int32: |
| 304 | case FieldType.SFixed32: |
| 305 | case FieldType.Enum: |
| 306 | return (int) value == 0; |
| 307 | case FieldType.Fixed32: |
| 308 | case FieldType.UInt32: |
| 309 | return (uint) value == 0; |
| 310 | case FieldType.Fixed64: |
| 311 | case FieldType.UInt64: |
| 312 | return (ulong) value == 0; |
| 313 | case FieldType.SFixed64: |
| 314 | case FieldType.Int64: |
| 315 | case FieldType.SInt64: |
| 316 | return (long) value == 0; |
| 317 | case FieldType.Float: |
| 318 | return (float) value == 0f; |
| 319 | case FieldType.Message: |
| 320 | case FieldType.Group: // Never expect to get this, but... |
| 321 | return value == null; |
| 322 | default: |
| 323 | throw new ArgumentException("Invalid field type"); |
| 324 | } |
| 325 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 326 | |
| 327 | /// <summary> |
| 328 | /// Writes a single value to the given writer as JSON. Only types understood by |
| 329 | /// Protocol Buffers can be written in this way. This method is only exposed for |
| 330 | /// advanced use cases; most users should be using <see cref="Format(IMessage)"/> |
| 331 | /// or <see cref="Format(IMessage, TextWriter)"/>. |
| 332 | /// </summary> |
| 333 | /// <param name="writer">The writer to write the value to. Must not be null.</param> |
| 334 | /// <param name="value">The value to write. May be null.</param> |
| 335 | public void WriteValue(TextWriter writer, object value) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 336 | { |
| 337 | if (value == null) |
| 338 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 339 | WriteNull(writer); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 340 | } |
| 341 | else if (value is bool) |
| 342 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 343 | writer.Write((bool)value ? "true" : "false"); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 344 | } |
| 345 | else if (value is ByteString) |
| 346 | { |
| 347 | // Nothing in Base64 needs escaping |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 348 | writer.Write('"'); |
| 349 | writer.Write(((ByteString)value).ToBase64()); |
| 350 | writer.Write('"'); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 351 | } |
| 352 | else if (value is string) |
| 353 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 354 | WriteString(writer, (string)value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 355 | } |
| 356 | else if (value is IDictionary) |
| 357 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 358 | WriteDictionary(writer, (IDictionary)value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 359 | } |
| 360 | else if (value is IList) |
| 361 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 362 | WriteList(writer, (IList)value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 363 | } |
| 364 | else if (value is int || value is uint) |
| 365 | { |
| 366 | IFormattable formattable = (IFormattable) value; |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 367 | writer.Write(formattable.ToString("d", CultureInfo.InvariantCulture)); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 368 | } |
| 369 | else if (value is long || value is ulong) |
| 370 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 371 | writer.Write('"'); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 372 | IFormattable formattable = (IFormattable) value; |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 373 | writer.Write(formattable.ToString("d", CultureInfo.InvariantCulture)); |
| 374 | writer.Write('"'); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 375 | } |
| 376 | else if (value is System.Enum) |
| 377 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 378 | if (settings.FormatEnumsAsIntegers) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 379 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 380 | WriteValue(writer, (int)value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 381 | } |
| 382 | else |
| 383 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 384 | string name = OriginalEnumValueHelper.GetOriginalName(value); |
| 385 | if (name != null) |
| 386 | { |
| 387 | WriteString(writer, name); |
| 388 | } |
| 389 | else |
| 390 | { |
| 391 | WriteValue(writer, (int)value); |
| 392 | } |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 393 | } |
| 394 | } |
| 395 | else if (value is float || value is double) |
| 396 | { |
| 397 | string text = ((IFormattable) value).ToString("r", CultureInfo.InvariantCulture); |
| 398 | if (text == "NaN" || text == "Infinity" || text == "-Infinity") |
| 399 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 400 | writer.Write('"'); |
| 401 | writer.Write(text); |
| 402 | writer.Write('"'); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 403 | } |
| 404 | else |
| 405 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 406 | writer.Write(text); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 407 | } |
| 408 | } |
| 409 | else if (value is IMessage) |
| 410 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 411 | Format((IMessage)value, writer); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 412 | } |
| 413 | else |
| 414 | { |
| 415 | throw new ArgumentException("Unable to format value of type " + value.GetType()); |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | /// <summary> |
| 420 | /// Central interception point for well-known type formatting. Any well-known types which |
| 421 | /// don't need special handling can fall back to WriteMessage. We avoid assuming that the |
| 422 | /// values are using the embedded well-known types, in order to allow for dynamic messages |
| 423 | /// in the future. |
| 424 | /// </summary> |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 425 | private void WriteWellKnownTypeValue(TextWriter writer, MessageDescriptor descriptor, object value) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 426 | { |
| 427 | // Currently, we can never actually get here, because null values are always handled by the caller. But if we *could*, |
| 428 | // this would do the right thing. |
| 429 | if (value == null) |
| 430 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 431 | WriteNull(writer); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 432 | return; |
| 433 | } |
| 434 | // For wrapper types, the value will either be the (possibly boxed) "native" value, |
| 435 | // or the message itself if we're formatting it at the top level (e.g. just calling ToString on the object itself). |
| 436 | // If it's the message form, we can extract the value first, which *will* be the (possibly boxed) native value, |
| 437 | // and then proceed, writing it as if we were definitely in a field. (We never need to wrap it in an extra string... |
| 438 | // WriteValue will do the right thing.) |
| 439 | if (descriptor.IsWrapperType) |
| 440 | { |
| 441 | if (value is IMessage) |
| 442 | { |
| 443 | var message = (IMessage) value; |
| 444 | value = message.Descriptor.Fields[WrappersReflection.WrapperValueFieldNumber].Accessor.GetValue(message); |
| 445 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 446 | WriteValue(writer, value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 447 | return; |
| 448 | } |
| 449 | if (descriptor.FullName == Timestamp.Descriptor.FullName) |
| 450 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 451 | WriteTimestamp(writer, (IMessage)value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 452 | return; |
| 453 | } |
| 454 | if (descriptor.FullName == Duration.Descriptor.FullName) |
| 455 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 456 | WriteDuration(writer, (IMessage)value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 457 | return; |
| 458 | } |
| 459 | if (descriptor.FullName == FieldMask.Descriptor.FullName) |
| 460 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 461 | WriteFieldMask(writer, (IMessage)value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 462 | return; |
| 463 | } |
| 464 | if (descriptor.FullName == Struct.Descriptor.FullName) |
| 465 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 466 | WriteStruct(writer, (IMessage)value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 467 | return; |
| 468 | } |
| 469 | if (descriptor.FullName == ListValue.Descriptor.FullName) |
| 470 | { |
| 471 | var fieldAccessor = descriptor.Fields[ListValue.ValuesFieldNumber].Accessor; |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 472 | WriteList(writer, (IList)fieldAccessor.GetValue((IMessage)value)); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 473 | return; |
| 474 | } |
| 475 | if (descriptor.FullName == Value.Descriptor.FullName) |
| 476 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 477 | WriteStructFieldValue(writer, (IMessage)value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 478 | return; |
| 479 | } |
| 480 | if (descriptor.FullName == Any.Descriptor.FullName) |
| 481 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 482 | WriteAny(writer, (IMessage)value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 483 | return; |
| 484 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 485 | WriteMessage(writer, (IMessage)value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 486 | } |
| 487 | |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 488 | private void WriteTimestamp(TextWriter writer, IMessage value) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 489 | { |
| 490 | // TODO: In the common case where this *is* using the built-in Timestamp type, we could |
| 491 | // avoid all the reflection at this point, by casting to Timestamp. In the interests of |
| 492 | // avoiding subtle bugs, don't do that until we've implemented DynamicMessage so that we can prove |
| 493 | // it still works in that case. |
| 494 | int nanos = (int) value.Descriptor.Fields[Timestamp.NanosFieldNumber].Accessor.GetValue(value); |
| 495 | long seconds = (long) value.Descriptor.Fields[Timestamp.SecondsFieldNumber].Accessor.GetValue(value); |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 496 | writer.Write(Timestamp.ToJson(seconds, nanos, DiagnosticOnly)); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 497 | } |
| 498 | |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 499 | private void WriteDuration(TextWriter writer, IMessage value) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 500 | { |
| 501 | // TODO: Same as for WriteTimestamp |
| 502 | int nanos = (int) value.Descriptor.Fields[Duration.NanosFieldNumber].Accessor.GetValue(value); |
| 503 | long seconds = (long) value.Descriptor.Fields[Duration.SecondsFieldNumber].Accessor.GetValue(value); |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 504 | writer.Write(Duration.ToJson(seconds, nanos, DiagnosticOnly)); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 505 | } |
| 506 | |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 507 | private void WriteFieldMask(TextWriter writer, IMessage value) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 508 | { |
| 509 | var paths = (IList<string>) value.Descriptor.Fields[FieldMask.PathsFieldNumber].Accessor.GetValue(value); |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 510 | writer.Write(FieldMask.ToJson(paths, DiagnosticOnly)); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 511 | } |
| 512 | |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 513 | private void WriteAny(TextWriter writer, IMessage value) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 514 | { |
| 515 | if (DiagnosticOnly) |
| 516 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 517 | WriteDiagnosticOnlyAny(writer, value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 518 | return; |
| 519 | } |
| 520 | |
| 521 | string typeUrl = (string) value.Descriptor.Fields[Any.TypeUrlFieldNumber].Accessor.GetValue(value); |
| 522 | ByteString data = (ByteString) value.Descriptor.Fields[Any.ValueFieldNumber].Accessor.GetValue(value); |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 523 | string typeName = Any.GetTypeName(typeUrl); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 524 | MessageDescriptor descriptor = settings.TypeRegistry.Find(typeName); |
| 525 | if (descriptor == null) |
| 526 | { |
| 527 | throw new InvalidOperationException($"Type registry has no descriptor for type name '{typeName}'"); |
| 528 | } |
| 529 | IMessage message = descriptor.Parser.ParseFrom(data); |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 530 | writer.Write("{ "); |
| 531 | WriteString(writer, AnyTypeUrlField); |
| 532 | writer.Write(NameValueSeparator); |
| 533 | WriteString(writer, typeUrl); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 534 | |
| 535 | if (descriptor.IsWellKnownType) |
| 536 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 537 | writer.Write(PropertySeparator); |
| 538 | WriteString(writer, AnyWellKnownTypeValueField); |
| 539 | writer.Write(NameValueSeparator); |
| 540 | WriteWellKnownTypeValue(writer, descriptor, message); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 541 | } |
| 542 | else |
| 543 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 544 | WriteMessageFields(writer, message, true); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 545 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 546 | writer.Write(" }"); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 547 | } |
| 548 | |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 549 | private void WriteDiagnosticOnlyAny(TextWriter writer, IMessage value) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 550 | { |
| 551 | string typeUrl = (string) value.Descriptor.Fields[Any.TypeUrlFieldNumber].Accessor.GetValue(value); |
| 552 | ByteString data = (ByteString) value.Descriptor.Fields[Any.ValueFieldNumber].Accessor.GetValue(value); |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 553 | writer.Write("{ "); |
| 554 | WriteString(writer, AnyTypeUrlField); |
| 555 | writer.Write(NameValueSeparator); |
| 556 | WriteString(writer, typeUrl); |
| 557 | writer.Write(PropertySeparator); |
| 558 | WriteString(writer, AnyDiagnosticValueField); |
| 559 | writer.Write(NameValueSeparator); |
| 560 | writer.Write('"'); |
| 561 | writer.Write(data.ToBase64()); |
| 562 | writer.Write('"'); |
| 563 | writer.Write(" }"); |
| 564 | } |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 565 | |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 566 | private void WriteStruct(TextWriter writer, IMessage message) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 567 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 568 | writer.Write("{ "); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 569 | IDictionary fields = (IDictionary) message.Descriptor.Fields[Struct.FieldsFieldNumber].Accessor.GetValue(message); |
| 570 | bool first = true; |
| 571 | foreach (DictionaryEntry entry in fields) |
| 572 | { |
| 573 | string key = (string) entry.Key; |
| 574 | IMessage value = (IMessage) entry.Value; |
| 575 | if (string.IsNullOrEmpty(key) || value == null) |
| 576 | { |
| 577 | throw new InvalidOperationException("Struct fields cannot have an empty key or a null value."); |
| 578 | } |
| 579 | |
| 580 | if (!first) |
| 581 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 582 | writer.Write(PropertySeparator); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 583 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 584 | WriteString(writer, key); |
| 585 | writer.Write(NameValueSeparator); |
| 586 | WriteStructFieldValue(writer, value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 587 | first = false; |
| 588 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 589 | writer.Write(first ? "}" : " }"); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 590 | } |
| 591 | |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 592 | private void WriteStructFieldValue(TextWriter writer, IMessage message) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 593 | { |
| 594 | var specifiedField = message.Descriptor.Oneofs[0].Accessor.GetCaseFieldDescriptor(message); |
| 595 | if (specifiedField == null) |
| 596 | { |
| 597 | throw new InvalidOperationException("Value message must contain a value for the oneof."); |
| 598 | } |
| 599 | |
| 600 | object value = specifiedField.Accessor.GetValue(message); |
| 601 | |
| 602 | switch (specifiedField.FieldNumber) |
| 603 | { |
| 604 | case Value.BoolValueFieldNumber: |
| 605 | case Value.StringValueFieldNumber: |
| 606 | case Value.NumberValueFieldNumber: |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 607 | WriteValue(writer, value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 608 | return; |
| 609 | case Value.StructValueFieldNumber: |
| 610 | case Value.ListValueFieldNumber: |
| 611 | // Structs and ListValues are nested messages, and already well-known types. |
| 612 | var nestedMessage = (IMessage) specifiedField.Accessor.GetValue(message); |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 613 | WriteWellKnownTypeValue(writer, nestedMessage.Descriptor, nestedMessage); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 614 | return; |
| 615 | case Value.NullValueFieldNumber: |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 616 | WriteNull(writer); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 617 | return; |
| 618 | default: |
| 619 | throw new InvalidOperationException("Unexpected case in struct field: " + specifiedField.FieldNumber); |
| 620 | } |
| 621 | } |
| 622 | |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 623 | internal void WriteList(TextWriter writer, IList list) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 624 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 625 | writer.Write("[ "); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 626 | bool first = true; |
| 627 | foreach (var value in list) |
| 628 | { |
| 629 | if (!first) |
| 630 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 631 | writer.Write(PropertySeparator); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 632 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 633 | WriteValue(writer, value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 634 | first = false; |
| 635 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 636 | writer.Write(first ? "]" : " ]"); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 637 | } |
| 638 | |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 639 | internal void WriteDictionary(TextWriter writer, IDictionary dictionary) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 640 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 641 | writer.Write("{ "); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 642 | bool first = true; |
| 643 | // This will box each pair. Could use IDictionaryEnumerator, but that's ugly in terms of disposal. |
| 644 | foreach (DictionaryEntry pair in dictionary) |
| 645 | { |
| 646 | if (!first) |
| 647 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 648 | writer.Write(PropertySeparator); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 649 | } |
| 650 | string keyText; |
| 651 | if (pair.Key is string) |
| 652 | { |
| 653 | keyText = (string) pair.Key; |
| 654 | } |
| 655 | else if (pair.Key is bool) |
| 656 | { |
| 657 | keyText = (bool) pair.Key ? "true" : "false"; |
| 658 | } |
| 659 | else if (pair.Key is int || pair.Key is uint | pair.Key is long || pair.Key is ulong) |
| 660 | { |
| 661 | keyText = ((IFormattable) pair.Key).ToString("d", CultureInfo.InvariantCulture); |
| 662 | } |
| 663 | else |
| 664 | { |
| 665 | if (pair.Key == null) |
| 666 | { |
| 667 | throw new ArgumentException("Dictionary has entry with null key"); |
| 668 | } |
| 669 | throw new ArgumentException("Unhandled dictionary key type: " + pair.Key.GetType()); |
| 670 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 671 | WriteString(writer, keyText); |
| 672 | writer.Write(NameValueSeparator); |
| 673 | WriteValue(writer, pair.Value); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 674 | first = false; |
| 675 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 676 | writer.Write(first ? "}" : " }"); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 677 | } |
| 678 | |
| 679 | /// <summary> |
| 680 | /// Writes a string (including leading and trailing double quotes) to a builder, escaping as required. |
| 681 | /// </summary> |
| 682 | /// <remarks> |
| 683 | /// Other than surrogate pair handling, this code is mostly taken from src/google/protobuf/util/internal/json_escaping.cc. |
| 684 | /// </remarks> |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 685 | internal static void WriteString(TextWriter writer, string text) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 686 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 687 | writer.Write('"'); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 688 | for (int i = 0; i < text.Length; i++) |
| 689 | { |
| 690 | char c = text[i]; |
| 691 | if (c < 0xa0) |
| 692 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 693 | writer.Write(CommonRepresentations[c]); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 694 | continue; |
| 695 | } |
| 696 | if (char.IsHighSurrogate(c)) |
| 697 | { |
| 698 | // Encountered first part of a surrogate pair. |
| 699 | // Check that we have the whole pair, and encode both parts as hex. |
| 700 | i++; |
| 701 | if (i == text.Length || !char.IsLowSurrogate(text[i])) |
| 702 | { |
| 703 | throw new ArgumentException("String contains low surrogate not followed by high surrogate"); |
| 704 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 705 | HexEncodeUtf16CodeUnit(writer, c); |
| 706 | HexEncodeUtf16CodeUnit(writer, text[i]); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 707 | continue; |
| 708 | } |
| 709 | else if (char.IsLowSurrogate(c)) |
| 710 | { |
| 711 | throw new ArgumentException("String contains high surrogate not preceded by low surrogate"); |
| 712 | } |
| 713 | switch ((uint) c) |
| 714 | { |
| 715 | // These are not required by json spec |
| 716 | // but used to prevent security bugs in javascript. |
| 717 | case 0xfeff: // Zero width no-break space |
| 718 | case 0xfff9: // Interlinear annotation anchor |
| 719 | case 0xfffa: // Interlinear annotation separator |
| 720 | case 0xfffb: // Interlinear annotation terminator |
| 721 | |
| 722 | case 0x00ad: // Soft-hyphen |
| 723 | case 0x06dd: // Arabic end of ayah |
| 724 | case 0x070f: // Syriac abbreviation mark |
| 725 | case 0x17b4: // Khmer vowel inherent Aq |
| 726 | case 0x17b5: // Khmer vowel inherent Aa |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 727 | HexEncodeUtf16CodeUnit(writer, c); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 728 | break; |
| 729 | |
| 730 | default: |
| 731 | if ((c >= 0x0600 && c <= 0x0603) || // Arabic signs |
| 732 | (c >= 0x200b && c <= 0x200f) || // Zero width etc. |
| 733 | (c >= 0x2028 && c <= 0x202e) || // Separators etc. |
| 734 | (c >= 0x2060 && c <= 0x2064) || // Invisible etc. |
| 735 | (c >= 0x206a && c <= 0x206f)) |
| 736 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 737 | HexEncodeUtf16CodeUnit(writer, c); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 738 | } |
| 739 | else |
| 740 | { |
| 741 | // No handling of surrogates here - that's done earlier |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 742 | writer.Write(c); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 743 | } |
| 744 | break; |
| 745 | } |
| 746 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 747 | writer.Write('"'); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 748 | } |
| 749 | |
| 750 | private const string Hex = "0123456789abcdef"; |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 751 | private static void HexEncodeUtf16CodeUnit(TextWriter writer, char c) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 752 | { |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 753 | writer.Write("\\u"); |
| 754 | writer.Write(Hex[(c >> 12) & 0xf]); |
| 755 | writer.Write(Hex[(c >> 8) & 0xf]); |
| 756 | writer.Write(Hex[(c >> 4) & 0xf]); |
| 757 | writer.Write(Hex[(c >> 0) & 0xf]); |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 758 | } |
| 759 | |
| 760 | /// <summary> |
| 761 | /// Settings controlling JSON formatting. |
| 762 | /// </summary> |
| 763 | public sealed class Settings |
| 764 | { |
| 765 | /// <summary> |
| 766 | /// Default settings, as used by <see cref="JsonFormatter.Default"/> |
| 767 | /// </summary> |
| 768 | public static Settings Default { get; } |
| 769 | |
| 770 | // Workaround for the Mono compiler complaining about XML comments not being on |
| 771 | // valid language elements. |
| 772 | static Settings() |
| 773 | { |
| 774 | Default = new Settings(false); |
| 775 | } |
| 776 | |
| 777 | /// <summary> |
| 778 | /// Whether fields whose values are the default for the field type (e.g. 0 for integers) |
| 779 | /// should be formatted (true) or omitted (false). |
| 780 | /// </summary> |
| 781 | public bool FormatDefaultValues { get; } |
| 782 | |
| 783 | /// <summary> |
| 784 | /// The type registry used to format <see cref="Any"/> messages. |
| 785 | /// </summary> |
| 786 | public TypeRegistry TypeRegistry { get; } |
| 787 | |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 788 | /// <summary> |
| 789 | /// Whether to format enums as ints. Defaults to false. |
| 790 | /// </summary> |
| 791 | public bool FormatEnumsAsIntegers { get; } |
| 792 | |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 793 | |
| 794 | /// <summary> |
| 795 | /// Creates a new <see cref="Settings"/> object with the specified formatting of default values |
| 796 | /// and an empty type registry. |
| 797 | /// </summary> |
| 798 | /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param> |
| 799 | public Settings(bool formatDefaultValues) : this(formatDefaultValues, TypeRegistry.Empty) |
| 800 | { |
| 801 | } |
| 802 | |
| 803 | /// <summary> |
| 804 | /// Creates a new <see cref="Settings"/> object with the specified formatting of default values |
| 805 | /// and type registry. |
| 806 | /// </summary> |
| 807 | /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param> |
| 808 | /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages.</param> |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 809 | public Settings(bool formatDefaultValues, TypeRegistry typeRegistry) : this(formatDefaultValues, typeRegistry, false) |
| 810 | { |
| 811 | } |
| 812 | |
| 813 | /// <summary> |
| 814 | /// Creates a new <see cref="Settings"/> object with the specified parameters. |
| 815 | /// </summary> |
| 816 | /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param> |
| 817 | /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages. TypeRegistry.Empty will be used if it is null.</param> |
| 818 | /// <param name="formatEnumsAsIntegers"><c>true</c> to format the enums as integers; <c>false</c> to format enums as enum names.</param> |
| 819 | private Settings(bool formatDefaultValues, |
| 820 | TypeRegistry typeRegistry, |
| 821 | bool formatEnumsAsIntegers) |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 822 | { |
| 823 | FormatDefaultValues = formatDefaultValues; |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 824 | TypeRegistry = typeRegistry ?? TypeRegistry.Empty; |
| 825 | FormatEnumsAsIntegers = formatEnumsAsIntegers; |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 826 | } |
Austin Schuh | 40c1652 | 2018-10-28 20:27:54 -0700 | [diff] [blame^] | 827 | |
| 828 | /// <summary> |
| 829 | /// Creates a new <see cref="Settings"/> object with the specified formatting of default values and the current settings. |
| 830 | /// </summary> |
| 831 | /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param> |
| 832 | public Settings WithFormatDefaultValues(bool formatDefaultValues) => new Settings(formatDefaultValues, TypeRegistry, FormatEnumsAsIntegers); |
| 833 | |
| 834 | /// <summary> |
| 835 | /// Creates a new <see cref="Settings"/> object with the specified type registry and the current settings. |
| 836 | /// </summary> |
| 837 | /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages.</param> |
| 838 | public Settings WithTypeRegistry(TypeRegistry typeRegistry) => new Settings(FormatDefaultValues, typeRegistry, FormatEnumsAsIntegers); |
| 839 | |
| 840 | /// <summary> |
| 841 | /// Creates a new <see cref="Settings"/> object with the specified enums formatting option and the current settings. |
| 842 | /// </summary> |
| 843 | /// <param name="formatEnumsAsIntegers"><c>true</c> to format the enums as integers; <c>false</c> to format enums as enum names.</param> |
| 844 | public Settings WithFormatEnumsAsIntegers(bool formatEnumsAsIntegers) => new Settings(FormatDefaultValues, TypeRegistry, formatEnumsAsIntegers); |
| 845 | } |
| 846 | |
| 847 | // Effectively a cache of mapping from enum values to the original name as specified in the proto file, |
| 848 | // fetched by reflection. |
| 849 | // The need for this is unfortunate, as is its unbounded size, but realistically it shouldn't cause issues. |
| 850 | private static class OriginalEnumValueHelper |
| 851 | { |
| 852 | // TODO: In the future we might want to use ConcurrentDictionary, at the point where all |
| 853 | // the platforms we target have it. |
| 854 | private static readonly Dictionary<System.Type, Dictionary<object, string>> dictionaries |
| 855 | = new Dictionary<System.Type, Dictionary<object, string>>(); |
| 856 | |
| 857 | internal static string GetOriginalName(object value) |
| 858 | { |
| 859 | var enumType = value.GetType(); |
| 860 | Dictionary<object, string> nameMapping; |
| 861 | lock (dictionaries) |
| 862 | { |
| 863 | if (!dictionaries.TryGetValue(enumType, out nameMapping)) |
| 864 | { |
| 865 | nameMapping = GetNameMapping(enumType); |
| 866 | dictionaries[enumType] = nameMapping; |
| 867 | } |
| 868 | } |
| 869 | |
| 870 | string originalName; |
| 871 | // If this returns false, originalName will be null, which is what we want. |
| 872 | nameMapping.TryGetValue(value, out originalName); |
| 873 | return originalName; |
| 874 | } |
| 875 | |
| 876 | #if NET35 |
| 877 | // TODO: Consider adding functionality to TypeExtensions to avoid this difference. |
| 878 | private static Dictionary<object, string> GetNameMapping(System.Type enumType) => |
| 879 | enumType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static) |
| 880 | .Where(f => (f.GetCustomAttributes(typeof(OriginalNameAttribute), false) |
| 881 | .FirstOrDefault() as OriginalNameAttribute) |
| 882 | ?.PreferredAlias ?? true) |
| 883 | .ToDictionary(f => f.GetValue(null), |
| 884 | f => (f.GetCustomAttributes(typeof(OriginalNameAttribute), false) |
| 885 | .FirstOrDefault() as OriginalNameAttribute) |
| 886 | // If the attribute hasn't been applied, fall back to the name of the field. |
| 887 | ?.Name ?? f.Name); |
| 888 | #else |
| 889 | private static Dictionary<object, string> GetNameMapping(System.Type enumType) => |
| 890 | enumType.GetTypeInfo().DeclaredFields |
| 891 | .Where(f => f.IsStatic) |
| 892 | .Where(f => f.GetCustomAttributes<OriginalNameAttribute>() |
| 893 | .FirstOrDefault()?.PreferredAlias ?? true) |
| 894 | .ToDictionary(f => f.GetValue(null), |
| 895 | f => f.GetCustomAttributes<OriginalNameAttribute>() |
| 896 | .FirstOrDefault() |
| 897 | // If the attribute hasn't been applied, fall back to the name of the field. |
| 898 | ?.Name ?? f.Name); |
| 899 | #endif |
Brian Silverman | 9c614bc | 2016-02-15 20:20:02 -0500 | [diff] [blame] | 900 | } |
| 901 | } |
| 902 | } |