diff --git a/assembly/buffer/index.ts b/assembly/buffer/index.ts index 2d43385..c68f327 100644 --- a/assembly/buffer/index.ts +++ b/assembly/buffer/index.ts @@ -23,6 +23,16 @@ export class Buffer extends Uint8Array { return result; } + public static compare(a: Buffer, b: Buffer): i32 { + let compareLength = min(a.length, b.length); + let result = memory.compare(a.dataStart, b.dataStart, compareLength); + if (result == 0) { + return a.length - b.length; + } else { + return result; + } + }; + public static isBuffer(value: T): bool { return value instanceof Buffer; } diff --git a/assembly/node.d.ts b/assembly/node.d.ts index d6da2cb..e9277fb 100644 --- a/assembly/node.d.ts +++ b/assembly/node.d.ts @@ -3,6 +3,8 @@ declare class Buffer extends Uint8Array { static alloc(size: i32): Buffer; /** This method allocates a new Buffer of indicated size. This is unsafe because the data is not zeroed. */ static allocUnsafe(size: i32): Buffer; + /** This method is used for sorting Buffer objects. */ + static compare(a: Buffer, b: Buffer): i32; /** This method asserts a value is a Buffer object via `value instanceof Buffer`. */ static isBuffer(value: T): bool; /** Reads an unsigned integer at the designated offset. */ diff --git a/tests/buffer.spec.ts b/tests/buffer.spec.ts index 8645074..bece056 100644 --- a/tests/buffer.spec.ts +++ b/tests/buffer.spec.ts @@ -1,3 +1,10 @@ +function createFrom(values: valueof[]): T { + let result = instantiate(values.length); + // @ts-ignore + for (let i = 0; i < values.length; i++) result[i] = values[i]; + return result; +} + /** * This is the buffer test suite. For each prototype function, put a single test * function call here. @@ -43,6 +50,18 @@ describe("buffer", () => { // TODO: expectFn(() => { Buffer.allocUnsafe(BLOCK_MAXSIZE + 1); }).toThrow(); }); + test("#compare", () => { + let a = createFrom([0x05, 0x06, 0x07, 0x08]); + let b = createFrom([0x01, 0x02, 0x03]); + let c = createFrom([0x05, 0x06, 0x07]); + let d = createFrom([0x04, 0x05, 0x06]); + + let actual: Buffer[] = [a, b, c, d]; + actual.sort(Buffer.compare); + let expected: Buffer[] = [b, d, c, a]; + expect(actual).toStrictEqual(expected); + }); + test("#isBuffer", () => { let a = ""; let b = new Uint8Array(0);