JsonInt32Converter.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using System.Buffers;
  3. using System.Buffers.Text;
  4. using System.Text.Json;
  5. using System.Text.Json.Serialization;
  6. namespace MediaBrowser.Common.Json.Converters
  7. {
  8. /// <summary>
  9. /// Converts a GUID object or value to/from JSON.
  10. /// </summary>
  11. public class JsonInt32Converter : JsonConverter<int>
  12. {
  13. /// <inheritdoc />
  14. public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  15. {
  16. static void ThrowFormatException() => throw new FormatException("Invalid format for an integer.");
  17. ReadOnlySpan<byte> span = stackalloc byte[0];
  18. if (reader.HasValueSequence)
  19. {
  20. long sequenceLength = reader.ValueSequence.Length;
  21. Span<byte> stackSpan = stackalloc byte[(int)sequenceLength];
  22. reader.ValueSequence.CopyTo(stackSpan);
  23. span = stackSpan;
  24. }
  25. else
  26. {
  27. span = reader.ValueSpan;
  28. }
  29. if (!Utf8Parser.TryParse(span, out int number, out _))
  30. {
  31. ThrowFormatException();
  32. }
  33. return number;
  34. }
  35. /// <inheritdoc />
  36. public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
  37. {
  38. static void ThrowInvalidOperationException() => throw new InvalidOperationException();
  39. Span<byte> span = stackalloc byte[16];
  40. if (Utf8Formatter.TryFormat(value, span, out int bytesWritten))
  41. {
  42. writer.WriteStringValue(span.Slice(0, bytesWritten));
  43. }
  44. ThrowInvalidOperationException();
  45. }
  46. }
  47. }