< Summary

Information
Class: Lattice.ECS.Core.Allocator
Assembly: Lattice
File(s): /home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Core/Allocator.cs
Line coverage
64%
Covered lines: 67
Uncovered lines: 37
Coverable lines: 104
Total lines: 353
Line coverage: 64.4%
Branch coverage
56%
Covered branches: 25
Total branches: 44
Branch coverage: 56.8%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
get_TotalAllocated()100%210%
get_TotalUsed()100%210%
get_Utilization()0%620%
Create()100%11100%
Destroy(...)50%2280%
Dispose()75%4492.3%
Alloc(...)100%11100%
AllocAndClear(...)100%22100%
AllocAligned(...)80%101092.3%
Realloc(...)0%4260%
Free(...)100%210%
GetStats()0%620%
NormalizeAlignment(...)33.33%11650%
GetBlockData(...)100%11100%
TryAllocFromBlock(...)100%22100%
AllocateBlock(...)87.5%8894.11%
AlignUp(...)100%11100%

File(s)

/home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Core/Allocator.cs

#LineLine coverage
 1// Copyright (c) 2026 Sideline Authors. All rights reserved.
 2// Licensed under GPL-3.0.
 3
 4using System;
 5using System.Runtime.CompilerServices;
 6using System.Runtime.InteropServices;
 7using Lattice.Math;
 8
 9namespace Lattice.ECS.Core
 10{
 11    /// <summary>
 12    /// 高性能非托管 Arena 分配器。
 13    ///
 14    /// 设计目标:
 15    /// 1. 完全驻留于非托管内存,可安全通过 <c>Allocator*</c> 传递;
 16    /// 2. 采用线性追加分配,避免 ECS 热路径中的碎片化与单次释放开销;
 17    /// 3. 为组件块、位图、命令缓冲等场景提供稳定的对齐分配能力。
 18    /// </summary>
 19    public unsafe struct Allocator
 20    {
 21        #region 常量
 22
 23        /// <summary>默认对齐边界(16 字节,兼顾 SIMD 与常见平台 ABI)。</summary>
 24        public const int DefaultAlignment = 16;
 25
 26        /// <summary>最小分配块大小(4KB)。</summary>
 27        private const int MinBlockSize = 4 * 1024;
 28
 29        /// <summary>最大常规分配块大小(1MB)。超出时按需扩展。</summary>
 30        private const int MaxBlockSize = 1024 * 1024;
 31
 32        #endregion
 33
 34        #region 内存块
 35
 36        private struct BlockHeader
 37        {
 38            public nuint Size;
 39            public nuint Used;
 40            public BlockHeader* Prev;
 41            public BlockHeader* Next;
 42        }
 43
 44        #endregion
 45
 46        #region 字段
 47
 48        private BlockHeader* _firstBlock;
 49        private BlockHeader* _currentBlock;
 50        private nuint _totalAllocated;
 51        private nuint _totalUsed;
 52        private bool _isDisposed;
 53
 54        #endregion
 55
 56        #region 属性
 57
 58        /// <summary>总分配内存(字节)。</summary>
 059        public int TotalAllocated => checked((int)_totalAllocated);
 60
 61        /// <summary>总使用内存(字节)。</summary>
 062        public int TotalUsed => checked((int)_totalUsed);
 63
 64        /// <summary>内存使用效率(定点数 0-1)。</summary>
 065        public FP Utilization => _totalAllocated > 0
 066            ? FP.FromRaw((long)_totalUsed * FP.One.RawValue / (long)_totalAllocated)
 067            : FP.Zero;
 68
 69        #endregion
 70
 71        #region 生命周期
 72
 73        /// <summary>
 74        /// 创建一个驻留在非托管内存中的分配器实例。
 75        /// </summary>
 76        public static Allocator* Create()
 77        {
 73278            return (Allocator*)NativeMemory.AllocZeroed((nuint)sizeof(Allocator));
 79        }
 80
 81        /// <summary>
 82        /// 销毁非托管分配器实例及其持有的所有块。
 83        /// </summary>
 84        public static void Destroy(Allocator* allocator)
 85        {
 73186            if (allocator == null)
 87            {
 088                return;
 89            }
 90
 73191            allocator->Dispose();
 73192            NativeMemory.Free(allocator);
 73193        }
 94
 95        /// <summary>
 96        /// 释放所有 Arena 块。
 97        /// </summary>
 98        public void Dispose()
 99        {
 731100            if (_isDisposed)
 101            {
 0102                return;
 103            }
 104
 731105            BlockHeader* block = _firstBlock;
 2856106            while (block != null)
 107            {
 2125108                BlockHeader* next = block->Next;
 2125109                NativeMemory.Free(block);
 2125110                block = next;
 111            }
 112
 731113            _firstBlock = null;
 731114            _currentBlock = null;
 731115            _totalAllocated = 0;
 731116            _totalUsed = 0;
 731117            _isDisposed = true;
 731118        }
 119
 120        #endregion
 121
 122        #region 分配方法
 123
 124        /// <summary>
 125        /// 分配默认对齐的非托管内存。
 126        /// </summary>
 127        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 128        public void* Alloc(int size)
 129        {
 11260130            return AllocAligned(size, DefaultAlignment);
 131        }
 132
 133        /// <summary>
 134        /// 分配并清零非托管内存。
 135        /// </summary>
 136        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 137        public void* AllocAndClear(int size)
 138        {
 1383139            void* ptr = Alloc(size);
 1383140            if (ptr != null)
 141            {
 1383142                Unsafe.InitBlockUnaligned(ptr, 0, checked((uint)size));
 143            }
 144
 1383145            return ptr;
 146        }
 147
 148        /// <summary>
 149        /// 分配指定对齐的非托管内存。
 150        /// </summary>
 151        public void* AllocAligned(int size, int alignment)
 152        {
 11260153            if (size <= 0)
 154            {
 0155                return null;
 156            }
 157
 11260158            int normalizedAlignment = NormalizeAlignment(alignment);
 159
 11260160            if (_currentBlock != null &&
 11260161                TryAllocFromBlock(_currentBlock, size, normalizedAlignment, out void* currentPtr))
 162            {
 9133163                return currentPtr;
 164            }
 165
 2127166            BlockHeader* newBlock = AllocateBlock(size, normalizedAlignment);
 2127167            _currentBlock = newBlock;
 168
 2127169            if (_firstBlock == null)
 170            {
 732171                _firstBlock = newBlock;
 172            }
 173
 2127174            return TryAllocFromBlock(newBlock, size, normalizedAlignment, out void* allocated)
 2127175                ? allocated
 2127176                : null;
 177        }
 178
 179        /// <summary>
 180        /// 重新分配内存。Arena 不支持原地扩容,因此会申请新区域并复制旧内容。
 181        /// </summary>
 182        public void* Realloc(void* ptr, int oldSize, int newSize)
 183        {
 0184            if (ptr == null)
 185            {
 0186                return Alloc(newSize);
 187            }
 188
 0189            if (newSize <= 0)
 190            {
 0191                Free(ptr);
 0192                return null;
 193            }
 194
 0195            void* newPtr = Alloc(newSize);
 0196            if (newPtr == null)
 197            {
 0198                return null;
 199            }
 200
 0201            int copySize = System.Math.Min(oldSize, newSize);
 0202            Buffer.MemoryCopy(ptr, newPtr, newSize, copySize);
 0203            return newPtr;
 204        }
 205
 206        /// <summary>
 207        /// 单个块不支持提前释放,统一由 <see cref="Dispose()" /> 回收。
 208        /// </summary>
 209        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 210        public void Free(void* ptr)
 211        {
 0212        }
 213
 214        #endregion
 215
 216        #region 统计与调试
 217
 218        /// <summary>
 219        /// 获取当前分配器统计信息。
 220        /// </summary>
 221        public AllocatorStats GetStats()
 222        {
 0223            int blockCount = 0;
 0224            BlockHeader* block = _firstBlock;
 0225            while (block != null)
 226            {
 0227                blockCount++;
 0228                block = block->Next;
 229            }
 230
 0231            return new AllocatorStats
 0232            {
 0233                TotalAllocated = TotalAllocated,
 0234                TotalUsed = TotalUsed,
 0235                BlockCount = blockCount,
 0236                Utilization = Utilization
 0237            };
 238        }
 239
 240        #endregion
 241
 242        #region 私有辅助
 243
 244        private static int NormalizeAlignment(int alignment)
 245        {
 11260246            int normalized = alignment <= 0 ? DefaultAlignment : alignment;
 11260247            normalized = System.Math.Max(normalized, sizeof(nuint));
 248
 11260249            if ((normalized & (normalized - 1)) != 0)
 250            {
 0251                int value = 1;
 0252                while (value < normalized)
 253                {
 0254                    value <<= 1;
 255                }
 256
 0257                normalized = value;
 258            }
 259
 11260260            return normalized;
 261        }
 262
 263        private static byte* GetBlockData(BlockHeader* block)
 264        {
 12655265            return (byte*)block + sizeof(BlockHeader);
 266        }
 267
 268        private bool TryAllocFromBlock(BlockHeader* block, int size, int alignment, out void* ptr)
 269        {
 12655270            byte* raw = GetBlockData(block) + block->Used;
 12655271            nuint aligned = AlignUp((nuint)raw, (nuint)alignment);
 12655272            nuint padding = aligned - (nuint)raw;
 12655273            nuint totalSize = padding + (nuint)size;
 274
 12655275            if (block->Used + totalSize > block->Size)
 276            {
 1395277                ptr = null;
 1395278                return false;
 279            }
 280
 11260281            block->Used += totalSize;
 11260282            _totalUsed += totalSize;
 11260283            ptr = (void*)aligned;
 11260284            return true;
 285        }
 286
 287        private BlockHeader* AllocateBlock(int requestedSize, int alignment)
 288        {
 2127289            int minRequired = checked(requestedSize + alignment);
 2127290            int blockSize = System.Math.Max(MinBlockSize, minRequired);
 291
 2127292            if (_currentBlock != null)
 293            {
 1395294                int doubled = checked((int)System.Math.Min((long)_currentBlock->Size * 2L, MaxBlockSize));
 1395295                blockSize = System.Math.Max(blockSize, doubled);
 296            }
 297
 2127298            if (blockSize > MaxBlockSize && minRequired <= MaxBlockSize)
 299            {
 0300                blockSize = MaxBlockSize;
 301            }
 302
 2127303            nuint allocationSize = (nuint)(sizeof(BlockHeader) + blockSize);
 2127304            BlockHeader* newBlock = (BlockHeader*)NativeMemory.AllocZeroed(allocationSize);
 305
 2127306            newBlock->Size = (nuint)blockSize;
 2127307            newBlock->Used = 0;
 2127308            newBlock->Prev = _currentBlock;
 2127309            newBlock->Next = null;
 310
 2127311            if (_currentBlock != null)
 312            {
 1395313                _currentBlock->Next = newBlock;
 314            }
 315
 2127316            _totalAllocated += (nuint)blockSize;
 2127317            return newBlock;
 318        }
 319
 320        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 321        private static nuint AlignUp(nuint value, nuint alignment)
 322        {
 12655323            return (value + alignment - 1) & ~(alignment - 1);
 324        }
 325
 326        #endregion
 327    }
 328
 329    /// <summary>
 330    /// 分配器统计信息。
 331    /// </summary>
 332    public struct AllocatorStats
 333    {
 334        /// <summary>总分配内存(字节)。</summary>
 335        public int TotalAllocated;
 336
 337        /// <summary>总使用内存(字节)。</summary>
 338        public int TotalUsed;
 339
 340        /// <summary>内存块数量。</summary>
 341        public int BlockCount;
 342
 343        /// <summary>内存使用效率(定点数 0-1)。</summary>
 344        public FP Utilization;
 345
 346        public override string ToString()
 347        {
 348            int utilPercent = (int)(Utilization * 100);
 349            return $"Allocator[Allocated: {TotalAllocated / 1024}KB, Used: {TotalUsed / 1024}KB, " +
 350                   $"Blocks: {BlockCount}, Util: {utilPercent}%]";
 351        }
 352    }
 353}