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 <limits> 8 #include <string> 9 10 namespace fml { 11 12 static constexpr char kEncoding[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; 13 Base32Encode(std::string_view input)14std::pair<bool, std::string> Base32Encode(std::string_view input) { 15 if (input.empty()) { 16 return {true, ""}; 17 } 18 19 if (input.size() > std::numeric_limits<size_t>::max() / 8) { 20 return {false, ""}; 21 } 22 23 std::string output; 24 const size_t encoded_length = (input.size() * 8 + 4) / 5; 25 output.reserve(encoded_length); 26 27 uint16_t bit_stream = (static_cast<uint8_t>(input[0]) << 8); 28 size_t next_byte_index = 1; 29 int free_bits = 8; 30 31 while (free_bits < 16) { 32 output.push_back(kEncoding[(bit_stream & 0xf800) >> 11]); 33 bit_stream <<= 5; 34 free_bits += 5; 35 36 if (free_bits >= 8 && next_byte_index < input.size()) { 37 free_bits -= 8; 38 bit_stream += static_cast<uint8_t>(input[next_byte_index++]) << free_bits; 39 } 40 } 41 42 return {true, output}; 43 } 44 45 } // namespace fml 46