| | | 1 | | // Licensed to the .NET Foundation under one or more agreements. |
| | | 2 | | // The .NET Foundation licenses this file to you under the MIT license. |
| | | 3 | | |
| | | 4 | | using System.Diagnostics; |
| | | 5 | | using System.Text.Json.Schema; |
| | | 6 | | |
| | | 7 | | namespace System.Text.Json.Serialization.Converters |
| | | 8 | | { |
| | | 9 | | internal sealed class CharConverter : JsonPrimitiveConverter<char> |
| | | 10 | | { |
| | | 11 | | private const int MaxEscapedCharacterLength = JsonConstants.MaxExpansionFactorWhileEscaping; |
| | | 12 | | |
| | | 13 | | public override char Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) |
| | 648 | 14 | | { |
| | 648 | 15 | | if (reader.TokenType is not (JsonTokenType.String or JsonTokenType.PropertyName)) |
| | 364 | 16 | | { |
| | 364 | 17 | | ThrowHelper.ThrowInvalidOperationException_ExpectedString(reader.TokenType); |
| | | 18 | | } |
| | | 19 | | |
| | 284 | 20 | | if (!JsonHelpers.IsInRangeInclusive(reader.ValueLength, 1, MaxEscapedCharacterLength)) |
| | 168 | 21 | | { |
| | 168 | 22 | | ThrowHelper.ThrowInvalidOperationException_ExpectedChar(reader.TokenType); |
| | | 23 | | } |
| | | 24 | | |
| | 116 | 25 | | Span<char> buffer = stackalloc char[MaxEscapedCharacterLength]; |
| | 116 | 26 | | int charsWritten = reader.CopyString(buffer); |
| | | 27 | | |
| | 52 | 28 | | if (charsWritten != 1) |
| | 26 | 29 | | { |
| | 26 | 30 | | ThrowHelper.ThrowInvalidOperationException_ExpectedChar(reader.TokenType); |
| | | 31 | | } |
| | | 32 | | |
| | 26 | 33 | | return buffer[0]; |
| | 26 | 34 | | } |
| | | 35 | | |
| | | 36 | | public override void Write(Utf8JsonWriter writer, char value, JsonSerializerOptions options) |
| | 0 | 37 | | { |
| | 0 | 38 | | writer.WriteStringValue( |
| | 0 | 39 | | #if NET |
| | 0 | 40 | | new ReadOnlySpan<char>(in value) |
| | 0 | 41 | | #else |
| | 0 | 42 | | value.ToString() |
| | 0 | 43 | | #endif |
| | 0 | 44 | | ); |
| | 0 | 45 | | } |
| | | 46 | | |
| | | 47 | | internal override char ReadAsPropertyNameCore(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptio |
| | 0 | 48 | | { |
| | 0 | 49 | | Debug.Assert(reader.TokenType == JsonTokenType.PropertyName); |
| | 0 | 50 | | return Read(ref reader, typeToConvert, options); |
| | 0 | 51 | | } |
| | | 52 | | |
| | | 53 | | internal override void WriteAsPropertyNameCore(Utf8JsonWriter writer, char value, JsonSerializerOptions options, |
| | 0 | 54 | | { |
| | 0 | 55 | | writer.WritePropertyName( |
| | 0 | 56 | | #if NET |
| | 0 | 57 | | new ReadOnlySpan<char>(in value) |
| | 0 | 58 | | #else |
| | 0 | 59 | | value.ToString() |
| | 0 | 60 | | #endif |
| | 0 | 61 | | ); |
| | 0 | 62 | | } |
| | | 63 | | |
| | | 64 | | internal override JsonSchema? GetSchema(JsonNumberHandling _) => |
| | 0 | 65 | | new() { Type = JsonSchemaType.String, MinLength = 1, MaxLength = 1 }; |
| | | 66 | | } |
| | | 67 | | } |