48 lines
1.8 KiB
C++
48 lines
1.8 KiB
C++
#pragma once
|
|
#include "gateway/broadcast_text_reply_data.hpp"
|
|
#include "gateway/protocol.hpp"
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <iterator>
|
|
#include <optional>
|
|
#include <zlib.h>
|
|
|
|
namespace gateway::broadcast_text {
|
|
inline constexpr uint32_t TableHash = 0x021826bb;
|
|
|
|
inline std::optional<Bytes> lookup(uint32_t id) {
|
|
const auto page = std::lower_bound(std::begin(data::Pages), std::end(data::Pages), id,
|
|
[](const data::Page& candidate, uint32_t key) { return candidate.last < key; });
|
|
if (page == std::end(data::Pages) || id < page->first) return std::nullopt;
|
|
|
|
std::array<uint8_t, data::PageLimit> raw;
|
|
uLongf size = raw.size();
|
|
if (uncompress(raw.data(), &size, reinterpret_cast<const Bytef*>(page->bytes), page->compressed) != Z_OK ||
|
|
size != page->size || size < 2) throw Error("invalid BroadcastText page");
|
|
const std::span<const uint8_t> bytes(raw.data(), size);
|
|
Reader index(bytes);
|
|
const size_t count = index.le(2);
|
|
const size_t start = 2 + count * 6;
|
|
if (!count || start > size) throw Error("invalid BroadcastText directory");
|
|
// Each directory entry is a 32-bit ID and a 16-bit offset within the payload.
|
|
size_t low = 0, high = count;
|
|
while (low < high) {
|
|
const size_t mid = low + (high - low) / 2;
|
|
Reader entry(bytes.subspan(2 + mid * 6));
|
|
if (entry.le(4) < id) low = mid + 1;
|
|
else high = mid;
|
|
}
|
|
if (low == count) return std::nullopt;
|
|
Reader entry(bytes.subspan(2 + low * 6));
|
|
if (entry.le(4) != id) return std::nullopt;
|
|
const size_t begin = start + entry.le(2);
|
|
size_t end = size;
|
|
if (low + 1 < count) {
|
|
entry.le(4);
|
|
end = start + entry.le(2);
|
|
}
|
|
if (begin >= end || end > size) throw Error("invalid BroadcastText row boundaries");
|
|
return Bytes(bytes.begin() + begin, bytes.begin() + end);
|
|
}
|
|
}
|