aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Common/Json/Converters/JsonInt32Converter.cs
diff options
context:
space:
mode:
authordkanada <dkanada@users.noreply.github.com>2020-01-09 15:10:29 +0900
committerGitHub <noreply@github.com>2020-01-09 15:10:29 +0900
commit162c1ac7b7fde0e4929cf262b0f275e3eb15524c (patch)
tree18283951ed26d9c5190ff8226a0269fe388643cd /MediaBrowser.Common/Json/Converters/JsonInt32Converter.cs
parent124a852787ff94201de452a952eb31376beafe12 (diff)
parentb1af8a4178b5d993b09e5682a0149ea37766ff91 (diff)
Merge pull request #2185 from Bond-009/scanerrors
Fix exceptions while scanning
Diffstat (limited to 'MediaBrowser.Common/Json/Converters/JsonInt32Converter.cs')
-rw-r--r--MediaBrowser.Common/Json/Converters/JsonInt32Converter.cs53
1 files changed, 53 insertions, 0 deletions
diff --git a/MediaBrowser.Common/Json/Converters/JsonInt32Converter.cs b/MediaBrowser.Common/Json/Converters/JsonInt32Converter.cs
new file mode 100644
index 000000000..fe5dd6cd4
--- /dev/null
+++ b/MediaBrowser.Common/Json/Converters/JsonInt32Converter.cs
@@ -0,0 +1,53 @@
+using System;
+using System.Buffers;
+using System.Buffers.Text;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace MediaBrowser.Common.Json.Converters
+{
+ /// <summary>
+ /// Converts a GUID object or value to/from JSON.
+ /// </summary>
+ public class JsonInt32Converter : JsonConverter<int>
+ {
+ /// <inheritdoc />
+ public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ static void ThrowFormatException() => throw new FormatException("Invalid format for an integer.");
+ ReadOnlySpan<byte> span = stackalloc byte[0];
+
+ if (reader.HasValueSequence)
+ {
+ long sequenceLength = reader.ValueSequence.Length;
+ Span<byte> stackSpan = stackalloc byte[(int)sequenceLength];
+ reader.ValueSequence.CopyTo(stackSpan);
+ span = stackSpan;
+ }
+ else
+ {
+ span = reader.ValueSpan;
+ }
+
+ if (!Utf8Parser.TryParse(span, out int number, out _))
+ {
+ ThrowFormatException();
+ }
+
+ return number;
+ }
+
+ /// <inheritdoc />
+ public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
+ {
+ static void ThrowInvalidOperationException() => throw new InvalidOperationException();
+ Span<byte> span = stackalloc byte[16];
+ if (Utf8Formatter.TryFormat(value, span, out int bytesWritten))
+ {
+ writer.WriteStringValue(span.Slice(0, bytesWritten));
+ }
+
+ ThrowInvalidOperationException();
+ }
+ }
+}