reprogl
1package hashid2
3import (4"errors"5"fmt"6
7"github.com/speps/go-hashids/v2"8)
9
10const (11User Option = 1 << iota12Commentator
13Male
14Female
15)
16
17type Option int18
19var hash *hashids.HashID20
21var WrongOptions = errors.New("hashid: wrong options")22
23func init() {24var err error25hash, err = hashids.NewWithData(&hashids.HashIDData{26Salt: "Thi5 is sa1t :)",27Alphabet: "1234567890ABCDEFGHJKLMNPQRSTUVWXYZ",28MinLength: 6,29})30if err != nil {31panic(err)32}33}
34
35func Encode(id int, options Option) (hashString string) {36hashString, err := encode(id, options)37if err != nil {38panic(err)39}40
41return42}
43
44func Decode(str string, isAvatar bool) (HashData, error) {45var data = HashData{Hash: str}46
47ids, err := decode(str)48if err != nil {49return data, err50}51if len(ids) != 2 {52return data, errors.New(fmt.Sprintf("hashid: incorrect result length: %d", len(ids)))53}54
55data.ID = ids[0]56data.options = Option(ids[1])57
58if isAvatar && !data.validOptions() {59return data, WrongOptions60}61
62return data, nil63}
64
65func decode(str string) ([]int, error) {66return hash.DecodeWithError(str)67}
68
69func encode(id int, options Option) (string, error) {70return hash.EncodeInt64([]int64{int64(id), int64(options)})71}
72