This is an automated email from the ASF dual-hosted git repository.
tisonkun pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/datasketches-rust.git
The following commit(s) were added to refs/heads/main by this push:
new 4266ad9 refactor: replace theta family sketch traits with concrete
views (#185)
4266ad9 is described below
commit 4266ad9cad21e0660c2ae9506174e01665bd100d
Author: tison <[email protected]>
AuthorDate: Sun Aug 9 22:48:51 2026 +0800
refactor: replace theta family sketch traits with concrete views (#185)
---
datasketches/src/thetafamily/common/a_not_b.rs | 259 ++++++++---------
.../src/thetafamily/common/binomial_bounds.rs | 20 +-
datasketches/src/thetafamily/common/hash_table.rs | 25 +-
.../src/thetafamily/common/intersection.rs | 193 ++-----------
.../src/thetafamily/common/jaccard_similarity.rs | 313 +++++++++------------
datasketches/src/thetafamily/common/mod.rs | 63 ++---
datasketches/src/thetafamily/common/union.rs | 126 ++-------
datasketches/src/thetafamily/theta/a_not_b.rs | 22 +-
datasketches/src/thetafamily/theta/hash_table.rs | 6 +-
datasketches/src/thetafamily/theta/intersection.rs | 3 +-
.../src/thetafamily/theta/jaccard_similarity.rs | 24 +-
datasketches/src/thetafamily/theta/sketch.rs | 187 ++++++++----
datasketches/src/thetafamily/theta/union.rs | 3 +-
datasketches/src/thetafamily/tuple/a_not_b.rs | 22 +-
datasketches/src/thetafamily/tuple/hash_table.rs | 4 +-
datasketches/src/thetafamily/tuple/intersection.rs | 9 +-
.../src/thetafamily/tuple/jaccard_similarity.rs | 34 ++-
datasketches/src/thetafamily/tuple/mod.rs | 1 -
datasketches/src/thetafamily/tuple/sketch.rs | 263 ++++++++++-------
datasketches/src/thetafamily/tuple/union.rs | 12 +-
20 files changed, 727 insertions(+), 862 deletions(-)
diff --git a/datasketches/src/thetafamily/common/a_not_b.rs
b/datasketches/src/thetafamily/common/a_not_b.rs
index 3e12151..643d7df 100644
--- a/datasketches/src/thetafamily/common/a_not_b.rs
+++ b/datasketches/src/thetafamily/common/a_not_b.rs
@@ -20,169 +20,158 @@ use std::collections::HashSet;
use crate::error::Error;
use crate::error::ErrorKind;
use crate::hash::check_seed_hash;
-use crate::hash::compute_seed_hash;
-use crate::thetacommon::RetainedEntry;
-use crate::thetacommon::ThetaFamilySketchView;
-use crate::thetacommon::ThetaKeySketchView;
+use crate::thetacommon::EntrySketch;
+use crate::thetacommon::KeySketch;
+use crate::thetacommon::SketchEntry;
+use crate::thetacommon::SketchScalars;
use crate::thetacommon::constants::MAX_THETA;
use crate::thetacommon::hash_table::CompactSketchParts;
-/// Stateless set difference (`A and not B`) operator shared by Theta and
Tuple sketches.
+/// Computes `a and not b` for Theta-family sketch views.
///
/// Ordinary Theta entries only contain a hash, while tuple entries also carry
a summary.
/// Surviving entries are moved from `A` unchanged, and `B` contributes only
hashes, so unlike
/// the union and intersection this operation needs neither matching entry
types nor an
/// entry-merge policy.
-#[derive(Debug, Clone, Copy)]
-pub struct ANotBOperator {
+pub fn compute<A, B>(
seed_hash: u16,
-}
+ a: A,
+ b: B,
+ ordered: bool,
+) -> Result<CompactSketchParts<A::Entry>, Error>
+where
+ A: EntrySketch,
+ B: KeySketch,
+{
+ let SketchScalars {
+ seed_hash: a_seed_hash,
+ theta: a_theta,
+ empty: a_empty,
+ ordered: a_ordered,
+ ..
+ } = a.scalars();
-impl ANotBOperator {
- /// Creates a new set difference operator for the given `seed`.
- pub fn new(seed: u64) -> Self {
- Self {
- seed_hash: compute_seed_hash(seed),
- }
+ // If A is empty the result is an (empty) copy of A. As with the union and
intersection, an
+ // empty input carries no keys, so its seed is not validated.
+ if a_empty {
+ return Ok(parts_from_sketch(a, ordered));
}
- /// Computes `a and not b`.
- ///
- /// The result retains every entry of `a` (below the combined theta) whose
hash is not present
- /// in `b`. If `ordered` is true, the retained entries are sorted
ascending by hash.
- ///
- /// # Errors
- ///
- /// Returns an error if either non-trivial input has a seed hash that
differs from this
- /// operator's seed.
- pub fn compute<A, B>(
- &self,
- a: &A,
- b: &B,
- ordered: bool,
- ) -> Result<CompactSketchParts<A::Entry>, Error>
- where
- A: ThetaFamilySketchView,
- B: ThetaKeySketchView,
- {
- // If A is empty the result is an (empty) copy of A. As with the union
and intersection, an
- // empty input carries no keys, so its seed is not validated.
- if a.is_empty() {
- return Ok(Self::parts_from_view(a, ordered));
- }
+ // A is non-empty, so its seed must be compatible.
+ check_seed_hash(seed_hash, a_seed_hash, "A", ErrorKind::InvalidArgument)?;
- // A is non-empty, so its seed must be compatible.
- check_seed_hash(
- self.seed_hash,
- a.seed_hash(),
- "A",
- ErrorKind::InvalidArgument,
- )?;
+ let SketchScalars {
+ seed_hash: b_seed_hash,
+ theta: b_theta,
+ empty: b_empty,
+ ordered: b_ordered,
+ num_retained: b_num_retained,
+ } = b.scalars();
- // An empty B subtracts nothing, so the result is simply a copy of A.
This also covers the
- // "A is non-empty but has no retained keys" state: B's seed and theta
must not influence
- // the result, so we return before touching them.
- if b.is_empty() {
- return Ok(Self::parts_from_view(a, ordered));
- }
+ // An empty B subtracts nothing, so the result is simply a copy of A. This
also covers the
+ // "A is non-empty but has no retained keys" state: B's seed and theta
must not influence
+ // the result.
+ if b_empty {
+ return Ok(parts_from_sketch(a, ordered));
+ }
- // B is non-empty, so its seed must be compatible.
- check_seed_hash(
- self.seed_hash,
- b.seed_hash(),
- "B",
- ErrorKind::InvalidArgument,
- )?;
+ // B is non-empty, so its seed must be compatible.
+ check_seed_hash(seed_hash, b_seed_hash, "B", ErrorKind::InvalidArgument)?;
- let theta = a.theta64().min(b.theta64());
- // A is non-empty here; the result only becomes empty if everything is
subtracted in exact
- // mode (handled below).
- let mut is_empty = false;
+ let theta = a_theta.min(b_theta);
+ // A is non-empty here; the result only becomes empty if everything is
subtracted in exact
+ // mode (handled below).
+ let mut is_empty = false;
- let entries: Vec<A::Entry> = if b.num_retained() == 0 {
- a.iter().filter(|entry| entry.hash() < theta).collect()
- } else if a.is_ordered() && b.is_ordered() {
- // Both inputs are sorted ascending by hash: merge-scan without a
hash set. Only
- // B hashes below theta can exclude an A entry (A entries are all
< theta), so
- // unexamined B entries at or above theta are harmless.
- let mut b_hashes = b.iter_hashes().peekable();
- let mut entries = vec![];
- for entry in a.iter() {
- let hash = entry.hash();
- if hash >= theta {
- break;
- }
- while let Some(&b_hash) = b_hashes.peek() {
- if b_hash < hash {
- b_hashes.next();
- } else {
- break;
- }
- }
- if b_hashes.peek() != Some(&hash) {
- entries.push(entry);
- }
+ let entries: Vec<A::Entry> = if b_num_retained == 0 {
+ a.entries().filter(|entry| entry.hash() < theta).collect()
+ } else if a_ordered && b_ordered {
+ // Both inputs are sorted ascending by hash: merge-scan without a hash
set. Only
+ // B hashes below theta can exclude an A entry (A entries are all <
theta), so
+ // unexamined B entries at or above theta are harmless.
+ let mut b_hashes = b.hashes().peekable();
+ let mut entries = vec![];
+ for entry in a.entries() {
+ let hash = entry.hash();
+ if hash >= theta {
+ break;
}
- entries
- } else {
- let mut b_keys: HashSet<u64> =
HashSet::with_capacity(b.num_retained());
- for hash in b.iter_hashes() {
- if hash < theta {
- b_keys.insert(hash);
- } else if b.is_ordered() {
+ while let Some(&b_hash) = b_hashes.peek() {
+ if b_hash < hash {
+ b_hashes.next();
+ } else {
break;
}
}
+ if b_hashes.peek() != Some(&hash) {
+ entries.push(entry);
+ }
+ }
+ entries
+ } else {
+ let mut b_keys: HashSet<u64> = HashSet::with_capacity(b_num_retained);
+ for hash in b.hashes() {
+ if hash < theta {
+ b_keys.insert(hash);
+ } else if b_ordered {
+ break;
+ }
+ }
- let mut entries = vec![];
- for entry in a.iter() {
- let hash = entry.hash();
- if hash < theta {
- if !b_keys.contains(&hash) {
- entries.push(entry);
- }
- } else if a.is_ordered() {
- break;
+ let mut entries = vec![];
+ for entry in a.entries() {
+ let hash = entry.hash();
+ if hash < theta {
+ if !b_keys.contains(&hash) {
+ entries.push(entry);
}
+ } else if a_ordered {
+ break;
}
- entries
- };
-
- if entries.is_empty() && theta == MAX_THETA {
- is_empty = true;
}
+ entries
+ };
- let out_ordered = ordered || a.is_ordered();
- let mut entries = entries;
- if ordered && !a.is_ordered() && entries.len() > 1 {
- entries.sort_unstable_by_key(RetainedEntry::hash);
- }
+ if entries.is_empty() && theta == MAX_THETA {
+ is_empty = true;
+ }
- Ok(CompactSketchParts {
- entries,
- theta,
- seed_hash: self.seed_hash,
- ordered: out_ordered,
- empty: is_empty,
- })
+ let out_ordered = ordered || a_ordered;
+ let mut entries = entries;
+ if ordered && !a_ordered && entries.len() > 1 {
+ entries.sort_unstable_by_key(SketchEntry::hash);
}
- /// Builds compact parts that are a copy of the view `a`.
- fn parts_from_view<V>(a: &V, ordered: bool) -> CompactSketchParts<V::Entry>
- where
- V: ThetaFamilySketchView,
- {
- let mut entries: Vec<V::Entry> = a.iter().collect();
- let out_ordered = ordered || a.is_ordered();
- if ordered && !a.is_ordered() && entries.len() > 1 {
- entries.sort_unstable_by_key(RetainedEntry::hash);
- }
- CompactSketchParts {
- entries,
- theta: a.theta64(),
- seed_hash: a.seed_hash(),
- ordered: out_ordered,
- empty: a.is_empty(),
- }
+ Ok(CompactSketchParts {
+ entries,
+ theta,
+ seed_hash,
+ ordered: out_ordered,
+ empty: is_empty,
+ })
+}
+
+fn parts_from_sketch<S>(sketch: S, ordered: bool) ->
CompactSketchParts<S::Entry>
+where
+ S: EntrySketch,
+{
+ let SketchScalars {
+ seed_hash,
+ theta,
+ empty,
+ ordered: input_ordered,
+ ..
+ } = sketch.scalars();
+ let mut entries: Vec<S::Entry> = sketch.entries().collect();
+ let out_ordered = ordered || input_ordered;
+ if ordered && !input_ordered && entries.len() > 1 {
+ entries.sort_unstable_by_key(SketchEntry::hash);
+ }
+ CompactSketchParts {
+ entries,
+ theta,
+ seed_hash,
+ ordered: out_ordered,
+ empty,
}
}
diff --git a/datasketches/src/thetafamily/common/binomial_bounds.rs
b/datasketches/src/thetafamily/common/binomial_bounds.rs
index d3a3dde..9ca251c 100644
--- a/datasketches/src/thetafamily/common/binomial_bounds.rs
+++ b/datasketches/src/thetafamily/common/binomial_bounds.rs
@@ -285,11 +285,7 @@ static UB_EQUIV_TABLE: [f64; 363] = [
/// # Errors
///
/// Returns an error if `theta` is not in the range `(0.0, 1.0]`.
-pub(crate) fn lower_bound(
- num_samples: u64,
- theta: f64,
- num_std_dev: NumStdDev,
-) -> Result<f64, Error> {
+pub fn lower_bound(num_samples: u64, theta: f64, num_std_dev: NumStdDev) ->
Result<f64, Error> {
if theta <= 0.0 || theta > 1.0 {
return Err(Error::invalid_argument(format!(
"theta must be in the range (0.0, 1.0], got {theta}"
@@ -320,7 +316,7 @@ pub(crate) fn lower_bound(
/// # Errors
///
/// Returns an error if `theta` is not in the range `(0.0, 1.0]`.
-pub(crate) fn upper_bound(
+pub fn upper_bound(
num_samples: u64,
theta: f64,
num_std_dev: NumStdDev,
@@ -342,11 +338,7 @@ pub(crate) fn upper_bound(
}
/// Computes an approximate lower bound for an unknown binomial proportion.
-pub(crate) fn approximate_lower_bound_on_p(
- n: u64,
- k: u64,
- num_std_devs: f64,
-) -> Result<f64, Error> {
+pub fn approximate_lower_bound_on_p(n: u64, k: u64, num_std_devs: f64) ->
Result<f64, Error> {
check_proportion_inputs(n, k)?;
if n == 0 || k == 0 {
Ok(0.0)
@@ -367,11 +359,7 @@ pub(crate) fn approximate_lower_bound_on_p(
}
/// Computes an approximate upper bound for an unknown binomial proportion.
-pub(crate) fn approximate_upper_bound_on_p(
- n: u64,
- k: u64,
- num_std_devs: f64,
-) -> Result<f64, Error> {
+pub fn approximate_upper_bound_on_p(n: u64, k: u64, num_std_devs: f64) ->
Result<f64, Error> {
check_proportion_inputs(n, k)?;
if n == 0 || k == n {
Ok(1.0)
diff --git a/datasketches/src/thetafamily/common/hash_table.rs
b/datasketches/src/thetafamily/common/hash_table.rs
index 6cc2a9c..3661bb7 100644
--- a/datasketches/src/thetafamily/common/hash_table.rs
+++ b/datasketches/src/thetafamily/common/hash_table.rs
@@ -16,11 +16,12 @@
// under the License.
use std::hash::Hash;
+use std::slice;
use crate::common::ResizeFactor;
use crate::hash::MurmurHash3X64128;
use crate::hash::compute_seed_hash;
-use crate::thetacommon::RetainedEntry;
+use crate::thetacommon::SketchEntry;
use crate::thetacommon::constants::HASH_TABLE_REBUILD_THRESHOLD;
use crate::thetacommon::constants::HASH_TABLE_RESIZE_THRESHOLD;
use crate::thetacommon::constants::MAX_THETA;
@@ -37,6 +38,20 @@ pub struct CompactSketchParts<E> {
pub empty: bool,
}
+pub struct SketchHashTableIter<'a, E>(slice::Iter<'a, Option<E>>);
+
+impl<'a, E> Iterator for SketchHashTableIter<'a, E> {
+ type Item = &'a E;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ self.0.find_map(Option::as_ref)
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ (0, self.0.size_hint().1)
+ }
+}
+
/// Generic hash-table mechanics shared by Theta and Tuple sketches.
///
/// The entry type supplies the retained hash and any sketch-specific payload.
The table owns all
@@ -74,7 +89,7 @@ pub struct SketchHashTable<E> {
impl<E> SketchHashTable<E>
where
- E: RetainedEntry,
+ E: SketchEntry,
{
/// Create a new hash table.
pub fn new(
@@ -256,8 +271,8 @@ where
}
/// Get iterator over retained entries.
- pub fn iter_entries(&self) -> impl Iterator<Item = &E> + '_ {
- self.entries.iter().filter_map(Option::as_ref)
+ pub fn iter_entries(&self) -> SketchHashTableIter<'_, E> {
+ SketchHashTableIter(self.entries.iter())
}
/// Returns the retained entries and theta as compact-sketch parts.
@@ -276,7 +291,7 @@ where
let is_single = entries.len() == 1 && theta == MAX_THETA;
let ordered = ordered || empty || is_single;
if ordered && entries.len() > 1 {
- entries.sort_unstable_by_key(RetainedEntry::hash);
+ entries.sort_unstable_by_key(SketchEntry::hash);
}
CompactSketchParts {
entries,
diff --git a/datasketches/src/thetafamily/common/intersection.rs
b/datasketches/src/thetafamily/common/intersection.rs
index 00e5ed4..e7a6172 100644
--- a/datasketches/src/thetafamily/common/intersection.rs
+++ b/datasketches/src/thetafamily/common/intersection.rs
@@ -19,8 +19,9 @@ use crate::common::ResizeFactor;
use crate::error::Error;
use crate::error::ErrorKind;
use crate::hash::check_seed_hash;
-use crate::thetacommon::RetainedEntry;
-use crate::thetacommon::ThetaFamilySketchView;
+use crate::thetacommon::EntrySketch;
+use crate::thetacommon::SketchEntry;
+use crate::thetacommon::SketchScalars;
use crate::thetacommon::constants::HASH_TABLE_REBUILD_THRESHOLD;
use crate::thetacommon::constants::MAX_THETA;
use crate::thetacommon::hash_table::CompactSketchParts;
@@ -47,7 +48,7 @@ pub struct IntersectionState<E, P> {
impl<E, P> IntersectionState<E, P>
where
- E: RetainedEntry,
+ E: SketchEntry,
{
/// Creates a new intersection operator for the given `seed` and
entry-merge `policy`.
pub fn new(seed: u64, policy: P) -> Self {
@@ -70,12 +71,19 @@ where
///
/// The intersection can be viewed as starting from the "universe" set,
and every update
/// reduces the current set to the keys it shares with `sketch`.
- pub fn update<S>(&mut self, sketch: &S) -> Result<(), Error>
+ pub fn update<S>(&mut self, sketch: S) -> Result<(), Error>
where
- S: ThetaFamilySketchView<Entry = E>,
+ S: EntrySketch<Entry = E>,
E: Clone,
P: IntersectionMergePolicy<E>,
{
+ let SketchScalars {
+ seed_hash,
+ theta,
+ empty,
+ ordered,
+ num_retained,
+ } = sketch.scalars();
let new_default_table = |table: &SketchHashTable<E>| {
SketchHashTable::from_raw_parts(
0,
@@ -92,12 +100,12 @@ where
return Ok(());
}
- if sketch.is_empty() {
+ if empty {
self.table.set_empty(true);
} else {
check_seed_hash(
self.table.seed_hash(),
- sketch.seed_hash(),
+ seed_hash,
"intersection update",
ErrorKind::InvalidArgument,
)?;
@@ -106,14 +114,14 @@ where
self.table.set_theta(if self.table.is_empty() {
MAX_THETA
} else {
- self.table.theta().min(sketch.theta64())
+ self.table.theta().min(theta)
});
if self.has_result && self.table.num_retained() == 0 {
return Ok(());
}
- if sketch.num_retained() == 0 {
+ if num_retained == 0 {
self.has_result = true;
self.table = new_default_table(&self.table);
return Ok(());
@@ -123,7 +131,7 @@ where
if !self.has_result {
self.has_result = true;
let lg_size = SketchHashTable::<E>::lg_size_from_count_for_rebuild(
- sketch.num_retained(),
+ num_retained,
HASH_TABLE_REBUILD_THRESHOLD,
);
// num_retained >= 1 here (the zero case returned early above), so
lg_size >= 1 and
@@ -138,7 +146,7 @@ where
self.table.seed(),
self.table.is_empty(),
);
- for entry in sketch.iter() {
+ for entry in sketch.entries() {
let hash = entry.hash();
if !self.table.upsert_entry(hash, |existing| match existing {
Some(_) => None,
@@ -150,16 +158,16 @@ where
}
}
// Safety check.
- if self.table.num_retained() != sketch.num_retained() {
+ if self.table.num_retained() != num_retained {
return Err(Error::invalid_argument(
"num entries mismatch, possibly corrupted input sketch",
));
}
} else {
- let max_matches =
self.table.num_retained().min(sketch.num_retained());
+ let max_matches = self.table.num_retained().min(num_retained);
let mut matched_entries = Vec::with_capacity(max_matches);
let mut count = 0;
- for entry in sketch.iter() {
+ for entry in sketch.entries() {
let hash = entry.hash();
if hash < self.table.theta() {
if let Some(existing) = self.table.entry(hash) {
@@ -172,17 +180,17 @@ where
self.policy.merge(&mut merged, entry);
matched_entries.push(merged);
}
- } else if sketch.is_ordered() {
+ } else if ordered {
break; // early stop for ordered sketches
}
count += 1;
}
// Safety check.
- if count > sketch.num_retained() {
+ if count > num_retained {
return Err(Error::invalid_argument(
"more keys than expected, possibly corrupted input sketch",
));
- } else if !sketch.is_ordered() && count < sketch.num_retained() {
+ } else if !ordered && count < num_retained {
return Err(Error::invalid_argument(
"fewer keys than expected, possibly corrupted input
sketch",
));
@@ -242,7 +250,7 @@ where
{
let mut entries: Vec<E> = self.table.iter_entries().cloned().collect();
if ordered {
- entries.sort_unstable_by_key(RetainedEntry::hash);
+ entries.sort_unstable_by_key(SketchEntry::hash);
}
CompactSketchParts {
entries,
@@ -253,152 +261,3 @@ where
}
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::hash::DEFAULT_UPDATE_SEED;
- use crate::hash::compute_seed_hash;
- use crate::thetacommon::ThetaKeySketchView;
-
- #[derive(Clone, Debug, Eq, PartialEq)]
- struct TestEntry {
- hash: u64,
- summary: u64,
- }
-
- impl RetainedEntry for TestEntry {
- fn hash(&self) -> u64 {
- self.hash
- }
- }
-
- struct TestSketch {
- entries: Vec<TestEntry>,
- }
-
- impl TestSketch {
- fn of_hashes(hashes: &[u64]) -> Self {
- Self {
- entries: hashes
- .iter()
- .map(|&hash| TestEntry { hash, summary: 1 })
- .collect(),
- }
- }
- }
-
- impl ThetaKeySketchView for TestSketch {
- fn seed_hash(&self) -> u16 {
- compute_seed_hash(DEFAULT_UPDATE_SEED)
- }
-
- fn theta64(&self) -> u64 {
- MAX_THETA
- }
-
- fn is_empty(&self) -> bool {
- self.entries.is_empty()
- }
-
- fn is_ordered(&self) -> bool {
- false
- }
-
- fn iter_hashes(&self) -> impl Iterator<Item = u64> + '_ {
- self.entries.iter().map(RetainedEntry::hash)
- }
-
- fn num_retained(&self) -> usize {
- self.entries.len()
- }
- }
-
- impl ThetaFamilySketchView for TestSketch {
- type Entry = TestEntry;
-
- fn iter(&self) -> impl Iterator<Item = TestEntry> + '_ {
- self.entries.iter().cloned()
- }
- }
-
- struct SumPolicy;
-
- impl IntersectionMergePolicy<TestEntry> for SumPolicy {
- fn merge(&self, existing: &mut TestEntry, incoming: TestEntry) {
- existing.summary += incoming.summary;
- }
- }
-
- #[test]
- fn first_update_copies_entries() {
- let mut intersection = IntersectionState::new(DEFAULT_UPDATE_SEED,
SumPolicy);
- assert!(!intersection.has_result());
-
- intersection
- .update(&TestSketch::of_hashes(&[1, 2, 3]))
- .unwrap();
-
- assert!(intersection.has_result());
- let parts = intersection.result(true);
- assert_eq!(
- parts.entries,
- vec![
- TestEntry {
- hash: 1,
- summary: 1
- },
- TestEntry {
- hash: 2,
- summary: 1
- },
- TestEntry {
- hash: 3,
- summary: 1
- },
- ]
- );
- }
-
- #[test]
- fn second_update_keeps_matches_and_merges_with_policy() {
- let mut intersection = IntersectionState::new(DEFAULT_UPDATE_SEED,
SumPolicy);
- intersection
- .update(&TestSketch::of_hashes(&[1, 2, 3]))
- .unwrap();
- intersection
- .update(&TestSketch::of_hashes(&[2, 3, 4]))
- .unwrap();
-
- let parts = intersection.result(true);
- assert_eq!(
- parts.entries,
- vec![
- TestEntry {
- hash: 2,
- summary: 2
- },
- TestEntry {
- hash: 3,
- summary: 2
- },
- ]
- );
- }
-
- #[test]
- fn disjoint_second_update_empties_intersection() {
- let mut intersection = IntersectionState::new(DEFAULT_UPDATE_SEED,
SumPolicy);
- intersection
- .update(&TestSketch::of_hashes(&[1, 2, 3]))
- .unwrap();
- intersection
- .update(&TestSketch::of_hashes(&[4, 5]))
- .unwrap();
-
- let parts = intersection.result(true);
- assert!(parts.entries.is_empty());
- assert!(parts.empty);
- assert_eq!(parts.theta, MAX_THETA);
- }
-}
diff --git a/datasketches/src/thetafamily/common/jaccard_similarity.rs
b/datasketches/src/thetafamily/common/jaccard_similarity.rs
index d1164dc..94a3d38 100644
--- a/datasketches/src/thetafamily/common/jaccard_similarity.rs
+++ b/datasketches/src/thetafamily/common/jaccard_similarity.rs
@@ -20,9 +20,10 @@ use crate::error::Error;
use crate::error::ErrorKind;
use crate::hash::check_seed_hash;
use crate::hash::compute_seed_hash;
-use crate::thetacommon::RetainedEntry;
-use crate::thetacommon::ThetaFamilySketchView;
-use crate::thetacommon::ThetaKeySketchView;
+use crate::thetacommon::EntrySketch;
+use crate::thetacommon::KeySketch;
+use crate::thetacommon::SketchEntry;
+use crate::thetacommon::SketchScalars;
use crate::thetacommon::binomial_bounds;
use crate::thetacommon::constants::MAX_LG_K;
use crate::thetacommon::constants::MAX_THETA;
@@ -115,220 +116,176 @@ struct KeyEntry {
hash: u64,
}
-impl RetainedEntry for KeyEntry {
+impl SketchEntry for KeyEntry {
fn hash(&self) -> u64 {
self.hash
}
}
-struct KeySketchView<'a, S> {
- sketch: &'a S,
-}
-
-impl<'a, S> KeySketchView<'a, S> {
- fn new(sketch: &'a S) -> Self {
- Self { sketch }
- }
-}
-
-impl<S: ThetaKeySketchView> ThetaKeySketchView for KeySketchView<'_, S> {
- fn seed_hash(&self) -> u16 {
- self.sketch.seed_hash()
- }
-
- fn theta64(&self) -> u64 {
- self.sketch.theta64()
- }
-
- fn is_empty(&self) -> bool {
- self.sketch.is_empty()
- }
-
- fn is_ordered(&self) -> bool {
- self.sketch.is_ordered()
- }
-
- fn iter_hashes(&self) -> impl Iterator<Item = u64> + '_ {
- self.sketch.iter_hashes()
- }
-
- fn num_retained(&self) -> usize {
- self.sketch.num_retained()
- }
-}
-
-impl<S: ThetaKeySketchView> ThetaFamilySketchView for KeySketchView<'_, S> {
- type Entry = KeyEntry;
-
- fn iter(&self) -> impl Iterator<Item = KeyEntry> + '_ {
- self.sketch.iter_hashes().map(|hash| KeyEntry { hash })
- }
-}
-
#[derive(Clone, Copy, Debug)]
struct NoopMergePolicy;
-impl<E: RetainedEntry> UnionMergePolicy<E> for NoopMergePolicy {
+impl<E: SketchEntry> UnionMergePolicy<E> for NoopMergePolicy {
fn merge(&self, _existing: &mut E, _incoming: E) {}
}
-impl<E: RetainedEntry> IntersectionMergePolicy<E> for NoopMergePolicy {
+impl<E: SketchEntry> IntersectionMergePolicy<E> for NoopMergePolicy {
fn merge(&self, _existing: &mut E, _incoming: E) {}
}
-struct CompactKeySketchView {
- entries: Vec<KeyEntry>,
- theta: u64,
- seed_hash: u16,
- ordered: bool,
- empty: bool,
-}
-
-impl ThetaKeySketchView for CompactKeySketchView {
- fn seed_hash(&self) -> u16 {
- self.seed_hash
- }
-
- fn theta64(&self) -> u64 {
- self.theta
- }
-
- fn is_empty(&self) -> bool {
- self.empty
- }
-
- fn is_ordered(&self) -> bool {
- self.ordered
- }
+#[derive(Clone, Copy, Debug)]
+struct KeyEntries<S>(S);
- fn iter_hashes(&self) -> impl Iterator<Item = u64> + '_ {
- self.entries.iter().map(RetainedEntry::hash)
+impl<S> KeySketch for KeyEntries<S>
+where
+ S: KeySketch,
+{
+ fn scalars(self) -> SketchScalars {
+ self.0.scalars()
}
- fn num_retained(&self) -> usize {
- self.entries.len()
+ fn hashes(self) -> impl Iterator<Item = u64> {
+ self.0.hashes()
}
}
-impl ThetaFamilySketchView for CompactKeySketchView {
+impl<S> EntrySketch for KeyEntries<S>
+where
+ S: KeySketch,
+{
type Entry = KeyEntry;
- fn iter(&self) -> impl Iterator<Item = KeyEntry> + '_ {
- self.entries.iter().copied()
+ fn entries(self) -> impl Iterator<Item = Self::Entry> {
+ self.0.hashes().map(|hash| KeyEntry { hash })
}
}
-/// Configured Jaccard operator shared by Theta and Tuple public wrappers.
-#[derive(Clone, Copy, Debug)]
-pub(crate) struct JaccardSimilarityOperator {
- seed: u64,
-}
-
-impl JaccardSimilarityOperator {
- pub(crate) fn new(seed: u64) -> Self {
- Self { seed }
+pub fn compute<A, B>(seed: u64, sketch_a: A, sketch_b: B) ->
Result<JaccardSimilarity, Error>
+where
+ A: KeySketch,
+ B: KeySketch,
+{
+ let SketchScalars {
+ theta: a_theta,
+ empty: a_empty,
+ num_retained: a_num_retained,
+ ..
+ } = sketch_a.scalars();
+ let SketchScalars {
+ theta: b_theta,
+ empty: b_empty,
+ num_retained: b_num_retained,
+ ..
+ } = sketch_b.scalars();
+ if a_empty && b_empty {
+ return Ok(JaccardSimilarity::exact(1.0));
+ }
+ if a_empty || b_empty {
+ return Ok(JaccardSimilarity::exact(0.0));
}
- pub(crate) fn compute<A, B>(
- &self,
- sketch_a: &A,
- sketch_b: &B,
- ) -> Result<JaccardSimilarity, Error>
- where
- A: ThetaKeySketchView,
- B: ThetaKeySketchView,
- {
- if sketch_a.is_empty() && sketch_b.is_empty() {
- return Ok(JaccardSimilarity::exact(1.0));
- }
- if sketch_a.is_empty() || sketch_b.is_empty() {
- return Ok(JaccardSimilarity::exact(0.0));
- }
-
- let union = self.compute_union(sketch_a, sketch_b)?;
- if !union.entries.is_empty() && identical_sets(sketch_a, sketch_b,
&union) {
- return Ok(JaccardSimilarity::exact(1.0));
- }
-
- let sketch_a = KeySketchView::new(sketch_a);
- let sketch_b = KeySketchView::new(sketch_b);
- let union = CompactKeySketchView {
- entries: union.entries,
- theta: union.theta,
- seed_hash: union.seed_hash,
- ordered: union.ordered,
- empty: union.empty,
- };
- let mut intersection = IntersectionState::new(self.seed,
NoopMergePolicy);
- intersection.update(&sketch_a)?;
- intersection.update(&sketch_b)?;
- intersection.update(&union)?;
- let intersection = intersection.result(false);
-
- JaccardSimilarity::ratio_bounds(
- union.num_retained() as u64,
- intersection.entries.len() as u64,
- union.theta64(),
- )
+ let sketch_a_state = (a_num_retained, a_theta);
+ let sketch_b_state = (b_num_retained, b_theta);
+ let union = compute_union(seed, sketch_a, sketch_b)?;
+ if !union.entries.is_empty() && identical_sets(sketch_a_state,
sketch_b_state, &union) {
+ return Ok(JaccardSimilarity::exact(1.0));
}
- pub(crate) fn exactly_equal<A, B>(&self, sketch_a: &A, sketch_b: &B) ->
Result<bool, Error>
- where
- A: ThetaKeySketchView,
- B: ThetaKeySketchView,
- {
- if sketch_a.is_empty() && sketch_b.is_empty() {
- return Ok(true);
- }
- if sketch_a.is_empty() || sketch_b.is_empty() {
- return Ok(false);
- }
+ let mut intersection = IntersectionState::new(seed, NoopMergePolicy);
+ intersection.update(KeyEntries(sketch_a))?;
+ intersection.update(KeyEntries(sketch_b))?;
+ let intersection = intersection.result(false);
+ let intersection_count = intersection
+ .entries
+ .iter()
+ .filter(|entry| entry.hash < union.theta)
+ .count();
+
+ JaccardSimilarity::ratio_bounds(
+ union.entries.len() as u64,
+ intersection_count as u64,
+ union.theta,
+ )
+}
- let union = self.compute_union(sketch_a, sketch_b)?;
- Ok(identical_sets(sketch_a, sketch_b, &union))
+pub fn exactly_equal<A, B>(seed: u64, sketch_a: A, sketch_b: B) ->
Result<bool, Error>
+where
+ A: KeySketch,
+ B: KeySketch,
+{
+ let SketchScalars {
+ theta: a_theta,
+ empty: a_empty,
+ num_retained: a_num_retained,
+ ..
+ } = sketch_a.scalars();
+ let SketchScalars {
+ theta: b_theta,
+ empty: b_empty,
+ num_retained: b_num_retained,
+ ..
+ } = sketch_b.scalars();
+ if a_empty && b_empty {
+ return Ok(true);
+ }
+ if a_empty || b_empty {
+ return Ok(false);
}
- fn compute_union<A, B>(
- &self,
- sketch_a: &A,
- sketch_b: &B,
- ) -> Result<CompactSketchParts<KeyEntry>, Error>
- where
- A: ThetaKeySketchView,
- B: ThetaKeySketchView,
- {
- let seed_hash = compute_seed_hash(self.seed);
- check_seed_hash(seed_hash, sketch_a.seed_hash(), "A",
ErrorKind::InvalidData)?;
- check_seed_hash(seed_hash, sketch_b.seed_hash(), "B",
ErrorKind::InvalidData)?;
+ let sketch_a_state = (a_num_retained, a_theta);
+ let sketch_b_state = (b_num_retained, b_theta);
+ let union = compute_union(seed, sketch_a, sketch_b)?;
+ Ok(identical_sets(sketch_a_state, sketch_b_state, &union))
+}
- let sketch_a = KeySketchView::new(sketch_a);
- let sketch_b = KeySketchView::new(sketch_b);
- let mut union = UnionState::new(
- union_lg_k(sketch_a.num_retained(), sketch_b.num_retained()),
- ResizeFactor::X8,
- 1.0,
- self.seed,
- NoopMergePolicy,
- );
- union.update(&sketch_a)?;
- union.update(&sketch_b)?;
- Ok(union.to_compact_parts(false))
- }
+fn compute_union<A, B>(
+ seed: u64,
+ sketch_a: A,
+ sketch_b: B,
+) -> Result<CompactSketchParts<KeyEntry>, Error>
+where
+ A: KeySketch,
+ B: KeySketch,
+{
+ let SketchScalars {
+ seed_hash: a_seed_hash,
+ num_retained: a_num_retained,
+ ..
+ } = sketch_a.scalars();
+ let SketchScalars {
+ seed_hash: b_seed_hash,
+ num_retained: b_num_retained,
+ ..
+ } = sketch_b.scalars();
+ let seed_hash = compute_seed_hash(seed);
+ check_seed_hash(seed_hash, a_seed_hash, "A", ErrorKind::InvalidData)?;
+ check_seed_hash(seed_hash, b_seed_hash, "B", ErrorKind::InvalidData)?;
+
+ let mut union = UnionState::new(
+ union_lg_k(a_num_retained, b_num_retained),
+ ResizeFactor::X8,
+ 1.0,
+ seed,
+ NoopMergePolicy,
+ );
+ union.update(KeyEntries(sketch_a))?;
+ union.update(KeyEntries(sketch_b))?;
+ Ok(union.to_compact_parts(false))
}
/// Returns whether both sketches have the same retained keys and theta.
///
/// When the union retains no additional keys and preserves both input theta
values, each input
/// contains exactly the same retained key set represented by the union.
-fn identical_sets<A, B>(sketch_a: &A, sketch_b: &B, union:
&CompactSketchParts<KeyEntry>) -> bool
-where
- A: ThetaKeySketchView,
- B: ThetaKeySketchView,
-{
- union.entries.len() == sketch_a.num_retained()
- && union.entries.len() == sketch_b.num_retained()
- && union.theta == sketch_a.theta64()
- && union.theta == sketch_b.theta64()
+fn identical_sets(
+ sketch_a: (usize, u64),
+ sketch_b: (usize, u64),
+ union: &CompactSketchParts<KeyEntry>,
+) -> bool {
+ union.entries.len() == sketch_a.0
+ && union.entries.len() == sketch_b.0
+ && union.theta == sketch_a.1
+ && union.theta == sketch_b.1
}
fn sampling_adjuster(sampling_probability: f64) -> f64 {
diff --git a/datasketches/src/thetafamily/common/mod.rs
b/datasketches/src/thetafamily/common/mod.rs
index 199e5cc..59f5dae 100644
--- a/datasketches/src/thetafamily/common/mod.rs
+++ b/datasketches/src/thetafamily/common/mod.rs
@@ -17,54 +17,39 @@
//! Data structures and functions that may be used across all the Theta sketch
family.
-pub(crate) mod a_not_b;
-pub(crate) mod binomial_bounds;
-pub(crate) mod constants;
-pub(crate) mod hash_table;
-pub(crate) mod intersection;
-pub(crate) mod jaccard_similarity;
-pub(crate) mod union;
+pub(super) mod a_not_b;
+pub(super) mod binomial_bounds;
+pub(super) mod constants;
+pub(super) mod hash_table;
+pub(super) mod intersection;
+pub(super) mod jaccard_similarity;
+pub(super) mod union;
pub use self::jaccard_similarity::JaccardSimilarity;
-/// An entry retained by a Theta sketch family hash table.
-pub trait RetainedEntry {
- /// Return the hash used as this entry's key.
+/// Minimal entry behavior required by the shared hash table and set
operations.
+pub(super) trait SketchEntry {
fn hash(&self) -> u64;
}
-/// Read-only hash-key view shared by Theta-family sketches.
-///
-/// Key-only operations use this interface without requiring access to, or
cloning, payloads such
-/// as Tuple summaries.
-pub trait ThetaKeySketchView {
- /// Return the 16-bit seed hash.
- fn seed_hash(&self) -> u16;
+pub(super) trait KeySketch: Copy {
+ fn scalars(self) -> SketchScalars;
- /// Return theta as a `u64` threshold.
- fn theta64(&self) -> u64;
-
- /// Return whether this sketch has not received any updates.
- fn is_empty(&self) -> bool;
-
- /// Return whether retained entries are ordered by ascending hash.
- fn is_ordered(&self) -> bool;
+ fn hashes(self) -> impl Iterator<Item = u64>;
+}
- /// Return an iterator over retained hash keys.
- fn iter_hashes(&self) -> impl Iterator<Item = u64> + '_;
+pub(super) trait EntrySketch: KeySketch {
+ type Entry: SketchEntry;
- /// Return the number of retained entries.
- fn num_retained(&self) -> usize;
+ fn entries(self) -> impl Iterator<Item = Self::Entry>;
}
-/// Read-only retained-entry view accepted by Theta-family set operations.
-///
-/// This trait extends [`ThetaKeySketchView`] with complete retained entries,
so operations such as
-/// union and intersection can preserve and combine Tuple summaries.
-pub trait ThetaFamilySketchView: ThetaKeySketchView {
- /// The retained entry representation yielded by this view.
- type Entry: RetainedEntry;
-
- /// Return an iterator over retained entries.
- fn iter(&self) -> impl Iterator<Item = Self::Entry> + '_;
+/// Scalar sketch values inspected by Theta-family set operations.
+#[derive(Clone, Copy, Debug)]
+pub(super) struct SketchScalars {
+ pub seed_hash: u16,
+ pub theta: u64,
+ pub empty: bool,
+ pub ordered: bool,
+ pub num_retained: usize,
}
diff --git a/datasketches/src/thetafamily/common/union.rs
b/datasketches/src/thetafamily/common/union.rs
index 5b4aebd..5e5bbca 100644
--- a/datasketches/src/thetafamily/common/union.rs
+++ b/datasketches/src/thetafamily/common/union.rs
@@ -19,8 +19,9 @@ use crate::common::ResizeFactor;
use crate::error::Error;
use crate::error::ErrorKind;
use crate::hash::check_seed_hash;
-use crate::thetacommon::RetainedEntry;
-use crate::thetacommon::ThetaFamilySketchView;
+use crate::thetacommon::EntrySketch;
+use crate::thetacommon::SketchEntry;
+use crate::thetacommon::SketchScalars;
use crate::thetacommon::constants::MAX_THETA;
use crate::thetacommon::hash_table::CompactSketchParts;
use crate::thetacommon::hash_table::SketchHashTable;
@@ -43,7 +44,7 @@ pub struct UnionState<E, P> {
impl<E, P> UnionState<E, P>
where
- E: RetainedEntry,
+ E: SketchEntry,
{
pub fn new(
lg_k: u8,
@@ -61,26 +62,33 @@ where
}
/// Incorporate a sketch into the union.
- pub fn update<S>(&mut self, sketch: &S) -> Result<(), Error>
+ pub fn update<S>(&mut self, sketch: S) -> Result<(), Error>
where
- S: ThetaFamilySketchView<Entry = E>,
+ S: EntrySketch<Entry = E>,
P: UnionMergePolicy<E>,
{
- if sketch.is_empty() {
+ let SketchScalars {
+ seed_hash,
+ theta,
+ empty,
+ ordered,
+ ..
+ } = sketch.scalars();
+ if empty {
return Ok(());
}
check_seed_hash(
self.table.seed_hash(),
- sketch.seed_hash(),
+ seed_hash,
"union update",
ErrorKind::InvalidArgument,
)?;
self.table.set_empty(false);
- self.union_theta = self.union_theta.min(sketch.theta64());
+ self.union_theta = self.union_theta.min(theta);
- for entry in sketch.iter() {
+ for entry in sketch.entries() {
let hash = entry.hash();
if hash < self.union_theta && hash < self.table.theta() {
self.table.upsert_entry(hash, |existing| match existing {
@@ -90,7 +98,7 @@ where
}
None => Some(entry),
});
- } else if sketch.is_ordered() {
+ } else if ordered {
break;
}
}
@@ -136,7 +144,7 @@ where
let ordered = ordered || (entries.len() == 1 && theta == MAX_THETA);
if ordered {
- entries.sort_unstable_by_key(RetainedEntry::hash);
+ entries.sort_unstable_by_key(SketchEntry::hash);
}
CompactSketchParts {
@@ -159,99 +167,3 @@ where
self.table.estimated_size()
}
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::hash::DEFAULT_UPDATE_SEED;
- use crate::hash::compute_seed_hash;
- use crate::thetacommon::ThetaKeySketchView;
-
- #[derive(Clone, Debug, Eq, PartialEq)]
- struct TestEntry {
- hash: u64,
- summary: u64,
- }
-
- impl RetainedEntry for TestEntry {
- fn hash(&self) -> u64 {
- self.hash
- }
- }
-
- struct TestSketch {
- entries: Vec<TestEntry>,
- }
-
- impl ThetaKeySketchView for TestSketch {
- fn seed_hash(&self) -> u16 {
- compute_seed_hash(DEFAULT_UPDATE_SEED)
- }
-
- fn theta64(&self) -> u64 {
- MAX_THETA
- }
-
- fn is_empty(&self) -> bool {
- false
- }
-
- fn is_ordered(&self) -> bool {
- false
- }
-
- fn iter_hashes(&self) -> impl Iterator<Item = u64> + '_ {
- self.entries.iter().map(RetainedEntry::hash)
- }
-
- fn num_retained(&self) -> usize {
- self.entries.len()
- }
- }
-
- impl ThetaFamilySketchView for TestSketch {
- type Entry = TestEntry;
-
- fn iter(&self) -> impl Iterator<Item = TestEntry> + '_ {
- self.entries.iter().cloned()
- }
- }
-
- struct SumPolicy;
-
- impl UnionMergePolicy<TestEntry> for SumPolicy {
- fn merge(&self, existing: &mut TestEntry, incoming: TestEntry) {
- existing.summary += incoming.summary;
- }
- }
-
- #[test]
- fn merges_equal_hash_entries_with_policy() {
- let mut union = UnionState::new(5, ResizeFactor::X1, 1.0,
DEFAULT_UPDATE_SEED, SumPolicy);
- union
- .update(&TestSketch {
- entries: vec![TestEntry {
- hash: 1,
- summary: 2,
- }],
- })
- .unwrap();
- union
- .update(&TestSketch {
- entries: vec![TestEntry {
- hash: 1,
- summary: 3,
- }],
- })
- .unwrap();
-
- let parts = union.to_compact_parts(true);
- assert_eq!(
- parts.entries,
- vec![TestEntry {
- hash: 1,
- summary: 5,
- }]
- );
- }
-}
diff --git a/datasketches/src/thetafamily/theta/a_not_b.rs
b/datasketches/src/thetafamily/theta/a_not_b.rs
index 7def6e9..29ea2f8 100644
--- a/datasketches/src/thetafamily/theta/a_not_b.rs
+++ b/datasketches/src/thetafamily/theta/a_not_b.rs
@@ -23,9 +23,10 @@
use crate::error::Error;
use crate::hash::DEFAULT_UPDATE_SEED;
+use crate::hash::compute_seed_hash;
use crate::theta::CompactThetaSketch;
use crate::theta::ThetaSketchView;
-use crate::thetacommon::a_not_b::ANotBOperator;
+use crate::thetacommon::a_not_b;
/// Set difference operator (`A and not B`) for Theta sketches.
///
@@ -51,7 +52,7 @@ use crate::thetacommon::a_not_b::ANotBOperator;
/// ```
#[derive(Debug, Clone, Copy)]
pub struct ThetaANotB {
- op: ANotBOperator,
+ seed_hash: u16,
}
impl Default for ThetaANotB {
@@ -64,7 +65,7 @@ impl ThetaANotB {
/// Creates a new set difference operator for the given `seed`.
pub fn with_seed(seed: u64) -> Self {
Self {
- op: ANotBOperator::new(seed),
+ seed_hash: compute_seed_hash(seed),
}
}
@@ -77,12 +78,15 @@ impl ThetaANotB {
///
/// Returns an error if either non-trivial input has a seed hash that
differs from this
/// operator's seed.
- pub fn compute<A, B>(&self, a: &A, b: &B, ordered: bool) ->
Result<CompactThetaSketch, Error>
- where
- A: ThetaSketchView,
- B: ThetaSketchView,
- {
- let parts = self.op.compute(a, b, ordered)?;
+ pub fn compute<'a, 'b>(
+ &self,
+ a: impl Into<ThetaSketchView<'a>>,
+ b: impl Into<ThetaSketchView<'b>>,
+ ordered: bool,
+ ) -> Result<CompactThetaSketch, Error> {
+ let a = a.into();
+ let b = b.into();
+ let parts = a_not_b::compute(self.seed_hash, a, b, ordered)?;
Ok(CompactThetaSketch::from_parts(
parts
.entries
diff --git a/datasketches/src/thetafamily/theta/hash_table.rs
b/datasketches/src/thetafamily/theta/hash_table.rs
index b10ae57..d7dd23b 100644
--- a/datasketches/src/thetafamily/theta/hash_table.rs
+++ b/datasketches/src/thetafamily/theta/hash_table.rs
@@ -18,7 +18,7 @@
use std::hash::Hash;
use std::num::NonZeroU64;
-use crate::thetacommon::RetainedEntry;
+use crate::thetacommon::SketchEntry;
use crate::thetacommon::hash_table::SketchHashTable;
/// Specific hash table for theta sketch
@@ -37,7 +37,7 @@ pub struct ThetaEntry {
}
impl ThetaEntry {
- pub(crate) fn new(hash: u64) -> Self {
+ pub(super) fn new(hash: u64) -> Self {
let hash = NonZeroU64::new(hash).expect("hash must be non-zero");
Self { hash }
}
@@ -48,7 +48,7 @@ impl ThetaEntry {
}
}
-impl RetainedEntry for ThetaEntry {
+impl SketchEntry for ThetaEntry {
fn hash(&self) -> u64 {
self.hash.get()
}
diff --git a/datasketches/src/thetafamily/theta/intersection.rs
b/datasketches/src/thetafamily/theta/intersection.rs
index 9afd6ba..e3bfdee 100644
--- a/datasketches/src/thetafamily/theta/intersection.rs
+++ b/datasketches/src/thetafamily/theta/intersection.rs
@@ -58,7 +58,8 @@ impl ThetaIntersection {
/// The intersection can be viewed as starting from the "universe" set,
/// and every update can reduce the current set to leave the overlapping
/// subset only.
- pub fn update<S: ThetaSketchView>(&mut self, sketch: &S) -> Result<(),
Error> {
+ pub fn update<'a>(&mut self, sketch: impl Into<ThetaSketchView<'a>>) ->
Result<(), Error> {
+ let sketch = sketch.into();
self.state.update(sketch)
}
diff --git a/datasketches/src/thetafamily/theta/jaccard_similarity.rs
b/datasketches/src/thetafamily/theta/jaccard_similarity.rs
index b32a922..0a88a9e 100644
--- a/datasketches/src/thetafamily/theta/jaccard_similarity.rs
+++ b/datasketches/src/thetafamily/theta/jaccard_similarity.rs
@@ -20,8 +20,8 @@
use crate::error::Error;
use crate::hash::DEFAULT_UPDATE_SEED;
use crate::theta::ThetaSketchView;
+use crate::thetacommon::jaccard_similarity;
use crate::thetacommon::jaccard_similarity::JaccardSimilarity;
-use crate::thetacommon::jaccard_similarity::JaccardSimilarityOperator;
/// Jaccard similarity operator for Theta sketches.
///
@@ -44,7 +44,7 @@ use
crate::thetacommon::jaccard_similarity::JaccardSimilarityOperator;
/// ```
#[derive(Clone, Copy, Debug)]
pub struct ThetaJaccardSimilarity {
- op: JaccardSimilarityOperator,
+ seed: u64,
}
impl Default for ThetaJaccardSimilarity {
@@ -56,9 +56,7 @@ impl Default for ThetaJaccardSimilarity {
impl ThetaJaccardSimilarity {
/// Creates a Jaccard similarity operator for the given `seed`.
pub fn with_seed(seed: u64) -> Self {
- Self {
- op: JaccardSimilarityOperator::new(seed),
- }
+ Self { seed }
}
/// Computes the Jaccard similarity index for `sketch_a` and `sketch_b`.
@@ -67,12 +65,12 @@ impl ThetaJaccardSimilarity {
///
/// Returns an error if either non-empty sketch was built with a seed
different from this
/// operator's configured seed.
- pub fn compute<A: ThetaSketchView, B: ThetaSketchView>(
+ pub fn compute<'a, 'b>(
&self,
- sketch_a: &A,
- sketch_b: &B,
+ sketch_a: impl Into<ThetaSketchView<'a>>,
+ sketch_b: impl Into<ThetaSketchView<'b>>,
) -> Result<JaccardSimilarity, Error> {
- self.op.compute(sketch_a, sketch_b)
+ jaccard_similarity::compute(self.seed, sketch_a.into(),
sketch_b.into())
}
/// Returns whether the two sketches are exactly equal.
@@ -85,11 +83,11 @@ impl ThetaJaccardSimilarity {
///
/// Returns an error if both sketches are non-empty and either was built
with a seed different
/// from this operator's configured seed.
- pub fn exactly_equal<A: ThetaSketchView, B: ThetaSketchView>(
+ pub fn exactly_equal<'a, 'b>(
&self,
- sketch_a: &A,
- sketch_b: &B,
+ sketch_a: impl Into<ThetaSketchView<'a>>,
+ sketch_b: impl Into<ThetaSketchView<'b>>,
) -> Result<bool, Error> {
- self.op.exactly_equal(sketch_a, sketch_b)
+ jaccard_similarity::exactly_equal(self.seed, sketch_a.into(),
sketch_b.into())
}
}
diff --git a/datasketches/src/thetafamily/theta/sketch.rs
b/datasketches/src/thetafamily/theta/sketch.rs
index 6a9662a..833ca7c 100644
--- a/datasketches/src/thetafamily/theta/sketch.rs
+++ b/datasketches/src/thetafamily/theta/sketch.rs
@@ -21,6 +21,7 @@
//! for cardinality estimation.
use std::hash::Hash;
+use std::slice;
use crate::codec::SketchBytes;
use crate::codec::SketchSlice;
@@ -45,8 +46,9 @@ use crate::theta::serialization;
use crate::theta::serialization::V2_PREAMBLE_EMPTY;
use crate::theta::serialization::V2_PREAMBLE_ESTIMATE;
use crate::theta::serialization::V2_PREAMBLE_PRECISE;
-use crate::thetacommon::ThetaFamilySketchView;
-use crate::thetacommon::ThetaKeySketchView;
+use crate::thetacommon::EntrySketch;
+use crate::thetacommon::KeySketch;
+use crate::thetacommon::SketchScalars;
use crate::thetacommon::binomial_bounds;
use crate::thetacommon::constants::DEFAULT_LG_K;
use crate::thetacommon::constants::FLAGS_IS_COMPACT;
@@ -56,46 +58,143 @@ use crate::thetacommon::constants::FLAGS_IS_READ_ONLY;
use crate::thetacommon::constants::MAX_LG_K;
use crate::thetacommon::constants::MAX_THETA;
use crate::thetacommon::constants::MIN_LG_K;
+use crate::thetacommon::hash_table::SketchHashTableIter;
/// Read-only view for Theta sketches.
///
-/// This trait provides a unified input abstraction for APIs that can accept
either
-/// mutable [`ThetaSketch`] or immutable [`CompactThetaSketch`].
-pub trait ThetaSketchView: ThetaFamilySketchView<Entry = ThetaEntry> {}
+/// The view borrows either a mutable [`ThetaSketch`] or immutable
[`CompactThetaSketch`] and is
+/// accepted by Theta set operations. Create one with [`ThetaSketch::as_view`],
+/// [`CompactThetaSketch::as_view`], or the corresponding `From` conversion.
+///
+/// # Examples
+///
+/// ```
+/// use datasketches::theta::ThetaSketchBuilder;
+///
+/// let mut sketch = ThetaSketchBuilder::default().build();
+/// sketch.update("apple");
+/// let view = sketch.as_view();
+/// assert_eq!(view.num_retained(), 1);
+/// ```
+#[derive(Clone, Copy, Debug)]
+pub struct ThetaSketchView<'a>(ThetaSketchViewState<'a>);
+
+#[derive(Clone, Copy, Debug)]
+enum ThetaSketchViewState<'a> {
+ Mutable(&'a ThetaSketch),
+ Compact(&'a CompactThetaSketch),
+}
+
+enum ThetaSketchIter<'a> {
+ Mutable(SketchHashTableIter<'a, ThetaEntry>),
+ Compact(slice::Iter<'a, u64>),
+}
+
+impl Iterator for ThetaSketchIter<'_> {
+ type Item = ThetaEntry;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ match self {
+ Self::Mutable(iter) => iter.next().copied(),
+ Self::Compact(iter) => iter.next().map(|&hash|
ThetaEntry::new(hash)),
+ }
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ match self {
+ Self::Mutable(iter) => iter.size_hint(),
+ Self::Compact(iter) => iter.size_hint(),
+ }
+ }
+}
+
+impl<'a> ThetaSketchView<'a> {
+ /// Returns the 16-bit seed hash.
+ pub fn seed_hash(&self) -> u16 {
+ match self.0 {
+ ThetaSketchViewState::Mutable(sketch) => sketch.seed_hash(),
+ ThetaSketchViewState::Compact(sketch) => sketch.seed_hash(),
+ }
+ }
-impl<T: ThetaFamilySketchView<Entry = ThetaEntry>> ThetaSketchView for T {}
+ /// Returns theta as a `u64` threshold.
+ pub fn theta64(&self) -> u64 {
+ match self.0 {
+ ThetaSketchViewState::Mutable(sketch) => sketch.theta64(),
+ ThetaSketchViewState::Compact(sketch) => sketch.theta64(),
+ }
+ }
-impl ThetaKeySketchView for ThetaSketch {
- fn seed_hash(&self) -> u16 {
- ThetaSketch::seed_hash(self)
+ /// Returns whether the viewed sketch has not received any updates.
+ pub fn is_empty(&self) -> bool {
+ match self.0 {
+ ThetaSketchViewState::Mutable(sketch) => sketch.is_empty(),
+ ThetaSketchViewState::Compact(sketch) => sketch.is_empty(),
+ }
}
- fn theta64(&self) -> u64 {
- ThetaSketch::theta64(self)
+ /// Returns whether retained entries are ordered by ascending hash.
+ pub fn is_ordered(&self) -> bool {
+ match self.0 {
+ ThetaSketchViewState::Mutable(_) => false,
+ ThetaSketchViewState::Compact(sketch) => sketch.is_ordered(),
+ }
}
- fn is_empty(&self) -> bool {
- ThetaSketch::is_empty(self)
+ /// Returns an iterator over retained entries.
+ pub fn iter(self) -> impl Iterator<Item = ThetaEntry> + 'a {
+ match self.0 {
+ ThetaSketchViewState::Mutable(sketch) => {
+ ThetaSketchIter::Mutable(sketch.table.iter_entries())
+ }
+ ThetaSketchViewState::Compact(sketch) => {
+ ThetaSketchIter::Compact(sketch.entries.iter())
+ }
+ }
}
- fn is_ordered(&self) -> bool {
- false
+ /// Returns the number of retained entries.
+ pub fn num_retained(&self) -> usize {
+ match self.0 {
+ ThetaSketchViewState::Mutable(sketch) => sketch.num_retained(),
+ ThetaSketchViewState::Compact(sketch) => sketch.num_retained(),
+ }
}
+}
- fn iter_hashes(&self) -> impl Iterator<Item = u64> + '_ {
- self.table.iter_entries().map(ThetaEntry::hash)
+impl KeySketch for ThetaSketchView<'_> {
+ fn scalars(self) -> SketchScalars {
+ SketchScalars {
+ seed_hash: self.seed_hash(),
+ theta: self.theta64(),
+ empty: self.is_empty(),
+ ordered: self.is_ordered(),
+ num_retained: self.num_retained(),
+ }
}
- fn num_retained(&self) -> usize {
- ThetaSketch::num_retained(self)
+ fn hashes(self) -> impl Iterator<Item = u64> {
+ self.iter().map(|entry| entry.hash())
}
}
-impl ThetaFamilySketchView for ThetaSketch {
+impl EntrySketch for ThetaSketchView<'_> {
type Entry = ThetaEntry;
- fn iter(&self) -> impl Iterator<Item = ThetaEntry> + '_ {
- self.table.iter_entries().copied()
+ fn entries(self) -> impl Iterator<Item = Self::Entry> {
+ self.iter()
+ }
+}
+
+impl<'a> From<&'a ThetaSketch> for ThetaSketchView<'a> {
+ fn from(sketch: &'a ThetaSketch) -> Self {
+ Self(ThetaSketchViewState::Mutable(sketch))
+ }
+}
+
+impl<'a> From<&'a CompactThetaSketch> for ThetaSketchView<'a> {
+ fn from(sketch: &'a CompactThetaSketch) -> Self {
+ Self(ThetaSketchViewState::Compact(sketch))
}
}
@@ -106,6 +205,11 @@ pub struct ThetaSketch {
}
impl ThetaSketch {
+ /// Returns a read-only view accepted by Theta set operations.
+ pub fn as_view(&self) -> ThetaSketchView<'_> {
+ self.into()
+ }
+
/// Update the sketch with a hashable value.
///
/// You may use [`hash::value`](crate::hash::value) wrappers when another
DataSketches
@@ -348,6 +452,11 @@ impl CompactThetaSketch {
}
}
+ /// Returns a read-only view accepted by Theta set operations.
+ pub fn as_view(&self) -> ThetaSketchView<'_> {
+ self.into()
+ }
+
/// Returns the cardinality estimate.
pub fn estimate(&self) -> f64 {
if self.is_empty() {
@@ -876,40 +985,6 @@ impl CompactThetaSketch {
}
}
-impl ThetaKeySketchView for CompactThetaSketch {
- fn seed_hash(&self) -> u16 {
- CompactThetaSketch::seed_hash(self)
- }
-
- fn theta64(&self) -> u64 {
- CompactThetaSketch::theta64(self)
- }
-
- fn is_empty(&self) -> bool {
- CompactThetaSketch::is_empty(self)
- }
-
- fn is_ordered(&self) -> bool {
- CompactThetaSketch::is_ordered(self)
- }
-
- fn iter_hashes(&self) -> impl Iterator<Item = u64> + '_ {
- self.entries.iter().copied()
- }
-
- fn num_retained(&self) -> usize {
- CompactThetaSketch::num_retained(self)
- }
-}
-
-impl ThetaFamilySketchView for CompactThetaSketch {
- type Entry = ThetaEntry;
-
- fn iter(&self) -> impl Iterator<Item = ThetaEntry> + '_ {
- self.entries.iter().copied().map(ThetaEntry::new)
- }
-}
-
/// Builder for ThetaSketch
#[derive(Debug)]
pub struct ThetaSketchBuilder {
diff --git a/datasketches/src/thetafamily/theta/union.rs
b/datasketches/src/thetafamily/theta/union.rs
index 3d58877..82341bc 100644
--- a/datasketches/src/thetafamily/theta/union.rs
+++ b/datasketches/src/thetafamily/theta/union.rs
@@ -42,7 +42,8 @@ impl UnionMergePolicy<ThetaEntry> for NoopUnionPolicy {
impl ThetaUnion {
/// Update this union with a given sketch.
- pub fn update<S: ThetaSketchView>(&mut self, sketch: &S) -> Result<(),
Error> {
+ pub fn update<'a>(&mut self, sketch: impl Into<ThetaSketchView<'a>>) ->
Result<(), Error> {
+ let sketch = sketch.into();
self.state.update(sketch)
}
diff --git a/datasketches/src/thetafamily/tuple/a_not_b.rs
b/datasketches/src/thetafamily/tuple/a_not_b.rs
index b79430f..f14ebf3 100644
--- a/datasketches/src/thetafamily/tuple/a_not_b.rs
+++ b/datasketches/src/thetafamily/tuple/a_not_b.rs
@@ -24,9 +24,9 @@
use crate::error::Error;
use crate::hash::DEFAULT_UPDATE_SEED;
-use crate::thetacommon::a_not_b::ANotBOperator;
+use crate::hash::compute_seed_hash;
+use crate::thetacommon::a_not_b;
use crate::tuple::sketch::CompactTupleSketch;
-use crate::tuple::sketch::TupleKeySketchView;
use crate::tuple::sketch::TupleSketchView;
/// Set difference operator (`A and not B`) for Tuple sketches.
@@ -56,7 +56,7 @@ use crate::tuple::sketch::TupleSketchView;
/// ```
#[derive(Debug, Clone, Copy)]
pub struct TupleANotB {
- op: ANotBOperator,
+ seed_hash: u16,
}
impl Default for TupleANotB {
@@ -69,7 +69,7 @@ impl TupleANotB {
/// Creates a new set difference operator for the given `seed`.
pub fn with_seed(seed: u64) -> Self {
Self {
- op: ANotBOperator::new(seed),
+ seed_hash: compute_seed_hash(seed),
}
}
@@ -83,17 +83,19 @@ impl TupleANotB {
///
/// Returns an error if either non-trivial input has a seed hash that
differs from this
/// operator's seed.
- pub fn compute<S, A, B>(
+ pub fn compute<'a, 'b, S, T>(
&self,
- a: &A,
- b: &B,
+ a: impl Into<TupleSketchView<'a, S>>,
+ b: impl Into<TupleSketchView<'b, T>>,
ordered: bool,
) -> Result<CompactTupleSketch<S>, Error>
where
- A: TupleSketchView<S>,
- B: TupleKeySketchView,
+ S: Clone + 'a,
+ T: 'b,
{
- let parts = self.op.compute(a, b, ordered)?;
+ let a = a.into();
+ let b = b.into();
+ let parts = a_not_b::compute(self.seed_hash, a, b, ordered)?;
Ok(CompactTupleSketch::from_parts(
parts.entries,
parts.theta,
diff --git a/datasketches/src/thetafamily/tuple/hash_table.rs
b/datasketches/src/thetafamily/tuple/hash_table.rs
index e64520f..00e0fec 100644
--- a/datasketches/src/thetafamily/tuple/hash_table.rs
+++ b/datasketches/src/thetafamily/tuple/hash_table.rs
@@ -18,7 +18,7 @@
use std::hash::Hash;
use std::num::NonZeroU64;
-use crate::thetacommon::RetainedEntry;
+use crate::thetacommon::SketchEntry;
use crate::thetacommon::hash_table::SketchHashTable;
use crate::thetacommon::intersection::IntersectionMergePolicy;
use crate::thetacommon::union::UnionMergePolicy;
@@ -63,7 +63,7 @@ impl<S> TupleEntry<S> {
/// update is merged into the existing summary rather than discarded.
pub(super) type TupleHashTable<S> = SketchHashTable<TupleEntry<S>>;
-impl<S> RetainedEntry for TupleEntry<S> {
+impl<S> SketchEntry for TupleEntry<S> {
fn hash(&self) -> u64 {
self.hash.get()
}
diff --git a/datasketches/src/thetafamily/tuple/intersection.rs
b/datasketches/src/thetafamily/tuple/intersection.rs
index 5dfaaf7..23e9fa7 100644
--- a/datasketches/src/thetafamily/tuple/intersection.rs
+++ b/datasketches/src/thetafamily/tuple/intersection.rs
@@ -117,11 +117,14 @@ where
///
/// Returns an error if `sketch` (when non-empty) has a different seed
hash, or if the input
/// appears corrupted (entry counts do not match what the sketch reports).
- pub fn update<V>(&mut self, sketch: &V) -> Result<(), Error>
+ pub fn update<'a>(
+ &mut self,
+ sketch: impl Into<TupleSketchView<'a, P::Summary>>,
+ ) -> Result<(), Error>
where
- V: TupleSketchView<P::Summary>,
- P::Summary: Clone,
+ P::Summary: Clone + 'a,
{
+ let sketch = sketch.into();
self.state.update(sketch)
}
diff --git a/datasketches/src/thetafamily/tuple/jaccard_similarity.rs
b/datasketches/src/thetafamily/tuple/jaccard_similarity.rs
index 1f47b3c..e4cd753 100644
--- a/datasketches/src/thetafamily/tuple/jaccard_similarity.rs
+++ b/datasketches/src/thetafamily/tuple/jaccard_similarity.rs
@@ -19,9 +19,9 @@
use crate::error::Error;
use crate::hash::DEFAULT_UPDATE_SEED;
+use crate::thetacommon::jaccard_similarity;
use crate::thetacommon::jaccard_similarity::JaccardSimilarity;
-use crate::thetacommon::jaccard_similarity::JaccardSimilarityOperator;
-use crate::tuple::TupleKeySketchView;
+use crate::tuple::TupleSketchView;
/// Jaccard similarity operator for Tuple sketches.
///
@@ -47,7 +47,7 @@ use crate::tuple::TupleKeySketchView;
/// ```
#[derive(Clone, Copy, Debug)]
pub struct TupleJaccardSimilarity {
- op: JaccardSimilarityOperator,
+ seed: u64,
}
impl Default for TupleJaccardSimilarity {
@@ -59,9 +59,7 @@ impl Default for TupleJaccardSimilarity {
impl TupleJaccardSimilarity {
/// Creates a Jaccard similarity operator for the given `seed`.
pub fn with_seed(seed: u64) -> Self {
- Self {
- op: JaccardSimilarityOperator::new(seed),
- }
+ Self { seed }
}
/// Computes the Jaccard similarity index for `sketch_a` and `sketch_b`.
@@ -72,12 +70,16 @@ impl TupleJaccardSimilarity {
///
/// Returns an error if either non-empty sketch was built with a seed
different from this
/// operator's configured seed.
- pub fn compute<A, B>(&self, sketch_a: &A, sketch_b: &B) ->
Result<JaccardSimilarity, Error>
+ pub fn compute<'a, 'b, S, T>(
+ &self,
+ sketch_a: impl Into<TupleSketchView<'a, S>>,
+ sketch_b: impl Into<TupleSketchView<'b, T>>,
+ ) -> Result<JaccardSimilarity, Error>
where
- A: TupleKeySketchView,
- B: TupleKeySketchView,
+ S: 'a,
+ T: 'b,
{
- self.op.compute(sketch_a, sketch_b)
+ jaccard_similarity::compute(self.seed, sketch_a.into(),
sketch_b.into())
}
/// Returns whether the two sketches are exactly equal.
@@ -91,11 +93,15 @@ impl TupleJaccardSimilarity {
///
/// Returns an error if both sketches are non-empty and either was built
with a seed different
/// from this operator's configured seed.
- pub fn exactly_equal<A, B>(&self, sketch_a: &A, sketch_b: &B) ->
Result<bool, Error>
+ pub fn exactly_equal<'a, 'b, S, T>(
+ &self,
+ sketch_a: impl Into<TupleSketchView<'a, S>>,
+ sketch_b: impl Into<TupleSketchView<'b, T>>,
+ ) -> Result<bool, Error>
where
- A: TupleKeySketchView,
- B: TupleKeySketchView,
+ S: 'a,
+ T: 'b,
{
- self.op.exactly_equal(sketch_a, sketch_b)
+ jaccard_similarity::exactly_equal(self.seed, sketch_a.into(),
sketch_b.into())
}
}
diff --git a/datasketches/src/thetafamily/tuple/mod.rs
b/datasketches/src/thetafamily/tuple/mod.rs
index a8dfcba..fa90d21 100644
--- a/datasketches/src/thetafamily/tuple/mod.rs
+++ b/datasketches/src/thetafamily/tuple/mod.rs
@@ -60,7 +60,6 @@ pub use self::policy::SummaryPolicy;
pub use self::policy::SummaryUpdatePolicy;
pub use self::serialization::TupleSummaryValue;
pub use self::sketch::CompactTupleSketch;
-pub use self::sketch::TupleKeySketchView;
pub use self::sketch::TupleSketch;
pub use self::sketch::TupleSketchBuilder;
pub use self::sketch::TupleSketchView;
diff --git a/datasketches/src/thetafamily/tuple/sketch.rs
b/datasketches/src/thetafamily/tuple/sketch.rs
index 21fa290..aafb0c3 100644
--- a/datasketches/src/thetafamily/tuple/sketch.rs
+++ b/datasketches/src/thetafamily/tuple/sketch.rs
@@ -23,6 +23,7 @@
//! implementations.
use std::hash::Hash;
+use std::slice;
use crate::codec::SketchBytes;
use crate::codec::SketchSlice;
@@ -36,8 +37,9 @@ use crate::error::ErrorKind;
use crate::hash::DEFAULT_UPDATE_SEED;
use crate::hash::check_seed_hash;
use crate::hash::compute_seed_hash;
-use crate::thetacommon::ThetaFamilySketchView;
-use crate::thetacommon::ThetaKeySketchView;
+use crate::thetacommon::EntrySketch;
+use crate::thetacommon::KeySketch;
+use crate::thetacommon::SketchScalars;
use crate::thetacommon::binomial_bounds;
use crate::thetacommon::constants::DEFAULT_LG_K;
use crate::thetacommon::constants::FLAGS_IS_COMPACT;
@@ -47,6 +49,7 @@ use crate::thetacommon::constants::FLAGS_IS_READ_ONLY;
use crate::thetacommon::constants::MAX_LG_K;
use crate::thetacommon::constants::MAX_THETA;
use crate::thetacommon::constants::MIN_LG_K;
+use crate::thetacommon::hash_table::SketchHashTableIter;
use crate::tuple::hash_table::TupleEntry;
use crate::tuple::hash_table::TupleHashTable;
use crate::tuple::policy::SummaryPolicy;
@@ -57,28 +60,163 @@ use crate::tuple::serialization::SKETCH_TYPE;
use crate::tuple::serialization::SKETCH_TYPE_LEGACY;
use crate::tuple::serialization::TupleSummaryValue;
-/// Read-only hash-key view for Tuple sketches.
+/// Read-only view of a mutable or compact Tuple sketch.
///
-/// This interface does not inspect summary values and therefore does not
require them to implement
-/// [`Clone`].
-pub trait TupleKeySketchView: ThetaKeySketchView {}
-
-/// Read-only retained-entry view for Tuple sketches.
+/// The view borrows the sketch without exposing its update policy. It can
inspect keys without
+/// requiring `S: Clone`; set operations that retain summaries require `S:
Clone` when invoked.
///
-/// This trait is the input abstraction for APIs (such as union and
intersection) that accept
-/// either a mutable [`TupleSketch`] or an immutable [`CompactTupleSketch`].
`S` is the
-/// summary type retained by the sketch.
+/// # Examples
///
-/// It is blanket-implemented for every [`TupleKeySketchView`] that also
implements
-/// [`ThetaFamilySketchView`] with [`TupleEntry<S>`] as its associated entry
type.
-pub trait TupleSketchView<S>:
- TupleKeySketchView + ThetaFamilySketchView<Entry = TupleEntry<S>>
+/// ```
+/// use datasketches::tuple::DefaultUpdatePolicy;
+/// use datasketches::tuple::TupleSketchBuilder;
+///
+/// let mut sketch =
TupleSketchBuilder::new(DefaultUpdatePolicy::<u64>::default()).build();
+/// sketch.update("apple", 1);
+/// let view = sketch.as_view();
+/// assert_eq!(view.iter().next().unwrap().1, &1);
+/// ```
+#[derive(Debug)]
+pub struct TupleSketchView<'a, S>(TupleSketchViewState<'a, S>);
+
+#[derive(Debug)]
+enum TupleSketchViewState<'a, S> {
+ Mutable(&'a TupleHashTable<S>),
+ Compact(&'a CompactTupleSketch<S>),
+}
+
+enum TupleSketchIter<'a, S> {
+ Mutable(SketchHashTableIter<'a, TupleEntry<S>>),
+ Compact(slice::Iter<'a, TupleEntry<S>>),
+}
+
+impl<'a, S> Iterator for TupleSketchIter<'a, S> {
+ type Item = (u64, &'a S);
+
+ fn next(&mut self) -> Option<Self::Item> {
+ match self {
+ Self::Mutable(iter) => iter.next().map(|entry| (entry.hash(),
entry.summary())),
+ Self::Compact(iter) => iter.next().map(|entry| (entry.hash(),
entry.summary())),
+ }
+ }
+
+ fn size_hint(&self) -> (usize, Option<usize>) {
+ match self {
+ Self::Mutable(iter) => iter.size_hint(),
+ Self::Compact(iter) => iter.size_hint(),
+ }
+ }
+}
+
+impl<S> Clone for TupleSketchView<'_, S> {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<S> Copy for TupleSketchView<'_, S> {}
+
+impl<S> Clone for TupleSketchViewState<'_, S> {
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<S> Copy for TupleSketchViewState<'_, S> {}
+
+impl<'a, S> TupleSketchView<'a, S> {
+ /// Returns the 16-bit seed hash.
+ pub fn seed_hash(&self) -> u16 {
+ match self.0 {
+ TupleSketchViewState::Mutable(table) => table.seed_hash(),
+ TupleSketchViewState::Compact(sketch) => sketch.seed_hash(),
+ }
+ }
+
+ /// Returns theta as a `u64` threshold.
+ pub fn theta64(&self) -> u64 {
+ match self.0 {
+ TupleSketchViewState::Mutable(table) => table.theta(),
+ TupleSketchViewState::Compact(sketch) => sketch.theta64(),
+ }
+ }
+
+ /// Returns whether the viewed sketch has not received any updates.
+ pub fn is_empty(&self) -> bool {
+ match self.0 {
+ TupleSketchViewState::Mutable(table) => table.is_empty(),
+ TupleSketchViewState::Compact(sketch) => sketch.is_empty(),
+ }
+ }
+
+ /// Returns whether retained entries are ordered by ascending hash.
+ pub fn is_ordered(&self) -> bool {
+ match self.0 {
+ TupleSketchViewState::Mutable(_) => false,
+ TupleSketchViewState::Compact(sketch) => sketch.is_ordered(),
+ }
+ }
+
+ /// Returns an iterator over retained hashes and borrowed summaries.
+ pub fn iter(self) -> impl Iterator<Item = (u64, &'a S)> + 'a {
+ match self.0 {
+ TupleSketchViewState::Mutable(table) =>
TupleSketchIter::Mutable(table.iter_entries()),
+ TupleSketchViewState::Compact(sketch) => {
+ TupleSketchIter::Compact(sketch.entries.iter())
+ }
+ }
+ }
+
+ /// Returns the number of retained entries.
+ pub fn num_retained(&self) -> usize {
+ match self.0 {
+ TupleSketchViewState::Mutable(table) => table.num_retained(),
+ TupleSketchViewState::Compact(sketch) => sketch.num_retained(),
+ }
+ }
+}
+
+impl<S> KeySketch for TupleSketchView<'_, S> {
+ fn scalars(self) -> SketchScalars {
+ SketchScalars {
+ seed_hash: self.seed_hash(),
+ theta: self.theta64(),
+ empty: self.is_empty(),
+ ordered: self.is_ordered(),
+ num_retained: self.num_retained(),
+ }
+ }
+
+ fn hashes(self) -> impl Iterator<Item = u64> {
+ self.iter().map(|(hash, _)| hash)
+ }
+}
+
+impl<'a, S> EntrySketch for TupleSketchView<'a, S>
+where
+ S: Clone + 'a,
{
+ type Entry = TupleEntry<S>;
+
+ fn entries(self) -> impl Iterator<Item = Self::Entry> {
+ self.iter()
+ .map(|(hash, summary)| TupleEntry::new(hash, summary.clone()))
+ }
}
-impl<S, T> TupleSketchView<S> for T where
- T: TupleKeySketchView + ThetaFamilySketchView<Entry = TupleEntry<S>>
+impl<'a, P> From<&'a TupleSketch<P>> for TupleSketchView<'a, P::Summary>
+where
+ P: SummaryPolicy,
{
+ fn from(sketch: &'a TupleSketch<P>) -> Self {
+ Self(TupleSketchViewState::Mutable(&sketch.table))
+ }
+}
+
+impl<'a, S> From<&'a CompactTupleSketch<S>> for TupleSketchView<'a, S> {
+ fn from(sketch: &'a CompactTupleSketch<S>) -> Self {
+ Self(TupleSketchViewState::Compact(sketch))
+ }
}
/// Mutable Tuple sketch for building from input data.
@@ -113,6 +251,11 @@ impl<P> TupleSketch<P>
where
P: SummaryPolicy,
{
+ /// Returns a read-only view accepted by Tuple set operations.
+ pub fn as_view(&self) -> TupleSketchView<'_, P::Summary> {
+ self.into()
+ }
+
/// Updates the sketch with a key and a value accepted by the policy.
///
/// If the key is new, the policy creates a summary and folds in `value`;
if the key already
@@ -269,51 +412,6 @@ where
}
}
-impl<P> ThetaKeySketchView for TupleSketch<P>
-where
- P: SummaryPolicy,
-{
- fn seed_hash(&self) -> u16 {
- self.table.seed_hash()
- }
-
- fn theta64(&self) -> u64 {
- self.table.theta()
- }
-
- fn is_empty(&self) -> bool {
- self.table.is_empty()
- }
-
- fn is_ordered(&self) -> bool {
- false
- }
-
- fn iter_hashes(&self) -> impl Iterator<Item = u64> + '_ {
- self.table.iter().map(|(hash, _)| hash)
- }
-
- fn num_retained(&self) -> usize {
- self.table.num_retained()
- }
-}
-
-impl<P> TupleKeySketchView for TupleSketch<P> where P: SummaryPolicy {}
-
-impl<P> ThetaFamilySketchView for TupleSketch<P>
-where
- P: SummaryPolicy,
- P::Summary: Clone,
-{
- type Entry = TupleEntry<P::Summary>;
-
- fn iter(&self) -> impl Iterator<Item = TupleEntry<P::Summary>> + '_ {
- self.table
- .iter()
- .map(|(hash, summary)| TupleEntry::new(hash, summary.clone()))
- }
-}
-
/// Compact (immutable) Tuple sketch.
///
/// This is the serialization-friendly form: a compact array of retained
[`TupleEntry`] values
@@ -345,6 +443,11 @@ impl<S> CompactTupleSketch<S> {
}
}
+ /// Returns a read-only view accepted by Tuple set operations.
+ pub fn as_view(&self) -> TupleSketchView<'_, S> {
+ self.into()
+ }
+
/// Returns the cardinality (distinct key count) estimate.
pub fn estimate(&self) -> f64 {
if self.is_empty() {
@@ -602,42 +705,6 @@ impl<S> CompactTupleSketch<S> {
}
}
-impl<S> ThetaKeySketchView for CompactTupleSketch<S> {
- fn seed_hash(&self) -> u16 {
- self.seed_hash
- }
-
- fn theta64(&self) -> u64 {
- self.theta
- }
-
- fn is_empty(&self) -> bool {
- self.empty
- }
-
- fn is_ordered(&self) -> bool {
- self.ordered
- }
-
- fn iter_hashes(&self) -> impl Iterator<Item = u64> + '_ {
- self.entries.iter().map(TupleEntry::hash)
- }
-
- fn num_retained(&self) -> usize {
- self.entries.len()
- }
-}
-
-impl<S> TupleKeySketchView for CompactTupleSketch<S> {}
-
-impl<S: Clone> ThetaFamilySketchView for CompactTupleSketch<S> {
- type Entry = TupleEntry<S>;
-
- fn iter(&self) -> impl Iterator<Item = TupleEntry<S>> + '_ {
- self.entries.iter().cloned()
- }
-}
-
/// Builder for [`TupleSketch`].
///
/// Every builder carries a concrete [`SummaryPolicy`]. Use
diff --git a/datasketches/src/thetafamily/tuple/union.rs
b/datasketches/src/thetafamily/tuple/union.rs
index 4568ed8..788d418 100644
--- a/datasketches/src/thetafamily/tuple/union.rs
+++ b/datasketches/src/thetafamily/tuple/union.rs
@@ -79,17 +79,21 @@ where
/// Merges a sketch into the union.
///
/// Accepts either an [`TupleSketch`](crate::tuple::TupleSketch) or a
- /// [`CompactTupleSketch`] through the shared [`TupleSketchView`] trait.
Keys present in both
- /// the running union and `sketch` have their summaries combined via the
union policy.
+ /// [`CompactTupleSketch`] through [`TupleSketchView`]. Keys present in
both the running union
+ /// and `sketch` have their summaries combined via the union policy.
///
/// # Errors
///
/// Returns an error if `sketch` was built with a different seed than this
union (its seed hash
/// does not match).
- pub fn update<V>(&mut self, sketch: &V) -> Result<(), Error>
+ pub fn update<'a>(
+ &mut self,
+ sketch: impl Into<TupleSketchView<'a, P::Summary>>,
+ ) -> Result<(), Error>
where
- V: TupleSketchView<P::Summary>,
+ P::Summary: Clone + 'a,
{
+ let sketch = sketch.into();
self.state.update(sketch)
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]