Skip to content

Commit 9a8893c

Browse files
authored
Add 'ParsePos' function (#50)
1 parent 68d3397 commit 9a8893c

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

ltx.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,28 @@ func NewPos(txID TXID, postApplyChecksum uint64) Pos {
7171
}
7272
}
7373

74+
// ParsePos parses Pos from its string representation.
75+
func ParsePos(s string) (Pos, error) {
76+
if len(s) != 33 {
77+
return Pos{}, fmt.Errorf("invalid formatted position length: %q", s)
78+
}
79+
80+
txid, err := ParseTXID(s[:16])
81+
if err != nil {
82+
return Pos{}, err
83+
}
84+
85+
checksum, err := strconv.ParseUint(s[17:], 16, 64)
86+
if err != nil {
87+
return Pos{}, fmt.Errorf("invalid checksum format: %q", s[17:])
88+
}
89+
90+
return Pos{
91+
TXID: txid,
92+
PostApplyChecksum: checksum,
93+
}, nil
94+
}
95+
7496
// String returns a string representation of the position.
7597
func (p Pos) String() string {
7698
return fmt.Sprintf("%s/%016x", p.TXID, p.PostApplyChecksum)

ltx_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,28 @@ func TestNewPos(t *testing.T) {
2525
}
2626
}
2727

28+
func TestPos_String(t *testing.T) {
29+
pos := ltx.NewPos(1000, 2000)
30+
if got, want := pos.String(), "00000000000003e8/00000000000007d0"; got != want {
31+
t.Fatalf("Pos = %s, want = %s", got, want)
32+
}
33+
}
34+
35+
func TestParsePos(t *testing.T) {
36+
t.Run("OK", func(t *testing.T) {
37+
if v, err := ltx.ParsePos("00000000000003e8/00000000000007d0"); err != nil {
38+
t.Fatal(err)
39+
} else if got, want := v, ltx.NewPos(1000, 2000); got != want {
40+
t.Fatalf("got=%d, want %d", got, want)
41+
}
42+
})
43+
t.Run("ErrTooShort", func(t *testing.T) {
44+
if _, err := ltx.ParsePos("00000000000003e8"); err == nil || err.Error() != `invalid formatted position length: "00000000000003e8"` {
45+
t.Fatal(err)
46+
}
47+
})
48+
}
49+
2850
func TestHeader_Validate(t *testing.T) {
2951
t.Run("OK", func(t *testing.T) {
3052
hdr := ltx.Header{

0 commit comments

Comments
 (0)