TimeSpanConverter
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)
ThrowHelper.
ThrowInvalidOperationException_ExpectedString(
reader.
TokenType);
if (!
JsonHelpers.
IsInRangeInclusive(
reader.
ValueLength,
8,
156))
ThrowHelper.
ThrowFormatException(
DataType.
TimeSpan);
ReadOnlySpan<
byte>
source;
if (!
reader.
HasValueSequence && !
reader.
ValueIsEscaped)
source =
reader.
ValueSpan;
else {
Span<
byte>
span =
new Span<
byte>(
stackalloc byte[
156],
156);
Span<
byte>
utf8Destination =
span;
int length =
reader.
CopyString(
utf8Destination);
source =
utf8Destination.
Slice(
0,
length);
}
byte b =
source[
0];
if (!
JsonHelpers.
IsDigit(
b) &&
b !=
45)
ThrowHelper.
ThrowFormatException(
DataType.
TimeSpan);
if (!
Utf8Parser.
TryParse(
source,
out TimeSpan value,
out int bytesConsumed,
'c') ||
source.
Length !=
bytesConsumed)
ThrowHelper.
ThrowFormatException(
DataType.
TimeSpan);
return value;
}
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));
}
}
}