OLD | NEW |
(Empty) | |
| 1 // Copyright 2016 The Chromium 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 "components/base32/base32.h" |
| 6 |
| 7 #include <stddef.h> |
| 8 #include <algorithm> |
| 9 |
| 10 #include "base/logging.h" |
| 11 |
| 12 namespace base32 { |
| 13 |
| 14 namespace { |
| 15 constexpr char kEncoding[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; |
| 16 } // namespace |
| 17 |
| 18 std::string Base32Encode(base::StringPiece input, Base32EncodePolicy policy) { |
| 19 if (input.empty()) |
| 20 return std::string(); |
| 21 |
| 22 if (input.size() > std::numeric_limits<size_t>::max() / 8) { |
| 23 NOTREACHED() |
| 24 << "Input is too large and would overflow encoded size computation."; |
| 25 return std::string(); |
| 26 } |
| 27 |
| 28 // Per RFC4648, the output is formed of 8 characters per 40 bits of input and |
| 29 // another 8 characters for the last group of [1,39] bits in the input. |
| 30 // That is: ceil(input.size() * 8.0 / 40.0) * 8 == |
| 31 // ceil(input.size() / 5.0) * 8 == |
| 32 // ((input.size() + 4) / 5) * 8. |
| 33 const size_t padded_length = ((input.size() + 4) / 5) * 8; |
| 34 |
| 35 // When no padding is used, the output is exactly 1 character per 5 bits of |
| 36 // input and one more for the last [1,4] bits. |
| 37 // That is: ceil(input.size() * 8.0 / 5.0) == |
| 38 // (input.size() * 8 + 4) / 5. |
| 39 const size_t unpadded_length = (input.size() * 8 + 4) / 5; |
| 40 |
| 41 std::string output; |
| 42 const size_t encoded_length = policy == Base32EncodePolicy::INCLUDE_PADDING |
| 43 ? padded_length |
| 44 : unpadded_length; |
| 45 output.reserve(encoded_length); |
| 46 |
| 47 // A bit stream which will be read from the left and appended to from the |
| 48 // right as it's emptied. |
| 49 uint16_t bit_stream = (static_cast<uint8_t>(input[0]) << 8); |
| 50 size_t next_byte_index = 1; |
| 51 int free_bits = 8; |
| 52 while (free_bits < 16) { |
| 53 // Extract the 5 leftmost bits in the stream |
| 54 output.push_back(kEncoding[(bit_stream & 0xf800) >> 11]); |
| 55 bit_stream <<= 5; |
| 56 free_bits += 5; |
| 57 |
| 58 // If there is enough room in the bit stream, inject another byte (if there |
| 59 // are any left...). |
| 60 if (free_bits >= 8 && next_byte_index < input.size()) { |
| 61 free_bits -= 8; |
| 62 bit_stream += static_cast<uint8_t>(input[next_byte_index++]) << free_bits; |
| 63 } |
| 64 } |
| 65 |
| 66 if (policy == Base32EncodePolicy::INCLUDE_PADDING) { |
| 67 output.append(padded_length - unpadded_length, '='); |
| 68 } |
| 69 |
| 70 DCHECK_EQ(encoded_length, output.size()); |
| 71 return output; |
| 72 } |
| 73 |
| 74 } // namespace base32 |
OLD | NEW |