DragonECS/src/DebugUtils/MetaAttributes/MetaIDAttribute.cs

74 lines
2.2 KiB
C#
Raw Normal View History

using DCFApixels.DragonECS.Internal;
using System;
using System.Runtime.InteropServices;
2024-10-12 20:06:21 +08:00
using System.Text.RegularExpressions;
namespace DCFApixels.DragonECS
{
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Interface, Inherited = false, AllowMultiple = false)]
public sealed class MetaIDAttribute : EcsMetaAttribute
{
public readonly string ID;
public MetaIDAttribute(string id)
{
if (string.IsNullOrEmpty(id))
{
Throw.ArgumentNull(nameof(id));
}
2024-10-12 20:06:21 +08:00
if (MetaID.IsGenericID(id) == false)
{
2024-10-12 20:06:21 +08:00
Throw.ArgumentException($"Иентификатор {id} содержит не допустимые символы: ,<>");
}
2024-09-27 21:46:16 +08:00
id = string.Intern(id);
ID = id;
}
}
2024-09-16 19:29:48 +08:00
2024-10-12 20:06:21 +08:00
public static class MetaID
2024-09-16 19:29:48 +08:00
{
[ThreadStatic]
2024-09-27 21:46:16 +08:00
private static Random _randon;
[ThreadStatic]
private static byte[] _buffer;
[ThreadStatic]
private static bool _isInit;
2024-10-12 20:06:21 +08:00
public static bool IsGenericID(string id)
{
return Regex.IsMatch(id, @"^[^,<>\s]*$");
}
2024-09-16 19:29:48 +08:00
public static unsafe string GenerateNewUniqueID()
{
if (_isInit == false)
{
IntPtr prt = Marshal.AllocHGlobal(1);
long alloc = (long)prt;
Marshal.Release(prt);
2024-09-27 21:46:16 +08:00
_randon = new Random((int)alloc);
_buffer = new byte[8];
_isInit = true;
}
2024-09-16 19:29:48 +08:00
byte* hibits = stackalloc byte[8];
long* hibitsL = (long*)hibits;
hibitsL[0] = DateTime.Now.Ticks;
hibitsL[1] = _randon.Next();
2024-09-16 19:29:48 +08:00
for (int i = 0; i < 8; i++)
2024-09-16 19:29:48 +08:00
{
_buffer[i] = hibits[i];
2024-09-16 19:29:48 +08:00
}
return BitConverter.ToString(_buffer).Replace("-", "");
2024-09-16 19:29:48 +08:00
}
2024-10-12 20:06:21 +08:00
public static string IDToAttribute(string id)
{
return $"[MetaID(\"id\")]";
}
public static string GenerateNewUniqueIDWithAttribute()
2024-09-16 19:29:48 +08:00
{
2024-10-12 20:06:21 +08:00
return IDToAttribute(GenerateNewUniqueID());
2024-09-16 19:29:48 +08:00
}
}
2024-10-12 20:06:21 +08:00
}