TimeSpanConverter
using System.Buffers;
using System.Buffers.Text;
namespace System.Text.Json.Serialization.Converters
{
internal sealed class TimeSpanConverter : JsonConverter<TimeSpan>
{
private const int MinimumTimeSpanFormatLength = 8;
private const int MaximumTimeSpanFormatLength = 26;
private const int MaximumEscapedTimeSpanFormatLength = 156;
public unsafe override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.String)
throw ThrowHelper.GetInvalidOperationException_ExpectedString(reader.TokenType);
bool stringHasEscaping = reader._stringHasEscaping;
int num = stringHasEscaping ? 156 : 26;
ReadOnlySpan<byte> readOnlySpan = default(Span<byte>);
if (reader.HasValueSequence) {
ReadOnlySequence<byte> source = reader.ValueSequence;
long length = source.Length;
if (!JsonHelpers.IsInRangeInclusive(length, 8, num))
throw ThrowHelper.GetFormatException(DataType.TimeSpan);
int num2 = stringHasEscaping ? 156 : 26;
Span<byte> span = new Span<byte>(stackalloc byte[(int)(uint)num2], num2);
Span<byte> destination = span;
ref source.CopyTo(destination);
readOnlySpan = destination.Slice(0, (int)length);
} else {
readOnlySpan = reader.ValueSpan;
if (!JsonHelpers.IsInRangeInclusive(readOnlySpan.Length, 8, num))
throw ThrowHelper.GetFormatException(DataType.TimeSpan);
}
if (stringHasEscaping) {
int idx = readOnlySpan.IndexOf<byte>(92);
Span<byte> span = new Span<byte>(stackalloc byte[156], 156);
Span<byte> destination2 = span;
JsonReaderHelper.Unescape(readOnlySpan, destination2, idx, out int written);
readOnlySpan = destination2.Slice(0, written);
}
byte b = readOnlySpan[0];
if (!JsonHelpers.IsDigit(b) && b != 45)
throw ThrowHelper.GetFormatException(DataType.TimeSpan);
if (Utf8Parser.TryParse(readOnlySpan, out TimeSpan value, out int bytesConsumed, 'c') && readOnlySpan.Length == bytesConsumed)
return value;
throw ThrowHelper.GetFormatException(DataType.TimeSpan);
}
public unsafe override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options)
{
Span<byte> span = new Span<byte>(stackalloc byte[26], 26);
Span<byte> destination = span;
int bytesWritten;
bool flag = Utf8Formatter.TryFormat(value, destination, out bytesWritten, 'c');
writer.WriteStringValue(destination.Slice(0, bytesWritten));
}
}
}