22Object . defineProperty ( exports , "__esModule" , { value : true } ) ;
33exports . isInSubnet = isInSubnet ;
44exports . isCorrect = isCorrect ;
5+ exports . prefixLengthFromMask = prefixLengthFromMask ;
56exports . numberToPaddedHex = numberToPaddedHex ;
67exports . stringToPaddedHex = stringToPaddedHex ;
78exports . testBit = testBit ;
9+ const address_error_1 = require ( "./address-error" ) ;
810function isInSubnet ( address ) {
911 if ( this . subnetMask < address . subnetMask ) {
1012 return false ;
@@ -25,6 +27,25 @@ function isCorrect(defaultBits) {
2527 return this . parsedSubnet === String ( this . subnetMask ) ;
2628 } ;
2729}
30+ /**
31+ * Returns the prefix length (number of leading 1 bits) of a contiguous
32+ * subnet mask. Throws `AddressError` if the mask is non-contiguous (e.g.
33+ * `255.0.255.0`).
34+ */
35+ function prefixLengthFromMask ( value , totalBits ) {
36+ const binary = value . toString ( 2 ) . padStart ( totalBits , '0' ) ;
37+ if ( binary . length > totalBits ) {
38+ throw new address_error_1 . AddressError ( 'Invalid subnet mask.' ) ;
39+ }
40+ const firstZero = binary . indexOf ( '0' ) ;
41+ if ( firstZero === - 1 ) {
42+ return totalBits ;
43+ }
44+ if ( binary . slice ( firstZero ) . includes ( '1' ) ) {
45+ throw new address_error_1 . AddressError ( 'Invalid subnet mask.' ) ;
46+ }
47+ return firstZero ;
48+ }
2849function numberToPaddedHex ( number ) {
2950 return number . toString ( 16 ) . padStart ( 2 , '0' ) ;
3051}
0 commit comments