-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathencoding.go
More file actions
58 lines (48 loc) · 1.26 KB
/
encoding.go
File metadata and controls
58 lines (48 loc) · 1.26 KB
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
// Package share provides URL encoding for sharing configs.
package share
import (
"bytes"
"compress/gzip"
"fmt"
"math/big"
)
var characterSet = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~")
var base = big.NewInt(int64(len(characterSet)))
func encodeBuffer(data []byte) string {
value := new(big.Int).SetBytes(data)
if value.Sign() == 0 {
return ""
}
var encoded bytes.Buffer
zero := big.NewInt(0)
mod := new(big.Int)
for value.Cmp(zero) > 0 {
value.DivMod(value, base, mod)
encoded.WriteByte(characterSet[mod.Int64()])
}
// Reverse the result
result := encoded.Bytes()
for i, j := 0, len(result)-1; i < j; i, j = i+1, j-1 {
result[i], result[j] = result[j], result[i]
}
return string(result)
}
func gzipCompress(data []byte) ([]byte, error) {
var buf bytes.Buffer
w := gzip.NewWriter(&buf)
if _, err := w.Write(data); err != nil {
return nil, err
}
if err := w.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Encode compresses and encodes content for sharing via yapi.run/c/{encoded}
func Encode(content string) (string, error) {
compressed, err := gzipCompress([]byte(content))
if err != nil {
return "", fmt.Errorf("compression failed: %w", err)
}
return encodeBuffer(compressed), nil
}