-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.ts
More file actions
83 lines (82 loc) · 2.48 KB
/
Copy patharray.ts
File metadata and controls
83 lines (82 loc) · 2.48 KB
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
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
import type {AppendableBuffer} from '../lib/appendable'
import * as assert from '../lib/assert'
import {BufferOffset, makeBaseValue, readFlexInt} from '../lib/read-util'
import {writeIterable} from '../lib/write-util'
import AbsoluteType from './absolute'
import AbstractType from './abstract'
import type {Type} from './type'
/**
* A type storing a variable-length array of values of the same type
*
* Example:
* ````javascript
* class Car {
* constructor(brand, model, year) {
* this.brand = brand
* this.model = model
* this.year = year
* }
* }
* let carType = new sb.StructType({ //Type<Car>
* brand: new sb.StringType,
* model: new sb.StringType,
* year: new sb.ShortType
* })
* let type = new sb.ArrayType(carType) //Type<Car[]>
* ````
*
* @param E The type of each element in the array
* @param READ_E The type of each element
* in the read array
*/
export class ArrayType<E, READ_E extends E = E> extends AbsoluteType<E[], READ_E[]> {
static get _value(): number {
return 0x52
}
/**
* @param type A [[Type]] that can serialize each element in the array
*/
constructor(readonly type: Type<E, READ_E>) {
super()
assert.instanceOf(type, AbstractType)
}
addToBuffer(buffer: AppendableBuffer): boolean {
/*istanbul ignore else*/
if (super.addToBuffer(buffer)) {
this.type.addToBuffer(buffer)
return true
}
/*istanbul ignore next*/
return false
}
/**
* Appends value bytes to an [[AppendableBuffer]] according to the type
*
* Example:
* ````javascript
* let car1 = new Car('VW', 'Bug', 1960)
* let car2 = new Car('Honda', 'Fit', 2015)
* let car3 = new Car('Tesla', 'Model 3', 2017)
* type.writeValue(buffer, [car1, car2, car3])
* ````
* @param buffer The buffer to which to append
* @param value The value to write
* @throws If the value doesn't match the type, e.g. `new sb.StringType().writeValue(buffer, 23)`
*/
writeValue(buffer: AppendableBuffer, value: E[]): void {
assert.isBuffer(buffer)
assert.instanceOf(value, Array)
writeIterable({type: this.type, buffer, value, length: value.length})
}
consumeValue(bufferOffset: BufferOffset, baseValue?: READ_E[]): READ_E[] {
const arrayLength = readFlexInt(bufferOffset)
const value = baseValue || makeBaseValue(this, arrayLength) as READ_E[]
for (let i = 0; i < arrayLength; i++) {
value[i] = this.type.consumeValue(bufferOffset)
}
return value
}
equals(otherType: unknown): boolean {
return this.isSameType(otherType) && this.type.equals(otherType.type)
}
}