// Copyright Epic Games, Inc. All Rights Reserved.
using System;
namespace EpicGames.Horde
{
///
/// Normalized string identifier for a resource
///
struct StringId : IEquatable
{
///
/// The text representing this id
///
public string Text { get; }
///
/// Constructor
///
/// Unique id for the string
public StringId(string input)
{
Text = input;
if (Text.Length == 0)
{
throw new ArgumentException("String id may not be empty");
}
const int MaxLength = 64;
if (Text.Length > MaxLength)
{
throw new ArgumentException($"String id may not be longer than {MaxLength} characters");
}
for (int idx = 0; idx < Text.Length; idx++)
{
char character = Text[idx];
if (!IsValidCharacter(character))
{
if (character >= 'A' && character <= 'Z')
{
#pragma warning disable CA1308 // Normalize strings to uppercase
Text = Text.ToLowerInvariant();
#pragma warning restore CA1308 // Normalize strings to uppercase
}
else
{
throw new ArgumentException($"{Text} is not a valid string id");
}
}
}
}
///
/// Checks whether this StringId is set
///
public bool IsEmpty => String.IsNullOrEmpty(Text);
///
/// Checks whether the given character is valid within a string id
///
/// The character to check
/// True if the character is valid
static bool IsValidCharacter(char character)
{
if (character >= 'a' && character <= 'z')
{
return true;
}
if (character >= '0' && character <= '9')
{
return true;
}
if (character == '-' || character == '_' || character == '.')
{
return true;
}
return false;
}
///
public override bool Equals(object? obj) => obj is StringId id && Equals(id);
///
public override int GetHashCode() => Text.GetHashCode(StringComparison.Ordinal);
///
public bool Equals(StringId other) => Text.Equals(other.Text, StringComparison.Ordinal);
///
public override string ToString() => Text;
///
/// Compares two string ids for equality
///
/// The first string id
/// Second string id
/// True if the two string ids are equal
public static bool operator ==(StringId left, StringId right) => left.Equals(right);
///
/// Compares two string ids for inequality
///
/// The first string id
/// Second string id
/// True if the two string ids are not equal
public static bool operator !=(StringId left, StringId right) => !left.Equals(right);
}
}