Using reinterpret_cast to parse templated network data

107 Views Asked by At

I am looking into a protocol that sends little endian data over a network and my machine is also little endian. I will not be concerned with big endian machines.

Separate from the data sent over the network, is a template file that instructs how to interpret the data.

For the sake of this question let's just say that the only template instructs to parse data as a 4 byte integer immediately followed by a 8 byte integer.

#include <cstdint>
#include <iostream>

class Int32 final {
public:
    Int32(
        const char* const a_buf,
        const int         a_offset
    ) :
        m_buf   (a_buf),
        m_offset(a_offset)
    {}

    int32_t getVal() const { return *reinterpret_cast<const int32_t*>(m_buf + m_offset); }

private:
    const char* const m_buf;
    const int         m_offset;
};

class Int64 final {
public:
    Int64(
        const char* const a_buf,
        const int         a_offset
    ) :
        m_buf   (a_buf),
        m_offset(a_offset)
    {}

    int64_t getVal() const { return *reinterpret_cast<const int64_t*>(m_buf + m_offset); }

private:
    const char* const m_buf;
    const int         m_offset;
};

int main(int argc, char** argv) {
    // Make up some data for the sake of a SO example
    //
    // The real data is sent over a network with little endian ordering and my
    // machine is also little endian
    char buf[12];
    *reinterpret_cast<int32_t*>(buf + 0) = 42;
    *reinterpret_cast<int64_t*>(buf + 4) = 69;

    // Example of "applying a template" to the data, in this case the "template"
    // is just a 4 byte int followed by a 8 byte int
    const Int32 foo(buf, 0);
    const Int64 bar(buf, 4);

    std::cout << foo.getVal() << " " << bar.getVal() << std::endl;

    return 0;
}

In the above code I am populating buf myself, in the real code buf is populated by copying the data sent over the network.

What I am concerned about is if there is any undefined behavior related to the two getVal methods.

Is it safe to reinterpret_cast m_buf + m_offset?

0

There are 0 best solutions below