writeBits method

int writeBits(
  1. int bits,
  2. int bitsLength
)

Writes the specified number of bits from the given integer value into the internal bytesBuffer.

Parameters:

  • bits: The integer containing the bits to be written.
  • bitsLength: The number of bits to write from the bits integer.

Returns the number of bits successfully written into the buffer.

Note that a byte is written to the internal bytesBuffer for every 8 accumulated bits. See writeBit and unflushedBitsLength.

Implementation

int writeBits(int bits, int bitsLength) {
  if (bitsLength == 8 && _bitsBufferLength == 0) {
    _bytesBuffer.writeByte(bits & 0xFF);
    return 8;
  }

  var bitsWrote = 0;

  while (bitsLength > 0) {
    var bufferRemaining = 8 - _bitsBufferLength;
    assert(bufferRemaining > 0);

    var bitsLng = bitsLength;
    if (bitsLng > bufferRemaining) {
      bitsLng = bufferRemaining;
    }
    assert(bitsLng >= 1 && bitsLng <= 8);

    var bitsExtra = bitsLength - bitsLng;

    var bMask = (1 << bitsLng) - 1;
    assert(bMask > 0);
    var bMask2 = (1 << bitsExtra) - 1;

    _bitsBuffer = (_bitsBuffer << bitsLng) | ((bits >> bitsExtra) & bMask);
    _bitsBufferLength += bitsLng;
    bits = bits & bMask2;

    bitsWrote += bitsLng;
    bitsLength -= bitsLng;

    assert(_bitsBufferLength >= 1 && _bitsBufferLength <= 8);

    if (_bitsBufferLength == 8) {
      _bytesBuffer.writeByte(_bitsBuffer);
      _bitsBuffer = 0;
      _bitsBufferLength = 0;
    }
  }

  return bitsWrote;
}