wouter...@publica.duodecim.org
unread,Sep 23, 2012, 10:29:11 PM9/23/12Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to golan...@googlegroups.com
Hello,
I'm serialising a struct into a []byte slice (for base64-encoding into a
cookie, but that's not relevant). There are several ways to do this,
such as formatting the data into a string with fmt and converting that
to []byte, using append to construct the []byte slice, or using a
bytes.Buffer.
I guess using fmt and converting the resulting string to []byte looks
easier than manually constructing the []byte slice, but perhaps this is
the slowest method. I'm not sure how one should weigh the use of strings
vs. []byte slices.
(I'm ignoring solutions such as the gob package here because I'd like
the data to be accessible to other languages.)
I was wondering which method of serialising to (plain) text is the most
idiomatic.
Opinions?
Some sample code:
type TimeStamp struct {
Stamp time.Time
Seqno uint16
Host []byte
Hmac []byte
}
func (ts *TimeStamp) String() string {
return fmt.Sprintf("%d.%d %d %s",
ts.Stamp.Unix(), ts.Stamp.Nanosecond(), ts.Seqno, ts.Host)
}
func (ts *TimeStamp) Bytes() []byte {
epoch := make([]byte, 20) // unix(10) + '.' + nsec(9)
epoch = strconv.AppendInt(epoch, ts.Stamp.Unix(), 10)
epoch = append(epoch, '.')
epoch = strconv.AppendInt(epoch, int64(ts.Stamp.Nanosecond()), 10)
var buf bytes.Buffer
buf.Write(epoch)
buf.WriteByte(0x20)
buf.Write(strconv.AppendUint(nil, uint64(ts.Seqno), 10))
buf.WriteByte(0x20)
buf.Write(ts.Host)
return buf.Bytes()
}