#include "../pch/pch.h" #include "CLewaimaiString.h" #include #include #include #include #include #include using namespace std; using namespace boost::archive::iterators; unsigned char ToHex(unsigned char x) { return x > 9 ? x + 55 : x + 48; } unsigned char FromHex(unsigned char x) { unsigned char y; if (x >= 'A' && x <= 'Z') y = x - 'A' + 10; else if (x >= 'a' && x <= 'z') y = x - 'a' + 10; else if (x >= '0' && x <= '9') y = x - '0'; else assert(0); return y; } CLewaimaiString::CLewaimaiString() { } CLewaimaiString::~CLewaimaiString() { } bool CLewaimaiString::base64_encode(const string& input, string* output) { typedef base64_from_binary> Base64EncodeIterator; stringstream result; try { copy(Base64EncodeIterator(input.begin()), Base64EncodeIterator(input.end()), ostream_iterator(result)); } catch (...) { return false; } size_t equal_count = (3 - input.length() % 3) % 3; for (size_t i = 0; i < equal_count; i++) { result.put('='); } *output = result.str(); return output->empty() == false; } bool CLewaimaiString::base64_decode(const string& input, string* output) { typedef transform_width, 8, 6> Base64DecodeIterator; stringstream result; try { copy(Base64DecodeIterator(input.begin()), Base64DecodeIterator(input.end()), ostream_iterator(result)); } catch (...) { return false; } *output = result.str(); return output->empty() == false; } void CLewaimaiString::trim(string &s) { if (!s.empty()) { s.erase(0, s.find_first_not_of(" ")); s.erase(s.find_last_not_of(" ") + 1); } } std::string CLewaimaiString::UrlEncode(const std::string& str) { std::string strTemp = ""; size_t length = str.length(); for (size_t i = 0; i < length; i++) { if (isalnum((unsigned char)str[i]) || (str[i] == '-') || (str[i] == '_') || (str[i] == '.') || (str[i] == '~')) strTemp += str[i]; else if (str[i] == ' ') strTemp += "+"; else { strTemp += '%'; strTemp += ToHex((unsigned char)str[i] >> 4); strTemp += ToHex((unsigned char)str[i] % 16); } } return strTemp; } std::string CLewaimaiString::UrlDecode(const std::string& str) { std::string strTemp = ""; size_t length = str.length(); for (size_t i = 0; i < length; i++) { if (str[i] == '+') strTemp += ' '; else if (str[i] == '%') { assert(i + 2 < length); unsigned char high = FromHex((unsigned char)str[++i]); unsigned char low = FromHex((unsigned char)str[++i]); strTemp += high * 16 + low; } else strTemp += str[i]; } return strTemp; }