1
1
// buf.toString('hex') -> toHex(buf)
2
2
import { assertBytes } from "@noble/hashes/utils" ;
3
3
export {
4
+ assertBool ,
4
5
assertBytes ,
6
+ bytesToHex ,
5
7
bytesToHex as toHex ,
6
- createView
8
+ concatBytes ,
9
+ hexToBytes ,
10
+ createView ,
11
+ utf8ToBytes
7
12
} from "@noble/hashes/utils" ;
8
- // Buffer.from(hex, 'hex') -> hexToBytes(hex)
9
- export function hexToBytes ( hex : string ) : Uint8Array {
10
- if ( typeof hex !== "string" ) {
11
- throw new TypeError ( `hexToBytes: expected string, got ${ typeof hex } ` ) ;
12
- }
13
- if ( hex . length % 2 ) {
14
- throw new Error ( "hexToBytes: received invalid unpadded hex" ) ;
15
- }
16
- const array = new Uint8Array ( hex . length / 2 ) ;
17
- for ( let i = 0 ; i < array . length ; i ++ ) {
18
- const j = i * 2 ;
19
- array [ i ] = Number . parseInt ( hex . slice ( j , j + 2 ) , 16 ) ;
20
- }
21
- return array ;
22
- }
23
- // Buffer.from(s, 'utf8') -> utf8ToBytes(s)
24
- export function utf8ToBytes ( s : string ) {
25
- if ( typeof s !== "string" ) {
26
- throw new TypeError ( `utf8ToBytes expected string, got ${ typeof s } ` ) ;
27
- }
28
- return new TextEncoder ( ) . encode ( s ) ;
29
- }
13
+
30
14
// buf.toString('utf8') -> bytesToUtf8(buf)
31
15
export function bytesToUtf8 ( data : Uint8Array ) : string {
32
16
if ( ! ( data instanceof Uint8Array ) ) {
33
17
throw new TypeError ( `bytesToUtf8 expected Uint8Array, got ${ typeof data } ` ) ;
34
18
}
35
19
return new TextDecoder ( ) . decode ( data ) ;
36
20
}
21
+
37
22
// buf.equals(buf2) -> equalsBytes(buf, buf2)
38
23
export function equalsBytes ( a : Uint8Array , b : Uint8Array ) : boolean {
39
24
if ( a . length !== b . length ) {
@@ -46,27 +31,8 @@ export function equalsBytes(a: Uint8Array, b: Uint8Array): boolean {
46
31
}
47
32
return true ;
48
33
}
49
- // Buffer.concat([buf1, buf2]) -> concatBytes(buf1, buf2)
50
- export function concatBytes ( ...arrays : Uint8Array [ ] ) : Uint8Array {
51
- if ( arrays . length === 1 ) {
52
- return arrays [ 0 ] ;
53
- }
54
- const length = arrays . reduce ( ( a , arr ) => a + arr . length , 0 ) ;
55
- const result = new Uint8Array ( length ) ;
56
- for ( let i = 0 , pad = 0 ; i < arrays . length ; i ++ ) {
57
- const arr = arrays [ i ] ;
58
- result . set ( arr , pad ) ;
59
- pad += arr . length ;
60
- }
61
- return result ;
62
- }
63
- // Internal utils
64
- export function assertBool ( b : boolean ) {
65
- if ( typeof b !== "boolean" ) {
66
- throw new Error ( `Expected boolean, not ${ b } ` ) ;
67
- }
68
- }
69
34
35
+ // Internal utils
70
36
export function wrapHash ( hash : ( msg : Uint8Array ) => Uint8Array ) {
71
37
return ( msg : Uint8Array ) => {
72
38
assertBytes ( msg ) ;
0 commit comments