| | | 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.Collections.Generic; |
| | | 5 | | using System.Diagnostics; |
| | | 6 | | using System.Diagnostics.CodeAnalysis; |
| | | 7 | | using System.Runtime.InteropServices; |
| | | 8 | | |
| | | 9 | | namespace System.Text.Json |
| | | 10 | | { |
| | | 11 | | /// <summary> |
| | | 12 | | /// A struct variant of <see cref="Queue{T}"/> that only allocates for Counts > 1. |
| | | 13 | | /// </summary> |
| | | 14 | | [StructLayout(LayoutKind.Auto)] |
| | | 15 | | internal struct ValueQueue<T> |
| | | 16 | | { |
| | | 17 | | private byte _state; // 0 = empty, 1 = single, 2 = multiple |
| | | 18 | | private T? _single; |
| | | 19 | | private Queue<T>? _multiple; |
| | | 20 | | |
| | | 21 | | public readonly int Count => _state < 2 ? _state : _multiple!.Count; |
| | | 22 | | |
| | | 23 | | public void Enqueue(T value) |
| | 0 | 24 | | { |
| | 0 | 25 | | switch (_state) |
| | | 26 | | { |
| | | 27 | | case 0: |
| | 0 | 28 | | _single = value; |
| | 0 | 29 | | _state = 1; |
| | 0 | 30 | | break; |
| | | 31 | | |
| | | 32 | | case 1: |
| | | 33 | | // Once a queue gets allocated the struct will always remain in the multiple state. |
| | 0 | 34 | | (_multiple ??= new()).Enqueue(_single!); |
| | 0 | 35 | | _single = default; |
| | 0 | 36 | | _state = 2; |
| | 0 | 37 | | goto default; |
| | | 38 | | |
| | | 39 | | default: |
| | 0 | 40 | | Debug.Assert(_multiple != null); |
| | 0 | 41 | | _multiple.Enqueue(value); |
| | 0 | 42 | | break; |
| | | 43 | | } |
| | 0 | 44 | | } |
| | | 45 | | |
| | | 46 | | public bool TryDequeue([MaybeNullWhen(false)] out T? value) |
| | 0 | 47 | | { |
| | 0 | 48 | | switch (_state) |
| | | 49 | | { |
| | | 50 | | case 0: |
| | 0 | 51 | | value = default; |
| | 0 | 52 | | return false; |
| | | 53 | | |
| | | 54 | | case 1: |
| | 0 | 55 | | value = _single; |
| | 0 | 56 | | _single = default; |
| | 0 | 57 | | _state = 0; |
| | 0 | 58 | | return true; |
| | | 59 | | |
| | | 60 | | default: |
| | 0 | 61 | | Debug.Assert(_multiple != null); |
| | 0 | 62 | | return _multiple.TryDequeue(out value); |
| | | 63 | | } |
| | 0 | 64 | | } |
| | | 65 | | } |
| | | 66 | | } |