-
Notifications
You must be signed in to change notification settings - Fork 1
/
BitHelper.cs
41 lines (36 loc) · 1.36 KB
/
BitHelper.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Collections.Generic
{
internal ref struct BitHelper
{
private const int IntSize = sizeof(int) * 8;
private readonly Span<int> _span;
internal BitHelper(Span<int> span, bool clear)
{
if (clear)
{
span.Clear();
}
_span = span;
}
internal void MarkBit(int bitPosition)
{
int bitArrayIndex = bitPosition / IntSize;
if ((uint)bitArrayIndex < (uint)_span.Length)
{
_span[bitArrayIndex] |= (1 << (bitPosition % IntSize));
}
}
internal bool IsMarked(int bitPosition)
{
int bitArrayIndex = bitPosition / IntSize;
return
(uint)bitArrayIndex < (uint)_span.Length &&
(_span[bitArrayIndex] & (1 << (bitPosition % IntSize))) != 0;
}
/// <summary>How many ints must be allocated to represent n bits. Returns (n+31)/32, but avoids overflow.</summary>
internal static int ToIntArrayLength(int n) => n > 0 ? ((n - 1) / IntSize + 1) : 0;
}
}