feedparser-rs 0.8.0

High-performance RSS/Atom/JSON Feed parser
Documentation
pub mod atom;
mod common;
mod context;
mod detect;
mod itunes;
pub mod json;
mod media;
pub mod rss;
pub mod rss10;

use crate::{
    error::{FeedError, Result},
    types::{FeedVersion, ParsedFeed},
    util::encoding::decode_document,
};

pub use detect::detect_format;
use detect::{Detected, detect};

/// Parse feed from raw bytes
///
/// This is the main entry point for parsing feeds. It automatically detects
/// the feed format (RSS, Atom, JSON) and parses accordingly. Uses
/// [`crate::ParseOptions::default`], which sanitizes HTML content and resolves
/// relative URIs.
///
/// # Errors
///
/// Returns a `FeedError` if the feed cannot be parsed. However, in most cases,
/// the parser will set the `bozo` flag and return partial results rather than
/// returning an error.
///
/// # Examples
///
/// ```
/// use feedparser_rs::parse;
///
/// let xml = r#"
///     <?xml version="1.0"?>
///     <rss version="2.0">
///         <channel>
///             <title>Example Feed</title>
///         </channel>
///     </rss>
/// "#;
///
/// let feed = parse(xml.as_bytes()).unwrap();
/// assert_eq!(feed.feed.title.as_deref(), Some("Example Feed"));
/// ```
pub fn parse(data: &[u8]) -> Result<ParsedFeed> {
    parse_with_options(data, &crate::ParseOptions::default())
}

/// Parse feed with custom parser limits
///
/// This allows controlling resource usage when parsing untrusted feeds. HTML
/// sanitization and relative URI resolution use their [`crate::ParseOptions::default`]
/// settings (both enabled); use [`parse_with_options`] to control them directly.
///
/// # Examples
///
/// ```
/// use feedparser_rs::{parse_with_limits, ParserLimits};
///
/// let xml = b"<rss version=\"2.0\"><channel><title>Test</title></channel></rss>";
/// let limits = ParserLimits::strict();
/// let feed = parse_with_limits(xml, limits).unwrap();
/// ```
///
/// # Errors
///
/// Returns `FeedError::InvalidFormat` if `data` exceeds `limits.max_feed_size_bytes`,
/// or the error of a parser that cannot continue. An unrecognized format is not an
/// error; it sets `bozo`.
pub fn parse_with_limits(data: &[u8], limits: crate::ParserLimits) -> Result<ParsedFeed> {
    parse_with_options(
        data,
        &crate::ParseOptions {
            limits,
            ..crate::ParseOptions::default()
        },
    )
}

/// Parse feed from raw bytes with full control over parser behavior
///
/// This is the most flexible entry point: [`parse`] and [`parse_with_limits`] are
/// thin wrappers around it. Controls HTML sanitization, relative URI resolution,
/// and resource limits via [`crate::ParseOptions`].
///
/// The input is decoded from its BOM or XML declaration, falling back to UTF-8.
/// A declaration that the bytes contradict, or bytes that are invalid in the
/// chosen encoding, set `bozo`.
///
/// # Examples
///
/// ```
/// use feedparser_rs::{parse_with_options, ParseOptions};
///
/// // Trust the feed source and skip sanitization
/// let options = ParseOptions::default().with_sanitize_html(false);
/// let xml = b"<rss version=\"2.0\"><channel><title>Test</title></channel></rss>";
/// let feed = parse_with_options(xml, &options).unwrap();
/// ```
///
/// # Errors
///
/// Returns `FeedError::InvalidFormat` if `data` exceeds the size limit, or the
/// error of a parser that cannot continue. An unrecognized format is not an error;
/// it sets `bozo`.
pub fn parse_with_options(data: &[u8], options: &crate::ParseOptions) -> Result<ParsedFeed> {
    parse_with_content_type(data, None, options)
}

/// Parse an already decoded string, ignoring any declared encoding.
///
/// Use it when the caller holds text rather than bytes, so no charset detection
/// can misread it: an XML declaration label is ignored, one leading U+FEFF is
/// stripped, `encoding` is `"utf-8"` and decoding never sets `bozo`. Everything
/// else matches [`parse_with_options`].
///
/// # Errors
///
/// Same as [`parse_with_options`].
///
/// # Examples
///
/// ```
/// use feedparser_rs::{ParseOptions, parse_str_with_options};
///
/// let xml = r#"<?xml version="1.0" encoding="gbk"?>
/// <rss version="2.0"><channel><title>héllo</title></channel></rss>"#;
/// let feed = parse_str_with_options(xml, &ParseOptions::default())?;
/// assert_eq!(feed.feed.title.as_deref(), Some("héllo"));
/// assert_eq!(feed.encoding, "utf-8");
/// # Ok::<(), feedparser_rs::FeedError>(())
/// ```
pub fn parse_str_with_options(text: &str, options: &crate::ParseOptions) -> Result<ParsedFeed> {
    check_input_size(text.len(), options)?;
    let feed = parse_decoded(text.trim_prefix('\u{FEFF}').as_bytes(), options)?;
    Ok(finish(feed, "utf-8".to_string(), None, options))
}

/// [`parse_with_options`] with the HTTP `Content-Type` header taking part in decoding.
pub fn parse_with_content_type(
    data: &[u8],
    content_type: Option<&str>,
    options: &crate::ParseOptions,
) -> Result<ParsedFeed> {
    check_input_size(data.len(), options)?;
    let decoded = decode_document(data, content_type);
    let feed = parse_decoded(decoded.text.as_bytes(), options)?;
    Ok(finish(
        feed,
        decoded.encoding.name(),
        decoded.problem(),
        options,
    ))
}

/// Rejects oversized input before any work is spent on it.
fn check_input_size(len: usize, options: &crate::ParseOptions) -> Result<()> {
    options
        .limits
        .check_feed_size(len)
        .map_err(|e| FeedError::InvalidFormat(e.to_string()))
}

/// Applies what every entry point adds on top of the format parser.
fn finish(
    mut feed: ParsedFeed,
    encoding: String,
    decoding_problem: Option<String>,
    options: &crate::ParseOptions,
) -> ParsedFeed {
    feed.encoding = encoding;

    if let Some(problem) = decoding_problem {
        feed.bozo = true;
        feed.bozo_exception.get_or_insert(problem);
    }

    if options.sanitize_html {
        crate::util::sanitize::sanitize_feed(&mut feed, &options.limits);
    }

    feed
}

/// Detects the format of UTF-8 `data` and runs the matching parser.
fn parse_decoded(data: &[u8], options: &crate::ParseOptions) -> Result<ParsedFeed> {
    let limits = options.limits;
    let resolve_relative_uris = options.resolve_relative_uris;
    // Detection needs UTF-8 input (required for correct UTF-16 handling).
    match detect(data) {
        // RSS variants (all use RSS 2.0 parser; overwrite version after parsing)
        Detected::Rss(dialect) => {
            let mut parsed = rss::parse_rss20_with_options(data, limits, resolve_relative_uris)?;
            parsed.version = dialect.version();
            Ok(parsed)
        }

        Detected::Atom(_) => atom::parse_atom10_with_options(data, limits, resolve_relative_uris),

        // RSS 1.0 and 0.90 (RDF)
        Detected::Rdf(dialect) => {
            let mut parsed = rss10::parse_rss10_with_options(data, limits, resolve_relative_uris)?;
            parsed.version = dialect.version();
            Ok(parsed)
        }

        // JSON Feed: `resolve_relative_uris` is intentionally not threaded through
        // here — the JSON Feed parser does not resolve relative URIs against a
        // base URL at all (JSON Feed has no `xml:base`-equivalent concept), so
        // there is nothing for the option to gate.
        Detected::JsonFeed(_) => json::parse_json_feed_with_limits(data, limits),

        // Unknown format - return a bozo feed since the format is unrecognized.
        // The bozo pattern requires we never panic and always return partial data,
        // but unrecognizable input must signal the caller via bozo=true.
        Detected::Unrecognized => {
            let mut feed = ParsedFeed::new();
            feed.version = FeedVersion::Unknown;
            feed.bozo = true;
            feed.bozo_exception = Some("Feed format not recognized".to_string());
            Ok(feed)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_returns_ok_bozo_for_garbage() {
        let feed = parse(b"test").unwrap();
        assert!(feed.bozo, "unrecognized input must set bozo");
        assert_eq!(feed.version, crate::types::FeedVersion::Unknown);
        assert!(feed.entries.is_empty());
    }

    #[test]
    fn test_rss091n_version_string() {
        // #283: RSS 0.91 with Netscape DOCTYPE must report "rss091n"
        let xml = br#"<?xml version="1.0"?>
<!DOCTYPE rss PUBLIC "-//Netscape Communications//DTD RSS 0.91//EN"
    "http://my.netscape.com/publish/formats/rss-0.91.dtd">
<rss version="0.91">
<channel><title>T</title><link>http://example.com</link><description>D</description>
<language>en</language></channel></rss>"#;
        let feed = parse(xml).unwrap();
        assert_eq!(feed.version.as_str(), "rss091n");
    }

    #[test]
    fn test_rss091u_version_string() {
        // #283: RSS 0.91 without Netscape DOCTYPE must report "rss091u"
        let xml = br#"<?xml version="1.0"?>
<rss version="0.91">
<channel><title>T</title><link>http://example.com</link><description>D</description>
<language>en</language></channel></rss>"#;
        let feed = parse(xml).unwrap();
        assert_eq!(feed.version.as_str(), "rss091u");
    }

    #[test]
    fn test_rss092_version_string() {
        // #283: RSS 0.92 feeds must report version "rss092", not "rss20"
        let xml = br#"<?xml version="1.0"?>
<rss version="0.92">
<channel><title>T</title><link>http://example.com</link><description>D</description>
</channel></rss>"#;
        let feed = parse(xml).unwrap();
        assert_eq!(feed.version.as_str(), "rss092");
    }

    #[test]
    fn test_rss20_version_string_unchanged() {
        // #283: RSS 2.0 feeds must still report version "rss20"
        let xml = br#"<?xml version="1.0"?>
<rss version="2.0">
<channel><title>T</title><link>http://example.com</link><description>D</description>
</channel></rss>"#;
        let feed = parse(xml).unwrap();
        assert_eq!(feed.version.as_str(), "rss20");
    }
}

#[cfg(test)]
#[path = "../../tests/internal/decode_acceptance.rs"]
mod decode_acceptance;