github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/crypto/rand/rand_arc4random.go (about)

     1  //go:build darwin || tinygo.wasm
     2  
     3  // This implementation of crypto/rand uses the arc4random_buf function
     4  // (available on both MacOS and WASI) to generate random numbers.
     5  //
     6  // Note: arc4random_buf (unlike what the name suggets) does not use the insecure
     7  // RC4 cipher. Instead, it uses a high-quality cipher, varying by the libc
     8  // implementation.
     9  
    10  package rand
    11  
    12  import "unsafe"
    13  
    14  func init() {
    15  	Reader = &reader{}
    16  }
    17  
    18  type reader struct {
    19  }
    20  
    21  func (r *reader) Read(b []byte) (n int, err error) {
    22  	if len(b) != 0 {
    23  		libc_arc4random_buf(unsafe.Pointer(&b[0]), uint(len(b)))
    24  	}
    25  	return len(b), nil
    26  }
    27  
    28  // void arc4random_buf(void *buf, size_t buflen);
    29  //
    30  //export arc4random_buf
    31  func libc_arc4random_buf(buf unsafe.Pointer, buflen uint)