Last active
April 29, 2024 17:56
-
-
Save makasim/36f8bb33ab2dd1edba591e9d2018628d to your computer and use it in GitHub Desktop.
Deterministic ULID generation from int64 in #golang
This file contains hidden or 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" | |
| "time" | |
| "github.com/oklog/ulid/v2" | |
| "golang.org/x/crypto/sha3" | |
| ) | |
| type Event struct { | |
| id int64 | |
| createdAt time.Time | |
| Foo string | |
| Bar string | |
| } | |
| type IDEntropy int64 | |
| func (ide IDEntropy) Read(p []byte) (n int, err error) { | |
| data := make([]byte, 8) | |
| binary.LittleEndian.PutUint64(data, uint64(ide)) | |
| hash := make([]byte, len(p)) | |
| sha3.ShakeSum256(hash, data) | |
| p = append(p[:0], hash...) | |
| return len(p), nil | |
| } | |
| func main() { | |
| t := time.Unix(123, 567) | |
| uniq := make(map[string]struct{}) | |
| for i := 0; i < 1000000000; i++ { | |
| e := Event{ | |
| id: int64(i), | |
| createdAt: t, | |
| Foo: "foo", | |
| Bar: "bar", | |
| } | |
| id, err := ulid.New(ulid.Timestamp(e.createdAt), IDEntropy(e.id)) | |
| if err != nil { | |
| panic(err) | |
| } | |
| fmt.Printf("%d -> %s\n", e.id, id.String()) | |
| if _, ok := uniq[id.String()]; ok { | |
| fmt.Printf("%d -> %s\n", e.id, id.String()) | |
| panic("duplicate id") | |
| } else { | |
| uniq[id.String()] = struct{}{} | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment