Skip to content

Commit 56e1e4a

Browse files
committed
Benchmark parse function
1 parent b7be5af commit 56e1e4a

2 files changed

Lines changed: 32 additions & 21 deletions

File tree

src/index.ts

Lines changed: 8 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -31,20 +31,18 @@ export function parse(string: string): Credentials | undefined {
3131

3232
// parse header
3333
const match = CREDENTIALS_REGEXP.exec(string);
34-
35-
if (!match) {
36-
return undefined;
37-
}
34+
if (!match) return undefined;
3835

3936
// decode user pass
40-
const userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1]));
41-
42-
if (!userPass) {
43-
return undefined;
44-
}
37+
const userPass = decodeBase64(match[1]);
38+
const colonIndex = userPass.indexOf(':');
39+
if (colonIndex === -1) return undefined;
4540

4641
// return credentials object
47-
return new CredentialsImpl(userPass[1], userPass[2]);
42+
return new CredentialsImpl(
43+
userPass.slice(0, colonIndex),
44+
userPass.slice(colonIndex + 1),
45+
);
4846
}
4947

5048
/**
@@ -59,17 +57,6 @@ export function parse(string: string): Credentials | undefined {
5957
const CREDENTIALS_REGEXP =
6058
/^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/;
6159

62-
/**
63-
* RegExp for basic auth user/pass
64-
*
65-
* user-pass = userid ":" password
66-
* userid = *<TEXT excluding ":">
67-
* password = *TEXT
68-
* @private
69-
*/
70-
71-
const USER_PASS_REGEXP = /^([^:]*):(.*)$/;
72-
7360
/**
7461
* Decode base64 string.
7562
* @private

src/parse.bench.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { describe, bench } from 'vitest';
2+
import { parse } from './index';
3+
4+
describe('parse', () => {
5+
bench('basic auth header', () => {
6+
const header = 'Basic dGVzdDpwYXNzd29yZA=='; // "test:password" in base64
7+
parse(header);
8+
});
9+
10+
bench('basic auth header with extra whitespace', () => {
11+
const header = ' Basic dGVzdDpwYXNzd29yZA== '; // "test:password" in base64 with extra whitespace
12+
parse(header);
13+
});
14+
15+
bench('invalid basic auth header', () => {
16+
const header = 'Basic invalidbase64'; // Invalid base64 string
17+
parse(header);
18+
});
19+
20+
bench('non-basic auth header', () => {
21+
const header = 'Bearer sometoken'; // Not a basic auth header
22+
parse(header);
23+
});
24+
});

0 commit comments

Comments
 (0)