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
//! A simple library for fast inspection of binary buffers to guess/determine the type of content.
//!
//! This is mainly intended to quickly determine whether a given buffer contains "binary" or "text"
//! data. The analysis is based on a very simple heuristic: Detection of special [byte order
//! marks](https://en.wikipedia.org/wiki/Byte_order_mark) and searching for NULL bytes. Note that
//! this analysis can fail. For example, even if unlikely, UTF-8-encoded text can legally contain
//! NULL bytes. Also, for performance reasons, only the first *1024* bytes are checked for the
//! NULL-byte (if no BOM) is detected.

extern crate memchr;

use memchr::memchr;
use std::cmp::min;
use std::fmt;

const MAX_SCAN_SIZE: usize = 1024;

/// The type of encoding that was detected (for "text" data) or `BINARY` for "binary" data.
#[allow(non_camel_case_types)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum ContentType {
    /// "binary" data
    BINARY,

    /// UTF-8 encoded "text" data
    UTF_8,

    /// UTF-8 encoded "text" data with a byte order mark.
    UTF_8_BOM,

    /// UTF-16 encoded "text" data (little endian)
    UTF_16LE,

    /// UTF-16 encoded "text" data (big endian)
    UTF_16BE,

    /// UTF-32 encoded "text" data (little endian)
    UTF_32LE,

    /// UTF-32 encoded "text" data (big endian)
    UTF_32BE,
}

impl ContentType {
    /// Returns `true`, if the `ContentType` is `BINARY`.
    pub fn is_binary(self) -> bool {
        self == ContentType::BINARY
    }

    /// Returns `true`, if the `ContentType` is __not__ `BINARY`.
    pub fn is_text(self) -> bool {
        !self.is_binary()
    }
}

impl fmt::Display for ContentType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use ContentType::*;

        let name: &str = match *self {
            BINARY => "binary",
            UTF_8 => "UTF-8",
            UTF_8_BOM => "UTF-8-BOM",
            UTF_16LE => "UTF-16LE",
            UTF_16BE => "UTF-16BE",
            UTF_32LE => "UTF-32LE",
            UTF_32BE => "UTF-32BE",
        };
        write!(f, "{}", name)
    }
}

/// Common byte order marks
/// (see https://en.wikipedia.org/wiki/Byte_order_mark)
static BYTE_ORDER_MARKS: &[(&[u8], ContentType)] = &[
    (&[0xEF, 0xBB, 0xBF], ContentType::UTF_8_BOM),
    // UTF-32 needs to be checked before UTF-16 (overlapping BOMs)
    (&[0x00, 0x00, 0xFE, 0xFF], ContentType::UTF_32BE),
    (&[0xFF, 0xFE, 0x00, 0x00], ContentType::UTF_32LE),
    (&[0xFE, 0xFF], ContentType::UTF_16BE),
    (&[0xFF, 0xFE], ContentType::UTF_16LE),
];

/// PDF header
static MAGIC_NUMBER_PDF: &[u8] = b"%PDF";

/// Try to determine (or rather: guess) the type of content in the given buffer. See the
/// documentation of the crate for more information about how the analysis is done.
///
/// If the buffer is empty, the content type will be reported as `UTF_8`.
///
/// ```rust
/// use content_inspector::{ContentType, inspect};
///
/// assert_eq!(ContentType::UTF_8, inspect(b"Hello"));
/// assert_eq!(ContentType::BINARY, inspect(b"\xFF\xE0\x00\x10\x4A\x46\x49\x46\x00"));
///
/// assert!(inspect(b"Hello").is_text());
/// ```
pub fn inspect(buffer: &[u8]) -> ContentType {
    use ContentType::*;

    for (bom, content_type) in BYTE_ORDER_MARKS {
        if buffer.starts_with(bom) {
            return *content_type;
        }
    }

    // Scan the first few bytes for zero-bytes
    let scan_size = min(buffer.len(), MAX_SCAN_SIZE);
    let has_zero_bytes = memchr(0x00, &buffer[..scan_size]).is_some();

    if has_zero_bytes {
        return BINARY;
    }

    if buffer.starts_with(MAGIC_NUMBER_PDF) {
        return BINARY;
    }

    UTF_8
}

#[cfg(test)]
mod tests {
    use {inspect, ContentType::*};

    #[test]
    fn test_empty_buffer_utf_8() {
        assert_eq!(UTF_8, inspect(b""));
    }

    #[test]
    fn test_text_simple() {
        assert_eq!(UTF_8, inspect("Simple UTF-8 string ☔".as_bytes()));
    }

    #[test]
    fn test_text_utf8() {
        assert_eq!(UTF_8, inspect(include_bytes!("../testdata/text_UTF-8.txt")));
    }

    #[test]
    fn test_text_utf8_bom() {
        assert_eq!(UTF_8_BOM, inspect(include_bytes!("../testdata/text_UTF-8-BOM.txt")));
    }

    #[test]
    fn test_text_utf16le() {
        assert_eq!(
            UTF_16LE,
            inspect(include_bytes!("../testdata/text_UTF-16LE-BOM.txt"))
        );
    }

    #[test]
    fn test_text_utf16be() {
        assert_eq!(
            UTF_16BE,
            inspect(include_bytes!("../testdata/text_UTF-16BE-BOM.txt"))
        );
    }

    #[test]
    fn test_text_utf32le() {
        assert_eq!(
            UTF_32LE,
            inspect(include_bytes!("../testdata/text_UTF-32LE-BOM.txt"))
        );
    }

    #[test]
    fn test_text_utf32be() {
        assert_eq!(
            UTF_32BE,
            inspect(include_bytes!("../testdata/text_UTF-32BE-BOM.txt"))
        );
    }

    #[test]
    fn test_png() {
        assert_eq!(BINARY, inspect(include_bytes!("../testdata/test.png")));
    }

    #[test]
    fn test_jpg() {
        assert_eq!(BINARY, inspect(include_bytes!("../testdata/test.jpg")));
    }

    #[test]
    fn test_pdf() {
        assert_eq!(BINARY, inspect(include_bytes!("../testdata/test.pdf")));
    }

    #[test]
    fn test_is_text() {
        assert!(UTF_8.is_text());
        assert!(UTF_32LE.is_text());
    }

    #[test]
    fn test_is_binary() {
        assert!(BINARY.is_binary());
    }
}