-
Notifications
You must be signed in to change notification settings - Fork 440
/
Windows.swift
360 lines (311 loc) · 11.4 KB
/
Windows.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// windows(ofCount:)
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns a collection of all the overlapping slices of a given size.
///
/// Use this method to iterate over overlapping subsequences of this
/// collection. This example prints every five character substring of `str`:
///
/// let str = "Hello, world!"
/// for substring in str.windows(ofCount: 5) {
/// print(substring)
/// }
/// // "Hello"
/// // "ello,"
/// // "llo, "
/// // "lo, W"
/// // ...
/// // "orld!"
///
/// - Parameter count: The number of elements in each window subsequence.
/// - Returns: A collection of subsequences of this collection, each with
/// length `count`. If this collection is shorter than `count`, the
/// resulting collection is empty.
///
/// - Complexity: O(1) if the collection conforms to
/// `RandomAccessCollection`, otherwise O(*k*) where `k` is `count`.
/// Access to successive windows is O(1).
@inlinable
public func windows(ofCount count: Int) -> WindowsOfCountCollection<Self> {
WindowsOfCountCollection(base: self, windowSize: count)
}
}
/// A collection wrapper that presents a sliding window over the elements of
/// a collection.
public struct WindowsOfCountCollection<Base: Collection> {
@usableFromInline
internal let base: Base
@usableFromInline
internal let windowSize: Int
@usableFromInline
internal var endOfFirstWindow: Base.Index?
@inlinable
internal init(base: Base, windowSize: Int) {
precondition(windowSize > 0, "Windows size must be greater than zero")
self.base = base
self.windowSize = windowSize
self.endOfFirstWindow =
base.index(base.startIndex, offsetBy: windowSize, limitedBy: base.endIndex)
}
}
extension WindowsOfCountCollection: Collection {
/// A position in a `WindowsOfCountCollection` instance.
public struct Index: Comparable {
@usableFromInline
internal var lowerBound: Base.Index
@usableFromInline
internal var upperBound: Base.Index
@inlinable
internal init(lowerBound: Base.Index, upperBound: Base.Index) {
self.lowerBound = lowerBound
self.upperBound = upperBound
}
@inlinable
public static func == (lhs: Index, rhs: Index) -> Bool {
lhs.lowerBound == rhs.lowerBound
}
@inlinable
public static func < (lhs: Index, rhs: Index) -> Bool {
lhs.lowerBound < rhs.lowerBound
}
}
@inlinable
public var startIndex: Index {
if let upperBound = endOfFirstWindow {
return Index(lowerBound: base.startIndex, upperBound: upperBound)
} else {
return endIndex
}
}
@inlinable
public var endIndex: Index {
Index(lowerBound: base.endIndex, upperBound: base.endIndex)
}
@inlinable
public subscript(index: Index) -> Base.SubSequence {
precondition(
index.lowerBound != index.upperBound,
"Windows index is out of range")
return base[index.lowerBound..<index.upperBound]
}
@inlinable
public func index(after index: Index) -> Index {
precondition(index != endIndex, "Advancing past end index")
guard index.upperBound < base.endIndex else { return endIndex }
let lowerBound = windowSize == 1
? index.upperBound
: base.index(after: index.lowerBound)
let upperBound = base.index(after: index.upperBound)
return Index(lowerBound: lowerBound, upperBound: upperBound)
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
guard distance != 0 else { return i }
return distance > 0
? offsetForward(i, by: distance)
: offsetBackward(i, by: -distance)
}
@inlinable
public func index(
_ i: Index,
offsetBy distance: Int,
limitedBy limit: Index
) -> Index? {
guard distance != 0 else { return i }
guard limit != i else { return nil }
if distance > 0 {
return limit > i
? offsetForward(i, by: distance, limitedBy: limit)
: offsetForward(i, by: distance)
} else {
return limit < i
? offsetBackward(i, by: -distance, limitedBy: limit)
: offsetBackward(i, by: -distance)
}
}
@inlinable
internal func offsetForward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetForward(i, by: distance, limitedBy: endIndex)
else { fatalError("Index is out of bounds") }
return index
}
@inlinable
internal func offsetBackward(_ i: Index, by distance: Int) -> Index {
guard let index = offsetBackward(i, by: distance, limitedBy: startIndex)
else { fatalError("Index is out of bounds") }
return index
}
@inlinable
internal func offsetForward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
assert(distance > 0)
assert(limit > i)
// `endIndex` and the index before it both have `base.endIndex` as their
// upper bound, so we first advance to the base index _before_ the upper
// bound of the output, in order to avoid advancing past the end of `base`
// when advancing to `endIndex`.
//
// Advancing by 4:
//
// input: [x|x x x x x|x x x x] [x x|x x x x x|x x x]
// |> > >|>| or |> > >|
// output: [x x x x x|x x x x x] [x x x x x x x x x x] (`endIndex`)
if distance >= windowSize {
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the lower
// bound of the output is greater than or equal to the upper bound of the
// input.
// input: [x|x x x x|x x x x x x x]
// |> >|> > >|>|
// output: [x x x x x x x|x x x x|x]
guard limit.lowerBound >= i.upperBound,
let lowerBound = base.index(
i.upperBound,
offsetBy: distance - windowSize,
limitedBy: limit.lowerBound),
let indexBeforeUpperBound = base.index(
lowerBound,
offsetBy: windowSize - 1,
limitedBy: limit.upperBound)
else { return nil }
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
// `endIndex`.
guard indexBeforeUpperBound != base.endIndex else { return endIndex }
return Index(
lowerBound: lowerBound,
upperBound: base.index(after: indexBeforeUpperBound))
} else {
// input: [x|x x x x x x|x x x x x]
// |> > > >| |> > >|>|
// output: [x x x x x|x x x x x x|x]
guard let indexBeforeUpperBound = base.index(
i.upperBound,
offsetBy: distance - 1,
limitedBy: limit.upperBound)
else { return nil }
// If `indexBeforeUpperBound` equals the limit, the upper bound itself
// exceeds it.
guard indexBeforeUpperBound != limit.upperBound || limit == endIndex
else { return nil }
// If `indexBeforeUpperBound` equals `base.endIndex`, we're advancing to
// `endIndex`.
guard indexBeforeUpperBound != base.endIndex else { return endIndex }
return Index(
lowerBound: base.index(i.lowerBound, offsetBy: distance),
upperBound: base.index(after: indexBeforeUpperBound))
}
}
@inlinable
internal func offsetBackward(
_ i: Index, by distance: Int, limitedBy limit: Index
) -> Index? {
assert(distance > 0)
assert(limit < i)
if i == endIndex {
// Advance `base.endIndex` by `distance - 1`, because the index before
// `endIndex` also has `base.endIndex` as its upper bound.
//
// Advancing by 4:
//
// input: [x x x x x x x x x x] (`endIndex`)
// |< < < < <|< < <|
// output: [x x|x x x x x|x x x]
guard let upperBound = base.index(
base.endIndex,
offsetBy: -(distance - 1),
limitedBy: limit.upperBound)
else { return nil }
return Index(
lowerBound: base.index(upperBound, offsetBy: -windowSize),
upperBound: upperBound)
} else if distance >= windowSize {
// Avoid traversing `self[i.lowerBound..<i.upperBound]` when the upper
// bound of the output is less than or equal to the lower bound of the
// input.
//
// input: [x x x x x x x|x x x x|x]
// |< < < <|< <|
// output: [x|x x x x|x x x x x x x]
guard limit.upperBound <= i.lowerBound,
let upperBound = base.index(
i.lowerBound,
offsetBy: -(distance - windowSize),
limitedBy: limit.upperBound)
else { return nil }
return Index(
lowerBound: base.index(upperBound, offsetBy: -windowSize),
upperBound: upperBound)
} else {
// input: [x x x x x|x x x x x x|x]
// |< < < <| |< < < <|
// output: [x|x x x x x x|x x x x x]
guard let lowerBound = base.index(
i.lowerBound,
offsetBy: -distance,
limitedBy: limit.lowerBound)
else { return nil }
return Index(
lowerBound: lowerBound,
upperBound: base.index(i.lowerBound, offsetBy: -distance))
}
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
guard start <= end else { return -distance(from: end, to: start) }
guard start != end else { return 0 }
guard end != endIndex else {
// We add 1 here because the index before `endIndex` also has
// `base.endIndex` as its upper bound.
return base[start.upperBound...].count + 1
}
if start.upperBound <= end.lowerBound {
// The distance between `start.lowerBound` and `start.upperBound` is
// already known.
//
// start: [x|x x x x|x x x x x x x]
// |- - - -|> >|
// end: [x x x x x x x|x x x x|x]
return windowSize + base[start.upperBound..<end.lowerBound].count
} else {
// start: [x|x x x x x x|x x x x x]
// |> > > >|
// end: [x x x x x|x x x x x x|x]
return base[start.lowerBound..<end.lowerBound].count
}
}
}
extension WindowsOfCountCollection: BidirectionalCollection
where Base: BidirectionalCollection
{
@inlinable
public func index(before index: Index) -> Index {
precondition(index != startIndex, "Incrementing past start index")
if index == endIndex {
return Index(
lowerBound: base.index(index.lowerBound, offsetBy: -windowSize),
upperBound: index.upperBound
)
} else {
return Index(
lowerBound: base.index(before: index.lowerBound),
upperBound: base.index(before: index.upperBound)
)
}
}
}
extension WindowsOfCountCollection: RandomAccessCollection
where Base: RandomAccessCollection {}
extension WindowsOfCountCollection: LazySequenceProtocol, LazyCollectionProtocol
where Base: LazySequenceProtocol {}
extension WindowsOfCountCollection.Index: Hashable where Base.Index: Hashable {}