2024-07-20 11:51:52 +00:00
|
|
|
namespace PkmnLib.Static.Utils;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// A case-insensitive string key. We use this class for things like looking up data from dictionaries, etc.
|
|
|
|
/// </summary>
|
|
|
|
/// <remarks>
|
|
|
|
/// This is a struct, as it's effectively just a wrapper around a single reference object. Heap allocation would be silly.
|
|
|
|
/// </remarks>
|
|
|
|
public readonly record struct StringKey
|
|
|
|
{
|
|
|
|
private readonly string _key;
|
|
|
|
|
2024-07-20 14:12:39 +00:00
|
|
|
/// <inheritdoc cref="StringKey"/>
|
2024-07-20 11:51:52 +00:00
|
|
|
public StringKey(string key)
|
|
|
|
{
|
2024-07-28 10:18:12 +00:00
|
|
|
if (string.IsNullOrWhiteSpace(key))
|
|
|
|
throw new ArgumentException("Key cannot be null or whitespace.", nameof(key));
|
2024-07-20 11:51:52 +00:00
|
|
|
_key = key;
|
|
|
|
}
|
|
|
|
|
2024-07-20 14:12:39 +00:00
|
|
|
/// <summary>
|
|
|
|
/// Converts a <see cref="StringKey"/> to a <see cref="string"/>.
|
|
|
|
/// </summary>
|
2024-07-20 11:51:52 +00:00
|
|
|
public static implicit operator string(StringKey key) => key._key;
|
2024-07-20 14:12:39 +00:00
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Converts a <see cref="string"/> to a <see cref="StringKey"/>.
|
|
|
|
/// </summary>
|
2024-09-03 07:31:32 +00:00
|
|
|
public static implicit operator StringKey(string key)
|
|
|
|
{
|
|
|
|
return string.IsNullOrWhiteSpace(key) ? default : new StringKey(key);
|
|
|
|
}
|
2024-07-20 11:51:52 +00:00
|
|
|
|
2024-07-20 14:12:39 +00:00
|
|
|
/// <inheritdoc cref="string.ToString()"/>
|
2024-07-20 11:51:52 +00:00
|
|
|
public override string ToString() => _key.ToLowerInvariant();
|
|
|
|
|
2024-07-20 14:12:39 +00:00
|
|
|
/// <inheritdoc />
|
|
|
|
public bool Equals(StringKey other) => string.Equals(_key, other._key, StringComparison.InvariantCultureIgnoreCase);
|
2024-07-20 11:51:52 +00:00
|
|
|
|
2024-07-20 14:12:39 +00:00
|
|
|
/// <inheritdoc />
|
|
|
|
public override int GetHashCode() => StringComparer.InvariantCultureIgnoreCase.GetHashCode(_key);
|
2024-07-20 11:51:52 +00:00
|
|
|
}
|