]> Cypherpunks repositories - gostls13.git/commitdiff
strconv: use Quote to escape the input string for failed conversion errors
authorMatt Brown <mdbrown@google.com>
Thu, 28 Feb 2013 18:08:05 +0000 (10:08 -0800)
committerRob Pike <r@golang.org>
Thu, 28 Feb 2013 18:08:05 +0000 (10:08 -0800)
This reveals the presence of control and non-printable characters in the
errors returned by the Parse functions.  Also add unit tests for NumError.

R=golang-dev, r, rsc
CC=golang-dev
https://golang.org/cl/7393075

src/pkg/strconv/atof_test.go
src/pkg/strconv/atoi.go
src/pkg/strconv/atoi_test.go

index b4f3a6f08f9999ea3303eae0e6d65332208346d9..ba4933218b0a0abd3ee4d8bbf562064c98e9b031 100644 (file)
@@ -110,6 +110,7 @@ var atoftests = []atofTest{
        {"1e", "0", ErrSyntax},
        {"1e-", "0", ErrSyntax},
        {".e-1", "0", ErrSyntax},
+       {"1\x00.2", "0", ErrSyntax},
 
        // http://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/
        {"2.2250738585072012e-308", "2.2250738585072014e-308", nil},
index bdd5d71f875d425b2b602db8d942dcbf8b518917..21c690096531462fd6b8d6cec8a94fae57e293e8 100644 (file)
@@ -20,7 +20,7 @@ type NumError struct {
 }
 
 func (e *NumError) Error() string {
-       return "strconv." + e.Func + ": " + `parsing "` + e.Num + `": ` + e.Err.Error()
+       return "strconv." + e.Func + ": " + "parsing " + Quote(e.Num) + ": " + e.Err.Error()
 }
 
 func syntaxError(fn, str string) *NumError {
index d0e7b61dba8c1cba5bc6bd6d592353ef4bc844f0..94075730788902ab33ea12066668706f11aee0b6 100644 (file)
@@ -5,6 +5,7 @@
 package strconv_test
 
 import (
+       "errors"
        "reflect"
        . "strconv"
        "testing"
@@ -146,6 +147,16 @@ var atoi32tests = []atoi32Test{
        {"-2147483649", -1 << 31, ErrRange},
 }
 
+type numErrorTest struct {
+       num, want string
+}
+
+var numErrorTests = []numErrorTest{
+       {"0", `strconv.ParseFloat: parsing "0": failed`},
+       {"`", "strconv.ParseFloat: parsing \"`\": failed"},
+       {"1\x00.2", `strconv.ParseFloat: parsing "1\x00.2": failed`},
+}
+
 func init() {
        // The atoi routines return NumErrors wrapping
        // the error and the string.  Convert the tables above.
@@ -277,6 +288,19 @@ func TestParseInt(t *testing.T) {
        }
 }
 
+func TestNumError(t *testing.T) {
+       for _, test := range numErrorTests {
+               err := &NumError{
+                       Func: "ParseFloat",
+                       Num:  test.num,
+                       Err:  errors.New("failed"),
+               }
+               if got := err.Error(); got != test.want {
+                       t.Errorf(`(&NumError{"ParseFloat", %q, "failed"}).Error() = %v, want %v`, test.num, got, test.want)
+               }
+       }
+}
+
 func BenchmarkAtoi(b *testing.B) {
        for i := 0; i < b.N; i++ {
                ParseInt("12345678", 10, 0)