content_scan 0.2.2

An extensible, plugin-based framework for identifying, analyzing, and recursively extracting structured content from arbitrary bytes.
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
use super::{
    analyzer_list::AnalyzerList, extractor_list::ExtractorList, AnalysisOutcome, Content, ContentAnalyzer, ContentExtractor, ContentIdentifier,
    ContentType, Filter,
};
use crate::utils;
use crate::ExtractionContext;
use crate::ExtractionRequestMetadata;
use crate::FindingMetadata;
use crate::IdentifierSet;
use crate::NoMetadata;
use crate::Object;
use crate::OwnedContentPtr;
use crate::ScanObserver;
use crate::StopCondition;
use crate::{ContentPtr, Context, ScanResult};
use std::collections::HashSet;
use std::marker::PhantomData;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd)]
enum ScanOutcome {
    Continue,
    Exit,
}

enum RunExtractorsMethod {
    All,
    OnlyRequested,
}

/// The engine that drives a scan.
///
/// A `Scanner` bundles together a set of
/// [`ContentIdentifier`](crate::ContentIdentifier)s,
/// [`ContentAnalyzer`](crate::ContentAnalyzer)s,
/// [`ContentExtractor`](crate::ContentExtractor)s, an optional
/// [`Filter`], and a maximum recursion depth. Build one with
/// [`ScannerBuilder`] and drive scans with [`Scanner::scan`].
///
/// The `M` type parameter is the [`FindingMetadata`](crate::FindingMetadata)
/// stored on each [`Finding`](crate::Finding). It is chosen when the
/// builder is constructed ([`ScannerBuilder::new`] for
/// [`NoMetadata`](crate::NoMetadata), or
/// [`ScannerBuilder::with_metadata`] for a custom type).
///
/// Scanners are reusable: the internal [`Context`] is cleared at the
/// start of every [`scan`](Self::scan) call, so a single instance can
/// process many independent inputs sequentially.
pub struct Scanner<T: ContentType, M: FindingMetadata> {
    filter: Option<Filter>,
    identifiers: IdentifierSet<T>,
    analyzers: AnalyzerList<Box<dyn ContentAnalyzer<T, M>>>,
    extractors: ExtractorList<Box<dyn ContentExtractor<T>>, T>,
    context: Context<T, M>,
    stop_condition: Option<Box<dyn StopCondition>>,
    max_depth: u32,
    max_change_type: u32,
}
impl<T: ContentType, M: FindingMetadata> Scanner<T, M> {
    /// Scans a single top-level [`Content`] and returns the results.
    ///
    /// The scanner:
    ///
    /// 1. Clears its internal [`Context`] so that no state leaks
    ///    between calls.
    /// 2. Applies the configured [`Filter`], if any, to the top-level
    ///    content — but only when `filter_root` is `true`. If the
    ///    filter rejects it, the returned [`ScanResult`] contains no
    ///    objects.
    /// 3. Recursively identifies, analyzes, and extracts nested
    ///    content up to the configured
    ///    [`max_depth`](ScannerBuilder::max_depth).
    ///
    /// Pass `filter_root = false` when the root is a container the
    /// filter was not written to accept, such as a
    /// [`FolderContent`](crate::FolderContent) scanned with a filter
    /// that only allows certain file extensions. Extracted children
    /// are filtered either way, unless their
    /// [`Entry`](crate::Entry) sets `skip_from_filtering`.
    ///
    /// The returned [`ScanResult`] borrows from `self` and stays
    /// valid until the next call on this scanner. It includes the
    /// object tree, global / local [`VarMap`](varmap::VarMap)s, and
    /// every [`Finding`](crate::Finding) recorded via
    /// [`Context::add_finding`]. Copy anything you need to keep out
    /// before starting another scan.
    pub fn scan<'a>(&'a mut self, content: &mut dyn Content<T>, filter_root: bool) -> ScanResult<'a, T, M> {
        self.context.clear();
        if let Some(observer) = self.context.observer.as_mut() {
            observer.on_begin(content.path().as_printable_string());
        }
        if filter_root {
            if let Some(filter) = self.filter.as_mut() {
                if !filter.should_process(content.path(), content.size()) {
                    if let Some(observer) = self.context.observer.as_mut() {
                        observer.on_filtered(content.path().as_printable_string());
                        observer.on_end();
                    }
                    return ScanResult::new(&self.context);
                }
            }
        }
        let cptr = ContentPtr::new(content);
        self.inner_scan(cptr, 1, Object::INVALID_INDEX);
        if let Some(observer) = self.context.observer.as_mut() {
            observer.on_end();
        }
        ScanResult::new(&self.context)
    }
    fn inner_scan(&mut self, content: ContentPtr<T>, depth: u32, parent_index: u32) -> ScanOutcome {
        self.context.local_varmap_handle = None; // so that next time someone ask for a local varmap, it will get one from the context varmap_pool
        self.context.current_object_index = None;
        let start_req_count = self.context.extraction_requests_stack.len();
        if let Some(stop_condition) = self.stop_condition.as_mut() {
            if stop_condition.should_stop() {
                return ScanOutcome::Exit;
            }
        }
        let (ty, my_index) = self.create_object(content, parent_index);
        let result = self.scan_object(content, ty, depth, my_index, start_req_count, 0);
        self.restore_extraction_request_stack(start_req_count);
        result
    }

    fn scan_object(
        &mut self,
        mut content: ContentPtr<T>,
        ty: Option<T>,
        depth: u32,
        my_index: u32,
        start_req_count: usize,
        change_type_count: u32,
    ) -> ScanOutcome {
        if let Some(observer) = self.context.observer.as_mut() {
            observer.on_scan_object(content.as_ref().path().as_printable_string(), ty);
        }
        let analysis_outcome = self.run_analyzers(content, ty);
        let result = match analysis_outcome {
            AnalysisOutcome::Continue => self.run_extractors(content, ty, depth, my_index, start_req_count, RunExtractorsMethod::All),
            AnalysisOutcome::Skip => ScanOutcome::Continue,
            AnalysisOutcome::Exit => ScanOutcome::Exit,
            AnalysisOutcome::ReprocessAsType(new_ty) => {
                let extr_response = self.run_extractors(content, ty, depth, my_index, start_req_count, RunExtractorsMethod::OnlyRequested);
                self.restore_extraction_request_stack(start_req_count);
                match extr_response {
                    ScanOutcome::Exit => ScanOutcome::Exit,
                    ScanOutcome::Continue => {
                        if change_type_count < self.max_change_type {
                            content.as_mut().set_content_type(new_ty);
                            let parent_local = if let Some(obj) = self.context.objects.get_mut(my_index as usize) {
                                obj.type_id = new_ty.as_u16();
                                obj.varmap_handle
                            } else {
                                None
                            };
                            // OnlyRequested children leave current_object_index on the last child.
                            // Re-analysis must write findings/maps onto this same node.
                            self.context.current_object_index = Some(my_index);
                            self.context.local_varmap_handle = parent_local;
                            self.scan_object(content, Some(new_ty), depth, my_index, start_req_count, change_type_count + 1)
                        } else {
                            ScanOutcome::Continue
                        }
                    }
                }
            }
        };
        result
    }

    fn create_object(&mut self, content: ContentPtr<T>, parent_index: u32) -> (Option<T>, u32) {
        let ty = self.retrieve_content_type(content);

        let path_index = self.context.path_arena.alloc(content.as_ref().path().as_printable_string().as_bytes());
        let obj = Object {
            path: path_index,
            parent_index,
            next_sibling_index: Object::INVALID_INDEX,
            varmap_handle: None,
            first_child_index: Object::INVALID_INDEX,
            last_child_index: Object::INVALID_INDEX,
            type_id: if let Some(ty) = ty { ty.as_u16() } else { u16::MAX },
        };
        let my_index = self.context.objects.len() as u32;
        self.context.objects.push(obj);
        self.context.current_object_index = Some(my_index);
        // links to parent and sibling
        let mut last_sibling_index = Object::INVALID_INDEX;
        if parent_index != Object::INVALID_INDEX {
            if let Some(parent) = self.context.objects.get_mut(parent_index as usize) {
                if parent.first_child_index == Object::INVALID_INDEX {
                    parent.first_child_index = my_index;
                } else {
                    last_sibling_index = parent.last_child_index;
                }
                parent.last_child_index = my_index;
                //println!("Parent: {}, Me: {}, First: {}, Last: {} -> {}", parent_index, my_index, parent.first_child_index, parent.last_child_index, content.path());
            }
        }
        if last_sibling_index != Object::INVALID_INDEX {
            if let Some(last_sibling) = self.context.objects.get_mut(last_sibling_index as usize) {
                last_sibling.next_sibling_index = my_index;
            }
        }
        (ty, my_index)
    }
    fn run_analyzers(&mut self, content: ContentPtr<T>, content_type: Option<T>) -> AnalysisOutcome<T> {
        if let Some(ty) = content_type {
            if let Some((start, end)) = self.analyzers.range(ty) {
                let res = self.scan_range(content, start, end);
                if matches!(res, AnalysisOutcome::Skip | AnalysisOutcome::Exit | AnalysisOutcome::ReprocessAsType(_)) {
                    return res;
                }
            }
        }
        // generic analyzers
        if let Some((start, end)) = self.analyzers.generic_range() {
            let res = self.scan_range(content, start, end);
            if matches!(res, AnalysisOutcome::Skip | AnalysisOutcome::Exit) {
                return res;
            }
        }
        AnalysisOutcome::Continue
    }
    fn run_extractors(
        &mut self,
        content: ContentPtr<T>,
        content_type: Option<T>,
        depth: u32,
        my_index: u32,
        start_req_index: usize,
        method: RunExtractorsMethod,
    ) -> ScanOutcome {
        // type-specific extractors (only if method is All)
        if matches!(method, RunExtractorsMethod::All) {
            if let Some(ty) = content_type {
                if let Some((start, end)) = self.extractors.range(ty) {
                    let res = self.extract_range(content, start, end, depth, my_index, None);
                    if matches!(res, ScanOutcome::Exit) {
                        return res;
                    }
                }
            }
        }
        // run extraction requests (for both All and OnlyRequested methods)
        let req_count = self.context.extraction_requests_stack.len();
        for i in start_req_index..req_count {
            let ty = self.context.extraction_requests_stack[i].content_type;
            if let Some((start, end)) = self.extractors.range(ty) {
                let res = self.extract_range(content, start, end, depth, my_index, Some(i as u32));
                if matches!(res, ScanOutcome::Exit) {
                    return res;
                }
            } else {
                if let Some(handle) = self.context.extraction_requests_stack[i].params_handle {
                    self.context.varmap_pool.release(handle);
                    self.context.extraction_requests_stack[i].params_handle = None;
                }
            }
        }
        ScanOutcome::Continue
    }
    fn restore_extraction_request_stack(&mut self, start_req_index: usize) {
        // first release the params
        for req in self.context.extraction_requests_stack.iter_mut().skip(start_req_index) {
            if let Some(handle) = req.params_handle {
                self.context.varmap_pool.release(handle);
            }
        }
        // restore the stack
        self.context.extraction_requests_stack.truncate(start_req_index);
    }
    fn scan_range(&mut self, mut content: ContentPtr<T>, start: usize, end: usize) -> AnalysisOutcome<T> {
        if (end <= start) || (end > self.analyzers.len()) {
            return AnalysisOutcome::Continue;
        }
        for i in start..end {
            let result = unsafe { self.analyzers.get(i).analyze(content.as_mut(), &mut self.context) };
            match result {
                AnalysisOutcome::Continue => continue,
                AnalysisOutcome::Exit => return AnalysisOutcome::Exit,
                AnalysisOutcome::Skip => return AnalysisOutcome::Skip,
                AnalysisOutcome::ReprocessAsType(ty) => return AnalysisOutcome::ReprocessAsType(ty),
            }
        }
        AnalysisOutcome::Continue
    }
    fn extract_range(
        &mut self,
        content: ContentPtr<T>,
        start: usize,
        end: usize,
        depth: u32,
        parent_index: u32,
        req_index: Option<u32>,
    ) -> ScanOutcome {
        if (end <= start) || (end > self.extractors.len()) {
            return ScanOutcome::Continue;
        }
        let ec_metadata = if let Some(req_index) = req_index {
            let request = &self.context.extraction_requests_stack[req_index as usize];
            ExtractionRequestMetadata {
                start: request.start,
                len: request.len,
                params_handle: request.params_handle,
            }
        } else {
            ExtractionRequestMetadata {
                start: 0,
                len: Some(content.as_ref().size()),
                params_handle: None,
            }
        };
        let next_action = {
            let mut next_action = ScanOutcome::Continue;
            for i in start..end {
                let result = self.extract_content(content, i, depth, parent_index, &ec_metadata);
                match result {
                    ScanOutcome::Continue => continue,
                    ScanOutcome::Exit => {
                        next_action = result;
                        break;
                    }
                }
            }
            next_action
        };
        if let Some(handle) = ec_metadata.params_handle {
            self.context.varmap_pool.release(handle);
            if let Some(req_index) = req_index {
                self.context.extraction_requests_stack[req_index as usize].params_handle = None;
            }
        }
        next_action
    }
    fn extract_content(
        &mut self,
        content: ContentPtr<T>,
        index: usize,
        depth: u32,
        parent_index: u32,
        ec_metadata: &ExtractionRequestMetadata,
    ) -> ScanOutcome {
        if depth >= self.max_depth {
            return ScanOutcome::Continue;
        }
        let len = self.extractors.len();
        if index >= len {
            return ScanOutcome::Continue;
        }
        let extractor = unsafe { self.extractors.get(index) };
        let ec = ExtractionContext {
            offset: ec_metadata.start,
            length: ec_metadata.len,
            params: ec_metadata.params_handle.and_then(|h| self.context.varmap_pool.get(h)),
        };
        let session = extractor.create_session(OwnedContentPtr::new(content), &ec);
        if let Some(mut session) = session {
            while let Some(entry) = session.advance() {
                if !entry.skip_from_filtering {
                    if let Some(filter) = self.filter.as_mut() {
                        if !filter.should_process(&entry.path, entry.size) {
                            if let Some(observer) = self.context.observer.as_mut() {
                                observer.on_filtered(entry.path.as_printable_string());
                            }
                            continue;
                        }
                    }
                }
                if let Some(observer) = self.context.observer.as_mut() {
                    observer.on_extraction(content.as_ref().path().as_printable_string(), entry);
                }
                if let Some(mut extracted_content) = session.extract() {
                    let c_ptr = ContentPtr::new(extracted_content.as_mut());
                    let result = self.inner_scan(c_ptr, depth + 1, parent_index);
                    match result {
                        ScanOutcome::Continue => continue,
                        ScanOutcome::Exit => return ScanOutcome::Exit,
                    }
                }
            }
        }
        ScanOutcome::Continue
    }
    fn retrieve_content_type(&mut self, mut content: ContentPtr<T>) -> Option<T> {
        if let Some(ty) = content.as_ref().content_type() {
            return Some(ty);
        }
        let p = content.as_ref().path().as_bytes();
        let file_name = utils::get_file_name(p);
        let type_from_file_name = self.identifiers.type_from_file_name(file_name);
        let extension = utils::get_extension(file_name);
        let type_from_extension = self.identifiers.type_from_extension(extension);
        let type_from_magic = if self.identifiers.has_magic() {
            if let Some(buf) = content.as_mut().read(0, 16) {
                self.identifiers.type_from_magic(buf)
            } else {
                None
            }
        } else {
            None
        };
        if let Some(ty) = type_from_magic {
            if self.validate_content_type(content, ty) {
                return Some(ty);
            }
        }
        if let Some(ty) = type_from_file_name {
            if self.validate_content_type(content, ty) {
                return Some(ty);
            }
        }
        if let Some(ty) = type_from_extension {
            if self.validate_content_type(content, ty) {
                return Some(ty);
            }
        }
        self.identifiers
            .identifiers_without_prefilter()
            .iter()
            .find(|&&ty| self.validate_content_type(content, ty))
            .copied()
    }
    #[inline(always)]
    fn validate_content_type(&self, mut content: ContentPtr<T>, content_type: T) -> bool {
        self.identifiers
            .get(content_type)
            .map(|identifier| identifier.validate(content.as_mut()))
            .unwrap_or(false)
    }
}
/// Fluent builder for [`Scanner`].
///
/// Register identifiers, analyzers, extractors, and (optionally) a
/// [`Filter`] with the `add_*` / [`filter`](Self::filter) methods,
/// then call [`build`](Self::build) to obtain a ready-to-use
/// [`Scanner`]. Attach a [`ScanObserver`](crate::ScanObserver) or
/// [`StopCondition`](crate::StopCondition) with
/// [`observer`](Self::observer) /
/// [`stop_condition`](Self::stop_condition). Findings are stored for
/// [`ScanResult::findings`](crate::ScanResult::findings) by default;
/// turn that off with [`store_findings`](Self::store_findings).
///
/// The `M` type parameter is the [`FindingMetadata`](crate::FindingMetadata)
/// stored on each [`Finding`](crate::Finding). [`new`](Self::new)
/// produces a builder with [`NoMetadata`](crate::NoMetadata). For a
/// custom metadata type, start from [`with_metadata`](Self::with_metadata)
/// so analyzers can implement
/// [`ContentAnalyzer<T, M>`](crate::ContentAnalyzer) and pass `Some(m)`
/// to [`Context::add_finding`](crate::Context::add_finding).
///
/// # Priorities
///
/// Analyzers are registered with a `priority` byte. Within the same
/// [`ContentType`] bucket (or within the generic bucket), they run in
/// **ascending** priority order — lower numbers first.
///
/// Extractors have no priority: multiple extractors for the same type
/// run in registration order.
///
/// # Dependencies
///
/// Every analyzer implements [`Dependencies`](crate::Dependencies)
/// (typically via `#[derive(Dependencies)]`). Its `name` identifies it
/// to other analyzers; `requires` lists names that must run first.
/// In debug builds, [`build`](Self::build) checks that each required
/// name is registered and has a **strictly smaller** `priority`.
/// Names are global across typed and generic analyzers.
///
/// # Generic vs. typed plugins
///
/// - `add_analyzer` registers a plugin against a specific
///   [`ContentType`]. It only runs when the scanner has positively
///   identified content of that type.
/// - `add_extractor` registers a plugin against a specific
///   [`ContentType`]. It runs when the current object is that type,
///   and also when an analyzer requested that type via
///   [`Context::request_extract`](crate::Context::request_extract).
/// - `add_generic_analyzer` registers an analyzer that runs for every
///   content object, regardless of type (including unidentified
///   content). Generic analyzers run after the type-specific ones.
pub struct ScannerBuilder<T: ContentType, M: FindingMetadata = NoMetadata> {
    filter: Option<Filter>,
    analyzers: Vec<(u32, Box<dyn ContentAnalyzer<T, M>>)>,
    extractors: Vec<(T, Box<dyn ContentExtractor<T>>)>,
    identifiers: Vec<(T, Box<dyn ContentIdentifier<T>>)>,
    stop_condition: Option<Box<dyn StopCondition>>,
    observer: Option<Box<dyn ScanObserver<T, M>>>,
    max_depth: u32,
    max_change_type: u32,
    store_findings: bool,
    _metadata: PhantomData<M>,
}
impl<T: ContentType, M: FindingMetadata> ScannerBuilder<T, M> {
    fn empty() -> Self {
        Self {
            filter: None,
            analyzers: Vec::with_capacity(16),
            extractors: Vec::with_capacity(4),
            identifiers: Vec::with_capacity(4),
            stop_condition: None,
            observer: None,
            max_depth: 8,
            max_change_type: 2,
            store_findings: true,
            _metadata: PhantomData,
        }
    }

    /// Attaches a pre-built [`Filter`] to the scanner.
    ///
    /// Extracted children are always tested against the filter
    /// (unless their [`Entry`](crate::Entry) sets
    /// `skip_from_filtering`). The top-level object is tested only
    /// when [`scan`](Scanner::scan) is called with `filter_root =
    /// true`. If a filter was previously set, it is replaced.
    pub fn filter(mut self, filter: Filter) -> Self {
        self.filter = Some(filter);
        self
    }

    /// Registers an analyzer for a specific `content_type`.
    ///
    /// `priority` (`0..=255`) orders analyzers registered for the
    /// same type; lower values run first. Multiple analyzers for the
    /// same `(content_type, priority)` are allowed and their relative
    /// order is unspecified.
    ///
    /// If this analyzer's [`Dependencies`](crate::Dependencies)
    /// `requires` another analyzer, that analyzer must be registered
    /// (typed or generic) with a strictly smaller `priority`. Debug
    /// builds check this in [`build`](Self::build).
    pub fn add_analyzer<A>(mut self, content_type: T, priority: u8, analyzer: A) -> Self
    where
        A: ContentAnalyzer<T, M> + 'static,
    {
        let hash = (content_type.as_u16() as u32) << 16 | priority as u32;
        self.analyzers.push((hash, Box::new(analyzer)));
        self
    }

    /// Registers a generic analyzer that runs on every content object.
    ///
    /// Generic analyzers run after all type-specific analyzers for a
    /// given object. `priority` (`0..=255`) orders generic analyzers
    /// among themselves; lower values run first.
    ///
    /// [`Dependencies`](crate::Dependencies) `requires` names are
    /// resolved against **all** registered analyzers (typed and
    /// generic). Debug builds check this in [`build`](Self::build).
    pub fn add_generic_analyzer<A>(mut self, priority: u8, analyzer: A) -> Self
    where
        A: ContentAnalyzer<T, M> + 'static,
    {
        let hash = 0xFFFF0000 | priority as u32;
        self.analyzers.push((hash, Box::new(analyzer)));
        self
    }

    /// Registers an extractor for a specific `content_type`.
    ///
    /// The extractor runs when the scanner has identified content of
    /// that type, and also when an analyzer requested that type via
    /// [`Context::request_extract`](crate::Context::request_extract).
    /// Multiple extractors for the same type run in registration
    /// order. Extracted children are scanned recursively as long as
    /// [`max_depth`](Self::max_depth) allows.
    pub fn add_extractor<E>(mut self, content_type: T, extractor: E) -> Self
    where
        E: ContentExtractor<T> + 'static,
    {
        self.extractors.push((content_type, Box::new(extractor)));
        self
    }

    /// Registers an identifier for `content_type`.
    ///
    /// Only one identifier is allowed per content type; registering
    /// two identifiers for the same type will cause
    /// [`build`](Self::build) to panic. An [`IdentifyMethod::Magic`](crate::IdentifyMethod::Magic)
    /// or [`IdentifyMethod::MultipleMagic`](crate::IdentifyMethod::MultipleMagic) pattern longer than 16
    /// bytes also panics at build.
    pub fn add_identifier<I>(mut self, content_type: T, identifier: I) -> Self
    where
        I: ContentIdentifier<T> + 'static,
    {
        self.identifiers.push((content_type, Box::new(identifier)));
        self
    }

    /// Sets the maximum recursion depth for the scanner.
    ///
    /// The value is clamped to `1..=u32::MAX - 2`. The top-level
    /// content is at depth `1`; children extracted from it are at
    /// depth `2`, and so on. Extraction stops when the next child
    /// would exceed `max_depth`.
    pub fn max_depth(mut self, max_depth: u32) -> Self {
        self.max_depth = max_depth.clamp(1, u32::MAX - 2);
        self
    }

    /// Sets the maximum number of times a content type can be changed per object.
    ///
    /// The value is clamped to `1..=T::COUNT`.
    ///
    /// This is useful to prevent infinite loops when a content type is changed
    /// to a type that is not supported by the analyzer.
    ///
    /// The default value is **2**.
    pub fn max_change_type(mut self, max_change_type: u32) -> Self {
        self.max_change_type = max_change_type.clamp(1, T::COUNT as u32);
        self
    }

    /// Attaches a [`ScanObserver`](crate::ScanObserver) that receives
    /// callbacks as the scan progresses.
    ///
    /// The observer is notified when a scan begins and ends, when an
    /// object is scanned, when content is filtered out, when a
    /// finding is recorded, and when a child is extracted. All
    /// methods have empty defaults, so an implementation only needs
    /// to override the events it cares about.
    ///
    /// If an observer was previously set, it is replaced. The
    /// observer is owned by the scanner and persists across
    /// [`scan`](Scanner::scan) calls.
    pub fn observer(mut self, observer: impl ScanObserver<T, M> + 'static) -> Self {
        self.observer = Some(Box::new(observer));
        self
    }

    /// Attaches a [`StopCondition`](crate::StopCondition) that can
    /// abort the scan early.
    ///
    /// `should_stop` is checked at the start of every content object,
    /// before identification and analysis. When it returns `true`,
    /// the scanner stops recursing and returns the
    /// [`ScanResult`](crate::ScanResult) accumulated so far.
    ///
    /// If a stop condition was previously set, it is replaced.
    pub fn stop_condition(mut self, stop_condition: impl StopCondition + 'static) -> Self {
        self.stop_condition = Some(Box::new(stop_condition));
        self
    }

    /// Controls whether findings are retained for
    /// [`ScanResult::findings`](crate::ScanResult::findings).
    ///
    /// Defaults to `true`. Set to `false` to skip storing findings
    /// in the result — useful when an [`observer`](Self::observer)
    /// already consumes them and you want to avoid the extra
    /// memory. [`Context::add_finding`](crate::Context::add_finding)
    /// still notifies the observer either way.
    pub fn store_findings(mut self, store_findings: bool) -> Self {
        self.store_findings = store_findings;
        self
    }

    fn check_unique_identifiers(&self) {
        let mut m = HashSet::new();
        for (content_type, _) in &self.identifiers {
            if m.contains(&content_type.as_u16()) {
                panic!(
                    "There can only be one identifier for type ! Type {:?} has multiple identifiers !",
                    content_type
                );
            }
            m.insert(content_type.as_u16());
        }
    }
    #[cfg(debug_assertions)]
    fn check_dependencies(&self) {
        use std::collections::HashMap;

        let mut map = HashMap::new();
        for (hash, analyzer) in &self.analyzers {
            let priority = hash & 0xFFFF;
            let name = analyzer.name();
            map.insert(name, priority);
        }
        // check dependencies
        for (hash, analyzer) in &self.analyzers {
            let priority = hash & 0xFFFF;
            let name = analyzer.name();
            let dep = analyzer.dependencies();
            for d in dep {
                if let Some(dep_priority) = map.get(d) {
                    if *dep_priority >= priority {
                        panic!("Analizer {} requiers dependecy {} to have a priority smaller than his. ", name, *d);
                    }
                } else {
                    panic!("Dependency {} not found for analyzer {}", d, name);
                }
            }
        }
    }
    /// Consumes the builder and produces a ready-to-use [`Scanner`].
    ///
    /// # Panics
    ///
    /// Panics if two identifiers are registered for the same
    /// [`ContentType`], or if an [`IdentifyMethod::Magic`](crate::IdentifyMethod::Magic) /
    /// [`IdentifyMethod::MultipleMagic`](crate::IdentifyMethod::MultipleMagic) pattern is longer than 16
    /// bytes.
    ///
    /// In debug builds, also panics if an analyzer's
    /// [`Dependencies`](crate::Dependencies) `requires` a name that is
    /// not registered, or if a required analyzer does not have a
    /// strictly smaller `priority`.
    pub fn build(self) -> Scanner<T, M> {
        self.check_unique_identifiers();
        #[cfg(debug_assertions)]
        self.check_dependencies();
        let analyzers = AnalyzerList::new(self.analyzers, T::COUNT);
        let extractors = ExtractorList::new(self.extractors);
        let identifiers = IdentifierSet::new(self.identifiers);
        Scanner {
            filter: self.filter,
            identifiers,
            analyzers,
            extractors,
            context: Context::new(self.observer, self.store_findings),
            max_depth: self.max_depth,
            stop_condition: self.stop_condition,
            max_change_type: self.max_change_type,
        }
    }
}
impl<T: ContentType> ScannerBuilder<T, NoMetadata> {
    /// Creates a new, empty builder with sensible defaults.
    ///
    /// The default maximum recursion depth is `8`. Change it with
    /// [`max_depth`](Self::max_depth).
    ///
    /// Defined only for [`NoMetadata`] so `ScannerBuilder::new()` can
    /// infer `M`. For a custom metadata type, use
    /// [`with_metadata`](Self::with_metadata).
    pub fn new() -> Self {
        Self::empty()
    }

    /// Creates an empty builder whose findings carry metadata of type `M`.
    ///
    /// Use this instead of [`new`](Self::new) when analyzers attach
    /// typed extras (severity, offset, rule id, …) via
    /// [`Context::add_finding`](crate::Context::add_finding). `M` must
    /// implement [`FindingMetadata`](crate::FindingMetadata).
    ///
    /// ```ignore
    /// #[derive(Copy, Clone)]
    /// enum Severity { Info, Warn }
    /// impl FindingMetadata for Severity {}
    ///
    /// let mut scanner = ScannerBuilder::<MyTypes>::with_metadata::<Severity>()
    ///     .add_generic_analyzer(0, MyAnalyzer {})
    ///     .build();
    /// ```
    pub fn with_metadata<M: FindingMetadata>() -> ScannerBuilder<T, M> {
        ScannerBuilder::empty()
    }
}

impl<T: ContentType, M: FindingMetadata> Default for ScannerBuilder<T, M> {
    fn default() -> Self {
        Self::empty()
    }
}