Skip to content

Commit

Permalink
Merge pull request #1 from creack/bug/creack/fix-mem-leak
Browse files Browse the repository at this point in the history
Bug/creack/fix mem leak
  • Loading branch information
devdazed committed Dec 5, 2014
2 parents e251f21 + a0a7004 commit 3ca4e01
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 13 deletions.
30 changes: 17 additions & 13 deletions parse.go
Original file line number Diff line number Diff line change
@@ -1,28 +1,32 @@
package timeutils

// #include "approxidate.h"
// #include <stdlib.h>
// #cgo LDFLAGS: -lm
import "C"
import "time"
import "fmt"

// Takes a string and passes it through Approxidate
import (
"fmt"
"time"
"unsafe"
)

// ParseDateString takes a string and passes it through Approxidate
// Parses into a time.Time
func ParseDateString(dt string) (t time.Time, err error) {
func ParseDateString(dt string) (time.Time, error) {
date := C.struct_timeval{}

ok := C.approxidate(C.CString(dt), &date)
cStr := C.CString(dt)
ok := C.approxidate(cStr, &date)
C.free(unsafe.Pointer(cStr))
if int(ok) != 0 {
err = fmt.Errorf("Invlid Date Format %s", dt)
return
return time.Time{}, fmt.Errorf("Invlid Date Format %s", dt)
}

t = time.Unix(int64(date.tv_sec), int64(date.tv_usec)*1000)
return
return time.Unix(int64(date.tv_sec), int64(date.tv_usec)*1000), nil
}

// Parses a milliseconds-since-epoch time stamp to a time.Time
func ParseMillis(dt int64) (t time.Time, err error) {
t = time.Unix(0, dt*1000*1000)
return
// ParseMillis parses a milliseconds-since-epoch time stamp to a time.Time
func ParseMillis(dt int64) (time.Time, error) {
return time.Unix(0, dt*1000*1000), nil
}
30 changes: 30 additions & 0 deletions parse_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package timeutils

import (
"os"
"testing"
)

var testData = []struct{ in, out string }{
{"2014-12-05 09:51:20.939152 -0500", "2014-12-05 14:51:20.939152 +0000 UTC"},
{"2014-12-05 09:51:20.939152 -0500 EST", "2014-12-05 14:51:20.939152 +0000 UTC"},
{"2014-12-05 09:51:20.939152", "2014-12-05 09:51:20.939152 +0000 UTC"},
{"2014/12/05 09:51:20.939152", "2014-12-05 09:51:20.939152 +0000 UTC"},
{"2014.12.05 09:51:20.939152", "2014-12-05 09:51:20.939152 +0000 UTC"},
{"09:51:20.939152 2014-31-12", "2014-12-31 09:51:20.939152 +0000 UTC"},
{"09:51:20.939152am 2014-31-12", "2014-12-31 09:51:20.939152 +0000 UTC"},
{"09:51:20.939152pm 2014-31-12", "2014-12-31 21:51:20.939152 +0000 UTC"},
}

func TestParseDateString(t *testing.T) {
defer os.Setenv("TZ", os.Getenv("TZ"))
os.Setenv("TZ", "UTC")

for i, elem := range testData {
if tt, err := ParseDateString(elem.in); err != nil {
t.Error(err)
} else if elem.out != tt.String() {
t.Errorf("[%d] Unexpected parsed time.\nExpect:\t%s\nGot:\t%s\n", i, elem.out, tt)
}
}
}

0 comments on commit 3ca4e01

Please sign in to comment.