orthrus_core/identify.rs
1//! Identification system that allows types to return information if they recognize a given type.
2//!
3//! This has two systems: basic identification, which should only perform operations if they won't
4//! take a significant amount of time, and "deep identification", which is allowed to perform any
5//! computation even if it may take multiple seconds, along with allowing recursion into nested
6//! types.
7
8#[cfg(not(feature = "std"))]
9use crate::no_std::*;
10
11/// Contains the relevant file info to return after identification.
12#[derive(Default)]
13#[non_exhaustive]
14pub struct FileInfo {
15 /// Contains plaintext info about the type, if recognized.
16 pub info: String,
17 /// Used for returning any inner data if using deep identification.
18 pub payload: Option<Box<[u8]>>,
19}
20
21impl FileInfo {
22 /// Creates a new instance to return information about a file.
23 #[must_use]
24 #[inline]
25 pub const fn new(info: String, payload: Option<Box<[u8]>>) -> Self {
26 Self { info, payload }
27 }
28}
29
30/// Trait that allows for identifying if a byte slice is of the same format as the type.
31pub trait FileIdentifier {
32 /// Attempts to identify a specific type, and return human-readable info about it.
33 #[must_use]
34 fn identify(data: &[u8]) -> Option<FileInfo>;
35
36 /// Attempts to identify a specific type and any sub-type, and return human-readable info about
37 /// it.
38 #[must_use]
39 #[inline]
40 fn identify_deep(data: &[u8]) -> Option<FileInfo> {
41 Self::identify(data)
42 }
43}
44
45/// Type alias for [`identify`](FileIdentifier::identify) and
46/// [`identify_deep`](FileIdentifier::identify_deep).
47pub type IdentifyFn = fn(&[u8]) -> Option<FileInfo>;