-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshinyid.go
92 lines (74 loc) · 2.43 KB
/
shinyid.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Copyright 2023 itpey
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package shinyid
import (
"errors"
)
const (
base64URLCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
)
var (
base64URLCharsetIndex [256]byte // Lookup table for character indices
base64URLCharsetLen = len(base64URLCharset) // Length of the character set
)
func init() {
for i := 0; i < base64URLCharsetLen; i++ {
base64URLCharsetIndex[base64URLCharset[i]] = byte(i)
}
}
// ToShiny converts an id to a shiny.
func ToShiny(id uint64) string {
if id == 0 {
return "A"
}
var shiny [11]byte // Fixed-length array to store the shiny
i := 10 // Index for storing characters in the shiny array
for id > 0 {
shiny[i] = base64URLCharset[id&0x3F] // Extract the character from the character set
id >>= 6 // Shift the id by 6 bits to the right
i-- // Decrement the index
}
return string(shiny[i+1:]) // Convert the shiny array to a string
}
// ToId converts a shiny to its corresponding id.
func ToId(shiny string) (uint64, error) {
if shiny == "A" {
return 0, nil
}
// Check if the shiny is a valid shiny
if !isValidShiny(shiny) {
return 0, errors.New("input must be a valid shiny")
}
// Convert the shiny to base10 id
base10 := uint64(0)
for i := 0; i < len(shiny); i++ {
base64 := shiny[i]
base64Value := base64URLCharsetIndex[base64]
base10 = (base10 << 6) | uint64(base64Value)
}
return base10, nil
}
// isValidShiny checks if a given shiny is a valid shiny.
func isValidShiny(shiny string) bool {
for _, char := range shiny {
if !isAlphaNumeric(char) && char != '-' && char != '_' {
return false
}
}
return true
}
// isAlphaNumeric checks if a character is an alphanumeric character.
func isAlphaNumeric(char rune) bool {
return ('A' <= char && char <= 'Z') || ('a' <= char && char <= 'z') || ('0' <= char && char <= '9')
}