xref: /aosp_15_r20/external/skia/src/base/SkBase64.h (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2006 The Android Open Source Project
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #ifndef SkBase64_DEFINED
9 #define SkBase64_DEFINED
10 
11 #include <cstddef>
12 
13 struct SkBase64 {
14 public:
15     enum Error {
16         kNoError,
17         kPadError,
18         kBadCharError
19     };
20 
21     /**
22        Base64 encodes src into dst.
23 
24        Normally this is called once with 'dst' nullptr to get the required size, then again with an
25        allocated 'dst' pointer to do the actual encoding.
26 
27        @param dst nullptr or a pointer to a buffer large enough to receive the result
28 
29        @param encode nullptr for default encoding or a pointer to at least 65 chars.
30                      encode[64] will be used as the pad character.
31                      Encodings other than the default encoding cannot be decoded.
32 
33        @return the required length of dst for encoding.
34     */
35     static size_t Encode(const void* src, size_t length, void* dst, const char* encode = nullptr);
36 
37     /**
38        Returns the length of the buffer that needs to be allocated to encode srcDataLength bytes.
39     */
EncodedSizeSkBase6440     static size_t EncodedSize(size_t srcDataLength) {
41         // Take the floor of division by 3 to find the number of groups that need to be encoded.
42         // Each group takes 4 bytes to be represented in base64.
43         return ((srcDataLength + 2) / 3) * 4;
44     }
45 
46     /**
47        Base64 decodes src into dst.
48 
49        Normally this is called once with 'dst' nullptr to get the required size, then again with an
50        allocated 'dst' pointer to do the actual encoding.
51 
52        @param dst nullptr or a pointer to a buffer large enough to receive the result
53 
54        @param dstLength assigned the length dst is required to be. Must not be nullptr.
55     */
56     [[nodiscard]] static Error Decode(const void* src, size_t  srcLength,
57                                       void* dst, size_t* dstLength);
58 };
59 
60 #endif // SkBase64_DEFINED
61