Skip to main content

analyze

Function analyze 

Source
pub fn analyze(bytes: &[u8]) -> Analysis
Expand description

Reads a file’s signature and, for images, its width and height (Active Storage’s analyze).

Recognized: PNG, JPEG, GIF, WebP, AVIF, PDF, ZIP (also .docx, .xlsx, .odt…: they are ZIP files), MP4, M4A and QuickTime (MOV). Sizes come from PNG, GIF and WebP (VP8, VP8L, VP8X) headers and from the JPEG frame header (SOF), found by jumping from segment to segment. Text formats (plain text, CSV, HTML, SVG, JSON) have no signature and give None: telling them apart would need guesses that an attacker can steer.

Pure and bounded: it reads the first 32 bytes, plus a JPEG’s segment headers (a few dozen jumps, never the image data): microseconds of CPU whatever the file size. Passing only the start of a file works (a few KB; up to 256 KB for JPEGs with large EXIF blocks), for example the first bytes of an R2 object from read_first.

§Examples

use ocre::storage::analyze;

// The first 24 bytes of a 640x480 PNG.
let png = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR\0\0\x02\x80\0\0\x01\xe0";
let analysis = analyze(png);
assert_eq!(analysis.content_type, Some("image/png"));
assert_eq!((analysis.width, analysis.height), (Some(640), Some(480)));