Created
November 14, 2021 18:12
-
-
Save EricRabil/ec7bd0db60966fe84fed638c12fda55f to your computer and use it in GitHub Desktop.
Seed a Hasher at runtime instead of through an environment variable
This file contains hidden or 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
extension Hasher { | |
static func randomSeed() -> [UInt8] { | |
Array(unsafeUninitializedCapacity: 32) { pointer, initializedCount in | |
for i in 0..<32 { | |
pointer[i] = UInt8(arc4random()) | |
} | |
initializedCount = 32 | |
} | |
} | |
init(seed: [UInt8]) { | |
guard seed.count == 32 else { | |
preconditionFailure("Seed must be exactly 32 bytes") | |
} | |
let buffer = UnsafeMutableRawBufferPointer.allocate(byteCount: MemoryLayout<Hasher>.size, alignment: MemoryLayout<Hasher>.alignment) | |
for index in 0..<8 { | |
buffer[index] = 0 | |
} | |
for index in 8..<40 { | |
buffer[index] = seed[index - 8] | |
} | |
for index in 40..<72 { | |
buffer[index] = 0 | |
} | |
self = buffer.bindMemory(to: Hasher.self).baseAddress!.pointee | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment