Skip to content
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

types/time: filter string that cannot be a unix timestamp #1715

Merged
merged 4 commits into from
Dec 3, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
15 changes: 14 additions & 1 deletion types/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,20 @@ func (t *Time) UnmarshalJSON(data []byte) error {
s = s[1 : len(s)-1]
}

if target := strings.Index(s, "."); target != -1 {
badSyntax := false
target := strings.IndexFunc(s, func(r rune) bool {
if r == '.' {
return true
}
// As a mistake this type can be used instead of time.Time and parse int below will not fail.
gloriousCode marked this conversation as resolved.
Show resolved Hide resolved
badSyntax = r < '0' || r > '9'
return badSyntax // exit early
gloriousCode marked this conversation as resolved.
Show resolved Hide resolved
})

if target != -1 {
if badSyntax {
return strconv.ErrSyntax
gloriousCode marked this conversation as resolved.
Show resolved Hide resolved
}
s = s[:target] + s[target+1:]
}

Expand Down
11 changes: 7 additions & 4 deletions types/time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,17 +56,20 @@ func TestUnmarshalJSON(t *testing.T) {

require.ErrorIs(t, json.Unmarshal([]byte(`"blurp"`), &testTime), strconv.ErrSyntax)
require.Error(t, json.Unmarshal([]byte(`"123456"`), &testTime))

// Captures bad syntax when type should be time.Time (RFC3339)
require.ErrorIs(t, json.Unmarshal([]byte(`"2025-03-28T08:00:00Z"`), &testTime), strconv.ErrSyntax)
// parse int failure
require.ErrorIs(t, json.Unmarshal([]byte(`"1606292218213.45.8"`), &testTime), strconv.ErrSyntax)
}

// 5046307 216.0 ns/op 168 B/op 2 allocs/op (current)
// 5030734 240.1 ns/op 168 B/op 2 allocs/op (current)
// 2716176 441.9 ns/op 352 B/op 6 allocs/op (previous)
func BenchmarkUnmarshalJSON(b *testing.B) {
var testTime Time
for i := 0; i < b.N; i++ {
err := json.Unmarshal([]byte(`"1691122380942.173000"`), &testTime)
if err != nil {
b.Fatal(err)
}
require.NoError(b, err)
}
}

Expand Down
Loading