@@ -9,15 +9,19 @@ export const isV6 = isIPv6
9
9
// but with buf/offset args removed because we don't use them
10
10
export const toBytes = function ( ip : string ) : Uint8Array {
11
11
let offset = 0
12
- let result
13
- ip = ip . trim ( )
12
+ ip = ip . toString ( ) . trim ( )
14
13
15
14
if ( isV4 ( ip ) ) {
16
- result = new Uint8Array ( offset + 4 )
15
+ const bytes = new Uint8Array ( offset + 4 )
16
+
17
17
ip . split ( / \. / g) . forEach ( ( byte ) => {
18
- result [ offset ++ ] = parseInt ( byte , 10 ) & 0xff
18
+ bytes [ offset ++ ] = parseInt ( byte , 10 ) & 0xff
19
19
} )
20
- } else if ( isV6 ( ip ) ) {
20
+
21
+ return bytes
22
+ }
23
+
24
+ if ( isV6 ( ip ) ) {
21
25
const sections = ip . split ( ':' , 8 )
22
26
23
27
let i
@@ -48,44 +52,50 @@ export const toBytes = function (ip: string): Uint8Array {
48
52
sections . splice . apply ( sections , argv )
49
53
}
50
54
51
- result = new Uint8Array ( offset + 16 )
55
+ const bytes = new Uint8Array ( offset + 16 )
56
+
52
57
for ( i = 0 ; i < sections . length ; i ++ ) {
53
58
const word = parseInt ( sections [ i ] , 16 )
54
- result [ offset ++ ] = ( word >> 8 ) & 0xff
55
- result [ offset ++ ] = word & 0xff
59
+ bytes [ offset ++ ] = ( word >> 8 ) & 0xff
60
+ bytes [ offset ++ ] = word & 0xff
56
61
}
57
- }
58
62
59
- if ( result == null ) {
60
- throw new Error ( `invalid ip address "${ ip } "` )
63
+ return bytes
61
64
}
62
65
63
- return result
66
+ throw new Error ( 'invalid ip address' )
64
67
}
65
68
66
69
// Copied from https://github.com/indutny/node-ip/blob/master/lib/ip.js#L63
67
70
export const toString = function ( buf : Uint8Array , offset : number = 0 , length ?: number ) {
68
71
offset = ~ ~ offset
69
72
length = length ?? ( buf . length - offset )
70
73
71
- const result = [ ]
72
- let string = ''
73
74
const view = new DataView ( buf . buffer )
75
+
74
76
if ( length === 4 ) {
77
+ const result = [ ]
78
+
75
79
// IPv4
76
80
for ( let i = 0 ; i < length ; i ++ ) {
77
81
result . push ( buf [ offset + i ] )
78
82
}
79
- string = result . join ( '.' )
80
- } else if ( length === 16 ) {
83
+
84
+ return result . join ( '.' )
85
+ }
86
+
87
+ if ( length === 16 ) {
88
+ const result = [ ]
89
+
81
90
// IPv6
82
91
for ( let i = 0 ; i < length ; i += 2 ) {
83
92
result . push ( view . getUint16 ( offset + i ) . toString ( 16 ) )
84
93
}
85
- string = result . join ( ':' )
86
- string = string . replace ( / ( ^ | : ) 0 ( : 0 ) * : 0 ( : | $ ) / , '$1::$3' )
87
- string = string . replace ( / : { 3 , 4 } / , '::' )
94
+
95
+ return result . join ( ':' )
96
+ . replace ( / ( ^ | : ) 0 ( : 0 ) * : 0 ( : | $ ) / , '$1::$3' )
97
+ . replace ( / : { 3 , 4 } / , '::' )
88
98
}
89
99
90
- return string
100
+ return ''
91
101
}
0 commit comments