/
Utf8Formatter.Boolean.cs
88 lines (82 loc) · 2.82 KB
/
Utf8Formatter.Boolean.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Buffers.Text
{
public static partial class Utf8Formatter
{
/// <summary>
/// Formats a Boolean as a UTF-8 string.
/// </summary>
/// <param name="value">Value to format</param>
/// <param name="destination">Buffer to write the UTF-8 formatted value to</param>
/// <param name="bytesWritten">Receives the length of the formatted text in bytes</param>
/// <param name="format">The standard format to use</param>
/// <returns>
/// true for success. "bytesWritten" contains the length of the formatted text in bytes.
/// false if buffer was too short. Iteratively increase the size of the buffer and retry until it succeeds.
/// </returns>
/// <remarks>
/// Formats supported:
/// G (default) True/False
/// l true/false
/// </remarks>
/// <exceptions>
/// <cref>System.FormatException</cref> if the format is not valid for this data type.
/// </exceptions>
public static bool TryFormat(bool value, Span<byte> destination, out int bytesWritten, StandardFormat format = default)
{
char symbol = FormattingHelpers.GetSymbolOrDefault(format, 'G');
if (value)
{
if (symbol == 'G')
{
if (!"True"u8.TryCopyTo(destination))
{
goto BufferTooSmall;
}
}
else if (symbol == 'l')
{
if (!"true"u8.TryCopyTo(destination))
{
goto BufferTooSmall;
}
}
else
{
goto BadFormat;
}
bytesWritten = 4;
return true;
}
else
{
if (symbol == 'G')
{
if (!"False"u8.TryCopyTo(destination))
{
goto BufferTooSmall;
}
}
else if (symbol == 'l')
{
if (!"false"u8.TryCopyTo(destination))
{
goto BufferTooSmall;
}
}
else
{
goto BadFormat;
}
bytesWritten = 5;
return true;
}
BadFormat:
ThrowHelper.ThrowFormatException_BadFormatSpecifier();
BufferTooSmall:
bytesWritten = 0;
return false;
}
}
}