-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnowflake.go
More file actions
64 lines (49 loc) · 1.11 KB
/
snowflake.go
File metadata and controls
64 lines (49 loc) · 1.11 KB
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
package objects
import (
"encoding/json"
"strconv"
"time"
)
var _ SnowflakeObject = (*Snowflake)(nil)
const (
DiscordEpoch = 1420070400000
)
type Snowflake uint64
func (s *Snowflake) UnmarshalJSON(bytes []byte) error {
var snowflake string
err := json.Unmarshal(bytes, &snowflake)
if err != nil {
return err
}
if snowflake == "" || snowflake == "null" {
*s = 0
return nil
}
snowInt, err := strconv.ParseInt(snowflake, 10, 64)
if err != nil {
return err
}
*s = Snowflake(snowInt)
return nil
}
func (s Snowflake) MarshalJSON() ([]byte, error) {
return json.Marshal(s.String())
}
// CreatedAt returns a time.Time representing the time a Snowflake was created
func (s Snowflake) CreatedAt() Time {
timestampMs := (int64(s) >> 22) + DiscordEpoch
return Time{time.Unix(0, timestampMs*int64(time.Millisecond))}
}
func (s Snowflake) String() string {
return strconv.FormatUint(uint64(s), 10)
}
func (s Snowflake) GetID() Snowflake {
return s
}
func SnowflakeFromString(s string) (Snowflake, error) {
i, err := strconv.ParseUint(s, 10, 64)
if err != nil {
return 0, err
}
return Snowflake(i), nil
}