I was working with program that deals on how to encode the data by using Base64 encoding. my program was working well if i'll be using
std::string_view of base64 characters, that is:-
std::string_view textEnc{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/+"};
But if i'll be using std::string instead of std::string_view, the program stops unexpected.
I dont understand the reason, why this happens.
I use MinGW (GCC 9.2.0).
#include <vector>
#include <string_view>
#include <string>
#include <cstddef>
#include <algorithm>
#include <iostream>
class Base64Encoder {
public:
std::string toBase64(std::vector<unsigned char> const & data);
private:
const std::string_view textEnc{"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/+"};
const char paddingSymbol{'='};
};
std::string Base64Encoder::toBase64(std::vector<unsigned char> const & data) {
std::string result{};
result.resize(data.size() / 3 * 4);
auto resultItr = result.begin();
size_t i{0};
size_t j{0};
while(j++ < data.size() / 3) {
unsigned int value = (data[i] << 16) | (data[i + 1] << 8) | (data[i + 2]);
i+=3;
*resultItr++ = textEnc[(value & 0x00fc0000) >> 18];
*resultItr++ = textEnc[(value & 0x003f0000) >> 12];
*resultItr++ = textEnc[(value & 0x00000fc0) >> 6];
*resultItr++ = textEnc[value & 0x0000003f];
}
if(auto rest = data.size() / 3 - i; rest == 1) {
*resultItr++ = textEnc[(data[i] & 0x000000fc) >> 2];
*resultItr++ = textEnc[(data[i] << 4) & 0x00000003];
*resultItr++ = paddingSymbol;
*resultItr++ = paddingSymbol;
} else {
unsigned int value = (data[i] << 8) | (data[i + 1]);
*resultItr++ = textEnc[(value & 0x0000fc00) >> 10];
*resultItr++ = textEnc[(value & 0x000003f0) >> 4];
*resultItr++ = textEnc[(value & 0x0000000f) << 2];
*resultItr++ = paddingSymbol;
}
return result;
}
/**Helper machineries
//For constructing a string from vector and vice versa.
**/
namespace converter {
std::string toString(std::vector<unsigned char> const & data) {
std::string result{};
std::copy(std::begin(data), std::end(data), std::back_inserter((result)));
return result;
}
std::vector<unsigned char> toVector(std::string_view data) {
std::vector<unsigned char> result{};
std::copy(begin(data), end(data), std::back_inserter((result)));
return result;
}
}//End of namespace converter.
int main() {
Base64Encoder enc;
auto text = "textToBeEncoded";
std::cout << "before: " << text;
auto textEncoded = enc.toBase64(converter::toVector(text));
std::cout << "\nAfter: " << textEncoded;
}
User contributions licensed under CC BY-SA 3.0