This repository was archived by the owner on Aug 8, 2022. It is now read-only.
forked from LimeChain/as-scale-codec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScaleSet.ts
79 lines (71 loc) · 2.12 KB
/
ScaleSet.ts
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
import { CompactInt } from "./Int/CompactInt";
import { BytesReader } from "./BytesReader";
import { Codec } from "./interfaces/Codec";
import { UnwrappableCodec } from "./interfaces/UnwrappableCodec";
/**
* @description SCALE Codec support for native Set type
*/
export class ScaleSet<T extends Codec>
extends Set<T>
implements UnwrappableCodec<Set<T>> {
/**
* @description return underlying native type
*/
@inline
unwrap(): Set<T> {
// TODO: remove unwrap?
return this;
}
/**
* The number of bytes this Set has
*/
@inline
encodedLength(): i32 {
return this.toU8a().length;
}
/**
* Convert it to u8[]
* Length is encoded first, followed by all key and value encodings concatenated
*/
toU8a(): u8[] {
const values: T[] = this.values();
let len: CompactInt = new CompactInt(values.length);
const result: Array<Array<u8>> = [len.toU8a()];
for (let i = 0; i < values.length; i++) {
result.push(values[i].toU8a());
}
return result.flat();
}
/**
* @description Non-static constructor
* @param bytes
* @param index
*/
populateFromBytes(bytes: u8[], index: i32 = 0): i32 {
const bytesReader = new BytesReader(bytes, index);
const lenComp = bytesReader.readInto<CompactInt>();
for (let i: i32 = 0; i < lenComp.unwrap(); i++) {
const value = bytesReader.readInto<T>();
this.add(value);
}
return bytesReader.currentIndex();
}
@operator("==")
eq(other: this): bool {
return this === other;
}
@operator("!=")
notEq(other: this): bool {
return !this.eq(this);
}
static fromU8a<T extends Codec>(input: u8[], index: i32 = 0): ScaleSet<T> {
const set = new ScaleSet<T>();
const bytesReader = new BytesReader(input, index);
const len = bytesReader.readInto<CompactInt>().unwrap();
for (let i: i32 = 0; i < len; i++) {
const val = bytesReader.readInto<T>();
set.add(val);
}
return set;
}
}