Skip to main content

alux_http/
header.rs

1//! States what a header name says, independently of how a framework spells one.
2//!
3//! A header name is words. The wire spells them with `-` and lowercases them, because case is not
4//! part of a header name; an argument spells the same words with `_`. Reading one as the other is
5//! the whole of what an interpretation needs stating once, and it is why an author states a header
6//! argument as an ordinary product rather than as a framework's type.
7
8/// Reads the name a header states as the name an argument states.
9pub fn read_header_name(name: &str) -> String {
10    name.trim().to_lowercase().replace('-', "_")
11}
12
13/// Writes the name an argument states as the name a header states.
14///
15/// The reverse of [`read_header_name`], for anything stating a header name to a reader rather than
16/// reading one: a document keying a parameter, or a client sending it.
17pub fn write_header_name(name: &str) -> String {
18    name.replace('_', "-")
19}
20
21#[cfg(test)]
22mod tests {
23    use super::{read_header_name, write_header_name};
24
25    #[test]
26    fn writes_the_words_an_argument_states_as_a_header_name() {
27        assert_eq!(write_header_name("user_agent"), "user-agent");
28        // A name survives the round trip, which is what makes one reading the other's reverse.
29        assert_eq!(read_header_name(&write_header_name("user_agent")), "user_agent");
30    }
31
32    #[test]
33    fn reads_a_header_name_as_the_words_it_states() {
34        assert_eq!(read_header_name("User-Agent"), "user_agent");
35        assert_eq!(read_header_name("  CONTENT-TYPE "), "content_type");
36        // A name already spelled the way an argument spells it states the same words.
37        assert_eq!(read_header_name("user_agent"), "user_agent");
38    }
39}