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

     1  //go:build nrf || (stm32 && !(stm32f103 || stm32l0x1)) || (sam && atsamd51) || (sam && atsame5x) || esp32c3
     2  
     3  // If you update the above build constraint, you'll probably also need to update
     4  // src/runtime/rand_hwrng.go.
     5  
     6  package rand
     7  
     8  import (
     9  	"machine"
    10  )
    11  
    12  func init() {
    13  	Reader = &reader{}
    14  }
    15  
    16  type reader struct {
    17  }
    18  
    19  func (r *reader) Read(b []byte) (n int, err error) {
    20  	if len(b) == 0 {
    21  		return
    22  	}
    23  
    24  	var randomByte uint32
    25  	for i := range b {
    26  		if i%4 == 0 {
    27  			randomByte, err = machine.GetRNG()
    28  			if err != nil {
    29  				return n, err
    30  			}
    31  		} else {
    32  			randomByte >>= 8
    33  		}
    34  		b[i] = byte(randomByte)
    35  	}
    36  
    37  	return len(b), nil
    38  }