Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
[Implement] Buffer.compare
  • Loading branch information
jtenner committed Jul 19, 2019
commit 09af2a253850a3276d3f1206ad10040678da264a
10 changes: 10 additions & 0 deletions assembly/buffer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,14 @@ export class Buffer extends Uint8Array {
result.dataLength = size;
return result;
}

public static readonly compare: (a: Buffer, b: Buffer) => i32 = (a: Buffer, b: Buffer): i32 => {
let compareLength = min<i32>(a.length, b.length);
let result = memory.compare(a.dataStart, b.dataStart, compareLength);
if (result == 0) {
return a.length - b.length;
} else {
return result;
}
};
}
2 changes: 2 additions & 0 deletions assembly/node.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ 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;
}
19 changes: 19 additions & 0 deletions tests/buffer.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
function instantiateFrom<T>(values: valueof<T>[]): T {
let result = instantiate<T>(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.
Expand Down Expand Up @@ -42,4 +49,16 @@ describe("buffer", () => {
// TODO: expectFn(() => { Buffer.allocUnsafe(-1); }).toThrow();
// TODO: expectFn(() => { Buffer.allocUnsafe(BLOCK_MAXSIZE + 1); }).toThrow();
});

test("#compare", () => {
let a = instantiateFrom<Buffer>([0x05, 0x06, 0x07, 0x08]);
let b = instantiateFrom<Buffer>([0x01, 0x02, 0x03]);
let c = instantiateFrom<Buffer>([0x05, 0x06, 0x07]);
let d = instantiateFrom<Buffer>([0x04, 0x05, 0x06]);

let actual: Buffer[] = [a, b, c, d];
actual.sort(Buffer.compare);
let expected: Buffer[] = [b, d, c, a];
expect<Buffer[]>(actual).toStrictEqual(expected);
});
});
4 changes: 4 additions & 0 deletions tests/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,3 +153,7 @@ function runTest(file, type, binary, wat) {
wasi.view = new DataView(wasm.memory.buffer);
context.run(wasm);
}

if (errors.length > 0) {
process.exit(1);
}