github.com/sagernet/sing@v0.4.0-beta.19.0.20240518125136-f67a0988a636/common/random/rng.go (about)

     1  package random
     2  
     3  import (
     4  	"encoding/binary"
     5  	"io"
     6  	"sync"
     7  
     8  	"github.com/sagernet/sing/common"
     9  )
    10  
    11  const (
    12  	rngMax  = 1 << 63
    13  	rngMask = rngMax - 1
    14  )
    15  
    16  type Source struct {
    17  	io.Reader
    18  }
    19  
    20  func (s Source) Int63() int64 {
    21  	return s.Int64() & rngMask
    22  }
    23  
    24  func (s Source) Int64() int64 {
    25  	var num int64
    26  	common.Must(binary.Read(s, binary.BigEndian, &num))
    27  	return num
    28  }
    29  
    30  func (s Source) Uint64() uint64 {
    31  	var num uint64
    32  	common.Must(binary.Read(s, binary.BigEndian, &num))
    33  	return num
    34  }
    35  
    36  func (s Source) Seed(int64) {
    37  }
    38  
    39  type SyncReader struct {
    40  	io.Reader
    41  	sync.Mutex
    42  }
    43  
    44  func (r *SyncReader) Read(p []byte) (n int, err error) {
    45  	r.Lock()
    46  	defer r.Unlock()
    47  	return r.Reader.Read(p)
    48  }