looksLikeTime is a fast-path byte-prefix check that rejects strings which cannot possibly match any of the date/time formats we try below. Avoiding the time.Parse loop on the 99%+ of strings that obviously aren't times saves an enormous amount of allocations (each failed time.Parse allocates a *time
(s string)
| 252 | // payload values) returns false immediately, skipping 20 failed time.Parse |
| 253 | // calls — each of which would allocate ~120 bytes. |
| 254 | func looksLikeTime(s string) bool { |
| 255 | // strip leading whitespace cheaply |
| 256 | i := 0 |
| 257 | for i < len(s) && (s[i] == ' ' || s[i] == '\t') { |
| 258 | i++ |
| 259 | } |
| 260 | if i >= len(s) { |
| 261 | return false |
| 262 | } |
| 263 | c := s[i] |
| 264 | if c >= '0' && c <= '9' { |
| 265 | return true |
| 266 | } |
| 267 | // Check 3-letter prefix against weekday/month abbreviations. |
| 268 | if len(s)-i < 3 { |
| 269 | return false |
| 270 | } |
| 271 | switch s[i : i+3] { |
| 272 | case "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", |
| 273 | "Jan", "Feb", "Mar", "Apr", "May", "Jun", |
| 274 | "Jul", "Aug", "Sep", "Oct", "Nov", "Dec": |
| 275 | return true |
| 276 | } |
| 277 | return false |
| 278 | } |
| 279 | |
| 280 | // IsTime verifies whether a given string represents a valid date or not. |
| 281 | // |