Skip to main content

path_kit/
op_builder.rs

1//! 路径操作构建器。Path operation builder for combining multiple paths.
2
3use crate::path::Path;
4use crate::path_op::PathOp;
5
6/// 路径操作构建器,用于批量执行路径布尔运算。
7/// Path operation builder, optimized for unioning/combining many paths.
8///
9/// 用法:多次 add 后调用 resolve 得到最终结果。
10/// Usage: call add multiple times, then resolve to get the final result.
11#[derive(Default)]
12pub struct OpBuilder {
13    paths: Vec<(Path, PathOp)>,
14}
15
16impl OpBuilder {
17    /// 创建空构建器。Creates an empty builder.
18    pub fn new() -> Self {
19        Self {
20            paths: Vec::new(),
21        }
22    }
23
24    /// 添加路径及对应操作。Add a path with its boolean operation.
25    ///
26    /// 第一次 add 时相当于 (空路径 OP path),后续每次为 (当前结果 OP path)。
27    /// First add: (empty OP path). Each subsequent: (current_result OP path).
28    pub fn add(&mut self, path: Path, op: PathOp) -> &mut Self {
29        self.paths.push((path, op));
30        self
31    }
32
33    /// 按引用添加路径(内部 clone)。Add path by reference (clones internally).
34    ///
35    /// 复用同一路径时比 `add(path.clone(), op)` 更简洁。
36    /// Convenient when reusing the same path.
37    pub fn add_ref(&mut self, path: &Path, op: PathOp) -> &mut Self {
38        self.paths.push((path.clone(), op));
39        self
40    }
41
42    /// 计算并返回所有路径运算的结果。Resolves all operations and returns the result.
43    ///
44    /// 调用后构建器会清空,可继续复用。
45    /// Builder is reset after resolve; can be reused.
46    pub fn resolve(&mut self) -> Option<Path> {
47        let paths = std::mem::take(&mut self.paths);
48        if paths.is_empty() {
49            return Some(Path::new());
50        }
51        let mut result = Path::new();
52        for (path, op) in paths {
53            result = crate::ops::path_op(&result, &path, op)?;
54        }
55        Some(result)
56    }
57}