Created
December 10, 2016 00:07
-
-
Save rayfix/cee812b398411d5399218873df1ed10f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
private enum RandomSource { | |
static private let file = fopen("/dev/urandom","r")! | |
static private let queue = DispatchQueue(label: "random") | |
static func get(count: Int) -> [Int8] { | |
let capacity = count + 1 // fgets adds null termination | |
var data = UnsafeMutablePointer<Int8>.allocate(capacity: capacity) | |
defer { | |
data.deallocate(capacity: capacity) | |
} | |
queue.sync { | |
fgets(data, Int32(capacity), file) | |
} | |
return Array(UnsafeMutableBufferPointer(start: data, count: count)) | |
} | |
} | |
public extension Integer { | |
public static var randomized: Self { | |
let numbers = RandomSource.get(count: MemoryLayout<Self>.size) | |
return numbers.withUnsafeBufferPointer { bufferPointer in | |
return bufferPointer.baseAddress!.withMemoryRebound(to: Self.self, capacity: 1) { | |
return $0.pointee | |
} | |
} | |
} | |
} | |
Int8.randomized | |
UInt8.randomized | |
Int16.randomized | |
UInt16.randomized | |
Int16.randomized | |
UInt32.randomized | |
Int64.randomized | |
UInt64.randomized |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment