-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.swift
243 lines (213 loc) · 7.28 KB
/
Utils.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
//
// Utils.swift
// MobileLighting
//
// Utility functions
//
import Foundation
import CoreVideo
import CoreMedia
import Yaml
/*=====================================================================================
String operators & extensions to support passing of [CChar]s to C
======================================================================================*/
// properly add C strings together (removes null byte from first)
func +(left: [CChar], right: [CChar]) -> [CChar] {
var result = [CChar](left.dropLast())
result.append(contentsOf: right)
return result
}
// Convert String to [CChar]
prefix operator *
extension String {
static prefix func * (swiftString: String) -> [CChar] {
return swiftString.cString(using: .ascii)!
}
}
// Convert [String] to [[CChar]]
prefix func * (swiftStringArray: [String]) -> [[CChar]] {
return swiftStringArray.map {
return *$0
}
}
// Convert [[CChar]] to [UnsafeMutablePointer<CChar>?]
prefix operator **
prefix func ** (cStringArray: inout [[CChar]]) -> [UnsafeMutablePointer<CChar>?] {
var ptrs = [UnsafeMutablePointer<CChar>?]()
for i in 0..<cStringArray.count { ptrs.append(getptr(&cStringArray[i])) }
return ptrs
}
func pathExists(_ path: String) -> Bool {
return FileManager.default.fileExists(atPath: path);
}
enum PathError: Error {
case invalidPath
}
func safePath(_ path: String) throws -> [CChar] {
if(!pathExists(path)) {
print( "Path \(path) does not exist." )
throw PathError.invalidPath
}
return *path
}
/*=====================================================================================
Misc
======================================================================================*/
func makeDir(_ str: String) -> Void {
do {
try FileManager.default.createDirectory(atPath: str, withIntermediateDirectories: true, attributes: nil)
} catch {
print("make dir - error - could not make directory.")
}
}
func getptr<T>(_ obj: inout [T]) -> UnsafeMutablePointer<T>? {
return UnsafeMutablePointer<T>(&obj)
}
// get an array of Integers from an array of paths "strs" to files or directories with the format [prefix]x[suffix]
func getIDs(_ strs: [String], prefix: String, suffix: String) -> [Int] {
return strs.map { // convert the array to contain only the filenames (not whole paths)
return String($0.split(separator: "/").last!)
}.map { // collect all the IDs, returning nil for all files not in the format [prefix]x[suffix]
guard $0.hasPrefix(prefix), $0.hasSuffix(suffix) else {
return nil
}
let base = $0.dropFirst(prefix.count).dropLast(suffix.count)
return Int(base)
}.filter{ // remove nil values from array
return $0 != nil
}.map{ return $0!}
}
let lockFlags = CVPixelBufferLockFlags(rawValue: 0) // read & write
// because the Swift standard library doesn't have a built-in linked list class,
// I wrote a minimalistic one. i'll add to it as needed
class List<T> {
private class ListNode<T> {
var head: T
var tail: ListNode<T>?
var parent: ListNode<T>?
init(head: T, tail: ListNode<T>? = nil, parent: ListNode<T>? = nil) {
self.head = head
self.tail = tail
self.parent = parent
tail?.parent = self
parent?.tail = self
}
}
var count: Int = 0
private var _first: ListNode<T>? = nil
private weak var _last: ListNode<T>? = nil
var first: T? {
get {
return _first?.head
}
set {
guard let newValue = newValue else {
return
}
_first?.head = newValue
}
}
var last: T? {
get {
return _last?.head
}
set {
guard let newValue = newValue else {
return
}
_last?.head = newValue
}
}
func insertFirst(_ obj: T) {
_first = ListNode<T>(head: obj, tail: _first)
_last = _last ?? _first
}
func popLast() -> T? {
let value = _last?.head
if _first === _last {
_first = nil
_last = nil
} else {
_last = _last?.parent
_last?.tail = nil
}
return value
}
func removeAll() {
self._first = nil
self._last = nil
}
}
// empty directory
func removeFiles(dir: String) -> Void {
guard let paths = try? FileManager.default.contentsOfDirectory(atPath: dir) else {
print("Could not remove files at directory \(dir).")
return
}
for path in paths {
do { try FileManager.default.removeItem(atPath: "\(dir)/\(path)") }
catch let error { print(error.localizedDescription) }
}
}
// divide command tokens into params and flags
func partitionTokens(_ tokens: [String]) -> ([String], [String]) {
let params = tokens.filter { return !$0.starts(with: "-") }
let flags = tokens.filter { return $0.starts(with: "-") }
return (params, flags)
}
// expects string in format [1,2,3,4
// converts to array of integers
// used for supporting arrays as command line arguments
func stringToIntArray(_ string: String ) -> [Int] {
// initialize an array of the connected ports on the switcher.
var liststr = string.dropFirst()// cut off the first character
// if last character is ], cut it off too
// this isn't a requirement because Xcode will sometimes automatically appear to add "]" without actially doing so
if( string.hasSuffix("]") ) {
liststr = liststr.dropLast()
}
let strArray = liststr.components(separatedBy: ",") // divide string into array by ","
let intArray = strArray.map { Int($0) } // convert [String] to [Int?]
// convert [Int?] to [Int], filtering nil values
var filteredArray: [Int] = []
for int in intArray {
int != nil ? filteredArray.append(int!) : ()
}
return filteredArray
}
extension CMTime {
init(exposureDuration: Double) {
let prefferedExposureDurationTimescale: CMTimeScale = 1000000
self.init(seconds: exposureDuration, preferredTimescale: prefferedExposureDurationTimescale)
}
}
// from https://stackoverflow.com/questions/32952248/get-all-enum-values-as-an-array
// temporary implementation of getting all cases of an Enum
// this can be replaced by CaseIterable protocol once Swift 4.2 and Xcode 10 are released (this summer 2018, I think)
protocol EnumCollection : Hashable {}
extension EnumCollection {
static func cases() -> AnySequence<Self> {
typealias S = Self
return AnySequence { () -> AnyIterator<S> in
var raw = 0
return AnyIterator {
let current : Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: S.self, capacity: 1) { $0.pointee }
}
guard current.hashValue == raw else { return nil }
raw += 1
return current
}
}
}
}
extension String {
subscript (i: Int) -> Character {
return self[index(startIndex, offsetBy: i)]
}
}
extension Dictionary where Key == Yaml, Value == Yaml {
subscript (_ string: String) -> Yaml? {
let key = Yaml.string(string)
return self[key]
}
}