-
Notifications
You must be signed in to change notification settings - Fork 402
/
reservoir.go
46 lines (39 loc) · 1.03 KB
/
reservoir.go
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
42
43
44
45
46
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package audit
import (
"math/rand"
"storj.io/common/storj"
)
const maxReservoirSize = 3
// Reservoir holds a certain number of segments to reflect a random sample.
type Reservoir struct {
Paths [maxReservoirSize]storj.Path
size int8
index int64
}
// NewReservoir instantiates a Reservoir.
func NewReservoir(size int) *Reservoir {
if size < 1 {
size = 1
} else if size > maxReservoirSize {
size = maxReservoirSize
}
return &Reservoir{
size: int8(size),
index: 0,
}
}
// Sample makes sure that for every segment in metainfo from index i=size..n-1,
// pick a random number r = rand(0..i), and if r < size, replace reservoir.Segments[r] with segment.
func (reservoir *Reservoir) Sample(r *rand.Rand, path storj.Path) {
reservoir.index++
if reservoir.index < int64(reservoir.size) {
reservoir.Paths[reservoir.index] = path
} else {
random := r.Int63n(reservoir.index)
if random < int64(reservoir.size) {
reservoir.Paths[random] = path
}
}
}