Skip to content

Commit 69179ea

Browse files
okmatijacopybara-github
authored andcommitted
Internal change.
PiperOrigin-RevId: 837829087 Change-Id: I110f2f9d1dff2aff8bcad7ac22ea8ed82323185f
1 parent 7caa3d6 commit 69179ea

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

wasm/unpack.h

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,21 +52,33 @@ class WasmBuffer {
5252
public:
5353
// Creates a buffer with the given element count
5454
explicit WasmBuffer(int element_count = 0) {
55-
bytes_.resize(element_count * sizeof(T));
55+
Resize(element_count);
5656
}
5757

5858
// Creates a buffer by copying data from a (typed) array
5959
static WasmBuffer<T> FromArray(const emscripten::val& array) {
6060
return WasmBuffer<T>(array);
6161
}
6262

63+
// Resizes the buffer to the given element count.
64+
// If element count is zero the memory is released.
65+
void Resize(int element_count) {
66+
if (element_count == 0) {
67+
std::vector<std::byte> empty;
68+
bytes_.swap(empty);
69+
} else {
70+
bytes_.resize(element_count * sizeof(T));
71+
}
72+
}
73+
6374
// Returns the pointer to the data in the buffer
6475
uintptr_t GetPointer() { return reinterpret_cast<uintptr_t>(bytes_.data()); }
6576

6677
// Returns the number of elements in the buffer
6778
int GetElementCount() { return bytes_.size() / sizeof(T); }
6879

69-
// Returns a TypedArray view of the buffer
80+
// Returns a TypedArray view of the buffer.
81+
// Do not cache this value, bytes_.data() is invalidated on Resize!
7082
emscripten::val GetView() {
7183
return emscripten::val(emscripten::typed_memory_view(
7284
bytes_.size() / sizeof(T), reinterpret_cast<const T*>(bytes_.data())));

0 commit comments

Comments
 (0)