From 018d54d65a3fe8249d913c06f53297bfb9f80bf7 Mon Sep 17 00:00:00 2001 From: Jaden Fix Date: Sun, 18 Oct 2026 04:15:57 -0700 Subject: [PATCH] Expose static descriptions for parser errors Make the existing Error::description_str accessor public so callers can obtain the display message without allocating or relying on the deprecated std::error::Error::description method. Cover every variant through the public API and exercise a description surviving a parsed error. --- src/lib.rs | 11 ++++++++++- tests/error_description.rs | 29 +++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 tests/error_description.rs diff --git a/src/lib.rs b/src/lib.rs index 98b37c7..6041423 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -117,8 +117,17 @@ pub enum Error { } impl Error { + /// Returns the error's description as a static string. + /// + /// This is the same message produced by the [`Display`](fmt::Display) + /// implementation, without allocating a string. + /// + /// ``` + /// let description: &'static str = httparse::Error::HeaderName.description_str(); + /// assert_eq!(description, "invalid header name"); + /// ``` #[inline] - fn description_str(&self) -> &'static str { + pub fn description_str(&self) -> &'static str { match *self { Error::HeaderName => "invalid header name", Error::HeaderValue => "invalid header value", diff --git a/tests/error_description.rs b/tests/error_description.rs new file mode 100644 index 0000000..8af270f --- /dev/null +++ b/tests/error_description.rs @@ -0,0 +1,29 @@ +use httparse::{Error, Request, EMPTY_HEADER}; + +#[test] +fn error_descriptions_are_static_and_match_display() { + for error in [ + Error::HeaderName, + Error::HeaderValue, + Error::NewLine, + Error::Status, + Error::Token, + Error::TooManyHeaders, + Error::Version, + ] { + let description: &'static str = error.description_str(); + assert_eq!(description, error.to_string()); + } +} + +#[test] +fn parsed_error_description_outlives_the_error() { + let description: &'static str = { + let mut headers = [EMPTY_HEADER; 1]; + let error = Request::new(&mut headers) + .parse(b"GET / HTTP/1.1\r\ninvalid header: value\r\n\r\n") + .unwrap_err(); + error.description_str() + }; + assert_eq!(description, "invalid header name"); +}