Skip to content

Commit 4e24ef1

Browse files
Bytes implementation (#161)
1 parent 437649a commit 4e24ef1

File tree

2 files changed

+37
-10
lines changed

2 files changed

+37
-10
lines changed

version.go

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
package version
55

66
import (
7-
"bytes"
87
"database/sql/driver"
98
"fmt"
109
"regexp"
@@ -382,22 +381,29 @@ func (v *Version) Segments64() []int64 {
382381
// missing parts (1.0 => 1.0.0) will be made into a canonicalized form
383382
// as shown in the parenthesized examples.
384383
func (v *Version) String() string {
385-
var buf bytes.Buffer
386-
fmtParts := make([]string, len(v.segments))
384+
return string(v.bytes())
385+
}
386+
387+
func (v *Version) bytes() []byte {
388+
var buf []byte
387389
for i, s := range v.segments {
388-
// We can ignore err here since we've pre-parsed the values in segments
389-
str := strconv.FormatInt(s, 10)
390-
fmtParts[i] = str
390+
if i > 0 {
391+
buf = append(buf, '.')
392+
}
393+
buf = strconv.AppendInt(buf, s, 10)
391394
}
392-
fmt.Fprintf(&buf, "%s", strings.Join(fmtParts, "."))
395+
393396
if v.pre != "" {
394-
fmt.Fprintf(&buf, "-%s", v.pre)
397+
buf = append(buf, '-')
398+
buf = append(buf, v.pre...)
395399
}
400+
396401
if v.metadata != "" {
397-
fmt.Fprintf(&buf, "+%s", v.metadata)
402+
buf = append(buf, '+')
403+
buf = append(buf, v.metadata...)
398404
}
399405

400-
return buf.String()
406+
return buf
401407
}
402408

403409
// Original returns the original parsed version as-is, including any

version_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -739,3 +739,24 @@ func BenchmarkVersionString(b *testing.B) {
739739
_ = v.String()
740740
}
741741
}
742+
743+
func BenchmarkCompareVersionV1(b *testing.B) {
744+
v, _ := NewVersion("3.4.5")
745+
746+
b.ResetTimer()
747+
b.ReportAllocs()
748+
for i := 0; i < b.N; i++ {
749+
v.Compare(v)
750+
}
751+
}
752+
753+
func BenchmarkVersionCompareV2(b *testing.B) {
754+
v, _ := NewVersion("1.2.3")
755+
o, _ := NewVersion("v1.2.3.4")
756+
757+
b.ResetTimer()
758+
b.ReportAllocs()
759+
for i := 0; i < b.N; i++ {
760+
v.Compare(o)
761+
}
762+
}

0 commit comments

Comments
 (0)