m/market labResearch, with a record.
Source on GitHub ↗

moldudp.cpp

1#include "itch/feed/moldudp/moldudp.hpp"2#include "itch/common/binary.hpp"3#include "itch/feed/itch/decoder.hpp"4#include <stdexcept>5#include <utility>67namespace itch {8MoldDatagram parse_moldudp64(const unsigned char* packet, size_t length,9                             const std::string& expected_session) {10    if (length < 20) {11        throw std::runtime_error("truncated MoldUDP64 header");12    }13    if (std::string(reinterpret_cast<const char*>(packet), 10) != expected_session) {14        throw std::runtime_error("session mismatch; new session requires a fresh book");15    }16    const auto sequence = read_big_endian(packet + 10, 8);17    const auto count = read_big_endian(packet + 18, 2);18    if (!sequence || sequence == UINT64_MAX) {19        throw std::runtime_error("invalid sequence");20    }21    const bool ending = count == 65535;22    const auto messages = ending ? 0 : count;23    if (messages > UINT64_MAX - sequence || sequence + messages == UINT64_MAX) {24        throw std::runtime_error("sequence overflow");25    }26    MoldDatagram result{sequence, sequence + messages, ending, {}};27    size_t offset = 20;28    for (uint64_t i = 0; i < messages; ++i) {29        if (offset + 2 > length) {30            throw std::runtime_error("truncated message length");31        }32        const auto size = static_cast<size_t>(read_big_endian(packet + offset, 2));33        offset += 2;34        if (!size || size > length - offset) {35            throw std::runtime_error("truncated/empty ITCH message");36        }37        Bytes bytes(packet + offset, packet + offset + size);38        decode(bytes, sequence + i);39        result.messages.push_back(std::move(bytes));40        offset += size;41    }42    if (offset != length) {43        throw std::runtime_error("trailing bytes in MoldUDP64 datagram");44    }45    return result;46}47} // namespace itch