#pragma once

#include <bit>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <optional>
#include <span>
#include <utility>
#include <vector>

struct Match {
    std::size_t length;
    std::int64_t value;
};

class RadixTree {
public:
    RadixTree();
    ~RadixTree();

    RadixTree(const RadixTree&) = delete;
    RadixTree& operator=(const RadixTree&) = delete;
    RadixTree(RadixTree&&) = delete;
    RadixTree& operator=(RadixTree&&) = delete;

    bool insert(std::span<const std::uint8_t> key, std::int64_t value);
    std::optional<std::int64_t> get(std::span<const std::uint8_t> key) const;
    bool remove(std::span<const std::uint8_t> key);
    std::optional<Match> longest_prefix(std::span<const std::uint8_t> key) const;
    std::size_t prefix_count(std::span<const std::uint8_t> prefix) const;
    std::size_t prefix_values(std::span<const std::uint8_t> prefix,
                              std::int64_t* out_values, std::size_t limit) const;
    std::size_t len() const;
    std::size_t node_count() const;
    std::size_t height() const;

private:
    static_assert(std::endian::native == std::endian::little,
                  "Little-endian byte order required");

    enum NodeTag : std::uint32_t {
        TAG_LEAF = 0,
        TAG_NODE4 = 1,
        TAG_NODE16 = 2,
        TAG_NODE48 = 3,
        TAG_NODE256 = 4,
    };

    static constexpr std::uint32_t TAG_SHIFT = 29;
    static constexpr std::uint32_t IDX_MASK = (1u << TAG_SHIFT) - 1u;
    static constexpr std::uint32_t LEAF_BOUND = 1u << TAG_SHIFT;
    static constexpr std::uint32_t NULL_HANDLE = 0xFFFFFFFFu;
    static constexpr std::uint32_t FREE_NONE = 0xFFFFFFFFu;

    static constexpr std::uint32_t make_handle(NodeTag tag, std::uint32_t idx) noexcept {
        return (static_cast<std::uint32_t>(tag) << TAG_SHIFT) | idx;
    }
    static constexpr NodeTag handle_tag(std::uint32_t h) noexcept {
        return static_cast<NodeTag>(h >> TAG_SHIFT);
    }
    static constexpr std::uint32_t handle_idx(std::uint32_t h) noexcept {
        return h & IDX_MASK;
    }
    static constexpr bool is_leaf(std::uint32_t h) noexcept {
        return h < LEAF_BOUND;
    }

    static constexpr std::size_t LEAF_INLINE = 7;
    static constexpr std::size_t NODE4_INLINE = 28;
    static constexpr std::size_t NODE16_INLINE = 32;
    static constexpr std::size_t NODE48_INLINE = 8;
    static constexpr std::size_t NODE256_INLINE = 48;

    // 16 bytes: 8 leaves per 128-byte Apple M3 cache line.
    struct alignas(16) Leaf {
        std::int64_t value;
        std::uint8_t label_len;
        std::uint8_t lab[LEAF_INLINE];
    };
    static_assert(sizeof(Leaf) == 16);

    // 64 bytes: 2 nodes per 128-byte cache line.
    struct alignas(64) Node4 {
        std::int64_t value;
        std::uint32_t subtree_count;
        std::uint8_t has_key;
        std::uint8_t num_children;
        std::uint8_t label_len;
        std::uint8_t _pad;
        std::uint8_t keys[4];
        std::uint32_t children[4];
        std::uint8_t lab[NODE4_INLINE];
    };
    static_assert(sizeof(Node4) == 64);

    // 128 bytes: exactly 1 Apple M3 cache line.
    struct alignas(128) Node16 {
        std::int64_t value;
        std::uint32_t subtree_count;
        std::uint8_t has_key;
        std::uint8_t num_children;
        std::uint8_t label_len;
        std::uint8_t _pad;
        std::uint8_t keys[16];
        std::uint32_t children[16];
        std::uint8_t lab[NODE16_INLINE];
    };
    static_assert(sizeof(Node16) == 128);

    // 512 bytes: 4 cache lines.
    struct alignas(128) Node48 {
        std::int64_t value;
        std::uint32_t subtree_count;
        std::uint8_t has_key;
        std::uint8_t num_children;
        std::uint8_t label_len;
        std::uint8_t _pad;
        std::uint64_t used_slots;
        std::uint8_t lab[NODE48_INLINE];
        std::uint64_t present[4];
        std::uint32_t children[48];
        std::uint8_t index[256];
    };
    static_assert(sizeof(Node48) == 512);

    // 1152 bytes: 9 cache lines.
    struct alignas(128) Node256 {
        std::int64_t value;
        std::uint32_t subtree_count;
        std::uint8_t has_key;
        std::uint8_t label_len;
        std::uint16_t num_children;
        std::uint8_t lab[NODE256_INLINE];
        std::uint64_t present[4];
        std::uint32_t children[256];
    };
    static_assert(sizeof(Node256) == 1152);

    struct alignas(32) ExtLabel32 {
        std::uint8_t data[32];
    };
    struct alignas(64) ExtLabel64 {
        std::uint8_t data[64];
    };
    struct alignas(64) ExtLabel256 {
        std::uint8_t data[256];
    };

    template <typename T>
    struct Pool {
        std::vector<T> items;
        std::uint32_t free_head = FREE_NONE;

        std::uint32_t alloc() {
            if (free_head != FREE_NONE) {
                std::uint32_t idx = free_head;
                std::memcpy(&free_head, &items[idx], sizeof(std::uint32_t));
                return idx;
            }
            std::uint32_t idx = static_cast<std::uint32_t>(items.size());
            items.emplace_back();
            return idx;
        }

        void free(std::uint32_t idx) noexcept {
            std::memcpy(&items[idx], &free_head, sizeof(std::uint32_t));
            free_head = idx;
        }
    };

    using u8x16 = std::uint8_t __attribute__((vector_size(16)));
    using i8x16 = std::int8_t __attribute__((vector_size(16)));

    static constexpr i8x16 kIdxMask[17] = {
        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 2, 3, 4, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 2, 3, 4, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0},
        {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0, 0, 0},
        {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 0, 0, 0, 0},
        {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 0},
        {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 0, 0},
        {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 0, 0},
        {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0},
        {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
    };

    static constexpr i8x16 kOneMask[17] = {
        {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
    };

    Pool<Leaf> leaves_;
    Pool<Node4> nodes4_;
    Pool<Node16> nodes16_;
    Pool<Node48> nodes48_;
    Pool<Node256> nodes256_;
    Pool<ExtLabel32> ext32_;
    Pool<ExtLabel64> ext64_;
    Pool<ExtLabel256> ext256_;
    std::uint32_t root_;
    std::size_t size_;

    // --------------------------------------------------------- byte helpers

    // Precondition: n >= 1.
    static inline bool bytes_equal_nonempty(const std::uint8_t* a, const std::uint8_t* b,
                                            std::uint32_t n) noexcept {
        if (n <= 8) {
            if (n >= 4) {
                std::uint32_t a0, b0, a1, b1;
                std::memcpy(&a0, a, 4);
                std::memcpy(&b0, b, 4);
                std::memcpy(&a1, a + n - 4, 4);
                std::memcpy(&b1, b + n - 4, 4);
                return ((a0 ^ b0) | (a1 ^ b1)) == 0;
            }
            if (n >= 2) {
                std::uint16_t a0, b0;
                std::memcpy(&a0, a, 2);
                std::memcpy(&b0, b, 2);
                return (a0 == b0) && (a[n - 1] == b[n - 1]);
            }
            return a[0] == b[0];
        }
        if (n <= 16) {
            std::uint64_t a0, b0, a1, b1;
            std::memcpy(&a0, a, 8);
            std::memcpy(&b0, b, 8);
            std::memcpy(&a1, a + n - 8, 8);
            std::memcpy(&b1, b + n - 8, 8);
            return ((a0 ^ b0) | (a1 ^ b1)) == 0;
        }
        return std::memcmp(a, b, n) == 0;
    }

    static inline std::uint32_t lcp_from_1(const std::uint8_t* a, const std::uint8_t* b,
                                           std::uint32_t max_len) noexcept {
        std::uint32_t i = 1;
        while (i + 8 <= max_len) {
            std::uint64_t x, y;
            std::memcpy(&x, a + i, 8);
            std::memcpy(&y, b + i, 8);
            std::uint64_t diff = x ^ y;
            if (diff != 0) {
                return i + static_cast<std::uint32_t>(std::countr_zero(diff) >> 3);
            }
            i += 8;
        }
        while (i < max_len && a[i] == b[i]) {
            ++i;
        }
        return i;
    }

    // -------------------------------------------------------- label helpers

    inline const std::uint8_t* get_ext_label(std::uint32_t len,
                                             std::uint32_t ext_idx) const noexcept {
        if (len <= 32) return ext32_.items[ext_idx].data;
        if (len <= 64) return ext64_.items[ext_idx].data;
        return ext256_.items[ext_idx].data;
    }

    inline std::uint32_t alloc_ext_label(const std::uint8_t* src, std::uint32_t len) {
        std::uint32_t idx;
        std::uint8_t* dst;
        if (len <= 32) {
            idx = ext32_.alloc();
            dst = ext32_.items[idx].data;
        } else if (len <= 64) {
            idx = ext64_.alloc();
            dst = ext64_.items[idx].data;
        } else {
            idx = ext256_.alloc();
            dst = ext256_.items[idx].data;
        }
        std::memcpy(dst, src, len);
        return idx;
    }

    inline void free_ext_label(std::uint32_t len, std::uint32_t ext_idx) noexcept {
        if (len <= 32) {
            ext32_.free(ext_idx);
        } else if (len <= 64) {
            ext64_.free(ext_idx);
        } else {
            ext256_.free(ext_idx);
        }
    }

    template <std::size_t INLINE_CAP>
    inline const std::uint8_t* read_label(std::uint32_t len,
                                          const std::uint8_t* lab) const noexcept {
        if (len <= INLINE_CAP) [[likely]] return lab;
        std::uint32_t ext_idx;
        std::memcpy(&ext_idx, lab, sizeof(std::uint32_t));
        return get_ext_label(len, ext_idx);
    }

    template <std::size_t INLINE_CAP>
    inline void set_label(std::uint8_t& len_field, std::uint8_t* lab,
                          const std::uint8_t* src, std::uint32_t len) {
        len_field = static_cast<std::uint8_t>(len);
        if (len <= INLINE_CAP) [[likely]] {
            if (len > 0) std::memcpy(lab, src, len);
        } else {
            std::uint32_t ext_idx = alloc_ext_label(src, len);
            std::memcpy(lab, &ext_idx, sizeof(std::uint32_t));
        }
    }

    template <std::size_t INLINE_CAP>
    inline void release_label(std::uint32_t len, const std::uint8_t* lab) noexcept {
        if (len > INLINE_CAP) [[unlikely]] {
            std::uint32_t ext_idx;
            std::memcpy(&ext_idx, lab, sizeof(std::uint32_t));
            free_ext_label(len, ext_idx);
        }
    }

    template <std::size_t SRC_CAP, std::size_t DST_CAP>
    inline void transfer_label(std::uint8_t& dst_len, std::uint8_t* dst_lab,
                               std::uint32_t src_len, const std::uint8_t* src_lab) {
        dst_len = static_cast<std::uint8_t>(src_len);
        if (src_len == 0) return;
        if (src_len <= SRC_CAP) {
            if (src_len <= DST_CAP) {
                std::memcpy(dst_lab, src_lab, src_len);
            } else {
                std::uint32_t ext_idx = alloc_ext_label(src_lab, src_len);
                std::memcpy(dst_lab, &ext_idx, sizeof(std::uint32_t));
            }
        } else {
            std::uint32_t ext_idx;
            std::memcpy(&ext_idx, src_lab, sizeof(std::uint32_t));
            if (src_len <= DST_CAP) {
                std::memcpy(dst_lab, get_ext_label(src_len, ext_idx), src_len);
                free_ext_label(src_len, ext_idx);
            } else {
                std::memcpy(dst_lab, &ext_idx, sizeof(std::uint32_t));
            }
        }
    }

    inline std::pair<const std::uint8_t*, std::uint32_t> get_node_label(
        std::uint32_t handle) const noexcept {
        if (is_leaf(handle)) {
            const Leaf& lf = leaves_.items[handle];
            return {read_label<LEAF_INLINE>(lf.label_len, lf.lab), lf.label_len};
        }
        const std::uint32_t idx = handle_idx(handle);
        switch (handle_tag(handle)) {
            case TAG_NODE4: {
                const Node4& nd = nodes4_.items[idx];
                return {read_label<NODE4_INLINE>(nd.label_len, nd.lab), nd.label_len};
            }
            case TAG_NODE16: {
                const Node16& nd = nodes16_.items[idx];
                return {read_label<NODE16_INLINE>(nd.label_len, nd.lab), nd.label_len};
            }
            case TAG_NODE48: {
                const Node48& nd = nodes48_.items[idx];
                return {read_label<NODE48_INLINE>(nd.label_len, nd.lab), nd.label_len};
            }
            default: {
                const Node256& nd = nodes256_.items[idx];
                return {read_label<NODE256_INLINE>(nd.label_len, nd.lab), nd.label_len};
            }
        }
    }

    inline void replace_node_label(std::uint32_t handle, const std::uint8_t* src,
                                   std::uint32_t new_len) {
        if (is_leaf(handle)) {
            Leaf& lf = leaves_.items[handle];
            release_label<LEAF_INLINE>(lf.label_len, lf.lab);
            set_label<LEAF_INLINE>(lf.label_len, lf.lab, src, new_len);
            return;
        }
        const std::uint32_t idx = handle_idx(handle);
        switch (handle_tag(handle)) {
            case TAG_NODE4: {
                Node4& nd = nodes4_.items[idx];
                release_label<NODE4_INLINE>(nd.label_len, nd.lab);
                set_label<NODE4_INLINE>(nd.label_len, nd.lab, src, new_len);
                break;
            }
            case TAG_NODE16: {
                Node16& nd = nodes16_.items[idx];
                release_label<NODE16_INLINE>(nd.label_len, nd.lab);
                set_label<NODE16_INLINE>(nd.label_len, nd.lab, src, new_len);
                break;
            }
            case TAG_NODE48: {
                Node48& nd = nodes48_.items[idx];
                release_label<NODE48_INLINE>(nd.label_len, nd.lab);
                set_label<NODE48_INLINE>(nd.label_len, nd.lab, src, new_len);
                break;
            }
            default: {
                Node256& nd = nodes256_.items[idx];
                release_label<NODE256_INLINE>(nd.label_len, nd.lab);
                set_label<NODE256_INLINE>(nd.label_len, nd.lab, src, new_len);
                break;
            }
        }
    }

    inline std::uint32_t get_subtree_count(std::uint32_t handle) const noexcept {
        if (is_leaf(handle)) return 1;
        const std::uint32_t idx = handle_idx(handle);
        switch (handle_tag(handle)) {
            case TAG_NODE4: return nodes4_.items[idx].subtree_count;
            case TAG_NODE16: return nodes16_.items[idx].subtree_count;
            case TAG_NODE48: return nodes48_.items[idx].subtree_count;
            default: return nodes256_.items[idx].subtree_count;
        }
    }

    inline void add_subtree_count(std::uint32_t handle, std::int32_t delta) noexcept {
        const std::uint32_t idx = handle_idx(handle);
        switch (handle_tag(handle)) {
            case TAG_NODE4:
                nodes4_.items[idx].subtree_count = static_cast<std::uint32_t>(
                    static_cast<std::int32_t>(nodes4_.items[idx].subtree_count) + delta);
                break;
            case TAG_NODE16:
                nodes16_.items[idx].subtree_count = static_cast<std::uint32_t>(
                    static_cast<std::int32_t>(nodes16_.items[idx].subtree_count) + delta);
                break;
            case TAG_NODE48:
                nodes48_.items[idx].subtree_count = static_cast<std::uint32_t>(
                    static_cast<std::int32_t>(nodes48_.items[idx].subtree_count) + delta);
                break;
            default:
                nodes256_.items[idx].subtree_count = static_cast<std::uint32_t>(
                    static_cast<std::int32_t>(nodes256_.items[idx].subtree_count) + delta);
                break;
        }
    }

    inline std::uint32_t alloc_leaf(std::int64_t value, const std::uint8_t* lab,
                                    std::uint32_t llen) {
        std::uint32_t idx = leaves_.alloc();
        Leaf& lf = leaves_.items[idx];
        lf.value = value;
        set_label<LEAF_INLINE>(lf.label_len, lf.lab, lab, llen);
        return idx;  // TAG_LEAF == 0
    }

    // --------------------------------------------------- child lookup helpers

    static inline std::uint32_t node4_find(const Node4& nd, std::uint8_t b) noexcept {
        const std::uint32_t n = nd.num_children;
        std::uint32_t pos = 0;
        if (n > 0 && nd.keys[0] == b) pos = 1;
        if (n > 1 && nd.keys[1] == b) pos = 2;
        if (n > 2 && nd.keys[2] == b) pos = 3;
        if (n > 3 && nd.keys[3] == b) pos = 4;
        return pos ? nd.children[pos - 1] : NULL_HANDLE;
    }

    static inline std::uint32_t node16_find_pos(const Node16& nd, std::uint8_t b) noexcept {
        u8x16 kv;
        std::memcpy(&kv, nd.keys, 16);
        u8x16 bv = {b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b};
        i8x16 eq = (kv == bv);
        i8x16 hit = eq & kIdxMask[nd.num_children];
        return static_cast<std::uint32_t>(__builtin_reduce_max(hit));
    }

    static inline std::uint32_t node16_find(const Node16& nd, std::uint8_t b) noexcept {
        std::uint32_t pos = node16_find_pos(nd, b);
        return pos ? nd.children[pos - 1] : NULL_HANDLE;
    }

    static inline std::uint32_t node16_insert_pos(const Node16& nd, std::uint8_t b) noexcept {
        u8x16 kv;
        std::memcpy(&kv, nd.keys, 16);
        u8x16 bv = {b, b, b, b, b, b, b, b, b, b, b, b, b, b, b, b};
        i8x16 lt = (kv < bv) & kOneMask[nd.num_children];
        return static_cast<std::uint32_t>(__builtin_reduce_add(lt));
    }

    static inline std::uint32_t node48_find(const Node48& nd, std::uint8_t b) noexcept {
        std::uint8_t idx = nd.index[b];
        return idx ? nd.children[idx - 1] : NULL_HANDLE;
    }

    inline std::uint32_t find_child_internal(std::uint32_t handle,
                                             std::uint8_t b) const noexcept {
        const std::uint32_t idx = handle_idx(handle);
        switch (handle_tag(handle)) {
            case TAG_NODE4: return node4_find(nodes4_.items[idx], b);
            case TAG_NODE16: return node16_find(nodes16_.items[idx], b);
            case TAG_NODE48: return node48_find(nodes48_.items[idx], b);
            default: return nodes256_.items[idx].children[b];
        }
    }

    inline void replace_child(std::uint32_t parent_handle, std::uint8_t b,
                              std::uint32_t new_child) noexcept {
        const std::uint32_t idx = handle_idx(parent_handle);
        switch (handle_tag(parent_handle)) {
            case TAG_NODE4: {
                Node4& nd = nodes4_.items[idx];
                for (std::uint32_t i = 0; i < nd.num_children; ++i) {
                    if (nd.keys[i] == b) {
                        nd.children[i] = new_child;
                        return;
                    }
                }
                break;
            }
            case TAG_NODE16: {
                Node16& nd = nodes16_.items[idx];
                std::uint32_t pos = node16_find_pos(nd, b);
                nd.children[pos - 1] = new_child;
                break;
            }
            case TAG_NODE48: {
                Node48& nd = nodes48_.items[idx];
                nd.children[nd.index[b] - 1] = new_child;
                break;
            }
            default: {
                nodes256_.items[idx].children[b] = new_child;
                break;
            }
        }
    }

    // Adds (b, child) to node `handle`. May grow the node and return a new handle.
    inline std::uint32_t add_child(std::uint32_t handle, std::uint8_t b,
                                   std::uint32_t child) {
        const std::uint32_t idx = handle_idx(handle);
        switch (handle_tag(handle)) {
            case TAG_NODE4: {
                Node4& nd = nodes4_.items[idx];
                if (nd.num_children < 4) {
                    std::uint32_t pos = 0;
                    while (pos < nd.num_children && nd.keys[pos] < b) ++pos;
                    for (std::uint32_t i = nd.num_children; i > pos; --i) {
                        nd.keys[i] = nd.keys[i - 1];
                        nd.children[i] = nd.children[i - 1];
                    }
                    nd.keys[pos] = b;
                    nd.children[pos] = child;
                    nd.num_children++;
                    return handle;
                }
                // Grow Node4 -> Node16
                std::uint32_t n16_idx = nodes16_.alloc();
                Node16& dst = nodes16_.items[n16_idx];
                const Node4& src = nodes4_.items[idx];
                dst.value = src.value;
                dst.subtree_count = src.subtree_count;
                dst.has_key = src.has_key;
                dst.num_children = 5;
                transfer_label<NODE4_INLINE, NODE16_INLINE>(
                    dst.label_len, dst.lab, src.label_len, src.lab);
                std::uint32_t pos = 0;
                while (pos < 4 && src.keys[pos] < b) {
                    dst.keys[pos] = src.keys[pos];
                    dst.children[pos] = src.children[pos];
                    ++pos;
                }
                dst.keys[pos] = b;
                dst.children[pos] = child;
                for (std::uint32_t i = pos; i < 4; ++i) {
                    dst.keys[i + 1] = src.keys[i];
                    dst.children[i + 1] = src.children[i];
                }
                nodes4_.free(idx);
                return make_handle(TAG_NODE16, n16_idx);
            }
            case TAG_NODE16: {
                Node16& nd = nodes16_.items[idx];
                if (nd.num_children < 16) {
                    std::uint32_t pos = node16_insert_pos(nd, b);
                    std::uint32_t tail = nd.num_children - pos;
                    if (tail > 0) {
                        std::memmove(nd.keys + pos + 1, nd.keys + pos, tail);
                        std::memmove(nd.children + pos + 1, nd.children + pos,
                                     tail * sizeof(std::uint32_t));
                    }
                    nd.keys[pos] = b;
                    nd.children[pos] = child;
                    nd.num_children++;
                    return handle;
                }
                // Grow Node16 -> Node48
                std::uint32_t n48_idx = nodes48_.alloc();
                Node48& dst = nodes48_.items[n48_idx];
                const Node16& src = nodes16_.items[idx];
                dst.value = src.value;
                dst.subtree_count = src.subtree_count;
                dst.has_key = src.has_key;
                dst.num_children = 17;
                std::memset(dst.index, 0, 256);
                std::memset(dst.present, 0, sizeof(dst.present));
                transfer_label<NODE16_INLINE, NODE48_INLINE>(
                    dst.label_len, dst.lab, src.label_len, src.lab);
                for (std::uint32_t i = 0; i < 16; ++i) {
                    std::uint8_t k = src.keys[i];
                    dst.children[i] = src.children[i];
                    dst.index[k] = static_cast<std::uint8_t>(i + 1);
                    dst.present[k >> 6] |= (1ULL << (k & 63));
                }
                dst.children[16] = child;
                dst.index[b] = 17;
                dst.present[b >> 6] |= (1ULL << (b & 63));
                dst.used_slots = (1ULL << 17) - 1ULL;
                nodes16_.free(idx);
                return make_handle(TAG_NODE48, n48_idx);
            }
            case TAG_NODE48: {
                Node48& nd = nodes48_.items[idx];
                if (nd.num_children < 48) {
                    std::uint32_t slot = static_cast<std::uint32_t>(std::countr_zero(~nd.used_slots));
                    nd.used_slots |= (1ULL << slot);
                    nd.children[slot] = child;
                    nd.index[b] = static_cast<std::uint8_t>(slot + 1);
                    nd.present[b >> 6] |= (1ULL << (b & 63));
                    nd.num_children++;
                    return handle;
                }
                // Grow Node48 -> Node256
                std::uint32_t n256_idx = nodes256_.alloc();
                Node256& dst = nodes256_.items[n256_idx];
                const Node48& src = nodes48_.items[idx];
                dst.value = src.value;
                dst.subtree_count = src.subtree_count;
                dst.has_key = src.has_key;
                dst.num_children = 49;
                std::memcpy(dst.present, src.present, sizeof(dst.present));
                std::memset(dst.children, 0xFF, sizeof(dst.children));
                transfer_label<NODE48_INLINE, NODE256_INLINE>(
                    dst.label_len, dst.lab, src.label_len, src.lab);
                for (std::uint32_t w = 0; w < 4; ++w) {
                    std::uint64_t bits = src.present[w];
                    while (bits) {
                        std::uint32_t bit = static_cast<std::uint32_t>(std::countr_zero(bits));
                        bits &= bits - 1;
                        std::uint32_t k = (w << 6) | bit;
                        dst.children[k] = src.children[src.index[k] - 1];
                    }
                }
                dst.children[b] = child;
                dst.present[b >> 6] |= (1ULL << (b & 63));
                nodes48_.free(idx);
                return make_handle(TAG_NODE256, n256_idx);
            }
            default: {
                Node256& nd = nodes256_.items[idx];
                nd.children[b] = child;
                nd.present[b >> 6] |= (1ULL << (b & 63));
                nd.num_children++;
                return handle;
            }
        }
    }

    // Removes byte `b` from node `handle`. May shrink the node (with hysteresis)
    // and return the new handle. Does NOT demote to Leaf or merge single-child.
    inline std::uint32_t remove_child_and_maybe_shrink(std::uint32_t handle,
                                                       std::uint8_t b) {
        const std::uint32_t idx = handle_idx(handle);
        switch (handle_tag(handle)) {
            case TAG_NODE4: {
                Node4& nd = nodes4_.items[idx];
                std::uint32_t pos = 0;
                while (nd.keys[pos] != b) ++pos;
                for (std::uint32_t i = pos; i + 1 < nd.num_children; ++i) {
                    nd.keys[i] = nd.keys[i + 1];
                    nd.children[i] = nd.children[i + 1];
                }
                nd.num_children--;
                return handle;
            }
            case TAG_NODE16: {
                Node16& nd = nodes16_.items[idx];
                std::uint32_t pos = node16_find_pos(nd, b) - 1;
                std::uint32_t tail = nd.num_children - 1 - pos;
                if (tail > 0) {
                    std::memmove(nd.keys + pos, nd.keys + pos + 1, tail);
                    std::memmove(nd.children + pos, nd.children + pos + 1,
                                 tail * sizeof(std::uint32_t));
                }
                nd.num_children--;
                if (nd.num_children <= 3) {
                    std::uint32_t n4_idx = nodes4_.alloc();
                    Node4& dst = nodes4_.items[n4_idx];
                    const Node16& src = nodes16_.items[idx];
                    dst.value = src.value;
                    dst.subtree_count = src.subtree_count;
                    dst.has_key = src.has_key;
                    dst.num_children = src.num_children;
                    transfer_label<NODE16_INLINE, NODE4_INLINE>(
                        dst.label_len, dst.lab, src.label_len, src.lab);
                    std::memcpy(dst.keys, src.keys, src.num_children);
                    std::memcpy(dst.children, src.children,
                                src.num_children * sizeof(std::uint32_t));
                    nodes16_.free(idx);
                    return make_handle(TAG_NODE4, n4_idx);
                }
                return handle;
            }
            case TAG_NODE48: {
                Node48& nd = nodes48_.items[idx];
                std::uint32_t slot = nd.index[b] - 1;
                nd.index[b] = 0;
                nd.used_slots &= ~(1ULL << slot);
                nd.present[b >> 6] &= ~(1ULL << (b & 63));
                nd.num_children--;
                if (nd.num_children <= 12) {
                    std::uint32_t n16_idx = nodes16_.alloc();
                    Node16& dst = nodes16_.items[n16_idx];
                    const Node48& src = nodes48_.items[idx];
                    dst.value = src.value;
                    dst.subtree_count = src.subtree_count;
                    dst.has_key = src.has_key;
                    dst.num_children = src.num_children;
                    transfer_label<NODE48_INLINE, NODE16_INLINE>(
                        dst.label_len, dst.lab, src.label_len, src.lab);
                    std::uint32_t out_i = 0;
                    for (std::uint32_t w = 0; w < 4; ++w) {
                        std::uint64_t bits = src.present[w];
                        while (bits) {
                            std::uint32_t bit = static_cast<std::uint32_t>(std::countr_zero(bits));
                            bits &= bits - 1;
                            std::uint32_t k = (w << 6) | bit;
                            dst.keys[out_i] = static_cast<std::uint8_t>(k);
                            dst.children[out_i] = src.children[src.index[k] - 1];
                            ++out_i;
                        }
                    }
                    nodes48_.free(idx);
                    return make_handle(TAG_NODE16, n16_idx);
                }
                return handle;
            }
            default: {
                Node256& nd = nodes256_.items[idx];
                nd.children[b] = NULL_HANDLE;
                nd.present[b >> 6] &= ~(1ULL << (b & 63));
                nd.num_children--;
                if (nd.num_children <= 36) {
                    std::uint32_t n48_idx = nodes48_.alloc();
                    Node48& dst = nodes48_.items[n48_idx];
                    const Node256& src = nodes256_.items[idx];
                    dst.value = src.value;
                    dst.subtree_count = src.subtree_count;
                    dst.has_key = src.has_key;
                    dst.num_children = static_cast<std::uint8_t>(src.num_children);
                    std::memset(dst.index, 0, 256);
                    std::memcpy(dst.present, src.present, sizeof(dst.present));
                    transfer_label<NODE256_INLINE, NODE48_INLINE>(
                        dst.label_len, dst.lab, src.label_len, src.lab);
                    std::uint32_t slot = 0;
                    for (std::uint32_t w = 0; w < 4; ++w) {
                        std::uint64_t bits = src.present[w];
                        while (bits) {
                            std::uint32_t bit = static_cast<std::uint32_t>(std::countr_zero(bits));
                            bits &= bits - 1;
                            std::uint32_t k = (w << 6) | bit;
                            dst.children[slot] = src.children[k];
                            dst.index[k] = static_cast<std::uint8_t>(slot + 1);
                            ++slot;
                        }
                    }
                    dst.used_slots = (1ULL << slot) - 1ULL;
                    nodes256_.free(idx);
                    return make_handle(TAG_NODE48, n48_idx);
                }
                return handle;
            }
        }
    }

    // Merge a non-root Node4 `n4_handle` (which has !has_key && num_children == 1)
    // into its sole child, freeing `n4_handle`, and return the child handle.
    inline std::uint32_t merge_node4_with_only_child(std::uint32_t n4_handle) {
        const std::uint32_t idx = handle_idx(n4_handle);
        Node4& nd = nodes4_.items[idx];
        const std::uint32_t only_child = nd.children[0];
        std::uint8_t buf[255];
        const std::uint32_t p_len = nd.label_len;
        std::memcpy(buf, read_label<NODE4_INLINE>(p_len, nd.lab), p_len);
        auto [c_ptr, c_len] = get_node_label(only_child);
        std::memcpy(buf + p_len, c_ptr, c_len);
        release_label<NODE4_INLINE>(p_len, nd.lab);
        nodes4_.free(idx);
        replace_node_label(only_child, buf, p_len + c_len);
        return only_child;
    }

    // --------------------------------------------------- traversal helpers

    inline void prefetch_node(std::uint32_t handle, const Leaf* leaves) const noexcept {
        if (is_leaf(handle)) {
            __builtin_prefetch(leaves + handle, 0, 1);
            return;
        }
        const std::uint32_t idx = handle_idx(handle);
        switch (handle_tag(handle)) {
            case TAG_NODE4: __builtin_prefetch(&nodes4_.items[idx], 0, 1); break;
            case TAG_NODE16: __builtin_prefetch(&nodes16_.items[idx], 0, 1); break;
            case TAG_NODE48: __builtin_prefetch(&nodes48_.items[idx], 0, 1); break;
            default: __builtin_prefetch(&nodes256_.items[idx], 0, 1); break;
        }
    }

    std::int64_t* collect_all_internal(std::uint32_t handle, std::int64_t* out,
                                       const Leaf* leaves) const noexcept {
        const std::uint32_t idx = handle_idx(handle);
        switch (handle_tag(handle)) {
            case TAG_NODE4: {
                const Node4& nd = nodes4_.items[idx];
                if (nd.has_key) *out++ = nd.value;
                const std::uint32_t n = nd.num_children;
                for (std::uint32_t i = 0; i < n; ++i) {
                    const std::uint32_t ch = nd.children[i];
                    if (is_leaf(ch)) [[likely]] {
                        *out++ = leaves[ch].value;
                    } else {
                        if (i + 1 < n) prefetch_node(nd.children[i + 1], leaves);
                        out = collect_all_internal(ch, out, leaves);
                    }
                }
                return out;
            }
            case TAG_NODE16: {
                const Node16& nd = nodes16_.items[idx];
                if (nd.has_key) *out++ = nd.value;
                const std::uint32_t n = nd.num_children;
                for (std::uint32_t i = 0; i < n; ++i) {
                    const std::uint32_t ch = nd.children[i];
                    if (is_leaf(ch)) [[likely]] {
                        *out++ = leaves[ch].value;
                    } else {
                        if (i + 1 < n) prefetch_node(nd.children[i + 1], leaves);
                        out = collect_all_internal(ch, out, leaves);
                    }
                }
                return out;
            }
            case TAG_NODE48: {
                const Node48& nd = nodes48_.items[idx];
                if (nd.has_key) *out++ = nd.value;
                for (std::uint32_t w = 0; w < 4; ++w) {
                    std::uint64_t bits = nd.present[w];
                    while (bits) {
                        std::uint32_t bit = static_cast<std::uint32_t>(std::countr_zero(bits));
                        bits &= bits - 1;
                        std::uint32_t k = (w << 6) | bit;
                        std::uint32_t ch = nd.children[nd.index[k] - 1];
                        if (is_leaf(ch)) {
                            *out++ = leaves[ch].value;
                        } else {
                            out = collect_all_internal(ch, out, leaves);
                        }
                    }
                }
                return out;
            }
            default: {
                const Node256& nd = nodes256_.items[idx];
                if (nd.has_key) *out++ = nd.value;
                for (std::uint32_t w = 0; w < 4; ++w) {
                    std::uint64_t bits = nd.present[w];
                    while (bits) {
                        std::uint32_t bit = static_cast<std::uint32_t>(std::countr_zero(bits));
                        bits &= bits - 1;
                        std::uint32_t ch = nd.children[(w << 6) | bit];
                        if (is_leaf(ch)) {
                            *out++ = leaves[ch].value;
                        } else {
                            out = collect_all_internal(ch, out, leaves);
                        }
                    }
                }
                return out;
            }
        }
    }

    std::int64_t* collect_limited_internal(std::uint32_t handle, std::int64_t* out,
                                           std::int64_t* end,
                                           const Leaf* leaves) const noexcept {
        const std::uint32_t idx = handle_idx(handle);
        switch (handle_tag(handle)) {
            case TAG_NODE4: {
                const Node4& nd = nodes4_.items[idx];
                if (nd.has_key) {
                    *out++ = nd.value;
                    if (out == end) return out;
                }
                const std::uint32_t n = nd.num_children;
                for (std::uint32_t i = 0; i < n; ++i) {
                    const std::uint32_t ch = nd.children[i];
                    if (is_leaf(ch)) [[likely]] {
                        *out++ = leaves[ch].value;
                        if (out == end) return out;
                    } else {
                        out = collect_limited_internal(ch, out, end, leaves);
                        if (out == end) return out;
                    }
                }
                return out;
            }
            case TAG_NODE16: {
                const Node16& nd = nodes16_.items[idx];
                if (nd.has_key) {
                    *out++ = nd.value;
                    if (out == end) return out;
                }
                const std::uint32_t n = nd.num_children;
                for (std::uint32_t i = 0; i < n; ++i) {
                    const std::uint32_t ch = nd.children[i];
                    if (is_leaf(ch)) [[likely]] {
                        *out++ = leaves[ch].value;
                        if (out == end) return out;
                    } else {
                        out = collect_limited_internal(ch, out, end, leaves);
                        if (out == end) return out;
                    }
                }
                return out;
            }
            case TAG_NODE48: {
                const Node48& nd = nodes48_.items[idx];
                if (nd.has_key) {
                    *out++ = nd.value;
                    if (out == end) return out;
                }
                for (std::uint32_t w = 0; w < 4; ++w) {
                    std::uint64_t bits = nd.present[w];
                    while (bits) {
                        std::uint32_t bit = static_cast<std::uint32_t>(std::countr_zero(bits));
                        bits &= bits - 1;
                        std::uint32_t k = (w << 6) | bit;
                        std::uint32_t ch = nd.children[nd.index[k] - 1];
                        if (is_leaf(ch)) {
                            *out++ = leaves[ch].value;
                            if (out == end) return out;
                        } else {
                            out = collect_limited_internal(ch, out, end, leaves);
                            if (out == end) return out;
                        }
                    }
                }
                return out;
            }
            default: {
                const Node256& nd = nodes256_.items[idx];
                if (nd.has_key) {
                    *out++ = nd.value;
                    if (out == end) return out;
                }
                for (std::uint32_t w = 0; w < 4; ++w) {
                    std::uint64_t bits = nd.present[w];
                    while (bits) {
                        std::uint32_t bit = static_cast<std::uint32_t>(std::countr_zero(bits));
                        bits &= bits - 1;
                        std::uint32_t ch = nd.children[(w << 6) | bit];
                        if (is_leaf(ch)) {
                            *out++ = leaves[ch].value;
                            if (out == end) return out;
                        } else {
                            out = collect_limited_internal(ch, out, end, leaves);
                            if (out == end) return out;
                        }
                    }
                }
                return out;
            }
        }
    }

    std::size_t count_nodes_rec(std::uint32_t handle) const noexcept {
        if (is_leaf(handle)) return 1;
        std::size_t total = 1;
        const std::uint32_t idx = handle_idx(handle);
        switch (handle_tag(handle)) {
            case TAG_NODE4: {
                const Node4& nd = nodes4_.items[idx];
                for (std::uint32_t i = 0; i < nd.num_children; ++i)
                    total += count_nodes_rec(nd.children[i]);
                break;
            }
            case TAG_NODE16: {
                const Node16& nd = nodes16_.items[idx];
                for (std::uint32_t i = 0; i < nd.num_children; ++i)
                    total += count_nodes_rec(nd.children[i]);
                break;
            }
            case TAG_NODE48: {
                const Node48& nd = nodes48_.items[idx];
                for (std::uint32_t w = 0; w < 4; ++w) {
                    std::uint64_t bits = nd.present[w];
                    while (bits) {
                        std::uint32_t bit = static_cast<std::uint32_t>(std::countr_zero(bits));
                        bits &= bits - 1;
                        total += count_nodes_rec(nd.children[nd.index[(w << 6) | bit] - 1]);
                    }
                }
                break;
            }
            default: {
                const Node256& nd = nodes256_.items[idx];
                for (std::uint32_t w = 0; w < 4; ++w) {
                    std::uint64_t bits = nd.present[w];
                    while (bits) {
                        std::uint32_t bit = static_cast<std::uint32_t>(std::countr_zero(bits));
                        bits &= bits - 1;
                        total += count_nodes_rec(nd.children[(w << 6) | bit]);
                    }
                }
                break;
            }
        }
        return total;
    }

    std::size_t height_rec(std::uint32_t handle) const noexcept {
        if (is_leaf(handle)) return 0;
        std::size_t max_h = 0;
        bool has_child = false;
        const std::uint32_t idx = handle_idx(handle);
        switch (handle_tag(handle)) {
            case TAG_NODE4: {
                const Node4& nd = nodes4_.items[idx];
                has_child = nd.num_children > 0;
                for (std::uint32_t i = 0; i < nd.num_children; ++i) {
                    std::size_t h = height_rec(nd.children[i]);
                    if (h > max_h) max_h = h;
                }
                break;
            }
            case TAG_NODE16: {
                const Node16& nd = nodes16_.items[idx];
                has_child = nd.num_children > 0;
                for (std::uint32_t i = 0; i < nd.num_children; ++i) {
                    std::size_t h = height_rec(nd.children[i]);
                    if (h > max_h) max_h = h;
                }
                break;
            }
            case TAG_NODE48: {
                const Node48& nd = nodes48_.items[idx];
                has_child = nd.num_children > 0;
                for (std::uint32_t w = 0; w < 4; ++w) {
                    std::uint64_t bits = nd.present[w];
                    while (bits) {
                        std::uint32_t bit = static_cast<std::uint32_t>(std::countr_zero(bits));
                        bits &= bits - 1;
                        std::size_t h = height_rec(nd.children[nd.index[(w << 6) | bit] - 1]);
                        if (h > max_h) max_h = h;
                    }
                }
                break;
            }
            default: {
                const Node256& nd = nodes256_.items[idx];
                has_child = nd.num_children > 0;
                for (std::uint32_t w = 0; w < 4; ++w) {
                    std::uint64_t bits = nd.present[w];
                    while (bits) {
                        std::uint32_t bit = static_cast<std::uint32_t>(std::countr_zero(bits));
                        bits &= bits - 1;
                        std::size_t h = height_rec(nd.children[(w << 6) | bit]);
                        if (h > max_h) max_h = h;
                    }
                }
                break;
            }
        }
        return has_child ? max_h + 1 : 0;
    }

    inline std::optional<std::int64_t> get_root_value() const noexcept {
        const std::uint32_t idx = handle_idx(root_);
        switch (handle_tag(root_)) {
            case TAG_NODE4: {
                const Node4& nd = nodes4_.items[idx];
                return nd.has_key ? std::optional<std::int64_t>(nd.value) : std::nullopt;
            }
            case TAG_NODE16: {
                const Node16& nd = nodes16_.items[idx];
                return nd.has_key ? std::optional<std::int64_t>(nd.value) : std::nullopt;
            }
            case TAG_NODE48: {
                const Node48& nd = nodes48_.items[idx];
                return nd.has_key ? std::optional<std::int64_t>(nd.value) : std::nullopt;
            }
            default: {
                const Node256& nd = nodes256_.items[idx];
                return nd.has_key ? std::optional<std::int64_t>(nd.value) : std::nullopt;
            }
        }
    }

    inline std::uint32_t find_prefix_node(const std::uint8_t* pp,
                                          std::uint32_t plen) const noexcept {
        if (plen == 0) return root_;
        std::uint32_t cur = find_child_internal(root_, pp[0]);
        if (cur == NULL_HANDLE) return NULL_HANDLE;
        std::uint32_t depth = 0;
        for (;;) {
            const std::uint32_t rem = plen - depth;
            if (is_leaf(cur)) {
                const Leaf& lf = leaves_.items[cur];
                const std::uint32_t llen = lf.label_len;
                if (rem > llen) return NULL_HANDLE;
                if (rem > 1) {
                    const std::uint8_t* lp = read_label<LEAF_INLINE>(llen, lf.lab);
                    if (!bytes_equal_nonempty(pp + depth + 1, lp + 1, rem - 1)) return NULL_HANDLE;
                }
                return cur;
            }
            const std::uint32_t idx = handle_idx(cur);
            switch (handle_tag(cur)) {
                case TAG_NODE4: {
                    const Node4& nd = nodes4_.items[idx];
                    const std::uint32_t llen = nd.label_len;
                    const std::uint32_t cmp_len = rem < llen ? rem : llen;
                    if (cmp_len > 1) {
                        const std::uint8_t* lp = read_label<NODE4_INLINE>(llen, nd.lab);
                        if (!bytes_equal_nonempty(pp + depth + 1, lp + 1, cmp_len - 1))
                            return NULL_HANDLE;
                    }
                    if (rem <= llen) return cur;
                    depth += llen;
                    cur = node4_find(nd, pp[depth]);
                    if (cur == NULL_HANDLE) return NULL_HANDLE;
                    break;
                }
                case TAG_NODE16: {
                    const Node16& nd = nodes16_.items[idx];
                    const std::uint32_t llen = nd.label_len;
                    const std::uint32_t cmp_len = rem < llen ? rem : llen;
                    if (cmp_len > 1) {
                        const std::uint8_t* lp = read_label<NODE16_INLINE>(llen, nd.lab);
                        if (!bytes_equal_nonempty(pp + depth + 1, lp + 1, cmp_len - 1))
                            return NULL_HANDLE;
                    }
                    if (rem <= llen) return cur;
                    depth += llen;
                    cur = node16_find(nd, pp[depth]);
                    if (cur == NULL_HANDLE) return NULL_HANDLE;
                    break;
                }
                case TAG_NODE48: {
                    const Node48& nd = nodes48_.items[idx];
                    const std::uint32_t llen = nd.label_len;
                    const std::uint32_t cmp_len = rem < llen ? rem : llen;
                    if (cmp_len > 1) {
                        const std::uint8_t* lp = read_label<NODE48_INLINE>(llen, nd.lab);
                        if (!bytes_equal_nonempty(pp + depth + 1, lp + 1, cmp_len - 1))
                            return NULL_HANDLE;
                    }
                    if (rem <= llen) return cur;
                    depth += llen;
                    cur = node48_find(nd, pp[depth]);
                    if (cur == NULL_HANDLE) return NULL_HANDLE;
                    break;
                }
                default: {
                    const Node256& nd = nodes256_.items[idx];
                    const std::uint32_t llen = nd.label_len;
                    const std::uint32_t cmp_len = rem < llen ? rem : llen;
                    if (cmp_len > 1) {
                        const std::uint8_t* lp = read_label<NODE256_INLINE>(llen, nd.lab);
                        if (!bytes_equal_nonempty(pp + depth + 1, lp + 1, cmp_len - 1))
                            return NULL_HANDLE;
                    }
                    if (rem <= llen) return cur;
                    depth += llen;
                    cur = nd.children[pp[depth]];
                    if (cur == NULL_HANDLE) return NULL_HANDLE;
                    break;
                }
            }
        }
    }
};

// ------------------------------------------------------------ implementation

inline RadixTree::RadixTree() : root_(NULL_HANDLE), size_(0) {
    std::uint32_t idx = nodes4_.alloc();
    Node4& r = nodes4_.items[idx];
    r.value = 0;
    r.subtree_count = 0;
    r.has_key = 0;
    r.num_children = 0;
    r.label_len = 0;
    root_ = make_handle(TAG_NODE4, idx);
}

inline RadixTree::~RadixTree() = default;

inline std::size_t RadixTree::len() const {
    return size_;
}

inline std::size_t RadixTree::node_count() const {
    return count_nodes_rec(root_);
}

inline std::size_t RadixTree::height() const {
    return height_rec(root_);
}

inline std::optional<std::int64_t> RadixTree::get(
    std::span<const std::uint8_t> key) const {
    const std::uint8_t* kp = key.data();
    const std::uint32_t klen = static_cast<std::uint32_t>(key.size());
    if (klen == 0) [[unlikely]] {
        return get_root_value();
    }
    std::uint32_t cur = find_child_internal(root_, kp[0]);
    if (cur == NULL_HANDLE) return std::nullopt;
    std::uint32_t depth = 0;

    for (;;) {
        if (is_leaf(cur)) {
            const Leaf& lf = leaves_.items[cur];
            const std::uint32_t llen = lf.label_len;
            if (klen - depth != llen) return std::nullopt;
            if (llen > 1) {
                const std::uint8_t* lp = read_label<LEAF_INLINE>(llen, lf.lab);
                if (!bytes_equal_nonempty(kp + depth + 1, lp + 1, llen - 1)) return std::nullopt;
            }
            return lf.value;
        }
        const std::uint32_t idx = handle_idx(cur);
        switch (handle_tag(cur)) {
            case TAG_NODE4: {
                const Node4& nd = nodes4_.items[idx];
                const std::uint32_t llen = nd.label_len;
                const std::uint32_t rem = klen - depth;
                if (rem < llen) return std::nullopt;
                if (llen > 1) {
                    const std::uint8_t* lp = read_label<NODE4_INLINE>(llen, nd.lab);
                    if (!bytes_equal_nonempty(kp + depth + 1, lp + 1, llen - 1))
                        return std::nullopt;
                }
                depth += llen;
                if (depth == klen) {
                    return nd.has_key ? std::optional<std::int64_t>(nd.value) : std::nullopt;
                }
                cur = node4_find(nd, kp[depth]);
                if (cur == NULL_HANDLE) return std::nullopt;
                break;
            }
            case TAG_NODE16: {
                const Node16& nd = nodes16_.items[idx];
                const std::uint32_t llen = nd.label_len;
                const std::uint32_t rem = klen - depth;
                if (rem < llen) return std::nullopt;
                if (llen > 1) {
                    const std::uint8_t* lp = read_label<NODE16_INLINE>(llen, nd.lab);
                    if (!bytes_equal_nonempty(kp + depth + 1, lp + 1, llen - 1))
                        return std::nullopt;
                }
                depth += llen;
                if (depth == klen) {
                    return nd.has_key ? std::optional<std::int64_t>(nd.value) : std::nullopt;
                }
                cur = node16_find(nd, kp[depth]);
                if (cur == NULL_HANDLE) return std::nullopt;
                break;
            }
            case TAG_NODE48: {
                const Node48& nd = nodes48_.items[idx];
                const std::uint32_t llen = nd.label_len;
                const std::uint32_t rem = klen - depth;
                if (rem < llen) return std::nullopt;
                if (llen > 1) {
                    const std::uint8_t* lp = read_label<NODE48_INLINE>(llen, nd.lab);
                    if (!bytes_equal_nonempty(kp + depth + 1, lp + 1, llen - 1))
                        return std::nullopt;
                }
                depth += llen;
                if (depth == klen) {
                    return nd.has_key ? std::optional<std::int64_t>(nd.value) : std::nullopt;
                }
                cur = node48_find(nd, kp[depth]);
                if (cur == NULL_HANDLE) return std::nullopt;
                break;
            }
            default: {
                const Node256& nd = nodes256_.items[idx];
                const std::uint32_t llen = nd.label_len;
                const std::uint32_t rem = klen - depth;
                if (rem < llen) return std::nullopt;
                if (llen > 1) {
                    const std::uint8_t* lp = read_label<NODE256_INLINE>(llen, nd.lab);
                    if (!bytes_equal_nonempty(kp + depth + 1, lp + 1, llen - 1))
                        return std::nullopt;
                }
                depth += llen;
                if (depth == klen) {
                    return nd.has_key ? std::optional<std::int64_t>(nd.value) : std::nullopt;
                }
                cur = nd.children[kp[depth]];
                if (cur == NULL_HANDLE) return std::nullopt;
                break;
            }
        }
    }
}

inline std::optional<Match> RadixTree::longest_prefix(
    std::span<const std::uint8_t> key) const {
    const std::uint8_t* kp = key.data();
    const std::uint32_t klen = static_cast<std::uint32_t>(key.size());

    bool found = false;
    std::size_t best_len = 0;
    std::int64_t best_val = 0;

    {
        const std::uint32_t ridx = handle_idx(root_);
        std::uint8_t rhk;
        std::int64_t rval;
        switch (handle_tag(root_)) {
            case TAG_NODE4:
                rhk = nodes4_.items[ridx].has_key;
                rval = nodes4_.items[ridx].value;
                break;
            case TAG_NODE16:
                rhk = nodes16_.items[ridx].has_key;
                rval = nodes16_.items[ridx].value;
                break;
            case TAG_NODE48:
                rhk = nodes48_.items[ridx].has_key;
                rval = nodes48_.items[ridx].value;
                break;
            default:
                rhk = nodes256_.items[ridx].has_key;
                rval = nodes256_.items[ridx].value;
                break;
        }
        if (rhk) [[unlikely]] {
            found = true;
            best_len = 0;
            best_val = rval;
        }
    }

    if (klen == 0) [[unlikely]] {
        return found ? std::optional<Match>(Match{0, best_val}) : std::nullopt;
    }

    std::uint32_t cur = find_child_internal(root_, kp[0]);
    if (cur == NULL_HANDLE) {
        return found ? std::optional<Match>(Match{best_len, best_val}) : std::nullopt;
    }
    std::uint32_t depth = 0;

    for (;;) {
        const std::uint32_t rem = klen - depth;
        if (is_leaf(cur)) {
            const Leaf& lf = leaves_.items[cur];
            const std::uint32_t llen = lf.label_len;
            if (rem >= llen) {
                if (llen == 1 ||
                    bytes_equal_nonempty(kp + depth + 1,
                                         read_label<LEAF_INLINE>(llen, lf.lab) + 1, llen - 1)) {
                    return Match{depth + llen, lf.value};
                }
            }
            return found ? std::optional<Match>(Match{best_len, best_val}) : std::nullopt;
        }
        const std::uint32_t idx = handle_idx(cur);
        switch (handle_tag(cur)) {
            case TAG_NODE4: {
                const Node4& nd = nodes4_.items[idx];
                const std::uint32_t llen = nd.label_len;
                if (rem < llen) goto done;
                if (llen > 1 &&
                    !bytes_equal_nonempty(kp + depth + 1,
                                          read_label<NODE4_INLINE>(llen, nd.lab) + 1, llen - 1)) {
                    goto done;
                }
                depth += llen;
                if (nd.has_key) {
                    found = true;
                    best_len = depth;
                    best_val = nd.value;
                }
                if (depth == klen) goto done;
                cur = node4_find(nd, kp[depth]);
                if (cur == NULL_HANDLE) goto done;
                break;
            }
            case TAG_NODE16: {
                const Node16& nd = nodes16_.items[idx];
                const std::uint32_t llen = nd.label_len;
                if (rem < llen) goto done;
                if (llen > 1 &&
                    !bytes_equal_nonempty(kp + depth + 1,
                                          read_label<NODE16_INLINE>(llen, nd.lab) + 1, llen - 1)) {
                    goto done;
                }
                depth += llen;
                if (nd.has_key) {
                    found = true;
                    best_len = depth;
                    best_val = nd.value;
                }
                if (depth == klen) goto done;
                cur = node16_find(nd, kp[depth]);
                if (cur == NULL_HANDLE) goto done;
                break;
            }
            case TAG_NODE48: {
                const Node48& nd = nodes48_.items[idx];
                const std::uint32_t llen = nd.label_len;
                if (rem < llen) goto done;
                if (llen > 1 &&
                    !bytes_equal_nonempty(kp + depth + 1,
                                          read_label<NODE48_INLINE>(llen, nd.lab) + 1, llen - 1)) {
                    goto done;
                }
                depth += llen;
                if (nd.has_key) {
                    found = true;
                    best_len = depth;
                    best_val = nd.value;
                }
                if (depth == klen) goto done;
                cur = node48_find(nd, kp[depth]);
                if (cur == NULL_HANDLE) goto done;
                break;
            }
            default: {
                const Node256& nd = nodes256_.items[idx];
                const std::uint32_t llen = nd.label_len;
                if (rem < llen) goto done;
                if (llen > 1 &&
                    !bytes_equal_nonempty(kp + depth + 1,
                                          read_label<NODE256_INLINE>(llen, nd.lab) + 1, llen - 1)) {
                    goto done;
                }
                depth += llen;
                if (nd.has_key) {
                    found = true;
                    best_len = depth;
                    best_val = nd.value;
                }
                if (depth == klen) goto done;
                cur = nd.children[kp[depth]];
                if (cur == NULL_HANDLE) goto done;
                break;
            }
        }
    }

done:
    return found ? std::optional<Match>(Match{best_len, best_val}) : std::nullopt;
}

inline std::size_t RadixTree::prefix_count(
    std::span<const std::uint8_t> prefix) const {
    const std::uint32_t plen = static_cast<std::uint32_t>(prefix.size());
    if (plen == 0) return size_;
    const std::uint32_t target = find_prefix_node(prefix.data(), plen);
    if (target == NULL_HANDLE) return 0;
    return get_subtree_count(target);
}

inline std::size_t RadixTree::prefix_values(std::span<const std::uint8_t> prefix,
                                            std::int64_t* out_values,
                                            std::size_t limit) const {
    if (limit == 0 || size_ == 0) return 0;
    const std::uint32_t plen = static_cast<std::uint32_t>(prefix.size());
    const std::uint32_t target = find_prefix_node(prefix.data(), plen);
    if (target == NULL_HANDLE) return 0;
    const Leaf* leaves = leaves_.items.data();
    if (is_leaf(target)) {
        out_values[0] = leaves[target].value;
        return 1;
    }
    const std::uint32_t sub = get_subtree_count(target);
    if (sub == 0) return 0;
    if (limit >= sub) {
        std::int64_t* end = collect_all_internal(target, out_values, leaves);
        return static_cast<std::size_t>(end - out_values);
    }
    std::int64_t* end = collect_limited_internal(target, out_values, out_values + limit, leaves);
    return static_cast<std::size_t>(end - out_values);
}

inline bool RadixTree::insert(std::span<const std::uint8_t> key,
                              std::int64_t value) {
    const std::uint8_t* kp = key.data();
    const std::uint32_t klen = static_cast<std::uint32_t>(key.size());

    if (klen == 0) [[unlikely]] {
        const std::uint32_t ridx = handle_idx(root_);
        switch (handle_tag(root_)) {
            case TAG_NODE4: {
                Node4& r = nodes4_.items[ridx];
                r.value = value;
                if (r.has_key) return false;
                r.has_key = 1;
                r.subtree_count += 1;
                size_ += 1;
                return true;
            }
            case TAG_NODE16: {
                Node16& r = nodes16_.items[ridx];
                r.value = value;
                if (r.has_key) return false;
                r.has_key = 1;
                r.subtree_count += 1;
                size_ += 1;
                return true;
            }
            case TAG_NODE48: {
                Node48& r = nodes48_.items[ridx];
                r.value = value;
                if (r.has_key) return false;
                r.has_key = 1;
                r.subtree_count += 1;
                size_ += 1;
                return true;
            }
            default: {
                Node256& r = nodes256_.items[ridx];
                r.value = value;
                if (r.has_key) return false;
                r.has_key = 1;
                r.subtree_count += 1;
                size_ += 1;
                return true;
            }
        }
    }

    std::uint32_t path[256];
    std::uint8_t path_byte[256];
    std::uint32_t path_len = 0;

    std::uint32_t cur = root_;
    std::uint8_t b = kp[0];
    std::uint32_t child = find_child_internal(cur, b);
    std::uint32_t depth = 0;

    for (;;) {
        path[path_len] = cur;
        path_byte[path_len] = b;
        path_len++;

        if (child == NULL_HANDLE) {
            std::uint32_t leaf_h = alloc_leaf(value, kp + depth, klen - depth);
            std::uint32_t new_cur = add_child(cur, b, leaf_h);
            if (new_cur != cur) {
                if (path_len == 1) {
                    root_ = new_cur;
                } else {
                    replace_child(path[path_len - 2], path_byte[path_len - 2], new_cur);
                }
                path[path_len - 1] = new_cur;
            }
            for (std::uint32_t i = 0; i < path_len; ++i) {
                add_subtree_count(path[i], 1);
            }
            size_ += 1;
            return true;
        }

        const std::uint32_t rem = klen - depth;
        const std::uint8_t* lp = nullptr;
        std::uint32_t llen = 0;
        std::uint32_t match = 0;

        if (is_leaf(child)) {
            Leaf& lf = leaves_.items[child];
            llen = lf.label_len;
            if (llen == 1) {
                match = 1;
            } else {
                lp = read_label<LEAF_INLINE>(llen, lf.lab);
                const std::uint32_t max_cmp = rem < llen ? rem : llen;
                match = lcp_from_1(kp + depth, lp, max_cmp);
            }
            if (match == llen) {
                depth += llen;
                if (depth == klen) {
                    lf.value = value;
                    return false;
                }
                // Promote Leaf -> Node4.
                const std::int64_t old_val = lf.value;
                const std::uint32_t old_llen = llen;
                std::uint8_t old_lab_copy[LEAF_INLINE];
                std::memcpy(old_lab_copy, lf.lab, LEAF_INLINE);
                leaves_.free(child);

                const std::uint32_t new_leaf = alloc_leaf(value, kp + depth, klen - depth);
                const std::uint32_t n4_idx = nodes4_.alloc();
                Node4& nd = nodes4_.items[n4_idx];
                nd.value = old_val;
                nd.subtree_count = 2;
                nd.has_key = 1;
                nd.num_children = 1;
                nd.keys[0] = kp[depth];
                nd.children[0] = new_leaf;
                transfer_label<LEAF_INLINE, NODE4_INLINE>(
                    nd.label_len, nd.lab, old_llen, old_lab_copy);

                replace_child(cur, b, make_handle(TAG_NODE4, n4_idx));
                for (std::uint32_t i = 0; i < path_len; ++i) {
                    add_subtree_count(path[i], 1);
                }
                size_ += 1;
                return true;
            }
            // Fall through to split `child` at `match < llen`.
        } else {
            const std::uint32_t cidx = handle_idx(child);
            switch (handle_tag(child)) {
                case TAG_NODE4: {
                    Node4& nd = nodes4_.items[cidx];
                    llen = nd.label_len;
                    if (llen == 1) {
                        match = 1;
                    } else {
                        lp = read_label<NODE4_INLINE>(llen, nd.lab);
                        match = lcp_from_1(kp + depth, lp, rem < llen ? rem : llen);
                    }
                    if (match < llen) break;
                    depth += llen;
                    if (depth == klen) {
                        const bool existed = nd.has_key != 0;
                        nd.value = value;
                        if (existed) return false;
                        nd.has_key = 1;
                        nd.subtree_count += 1;
                        for (std::uint32_t i = 0; i < path_len; ++i) add_subtree_count(path[i], 1);
                        size_ += 1;
                        return true;
                    }
                    cur = child;
                    b = kp[depth];
                    child = node4_find(nd, b);
                    continue;
                }
                case TAG_NODE16: {
                    Node16& nd = nodes16_.items[cidx];
                    llen = nd.label_len;
                    if (llen == 1) {
                        match = 1;
                    } else {
                        lp = read_label<NODE16_INLINE>(llen, nd.lab);
                        match = lcp_from_1(kp + depth, lp, rem < llen ? rem : llen);
                    }
                    if (match < llen) break;
                    depth += llen;
                    if (depth == klen) {
                        const bool existed = nd.has_key != 0;
                        nd.value = value;
                        if (existed) return false;
                        nd.has_key = 1;
                        nd.subtree_count += 1;
                        for (std::uint32_t i = 0; i < path_len; ++i) add_subtree_count(path[i], 1);
                        size_ += 1;
                        return true;
                    }
                    cur = child;
                    b = kp[depth];
                    child = node16_find(nd, b);
                    continue;
                }
                case TAG_NODE48: {
                    Node48& nd = nodes48_.items[cidx];
                    llen = nd.label_len;
                    if (llen == 1) {
                        match = 1;
                    } else {
                        lp = read_label<NODE48_INLINE>(llen, nd.lab);
                        match = lcp_from_1(kp + depth, lp, rem < llen ? rem : llen);
                    }
                    if (match < llen) break;
                    depth += llen;
                    if (depth == klen) {
                        const bool existed = nd.has_key != 0;
                        nd.value = value;
                        if (existed) return false;
                        nd.has_key = 1;
                        nd.subtree_count += 1;
                        for (std::uint32_t i = 0; i < path_len; ++i) add_subtree_count(path[i], 1);
                        size_ += 1;
                        return true;
                    }
                    cur = child;
                    b = kp[depth];
                    child = node48_find(nd, b);
                    continue;
                }
                default: {
                    Node256& nd = nodes256_.items[cidx];
                    llen = nd.label_len;
                    if (llen == 1) {
                        match = 1;
                    } else {
                        lp = read_label<NODE256_INLINE>(llen, nd.lab);
                        match = lcp_from_1(kp + depth, lp, rem < llen ? rem : llen);
                    }
                    if (match < llen) break;
                    depth += llen;
                    if (depth == klen) {
                        const bool existed = nd.has_key != 0;
                        nd.value = value;
                        if (existed) return false;
                        nd.has_key = 1;
                        nd.subtree_count += 1;
                        for (std::uint32_t i = 0; i < path_len; ++i) add_subtree_count(path[i], 1);
                        size_ += 1;
                        return true;
                    }
                    cur = child;
                    b = kp[depth];
                    child = nd.children[b];
                    continue;
                }
            }
        }

        // Split `child`'s edge at `match < llen`.
        std::uint8_t tail_buf[255];
        const std::uint32_t tail_len = llen - match;
        std::memcpy(tail_buf, lp + match, tail_len);
        const std::uint8_t child_first = tail_buf[0];
        const std::uint32_t child_sub = get_subtree_count(child);

        replace_node_label(child, tail_buf, tail_len);

        std::uint32_t split_idx = nodes4_.alloc();
        if (match == rem) {
            Node4& sn = nodes4_.items[split_idx];
            sn.value = value;
            sn.subtree_count = child_sub + 1;
            sn.has_key = 1;
            sn.num_children = 1;
            sn.keys[0] = child_first;
            sn.children[0] = child;
            set_label<NODE4_INLINE>(sn.label_len, sn.lab, kp + depth, match);
        } else {
            const std::uint8_t new_first = kp[depth + match];
            const std::uint32_t new_leaf =
                alloc_leaf(value, kp + depth + match, rem - match);
            Node4& sn = nodes4_.items[split_idx];
            sn.value = 0;
            sn.subtree_count = child_sub + 1;
            sn.has_key = 0;
            sn.num_children = 2;
            if (child_first < new_first) {
                sn.keys[0] = child_first;
                sn.children[0] = child;
                sn.keys[1] = new_first;
                sn.children[1] = new_leaf;
            } else {
                sn.keys[0] = new_first;
                sn.children[0] = new_leaf;
                sn.keys[1] = child_first;
                sn.children[1] = child;
            }
            set_label<NODE4_INLINE>(sn.label_len, sn.lab, kp + depth, match);
        }
        const std::uint32_t split_h = make_handle(TAG_NODE4, split_idx);
        replace_child(cur, b, split_h);
        for (std::uint32_t i = 0; i < path_len; ++i) {
            add_subtree_count(path[i], 1);
        }
        size_ += 1;
        return true;
    }
}

inline bool RadixTree::remove(std::span<const std::uint8_t> key) {
    const std::uint8_t* kp = key.data();
    const std::uint32_t klen = static_cast<std::uint32_t>(key.size());

    if (klen == 0) [[unlikely]] {
        const std::uint32_t ridx = handle_idx(root_);
        switch (handle_tag(root_)) {
            case TAG_NODE4: {
                Node4& r = nodes4_.items[ridx];
                if (!r.has_key) return false;
                r.has_key = 0;
                r.subtree_count -= 1;
                size_ -= 1;
                return true;
            }
            case TAG_NODE16: {
                Node16& r = nodes16_.items[ridx];
                if (!r.has_key) return false;
                r.has_key = 0;
                r.subtree_count -= 1;
                size_ -= 1;
                return true;
            }
            case TAG_NODE48: {
                Node48& r = nodes48_.items[ridx];
                if (!r.has_key) return false;
                r.has_key = 0;
                r.subtree_count -= 1;
                size_ -= 1;
                return true;
            }
            default: {
                Node256& r = nodes256_.items[ridx];
                if (!r.has_key) return false;
                r.has_key = 0;
                r.subtree_count -= 1;
                size_ -= 1;
                return true;
            }
        }
    }

    std::uint32_t path[256];
    std::uint8_t path_byte[256];
    std::uint32_t path_len = 0;

    std::uint32_t cur = root_;
    std::uint8_t b = kp[0];
    std::uint32_t child = find_child_internal(cur, b);
    if (child == NULL_HANDLE) return false;
    std::uint32_t depth = 0;

    for (;;) {
        path[path_len] = cur;
        path_byte[path_len] = b;
        path_len++;

        const std::uint32_t rem = klen - depth;
        if (is_leaf(child)) {
            const Leaf& lf = leaves_.items[child];
            const std::uint32_t llen = lf.label_len;
            if (rem != llen) return false;
            if (llen > 1 &&
                !bytes_equal_nonempty(kp + depth + 1,
                                      read_label<LEAF_INLINE>(llen, lf.lab) + 1, llen - 1)) {
                return false;
            }
            break;
        }

        const std::uint32_t cidx = handle_idx(child);
        switch (handle_tag(child)) {
            case TAG_NODE4: {
                const Node4& nd = nodes4_.items[cidx];
                const std::uint32_t llen = nd.label_len;
                if (rem < llen) return false;
                if (llen > 1 &&
                    !bytes_equal_nonempty(kp + depth + 1,
                                          read_label<NODE4_INLINE>(llen, nd.lab) + 1, llen - 1)) {
                    return false;
                }
                depth += llen;
                if (depth == klen) goto found_target;
                cur = child;
                b = kp[depth];
                child = node4_find(nd, b);
                if (child == NULL_HANDLE) return false;
                break;
            }
            case TAG_NODE16: {
                const Node16& nd = nodes16_.items[cidx];
                const std::uint32_t llen = nd.label_len;
                if (rem < llen) return false;
                if (llen > 1 &&
                    !bytes_equal_nonempty(kp + depth + 1,
                                          read_label<NODE16_INLINE>(llen, nd.lab) + 1, llen - 1)) {
                    return false;
                }
                depth += llen;
                if (depth == klen) goto found_target;
                cur = child;
                b = kp[depth];
                child = node16_find(nd, b);
                if (child == NULL_HANDLE) return false;
                break;
            }
            case TAG_NODE48: {
                const Node48& nd = nodes48_.items[cidx];
                const std::uint32_t llen = nd.label_len;
                if (rem < llen) return false;
                if (llen > 1 &&
                    !bytes_equal_nonempty(kp + depth + 1,
                                          read_label<NODE48_INLINE>(llen, nd.lab) + 1, llen - 1)) {
                    return false;
                }
                depth += llen;
                if (depth == klen) goto found_target;
                cur = child;
                b = kp[depth];
                child = node48_find(nd, b);
                if (child == NULL_HANDLE) return false;
                break;
            }
            default: {
                const Node256& nd = nodes256_.items[cidx];
                const std::uint32_t llen = nd.label_len;
                if (rem < llen) return false;
                if (llen > 1 &&
                    !bytes_equal_nonempty(kp + depth + 1,
                                          read_label<NODE256_INLINE>(llen, nd.lab) + 1, llen - 1)) {
                    return false;
                }
                depth += llen;
                if (depth == klen) goto found_target;
                cur = child;
                b = kp[depth];
                child = nd.children[b];
                if (child == NULL_HANDLE) return false;
                break;
            }
        }
    }

found_target:
    const std::uint32_t parent = path[path_len - 1];
    const std::uint8_t pb = path_byte[path_len - 1];

    if (is_leaf(child)) {
        Leaf& lf = leaves_.items[child];
        release_label<LEAF_INLINE>(lf.label_len, lf.lab);
        leaves_.free(child);

        for (std::uint32_t i = 0; i < path_len; ++i) {
            add_subtree_count(path[i], -1);
        }
        size_ -= 1;

        std::uint32_t new_parent = remove_child_and_maybe_shrink(parent, pb);
        if (path_len == 1) {
            root_ = new_parent;
            return true;
        }

        const std::uint32_t gp = path[path_len - 2];
        const std::uint8_t gpb = path_byte[path_len - 2];
        if (handle_tag(new_parent) == TAG_NODE4) {
            const std::uint32_t pidx = handle_idx(new_parent);
            const Node4& pnd = nodes4_.items[pidx];
            if (pnd.num_children == 0) {
                const std::int64_t pval = pnd.value;
                const std::uint32_t plen = pnd.label_len;
                std::uint8_t plab_copy[NODE4_INLINE];
                std::memcpy(plab_copy, pnd.lab, NODE4_INLINE);
                nodes4_.free(pidx);

                const std::uint32_t lf_idx = leaves_.alloc();
                Leaf& nlf = leaves_.items[lf_idx];
                nlf.value = pval;
                transfer_label<NODE4_INLINE, LEAF_INLINE>(
                    nlf.label_len, nlf.lab, plen, plab_copy);
                replace_child(gp, gpb, lf_idx);
                return true;
            }
            if (pnd.num_children == 1 && !pnd.has_key) {
                std::uint32_t merged = merge_node4_with_only_child(new_parent);
                replace_child(gp, gpb, merged);
                return true;
            }
        }
        if (new_parent != parent) {
            replace_child(gp, gpb, new_parent);
        }
        return true;
    }

    const std::uint32_t cidx = handle_idx(child);
    bool should_merge = false;
    switch (handle_tag(child)) {
        case TAG_NODE4: {
            Node4& nd = nodes4_.items[cidx];
            if (!nd.has_key) return false;
            nd.has_key = 0;
            nd.subtree_count -= 1;
            should_merge = (nd.num_children == 1);
            break;
        }
        case TAG_NODE16: {
            Node16& nd = nodes16_.items[cidx];
            if (!nd.has_key) return false;
            nd.has_key = 0;
            nd.subtree_count -= 1;
            break;
        }
        case TAG_NODE48: {
            Node48& nd = nodes48_.items[cidx];
            if (!nd.has_key) return false;
            nd.has_key = 0;
            nd.subtree_count -= 1;
            break;
        }
        default: {
            Node256& nd = nodes256_.items[cidx];
            if (!nd.has_key) return false;
            nd.has_key = 0;
            nd.subtree_count -= 1;
            break;
        }
    }

    for (std::uint32_t i = 0; i < path_len; ++i) {
        add_subtree_count(path[i], -1);
    }
    size_ -= 1;

    if (should_merge) {
        std::uint32_t merged = merge_node4_with_only_child(child);
        replace_child(parent, pb, merged);
    }
    return true;
}
