1
- using MLAPI . NetworkingManagerComponents . Binary ;
2
- using System ;
1
+ using System ;
3
2
using System . Collections . Generic ;
4
- using System . IO ;
5
- using System . Linq ;
6
3
using System . Reflection ;
7
- using System . Runtime . InteropServices ;
8
4
using System . Text ;
5
+ using UnityEngine ;
9
6
10
- namespace Tofvesson . Common
7
+ namespace MLAPI . NetworkingManagerComponents . Binary
11
8
{
12
- public sealed class BinaryCollector : IDisposable
9
+ public sealed class BitWiter : IDisposable
13
10
{
14
11
// Collects reusable
15
12
private static readonly List < WeakReference > expired = new List < WeakReference > ( ) ;
@@ -41,7 +38,7 @@ private static readonly FieldInfo
41
38
dec_hi ,
42
39
dec_flags ;
43
40
44
- static BinaryCollector ( )
41
+ static BitWiter ( )
45
42
{
46
43
dec_lo = typeof ( decimal ) . GetField ( "lo" , BindingFlags . NonPublic ) ;
47
44
dec_mid = typeof ( decimal ) . GetField ( "mid" , BindingFlags . NonPublic ) ;
@@ -56,7 +53,7 @@ static BinaryCollector()
56
53
/// <summary>
57
54
/// Allocates a new binary collector.
58
55
/// </summary>
59
- public BinaryCollector ( int bufferSize )
56
+ public BitWiter ( int bufferSize )
60
57
{
61
58
this . bufferSize = bufferSize ;
62
59
for ( int i = expired . Count - 1 ; i >= 0 ; -- i )
@@ -106,17 +103,33 @@ private void Push<T>(T b)
106
103
public void WriteLongArray ( long [ ] l ) => Push ( l ) ;
107
104
public void WriteString ( string s ) => Push ( s ) ;
108
105
109
- public byte [ ] ToArray ( )
106
+ public long Finalize ( ref byte [ ] buffer )
110
107
{
108
+ if ( buffer == null )
109
+ {
110
+ Debug . LogWarning ( "MLAPI: no buffer provided" ) ;
111
+ return 0 ;
112
+ }
111
113
long bitCount = 0 ;
112
114
for ( int i = 0 ; i < collectCount ; ++ i ) bitCount += GetBitCount ( collect [ i ] ) ;
113
115
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
+ }
115
121
long bitOffset = 0 ;
116
122
foreach ( var item in collect )
117
- Serialize ( item , alloc , ref bitOffset ) ;
123
+ Serialize ( item , buffer , ref bitOffset ) ;
118
124
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 ) ) ;
120
133
}
121
134
122
135
private static void Serialize < T > ( T t , byte [ ] writeTo , ref long bitOffset )
0 commit comments