bnc | 9de6abe | 2021-04-28 06:24:19 -0700 | [diff] [blame] | 1 | // Copyright 2021 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 "common/quiche_text_utils.h" |
| 6 | |
| 7 | #include "absl/strings/escaping.h" |
| 8 | #include "absl/strings/str_cat.h" |
| 9 | #include "absl/strings/str_format.h" |
| 10 | |
| 11 | namespace quiche { |
| 12 | |
| 13 | // static |
| 14 | void QuicheTextUtils::Base64Encode(const uint8_t* data, |
| 15 | size_t data_len, |
| 16 | std::string* output) { |
| 17 | absl::Base64Escape(std::string(reinterpret_cast<const char*>(data), data_len), |
| 18 | output); |
| 19 | // Remove padding. |
| 20 | size_t len = output->size(); |
| 21 | if (len >= 2) { |
| 22 | if ((*output)[len - 1] == '=') { |
| 23 | len--; |
| 24 | if ((*output)[len - 1] == '=') { |
| 25 | len--; |
| 26 | } |
| 27 | output->resize(len); |
| 28 | } |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | // static |
| 33 | absl::optional<std::string> QuicheTextUtils::Base64Decode( |
| 34 | absl::string_view input) { |
| 35 | std::string output; |
| 36 | if (!absl::Base64Unescape(input, &output)) { |
| 37 | return absl::nullopt; |
| 38 | } |
| 39 | return output; |
| 40 | } |
| 41 | |
| 42 | // static |
| 43 | std::string QuicheTextUtils::HexDump(absl::string_view binary_data) { |
| 44 | const int kBytesPerLine = 16; // Maximum bytes dumped per line. |
| 45 | int offset = 0; |
| 46 | const char* p = binary_data.data(); |
| 47 | int bytes_remaining = binary_data.size(); |
| 48 | std::string output; |
| 49 | while (bytes_remaining > 0) { |
| 50 | const int line_bytes = std::min(bytes_remaining, kBytesPerLine); |
| 51 | absl::StrAppendFormat(&output, "0x%04x: ", offset); |
| 52 | for (int i = 0; i < kBytesPerLine; ++i) { |
| 53 | if (i < line_bytes) { |
| 54 | absl::StrAppendFormat(&output, "%02x", |
| 55 | static_cast<unsigned char>(p[i])); |
| 56 | } else { |
| 57 | absl::StrAppend(&output, " "); |
| 58 | } |
| 59 | if (i % 2) { |
| 60 | absl::StrAppend(&output, " "); |
| 61 | } |
| 62 | } |
| 63 | absl::StrAppend(&output, " "); |
| 64 | for (int i = 0; i < line_bytes; ++i) { |
| 65 | // Replace non-printable characters and 0x20 (space) with '.' |
| 66 | output += absl::ascii_isgraph(p[i]) ? p[i] : '.'; |
| 67 | } |
| 68 | |
| 69 | bytes_remaining -= line_bytes; |
| 70 | offset += line_bytes; |
| 71 | p += line_bytes; |
| 72 | absl::StrAppend(&output, "\n"); |
| 73 | } |
| 74 | return output; |
| 75 | } |
| 76 | |
| 77 | } // namespace quiche |