2019-08-21 16:49:27 +01:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package audit
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math/rand"
|
|
|
|
|
2019-12-27 11:48:47 +00:00
|
|
|
"storj.io/common/storj"
|
2019-08-21 16:49:27 +01:00
|
|
|
)
|
|
|
|
|
2019-09-05 16:40:52 +01:00
|
|
|
const maxReservoirSize = 3
|
2019-08-21 16:49:27 +01:00
|
|
|
|
2020-07-16 15:18:02 +01:00
|
|
|
// Reservoir holds a certain number of segments to reflect a random sample.
|
2019-08-21 16:49:27 +01:00
|
|
|
type Reservoir struct {
|
|
|
|
Paths [maxReservoirSize]storj.Path
|
|
|
|
size int8
|
|
|
|
index int64
|
|
|
|
}
|
|
|
|
|
2020-07-16 15:18:02 +01:00
|
|
|
// NewReservoir instantiates a Reservoir.
|
2019-08-21 16:49:27 +01:00
|
|
|
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,
|
2020-07-16 15:18:02 +01:00
|
|
|
// pick a random number r = rand(0..i), and if r < size, replace reservoir.Segments[r] with segment.
|
2019-08-21 16:49:27 +01:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|