writePadding method
Writes padding bits to ensure proper byte alignment and returns the length of the written padding.
Since data is flushed in blocks of 8 bits (bytes), if the internal buffer's size is not a multiple of 8, padding bits are needed to ensure that the remaining bits are properly flushed.
The padding format consists of a 1
bit (the head) followed by an optional
sequence of 0
bits until a full byte is completed.
Example:
-
If the internal unflushed buffer contains 5 bits (e.g.,
00110
) and you call writePadding, it will add a1
bit and 20
bits (100
) to the buffer, completing the byte to flush (00110100
). This ensures that the unflushed bits can be written to bytesBuffer and later be read, with knowledge of how to remove the padding. -
If there are no unflushed bits, a full padding byte (
10000000
) is written to bytesBuffer.
See isAtPadding.
Implementation
int writePadding() {
if (_bitsBufferLength == 0) {
var padding = (1 << 7);
_bytesBuffer.writeByte(padding);
return 8;
} else {
final gapBits = 8 - _bitsBufferLength;
assert(gapBits > 0);
var padding = 1 << (gapBits - 1);
return writeBits(padding, gapBits);
}
}