writeTo method
Serializes everything written to this writer so far to buffer
, starting
from offset
in buffer
. Returns true
on success.
Implementation
bool writeTo(Uint8List buffer, [int offset = 0]) {
if (buffer.length - offset < _bytesTotal) {
return false;
}
// Move the current output chunk into _outputChunks and commit the current
// splice for uniformity.
_commitChunk(false);
_commitSplice();
var outPos = offset; // Output position in the buffer.
var chunkIndex = 0, chunkPos = 0; // Position within _outputChunks.
for (var i = 0; i < _splices.length; i++) {
final action = _splices[i];
if (action is int) {
if (action <= 0) {
// action is a positive varint to be emitted into the output buffer.
var v = 0 - action; // Note: 0 - action to avoid -0.0 in JS.
while (v >= 0x80) {
buffer[outPos++] = 0x80 | (v & 0x7f);
v >>= 7;
}
buffer[outPos++] = v;
} else {
// action is an amount of bytes to copy from _outputChunks into the
// buffer.
var bytesToCopy = action;
while (bytesToCopy > 0) {
final Uint8List chunk = _outputChunks[chunkIndex];
final int bytesInChunk = _outputChunks[chunkIndex + 1];
// Copy at most bytesToCopy bytes from the current chunk.
final leftInChunk = bytesInChunk - chunkPos;
final bytesToCopyFromChunk =
leftInChunk > bytesToCopy ? bytesToCopy : leftInChunk;
final endPos = chunkPos + bytesToCopyFromChunk;
while (chunkPos < endPos) {
buffer[outPos++] = chunk[chunkPos++];
}
bytesToCopy -= bytesToCopyFromChunk;
// Move to the next chunk if the current one is exhausted.
if (chunkPos == bytesInChunk) {
chunkIndex += 2;
chunkPos = 0;
}
}
}
} else {
// action is a TypedData containing bytes to emit into the output
// buffer.
outPos = _copyInto(buffer, outPos, action);
}
}
return true;
}