From 2aa95c4e8748027c30dec3e89bb069dae14dfd3f Mon Sep 17 00:00:00 2001 From: Luke Shumaker Date: Sat, 11 Jun 2022 22:04:12 -0600 Subject: addr formatting --- pkg/btrfs/internal/addr.go | 25 +++++++++++++++++++++++++ pkg/btrfs/internal/addr_test.go | 36 ++++++++++++++++++++++++++++++++++++ pkg/btrfs/internal/misc.go | 6 +----- 3 files changed, 62 insertions(+), 5 deletions(-) create mode 100644 pkg/btrfs/internal/addr.go create mode 100644 pkg/btrfs/internal/addr_test.go (limited to 'pkg') diff --git a/pkg/btrfs/internal/addr.go b/pkg/btrfs/internal/addr.go new file mode 100644 index 0000000..7067982 --- /dev/null +++ b/pkg/btrfs/internal/addr.go @@ -0,0 +1,25 @@ +package internal + +import ( + "fmt" + + "lukeshu.com/btrfs-tools/pkg/util" +) + +type ( + PhysicalAddr int64 + LogicalAddr int64 +) + +func formatAddr(addr int64, f fmt.State, verb rune) { + switch verb { + case 'v', 's', 'q': + str := fmt.Sprintf("%#016x", addr) + fmt.Fprintf(f, util.FmtStateString(f, verb), str) + default: + fmt.Fprintf(f, util.FmtStateString(f, verb), addr) + } +} + +func (a PhysicalAddr) Format(f fmt.State, verb rune) { formatAddr(int64(a), f, verb) } +func (a LogicalAddr) Format(f fmt.State, verb rune) { formatAddr(int64(a), f, verb) } diff --git a/pkg/btrfs/internal/addr_test.go b/pkg/btrfs/internal/addr_test.go new file mode 100644 index 0000000..7af87bd --- /dev/null +++ b/pkg/btrfs/internal/addr_test.go @@ -0,0 +1,36 @@ +package internal_test + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + + "lukeshu.com/btrfs-tools/pkg/btrfs/internal" +) + +func TestAddrFormat(t *testing.T) { + t.Parallel() + type TestCase struct { + InputAddr internal.LogicalAddr + InputFmt string + Output string + } + addr := internal.LogicalAddr(0x3a41678000) + testcases := map[string]TestCase{ + "v": TestCase{InputAddr: addr, InputFmt: "%v", Output: "0x0000003a41678000"}, + "s": TestCase{InputAddr: addr, InputFmt: "%s", Output: "0x0000003a41678000"}, + "q": TestCase{InputAddr: addr, InputFmt: "%q", Output: `"0x0000003a41678000"`}, + "x": TestCase{InputAddr: addr, InputFmt: "%x", Output: "3a41678000"}, + "d": TestCase{InputAddr: addr, InputFmt: "%d", Output: "250205405184"}, + "neg": TestCase{InputAddr: -1, InputFmt: "%v", Output: "-0x000000000000001"}, + } + for tcName, tc := range testcases { + tc := tc + t.Run(tcName, func(t *testing.T) { + t.Parallel() + actual := fmt.Sprintf(tc.InputFmt, tc.InputAddr) + assert.Equal(t, tc.Output, actual) + }) + } +} diff --git a/pkg/btrfs/internal/misc.go b/pkg/btrfs/internal/misc.go index de8120a..2a98464 100644 --- a/pkg/btrfs/internal/misc.go +++ b/pkg/btrfs/internal/misc.go @@ -6,11 +6,7 @@ import ( "lukeshu.com/btrfs-tools/pkg/binstruct" ) -type ( - PhysicalAddr int64 - LogicalAddr int64 - Generation uint64 -) +type Generation uint64 type Key struct { ObjectID ObjID `bin:"off=0x0, siz=0x8"` // Each tree has its own set of Object IDs. -- cgit v1.2.3-2-g168b