using Collections.Pooled; 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> { public PooledList Get() { return new PooledList(); } public override PooledList Create() { return new PooledList(); } public override bool Return(PooledList list) { foreach (var entry in list.Span) { if (entry is IDisposable disposable) disposable.Dispose(); if (entry is IResettable resettable) resettable.TryReset(); } list.Clear(); return true; } } 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)); } } }