html-cleaning 0.3.0

HTML cleaning, sanitization, and text processing utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! Content deduplication utilities.
//!
//! LRU-based cache for detecting duplicate text content.

use std::collections::HashMap;

/// Simple LRU cache for text deduplication.
///
/// Maintains insertion order and evicts the oldest entry when capacity is reached.
/// Note: Updating an existing key does NOT refresh its position (matches Go behavior).
///
/// # Example
///
/// ```
/// use html_cleaning::dedup::LruCache;
///
/// let mut cache = LruCache::new(3);
/// cache.put("a", 1);
/// cache.put("b", 2);
/// assert_eq!(cache.get("a"), Some(1));
/// assert!(cache.has("b"));
/// ```
pub struct LruCache {
    max_size: usize,
    keys: Vec<String>,
    data: HashMap<String, i32>,
}

impl LruCache {
    /// Create new cache with specified capacity.
    #[must_use]
    pub fn new(max_size: usize) -> Self {
        Self {
            max_size,
            keys: Vec::new(),
            data: HashMap::new(),
        }
    }

    /// Get value for key.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<i32> {
        self.data.get(key).copied()
    }

    /// Check if key exists.
    #[must_use]
    pub fn has(&self, key: &str) -> bool {
        self.data.contains_key(key)
    }

    /// Store key-value pair, evicting oldest if at capacity.
    pub fn put(&mut self, key: &str, value: i32) {
        if self.data.contains_key(key) {
            self.data.insert(key.to_string(), value);
            return;
        }

        if self.max_size == 0 {
            return;
        }

        if self.keys.len() >= self.max_size {
            if let Some(oldest_key) = self.keys.first().cloned() {
                self.keys.remove(0);
                self.data.remove(&oldest_key);
            }
        }

        self.keys.push(key.to_string());
        self.data.insert(key.to_string(), value);
    }

    /// Clear all entries.
    pub fn clear(&mut self) {
        self.keys.clear();
        self.data.clear();
    }

    /// Get current size.
    #[must_use]
    pub fn len(&self) -> usize {
        self.keys.len()
    }

    /// Check if empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.keys.is_empty()
    }

    /// Remove a specific key from the cache.
    pub fn remove(&mut self, key: &str) {
        if !self.data.contains_key(key) {
            return;
        }

        // Find and remove from keys list
        if let Some(idx) = self.keys.iter().position(|k| k == key) {
            self.keys.remove(idx);
        }
        self.data.remove(key);
    }
}

/// LRU-based content deduplicator.
///
/// Tracks seen text fragments to detect duplicates during processing.
///
/// # Example
///
/// ```
/// use html_cleaning::dedup::Deduplicator;
///
/// let mut dedup = Deduplicator::new(100);
///
/// assert!(!dedup.is_duplicate("first occurrence"));
/// assert!(!dedup.is_duplicate("first occurrence")); // seen once
/// assert!(!dedup.is_duplicate("first occurrence")); // seen twice
/// assert!(dedup.is_duplicate("first occurrence"));  // now duplicate (>2)
/// ```
pub struct Deduplicator {
    cache: LruCache,
    threshold: i32,
}

impl Deduplicator {
    /// Create with specified capacity.
    ///
    /// Uses default threshold of 2 (text seen more than 2 times is duplicate).
    ///
    /// # Arguments
    /// * `capacity` - Maximum number of entries to track
    #[must_use]
    pub fn new(capacity: usize) -> Self {
        Self {
            cache: LruCache::new(capacity),
            threshold: 2,
        }
    }

    /// Create with capacity and custom duplicate threshold.
    ///
    /// # Arguments
    /// * `capacity` - Maximum entries
    /// * `threshold` - Number of times text can appear before considered duplicate
    #[must_use]
    pub fn with_threshold(capacity: usize, threshold: i32) -> Self {
        Self {
            cache: LruCache::new(capacity),
            threshold,
        }
    }

    /// Check if text is duplicate, adding to cache.
    ///
    /// Returns `true` if text has been seen more than threshold times.
    pub fn is_duplicate(&mut self, text: &str) -> bool {
        let count = self.cache.get(text).unwrap_or(0);
        let is_dup = count > self.threshold;

        // Always increment count
        self.cache.put(text, count + 1);

        is_dup
    }

    /// Check without adding to cache.
    #[must_use]
    pub fn check(&self, text: &str) -> bool {
        self.cache
            .get(text)
            .is_some_and(|count| count > self.threshold)
    }

    /// Check if text has been seen (regardless of count).
    #[must_use]
    pub fn has_seen(&self, text: &str) -> bool {
        self.cache.has(text)
    }

    /// Clear the cache.
    pub fn clear(&mut self) {
        self.cache.clear();
    }

    /// Get current cache size.
    #[must_use]
    pub fn len(&self) -> usize {
        self.cache.len()
    }

    /// Check if cache is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.cache.is_empty()
    }
}

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

    #[test]
    fn test_new_deduplicator() {
        let dedup = Deduplicator::new(100);
        assert!(dedup.is_empty());
        assert_eq!(dedup.len(), 0);
    }

    #[test]
    fn test_is_duplicate() {
        let mut dedup = Deduplicator::new(100);

        // First 3 occurrences should not be duplicate (threshold is 2)
        assert!(!dedup.is_duplicate("test"));
        assert!(!dedup.is_duplicate("test"));
        assert!(!dedup.is_duplicate("test"));

        // Fourth should be duplicate
        assert!(dedup.is_duplicate("test"));
    }

    #[test]
    fn test_check_without_adding() {
        let mut dedup = Deduplicator::new(100);

        // check on unseen text returns false without modifying state
        assert!(!dedup.check("test"));
        assert!(!dedup.has_seen("test"));

        // Add text enough times to exceed threshold
        dedup.is_duplicate("test");
        dedup.is_duplicate("test");
        dedup.is_duplicate("test");

        // check returns true now (count 3 > threshold 2)
        assert!(dedup.check("test"));
    }

    #[test]
    fn test_has_seen() {
        let mut dedup = Deduplicator::new(100);

        assert!(!dedup.has_seen("test"));
        dedup.is_duplicate("test");
        assert!(dedup.has_seen("test"));
    }

    #[test]
    fn test_custom_threshold() {
        let mut dedup = Deduplicator::with_threshold(100, 1);

        // With threshold 1, second occurrence is duplicate
        assert!(!dedup.is_duplicate("test")); // count: 1
        assert!(!dedup.is_duplicate("test")); // count: 2, 1 > 1 = false
        assert!(dedup.is_duplicate("test")); // count: 3, 2 > 1 = true
    }

    #[test]
    fn test_clear() {
        let mut dedup = Deduplicator::new(100);

        dedup.is_duplicate("test");
        assert!(!dedup.is_empty());

        dedup.clear();
        assert!(dedup.is_empty());
        assert!(!dedup.has_seen("test"));
    }

    #[test]
    fn test_capacity_eviction() {
        let mut dedup = Deduplicator::new(2);

        dedup.is_duplicate("a");
        dedup.is_duplicate("b");
        assert_eq!(dedup.len(), 2);

        dedup.is_duplicate("c"); // Should evict "a"
        assert_eq!(dedup.len(), 2);
        assert!(!dedup.has_seen("a"));
        assert!(dedup.has_seen("b"));
        assert!(dedup.has_seen("c"));
    }

    // ========== LruCache Tests ==========

    #[test]
    fn test_lru_basic_put_get() {
        let mut cache = LruCache::new(10);

        cache.put("key1", 1);
        cache.put("key2", 2);

        assert_eq!(cache.get("key1"), Some(1));
        assert_eq!(cache.get("key2"), Some(2));
        assert_eq!(cache.get("key3"), None);
    }

    #[test]
    fn test_lru_has() {
        let mut cache = LruCache::new(10);

        cache.put("exists", 1);

        assert!(cache.has("exists"));
        assert!(!cache.has("missing"));
    }

    #[test]
    fn test_lru_eviction_at_capacity() {
        let mut cache = LruCache::new(3);

        cache.put("a", 1);
        cache.put("b", 2);
        cache.put("c", 3);

        // All three should exist
        assert!(cache.has("a"));
        assert!(cache.has("b"));
        assert!(cache.has("c"));

        // Add fourth, should evict "a" (oldest)
        cache.put("d", 4);

        assert!(!cache.has("a")); // Evicted
        assert!(cache.has("b"));
        assert!(cache.has("c"));
        assert!(cache.has("d"));
    }

    #[test]
    fn test_lru_update_existing_key() {
        let mut cache = LruCache::new(3);

        cache.put("a", 1);
        cache.put("b", 2);
        cache.put("c", 3);

        // Update "a" - should NOT change order
        cache.put("a", 100);

        assert_eq!(cache.get("a"), Some(100));

        // Add new key, should still evict "a" (oldest by insertion)
        cache.put("d", 4);

        // Updating doesn't refresh position, so "a" should be evicted
        assert!(!cache.has("a"));
    }

    #[test]
    fn test_lru_remove() {
        let mut cache = LruCache::new(10);

        cache.put("a", 1);
        cache.put("b", 2);

        assert!(cache.has("a"));
        cache.remove("a");
        assert!(!cache.has("a"));
        assert!(cache.has("b"));
    }

    #[test]
    fn test_lru_clear() {
        let mut cache = LruCache::new(10);

        cache.put("a", 1);
        cache.put("b", 2);

        assert_eq!(cache.len(), 2);
        cache.clear();
        assert_eq!(cache.len(), 0);
        assert!(cache.is_empty());
    }

    #[test]
    fn test_lru_zero_capacity() {
        let mut cache = LruCache::new(0);

        // With zero capacity, nothing should be stored
        cache.put("a", 1);
        assert!(!cache.has("a"));
    }

    #[test]
    fn test_lru_len() {
        let mut cache = LruCache::new(10);

        assert_eq!(cache.len(), 0);
        cache.put("a", 1);
        assert_eq!(cache.len(), 1);
        cache.put("b", 2);
        assert_eq!(cache.len(), 2);
    }

    #[test]
    fn test_lru_multiple_evictions() {
        let mut cache = LruCache::new(2);

        cache.put("a", 1);
        cache.put("b", 2);
        cache.put("c", 3); // Evicts "a"
        cache.put("d", 4); // Evicts "b"

        assert!(!cache.has("a"));
        assert!(!cache.has("b"));
        assert!(cache.has("c"));
        assert!(cache.has("d"));
        assert_eq!(cache.len(), 2);
    }

    #[test]
    fn test_lru_remove_then_add() {
        let mut cache = LruCache::new(3);

        cache.put("a", 1);
        cache.put("b", 2);
        cache.remove("a");

        // Should have room for "a" again
        cache.put("a", 10);
        assert_eq!(cache.get("a"), Some(10));
        assert_eq!(cache.len(), 2);
    }

    #[test]
    fn test_lru_single_capacity() {
        let mut cache = LruCache::new(1);

        cache.put("a", 1);
        assert!(cache.has("a"));

        cache.put("b", 2);
        assert!(!cache.has("a")); // Evicted
        assert!(cache.has("b"));
    }

    #[test]
    fn test_lru_empty_operations() {
        let mut cache = LruCache::new(10);

        assert!(cache.is_empty());
        assert_eq!(cache.len(), 0);
        assert_eq!(cache.get("missing"), None);
        assert!(!cache.has("missing"));

        // Remove on empty cache should not panic
        cache.remove("missing");
        assert!(cache.is_empty());

        // Clear on empty cache should not panic
        cache.clear();
        assert!(cache.is_empty());
    }
}