mus-format / mus-go

A set of serialization primitives for Golang
MIT License
78 stars 3 forks source link

time.Time support ? #6

Closed sylr closed 1 year ago

sylr commented 1 year ago

I believe "native" support for time.Time would be useful.

Regards.

sylr commented 1 year ago

I did this in my project, maybe it could belong here:

func TimeMarshaller(t time.Time, bs []byte) (n int) {
    bt, _ := t.MarshalBinary()
    n += ord.MarshalSlice[byte](
        bt,
        mus.MarshallerFn[byte](raw.MarshalByte),
        bs[n:],
    )
    return n
}

func TimeUnmarshaller(bs []byte) (t time.Time, n int, err error) {
    if bt, i, err := ord.UnmarshalSlice[byte](mus.UnmarshallerFn[byte](raw.UnmarshalByte), bs); err != nil {
        return t, i, nil
    } else {
        if err := t.UnmarshalBinary(bt); err != nil {
            return t, i, err
        }
        n += i
    }
    return t, n, nil
}

func TimeSizer(t time.Time) (n int) {
    // time.MarshalBinary() returns 16 bytes max
    return varint.SizeInt(0) + 16
}
ymz-ncnk commented 1 year ago

This implementation is Golang-dependent, so I don't think it's a good fit.

sylr commented 1 year ago

Indeed.