DragonECS/src/DebugUtils/MetaAttributes/MetaIDAttribute.cs

65 lines
1.9 KiB
C#
Raw Normal View History

using DCFApixels.DragonECS.Internal;
using System;
using System.Runtime.InteropServices;
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-09-16 19:29:48 +08:00
if (id.Contains(','))
{
2024-09-16 19:29:48 +08:00
Throw.ArgumentException($"Аргумент {nameof(id)} не может содержать символ запятой ','");
}
2024-09-27 21:46:16 +08:00
id = string.Intern(id);
ID = id;
}
}
2024-09-16 19:29:48 +08:00
public static class MetaIDUtility
{
[ThreadStatic]
2024-09-27 21:46:16 +08:00
private static Random _randon;
[ThreadStatic]
private static byte[] _buffer;
[ThreadStatic]
private static bool _isInit;
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
}
public static unsafe string GenerateNewUniqueIDWithAttribute()
{
return $"[MetaID(\"{GenerateNewUniqueID()}\")]";
}
}
}