feedparser-rs 0.8.0

High-performance RSS/Atom/JSON Feed parser
Documentation

feedparser-rs

Crates.io docs.rs MSRV License

High-performance RSS/Atom/JSON Feed parser written in Rust.

This is the core parsing library that powers the Python and Node.js bindings.

Features

  • Multi-format: RSS 0.9x/1.0/2.0, Atom 0.3/1.0, JSON Feed 1.0/1.1
  • Tolerant: Bozo flag for graceful handling of malformed feeds
  • Sanitized by default: HTML-bearing fields are sanitized against XSS unless explicitly disabled via ParseOptions
  • Fast: Native Rust performance (200+ MB/s throughput)
  • Safe: unsafe_code is forbidden (the crate contains no unsafe), comprehensive error handling
  • HTTP support: Fetch feeds from URLs with compression and conditional GET
  • Podcast support: iTunes and Podcast 2.0 namespace extensions (Podcast 2.0 in RSS 2.0, RSS 1.0 and Atom, under any prefix bound to its URI)
  • Namespace extensions: Dublin Core, Media RSS (media:title, media:description, media:content, media:thumbnail, media:credit, media:copyright, media:rating, media:keywords), Syndication, GeoRSS, Creative Commons
  • JSON Feed extension objects: generic capture of underscore-prefixed custom objects (e.g. _cast) at feed- and item-level and on authors, attachments and hubs via json_extensions
  • Entry images: Entry::image from itunes:image and the JSON Feed item image
  • Well-tested: 91%+ test coverage with real-world feed fixtures

Installation

cargo add feedparser-rs

Or add to your Cargo.toml:

[dependencies]
feedparser-rs = "0.8"

[!IMPORTANT] Requires Rust 1.100.0 or later (edition 2024).

Quick Start

use feedparser_rs::parse;

let xml = r#"
    <?xml version="1.0"?>
    <rss version="2.0">
        <channel>
            <title>My Blog</title>
            <item>
                <title>Hello World</title>
                <link>https://example.com/1</link>
            </item>
        </channel>
    </rss>
"#;

let feed = parse(xml.as_bytes())?;
assert_eq!(feed.feed.title.as_deref(), Some("My Blog"));
assert_eq!(feed.entries.len(), 1);
# Ok::<(), feedparser_rs::FeedError>(())

FeedVersion::as_str returns these RSS version strings: rss090 (Netscape RDF feeds only), rss091n, rss091u, rss092, rss093, rss094, rss20 (also for any 2.x) and rss (a missing version attribute, 0.90 on <rss>, or any other version value); RSS 1.0 reports rss10.

Already Decoded Text

Use parse_str_with_options when you hold a str rather than bytes. No charset detection runs: a declared encoding is ignored and encoding is "utf-8".

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>(())

HTTP Fetching

Fetch feeds directly from URLs with automatic compression handling:

use feedparser_rs::parse_url;

let feed = parse_url("https://example.com/feed.xml", None, None, None)?;
println!("Title: {:?}", feed.feed.title);
println!("Entries: {}", feed.entries.len());

// Subsequent fetch with caching (uses ETag/Last-Modified)
let feed2 = parse_url(
    "https://example.com/feed.xml",
    feed.etag.as_deref(),
    feed.modified.as_deref(),
    None
)?;

if feed2.status == Some(304) {
    println!("Not modified, use cached version");
}
# Ok::<(), feedparser_rs::FeedError>(())

[!TIP] Use conditional GET with ETag/Last-Modified to minimize bandwidth when polling feeds.

The decompressed response body is capped: 100 MB for parse_url, and max_feed_size_bytes for parse_url_with_limits and parse_url_with_options. A larger body returns FeedError::Fetch(FetchError::BodyTooLarge { .. }). When you use FeedHttpClient directly, set the cap with with_max_body_size (default 100 MB).

Fetch errors

A failed fetch returns FeedError::Fetch, which wraps a typed feedparser_rs::http::FetchError. Match on it to tell a missing feed from a blocked address or a flaky network:

use feedparser_rs::{parse_url, FeedError};
use feedparser_rs::http::FetchError;

match parse_url("https://example.com/feed.xml", None, None, None) {
    Ok(feed) => println!("{} entries", feed.entries.len()),
    Err(FeedError::Fetch(FetchError::Status { status, url })) => {
        eprintln!("server answered {status} for {url}");
    }
    Err(FeedError::Fetch(FetchError::BlockedAddress { reason })) => {
        eprintln!("rejected by SSRF protection: {reason}");
    }
    Err(FeedError::Fetch(FetchError::BodyTooLarge { limit })) => {
        eprintln!("body exceeds {limit} bytes");
    }
    Err(other) => eprintln!("failed: {other}"),
}

FetchError has the variants Status (4xx/5xx, with HttpStatus and the final URL), BlockedAddress (carries a SsrfRejection), TooManyRedirects, BodyTooLarge, InvalidHeader, InvalidUrl and Transport (TransportError::is_timeout() reports timeouts). FeedError and FetchError are #[non_exhaustive], so keep a catch-all arm.

To disable HTTP support and reduce dependencies:

[dependencies]
feedparser-rs = { version = "0.8", default-features = false }

Character Encoding

For bytes, the parser picks the encoding in this order:

  1. Byte order mark
  2. charset of the HTTP Content-Type header (parse_url only; ignored for JSON bodies)
  3. XML declaration at the start of the document (leading ASCII whitespace is allowed)
  4. UTF-8

Unknown labels, and labels that map to the WHATWG replacement encoding (such as iso-2022-kr), are skipped.

encoding reports the encoding that decoded the document, as a lowercase WHATWG name: a feed declared as iso-8859-1 reports windows-1252. The bytes can overrule the chosen label. The parser rejects it if:

  • the label names a single-byte encoding, and the body contains non-ASCII bytes that are valid UTF-8
  • the label names UTF-16, there is no BOM, and the body starts (after any ASCII whitespace) with a single-byte <

When the label is rejected, or decoding with it fails, the parser tries in turn:

  1. UTF-8, if the body is valid UTF-8
  2. The XML declaration encoding, if there is no BOM and the body decodes with it without errors (a declaration the rules above reject is not used)

If neither works, invalid sequences become U+FFFD, decoded with the chosen encoding, or with UTF-8 if the label was rejected.

Documents with a UTF-16 BOM, and genuine BOM-less UTF-16 (NUL-interleaved), are decoded as UTF-16. Documents with a UTF-32 BOM are decoded as UTF-32 and report utf-32le or utf-32be; invalid units become U+FFFD.

Decoding with a fallback or replacing a byte sets bozo, and bozo_exception describes the problem (unless the parser already recorded another one).

Upgrading to 0.8

0.8 is a breaking release. The changes that most often need code edits:

  • #[non_exhaustive] types. Output types, ParserLimits, ParseOptions, FeedHttpResponse, FeedError, LimitError, FeedVersion and GeoType can no longer be built with struct literals or matched exhaustively. Use Default, the with_* builders or the new new constructors (for example Image::new, Enclosure::new), and add a wildcard arm when matching enums.
  • Errors. FeedError::Http is now FeedError::Fetch(FetchError). FeedError::XmlError holds an opaque XmlParseError; FeedError::JsonError, FeedError::UrlError and the From impls for dependency errors are gone.
  • Dates. chrono::DateTime<Utc> became jiff::Timestamp (see Dates).
  • Limits. max_text_length and max_attribute_length count bytes, XML text over the limit is truncated instead of dropped, and HTTP bodies are capped at 100 MB by default.
  • Removed. ParsedFeed::check_entry_limit, FeedHttpResponse::encoding and FeedHttpResponse::extract_charset_from_content_type (use util::encoding::extract_charset_from_content_type).
  • Versions. FeedVersion gains Rss093, Rss094 and RssUnknown; <rss> without a usable version reports rss.
  • MSRV is 1.100.0.

The changelog lists every change with its pull request.

Dates

Parsed dates are jiff::Timestamp values. The crate does not re-export jiff, so add it to your dependencies to name the type:

[dependencies]
jiff = "1"

Cargo Features

Feature Description Default
http URL fetching with reqwest (gzip/deflate/brotli) Yes

Error Handling

The library uses a "bozo" flag (like Python's feedparser) to indicate parsing errors while still returning partial results:

use feedparser_rs::parse;

let malformed = b"<rss><channel><title>Broken</title></rss>";
let feed = parse(malformed)?;

assert!(feed.bozo);
assert!(feed.bozo_exception.is_some());
// Still can access parsed data
assert_eq!(feed.feed.title.as_deref(), Some("Broken"));
# Ok::<(), feedparser_rs::FeedError>(())

Recovery keeps as much data as possible, and each case sets bozo = true:

  • A bare & in element text stays literal; the item is not dropped.
  • An unclosed unknown element or corrupted markup does not swallow the items that follow.
  • Truncated or corrupted JSON Feed keeps the feed metadata and the complete leading items.
  • A numeric JSON Feed item id is kept as a string.

Parser Limits

To prevent resource exhaustion (DoS protection), the parser enforces configurable limits:

use feedparser_rs::{parse_with_limits, ParserLimits};

let xml = "<rss version=\"2.0\"><channel><title>Example</title></channel></rss>";

// ParserLimits is #[non_exhaustive]: start from a preset and chain `with_*` builders
let limits = ParserLimits::default()
    .with_max_entries(100)
    .with_max_nesting_depth(20);

let feed = parse_with_limits(xml.as_bytes(), limits)?;
# Ok::<(), feedparser_rs::FeedError>(())

Every limit has a matching with_<limit> builder. Struct literals such as ParserLimits { max_entries: 100, ..Default::default() } no longer compile outside the crate, because the public data types are #[non_exhaustive]; use the builders and new(..) constructors instead, so new fields do not break your code.

max_geo_points caps the points of each GeoRSS or GML geometry: 10,000 by default, 1,000 with ParserLimits::strict(), 100,000 with ParserLimits::permissive(). Extra points are dropped without setting bozo, and a geometry left below its minimum (1 point, 2 for a line or box, 3 for a polygon) is omitted. A truncated polygon can end up unclosed.

In XML, text longer than max_text_length is truncated at a character boundary and sets bozo = true; it is no longer dropped.

Input larger than max_feed_size_bytes returns an error before decoding. Most collections, such as links, authors, tags, content blocks and enclosures, are truncated at a ParserLimits count, in XML and JSON Feed alike.

Text length limits (max_text_length, max_attribute_length) count bytes, not characters. Truncation cuts at a character boundary, so multibyte text never exceeds the limit.

max_json_extension_memory_bytes bounds the estimated memory that all captured JSON Feed extensions of one document retain: 32 MB by default, 4 MB with ParserLimits::strict(), 256 MB with ParserLimits::permissive(). Values are admitted in document order, and a value that does not fit in the remaining budget is dropped without setting bozo. A single value can need about twice max_text_length, so raise both limits together.

[!NOTE] Default limits are generous for typical feeds. Use ParserLimits::strict() for untrusted input.

Full Control with ParseOptions

parse_with_options/parse_url_with_options expose every knob in one call: HTML sanitization, relative URI resolution, and ParserLimits. parse/parse_with_limits (and their parse_url* counterparts) are thin wrappers over these with sanitization and URI resolution both enabled.

use feedparser_rs::{parse_with_options, ParseOptions, ParserLimits};

let xml = b"<rss version=\"2.0\"><channel><title>Trusted Feed</title></channel></rss>";

let options = ParseOptions::default()
    .with_sanitize_html(false) // Trust this feed source; skips the sanitizer pass
    .with_resolve_relative_uris(true)
    .with_limits(ParserLimits::strict());

let feed = parse_with_options(xml, &options)?;
# Ok::<(), feedparser_rs::FeedError>(())

[!IMPORTANT] sanitize_html defaults to true: HTML-bearing fields (titles, summaries, content:encoded, etc.) are sanitized against XSS by default, matching Python feedparser's sanitizer coverage. Disable it only for feed sources you fully trust.

Benchmarks

Measured on Apple M1 Pro:

Feed Size Time Throughput
Small (2 KB) 10.7 µs 187 MB/s
Medium (20 KB) 93.6 µs 214 MB/s
Large (200 KB) 939 µs 213 MB/s

Format detection: 128 ns

Run benchmarks:

cargo bench

Platform Bindings

MSRV Policy

Minimum Supported Rust Version: 1.100.0 (edition 2024).

MSRV increases are considered breaking changes and will result in a minor version bump.

License

Licensed under either of:

at your option.

Links