Skip to main content

apache_datasketches/cpc/
union.rs

1use crate::cpc::sketch::CpcSketch;
2use crate::error::SketchError;
3use apache_datasketches_sys::cpc_union::ffi as sys;
4use cxx::UniquePtr;
5
6/// Merges multiple [`CpcSketch`]es into one, e.g. combining per-shard or
7/// per-day counts into a total distinct count across all of them. Build
8/// one with [`CpcUnionBuilder`](super::CpcUnionBuilder).
9///
10/// Unlike HLL's `HllUnion`, `CpcUnion` has no
11/// `get_estimate`/`is_empty`/`reset` convenience methods of its own —
12/// upstream's `cpc_union` doesn't have them either; query the sketch
13/// returned by [`Self::get_result`] instead.
14pub struct CpcUnion {
15    inner: UniquePtr<sys::CpcUnionShim>,
16}
17
18unsafe impl Send for CpcUnion {}
19
20impl CpcUnion {
21    pub(crate) fn from_lg_k(lg_k: u8) -> Result<Self, SketchError> {
22        let inner = sys::new_cpc_union(lg_k)
23            .map_err(|e| SketchError::InvalidConfig(e.what().to_string()))?;
24        Ok(Self { inner })
25    }
26
27    /// Merges the given sketch's state into this union.
28    pub fn update(&mut self, sketch: &CpcSketch) {
29        self.inner.pin_mut().update_sketch(&sketch.inner);
30    }
31
32    /// Returns the current merged result as a standalone [`CpcSketch`].
33    pub fn get_result(&self) -> CpcSketch {
34        let inner = self.inner.get_result();
35        CpcSketch { inner }
36    }
37}