file_format/
lib.rs

1/*!
2Crate for determining the file format of a [given file](`FileFormat::from_file`) or stream.
3
4It provides a variety of functions for identifying a wide range of file formats, including
5[ZIP](`FileFormat::Zip`), [Compound File Binary (CFB)](`FileFormat::CompoundFileBinary`),
6[Extensible Markup Language (XML)](`FileFormat::ExtensibleMarkupLanguage`) and [more](`FileFormat`).
7
8It checks the signature of the file to determine its format and intelligently employs specific
9readers when available for accurate identification. If the signature is not recognized, the crate
10falls back to the [default](`FileFormat::default`) file format, which is
11[Arbitrary Binary Data (BIN)](`FileFormat::ArbitraryBinaryData`).
12
13# Examples
14
15Determines from a file:
16
17```no_run
18use file_format::{FileFormat, Kind};
19
20let fmt = FileFormat::from_file("fixtures/document/sample.pdf")?;
21assert_eq!(fmt, FileFormat::PortableDocumentFormat);
22assert_eq!(fmt.name(), "Portable Document Format");
23assert_eq!(fmt.short_name(), Some("PDF"));
24assert_eq!(fmt.media_type(), "application/pdf");
25assert_eq!(fmt.extension(), "pdf");
26assert_eq!(fmt.kind(), Kind::Document);
27# Ok::<(), std::io::Error>(())
28```
29
30Determines from bytes:
31
32```
33use file_format::{FileFormat, Kind};
34
35let fmt = FileFormat::from_bytes(&[0xFF, 0xD8, 0xFF]);
36assert_eq!(fmt, FileFormat::JointPhotographicExpertsGroup);
37assert_eq!(fmt.name(), "Joint Photographic Experts Group");
38assert_eq!(fmt.short_name(), Some("JPEG"));
39assert_eq!(fmt.media_type(), "image/jpeg");
40assert_eq!(fmt.extension(), "jpg");
41assert_eq!(fmt.kind(), Kind::Image);
42```
43
44# Crate features
45
46All features below are disabled by default.
47
48## Reader features
49
50These features enable the detection of file formats that require a specific reader for
51identification.
52
53- `reader` - Enables all reader features.
54- `reader-asf` - Enables [Advanced Systems Format (ASF)](`FileFormat::AdvancedSystemsFormat`) based
55  file formats detection.
56  * [Microsoft Digital Video Recording (DVR-MS)](`FileFormat::MicrosoftDigitalVideoRecording`)
57  * [Windows Media Audio (WMA)](`FileFormat::WindowsMediaAudio`)
58  * [Windows Media Video (WMV)](`FileFormat::WindowsMediaVideo`)
59- `reader-cfb` - Enables [Compound File Binary (CFB)](`FileFormat::CompoundFileBinary`) based file
60  formats detection.
61  * [3D Studio Max (MAX)](`FileFormat::ThreeDimensionalStudioMax`)
62  * [Autodesk Inventor Assembly (IAM)](`FileFormat::AutodeskInventorAssembly`)
63  * [Autodesk Inventor Drawing (IDW)](`FileFormat::AutodeskInventorDrawing`)
64  * [Autodesk Inventor Part (IPT)](`FileFormat::AutodeskInventorPart`)
65  * [Autodesk Inventor Presentation (IPN)](`FileFormat::AutodeskInventorPresentation`)
66  * [Corel Presentations 7 (SHW)](`FileFormat::CorelPresentations7`)
67  * [Flash Project (FLA)](`FileFormat::FlashProject`)
68  * [Microsoft Excel Spreadsheet (XLS)](`FileFormat::MicrosoftExcelSpreadsheet`)
69  * [Microsoft PowerPoint Presentation (PPT)](`FileFormat::MicrosoftPowerpointPresentation`)
70  * [Microsoft Project Plan (MPP)](`FileFormat::MicrosoftProjectPlan`)
71  * [Microsoft Publisher Document (PUB)](`FileFormat::MicrosoftPublisherDocument`)
72  * [Microsoft Software Installer (MSI)](`FileFormat::MicrosoftSoftwareInstaller`)
73  * [Microsoft Visio Drawing (VSD)](`FileFormat::MicrosoftVisioDrawing`)
74  * [Microsoft Word Document (DOC)](`FileFormat::MicrosoftWordDocument`)
75  * [Microsoft Works 6 Spreadsheet (XLR)](`FileFormat::MicrosoftWorks6Spreadsheet`)
76  * [Microsoft Works Database (WDB)](`FileFormat::MicrosoftWorksDatabase`)
77  * [Microsoft Works Word Processor (WPS)](`FileFormat::MicrosoftWorksWordProcessor`)
78  * [SolidWorks Assembly (SLDASM)](`FileFormat::SolidworksAssembly`)
79  * [SolidWorks Drawing (SLDDRW)](`FileFormat::SolidworksDrawing`)
80  * [SolidWorks Part (SLDPRT)](`FileFormat::SolidworksPart`)
81  * [StarCalc (SDC)](`FileFormat::Starcalc`)
82  * [StarChart (SDS)](`FileFormat::Starchart`)
83  * [StarDraw (SDA)](`FileFormat::Stardraw`)
84  * [StarImpress (SDD)](`FileFormat::Starimpress`)
85  * [StarMath (SMF)](`FileFormat::Starmath`)
86  * [StarWriter (SDW)](`FileFormat::Starwriter`)
87  * [WordPerfect Document (WPD)](`FileFormat::WordperfectDocument`)
88  * [WordPerfect Graphics (WPG)](`FileFormat::WordperfectGraphics`)
89- `reader-ebml` - Enables [Extensible Binary Meta Language (EBML)](`FileFormat::ExtensibleBinaryMetaLanguage`)
90  based file formats detection.
91  * [Matroska 3D Video (MK3D)](`FileFormat::Matroska3dVideo`)
92  * [Matroska Audio (MKA)](`FileFormat::MatroskaAudio`)
93  * [Matroska Subtitles (MKS)](`FileFormat::MatroskaSubtitles`)
94  * [Matroska Video (MKV)](`FileFormat::MatroskaVideo`)
95  * [WebM](`FileFormat::Webm`)
96- `reader-exe` - Enables [MS-DOS Executable (EXE)](`FileFormat::MsDosExecutable`) based file formats
97  detection.
98  * [Dynamic Link Library (DLL)](`FileFormat::DynamicLinkLibrary`)
99  * [Linear Executable (LE)](`FileFormat::LinearExecutable`)
100  * [New Executable (NE)](`FileFormat::NewExecutable`)
101  * [Portable Executable (PE)](`FileFormat::PortableExecutable`)
102- `reader-id3v2` - Enables [ID3v2 (ID3)](`FileFormat::Id3v2`) based file formats detection.
103  * [Free Lossless Audio Codec (FLAC)](`FileFormat::FreeLosslessAudioCodec`)
104  * [MPEG-1/2 Audio Layer 3 (MP3)](`FileFormat::Mpeg12AudioLayer3`)
105- `reader-mp4` - Enables [MPEG-4 Part 14 (MP4)](`FileFormat::Mpeg4Part14`) based file formats
106  detection.
107  * [MPEG-4 Part 14 Audio (MP4)](`FileFormat::Mpeg4Part14Audio`)
108  * [MPEG-4 Part 14 Subtitles (MP4)](`FileFormat::Mpeg4Part14Subtitles`)
109  * [MPEG-4 Part 14 Video (MP4)](`FileFormat::Mpeg4Part14Video`)
110- `reader-pdf` - Enables [Portable Document Format (PDF)](`FileFormat::PortableDocumentFormat`)
111  based file formats detection.
112  * [Adobe Illustrator Artwork (AI)](`FileFormat::AdobeIllustratorArtwork`)
113- `reader-rm` - Enables [RealMedia (RM)](`FileFormat::Realmedia`) based file formats detection.
114  * [RealAudio (RA)](`FileFormat::Realaudio`)
115  * [RealVideo (RV)](`FileFormat::Realvideo`)
116- `reader-sqlite3` - Enables [SQLite 3](`FileFormat::Sqlite3`) based file formats detection.
117  * [Sketch](`FileFormat::Sketch`)
118- `reader-txt` - Enables [Plain Text (TXT)](`FileFormat::PlainText`) detection when the file format
119  is not recognized by its signature. Please note that this feature only detects files containing
120  ASCII/UTF-8-encoded text.
121- `reader-xml` - Enables [Extensible Markup Language (XML)](`FileFormat::ExtensibleMarkupLanguage`)
122  based file formats detection. Please note that these file formats may be detected without the
123  feature in certain cases.
124  * [AbiWord (ABW)](`FileFormat::Abiword`)
125  * [AbiWord Template (AWT)](`FileFormat::AbiwordTemplate`)
126  * [Additive Manufacturing Format (AMF)](`FileFormat::AdditiveManufacturingFormat`)
127  * [Advanced Stream Redirector (ASX)](`FileFormat::AdvancedStreamRedirector`)
128  * [Atom](`FileFormat::Atom`)
129  * [Collaborative Design Activity (COLLADA)](`FileFormat::CollaborativeDesignActivity`)
130  * [Extensible 3D (X3D)](`FileFormat::Extensible3d`)
131  * [Extensible Stylesheet Language Transformations (XSLT)](`FileFormat::ExtensibleStylesheetLanguageTransformations`)
132  * [FictionBook (FB2)](`FileFormat::Fictionbook`)
133  * [GPS Exchange Format (GPX)](`FileFormat::GpsExchangeFormat`)
134  * [Geography Markup Language (GML)](`FileFormat::GeographyMarkupLanguage`)
135  * [Keyhole Markup Language (KML)](`FileFormat::KeyholeMarkupLanguage`)
136  * [MPEG-DASH MPD (MPD)](`FileFormat::MpegDashMpd`)
137  * [Mathematical Markup Language (MathML)](`FileFormat::MathematicalMarkupLanguage`)
138  * [MusicXML](`FileFormat::Musicxml`)
139  * [Really Simple Syndication (RSS)](`FileFormat::ReallySimpleSyndication`)
140  * [Scalable Vector Graphics (SVG)](`FileFormat::ScalableVectorGraphics`)
141  * [Simple Object Access Protocol (SOAP)](`FileFormat::SimpleObjectAccessProtocol`)
142  * [Tiled Map XML (TMX)](`FileFormat::TiledMapXml`)
143  * [Tiled Tileset XML (TSX)](`FileFormat::TiledTilesetXml`)
144  * [Timed Text Markup Language (TTML)](`FileFormat::TimedTextMarkupLanguage`)
145  * [Training Center XML (TCX)](`FileFormat::TrainingCenterXml`)
146  * [Uniform Office Format Presentation (UOP)](`FileFormat::UniformOfficeFormatPresentation`)
147  * [Uniform Office Format Spreadsheet (UOS)](`FileFormat::UniformOfficeFormatSpreadsheet`)
148  * [Uniform Office Format Text (UOT)](`FileFormat::UniformOfficeFormatText`)
149  * [Universal Subtitle Format (USF)](`FileFormat::UniversalSubtitleFormat`)
150  * [XML Localization Interchange File Format (XLIFF)](`FileFormat::XmlLocalizationInterchangeFileFormat`)
151  * [XML Shareable Playlist Format (XSPF)](`FileFormat::XmlShareablePlaylistFormat`)
152  * [draw.io (DRAWIO)](`FileFormat::Drawio`)
153- `reader-zip` - Enables [ZIP](`FileFormat::Zip`)-based file formats detection.
154  * [3D Manufacturing Format (3MF)](`FileFormat::ThreeDimensionalManufacturingFormat`)
155  * [Adobe Integrated Runtime (AIR)](`FileFormat::AdobeIntegratedRuntime`)
156  * [Android App Bundle (AAB)](`FileFormat::AndroidAppBundle`)
157  * [Android Package (APK)](`FileFormat::AndroidPackage`)
158  * [Autodesk 123D (123DX)](`FileFormat::Autodesk123d`)
159  * [Circuit Diagram Document (CDDX)](`FileFormat::CircuitDiagramDocument`)
160  * [Design Web Format XPS (DWFX)](`FileFormat::DesignWebFormatXps`)
161  * [Electronic Publication (EPUB)](`FileFormat::ElectronicPublication`)
162  * [Enterprise Application Archive (EAR)](`FileFormat::EnterpriseApplicationArchive`)
163  * [FictionBook ZIP (FBZ)](`FileFormat::FictionbookZip`)
164  * [Figma Design (FIG)](`FileFormat::FigmaDesign`)
165  * [Flash CS5 Project (FLA)](`FileFormat::FlashCs5Project`)
166  * [Fusion 360 (F3D)](`FileFormat::Fusion360`)
167  * [InDesign Markup Language (IDML)](`FileFormat::IndesignMarkupLanguage`)
168  * [Java Archive (JAR)](`FileFormat::JavaArchive`)
169  * [Keyhole Markup Language ZIP (KMZ)](`FileFormat::KeyholeMarkupLanguageZip`)
170  * [Microsoft Visual Studio Extension (VSIX)](`FileFormat::MicrosoftVisualStudioExtension`)
171  * [MusicXML ZIP (MXL)](`FileFormat::MusicxmlZip`)
172  * [Office Open XML Document (DOCX)](`FileFormat::OfficeOpenXmlDocument`)
173  * [Office Open XML Drawing (VSDX)](`FileFormat::OfficeOpenXmlDrawing`)
174  * [Office Open XML Presentation (PPTX)](`FileFormat::OfficeOpenXmlPresentation`)
175  * [Office Open XML Spreadsheet (XLSX)](`FileFormat::OfficeOpenXmlSpreadsheet`)
176  * [OpenDocument Database (ODB)](`FileFormat::OpendocumentDatabase`)
177  * [OpenDocument Formula (ODF)](`FileFormat::OpendocumentFormula`)
178  * [OpenDocument Formula Template (OTF)](`FileFormat::OpendocumentFormulaTemplate`)
179  * [OpenDocument Graphics (ODG)](`FileFormat::OpendocumentGraphics`)
180  * [OpenDocument Graphics Template (OTG)](`FileFormat::OpendocumentGraphicsTemplate`)
181  * [OpenDocument Presentation (ODP)](`FileFormat::OpendocumentPresentation`)
182  * [OpenDocument Presentation Template (OTP)](`FileFormat::OpendocumentPresentationTemplate`)
183  * [OpenDocument Spreadsheet (ODS)](`FileFormat::OpendocumentSpreadsheet`)
184  * [OpenDocument Spreadsheet Template (OTS)](`FileFormat::OpendocumentSpreadsheetTemplate`)
185  * [OpenDocument Text (ODT)](`FileFormat::OpendocumentText`)
186  * [OpenDocument Text Master (ODM)](`FileFormat::OpendocumentTextMaster`)
187  * [OpenDocument Text Master Template (OTM)](`FileFormat::OpendocumentTextMasterTemplate`)
188  * [OpenDocument Text Template (OTT)](`FileFormat::OpendocumentTextTemplate`)
189  * [OpenRaster (ORA)](`FileFormat::Openraster`)
190  * [OpenXPS (OXPS)](`FileFormat::Openxps`)
191  * [Sketch 43](`FileFormat::Sketch43`)
192  * [SpaceClaim Document (SCDOC)](`FileFormat::SpaceclaimDocument`)
193  * [Sun XML Calc (SXC)](`FileFormat::SunXmlCalc`)
194  * [Sun XML Calc Template (STC)](`FileFormat::SunXmlCalcTemplate`)
195  * [Sun XML Draw (SXD)](`FileFormat::SunXmlDraw`)
196  * [Sun XML Draw Template (STD)](`FileFormat::SunXmlDrawTemplate`)
197  * [Sun XML Impress (SXI)](`FileFormat::SunXmlImpress`)
198  * [Sun XML Impress Template (STI)](`FileFormat::SunXmlImpressTemplate`)
199  * [Sun XML Math (SXM)](`FileFormat::SunXmlMath`)
200  * [Sun XML Writer (SXW)](`FileFormat::SunXmlWriter`)
201  * [Sun XML Writer Global (SGW)](`FileFormat::SunXmlWriterGlobal`)
202  * [Sun XML Writer Template (STW)](`FileFormat::SunXmlWriterTemplate`)
203  * [Universal Scene Description ZIP (USDZ)](`FileFormat::UniversalSceneDescriptionZip`)
204  * [Web Application Archive (WAR)](`FileFormat::WebApplicationArchive`)
205  * [Windows App Bundle (APPXBUNDLE)](`FileFormat::WindowsAppBundle`)
206  * [Windows App Package (APPX)](`FileFormat::WindowsAppPackage`)
207  * [XAP](`FileFormat::Xap`)
208  * [XPInstall (XPI)](`FileFormat::Xpinstall`)
209  * [iOS App Store Package (IPA)](`FileFormat::IosAppStorePackage`)
210*/
211
212#![deny(missing_docs)]
213#![forbid(unsafe_code)]
214
215#[macro_use]
216mod macros;
217
218mod formats;
219mod readers;
220mod signatures;
221
222use std::{
223    fmt::{self, Display, Formatter},
224    fs::File,
225    io::{Cursor, Read, Result, Seek},
226    path::Path,
227};
228
229pub use formats::FileFormat;
230
231impl FileFormat {
232    /// Determines file format from bytes.
233    ///
234    /// # Examples
235    ///
236    /// Detects from the first bytes of a
237    /// [Portable Network Graphics (PNG)](`FileFormat::PortableNetworkGraphics`) file:
238    ///
239    /// ```
240    /// use file_format::FileFormat;
241    ///
242    /// let fmt = FileFormat::from_bytes(b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A");
243    /// assert_eq!(fmt, FileFormat::PortableNetworkGraphics);
244    ///```
245    ///
246    /// Detects from a zeroed buffer:
247    ///
248    /// ```
249    /// use file_format::FileFormat;
250    ///
251    /// let fmt = FileFormat::from_bytes(&[0; 1000]);
252    /// assert_eq!(fmt, FileFormat::ArbitraryBinaryData);
253    ///```
254    ///
255    /// [default value]: FileFormat::default
256    #[inline]
257    pub fn from_bytes<B: AsRef<[u8]>>(bytes: B) -> Self {
258        Self::from(bytes.as_ref())
259    }
260
261    /// Determines file format from a file.
262    ///
263    /// # Examples
264    ///
265    /// Basic usage:
266    ///
267    /// ```no_run
268    /// use file_format::FileFormat;
269    ///
270    /// let fmt = FileFormat::from_file("fixtures/video/sample.avi")?;
271    /// assert_eq!(fmt, FileFormat::AudioVideoInterleave);
272    /// # Ok::<(), std::io::Error>(())
273    ///```
274    #[inline]
275    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
276        Self::from_reader(File::open(path)?)
277    }
278
279    /// Determines file format from a reader.
280    ///
281    /// # Examples
282    ///
283    /// Basic usage:
284    ///
285    /// ```
286    /// use file_format::FileFormat;
287    ///
288    /// let fmt = FileFormat::from_reader(std::io::empty())?;
289    /// assert_eq!(fmt, FileFormat::Empty);
290    /// # Ok::<(), std::io::Error>(())
291    ///```
292    pub fn from_reader<R: Read + Seek>(mut reader: R) -> Result<Self> {
293        // Creates and fills a buffer.
294        let mut buf = [0; 36_870];
295        let nread = reader.read(&mut buf)?;
296
297        // Determines file format.
298        Ok(if nread == 0 {
299            Self::Empty
300        } else if let Some(fmt) = Self::from_signature(&buf[..nread]) {
301            Self::from_fmt_reader(fmt, &mut reader)
302                .unwrap_or_else(|_| Self::from_generic_reader(&mut reader))
303        } else {
304            Self::from_generic_reader(&mut reader)
305        })
306    }
307}
308
309impl Default for FileFormat {
310    /// Returns the default file format which is
311    /// [Arbitrary Binary Data (BIN)](`FileFormat::ArbitraryBinaryData`).
312    #[inline]
313    fn default() -> Self {
314        Self::ArbitraryBinaryData
315    }
316}
317
318impl Display for FileFormat {
319    #[inline]
320    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
321        write!(formatter, "{}", self.name())
322    }
323}
324
325impl From<&[u8]> for FileFormat {
326    #[inline]
327    fn from(value: &[u8]) -> Self {
328        Self::from_reader(Cursor::new(value)).unwrap_or_default()
329    }
330}
331
332/// A kind of file format.
333#[derive(Clone, Copy, Debug, Eq, PartialEq)]
334#[non_exhaustive]
335pub enum Kind {
336    /// Files and directories stored in a single, possibly compressed, archive.
337    Archive,
338    /// Musics, sound effects, and spoken audio recordings.
339    Audio,
340    /// Compressed single files or streams.
341    Compressed,
342    /// Organized collections of data.
343    Database,
344    /// Visual information using graphics and spatial relationships.
345    Diagram,
346    /// Floppy disk images, optical disc images and virtual machine disks.
347    Disk,
348    /// Word processing and desktop publishing documents.
349    Document,
350    /// Electronic books.
351    Ebook,
352    /// Machine-executable code, virtual machine code and shared libraries.
353    Executable,
354    /// Typefaces used for displaying text on screen or in print.
355    Font,
356    /// Mathematical formulas.
357    Formula,
358    /// Collections of geospatial features, GPS tracks and other location-related files.
359    Geospatial,
360    /// Animated images, icons, cursors, raster graphics and vector graphics.
361    Image,
362    /// Data that provides information about other data.
363    Metadata,
364    /// 3D models, CAD drawings, and other types of files used for creating or displaying 3D images.
365    Model,
366    /// Data which do not fit in any of the other kinds.
367    Other,
368    /// Collections of files bundled together for software distribution.
369    Package,
370    /// Lists of audio or video files, organized in a specific order for sequential playback.
371    Playlist,
372    /// Slide shows.
373    Presentation,
374    /// Copies of a read-only memory chip of computers, cartridges, or other electronic devices.
375    Rom,
376    /// Data in tabular form.
377    Spreadsheet,
378    /// Subtitles and captions.
379    Subtitle,
380    /// Moving images, possibly with color and coordinated sound.
381    Video,
382}