internal/restic: Make FileType a uint8 instead of a string

The string form was presumably useful before the introduction of
layouts, but right now it just makes call sequences and garbage
collection more expensive (the latter because every string contains
a pointer to be scanned).
This commit is contained in:
greatroar 2022-10-16 10:36:37 +02:00
parent 22147e1e02
commit b513597546
2 changed files with 47 additions and 23 deletions

View File

@ -7,18 +7,38 @@ import (
)
// FileType is the type of a file in the backend.
type FileType string
type FileType uint8
// These are the different data types a backend can store.
const (
PackFile FileType = "data" // use data, as packs are stored under /data in repo
KeyFile FileType = "key"
LockFile FileType = "lock"
SnapshotFile FileType = "snapshot"
IndexFile FileType = "index"
ConfigFile FileType = "config"
PackFile FileType = 1 + iota
KeyFile
LockFile
SnapshotFile
IndexFile
ConfigFile
)
func (t FileType) String() string {
s := "invalid"
switch t {
case PackFile:
// Spelled "data" instead of "pack" for historical reasons.
s = "data"
case KeyFile:
s = "key"
case LockFile:
s = "lock"
case SnapshotFile:
s = "snapshot"
case IndexFile:
s = "index"
case ConfigFile:
s = "config"
}
return s
}
// Handle is used to store and access data in a backend.
type Handle struct {
Type FileType
@ -36,10 +56,6 @@ func (h Handle) String() string {
// Valid returns an error if h is not valid.
func (h Handle) Valid() error {
if h.Type == "" {
return errors.New("type is empty")
}
switch h.Type {
case PackFile:
case KeyFile:
@ -48,7 +64,7 @@ func (h Handle) Valid() error {
case IndexFile:
case ConfigFile:
default:
return errors.Errorf("invalid Type %q", h.Type)
return errors.Errorf("invalid Type %d", h.Type)
}
if h.Type == ConfigFile {

View File

@ -1,20 +1,28 @@
package restic
import "testing"
import (
"testing"
var handleTests = []struct {
h Handle
valid bool
}{
{Handle{Name: "foo"}, false},
{Handle{Type: "foobar"}, false},
{Handle{Type: ConfigFile, Name: ""}, true},
{Handle{Type: PackFile, Name: ""}, false},
{Handle{Type: "", Name: "x"}, false},
{Handle{Type: LockFile, Name: "010203040506"}, true},
rtest "github.com/restic/restic/internal/test"
)
func TestHandleString(t *testing.T) {
rtest.Equals(t, "<data/foobar>", Handle{Type: PackFile, Name: "foobar"}.String())
rtest.Equals(t, "<lock/1>", Handle{Type: LockFile, Name: "1"}.String())
}
func TestHandleValid(t *testing.T) {
var handleTests = []struct {
h Handle
valid bool
}{
{Handle{Name: "foo"}, false},
{Handle{Type: 0}, false},
{Handle{Type: ConfigFile, Name: ""}, true},
{Handle{Type: PackFile, Name: ""}, false},
{Handle{Type: LockFile, Name: "010203040506"}, true},
}
for i, test := range handleTests {
err := test.h.Valid()
if err != nil && test.valid {