Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reimplement random_bytes to be consistent with endianness #2

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 10 additions & 12 deletions src/random.cr
Original file line number Diff line number Diff line change
Expand Up @@ -298,19 +298,17 @@ module Random
# slice # => [217, 118, 38, 196]
# ```
def random_bytes(buf : Bytes) : Nil
n = buf.size / sizeof(typeof(next_u))
remaining = buf.size - n * sizeof(typeof(next_u))

slice = buf.to_unsafe.as(typeof(next_u)*).to_slice(n)
slice.each_index { |i| slice[i] = next_u }

if remaining > 0
bytes = next_u
remaining.times do |i|
bits = i * 8
mask = typeof(next_u).new(0xff << bits)
buf[-i - 1] = UInt8.new((bytes & mask) >> bits)
ptr = buf.to_unsafe
finish = buf.to_unsafe + buf.size

while ptr < finish
random = next_u
rand_ptr = pointerof(random).as(UInt8*)
if IO::ByteFormat::SystemEndian != IO::ByteFormat::LittleEndian
rand_ptr.to_slice(sizeof(typeof(next_u))).reverse!
end
rand_ptr.copy_to(ptr, {finish - ptr, sizeof(typeof(next_u))}.min)
ptr += sizeof(typeof(next_u))
end
end

Expand Down