mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
base64: add encode
This commit is contained in:
parent
b16828dd4d
commit
7298a961c9
@ -47,3 +47,49 @@ fn decode(data string) string {
|
|||||||
return tos(str, str_len+2)
|
return tos(str, str_len+2)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
EncodingTable = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
|
||||||
|
)
|
||||||
|
|
||||||
|
fn encode(data string) string {
|
||||||
|
input_length := data.len
|
||||||
|
output_length := 4 * ((input_length + 2) / 3)
|
||||||
|
|
||||||
|
mut i := 0
|
||||||
|
mut j := 0
|
||||||
|
mut str := malloc(output_length)
|
||||||
|
|
||||||
|
for i < input_length {
|
||||||
|
mut octet_a := 0
|
||||||
|
mut octet_b := 0
|
||||||
|
mut octet_c := 0
|
||||||
|
|
||||||
|
if i < input_length {
|
||||||
|
octet_a = int(data[i])
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
if i < input_length {
|
||||||
|
octet_b = int(data[i])
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
if i < input_length {
|
||||||
|
octet_c = int(data[i])
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
|
||||||
|
triple := ((octet_a << 0x10) + (octet_b << 0x08) + octet_c)
|
||||||
|
|
||||||
|
str[j+0] = EncodingTable[(triple >> 3 * 6) & 63] // 63 is 0x3F
|
||||||
|
str[j+1] = EncodingTable[(triple >> 2 * 6) & 63]
|
||||||
|
str[j+2] = EncodingTable[(triple >> 1 * 6) & 63]
|
||||||
|
str[j+3] = EncodingTable[(triple >> 0 * 6) & 63]
|
||||||
|
j += 4
|
||||||
|
}
|
||||||
|
|
||||||
|
mod_table := [0, 2, 1]
|
||||||
|
for i = 0; i < mod_table[input_length % 3]; i++ {
|
||||||
|
str[output_length - 1 - i] = `=`
|
||||||
|
}
|
||||||
|
|
||||||
|
return tos(str, output_length)
|
||||||
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user