type Cache struct { // Due to a bug in atomic size needs to be the first word in the struct, as // that's the only place where you're guaranteed to be 64-bit aligned on a // 32 bit system. See: https://golang.org/pkg/sync/atomic/#pkg-note-BUG size uint64 snapshotSize uint64
mu sync.RWMutex store storer maxSize uint64
// snapshots are the cache objects that are currently being written to tsm files // they're kept in memory while flushing so they can be queried along with the cache. // they are read only and should never be modified snapshot *Cache snapshotting bool
// This number is the number of pending or failed WriteSnaphot attempts since the last successful one. snapshotAttempts int
// A one time synchronization used to initial the cache with a store. Since the store can allocate a // a large amount memory across shards, we lazily create it. initialize atomic.Value initializedCount uint32 }
func newring(n int) (*ring, error) { if n <= 0 || n > partitions { return nil, fmt.Errorf("invalid number of paritions: %d", n) }
r := ring{ partitions: make([]*partition, n), // maximum number of partitions. }
// The trick here is to map N partitions to all points on the continuum, // such that the first eight bits of a given hash will map directly to one // of the N partitions. for i := 0; i < len(r.partitions); i++ { r.partitions[i] = &partition{ store: make(map[string]*entry), } } return &r, nil }
// Deduplicate returns a new slice with any values that have the same timestamp removed. // The Value that appears last in the slice is the one that is kept. The returned // Values are sorted if necessary. func (a Values) Deduplicate() Values { if len(a) <= 1 { return a }
// See if we're already sorted and deduped var needSort bool for i := 1; i < len(a); i++ { if a[i-1].UnixNano() >= a[i].UnixNano() { needSort = true break } }
if !needSort { return a }
// 先排序 sort.Stable(a) // 下面这段代码实际上就是去重,如果i和j指向的数据一样,则i不移动,让i指向的数据变成j指向的数据(本来就一样),然后j++;如果i和j指向的数据不一样,则都进行++,然后i指向j的数据。 var i int for j := 1; j < len(a); j++ { v := a[j] if v.UnixNano() != a[i].UnixNano() { i++ } a[i] = v