forked from swiftlang/swift-corelibs-foundation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDateInterval.swift
220 lines (187 loc) · 8.32 KB
/
DateInterval.swift
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import CoreFoundation
/// DateInterval represents a closed date interval in the form of [startDate, endDate]. It is possible for the start and end dates to be the same with a duration of 0. DateInterval does not support reverse intervals i.e. intervals where the duration is less than 0 and the end date occurs earlier in time than the start date.
public struct DateInterval : ReferenceConvertible, Comparable, Hashable {
public typealias ReferenceType = NSDateInterval
/// The start date.
public var start: Date
/// The end date.
///
/// - precondition: `end >= start`
public var end: Date {
get {
return start + duration
}
set {
precondition(newValue >= start, "Reverse intervals are not allowed")
duration = newValue.timeIntervalSinceReferenceDate - start.timeIntervalSinceReferenceDate
}
}
/// The duration.
///
/// - precondition: `duration >= 0`
public var duration: TimeInterval {
willSet {
precondition(newValue >= 0, "Negative durations are not allowed")
}
}
/// Initializes a `DateInterval` with start and end dates set to the current date and the duration set to `0`.
public init() {
let d = Date()
start = d
duration = 0
}
/// Initialize a `DateInterval` with the specified start and end date.
///
/// - precondition: `end >= start`
public init(start: Date, end: Date) {
precondition(end >= start, "Reverse intervals are not allowed")
self.start = start
duration = end.timeIntervalSince(start)
}
/// Initialize a `DateInterval` with the specified start date and duration.
///
/// - precondition: `duration >= 0`
public init(start: Date, duration: TimeInterval) {
precondition(duration >= 0, "Negative durations are not allowed")
self.start = start
self.duration = duration
}
/**
Compare two DateIntervals.
This method prioritizes ordering by start date. If the start dates are equal, then it will order by duration.
e.g. Given intervals a and b
```
a. |-----|
b. |-----|
```
`a.compare(b)` would return `.OrderedAscending` because a's start date is earlier in time than b's start date.
In the event that the start dates are equal, the compare method will attempt to order by duration.
e.g. Given intervals c and d
```
c. |-----|
d. |---|
```
`c.compare(d)` would result in `.OrderedDescending` because c is longer than d.
If both the start dates and the durations are equal, then the intervals are considered equal and `.OrderedSame` is returned as the result.
*/
public func compare(_ dateInterval: DateInterval) -> ComparisonResult {
let result = start.compare(dateInterval.start)
if result == .orderedSame {
if self.duration < dateInterval.duration { return .orderedAscending }
if self.duration > dateInterval.duration { return .orderedDescending }
return .orderedSame
}
return result
}
/// Returns `true` if `self` intersects the `dateInterval`.
public func intersects(_ dateInterval: DateInterval) -> Bool {
return contains(dateInterval.start) || contains(dateInterval.end) || dateInterval.contains(start) || dateInterval.contains(end)
}
/// Returns a DateInterval that represents the interval where the given date interval and the current instance intersect.
///
/// In the event that there is no intersection, the method returns nil.
public func intersection(with dateInterval: DateInterval) -> DateInterval? {
if !intersects(dateInterval) {
return nil
}
if self == dateInterval {
return self
}
let timeIntervalForSelfStart = start.timeIntervalSinceReferenceDate
let timeIntervalForSelfEnd = end.timeIntervalSinceReferenceDate
let timeIntervalForGivenStart = dateInterval.start.timeIntervalSinceReferenceDate
let timeIntervalForGivenEnd = dateInterval.end.timeIntervalSinceReferenceDate
let resultStartDate : Date
if timeIntervalForGivenStart >= timeIntervalForSelfStart {
resultStartDate = dateInterval.start
} else {
// self starts after given
resultStartDate = start
}
let resultEndDate : Date
if timeIntervalForGivenEnd >= timeIntervalForSelfEnd {
resultEndDate = end
} else {
// given ends before self
resultEndDate = dateInterval.end
}
return DateInterval(start: resultStartDate, end: resultEndDate)
}
/// Returns `true` if `self` contains `date`.
public func contains(_ date: Date) -> Bool {
let timeIntervalForGivenDate = date.timeIntervalSinceReferenceDate
let timeIntervalForSelfStart = start.timeIntervalSinceReferenceDate
let timeIntervalforSelfEnd = end.timeIntervalSinceReferenceDate
if (timeIntervalForGivenDate >= timeIntervalForSelfStart) && (timeIntervalForGivenDate <= timeIntervalforSelfEnd) {
return true
}
return false
}
public var hashValue: Int {
var buf: (UInt, UInt) = (UInt(start.timeIntervalSinceReferenceDate), UInt(end.timeIntervalSinceReferenceDate))
return withUnsafeMutablePointer(to: &buf) { bufferPtr in
let count = MemoryLayout<UInt>.size * 2
return bufferPtr.withMemoryRebound(to: UInt8.self, capacity: count) { bufferBytes in
return Int(bitPattern: CFHashBytes(bufferBytes, CFIndex(count)))
}
}
}
public static func ==(lhs: DateInterval, rhs: DateInterval) -> Bool {
return lhs.start == rhs.start && lhs.duration == rhs.duration
}
public static func <(lhs: DateInterval, rhs: DateInterval) -> Bool {
return lhs.compare(rhs) == .orderedAscending
}
}
extension DateInterval : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return "(Start Date) \(start) + (Duration) \(duration) seconds = (End Date) \(end)"
}
public var debugDescription: String {
return description
}
public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "start", value: start))
c.append((label: "end", value: end))
c.append((label: "duration", value: duration))
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
}
extension DateInterval : _ObjectTypeBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}
public static func _getObjectiveCType() -> Any.Type {
return NSDateInterval.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSDateInterval {
return NSDateInterval(start: start, duration: duration)
}
public static func _forceBridgeFromObjectiveC(_ dateInterval: NSDateInterval, result: inout DateInterval?) {
if !_conditionallyBridgeFromObjectiveC(dateInterval, result: &result) {
fatalError("Unable to bridge \(NSDateInterval.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ dateInterval : NSDateInterval, result: inout DateInterval?) -> Bool {
result = DateInterval(start: dateInterval.startDate, duration: dateInterval.duration)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDateInterval?) -> DateInterval {
var result: DateInterval? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}