1package driver
2
3import (
4 "bytes"
5 "time"
6)
7
8// Convert a string in [time.RFC3339Nano] format into a [time.Time]
9// if it roundtrips back to the same string.
10// This way times can be persisted to, and recovered from, the database,
11// but if a string is needed, [database/sql] will recover the same string.
12func maybeTime(text []byte) (_ time.Time, _ bool) {
13 // Weed out (some) values that can't possibly be
14 // [time.RFC3339Nano] timestamps.
15 if len(text) < len("2006-01-02T15:04:05Z") {
16 return
17 }
18 if len(text) > len(time.RFC3339Nano) {
19 return
20 }
21 if text[4] != '-' || text[10] != 'T' || text[16] != ':' {
22 return
23 }
24
25 // Slow path.
26 var buf [len(time.RFC3339Nano)]byte
27 date, err := time.Parse(time.RFC3339Nano, string(text))
28 if err == nil && bytes.Equal(text, date.AppendFormat(buf[:0], time.RFC3339Nano)) {
29 return date, true
30 }
31 return
32}