File: service.go

package info (click to toggle)
golang-github-viant-toolbox 0.33.2-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 1,280 kB
  • sloc: makefile: 16
file content (41 lines) | stat: -rw-r--r-- 895 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package sampler

import (
	"math/rand"
	"sync"
	"time"
)

//Service represents a sampler service
type Service struct {
	rand            *rand.Rand
	acceptThreshold int32
	mux             sync.Mutex
	PCT             float64
}

//Accept accept sample meeting accept gaol PCT
func (s *Service) Accept() bool {
	s.mux.Lock()
	defer s.mux.Unlock()
	n := s.rand.Int31n(100000)
	return n < s.acceptThreshold
}

//Accept accept with threshold with PCT being ignored (same as PCT=100)
func (s *Service) AcceptWithThreshold(threshold float64) bool {
	s.mux.Lock()
	defer s.mux.Unlock()
	n := s.rand.Int31n(100000)
	return n < int32(threshold*1000.0)
}

//New creates a pct sampler
func New(acceptPCT float64) *Service {
	source := rand.NewSource(time.Now().UnixNano())
	return &Service{
		PCT:             acceptPCT,
		rand:            rand.New(source),
		acceptThreshold: int32(acceptPCT * 1000.0),
	}
}