Skip to content

[Implement] Buffer.compare #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
10 changes: 10 additions & 0 deletions assembly/buffer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ export class Buffer extends Uint8Array {
return result;
}

public static compare(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;
}
};

public static isBuffer<T>(value: T): bool {
return value instanceof Buffer;
}
Expand Down
2 changes: 2 additions & 0 deletions assembly/node.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>(value: T): bool;
/** Reads an unsigned integer at the designated offset. */
Expand Down
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 createFrom<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 @@ -43,6 +50,18 @@ describe("buffer", () => {
// TODO: expectFn(() => { Buffer.allocUnsafe(BLOCK_MAXSIZE + 1); }).toThrow();
});

test("#compare", () => {
let a = createFrom<Buffer>([0x05, 0x06, 0x07, 0x08]);
let b = createFrom<Buffer>([0x01, 0x02, 0x03]);
let c = createFrom<Buffer>([0x05, 0x06, 0x07]);
let d = createFrom<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);
});

test("#isBuffer", () => {
let a = "";
let b = new Uint8Array(0);
Expand Down