BitStream.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182
  1. /*
  2. * Copyright (c) 2014, Oculus VR, Inc.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under the BSD-style license found in the
  6. * LICENSE file in the root directory of this source tree. An additional grant
  7. * of patent rights can be found in the PATENTS file in the same directory.
  8. *
  9. */
  10. /// \file
  11. ///
  12. #if defined(_MSC_VER) && _MSC_VER < 1299 // VC6 doesn't support template specialization
  13. #include "BitStream_NoTemplate.cpp"
  14. #else
  15. #include "BitStream.h"
  16. #include <stdio.h>
  17. #include <string.h>
  18. #include <stdlib.h>
  19. #include "SocketIncludes.h"
  20. #include "RakNetDefines.h"
  21. #if defined(_WIN32)
  22. #include "WindowsIncludes.h"
  23. #include <memory.h>
  24. #include <cmath>
  25. #include <float.h>
  26. #else
  27. #include <arpa/inet.h>
  28. #include <memory.h>
  29. #if defined(ANDROID)
  30. #include <math.h>
  31. #else
  32. #include <cmath>
  33. #endif
  34. #include <float.h>
  35. #endif
  36. // MSWin uses _copysign, others use copysign...
  37. #ifndef _WIN32
  38. #define _copysign copysign
  39. #endif
  40. using namespace RakNet;
  41. #ifdef _MSC_VER
  42. #pragma warning( push )
  43. #endif
  44. STATIC_FACTORY_DEFINITIONS(BitStream,BitStream)
  45. BitStream::BitStream()
  46. {
  47. numberOfBitsUsed = 0;
  48. //numberOfBitsAllocated = 32 * 8;
  49. numberOfBitsAllocated = BITSTREAM_STACK_ALLOCATION_SIZE * 8;
  50. readOffset = 0;
  51. //data = ( unsigned char* ) rakMalloc_Ex( 32, _FILE_AND_LINE_ );
  52. data = ( unsigned char* ) stackData;
  53. #ifdef _DEBUG
  54. // RakAssert( data );
  55. #endif
  56. //memset(data, 0, 32);
  57. copyData = true;
  58. }
  59. BitStream::BitStream( const unsigned int initialBytesToAllocate )
  60. {
  61. numberOfBitsUsed = 0;
  62. readOffset = 0;
  63. if (initialBytesToAllocate <= BITSTREAM_STACK_ALLOCATION_SIZE)
  64. {
  65. data = ( unsigned char* ) stackData;
  66. numberOfBitsAllocated = BITSTREAM_STACK_ALLOCATION_SIZE * 8;
  67. }
  68. else
  69. {
  70. data = ( unsigned char* ) rakMalloc_Ex( (size_t) initialBytesToAllocate, _FILE_AND_LINE_ );
  71. numberOfBitsAllocated = initialBytesToAllocate << 3;
  72. }
  73. #ifdef _DEBUG
  74. RakAssert( data );
  75. #endif
  76. // memset(data, 0, initialBytesToAllocate);
  77. copyData = true;
  78. }
  79. BitStream::BitStream( unsigned char* _data, const unsigned int lengthInBytes, bool _copyData )
  80. {
  81. numberOfBitsUsed = lengthInBytes << 3;
  82. readOffset = 0;
  83. copyData = _copyData;
  84. numberOfBitsAllocated = lengthInBytes << 3;
  85. if ( copyData )
  86. {
  87. if ( lengthInBytes > 0 )
  88. {
  89. if (lengthInBytes < BITSTREAM_STACK_ALLOCATION_SIZE)
  90. {
  91. data = ( unsigned char* ) stackData;
  92. numberOfBitsAllocated = BITSTREAM_STACK_ALLOCATION_SIZE << 3;
  93. }
  94. else
  95. {
  96. data = ( unsigned char* ) rakMalloc_Ex( (size_t) lengthInBytes, _FILE_AND_LINE_ );
  97. }
  98. #ifdef _DEBUG
  99. RakAssert( data );
  100. #endif
  101. memcpy( data, _data, (size_t) lengthInBytes );
  102. }
  103. else
  104. data = 0;
  105. }
  106. else
  107. data = ( unsigned char* ) _data;
  108. }
  109. // Use this if you pass a pointer copy to the constructor (_copyData==false) and want to overallocate to prevent reallocation
  110. void BitStream::SetNumberOfBitsAllocated( const BitSize_t lengthInBits )
  111. {
  112. #ifdef _DEBUG
  113. RakAssert( lengthInBits >= ( BitSize_t ) numberOfBitsAllocated );
  114. #endif
  115. numberOfBitsAllocated = lengthInBits;
  116. }
  117. BitStream::~BitStream()
  118. {
  119. if ( copyData && numberOfBitsAllocated > (BITSTREAM_STACK_ALLOCATION_SIZE << 3))
  120. rakFree_Ex( data , _FILE_AND_LINE_ ); // Use realloc and free so we are more efficient than delete and new for resizing
  121. }
  122. void BitStream::Reset( void )
  123. {
  124. // Note: Do NOT reallocate memory because BitStream is used
  125. // in places to serialize/deserialize a buffer. Reallocation
  126. // is a dangerous operation (may result in leaks).
  127. if ( numberOfBitsUsed > 0 )
  128. {
  129. // memset(data, 0, BITS_TO_BYTES(numberOfBitsUsed));
  130. }
  131. // Don't free memory here for speed efficiency
  132. //free(data); // Use realloc and free so we are more efficient than delete and new for resizing
  133. numberOfBitsUsed = 0;
  134. //numberOfBitsAllocated=8;
  135. readOffset = 0;
  136. //data=(unsigned char*)rakMalloc_Ex(1, _FILE_AND_LINE_);
  137. // if (numberOfBitsAllocated>0)
  138. // memset(data, 0, BITS_TO_BYTES(numberOfBitsAllocated));
  139. }
  140. // Write an array or casted stream
  141. void BitStream::Write( const char* inputByteArray, const unsigned int numberOfBytes )
  142. {
  143. if (numberOfBytes==0)
  144. return;
  145. // Optimization:
  146. if ((numberOfBitsUsed & 7) == 0)
  147. {
  148. AddBitsAndReallocate( BYTES_TO_BITS(numberOfBytes) );
  149. memcpy(data+BITS_TO_BYTES(numberOfBitsUsed), inputByteArray, (size_t) numberOfBytes);
  150. numberOfBitsUsed+=BYTES_TO_BITS(numberOfBytes);
  151. }
  152. else
  153. {
  154. WriteBits( ( unsigned char* ) inputByteArray, numberOfBytes * 8, true );
  155. }
  156. }
  157. void BitStream::Write( BitStream *bitStream)
  158. {
  159. Write(bitStream, bitStream->GetNumberOfBitsUsed()-bitStream->GetReadOffset());
  160. }
  161. void BitStream::Write( BitStream *bitStream, BitSize_t numberOfBits )
  162. {
  163. AddBitsAndReallocate( numberOfBits );
  164. BitSize_t numberOfBitsMod8;
  165. if ((bitStream->GetReadOffset()&7)==0 && (numberOfBitsUsed&7)==0)
  166. {
  167. int readOffsetBytes=bitStream->GetReadOffset()/8;
  168. int numBytes=numberOfBits/8;
  169. memcpy(data + (numberOfBitsUsed >> 3), bitStream->GetData()+readOffsetBytes, numBytes);
  170. numberOfBits-=BYTES_TO_BITS(numBytes);
  171. bitStream->SetReadOffset(BYTES_TO_BITS(numBytes+readOffsetBytes));
  172. numberOfBitsUsed+=BYTES_TO_BITS(numBytes);
  173. }
  174. while (numberOfBits-->0 && bitStream->readOffset + 1 <= bitStream->numberOfBitsUsed)
  175. {
  176. numberOfBitsMod8 = numberOfBitsUsed & 7;
  177. if ( numberOfBitsMod8 == 0 )
  178. {
  179. // New byte
  180. if (bitStream->data[ bitStream->readOffset >> 3 ] & ( 0x80 >> ( bitStream->readOffset & 7 ) ) )
  181. {
  182. // Write 1
  183. data[ numberOfBitsUsed >> 3 ] = 0x80;
  184. }
  185. else
  186. {
  187. // Write 0
  188. data[ numberOfBitsUsed >> 3 ] = 0;
  189. }
  190. }
  191. else
  192. {
  193. // Existing byte
  194. if (bitStream->data[ bitStream->readOffset >> 3 ] & ( 0x80 >> ( bitStream->readOffset & 7 ) ) )
  195. data[ numberOfBitsUsed >> 3 ] |= 0x80 >> ( numberOfBitsMod8 ); // Set the bit to 1
  196. // else 0, do nothing
  197. }
  198. bitStream->readOffset++;
  199. numberOfBitsUsed++;
  200. }
  201. }
  202. void BitStream::Write( BitStream &bitStream, BitSize_t numberOfBits )
  203. {
  204. Write(&bitStream, numberOfBits);
  205. }
  206. void BitStream::Write( BitStream &bitStream )
  207. {
  208. Write(&bitStream);
  209. }
  210. bool BitStream::Read( BitStream *bitStream, BitSize_t numberOfBits )
  211. {
  212. if (GetNumberOfUnreadBits() < numberOfBits)
  213. return false;
  214. bitStream->Write(this, numberOfBits);
  215. return true;
  216. }
  217. bool BitStream::Read( BitStream *bitStream )
  218. {
  219. bitStream->Write(this);
  220. return true;
  221. }
  222. bool BitStream::Read( BitStream &bitStream, BitSize_t numberOfBits )
  223. {
  224. if (GetNumberOfUnreadBits() < numberOfBits)
  225. return false;
  226. bitStream.Write(this, numberOfBits);
  227. return true;
  228. }
  229. bool BitStream::Read( BitStream &bitStream )
  230. {
  231. bitStream.Write(this);
  232. return true;
  233. }
  234. // Read an array or casted stream
  235. bool BitStream::Read( char* outByteArray, const unsigned int numberOfBytes )
  236. {
  237. // Optimization:
  238. if ((readOffset & 7) == 0)
  239. {
  240. if ( readOffset + ( numberOfBytes << 3 ) > numberOfBitsUsed )
  241. return false;
  242. // Write the data
  243. memcpy( outByteArray, data + ( readOffset >> 3 ), (size_t) numberOfBytes );
  244. readOffset += numberOfBytes << 3;
  245. return true;
  246. }
  247. else
  248. {
  249. return ReadBits( ( unsigned char* ) outByteArray, numberOfBytes * 8 );
  250. }
  251. }
  252. // Sets the read pointer back to the beginning of your data.
  253. void BitStream::ResetReadPointer( void )
  254. {
  255. readOffset = 0;
  256. }
  257. // Sets the write pointer back to the beginning of your data.
  258. void BitStream::ResetWritePointer( void )
  259. {
  260. numberOfBitsUsed = 0;
  261. }
  262. // Write a 0
  263. void BitStream::Write0( void )
  264. {
  265. AddBitsAndReallocate( 1 );
  266. // New bytes need to be zeroed
  267. if ( ( numberOfBitsUsed & 7 ) == 0 )
  268. data[ numberOfBitsUsed >> 3 ] = 0;
  269. numberOfBitsUsed++;
  270. }
  271. // Write a 1
  272. void BitStream::Write1( void )
  273. {
  274. AddBitsAndReallocate( 1 );
  275. BitSize_t numberOfBitsMod8 = numberOfBitsUsed & 7;
  276. if ( numberOfBitsMod8 == 0 )
  277. data[ numberOfBitsUsed >> 3 ] = 0x80;
  278. else
  279. data[ numberOfBitsUsed >> 3 ] |= 0x80 >> ( numberOfBitsMod8 ); // Set the bit to 1
  280. numberOfBitsUsed++;
  281. }
  282. // Returns true if the next data read is a 1, false if it is a 0
  283. bool BitStream::ReadBit( void )
  284. {
  285. bool result = ( data[ readOffset >> 3 ] & ( 0x80 >> ( readOffset & 7 ) ) ) !=0;
  286. readOffset++;
  287. return result;
  288. }
  289. // Align the bitstream to the byte boundary and then write the specified number of bits.
  290. // This is faster than WriteBits but wastes the bits to do the alignment and requires you to call
  291. // SetReadToByteAlignment at the corresponding read position
  292. void BitStream::WriteAlignedBytes( const unsigned char* inByteArray, const unsigned int numberOfBytesToWrite )
  293. {
  294. AlignWriteToByteBoundary();
  295. Write((const char*) inByteArray, numberOfBytesToWrite);
  296. }
  297. void BitStream::EndianSwapBytes( int byteOffset, int length )
  298. {
  299. if (DoEndianSwap())
  300. {
  301. ReverseBytesInPlace(data+byteOffset, length);
  302. }
  303. }
  304. /// Aligns the bitstream, writes inputLength, and writes input. Won't write beyond maxBytesToWrite
  305. void BitStream::WriteAlignedBytesSafe( const char *inByteArray, const unsigned int inputLength, const unsigned int maxBytesToWrite )
  306. {
  307. if (inByteArray==0 || inputLength==0)
  308. {
  309. WriteCompressed((unsigned int)0);
  310. return;
  311. }
  312. WriteCompressed(inputLength);
  313. WriteAlignedBytes((const unsigned char*) inByteArray, inputLength < maxBytesToWrite ? inputLength : maxBytesToWrite);
  314. }
  315. // Read bits, starting at the next aligned bits. Note that the modulus 8 starting offset of the
  316. // sequence must be the same as was used with WriteBits. This will be a problem with packet coalescence
  317. // unless you byte align the coalesced packets.
  318. bool BitStream::ReadAlignedBytes( unsigned char* inOutByteArray, const unsigned int numberOfBytesToRead )
  319. {
  320. #ifdef _DEBUG
  321. RakAssert( numberOfBytesToRead > 0 );
  322. #endif
  323. if ( numberOfBytesToRead <= 0 )
  324. return false;
  325. // Byte align
  326. AlignReadToByteBoundary();
  327. if ( readOffset + ( numberOfBytesToRead << 3 ) > numberOfBitsUsed )
  328. return false;
  329. // Write the data
  330. memcpy( inOutByteArray, data + ( readOffset >> 3 ), (size_t) numberOfBytesToRead );
  331. readOffset += numberOfBytesToRead << 3;
  332. return true;
  333. }
  334. bool BitStream::ReadAlignedBytesSafe( char *inOutByteArray, int &inputLength, const int maxBytesToRead )
  335. {
  336. return ReadAlignedBytesSafe(inOutByteArray,(unsigned int&) inputLength,(unsigned int)maxBytesToRead);
  337. }
  338. bool BitStream::ReadAlignedBytesSafe( char *inOutByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead )
  339. {
  340. if (ReadCompressed(inputLength)==false)
  341. return false;
  342. if (inputLength > maxBytesToRead)
  343. inputLength=maxBytesToRead;
  344. if (inputLength==0)
  345. return true;
  346. return ReadAlignedBytes((unsigned char*) inOutByteArray, inputLength);
  347. }
  348. bool BitStream::ReadAlignedBytesSafeAlloc( char **outByteArray, int &inputLength, const unsigned int maxBytesToRead )
  349. {
  350. return ReadAlignedBytesSafeAlloc(outByteArray,(unsigned int&) inputLength, maxBytesToRead);
  351. }
  352. bool BitStream::ReadAlignedBytesSafeAlloc( char ** outByteArray, unsigned int &inputLength, const unsigned int maxBytesToRead )
  353. {
  354. rakFree_Ex(*outByteArray, _FILE_AND_LINE_ );
  355. *outByteArray=0;
  356. if (ReadCompressed(inputLength)==false)
  357. return false;
  358. if (inputLength > maxBytesToRead)
  359. inputLength=maxBytesToRead;
  360. if (inputLength==0)
  361. return true;
  362. *outByteArray = (char*) rakMalloc_Ex( (size_t) inputLength, _FILE_AND_LINE_ );
  363. return ReadAlignedBytes((unsigned char*) *outByteArray, inputLength);
  364. }
  365. // Write numberToWrite bits from the input source
  366. void BitStream::WriteBits( const unsigned char* inByteArray, BitSize_t numberOfBitsToWrite, const bool rightAlignedBits )
  367. {
  368. // if (numberOfBitsToWrite<=0)
  369. // return;
  370. AddBitsAndReallocate( numberOfBitsToWrite );
  371. const BitSize_t numberOfBitsUsedMod8 = numberOfBitsUsed & 7;
  372. // If currently aligned and numberOfBits is a multiple of 8, just memcpy for speed
  373. if (numberOfBitsUsedMod8==0 && (numberOfBitsToWrite&7)==0)
  374. {
  375. memcpy( data + ( numberOfBitsUsed >> 3 ), inByteArray, numberOfBitsToWrite>>3);
  376. numberOfBitsUsed+=numberOfBitsToWrite;
  377. return;
  378. }
  379. unsigned char dataByte;
  380. const unsigned char* inputPtr=inByteArray;
  381. // Faster to put the while at the top surprisingly enough
  382. while ( numberOfBitsToWrite > 0 )
  383. //do
  384. {
  385. dataByte = *( inputPtr++ );
  386. if ( numberOfBitsToWrite < 8 && rightAlignedBits ) // rightAlignedBits means in the case of a partial byte, the bits are aligned from the right (bit 0) rather than the left (as in the normal internal representation)
  387. dataByte <<= 8 - numberOfBitsToWrite; // shift left to get the bits on the left, as in our internal representation
  388. // Writing to a new byte each time
  389. if ( numberOfBitsUsedMod8 == 0 )
  390. * ( data + ( numberOfBitsUsed >> 3 ) ) = dataByte;
  391. else
  392. {
  393. // Copy over the new data.
  394. *( data + ( numberOfBitsUsed >> 3 ) ) |= dataByte >> ( numberOfBitsUsedMod8 ); // First half
  395. if ( 8 - ( numberOfBitsUsedMod8 ) < 8 && 8 - ( numberOfBitsUsedMod8 ) < numberOfBitsToWrite ) // If we didn't write it all out in the first half (8 - (numberOfBitsUsed%8) is the number we wrote in the first half)
  396. {
  397. *( data + ( numberOfBitsUsed >> 3 ) + 1 ) = (unsigned char) ( dataByte << ( 8 - ( numberOfBitsUsedMod8 ) ) ); // Second half (overlaps byte boundary)
  398. }
  399. }
  400. if ( numberOfBitsToWrite >= 8 )
  401. {
  402. numberOfBitsUsed += 8;
  403. numberOfBitsToWrite -= 8;
  404. }
  405. else
  406. {
  407. numberOfBitsUsed += numberOfBitsToWrite;
  408. numberOfBitsToWrite=0;
  409. }
  410. }
  411. // } while(numberOfBitsToWrite>0);
  412. }
  413. // Set the stream to some initial data. For internal use
  414. void BitStream::SetData( unsigned char *inByteArray )
  415. {
  416. data=inByteArray;
  417. copyData=false;
  418. }
  419. // Assume the input source points to a native type, compress and write it
  420. void BitStream::WriteCompressed( const unsigned char* inByteArray,
  421. const unsigned int size, const bool unsignedData )
  422. {
  423. BitSize_t currentByte = ( size >> 3 ) - 1; // PCs
  424. unsigned char byteMatch;
  425. if ( unsignedData )
  426. {
  427. byteMatch = 0;
  428. }
  429. else
  430. {
  431. byteMatch = 0xFF;
  432. }
  433. // Write upper bytes with a single 1
  434. // From high byte to low byte, if high byte is a byteMatch then write a 1 bit. Otherwise write a 0 bit and then write the remaining bytes
  435. while ( currentByte > 0 )
  436. {
  437. if ( inByteArray[ currentByte ] == byteMatch ) // If high byte is byteMatch (0 of 0xff) then it would have the same value shifted
  438. {
  439. bool b = true;
  440. Write( b );
  441. }
  442. else
  443. {
  444. // Write the remainder of the data after writing 0
  445. bool b = false;
  446. Write( b );
  447. WriteBits( inByteArray, ( currentByte + 1 ) << 3, true );
  448. // currentByte--;
  449. return ;
  450. }
  451. currentByte--;
  452. }
  453. // If the upper half of the last byte is a 0 (positive) or 16 (negative) then write a 1 and the remaining 4 bits. Otherwise write a 0 and the 8 bites.
  454. if ( ( unsignedData && ( ( *( inByteArray + currentByte ) ) & 0xF0 ) == 0x00 ) ||
  455. ( unsignedData == false && ( ( *( inByteArray + currentByte ) ) & 0xF0 ) == 0xF0 ) )
  456. {
  457. bool b = true;
  458. Write( b );
  459. WriteBits( inByteArray + currentByte, 4, true );
  460. }
  461. else
  462. {
  463. bool b = false;
  464. Write( b );
  465. WriteBits( inByteArray + currentByte, 8, true );
  466. }
  467. }
  468. // Read numberOfBitsToRead bits to the output source
  469. // alignBitsToRight should be set to true to convert internal bitstream data to userdata
  470. // It should be false if you used WriteBits with rightAlignedBits false
  471. bool BitStream::ReadBits( unsigned char *inOutByteArray, BitSize_t numberOfBitsToRead, const bool alignBitsToRight )
  472. {
  473. #ifdef _DEBUG
  474. // RakAssert( numberOfBitsToRead > 0 );
  475. #endif
  476. if (numberOfBitsToRead<=0)
  477. return false;
  478. if ( readOffset + numberOfBitsToRead > numberOfBitsUsed )
  479. return false;
  480. const BitSize_t readOffsetMod8 = readOffset & 7;
  481. // If currently aligned and numberOfBits is a multiple of 8, just memcpy for speed
  482. if (readOffsetMod8==0 && (numberOfBitsToRead&7)==0)
  483. {
  484. memcpy( inOutByteArray, data + ( readOffset >> 3 ), numberOfBitsToRead>>3);
  485. readOffset+=numberOfBitsToRead;
  486. return true;
  487. }
  488. BitSize_t offset = 0;
  489. memset( inOutByteArray, 0, (size_t) BITS_TO_BYTES( numberOfBitsToRead ) );
  490. while ( numberOfBitsToRead > 0 )
  491. {
  492. *( inOutByteArray + offset ) |= *( data + ( readOffset >> 3 ) ) << ( readOffsetMod8 ); // First half
  493. if ( readOffsetMod8 > 0 && numberOfBitsToRead > 8 - ( readOffsetMod8 ) ) // If we have a second half, we didn't read enough bytes in the first half
  494. *( inOutByteArray + offset ) |= *( data + ( readOffset >> 3 ) + 1 ) >> ( 8 - ( readOffsetMod8 ) ); // Second half (overlaps byte boundary)
  495. if (numberOfBitsToRead>=8)
  496. {
  497. numberOfBitsToRead -= 8;
  498. readOffset += 8;
  499. offset++;
  500. }
  501. else
  502. {
  503. int neg = (int) numberOfBitsToRead - 8;
  504. if ( neg < 0 ) // Reading a partial byte for the last byte, shift right so the data is aligned on the right
  505. {
  506. if ( alignBitsToRight )
  507. * ( inOutByteArray + offset ) >>= -neg;
  508. readOffset += 8 + neg;
  509. }
  510. else
  511. readOffset += 8;
  512. offset++;
  513. numberOfBitsToRead=0;
  514. }
  515. }
  516. return true;
  517. }
  518. // Assume the input source points to a compressed native type. Decompress and read it
  519. bool BitStream::ReadCompressed( unsigned char* inOutByteArray,
  520. const unsigned int size, const bool unsignedData )
  521. {
  522. unsigned int currentByte = ( size >> 3 ) - 1;
  523. unsigned char byteMatch, halfByteMatch;
  524. if ( unsignedData )
  525. {
  526. byteMatch = 0;
  527. halfByteMatch = 0;
  528. }
  529. else
  530. {
  531. byteMatch = 0xFF;
  532. halfByteMatch = 0xF0;
  533. }
  534. // Upper bytes are specified with a single 1 if they match byteMatch
  535. // From high byte to low byte, if high byte is a byteMatch then write a 1 bit. Otherwise write a 0 bit and then write the remaining bytes
  536. while ( currentByte > 0 )
  537. {
  538. // If we read a 1 then the data is byteMatch.
  539. bool b;
  540. if ( Read( b ) == false )
  541. return false;
  542. if ( b ) // Check that bit
  543. {
  544. inOutByteArray[ currentByte ] = byteMatch;
  545. currentByte--;
  546. }
  547. else
  548. {
  549. // Read the rest of the bytes
  550. if ( ReadBits( inOutByteArray, ( currentByte + 1 ) << 3 ) == false )
  551. return false;
  552. return true;
  553. }
  554. }
  555. // All but the first bytes are byteMatch. If the upper half of the last byte is a 0 (positive) or 16 (negative) then what we read will be a 1 and the remaining 4 bits.
  556. // Otherwise we read a 0 and the 8 bytes
  557. //RakAssert(readOffset+1 <=numberOfBitsUsed); // If this assert is hit the stream wasn't long enough to read from
  558. if ( readOffset + 1 > numberOfBitsUsed )
  559. return false;
  560. bool b=false;
  561. if ( Read( b ) == false )
  562. return false;
  563. if ( b ) // Check that bit
  564. {
  565. if ( ReadBits( inOutByteArray + currentByte, 4 ) == false )
  566. return false;
  567. inOutByteArray[ currentByte ] |= halfByteMatch; // We have to set the high 4 bits since these are set to 0 by ReadBits
  568. }
  569. else
  570. {
  571. if ( ReadBits( inOutByteArray + currentByte, 8 ) == false )
  572. return false;
  573. }
  574. return true;
  575. }
  576. // Reallocates (if necessary) in preparation of writing numberOfBitsToWrite
  577. void BitStream::AddBitsAndReallocate( const BitSize_t numberOfBitsToWrite )
  578. {
  579. BitSize_t newNumberOfBitsAllocated = numberOfBitsToWrite + numberOfBitsUsed;
  580. if ( numberOfBitsToWrite + numberOfBitsUsed > 0 && ( ( numberOfBitsAllocated - 1 ) >> 3 ) < ( ( newNumberOfBitsAllocated - 1 ) >> 3 ) ) // If we need to allocate 1 or more new bytes
  581. {
  582. #ifdef _DEBUG
  583. // If this assert hits then we need to specify true for the third parameter in the constructor
  584. // It needs to reallocate to hold all the data and can't do it unless we allocated to begin with
  585. // Often hits if you call Write or Serialize on a read-only bitstream
  586. RakAssert( copyData == true );
  587. #endif
  588. // Less memory efficient but saves on news and deletes
  589. /// Cap to 1 meg buffer to save on huge allocations
  590. newNumberOfBitsAllocated = ( numberOfBitsToWrite + numberOfBitsUsed ) * 2;
  591. if (newNumberOfBitsAllocated - ( numberOfBitsToWrite + numberOfBitsUsed ) > 1048576 )
  592. newNumberOfBitsAllocated = numberOfBitsToWrite + numberOfBitsUsed + 1048576;
  593. // BitSize_t newByteOffset = BITS_TO_BYTES( numberOfBitsAllocated );
  594. // Use realloc and free so we are more efficient than delete and new for resizing
  595. BitSize_t amountToAllocate = BITS_TO_BYTES( newNumberOfBitsAllocated );
  596. if (data==(unsigned char*)stackData)
  597. {
  598. if (amountToAllocate > BITSTREAM_STACK_ALLOCATION_SIZE)
  599. {
  600. data = ( unsigned char* ) rakMalloc_Ex( (size_t) amountToAllocate, _FILE_AND_LINE_ );
  601. RakAssert(data);
  602. // need to copy the stack data over to our new memory area too
  603. memcpy ((void *)data, (void *)stackData, (size_t) BITS_TO_BYTES( numberOfBitsAllocated ));
  604. }
  605. }
  606. else
  607. {
  608. data = ( unsigned char* ) rakRealloc_Ex( data, (size_t) amountToAllocate, _FILE_AND_LINE_ );
  609. }
  610. #ifdef _DEBUG
  611. RakAssert( data ); // Make sure realloc succeeded
  612. #endif
  613. // memset(data+newByteOffset, 0, ((newNumberOfBitsAllocated-1)>>3) - ((numberOfBitsAllocated-1)>>3)); // Set the new data block to 0
  614. }
  615. if ( newNumberOfBitsAllocated > numberOfBitsAllocated )
  616. numberOfBitsAllocated = newNumberOfBitsAllocated;
  617. }
  618. BitSize_t BitStream::GetNumberOfBitsAllocated(void) const
  619. {
  620. return numberOfBitsAllocated;
  621. }
  622. void BitStream::PadWithZeroToByteLength( unsigned int bytes )
  623. {
  624. if (GetNumberOfBytesUsed() < bytes)
  625. {
  626. AlignWriteToByteBoundary();
  627. unsigned int numToWrite = bytes - GetNumberOfBytesUsed();
  628. AddBitsAndReallocate( BYTES_TO_BITS(numToWrite) );
  629. memset(data+BITS_TO_BYTES(numberOfBitsUsed), 0, (size_t) numToWrite);
  630. numberOfBitsUsed+=BYTES_TO_BITS(numToWrite);
  631. }
  632. }
  633. /*
  634. // Julius Goryavsky's version of Harley's algorithm.
  635. // 17 elementary ops plus an indexed load, if the machine
  636. // has "and not."
  637. int nlz10b(unsigned x) {
  638. static char table[64] =
  639. {32,20,19, u, u,18, u, 7, 10,17, u, u,14, u, 6, u,
  640. u, 9, u,16, u, u, 1,26, u,13, u, u,24, 5, u, u,
  641. u,21, u, 8,11, u,15, u, u, u, u, 2,27, 0,25, u,
  642. 22, u,12, u, u, 3,28, u, 23, u, 4,29, u, u,30,31};
  643. x = x | (x >> 1); // Propagate leftmost
  644. x = x | (x >> 2); // 1-bit to the right.
  645. x = x | (x >> 4);
  646. x = x | (x >> 8);
  647. x = x & ~(x >> 16);
  648. x = x*0xFD7049FF; // Activate this line or the following 3.
  649. // x = (x << 9) - x; // Multiply by 511.
  650. // x = (x << 11) - x; // Multiply by 2047.
  651. // x = (x << 14) - x; // Multiply by 16383.
  652. return table[x >> 26];
  653. }
  654. */
  655. int BitStream::NumberOfLeadingZeroes( int8_t x ) {return NumberOfLeadingZeroes((uint8_t)x);}
  656. int BitStream::NumberOfLeadingZeroes( uint8_t x )
  657. {
  658. uint8_t y;
  659. int n;
  660. n = 8;
  661. y = x >> 4; if (y != 0) {n = n - 4; x = y;}
  662. y = x >> 2; if (y != 0) {n = n - 2; x = y;}
  663. y = x >> 1; if (y != 0) return n - 2;
  664. return (int)(n - x);
  665. }
  666. int BitStream::NumberOfLeadingZeroes( int16_t x ) {return NumberOfLeadingZeroes((uint16_t)x);}
  667. int BitStream::NumberOfLeadingZeroes( uint16_t x )
  668. {
  669. uint16_t y;
  670. int n;
  671. n = 16;
  672. y = x >> 8; if (y != 0) {n = n - 8; x = y;}
  673. y = x >> 4; if (y != 0) {n = n - 4; x = y;}
  674. y = x >> 2; if (y != 0) {n = n - 2; x = y;}
  675. y = x >> 1; if (y != 0) return n - 2;
  676. return (int)(n - x);
  677. }
  678. int BitStream::NumberOfLeadingZeroes( int32_t x ) {return NumberOfLeadingZeroes((uint32_t)x);}
  679. int BitStream::NumberOfLeadingZeroes( uint32_t x )
  680. {
  681. uint32_t y;
  682. int n;
  683. n = 32;
  684. y = x >>16; if (y != 0) {n = n -16; x = y;}
  685. y = x >> 8; if (y != 0) {n = n - 8; x = y;}
  686. y = x >> 4; if (y != 0) {n = n - 4; x = y;}
  687. y = x >> 2; if (y != 0) {n = n - 2; x = y;}
  688. y = x >> 1; if (y != 0) return n - 2;
  689. return (int)(n - x);
  690. }
  691. int BitStream::NumberOfLeadingZeroes( int64_t x ) {return NumberOfLeadingZeroes((uint64_t)x);}
  692. int BitStream::NumberOfLeadingZeroes( uint64_t x )
  693. {
  694. uint64_t y;
  695. int n;
  696. n = 64;
  697. y = x >>32; if (y != 0) {n = n -32; x = y;}
  698. y = x >>16; if (y != 0) {n = n -16; x = y;}
  699. y = x >> 8; if (y != 0) {n = n - 8; x = y;}
  700. y = x >> 4; if (y != 0) {n = n - 4; x = y;}
  701. y = x >> 2; if (y != 0) {n = n - 2; x = y;}
  702. y = x >> 1; if (y != 0) return n - 2;
  703. return (int)(n - x);
  704. }
  705. // Should hit if reads didn't match writes
  706. void BitStream::AssertStreamEmpty( void )
  707. {
  708. RakAssert( readOffset == numberOfBitsUsed );
  709. }
  710. void BitStream::PrintBits( char *out ) const
  711. {
  712. if ( numberOfBitsUsed <= 0 )
  713. {
  714. strcpy(out, "No bits\n" );
  715. return;
  716. }
  717. unsigned int strIndex=0;
  718. for ( BitSize_t counter = 0; counter < BITS_TO_BYTES( numberOfBitsUsed ) && strIndex < 2000 ; counter++ )
  719. {
  720. BitSize_t stop;
  721. if ( counter == ( numberOfBitsUsed - 1 ) >> 3 )
  722. stop = 8 - ( ( ( numberOfBitsUsed - 1 ) & 7 ) + 1 );
  723. else
  724. stop = 0;
  725. for ( BitSize_t counter2 = 7; counter2 >= stop; counter2-- )
  726. {
  727. if ( ( data[ counter ] >> counter2 ) & 1 )
  728. out[strIndex++]='1';
  729. else
  730. out[strIndex++]='0';
  731. if (counter2==0)
  732. break;
  733. }
  734. out[strIndex++]=' ';
  735. }
  736. out[strIndex++]='\n';
  737. out[strIndex++]=0;
  738. }
  739. void BitStream::PrintBits( void ) const
  740. {
  741. char out[2048];
  742. PrintBits(out);
  743. RAKNET_DEBUG_PRINTF("%s", out);
  744. }
  745. void BitStream::PrintHex( char *out ) const
  746. {
  747. BitSize_t i;
  748. for ( i=0; i < GetNumberOfBytesUsed(); i++)
  749. {
  750. sprintf(out+i*3, "%02x ", data[i]);
  751. }
  752. }
  753. void BitStream::PrintHex( void ) const
  754. {
  755. char out[2048];
  756. PrintHex(out);
  757. RAKNET_DEBUG_PRINTF("%s", out);
  758. }
  759. // Exposes the data for you to look at, like PrintBits does.
  760. // Data will point to the stream. Returns the length in bits of the stream.
  761. BitSize_t BitStream::CopyData( unsigned char** _data ) const
  762. {
  763. #ifdef _DEBUG
  764. RakAssert( numberOfBitsUsed > 0 );
  765. #endif
  766. *_data = (unsigned char*) rakMalloc_Ex( (size_t) BITS_TO_BYTES( numberOfBitsUsed ), _FILE_AND_LINE_ );
  767. memcpy( *_data, data, sizeof(unsigned char) * (size_t) ( BITS_TO_BYTES( numberOfBitsUsed ) ) );
  768. return numberOfBitsUsed;
  769. }
  770. // Ignore data we don't intend to read
  771. void BitStream::IgnoreBits( const BitSize_t numberOfBits )
  772. {
  773. readOffset += numberOfBits;
  774. }
  775. void BitStream::IgnoreBytes( const unsigned int numberOfBytes )
  776. {
  777. IgnoreBits(BYTES_TO_BITS(numberOfBytes));
  778. }
  779. // Move the write pointer to a position on the array. Dangerous if you don't know what you are doing!
  780. // Doesn't work with non-aligned data!
  781. void BitStream::SetWriteOffset( const BitSize_t offset )
  782. {
  783. numberOfBitsUsed = offset;
  784. }
  785. /*
  786. BitSize_t BitStream::GetWriteOffset( void ) const
  787. {
  788. return numberOfBitsUsed;
  789. }
  790. // Returns the length in bits of the stream
  791. BitSize_t BitStream::GetNumberOfBitsUsed( void ) const
  792. {
  793. return GetWriteOffset();
  794. }
  795. // Returns the length in bytes of the stream
  796. BitSize_t BitStream::GetNumberOfBytesUsed( void ) const
  797. {
  798. return BITS_TO_BYTES( numberOfBitsUsed );
  799. }
  800. // Returns the number of bits into the stream that we have read
  801. BitSize_t BitStream::GetReadOffset( void ) const
  802. {
  803. return readOffset;
  804. }
  805. // Sets the read bit index
  806. void BitStream::SetReadOffset( const BitSize_t newReadOffset )
  807. {
  808. readOffset=newReadOffset;
  809. }
  810. // Returns the number of bits left in the stream that haven't been read
  811. BitSize_t BitStream::GetNumberOfUnreadBits( void ) const
  812. {
  813. return numberOfBitsUsed - readOffset;
  814. }
  815. // Exposes the internal data
  816. unsigned char* BitStream::GetData( void ) const
  817. {
  818. return data;
  819. }
  820. */
  821. // If we used the constructor version with copy data off, this makes sure it is set to on and the data pointed to is copied.
  822. void BitStream::AssertCopyData( void )
  823. {
  824. if ( copyData == false )
  825. {
  826. copyData = true;
  827. if ( numberOfBitsAllocated > 0 )
  828. {
  829. unsigned char * newdata = ( unsigned char* ) rakMalloc_Ex( (size_t) BITS_TO_BYTES( numberOfBitsAllocated ), _FILE_AND_LINE_ );
  830. #ifdef _DEBUG
  831. RakAssert( data );
  832. #endif
  833. memcpy( newdata, data, (size_t) BITS_TO_BYTES( numberOfBitsAllocated ) );
  834. data = newdata;
  835. }
  836. else
  837. data = 0;
  838. }
  839. }
  840. bool BitStream::IsNetworkOrderInternal(void)
  841. {
  842. static unsigned long htonlValue = htonl(12345);
  843. return htonlValue == 12345;
  844. }
  845. void BitStream::ReverseBytes(unsigned char *inByteArray, unsigned char *inOutByteArray, const unsigned int length)
  846. {
  847. for (BitSize_t i=0; i < length; i++)
  848. inOutByteArray[i]=inByteArray[length-i-1];
  849. }
  850. void BitStream::ReverseBytesInPlace(unsigned char *inOutData,const unsigned int length)
  851. {
  852. unsigned char temp;
  853. BitSize_t i;
  854. for (i=0; i < (length>>1); i++)
  855. {
  856. temp = inOutData[i];
  857. inOutData[i]=inOutData[length-i-1];
  858. inOutData[length-i-1]=temp;
  859. }
  860. }
  861. bool BitStream::Read(char *varString)
  862. {
  863. return RakString::Deserialize(varString,this);
  864. }
  865. bool BitStream::Read(unsigned char *varString)
  866. {
  867. return RakString::Deserialize((char*) varString,this);
  868. }
  869. void BitStream::WriteAlignedVar8(const char *inByteArray)
  870. {
  871. RakAssert((numberOfBitsUsed&7)==0);
  872. AddBitsAndReallocate(1*8);
  873. data[( numberOfBitsUsed >> 3 ) + 0] = inByteArray[0];
  874. numberOfBitsUsed+=1*8;
  875. }
  876. bool BitStream::ReadAlignedVar8(char *inOutByteArray)
  877. {
  878. RakAssert((readOffset&7)==0);
  879. if ( readOffset + 1*8 > numberOfBitsUsed )
  880. return false;
  881. inOutByteArray[0] = data[( readOffset >> 3 ) + 0];
  882. readOffset+=1*8;
  883. return true;
  884. }
  885. void BitStream::WriteAlignedVar16(const char *inByteArray)
  886. {
  887. RakAssert((numberOfBitsUsed&7)==0);
  888. AddBitsAndReallocate(2*8);
  889. #ifndef __BITSTREAM_NATIVE_END
  890. if (DoEndianSwap())
  891. {
  892. data[( numberOfBitsUsed >> 3 ) + 0] = inByteArray[1];
  893. data[( numberOfBitsUsed >> 3 ) + 1] = inByteArray[0];
  894. }
  895. else
  896. #endif
  897. {
  898. data[( numberOfBitsUsed >> 3 ) + 0] = inByteArray[0];
  899. data[( numberOfBitsUsed >> 3 ) + 1] = inByteArray[1];
  900. }
  901. numberOfBitsUsed+=2*8;
  902. }
  903. bool BitStream::ReadAlignedVar16(char *inOutByteArray)
  904. {
  905. RakAssert((readOffset&7)==0);
  906. if ( readOffset + 2*8 > numberOfBitsUsed )
  907. return false;
  908. #ifndef __BITSTREAM_NATIVE_END
  909. if (DoEndianSwap())
  910. {
  911. inOutByteArray[0] = data[( readOffset >> 3 ) + 1];
  912. inOutByteArray[1] = data[( readOffset >> 3 ) + 0];
  913. }
  914. else
  915. #endif
  916. {
  917. inOutByteArray[0] = data[( readOffset >> 3 ) + 0];
  918. inOutByteArray[1] = data[( readOffset >> 3 ) + 1];
  919. }
  920. readOffset+=2*8;
  921. return true;
  922. }
  923. void BitStream::WriteAlignedVar32(const char *inByteArray)
  924. {
  925. RakAssert((numberOfBitsUsed&7)==0);
  926. AddBitsAndReallocate(4*8);
  927. #ifndef __BITSTREAM_NATIVE_END
  928. if (DoEndianSwap())
  929. {
  930. data[( numberOfBitsUsed >> 3 ) + 0] = inByteArray[3];
  931. data[( numberOfBitsUsed >> 3 ) + 1] = inByteArray[2];
  932. data[( numberOfBitsUsed >> 3 ) + 2] = inByteArray[1];
  933. data[( numberOfBitsUsed >> 3 ) + 3] = inByteArray[0];
  934. }
  935. else
  936. #endif
  937. {
  938. data[( numberOfBitsUsed >> 3 ) + 0] = inByteArray[0];
  939. data[( numberOfBitsUsed >> 3 ) + 1] = inByteArray[1];
  940. data[( numberOfBitsUsed >> 3 ) + 2] = inByteArray[2];
  941. data[( numberOfBitsUsed >> 3 ) + 3] = inByteArray[3];
  942. }
  943. numberOfBitsUsed+=4*8;
  944. }
  945. bool BitStream::ReadAlignedVar32(char *inOutByteArray)
  946. {
  947. RakAssert((readOffset&7)==0);
  948. if ( readOffset + 4*8 > numberOfBitsUsed )
  949. return false;
  950. #ifndef __BITSTREAM_NATIVE_END
  951. if (DoEndianSwap())
  952. {
  953. inOutByteArray[0] = data[( readOffset >> 3 ) + 3];
  954. inOutByteArray[1] = data[( readOffset >> 3 ) + 2];
  955. inOutByteArray[2] = data[( readOffset >> 3 ) + 1];
  956. inOutByteArray[3] = data[( readOffset >> 3 ) + 0];
  957. }
  958. else
  959. #endif
  960. {
  961. inOutByteArray[0] = data[( readOffset >> 3 ) + 0];
  962. inOutByteArray[1] = data[( readOffset >> 3 ) + 1];
  963. inOutByteArray[2] = data[( readOffset >> 3 ) + 2];
  964. inOutByteArray[3] = data[( readOffset >> 3 ) + 3];
  965. }
  966. readOffset+=4*8;
  967. return true;
  968. }
  969. bool BitStream::ReadFloat16( float &outFloat, float floatMin, float floatMax )
  970. {
  971. unsigned short percentile;
  972. if (Read(percentile))
  973. {
  974. RakAssert(floatMax>floatMin);
  975. outFloat = floatMin + ((float) percentile / 65535.0f) * (floatMax-floatMin);
  976. if (outFloat<floatMin)
  977. outFloat=floatMin;
  978. else if (outFloat>floatMax)
  979. outFloat=floatMax;
  980. return true;
  981. }
  982. return false;
  983. }
  984. bool BitStream::SerializeFloat16(bool writeToBitstream, float &inOutFloat, float floatMin, float floatMax)
  985. {
  986. if (writeToBitstream)
  987. WriteFloat16(inOutFloat, floatMin, floatMax);
  988. else
  989. return ReadFloat16(inOutFloat, floatMin, floatMax);
  990. return true;
  991. }
  992. void BitStream::WriteFloat16( float inOutFloat, float floatMin, float floatMax )
  993. {
  994. RakAssert(floatMax>floatMin);
  995. if (inOutFloat>floatMax+.001)
  996. {
  997. RakAssert(inOutFloat<=floatMax+.001);
  998. }
  999. if (inOutFloat<floatMin-.001)
  1000. {
  1001. RakAssert(inOutFloat>=floatMin-.001);
  1002. }
  1003. float percentile=65535.0f * (inOutFloat-floatMin)/(floatMax-floatMin);
  1004. if (percentile<0.0)
  1005. percentile=0.0;
  1006. if (percentile>65535.0f)
  1007. percentile=65535.0f;
  1008. Write((unsigned short)percentile);
  1009. }
  1010. #ifdef _MSC_VER
  1011. #pragma warning( pop )
  1012. #endif
  1013. #endif // #if _MSC_VER < 1299
粤ICP备19079148号