github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/utils/random/concurrent.go (about)

     1  /*
     2   * Copyright (C) 2021 The "MysteriumNetwork/node" Authors.
     3   *
     4   * This program is free software: you can redistribute it and/or modify
     5   * it under the terms of the GNU General Public License as published by
     6   * the Free Software Foundation, either version 3 of the License, or
     7   * (at your option) any later version.
     8   *
     9   * This program is distributed in the hope that it will be useful,
    10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12   * GNU General Public License for more details.
    13   *
    14   * You should have received a copy of the GNU General Public License
    15   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    16   */
    17  
    18  package random
    19  
    20  import (
    21  	"math/rand"
    22  	"sync"
    23  )
    24  
    25  type concurrentRandomSource struct {
    26  	src rand.Source
    27  	mux sync.Mutex
    28  }
    29  
    30  // NewConcurrentRandomSource constructs ConcurrentRandomSource, wrapping
    31  // existing rand.Source/rand.Source64
    32  func NewConcurrentRandomSource(src rand.Source) rand.Source {
    33  	src64, ok := src.(rand.Source64)
    34  	if ok {
    35  		return &concurrentRandomSource64{
    36  			src: src64,
    37  		}
    38  	}
    39  	return &concurrentRandomSource{
    40  		src: src,
    41  	}
    42  }
    43  
    44  // Seed is a part of rand.Source interface
    45  func (s *concurrentRandomSource) Seed(seed int64) {
    46  	s.mux.Lock()
    47  	defer s.mux.Unlock()
    48  	s.src.Seed(seed)
    49  }
    50  
    51  // Int63 is a part of rand.Source interface
    52  func (s *concurrentRandomSource) Int63() int64 {
    53  	s.mux.Lock()
    54  	defer s.mux.Unlock()
    55  	return s.src.Int63()
    56  }
    57  
    58  type concurrentRandomSource64 struct {
    59  	src rand.Source64
    60  	mux sync.Mutex
    61  }
    62  
    63  // Seed is a part of rand.Source interface
    64  func (s *concurrentRandomSource64) Seed(seed int64) {
    65  	s.mux.Lock()
    66  	defer s.mux.Unlock()
    67  	s.src.Seed(seed)
    68  }
    69  
    70  // Int63 is a part of rand.Source interface
    71  func (s *concurrentRandomSource64) Int63() int64 {
    72  	s.mux.Lock()
    73  	defer s.mux.Unlock()
    74  	return s.src.Int63()
    75  }
    76  
    77  // Uint64 is a part of rand.Source64 interface
    78  func (s *concurrentRandomSource64) Uint64() uint64 {
    79  	s.mux.Lock()
    80  	defer s.mux.Unlock()
    81  	return s.src.Uint64()
    82  }