-
Notifications
You must be signed in to change notification settings - Fork 54
/
rust_vec.swift
111 lines (83 loc) · 2.72 KB
/
rust_vec.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
public class RustVec<T: Vectorizable> {
var ptr: UnsafeMutableRawPointer
var isOwned: Bool = true
public init(ptr: UnsafeMutableRawPointer) {
self.ptr = ptr
}
public init() {
ptr = T.vecOfSelfNew()
isOwned = true
}
public func push (value: T) {
T.vecOfSelfPush(vecPtr: ptr, value: value)
}
public func pop () -> Optional<T> {
T.vecOfSelfPop(vecPtr: ptr)
}
public func get(index: UInt) -> Optional<T.SelfRef> {
T.vecOfSelfGet(vecPtr: ptr, index: index)
}
public func as_ptr() -> UnsafePointer<T.SelfRef> {
UnsafePointer<T.SelfRef>(OpaquePointer(T.vecOfSelfAsPtr(vecPtr: ptr)))
}
/// Rust returns a UInt, but we cast to an Int because many Swift APIs such as
/// `ForEach(0..rustVec.len())` expect Int.
public func len() -> Int {
Int(T.vecOfSelfLen(vecPtr: ptr))
}
deinit {
if isOwned {
T.vecOfSelfFree(vecPtr: ptr)
}
}
}
extension RustVec: Sequence {
public func makeIterator() -> RustVecIterator<T> {
return RustVecIterator(self)
}
}
public struct RustVecIterator<T: Vectorizable>: IteratorProtocol {
var rustVec: RustVec<T>
var index: UInt = 0
init (_ rustVec: RustVec<T>) {
self.rustVec = rustVec
}
public mutating func next() -> T.SelfRef? {
let val = rustVec.get(index: index)
index += 1
return val
}
}
extension RustVec: Collection {
public typealias Index = Int
public func index(after i: Int) -> Int {
i + 1
}
public subscript(position: Int) -> T.SelfRef {
self.get(index: UInt(position))!
}
public var startIndex: Int {
0
}
public var endIndex: Int {
self.len()
}
}
extension RustVec: RandomAccessCollection {}
extension UnsafeBufferPointer {
func toFfiSlice () -> __private__FfiSlice {
__private__FfiSlice(start: UnsafeMutablePointer(mutating: self.baseAddress), len: UInt(self.count))
}
}
public protocol Vectorizable {
associatedtype SelfRef
associatedtype SelfRefMut
static func vecOfSelfNew() -> UnsafeMutableRawPointer;
static func vecOfSelfFree(vecPtr: UnsafeMutableRawPointer)
static func vecOfSelfPush(vecPtr: UnsafeMutableRawPointer, value: Self)
static func vecOfSelfPop(vecPtr: UnsafeMutableRawPointer) -> Optional<Self>
static func vecOfSelfGet(vecPtr: UnsafeMutableRawPointer, index: UInt) -> Optional<SelfRef>
static func vecOfSelfGetMut(vecPtr: UnsafeMutableRawPointer, index: UInt) -> Optional<SelfRefMut>
static func vecOfSelfAsPtr(vecPtr: UnsafeMutableRawPointer) -> UnsafePointer<SelfRef>
static func vecOfSelfLen(vecPtr: UnsafeMutableRawPointer) -> UInt
}