-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
enc.go
81 lines (66 loc) · 2.01 KB
/
enc.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
package internal
import (
"encoding/base64"
"encoding/hex"
"io"
"github.com/inoxlang/inox/internal/core"
"github.com/inoxlang/inox/internal/utils"
)
// encodeBase64 encodes to base 64 the bytes read from a readable.
func encodeBase64(_ *core.Context, readable core.Readable) core.String {
reader := readable.Reader()
var src []byte
if reader.AlreadyHasAllData() {
src = reader.GetBytesDataToNotModify()
} else {
slice, err := reader.ReadAll()
if err != nil {
panic(err)
}
src = slice.UnderlyingBytes()
}
return core.String(base64.StdEncoding.EncodeToString(src))
}
// decodeBase64 decodes base64 data read from a readable.
func decodeBase64(_ *core.Context, readable core.Readable) (*core.ByteSlice, error) {
var encoding = base64.StdEncoding
reader := readable.Reader()
if reader.AlreadyHasAllData() {
src := reader.GetBytesDataToNotModify()
buf := make([]byte, encoding.DecodedLen(len(src)))
n, err := encoding.Decode(buf, src)
return core.NewMutableByteSlice(buf[:n], ""), err
} else {
decoder := base64.NewDecoder(encoding, reader)
b, err := io.ReadAll(decoder)
return core.NewMutableByteSlice(b, ""), err
}
}
// encodeHex encodes to hexadecimal the bytes read from a readable.
func encodeHex(_ *core.Context, readable core.Readable) core.String {
reader := readable.Reader()
var src []byte
if reader.AlreadyHasAllData() {
src = reader.GetBytesDataToNotModify()
} else {
slice, err := reader.ReadAll()
if err != nil {
panic(err)
}
src = slice.UnderlyingBytes()
}
return core.String(hex.EncodeToString(src))
}
// decodeHex decodes hex data read from a readable.
func decodeHex(_ *core.Context, readable core.Readable) (*core.ByteSlice, error) {
reader := readable.Reader()
if reader.AlreadyHasAllData() {
src := reader.GetBytesDataToNotModify()
b, err := hex.DecodeString(utils.BytesAsString(src))
return core.NewMutableByteSlice(b, ""), err
} else {
decoder := hex.NewDecoder(reader)
b, err := io.ReadAll(decoder)
return core.NewMutableByteSlice(b, ""), err
}
}