| | 1 | | // Copyright (c) 2020-2024 dotBunny Inc. |
| | 2 | | // dotBunny licenses this file to you under the BSL-1.0 license. |
| | 3 | | // See the LICENSE file in the project root for more information. |
| | 4 | |
|
| | 5 | | using System.Runtime.CompilerServices; |
| | 6 | | using System.Runtime.InteropServices; |
| | 7 | |
|
| | 8 | | namespace GDX.Collections |
| | 9 | | { |
| | 10 | | /// <summary> |
| | 11 | | /// A 128-bit array. |
| | 12 | | /// </summary> |
| | 13 | | /// <example> |
| | 14 | | /// Useful for packing a bunch of data with known indices tightly. |
| | 15 | | /// <code> |
| | 16 | | /// if(myBitArray128[1]) |
| | 17 | | /// { |
| | 18 | | /// BeAwesome(); |
| | 19 | | /// } |
| | 20 | | /// </code> |
| | 21 | | /// </example> |
| | 22 | | [StructLayout(LayoutKind.Sequential)] |
| | 23 | | public struct BitArray128 |
| | 24 | | { |
| | 25 | | /// <summary> |
| | 26 | | /// First reserved <see cref="System.Int32" /> memory block. |
| | 27 | | /// </summary> |
| | 28 | | /// <remarks>Indices 0-31</remarks> |
| | 29 | | public int Bits0; |
| | 30 | |
|
| | 31 | | /// <summary> |
| | 32 | | /// Second reserved <see cref="System.Int32" /> memory block. |
| | 33 | | /// </summary> |
| | 34 | | /// <remarks>Indices 32-63</remarks> |
| | 35 | | public int Bits1; |
| | 36 | |
|
| | 37 | | /// <summary> |
| | 38 | | /// Third reserved <see cref="System.Int32" /> memory block. |
| | 39 | | /// </summary> |
| | 40 | | /// <remarks>Indices 64-95</remarks> |
| | 41 | | public int Bits2; |
| | 42 | |
|
| | 43 | | /// <summary> |
| | 44 | | /// Fourth reserved <see cref="System.Int32" /> memory block. |
| | 45 | | /// </summary> |
| | 46 | | /// <remarks>Indices 96-127</remarks> |
| | 47 | | public int Bits3; |
| | 48 | |
|
| | 49 | | /// <summary> |
| | 50 | | /// Access bit in array. |
| | 51 | | /// </summary> |
| | 52 | | /// <param name="index">Target bit index.</param> |
| | 53 | | public unsafe bool this[int index] |
| | 54 | | { |
| | 55 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 56 | | get |
| 0 | 57 | | { |
| 0 | 58 | | int intIndex = (index & 127) >> 5; |
| 0 | 59 | | int bitIndex = index & 31; |
| | 60 | | int intContainingBits; |
| 0 | 61 | | fixed (BitArray128* array = &this) { intContainingBits = ((int*)array)[intIndex]; } |
| | 62 | |
|
| 0 | 63 | | return (intContainingBits & (1 << bitIndex)) != 0; |
| 0 | 64 | | } |
| | 65 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 66 | | set |
| 0 | 67 | | { |
| 0 | 68 | | int intIndex = (index & 127) >> 5; |
| 0 | 69 | | int bitIndex = index & 31; |
| 0 | 70 | | int negativeVal = value ? -1 : 0; |
| 0 | 71 | | fixed (int* array = &Bits0) |
| 0 | 72 | | { |
| 0 | 73 | | array[intIndex] ^= (negativeVal ^ array[intIndex]) & (1 << bitIndex); |
| 0 | 74 | | } |
| 0 | 75 | | } |
| | 76 | | } |
| | 77 | | } |
| | 78 | | } |