1
0
mirror of https://github.com/danog/liquid.git synced 2024-11-26 22:24:39 +01:00

Improve strftime error test

This commit is contained in:
Oliver Steele 2017-07-11 10:23:57 -04:00
parent 4163dfa842
commit 55cf56e9a0
2 changed files with 20 additions and 13 deletions

View File

@ -14,27 +14,33 @@ import (
"unsafe" "unsafe"
) )
// Note: The use of errno below is not thread-safe.
//
// Even if we added a mutex, it would not be thread-safe
// relative to other C stdlib calls that don't use that mutex.
//
// OTOH, I can't find a format string that C strftime thinks is illegal
// to test this with, so maybe this is a non-issue
// Strftime wraps the C Strftime function // Strftime wraps the C Strftime function
func Strftime(format string, t time.Time) (string, error) { func Strftime(format string, t time.Time) (string, error) {
_, off := t.Zone()
tz := t.Location()
var ( var (
secs = t.Sub(time.Date(1970, 1, 1, 0, 0, 0, 0, tz)).Seconds() - float64(off) _, offset = t.Zone()
tt = C.time_t(secs) tz = t.Location()
tm = C.struct_tm{} secs = t.Sub(time.Date(1970, 1, 1, 0, 0, 0, 0, tz)).Seconds() - float64(offset)
cFormat = C.CString(format) tt = C.time_t(secs)
cOut [256]C.char tm = C.struct_tm{}
cFormat = C.CString(format)
cOut [256]C.char
) )
defer C.free(unsafe.Pointer(cFormat)) // nolint: gas defer C.free(unsafe.Pointer(cFormat)) // nolint: gas
C.localtime_r(&tt, &tm) C.localtime_r(&tt, &tm)
size := C.strftime(&cOut[0], C.size_t(len(cOut)), cFormat, &tm) size := C.strftime(&cOut[0], C.size_t(len(cOut)), cFormat, &tm)
// This is not thread-safe. Even if we add a mutex, it is not thread-safe
// relative to other C stdlib calls that don't use it.
// OTOH, I can't find a format string that C strftime thinks is illegal,
// so maybe this is a non-issue
if size == 0 { if size == 0 {
errno := C.read_errno() // If size == 0 there *might* be an error.
return "", syscall.Errno(errno) if errno := C.read_errno(); errno != 0 {
return "", syscall.Errno(errno)
}
} }
return C.GoString(&cOut[0]), nil return C.GoString(&cOut[0]), nil
} }

View File

@ -42,6 +42,7 @@ func TestStrftime(t *testing.T) {
{"%Y/%-m/%-d", "2006/1/2"}, {"%Y/%-m/%-d", "2006/1/2"},
{"%a, %b %d, %Y %z", "Mon, Jan 02, 2006 -0500"}, {"%a, %b %d, %Y %z", "Mon, Jan 02, 2006 -0500"},
{"%a, %b %d, %Y %Z", "Mon, Jan 02, 2006 EST"}, {"%a, %b %d, %Y %Z", "Mon, Jan 02, 2006 EST"},
{"", ""},
} }
for _, test := range tests { for _, test := range tests {
s, err := Strftime(test.format, rt) s, err := Strftime(test.format, rt)