Initial commit
This commit is contained in:
58
adapters/randomsource/service.go
Normal file
58
adapters/randomsource/service.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package randomsource
|
||||
|
||||
import (
|
||||
"context"
|
||||
crand "crypto/rand"
|
||||
"io"
|
||||
"math/big"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
func NewService(ch chan [10]int, interval time.Duration, maxInt int64) *Service {
|
||||
return &Service{
|
||||
interval: interval,
|
||||
ch: ch,
|
||||
rand: crand.Reader,
|
||||
maxInt: maxInt,
|
||||
}
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
interval time.Duration
|
||||
rand io.Reader
|
||||
ch chan [10]int
|
||||
maxInt int64
|
||||
}
|
||||
|
||||
func (s *Service) SourceCh() <-chan [10]int {
|
||||
return s.ch
|
||||
}
|
||||
|
||||
func (s *Service) Start(ctx context.Context, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
|
||||
var res [10]int
|
||||
|
||||
ticker := time.NewTicker(s.interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
|
||||
case <-ticker.C:
|
||||
for i := 0; i < 10; i++ {
|
||||
v, err := crand.Int(s.rand, big.NewInt(s.maxInt))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
res[i] = int(v.Int64())
|
||||
}
|
||||
|
||||
s.ch <- res
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user