srdusr
aboutsummaryrefslogtreecommitdiffstats
path: root/include/wireframe/byteio.hpp
blob: c37c29e756ce5001bae17192349f9842423481f2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#pragma once

#include <cstdint>
#include <span>

// Manual big-endian reads instead of reinterpret_cast onto a packed
// struct: network buffers from pcap aren't guaranteed aligned for
// multi-byte integer types, so casting would be undefined behavior.
namespace wireframe {

inline std::uint16_t read_be16(std::span<const unsigned char> bytes, std::size_t offset) {
    return static_cast<std::uint16_t>((bytes[offset] << 8) | bytes[offset + 1]);
}

inline std::uint32_t read_be32(std::span<const unsigned char> bytes, std::size_t offset) {
    return (static_cast<std::uint32_t>(bytes[offset]) << 24) |
           (static_cast<std::uint32_t>(bytes[offset + 1]) << 16) |
           (static_cast<std::uint32_t>(bytes[offset + 2]) << 8) |
           static_cast<std::uint32_t>(bytes[offset + 3]);
}

}  // namespace wireframe