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 #ifndef QUICHE_COMMON_QUICHE_TEXT_UTILS_H_ 6 #define QUICHE_COMMON_QUICHE_TEXT_UTILS_H_ 7 8 #include <optional> 9 #include <string> 10 11 #include "absl/hash/hash.h" 12 #include "absl/strings/ascii.h" 13 #include "absl/strings/escaping.h" 14 #include "absl/strings/match.h" 15 #include "absl/strings/string_view.h" 16 #include "quiche/common/platform/api/quiche_export.h" 17 18 namespace quiche { 19 20 struct QUICHE_EXPORT StringPieceCaseHash { operatorStringPieceCaseHash21 size_t operator()(absl::string_view data) const { 22 std::string lower = absl::AsciiStrToLower(data); 23 absl::Hash<absl::string_view> hasher; 24 return hasher(lower); 25 } 26 }; 27 28 struct QUICHE_EXPORT StringPieceCaseEqual { operatorStringPieceCaseEqual29 bool operator()(absl::string_view piece1, absl::string_view piece2) const { 30 return absl::EqualsIgnoreCase(piece1, piece2); 31 } 32 }; 33 34 // Various utilities for manipulating text. 35 class QUICHE_EXPORT QuicheTextUtils { 36 public: 37 // Returns a new string in which |data| has been converted to lower case. ToLower(absl::string_view data)38 static std::string ToLower(absl::string_view data) { 39 return absl::AsciiStrToLower(data); 40 } 41 42 // Removes leading and trailing whitespace from |data|. RemoveLeadingAndTrailingWhitespace(absl::string_view * data)43 static void RemoveLeadingAndTrailingWhitespace(absl::string_view* data) { 44 *data = absl::StripAsciiWhitespace(*data); 45 } 46 47 // Base64 encodes with no padding |data_len| bytes of |data| into |output|. 48 static void Base64Encode(const uint8_t* data, size_t data_len, 49 std::string* output); 50 51 // Decodes a base64-encoded |input|. Returns nullopt when the input is 52 // invalid. 53 static std::optional<std::string> Base64Decode(absl::string_view input); 54 55 // Returns a string containing hex and ASCII representations of |binary|, 56 // side-by-side in the style of hexdump. Non-printable characters will be 57 // printed as '.' in the ASCII output. 58 // For example, given the input "Hello, QUIC!\01\02\03\04", returns: 59 // "0x0000: 4865 6c6c 6f2c 2051 5549 4321 0102 0304 Hello,.QUIC!...." 60 static std::string HexDump(absl::string_view binary_data); 61 62 // Returns true if |data| contains any uppercase characters. ContainsUpperCase(absl::string_view data)63 static bool ContainsUpperCase(absl::string_view data) { 64 return std::any_of(data.begin(), data.end(), absl::ascii_isupper); 65 } 66 67 // Returns true if |data| contains only decimal digits. IsAllDigits(absl::string_view data)68 static bool IsAllDigits(absl::string_view data) { 69 return std::all_of(data.begin(), data.end(), absl::ascii_isdigit); 70 } 71 }; 72 73 } // namespace quiche 74 75 #endif // QUICHE_COMMON_QUICHE_TEXT_UTILS_H_ 76