Venelin
Venelin

Reputation: 3308

C++ how can I convert std::vector<std::byte> to const uint8_t *

The question is explained in the title.

How can I convert std::vector<std::byte> to const uint8_t * ?

Is this a correct approach:

class Packet {
public:
    Packet():
    std::vector<std::byte> body_buffer;
};

void Test(const Packet& packet) {
    flatbuffers::Verifier verifier(reinterpret_cast<const uint8_t *>(packet.body_buffer.data()), packet.body_size);
    bool check = Vibranium::VerifyLoginRequestBuffer(verifier);
    if(check){
        Logger::Log("Valid",Logger::LogLevel::Info);
    } else {
        Logger::Log("In valid check",Logger::LogLevel::Info);

    }
}

Note: packet.body_size is known but not shown in the sample. All is fine with that variable.

Verifier construct takes:

class Verifier FLATBUFFERS_FINAL_CLASS {
 public:
  Verifier(const uint8_t *buf, size_t buf_len, uoffset_t _max_depth = 64,
           uoffset_t _max_tables = 1000000, bool _check_alignment = true)
      : buf_(buf),
        size_(buf_len),
        depth_(0),
        max_depth_(_max_depth),
        num_tables_(0),
        max_tables_(_max_tables),
        upper_bound_(0),
        check_alignment_(_check_alignment) {
    FLATBUFFERS_ASSERT(size_ < FLATBUFFERS_MAX_BUFFER_SIZE);
  }
  ....

When I do that it seems it is not correct. Is there any other better way ? Even when I pass incorrect buffer type it always says it is Valid which is not true.

Upvotes: 0

Views: 1637

Answers (1)

eerorika
eerorika

Reputation: 238291

C++ how can I convert std::vector<std::byte> to const uint8_t *

Is this a correct approach:

flatbuffers::Verifier verifier(reinterpret_cast<const uint8_t *>(packet.body_buffer.data()), packet.body_size);

The conversion can be correct, under these conditions:

static_assert(std::is_same_v<uint8_t, unsigned char>);
assert(packet.body_size <= packet.body_buffer.size());

When this is satisfied, uint8_t is allowed to alias all other types by virtue of being a name of unsigned char. I don't know of a language implementation where uint8_t is defined and is not defined as unsigned char so this is basically a sanity check that probably never fails.

Upvotes: 4

Related Questions