Search code examples
c++boostboost-asioboost-beastbeast-websockets

Store a STL map into a Boost ConstBufferSequence


I'm trying to store a std::map<enum, int> in a boost::beast::multi_buffer. So far I've been using boost::asio::buffer_copy and boost::asio::buffer to store vectors and PODs. However, I couldn't find a way to store a STL map.

I've tried this:

auto t_map = std::map<CODES, int>(); // CODES is an enum type

auto t_map_size = t_map.size() * sizeof(std::pair<CODES, int>);
auto tmp_buffer = boost::asio::buffer(t_map, t_map_size); // this is not supported

auto size = boost::asio::buffer_copy(t_map_size , tmp_buffer);

boost::beast::multi_buffer buffer;
buffer.commit(size);
  1. Is there any way to store a std::map<enum, int> in a ConstBufferSequence? (because the boost::asio::buffer_copy needs one)
  2. If not, is there any workaround to store a std::map<enum, int> in a boost::beast::multi_buffer?

Thanks!


Solution

  • You can convert your map into vector of POD, as POD choose type which can store enum + int, for example int64_t:

    So create vector, scan your map creating items of vector using some bitwise operations and data is ready:

    auto t_map = std::map<CODES, int>(); // CODES is an enum type
    
    std::vector<int64_t> vec;
    for (auto&& elemMap : t_map)
    {
        int64_t val = elemMap.first;   // store key
        val <<= 32; // shift key
        val |= elemMap.second; // store value
    
        vec.push_back (val);
    }
    
    auto tmp_buffer = boost::asio::buffer(vec); // this is supported
    

    Unpack vector into map should be easy.