Skip to content

Commit 0b83ba3

Browse files
Miraculously fixed misaligned byte writing
1 parent 1f49ad9 commit 0b83ba3

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

MLAPI/NetworkingManagerComponents/Binary/BitStream.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ public override void Flush() { } // NOP
144144
private byte ReadByteMisaligned()
145145
{
146146
int mod = (int)(BitPosition & 7);
147-
return (byte)((target[(int)Position++] >> mod) | (target[(int)Position] << (8 - mod)));
147+
return (byte)((target[(int)Position] >> mod) | (target[(int)(BitPosition += 8) >> 3] << (8 - mod)));
148148
}
149149
/// <summary>
150150
/// Read an aligned byte from the buffer. It's recommended to not use this when the BitPosition is byte-misaligned.
@@ -224,6 +224,7 @@ public override void SetLength(long value)
224224
if (value < 0) throw new IndexOutOfRangeException("Cannot set a negative length!");
225225
if (value > Capacity) Grow(value - Capacity);
226226
BitLength = (ulong)value << 3;
227+
BitPosition = Math.Min((ulong)value << 3, BitPosition);
227228
}
228229

229230
/// <summary>
@@ -269,7 +270,7 @@ public void WriteBit(bool bit)
269270
{
270271
if (BitAligned && Position == target.Length) Grow(1);
271272
int offset = (int)(BitPosition & 7);
272-
ulong pos = BitPosition >> 3;
273+
long pos = Position;
273274
++BitPosition;
274275
target[pos] = (byte)(bit ? (target[pos] & ~(1 << offset)) | (1 << offset) : (target[pos] & ~(1 << offset)));
275276
UpdateLength();
@@ -810,7 +811,7 @@ private void _WriteMisaligned(byte value)
810811
{
811812
int off = (int)(BitPosition & 7);
812813
int shift1 = 8 - off;
813-
target[Position + 1] = (byte)((target[Position + 1] & (0xFF >> off)) | (value >> shift1));
814+
target[Position + 1] = (byte)((target[Position + 1] & (0xFF << off)) | (value >> shift1));
814815
target[Position] = (byte)((target[Position] & (0xFF >> shift1)) | (value << off));
815816

816817
BitPosition += 8;

0 commit comments

Comments
 (0)