-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder.go
105 lines (80 loc) · 1.95 KB
/
encoder.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
93
94
95
96
97
98
99
100
101
102
103
104
105
package uid
import (
"encoding/base32"
"encoding/base64"
"encoding/hex"
"math/big"
)
type Encoder interface {
EncodeToString(src []byte) string
DecodeString(s string) ([]byte, error)
}
func NewEncoder() Encoder {
return NewEncoderBase32Std()
}
func NewEncoderBase16Std() Encoder {
return NewEncoderCustom(&Base16Encoding{})
}
func NewEncoderBase32Std() Encoder {
return NewEncoderCustom(base32.StdEncoding.WithPadding(base32.NoPadding))
}
func NewEncoderBase32Hex() Encoder {
return NewEncoderCustom(base32.HexEncoding.WithPadding(base32.NoPadding))
}
func NewEncoderBase36() Encoder {
return NewEncoderCustom(&BaseXEncoding{base: 36})
}
func NewEncoderBaseX(base int) Encoder {
return NewEncoderCustom(&BaseXEncoding{base: base})
}
func NewEncoderBase62() Encoder {
return NewEncoderCustom(&BaseXEncoding{base: 62})
}
func NewEncoderBase64Std() Encoder {
return NewEncoderCustom(base64.RawStdEncoding)
}
func NewEncoderBase64Url() Encoder {
return NewEncoderCustom(base64.RawURLEncoding)
}
func NewEncoderCustom(encoder Encoder) Encoder {
return &Encoding{
Encoder: encoder,
}
}
type Encoding struct {
Encoder
}
type Base16Encoding struct{}
func (b Base16Encoding) EncodeToString(src []byte) string {
return hex.EncodeToString(src)
}
func (b Base16Encoding) DecodeString(s string) ([]byte, error) {
return hex.DecodeString(s)
}
type BaseXEncoding struct {
base int
}
func (b BaseXEncoding) EncodeToString(src []byte) string {
bi := new(big.Int)
bi.SetBytes(src)
return bi.Text(b.base)
}
func (b BaseXEncoding) DecodeString(s string) ([]byte, error) {
bi := new(big.Int)
bi.SetString(s, b.base)
return bi.Bytes(), nil
}
type MockEncoding struct {
EncodedString string
DecodedBytes []byte
DecodedErr error
}
func (e MockEncoding) EncodeToString(src []byte) string {
return e.EncodedString
}
func (e MockEncoding) DecodeString(s string) ([]byte, error) {
if e.DecodedErr != nil {
return nil, e.DecodedErr
}
return e.DecodedBytes, nil
}