From f846fd46d1986f8788535501a429bcb1abe6d16e Mon Sep 17 00:00:00 2001 From: Alicia Sykes Date: Sun, 31 Aug 2025 20:04:33 +0100 Subject: [PATCH] unary set calculations --- src/lib/components/CIDRContains.svelte | 976 ++++++++++++++++++ src/lib/components/CIDRDiff.svelte | 87 +- src/lib/components/CIDROverlap.svelte | 931 +++++++++++++++++ src/lib/components/CIDRSplitter.svelte | 8 +- src/lib/components/Icon.svelte | 8 + src/lib/components/SubHeader.svelte | 9 +- src/lib/constants/nav.ts | 27 +- src/lib/utils/cidr-contains.ts | 378 +++++++ src/lib/utils/cidr-overlap.ts | 274 +++++ src/routes/cidr/diff/+page.svelte | 500 --------- src/routes/cidr/set-operations/+layout.svelte | 396 +++++++ .../cidr/set-operations/contains/+page.svelte | 17 + .../cidr/set-operations/diff/+page.svelte | 17 + .../cidr/set-operations/overlap/+page.svelte | 17 + src/styles/converters.scss | 2 +- 15 files changed, 3104 insertions(+), 543 deletions(-) create mode 100644 src/lib/components/CIDRContains.svelte create mode 100644 src/lib/components/CIDROverlap.svelte create mode 100644 src/lib/utils/cidr-contains.ts create mode 100644 src/lib/utils/cidr-overlap.ts delete mode 100644 src/routes/cidr/diff/+page.svelte create mode 100644 src/routes/cidr/set-operations/+layout.svelte create mode 100644 src/routes/cidr/set-operations/contains/+page.svelte create mode 100644 src/routes/cidr/set-operations/diff/+page.svelte create mode 100644 src/routes/cidr/set-operations/overlap/+page.svelte diff --git a/src/lib/components/CIDRContains.svelte b/src/lib/components/CIDRContains.svelte new file mode 100644 index 0000000..17ec6ce --- /dev/null +++ b/src/lib/components/CIDRContains.svelte @@ -0,0 +1,976 @@ + + +
+
+

CIDR Containment Checker

+

Check if set A fully contains each item in set B. Supports many-to-many containment analysis with detailed classification.

+
+ + +
+

Options

+
+ + +
+
+ + +
+
+ +
+

+ Set A (Containers) + + + +

+
+ +
+
+ + +
+

+ Set B (Candidates) + + + +

+
+ +
+
+
+ +
+ +
+ + +
+

Quick Examples

+
+ {#each examples as example} + + {/each} +
+
+
+ + + {#if result} +
+ {#if result.errors.length > 0} +
+

Parse Errors

+
    + {#each result.errors as error} +
  • {error}
  • + {/each} +
+
+ {/if} + + {#if result.checks.length > 0} + +
+
+

Containment Analysis

+
+ + +
+
+ +
+
+ Containers (A) + {result.stats.setA.count} items + {result.stats.setA.addresses} addresses +
+
+ Candidates (B) + {result.stats.totalChecked} items + checked for containment +
+
+ Inside + {result.stats.inside} + fully contained +
+
+ Equal + {result.stats.equal} + exact matches +
+
+ Partial + {result.stats.partial} + partial overlap +
+
+ Outside + {result.stats.outside} + no overlap +
+
+
+ + +
+

Containment Results

+
+
+
Candidate
+
Status
+
Coverage
+
Containers
+
Gaps
+
+ + {#each result.checks as check} + {@const statusInfo = getStatusInfo(check.status)} +
+
+ {check.input} +
+
+
+ + {statusInfo.label} +
+
+
+
+
+ {check.coverage}% +
+
+
+ {#if check.matchingContainers.length > 0} +
+ {#each check.matchingContainers as container} + {container} + {/each} +
+ {:else} + - + {/if} +
+
+ {#if check.gaps.length > 0} +
+ {#each check.gaps as gap} + {gap} + {/each} +
+ + {:else} + - + {/if} +
+
+ {/each} +
+
+ + + {#if result.visualization.length > 0} +
+

Containment Visualization

+
+
+
+ Candidate Range +
+
+
+ Container Coverage +
+
+
+ Uncovered Gaps +
+
+ +
+ {#each result.visualization as viz, index} + {@const check = result.checks[index]} + {@const statusInfo = getStatusInfo(check.status)} +
+
+ {viz.candidate} +
+ + {statusInfo.label} ({check.coverage}%) +
+
+ +
+ +
+
+
+ + +
+ {#each viz.containers as container} +
+ {/each} +
+ + +
+ {#each viz.gaps as gap} +
+ {/each} +
+
+
+ {/each} +
+
+ {/if} + {/if} +
+ {/if} +
+ + \ No newline at end of file diff --git a/src/lib/components/CIDRDiff.svelte b/src/lib/components/CIDRDiff.svelte index d37b56b..628c9a0 100644 --- a/src/lib/components/CIDRDiff.svelte +++ b/src/lib/components/CIDRDiff.svelte @@ -12,6 +12,8 @@ let constrainedPrefix = $state(24); let result = $state(null); let copiedStates = $state>({}); + let selectedExample = $state(null); + let userModified = $state(false); const alignmentModes = [ { @@ -57,6 +59,8 @@ function setExample(example: typeof examples[0]) { setA = example.setA; setB = example.setB; + selectedExample = example.label; + userModified = false; performDiff(); } @@ -158,6 +162,13 @@ return `Set ${type}\nRange: ${startIP} - ${endIP}\nSize: ${size.toLocaleString()}${range.cidr ? `\nCIDR: ${range.cidr}` : ''}`; } + // Track user modifications + $effect(() => { + if (userModified) { + selectedExample = null; + } + }); + // Reactive computation $effect(() => { if (setA.trim()) { @@ -203,6 +214,7 @@ id="constrained-prefix" type="number" bind:value={constrainedPrefix} + oninput={() => userModified = true} min="8" max="30" class="input-field constraint-field" @@ -225,6 +237,7 @@
+
+ + + +
+

+ Set B + + + +

+
+ +
+
+ + +
+ +
+ + +
+

Quick Examples

+
+ {#each examples as example} + + {/each} +
+
+ + + + {#if result} +
+ {#if result.errors.length > 0} +
+

Parse Errors

+
    + {#each result.errors as error} +
  • {error}
  • + {/each} +
+
+ {/if} + + +
+
+
+ +
+
+

{result.hasOverlap ? 'Overlap Detected' : 'No Overlap'}

+

+ {result.hasOverlap + ? `Sets A and B have overlapping address ranges (${result.stats.overlapPercent}% of smaller set)` + : 'Sets A and B do not share any common address ranges' + } +

+
+
+
+ + {#if !showOnlyBoolean && (result.ipv4.length > 0 || result.ipv6.length > 0)} + +
+
+

Intersection Results (A ∩ B)

+
+ + +
+
+ +
+
+ Set A + {result.stats.setA.count} items + {result.stats.setA.addresses} addresses +
+
+ Set B + {result.stats.setB.count} items + {result.stats.setB.addresses} addresses +
+
+ Intersection + {result.stats.intersection.count} CIDRs + {result.stats.intersection.addresses} addresses +
+
+ Overlap + {result.stats.overlapPercent}% + of smaller set +
+
+
+ + + {#if result.visualization.setA.length > 0 || result.visualization.setB.length > 0} +
+

Overlap Visualization

+
+
+
+ Set A +
+
+
+ Set B +
+
+
+ Intersection (A ∩ B) +
+
+ +
+ +
+
Set A
+
+ {#each result.visualization.setA as range} +
+ {/each} +
+
+ + +
+
Set B
+
+ {#each result.visualization.setB as range} +
+ {/each} +
+
+ + +
+
A ∩ B
+
+ {#each result.visualization.intersection as range} +
+ {/each} +
+
+
+
+ {/if} + + +
+ + {#if result.ipv4.length > 0} +
+
+

IPv4 Intersection ({result.ipv4.length})

+ +
+
+ {#each result.ipv4 as cidr} +
+ {cidr} + +
+ {/each} +
+
+ {/if} + + + {#if result.ipv6.length > 0} +
+
+

IPv6 Intersection ({result.ipv6.length})

+ +
+
+ {#each result.ipv6 as cidr} +
+ {cidr} + +
+ {/each} +
+
+ {/if} +
+ {/if} +
+ {/if} + + + \ No newline at end of file diff --git a/src/lib/components/CIDRSplitter.svelte b/src/lib/components/CIDRSplitter.svelte index ba05076..b25b47e 100644 --- a/src/lib/components/CIDRSplitter.svelte +++ b/src/lib/components/CIDRSplitter.svelte @@ -506,13 +506,15 @@ .subnet-segment { position: absolute; height: 100%; - background: linear-gradient(45deg, var(--color-primary), var(--color-info)); - border-right: 1px solid var(--bg-primary); + background: linear-gradient(45deg, var(--color-primary), var(--color-primary-hover)); + border-right: 3px solid var(--bg-primary); transition: all var(--transition-fast); + opacity: 0.85; cursor: pointer; &:hover { filter: brightness(1.1); + opacity: 1; z-index: 2; } @@ -642,4 +644,4 @@ gap: var(--spacing-xs); } } - \ No newline at end of file + diff --git a/src/lib/components/Icon.svelte b/src/lib/components/Icon.svelte index df566c6..83c0de8 100644 --- a/src/lib/components/Icon.svelte +++ b/src/lib/components/Icon.svelte @@ -115,6 +115,14 @@ + {:else if name === 'union'} + + {:else if name === 'intersection'} + + {:else if name === 'diff'} + + {:else if name === 'containment'} + {:else} diff --git a/src/lib/components/SubHeader.svelte b/src/lib/components/SubHeader.svelte index f448505..ea7a47f 100644 --- a/src/lib/components/SubHeader.svelte +++ b/src/lib/components/SubHeader.svelte @@ -116,17 +116,10 @@ /* Mixed navigation styles */ .mixed-nav { display: flex; - gap: var(--spacing-xl); + gap: var(--spacing-md); flex-wrap: wrap; align-items: flex-start; } - - /* Grouped navigation styles (legacy) */ - .sub-nav-groups { - display: flex; - gap: var(--spacing-xl); - flex-wrap: wrap; - } .nav-group { display: flex; diff --git a/src/lib/constants/nav.ts b/src/lib/constants/nav.ts index 38e7948..2960279 100644 --- a/src/lib/constants/nav.ts +++ b/src/lib/constants/nav.ts @@ -78,11 +78,28 @@ export const SUB_NAV: Record = { description: 'Split a network into N equal child subnets or to a target prefix length', icon: 'subnet-splitter' }, - { - href: '/cidr/diff', - label: 'Set Difference', - description: 'Compute A - B set operations on CIDR blocks, ranges, and IP addresses', - icon: 'set-difference' + { + title: 'Set Operations', + items: [ + { + href: '/cidr/set-operations/diff', + label: 'Difference (A - B)', + description: 'Compute A - B set operations on CIDR blocks, ranges, and IP addresses', + icon: 'diff' + }, + { + href: '/cidr/set-operations/overlap', + label: 'Overlap (A ∩ B)', + description: 'Detect intersections between two sets of IP addresses and ranges', + icon: 'intersection' + }, + { + href: '/cidr/set-operations/contains', + label: 'Contains (A ⊆ B)', + description: 'Check if one set fully contains another with detailed containment analysis', + icon: 'containment' + } + ] } ], '/ip-address-convertor': [ diff --git a/src/lib/utils/cidr-contains.ts b/src/lib/utils/cidr-contains.ts new file mode 100644 index 0000000..d0cbc15 --- /dev/null +++ b/src/lib/utils/cidr-contains.ts @@ -0,0 +1,378 @@ +/* CIDR Contains Utilities */ + +import { parseInput, type IPRange, type ParsedInput } from './cidr-diff.js'; + +export type ContainmentStatus = 'inside' | 'equal' | 'partial' | 'outside'; + +export interface ContainmentCheck { + input: string; + status: ContainmentStatus; + gaps: string[]; // B - A (uncovered parts) if partial + coverage: number; // percentage of B covered by A + matchingContainers: string[]; // which A items contain this B +} + +export interface ContainsResult { + checks: ContainmentCheck[]; + stats: { + setA: { count: number; addresses: string }; + totalChecked: number; + inside: number; + equal: number; + partial: number; + outside: number; + }; + visualization: Array<{ + candidate: string; + candidateRange: { start: bigint; end: bigint }; + containers: Array<{ start: bigint; end: bigint; label: string }>; + gaps: Array<{ start: bigint; end: bigint; cidr: string }>; + totalRange: { start: bigint; end: bigint }; + version: 4 | 6; + }>; + errors: string[]; +} + +/* Convert bigint to IP address */ +function bigIntToIP(num: bigint, version: 4 | 6): string { + if (version === 4) { + const n = Number(num); + return [ + Math.floor(n / 16777216) % 256, + Math.floor(n / 65536) % 256, + Math.floor(n / 256) % 256, + n % 256 + ].join('.'); + } else { + const groups = []; + let remaining = num; + + for (let i = 0; i < 8; i++) { + groups.unshift((remaining & 0xffffn).toString(16)); + remaining >>= 16n; + } + + return groups.join(':'); + } +} + +/* Merge overlapping ranges */ +function mergeRanges(ranges: IPRange[]): IPRange[] { + if (ranges.length === 0) return []; + + const sorted = [...ranges].sort((a, b) => a.start < b.start ? -1 : 1); + const merged: IPRange[] = [sorted[0]]; + + for (let i = 1; i < sorted.length; i++) { + const current = sorted[i]; + const last = merged[merged.length - 1]; + + if (current.start <= last.end + 1n) { + last.end = current.end > last.end ? current.end : last.end; + } else { + merged.push(current); + } + } + + return merged; +} + +/* Subtract ranges B from ranges A */ +function subtractRanges(setA: IPRange[], setB: IPRange[]): IPRange[] { + if (setA.length === 0) return []; + if (setB.length === 0) return setA; + + let result: IPRange[] = [...setA]; + + for (const b of setB) { + const newResult: IPRange[] = []; + + for (const a of result) { + // No overlap + if (a.end < b.start || a.start > b.end) { + newResult.push(a); + continue; + } + + // B completely contains A + if (b.start <= a.start && b.end >= a.end) { + // A is completely removed + continue; + } + + // A completely contains B + if (a.start < b.start && a.end > b.end) { + // Split A into two ranges + newResult.push({ start: a.start, end: b.start - 1n, version: a.version }); + newResult.push({ start: b.end + 1n, end: a.end, version: a.version }); + continue; + } + + // Partial overlap - left side of A remains + if (a.start < b.start && a.end >= b.start) { + newResult.push({ start: a.start, end: b.start - 1n, version: a.version }); + } + + // Partial overlap - right side of A remains + if (a.start <= b.end && a.end > b.end) { + newResult.push({ start: b.end + 1n, end: a.end, version: a.version }); + } + } + + result = newResult; + } + + return result; +} + +/* Convert range to CIDR blocks */ +function rangeToCIDRs(range: IPRange): string[] { + const cidrs: string[] = []; + let start = range.start; + const end = range.end; + const maxPrefix = range.version === 4 ? 32 : 128; + + // Safety counter + let iterations = 0; + const maxIterations = 1000; + + while (start <= end && iterations < maxIterations) { + iterations++; + + let prefixLength = maxPrefix; + let blockSize = 1n; + + // Find largest aligned block that fits + for (let p = 0; p < maxPrefix; p++) { + const testBlockSize = 1n << BigInt(p); + const alignedStart = start & ~(testBlockSize - 1n); + + if (alignedStart === start && start + testBlockSize - 1n <= end) { + blockSize = testBlockSize; + prefixLength = maxPrefix - p; + } else { + break; + } + } + + const ip = bigIntToIP(start, range.version); + cidrs.push(`${ip}/${prefixLength}`); + + start += blockSize; + } + + if (iterations >= maxIterations) { + const ip = bigIntToIP(range.start, range.version); + return [`${ip}/${maxPrefix}`]; + } + + return cidrs; +} + +/* Calculate total addresses in ranges */ +function calculateTotalAddresses(ranges: IPRange[]): bigint { + return ranges.reduce((total, range) => { + return total + (range.end - range.start + 1n); + }, 0n); +} + +/* Check containment status for a single candidate against containers */ +function checkContainment( + candidate: IPRange, + containers: IPRange[], + originalInputs: ParsedInput[], + strictEquality: boolean = false +): ContainmentCheck { + const candidateSize = candidate.end - candidate.start + 1n; + let coveredRanges: IPRange[] = []; + const matchingContainers: string[] = []; + + // Find all containers that overlap with candidate + for (let i = 0; i < containers.length; i++) { + const container = containers[i]; + + // Check if container overlaps with candidate + const overlapStart = candidate.start > container.start ? candidate.start : container.start; + const overlapEnd = candidate.end < container.end ? candidate.end : container.end; + + if (overlapStart <= overlapEnd) { + // There's an overlap + coveredRanges.push({ + start: overlapStart, + end: overlapEnd, + version: candidate.version + }); + + // Check if this container fully contains the candidate + if (container.start <= candidate.start && container.end >= candidate.end) { + matchingContainers.push(originalInputs[i]?.ip || `${bigIntToIP(container.start, container.version)}`); + } + } + } + + // Merge covered ranges to avoid double-counting + const mergedCovered = mergeRanges(coveredRanges); + const coveredSize = calculateTotalAddresses(mergedCovered); + const coverage = candidateSize > 0 ? Number((coveredSize * 100n) / candidateSize) : 0; + + // Calculate gaps (uncovered parts) + const gaps = subtractRanges([candidate], mergedCovered); + const gapCIDRs = gaps.flatMap(rangeToCIDRs); + + // Determine status + let status: ContainmentStatus; + + if (coverage === 0) { + status = 'outside'; + } else if (coverage === 100) { + // Check for exact equality + if (strictEquality && mergedCovered.length === 1 && + mergedCovered[0].start === candidate.start && + mergedCovered[0].end === candidate.end) { + status = 'equal'; + } else { + status = 'inside'; + } + } else { + status = 'partial'; + } + + return { + input: '', // Will be filled by caller + status, + gaps: gapCIDRs, + coverage: Math.round(coverage), + matchingContainers + }; +} + +/* Main CIDR contains function */ +export function computeCIDRContains( + inputA: string, // containers + inputB: string, // candidates + mergeContainers: boolean = true, + strictEquality: boolean = false +): ContainsResult { + const linesA = inputA.trim().split('\n').filter(line => line.trim()); + const linesB = inputB.trim().split('\n').filter(line => line.trim()); + + const parsedA: ParsedInput[] = []; + const parsedB: ParsedInput[] = []; + const errors: string[] = []; + + // Parse inputs + linesA.forEach((line, index) => { + try { + parsedA.push(parseInput(line)); + } catch (error) { + errors.push(`Set A line ${index + 1}: ${error instanceof Error ? error.message : 'Parse error'}`); + } + }); + + linesB.forEach((line, index) => { + try { + parsedB.push(parseInput(line)); + } catch (error) { + errors.push(`Set B line ${index + 1}: ${error instanceof Error ? error.message : 'Parse error'}`); + } + }); + + // Separate by version + const ipv4RangesA = parsedA.filter(p => p.version === 4).map(p => p.range); + const ipv6RangesA = parsedA.filter(p => p.version === 6).map(p => p.range); + const ipv4ParsedA = parsedA.filter(p => p.version === 4); + const ipv6ParsedA = parsedA.filter(p => p.version === 6); + + // Merge containers if requested + const containersA4 = mergeContainers ? mergeRanges(ipv4RangesA) : ipv4RangesA; + const containersA6 = mergeContainers ? mergeRanges(ipv6RangesA) : ipv6RangesA; + + // Process each candidate + const checks: ContainmentCheck[] = []; + const visualization: ContainsResult['visualization'] = []; + + // Counters + let inside = 0, equal = 0, partial = 0, outside = 0; + + for (const candidateInput of parsedB) { + const containers = candidateInput.version === 4 ? containersA4 : containersA6; + const originalContainers = candidateInput.version === 4 ? ipv4ParsedA : ipv6ParsedA; + + const check = checkContainment(candidateInput.range, containers, originalContainers, strictEquality); + check.input = candidateInput.ip; + checks.push(check); + + // Update counters + switch (check.status) { + case 'inside': inside++; break; + case 'equal': equal++; break; + case 'partial': partial++; break; + case 'outside': outside++; break; + } + + // Create visualization data + const candidateRange = candidateInput.range; + const vizContainers = containers.map((c, i) => ({ + start: c.start, + end: c.end, + label: originalContainers[i]?.ip || `Container ${i + 1}` + })); + + // Calculate gaps for visualization + const coveredRanges: IPRange[] = []; + for (const container of containers) { + const overlapStart = candidateRange.start > container.start ? candidateRange.start : container.start; + const overlapEnd = candidateRange.end < container.end ? candidateRange.end : container.end; + + if (overlapStart <= overlapEnd) { + coveredRanges.push({ + start: overlapStart, + end: overlapEnd, + version: candidateRange.version + }); + } + } + + const gaps = subtractRanges([candidateRange], mergeRanges(coveredRanges)); + + // Find total range for visualization + const allRanges = [candidateRange, ...containers, ...gaps]; + const totalStart = allRanges.reduce((min, r) => r.start < min ? r.start : min, allRanges[0].start); + const totalEnd = allRanges.reduce((max, r) => r.end > max ? r.end : max, allRanges[0].end); + + visualization.push({ + candidate: candidateInput.ip, + candidateRange: { start: candidateRange.start, end: candidateRange.end }, + containers: vizContainers, + gaps: gaps.map(g => ({ + start: g.start, + end: g.end, + cidr: rangeToCIDRs(g)[0] || `${bigIntToIP(g.start, g.version)}/${g.version === 4 ? 32 : 128}` + })), + totalRange: { start: totalStart, end: totalEnd }, + version: candidateRange.version + }); + } + + // Calculate stats + const totalA4 = calculateTotalAddresses(containersA4); + const totalA6 = calculateTotalAddresses(containersA6); + const totalSetA = totalA4 + totalA6; + + return { + checks, + stats: { + setA: { + count: ipv4RangesA.length + ipv6RangesA.length, + addresses: totalSetA.toLocaleString() + }, + totalChecked: checks.length, + inside, + equal, + partial, + outside + }, + visualization, + errors + }; +} \ No newline at end of file diff --git a/src/lib/utils/cidr-overlap.ts b/src/lib/utils/cidr-overlap.ts new file mode 100644 index 0000000..669fd93 --- /dev/null +++ b/src/lib/utils/cidr-overlap.ts @@ -0,0 +1,274 @@ +/* CIDR Overlap Utilities */ + +import { parseInput, type IPRange, type ParsedInput } from './cidr-diff.js'; + +export interface OverlapResult { + hasOverlap: boolean; + ipv4: string[]; + ipv6: string[]; + stats: { + setA: { count: number; addresses: string }; + setB: { count: number; addresses: string }; + intersection: { count: number; addresses: string }; + overlapPercent: number; + }; + visualization: { + setA: Array<{ start: bigint; end: bigint }>; + setB: Array<{ start: bigint; end: bigint }>; + intersection: Array<{ start: bigint; end: bigint; cidr: string }>; + version: 4 | 6; + totalRange: { start: bigint; end: bigint }; + }; + errors: string[]; +} + +/* Convert bigint to IP address */ +function bigIntToIP(num: bigint, version: 4 | 6): string { + if (version === 4) { + const n = Number(num); + return [ + Math.floor(n / 16777216) % 256, + Math.floor(n / 65536) % 256, + Math.floor(n / 256) % 256, + n % 256 + ].join('.'); + } else { + const groups = []; + let remaining = num; + + for (let i = 0; i < 8; i++) { + groups.unshift((remaining & 0xffffn).toString(16)); + remaining >>= 16n; + } + + return groups.join(':'); + } +} + +/* Merge overlapping ranges */ +function mergeRanges(ranges: IPRange[]): IPRange[] { + if (ranges.length === 0) return []; + + const sorted = [...ranges].sort((a, b) => a.start < b.start ? -1 : 1); + const merged: IPRange[] = [sorted[0]]; + + for (let i = 1; i < sorted.length; i++) { + const current = sorted[i]; + const last = merged[merged.length - 1]; + + if (current.start <= last.end + 1n) { + last.end = current.end > last.end ? current.end : last.end; + } else { + merged.push(current); + } + } + + return merged; +} + +/* Find intersection of two range sets */ +function findIntersection(setA: IPRange[], setB: IPRange[]): IPRange[] { + const intersections: IPRange[] = []; + + for (const a of setA) { + for (const b of setB) { + // Check if ranges overlap + const start = a.start > b.start ? a.start : b.start; + const end = a.end < b.end ? a.end : b.end; + + if (start <= end) { + intersections.push({ + start, + end, + version: a.version + }); + } + } + } + + return mergeRanges(intersections); +} + +/* Convert range to CIDR blocks */ +function rangeToCIDRs(range: IPRange): string[] { + const cidrs: string[] = []; + let start = range.start; + const end = range.end; + const maxPrefix = range.version === 4 ? 32 : 128; + + // Safety counter + let iterations = 0; + const maxIterations = 1000; + + while (start <= end && iterations < maxIterations) { + iterations++; + + let prefixLength = maxPrefix; + let blockSize = 1n; + + // Find largest aligned block that fits + for (let p = 0; p < maxPrefix; p++) { + const testBlockSize = 1n << BigInt(p); + const alignedStart = start & ~(testBlockSize - 1n); + + if (alignedStart === start && start + testBlockSize - 1n <= end) { + blockSize = testBlockSize; + prefixLength = maxPrefix - p; + } else { + break; + } + } + + const ip = bigIntToIP(start, range.version); + cidrs.push(`${ip}/${prefixLength}`); + + start += blockSize; + } + + if (iterations >= maxIterations) { + const ip = bigIntToIP(range.start, range.version); + return [`${ip}/${maxPrefix}`]; + } + + return cidrs; +} + +/* Calculate total addresses in ranges */ +function calculateTotalAddresses(ranges: IPRange[]): bigint { + return ranges.reduce((total, range) => { + return total + (range.end - range.start + 1n); + }, 0n); +} + +/* Create visualization data */ +function createVisualization( + setA: IPRange[], + setB: IPRange[], + intersection: IPRange[], + version: 4 | 6 +): OverlapResult['visualization'] { + const allRanges = [...setA, ...setB, ...intersection]; + if (allRanges.length === 0) { + return { + setA: [], + setB: [], + intersection: [], + version, + totalRange: { start: 0n, end: 0n } + }; + } + + const totalStart = allRanges.reduce((min, r) => r.start < min ? r.start : min, allRanges[0].start); + const totalEnd = allRanges.reduce((max, r) => r.end > max ? r.end : max, allRanges[0].end); + + return { + setA: setA.map(r => ({ start: r.start, end: r.end })), + setB: setB.map(r => ({ start: r.start, end: r.end })), + intersection: intersection.map(r => ({ + start: r.start, + end: r.end, + cidr: rangeToCIDRs(r)[0] || `${bigIntToIP(r.start, version)}/${version === 4 ? 32 : 128}` + })), + version, + totalRange: { start: totalStart, end: totalEnd } + }; +} + +/* Main CIDR overlap function */ +export function computeCIDROverlap( + inputA: string, + inputB: string, + mergeInputs: boolean = true +): OverlapResult { + const linesA = inputA.trim().split('\n').filter(line => line.trim()); + const linesB = inputB.trim().split('\n').filter(line => line.trim()); + + const parsedA: ParsedInput[] = []; + const parsedB: ParsedInput[] = []; + const errors: string[] = []; + + // Parse inputs + linesA.forEach((line, index) => { + try { + parsedA.push(parseInput(line)); + } catch (error) { + errors.push(`Set A line ${index + 1}: ${error instanceof Error ? error.message : 'Parse error'}`); + } + }); + + linesB.forEach((line, index) => { + try { + parsedB.push(parseInput(line)); + } catch (error) { + errors.push(`Set B line ${index + 1}: ${error instanceof Error ? error.message : 'Parse error'}`); + } + }); + + // Separate by version + const ipv4RangesA = parsedA.filter(p => p.version === 4).map(p => p.range); + const ipv6RangesA = parsedA.filter(p => p.version === 6).map(p => p.range); + const ipv4RangesB = parsedB.filter(p => p.version === 4).map(p => p.range); + const ipv6RangesB = parsedB.filter(p => p.version === 6).map(p => p.range); + + // Optionally merge overlapping ranges within each set + const setA4 = mergeInputs ? mergeRanges(ipv4RangesA) : ipv4RangesA; + const setA6 = mergeInputs ? mergeRanges(ipv6RangesA) : ipv6RangesA; + const setB4 = mergeInputs ? mergeRanges(ipv4RangesB) : ipv4RangesB; + const setB6 = mergeInputs ? mergeRanges(ipv6RangesB) : ipv6RangesB; + + // Find intersections + const intersection4 = findIntersection(setA4, setB4); + const intersection6 = findIntersection(setA6, setB6); + + // Convert to CIDRs + const ipv4CIDRs = intersection4.flatMap(rangeToCIDRs).sort(); + const ipv6CIDRs = intersection6.flatMap(rangeToCIDRs).sort(); + + // Check if there's any overlap + const hasOverlap = intersection4.length > 0 || intersection6.length > 0; + + // Calculate statistics + const totalA4 = calculateTotalAddresses(setA4); + const totalA6 = calculateTotalAddresses(setA6); + const totalB4 = calculateTotalAddresses(setB4); + const totalB6 = calculateTotalAddresses(setB6); + const totalInt4 = calculateTotalAddresses(intersection4); + const totalInt6 = calculateTotalAddresses(intersection6); + + const totalSetA = totalA4 + totalA6; + const totalSetB = totalB4 + totalB6; + const totalIntersection = totalInt4 + totalInt6; + + // Calculate overlap percentage (intersection / smaller set) + const smallerSet = totalSetA < totalSetB ? totalSetA : totalSetB; + const overlapPercent = smallerSet > 0 ? Number((totalIntersection * 100n) / smallerSet) : 0; + + // Create visualization (prefer IPv4 if available) + const vizVersion = setA4.length > 0 || setB4.length > 0 ? 4 : 6; + const vizA = vizVersion === 4 ? setA4 : setA6; + const vizB = vizVersion === 4 ? setB4 : setB6; + const vizIntersection = vizVersion === 4 ? intersection4 : intersection6; + + return { + hasOverlap, + ipv4: ipv4CIDRs, + ipv6: ipv6CIDRs, + stats: { + setA: { + count: ipv4RangesA.length + ipv6RangesA.length, + addresses: totalSetA.toLocaleString() + }, + setB: { + count: ipv4RangesB.length + ipv6RangesB.length, + addresses: totalSetB.toLocaleString() + }, + intersection: { + count: ipv4CIDRs.length + ipv6CIDRs.length, + addresses: totalIntersection.toLocaleString() + }, + overlapPercent: Math.round(overlapPercent) + }, + visualization: createVisualization(vizA, vizB, vizIntersection, vizVersion), + errors + }; +} \ No newline at end of file diff --git a/src/routes/cidr/diff/+page.svelte b/src/routes/cidr/diff/+page.svelte deleted file mode 100644 index 351db84..0000000 --- a/src/routes/cidr/diff/+page.svelte +++ /dev/null @@ -1,500 +0,0 @@ - - - - CIDR Set Difference Calculator - Compute A - B Operations | {site.title} - - - - - - - -
- - -
-

About CIDR Set Operations

-

- Set operations allow you to combine, subtract, and analyze IP address ranges mathematically. - The difference operation (A - B) returns all addresses in set A that are NOT in set B. -

- -
-

Set Operations Quick Reference

-
-
-
A ∪ B
-
Union
-
All addresses in A OR B
-
-
-
A ∩ B
-
Intersection
-
Addresses in BOTH A AND B
-
-
-
A - B
-
Difference
-
Addresses in A but NOT in B
-
-
-
A ⊆ B
-
Containment
-
Check if A is subset of B
-
-
-
- -
-

Worked Examples

- -
-
IPv4 Network Segmentation
-
-
- Set A: 192.168.1.0/24 (256 addresses)
- Set B: 192.168.1.128/25 (128 addresses) -
-
↓
-
- A - B: 192.168.1.0/25 (128 addresses)
- The first half remains after subtracting the second half -
-
-
- -
-
IPv6 Address Management
-
-
- Set A: 2001:db8::/48 (entire /48 block)
- Set B: 2001:db8:1::/64 (single /64 subnet) -
-
↓
-
- A - B: Multiple CIDR blocks excluding the /64
- All /48 addresses except the allocated /64 subnet -
-
-
- -
-
Complex Range Operations
-
-
- Set A: 10.0.0.0/16 (65,536 addresses)
- Set B: 10.0.10.0/24, 10.0.20.50-10.0.20.100 -
-
↓
-
- A - B: Multiple optimized CIDR blocks
- Original /16 with specific ranges carved out -
-
-
-
- -
-

Edge Cases & Considerations

-
-
-
Non-aligned Ranges
-

- When subtracting ranges that don't align to CIDR boundaries, the result may - require multiple smaller CIDR blocks to represent exactly. -

-
-
-
Duplicate Inputs
-

- Overlapping ranges in the same set are automatically merged before processing. - 10.0.0.0/24 + 10.0.0.128/25 = 10.0.0.0/24 -

-
-
-
Mixed IP Families
-

- IPv4 and IPv6 addresses are processed separately. You cannot subtract - IPv6 ranges from IPv4 ranges (and vice versa). -

-
-
-
Empty Results
-

- If set B completely contains set A, the result is empty. For example: - 192.168.1.0/25 - 192.168.1.0/24 = ∅ -

-
-
-
- -
-

Alignment Modes

-
-
-
Minimal Alignment
-

- Generates the most efficient CIDR representation with the fewest blocks. - Uses variable prefix lengths to exactly cover the result ranges. -

-
- Example: Result might use /25, /26, /30 prefixes for optimal coverage -
-
-
-
Constrained Alignment
-

- Forces results to align to specific prefix boundaries. Useful for - organizational policies or routing requirements. -

-
- Example: Force all results to /24 boundaries, may require more blocks -
-
-
-
- -
-

Common Use Cases

-
-
- -
- Firewall Rules: Define allowed ranges by subtracting blocked addresses -
-
-
- -
- IP Allocation: Track available addresses after assignments -
-
-
- -
- Cloud Networks: Reserve address space while excluding system ranges -
-
-
- -
- Network Analysis: Calculate unused address space in allocations -
-
-
-
- -
-

Understanding the Visualization

-
-

- The overlay visualization shows how set operations work spatially across the address space: -

-
    -
  • Blue bars: Set A (base ranges) - your starting address space
  • -
  • Orange overlay: Set B (subtract ranges) - what gets removed
  • -
  • Green segments: Final result - remaining address ranges
  • -
  • Hover details: Shows exact IP ranges, sizes, and CIDR notations
  • -
-

- - Tip: The visualization helps you understand why certain results - require multiple CIDR blocks - they represent the "holes" left after subtraction. -

-
-
-
-
- - diff --git a/src/routes/cidr/set-operations/+layout.svelte b/src/routes/cidr/set-operations/+layout.svelte new file mode 100644 index 0000000..38d3214 --- /dev/null +++ b/src/routes/cidr/set-operations/+layout.svelte @@ -0,0 +1,396 @@ + + + + +
+

Set Operations Reference

+

+ Mathematical set operations allow you to combine, analyze, and manipulate IP address ranges + systematically. Each operation serves different network analysis and management purposes. +

+ +
+
+
+
A ∪ B
+
Union
+
+
+ Combines all addresses from both sets. Results in addresses that are in A OR B. + Useful for merging address allocations or creating comprehensive allow-lists. +
+
+ Example: 192.168.1.0/24 ∪ 192.168.2.0/24 = both networks +
+
+ +
+
+
A ∩ B
+
Intersection
+
+
+ Finds common addresses between sets. Results in addresses that are in BOTH A AND B. + Essential for identifying conflicts or overlapping allocations. +
+
+ Example: 192.168.0.0/16 ∩ 192.168.1.0/24 = 192.168.1.0/24 +
+
+ +
+
+
A - B
+
Difference
+
+
+ Removes B's addresses from A. Results in addresses that are in A but NOT in B. + Critical for calculating remaining capacity or excluding reserved ranges. +
+
+ Example: 192.168.1.0/24 - 192.168.1.128/25 = 192.168.1.0/25 +
+
+ +
+
+
A ⊆ B
+
Containment
+
+
+ Tests if A is completely contained within B. Returns boolean result plus coverage analysis. + Valuable for validating subnet hierarchies and allocation compliance. +
+
+ Example: 192.168.1.0/25 ⊆ 192.168.1.0/24 = true +
+
+
+ +
+

Common Network Patterns

+
+
+
Firewall Management
+
    +
  • Allow Lists: Union of trusted networks
  • +
  • Conflicts: Intersection of allow/deny rules
  • +
  • Exceptions: Difference to exclude specific ranges
  • +
+
+ +
+
IP Allocation
+
    +
  • Available Space: Difference from allocated ranges
  • +
  • Overlaps: Intersection of allocation requests
  • +
  • Validation: Containment within authorized blocks
  • +
+
+ +
+
Network Analysis
+
    +
  • Coverage: Union of monitoring ranges
  • +
  • Gaps: Difference to find unmonitored areas
  • +
  • Redundancy: Intersection of backup networks
  • +
+
+ +
+
Cloud Networks
+
    +
  • VPC Planning: Union of required address space
  • +
  • Peering: Intersection analysis for conflicts
  • +
  • Segmentation: Difference for isolation
  • +
+
+
+
+ +
+

Implementation Notes

+
+
+
IPv4 vs IPv6
+

+ All operations process IPv4 and IPv6 addresses separately. You cannot perform + set operations between different IP versions - they operate in distinct address spaces. +

+
+ +
+
CIDR Optimization
+

+ Results are automatically optimized into minimal CIDR representations. + Complex operations may require multiple CIDR blocks to exactly represent the result. +

+
+ +
+
Range Normalization
+

+ Input ranges are normalized and merged before operations. Overlapping inputs + within the same set are automatically combined for accurate results. +

+
+ +
+
Performance Considerations
+

+ Operations are optimized for network-sized ranges. Very large address spaces + or numerous small ranges may require additional processing time. +

+
+
+
+ +
+

Best Practices

+
+
+ +
+ Validate Inputs: Always verify CIDR notation and IP formats before operations +
+
+
+ +
+ Document Operations: Export results and maintain records of set operations +
+
+
+ +
+ Test in Stages: For complex operations, break into smaller steps for verification +
+
+
+ +
+ Monitor Results: Use visualization to verify operations produce expected outcomes +
+
+
+
+
+ + diff --git a/src/routes/cidr/set-operations/contains/+page.svelte b/src/routes/cidr/set-operations/contains/+page.svelte new file mode 100644 index 0000000..b947f79 --- /dev/null +++ b/src/routes/cidr/set-operations/contains/+page.svelte @@ -0,0 +1,17 @@ + + + + CIDR Containment Checker - Analyze Set Containment | {site.title} + + + + + + + +
+ +
\ No newline at end of file diff --git a/src/routes/cidr/set-operations/diff/+page.svelte b/src/routes/cidr/set-operations/diff/+page.svelte new file mode 100644 index 0000000..9e82b5e --- /dev/null +++ b/src/routes/cidr/set-operations/diff/+page.svelte @@ -0,0 +1,17 @@ + + + + CIDR Set Difference Calculator - Compute A - B Operations | {site.title} + + + + + + + +
+ +
diff --git a/src/routes/cidr/set-operations/overlap/+page.svelte b/src/routes/cidr/set-operations/overlap/+page.svelte new file mode 100644 index 0000000..318a908 --- /dev/null +++ b/src/routes/cidr/set-operations/overlap/+page.svelte @@ -0,0 +1,17 @@ + + + + CIDR Overlap Checker - Detect Set Intersections | {site.title} + + + + + + + +
+ +
\ No newline at end of file diff --git a/src/styles/converters.scss b/src/styles/converters.scss index 2de6b90..0e915fc 100644 --- a/src/styles/converters.scss +++ b/src/styles/converters.scss @@ -16,7 +16,7 @@ .input-group, .output-group { flex: 1; - max-width: 300px; + // max-width: 300px; @media (max-width: 768px) { width: 100%;