-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnowflake.go
106 lines (87 loc) · 2.33 KB
/
snowflake.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package snowflake
import (
"encoding/json"
"reflect"
"strconv"
"time"
)
// Snowflake represents a Discord snowflake.
// See https://discord.com/developers/docs/reference
// for more information.
type Snowflake int64
// Nil represents an empty Snowflake.
var Nil = (*Snowflake)(nil)
// Zero represents the zero value for a Snowflake.
var Zero = Snowflake(0)
// discordEpoch is the time of the first second of 2015, in milliseconds.
const discordEpoch = 1420070400000
// Parse constructs a Snowflake from s.
func Parse(s string) (Snowflake, error) {
if s == "" {
return Zero, nil
}
parsed, err := strconv.ParseInt(s, 10, 0)
return Snowflake(parsed), err
}
// MustParse is like Parse, but panics if it encounters an error.
func MustParse(s string) Snowflake {
flake, err := Parse(s)
if err != nil {
panic(err)
}
return flake
}
// FromTimestamp generates a Snowflake for the given time.
func FromTimestamp(time time.Time) Snowflake {
return Snowflake(time.UnixMilli()-discordEpoch) << 22
}
// Timestamp returns the number of milliseconds since discordEpoch.
func (s Snowflake) Timestamp() int64 {
return (int64(s) >> 22) + discordEpoch
}
// WorkerID returns the Snowflake's worker id.
func (s Snowflake) WorkerID() int64 {
return (int64(s) & 0x3E0000) >> 17
}
// ProcessID returns the Snowflake's process id.
func (s Snowflake) ProcessID() int64 {
return (int64(s) & 0x1F000) >> 12
}
// Increment returns the number of id's that have
// been generated on the Snowflake's process.
func (s Snowflake) Increment() int64 {
return int64(s) & 0xFFF
}
// UnmarshalJSON unmarshals data into s.
func (s *Snowflake) UnmarshalJSON(data []byte) error {
if !json.Valid(data) {
return &json.InvalidUnmarshalError{Type: reflect.TypeOf(s)}
}
start, stop := 0, len(data)
if data[0] == '"' && data[len(data)-1] == '"' {
start++
stop--
}
raw := data[start:stop]
if len(raw) == 0 {
*s = 0
return nil
}
parsed, err := strconv.Atoi(string(raw))
if err != nil {
return UnmarshalTypeError{
value: string(data),
typ: "int or string",
}
}
*s = Snowflake(parsed)
return nil
}
// MarshalJSON returns the JSON representation of s.
func (s Snowflake) MarshalJSON() ([]byte, error) {
return []byte(s.String()), nil
}
// String returns the string representation of s.
func (s Snowflake) String() string {
return strconv.FormatInt(int64(s), 10)
}