From cbd965fbda5a2a8fed78d5c9dcd152e6c7e29af9 Mon Sep 17 00:00:00 2001 From: Utkarsh Umesan Pillai <66651184+utpilla@users.noreply.github.com> Date: Thu, 2 Nov 2023 20:03:05 -0700 Subject: [PATCH] Update JsonSerializer --- .../TLDExporter/JsonSerializer.cs | 36 ++++++++++++++++--- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/src/OpenTelemetry.Exporter.Geneva/TLDExporter/JsonSerializer.cs b/src/OpenTelemetry.Exporter.Geneva/TLDExporter/JsonSerializer.cs index e80c8477c2..b475b6694b 100644 --- a/src/OpenTelemetry.Exporter.Geneva/TLDExporter/JsonSerializer.cs +++ b/src/OpenTelemetry.Exporter.Geneva/TLDExporter/JsonSerializer.cs @@ -104,6 +104,22 @@ public static int SerializeString(byte[] buffer, int cursor, string value) return cursor; } +#if NET6_0_OR_GREATER + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static int SerializeString(byte[] buffer, int cursor, ReadOnlySpan value) + { + if (value == null) + { + return SerializeNull(buffer, cursor); + } + + buffer[cursor++] = ASCII_QUOTATION_MARK; + cursor = WriteString(buffer, cursor, value); + buffer[cursor++] = ASCII_QUOTATION_MARK; + return cursor; + } +#endif + [MethodImpl(MethodImplOptions.AggressiveInlining)] public static string SerializeArray(T[] array) { @@ -316,18 +332,30 @@ public static int Serialize(byte[] buffer, int cursor, object obj) return SerializeMap(buffer, cursor, v); case object[] v: return SerializeArray(buffer, cursor, v); + #if NET6_0_OR_GREATER case ISpanFormattable v: tmp = stackalloc char[MAX_STACK_ALLOC_SIZE_IN_BYTES / sizeof(char)]; - if (v.TryFormat(tmp, out charsWritten, default, CultureInfo.InvariantCulture)) + if (v.TryFormat(tmp, out charsWritten, default, CultureInfo.InvariantCulture) && charsWritten > 0) { - return WriteString(buffer, cursor, tmp.Slice(0, charsWritten)); + return SerializeString(buffer, cursor, tmp.Slice(0, charsWritten)); } goto default; #endif + default: - return SerializeString(buffer, cursor, $"ERROR: type {obj.GetType().FullName} is not supported"); + string repr; + try + { + repr = Convert.ToString(obj, CultureInfo.InvariantCulture); + } + catch + { + repr = $"ERROR: type {obj.GetType().FullName} is not supported"; + } + + return SerializeString(buffer, cursor, repr); } } @@ -400,7 +428,7 @@ private static int WriteString(byte[] buffer, int cursor, string value) #if NET6_0_OR_GREATER [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static int WriteString(byte[] buffer, int cursor, Span value) + private static int WriteString(byte[] buffer, int cursor, ReadOnlySpan value) { for (int i = 0; i < value.Length; i++) {