-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathvar-array.js
More file actions
72 lines (64 loc) · 1.9 KB
/
var-array.js
File metadata and controls
72 lines (64 loc) · 1.9 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
import { UnsignedInt } from './unsigned-int';
import { NestedXdrType } from './xdr-type';
import { XdrReaderError, XdrWriterError } from './errors';
export class VarArray extends NestedXdrType {
constructor(
childType,
maxLength = UnsignedInt.MAX_VALUE,
maxDepth = NestedXdrType.DEFAULT_MAX_DEPTH
) {
super(maxDepth);
this._childType = childType;
this._maxLength = maxLength;
}
/**
* @inheritDoc
*/
read(reader, remainingDepth = this._maxDepth) {
NestedXdrType.checkDepth(remainingDepth);
const length = UnsignedInt.read(reader);
if (length > this._maxLength)
throw new XdrReaderError(
`saw ${length} length VarArray, max allowed is ${this._maxLength}`
);
// Upper-bound fast-fail: remaining bytes is a loose capacity check since
// each XDR element typically consumes more than 1 byte (e.g., 4+ bytes)
if (length > reader.remainingBytes()) {
throw new XdrReaderError(
`VarArray length ${length} exceeds remaining ${reader.remainingBytes()} bytes`
);
}
const result = new Array(length);
for (let i = 0; i < length; i++) {
result[i] = this._childType.read(reader, remainingDepth - 1);
}
return result;
}
/**
* @inheritDoc
*/
write(value, writer) {
if (!(value instanceof Array))
throw new XdrWriterError(`value is not array`);
if (value.length > this._maxLength)
throw new XdrWriterError(
`got array of size ${value.length}, max allowed is ${this._maxLength}`
);
UnsignedInt.write(value.length, writer);
for (const child of value) {
this._childType.write(child, writer);
}
}
/**
* @inheritDoc
*/
isValid(value) {
if (!(value instanceof Array) || value.length > this._maxLength) {
return false;
}
for (const child of value) {
if (!this._childType.isValid(child)) return false;
}
return true;
}
}