Skip to content

Instantly share code, notes, and snippets.

@lahma
Created November 24, 2023 18:29
Show Gist options
  • Save lahma/109a7eb3b76d6858a24fd9b51d15212f to your computer and use it in GitHub Desktop.
Save lahma/109a7eb3b76d6858a24fd9b51d15212f to your computer and use it in GitHub Desktop.
SearchValues shim for > 10 char basic ASCII strings
#if !NET8_0_OR_GREATER
using System.Runtime.CompilerServices;
namespace System.Buffers;
internal static class SearchValues
{
internal static SearchValues<char> Create(string input) => new(input.AsSpan());
internal static SearchValues<char> Create(ReadOnlySpan<char> input) => new(input);
}
internal sealed class SearchValues<T>
{
private readonly bool[] _data;
private readonly char _min;
private readonly char _max;
internal SearchValues(ReadOnlySpan<char> input)
{
_min = char.MaxValue;
_max = char.MinValue;
foreach (var c in input)
{
_min = (char) Math.Min(_min, c);
_max = (char) Math.Max(_max, c);
}
_data = new bool[_max - _min + 1];
foreach (var c in input)
{
_data[c - _min] = true;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Contains(char c)
{
var i = (uint) (c - _min);
var temp = _data;
return i < temp.Length && temp[i];
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment