bwmarrin / snowflake

A simple to use Go (golang) package to generate or parse Twitter snowflake IDs
BSD 2-Clause "Simplified" License
2.98k stars 371 forks source link

Base64 should encode bytes rather than string representation of int64 #62

Open jiaoyuedave opened 8 months ago

jiaoyuedave commented 8 months ago
func main() {

    // Create a new Node with a Node number of 1
    node, err := snowflake.NewNode(1)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Generate a snowflake ID.
    id := node.Generate()

    // Print out the ID in a few different ways.
    fmt.Println(id)
    fmt.Println(id.Base64())
    b := id.IntBytes()
    fmt.Println(base64.StdEncoding.EncodeToString(b[:]))
}

result:

-129775853767749632
LTEyOTc3NTg1Mzc2Nzc0OTYzMg==
/jLxjG/AEAA=

dig into souce, i found that base64 method use string representation of int64 for encoding, which make no sense:

// Base64 returns a base64 string of the snowflake ID
func (f ID) Base64() string {
    return base64.StdEncoding.EncodeToString(f.Bytes())
}

// Bytes returns a byte slice of the snowflake ID
func (f ID) Bytes() []byte {
    return []byte(f.String())
}

it only make representation much longer.

bwmarrin commented 8 months ago

Thanks for the report, and good catch on this. Let me look at it and decide what we can do.