1/**
2 * Copyright 2021 Alibaba, Inc. and its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15
16 * \author Jiliang.ljl
17 * \date Mar 2021
18 * \brief Interface of Base64 encode & decode
19 */
20
21#ifndef __AILEGO_ENCODING_BASE64_H__
22#define __AILEGO_ENCODING_BASE64_H__
23
24#include <cstring>
25#include <string>
26
27namespace ailego {
28
29/*! Base64 encode & decode
30 */
31struct Base64 {
32 //! Encode the bytes in base64 encoding
33 static size_t Encode(const uint8_t *src, size_t len, uint8_t *dst);
34
35 //! Decode the bytes with base64 encoding
36 static size_t Decode(const uint8_t *src, size_t len, uint8_t *dst);
37
38 //! Encode the bytes in base64 encoding
39 static std::string Encode(const uint8_t *src, size_t len) {
40 std::string out;
41 out.resize((len + 2) / 3 * 4);
42 Encode(src, len, (uint8_t *)out.data());
43 return out;
44 }
45
46 //! Encode a stl-string in base64 encoding
47 static std::string Encode(const std::string &src) {
48 return Encode(reinterpret_cast<const uint8_t *>(src.c_str()), src.size());
49 }
50
51 //! Encode a c-string in base64 encoding
52 static std::string Encode(const char *src) {
53 return Encode(reinterpret_cast<const uint8_t *>(src), std::strlen(src));
54 }
55
56 //! Decode the bytes with base64 encoding
57 static std::string Decode(const uint8_t *src, size_t len) {
58 std::string out;
59 out.resize((len + 3) / 4 * 3);
60 out.resize(Decode(src, len, (uint8_t *)out.data()));
61 return out;
62 }
63
64 //! Decode a c-string with base64 encoding
65 static std::string Decode(const char *src) {
66 return Decode(reinterpret_cast<const uint8_t *>(src), std::strlen(src));
67 }
68
69 //! Decode a stl-string with base64 encoding
70 static std::string Decode(const std::string &src) {
71 return Decode(reinterpret_cast<const uint8_t *>(src.c_str()), src.size());
72 }
73};
74
75} // namespace ailego
76
77#endif // __AILEGO_ENCODING_BASE64_H__
78