dart Builder - expose finished buffer size (#6403)

This commit is contained in:
Ivan Dlugos
2021-01-22 01:06:11 +01:00
committed by GitHub
parent 52e2177069
commit ad3a729f96
2 changed files with 9 additions and 6 deletions

View File

@@ -149,6 +149,9 @@ class Builder {
reset();
}
/// Calculate the finished buffer size (aligned).
int size() => _tail + ((-_tail) % _maxAlign);
/// Add the [field] with the given boolean [value]. The field is not added if
/// the [value] is equal to [def]. Booleans are stored as 8-bit fields with
/// `0` for `false` and `1` for `true`.
@@ -335,8 +338,7 @@ class Builder {
///
/// Most clients should prefer calling [finish].
Uint8List lowFinish() {
int alignedTail = _tail + ((-_tail) % _maxAlign);
return _buf.buffer.asUint8List(_buf.lengthInBytes - alignedTail);
return _buf.buffer.asUint8List(_buf.lengthInBytes - size());
}
/// Finish off the creation of the buffer. The given [offset] is used as the
@@ -346,15 +348,15 @@ class Builder {
/// bytes 4-7 of the file.
Uint8List finish(int offset, [String fileIdentifier]) {
_prepare(max(_sizeofUint32, _maxAlign), fileIdentifier == null ? 1 : 2);
int alignedTail = _tail + ((-_tail) % _maxAlign);
_setUint32AtTail(_buf, alignedTail, alignedTail - offset);
final finishedSize = size();
_setUint32AtTail(_buf, finishedSize, finishedSize - offset);
if (fileIdentifier != null) {
for (int i = 0; i < 4; i++) {
_setUint8AtTail(_buf, alignedTail - _sizeofUint32 - i,
_setUint8AtTail(_buf, finishedSize - _sizeofUint32 - i,
fileIdentifier.codeUnitAt(i));
}
}
return _buf.buffer.asUint8List(_buf.lengthInBytes - alignedTail);
return _buf.buffer.asUint8List(_buf.lengthInBytes - finishedSize);
}
/// Writes a Float64 to the tail of the buffer after preparing space for it.

View File

@@ -265,6 +265,7 @@ class BuilderTest {
builder.addInt32(1, 20, 10);
int offset = builder.endTable();
byteList = builder.finish(offset);
expect(builder.size(), byteList.length);
}
// read and verify
BufferContext buffer = new BufferContext.fromBytes(byteList);