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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
/**
 * @author jdiaz5513
 */

import initTrace from "debug";

import { MAX_SEGMENT_LENGTH, NATIVE_LITTLE_ENDIAN } from "../constants";
import { NOT_IMPLEMENTED, SEG_REPLACEMENT_BUFFER_TOO_SMALL, SEG_SIZE_OVERFLOW } from "../errors";
import { Int64, Uint64 } from "../types";
import { format, padToWord } from "../util";
import { Message } from "./message";
import { Pointer } from "./pointers";

const trace = initTrace("capnp:segment");
trace("load");

export class Segment implements DataView {
  buffer: ArrayBuffer;

  /** The number of bytes currently allocated in the segment. */

  byteLength: number;

  /**
   * This value should always be zero. It's only here to satisfy the DataView interface.
   *
   * In the future the Segment implementation (or a child class) may allow accessing the buffer from a nonzero offset,
   * but that adds a lot of extra arithmetic.
   */

  byteOffset: number;

  readonly [Symbol.toStringTag] = "Segment" as "DataView";

  readonly id: number;

  readonly message: Message;

  private _dv: DataView;

  constructor(id: number, message: Message, buffer: ArrayBuffer, byteLength = 0) {
    this.id = id;
    this.message = message;
    this.buffer = buffer;
    this._dv = new DataView(buffer);

    this.byteOffset = 0;
    this.byteLength = byteLength;
  }

  /**
   * Attempt to allocate the requested number of bytes in this segment. If this segment is full this method will return
   * a pointer to freshly allocated space in another segment from the same message.
   *
   * @param {number} byteLength The number of bytes to allocate, will be rounded up to the nearest word.
   * @returns {Pointer} A pointer to the newly allocated space.
   */

  allocate(byteLength: number): Pointer {
    trace("allocate(%d)", byteLength);

    // eslint-disable-next-line @typescript-eslint/no-this-alias
    let segment: Segment = this;

    byteLength = padToWord(byteLength);

    if (byteLength > MAX_SEGMENT_LENGTH - 8) {
      throw new Error(format(SEG_SIZE_OVERFLOW, byteLength));
    }

    if (!segment.hasCapacity(byteLength)) {
      segment = segment.message.allocateSegment(byteLength);
    }

    const byteOffset = segment.byteLength;

    segment.byteLength = segment.byteLength + byteLength;

    trace("Allocated %x bytes in %s (requested segment: %s).", byteLength, this, segment);

    return new Pointer(segment, byteOffset);
  }

  /**
   * Quickly copy a word (8 bytes) from `srcSegment` into this one at the given offset.
   *
   * @param {number} byteOffset The offset to write the word to.
   * @param {Segment} srcSegment The segment to copy the word from.
   * @param {number} srcByteOffset The offset from the start of `srcSegment` to copy from.
   * @returns {void}
   */

  copyWord(byteOffset: number, srcSegment: Segment, srcByteOffset: number): void {
    const value = srcSegment._dv.getFloat64(srcByteOffset, NATIVE_LITTLE_ENDIAN);

    this._dv.setFloat64(byteOffset, value, NATIVE_LITTLE_ENDIAN);
  }

  /**
   * Quickly copy words from `srcSegment` into this one.
   *
   * @param {number} byteOffset The offset to start copying into.
   * @param {Segment} srcSegment The segment to copy from.
   * @param {number} srcByteOffset The start offset to copy from.
   * @param {number} wordLength The number of words to copy.
   * @returns {void}
   */

  copyWords(byteOffset: number, srcSegment: Segment, srcByteOffset: number, wordLength: number): void {
    const dst = new Float64Array(this.buffer, byteOffset, wordLength);
    const src = new Float64Array(srcSegment.buffer, srcByteOffset, wordLength);

    dst.set(src);
  }

  /**
   * Quickly fill a number of words in the buffer with zeroes.
   *
   * @param {number} byteOffset The first byte to set to zero.
   * @param {number} wordLength The number of words (not bytes!) to zero out.
   * @returns {void}
   */

  fillZeroWords(byteOffset: number, wordLength: number): void {
    new Float64Array(this.buffer, byteOffset, wordLength).fill(0);
  }

  /** WARNING: This function is not yet implemented. */

  getBigInt64(byteOffset: number, littleEndian?: boolean): bigint {
    throw new Error(format(NOT_IMPLEMENTED, byteOffset, littleEndian));
  }

  /** WARNING: This function is not yet implemented. */

  getBigUint64(byteOffset: number, littleEndian?: boolean): bigint {
    throw new Error(format(NOT_IMPLEMENTED, byteOffset, littleEndian));
  }

  /**
   * Get the total number of bytes available in this segment (the size of its underlying buffer).
   *
   * @returns {number} The total number of bytes this segment can hold.
   */

  getCapacity(): number {
    return this.buffer.byteLength;
  }

  /**
   * Read a float32 value out of this segment.
   *
   * @param {number} byteOffset The offset in bytes to the value.
   * @returns {number} The value.
   */

  getFloat32(byteOffset: number): number {
    return this._dv.getFloat32(byteOffset, true);
  }

  /**
   * Read a float64 value out of this segment.
   *
   * @param {number} byteOffset The offset in bytes to the value.
   * @returns {number} The value.
   */

  getFloat64(byteOffset: number): number {
    return this._dv.getFloat64(byteOffset, true);
  }

  /**
   * Read an int16 value out of this segment.
   *
   * @param {number} byteOffset The offset in bytes to the value.
   * @returns {number} The value.
   */

  getInt16(byteOffset: number): number {
    return this._dv.getInt16(byteOffset, true);
  }

  /**
   * Read an int32 value out of this segment.
   *
   * @param {number} byteOffset The offset in bytes to the value.
   * @returns {number} The value.
   */

  getInt32(byteOffset: number): number {
    return this._dv.getInt32(byteOffset, true);
  }

  /**
   * Read an int64 value out of this segment.
   *
   * @param {number} byteOffset The offset in bytes to the value.
   * @returns {number} The value.
   */

  getInt64(byteOffset: number): Int64 {
    return new Int64(new Uint8Array(this.buffer.slice(byteOffset, byteOffset + 8)));
  }

  /**
   * Read an int8 value out of this segment.
   *
   * @param {number} byteOffset The offset in bytes to the value.
   * @returns {number} The value.
   */

  getInt8(byteOffset: number): number {
    return this._dv.getInt8(byteOffset);
  }

  /**
   * Read a uint16 value out of this segment.
   *
   * @param {number} byteOffset The offset in bytes to the value.
   * @returns {number} The value.
   */

  getUint16(byteOffset: number): number {
    return this._dv.getUint16(byteOffset, true);
  }

  /**
   * Read a uint32 value out of this segment.
   *
   * @param {number} byteOffset The offset in bytes to the value.
   * @returns {number} The value.
   */

  getUint32(byteOffset: number): number {
    return this._dv.getUint32(byteOffset, true);
  }

  /**
   * Read a uint8 value out of this segment.
   * NOTE: this does not copy the memory region, so updates to the underlying buffer will affect the Uint64 value!
   *
   * @param {number} byteOffset The offset in bytes to the value.
   * @returns {number} The value.
   */

  getUint64(byteOffset: number): Uint64 {
    return new Uint64(new Uint8Array(this.buffer.slice(byteOffset, byteOffset + 8)));
  }

  /**
   * Read a uint8 value out of this segment.
   *
   * @param {number} byteOffset The offset in bytes to the value.
   * @returns {number} The value.
   */

  getUint8(byteOffset: number): number {
    return this._dv.getUint8(byteOffset);
  }

  hasCapacity(byteLength: number): boolean {
    trace("hasCapacity(%d)", byteLength);

    // capacity - allocated >= requested

    return this.buffer.byteLength - this.byteLength >= byteLength;
  }

  /**
   * Quickly check the word at the given offset to see if it is equal to zero.
   *
   * PERF_V8: Fastest way to do this is by reading the whole word as a `number` (float64) in the _native_ endian format
   * and see if it's zero.
   *
   * Benchmark: http://jsben.ch/#/Pjooc
   *
   * @param {number} byteOffset The offset to the word.
   * @returns {boolean} `true` if the word is zero.
   */

  isWordZero(byteOffset: number): boolean {
    return this._dv.getFloat64(byteOffset, NATIVE_LITTLE_ENDIAN) === 0;
  }

  /**
   * Swap out this segment's underlying buffer with a new one. It's assumed that the new buffer has the same content but
   * more free space, otherwise all existing pointers to this segment will be hilariously broken.
   *
   * @param {ArrayBuffer} buffer The new buffer to use.
   * @returns {void}
   */

  replaceBuffer(buffer: ArrayBuffer): void {
    trace("replaceBuffer(%p)", buffer);

    if (this.buffer === buffer) return;

    if (buffer.byteLength < this.byteLength) {
      throw new Error(SEG_REPLACEMENT_BUFFER_TOO_SMALL);
    }

    this._dv = new DataView(buffer);
    this.buffer = buffer;
  }

  /** WARNING: This function is not yet implemented.  */

  setBigInt64(byteOffset: number, value: bigint, littleEndian?: boolean): void {
    throw new Error(format(NOT_IMPLEMENTED, byteOffset, value, littleEndian));
  }

  /** WARNING: This function is not yet implemented.  */

  setBigUint64(byteOffset: number, value: bigint, littleEndian?: boolean): void {
    throw new Error(format(NOT_IMPLEMENTED, byteOffset, value, littleEndian));
  }

  /**
   * Write a float32 value to the specified offset.
   *
   * @param {number} byteOffset The offset from the beginning of the buffer.
   * @param {number} val The value to store.
   * @returns {void}
   */

  setFloat32(byteOffset: number, val: number): void {
    this._dv.setFloat32(byteOffset, val, true);
  }

  /**
   * Write an float64 value to the specified offset.
   *
   * @param {number} byteOffset The offset from the beginning of the buffer.
   * @param {number} val The value to store.
   * @returns {void}
   */

  setFloat64(byteOffset: number, val: number): void {
    this._dv.setFloat64(byteOffset, val, true);
  }

  /**
   * Write an int16 value to the specified offset.
   *
   * @param {number} byteOffset The offset from the beginning of the buffer.
   * @param {number} val The value to store.
   * @returns {void}
   */

  setInt16(byteOffset: number, val: number): void {
    this._dv.setInt16(byteOffset, val, true);
  }

  /**
   * Write an int32 value to the specified offset.
   *
   * @param {number} byteOffset The offset from the beginning of the buffer.
   * @param {number} val The value to store.
   * @returns {void}
   */

  setInt32(byteOffset: number, val: number): void {
    this._dv.setInt32(byteOffset, val, true);
  }

  /**
   * Write an int8 value to the specified offset.
   *
   * @param {number} byteOffset The offset from the beginning of the buffer.
   * @param {number} val The value to store.
   * @returns {void}
   */

  setInt8(byteOffset: number, val: number): void {
    this._dv.setInt8(byteOffset, val);
  }

  /**
   * Write an int64 value to the specified offset.
   *
   * @param {number} byteOffset The offset from the beginning of the buffer.
   * @param {Int64} val The value to store.
   * @returns {void}
   */

  setInt64(byteOffset: number, val: Int64): void {
    this._dv.setUint8(byteOffset, val.buffer[0]);
    this._dv.setUint8(byteOffset + 1, val.buffer[1]);
    this._dv.setUint8(byteOffset + 2, val.buffer[2]);
    this._dv.setUint8(byteOffset + 3, val.buffer[3]);
    this._dv.setUint8(byteOffset + 4, val.buffer[4]);
    this._dv.setUint8(byteOffset + 5, val.buffer[5]);
    this._dv.setUint8(byteOffset + 6, val.buffer[6]);
    this._dv.setUint8(byteOffset + 7, val.buffer[7]);
  }

  /**
   * Write a uint16 value to the specified offset.
   *
   * @param {number} byteOffset The offset from the beginning of the buffer.
   * @param {number} val The value to store.
   * @returns {void}
   */

  setUint16(byteOffset: number, val: number): void {
    this._dv.setUint16(byteOffset, val, true);
  }

  /**
   * Write a uint32 value to the specified offset.
   *
   * @param {number} byteOffset The offset from the beginning of the buffer.
   * @param {number} val The value to store.
   * @returns {void}
   */

  setUint32(byteOffset: number, val: number): void {
    this._dv.setUint32(byteOffset, val, true);
  }

  /**
   * Write a uint64 value to the specified offset.
   * TODO: benchmark other ways to perform this write operation.
   *
   * @param {number} byteOffset The offset from the beginning of the buffer.
   * @param {Uint64} val The value to store.
   * @returns {void}
   */

  setUint64(byteOffset: number, val: Uint64): void {
    this._dv.setUint8(byteOffset + 0, val.buffer[0]);
    this._dv.setUint8(byteOffset + 1, val.buffer[1]);
    this._dv.setUint8(byteOffset + 2, val.buffer[2]);
    this._dv.setUint8(byteOffset + 3, val.buffer[3]);
    this._dv.setUint8(byteOffset + 4, val.buffer[4]);
    this._dv.setUint8(byteOffset + 5, val.buffer[5]);
    this._dv.setUint8(byteOffset + 6, val.buffer[6]);
    this._dv.setUint8(byteOffset + 7, val.buffer[7]);
  }

  /**
   * Write a uint8 (byte) value to the specified offset.
   *
   * @param {number} byteOffset The offset from the beginning of the buffer.
   * @param {number} val The value to store.
   * @returns {void}
   */

  setUint8(byteOffset: number, val: number): void {
    this._dv.setUint8(byteOffset, val);
  }

  /**
   * Write a zero word (8 bytes) to the specified offset. This is slightly faster than calling `setUint64` or
   * `setFloat64` with a zero value.
   *
   * Benchmark: http://jsben.ch/#/dUdPI
   *
   * @param {number} byteOffset The offset of the word to set to zero.
   * @returns {void}
   */

  setWordZero(byteOffset: number): void {
    this._dv.setFloat64(byteOffset, 0, NATIVE_LITTLE_ENDIAN);
  }

  toString(): string {
    return format(
      "Segment_id:%d,off:%a,len:%a,cap:%a",
      this.id,
      this.byteLength,
      this.byteOffset,
      this.buffer.byteLength
    );
  }
}