1 // Copyright 2015 The Weave 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 LIBWEAVE_SRC_DATA_ENCODING_H_ 6 #define LIBWEAVE_SRC_DATA_ENCODING_H_ 7 8 #include <string> 9 #include <utility> 10 #include <vector> 11 12 namespace weave { 13 14 using WebParamList = std::vector<std::pair<std::string, std::string>>; 15 16 // Encode/escape string to be used in the query portion of a URL. 17 // If |encodeSpaceAsPlus| is set to true, spaces are encoded as '+' instead 18 // of "%20" 19 std::string UrlEncode(const char* data, bool encodeSpaceAsPlus); 20 21 inline std::string UrlEncode(const char* data) { 22 return UrlEncode(data, true); 23 } 24 25 // Decodes/unescapes a URL. Replaces all %XX sequences with actual characters. 26 // Also replaces '+' with spaces. 27 std::string UrlDecode(const char* data); 28 29 // Converts a list of key-value pairs into a string compatible with 30 // 'application/x-www-form-urlencoded' content encoding. 31 std::string WebParamsEncode(const WebParamList& params, bool encodeSpaceAsPlus); 32 33 inline std::string WebParamsEncode(const WebParamList& params) { 34 return WebParamsEncode(params, true); 35 } 36 37 // Parses a string of '&'-delimited key-value pairs (separated by '=') and 38 // encoded in a way compatible with 'application/x-www-form-urlencoded' 39 // content encoding. 40 WebParamList WebParamsDecode(const std::string& data); 41 42 // Encodes binary data using base64-encoding. 43 std::string Base64Encode(const void* data, size_t size); 44 45 // Encodes binary data using base64-encoding and wraps lines at 64 character 46 // boundary using LF as required by PEM (RFC 1421) specification. 47 std::string Base64EncodeWrapLines(const void* data, size_t size); 48 49 // Decodes the input string from Base64. 50 bool Base64Decode(const std::string& input, std::vector<uint8_t>* output); 51 52 // Helper wrappers to use std::string and std::vector<uint8_t> as binary data 53 // containers. 54 inline std::string Base64Encode(const std::vector<uint8_t>& input) { 55 return Base64Encode(input.data(), input.size()); 56 } 57 inline std::string Base64EncodeWrapLines(const std::vector<uint8_t>& input) { 58 return Base64EncodeWrapLines(input.data(), input.size()); 59 } 60 inline std::string Base64Encode(const std::string& input) { 61 return Base64Encode(input.data(), input.size()); 62 } 63 inline std::string Base64EncodeWrapLines(const std::string& input) { 64 return Base64EncodeWrapLines(input.data(), input.size()); 65 } 66 inline bool Base64Decode(const std::string& input, std::string* output) { 67 std::vector<uint8_t> blob; 68 if (!Base64Decode(input, &blob)) 69 return false; 70 *output = std::string{blob.begin(), blob.end()}; 71 return true; 72 } 73 74 } // namespace weave 75 76 #endif // LIBWEAVE_SRC_DATA_ENCODING_H_ 77