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 87ee04b  refactor(xor): remove item counts and simplify construction 
(#329)
87ee04b is described below

commit 87ee04b2514df58f0c07434bd16e0b8dd73bd0cf
Author: tison <[email protected]>
AuthorDate: Fri Nov 6 16:35:28 2026 +0800

    refactor(xor): remove item counts and simplify construction (#329)
---
 .github/workflows/ci.yml                           |   2 +-
 CHANGELOG.md                                       |   2 +-
 CONTRIBUTING.md                                    |   2 +-
 README.md                                          |   2 +-
 benchmarks/xor/build.rs                            |  22 +-
 benchmarks/xor/query_shards.rs                     |  37 +--
 datasketches/src/codec/family.rs                   |   4 +-
 datasketches/src/xor/filter.rs                     | 345 ++++++++-------------
 datasketches/src/xor/mod.rs                        |  29 +-
 tests-integration/tests/serde_tests/xor.rs         | 114 +++----
 tests-integration/tests/xor_test/filter.rs         |  66 ++--
 .../tests/xor_test/{parts.rs => fingerprints.rs}   |  93 ++----
 tests-integration/tests/xor_test/main.rs           |   3 +-
 13 files changed, 261 insertions(+), 460 deletions(-)

diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ecd4d8f..ff4ca5d 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -75,7 +75,7 @@ jobs:
     needs: msrv
     strategy:
       matrix:
-        os: [ ubuntu-24.04, macos-14, windows-2022 ]
+        os: [ ubuntu-24.04, macos-15, windows-2022 ]
         rust-version: ${{ fromJson(needs.msrv.outputs.rust-versions) }}
     runs-on: ${{ matrix.os }}
     steps:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8fc9c25..74e356d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,7 +7,7 @@ All significant changes to this project will be documented in 
this file.
 ### New features
 
 * Add `HllUnion::serialize` to serialize union results directly.
-* Add immutable `XorFilter` behind the `xor` feature, with 8-, 16-, and 32-bit 
fingerprints, construction from values with automatic deduplication or borrowed 
distinct precomputed hashes, bounded seeded retries and compact temporary 
storage, optional cardinality metadata for imported filters, standard 
serialization for all three widths (Java-compatible for 8/16-bit filters), and 
validated imports for application-defined storage.
+* Add immutable `XorFilter` behind the `xor` feature, with 8-, 16-, and 32-bit 
fingerprints. Build from distinct precomputed hashes or import a seed and 
fingerprints with `from_fingerprints`. `XorFilterBuilder` accepts values or 
hashes individually or in batches. Inputs may repeat. Serialization stores no 
item count; readers must support the encoded fingerprint width.
 
 ### Improvements
 
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 4a06fb0..dab6a11 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -192,7 +192,7 @@ cargo x prepare-testdata java
 
 If no language is specified, all languages are prepared. These directories are 
not stored in Git. Run the command before the first test run and again whenever 
the pinned TCK revision changes. It requires network access and replaces the 
selected generated directories.
 
-The pinned TCK revision does not yet contain XOR filter snapshots. Until it 
does, `serde_tests/xor.rs` retains small hexadecimal fixtures generated from 
the merged Java implementation, with the source revision and inputs documented 
alongside them. Keep these separate from the synchronized `*_generated_files` 
directories; replace them with TCK fixtures when available.
+The pinned TCK revision does not yet contain XOR filter snapshots. Until it 
does, `serde_tests/xor.rs` retains small hexadecimal fixtures generated from 
the Java implementation, with the source revision and inputs documented 
alongside them. Keep these separate from the synchronized `*_generated_files` 
directories; replace them with TCK fixtures when available.
 
 ## Code of Conduct
 
diff --git a/README.md b/README.md
index 37a86a3..40c3131 100644
--- a/README.md
+++ b/README.md
@@ -83,7 +83,7 @@ See the [API documentation](https://docs.rs/datasketches) for 
configuration, acc
 
 The minimum supported Rust version is 1.86.0. The crate currently supports 
little-endian targets only.
 
-Supported serialization formats are tested with fixtures produced by Apache 
DataSketches Java, C++, and Go through the [DataSketches 
TCK](https://github.com/apache/datasketches-tck). XOR additionally uses 
fixtures generated from the merged Java implementation until TCK snapshots are 
available. Its standard format supports 8-, 16-, and 32-bit fingerprints; 
32-bit images require a reader that supports that width. Formats without an 
item count use the raw-parts API.
+Supported serialization formats are tested with fixtures produced by Apache 
DataSketches Java, C++, and Go through the [DataSketches 
TCK](https://github.com/apache/datasketches-tck). XOR also uses Java fixtures 
until TCK snapshots are available. Its standard format supports 8-, 16-, and 
32-bit fingerprints; readers must support the encoded width. Use 
`XorFilter::from_fingerprints` to import a seed and fingerprints from another 
format.
 
 Serialization compatibility does not imply that an ordinary Rust `Hash` 
implementation produces the same update bytes across languages. When sketches 
must represent the same inputs across implementations, use 
`hash::value::{raw_bytes, canonical_float, sign_extend, natural_extend}` (and 
the constructors within those modules) to select matching input encodings. When 
interoperating with an implementation that skips empty strings, skip them 
before updating here as well.
 
diff --git a/benchmarks/xor/build.rs b/benchmarks/xor/build.rs
index f203a2f..d3bcc15 100644
--- a/benchmarks/xor/build.rs
+++ b/benchmarks/xor/build.rs
@@ -20,6 +20,7 @@ use std::hint::black_box;
 use benchmarks::Bencher;
 use benchmarks::Runner;
 use datasketches::xor::XorFilter;
+use datasketches::xor::XorFilterBuilder;
 use datasketches::xor::XorFilterType;
 
 use crate::xor::hashes;
@@ -43,10 +44,9 @@ fn xorf_distinct_8(bencher: Bencher, cardinality: usize) {
 fn deduplicate_8(bencher: Bencher, rows: usize) {
     let keys = repeated_hashes(rows);
     bencher.bench_local(|| {
-        let mut distinct = keys.clone();
-        distinct.sort_unstable();
-        distinct.dedup();
-        black_box(XorFilter::from_hashes(&distinct, XorFilterType::Xor8, 
0).unwrap())
+        let mut builder = XorFilterBuilder::new(XorFilterType::Xor8, 0);
+        builder.update_hashes(keys.iter().copied());
+        black_box(builder.build().unwrap())
     });
 }
 
@@ -75,10 +75,9 @@ fn xorf_distinct_16(bencher: Bencher, cardinality: usize) {
 fn deduplicate_16(bencher: Bencher, rows: usize) {
     let keys = repeated_hashes(rows);
     bencher.bench_local(|| {
-        let mut distinct = keys.clone();
-        distinct.sort_unstable();
-        distinct.dedup();
-        black_box(XorFilter::from_hashes(&distinct, XorFilterType::Xor16, 
0).unwrap())
+        let mut builder = XorFilterBuilder::new(XorFilterType::Xor16, 0);
+        builder.update_hashes(keys.iter().copied());
+        black_box(builder.build().unwrap())
     });
 }
 
@@ -107,10 +106,9 @@ fn xorf_distinct_32(bencher: Bencher, cardinality: usize) {
 fn deduplicate_32(bencher: Bencher, rows: usize) {
     let keys = repeated_hashes(rows);
     bencher.bench_local(|| {
-        let mut distinct = keys.clone();
-        distinct.sort_unstable();
-        distinct.dedup();
-        black_box(XorFilter::from_hashes(&distinct, XorFilterType::Xor32, 
0).unwrap())
+        let mut builder = XorFilterBuilder::new(XorFilterType::Xor32, 0);
+        builder.update_hashes(keys.iter().copied());
+        black_box(builder.build().unwrap())
     });
 }
 
diff --git a/benchmarks/xor/query_shards.rs b/benchmarks/xor/query_shards.rs
index 4a52ede..2df7c63 100644
--- a/benchmarks/xor/query_shards.rs
+++ b/benchmarks/xor/query_shards.rs
@@ -30,7 +30,7 @@ const SHARDS: usize = 32;
 const QUERIES: usize = 256;
 
 // Storage formats can choose a fingerprint width at runtime. Give both peers
-// this dispatch, and import identical payloads without cardinality metadata.
+// this dispatch, and import identical payloads.
 enum Reference {
     Xor8(xorf::Xor8),
     Xor16(xorf::Xor16),
@@ -56,24 +56,12 @@ impl Reference {
     }
 
     fn into_datasketches(self) -> XorFilter {
-        let (seed, segment, fingerprints) = match self {
-            Self::Xor8(f) => (
-                f.seed,
-                f.block_length,
-                XorFingerprints::Xor8(f.fingerprints),
-            ),
-            Self::Xor16(f) => (
-                f.seed,
-                f.block_length,
-                XorFingerprints::Xor16(f.fingerprints),
-            ),
-            Self::Xor32(f) => (
-                f.seed,
-                f.block_length,
-                XorFingerprints::Xor32(f.fingerprints),
-            ),
+        let (seed, fingerprints) = match self {
+            Self::Xor8(f) => (f.seed, XorFingerprints::Xor8(f.fingerprints)),
+            Self::Xor16(f) => (f.seed, XorFingerprints::Xor16(f.fingerprints)),
+            Self::Xor32(f) => (f.seed, XorFingerprints::Xor32(f.fingerprints)),
         };
-        XorFilter::from_parts(seed, segment, fingerprints, None).unwrap()
+        XorFilter::from_fingerprints(seed, fingerprints).unwrap()
     }
 }
 
@@ -112,18 +100,15 @@ fn query<F>(
 }
 
 pub fn register(runner: &mut Runner) {
-    for kind in [
-        XorFilterType::Xor8,
-        XorFilterType::Xor16,
-        XorFilterType::Xor32,
+    for (bits, kind) in [
+        (8, XorFilterType::Xor8),
+        (16, XorFilterType::Xor16),
+        (32, XorFilterType::Xor32),
     ] {
         for cardinality in [128, 16_384] {
             for (name, present) in [("present", true), ("absent", false)] {
                 runner.compare(
-                    &format!(
-                        "xor::query_shards::{}_{name}/{cardinality}",
-                        kind.bits_per_fingerprint()
-                    ),
+                    &format!("xor::query_shards::{bits}_{name}/{cardinality}"),
                     20_000,
                     &[
                         ("DataSketches", &|b| {
diff --git a/datasketches/src/codec/family.rs b/datasketches/src/codec/family.rs
index 06a8f3d..d613eec 100644
--- a/datasketches/src/codec/family.rs
+++ b/datasketches/src/codec/family.rs
@@ -130,8 +130,8 @@ impl Family {
     pub const XORFILTER: Family = Family {
         id: 22,
         name: "XORFILTER",
-        min_pre_longs: 3,
-        max_pre_longs: 3,
+        min_pre_longs: 2,
+        max_pre_longs: 2,
     };
 }
 
diff --git a/datasketches/src/xor/filter.rs b/datasketches/src/xor/filter.rs
index 36fc374..7aefd4d 100644
--- a/datasketches/src/xor/filter.rs
+++ b/datasketches/src/xor/filter.rs
@@ -30,7 +30,7 @@ use crate::hash::XxHash64;
 
 const NUM_HASHES: u8 = 3;
 const SERIAL_VERSION: u8 = 1;
-const PREAMBLE_BYTES: usize = 3 * size_of::<u64>();
+const PREAMBLE_BYTES: usize = 2 * size_of::<u64>();
 const HASH_SEED: u64 = 0;
 const LOAD_FACTOR: f64 = 1.23;
 const CAPACITY_OFFSET: u64 = 32;
@@ -46,18 +46,16 @@ const SPLITMIX_MUL2: u64 = 0x94d0_49bb_1331_11eb;
 /// Fingerprint representation used by an [`XorFilter`].
 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
 pub enum XorFilterType {
-    /// Uses 8-bit fingerprints and has an expected false-positive probability 
of about `1 / 256`.
+    /// Uses 8-bit fingerprints and has an expected false-positive probability 
of about `2^-8`.
     Xor8,
-    /// Uses 16-bit fingerprints and has an expected false-positive 
probability of about
-    /// `1 / 65_536`.
+    /// Uses 16-bit fingerprints and has an expected false-positive 
probability of about `2^-16`.
     Xor16,
     /// Uses 32-bit fingerprints and has an expected false-positive 
probability of about `2^-32`.
     Xor32,
 }
 
 impl XorFilterType {
-    /// Returns the number of bits in each fingerprint.
-    pub const fn bits_per_fingerprint(self) -> u8 {
+    const fn bits_per_fingerprint(self) -> u8 {
         match self {
             Self::Xor8 => 8,
             Self::Xor16 => 16,
@@ -66,7 +64,11 @@ impl XorFilterType {
     }
 
     const fn bytes_per_fingerprint(self) -> usize {
-        (self.bits_per_fingerprint() / 8) as usize
+        match self {
+            Self::Xor8 => 1,
+            Self::Xor16 => 2,
+            Self::Xor32 => 4,
+        }
     }
 }
 
@@ -101,72 +103,95 @@ impl XorFingerprints {
     }
 }
 
-/// An immutable xor filter for probabilistic set membership.
+/// An [`XorFilter`] builder for values or precomputed hashes.
 ///
-/// A query that returns `false` proves that the item was not in the input 
set. A query that returns
-/// `true` may be a false positive, with probability determined by 
[`XorFilterType`]. A filter
-/// known to be empty always returns `false`. Values cannot
-/// be added after construction; rebuild the filter when the set changes.
+/// Inputs may repeat. Temporary memory use can grow linearly with the total 
input count.
 ///
-/// Ordinary values passed to [`contains`](Self::contains) are reduced to 
64-bit hashes with
-/// xxHash64 and seed `0`. Use [`contains_hash`](Self::contains_hash) only 
with the same hashes that
-/// were supplied to [`from_hashes`](Self::from_hashes).
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct XorFilter {
-    segment_length: usize,
-    num_items: Option<usize>,
+/// Query values with [`XorFilter::contains`] and precomputed hashes with
+/// [`XorFilter::contains_hash`].
+#[derive(Debug)]
+pub struct XorFilterBuilder {
+    filter_type: XorFilterType,
     seed: u64,
-    fingerprints: XorFingerprints,
+    hashes: Vec<u64>,
 }
 
-impl XorFilter {
-    /// Creates a filter from values hashed by xxHash64 with seed `0`.
+impl XorFilterBuilder {
+    /// Creates a builder with the given fingerprint width and initial 
construction seed.
     ///
-    /// Removes duplicate hashes before construction. The construction `seed` 
selects a
-    /// deterministic sequence of attempts; it does not change the hash 
function used for values.
-    /// Pass borrowed values to retain them after construction.
+    /// The `seed` determines which layouts to try during construction. Values 
are hashed
+    /// independently of it.
+    pub fn new(filter_type: XorFilterType, seed: u64) -> Self {
+        Self {
+            filter_type,
+            seed,
+            hashes: Vec::new(),
+        }
+    }
+
+    /// Adds a value.
+    #[inline]
+    pub fn update<T: Hash + ?Sized>(&mut self, item: &T) {
+        self.update_hash(hash_item(item));
+    }
+
+    /// Adds a precomputed 64-bit hash.
+    #[inline]
+    pub fn update_hash(&mut self, hash: u64) {
+        self.hashes.push(hash);
+    }
+
+    /// Adds a batch of values.
+    pub fn update_values<T: Hash>(&mut self, items: impl IntoIterator<Item = 
T>) {
+        self.update_hashes(items.into_iter().map(|item| hash_item(&item)));
+    }
+
+    /// Adds a batch of precomputed 64-bit hashes.
+    pub fn update_hashes(&mut self, hashes: impl IntoIterator<Item = u64>) {
+        self.hashes.extend(hashes);
+    }
+
+    /// Consumes the builder and creates a filter from the distinct hashes.
     ///
     /// # Errors
     ///
-    /// Returns an error under the size and construction-attempt limits of
-    /// [`from_hashes`](Self::from_hashes). Duplicate values are removed 
before construction.
-    ///
-    /// # Examples
-    ///
-    /// ```
-    /// use datasketches::xor::XorFilter;
-    /// use datasketches::xor::XorFilterType;
-    ///
-    /// let filter = XorFilter::from_values(["apple", "banana"], 
XorFilterType::Xor8, 0)?;
-    /// assert!(filter.contains("apple"));
-    /// # Ok::<(), datasketches::error::Error>(())
-    /// ```
-    pub fn from_values<T: Hash>(
-        items: impl IntoIterator<Item = T>,
-        ty: XorFilterType,
-        seed: u64,
-    ) -> Result<Self, Error> {
-        let mut hashes: Vec<_> = items.into_iter().map(|item| 
hash_item(&item)).collect();
-        hashes.sort_unstable();
-        hashes.dedup();
-        Self::from_hashes(&hashes, ty, seed)
+    /// Returns an error if the set of distinct hashes is too large or no 
valid layout is found.
+    pub fn build(mut self) -> Result<XorFilter, Error> {
+        self.hashes.sort_unstable();
+        self.hashes.dedup();
+        XorFilter::from_hashes(&self.hashes, self.filter_type, self.seed)
     }
+}
 
+/// An immutable xor filter for probabilistic set membership.
+///
+/// A query that returns `false` proves that the item was not in the input 
set. A query that returns
+/// `true` may be a false positive, with probability determined by 
[`XorFilterType`], even for an
+/// empty input set. Values cannot be added after construction; rebuild the 
filter when the set
+/// changes.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct XorFilter {
+    // Cache the derived length to avoid division on every query.
+    segment_length: usize,
+    seed: u64,
+    fingerprints: XorFingerprints,
+}
+
+impl XorFilter {
     /// Creates a filter from distinct precomputed 64-bit hashes.
     ///
-    /// Duplicate hashes return an error.
-    /// Query with [`contains_hash`](Self::contains_hash) using hashes from 
the same source.
-    /// The construction `seed` selects a deterministic sequence of attempts; 
input order
-    /// does not affect the result.
+    /// The initial `seed` determines which layouts to try during 
construction. The same set of
+    /// hashes, filter type, and seed produce the same filter regardless of 
input order.
+    /// Query with [`contains_hash`](Self::contains_hash) using the same hash 
function.
     ///
     /// # Errors
     ///
-    /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) 
if hashes contain
-    /// duplicates, the fingerprint slot count exceeds `u32::MAX`, a scratch 
allocation would
-    /// exceed `isize::MAX` bytes, or no peelable construction is found within 
100 attempts.
-    /// Valid input can also exhaust the attempts. A successful build may 
still exceed the
-    /// limits of [`serialize`](Self::serialize).
-    pub fn from_hashes(keys: &[u64], ty: XorFilterType, seed: u64) -> 
Result<Self, Error> {
+    /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) 
in these cases:
+    ///
+    /// - The input contains duplicate hashes.
+    /// - The input is too large to build a filter.
+    /// - Construction cannot find a valid layout. For distinct hashes, try 
another `seed`.
+    pub fn from_hashes(keys: &[u64], filter_type: XorFilterType, seed: u64) -> 
Result<Self, Error> {
         let num_items = keys.len();
         let capacity = compute_capacity(num_items)?;
         let segment_length = capacity / usize::from(NUM_HASHES);
@@ -211,9 +236,9 @@ impl XorFilter {
         }
 
         if stack_size != num_items {
-            return Err(Error::invalid_argument(format!(
-                "xor filter construction failed after 
{MAX_CONSTRUCTION_ATTEMPTS} attempts"
-            ))
+            return Err(Error::invalid_argument(
+                "xor filter construction could not find a valid layout",
+            )
             .with_context("num_items", num_items));
         }
 
@@ -223,7 +248,7 @@ impl XorFilter {
         drop(count);
         drop(queue);
 
-        let fingerprints = match ty {
+        let fingerprints = match filter_type {
             XorFilterType::Xor8 => XorFingerprints::Xor8(assign_fingerprints(
                 capacity,
                 segment_length,
@@ -249,25 +274,19 @@ impl XorFilter {
 
         Ok(Self {
             segment_length,
-            num_items: Some(num_items),
             seed: construction_seed,
             fingerprints,
         })
     }
 
-    /// Imports a filter from its raw fields without requiring a DataSketches 
serialization header.
+    /// Imports a filter from its stored seed and fingerprint slots.
     ///
-    /// The caller must preserve the original construction seed and 
fingerprint order, and query
-    /// with the original input hashes. A supplied item count must describe 
the original set.
-    /// A valid layout alone cannot establish these invariants.
-    /// Pass `None` when the storage format omits the item count. Standard 
serialization requires
-    /// a known count; a known zero count makes every query return `false`.
+    /// Pass the original filter's [`seed`](Self::seed), which can differ from 
the initial
+    /// construction seed. Preserve the fingerprint order and query with the 
original input hashes.
     ///
     /// # Errors
     ///
-    /// Returns an error unless the segment length is positive, the payload 
has exactly three
-    /// segments, and a supplied item count fits the capacity. Segment lengths 
above `u32::MAX`
-    /// are rejected because the index reduction uses 32-bit hash words.
+    /// Returns an error unless the payload has three equal segments of 
`1..=u32::MAX` slots each.
     ///
     /// # Examples
     ///
@@ -276,48 +295,36 @@ impl XorFilter {
     /// use datasketches::xor::XorFilterType;
     ///
     /// let filter = XorFilter::from_hashes(&[10, 20, 30], 
XorFilterType::Xor8, 0)?;
-    /// let imported = XorFilter::from_parts(
-    ///     filter.seed(),
-    ///     filter.segment_length(),
-    ///     filter.fingerprints().clone(),
-    ///     None,
-    /// )?;
+    /// let imported = XorFilter::from_fingerprints(filter.seed(), 
filter.fingerprints().clone())?;
     /// assert!(imported.contains_hash(20));
-    /// assert_eq!(imported.num_items(), None);
     /// # Ok::<(), datasketches::error::Error>(())
     /// ```
-    pub fn from_parts(
-        seed: u64,
-        segment_length: usize,
-        fingerprints: XorFingerprints,
-        num_items: Option<usize>,
-    ) -> Result<Self, Error> {
-        if segment_length == 0
-            || segment_length > u32::MAX as usize
-            || segment_length.checked_mul(3) != Some(fingerprints.len())
-        {
+    pub fn from_fingerprints(seed: u64, fingerprints: XorFingerprints) -> 
Result<Self, Error> {
+        let slots = fingerprints.len();
+        if slots == 0 {
             return Err(Error::invalid_argument(
-                "invalid xor filter segment or payload length",
+                "xor filter fingerprint array must not be empty",
             ));
         }
-        if num_items.is_some_and(|count| count > fingerprints.len()) {
-            return Err(Error::invalid_argument(
-                "item count exceeds xor filter capacity",
-            ));
+        if slots % 3 != 0 {
+            return Err(Error::invalid_argument(format!(
+                "xor filter fingerprint slot count must be a multiple of 3, 
got {slots}"
+            )));
+        }
+        let segment_length = slots / 3;
+        if segment_length > u32::MAX as usize {
+            return Err(Error::invalid_argument(format!(
+                "xor filter segment length must be at most {}, got 
{segment_length}",
+                u32::MAX
+            )));
         }
         Ok(Self {
             segment_length,
-            num_items,
             seed,
             fingerprints,
         })
     }
 
-    /// Returns the number of fingerprint slots in each of the three segments.
-    pub fn segment_length(&self) -> usize {
-        self.segment_length
-    }
-
     /// Returns the fingerprint slots for application-defined serialization.
     pub fn fingerprints(&self) -> &XorFingerprints {
         &self.fingerprints
@@ -334,15 +341,14 @@ impl XorFilter {
 
     /// Returns `true` if a precomputed 64-bit hash is possibly in the input 
set.
     ///
-    /// This method bypasses xxHash64. The caller must use the same hash value 
during construction
-    /// and queries; mixing raw values with precomputed hashes can introduce 
false negatives.
+    /// Use the same hash function for construction and queries.
     // Keep the width dispatch in the caller's hot loop, including across 
crates.
     #[inline(always)]
     pub fn contains_hash(&self, hash: u64) -> bool {
         let mixed = mix(hash, self.seed);
         let [h0, h1, h2] = indexes(mixed, self.segment_length);
 
-        let found = match &self.fingerprints {
+        match &self.fingerprints {
             XorFingerprints::Xor8(fingerprints) => {
                 fingerprint(mixed) as u8 == fingerprints[h0] ^ 
fingerprints[h1] ^ fingerprints[h2]
             }
@@ -352,22 +358,7 @@ impl XorFilter {
             XorFingerprints::Xor32(fingerprints) => {
                 fingerprint(mixed) as u32 == fingerprints[h0] ^ 
fingerprints[h1] ^ fingerprints[h2]
             }
-        };
-        // Avoid branching on the fingerprint comparison, including rare false
-        // positives. Unknown counts must preserve the raw comparison.
-        found & (self.num_items != Some(0))
-    }
-
-    /// Returns whether the input set was empty, or `None` if imported without 
an item count.
-    ///
-    /// Fingerprint contents cannot reliably establish whether the original 
set was empty.
-    pub fn is_empty(&self) -> Option<bool> {
-        self.num_items.map(|count| count == 0)
-    }
-
-    /// Returns the number of distinct input hashes, or `None` if imported 
without a count.
-    pub fn num_items(&self) -> Option<usize> {
-        self.num_items
+        }
     }
 
     /// Returns the fingerprint representation.
@@ -379,41 +370,11 @@ impl XorFilter {
         }
     }
 
-    /// Returns the number of bits in each fingerprint.
-    pub fn bits_per_fingerprint(&self) -> u8 {
-        self.filter_type().bits_per_fingerprint()
-    }
-
-    /// Returns the number of hash locations used by non-empty filter queries.
-    pub fn num_hashes(&self) -> u8 {
-        NUM_HASHES
-    }
-
-    /// Returns the number of fingerprint slots in the filter.
-    pub fn capacity(&self) -> usize {
-        self.fingerprints.len()
-    }
-
-    /// Returns the construction seed stored with the filter.
+    /// Returns the seed paired with these fingerprints for queries and 
imports.
     pub fn seed(&self) -> u64 {
         self.seed
     }
 
-    /// Returns the number of fingerprint bits allocated per distinct input 
hash.
-    ///
-    /// Returns `None` for an unknown item count and `Some(0.0)` for an empty 
filter. For
-    /// sufficiently large inputs the value approaches `9.84` for 
[`XorFilterType::Xor8`],
-    /// `19.68` for [`XorFilterType::Xor16`], and `39.36` for 
[`XorFilterType::Xor32`].
-    pub fn bits_per_item(&self) -> Option<f64> {
-        self.num_items.map(|count| {
-            if count == 0 {
-                0.0
-            } else {
-                self.capacity() as f64 * 
f64::from(self.bits_per_fingerprint()) / count as f64
-            }
-        })
-    }
-
     /// Returns the estimated in-memory size of the filter in bytes.
     pub fn estimated_size(&self) -> usize {
         size_of::<Self>() + self.fingerprints.byte_len()
@@ -422,36 +383,31 @@ impl XorFilter {
     /// Serializes the filter using DataSketches family `22`, version `1`.
     ///
     /// Supports 8-, 16-, and 32-bit fingerprints, recorded in the header's 
fingerprint width
-    /// field. Reserved fields are written as zero; integers and fingerprints 
are little-endian.
-    /// The 8- and 16-bit images are compatible with Java when input hashing 
agrees. Readers
-    /// must support the encoded fingerprint width; implementations limited to 
8/16 bits cannot
-    /// read 32-bit images.
+    /// field. Integers and fingerprints are little-endian. Readers must 
support the encoded
+    /// fingerprint width; implementations limited to 8/16 bits cannot read 
32-bit images.
     ///
     /// # Errors
     ///
-    /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) 
for an unknown
-    /// item count, or an item count or segment length above `i32::MAX`.
-    /// The total number of slots must also fit `i32::MAX` so that Java can 
index all three
-    /// segments; this is an additional interoperability limit, not a header 
field. Construction
-    /// and raw parts allow larger capacities, so successful construction does 
not guarantee
-    /// standard serialization. Use raw parts for other storage formats.
+    /// Returns [`InvalidArgument`](crate::error::ErrorKind::InvalidArgument) 
if the fingerprint
+    /// slot count exceeds `i32::MAX` or the serialized size overflows 
`usize`. Construction and
+    /// imports allow larger capacities than the standard format.
     pub fn serialize(&self) -> Result<Vec<u8>, Error> {
-        let size = self.serialized_size()?;
-        let num_items = self
-            .num_items
-            .expect("serialized_size checked the item count");
+        if self.fingerprints.len() > i32::MAX as usize {
+            return Err(Error::invalid_argument(
+                "xor filter exceeds standard format limits",
+            ));
+        }
+        let size = PREAMBLE_BYTES
+            .checked_add(self.fingerprints.byte_len())
+            .ok_or_else(|| Error::invalid_argument("xor filter serialized size 
overflow"))?;
         let mut bytes = SketchBytes::with_capacity(size);
 
         bytes.write_u8(Family::XORFILTER.min_pre_longs);
         bytes.write_u8(SERIAL_VERSION);
         bytes.write_u8(Family::XORFILTER.id);
-        bytes.write_u8(0); // flags
-        bytes.write_u8(self.bits_per_fingerprint());
-        bytes.write_u8(NUM_HASHES);
-        bytes.write_u16_le(0); // unused
-        bytes.write_u64_le(self.seed);
+        bytes.write_u8(self.filter_type().bits_per_fingerprint());
         bytes.write_i32_le(self.segment_length as i32);
-        bytes.write_i32_le(num_items as i32);
+        bytes.write_u64_le(self.seed);
 
         match &self.fingerprints {
             XorFingerprints::Xor8(fingerprints) => bytes.write(fingerprints),
@@ -473,7 +429,7 @@ impl XorFilter {
     /// Deserializes an owned filter from bytes.
     ///
     /// Accepts 8-, 16-, and 32-bit images within the limits of 
[`serialize`](Self::serialize).
-    /// Reserved fields and trailing bytes are ignored.
+    /// Trailing bytes are ignored.
     ///
     /// # Errors
     ///
@@ -489,12 +445,9 @@ impl XorFilter {
             .read_u8()
             .map_err(insufficient_data("serial_version"))?;
         let family_id = 
cursor.read_u8().map_err(insufficient_data("family_id"))?;
-        let _flags = cursor.read_u8().map_err(insufficient_data("flags"))?;
         let bits_per_fingerprint = cursor
             .read_u8()
             .map_err(insufficient_data("bits_per_fingerprint"))?;
-        let num_hashes = 
cursor.read_u8().map_err(insufficient_data("num_hashes"))?;
-        let _unused = 
cursor.read_u16_le().map_err(insufficient_data("unused"))?;
 
         Family::XORFILTER.validate_id(family_id)?;
         ensure_serial_version_is(SERIAL_VERSION, serial_version)?;
@@ -502,7 +455,7 @@ impl XorFilter {
             Family::XORFILTER.min_pre_longs..=Family::XORFILTER.max_pre_longs,
             preamble_longs,
         )?;
-        let ty = match bits_per_fingerprint {
+        let filter_type = match bits_per_fingerprint {
             8 => XorFilterType::Xor8,
             16 => XorFilterType::Xor16,
             32 => XorFilterType::Xor32,
@@ -512,13 +465,6 @@ impl XorFilter {
                 ));
             }
         };
-        if num_hashes != NUM_HASHES {
-            return Err(Error::deserial(format!(
-                "invalid number of hashes: expected {NUM_HASHES}, got 
{num_hashes}"
-            )));
-        }
-
-        let seed = cursor.read_u64_le().map_err(insufficient_data("seed"))?;
         let segment_length = cursor
             .read_i32_le()
             .map_err(insufficient_data("segment_length"))?;
@@ -529,15 +475,7 @@ impl XorFilter {
         }
         let segment_length = segment_length as usize;
 
-        let num_items = cursor
-            .read_i32_le()
-            .map_err(insufficient_data("num_items"))?;
-        if num_items < 0 {
-            return Err(Error::deserial(format!(
-                "invalid item count: expected a non-negative value, got 
{num_items}"
-            )));
-        }
-        let num_items = num_items as usize;
+        let seed = cursor.read_u64_le().map_err(insufficient_data("seed"))?;
 
         let capacity = segment_length
             .checked_mul(usize::from(NUM_HASHES))
@@ -548,14 +486,9 @@ impl XorFilter {
                 i32::MAX
             )));
         }
-        if num_items > capacity {
-            return Err(Error::deserial(format!(
-                "invalid item count: capacity is {capacity}, got {num_items}"
-            )));
-        }
 
         let fingerprint_bytes = capacity
-            .checked_mul(ty.bytes_per_fingerprint())
+            .checked_mul(filter_type.bytes_per_fingerprint())
             .ok_or_else(|| Error::deserial("xor filter fingerprint size 
overflow"))?;
         if cursor.remaining().len() < fingerprint_bytes {
             return Err(Error::insufficient_data_of(
@@ -567,7 +500,7 @@ impl XorFilter {
             ));
         }
 
-        let fingerprints = match ty {
+        let fingerprints = match filter_type {
             XorFilterType::Xor8 => {
                 let mut values = vec![0_u8; capacity].into_boxed_slice();
                 cursor
@@ -601,28 +534,10 @@ impl XorFilter {
 
         Ok(Self {
             segment_length,
-            num_items: Some(num_items),
             seed,
             fingerprints,
         })
     }
-
-    fn serialized_size(&self) -> Result<usize, Error> {
-        let count = self
-            .num_items
-            .ok_or_else(|| Error::invalid_argument("standard xor format 
requires an item count"))?;
-        if count > i32::MAX as usize
-            || self.segment_length > i32::MAX as usize
-            || self.capacity() > i32::MAX as usize
-        {
-            return Err(Error::invalid_argument(
-                "xor filter exceeds standard format limits",
-            ));
-        }
-        PREAMBLE_BYTES
-            .checked_add(self.fingerprints.byte_len())
-            .ok_or_else(|| Error::invalid_argument("xor filter serialized size 
overflow"))
-    }
 }
 
 fn hash_item<T: Hash + ?Sized>(item: &T) -> u64 {
diff --git a/datasketches/src/xor/mod.rs b/datasketches/src/xor/mod.rs
index 104edc1..9f386ce 100644
--- a/datasketches/src/xor/mod.rs
+++ b/datasketches/src/xor/mod.rs
@@ -19,19 +19,16 @@
 //!
 //! An XOR filter is built from the complete input set and cannot be updated 
afterward. Compared
 //! with a Bloom filter at the same false-positive probability, it generally 
needs less space and
-//! performs exactly three fingerprint reads per query. Construction needs 
temporary space linear
-//! in the number of distinct hashes.
+//! performs exactly three fingerprint reads per query.
 //!
-//! [`XorFilter::from_values`] hashes ordinary Rust values with xxHash64. Call
-//! [`XorFilter::from_hashes`] with distinct hashes
-//! when hashes have already been computed and must not be hashed again.
+//! [`XorFilterBuilder`] accepts values or precomputed hashes, including 
duplicates.
+//! Use [`XorFilter::from_hashes`] when the hashes are already distinct.
 //!
 //! # Cross-language hashing
 //!
 //! Standard serialization supports 8-, 16-, and 32-bit fingerprints using 
family `22`, version `1`.
-//! Interoperability requires the reader to support the encoded fingerprint 
width. The 8- and
-//! 16-bit images match Java's format; 32-bit images extend the same layout 
with little-endian
-//! `u32` slots and cannot be read by implementations limited to 8/16 bits.
+//! Interoperability requires the reader to support the encoded fingerprint 
width. The format
+//! stores the seed, segment layout, and fingerprints, without an item count.
 //! Construction may choose a different valid fingerprint array from another 
implementation;
 //! byte-for-byte equality of independently constructed filters is not 
guaranteed. Rust's
 //! [`Hash`](std::hash::Hash) implementations do not always encode values like 
other languages. Use
@@ -46,21 +43,20 @@
 //!
 //! # Application-defined storage
 //!
-//! [`XorFilter::from_parts`] imports a construction seed, segment length, and 
typed fingerprint
-//! slots without adding metadata to an existing disk format. Accessors expose 
these fields for
-//! serialization. Imports may omit the item count. Filters with a
-//! known zero item count always reject queries; imported parts with an 
unknown count retain the
-//! ordinary fingerprint comparison, including possible false positives.
+//! [`XorFilter::from_fingerprints`] restores a filter from its stored 
[`seed`](XorFilter::seed)
+//! and [`fingerprints`](XorFilter::fingerprints).
 //!
 //! # Examples
 //!
 //! ```
-//! use datasketches::xor::XorFilter;
+//! use datasketches::xor::XorFilterBuilder;
 //! use datasketches::xor::XorFilterType;
 //!
-//! let filter = XorFilter::from_values(["apple", "banana"], 
XorFilterType::Xor8, 0).unwrap();
+//! let mut builder = XorFilterBuilder::new(XorFilterType::Xor8, 0);
+//! builder.update_values(["apple", "banana"]);
+//! let filter = builder.build().unwrap();
 //!
-//! assert!(filter.contains(&"apple"));
+//! assert!(filter.contains("apple"));
 //! ```
 //!
 //! # References
@@ -71,5 +67,6 @@
 mod filter;
 
 pub use self::filter::XorFilter;
+pub use self::filter::XorFilterBuilder;
 pub use self::filter::XorFilterType;
 pub use self::filter::XorFingerprints;
diff --git a/tests-integration/tests/serde_tests/xor.rs 
b/tests-integration/tests/serde_tests/xor.rs
index 18de001..2a9aa35 100644
--- a/tests-integration/tests/serde_tests/xor.rs
+++ b/tests-integration/tests/serde_tests/xor.rs
@@ -17,28 +17,20 @@
 
 use datasketches::error::ErrorKind;
 use datasketches::xor::XorFilter;
+use datasketches::xor::XorFilterBuilder;
 use datasketches::xor::XorFilterType;
 use datasketches::xor::XorFingerprints;
 
-// Generated from datasketches-java commit 
1034fb33b6e013334ff870f130b9c388cae5dfa9.
+// Generated from datasketches-java commit 
c179c5bc00d5aadaed8c68ce11d14d812abe08d6.
 // XorFilterBuilder.create([1, 2, 3, Long.MIN_VALUE], bits, 42).toByteArray().
 const JAVA_XOR8_IMAGE: &str = concat!(
-    "0301160008030000956eeb2f2632d7bd0c00000004000000",
-    "00000000000000000000c500000000000000000000000000dd000000040000000b000000"
+    "020116080c000000956eeb2f2632d7bd",
+    "000000000000000400dd0000000000000000ce0000c50000000000000000000000000000"
 );
 const JAVA_XOR16_IMAGE: &str = concat!(
-    "0301160010030000",
-    "956eeb2f2632d7bd",
-    "0c00000004000000",
-    "0000000000000000",
-    "0000000000000000",
-    "00000000c5b60000",
-    "0000000000000000",
-    "0000000000000000",
-    "0000000000000000",
-    "dd6e000000000000",
-    "04e8000000000000",
-    "0b23000000000000",
+    "020116100c000000956eeb2f2632d7bd",
+    "000000000000000000000000000004e80000dd6e00000000000000000000000000000000",
+    "ce9500000000c5b600000000000000000000000000000000000000000000000000000000",
 );
 
 #[test]
@@ -50,19 +42,14 @@ fn java_images_round_trip_byte_for_byte() {
         (XorFilterType::Xor16, JAVA_XOR16_IMAGE),
     ] {
         let expected = decode_hex(image);
-        let built = XorFilter::from_values(values, ty, 42).unwrap();
+        let mut builder = XorFilterBuilder::new(ty, 42);
+        builder.update_values(values.iter());
+        let built = builder.build().unwrap();
 
         let restored = XorFilter::deserialize(&expected).unwrap();
         assert_eq!(restored.serialize().unwrap(), expected);
-        // Peelability does not depend on peeling order, so both builders 
select the same
-        // construction seed and layout. Fingerprint slots may still differ by 
peeling order.
-        assert_eq!(
-            built.serialize().unwrap()[..24],
-            expected[..24],
-            "{ty:?} header differs from Java"
-        );
+        assert_eq!(built.serialize().unwrap(), expected);
         assert_eq!(restored.filter_type(), ty);
-        assert_eq!(restored.num_items(), Some(values.len()));
         for value in values {
             assert!(built.contains(&value));
             assert!(
@@ -90,9 +77,6 @@ fn serialization_round_trips_standard_fingerprint_types() {
             for hash in 0..count {
                 assert!(restored.contains_hash(hash));
             }
-            if count == 0 {
-                
assert!(!restored.contains_hash(restored.seed().wrapping_neg()));
-            }
         }
     }
 }
@@ -126,14 +110,14 @@ fn invalid_preamble_fields_are_rejected() {
         .unwrap();
 
     for (offset, value) in [
-        (0, 2),
-        (0, 4),
+        (0, 1),
+        (0, 3),
+        (1, 0),
         (1, 2),
         (2, 21),
-        (4, 7),
-        (4, 24),
-        (4, 64),
-        (5, 4),
+        (3, 7),
+        (3, 24),
+        (3, 64),
     ] {
         let mut corrupted = valid.clone();
         corrupted[offset] = value;
@@ -152,16 +136,7 @@ fn unsafe_lengths_are_rejected_before_indexing() {
 
     for segment_length in [0_i32, -1, i32::MAX] {
         let mut corrupted = valid.clone();
-        corrupted[16..20].copy_from_slice(&segment_length.to_le_bytes());
-        assert_eq!(
-            XorFilter::deserialize(&corrupted).unwrap_err().kind(),
-            ErrorKind::InvalidData
-        );
-    }
-
-    for num_items in [-1_i32, i32::MAX] {
-        let mut corrupted = valid.clone();
-        corrupted[20..24].copy_from_slice(&num_items.to_le_bytes());
+        corrupted[4..8].copy_from_slice(&segment_length.to_le_bytes());
         assert_eq!(
             XorFilter::deserialize(&corrupted).unwrap_err().kind(),
             ErrorKind::InvalidData
@@ -200,39 +175,27 @@ fn decode_hex(input: &str) -> Vec<u8> {
 #[test]
 fn java_utf8_and_raw_byte_inputs_match() {
     use datasketches::hash::value::raw_bytes;
-    // The same merged Java implementation, using update(String) and 
update(byte[]).
+    // The same Java revision, using update(String) and update(byte[]).
     let images = [
         (
             XorFilterType::Xor8,
-            
"0301160008030000956eeb2f2632d7bd0c0000000400000000000000000000000000000000df00000000000000000000cc0000003000000091000000",
+            
"020116080c000000956eeb2f2632d7bdccdf00000000000000ef0091000000000000000000000000000000000000000000000000",
         ),
         (
             XorFilterType::Xor16,
-            
"0301160010030000956eeb2f2632d7bd0c000000040000000000000000000000000000000000000000000000000000000000df500000000000000000000000000000000000000000ccb5000000000000301200000000000091b8000000000000",
+            
"020116100c000000956eeb2f2632d7bdccb5df500000000000000000000000000000ef42000091b8000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
         ),
     ];
     for (kind, image) in images {
-        let built = XorFilter::from_values(
-            [
-                raw_bytes::from_slice(b"hello"),
-                raw_bytes::from_slice("数据🔎".as_bytes()),
-                raw_bytes::from_slice(&[]),
-                raw_bytes::from_slice(&[0, 1, 255]),
-            ],
-            kind,
-            42,
-        )
-        .unwrap();
+        let mut builder = XorFilterBuilder::new(kind, 42);
+        for bytes in [b"hello".as_slice(), "数据🔎".as_bytes(), &[], &[0, 1, 
255]] {
+            builder.update(&raw_bytes::from_slice(bytes));
+        }
+        let built = builder.build().unwrap();
         let expected = decode_hex(image);
         let restored = XorFilter::deserialize(&expected).unwrap();
         assert_eq!(restored.serialize().unwrap(), expected);
-        // Peelability does not depend on peeling order, so both builders 
select the same
-        // construction seed and layout. Fingerprint slots may still differ by 
peeling order.
-        assert_eq!(
-            built.serialize().unwrap()[..24],
-            expected[..24],
-            "{kind:?} header differs from Java"
-        );
+        assert_eq!(built.serialize().unwrap(), expected);
         for bytes in [b"hello".as_slice(), "数据🔎".as_bytes(), &[], &[0, 1, 
255]] {
             assert!(built.contains(&raw_bytes::from_slice(bytes)));
             assert!(restored.contains(&raw_bytes::from_slice(bytes)));
@@ -243,18 +206,15 @@ fn java_utf8_and_raw_byte_inputs_match() {
 #[test]
 fn xor32_image_preserves_full_width_little_endian_slots() {
     // Hand-authored layout fixture, independent of the construction algorithm:
-    // family 22/version 1, width 32, three one-slot segments, one item.
+    // family 22/version 1, width 32, three one-slot segments.
     let bytes = decode_hex(concat!(
-        "0301160020030000",
+        "0201162001000000",
         "efcdab8967452301",
-        "0100000001000000",
         "67452301efcdab89ffffffff",
     ));
-    let filter = XorFilter::from_parts(
+    let filter = XorFilter::from_fingerprints(
         0x0123_4567_89ab_cdef,
-        1,
         XorFingerprints::Xor32(vec![0x0123_4567, 0x89ab_cdef, 
u32::MAX].into_boxed_slice()),
-        Some(1),
     )
     .unwrap();
     assert_eq!(filter.serialize().unwrap(), bytes);
@@ -262,7 +222,7 @@ fn xor32_image_preserves_full_width_little_endian_slots() {
 }
 
 #[test]
-fn raw_parts_preserve_an_application_storage_layout() {
+fn fingerprints_preserve_an_application_storage_layout() {
     use datasketches::codec::SketchSlice;
     // Synthetic storage fixtures with public xorf 0.13.0 payloads for [0, 1, 
2, u64::MAX].
     // This test-only envelope omits cardinality: magic, width:u8, 
segment:u32, seed:u64,
@@ -293,6 +253,7 @@ fn raw_parts_preserve_an_application_storage_layout() {
         let segment = cursor.read_u32_le().unwrap() as usize;
         let seed = cursor.read_u64_le().unwrap();
         let slots = cursor.remaining().len() / usize::from(width / 8);
+        assert_eq!(segment * 3, slots);
         let payload = match width {
             8 => XorFingerprints::Xor8(cursor.remaining().into()),
             16 => {
@@ -303,15 +264,18 @@ fn raw_parts_preserve_an_application_storage_layout() {
             }
             _ => unreachable!(),
         };
-        let filter = XorFilter::from_parts(seed, segment, payload, 
None).unwrap();
+        let filter = XorFilter::from_fingerprints(seed, payload).unwrap();
         for hash in [0, 1, 2, u64::MAX] {
             assert!(filter.contains_hash(hash));
         }
-        assert_eq!(filter.capacity(), slots);
-        assert_eq!(filter.num_items(), None);
 
-        let (seed, segment) = (filter.seed(), filter.segment_length());
+        let seed = filter.seed();
         let payload = filter.fingerprints();
+        let segment = match payload {
+            XorFingerprints::Xor8(values) => values.len() / 3,
+            XorFingerprints::Xor16(values) => values.len() / 3,
+            XorFingerprints::Xor32(values) => values.len() / 3,
+        };
         let mut encoded = b"TEST".to_vec();
         encoded.push(width);
         encoded.extend((segment as u32).to_le_bytes());
diff --git a/tests-integration/tests/xor_test/filter.rs 
b/tests-integration/tests/xor_test/filter.rs
index cc2a714..2deec7f 100644
--- a/tests-integration/tests/xor_test/filter.rs
+++ b/tests-integration/tests/xor_test/filter.rs
@@ -16,11 +16,16 @@
 // under the License.
 
 use datasketches::xor::XorFilter;
+use datasketches::xor::XorFilterBuilder;
 use datasketches::xor::XorFilterType;
 
 #[test]
 fn values_have_no_false_negatives() {
-    let filter = XorFilter::from_values(0..10_000_u64, XorFilterType::Xor8, 
8123).unwrap();
+    let mut builder = XorFilterBuilder::new(XorFilterType::Xor8, 8123);
+    for value in 0..10_000_u64 {
+        builder.update(&value);
+    }
+    let filter = builder.build().unwrap();
 
     for value in 0..10_000_u64 {
         assert!(filter.contains(&value), "false negative for {value}");
@@ -46,49 +51,28 @@ fn precomputed_hashes_have_no_false_negatives() {
 }
 
 #[test]
-fn borrowed_values_can_be_reused() {
-    let values = vec!["datasketches".to_string(), "xor filter".to_string()];
-    let first = XorFilter::from_values(&values, XorFilterType::Xor16, 
42).unwrap();
-    let second = XorFilter::from_values(&values, XorFilterType::Xor16, 
42).unwrap();
-    assert_eq!(first, second);
-    for value in &values {
-        assert!(first.contains(value));
+fn builder_deduplicates_values_and_hashes() {
+    for ty in [
+        XorFilterType::Xor8,
+        XorFilterType::Xor16,
+        XorFilterType::Xor32,
+    ] {
+        let mut values = XorFilterBuilder::new(ty, 0);
+        let mut hashes = XorFilterBuilder::new(ty, 0);
+        values.update(&7_u64);
+        values.update_values([11_u64, 7, 11]);
+        hashes.update_hash(7);
+        hashes.update_hashes([11, 7, 11]);
+        let filter = values.build().unwrap();
+        assert!(filter.contains(&7_u64));
+        assert!(filter.contains(&11_u64));
+        assert_eq!(
+            hashes.build().unwrap(),
+            XorFilter::from_hashes(&[7, 11], ty, 0).unwrap()
+        );
     }
 }
 
-#[test]
-fn duplicates_are_removed_before_construction() {
-    let filter = XorFilter::from_values([7_u64, 7, 11, 11, 11], 
XorFilterType::Xor8, 0).unwrap();
-    assert_eq!(filter.num_items(), Some(2));
-    assert!(filter.contains(&7_u64));
-    assert!(filter.contains(&11_u64));
-}
-
-#[test]
-fn metadata_describes_the_compact_payload() {
-    let hashes: Vec<_> = (0..10_000_u64).collect();
-    let filter = XorFilter::from_hashes(&hashes, XorFilterType::Xor8, 
0).unwrap();
-
-    assert_eq!(filter.is_empty(), Some(false));
-    assert_eq!(filter.num_items(), Some(10_000));
-    assert_eq!(filter.filter_type(), XorFilterType::Xor8);
-    assert_eq!(filter.bits_per_fingerprint(), 8);
-    assert_eq!(filter.num_hashes(), 3);
-    assert_eq!(filter.capacity() % 3, 0);
-    assert!((9.5..10.5).contains(&filter.bits_per_item().unwrap()));
-    assert!(filter.estimated_size() >= filter.capacity());
-}
-
-#[test]
-fn empty_filter_is_well_formed() {
-    let filter = XorFilter::from_hashes(&[], XorFilterType::Xor16, 0).unwrap();
-
-    assert_eq!(filter.is_empty(), Some(true));
-    assert_eq!(filter.num_items(), Some(0));
-    assert_eq!(filter.capacity(), 30);
-    assert_eq!(filter.bits_per_item().unwrap(), 0.0);
-}
-
 #[test]
 fn false_positive_rates_follow_fingerprint_width() {
     const NUM_ITEMS: u64 = 50_000;
diff --git a/tests-integration/tests/xor_test/parts.rs 
b/tests-integration/tests/xor_test/fingerprints.rs
similarity index 65%
rename from tests-integration/tests/xor_test/parts.rs
rename to tests-integration/tests/xor_test/fingerprints.rs
index 9b5272a..b5d000c 100644
--- a/tests-integration/tests/xor_test/parts.rs
+++ b/tests-integration/tests/xor_test/fingerprints.rs
@@ -22,7 +22,7 @@ use datasketches::xor::XorFingerprints;
 use xorf::Filter;
 
 #[test]
-fn raw_parts_interoperate_with_xorf_in_both_directions() {
+fn fingerprints_interoperate_with_xorf_in_both_directions() {
     let keys: Vec<_> = (0..16_384u64)
         .map(|n| n.wrapping_mul(0x9e3779b97f4a7c15))
         .collect();
@@ -31,63 +31,47 @@ fn raw_parts_interoperate_with_xorf_in_both_directions() {
         XorFilterType::Xor16,
         XorFilterType::Xor32,
     ] {
-        let (seed, segment, payload) = match kind {
+        let (seed, payload) = match kind {
             XorFilterType::Xor8 => {
                 let f = xorf::Xor8::from(&keys);
-                (
-                    f.seed,
-                    f.block_length,
-                    XorFingerprints::Xor8(f.fingerprints),
-                )
+                (f.seed, XorFingerprints::Xor8(f.fingerprints))
             }
             XorFilterType::Xor16 => {
                 let f = xorf::Xor16::from(&keys);
-                (
-                    f.seed,
-                    f.block_length,
-                    XorFingerprints::Xor16(f.fingerprints),
-                )
+                (f.seed, XorFingerprints::Xor16(f.fingerprints))
             }
             XorFilterType::Xor32 => {
                 let f = xorf::Xor32::from(&keys);
-                (
-                    f.seed,
-                    f.block_length,
-                    XorFingerprints::Xor32(f.fingerprints),
-                )
+                (f.seed, XorFingerprints::Xor32(f.fingerprints))
             }
         };
-        let imported = XorFilter::from_parts(seed, segment, payload, 
None).unwrap();
-        assert_eq!(imported.num_items(), None);
-        assert_eq!(imported.bits_per_item(), None);
-        assert_eq!(imported.is_empty(), None);
+        let imported = XorFilter::from_fingerprints(seed, payload).unwrap();
         assert_eq!(
-            imported.serialize().unwrap_err().kind(),
-            ErrorKind::InvalidArgument
+            XorFilter::deserialize(&imported.serialize().unwrap()).unwrap(),
+            imported
         );
         for &key in &keys {
             assert!(imported.contains_hash(key));
         }
 
         let built = XorFilter::from_hashes(&keys, kind, 0).unwrap();
-        assert_eq!(built.num_items(), Some(keys.len()));
-        let (seed, block_length) = (built.seed(), built.segment_length());
+        let seed = built.seed();
         let payload = built.fingerprints().clone();
         // Compare all answers, including false positives, after exporting the 
fingerprints.
         let reference: Box<dyn Filter<u64>> = match payload {
             XorFingerprints::Xor8(fingerprints) => Box::new(xorf::Xor8 {
                 seed,
-                block_length,
+                block_length: fingerprints.len() / 3,
                 fingerprints,
             }),
             XorFingerprints::Xor16(fingerprints) => Box::new(xorf::Xor16 {
                 seed,
-                block_length,
+                block_length: fingerprints.len() / 3,
                 fingerprints,
             }),
             XorFingerprints::Xor32(fingerprints) => Box::new(xorf::Xor32 {
                 seed,
-                block_length,
+                block_length: fingerprints.len() / 3,
                 fingerprints,
             }),
         };
@@ -98,25 +82,12 @@ fn raw_parts_interoperate_with_xorf_in_both_directions() {
 }
 
 #[test]
-fn raw_parts_reject_invalid_layouts_and_counts() {
-    for (segment, length, count) in [
-        (0, 0, None),
-        (1, 2, None),
-        (1, 4, None),
-        (usize::MAX, 3, None),
-        (1, 3, Some(4)),
-    ] {
-        assert_eq!(
-            XorFilter::from_parts(
-                0,
-                segment,
-                XorFingerprints::Xor8(vec![0; length].into()),
-                count
-            )
-            .unwrap_err()
-            .kind(),
-            ErrorKind::InvalidArgument
-        );
+fn fingerprints_reject_invalid_layouts() {
+    for (length, reason) in [(0, "empty"), (2, "multiple of 3"), (4, "multiple 
of 3")] {
+        let error = XorFilter::from_fingerprints(0, 
XorFingerprints::Xor8(vec![0; length].into()))
+            .unwrap_err();
+        assert_eq!(error.kind(), ErrorKind::InvalidArgument);
+        assert!(error.message().contains(reason), "{error}");
     }
 }
 
@@ -132,7 +103,6 @@ fn 
distinct_construction_is_bounded_and_does_not_deduplicate() {
         assert!(error.message().contains("duplicate hashes"));
         for keys in [vec![], vec![0], vec![u64::MAX], vec![0, u64::MAX]] {
             let f = XorFilter::from_hashes(&keys, kind, 0).unwrap();
-            assert_eq!(f.num_items(), Some(keys.len()));
             for key in keys {
                 assert!(f.contains_hash(key));
             }
@@ -174,7 +144,7 @@ fn 
construction_recovers_after_an_unpeelable_first_attempt() {
 }
 
 #[test]
-fn unknown_count_does_not_infer_emptiness_from_zero_fingerprints() {
+fn empty_input_uses_fingerprint_queries() {
     for kind in [
         XorFilterType::Xor8,
         XorFilterType::Xor16,
@@ -182,23 +152,12 @@ fn 
unknown_count_does_not_infer_emptiness_from_zero_fingerprints() {
     ] {
         let empty = XorFilter::from_hashes(&[], kind, 0).unwrap();
         let zero_hash = empty.seed().wrapping_neg();
-        assert_eq!(empty.is_empty(), Some(true));
-        assert!(!empty.contains_hash(zero_hash));
-        let unknown = XorFilter::from_parts(
-            empty.seed(),
-            empty.segment_length(),
-            empty.fingerprints().clone(),
-            None,
-        )
-        .unwrap();
-        assert_eq!(unknown.is_empty(), None);
-        assert_eq!(unknown.num_items(), None);
-        assert_eq!(unknown.bits_per_item(), None);
-        // An omitted count must preserve the raw fingerprint comparison, even 
for all-zero slots.
-        assert!(unknown.contains_hash(zero_hash));
-        assert_eq!(
-            unknown.serialize().unwrap_err().kind(),
-            ErrorKind::InvalidArgument
-        );
+        // This query produces a false positive even though the input set is 
empty.
+        assert!(empty.contains_hash(zero_hash));
+        let imported =
+            XorFilter::from_fingerprints(empty.seed(), 
empty.fingerprints().clone()).unwrap();
+        for hash in (0..1_000).chain([zero_hash]) {
+            assert_eq!(imported.contains_hash(hash), 
empty.contains_hash(hash));
+        }
     }
 }
diff --git a/tests-integration/tests/xor_test/main.rs 
b/tests-integration/tests/xor_test/main.rs
index 656a505..34b0359 100644
--- a/tests-integration/tests/xor_test/main.rs
+++ b/tests-integration/tests/xor_test/main.rs
@@ -16,5 +16,4 @@
 // under the License.
 
 mod filter;
-
-mod parts;
+mod fingerprints;


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to