CSharp · Console
using System;
using System.Collections.Generic;
using System.Linq;
Dictionary<string, Type> seedDataDictionary = new()
{
[nameof(Int32)] = typeof(int),
[nameof(Object)] = typeof(object),
[nameof(String)] = typeof(string),
[nameof(Boolean)] = typeof(bool)
};
// Sort keys by length to make IndexOf behavior predictable
seedDataDictionary = seedDataDictionary
.OrderBy(x => x.Key.Length)
.ToDictionary(x => x.Key, x => x.Value);
string keysConcat = string.Join("", seedDataDictionary.Keys);
List<int> keyOffsets = new();
List<int> keyLengths = new();
List<Type> values = new();
int keyOffset = 0;
foreach (var pair in seedDataDictionary)
{
keyOffsets.Add(keyOffset);
keyLengths.Add(pair.Key.Length);
values.Add(pair.Value);
keyOffset += pair.Key.Length;
}
Console.WriteLine($$"""
// <auto-generated />
public static class StaticLookupTable
{
public static bool TryFind(ReadOnlySpan<char> key, out Type value)
{
if (key.Length == 0)
{
value = default;
return false;
}
ReadOnlySpan<char> keysConcat = "{{keysConcat}}";
ReadOnlySpan<int> keyOffsets = [{{string.Join(", ", keyOffsets)}}];
ReadOnlySpan<int> keyLengths = [{{string.Join(", ", keyLengths)}}];
ReadOnlySpan<Type> values = [typeof({{string.Join("), typeof(", values)}})];
int searchStart = 0;
while (true)
{
int foundOffset = searchStart + keysConcat[searchStart..].IndexOf(key);
if (foundOffset < 0)
{
value = default;
return false;
}
int keyIndex = keyOffsets.IndexOf(foundOffset);
if (key.Length != keyLengths[keyIndex])
{
if (keyIndex + 1 >= keyOffsets.Length)
{
value = default;
return false;
}
searchStart = keyOffsets[keyIndex + 1];
continue;
}
value = values[keyIndex];
return true;
}
}
}
""");