refactor(uuid): prepare for noUncheckedIndexedAccess (#4445)

* refactor(uuid): prepare for `noUncheckedIndexedAccess`

* added a test and updated the error message

* changed to !== 6 and added another test

* update error message to be clearer
This commit is contained in:
Simon Holloway 2024-03-10 21:59:30 +00:00 committed by GitHub
parent 623d7d0bf1
commit 5c23dcbe86
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 32 additions and 6 deletions

View File

@ -76,5 +76,5 @@ export function version(uuid: string): number {
throw new TypeError("Invalid UUID");
}
return parseInt(uuid[14], 16);
return parseInt(uuid[14]!, 16);
}

View File

@ -136,6 +136,12 @@ export function generate(
throw new Error("Can't create more than 10M uuids/sec");
}
if (node.length !== 6) {
throw new Error(
"Cannot create UUID. The node option must be an array of 6 bytes",
);
}
_lastMSecs = msecs;
_lastNSecs = nsecs;
_clockseq = clockseq;
@ -163,7 +169,7 @@ export function generate(
b[i++] = clockseq & 0xff;
for (let n = 0; n < 6; ++n) {
b[i + n] = node[n];
b[i + n] = node[n]!;
}
return buf ?? bytesToUuid(b);

View File

@ -59,6 +59,26 @@ Deno.test("generate() can fill the UUID into a buffer", () => {
assertEquals(buf, uuid);
});
Deno.test("generate() throws when node is passed with less than 6 numbers", () => {
assertThrows(
() => {
generate({ node: [0x01, 0x23, 0x45, 0x67, 0x89] });
},
Error,
"Cannot create UUID. The node option must be an array of 6 bytes",
);
});
Deno.test("generate() throws when node is passed with more than 6 numbers", () => {
assertThrows(
() => {
generate({ node: [0x01, 0x23, 0x45, 0x67, 0x89, 0x89, 0x89] });
},
Error,
"Cannot create UUID. The node option must be an array of 6 bytes",
);
});
Deno.test("generate() throws when create more than 10M uuids/sec", () => {
assertThrows(
() => {

View File

@ -54,8 +54,8 @@ export async function generate(
const buffer = await crypto.subtle.digest("MD5", toHash);
const bytes = new Uint8Array(buffer);
bytes[6] = (bytes[6] & 0x0f) | 0x30;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
bytes[6] = (bytes[6]! & 0x0f) | 0x30;
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
return bytesToUuid(bytes);
}

View File

@ -53,8 +53,8 @@ export async function generate(
const buffer = await crypto.subtle.digest("sha-1", toHash);
const bytes = new Uint8Array(buffer);
bytes[6] = (bytes[6] & 0x0f) | 0x50;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
bytes[6] = (bytes[6]! & 0x0f) | 0x50;
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
return bytesToUuid(bytes);
}