-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathindex.ts
More file actions
745 lines (663 loc) · 24.7 KB
/
Copy pathindex.ts
File metadata and controls
745 lines (663 loc) · 24.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
import cidrRegex from "cidr-regex";
import {parseIp, stringifyIp} from "ip-bigint";
const bits = {4: 32, 6: 128};
const octetStrings: string[] = Array.from({length: 256}, (_, i) => String(i));
const octetDotStrings: string[] = Array.from({length: 256}, (_, i) => `${i}.`);
const prefixStrings: string[] = Array.from({length: 129}, (_, i) => `/${i}`);
const prefixNumStrings: string[] = Array.from({length: 129}, (_, i) => String(i));
const hexStrings: string[] = Array.from({length: 256}, (_, i) => i.toString(16));
const hexPadStrings: string[] = Array.from({length: 256}, (_, i) => i.toString(16).padStart(2, "0"));
const hostMasks: bigint[] = Array.from({length: 129}, (_, i) => (1n << BigInt(i)) - 1n);
const hostNotMasks: bigint[] = hostMasks.map(mask => ~mask);
type Network = string;
type Networks = Network | ReadonlyArray<Network>;
type ValidIpVersion = 4 | 6;
type ParsedCidr = {
cidr: string;
ip: string;
version: ValidIpVersion;
prefix: string;
prefixPresent: boolean;
start: bigint;
end: bigint;
};
type CidrOpts = {
/** Whether to reject networks that are not a CIDR or IP address. Default: `true` */
validate?: boolean;
};
type NormalizeOpts = {
/** Whether to reject networks that are not a CIDR or IP address. Default: `true` */
validate?: boolean;
compress?: boolean;
hexify?: boolean;
};
const networkRe = cidrRegex({exact: true, prefix: "optional"});
// networks are validated at the boundary, so inner parses skip ip-bigint's own check
const unchecked = {validate: false};
function invalidNetwork(net: Network): Error {
return new Error(`Network is not a CIDR or IP: "${net}"`);
}
function checkNetwork(net: Network): void {
if (!networkRe.test(net)) throw invalidNetwork(net);
}
function checkNetworks(nets: Networks, opts?: CidrOpts): void {
if (opts?.validate === false) return;
if (typeof nets === "string") {
checkNetwork(nets);
} else {
for (const net of nets) checkNetwork(net);
}
}
type Range4 = {
start: number;
end: number;
};
type Range6 = {
start: bigint;
end: bigint;
};
type LeanParsedCidr4 = Range4 & {version: 4};
type LeanParsedCidr6 = Range6 & {version: 6};
type LeanParsedCidr = LeanParsedCidr4 | LeanParsedCidr6;
const cmpV4StartEnd = (a: LeanParsedCidr4, b: LeanParsedCidr4): number => a.start - b.start || a.end - b.end;
const cmpV4Start = (a: LeanParsedCidr4, b: LeanParsedCidr4): number => a.start - b.start;
const cmpV6StartEnd = (a: LeanParsedCidr6, b: LeanParsedCidr6): number => a.start > b.start ? 1 : a.start < b.start ? -1 : a.end > b.end ? 1 : a.end < b.end ? -1 : 0;
const cmpV6Start = (a: LeanParsedCidr6, b: LeanParsedCidr6): number => a.start > b.start ? 1 : a.start < b.start ? -1 : 0;
// 32-bit host masks indexed by host bit count, so index 32 is the whole space and 0 a single
// address. Callers derive hostBits from a non-negative prefix and clamp it to a valid index with
// `Math.max`. Int32Array keeps the all-ones entry a plain int32 (-1), which masks identically to
// 0xFFFFFFFF.
const hostMasks4 = Int32Array.from({length: 33}, (_, i) => i === 32 ? -1 : (1 << i) - 1);
function formatIPv4Fast(n: number): string {
return octetDotStrings[(n >>> 24) & 0xff] + octetDotStrings[(n >>> 16) & 0xff] + octetDotStrings[(n >>> 8) & 0xff] + octetStrings[n & 0xff];
}
// Returns a 32-bit number, or -1 on failure. Parses s[0..end-1] to avoid a substring allocation.
function parseIPv4Fast(s: string, end: number): number {
let num = 0;
let octet = 0;
let dots = 0;
let digits = 0;
for (let i = 0; i < end; i++) {
const c = s.charCodeAt(i);
if (c >= 48 && c <= 57) {
octet = octet * 10 + (c - 48);
digits++;
} else if (c === 46) { // "."
if (digits === 0 || octet > 255) return -1;
num = (num << 8) | octet;
octet = 0;
dots++;
digits = 0;
} else {
return -1;
}
}
if (dots !== 3 || digits === 0 || octet > 255) return -1;
return ((num << 8) | octet) >>> 0;
}
function parsePrefixNum(str: string, slashIndex: number): number {
if (slashIndex + 1 >= str.length) throw invalidNetwork(str);
let prefixNum = 0;
for (let i = slashIndex + 1; i < str.length; i++) {
const c = str.charCodeAt(i);
if (c < 48 || c > 57) throw invalidNetwork(str);
prefixNum = prefixNum * 10 + (c - 48);
}
return prefixNum;
}
// Scratch output of parseIPv4Range, clobbered by its next call. Only rangeSlashIndex is valid
// when it returns false.
let rangeV4Start = 0;
let rangeV4End = 0;
let rangeV4Prefix = 0;
let rangeSlashIndex = -1;
// Reads a plain dotted-quad IPv4 and its optional prefix in one pass, without substrings.
function parseIPv4Range(str: string): boolean {
const len = str.length;
let num = 0;
let octet = 0;
let dots = 0;
let digits = 0;
let i = 0;
for (; i < len; i++) {
const c = str.charCodeAt(i);
if (c >= 48 && c <= 57) {
octet = octet * 10 + (c - 48);
digits++;
} else if (c === 46) { // "."
if (digits === 0 || octet > 255) break;
num = (num << 8) | octet;
octet = 0;
dots++;
digits = 0;
} else {
break; // "/" ends the address, anything else is not plain IPv4
}
}
if (i < len && str.charCodeAt(i) === 47) { // "/"
rangeSlashIndex = i;
} else {
rangeSlashIndex = str.indexOf("/", i); // -1 once the loop consumed the whole string
if (i < len) return false;
}
if (dots !== 3 || digits === 0 || octet > 255) return false;
const v4num = ((num << 8) | octet) >>> 0;
rangeV4Prefix = rangeSlashIndex !== -1 ? parsePrefixNum(str, rangeSlashIndex) : 32;
const mask = hostMasks4[Math.max(32 - rangeV4Prefix, 0)];
rangeV4Start = (v4num & ~mask) >>> 0;
rangeV4End = (v4num | mask) >>> 0;
return true;
}
function doNormalize(cidr: Network, opts?: NormalizeOpts): Network {
if (parseIPv4Range(cidr)) {
const ip = formatIPv4Fast(rangeV4Start);
return rangeSlashIndex !== -1 ? ip + prefixStrings[rangeV4Prefix] : ip;
}
// IPv6, and the IPv4 forms the fast path above declines: delegate to ip-bigint.
const slashIndex = rangeSlashIndex; // reuse from the parseIPv4Range call above
const prefixPresent = slashIndex !== -1;
let prefixNum = prefixPresent ? parsePrefixNum(cidr, slashIndex) : -1;
const {number, version, ipv4mapped, scopeid} = parseIp(prefixPresent ? cidr.substring(0, slashIndex) : cidr, unchecked);
if (prefixNum === -1) {
prefixNum = bits[version];
}
if (version === 4) {
const hostBits = 32 - prefixNum;
const mask = hostMasks4[Math.max(hostBits, 0)];
const ip = formatIPv4Fast((Number(number) & ~mask) >>> 0);
return (hostBits > 0 || prefixPresent) ? ip + prefixStrings[prefixNum] : ip;
}
const compress = opts?.compress ?? true;
const hexify = opts?.hexify ?? false;
const hostBits = 128 - prefixNum;
if (hostBits <= 0 && !prefixPresent) {
return stringifyIp({number, version, ipv4mapped, scopeid}, {compress, hexify});
}
const start = hostBits > 0 ? number & hostNotMasks[hostBits] : number;
// Masking can clear the `::ffff:` marker, leaving an address that is no longer v4-mapped.
const startMapped = ipv4mapped && (start >> 32n) === 0xffffn;
return stringifyIp({number: start, version, ipv4mapped: startMapped, scopeid}, {compress, hexify}) + prefixStrings[prefixNum];
}
/** Returns a string or array (depending on input) with a normalized representation. Will not include a prefix on single IPs. Will set network address to the start of the network. */
export function normalizeCidr<T extends Networks>(cidr: T, opts?: NormalizeOpts): T {
checkNetworks(cidr, opts);
return (typeof cidr === "string" ? doNormalize(cidr, opts) : cidr.map(entry => doNormalize(entry, opts))) as T;
}
/** Returns a `parsed` Object which is used internally by this module. It can be used to test whether the passed network is IPv4 or IPv6 or to work with the BigInts directly. */
export function parseCidr(str: Network, opts?: CidrOpts): ParsedCidr {
if (opts?.validate !== false) checkNetwork(str);
const slashIndex = str.indexOf("/");
const prefixPresent = slashIndex !== -1;
// Parsed with locals rather than parseIPv4Range, whose scratch state costs more than this second
// scan once the returned object escapes.
const v4num = parseIPv4Fast(str, prefixPresent ? slashIndex : str.length);
if (v4num !== -1) {
const prefixNum = prefixPresent ? parsePrefixNum(str, slashIndex) : 32;
const ip = formatIPv4Fast(v4num);
const mask = hostMasks4[Math.max(32 - prefixNum, 0)];
return {
cidr: ip + prefixStrings[prefixNum],
ip,
version: 4,
prefix: prefixNumStrings[prefixNum] ?? String(prefixNum),
prefixPresent,
start: BigInt((v4num & ~mask) >>> 0),
end: BigInt((v4num | mask) >>> 0),
};
}
// IPv6, and the IPv4 forms the fast path above declines: delegate to ip-bigint.
const ipPart = prefixPresent ? str.substring(0, slashIndex) : str;
let prefixNum = prefixPresent ? parsePrefixNum(str, slashIndex) : -1;
const {number, version, ipv4mapped, scopeid} = parseIp(ipPart, unchecked);
const numBits = bits[version];
if (prefixNum === -1) {
prefixNum = numBits;
}
const prefix = prefixNumStrings[prefixNum] ?? String(prefixNum);
const ip = stringifyIp({number, version, ipv4mapped, scopeid});
const hostBits = numBits - prefixNum;
let start = number;
let end = number;
if (hostBits > 0) {
start = number & hostNotMasks[hostBits];
end = number | hostMasks[hostBits];
}
return {
cidr: ip + prefixStrings[prefixNum],
ip,
version,
prefix,
prefixPresent,
start,
end,
};
}
// IPv6, and the IPv4 forms the fast path declines. Call only after parseIPv4Range(str) returned
// false, whose rangeSlashIndex it reuses.
function parseCidrLeanSlow(str: Network): LeanParsedCidr {
const slashIndex = rangeSlashIndex;
const ipPart = slashIndex !== -1 ? str.substring(0, slashIndex) : str;
let prefixNum = slashIndex !== -1 ? parsePrefixNum(str, slashIndex) : -1;
const {number, version} = parseIp(ipPart, unchecked);
const numBits = bits[version];
if (prefixNum === -1) {
prefixNum = numBits;
}
const hostBits = numBits - prefixNum;
if (version === 4) {
const num = Number(number);
const mask = hostMasks4[Math.max(hostBits, 0)];
return {
start: (num & ~mask) >>> 0,
end: (num | mask) >>> 0,
version: 4,
};
}
if (hostBits <= 0) {
return {start: number, end: number, version: 6};
}
return {
start: number & hostNotMasks[hostBits],
end: number | hostMasks[hostBits],
version: 6,
};
}
// Internal parser. v4 returns number start/end (32-bit math); v6 returns bigint start/end.
function parseCidrLean(str: Network): LeanParsedCidr {
if (parseIPv4Range(str)) {
return {start: rangeV4Start, end: rangeV4End, version: 4};
}
return parseCidrLeanSlow(str);
}
// Bit length via Math.clz32, avoiding toString(2) allocation.
function bigintBitLength(n: bigint): number {
if (n === 0n) return 0;
let len = 0;
if (n >= 0x10000000000000000n) { n >>= 64n; len = 64; }
while (n >= 0x100000000n) { n >>= 32n; len += 32; }
return len + 32 - Math.clz32(Number(n));
}
function biggestPowerOfTwo4(num: number): number {
if (num === 0) return 0;
if (num >= 0x100000000) return 0x100000000;
return (1 << (31 - Math.clz32(num))) >>> 0;
}
// Greedily emit the largest CIDR-aligned block at each position, bounded by
// start's alignment (its lowest set bit) and the remaining size.
function subparts4(pStart: number, pEnd: number, output: string[]): void {
let start = pStart;
while (start <= pEnd) {
const size = pEnd - start + 1;
const lowBit = (start & -start) >>> 0; // 0 when start === 0, i.e. no alignment limit
const blockSize = (lowBit !== 0 && lowBit <= size) ? lowBit : biggestPowerOfTwo4(size);
output.push(formatIPv4Fast(start) + prefixStrings[Math.clz32(blockSize - 1)]);
start += blockSize;
}
}
// Greedily emit the largest CIDR-aligned block at each position. The block is
// bounded by start's alignment (its lowest set bit) and the remaining size.
function subparts6(pStart: bigint, pEnd: bigint, output: string[]): void {
// Shortcut for what the loop below would find anyway: the whole range is one aligned block.
const fullSize = pEnd - pStart + 1n;
const startLowBit = pStart & -pStart;
if ((fullSize & (fullSize - 1n)) === 0n && (startLowBit === 0n || startLowBit >= fullSize)) {
output.push(stringifyIp({number: pStart, version: 6}) + prefixStrings[129 - bigintBitLength(fullSize)]);
return;
}
let start = pStart;
while (start <= pEnd) {
const size = pEnd - start + 1n;
const lowBit = start & -start; // 0n when start === 0n, i.e. no alignment limit
const alignedFully = lowBit !== 0n && lowBit <= size;
// size and the largest power of two below it share a bit length
const blockBits = bigintBitLength(alignedFully ? lowBit : size);
output.push(stringifyIp({number: start, version: 6}) + prefixStrings[129 - blockBits]);
start += alignedFully ? lowBit : 1n << BigInt(blockBits - 1);
}
}
// Sorts and coalesces overlapping or adjacent ranges in place. `cur` trails the read index, so
// every entry it overwrites is already consumed.
function mergeIntervalsRaw4(nets: LeanParsedCidr4[]): Range4[] {
if (nets.length < 2) return nets;
nets.sort(cmpV4StartEnd);
let last = 0;
let cur = nets[0];
for (let i = 1; i < nets.length; i++) {
const {start, end} = nets[i];
if (start <= cur.end + 1) {
if (end > cur.end) cur.end = end;
} else {
cur = nets[++last];
cur.start = start;
cur.end = end;
}
}
nets.length = last + 1;
return nets;
}
function mergeIntervalsRaw6(nets: LeanParsedCidr6[]): Range6[] {
if (nets.length < 2) return nets;
nets.sort(cmpV6StartEnd);
let last = 0;
let cur = nets[0];
for (let i = 1; i < nets.length; i++) {
const {start, end} = nets[i];
if (start <= cur.end + 1n) {
if (end > cur.end) cur.end = end;
} else {
cur = nets[++last];
cur.start = start;
cur.end = end;
}
}
nets.length = last + 1;
return nets;
}
function subtractSorted4(bases: Range4[], excls: Range4[]): Range4[] {
if (excls.length === 0) return bases;
if (bases.length === 0) return [];
const result: Range4[] = [];
let j = 0;
for (const base of bases) {
let start = base.start;
const end = base.end;
while (j < excls.length && excls[j].end < start) {
j++;
}
let k = j;
while (k < excls.length && excls[k].start <= end && start <= end) {
if (excls[k].start > start) {
result.push({start, end: excls[k].start - 1});
}
start = excls[k].end + 1;
k++;
}
if (start <= end) {
result.push({start, end});
}
}
return result;
}
function subtractSorted6(bases: Range6[], excls: Range6[]): Range6[] {
if (excls.length === 0) return bases;
if (bases.length === 0) return [];
const result: Range6[] = [];
let j = 0;
for (const base of bases) {
let start = base.start;
const end = base.end;
while (j < excls.length && excls[j].end < start) {
j++;
}
let k = j;
while (k < excls.length && excls[k].start <= end && start <= end) {
if (excls[k].start > start) {
result.push({start, end: excls[k].start - 1n});
}
start = excls[k].end + 1n;
k++;
}
if (start <= end) {
result.push({start, end});
}
}
return result;
}
/** Returns an array of merged networks */
export function mergeCidr(nets: Networks, opts?: CidrOpts): Array<Network> {
checkNetworks(nets, opts);
const v4: LeanParsedCidr4[] = [], v6: LeanParsedCidr6[] = [];
for (const str of typeof nets === "string" ? [nets] : nets) {
const net = parseCidrLean(str);
if (net.version === 4) v4.push(net); else v6.push(net);
}
const merged: Array<Network> = [];
for (const part of mergeIntervalsRaw4(v4)) {
subparts4(part.start, part.end, merged);
}
for (const part of mergeIntervalsRaw6(v6)) {
subparts6(part.start, part.end, merged);
}
return merged;
}
/** Returns an array of merged remaining networks of the subtraction of `excludeNetworks` from `baseNetworks`. */
export function excludeCidr(base: Networks, excl: Networks, opts?: CidrOpts): Array<Network> {
checkNetworks(base, opts);
checkNetworks(excl, opts);
const v4base: LeanParsedCidr4[] = [], v6base: LeanParsedCidr6[] = [];
const v4excl: LeanParsedCidr4[] = [], v6excl: LeanParsedCidr6[] = [];
for (const str of typeof base === "string" ? [base] : base) {
const net = parseCidrLean(str);
if (net.version === 4) v4base.push(net); else v6base.push(net);
}
for (const str of typeof excl === "string" ? [excl] : excl) {
const net = parseCidrLean(str);
if (net.version === 4) v4excl.push(net); else v6excl.push(net);
}
const result: Array<Network> = [];
if (v4base.length > 0) {
for (const part of subtractSorted4(mergeIntervalsRaw4(v4base), mergeIntervalsRaw4(v4excl))) {
subparts4(part.start, part.end, result);
}
}
if (v6base.length > 0) {
for (const part of subtractSorted6(mergeIntervalsRaw6(v6base), mergeIntervalsRaw6(v6excl))) {
subparts6(part.start, part.end, result);
}
}
return result;
}
/** Returns a generator for individual IPs contained in the networks. */
export function expandCidr(nets: Networks, opts?: CidrOpts): Generator<Network> {
checkNetworks(nets, opts); // eagerly, so all seven entry points reject at call time alike
return expandChecked(nets);
}
function* expandChecked(nets: Networks): Generator<Network> {
const v4: LeanParsedCidr4[] = [], v6: LeanParsedCidr6[] = [];
for (const str of typeof nets === "string" ? [nets] : nets) {
const net = parseCidrLean(str);
if (net.version === 4) v4.push(net); else v6.push(net);
}
if (v4.length > 0) {
for (const part of mergeIntervalsRaw4(v4)) {
let prevHigh = -1;
let prefix = "";
for (let num = part.start; num <= part.end; num++) {
const high = num >>> 8;
if (high !== prevHigh) {
prefix = octetDotStrings[(num >>> 24) & 0xff] + octetDotStrings[(num >>> 16) & 0xff] + octetDotStrings[(num >>> 8) & 0xff];
prevHigh = high;
}
yield prefix + octetStrings[num & 0xff];
}
}
}
if (v6.length > 0) {
const ipObj = {number: 0n, version: 6 as const};
for (const part of mergeIntervalsRaw6(v6)) {
// Per 65536-IP block, the upper 112 bits are constant: stringify them once
// and iterate the last group numerically. A nonzero last group never joins or
// alters a zero run, so the compressed form is always that constant prefix
// plus the group's hex digits.
let num = part.start;
while (num <= part.end) {
const blockStart = num & ~0xffffn;
const blockEnd = blockStart | 0xffffn;
let group = Number(num & 0xffffn);
const groupEnd = part.end < blockEnd ? Number(part.end & 0xffffn) : 0xffff;
if (group === 0) {
ipObj.number = blockStart;
yield stringifyIp(ipObj); // last group zero can be absorbed into "::", stringify in full
group = 1;
}
if (group <= groupEnd) {
ipObj.number = blockStart | 1n;
const prefix = stringifyIp(ipObj).slice(0, -1);
for (; group <= groupEnd; group++) {
yield group < 256 ? prefix + hexStrings[group] : prefix + hexStrings[group >>> 8] + hexPadStrings[group & 0xff];
}
}
num = blockEnd + 1n;
}
}
}
}
/** Returns a boolean that indicates if `networksA` overlap (intersect) with `networksB`. */
export function overlapCidr(a: Networks, b: Networks, opts?: CidrOpts): boolean {
checkNetworks(a, opts);
checkNetworks(b, opts);
// Fast path for single-vs-single (most common case)
if (typeof a === "string" && typeof b === "string") {
// Zero-allocation IPv4 fast path
if (parseIPv4Range(a)) {
const startA = rangeV4Start, endA = rangeV4End;
if (parseIPv4Range(b)) {
return startA <= rangeV4End && rangeV4Start <= endA;
}
const pb = parseCidrLeanSlow(b);
if (pb.version !== 4) return false;
return startA <= pb.end && pb.start <= endA;
}
const pa = parseCidrLeanSlow(a);
const pb = parseCidrLean(b);
if (pa.version !== pb.version) return false;
return pa.start <= pb.end && pb.start <= pa.end;
}
const v4a: LeanParsedCidr4[] = [], v6a: LeanParsedCidr6[] = [];
const v4b: LeanParsedCidr4[] = [], v6b: LeanParsedCidr6[] = [];
for (const str of typeof a === "string" ? [a] : a) {
const net = parseCidrLean(str);
if (net.version === 4) v4a.push(net); else v6a.push(net);
}
for (const str of typeof b === "string" ? [b] : b) {
const net = parseCidrLean(str);
if (net.version === 4) v4b.push(net); else v6b.push(net);
}
// Single-element side uses linear scan to avoid sorting both arrays.
if (v4a.length > 0 && v4b.length > 0) {
if (v4a.length === 1 || v4b.length === 1) {
const bIsSingle = v4b.length === 1;
const one = bIsSingle ? v4b[0] : v4a[0];
for (const el of bIsSingle ? v4a : v4b) {
if (one.start <= el.end && el.start <= one.end) return true;
}
} else {
v4a.sort(cmpV4Start);
v4b.sort(cmpV4Start);
let i = 0, j = 0;
while (i < v4a.length && j < v4b.length) {
if (v4a[i].start <= v4b[j].end && v4b[j].start <= v4a[i].end) return true;
if (v4a[i].end < v4b[j].end) i++; else j++;
}
}
}
if (v6a.length > 0 && v6b.length > 0) {
if (v6a.length === 1 || v6b.length === 1) {
const bIsSingle = v6b.length === 1;
const one = bIsSingle ? v6b[0] : v6a[0];
for (const el of bIsSingle ? v6a : v6b) {
if (one.start <= el.end && el.start <= one.end) return true;
}
} else {
v6a.sort(cmpV6Start);
v6b.sort(cmpV6Start);
let i = 0, j = 0;
while (i < v6a.length && j < v6b.length) {
if (v6a[i].start <= v6b[j].end && v6b[j].start <= v6a[i].end) return true;
if (v6a[i].end < v6b[j].end) i++; else j++;
}
}
}
return false;
}
/** Returns a boolean that indicates whether `networksA` fully contain all `networksB`. */
export function containsCidr(a: Networks, b: Networks, opts?: CidrOpts): boolean {
checkNetworks(a, opts);
checkNetworks(b, opts);
// Fast path for single-vs-single (most common case)
if (typeof a === "string" && typeof b === "string") {
// Zero-allocation IPv4 fast path
if (parseIPv4Range(a)) {
const startA = rangeV4Start, endA = rangeV4End;
if (parseIPv4Range(b)) {
return startA <= rangeV4Start && endA >= rangeV4End;
}
const pb = parseCidrLeanSlow(b);
if (pb.version !== 4) return false;
return startA <= pb.start && endA >= pb.end;
}
const pa = parseCidrLeanSlow(a);
const pb = parseCidrLean(b);
if (pa.version !== pb.version) return false;
return pa.start <= pb.start && pa.end >= pb.end;
}
const v4a: LeanParsedCidr4[] = [], v6a: LeanParsedCidr6[] = [];
const v4b: LeanParsedCidr4[] = [], v6b: LeanParsedCidr6[] = [];
for (const str of typeof a === "string" ? [a] : a) {
const net = parseCidrLean(str);
if (net.version === 4) v4a.push(net); else v6a.push(net);
}
for (const str of typeof b === "string" ? [b] : b) {
const net = parseCidrLean(str);
if (net.version === 4) v4b.push(net); else v6b.push(net);
}
// A target is contained iff the union of containers covers it. Fast path: a single
// container covers it (no sort needed). Otherwise sort once and sweep contiguous
// coverage, which coalesces adjacent blocks so blocks that tile a target also count.
if (v4b.length > 0) {
if (v4a.length === 0) return false;
let sorted = false;
for (const target of v4b) {
const ts = target.start, te = target.end;
let covered = false;
for (const iv of v4a) {
if (iv.start > ts || iv.end < te) continue;
covered = true; break;
}
if (covered) continue;
if (!sorted) { v4a.sort(cmpV4Start); sorted = true; }
let cur = ts;
for (const iv of v4a) {
if (iv.start > cur) break;
if (iv.end >= cur) {
if (iv.end >= te) { covered = true; break; }
cur = iv.end + 1;
}
}
if (!covered) return false;
}
}
if (v6b.length > 0) {
if (v6a.length === 0) return false;
let sorted = false;
for (const target of v6b) {
const ts = target.start, te = target.end;
let covered = false;
for (const iv of v6a) {
if (iv.start > ts || iv.end < te) continue;
covered = true; break;
}
if (covered) continue;
if (!sorted) { v6a.sort(cmpV6Start); sorted = true; }
let cur = ts;
for (const iv of v6a) {
if (iv.start > cur) break;
if (iv.end >= cur) {
if (iv.end >= te) { covered = true; break; }
cur = iv.end + 1n;
}
}
if (!covered) return false;
}
}
return true;
}
export default {
mergeCidr,
excludeCidr,
expandCidr,
overlapCidr,
containsCidr,
normalizeCidr,
parseCidr,
};