blob: 6ce4a4c05136666011518f278eb76901fb18bd50 [file] [log] [blame]
Wyatt Hepler3c2e9522020-01-09 16:08:54 -08001// 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 Heplere2cbadf2020-06-22 11:21:45 -070017#include <span>
18
Wyatt Hepler3c2e9522020-01-09 16:08:54 -080019#include "pw_base64/base64.h"
Wyatt Hepler3c2e9522020-01-09 16:08:54 -080020
21namespace pw::tokenizer {
22
23extern "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 Heplere2cbadf2020-06-22 11:21:45 -070037 base64::Encode(std::span(static_cast<const std::byte*>(binary_message),
38 binary_size_bytes),
39 &output[1]);
Wyatt Hepler3c2e9522020-01-09 16:08:54 -080040
41 return encoded_size;
42}
43
44extern "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 Heplere2cbadf2020-06-22 11:21:45 -070056 std::span(static_cast<std::byte*>(output_buffer), output_buffer_size));
Wyatt Hepler3c2e9522020-01-09 16:08:54 -080057}
58
59} // namespace pw::tokenizer