Wyatt Hepler | 3c2e952 | 2020-01-09 16:08:54 -0800 | [diff] [blame] | 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 | |
Wyatt Hepler | e2cbadf | 2020-06-22 11:21:45 -0700 | [diff] [blame^] | 17 | #include <span> |
| 18 | |
Wyatt Hepler | 3c2e952 | 2020-01-09 16:08:54 -0800 | [diff] [blame] | 19 | #include "pw_base64/base64.h" |
Wyatt Hepler | 3c2e952 | 2020-01-09 16:08:54 -0800 | [diff] [blame] | 20 | |
| 21 | namespace pw::tokenizer { |
| 22 | |
| 23 | extern "C" size_t pw_TokenizerPrefixedBase64Encode( |
| 24 | const void* binary_message, |
| 25 | size_t binary_size_bytes, |
| 26 | void* output_buffer, |
| 27 | size_t output_buffer_size_bytes) { |
| 28 | const size_t encoded_size = base64::EncodedSize(binary_size_bytes) + 1; |
| 29 | |
| 30 | if (output_buffer_size_bytes < encoded_size) { |
| 31 | return 0; |
| 32 | } |
| 33 | |
| 34 | char* output = static_cast<char*>(output_buffer); |
| 35 | output[0] = kBase64Prefix; |
| 36 | |
Wyatt Hepler | e2cbadf | 2020-06-22 11:21:45 -0700 | [diff] [blame^] | 37 | base64::Encode(std::span(static_cast<const std::byte*>(binary_message), |
| 38 | binary_size_bytes), |
| 39 | &output[1]); |
Wyatt Hepler | 3c2e952 | 2020-01-09 16:08:54 -0800 | [diff] [blame] | 40 | |
| 41 | return encoded_size; |
| 42 | } |
| 43 | |
| 44 | extern "C" size_t pw_TokenizerPrefixedBase64Decode(const void* base64_message, |
| 45 | size_t base64_size_bytes, |
| 46 | void* output_buffer, |
| 47 | size_t output_buffer_size) { |
| 48 | const char* base64 = static_cast<const char*>(base64_message); |
| 49 | |
| 50 | if (base64_size_bytes == 0 || base64[0] != kBase64Prefix) { |
| 51 | return 0; |
| 52 | } |
| 53 | |
| 54 | return base64::Decode( |
| 55 | std::string_view(&base64[1], base64_size_bytes - 1), |
Wyatt Hepler | e2cbadf | 2020-06-22 11:21:45 -0700 | [diff] [blame^] | 56 | std::span(static_cast<std::byte*>(output_buffer), output_buffer_size)); |
Wyatt Hepler | 3c2e952 | 2020-01-09 16:08:54 -0800 | [diff] [blame] | 57 | } |
| 58 | |
| 59 | } // namespace pw::tokenizer |