< Summary

Information
Class: Lattice.ECS.Core.BitStream
Assembly: Lattice
File(s): /home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Core/BitStream.cs
Line coverage
37%
Covered lines: 59
Uncovered lines: 99
Coverable lines: 158
Total lines: 544
Line coverage: 37.3%
Branch coverage
42%
Covered branches: 21
Total branches: 50
Branch coverage: 42%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
get_IsWriting()100%11100%
get_IsReading()100%11100%
get_BytePosition()100%210%
get_Length()100%210%
get_BytesUsed()100%11100%
.ctor(...)100%11100%
.ctor(...)50%22100%
WriteBit(...)83.33%6690%
ReadBit()66.66%6680%
WriteBits(...)66.66%6680%
ReadBits(...)75%8885.71%
WriteInt(...)100%11100%
ReadInt()100%11100%
WriteUInt(...)100%210%
ReadUInt()100%210%
WriteShort(...)100%210%
ReadShort()100%210%
WriteUShort(...)100%210%
ReadUShort()100%210%
WriteByte(...)100%210%
ReadByte()100%210%
WriteBool(...)100%210%
ReadBool()100%210%
WriteLong(...)100%210%
ReadLong()100%210%
WriteULong(...)100%11100%
ReadULong()100%11100%
WriteVarUInt(...)0%620%
ReadVarUInt()0%620%
WriteVarInt(...)100%210%
ReadVarInt()100%210%
WriteBytes(...)0%620%
ReadBytes(...)0%2040%
WriteMemory(...)0%620%
ReadMemory(...)0%2040%
ToArray()100%11100%
GetWrittenSpan()100%210%
Reset()0%620%
EnsureCapacity(...)50%4225%
CanWrite(...)100%210%
CanRead(...)100%210%
VerifyCanRead(...)0%620%
get_RemainingBytes()100%210%
get_PositionInfo()100%210%

File(s)

/home/runner/work/Sideline/Sideline/godot/scripts/lattice/ECS/Core/BitStream.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;
 6
 7namespace Lattice.ECS.Core
 8{
 9    /// <summary>
 10    /// 位流 - FrameSync 风格的高效二进制序列化
 11    ///
 12    /// 特性:
 13    /// 1. 位级别的读写(Bit-packing)
 14    /// 2. 支持有符号/无符号整数变长编码
 15    /// 3. 支持原始内存拷贝
 16    /// 4. 可扩展的缓冲区
 17    /// </summary>
 18    public unsafe class BitStream
 19    {
 20        #region 字段
 21
 22        /// <summary>数据缓冲区</summary>
 23        private byte[] _buffer;
 24
 25        /// <summary>当前逻辑终点(读取模式下可能小于缓冲区长度)。</summary>
 26        private int _byteLimit;
 27
 28        /// <summary>当前字节位置</summary>
 29        private int _bytePosition;
 30
 31        /// <summary>当前位位置(0-7)</summary>
 32        private int _bitPosition;
 33
 34        /// <summary>是否正在写入</summary>
 20435        public bool IsWriting { get; set; }
 36
 37        /// <summary>是否正在读取</summary>
 9838        public bool IsReading => !IsWriting;
 39
 40        /// <summary>当前字节位置</summary>
 041        public int BytePosition => _bytePosition;
 42
 43        /// <summary>缓冲区长度</summary>
 044        public int Length => _buffer.Length;
 45
 46        /// <summary>已使用的字节数</summary>
 147        public int BytesUsed => _bytePosition + (_bitPosition > 0 ? 1 : 0);
 48
 49        #endregion
 50
 51        #region 构造函数
 52
 53        /// <summary>
 54        /// 创建位流(写入模式)
 55        /// </summary>
 256        public BitStream(int initialCapacity = 1024)
 57        {
 258            _buffer = new byte[initialCapacity];
 259            _byteLimit = _buffer.Length;
 260            _bytePosition = 0;
 261            _bitPosition = 0;
 262            IsWriting = true;
 263        }
 64
 65        /// <summary>
 66        /// 创建位流(从现有数据读取)
 67        /// </summary>
 168        public BitStream(byte[] data, int offset = 0, int length = -1)
 69        {
 170            _buffer = data;
 171            _byteLimit = length >= 0 ? System.Math.Min(data.Length, offset + length) : data.Length;
 172            _bytePosition = offset;
 173            _bitPosition = 0;
 174            IsWriting = false;
 175        }
 76
 77        #endregion
 78
 79        #region 基础位操作
 80
 81        /// <summary>
 82        /// 写入一个位
 83        /// </summary>
 84        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 85        public void WriteBit(bool value)
 86        {
 9687            if (IsReading)
 088                throw new InvalidOperationException("Cannot write in reading mode");
 89
 9690            EnsureCapacity(_bytePosition + 1);
 91
 9692            if (value)
 93            {
 1194                _buffer[_bytePosition] |= (byte)(1 << _bitPosition);
 95            }
 96
 9697            _bitPosition++;
 9698            if (_bitPosition >= 8)
 99            {
 12100                _bitPosition = 0;
 12101                _bytePosition++;
 102            }
 96103        }
 104
 105        /// <summary>
 106        /// 读取一个位
 107        /// </summary>
 108        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 109        public bool ReadBit()
 110        {
 96111            if (IsWriting)
 0112                throw new InvalidOperationException("Cannot read in writing mode");
 113
 96114            if (_bytePosition >= _byteLimit)
 0115                throw new EndOfStreamException($"Attempted to read beyond buffer length ({_byteLimit} bytes at position 
 116
 96117            bool value = (_buffer[_bytePosition] & (1 << _bitPosition)) != 0;
 118
 96119            _bitPosition++;
 96120            if (_bitPosition >= 8)
 121            {
 12122                _bitPosition = 0;
 12123                _bytePosition++;
 124            }
 125
 96126            return value;
 127        }
 128
 129        /// <summary>
 130        /// 写入指定数量的位
 131        /// </summary>
 132        public void WriteBits(uint value, int bits)
 133        {
 3134            if (bits < 0 || bits > 32)
 0135                throw new ArgumentOutOfRangeException(nameof(bits));
 136
 198137            for (int i = 0; i < bits; i++)
 138            {
 96139                WriteBit(((value >> i) & 1) != 0);
 140            }
 3141        }
 142
 143        /// <summary>
 144        /// 读取指定数量的位
 145        /// </summary>
 146        public uint ReadBits(int bits)
 147        {
 3148            if (bits < 0 || bits > 32)
 0149                throw new ArgumentOutOfRangeException(nameof(bits));
 150
 3151            uint value = 0;
 198152            for (int i = 0; i < bits; i++)
 153            {
 96154                if (ReadBit())
 11155                    value |= (1u << i);
 156            }
 3157            return value;
 158        }
 159
 160        #endregion
 161
 162        #region 整数序列化
 163
 164        /// <summary>
 165        /// 写入 int(32位)
 166        /// </summary>
 167        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 168        public void WriteInt(int value)
 169        {
 1170            WriteBits((uint)value, 32);
 1171        }
 172
 173        /// <summary>
 174        /// 读取 int(32位)
 175        /// </summary>
 176        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 177        public int ReadInt()
 178        {
 1179            return (int)ReadBits(32);
 180        }
 181
 182        /// <summary>
 183        /// 写入 uint(32位)
 184        /// </summary>
 185        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 186        public void WriteUInt(uint value)
 187        {
 0188            WriteBits(value, 32);
 0189        }
 190
 191        /// <summary>
 192        /// 读取 uint(32位)
 193        /// </summary>
 194        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 195        public uint ReadUInt()
 196        {
 0197            return ReadBits(32);
 198        }
 199
 200        /// <summary>
 201        /// 写入 short(16位)
 202        /// </summary>
 203        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 204        public void WriteShort(short value)
 205        {
 0206            WriteBits((uint)(ushort)value, 16);
 0207        }
 208
 209        /// <summary>
 210        /// 读取 short(16位)
 211        /// </summary>
 212        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 213        public short ReadShort()
 214        {
 0215            return (short)ReadBits(16);
 216        }
 217
 218        /// <summary>
 219        /// 写入 ushort(16位)
 220        /// </summary>
 221        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 222        public void WriteUShort(ushort value)
 223        {
 0224            WriteBits(value, 16);
 0225        }
 226
 227        /// <summary>
 228        /// 读取 ushort(16位)
 229        /// </summary>
 230        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 231        public ushort ReadUShort()
 232        {
 0233            return (ushort)ReadBits(16);
 234        }
 235
 236        /// <summary>
 237        /// 写入 byte(8位)
 238        /// </summary>
 239        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 240        public void WriteByte(byte value)
 241        {
 0242            WriteBits(value, 8);
 0243        }
 244
 245        /// <summary>
 246        /// 读取 byte(8位)
 247        /// </summary>
 248        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 249        public byte ReadByte()
 250        {
 0251            return (byte)ReadBits(8);
 252        }
 253
 254        /// <summary>
 255        /// 写入 bool(1位)
 256        /// </summary>
 257        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 258        public void WriteBool(bool value)
 259        {
 0260            WriteBit(value);
 0261        }
 262
 263        /// <summary>
 264        /// 读取 bool(1位)
 265        /// </summary>
 266        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 267        public bool ReadBool()
 268        {
 0269            return ReadBit();
 270        }
 271
 272        /// <summary>
 273        /// 写入 long(64位)
 274        /// </summary>
 275        public void WriteLong(long value)
 276        {
 0277            WriteBits((uint)value, 32);
 0278            WriteBits((uint)(value >> 32), 32);
 0279        }
 280
 281        /// <summary>
 282        /// 读取 long(64位)
 283        /// </summary>
 284        public long ReadLong()
 285        {
 0286            long low = ReadBits(32);
 0287            long high = ReadBits(32);
 0288            return low | (high << 32);
 289        }
 290
 291        /// <summary>
 292        /// 写入 ulong(64位)
 293        /// </summary>
 294        public void WriteULong(ulong value)
 295        {
 1296            WriteBits((uint)value, 32);
 1297            WriteBits((uint)(value >> 32), 32);
 1298        }
 299
 300        /// <summary>
 301        /// 读取 ulong(64位)
 302        /// </summary>
 303        public ulong ReadULong()
 304        {
 1305            ulong low = ReadBits(32);
 1306            ulong high = ReadBits(32);
 1307            return low | (high << 32);
 308        }
 309
 310        #endregion
 311
 312        #region 变长整数(VarInt)
 313
 314        /// <summary>
 315        /// 写入变长 uint(小值更省空间)
 316        /// </summary>
 317        public void WriteVarUInt(uint value)
 318        {
 319            // 每个字节使用 7 位数据 + 1 位继续标志
 0320            while (value >= 0x80)
 321            {
 0322                WriteByte((byte)(value | 0x80));
 0323                value >>= 7;
 324            }
 0325            WriteByte((byte)value);
 0326        }
 327
 328        /// <summary>
 329        /// 读取变长 uint
 330        /// </summary>
 331        public uint ReadVarUInt()
 332        {
 0333            uint value = 0;
 0334            int shift = 0;
 335            byte b;
 336
 337            do
 338            {
 0339                b = ReadByte();
 0340                value |= (uint)(b & 0x7F) << shift;
 0341                shift += 7;
 0342            } while ((b & 0x80) != 0);
 343
 0344            return value;
 345        }
 346
 347        /// <summary>
 348        /// 写入变长 int(ZigZag 编码)
 349        /// </summary>
 350        public void WriteVarInt(int value)
 351        {
 352            // ZigZag 编码:将符号位移到最低位
 0353            uint encoded = (uint)((value << 1) ^ (value >> 31));
 0354            WriteVarUInt(encoded);
 0355        }
 356
 357        /// <summary>
 358        /// 读取变长 int
 359        /// </summary>
 360        public int ReadVarInt()
 361        {
 0362            uint encoded = ReadVarUInt();
 0363            return (int)((encoded >> 1) ^ -(encoded & 1));
 364        }
 365
 366        #endregion
 367
 368        #region 原始内存操作
 369
 370        /// <summary>
 371        /// 写入原始字节数组
 372        /// </summary>
 373        public void WriteBytes(byte[] data, int offset, int length)
 374        {
 375            // 对齐到字节边界
 0376            if (_bitPosition != 0)
 377            {
 0378                _bitPosition = 0;
 0379                _bytePosition++;
 380            }
 381
 0382            EnsureCapacity(_bytePosition + length);
 383
 0384            Buffer.BlockCopy(data, offset, _buffer, _bytePosition, length);
 0385            _bytePosition += length;
 0386        }
 387
 388        /// <summary>
 389        /// 读取原始字节数组
 390        /// </summary>
 391        public void ReadBytes(byte[] destination, int offset, int length)
 392        {
 393            // 对齐到字节边界
 0394            if (_bitPosition != 0)
 395            {
 0396                _bitPosition = 0;
 0397                _bytePosition++;
 398            }
 399
 0400            if (_bytePosition + length > _byteLimit)
 0401                throw new EndOfStreamException();
 402
 0403            Buffer.BlockCopy(_buffer, _bytePosition, destination, offset, length);
 0404            _bytePosition += length;
 0405        }
 406
 407        /// <summary>
 408        /// 写入非托管内存
 409        /// </summary>
 410        public void WriteMemory(void* source, int length)
 411        {
 412            // 对齐到字节边界
 0413            if (_bitPosition != 0)
 414            {
 0415                _bitPosition = 0;
 0416                _bytePosition++;
 417            }
 418
 0419            EnsureCapacity(_bytePosition + length);
 420
 0421            fixed (byte* dest = &_buffer[_bytePosition])
 422            {
 0423                Buffer.MemoryCopy(source, dest, length, length);
 424            }
 425
 0426            _bytePosition += length;
 0427        }
 428
 429        /// <summary>
 430        /// 读取到非托管内存
 431        /// </summary>
 432        public void ReadMemory(void* destination, int length)
 433        {
 434            // 对齐到字节边界
 0435            if (_bitPosition != 0)
 436            {
 0437                _bitPosition = 0;
 0438                _bytePosition++;
 439            }
 440
 0441            if (_bytePosition + length > _byteLimit)
 0442                throw new EndOfStreamException();
 443
 0444            fixed (byte* src = &_buffer[_bytePosition])
 445            {
 0446                Buffer.MemoryCopy(src, destination, length, length);
 447            }
 448
 0449            _bytePosition += length;
 0450        }
 451
 452        #endregion
 453
 454        #region 辅助方法
 455
 456        /// <summary>
 457        /// 获取写入的数据
 458        /// </summary>
 459        public byte[] ToArray()
 460        {
 1461            int length = BytesUsed;
 1462            byte[] result = new byte[length];
 1463            Buffer.BlockCopy(_buffer, 0, result, 0, length);
 1464            return result;
 465        }
 466
 467        /// <summary>
 468        /// 获取当前已写入数据的只读视图,不发生额外分配。
 469        /// </summary>
 470        public ReadOnlySpan<byte> GetWrittenSpan()
 471        {
 0472            return new ReadOnlySpan<byte>(_buffer, 0, BytesUsed);
 473        }
 474
 475        /// <summary>
 476        /// 重置流(用于复用)
 477        /// </summary>
 478        public void Reset()
 479        {
 0480            _bytePosition = 0;
 0481            _bitPosition = 0;
 0482            if (IsWriting)
 483            {
 0484                _byteLimit = _buffer.Length;
 485            }
 0486        }
 487
 488        /// <summary>
 489        /// 确保容量
 490        /// </summary>
 491        private void EnsureCapacity(int required)
 492        {
 96493            if (required <= _buffer.Length)
 96494                return;
 495
 0496            int newCapacity = System.Math.Max(required, _buffer.Length * 2);
 0497            byte[] newBuffer = new byte[newCapacity];
 0498            Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _buffer.Length);
 0499            _buffer = newBuffer;
 0500            _byteLimit = _buffer.Length;
 0501        }
 502
 503        #endregion
 504
 505        #region 缓冲区安全检查
 506
 507        /// <summary>
 508        /// 检查剩余写入空间是否足够
 509        /// </summary>
 510        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 0511        public bool CanWrite(int bytes) => _bytePosition + bytes <= _buffer.Length;
 512
 513        /// <summary>
 514        /// 检查剩余读取空间是否足够
 515        /// </summary>
 516        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 0517        public bool CanRead(int bytes) => _bytePosition + bytes <= _byteLimit;
 518
 519        /// <summary>
 520        /// 验证可以读取指定数量的字节
 521        /// </summary>
 522        public void VerifyCanRead(int bytes, string operation = "read")
 523        {
 0524            if (!CanRead(bytes))
 0525                throw new EndOfStreamException(
 0526                    $"Insufficient data to {operation}. " +
 0527                    $"Required: {bytes} bytes, Available: {_byteLimit - _bytePosition} bytes " +
 0528                    $"(at position {_bytePosition})");
 0529        }
 530
 531        /// <summary>
 532        /// 获取剩余可读字节数
 533        /// </summary>
 0534        public int RemainingBytes => System.Math.Max(0, _byteLimit - _bytePosition);
 535
 536        /// <summary>
 537        /// 获取当前位置信息(用于调试)
 538        /// </summary>
 539        public string PositionInfo =>
 0540            $"Byte: {_bytePosition}, Bit: {_bitPosition}, Length: {_byteLimit}";
 541
 542        #endregion
 543    }
 544}