< Summary

Information
Class: Lattice.Core.NativeMemoryPool
Assembly: Lattice
File(s): /home/runner/work/Sideline/Sideline/godot/scripts/lattice/Core/NativeMemoryPool.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 70
Coverable lines: 70
Total lines: 268
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 32
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
.ctor(...)0%2040%
Alloc()0%7280%
Free(...)0%2040%
AllocateNewPage()0%4260%
GetStats()100%210%
Dispose()0%110100%

File(s)

/home/runner/work/Sideline/Sideline/godot/scripts/lattice/Core/NativeMemoryPool.cs

#LineLine coverage
 1using System;
 2using System.Buffers;
 3using System.Runtime.CompilerServices;
 4using System.Runtime.InteropServices;
 5using Lattice.Math;
 6
 7namespace Lattice.Core
 8{
 9    /// <summary>
 10    /// 原生内存池 - 高性能内存管理
 11    ///
 12    /// 特性:
 13    /// 1. 使用GC.AllocateArray(pinned: true)避免GC移动
 14    /// 2. 按页分配减少分配开销
 15    /// 3. 零内存清除(重用时不清零)
 16    /// </summary>
 17    public sealed unsafe class NativeMemoryPool : IDisposable
 18    {
 19        private readonly int _pageSize;
 20        private readonly int _elementSize;
 21
 22        // 空闲链表
 23        private IntPtr* _freeList;
 24        private int _freeCount;
 25        private int _freeCapacity;
 26
 27        // 已分配页
 28        private byte[][] _pages = null!;
 29        private int _pageCount;
 30        private int _pageCapacity;
 31
 32        // GCHandles保持数组固定
 33        private GCHandle[] _handles = null!;
 34
 35        // 当前页和偏移
 36        private byte[]? _currentPage;
 37        private int _currentOffset;
 38        private GCHandle _currentHandle;
 39        private byte* _currentPtr;
 40
 41        // 统计
 42        private int _allocatedCount;
 43        private int _peakAllocatedCount;
 44
 045        public NativeMemoryPool(int elementSize, int pageSize = 64 * 1024) // 默认64KB一页
 46        {
 047            if (elementSize <= 0) throw new ArgumentException("Element size must be positive", nameof(elementSize));
 048            if (pageSize <= 0) throw new ArgumentException("Page size must be positive", nameof(pageSize));
 49
 050            _elementSize = elementSize;
 051            _pageSize = pageSize;
 52
 053            _freeList = (IntPtr*)NativeMemory.Alloc((nuint)(1024 * sizeof(IntPtr)));
 054            _freeCapacity = 1024;
 55
 56            // 初始化页数组
 057            _pages = new byte[4][];
 058            _handles = new GCHandle[4];
 059            _pageCapacity = 4;
 060        }
 61
 62        /// <summary>
 63        /// 分配内存
 64        /// </summary>
 65        public byte* Alloc()
 66        {
 67            // 优先从空闲链表获取
 068            if (_freeCount > 0)
 69            {
 070                var ptr = (byte*)_freeList[--_freeCount];
 071                _allocatedCount++;
 072                return ptr;
 73            }
 74
 75            // 检查当前页是否有空间
 076            if (_currentPage == null || _currentOffset + _elementSize > _pageSize)
 77            {
 078                AllocateNewPage();
 79            }
 80
 081            var result = _currentPtr + _currentOffset;
 082            _currentOffset += _elementSize;
 83
 084            _allocatedCount++;
 085            if (_allocatedCount > _peakAllocatedCount)
 86            {
 087                _peakAllocatedCount = _allocatedCount;
 88            }
 89
 090            return result;
 91        }
 92
 93        /// <summary>
 94        /// 释放内存(返回到池中)
 95        /// </summary>
 96        public void Free(byte* ptr)
 97        {
 098            if (ptr == null) return;
 99
 100            // 扩容空闲链表
 0101            if (_freeCount >= _freeCapacity)
 102            {
 0103                int newCapacity = _freeCapacity * 2;
 0104                var newList = (IntPtr*)NativeMemory.Alloc((nuint)(newCapacity * sizeof(IntPtr)));
 0105                Buffer.MemoryCopy(_freeList, newList, newCapacity * sizeof(IntPtr), _freeCount * sizeof(IntPtr));
 0106                NativeMemory.Free(_freeList);
 0107                _freeList = newList;
 0108                _freeCapacity = newCapacity;
 109            }
 110
 0111            _freeList[_freeCount++] = (IntPtr)ptr;
 0112            _allocatedCount--;
 0113        }
 114
 115        /// <summary>
 116        /// 分配新页
 117        /// </summary>
 118        private void AllocateNewPage()
 119        {
 120            // 扩容
 0121            if (_pageCount >= _pageCapacity)
 122            {
 0123                int newCapacity = _pageCapacity * 2;
 0124                Array.Resize(ref _pages, newCapacity);
 0125                Array.Resize(ref _handles, newCapacity);
 0126                _pageCapacity = newCapacity;
 127            }
 128
 129            // 释放当前页的GCHandle
 0130            if (_currentPage != null && _pageCount > 0)
 131            {
 0132                _handles[_pageCount - 1] = _currentHandle;
 133            }
 134
 135            // 分配新页(固定)
 0136            _currentPage = GC.AllocateArray<byte>(_pageSize, pinned: true);
 0137            _currentHandle = GCHandle.Alloc(_currentPage, GCHandleType.Pinned);
 0138            _currentPtr = (byte*)_currentHandle.AddrOfPinnedObject();
 0139            _currentOffset = 0;
 140
 0141            _pages[_pageCount++] = _currentPage;
 0142        }
 143
 144        /// <summary>
 145        /// 获取统计信息
 146        /// </summary>
 147        public MemoryPoolStats GetStats()
 148        {
 0149            return new MemoryPoolStats
 0150            {
 0151                PageCount = _pageCount,
 0152                TotalBytes = _pageCount * _pageSize,
 0153                AllocatedCount = _allocatedCount,
 0154                PeakAllocatedCount = _peakAllocatedCount,
 0155                FreeCount = _freeCount,
 0156                ElementSize = _elementSize
 0157            };
 158        }
 159
 160        public void Dispose()
 161        {
 162            // 释放GCHandles
 0163            if (_handles != null)
 164            {
 0165                for (int i = 0; i < _pageCount; i++)
 166                {
 0167                    if (_handles[i].IsAllocated)
 168                    {
 0169                        _handles[i].Free();
 170                    }
 171                }
 172            }
 173
 174            // 释放当前页
 0175            if (_currentHandle.IsAllocated)
 176            {
 0177                _currentHandle.Free();
 178            }
 179
 180            // 释放空闲链表
 0181            if (_freeList != null)
 182            {
 0183                NativeMemory.Free(_freeList);
 0184                _freeList = null;
 185            }
 186
 0187            _pages = null!;
 0188            _handles = null!;
 0189            _currentPage = null;
 0190            _currentPtr = null;
 0191        }
 192    }
 193
 194    /// <summary>
 195    /// 内存池统计
 196    /// </summary>
 197    public readonly struct MemoryPoolStats
 198    {
 199        public int PageCount { get; init; }
 200        public int TotalBytes { get; init; }
 201        public int AllocatedCount { get; init; }
 202        public int PeakAllocatedCount { get; init; }
 203        public int FreeCount { get; init; }
 204        public int ElementSize { get; init; }
 205
 206        public FP UtilizationRate => TotalBytes > 0 ? (FP)AllocatedCount * (FP)ElementSize / (FP)TotalBytes : FP.Zero;
 207
 208        public override string ToString()
 209        {
 210            return $"MemoryPool[Pages={PageCount}, Allocated={AllocatedCount}, Free={FreeCount}, " +
 211                   $"Util={UtilizationRate:P1}, Total={TotalBytes}B]";
 212        }
 213    }
 214
 215    /// <summary>
 216    /// 数组池包装器 - 提供固定数组
 217    /// </summary>
 218    public static class PinnedArrayPool
 219    {
 220        /// <summary>
 221        /// 租用固定数组
 222        /// </summary>
 223        public static PinnedArray<T> Rent<T>(int minimumLength) where T : unmanaged
 224        {
 225            var array = GC.AllocateArray<T>(minimumLength, pinned: true);
 226            return new PinnedArray<T>(array);
 227        }
 228
 229        /// <summary>
 230        /// 归还数组
 231        /// </summary>
 232        public static void Return<T>(PinnedArray<T> pinnedArray) where T : unmanaged
 233        {
 234            pinnedArray.Dispose();
 235        }
 236    }
 237
 238    /// <summary>
 239    /// 固定数组包装
 240    /// </summary>
 241    public readonly unsafe struct PinnedArray<T> : IDisposable where T : unmanaged
 242    {
 243        private readonly T[] _array;
 244        private readonly GCHandle _handle;
 245        private readonly T* _ptr;
 246
 247        public PinnedArray(T[] array)
 248        {
 249            _array = array;
 250            _handle = GCHandle.Alloc(array, GCHandleType.Pinned);
 251            _ptr = (T*)_handle.AddrOfPinnedObject();
 252        }
 253
 254        public int Length => _array.Length;
 255        public T[] Array => _array;
 256        public T* Pointer => _ptr;
 257
 258        public ref T this[int index] => ref _array[index];
 259
 260        public void Dispose()
 261        {
 262            if (_handle.IsAllocated)
 263            {
 264                _handle.Free();
 265            }
 266        }
 267    }
 268}