UNPKG

@thi.ng/vector-pools

Version:

Data structures for managing & working with strided, memory mapped vectors

75 lines (74 loc) 2.02 kB
import { asNativeType, GLType } from "@thi.ng/api/typedarray"; import { isTypedArray } from "@thi.ng/checks/is-typedarray"; import { MemPool } from "@thi.ng/malloc/pool"; import { wrap } from "./wrap.js"; class VecPool { pool; constructor(pool) { this.pool = pool instanceof MemPool ? pool : new MemPool(pool); } stats() { return this.pool.stats(); } malloc(size, type = "f32") { return this.pool.callocAs(asNativeType(type), size); } mallocWrapped(size, stride = 1, type = "f32") { const buf = this.pool.callocAs(asNativeType(type), size * stride); return buf ? wrap(buf, size, 0, stride) : void 0; } /** * Intended to provide individual vector views of a larger * underlying buffer. Attempts to allocate a single block of * sufficient memory to hold `num` vectors of `size` elements and if * successful returns array of vectors mapping the buffer with given * stride lengths (both component and element strides can be * provided). * * *Note:* Since all result vectors share the same continuous memory * block, freeing any of them from the pool will invalidate all of * them. * * Also see: * - `Vec2.mapBuffer()` * - `Vec3.mapBuffer()` * - `Vec4.mapBuffer()` * - `NDArray1.mapBuffer()` * * @param num - * @param size - * @param cstride - * @param estride - * @param type - */ mallocArray(num, size, cstride = 1, estride = size, type = "f32") { const buf = this.malloc( Math.max(cstride, estride, size) * num, asNativeType(type) ); if (!buf) return; const res = []; for (let i = 0; i < num; i += estride) { res.push(wrap(buf, size, i, cstride)); } return res; } free(vec) { const buf = vec.buf; return buf ? isTypedArray(buf) ? this.pool.free(buf) : false : this.pool.free(vec); } freeAll() { this.pool.freeAll(); } release() { const res = this.pool.release(); res && delete this.pool; return res; } } export { VecPool };