COMMON: Optimize BitStream::getBits

This commit is contained in:
Willem Jan Palenstijn 2017-07-24 23:59:35 +02:00
parent 47539e1939
commit 4278cff7f0

View file

@ -29,6 +29,7 @@
#include "common/textconsole.h" #include "common/textconsole.h"
#include "common/stream.h" #include "common/stream.h"
#include "common/types.h" #include "common/types.h"
#include "common/util.h"
namespace Common { namespace Common {
@ -115,14 +116,10 @@ public:
delete _stream; delete _stream;
} }
/** Read a bit from the bit stream. */ private:
uint32 getBit() { uint32 getBit_internal() {
// Check if we need the next value
if (_inValue == 0)
readValue();
// Get the current bit // Get the current bit
int b = 0; uint32 b = 0;
if (isMSB2LSB) if (isMSB2LSB)
b = ((_value & 0x80000000) == 0) ? 0 : 1; b = ((_value & 0x80000000) == 0) ? 0 : 1;
else else
@ -134,6 +131,18 @@ public:
else else
_value >>= 1; _value >>= 1;
return b;
}
public:
/** Read a bit from the bit stream. */
uint32 getBit() {
// Check if we need the next value
if (_inValue == 0)
readValue();
uint32 b = getBit_internal();
// Increase the position within the current value // Increase the position within the current value
_inValue = (_inValue + 1) % valueBits; _inValue = (_inValue + 1) % valueBits;
_pos++; _pos++;
@ -161,16 +170,42 @@ public:
// Read the number of bits // Read the number of bits
uint32 v = 0; uint32 v = 0;
if (isMSB2LSB) { uint8 nOrig = n;
while (n-- > 0) if (_inValue) {
v = (v << 1) | getBit(); int count = MIN((int)n, valueBits - _inValue);
} else { for (int i = 0; i < count; ++i) {
for (uint32 i = 0; i < n; i++) if (isMSB2LSB) {
v = (v >> 1) | (((uint32) getBit()) << 31); v = (v << 1) | getBit_internal();
} else {
v = (v >> 1) | (getBit_internal() << 31);
}
}
v >>= (32 - n); n -= count;
} }
while (n > 0) {
// NB: readValue doesn't care that _inValue is incorrect here
readValue();
int count = MIN((int)n, valueBits);
for (int i = 0; i < count; ++i) {
if (isMSB2LSB) {
v = (v << 1) | getBit_internal();
} else {
v = (v >> 1) | (getBit_internal() << 31);
}
}
n -= count;
}
_inValue = (_inValue + nOrig) % valueBits;
_pos += nOrig;
if (!isMSB2LSB)
v >>= (32 - nOrig);
return v; return v;
} }