using CodeWalker.GameFiles; using Collections.Pooled; using CommunityToolkit.Diagnostics; using CommunityToolkit.HighPerformance.Buffers; using Microsoft.Extensions.ObjectPool; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace CodeWalker.Core.Utils { public class SharedObjectPool where T : class, new() { private static readonly ObjectPool s_shared = ObjectPool.Create(); public static ObjectPool Shared => s_shared; } public class PooledListObjectPolicy : PooledObjectPolicy> { private readonly ClearMode clearMode; public PooledListObjectPolicy(ClearMode _clearMode = ClearMode.Auto) { clearMode = _clearMode; } public PooledList Get() { return new PooledList(clearMode); } public override PooledList Create() { return new PooledList(clearMode); } public override bool Return(PooledList list) { list.Clear(); return true; } } public static class PooledListPool { private static readonly ObjectPool> s_shared = ObjectPool.Create(new PooledListObjectPolicy(ClearMode.Never)); public static ObjectPool> Shared => s_shared; } public static class PooledListExtensions { public static int EnsureCapacity(this PooledList list, int capacity) { ArgumentOutOfRangeException.ThrowIfLessThan(capacity, 0, nameof(capacity)); if (list.Capacity < capacity) { list.Capacity = capacity; } return list.Capacity; } } public static class StringPoolExtension { [SkipLocalsInit] public static string GetStringPooled(this Encoding encoding, ReadOnlySpan bytes) { Span buffer = stackalloc char[bytes.Length]; var charsWritten = encoding.GetChars(bytes, buffer); return StringPool.Shared.GetOrAdd(buffer.Slice(0, charsWritten)); } } }