-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathsnowflake.go
49 lines (39 loc) · 973 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
45
46
47
48
49
package tempest
import (
"encoding/json"
"os"
"strconv"
"time"
)
// 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
}
// Shortcut to calling os.Getenv method and casting to Snowflake.
func EnvToSnowflake(key string) (Snowflake, error) {
return StringToSnowflake(os.Getenv(key))
}
func (s Snowflake) String() string {
return strconv.FormatUint(uint64(s), 10)
}
func (s Snowflake) CreationTimestamp() time.Time {
return time.UnixMilli(int64(s>>22 + DISCORD_EPOCH))
}
func (s Snowflake) MarshalJSON() ([]byte, error) {
b := strconv.FormatUint(uint64(s), 10)
return json.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
}