-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathJsonVersionConverter.cs
61 lines (55 loc) · 1.92 KB
/
JsonVersionConverter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#if NETSTANDARD2_1_OR_GREATER
using System.Buffers;
#endif
using Macross.Json.Extensions;
namespace System.Text.Json.Serialization
{
/// <summary>
/// <see cref="JsonConverterFactory"/> to convert <see cref="Version"/> to and from strings.
/// </summary>
public class JsonVersionConverter : JsonConverter<Version>
{
#if NETSTANDARD2_1_OR_GREATER
private const int MaxLength = (4 * 11) + 3;
#endif
/// <inheritdoc/>
public override Version Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.String)
throw ThrowHelper.GenerateJsonException_DeserializeUnableToConvertValue(typeof(Version));
#if NETSTANDARD2_1_OR_GREATER
Span<char> charData = stackalloc char[MaxLength];
int count = Encoding.UTF8.GetChars(
reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan,
charData);
return !Version.TryParse(charData.Slice(0, count), out Version value)
? throw ThrowHelper.GenerateJsonException_DeserializeUnableToConvertValue(typeof(Version))
: value;
#else
string value = reader.GetString()!;
try
{
return Version.Parse(value);
}
catch (Exception ex)
{
throw ThrowHelper.GenerateJsonException_DeserializeUnableToConvertValue(typeof(Version), value, ex);
}
#endif
}
/// <inheritdoc/>
public override void Write(Utf8JsonWriter writer, Version value, JsonSerializerOptions options)
{
#pragma warning disable CA1062 // Don't perform checks for performance. Trust our callers will be nice.
#if NETSTANDARD2_1_OR_GREATER
Span<char> data = stackalloc char[MaxLength];
if (!value.TryFormat(data, out int charsWritten))
throw new JsonException($"Version [{value}] could not be written to JSON.");
writer.WriteStringValue(data.Slice(0, charsWritten));
#else
writer.WriteStringValue(value.ToString());
#endif
#pragma warning restore CA1062 // Validate arguments of public methods
}
}
}