< Summary

Information
Class: Lattice.ECS.Core.AllocatorStats
Assembly: Lattice
File(s): /home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Core/Allocator.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 3
Coverable lines: 3
Total lines: 353
Line coverage: 0%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
ToString()100%210%

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>
 59        public int TotalAllocated => checked((int)_totalAllocated);
 60
 61        /// <summary>总使用内存(字节)。</summary>
 62        public int TotalUsed => checked((int)_totalUsed);
 63
 64        /// <summary>内存使用效率(定点数 0-1)。</summary>
 65        public FP Utilization => _totalAllocated > 0
 66            ? FP.FromRaw((long)_totalUsed * FP.One.RawValue / (long)_totalAllocated)
 67            : FP.Zero;
 68
 69        #endregion
 70
 71        #region 生命周期
 72
 73        /// <summary>
 74        /// 创建一个驻留在非托管内存中的分配器实例。
 75        /// </summary>
 76        public static Allocator* Create()
 77        {
 78            return (Allocator*)NativeMemory.AllocZeroed((nuint)sizeof(Allocator));
 79        }
 80
 81        /// <summary>
 82        /// 销毁非托管分配器实例及其持有的所有块。
 83        /// </summary>
 84        public static void Destroy(Allocator* allocator)
 85        {
 86            if (allocator == null)
 87            {
 88                return;
 89            }
 90
 91            allocator->Dispose();
 92            NativeMemory.Free(allocator);
 93        }
 94
 95        /// <summary>
 96        /// 释放所有 Arena 块。
 97        /// </summary>
 98        public void Dispose()
 99        {
 100            if (_isDisposed)
 101            {
 102                return;
 103            }
 104
 105            BlockHeader* block = _firstBlock;
 106            while (block != null)
 107            {
 108                BlockHeader* next = block->Next;
 109                NativeMemory.Free(block);
 110                block = next;
 111            }
 112
 113            _firstBlock = null;
 114            _currentBlock = null;
 115            _totalAllocated = 0;
 116            _totalUsed = 0;
 117            _isDisposed = true;
 118        }
 119
 120        #endregion
 121
 122        #region 分配方法
 123
 124        /// <summary>
 125        /// 分配默认对齐的非托管内存。
 126        /// </summary>
 127        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 128        public void* Alloc(int size)
 129        {
 130            return AllocAligned(size, DefaultAlignment);
 131        }
 132
 133        /// <summary>
 134        /// 分配并清零非托管内存。
 135        /// </summary>
 136        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 137        public void* AllocAndClear(int size)
 138        {
 139            void* ptr = Alloc(size);
 140            if (ptr != null)
 141            {
 142                Unsafe.InitBlockUnaligned(ptr, 0, checked((uint)size));
 143            }
 144
 145            return ptr;
 146        }
 147
 148        /// <summary>
 149        /// 分配指定对齐的非托管内存。
 150        /// </summary>
 151        public void* AllocAligned(int size, int alignment)
 152        {
 153            if (size <= 0)
 154            {
 155                return null;
 156            }
 157
 158            int normalizedAlignment = NormalizeAlignment(alignment);
 159
 160            if (_currentBlock != null &&
 161                TryAllocFromBlock(_currentBlock, size, normalizedAlignment, out void* currentPtr))
 162            {
 163                return currentPtr;
 164            }
 165
 166            BlockHeader* newBlock = AllocateBlock(size, normalizedAlignment);
 167            _currentBlock = newBlock;
 168
 169            if (_firstBlock == null)
 170            {
 171                _firstBlock = newBlock;
 172            }
 173
 174            return TryAllocFromBlock(newBlock, size, normalizedAlignment, out void* allocated)
 175                ? allocated
 176                : null;
 177        }
 178
 179        /// <summary>
 180        /// 重新分配内存。Arena 不支持原地扩容,因此会申请新区域并复制旧内容。
 181        /// </summary>
 182        public void* Realloc(void* ptr, int oldSize, int newSize)
 183        {
 184            if (ptr == null)
 185            {
 186                return Alloc(newSize);
 187            }
 188
 189            if (newSize <= 0)
 190            {
 191                Free(ptr);
 192                return null;
 193            }
 194
 195            void* newPtr = Alloc(newSize);
 196            if (newPtr == null)
 197            {
 198                return null;
 199            }
 200
 201            int copySize = System.Math.Min(oldSize, newSize);
 202            Buffer.MemoryCopy(ptr, newPtr, newSize, copySize);
 203            return newPtr;
 204        }
 205
 206        /// <summary>
 207        /// 单个块不支持提前释放,统一由 <see cref="Dispose()" /> 回收。
 208        /// </summary>
 209        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 210        public void Free(void* ptr)
 211        {
 212        }
 213
 214        #endregion
 215
 216        #region 统计与调试
 217
 218        /// <summary>
 219        /// 获取当前分配器统计信息。
 220        /// </summary>
 221        public AllocatorStats GetStats()
 222        {
 223            int blockCount = 0;
 224            BlockHeader* block = _firstBlock;
 225            while (block != null)
 226            {
 227                blockCount++;
 228                block = block->Next;
 229            }
 230
 231            return new AllocatorStats
 232            {
 233                TotalAllocated = TotalAllocated,
 234                TotalUsed = TotalUsed,
 235                BlockCount = blockCount,
 236                Utilization = Utilization
 237            };
 238        }
 239
 240        #endregion
 241
 242        #region 私有辅助
 243
 244        private static int NormalizeAlignment(int alignment)
 245        {
 246            int normalized = alignment <= 0 ? DefaultAlignment : alignment;
 247            normalized = System.Math.Max(normalized, sizeof(nuint));
 248
 249            if ((normalized & (normalized - 1)) != 0)
 250            {
 251                int value = 1;
 252                while (value < normalized)
 253                {
 254                    value <<= 1;
 255                }
 256
 257                normalized = value;
 258            }
 259
 260            return normalized;
 261        }
 262
 263        private static byte* GetBlockData(BlockHeader* block)
 264        {
 265            return (byte*)block + sizeof(BlockHeader);
 266        }
 267
 268        private bool TryAllocFromBlock(BlockHeader* block, int size, int alignment, out void* ptr)
 269        {
 270            byte* raw = GetBlockData(block) + block->Used;
 271            nuint aligned = AlignUp((nuint)raw, (nuint)alignment);
 272            nuint padding = aligned - (nuint)raw;
 273            nuint totalSize = padding + (nuint)size;
 274
 275            if (block->Used + totalSize > block->Size)
 276            {
 277                ptr = null;
 278                return false;
 279            }
 280
 281            block->Used += totalSize;
 282            _totalUsed += totalSize;
 283            ptr = (void*)aligned;
 284            return true;
 285        }
 286
 287        private BlockHeader* AllocateBlock(int requestedSize, int alignment)
 288        {
 289            int minRequired = checked(requestedSize + alignment);
 290            int blockSize = System.Math.Max(MinBlockSize, minRequired);
 291
 292            if (_currentBlock != null)
 293            {
 294                int doubled = checked((int)System.Math.Min((long)_currentBlock->Size * 2L, MaxBlockSize));
 295                blockSize = System.Math.Max(blockSize, doubled);
 296            }
 297
 298            if (blockSize > MaxBlockSize && minRequired <= MaxBlockSize)
 299            {
 300                blockSize = MaxBlockSize;
 301            }
 302
 303            nuint allocationSize = (nuint)(sizeof(BlockHeader) + blockSize);
 304            BlockHeader* newBlock = (BlockHeader*)NativeMemory.AllocZeroed(allocationSize);
 305
 306            newBlock->Size = (nuint)blockSize;
 307            newBlock->Used = 0;
 308            newBlock->Prev = _currentBlock;
 309            newBlock->Next = null;
 310
 311            if (_currentBlock != null)
 312            {
 313                _currentBlock->Next = newBlock;
 314            }
 315
 316            _totalAllocated += (nuint)blockSize;
 317            return newBlock;
 318        }
 319
 320        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 321        private static nuint AlignUp(nuint value, nuint alignment)
 322        {
 323            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        {
 0348            int utilPercent = (int)(Utilization * 100);
 0349            return $"Allocator[Allocated: {TotalAllocated / 1024}KB, Used: {TotalUsed / 1024}KB, " +
 0350                   $"Blocks: {BlockCount}, Util: {utilPercent}%]";
 351        }
 352    }
 353}

Methods/Properties

ToString()