blasphem/internal/common/types.go
2022-11-13 12:04:44 -05:00

40 lines
857 B
Go

package common
// Convenience types
import (
"fmt"
"strconv"
"strings"
"time"
)
type (
// PyTimeStamp is a python-style long nano timestamp
PyTimestamp time.Time
// KeepZero is a special float that keeps the trailing zero on marshal
KeepZero float64
)
func (f KeepZero) MarshalJSON() ([]byte, error) {
if float64(f) == float64(int(f)) {
return []byte(strconv.FormatFloat(float64(f), 'f', 1, 32)), nil
}
return []byte(strconv.FormatFloat(float64(f), 'f', -1, 32)), nil
}
const PytTimeFormat = "2006-01-02T15:04:05.999999-07:00"
func (t *PyTimestamp) MarshalJSON() ([]byte, error) {
rv := fmt.Sprintf("%q", time.Time(*t).Format(PytTimeFormat))
return []byte(rv), nil
}
func (t *PyTimestamp) UnmarshalJSON(b []byte) error {
s := strings.Trim(string(b), `"`)
tm, err := time.Parse(PytTimeFormat, s)
*t = PyTimestamp(tm)
return err
}