File size: 1,394 Bytes
5641073
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
 * @author jdiaz5513
 */

import initTrace from "debug";
import { DEFAULT_BUFFER_SIZE } from "../../constants";
import { SEG_ID_OUT_OF_BOUNDS } from "../../errors";
import { padToWord, format } from "../../util";
import { ArenaAllocationResult } from "./arena-allocation-result";
import { ArenaKind } from "./arena-kind";

const trace = initTrace("capnp:arena:multi");
trace("load");

export class MultiSegmentArena {
  static readonly allocate = allocate;
  static readonly getBuffer = getBuffer;
  static readonly getNumSegments = getNumSegments;

  readonly buffers: ArrayBuffer[];
  readonly kind = ArenaKind.MULTI_SEGMENT;

  constructor(buffers: ArrayBuffer[] = []) {
    this.buffers = buffers;

    trace("new %s", this);
  }

  toString(): string {
    return format("MultiSegmentArena_segments:%d", getNumSegments(this));
  }
}

export function allocate(minSize: number, m: MultiSegmentArena): ArenaAllocationResult {
  const b = new ArrayBuffer(padToWord(Math.max(minSize, DEFAULT_BUFFER_SIZE)));
  m.buffers.push(b);

  return new ArenaAllocationResult(m.buffers.length - 1, b);
}

export function getBuffer(id: number, m: MultiSegmentArena): ArrayBuffer {
  if (id < 0 || id >= m.buffers.length) {
    throw new Error(format(SEG_ID_OUT_OF_BOUNDS, id));
  }

  return m.buffers[id];
}

export function getNumSegments(m: MultiSegmentArena): number {
  return m.buffers.length;
}