mirror of
https://github.com/restic/restic.git
synced 2026-09-19 10:47:58 +00:00
internal/data: extract HardlinkIndex from restorer
The HardlinkIndex is also used by `cmd_stats`, thus place it in a shared package.
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
package data
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
// hardlinkKey is a composed key for finding inodes on a specific device.
|
||||
type hardlinkKey struct {
|
||||
Inode, Device uint64
|
||||
}
|
||||
|
||||
// HardlinkIndex maps inodes on devices to associated values.
|
||||
type HardlinkIndex[T any] struct {
|
||||
m sync.Mutex
|
||||
index map[hardlinkKey]T
|
||||
}
|
||||
|
||||
// NewHardlinkIndex create a new index for hard links
|
||||
func NewHardlinkIndex[T any]() *HardlinkIndex[T] {
|
||||
return &HardlinkIndex[T]{
|
||||
index: make(map[hardlinkKey]T),
|
||||
}
|
||||
}
|
||||
|
||||
// Has checks whether the link already exist in the index.
|
||||
func (idx *HardlinkIndex[T]) Has(inode uint64, device uint64) bool {
|
||||
idx.m.Lock()
|
||||
defer idx.m.Unlock()
|
||||
_, ok := idx.index[hardlinkKey{inode, device}]
|
||||
|
||||
return ok
|
||||
}
|
||||
|
||||
// Add adds a link to the index.
|
||||
func (idx *HardlinkIndex[T]) Add(inode uint64, device uint64, value T) {
|
||||
idx.m.Lock()
|
||||
defer idx.m.Unlock()
|
||||
_, ok := idx.index[hardlinkKey{inode, device}]
|
||||
|
||||
if !ok {
|
||||
idx.index[hardlinkKey{inode, device}] = value
|
||||
}
|
||||
}
|
||||
|
||||
// Value obtains the filename from the index.
|
||||
func (idx *HardlinkIndex[T]) Value(inode uint64, device uint64) T {
|
||||
idx.m.Lock()
|
||||
defer idx.m.Unlock()
|
||||
return idx.index[hardlinkKey{inode, device}]
|
||||
}
|
||||
|
||||
// Remove removes a link from the index.
|
||||
func (idx *HardlinkIndex[T]) Remove(inode uint64, device uint64) {
|
||||
idx.m.Lock()
|
||||
defer idx.m.Unlock()
|
||||
delete(idx.index, hardlinkKey{inode, device})
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package data_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/restic/restic/internal/data"
|
||||
rtest "github.com/restic/restic/internal/test"
|
||||
)
|
||||
|
||||
// TestHardLinks contains various tests for HardlinkIndex.
|
||||
func TestHardLinks(t *testing.T) {
|
||||
|
||||
idx := data.NewHardlinkIndex[string]()
|
||||
|
||||
idx.Add(1, 2, "inode1-file1-on-device2")
|
||||
idx.Add(2, 3, "inode2-file2-on-device3")
|
||||
|
||||
sresult := idx.Value(1, 2)
|
||||
rtest.Equals(t, sresult, "inode1-file1-on-device2")
|
||||
|
||||
sresult = idx.Value(2, 3)
|
||||
rtest.Equals(t, sresult, "inode2-file2-on-device3")
|
||||
|
||||
bresult := idx.Has(1, 2)
|
||||
rtest.Equals(t, bresult, true)
|
||||
|
||||
bresult = idx.Has(1, 3)
|
||||
rtest.Equals(t, bresult, false)
|
||||
|
||||
idx.Remove(1, 2)
|
||||
bresult = idx.Has(1, 2)
|
||||
rtest.Equals(t, bresult, false)
|
||||
}
|
||||
Reference in New Issue
Block a user