Skip to content

new: TextMarshal and TextUnmarshal #74

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions semver_test.go
Original file line number Diff line number Diff line change
@@ -441,6 +441,32 @@ func TestFinalizeVersion(t *testing.T) {
}
}

func TestMarshalText(t *testing.T) {
for _, test := range formatTests {
res, err := test.v.MarshalText()
if err != nil {
t.Fatalf("Unexpected error %q", err)
}
if string(res) != test.result {
t.Errorf("MarshalText, expected %q but got %q", test.result, string(res))
}
}
}

func TestUnmarshalText(t *testing.T) {
for _, test := range formatTests {
var v Version
err := v.UnmarshalText([]byte(test.result))
if err != nil {
t.Fatalf("Unexpected error %q", err)
} else if comp := v.Compare(test.v); comp != 0 {
t.Errorf("Parsing, expected %q but got %q, comp: %d ", test.v, v, comp)
} else if err := v.Validate(); err != nil {
t.Errorf("Error validating parsed version %q: %q", test.v, err)
}
}
}

func BenchmarkParseSimple(b *testing.B) {
const VERSION = "0.0.1"
b.ReportAllocs()
17 changes: 17 additions & 0 deletions v4/semver.go
Original file line number Diff line number Diff line change
@@ -221,6 +221,23 @@ func (v Version) Validate() error {
return nil
}

// MarshalText implements the encoding.TextMarshaler interface.
func (v Version) MarshalText() ([]byte, error) {
return []byte(v.String()), nil
}

// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (v *Version) UnmarshalText(data []byte) error {
value, err := Parse(string(data))
if err != nil {
return err
}

*v = value

return nil
}

// New is an alias for Parse and returns a pointer, parses version string and returns a validated Version or error
func New(s string) (*Version, error) {
v, err := Parse(s)