Skip to content

Commit f9286b7

Browse files
authored
Assert filterDateRange input is sorted ascending (#38)
The binary-search filterDateRange overload assumes its collection is sorted ascending by startDate, but returns silently-wrong results otherwise. Add a debug-only assert enforcing that contract (compiled out of release builds, so no runtime cost). This immediately surfaced an existing violation: testGlucoseEffectFromHistory built a `basal` schedule with segments out of order (and one with endDate before startDate, plus overlaps). Replace it with a well-formed sorted, contiguous, non-overlapping schedule, and regenerate the expected-effect fixture to match the corrected schedule.
1 parent 925e672 commit f9286b7

3 files changed

Lines changed: 114 additions & 107 deletions

File tree

Sources/LoopAlgorithm/SampleValue.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,13 @@ public extension Sequence where Element: TimelineValue {
111111
public extension RandomAccessCollection where Element: TimelineValue, Index == Int {
112112
func filterDateRange(_ startDate: Date?, _ endDate: Date?) -> [Element] {
113113
guard !isEmpty else { return [] }
114+
// This binary-search filter is only correct when the elements are sorted
115+
// ascending by startDate. Catch contract violations in debug builds; the
116+
// check is compiled out of release builds, so there is no runtime cost.
117+
assert(
118+
zip(self, dropFirst()).allSatisfy { $0.startDate <= $1.startDate },
119+
"filterDateRange requires elements sorted ascending by startDate"
120+
)
114121
// Lower bound: first index where element.endDate >= startDate
115122
var lo = startIndex
116123
if let startDate {

0 commit comments

Comments
 (0)