forked from amatsagu/tempest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
snowflake.go
44 lines (34 loc) · 816 Bytes
/
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
package tempest
import (
"strconv"
"time"
"github.com/sugawarayuuta/sonnet"
)
// Snowflake represents a Discord's id snowflake.
type Snowflake uint64
func StringToSnowflake(s string) (Snowflake, error) {
i, err := strconv.ParseUint(s, 10, 64)
return Snowflake(i), err
}
func (s Snowflake) String() string {
return strconv.FormatUint(uint64(s), 10)
}
func (s Snowflake) CreationTimestamp() time.Time {
return time.UnixMilli(int64(s>>22 + EPOCH))
}
func (s Snowflake) MarshalJSON() ([]byte, error) {
b := strconv.FormatUint(uint64(s), 10)
return sonnet.Marshal(b)
}
func (s *Snowflake) UnmarshalJSON(b []byte) error {
str, err := strconv.Unquote(string(b))
if err != nil {
return err
}
i, err := strconv.ParseUint(str, 10, 64)
if err != nil {
return err
}
*s = Snowflake(i)
return nil
}