Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
base32.cc
Go to the documentation of this file.
1// Copyright 2013 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "flutter/fml/base32.h"
6
7#include <cstdint> // uint8_t
8#include <limits>
9#include <string>
10
11namespace fml {
12
13static constexpr char kEncoding[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
14
15std::pair<bool, std::string> Base32Encode(std::string_view input) {
16 if (input.empty()) {
17 return {true, ""};
18 }
19
20 if (input.size() > std::numeric_limits<size_t>::max() / 8) {
21 return {false, ""};
22 }
23
24 std::string output;
25 const size_t encoded_length = (input.size() * 8 + 4) / 5;
26 output.reserve(encoded_length);
27
28 Base32EncodeConverter converter;
29 converter.Append(static_cast<uint8_t>(input[0]));
30 size_t next_byte_index = 1;
31
32 while (converter.CanExtract()) {
33 output.push_back(kEncoding[converter.Extract()]);
34 if (converter.CanAppend() && next_byte_index < input.size()) {
35 converter.Append(static_cast<uint8_t>(input[next_byte_index++]));
36 }
37 }
38
39 if (converter.BitsAvailable() > 0) {
40 output.push_back(kEncoding[converter.Peek()]);
41 }
42
43 return {true, output};
44}
45
46static constexpr signed char kDecodeMap[] = {
47 // starting from ASCII 50 '2'
48 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1,
49 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
50 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25};
51
52static constexpr int kDecodeMapSize =
53 sizeof(kDecodeMap) / sizeof(kDecodeMap[0]);
54
55std::pair<bool, std::string> Base32Decode(const std::string& input) {
56 std::string result;
57 Base32DecodeConverter converter;
58 for (char c : input) {
59 int map_index = c - '2';
60 if (map_index < 0 || map_index >= kDecodeMapSize ||
61 kDecodeMap[map_index] == -1) {
62 return {false, result};
63 }
64 converter.Append(kDecodeMap[map_index]);
65 if (converter.CanExtract()) {
66 result.push_back(converter.Extract());
67 }
68 }
69 if (converter.Peek() != 0) {
70 // The padding should always be zero. Return false if not.
71 return {false, result};
72 }
73 return {true, result};
74}
75
76} // namespace fml
GAsyncResult * result
static constexpr int kDecodeMapSize
Definition base32.cc:52
static constexpr signed char kDecodeMap[]
Definition base32.cc:46
std::pair< bool, std::string > Base32Decode(const std::string &input)
Definition base32.cc:55
static constexpr char kEncoding[]
Definition base32.cc:13
std::pair< bool, std::string > Base32Encode(std::string_view input)
Definition base32.cc:15