2020-03-26 03:10:48 +00:00
|
|
|
//
|
2022-11-30 03:41:36 +00:00
|
|
|
// Weak.swift
|
2020-03-26 03:10:48 +00:00
|
|
|
// Tusker
|
|
|
|
//
|
|
|
|
// Created by Shadowfacts on 3/25/20.
|
|
|
|
// Copyright © 2020 Shadowfacts. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
|
2024-07-09 04:48:35 +00:00
|
|
|
final class WeakHolder<T: AnyObject> {
|
2022-11-30 03:41:36 +00:00
|
|
|
weak var object: T?
|
2020-03-26 03:10:48 +00:00
|
|
|
|
2022-11-30 03:41:36 +00:00
|
|
|
init(_ object: T?) {
|
|
|
|
self.object = object
|
2020-03-26 03:10:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-09 04:48:35 +00:00
|
|
|
struct WeakArray<Element: AnyObject>: MutableCollection, RangeReplaceableCollection, RandomAccessCollection, BidirectionalCollection {
|
2022-11-30 03:41:36 +00:00
|
|
|
private var array: [WeakHolder<Element>]
|
2020-03-26 03:10:48 +00:00
|
|
|
|
|
|
|
var startIndex: Int { array.startIndex }
|
|
|
|
var endIndex: Int { array.endIndex }
|
|
|
|
|
2020-09-20 15:27:14 +00:00
|
|
|
init() {
|
|
|
|
array = []
|
|
|
|
}
|
|
|
|
|
2020-03-26 03:10:48 +00:00
|
|
|
init(_ elements: [Element]) {
|
2022-11-30 03:41:36 +00:00
|
|
|
array = elements.map { WeakHolder($0) }
|
2020-03-26 03:10:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
init(_ elements: [Element?]) {
|
2022-11-30 03:41:36 +00:00
|
|
|
array = elements.map { WeakHolder($0) }
|
2020-03-26 03:10:48 +00:00
|
|
|
}
|
|
|
|
|
2020-09-20 15:27:14 +00:00
|
|
|
subscript(position: Int) -> Element? {
|
|
|
|
get {
|
2022-11-30 03:41:36 +00:00
|
|
|
array[position].object
|
2020-09-20 15:27:14 +00:00
|
|
|
}
|
|
|
|
set(newValue) {
|
2022-11-30 03:41:36 +00:00
|
|
|
array[position] = WeakHolder(newValue)
|
2020-09-20 15:27:14 +00:00
|
|
|
}
|
2020-03-26 03:10:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func index(after i: Int) -> Int {
|
|
|
|
return array.index(after: i)
|
|
|
|
}
|
2020-09-20 15:27:14 +00:00
|
|
|
|
2024-07-09 04:48:35 +00:00
|
|
|
func index(before i: Int) -> Int {
|
|
|
|
return array.index(before: i)
|
|
|
|
}
|
|
|
|
|
2020-09-20 15:27:14 +00:00
|
|
|
mutating func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C) where C : Collection, Self.Element == C.Element {
|
2022-11-30 03:41:36 +00:00
|
|
|
array.replaceSubrange(subrange, with: newElements.map { WeakHolder($0) })
|
2020-09-20 15:27:14 +00:00
|
|
|
}
|
2020-03-26 03:10:48 +00:00
|
|
|
}
|