# HG changeset patch # User Paul Boddie # Date 1414358516 -3600 # Node ID 5b96860644e4017018103b574fd74c241d0957f3 # Parent 18ffda1dbfc10c6e6a2d822bee26089622c8457c Fixed period overlapping and conflicting functions to work as promised. diff -r 18ffda1dbfc1 -r 5b96860644e4 imiptools/period.py --- a/imiptools/period.py Sun Oct 26 19:44:25 2014 +0100 +++ b/imiptools/period.py Sun Oct 26 22:21:56 2014 +0100 @@ -14,12 +14,13 @@ conflicts = [] for start, end in periods: - period = period_overlaps(freebusy, (start, end)) - if period: + overlapping = period_overlaps(freebusy, (start, end), get_conflicts) + if overlapping: if get_conflicts: - conflicts.append(period) + conflicts += overlapping else: return True + if get_conflicts: return conflicts else: @@ -37,21 +38,44 @@ else: i += 1 -def period_overlaps(freebusy, period): +def period_overlaps(freebusy, period, get_periods=False): """ - Return from 'freebusy' any period overlapping with the given 'period', or - None if no overlap occurs. + Return whether any period in 'freebusy' overlaps with the given 'period', + returning a collection of overlapping periods if 'get_periods' is set to a + true value. """ dtstart, dtend = period[:2] - i = bisect_left(freebusy, (dtstart, dtend, None)) - return ( - i < len(freebusy) and (dtend is None or freebusy[i][0] < dtend) and freebusy[i] - or - i > 0 and freebusy[i - 1][1] > dtstart and freebusy[i - 1] - or - None - ) + found = bisect_left(freebusy, (dtstart, dtend, None)) + + overlapping = [] + + # Find earlier overlapping periods. + + i = found + + while i > 0 and freebusy[i - 1][1] > dtstart: + if get_periods: + overlapping.insert(0, freebusy[i - 1]) + else: + return True + i -= 1 + + # Find later overlapping periods. + + i = found + + while i < len(freebusy) and (dtend is None or freebusy[i][0] < dtend): + if get_periods: + overlapping.append(freebusy[i]) + else: + return True + i += 1 + + if get_periods: + return overlapping + else: + return False # vim: tabstop=4 expandtab shiftwidth=4