-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy patharray.js
More file actions
60 lines (52 loc) · 1.34 KB
/
array.js
File metadata and controls
60 lines (52 loc) · 1.34 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
import { XdrCompositeType } from './xdr-type';
import { XdrReaderError, XdrWriterError } from './errors';
export class Array extends XdrCompositeType {
constructor(childType, length) {
super();
this._childType = childType;
this._length = length;
}
/**
* @inheritDoc
*/
read(reader) {
if (this._length > reader.remainingBytes()) {
throw new XdrReaderError(
`insufficient bytes to decode Array of length ${this._length}`
);
}
// allocate array of specified length
const result = new global.Array(this._length);
// read values
for (let i = 0; i < this._length; i++) {
result[i] = this._childType.read(reader);
}
return result;
}
/**
* @inheritDoc
*/
write(value, writer) {
if (!global.Array.isArray(value))
throw new XdrWriterError(`value is not array`);
if (value.length !== this._length)
throw new XdrWriterError(
`got array of size ${value.length}, expected ${this._length}`
);
for (const child of value) {
this._childType.write(child, writer);
}
}
/**
* @inheritDoc
*/
isValid(value) {
if (!(value instanceof global.Array) || value.length !== this._length) {
return false;
}
for (const child of value) {
if (!this._childType.isValid(child)) return false;
}
return true;
}
}