-
Notifications
You must be signed in to change notification settings - Fork 55
/
PlutusList.ts
100 lines (82 loc) · 2.54 KB
/
PlutusList.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import { CborReader, CborReaderState, CborWriter } from '../CBOR';
import { HexBlob } from '@cardano-sdk/util';
import { PlutusData } from './PlutusData';
import { bytesToHex, hexToBytes } from '../../util/misc';
/** A list of plutus data. */
export class PlutusList {
readonly #array = new Array<PlutusData>();
#useIndefiniteEncoding = true;
/**
* Serializes this PlutusList instance into its CBOR representation as a Uint8Array.
*
* @returns The CBOR representation of this instance as a Uint8Array.
*/
toCbor(): HexBlob {
const writer = new CborWriter();
if (this.#useIndefiniteEncoding) {
writer.writeStartArray();
} else {
writer.writeStartArray(this.#array.length);
}
for (const elem of this.#array) {
writer.writeEncodedValue(hexToBytes(elem.toCbor()));
}
if (this.#useIndefiniteEncoding) writer.writeEndArray();
return HexBlob.fromBytes(writer.encode());
}
/**
* Deserializes a PlutusList instance from its CBOR representation.
*
* @param cbor The CBOR representation of this instance as a Uint8Array.
* @returns A PlutusList instance.
*/
static fromCbor(cbor: HexBlob): PlutusList {
const list = new PlutusList();
const reader = new CborReader(cbor);
const length = reader.readStartArray();
if (length === null) list.#useIndefiniteEncoding = true;
while (reader.peekState() !== CborReaderState.EndArray) {
list.add(PlutusData.fromCbor(bytesToHex(reader.readEncodedValue())));
}
reader.readEndArray();
return list;
}
/**
* Gets the length of the list.
*
* @returns the length of the list.
*/
getLength(): number {
return this.#array.length;
}
/**
* Gets an element from the list.
*
* @param index The index in the list of the element to get.
*/
get(index: number): PlutusData {
return this.#array[index];
}
/**
* Adds an element to the Plutus List.
*
* @param elem The element to be added.
*/
add(elem: PlutusData): void {
this.#array.push(elem);
}
/**
* Indicates whether some other PlutusList is "equal to" this one.
*
* @param other The other object to be compared.
* @returns true if objects are equals; otherwise false.
*/
equals(other: PlutusList): boolean {
if (this.#useIndefiniteEncoding !== other.#useIndefiniteEncoding) return false;
if (this.#array.length !== other.#array.length) return false;
for (let i = 0; i < this.#array.length; ++i) {
if (!this.#array[i].equals(other.#array[i])) return false;
}
return true;
}
}