Skip to content

Instantly share code, notes, and snippets.

@zvonicek
Last active October 11, 2023 15:24
Show Gist options
  • Save zvonicek/1a2b69e45d1b157ee36207f3615ba2d2 to your computer and use it in GitHub Desktop.
Save zvonicek/1a2b69e45d1b157ee36207f3615ba2d2 to your computer and use it in GitHub Desktop.
final class RunLoopSource {
private static let eventHandler: @convention(c) (UnsafeMutableRawPointer?) -> Void = { context in
unsafeBitCast(context, to: RunLoopSource.self).eventHandler()
}
private let eventHandler: () -> Void
private let mode: CFRunLoopMode
private let runLoop: CFRunLoop
private var source: CFRunLoopSource!
init(runLoop: RunLoop, mode: RunLoop.Mode, eventHandler: @escaping () -> Void) {
self.eventHandler = eventHandler
self.mode = CFRunLoopMode(mode.rawValue as CFString)
self.runLoop = runLoop.getCFRunLoop()
var context = CFRunLoopSourceContext()
context.info = Unmanaged.passUnretained(self).toOpaque()
context.perform = RunLoopSource.eventHandler
self.source = CFRunLoopSourceCreate(nil, 0, &context)!
CFRunLoopAddSource(runLoop, source, mode)
}
deinit {
CFRunLoopRemoveSource(runLoop, source, mode)
}
func signal() {
CFRunLoopSourceSignal(source)
CFRunLoopWakeUp(runLoop)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment