1
0
Fork 0
mirror of https://github.com/diamondburned/arikawa.git synced 2024-11-10 00:45:48 +00:00
arikawa/discord/snowflake.go

83 lines
1.4 KiB
Go
Raw Normal View History

2020-01-02 05:39:52 +00:00
package discord
import (
"strconv"
2020-01-17 22:29:13 +00:00
"strings"
2020-01-02 05:39:52 +00:00
"time"
)
const DiscordEpoch = 1420070400000 * int64(time.Millisecond)
2020-01-21 04:30:13 +00:00
type Snowflake int64
2020-01-02 05:39:52 +00:00
func NewSnowflake(t time.Time) Snowflake {
return Snowflake(TimeToDiscordEpoch(t) << 22)
}
2020-01-22 07:24:15 +00:00
func ParseSnowflake(sf string) (Snowflake, error) {
i, err := strconv.ParseInt(sf, 10, 64)
if err != nil {
return 0, err
}
return Snowflake(i), nil
}
2020-01-04 04:19:24 +00:00
func (s *Snowflake) UnmarshalJSON(v []byte) error {
2020-01-17 22:29:13 +00:00
id := strings.Trim(string(v), `"`)
if id == "null" {
return nil
}
i, err := strconv.ParseInt(id, 10, 64)
2020-01-04 04:19:24 +00:00
if err != nil {
return err
}
2020-01-17 22:29:13 +00:00
*s = Snowflake(i)
2020-01-04 04:19:24 +00:00
return nil
}
func (s *Snowflake) MarshalJSON() ([]byte, error) {
2020-01-17 22:29:13 +00:00
var id string
switch i := int64(*s); i {
case -1: // @me
id = "@me"
2020-01-19 06:06:00 +00:00
case 0:
return []byte("null"), nil
2020-01-17 22:29:13 +00:00
default:
id = strconv.FormatInt(i, 10)
}
return []byte(`"` + id + `"`), nil
2020-01-04 04:19:24 +00:00
}
2020-01-02 05:39:52 +00:00
func (s Snowflake) String() string {
return strconv.FormatUint(uint64(s), 10)
}
2020-01-15 04:43:34 +00:00
func (s Snowflake) Valid() bool {
2020-01-15 04:46:47 +00:00
return uint64(s) > 0
2020-01-15 04:43:34 +00:00
}
2020-01-02 05:39:52 +00:00
func (s Snowflake) Time() time.Time {
return time.Unix(0, int64(s)>>22*1000000+DiscordEpoch)
}
func (s Snowflake) Worker() uint8 {
return uint8(s & 0x3E0000)
}
func (s Snowflake) PID() uint8 {
return uint8(s & 0x1F000 >> 12)
}
func (s Snowflake) Increment() uint16 {
return uint16(s & 0xFFF)
}
func TimeToDiscordEpoch(t time.Time) int64 {
return t.UnixNano()/int64(time.Millisecond) - DiscordEpoch
}