Skip to content
This repository has been archived by the owner on Jun 11, 2024. It is now read-only.

Implement big endian encoding and decoding - Closes #24 #37

Merged
merged 3 commits into from
Sep 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/app/modules/dex/utils/bigEndian.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Big Endian Encoding and Decoding
export const int32be = (x: number) => {
const buf = Buffer.allocUnsafe(4);
buf.writeInt32BE(x, 0);

return buf.toString('hex');
}

export const int32beInv = (bufferX: string) => {
const buf = Buffer.from(bufferX, "hex");

return buf.readInt32BE(0);
}

export const uint32be = (x: number) => {
const buf = Buffer.allocUnsafe(4);
buf.writeUInt32BE(x, 0);

return buf.toString('hex');
}

export const uint32beInv = (bufferX: string): number => {
const buf = Buffer.from(bufferX, "hex");

return buf.readUInt32BE(0);
}
27 changes: 27 additions & 0 deletions test/unit/modules/dex/bigEndian.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import {
int32be,
uint32be,
int32beInv,
uint32beInv
} from '../../../../src/app/modules/dex/utils/bigEndian';

describe('dex:bigEndian', () => {
describe('constructor', () => {
it('int32be/int32beInv should convert and revert to original values', async () => {
expect(int32be(2147483647)).toEqual('7fffffff');
expect(int32beInv('7fffffff')).toEqual(2147483647);
});
it('uint32be/uint32beInv should convert and revert to original values', async () => {
expect(uint32be(4294967295)).toBe('ffffffff');
expect(uint32beInv('ffffffff')).toBe(4294967295);
});
it('int32be/int32beInv should fail on out of bounds values', async () => {
expect(() => int32beInv('wrong value')).toThrow();
expect(() => int32be(2147483648)).toThrow();
});
it('uint32be/uint32beInv should fail on out of bounds values', async () => {
expect(() => uint32beInv('wrong value')).toThrow();
expect(() => uint32be(4294967296)).toThrow();
});
});
});
3 changes: 1 addition & 2 deletions test/unit/modules/dex/utils.sqrt.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {
sqrt
} from '../../../../src/app/modules/dex/utils/math_constants'
} from '../../../../src/app/modules/dex/utils/mathConstants'
import {
MAX_SQRT_RATIO
} from '../../../../src/app/modules/dex/constants'
Expand All @@ -9,6 +9,5 @@ describe('sqrt', () => {
it('should calculate sqrt', async () => {
expect(sqrt(BigInt(100))).toBe(BigInt(10));
expect(sqrt(MAX_SQRT_RATIO)).toBe(BigInt('1208903099313551102292995'));

});
});