---
source: boltffi_bindgen/src/render/typescript/templates.rs
expression: template.render().unwrap()
---
const _CacheFinalizer: FinalizationRegistry<number> | null =
  typeof FinalizationRegistry === "undefined"
    ? null
    : new FinalizationRegistry<number>((handle) => {
        (_exports.boltffi_cache_free as Function)(handle);
      });

export class Cache {
  private _handle: number;
  private _disposed: boolean;

  private constructor(handle: number) {
    this._handle = handle;
    this._disposed = false;
    _CacheFinalizer?.register(this, handle, this);
  }

  static _fromHandle(handle: number): Cache {
    if (handle === 0) {
      throw new Error("Cache received a null handle");
    }
    return new Cache(handle);
  }

  [Symbol.dispose](): void {
    this.dispose();
  }

  dispose(): void {
    if (this._disposed) {
      return;
    }
    this._disposed = true;
    _CacheFinalizer?.unregister(this);
    (_exports.boltffi_cache_free as Function)(this._handle);
    this._handle = 0;
  }

  private _assertNotDisposed(): void {
    if (this._disposed) {
      throw new Error("Cache has been disposed");
    }
  }

  get(key: string): Entry | null {
    this._assertNotDisposed();
    const key_alloc = _module.allocString(key);
    try {
      const result = (_exports.boltffi_cache_get as Function)(this._handle, key_alloc.ptr, key_alloc.len);
      if (result === 0) {
        return null;
      }
      return Entry._fromHandle(result);
    } finally {
      _module.freeAlloc(key_alloc);
    }
  }
}
