From ad3a729f967d3651f80cc89a9315eff964f865d8 Mon Sep 17 00:00:00 2001 From: Ivan Dlugos <6349682+vaind@users.noreply.github.com> Date: Fri, 22 Jan 2021 01:06:11 +0100 Subject: [PATCH] dart Builder - expose finished buffer size (#6403) --- dart/lib/flat_buffers.dart | 14 ++++++++------ dart/test/flat_buffers_test.dart | 1 + 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/dart/lib/flat_buffers.dart b/dart/lib/flat_buffers.dart index 99fd6a2d5..c77a835c4 100644 --- a/dart/lib/flat_buffers.dart +++ b/dart/lib/flat_buffers.dart @@ -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. diff --git a/dart/test/flat_buffers_test.dart b/dart/test/flat_buffers_test.dart index 3f854d873..999a837a8 100644 --- a/dart/test/flat_buffers_test.dart +++ b/dart/test/flat_buffers_test.dart @@ -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);