From 7298a961c9cccf8ce6379336af674490dc0b63b2 Mon Sep 17 00:00:00 2001 From: chai2010 Date: Wed, 26 Jun 2019 01:37:18 +0800 Subject: [PATCH] base64: add encode --- base64/base64.v | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/base64/base64.v b/base64/base64.v index 6f8c5df43d..64448166a3 100644 --- a/base64/base64.v +++ b/base64/base64.v @@ -47,3 +47,49 @@ fn decode(data string) string { 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) +}