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
|
import { BigNumber } from '@0xproject/utils';
import * as chai from 'chai';
import { TestLibMemContract } from '../../src/contract_wrappers/generated/test_lib_mem';
import { artifacts } from '../../src/utils/artifacts';
import { chaiSetup } from '../../src/utils/chai_setup';
import { provider, txDefaults, web3Wrapper } from '../../src/utils/web3_wrapper';
chaiSetup.configure();
const expect = chai.expect;
// BUG: Ideally we would use Buffer.from(memory).toString('hex')
// https://github.com/Microsoft/TypeScript/issues/23155
const toHex = (buf: Uint8Array): string =>
buf.reduce((a, v) => a + ('00' + v.toString(16)).slice(-2), '0x');
const fromHex = (str: string): Uint8Array =>
Uint8Array.from(Buffer.from(str.slice(2), 'hex'));
describe('LibMem', () => {
let owner: string;
let testLibMem: TestLibMemContract;
before(async () => {
// Setup accounts & addresses
const accounts = await web3Wrapper.getAvailableAddressesAsync();
owner = accounts[0];
// Deploy TestLibMem
testLibMem = await TestLibMemContract.deployFrom0xArtifactAsync(artifacts.TestLibMem, provider, txDefaults);
});
describe('memcpy', () => {
// Create memory 0x000102...FF
const memSize = 256;
const memory = (new Uint8Array(memSize)).map((_, i) => i);
const memHex = toHex(memory);
// Reference implementation to test against
const refMemcpy = (mem: Uint8Array, dest: number, source: number, length: number): Uint8Array =>
Uint8Array.from(memory).copyWithin(dest, source, source + length);
// Test vectors: destination, source, length, job description
const tests: Array<[number, number, number, string]> = [
[128, 0, 0, 'zero bytes'],
[128, 0, 1, 'one byte'],
[128, 0, 11, 'eleven bytes'],
[128, 0, 32, 'one word'],
[128, 0, 72, 'two words and eight bytes'],
[128, 0, 100, 'three words and four bytes'],
];
// Construct test cases
tests.forEach(([dest, source, length, job]) =>
it(`copies ${job}`, async () => {
const expected = refMemcpy(memory, dest, source, length);
const resultStr = await testLibMem.testMemcpy.callAsync(
memHex,
new BigNumber(dest),
new BigNumber(source),
new BigNumber(length),
);
const result = fromHex(resultStr);
expect(result).to.deep.equal(expected);
}),
);
});
});
|