Hi all,
I am writing a program to read device /dev/urandom file to get
some random bytes. I am trying to bypass D's GC as I know the
length of the buffer needed. I tried using std.stdio.File and
rawRead but File cannot be used with @nogc. So I used
core.stdc.stdio and used traditional C style. My code is here -
https://dpaste.dzfl.pl/36e1df4cb99b (Also at end of post). I am
using fread instead of read because /dev/urandom can be accessed
by other programs (From this post -
http://insanecoding.blogspot.in/2014/05/a-good-idea-with-bad-usage-devurandom.html ). As you can see from code, I ended up doing pointer arithmetic. Is there a way of making this work with D slices? Can they be used as C-style pointers?
My D function used for getting random bytes:
@nogc ubyte[n] rand_bytes(uint n)() {
import core.stdc.stdio;
FILE *fp;
fp = fopen("/dev/urandom", "r");
ubyte[n] buf;
ubyte *bp = &buf[0];
uint bread = 0;
while (bread < n) {
auto toread = n - bread;
auto read = fread(bp, ubyte.sizeof, toread, fp);
bread += read;
bp += read;
}
fclose(fp);
return buf;
}