1- using MLAPI . NetworkingManagerComponents . Binary ;
2- using System ;
1+ using System ;
32using System . Collections . Generic ;
4- using System . IO ;
5- using System . Linq ;
63using System . Reflection ;
7- using System . Runtime . InteropServices ;
84using System . Text ;
5+ using UnityEngine ;
96
10- namespace Tofvesson . Common
7+ namespace MLAPI . NetworkingManagerComponents . Binary
118{
12- public sealed class BinaryCollector : IDisposable
9+ public sealed class BitWiter : IDisposable
1310 {
1411 // Collects reusable
1512 private static readonly List < WeakReference > expired = new List < WeakReference > ( ) ;
@@ -41,7 +38,7 @@ private static readonly FieldInfo
4138 dec_hi ,
4239 dec_flags ;
4340
44- static BinaryCollector ( )
41+ static BitWiter ( )
4542 {
4643 dec_lo = typeof ( decimal ) . GetField ( "lo" , BindingFlags . NonPublic ) ;
4744 dec_mid = typeof ( decimal ) . GetField ( "mid" , BindingFlags . NonPublic ) ;
@@ -56,7 +53,7 @@ static BinaryCollector()
5653 /// <summary>
5754 /// Allocates a new binary collector.
5855 /// </summary>
59- public BinaryCollector ( int bufferSize )
56+ public BitWiter ( int bufferSize )
6057 {
6158 this . bufferSize = bufferSize ;
6259 for ( int i = expired . Count - 1 ; i >= 0 ; -- i )
@@ -106,17 +103,33 @@ private void Push<T>(T b)
106103 public void WriteLongArray ( long [ ] l ) => Push ( l ) ;
107104 public void WriteString ( string s ) => Push ( s ) ;
108105
109- public byte [ ] ToArray ( )
106+ public long Finalize ( ref byte [ ] buffer )
110107 {
108+ if ( buffer == null )
109+ {
110+ Debug . LogWarning ( "MLAPI: no buffer provided" ) ;
111+ return 0 ;
112+ }
111113 long bitCount = 0 ;
112114 for ( int i = 0 ; i < collectCount ; ++ i ) bitCount += GetBitCount ( collect [ i ] ) ;
113115
114- byte [ ] alloc = new byte [ ( bitCount / 8 ) + ( bitCount % 8 == 0 ? 0 : 1 ) ] ;
116+ if ( buffer . Length < ( ( bitCount / 8 ) + ( bitCount % 8 == 0 ? 0 : 1 ) ) )
117+ {
118+ Debug . LogWarning ( "MLAPI: The buffer size is not large enough" ) ;
119+ return 0 ;
120+ }
115121 long bitOffset = 0 ;
116122 foreach ( var item in collect )
117- Serialize ( item , alloc , ref bitOffset ) ;
123+ Serialize ( item , buffer , ref bitOffset ) ;
118124
119- return alloc ;
125+ return ( bitCount / 8 ) + ( bitCount % 8 == 0 ? 0 : 1 ) ) ;
126+ }
127+
128+ public long GetFinalizeSize ( )
129+ {
130+ long bitCount = 0 ;
131+ for ( int i = 0 ; i < collectCount ; ++ i ) bitCount += GetBitCount ( collect [ i ] ) ;
132+ return ( ( bitCount / 8 ) + ( bitCount % 8 == 0 ? 0 : 1 ) ) ;
120133 }
121134
122135 private static void Serialize < T > ( T t , byte [ ] writeTo , ref long bitOffset )
0 commit comments