From a588584673031483dbc979419125c49b5fadcf9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Albin=20Cor=C3=A9n?= <2108U9@gmail.com> Date: Sat, 14 Apr 2018 09:08:18 +0100 Subject: [PATCH] Added allocating Finalize overload to BitWriter --- .../Binary/BitWriter.cs | 23 +++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/MLAPI/NetworkingManagerComponents/Binary/BitWriter.cs b/MLAPI/NetworkingManagerComponents/Binary/BitWriter.cs index c5c41f2..5a6c46b 100644 --- a/MLAPI/NetworkingManagerComponents/Binary/BitWriter.cs +++ b/MLAPI/NetworkingManagerComponents/Binary/BitWriter.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using System.Text; @@ -114,6 +113,26 @@ namespace MLAPI.NetworkingManagerComponents.Binary 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); } + public byte[] Finalize() + { + long bitCount = 0; + for (int i = 0; i < collect.Count; ++i) bitCount += collect[i] == null ? (8 - (bitCount % 8)) % 8 : GetBitCount(collect[i]); + byte[] buffer = new byte[((bitCount / 8) + (bitCount % 8 == 0 ? 0 : 1))]; + + long bitOffset = 0; + bool isAligned = true; + foreach (var item in collect) + if (item == null) + { + bitOffset += (8 - (bitOffset % 8)) % 8; + isAligned = true; + } + else Serialize(item, buffer, ref bitOffset, ref isAligned); + + return buffer; + } + + //The ref is not needed. It's purley there to indicate that it's treated as a reference inside the method. public long Finalize(ref byte[] buffer) { if(buffer == null) @@ -145,7 +164,7 @@ namespace MLAPI.NetworkingManagerComponents.Binary public long GetFinalizeSize() { long bitCount = 0; - for (int i = 0; i < collect.Count; ++i) bitCount += collect[i]==null ? (8 - (bitCount % 8)) % 8 : GetBitCount(collect[i]); + for (int i = 0; i < collect.Count; ++i) bitCount += collect[i] == null ? (8 - (bitCount % 8)) % 8 : GetBitCount(collect[i]); return ((bitCount / 8) + (bitCount % 8 == 0 ? 0 : 1)); }