3

I need to design an efficient and readable class with 2 main functions:

  • add_buffer(char* buffer) - add a buffer.
  • char* read_all() - get one big buffer that contains all the buffers that the user added until now (by order).

for example:

char first_buffer[] = {1,2,3};
char second_buffer[] = {4,5,6};

MyClass instance;
instance.add_buffer(first_buffer);
instance.add_buffer(second_buffer);
char* big_buffer = instance.read_all(); // big_buffer = [1,2,3,4,5,6]

NOTE: There are a lot of solutions for this problem but I'm looking for an efficient one because in real life the buffers will be many and big, and I want to save a lot of copying and reallocs (like what std::vector does). I'm also want a readble c++ code.

NOTE: The real life problem is: I'm reading data from an HTTP request that came to me at separated chunks. After all chunks arrived I want to return the whole data to the user.

Ofer
  • 333
  • 4
  • 14

3 Answers3

8

Use an std::vector<char> with enough memory reserved. Since C++11, you can access the internal buffer with std::vector::data() (until C++11, you have to use &*std::vector::begin()).

YSC
  • 38,212
  • 9
  • 96
  • 149
2

If you can use Boost, boost::algorithm::join will do:

#include <boost/algorithm/string/join.hpp>
#include <vector>
#include <iostream>

int main(int, char **)
{
    std::vector<std::string> list;
    list.push_back("Hello");
    list.push_back("World!");

    std::string joined = boost::algorithm::join(list, ", ");
    std::cout << joined << std::endl;
}

Output:

Hello, World!

Original answer by Tristram Gräbener

Community
  • 1
  • 1
GingerPlusPlus
  • 5,336
  • 1
  • 29
  • 52
0

Use some standard approach like,

  • start with some initial memory, say 256
  • whenever it gets full use reallocate and double the size.

If you don't want to do it yourself, use STL containers like

std::vector<char>

It automatically reallocates memory for you when buffer is full.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055