Skip to main content

detect_content

Function detect_content 

Source
pub fn detect_content(input: &[u8]) -> Result<Format, Box<dyn Error>>
Expand description

Detects the format of a byte buffer by content.

Tries formats in order: JSON, NDJSON, XML (if it starts with <), CSV, TSV, TOML, YAML. Returns the first format whose parser accepts the input. The order matters: JSON beats NDJSON (since [1,2] is both), and CSV/TSV beat YAML (which would otherwise happily eat a tabular file as a multi-line scalar).

§Errors

Returns an error if the input is not valid UTF-8 or no parser accepts it.

§Examples

use sheeter_engine::{detect_content, Format};
assert_eq!(detect_content(b"[1,2]").unwrap(), Format::Json);
assert_eq!(detect_content(b"a,b\n1,2\n").unwrap(), Format::Csv);
assert_eq!(detect_content(b"a\tb\n1\t2\n").unwrap(), Format::Tsv);
assert_eq!(detect_content(b"{\"a\":1}\n{\"a\":2}\n").unwrap(), Format::Ndjson);
assert_eq!(detect_content(b"<r><a>1</a></r>").unwrap(), Format::Xml);