---
source: boltffi_bindgen/src/render/typescript/templates.rs
assertion_line: 1163
expression: template.render().unwrap()
---
/**
 * A counter class
 */
const _CounterFinalizer: FinalizationRegistry<number> | null =
  typeof FinalizationRegistry === "undefined"
    ? null
    : new FinalizationRegistry<number>((handle) => {
        (_exports.boltffi_counter_free as Function)(handle);
      });

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

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

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

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

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

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

  /**
   * Creates a counter
   */
  static new(): Counter {
    const handle = (_exports.boltffi_counter_new as Function)();
    return Counter._fromHandle(handle);
  }

  increment(delta: number): number {
    this._assertNotDisposed();
    return (_exports.boltffi_counter_increment as Function)(this._handle, delta);
  }

  async nextValue(): Promise<number> {
    this._assertNotDisposed();
    const handle = (_exports.boltffi_counter_next_value as Function)(this._handle);
    const awaitedHandle = await _module.asyncManager.pollAsync(
      handle,
      (futureHandle: number) => (_exports.boltffi_counter_next_value_poll_sync as Function)(futureHandle),
      (futureHandle: number) => (_exports.boltffi_counter_next_value_panic_message as Function)(futureHandle),
      (futureHandle: number) => (_exports.boltffi_counter_next_value_free as Function)(futureHandle)
    );
    const outPtr = _module.allocBufDescriptor();
    let completeCompleted = false;
    try {
      _module.completeAsync((statusPtr: number) => (_exports.boltffi_counter_next_value_complete as Function)(outPtr, awaitedHandle, statusPtr));
      completeCompleted = true;
      const reader = _module.readerFromBuf(outPtr);
      const result = reader.readI32();
      return result;
    } finally {
      if (completeCompleted) {
        _module.freeBuf(outPtr);
      } else {
        _module.freeBufDescriptor(outPtr);
      }
      (_exports.boltffi_counter_next_value_free as Function)(awaitedHandle);
    }
  }
}
