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 namespace base32 { |
| 11 |
| 12 namespace { |
| 13 const char kEncoding[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; |
| 14 } // namespace |
| 15 |
| 16 void Base32Encode(base::StringPiece input, |
| 17 Base32EncodePolicy policy, |
| 18 std::string* output) { |
| 19 output->clear(); |
| 20 |
| 21 // Transform 5 input bytes into 8 output bytes at a time. |
| 22 // Based on the encoding process described in RFC4648, section 6. |
| 23 for (size_t input_offset = 0; input_offset < input.size(); |
| 24 input_offset += 5) { |
| 25 // Bits of input left to encode. |
| 26 size_t bits_remaining = |
| 27 std::min(size_t(5), input.size() - input_offset) * 8; |
| 28 // A buffer for up to 40 bits of input that is consumed 5 bits at a time. |
| 29 // 40 bits is used because it is the lowest common multiple of 5 and 8. |
| 30 uint64_t input_group = 0; |
| 31 |
| 32 // Load 8 bits at a time into the buffer. |
| 33 // Can't simply memcpy because of endianness. |
| 34 for (size_t i = 0; i < bits_remaining / 8; ++i) { |
| 35 input_group <<= 8; |
| 36 input_group |= static_cast<uint8_t>(input[input_offset + i]); |
| 37 } |
| 38 // Shift the bits we've set to start at the MSB, for ease of access. |
| 39 input_group <<= (64 - bits_remaining); |
| 40 |
| 41 // Output the |input_group| as up to 8 bytes in base32. |
| 42 // If we run out of bits, padding will make up the remaining bytes |
| 43 // (unless |policy| dictates otherwise). |
| 44 for (size_t output_count = 0; output_count < 8; ++output_count) { |
| 45 if (bits_remaining == 0) { |
| 46 if (policy == Base32EncodePolicy::INCLUDE_PADDING) |
| 47 output->append(8 - output_count, '='); |
| 48 break; |
| 49 } |
| 50 // Encode the first 5 bits, then shift them out of the buffer. |
| 51 output->push_back(kEncoding[input_group >> 59]); |
| 52 input_group <<= 5; |
| 53 // Subtract 5 bits, or however many are left, whichever is smaller. |
| 54 bits_remaining -= (bits_remaining >= 5) ? 5 : bits_remaining; |
| 55 } |
| 56 } |
| 57 } |
| 58 |
| 59 } // namespace base32 |
OLD | NEW |