c++ - Replace std::vector's buffer with a malloc'ed char array -
i have following class holding std::vector
resizable "buffer" data.
class packet { public: struct packetheader { size_t datasize = 0; size_t paddeddatasize = 0; } header_; const unsigned char* data() const { return &data_[0]; } unsigned char* data() { return &data_[0]; } /// changes size of data vector void resize(size_t sz) { header_.datasize = sz; // check if padding needed if (sz % aes_block_size != 0){ auto padding = aes_block_size - (sz % aes_block_size); data_.resize(sz + padding); (int = 1; <= padding; i++) { data_[(sz + padding) - i] = '\0'; } header_.paddeddatasize = sz + padding; } else{ data_.resize(sz); } } private: std::vector<unsigned char> data_; };
then i'm performing aes encryption on data before transfering them on network, requires temporary buffer of same size generate ciphertext, has copied vector.
void tcpconnection::send_packet(packet& pkg) { // cut out unrelevant lines of code // need temporary buffer encryption unsigned char* enc_out = (unsigned char*)malloc(pkg.header_.paddeddatasize); // aes-128 bit cbc encryption aes_cbc_encrypt(pkg.data(), enc_out, pkg.header_.paddeddatasize); // need copy data temporary buffer objects vector memcpy(pkg.data(), enc_out, pkg.header_.paddeddatasize); free(enc_out); io_service_.post([this, pkg]() { transmit(pkg); }); }
this seems rather expensive task. isn't there better way, kind of let vector take ownership of temporary buffer (did understand correctly these new std::move
, rvalue move semantics used kind of stuff?)
move semantics can avoid copy.
however instead of malloc'ing buffer encrypted data, use vector. can use std::move
replace contents of packet
's data_
member.
Comments
Post a Comment