Skip to content

Commit

Permalink
fix error when discord sends 0 instead of null for snowfakes & wrap d…
Browse files Browse the repository at this point in the history
…ecoding errors
  • Loading branch information
topi314 committed Oct 15, 2022
1 parent 06f0dcc commit a0c2300
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions snowflake.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package snowflake

import (
"bytes"
"fmt"
"os"
"strconv"
"time"
Expand All @@ -10,6 +11,11 @@ import (
// Epoch is the discord epoch in milliseconds.
const Epoch = 1420070400000

var (
nullBytes = []byte("null")
zeroBytes = []byte("0")
)

// Parse parses a string into a snowflake ID.
// returns ID(0) if the string is "null"
func Parse(str string) (ID, error) {
Expand Down Expand Up @@ -66,16 +72,16 @@ func (id ID) MarshalJSON() ([]byte, error) {

// UnmarshalJSON unmarshals the snowflake ID from a JSON string.
func (id *ID) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, []byte("null")) {
if bytes.Equal(data, nullBytes) || bytes.Equal(data, zeroBytes) {
return nil
}
snowflake, err := strconv.Unquote(string(data))
if err != nil {
return err
return fmt.Errorf("failed to unquote snowflake: %w", err)
}
i, err := strconv.ParseUint(snowflake, 10, 64)
if err != nil {
return err
return fmt.Errorf("failed to parse snowflake as uint64: %w", err)
}
*id = ID(i)
return nil
Expand Down

0 comments on commit a0c2300

Please sign in to comment.