This repository has been archived by the owner on Feb 26, 2024. It is now read-only.
/
bytes.ts
62 lines (52 loc) · 1.48 KB
/
bytes.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
import BN from "bn.js";
import * as CodecUtils from "@truffle/codec/utils";
import { DecodingError } from "@truffle/codec/decode/errors";
/**
* read word from memory
*
* requires `byte` to be a multiple of WORD_SIZE (32)
*
* @param memory - Uint8Array
* @param offset - number
* @return {BN}
*/
export function read(memory: Uint8Array, offset: number) {
return readBytes(memory, offset, CodecUtils.EVM.WORD_SIZE);
}
/**
* read <length> amount of bytes from memory, starting at <offset>
*
* @param memory - Uint8Array
* @param offset - number
* @param length - number
*/
export function readBytes(memory: Uint8Array, offset: number, length: number) {
if(!Number.isSafeInteger(offset + length)) {
throw new DecodingError({
kind: "ReadErrorBytes" as const,
start: offset,
length
});
}
// grab `length` bytes no matter what, here fill this array
var bytes = new Uint8Array(length);
bytes.fill(0); //fill it wil zeroes to start
//if the start is beyond the end of memory, just return those 0s
if (offset >= memory.length) {
return bytes;
}
// if we're reading past the end of memory, truncate the length to read
let excess = offset + length - memory.length;
let readLength;
if (excess > 0) {
readLength = memory.length - offset;
}
else {
readLength = length;
}
//get the (truncated) memory
let existing = new Uint8Array(memory.buffer, offset, readLength);
//copy it into our buffer
bytes.set(existing);
return bytes;
}