-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathencdec.go
48 lines (45 loc) · 1.09 KB
/
encdec.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
package simplemaria
import (
"bytes"
"compress/flate"
"encoding/hex"
"io"
)
// MariaDB/MySQL does not handle some characters well.
// Compressing and hex encoding the value is one of many possible ways
// to avoid this. Using BLOB fields and different datatypes is another.
func Encode(value *string) error {
// Don't encode empty strings
if *value == "" {
return nil
}
var buf bytes.Buffer
compressorWriter, err := flate.NewWriter(&buf, 1) // compression level 1 (fastest)
if err != nil {
return err
}
compressorWriter.Write([]byte(*value))
compressorWriter.Close()
*value = hex.EncodeToString(buf.Bytes())
return nil
}
// Dehex and decompress the given string
func Decode(code *string) error {
// Don't decode empty strings
if *code == "" {
return nil
}
unhexedBytes, err := hex.DecodeString(*code)
if err != nil {
return err
}
buf := bytes.NewBuffer(unhexedBytes)
decompressorReader := flate.NewReader(buf)
decompressedBytes, err := io.ReadAll(decompressorReader)
decompressorReader.Close()
if err != nil {
return err
}
*code = string(decompressedBytes)
return nil
}