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())));