Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

809 lines
21 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //
  7. //=============================================================================//
  8. // NOTE: bf_read is guaranteed to return zeros if it overflows.
  9. #ifndef BITBUF_H
  10. #define BITBUF_H
  11. #ifdef _WIN32
  12. #pragma once
  13. #endif
  14. #include "mathlib/mathlib.h"
  15. #include "mathlib/vector.h"
  16. #include "basetypes.h"
  17. #include "tier0/dbg.h"
  18. #if _DEBUG
  19. #define BITBUF_INLINE inline
  20. #else
  21. #define BITBUF_INLINE FORCEINLINE
  22. #endif
  23. //-----------------------------------------------------------------------------
  24. // Forward declarations.
  25. //-----------------------------------------------------------------------------
  26. class Vector;
  27. class QAngle;
  28. //-----------------------------------------------------------------------------
  29. // You can define a handler function that will be called in case of
  30. // out-of-range values and overruns here.
  31. //
  32. // NOTE: the handler is only called in debug mode.
  33. //
  34. // Call SetBitBufErrorHandler to install a handler.
  35. //-----------------------------------------------------------------------------
  36. typedef enum
  37. {
  38. BITBUFERROR_VALUE_OUT_OF_RANGE=0, // Tried to write a value with too few bits.
  39. BITBUFERROR_BUFFER_OVERRUN, // Was about to overrun a buffer.
  40. BITBUFERROR_NUM_ERRORS
  41. } BitBufErrorType;
  42. typedef void (*BitBufErrorHandler)( BitBufErrorType errorType, const char *pDebugName );
  43. #if defined( _DEBUG )
  44. extern void InternalBitBufErrorHandler( BitBufErrorType errorType, const char *pDebugName );
  45. #define CallErrorHandler( errorType, pDebugName ) InternalBitBufErrorHandler( errorType, pDebugName );
  46. #else
  47. #define CallErrorHandler( errorType, pDebugName )
  48. #endif
  49. // Use this to install the error handler. Call with NULL to uninstall your error handler.
  50. void SetBitBufErrorHandler( BitBufErrorHandler fn );
  51. //-----------------------------------------------------------------------------
  52. // Helpers.
  53. //-----------------------------------------------------------------------------
  54. inline int BitByte( int bits )
  55. {
  56. // return PAD_NUMBER( bits, 8 ) >> 3;
  57. return (bits + 7) >> 3;
  58. }
  59. //-----------------------------------------------------------------------------
  60. // namespaced helpers
  61. //-----------------------------------------------------------------------------
  62. namespace bitbuf
  63. {
  64. // ZigZag Transform: Encodes signed integers so that they can be
  65. // effectively used with varint encoding.
  66. //
  67. // varint operates on unsigned integers, encoding smaller numbers into
  68. // fewer bytes. If you try to use it on a signed integer, it will treat
  69. // this number as a very large unsigned integer, which means that even
  70. // small signed numbers like -1 will take the maximum number of bytes
  71. // (10) to encode. ZigZagEncode() maps signed integers to unsigned
  72. // in such a way that those with a small absolute value will have smaller
  73. // encoded values, making them appropriate for encoding using varint.
  74. //
  75. // int32 -> uint32
  76. // -------------------------
  77. // 0 -> 0
  78. // -1 -> 1
  79. // 1 -> 2
  80. // -2 -> 3
  81. // ... -> ...
  82. // 2147483647 -> 4294967294
  83. // -2147483648 -> 4294967295
  84. //
  85. // >> encode >>
  86. // << decode <<
  87. inline uint32 ZigZagEncode32(int32 n)
  88. {
  89. // Note: the right-shift must be arithmetic
  90. return(n << 1) ^ (n >> 31);
  91. }
  92. inline int32 ZigZagDecode32(uint32 n)
  93. {
  94. return(n >> 1) ^ -static_cast<int32>(n & 1);
  95. }
  96. inline uint64 ZigZagEncode64(int64 n)
  97. {
  98. // Note: the right-shift must be arithmetic
  99. return(n << 1) ^ (n >> 63);
  100. }
  101. inline int64 ZigZagDecode64(uint64 n)
  102. {
  103. return(n >> 1) ^ -static_cast<int64>(n & 1);
  104. }
  105. const int kMaxVarintBytes = 10;
  106. const int kMaxVarint32Bytes = 5;
  107. }
  108. //-----------------------------------------------------------------------------
  109. // Used for serialization
  110. //-----------------------------------------------------------------------------
  111. class bf_write
  112. {
  113. public:
  114. bf_write();
  115. // nMaxBits can be used as the number of bits in the buffer.
  116. // It must be <= nBytes*8. If you leave it at -1, then it's set to nBytes * 8.
  117. bf_write( void *pData, int nBytes, int nMaxBits = -1 );
  118. bf_write( const char *pDebugName, void *pData, int nBytes, int nMaxBits = -1 );
  119. // Start writing to the specified buffer.
  120. // nMaxBits can be used as the number of bits in the buffer.
  121. // It must be <= nBytes*8. If you leave it at -1, then it's set to nBytes * 8.
  122. void StartWriting( void *pData, int nBytes, int iStartBit = 0, int nMaxBits = -1 );
  123. // Restart buffer writing.
  124. void Reset();
  125. // Get the base pointer.
  126. unsigned char* GetBasePointer() { return (unsigned char*) m_pData; }
  127. // Enable or disable assertion on overflow. 99% of the time, it's a bug that we need to catch,
  128. // but there may be the occasional buffer that is allowed to overflow gracefully.
  129. void SetAssertOnOverflow( bool bAssert );
  130. // This can be set to assign a name that gets output if the buffer overflows.
  131. const char* GetDebugName();
  132. void SetDebugName( const char *pDebugName );
  133. // Seek to a specific position.
  134. public:
  135. void SeekToBit( int bitPos );
  136. // Bit functions.
  137. public:
  138. void WriteOneBit(int nValue);
  139. void WriteOneBitNoCheck(int nValue);
  140. void WriteOneBitAt( int iBit, int nValue );
  141. // Write signed or unsigned. Range is only checked in debug.
  142. void WriteUBitLong( unsigned int data, int numbits, bool bCheckRange=true );
  143. void WriteSBitLong( int data, int numbits );
  144. // Tell it whether or not the data is unsigned. If it's signed,
  145. // cast to unsigned before passing in (it will cast back inside).
  146. void WriteBitLong(unsigned int data, int numbits, bool bSigned);
  147. // Write a list of bits in.
  148. bool WriteBits(const void *pIn, int nBits);
  149. // writes an unsigned integer with variable bit length
  150. void WriteUBitVar( unsigned int data );
  151. // writes a varint encoded integer
  152. void WriteVarInt32( uint32 data );
  153. void WriteVarInt64( uint64 data );
  154. void WriteSignedVarInt32( int32 data );
  155. void WriteSignedVarInt64( int64 data );
  156. int ByteSizeVarInt32( uint32 data );
  157. int ByteSizeVarInt64( uint64 data );
  158. int ByteSizeSignedVarInt32( int32 data );
  159. int ByteSizeSignedVarInt64( int64 data );
  160. // Copy the bits straight out of pIn. This seeks pIn forward by nBits.
  161. // Returns an error if this buffer or the read buffer overflows.
  162. bool WriteBitsFromBuffer( class bf_read *pIn, int nBits );
  163. void WriteBitAngle( float fAngle, int numbits );
  164. void WriteBitCoord (const float f);
  165. void WriteBitCoordMP( const float f, bool bIntegral, bool bLowPrecision );
  166. void WriteBitFloat(float val);
  167. void WriteBitVec3Coord( const Vector& fa );
  168. void WriteBitNormal( float f );
  169. void WriteBitVec3Normal( const Vector& fa );
  170. void WriteBitAngles( const QAngle& fa );
  171. // Byte functions.
  172. public:
  173. void WriteChar(int val);
  174. void WriteByte(int val);
  175. void WriteShort(int val);
  176. void WriteWord(int val);
  177. void WriteLong(long val);
  178. void WriteLongLong(int64 val);
  179. void WriteFloat(float val);
  180. bool WriteBytes( const void *pBuf, int nBytes );
  181. // Returns false if it overflows the buffer.
  182. bool WriteString(const char *pStr);
  183. // Status.
  184. public:
  185. // How many bytes are filled in?
  186. int GetNumBytesWritten() const;
  187. int GetNumBitsWritten() const;
  188. int GetMaxNumBits();
  189. int GetNumBitsLeft();
  190. int GetNumBytesLeft();
  191. unsigned char* GetData();
  192. const unsigned char* GetData() const;
  193. // Has the buffer overflowed?
  194. bool CheckForOverflow(int nBits);
  195. inline bool IsOverflowed() const {return m_bOverflow;}
  196. void SetOverflowFlag();
  197. public:
  198. // The current buffer.
  199. unsigned long* RESTRICT m_pData;
  200. int m_nDataBytes;
  201. int m_nDataBits;
  202. // Where we are in the buffer.
  203. int m_iCurBit;
  204. private:
  205. // Errors?
  206. bool m_bOverflow;
  207. bool m_bAssertOnOverflow;
  208. const char *m_pDebugName;
  209. };
  210. //-----------------------------------------------------------------------------
  211. // Inlined methods
  212. //-----------------------------------------------------------------------------
  213. // How many bytes are filled in?
  214. inline int bf_write::GetNumBytesWritten() const
  215. {
  216. return BitByte(m_iCurBit);
  217. }
  218. inline int bf_write::GetNumBitsWritten() const
  219. {
  220. return m_iCurBit;
  221. }
  222. inline int bf_write::GetMaxNumBits()
  223. {
  224. return m_nDataBits;
  225. }
  226. inline int bf_write::GetNumBitsLeft()
  227. {
  228. return m_nDataBits - m_iCurBit;
  229. }
  230. inline int bf_write::GetNumBytesLeft()
  231. {
  232. return GetNumBitsLeft() >> 3;
  233. }
  234. inline unsigned char* bf_write::GetData()
  235. {
  236. return (unsigned char*) m_pData;
  237. }
  238. inline const unsigned char* bf_write::GetData() const
  239. {
  240. return (unsigned char*) m_pData;
  241. }
  242. BITBUF_INLINE bool bf_write::CheckForOverflow(int nBits)
  243. {
  244. if ( m_iCurBit + nBits > m_nDataBits )
  245. {
  246. SetOverflowFlag();
  247. CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, GetDebugName() );
  248. }
  249. return m_bOverflow;
  250. }
  251. BITBUF_INLINE void bf_write::SetOverflowFlag()
  252. {
  253. #ifdef DBGFLAG_ASSERT
  254. if ( m_bAssertOnOverflow )
  255. {
  256. Assert( false );
  257. }
  258. #endif
  259. m_bOverflow = true;
  260. }
  261. BITBUF_INLINE void bf_write::WriteOneBitNoCheck(int nValue)
  262. {
  263. #if __i386__
  264. if(nValue)
  265. m_pData[m_iCurBit >> 5] |= 1u << (m_iCurBit & 31);
  266. else
  267. m_pData[m_iCurBit >> 5] &= ~(1u << (m_iCurBit & 31));
  268. #else
  269. extern unsigned long g_LittleBits[32];
  270. if(nValue)
  271. m_pData[m_iCurBit >> 5] |= g_LittleBits[m_iCurBit & 31];
  272. else
  273. m_pData[m_iCurBit >> 5] &= ~g_LittleBits[m_iCurBit & 31];
  274. #endif
  275. ++m_iCurBit;
  276. }
  277. inline void bf_write::WriteOneBit(int nValue)
  278. {
  279. if( m_iCurBit >= m_nDataBits )
  280. {
  281. SetOverflowFlag();
  282. CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, GetDebugName() );
  283. return;
  284. }
  285. WriteOneBitNoCheck( nValue );
  286. }
  287. inline void bf_write::WriteOneBitAt( int iBit, int nValue )
  288. {
  289. if( iBit >= m_nDataBits )
  290. {
  291. SetOverflowFlag();
  292. CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, GetDebugName() );
  293. return;
  294. }
  295. #if __i386__
  296. if(nValue)
  297. m_pData[iBit >> 5] |= 1u << (iBit & 31);
  298. else
  299. m_pData[iBit >> 5] &= ~(1u << (iBit & 31));
  300. #else
  301. extern unsigned long g_LittleBits[32];
  302. if(nValue)
  303. m_pData[iBit >> 5] |= g_LittleBits[iBit & 31];
  304. else
  305. m_pData[iBit >> 5] &= ~g_LittleBits[iBit & 31];
  306. #endif
  307. }
  308. BITBUF_INLINE void bf_write::WriteUBitLong( unsigned int curData, int numbits, bool bCheckRange ) RESTRICT
  309. {
  310. #ifdef _DEBUG
  311. // Make sure it doesn't overflow.
  312. if ( bCheckRange && numbits < 32 )
  313. {
  314. if ( curData >= (unsigned long)(1 << numbits) )
  315. {
  316. CallErrorHandler( BITBUFERROR_VALUE_OUT_OF_RANGE, GetDebugName() );
  317. }
  318. }
  319. Assert( numbits >= 0 && numbits <= 32 );
  320. #endif
  321. if ( GetNumBitsLeft() < numbits )
  322. {
  323. m_iCurBit = m_nDataBits;
  324. SetOverflowFlag();
  325. CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, GetDebugName() );
  326. return;
  327. }
  328. int iCurBitMasked = m_iCurBit & 31;
  329. int iDWord = m_iCurBit >> 5;
  330. m_iCurBit += numbits;
  331. // Mask in a dword.
  332. Assert( (iDWord*4 + sizeof(long)) <= (unsigned int)m_nDataBytes );
  333. unsigned long * RESTRICT pOut = &m_pData[iDWord];
  334. // Rotate data into dword alignment
  335. curData = (curData << iCurBitMasked) | (curData >> (32 - iCurBitMasked));
  336. // Calculate bitmasks for first and second word
  337. unsigned int temp = 1 << (numbits-1);
  338. unsigned int mask1 = (temp*2-1) << iCurBitMasked;
  339. unsigned int mask2 = (temp-1) >> (31 - iCurBitMasked);
  340. // Only look beyond current word if necessary (avoid access violation)
  341. int i = mask2 & 1;
  342. unsigned long dword1 = LoadLittleDWord( pOut, 0 );
  343. unsigned long dword2 = LoadLittleDWord( pOut, i );
  344. // Drop bits into place
  345. dword1 ^= ( mask1 & ( curData ^ dword1 ) );
  346. dword2 ^= ( mask2 & ( curData ^ dword2 ) );
  347. // Note reversed order of writes so that dword1 wins if mask2 == 0 && i == 0
  348. StoreLittleDWord( pOut, i, dword2 );
  349. StoreLittleDWord( pOut, 0, dword1 );
  350. }
  351. // writes an unsigned integer with variable bit length
  352. BITBUF_INLINE void bf_write::WriteUBitVar( unsigned int data )
  353. {
  354. /* Reference:
  355. if ( data < 0x10u )
  356. WriteUBitLong( 0, 2 ), WriteUBitLong( data, 4 );
  357. else if ( data < 0x100u )
  358. WriteUBitLong( 1, 2 ), WriteUBitLong( data, 8 );
  359. else if ( data < 0x1000u )
  360. WriteUBitLong( 2, 2 ), WriteUBitLong( data, 12 );
  361. else
  362. WriteUBitLong( 3, 2 ), WriteUBitLong( data, 32 );
  363. */
  364. // a < b ? -1 : 0 translates into a CMP, SBB instruction pair
  365. // with no flow control. should also be branchless on consoles.
  366. int n = (data < 0x10u ? -1 : 0) + (data < 0x100u ? -1 : 0) + (data < 0x1000u ? -1 : 0);
  367. WriteUBitLong( data*4 + n + 3, 6 + n*4 + 12 );
  368. if ( data >= 0x1000u )
  369. {
  370. WriteUBitLong( data >> 16, 16 );
  371. }
  372. }
  373. // write raw IEEE float bits in little endian form
  374. BITBUF_INLINE void bf_write::WriteBitFloat(float val)
  375. {
  376. long intVal;
  377. Assert(sizeof(long) == sizeof(float));
  378. Assert(sizeof(float) == 4);
  379. intVal = *((long*)&val);
  380. WriteUBitLong( intVal, 32 );
  381. }
  382. //-----------------------------------------------------------------------------
  383. // This is useful if you just want a buffer to write into on the stack.
  384. //-----------------------------------------------------------------------------
  385. template<int SIZE>
  386. class old_bf_write_static : public bf_write
  387. {
  388. public:
  389. inline old_bf_write_static() : bf_write(m_StaticData, SIZE) {}
  390. char m_StaticData[SIZE];
  391. };
  392. //-----------------------------------------------------------------------------
  393. // Used for unserialization
  394. //-----------------------------------------------------------------------------
  395. class bf_read
  396. {
  397. public:
  398. bf_read();
  399. // nMaxBits can be used as the number of bits in the buffer.
  400. // It must be <= nBytes*8. If you leave it at -1, then it's set to nBytes * 8.
  401. bf_read( const void *pData, int nBytes, int nBits = -1 );
  402. bf_read( const char *pDebugName, const void *pData, int nBytes, int nBits = -1 );
  403. // Start reading from the specified buffer.
  404. // pData's start address must be dword-aligned.
  405. // nMaxBits can be used as the number of bits in the buffer.
  406. // It must be <= nBytes*8. If you leave it at -1, then it's set to nBytes * 8.
  407. void StartReading( const void *pData, int nBytes, int iStartBit = 0, int nBits = -1 );
  408. // Restart buffer reading.
  409. void Reset();
  410. // Enable or disable assertion on overflow. 99% of the time, it's a bug that we need to catch,
  411. // but there may be the occasional buffer that is allowed to overflow gracefully.
  412. void SetAssertOnOverflow( bool bAssert );
  413. // This can be set to assign a name that gets output if the buffer overflows.
  414. const char* GetDebugName() const { return m_pDebugName; }
  415. void SetDebugName( const char *pName );
  416. void ExciseBits( int startbit, int bitstoremove );
  417. // Bit functions.
  418. public:
  419. // Returns 0 or 1.
  420. int ReadOneBit();
  421. protected:
  422. unsigned int CheckReadUBitLong(int numbits); // For debugging.
  423. int ReadOneBitNoCheck(); // Faster version, doesn't check bounds and is inlined.
  424. bool CheckForOverflow(int nBits);
  425. public:
  426. // Get the base pointer.
  427. const unsigned char* GetBasePointer() { return m_pData; }
  428. BITBUF_INLINE int TotalBytesAvailable( void ) const
  429. {
  430. return m_nDataBytes;
  431. }
  432. // Read a list of bits in.
  433. void ReadBits(void *pOut, int nBits);
  434. // Read a list of bits in, but don't overrun the destination buffer.
  435. // Returns the number of bits read into the buffer. The remaining
  436. // bits are skipped over.
  437. int ReadBitsClamped_ptr(void *pOut, size_t outSizeBytes, size_t nBits);
  438. // Helper 'safe' template function that infers the size of the destination
  439. // array. This version of the function should be preferred.
  440. // Usage: char databuffer[100];
  441. // ReadBitsClamped( dataBuffer, msg->m_nLength );
  442. template <typename T, size_t N>
  443. int ReadBitsClamped( T (&pOut)[N], size_t nBits )
  444. {
  445. return ReadBitsClamped_ptr( pOut, N * sizeof(T), nBits );
  446. }
  447. float ReadBitAngle( int numbits );
  448. unsigned int ReadUBitLong( int numbits ) RESTRICT;
  449. unsigned int ReadUBitLongNoInline( int numbits ) RESTRICT;
  450. unsigned int PeekUBitLong( int numbits );
  451. int ReadSBitLong( int numbits );
  452. // reads an unsigned integer with variable bit length
  453. unsigned int ReadUBitVar();
  454. unsigned int ReadUBitVarInternal( int encodingType );
  455. // reads a varint encoded integer
  456. uint32 ReadVarInt32();
  457. uint64 ReadVarInt64();
  458. int32 ReadSignedVarInt32();
  459. int64 ReadSignedVarInt64();
  460. // You can read signed or unsigned data with this, just cast to
  461. // a signed int if necessary.
  462. unsigned int ReadBitLong(int numbits, bool bSigned);
  463. float ReadBitCoord();
  464. float ReadBitCoordMP( bool bIntegral, bool bLowPrecision );
  465. float ReadBitFloat();
  466. float ReadBitNormal();
  467. void ReadBitVec3Coord( Vector& fa );
  468. void ReadBitVec3Normal( Vector& fa );
  469. void ReadBitAngles( QAngle& fa );
  470. // Faster for comparisons but do not fully decode float values
  471. unsigned int ReadBitCoordBits();
  472. unsigned int ReadBitCoordMPBits( bool bIntegral, bool bLowPrecision );
  473. // Byte functions (these still read data in bit-by-bit).
  474. public:
  475. BITBUF_INLINE int ReadChar() { return (char)ReadUBitLong(8); }
  476. BITBUF_INLINE int ReadByte() { return ReadUBitLong(8); }
  477. BITBUF_INLINE int ReadShort() { return (short)ReadUBitLong(16); }
  478. BITBUF_INLINE int ReadWord() { return ReadUBitLong(16); }
  479. BITBUF_INLINE long ReadLong() { return ReadUBitLong(32); }
  480. int64 ReadLongLong();
  481. float ReadFloat();
  482. bool ReadBytes(void *pOut, int nBytes);
  483. // Returns false if bufLen isn't large enough to hold the
  484. // string in the buffer.
  485. //
  486. // Always reads to the end of the string (so you can read the
  487. // next piece of data waiting).
  488. //
  489. // If bLine is true, it stops when it reaches a '\n' or a null-terminator.
  490. //
  491. // pStr is always null-terminated (unless bufLen is 0).
  492. //
  493. // pOutNumChars is set to the number of characters left in pStr when the routine is
  494. // complete (this will never exceed bufLen-1).
  495. //
  496. bool ReadString( char *pStr, int bufLen, bool bLine=false, int *pOutNumChars=NULL );
  497. // Reads a string and allocates memory for it. If the string in the buffer
  498. // is > 2048 bytes, then pOverflow is set to true (if it's not NULL).
  499. char* ReadAndAllocateString( bool *pOverflow = 0 );
  500. // Returns nonzero if any bits differ
  501. int CompareBits( bf_read * RESTRICT other, int bits ) RESTRICT;
  502. int CompareBitsAt( int offset, bf_read * RESTRICT other, int otherOffset, int bits ) RESTRICT;
  503. // Status.
  504. public:
  505. int GetNumBytesLeft();
  506. int GetNumBytesRead();
  507. int GetNumBitsLeft();
  508. int GetNumBitsRead() const;
  509. // Has the buffer overflowed?
  510. inline bool IsOverflowed() const {return m_bOverflow;}
  511. inline bool Seek(int iBit); // Seek to a specific bit.
  512. inline bool SeekRelative(int iBitDelta); // Seek to an offset from the current position.
  513. // Called when the buffer is overflowed.
  514. void SetOverflowFlag();
  515. public:
  516. // The current buffer.
  517. const unsigned char* RESTRICT m_pData;
  518. int m_nDataBytes;
  519. int m_nDataBits;
  520. // Where we are in the buffer.
  521. int m_iCurBit;
  522. private:
  523. // Errors?
  524. bool m_bOverflow;
  525. // For debugging..
  526. bool m_bAssertOnOverflow;
  527. const char *m_pDebugName;
  528. };
  529. //-----------------------------------------------------------------------------
  530. // Inlines.
  531. //-----------------------------------------------------------------------------
  532. inline int bf_read::GetNumBytesRead()
  533. {
  534. return BitByte(m_iCurBit);
  535. }
  536. inline int bf_read::GetNumBitsLeft()
  537. {
  538. return m_nDataBits - m_iCurBit;
  539. }
  540. inline int bf_read::GetNumBytesLeft()
  541. {
  542. return GetNumBitsLeft() >> 3;
  543. }
  544. inline int bf_read::GetNumBitsRead() const
  545. {
  546. return m_iCurBit;
  547. }
  548. inline bool bf_read::Seek(int iBit)
  549. {
  550. if(iBit < 0 || iBit > m_nDataBits)
  551. {
  552. SetOverflowFlag();
  553. m_iCurBit = m_nDataBits;
  554. return false;
  555. }
  556. else
  557. {
  558. m_iCurBit = iBit;
  559. return true;
  560. }
  561. }
  562. // Seek to an offset from the current position.
  563. inline bool bf_read::SeekRelative(int iBitDelta)
  564. {
  565. return Seek(m_iCurBit+iBitDelta);
  566. }
  567. inline bool bf_read::CheckForOverflow(int nBits)
  568. {
  569. if( m_iCurBit + nBits > m_nDataBits )
  570. {
  571. SetOverflowFlag();
  572. CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, GetDebugName() );
  573. }
  574. return m_bOverflow;
  575. }
  576. inline int bf_read::ReadOneBitNoCheck()
  577. {
  578. #if VALVE_LITTLE_ENDIAN
  579. unsigned int value = ((unsigned long * RESTRICT)m_pData)[m_iCurBit >> 5] >> (m_iCurBit & 31);
  580. #else
  581. unsigned char value = m_pData[m_iCurBit >> 3] >> (m_iCurBit & 7);
  582. #endif
  583. ++m_iCurBit;
  584. return value & 1;
  585. }
  586. inline int bf_read::ReadOneBit()
  587. {
  588. if( GetNumBitsLeft() <= 0 )
  589. {
  590. SetOverflowFlag();
  591. CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, GetDebugName() );
  592. return 0;
  593. }
  594. return ReadOneBitNoCheck();
  595. }
  596. inline float bf_read::ReadBitFloat()
  597. {
  598. union { uint32 u; float f; } c = { ReadUBitLong(32) };
  599. return c.f;
  600. }
  601. BITBUF_INLINE unsigned int bf_read::ReadUBitVar()
  602. {
  603. // six bits: low 2 bits for encoding + first 4 bits of value
  604. unsigned int sixbits = ReadUBitLong(6);
  605. unsigned int encoding = sixbits & 3;
  606. if ( encoding )
  607. {
  608. // this function will seek back four bits and read the full value
  609. return ReadUBitVarInternal( encoding );
  610. }
  611. return sixbits >> 2;
  612. }
  613. BITBUF_INLINE unsigned int bf_read::ReadUBitLong( int numbits ) RESTRICT
  614. {
  615. Assert( numbits > 0 && numbits <= 32 );
  616. if ( GetNumBitsLeft() < numbits )
  617. {
  618. m_iCurBit = m_nDataBits;
  619. SetOverflowFlag();
  620. CallErrorHandler( BITBUFERROR_BUFFER_OVERRUN, GetDebugName() );
  621. return 0;
  622. }
  623. unsigned int iStartBit = m_iCurBit & 31u;
  624. int iLastBit = m_iCurBit + numbits - 1;
  625. unsigned int iWordOffset1 = m_iCurBit >> 5;
  626. unsigned int iWordOffset2 = iLastBit >> 5;
  627. m_iCurBit += numbits;
  628. #if __i386__
  629. unsigned int bitmask = (2 << (numbits-1)) - 1;
  630. #else
  631. extern unsigned long g_ExtraMasks[33];
  632. unsigned int bitmask = g_ExtraMasks[numbits];
  633. #endif
  634. unsigned int dw1 = LoadLittleDWord( (unsigned long* RESTRICT)m_pData, iWordOffset1 ) >> iStartBit;
  635. unsigned int dw2 = LoadLittleDWord( (unsigned long* RESTRICT)m_pData, iWordOffset2 ) << (32 - iStartBit);
  636. return (dw1 | dw2) & bitmask;
  637. }
  638. BITBUF_INLINE int bf_read::CompareBits( bf_read * RESTRICT other, int numbits ) RESTRICT
  639. {
  640. return (ReadUBitLong(numbits) != other->ReadUBitLong(numbits));
  641. }
  642. #endif