Skip to content

Commit 2052dcb

Browse files
author
1911860538
committed
archive/tar: optimize nanosecond parsing in parsePAXTime
1 parent bc5f4a5 commit 2052dcb

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

src/archive/tar/strconv.go

+15-7
Original file line numberDiff line numberDiff line change
@@ -213,15 +213,23 @@ func parsePAXTime(s string) (time.Time, error) {
213213
}
214214

215215
// Parse the nanoseconds.
216-
if strings.Trim(sn, "0123456789") != "" {
217-
return time.Time{}, ErrHeader
216+
nanoDigits := [maxNanoSecondDigits]byte{}
217+
i := 0
218+
for _, c := range sn {
219+
if c < '0' || c > '9' {
220+
return time.Time{}, ErrHeader
221+
}
222+
// Right truncate
223+
if i < maxNanoSecondDigits {
224+
nanoDigits[i] = byte(c)
225+
i++
226+
}
218227
}
219-
if len(sn) < maxNanoSecondDigits {
220-
sn += strings.Repeat("0", maxNanoSecondDigits-len(sn)) // Right pad
221-
} else {
222-
sn = sn[:maxNanoSecondDigits] // Right truncate
228+
// Right pad
229+
for ; i < maxNanoSecondDigits; i++ {
230+
nanoDigits[i] = '0'
223231
}
224-
nsecs, _ := strconv.ParseInt(sn, 10, 64) // Must succeed
232+
nsecs, _ := strconv.ParseInt(string(nanoDigits[:]), 10, 64) // Must succeed after validation
225233
if len(ss) > 0 && ss[0] == '-' {
226234
return time.Unix(secs, -1*nsecs), nil // Negative correction
227235
}

0 commit comments

Comments
 (0)