2023-08-11 08:32:43 +00:00
|
|
|
package fstree
|
|
|
|
|
|
|
|
import (
|
2024-09-10 08:01:30 +00:00
|
|
|
"sync"
|
2023-08-11 08:32:43 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// FileCounter used to count files in FSTree. The implementation must be thread-safe.
|
|
|
|
type FileCounter interface {
|
2024-09-10 08:01:30 +00:00
|
|
|
Set(count, size uint64)
|
|
|
|
Inc(size uint64)
|
|
|
|
Dec(size uint64)
|
2023-08-11 08:32:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type noopCounter struct{}
|
|
|
|
|
2024-09-10 08:01:30 +00:00
|
|
|
func (c *noopCounter) Set(uint64, uint64) {}
|
|
|
|
func (c *noopCounter) Inc(uint64) {}
|
|
|
|
func (c *noopCounter) Dec(uint64) {}
|
2023-08-11 08:32:43 +00:00
|
|
|
|
2024-02-08 15:04:18 +00:00
|
|
|
func counterEnabled(c FileCounter) bool {
|
|
|
|
_, noop := c.(*noopCounter)
|
|
|
|
return !noop
|
|
|
|
}
|
|
|
|
|
2023-08-11 08:32:43 +00:00
|
|
|
type SimpleCounter struct {
|
2024-09-10 08:01:30 +00:00
|
|
|
mtx sync.RWMutex
|
|
|
|
count uint64
|
|
|
|
size uint64
|
2023-08-11 08:32:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewSimpleCounter() *SimpleCounter {
|
|
|
|
return &SimpleCounter{}
|
|
|
|
}
|
|
|
|
|
2024-09-10 08:01:30 +00:00
|
|
|
func (c *SimpleCounter) Set(count, size uint64) {
|
|
|
|
c.mtx.Lock()
|
|
|
|
defer c.mtx.Unlock()
|
|
|
|
|
|
|
|
c.count = count
|
|
|
|
c.size = size
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *SimpleCounter) Inc(size uint64) {
|
|
|
|
c.mtx.Lock()
|
|
|
|
defer c.mtx.Unlock()
|
|
|
|
|
|
|
|
c.count++
|
|
|
|
c.size += size
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *SimpleCounter) Dec(size uint64) {
|
|
|
|
c.mtx.Lock()
|
|
|
|
defer c.mtx.Unlock()
|
|
|
|
|
|
|
|
if c.count > 0 {
|
|
|
|
c.count--
|
|
|
|
} else {
|
|
|
|
panic("fstree.SimpleCounter: invalid count")
|
|
|
|
}
|
|
|
|
if c.size >= size {
|
|
|
|
c.size -= size
|
|
|
|
} else {
|
|
|
|
panic("fstree.SimpleCounter: invalid size")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *SimpleCounter) CountSize() (uint64, uint64) {
|
|
|
|
c.mtx.RLock()
|
|
|
|
defer c.mtx.RUnlock()
|
|
|
|
|
|
|
|
return c.count, c.size
|
|
|
|
}
|