Last active
October 19, 2019 17:56
-
-
Save m-dango/41d75cd7e32b294f9f5a2a7fdc4cc078 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
#!/usr/bin/env perl6 | |
use NativeCall; | |
my %*SUB-MAIN-OPTS = | |
:named-anywhere, | |
; | |
#| http://man7.org/linux/man-pages/man2/getrandom.2.html | |
#| https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom | |
sub MAIN ( | |
UInt $bytes = 8, #= Number of random bytes (defaults to 8) | |
UInt :$flags = 0, | |
--> Nil | |
) { | |
my Buf $buf.=allocate: $bytes; | |
LEAVE $buf.say; | |
if $*DISTRO.is-win { | |
rand-api( Nil, $buf, $bytes, 2 ); | |
} | |
else { | |
given rand-api( $buf, $bytes, $flags ) { | |
when -1 { | |
die sub strerror( long --> Str ) is native {*}( | |
cglobal |( 'c', v6; 'errno'; long ) ); | |
} | |
when * < $bytes { die 'got fewer bytes than requested' } | |
} | |
} | |
} | |
my &rand-api = $*DISTRO.is-win | |
?? sub ( Pointer, Buf, size_t, ulong --> ulong ) | |
is symbol('BCryptGenRandom') | |
is native('bcrypt') {*} | |
!! sub ( Buf, size_t, ulong --> ssize_t ) | |
is symbol('getrandom') | |
is native('c', v6) {*}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment