4 ms·
Nice post! To me, "math/big" feels like a big hammer for working on an int64; a nice alternative is "encoding/binary": func atomSlug(publishedAt time.Time)
by jminter 4y ago
Nice post!
To me, "math/big" feels like a big hammer for working on an int64; a nice alternative is "encoding/binary":
func atomSlug(publishedAt time.Time) string {
b := make([]byte, 0, 8)
b = binary.BigEndian.AppendUint64(b, uint64(publishedAt.Unix()))
b = bytes.TrimLeft(b, "\x00")
return lexicographicBase32Encoding.EncodeToString(b)
}
- pavon 4y agoNow that you made me think about it, I think both this approach and the original math.big one will cause more base32 digits to be added early than needed, breaking sorting earlier than needed, since slugs with different number of chars won't sort properly (think 1, 10, 11, ..., 2, 20...). Right now the time is converted to 4 bytes which then uses 7 base32 characters to encode. When the time rolls over to 33 bits in 2106, it will increase to 5 bytes encoded as 8 base32 chars, even though 7 base32 chars have enough bits (35) to represent the number. So perhaps a better way would be something like: func atomSlug(publishedAt time.Time) string { b := make([]byte, 0, 8) b = binary.BigEndian.AppendUint64(b, uint64(publishedAt.Unix())) s = lexicographicBase32Encoding.EncodeToString(b) return strings.TrimLeft(s, '2'); // '2' is all zero bits } This will stick with 7 base32 chars until you exceed 35 bits in 3058.