Skip to content

Commit a588584

Browse files
committed
Added allocating Finalize overload to BitWriter
1 parent 8e84391 commit a588584

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

MLAPI/NetworkingManagerComponents/Binary/BitWriter.cs

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
using System;
22
using System.Collections.Generic;
3-
using System.Diagnostics;
43
using System.Reflection;
54
using System.Runtime.InteropServices;
65
using System.Text;
@@ -114,6 +113,26 @@ public void PushArray<T>(T[] t, bool knownSize = false)
114113
foreach (T t1 in t) Push(signed ? (object)ZigZagEncode(t1 as long? ?? t1 as int? ?? t1 as short? ?? t1 as sbyte? ?? 0, size) : (object)t1);
115114
}
116115

116+
public byte[] Finalize()
117+
{
118+
long bitCount = 0;
119+
for (int i = 0; i < collect.Count; ++i) bitCount += collect[i] == null ? (8 - (bitCount % 8)) % 8 : GetBitCount(collect[i]);
120+
byte[] buffer = new byte[((bitCount / 8) + (bitCount % 8 == 0 ? 0 : 1))];
121+
122+
long bitOffset = 0;
123+
bool isAligned = true;
124+
foreach (var item in collect)
125+
if (item == null)
126+
{
127+
bitOffset += (8 - (bitOffset % 8)) % 8;
128+
isAligned = true;
129+
}
130+
else Serialize(item, buffer, ref bitOffset, ref isAligned);
131+
132+
return buffer;
133+
}
134+
135+
//The ref is not needed. It's purley there to indicate that it's treated as a reference inside the method.
117136
public long Finalize(ref byte[] buffer)
118137
{
119138
if(buffer == null)
@@ -145,7 +164,7 @@ public long Finalize(ref byte[] buffer)
145164
public long GetFinalizeSize()
146165
{
147166
long bitCount = 0;
148-
for (int i = 0; i < collect.Count; ++i) bitCount += collect[i]==null ? (8 - (bitCount % 8)) % 8 : GetBitCount(collect[i]);
167+
for (int i = 0; i < collect.Count; ++i) bitCount += collect[i] == null ? (8 - (bitCount % 8)) % 8 : GetBitCount(collect[i]);
149168
return ((bitCount / 8) + (bitCount % 8 == 0 ? 0 : 1));
150169
}
151170

0 commit comments

Comments
 (0)