Source file src/math/rand/v2/chacha8.go

     1  // Copyright 2023 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package rand
     6  
     7  import "internal/chacha8rand"
     8  
     9  // A ChaCha8 is a ChaCha8-based cryptographically strong
    10  // random number generator.
    11  type ChaCha8 struct {
    12  	state chacha8rand.State
    13  }
    14  
    15  // NewChaCha8 returns a new ChaCha8 seeded with the given seed.
    16  func NewChaCha8(seed [32]byte) *ChaCha8 {
    17  	c := new(ChaCha8)
    18  	c.state.Init(seed)
    19  	return c
    20  }
    21  
    22  // Seed resets the ChaCha8 to behave the same way as NewChaCha8(seed).
    23  func (c *ChaCha8) Seed(seed [32]byte) {
    24  	c.state.Init(seed)
    25  }
    26  
    27  // Uint64 returns a uniformly distributed random uint64 value.
    28  func (c *ChaCha8) Uint64() uint64 {
    29  	for {
    30  		x, ok := c.state.Next()
    31  		if ok {
    32  			return x
    33  		}
    34  		c.state.Refill()
    35  	}
    36  }
    37  
    38  // UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
    39  func (c *ChaCha8) UnmarshalBinary(data []byte) error {
    40  	return chacha8rand.Unmarshal(&c.state, data)
    41  }
    42  
    43  // MarshalBinary implements the encoding.BinaryMarshaler interface.
    44  func (c *ChaCha8) MarshalBinary() ([]byte, error) {
    45  	return chacha8rand.Marshal(&c.state), nil
    46  }
    47  

View as plain text