From 69179ead4844c850129e41a8be5d23cc0ea87cfd Mon Sep 17 00:00:00 2001 From: Matija Kecman Date: Fri, 28 Nov 2025 06:35:11 -0800 Subject: [PATCH] Internal change. PiperOrigin-RevId: 837829087 Change-Id: I110f2f9d1dff2aff8bcad7ac22ea8ed82323185f --- wasm/unpack.h | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/wasm/unpack.h b/wasm/unpack.h index a40fec31..9942a773 100644 --- a/wasm/unpack.h +++ b/wasm/unpack.h @@ -52,7 +52,7 @@ class WasmBuffer { public: // Creates a buffer with the given element count explicit WasmBuffer(int element_count = 0) { - bytes_.resize(element_count * sizeof(T)); + Resize(element_count); } // Creates a buffer by copying data from a (typed) array @@ -60,13 +60,25 @@ class WasmBuffer { return WasmBuffer(array); } + // Resizes the buffer to the given element count. + // If element count is zero the memory is released. + void Resize(int element_count) { + if (element_count == 0) { + std::vector empty; + bytes_.swap(empty); + } else { + bytes_.resize(element_count * sizeof(T)); + } + } + // Returns the pointer to the data in the buffer uintptr_t GetPointer() { return reinterpret_cast(bytes_.data()); } // Returns the number of elements in the buffer int GetElementCount() { return bytes_.size() / sizeof(T); } - // Returns a TypedArray view of the buffer + // Returns a TypedArray view of the buffer. + // Do not cache this value, bytes_.data() is invalidated on Resize! emscripten::val GetView() { return emscripten::val(emscripten::typed_memory_view( bytes_.size() / sizeof(T), reinterpret_cast(bytes_.data())));