~ruther/NosSmooth

ref: 762fc34c97e8b1f6e9290426b8bc2a78122e28ba NosSmooth/Packets/NosSmooth.PacketSerializer.Abstractions/PacketStringBuilder.cs -rw-r--r-- 9.4 KiB
762fc34c — Rutherther Merge pull request #82 from Rutherther/feat/serialize-stackalloc 2 years ago
                                                                                
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
//
//  PacketStringBuilder.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Buffers;
using System.Text;
using Remora.Results;

namespace NosSmooth.PacketSerializer.Abstractions;

/// <summary>
/// String builder for packets.
/// </summary>
public ref struct PacketStringBuilder
{
    private Span<char> _buffer;
    private char[]? _bufferArray;
    private int _position;
    private StringBuilderLevel _currentLevel;
    private char? _insertSeparator;

    /// <summary>
    /// Initializes a new instance of the <see cref="PacketStringBuilder"/> struct.
    /// </summary>
    /// <param name="initialBuffer">The initial buffer to store the packet to. Will grow in size if needed.</param>
    /// <param name="separator">The top level separator.</param>
    public PacketStringBuilder(Span<char> initialBuffer, char separator = ' ')
    {
        _currentLevel = new StringBuilderLevel(null, separator);
        _insertSeparator = null;
        _buffer = initialBuffer;
        _position = 0;
        _bufferArray = null;
    }

    /// <summary>
    /// Sets the separator to search for only once.
    /// </summary>
    /// <remarks>
    /// This separator will have the most priority.
    /// </remarks>
    /// <param name="separator">The separator to look for.</param>
    public void SetAfterSeparatorOnce(char separator)
    {
        _currentLevel.SeparatorOnce = separator;
    }

    /// <summary>
    /// Prepare the given level that can be set when needed.
    /// </summary>
    /// <param name="separator">The separator of the prepared level.</param>
    public void PrepareLevel(char separator)
    {
        _currentLevel.PreparedLevelSeparator = separator;
    }

    /// <summary>
    /// Reset the prepared level, if there is any.
    /// </summary>
    public void RemovePreparedLevel()
    {
        _currentLevel.PreparedLevelSeparator = null;
    }

    /// <summary>
    /// Create next level with the separator given in the prepared level.
    /// </summary>
    /// <remarks>
    /// Level of the current builder will stay the same.
    /// Will return null, if there is not a level prepared.
    /// </remarks>
    /// <returns>An enumerator with the new level pushed.</returns>
    public bool PushPreparedLevel()
    {
        if (_currentLevel.PreparedLevelSeparator is null)
        {
            return false;
        }

        _currentLevel = new StringBuilderLevel(_currentLevel, _currentLevel.PreparedLevelSeparator.Value);
        return true;
    }

    /// <summary>
    /// Push new separator level to the stack.
    /// </summary>
    /// <remarks>
    /// This will change the current enumerator.
    /// It has to be <see cref="PopLevel"/> after parent level should be used.
    /// </remarks>
    /// <param name="separator">The separator of the new level.</param>
    public void PushLevel(char separator)
    {
        _currentLevel = new StringBuilderLevel(_currentLevel, separator);
    }

    /// <summary>
    /// Pop the current level.
    /// </summary>
    /// <param name="replaceSeparator">Whether to replace the last separator with the parent one.</param>
    /// <returns>A result that may or may not have succeeded. There will be an error if the current level is the top one.</returns>
    public Result PopLevel(bool replaceSeparator = true)
    {
        if (_currentLevel.Parent is null)
        {
            return new InvalidOperationError("The level cannot be popped, the stack is already at the top level.");
        }

        if (replaceSeparator)
        {
            ReplaceWithParentSeparator();
        }

        _currentLevel = _currentLevel.Parent;

        return Result.FromSuccess();
    }

    /// <summary>
    /// Appends a value that is span formattable.
    /// </summary>
    /// <param name="value">The value to append.</param>
    /// <typeparam name="T">The span formattable type.</typeparam>
    public void Append<T>(T value)
        where T : ISpanFormattable
    {
        AppendSpanFormattable(value);
    }

    /// <summary>
    /// Appends the value to the string.
    /// </summary>
    /// <param name="value">The value to append.</param>
    public void Append(ReadOnlySpan<char> value)
    {
        BeforeAppend();
        while (!value.TryCopyTo(_buffer.Slice(_position)))
        {
            GrowBuffer(value.Length);
        }
        _position += value.Length;
        AfterAppend();
    }

    /// <summary>
    /// Appends the value to the string.
    /// </summary>
    /// <param name="value">The value to append.</param>
    public void Append(int value)
        => AppendSpanFormattable(value);

    /// <summary>
    /// Appends the value to the string.
    /// </summary>
    /// <param name="value">The value to append.</param>
    public void Append(uint value)
        => AppendSpanFormattable(value);

    /// <summary>
    /// Appends the value to the string.
    /// </summary>
    /// <param name="value">The value to append.</param>
    public void Append(short value)
        => AppendSpanFormattable(value);

    /// <summary>
    /// Appends the value to the string.
    /// </summary>
    /// <param name="value">The value to append.</param>
    public void Append(char value)
        => AppendSpanFormattable(value);

    /// <summary>
    /// Appends the value to the string.
    /// </summary>
    /// <param name="value">The value to append.</param>
    public void Append(ushort value)
        => AppendSpanFormattable(value);

    /// <summary>
    /// Appends the value to the string.
    /// </summary>
    /// <param name="value">The value to append.</param>
    public void Append(long value)
        => AppendSpanFormattable(value);

    /// <summary>
    /// Appends the value to the string.
    /// </summary>
    /// <param name="value">The value to append.</param>
    public void Append(ulong value)
        => AppendSpanFormattable(value);

    /// <summary>
    /// Appends the value to the string.
    /// </summary>
    /// <param name="value">The value to append.</param>
    public void Append(byte value)
        => AppendSpanFormattable(value);

    /// <summary>
    /// Appends the value to the string.
    /// </summary>
    /// <param name="value">The value to append.</param>
    public void Append(sbyte value)
        => AppendSpanFormattable(value);

    /// <summary>
    /// Appends the value to the string.
    /// </summary>
    /// <param name="value">The value to append.</param>
    public void Append(float value)
        => AppendSpanFormattable(value);

    /// <summary>
    /// Appends the value to the string.
    /// </summary>
    /// <param name="value">The value to append.</param>
    public void Append(double value)
        => AppendSpanFormattable(value);

    /// <summary>
    /// Appends the value to the string.
    /// </summary>
    /// <param name="value">The value to append.</param>
    public void Append(decimal value)
        => AppendSpanFormattable(value);

    /// <summary>
    /// Returns buffer to ArrayPool if it has been used.
    /// </summary>
    public void Dispose()
    {
        if (_bufferArray is not null)
        {
            ArrayPool<char>.Shared.Return(_bufferArray);
        }
    }

    private void AppendSpanFormattable<T>(T value)
        where T : ISpanFormattable
    {
        BeforeAppend();
        int charsWritten;
        while (!value.TryFormat(_buffer.Slice(_position), out charsWritten, default, null))
        {
            GrowBuffer();
        }
        _position += charsWritten;
        AfterAppend();
    }

    private void GrowBuffer(int needed = 0)
    {
        var sizeNeeded = _buffer.Length + needed;
        var doubleSize = _buffer.Length * 2;
        var newSize = Math.Max(doubleSize, sizeNeeded);
        var newBuffer = ArrayPool<char>.Shared.Rent(newSize);

        _buffer.CopyTo(newBuffer);
        _buffer = newBuffer;

        if (_bufferArray is not null)
        {
            ArrayPool<char>.Shared.Return(_bufferArray);
        }
        _bufferArray = newBuffer;
    }

    private void BeforeAppend()
    {
        if (_insertSeparator is not null)
        {
            if (_buffer.Length <= _position + 1)
            {
                GrowBuffer();
            }

            _buffer[_position] = _insertSeparator.Value;
            _position += 1;
            _insertSeparator = null;
        }
    }

    private void AfterAppend()
    {
        _insertSeparator = _currentLevel.SeparatorOnce ?? _currentLevel.Separator;
        _currentLevel.SeparatorOnce = null;
    }

    /// <summary>
    /// Replace the last separator with the parent separator.
    /// </summary>
    public void ReplaceWithParentSeparator()
    {
        var parent = _currentLevel.Parent;
        if (_insertSeparator is null || parent is null)
        {
            return;
        }

        _insertSeparator = parent.SeparatorOnce ?? parent.Separator;
        parent.SeparatorOnce = null;
    }

    /// <inheritdoc />
    public override string ToString()
    {
        return _buffer.Slice(0, _position).ToString();
    }

    private class StringBuilderLevel
    {
        public StringBuilderLevel(StringBuilderLevel? parent, char separator)
        {
            Parent = parent;
            Separator = separator;
        }

        public StringBuilderLevel? Parent { get; }

        public char? PreparedLevelSeparator { get; set; }

        public char Separator { get; }

        public char? SeparatorOnce { get; set; }
    }
}
Do not follow this link