Skip to content

Instantly share code, notes, and snippets.

View zwaldowski's full-sized avatar

Zachary Waldowski zwaldowski

View GitHub Profile
extension NSData {
func toHexString() -> String {
var string = ""
enumerateByteRangesUsingBlock { bytes, range, _ in
let buffer = UnsafeBufferPointer<UInt8>(start: .init(bytes), count: range.length)
for byte in buffer {
if byte <= 0xF { string.unicodeScalars.append("0") }
string += String(byte, radix: 16)
}
import Foundation
extension String {
func rangesOfString(findStr: String, options: NSStringCompareOptions = []) -> [Range<String.Index>] {
var ranges = [Range<String.Index>]()
var startIndex = self.startIndex
while startIndex != endIndex {
guard let range = rangeOfString(findStr, options: options, range: startIndex ..< endIndex) else { break }
ranges.append(range)
startIndex = range.endIndex
@zwaldowski
zwaldowski / JSONStringSkipAhead.swift
Last active May 4, 2016 09:08
Code outline for bignerdranch/Freddy#42.
extension JSON {
private mutating func scanUntilEndOfString() throws -> (UnsafeBufferPointer<UInt8>, hasEscapes: Bool) {
// skip past the opening "
loc = loc.successor()
var range = loc..<loc
var hasEscapes = false
var inEscape = false
@zwaldowski
zwaldowski / FromCString.swift
Created January 8, 2016 20:19
String initialization notes
// The gold standard, at least at present
let utf8Buffer: UnsafeBufferPointer<CChar> = ...
var arrayVersion = Array(utf8Buffer)
arrayVersion.append(0)
let string = String.fromCString(arrayVersion)
#!/usr/bin/env xcrun swift
import Cocoa
enum Playground {
enum OS: String {
case Mac = "osx"
case iOS = "ios"
case tvOS = "tvos"
#!/usr/bin/env xcrun swift
import Foundation
import ApplicationServices
func sendEventToSystemProcess(eventToSend: AEEventID) throws {
let target = NSAppleEventDescriptor(bundleIdentifier: "com.apple.loginwindow")
let event = NSAppleEventDescriptor(eventClass: numericCast(kCoreEventClass), eventID: eventToSend, targetDescriptor: target, returnID: numericCast(kAutoGenerateReturnID), transactionID: numericCast(kAnyTransactionID))
try event.sendEventWithOptions([.NoReply, .NeverInteract, .DontRecord], timeout: 2.0)
}
@zwaldowski
zwaldowski / gist:777c5b9e004122ba7930
Last active April 11, 2016 13:31 — forked from groue/gist:f2ecc98b8301ed63d843
A function declared as rethrows that synchronously executes a throwing block in a dispatch_queue.
import Dispatch
@_silgen_name("dispatch_sync") private func os_dispatch_sync(queue: dispatch_queue_t, @noescape _ block: dispatch_block_t)
@_silgen_name("dispatch_barrier_sync") private func os_dispatch_barrier_sync(queue: dispatch_queue_t, @noescape _ block: dispatch_block_t)
private func dispatch_sync_rethrow_wrapper<Return>(queue: dispatch_queue_t, @noescape dispatcher: (dispatch_queue_t, dispatch_block_t) -> Void, @noescape body: () throws -> Return, @noescape onError: ErrorType throws -> Void) rethrows -> Return {
var ret: Return!
var innerError: ErrorType?
os_dispatch_sync(queue) {
public final class StaticCStringArray {
private let storage: AnyForwardCollection<StaticString>
private lazy var pointers: ContiguousArray<UnsafeMutablePointer<Int8>> = {
ContiguousArray(self.storage.lazy.map { UnsafeMutablePointer($0.utf8Start) })
}()
init<Collection: CollectionType where Collection.Generator.Element == StaticString>(_ strings: Collection) {
self.storage = AnyForwardCollection(strings)
@zwaldowski
zwaldowski / DZWWithStackBuffer.h
Last active January 30, 2016 16:17
Swift Stack Arrays
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#if defined(__APPLE__)
#include <malloc/malloc.h>
static inline size_t __attribute__((always_inline, availability(swift, unavailable))) _stackbuf_malloc_size(const void *_Nonnull ptr) { return malloc_size(ptr); }
#elif defined(__GNU_LIBRARY__)
#include <malloc.h>
static inline size_t __attribute__((always_inline, availability(swift, unavailable))) _stackbuf_malloc_size(const void *_Nonnull ptr) {
func postAllEvents(events: [Event]) {
log("Ready to post!")
let batch = Array(events.lazy.filter(didNotProcessEventOnPreviousRun).prefix(100))
func finished(processedIDs: Set<String>) {
dispatch_async(dispatch_get_main_queue()) {
self.log("Finished posting \(processedIDs.count) events.")
self.savePostedEventIDs(processedIDs)
}