Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
29 changes: 29 additions & 0 deletions tests/error_description.rs
Original file line number Diff line number Diff line change
@@ -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");
}