-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuffer-equal.match.ts
More file actions
72 lines (67 loc) · 2.06 KB
/
Copy pathbuffer-equal.match.ts
File metadata and controls
72 lines (67 loc) · 2.06 KB
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
69
70
71
72
import { desc, repr } from "../../describe/describe.js";
import { createMatcher } from "../../match/match.js";
import { assertTypeTypedArray } from "../type-typed-array/type-typed-array.assert.js";
import {
bufferEqualToMatcher,
type BufferEqualToMatcher,
} from "./buffer-equal.type.js";
import type { TypedArray } from "../type-typed-array/type-typed-array.type.js";
/**
* Matcher for a TypedArray equal to an expected TypedArray, comparing byte by byte.
* Matchers are applied through assertObjectMatches, where they narrow the
* corresponding property type.
* Type information that already exists in the calling scope is incorporated.
* @example
* ```ts
* import { assertObjectMatches, bufferEqualTo } from "@kensio/smartass";
*
* const expected = new Uint8Array([0x01, 0x02, 0x03]);
*
* const value: unknown = {
* data: new Uint8Array([0x01, 0x02, 0x03]),
* };
*
* assertObjectMatches(value, {
* data: bufferEqualTo(expected),
* });
*
* // value is now narrowed to an object with data equal to the expected buffer
* // {
* // data: Uint8Array;
* // }
* ```
*/
export function bufferEqualTo<T extends TypedArray>(
expected: T,
): BufferEqualToMatcher<T> {
return {
...createMatcher(
(value): value is T => {
try {
assertTypeTypedArray(value);
} catch {
return false;
}
if (value.constructor !== expected.constructor) {
return false;
}
const actualBuffer = Buffer.from(
value.buffer,
value.byteOffset,
value.byteLength,
);
const expectedBuffer = Buffer.from(
expected.buffer,
expected.byteOffset,
expected.byteLength,
);
return Buffer.compare(actualBuffer, expectedBuffer) === 0;
},
() => `buffer equal to ${desc(expected)}`,
() => repr(expected),
),
// Runtime marker used only to make the matcher type nominal for type-level
// refinement dispatch. It is not part of the user-facing matcher behaviour.
[bufferEqualToMatcher]: expected,
};
}