Skip to content

Commit

Permalink
Implement Format on rat
Browse files Browse the repository at this point in the history
  • Loading branch information
bep committed Aug 5, 2024
1 parent 2ced9e0 commit c134461
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
9 changes: 9 additions & 0 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,15 @@ func (r rat[T]) String() string {
return fmt.Sprintf("%d/%d", r.num, r.den)
}

func (r rat[T]) Format(w fmt.State, v rune) {
switch v {
case 'f':
fmt.Fprintf(w, "%f", r.Float64())
default:
fmt.Fprintf(w, "%s", r.String())
}
}

func (r *rat[T]) UnmarshalText(text []byte) error {
s := string(text)
if !strings.Contains(s, "/") {
Expand Down
9 changes: 9 additions & 0 deletions helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package imagemeta

import (
"encoding"
"fmt"
"testing"

qt "github.com/frankban/quicktest"
Expand Down Expand Up @@ -106,4 +107,12 @@ func TestRat(t *testing.T) {
ru, _ = NewRat[uint32](4, 1)
c.Assert(ru.String(), qt.Equals, "4")
})

c.Run("Format", func(c *qt.C) {
ru, _ := NewRat[uint32](1, 3)
s := fmt.Sprintf("%.2f", ru)
c.Assert(s, qt.Equals, "0.333333")
s = fmt.Sprintf("%s", ru)

Check failure on line 115 in helpers_test.go

View workflow job for this annotation

GitHub Actions / test (1.21.x, ubuntu-latest)

should use String() instead of fmt.Sprintf (S1025)

Check failure on line 115 in helpers_test.go

View workflow job for this annotation

GitHub Actions / test (1.21.x, macos-latest)

should use String() instead of fmt.Sprintf (S1025)

Check failure on line 115 in helpers_test.go

View workflow job for this annotation

GitHub Actions / test (1.22.x, ubuntu-latest)

should use String() instead of fmt.Sprintf (S1025)

Check failure on line 115 in helpers_test.go

View workflow job for this annotation

GitHub Actions / test (1.22.x, macos-latest)

should use String() instead of fmt.Sprintf (S1025)
c.Assert(s, qt.Equals, "1/3")
})
}

0 comments on commit c134461

Please sign in to comment.