1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
12 func TestNumberIsValid(t
*testing
.T
) {
13 // From: https://stackoverflow.com/a/13340826
14 var jsonNumberRegexp
= regexp
.MustCompile(`^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$`)
16 validTests
:= []string{
65 for _
, test
:= range validTests
{
66 if !isValidNumber(test
) {
67 t
.Errorf("%s should be valid", test
)
71 if err
:= Unmarshal([]byte(test
), &f
); err
!= nil {
72 t
.Errorf("%s should be valid but Unmarshal failed: %v", test
, err
)
75 if !jsonNumberRegexp
.MatchString(test
) {
76 t
.Errorf("%s should be valid but regexp does not match", test
)
80 invalidTests
:= []string{
104 for _
, test
:= range invalidTests
{
105 if isValidNumber(test
) {
106 t
.Errorf("%s should be invalid", test
)
110 if err
:= Unmarshal([]byte(test
), &f
); err
== nil {
111 t
.Errorf("%s should be invalid but unmarshal wrote %v", test
, f
)
114 if jsonNumberRegexp
.MatchString(test
) {
115 t
.Errorf("%s should be invalid but matches regexp", test
)
120 func BenchmarkNumberIsValid(b
*testing
.B
) {
121 s
:= "-61657.61667E+61673"
122 for i
:= 0; i
< b
.N
; i
++ {
127 func BenchmarkNumberIsValidRegexp(b
*testing
.B
) {
128 var jsonNumberRegexp
= regexp
.MustCompile(`^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$`)
129 s
:= "-61657.61667E+61673"
130 for i
:= 0; i
< b
.N
; i
++ {
131 jsonNumberRegexp
.MatchString(s
)