Created
July 25, 2023 21:40
-
-
Save iSnakeBuzz/a53a67db4e9e35ca46d5f8e7b4dd7bdf to your computer and use it in GitHub Desktop.
MongoDB Like Unique ID Generator
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 ( | |
"crypto/rand" | |
"encoding/binary" | |
"fmt" | |
"time" | |
) | |
type ObjectId [12]byte | |
var ( | |
processUniqueValue = make([]byte, 5) | |
counter = initCounter() | |
) | |
func init() { | |
// Generate a random 5-byte value for the process | |
if _, err := rand.Read(processUniqueValue); err != nil { | |
panic(err) | |
} | |
} | |
func initCounter() []byte { | |
// Generate a random 3-byte value for the counter | |
counter := make([]byte, 3) | |
if _, err := rand.Read(counter); err != nil { | |
panic(err) | |
} | |
return counter | |
} | |
func NewObjectId() ObjectId { | |
// Timestamp in seconds since the Unix epoch | |
timestamp := time.Now().Unix() | |
var id ObjectId | |
// Add 4-byte timestamp to the ObjectId | |
binary.BigEndian.PutUint32(id[0:4], uint32(timestamp)) | |
// Add 5-byte processUniqueValue to the ObjectId | |
copy(id[4:9], processUniqueValue) | |
// Add 3-byte counter to the ObjectId | |
copy(id[9:], counter) | |
incrementCounter() | |
return id | |
} | |
func (id ObjectId) ToString() string { | |
return fmt.Sprintf("%x", id) | |
} | |
func incrementCounter() { | |
for i := 2; i >= 0; i-- { | |
counter[i]++ | |
if counter[i] != 0 { | |
break | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment