在 `CharacterSet::remove_intersection` 中生成二次范围向量编辑

作者: jkbz64创建于 2026年9月29日更新于 2026年9月30日
标签parser-generationperf

use std::{ cmp::{Ordering, max}, fmt, iter::ExactSizeIterator,

  • mem::{self, swap},
  • mem, ops::{Range, RangeInclusive}, };

impl CharacterSet { #[cfg(test)] fn from_range(mut first: char, mut last: char) -> Self { if first > last {

  •        swap(&mut first, &mut last);
  •        mem::swap(&mut first, &mut last);
       }
       Self {
           ranges: vec![(first as u32)..(last as u32 + 1)],

@@ -181,112 +181,50 @@ impl CharacterSet { /// of the operands. #[allow(clippy::return_self_not_must_use)] pub fn remove_intersection(&mut self, other: &mut Self) -> Self {

  •    if !self.does_intersect(other) {
  •        return Self::empty();
  •    }
       let mut intersection = Vec::new();
  •    let mut left_only = Vec::new();
  •    let mut right_only = Vec::new();
       let mut left_i = 0;
       let mut right_i = 0;
  •    // Consume sorted ranges once. Removing or inserting ranges in the middle
  •    // of either vector repeatedly shifts its tail, making Unicode sets quadratic.
       while left_i < self.ranges.len() && right_i < other.ranges.len() {
           let left = &mut self.ranges[left_i];
           let right = &mut other.ranges[right_i];
  •        match left.start.cmp(&right.start) {
  •            Ordering::Less => {
  •                // [ L ]
  •                //     [ R ]
  •                if left.end <= right.start {
  •                    left_i += 1;
  •                    continue;
  •                }
  •                match left.end.cmp(&right.end) {
  •                    // [ L ]
  •                    //   [ R ]
  •                    Ordering::Less => {

…

内容来源: tree-sitter/tree-sitter