geolith 0.2.1

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
Documentation
//! Tile content deduplication via ahash.
//!
//! Many tiles at lower zoom levels have identical content (e.g., ocean tiles).
//! Deduplication avoids writing duplicate tile data by mapping content hashes
//! to previously-written offsets.

use std::collections::HashMap;

use ahash::AHasher;
use std::hash::Hasher;

/// Tile deduplication tracker using content hashing.
///
/// Uses ahash (non-cryptographic, fast) to fingerprint tile bytes.
/// When a duplicate is detected, the existing offset is returned instead
/// of writing the tile data again.
#[derive(Debug)]
pub struct TileDedup {
    /// Maps content hash → (offset, length) in the output file.
    seen: HashMap<u64, (u64, u32)>,
}

impl TileDedup {
    /// Create a new dedup tracker.
    #[must_use]
    pub fn new() -> Self {
        Self {
            seen: HashMap::with_capacity(1 << 20),
        }
    }

    /// Check if we've seen this tile content before.
    ///
    /// Returns `Some((offset, length))` if duplicate, `None` if new.
    #[must_use]
    pub fn check(&self, data: &[u8]) -> Option<(u64, u32)> {
        let hash = Self::hash_bytes(data);
        self.seen.get(&hash).copied()
    }

    /// Record a newly-written tile's location.
    pub fn record(&mut self, data: &[u8], offset: u64, length: u32) {
        let hash = Self::hash_bytes(data);
        self.seen.insert(hash, (offset, length));
    }

    /// Number of unique tiles recorded.
    #[must_use]
    pub fn unique_count(&self) -> usize {
        self.seen.len()
    }

    fn hash_bytes(data: &[u8]) -> u64 {
        let mut hasher = AHasher::default();
        hasher.write(data);
        hasher.finish()
    }
}

impl Default for TileDedup {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn detects_duplicate() {
        let mut dedup = TileDedup::new();
        let data = b"hello tile";
        assert!(dedup.check(data).is_none());
        dedup.record(data, 100, 10);
        let result = dedup.check(data);
        assert_eq!(result, Some((100, 10)));
    }

    #[test]
    fn different_content_not_duplicate() {
        let mut dedup = TileDedup::new();
        dedup.record(b"tile-a", 0, 6);
        assert!(dedup.check(b"tile-b").is_none());
    }
}