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 * [Flash CS5 Project (FLA)](`FileFormat::FlashCs5Project`)
165 * [Fusion 360 (F3D)](`FileFormat::Fusion360`)
166 * [InDesign Markup Language (IDML)](`FileFormat::IndesignMarkupLanguage`)
167 * [Java Archive (JAR)](`FileFormat::JavaArchive`)
168 * [Keyhole Markup Language ZIP (KMZ)](`FileFormat::KeyholeMarkupLanguageZip`)
169 * [Microsoft Visual Studio Extension (VSIX)](`FileFormat::MicrosoftVisualStudioExtension`)
170 * [MusicXML ZIP (MXL)](`FileFormat::MusicxmlZip`)
171 * [Office Open XML Document (DOCX)](`FileFormat::OfficeOpenXmlDocument`)
172 * [Office Open XML Drawing (VSDX)](`FileFormat::OfficeOpenXmlDrawing`)
173 * [Office Open XML Presentation (PPTX)](`FileFormat::OfficeOpenXmlPresentation`)
174 * [Office Open XML Spreadsheet (XLSX)](`FileFormat::OfficeOpenXmlSpreadsheet`)
175 * [OpenDocument Database (ODB)](`FileFormat::OpendocumentDatabase`)
176 * [OpenDocument Formula (ODF)](`FileFormat::OpendocumentFormula`)
177 * [OpenDocument Formula Template (OTF)](`FileFormat::OpendocumentFormulaTemplate`)
178 * [OpenDocument Graphics (ODG)](`FileFormat::OpendocumentGraphics`)
179 * [OpenDocument Graphics Template (OTG)](`FileFormat::OpendocumentGraphicsTemplate`)
180 * [OpenDocument Presentation (ODP)](`FileFormat::OpendocumentPresentation`)
181 * [OpenDocument Presentation Template (OTP)](`FileFormat::OpendocumentPresentationTemplate`)
182 * [OpenDocument Spreadsheet (ODS)](`FileFormat::OpendocumentSpreadsheet`)
183 * [OpenDocument Spreadsheet Template (OTS)](`FileFormat::OpendocumentSpreadsheetTemplate`)
184 * [OpenDocument Text (ODT)](`FileFormat::OpendocumentText`)
185 * [OpenDocument Text Master (ODM)](`FileFormat::OpendocumentTextMaster`)
186 * [OpenDocument Text Master Template (OTM)](`FileFormat::OpendocumentTextMasterTemplate`)
187 * [OpenDocument Text Template (OTT)](`FileFormat::OpendocumentTextTemplate`)
188 * [OpenRaster (ORA)](`FileFormat::Openraster`)
189 * [OpenXPS (OXPS)](`FileFormat::Openxps`)
190 * [Sketch 43](`FileFormat::Sketch43`)
191 * [SpaceClaim Document (SCDOC)](`FileFormat::SpaceclaimDocument`)
192 * [Sun XML Calc (SXC)](`FileFormat::SunXmlCalc`)
193 * [Sun XML Calc Template (STC)](`FileFormat::SunXmlCalcTemplate`)
194 * [Sun XML Draw (SXD)](`FileFormat::SunXmlDraw`)
195 * [Sun XML Draw Template (STD)](`FileFormat::SunXmlDrawTemplate`)
196 * [Sun XML Impress (SXI)](`FileFormat::SunXmlImpress`)
197 * [Sun XML Impress Template (STI)](`FileFormat::SunXmlImpressTemplate`)
198 * [Sun XML Math (SXM)](`FileFormat::SunXmlMath`)
199 * [Sun XML Writer (SXW)](`FileFormat::SunXmlWriter`)
200 * [Sun XML Writer Global (SGW)](`FileFormat::SunXmlWriterGlobal`)
201 * [Sun XML Writer Template (STW)](`FileFormat::SunXmlWriterTemplate`)
202 * [Universal Scene Description ZIP (USDZ)](`FileFormat::UniversalSceneDescriptionZip`)
203 * [Web Application Archive (WAR)](`FileFormat::WebApplicationArchive`)
204 * [Windows App Bundle (APPXBUNDLE)](`FileFormat::WindowsAppBundle`)
205 * [Windows App Package (APPX)](`FileFormat::WindowsAppPackage`)
206 * [XAP](`FileFormat::Xap`)
207 * [XPInstall (XPI)](`FileFormat::Xpinstall`)
208 * [iOS App Store Package (IPA)](`FileFormat::IosAppStorePackage`)
209*/
210
211#![deny(missing_docs)]
212#![forbid(unsafe_code)]
213
214#[macro_use]
215mod macros;
216
217mod formats;
218mod readers;
219mod signatures;
220
221use std::{
222 fmt::{self, Display, Formatter},
223 fs::File,
224 io::{Cursor, Read, Result, Seek},
225 path::Path,
226};
227
228pub use formats::FileFormat;
229
230impl FileFormat {
231 /// Determines file format from bytes.
232 ///
233 /// # Examples
234 ///
235 /// Detects from the first bytes of a
236 /// [Portable Network Graphics (PNG)](`FileFormat::PortableNetworkGraphics`) file:
237 ///
238 /// ```
239 /// use file_format::FileFormat;
240 ///
241 /// let fmt = FileFormat::from_bytes(b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A");
242 /// assert_eq!(fmt, FileFormat::PortableNetworkGraphics);
243 ///```
244 ///
245 /// Detects from a zeroed buffer:
246 ///
247 /// ```
248 /// use file_format::FileFormat;
249 ///
250 /// let fmt = FileFormat::from_bytes(&[0; 1000]);
251 /// assert_eq!(fmt, FileFormat::ArbitraryBinaryData);
252 ///```
253 ///
254 /// [default value]: FileFormat::default
255 #[inline]
256 pub fn from_bytes<B: AsRef<[u8]>>(bytes: B) -> Self {
257 Self::from(bytes.as_ref())
258 }
259
260 /// Determines file format from a file.
261 ///
262 /// # Examples
263 ///
264 /// Basic usage:
265 ///
266 /// ```no_run
267 /// use file_format::FileFormat;
268 ///
269 /// let fmt = FileFormat::from_file("fixtures/video/sample.avi")?;
270 /// assert_eq!(fmt, FileFormat::AudioVideoInterleave);
271 /// # Ok::<(), std::io::Error>(())
272 ///```
273 #[inline]
274 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
275 Self::from_reader(File::open(path)?)
276 }
277
278 /// Determines file format from a reader.
279 ///
280 /// # Examples
281 ///
282 /// Basic usage:
283 ///
284 /// ```
285 /// use file_format::FileFormat;
286 ///
287 /// let fmt = FileFormat::from_reader(std::io::empty())?;
288 /// assert_eq!(fmt, FileFormat::Empty);
289 /// # Ok::<(), std::io::Error>(())
290 ///```
291 pub fn from_reader<R: Read + Seek>(mut reader: R) -> Result<Self> {
292 // Creates and fills a buffer.
293 let mut buf = [0; 36_870];
294 let nread = reader.read(&mut buf)?;
295
296 // Determines file format.
297 Ok(if nread == 0 {
298 Self::Empty
299 } else if let Some(fmt) = Self::from_signature(&buf[..nread]) {
300 Self::from_fmt_reader(fmt, &mut reader)
301 .unwrap_or_else(|_| Self::from_generic_reader(&mut reader))
302 } else {
303 Self::from_generic_reader(&mut reader)
304 })
305 }
306}
307
308impl Default for FileFormat {
309 /// Returns the default file format which is
310 /// [Arbitrary Binary Data (BIN)](`FileFormat::ArbitraryBinaryData`).
311 #[inline]
312 fn default() -> Self {
313 Self::ArbitraryBinaryData
314 }
315}
316
317impl Display for FileFormat {
318 #[inline]
319 fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
320 write!(formatter, "{}", self.name())
321 }
322}
323
324impl From<&[u8]> for FileFormat {
325 #[inline]
326 fn from(value: &[u8]) -> Self {
327 Self::from_reader(Cursor::new(value)).unwrap_or_default()
328 }
329}
330
331/// A kind of file format.
332#[derive(Clone, Copy, Debug, Eq, PartialEq)]
333#[non_exhaustive]
334pub enum Kind {
335 /// Files and directories stored in a single, possibly compressed, archive.
336 Archive,
337 /// Musics, sound effects, and spoken audio recordings.
338 Audio,
339 /// Compressed single files or streams.
340 Compressed,
341 /// Organized collections of data.
342 Database,
343 /// Visual information using graphics and spatial relationships.
344 Diagram,
345 /// Floppy disk images, optical disc images and virtual machine disks.
346 Disk,
347 /// Word processing and desktop publishing documents.
348 Document,
349 /// Electronic books.
350 Ebook,
351 /// Machine-executable code, virtual machine code and shared libraries.
352 Executable,
353 /// Typefaces used for displaying text on screen or in print.
354 Font,
355 /// Mathematical formulas.
356 Formula,
357 /// Collections of geospatial features, GPS tracks and other location-related files.
358 Geospatial,
359 /// Animated images, icons, cursors, raster graphics and vector graphics.
360 Image,
361 /// Data that provides information about other data.
362 Metadata,
363 /// 3D models, CAD drawings, and other types of files used for creating or displaying 3D images.
364 Model,
365 /// Data which do not fit in any of the other kinds.
366 Other,
367 /// Collections of files bundled together for software distribution.
368 Package,
369 /// Lists of audio or video files, organized in a specific order for sequential playback.
370 Playlist,
371 /// Slide shows.
372 Presentation,
373 /// Copies of a read-only memory chip of computers, cartridges, or other electronic devices.
374 Rom,
375 /// Data in tabular form.
376 Spreadsheet,
377 /// Subtitles and captions.
378 Subtitle,
379 /// Moving images, possibly with color and coordinated sound.
380 Video,
381}