Last active
December 19, 2017 18:47
-
-
Save icholy/494b0a778bd4b5885bed21d241c1f996 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/binary" | |
"fmt" | |
"log" | |
"time" | |
) | |
// Layout: [8 bytes: unix timestamp][4 bytes: sequence id] | |
// Properties: | |
// * byte representation ordered chronologically & lexicographically | |
// * allows inserting out of chronological order | |
// * seeking to a Key{Seq: 0, Time: ts} will find the first record with the specified timestamp | |
var order = binary.LittleEndian | |
type Key struct { | |
Seq uint32 | |
Time time.Time | |
} | |
func ParseKey(buf []byte) (*Key, error) { | |
if len(buf) != 12 { | |
return nil, fmt.Errorf("key buffer must be 12 bytes") | |
} | |
ts := int64(order.Uint64(buf[:8])) | |
return &Key{ | |
Seq: order.Uint32(buf[8:]), | |
Time: time.Unix(ts, 0), | |
}, nil | |
} | |
func (k *Key) Bytes() []byte { | |
buf := make([]byte, 12) | |
order.PutUint32(buf[8:], k.Seq) | |
order.PutUint64(buf[:8], uint64(k.Time.Unix())) | |
return buf | |
} | |
func main() { | |
k1 := &Key{ | |
Seq: 123, | |
Time: time.Now(), | |
} | |
buf := k1.Bytes() | |
k2, err := ParseKey(buf) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("%v, %v\n", k1, k2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment