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