Skip to content

Commit f2bd4f8

Browse files
committed
fix: validate interval bounds in Union before appending
The Union function computes intersection intervals by taking max(start) and min(end) of two intervals. However, when intervals don't actually overlap (e.g., [90,95] and [80,88]), this produces invalid intervals where start > end (e.g., [90,88]). This causes a panic in TotalWhitespace when it tries to slice with invalid bounds: `lines[90:88]` -> "slice bounds out of range [90:88]" The fix validates that start <= end before appending to the result, which correctly handles non-overlapping intervals by excluding them. Added test cases for non-overlapping and adjacent intervals.
1 parent 02f4237 commit f2bd4f8

2 files changed

Lines changed: 29 additions & 4 deletions

File tree

interval/interval.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -98,10 +98,13 @@ func Union(a []Interval, b []Interval) []Interval {
9898
i++
9999
}
100100

101-
result = append(result, Interval{
102-
Start: start,
103-
End: end,
104-
})
101+
// Only append if the intervals actually overlap (start <= end)
102+
if start <= end {
103+
result = append(result, Interval{
104+
Start: start,
105+
End: end,
106+
})
107+
}
105108
}
106109

107110
return joinSortedIntervals(result)

interval/interval_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,28 @@ func TestUnion(t *testing.T) {
7777
{Start: 5, End: 5},
7878
},
7979
},
80+
{
81+
name: "non-overlapping intervals should produce empty result",
82+
a: []interval.Interval{
83+
{Start: 90, End: 95},
84+
},
85+
b: []interval.Interval{
86+
{Start: 80, End: 88},
87+
},
88+
e: []interval.Interval{},
89+
},
90+
{
91+
name: "adjacent but non-overlapping intervals",
92+
a: []interval.Interval{
93+
{Start: 10, End: 20},
94+
{Start: 50, End: 60},
95+
},
96+
b: []interval.Interval{
97+
{Start: 21, End: 30},
98+
{Start: 40, End: 49},
99+
},
100+
e: []interval.Interval{},
101+
},
80102
}
81103

82104
for _, tc := range testacses {

0 commit comments

Comments
 (0)