基于Rust的区间树
Intervaltree with Rust Back End

原始链接: https://github.com/Athe-kunal/intervaltree_rs

## intervaltree_rs:Python 的 Rust 区间树 `intervaltree_rs` 使用 PyO3 将用 Rust 编写的高性能区间树实现带到 Python。该包允许高效地管理和查询区间。 用户可以从元组列表 (left, right, payload) 创建一个 `IntervalTree`,插入新的区间,并在指定的范围内搜索重叠。`search` 方法支持包含或排除边界。还可以使用它们的 (left, right) 键删除区间。 **安装:** 需要 Rust 工具链、Python 3.8+ 和 `maturin`。使用 `maturin develop` 进行原地开发构建,或使用 `maturin build` 构建可分发的 wheel。然后,该包可以在 Python 中作为 `intervaltree_rs` 访问。 核心功能经过 Rust 单元测试的全面测试,确保可靠性和性能。

一位开发者 (@athekunal) 使用 Rust 构建了一个基于区间树的实现,并提供了 Python 绑定(通过 PyO3),作为 Python 原生 `intervaltree` 的更快替代方案。该项目旨在成为一个可以直接替换的方案,未来的计划包括实现 AVL 树和红黑树来进行平衡。 Hacker News 的评论讨论主要集中在平衡方法上,有人建议探索 Rust 的 `BTreeMap` 和 `rangemap` crate 用于范围映射。 同时也出现了关于支持集合运算和序列化,以及是否可以作为独立的 Rust crate 发布的问题。 其他用户分享了相关的项目——一个 TypeScript 实现和 C++ 中的 Boost 区间容器库,并讨论了诸如大数据集中的堆内存使用等性能考量。 该帖子还包含了一个 Y Combinator 申请的公告。
相关文章

原文

This crate exposes an interval tree implementation written in Rust to Python via PyO3. The Python wrapper provides the ability to build a tree from tuples, insert additional intervals, search for overlaps, and delete intervals by their (left, right) key.

  • Rust toolchain (for compiling the extension module)
  • Python 3.8+
  • maturin for building/installing the package
python -m venv .venv
source .venv/bin/activate
pip install maturin
maturin develop

You can install the package with (also with uv)

pip install intervaltree_rs

maturin develop builds the extension module in-place and installs it into the active virtual environment, making it importable as intervaltree_rs.

Once installed, you can use the interval tree directly from Python:

from intervaltree_rs import IntervalTree

# Build a tree from tuples: (left, right, payload)
intervals = [
    (5, 10, "a"),
    (12, 18, "b"),
    (1, 4, "c"),
]
tree = IntervalTree.from_tuples(intervals)

# Insert another interval
tree.insert((8, 11, "d"))

# Search for overlaps. Inclusive bounds are enabled by default.
hits = tree.search(9, 10)
for left, right, value in hits:
    print(left, right, value)

# Delete by the interval key
removed = tree.delete((12, 18))
print("Removed:", removed)

IntervalTree.search(ql, qr, inclusive=True) accepts an inclusive flag. Set it to False to perform exclusive range queries.

Building a distributable wheel

To build a wheel that you can distribute or upload to PyPI, run:

The built wheels will be placed under target/wheels/.

The Python bindings are covered by Rust unit tests. Run them with:

联系我们 contact @ memedata.com