Created
June 1, 2024 00:48
-
-
Save sidepelican/ccced5ae6231a1179d62332b2ea2c0a8 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
public struct RandomUInt8Sequence: Sequence { | |
@usableFromInline var count: Int | |
public init(count: Int) { | |
self.count = count | |
} | |
public func makeIterator() -> Iterator { | |
Iterator(self) | |
} | |
public struct Iterator: IteratorProtocol { | |
private var count: Int | |
private var current: Int = 0 | |
private var buf: (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) = (0, 0, 0, 0, 0, 0, 0, 0) | |
init(_ wrapped: RandomUInt8Sequence) { | |
self.count = wrapped.count | |
} | |
public mutating func next() -> UInt8? { | |
guard current < count else { | |
return nil | |
} | |
defer { | |
self.current += 1 | |
} | |
let i = self.current % 8 | |
if i == 0 { | |
withUnsafeMutableBytes(of: &buf) { p in | |
p.bindMemory(to: UInt64.self).baseAddress!.pointee = UInt64.random(in: .min ... .max) | |
} | |
} | |
return withUnsafeBytes(of: &buf) { p in | |
p[i] | |
} | |
} | |
public typealias Element = UInt8 | |
} | |
@inlinable public func forEachSpecial(_ body: (Self.Element) throws -> Void) rethrows { | |
print("Using special forEach") | |
var i = 0 | |
while i + 8 < count { | |
var rand = UInt64.random(in: .min ... .max) | |
try withUnsafeBytes(of: &rand) { bytes in | |
for byte in bytes { | |
try body(byte) | |
} | |
} | |
i += 8 | |
} | |
for _ in i ..< count { | |
try body(UInt8.random(in: .min ... .max)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment