xref: /aosp_15_r20/external/pigweed/pw_tokenizer/base64.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2020 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 
15 #include "pw_tokenizer/base64.h"
16 
17 namespace pw::tokenizer {
18 
pw_tokenizer_PrefixedBase64Encode(const void * binary_message,size_t binary_size_bytes,void * output_buffer,size_t output_buffer_size_bytes)19 extern "C" size_t pw_tokenizer_PrefixedBase64Encode(
20     const void* binary_message,
21     size_t binary_size_bytes,
22     void* output_buffer,
23     size_t output_buffer_size_bytes) {
24   char* output = static_cast<char*>(output_buffer);
25   const size_t encoded_size = Base64EncodedBufferSize(binary_size_bytes);
26 
27   if (output_buffer_size_bytes < encoded_size) {
28     if (output_buffer_size_bytes > 0u) {
29       output[0] = '\0';
30     }
31 
32     return 0;
33   }
34 
35   output[0] = PW_TOKENIZER_NESTED_PREFIX;
36   base64::Encode(
37       span(static_cast<const std::byte*>(binary_message), binary_size_bytes),
38       &output[1]);
39   output[encoded_size - 1] = '\0';
40   return encoded_size - sizeof('\0');  // exclude the null terminator
41 }
42 
PrefixedBase64Encode(span<const std::byte> binary_message,InlineString<> & output)43 void PrefixedBase64Encode(span<const std::byte> binary_message,
44                           InlineString<>& output) {
45   output.push_back(PW_TOKENIZER_NESTED_PREFIX);
46   base64::Encode(binary_message, output);
47 }
48 
pw_tokenizer_PrefixedBase64Decode(const void * base64_message,size_t base64_size_bytes,void * output_buffer,size_t output_buffer_size)49 extern "C" size_t pw_tokenizer_PrefixedBase64Decode(const void* base64_message,
50                                                     size_t base64_size_bytes,
51                                                     void* output_buffer,
52                                                     size_t output_buffer_size) {
53   const char* base64 = static_cast<const char*>(base64_message);
54 
55   if (base64_size_bytes == 0 || base64[0] != PW_TOKENIZER_NESTED_PREFIX) {
56     return 0;
57   }
58 
59   return base64::Decode(
60       std::string_view(&base64[1], base64_size_bytes - 1),
61       span(static_cast<std::byte*>(output_buffer), output_buffer_size));
62 }
63 
64 }  // namespace pw::tokenizer
65