Mini-Alloc

一个基本的、线程安全的、稀疏容器,用于保存对 Swift 对象的引用。

其预期用途是当您需要创建未知数量的对象,并通过引用将它们传递给一些 C 代码时,并确保它们在 C 代码完成对这些对象的处理之前不会被垃圾回收。

它不会压缩内部存储,除非您运行 releaseAll 方法并提供新的默认大小。

此项目目前需要 Swift 6.0+

用法示例

// Basic Usage
final class TestObject {
    var counter = 0
}

let allocator1 = MAContainer<TestObject>()

let id1 = allocator1.retain(TestObject())

// and when done
allocator1.release(id1)

// Or if your object requires knowing its own id

final class TestObjectWithId {
    let id: Int
    var counter = 0

    init(id: Int = 0) {
        self.id = id
    }
}

let allocator2 = MAContainer<TestObjectWithId>()

allocator2.retain { .init(id: $0) }

所有方法

init(initialSize size: Int = 8) // size states how much space to reserved for references

// T: AnyObject
@discardableResult func retain(using: (Int) -> T?) -> Int? // returns a retained object id
@discardableResult func retain(_ item: T) -> Int? // returns a retained object id

@discardableResult func release(_ id: Int) -> Bool // returns true only if a retained object with the given id was released
func release(_ ids: [Int])

func find(by id: Int) -> T? // returns a retained object if it exists

@discardableResult func update<U>(with id: Int, using: (inout T) -> U) -> U? // returns an update function result if the retained object with a given id is found

// do something with every retained object in the container
func map<U>(using: (T) -> U) -> [U]
func each(using: (T) -> Void)
func filter(_ predicate: (T) -> Bool) -> [T]

func releaseAll(size: Int? = nil) // if the size is provided, it will resize the internal storage to the specified size. Otherwise, it will leave it as it is.

func pointer(to id: Int) -> UnsafeMutablePointer<T>? // returns a pointer to a retained object with the provided id if it exists

SPM 安装

.package(url: "https://github.com/RussBaz/mini-alloc", from: "1.0.2"),
.product(name: "MA", package: "mini-alloc"),