Skip to content

Commit 522dda4

Browse files
pdaurescbusbey
authored andcommitted
replaced regex with faster impl for float parsing (quickfixgo#143)
* replaced regex with faster impl for float parsing * added test cases for fix_float
1 parent dcbb623 commit 522dda4

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

fix_float.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package quickfix
22

33
import (
44
"fmt"
5-
"regexp"
65
"strconv"
76
)
87

@@ -22,8 +21,10 @@ func (f *FIXFloat) Read(bytes []byte) error {
2221
}
2322

2423
//strconv allows values like "+100.00", which is not allowed for FIX float types
25-
if valid, _ := regexp.MatchString("^[0-9.-]+$", string(bytes)); !valid {
26-
return fmt.Errorf("invalid value %v", string(bytes))
24+
for _, b := range bytes {
25+
if b != '.' && b != '-' && !isDecimal(b) {
26+
return fmt.Errorf("invalid value %v", string(bytes))
27+
}
2728
}
2829

2930
*f = FIXFloat(val)
@@ -34,3 +35,7 @@ func (f *FIXFloat) Read(bytes []byte) error {
3435
func (f FIXFloat) Write() []byte {
3536
return []byte(strconv.FormatFloat(float64(f), 'f', -1, 64))
3637
}
38+
39+
func isDecimal(b byte) bool {
40+
return '0' <= b && b <= '9'
41+
}

fix_float_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,12 @@ func TestFloatRead(t *testing.T) {
2929
expectError bool
3030
}{
3131
{[]byte("15"), 15.0, false},
32+
{[]byte("99.9"), 99.9, false},
33+
{[]byte("0.00"), 0.0, false},
34+
{[]byte("-99.9"), -99.9, false},
35+
{[]byte("-99.9.9"), 0.0, true},
3236
{[]byte("blah"), 0.0, true},
37+
{[]byte("1.a1"), 0.0, true},
3338
{[]byte("+200.00"), 0.0, true},
3439
}
3540

@@ -46,3 +51,11 @@ func TestFloatRead(t *testing.T) {
4651
}
4752
}
4853
}
54+
55+
func BenchmarkFloatRead(b *testing.B) {
56+
val := []byte("15.1234")
57+
for i := 0; i < b.N; i++ {
58+
var field FIXFloat
59+
field.Read(val)
60+
}
61+
}

0 commit comments

Comments
 (0)