-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathWeebly∕OrderedSet-3.1.0.swift
460 lines (379 loc) · 15.4 KB
/
Weebly∕OrderedSet-3.1.0.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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
// Copyright (c) 2014 James Richard.
// Distributed under the MIT License (http://opensource.org/licenses/MIT).
/// An ordered, unique collection of objects.
public class OrderedSet<T: Hashable> {
fileprivate var contents = [T: Index]() // Needs to have a value of Index instead of Void for fast removals
fileprivate var sequencedContents = [UnsafeMutablePointer<T>]()
/**
Inititalizes an empty ordered set.
- returns: An empty ordered set.
*/
public init() { }
deinit {
removeAllObjects()
}
/**
Initializes a new ordered set with the order and contents
of sequence.
If an object appears more than once in the sequence it will only appear
once in the ordered set, at the position of its first occurance.
- parameter sequence: The sequence to initialize the ordered set with.
- returns: An initialized ordered set with the contents of sequence.
*/
public init<S: Sequence>(sequence: S) where S.Iterator.Element == T {
for object in sequence where contents[object] == nil {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: object)
sequencedContents.append(pointer)
}
}
public required init(arrayLiteral elements: T...) {
for object in elements where contents[object] == nil {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: object)
sequencedContents.append(pointer)
}
}
/**
Locate the index of an object in the ordered set.
It is preferable to use this method over the global find() for performance reasons.
- parameter object: The object to find the index for.
- returns: The index of the object, or nil if the object is not in the ordered set.
*/
public func index(of object: T) -> Index? {
if let index = contents[object] {
return index
}
return nil
}
/**
Appends an object to the end of the ordered set.
- parameter object: The object to be appended.
*/
public func append(_ object: T) {
if let lastIndex = index(of: object) {
remove(object)
insert(object, at: lastIndex)
} else {
contents[object] = contents.count
let pointer = UnsafeMutablePointer<T>.allocate(capacity: 1)
pointer.initialize(to: object)
sequencedContents.append(pointer)
}
}
/**
Appends a sequence of objects to the end of the ordered set.
- parameter sequence: The sequence of objects to be appended.
*/
public func append<S: Sequence>(contentsOf sequence: S) where S.Iterator.Element == T {
var gen = sequence.makeIterator()
while let object: T = gen.next() {
append(object)
}
}
/**
Removes an object from the ordered set.
If the object exists in the ordered set, it will be removed.
If it is not the last object in the ordered set, subsequent
objects will be shifted down one position.
- parameter object: The object to be removed.
- returns: The former index position of the object.
*/
@discardableResult
public func remove(_ object: T) -> Index? {
if let index = contents[object] {
contents[object] = nil
sequencedContents[index].deinitialize(count: 1)
sequencedContents[index].deallocate()
sequencedContents.remove(at: index)
for (object, i) in contents {
if i < index {
continue
}
contents[object] = i - 1
}
return index
}
return nil
}
/**
Removes the given objects from the ordered set.
- parameter objects: The objects to be removed.
- returns: A collection of the former index positions of the objects. An index position is not provided for objects that were not found.
*/
@discardableResult
public func remove<S: Sequence>(_ objects: S) -> [Index]? where S.Iterator.Element == T {
var indexes = [Index]()
objects.forEach { object in
if let index = index(of: object) {
indexes.append(index)
}
}
var gen = objects.makeIterator()
while let object: T = gen.next() {
remove(object)
}
return indexes
}
/**
Removes an object at a given index.
This method will cause a fatal error if you attempt to move an object to an index that is out of bounds.
- parameter index: The index of the object to be removed.
*/
public func removeObject(at index: Index) {
if index < 0 || index >= count {
fatalError("Attempting to remove an object at an index that does not exist")
}
remove(sequencedContents[index].pointee)
}
/**
Removes all objects in the ordered set.
*/
public func removeAllObjects() {
contents.removeAll()
for sequencedContent in sequencedContents {
sequencedContent.deinitialize(count: 1)
sequencedContent.deallocate()
}
sequencedContents.removeAll()
}
/**
Swaps two objects contained within the ordered set.
Both objects must exist within the set, or the swap will not occur.
- parameter first: The first object to be swapped.
- parameter second: The second object to be swapped.
*/
public func swapObject(_ first: T, with second: T) {
if let firstPosition = contents[first] {
if let secondPosition = contents[second] {
contents[first] = secondPosition
contents[second] = firstPosition
sequencedContents[firstPosition].pointee = second
sequencedContents[secondPosition].pointee = first
}
}
}
/**
Tests if the ordered set contains any objects within a sequence.
- parameter other: The sequence to look for the intersection in.
- returns: Returns true if the sequence and set contain any equal objects, otherwise false.
*/
public func intersects<S: Sequence>(_ other: S) -> Bool where S.Iterator.Element == T {
var gen = other.makeIterator()
while let object: T = gen.next() {
if contains(object) {
return true
}
}
return false
}
/**
Tests if a the ordered set is a subset of another sequence.
- parameter sequence: The sequence to check.
- returns: true if the sequence contains all objects contained in the receiver, otherwise false.
*/
public func isSubset<S: Sequence>(of sequence: S) -> Bool where S.Iterator.Element == T {
for (object, _) in contents {
if !sequence.contains(object) {
return false
}
}
return true
}
/**
Moves an object to a different index, shifting all objects in between the movement.
This method is a no-op if the object doesn't exist in the set or the index is the
same that the object is currently at.
This method will cause a fatal error if you attempt to move an object to an index that is out of bounds.
- parameter object: The object to be moved
- parameter index: The index that the object should be moved to.
*/
public func moveObject(_ object: T, toIndex index: Index) {
if index < 0 || index >= count {
fatalError("Attempting to move an object at an index that does not exist")
}
if let position = contents[object] {
// Return if the client attempted to move to the current index
if position == index {
return
}
let adjustment = position > index ? -1 : 1
var currentIndex = position
while currentIndex != index {
let nextIndex = currentIndex + adjustment
let firstObject = sequencedContents[currentIndex].pointee
let secondObject = sequencedContents[nextIndex].pointee
sequencedContents[currentIndex].pointee = secondObject
sequencedContents[nextIndex].pointee = firstObject
contents[firstObject] = nextIndex
contents[secondObject] = currentIndex
currentIndex += adjustment
}
}
}
/**
Moves an object from one index to a different index, shifting all objects in between the movement.
This method is a no-op if the index is the same that the object is currently at.
This method will cause a fatal error if you attempt to move an object fro man index that is out of bounds
or to an index that is out of bounds.
- parameter index: The index of the object to be moved.
- parameter toIndex: The index that the object should be moved to.
*/
public func moveObject(at index: Index, to toIndex: Index) {
if (index < 0 || index >= count) || (toIndex < 0 || toIndex >= count) {
fatalError("Attempting to move an object at or to an index that does not exist")
}
moveObject(self[index], toIndex: toIndex)
}
/**
Inserts an object at a given index, shifting all objects above it up one.
This method will cause a fatal error if you attempt to insert the object out of bounds.
If the object already exists in the OrderedSet, this operation is a no-op.
- parameter object: The object to be inserted.
- parameter index: The index to be inserted at.
*/
public func insert(_ object: T, at index: Index) {
if index > count || index < 0 {
fatalError("Attempting to insert an object at an index that does not exist")
}
if contents[object] != nil {
return
}
// Append our object, then swap them until its at the end.
append(object)
for i in (index..<count-1).reversed() {
swapObject(self[i], with: self[i+1])
}
}
/**
Inserts objects at a given index, shifting all objects above it up one.
This method will cause a fatal error if you attempt to insert the objects out of bounds.
If an object in objects already exists in the OrderedSet it will not be added. Objects that occur twice
in the sequence will only be added once.
- parameter objects: The objects to be inserted.
- parameter index: The index to be inserted at.
*/
public func insert<S: Sequence>(_ objects: S, at index: Index) where S.Iterator.Element == T {
if index > count || index < 0 {
fatalError("Attempting to insert an object at an index that does not exist")
}
var addedObjectCount = 0
for object in objects where contents[object] == nil {
let seqIdx = index + addedObjectCount
let element = UnsafeMutablePointer<T>.allocate(capacity: 1)
element.initialize(to: object)
sequencedContents.insert(element, at: seqIdx)
contents[object] = seqIdx
addedObjectCount += 1
}
// Now we'll remove duplicates and update the shifted objects position in the contents
// dictionary.
for i in index + addedObjectCount..<count {
contents[sequencedContents[i].pointee] = i
}
}
/**
Create a copy of the given ordered set with the same content. Important: the new array has the
same references to the previous. This is NOT a deep copy or a clone!
*/
public func copy() -> OrderedSet<T> {
return OrderedSet<T>(sequence: self)
}
/// Returns the last object in the set, or `nil` if the set is empty.
public var last: T? {
return sequencedContents.last?.pointee
}
}
extension OrderedSet: ExpressibleByArrayLiteral { }
extension OrderedSet where T: Comparable {}
extension OrderedSet {
public var count: Int {
return contents.count
}
public var isEmpty: Bool {
return count == 0
}
public var first: T? {
guard count > 0 else { return nil }
return sequencedContents[0].pointee
}
public func index(after index: Int) -> Int {
return sequencedContents.index(after: index)
}
public typealias Index = Int
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return contents.count
}
public subscript(index: Index) -> T {
get {
return sequencedContents[index].pointee
}
set {
let previousCount = contents.count
contents[sequencedContents[index].pointee] = nil
contents[newValue] = index
// If the count is reduced we used an existing value, and need to sync up sequencedContents
if contents.count == previousCount {
sequencedContents[index].pointee = newValue
} else {
sequencedContents[index].deinitialize(count: 1)
sequencedContents[index].deallocate()
sequencedContents.remove(at: index)
}
}
}
}
extension OrderedSet: Sequence {
public typealias Iterator = OrderedSetGenerator<T>
public func makeIterator() -> Iterator {
return OrderedSetGenerator(set: self)
}
}
public struct OrderedSetGenerator<T: Hashable>: IteratorProtocol {
public typealias Element = T
private var generator: IndexingIterator<[UnsafeMutablePointer<T>]>
public init(set: OrderedSet<T>) {
generator = set.sequencedContents.makeIterator()
}
public mutating func next() -> Element? {
return generator.next()?.pointee
}
}
extension OrderedSetGenerator where T: Comparable {}
public func +<T, S: Sequence> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> where S.Element == T {
let joinedSet = lhs.copy()
joinedSet.append(contentsOf: rhs)
return joinedSet
}
public func +=<T, S: Sequence> (lhs: inout OrderedSet<T>, rhs: S) where S.Element == T {
lhs.append(contentsOf: rhs)
}
public func -<T, S: Sequence> (lhs: OrderedSet<T>, rhs: S) -> OrderedSet<T> where S.Element == T {
let purgedSet = lhs.copy()
purgedSet.remove(rhs)
return purgedSet
}
public func -=<T, S: Sequence> (lhs: inout OrderedSet<T>, rhs: S) where S.Element == T {
lhs.remove(rhs)
}
extension OrderedSet: Equatable { }
public func ==<T> (lhs: OrderedSet<T>, rhs: OrderedSet<T>) -> Bool {
if lhs.count != rhs.count {
return false
}
for object in lhs where lhs.contents[object] != rhs.contents[object] {
return false
}
return true
}
extension OrderedSet: CustomStringConvertible {
public var description: String {
let children = map({ "\($0)" }).joined(separator: ", ")
return "OrderedSet (\(count) object(s)): [\(children)]"
}
}