perf(bytes): skip doing extra work in some scenarios (#4767)

perf: skip doing extra work in std/bytes in some scenarios
This commit is contained in:
David Sherret 2024-05-18 22:10:00 -04:00 committed by GitHub
parent 377043ce82
commit 196101fbea
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 10 additions and 3 deletions

View File

@ -25,6 +25,9 @@
*/
export function endsWith(source: Uint8Array, suffix: Uint8Array): boolean {
const diff = source.length - suffix.length;
if (diff < 0) {
return false;
}
for (let i = suffix.length - 1; i >= 0; i--) {
if (source[diff + i] !== suffix[i]) {
return false;

View File

@ -49,12 +49,12 @@ export function indexOfNeedle(
needle: Uint8Array,
start = 0,
): number {
if (start >= source.length) {
return -1;
}
if (start < 0) {
start = Math.max(0, source.length + start);
}
if (needle.length > source.length - start) {
return -1;
}
const s = needle[0];
for (let i = start; i < source.length; i++) {
if (source[i] !== s) continue;

View File

@ -24,6 +24,10 @@
* ```
*/
export function startsWith(source: Uint8Array, prefix: Uint8Array): boolean {
if (prefix.length > source.length) {
return false;
}
for (let i = 0; i < prefix.length; i++) {
if (source[i] !== prefix[i]) return false;
}