using System; using System.Buffers; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace PerfectNumbers.Core { public static class ThreadStaticPools { [ThreadStatic] private static ArrayPool? _factorEntryPool; public static ArrayPool FactorEntryPool { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _factorEntryPool ??= ArrayPool.Create(); } } [ThreadStatic] private static ArrayPool? _factorEntry128Pool; public static ArrayPool FactorEntry128Pool { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _factorEntry128Pool ??= ArrayPool.Create(); } } [ThreadStatic] private static ArrayPool? _ulongPool; public static ArrayPool UlongPool { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _ulongPool ??= ArrayPool.Create(); } } [ThreadStatic] private static Dictionary? _mersenneFactorCacheDictionary; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Dictionary RentMersenneFactorCacheDictionary() { Dictionary? cache = _mersenneFactorCacheDictionary; if (cache is null) { return new Dictionary(8); } _mersenneFactorCacheDictionary = null; cache.Clear(); return cache; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ReturnMersenneFactorCacheDictionary(Dictionary cache) { cache.Clear(); _mersenneFactorCacheDictionary = cache; } [ThreadStatic] private static Dictionary? _factorCountDictionary; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Dictionary RentFactorCountDictionary() { Dictionary? dictionary = _factorCountDictionary; if (dictionary is null) { return new Dictionary(8); } _factorCountDictionary = null; dictionary.Clear(); return dictionary; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ReturnFactorCountDictionary(Dictionary dictionary) { dictionary.Clear(); _factorCountDictionary = dictionary; } [ThreadStatic] private static Dictionary? _factorScratchDictionary; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Dictionary RentFactorScratchDictionary() { Dictionary? dictionary = _factorScratchDictionary; if (dictionary is null) { return new Dictionary(8); } _factorScratchDictionary = null; dictionary.Clear(); return dictionary; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ReturnFactorScratchDictionary(Dictionary dictionary) { dictionary.Clear(); _factorScratchDictionary = dictionary; } } }