apache_datasketches/cpc/builder.rs
1use crate::error::SketchError;
2
3/// Builder for [`crate::cpc::CpcSketch`], mirroring upstream's
4/// `cpc_sketch_alloc` constructor. `lg_k` defaults to `11`
5/// (`cpc_constants::DEFAULT_LG_K`). The seed is never exposed — every
6/// sketch built by this crate always uses upstream's `DEFAULT_SEED`.
7#[derive(Debug, Clone, Copy)]
8pub struct CpcSketchBuilder {
9 lg_k: u8,
10}
11
12impl Default for CpcSketchBuilder {
13 fn default() -> Self {
14 Self { lg_k: 11 }
15 }
16}
17
18impl CpcSketchBuilder {
19 /// Creates a new builder with the default `lg_k` (`11`).
20 pub fn new() -> Self {
21 Self::default()
22 }
23
24 /// Sets the base-2 log of the number of bins in the sketch (`4..=26`).
25 pub fn lg_k(mut self, lg_k: u8) -> Self {
26 self.lg_k = lg_k;
27 self
28 }
29
30 /// Builds the sketch. Returns [`SketchError::InvalidConfig`] if `lg_k`
31 /// is out of range.
32 pub fn build(self) -> Result<super::CpcSketch, SketchError> {
33 super::CpcSketch::from_lg_k(self.lg_k)
34 }
35}
36
37/// Builder for [`crate::cpc::CpcUnion`], mirroring upstream's
38/// `cpc_union_alloc` constructor. `lg_k` defaults to `11`
39/// (`cpc_constants::DEFAULT_LG_K`). The seed is never exposed, same as
40/// [`CpcSketchBuilder`].
41#[derive(Debug, Clone, Copy)]
42pub struct CpcUnionBuilder {
43 lg_k: u8,
44}
45
46impl Default for CpcUnionBuilder {
47 fn default() -> Self {
48 Self { lg_k: 11 }
49 }
50}
51
52impl CpcUnionBuilder {
53 /// Creates a new builder with the default `lg_k` (`11`).
54 pub fn new() -> Self {
55 Self::default()
56 }
57
58 /// Sets the base-2 log of the number of bins in the union (`4..=26`).
59 pub fn lg_k(mut self, lg_k: u8) -> Self {
60 self.lg_k = lg_k;
61 self
62 }
63
64 /// Builds the union. Returns [`SketchError::InvalidConfig`] if `lg_k`
65 /// is out of range.
66 pub fn build(self) -> Result<super::CpcUnion, SketchError> {
67 super::CpcUnion::from_lg_k(self.lg_k)
68 }
69}