Files
mixtape/zero.Core/Persistence/IdGenerator.cs
T

112 lines
2.7 KiB
C#
Raw Normal View History

2022-01-15 01:15:05 +01:00
using System.Text.Json;
namespace zero.Persistence;
2021-11-19 14:59:24 +01:00
public class IdGenerator
{
const string CHARS = "abcdefghijklmnopqrstuvwxyz0123456789";
2022-06-23 16:14:22 +02:00
const string CHARS_COMPLEX = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-@#.:!?*";
2021-11-19 14:59:24 +01:00
private static Random random = new();
/// <summary>
/// Create a new unique Id
/// </summary>
2022-06-23 16:14:22 +02:00
public static string Create(int length = -1, Charset charset = Charset.az09)
2021-11-19 14:59:24 +01:00
{
if (length < 1)
{
length = 12;
}
2022-06-23 16:14:22 +02:00
string chars = charset == Charset.az09 ? CHARS : CHARS_COMPLEX;
return new string(Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)]).ToArray());
2021-11-19 14:59:24 +01:00
//if (length > 0)
//{
//return Convert.ToBase64String(Guid.NewGuid().ToByteArray())
// .Replace("/", String.Empty)
// .Replace("+", String.Empty)
// .Replace("-", String.Empty)
// .ToLowerInvariant()
// .Substring(0, length);
//}
//return Guid.NewGuid().ToString();
}
2021-12-12 15:41:51 +01:00
/// <summary>
/// Creates a simple hash from a string
/// </summary>
public static string HashString(string value)
{
2022-01-15 01:15:05 +01:00
return GetStableHashCode(value).ToString().Replace("-", String.Empty);
}
/// <summary>
/// Creates a simple hash from a string
/// </summary>
public static string HashObject(params object[] values)
{
return GetStableHashCode(JsonSerializer.Serialize(values)).ToString().Replace("-", String.Empty);
2021-12-12 15:41:51 +01:00
}
2022-01-06 17:03:05 +01:00
/// <summary>
/// Autofill IDs on an object with [GenerateId] attributes
/// </summary>
public static T Autofill<T>(T model)
{
// find all Raven Ids
List<ObjectTraverser.Result<GenerateIdAttribute>> ravenIds = ObjectTraverser.FindAttribute<GenerateIdAttribute>(model);
// set unset Raven Ids
foreach (ObjectTraverser.Result<GenerateIdAttribute> item in ravenIds)
{
string id = item.Property.GetValue(item.Parent, null) as string;
if (id.IsNullOrWhiteSpace())
{
id = item.Item.Length.HasValue ? Create(item.Item.Length.Value) : Create();
item.Property.SetValue(item.Parent, id);
}
}
return model;
}
2022-01-15 01:15:05 +01:00
static int GetStableHashCode(string str)
{
unchecked
{
int hash1 = 5381;
int hash2 = hash1;
for (int i = 0; i < str.Length && str[i] != '\0'; i += 2)
{
hash1 = ((hash1 << 5) + hash1) ^ str[i];
if (i == str.Length - 1 || str[i + 1] == '\0')
break;
hash2 = ((hash2 << 5) + hash2) ^ str[i + 1];
}
return hash1 + (hash2 * 1566083941);
}
}
2022-06-23 16:14:22 +02:00
public enum Charset
{
/// <summary>
/// a-z, 0-9
/// </summary>
az09 = 0,
/// <summary>
/// a-z, A-Z, 0-9, _-@#.:!?*
/// </summary>
azAZ09x = 1
}
}