vary_header/lib.rs
1//! # vary-header — append fields to an HTTP `Vary` header
2//!
3//! Correctly add field names to a `Vary` response header: de-duplicating
4//! case-insensitively, preserving the existing casing, and collapsing to `*` when
5//! appropriate. A faithful Rust port of the [`vary`](https://www.npmjs.com/package/vary)
6//! npm package (used by `cors`, `compression`, …). Zero dependencies and `#![no_std]`.
7//!
8//! ```
9//! use vary_header::append;
10//!
11//! assert_eq!(append("", "Accept").unwrap(), "Accept");
12//! assert_eq!(append("Accept", "Accept-Encoding").unwrap(), "Accept, Accept-Encoding");
13//! assert_eq!(append("Accept", "accept").unwrap(), "Accept"); // already present
14//! assert_eq!(append("Accept", "*").unwrap(), "*"); // varies on everything
15//! ```
16
17#![no_std]
18#![doc(html_root_url = "https://docs.rs/vary-header/0.1.0")]
19
20extern crate alloc;
21
22use alloc::format;
23use alloc::string::{String, ToString};
24use alloc::vec::Vec;
25
26// Compile-test the README's examples as part of `cargo test`.
27#[cfg(doctest)]
28#[doc = include_str!("../README.md")]
29struct ReadmeDoctests;
30
31/// An error returned when a field cannot be appended.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub enum VaryError {
34 /// The field argument was empty.
35 FieldRequired,
36 /// A field is not a valid header field-name token.
37 InvalidFieldName(String),
38}
39
40impl core::fmt::Display for VaryError {
41 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
42 match self {
43 VaryError::FieldRequired => f.write_str("field argument is required"),
44 VaryError::InvalidFieldName(name) => {
45 write!(f, "field argument contains an invalid header name: {name}")
46 }
47 }
48 }
49}
50
51impl core::error::Error for VaryError {}
52
53/// Append `field` to a `Vary` header value, returning the new value.
54///
55/// `field` may be a single field name or a comma-separated list (e.g.
56/// `"Accept, Accept-Encoding"`); each name is validated as an RFC 7230 token. Names
57/// already present (case-insensitively) are skipped, and existing casing is kept. If
58/// the header or any field is `*`, the result is `*`.
59///
60/// ```
61/// assert_eq!(
62/// vary_header::append("Origin", "Accept, Origin, Accept-Encoding").unwrap(),
63/// "Origin, Accept, Accept-Encoding"
64/// );
65/// ```
66///
67/// # Errors
68///
69/// Returns [`VaryError::FieldRequired`] if `field` is empty, or
70/// [`VaryError::InvalidFieldName`] if a parsed field name is not a valid token.
71pub fn append(header: &str, field: &str) -> Result<String, VaryError> {
72 if field.is_empty() {
73 return Err(VaryError::FieldRequired);
74 }
75 let fields = parse(field);
76 append_impl(header, &fields)
77}
78
79/// Append several already-separated field names to a `Vary` header value.
80///
81/// Unlike [`append`], each entry in `fields` is treated as a single literal field
82/// name (it is not split on commas) and validated as a token. An empty slice returns
83/// the header unchanged.
84///
85/// ```
86/// assert_eq!(
87/// vary_header::append_fields("Accept", &["Accept-Encoding", "Origin"]).unwrap(),
88/// "Accept, Accept-Encoding, Origin"
89/// );
90/// ```
91///
92/// # Errors
93///
94/// Returns [`VaryError::InvalidFieldName`] if any entry is not a valid token.
95pub fn append_fields(header: &str, fields: &[&str]) -> Result<String, VaryError> {
96 let owned: Vec<String> = fields.iter().map(|s| (*s).to_string()).collect();
97 append_impl(header, &owned)
98}
99
100fn append_impl(header: &str, fields: &[String]) -> Result<String, VaryError> {
101 // Validate every field name first (matching the reference's ordering).
102 for field in fields {
103 if !is_field_name(field) {
104 return Err(VaryError::InvalidFieldName(field.clone()));
105 }
106 }
107
108 // An existing unspecified vary.
109 if header == "*" {
110 return Ok("*".to_string());
111 }
112
113 let mut val = header.to_string();
114 let mut vals = parse(&lowercase(header));
115
116 // Unspecified vary requested.
117 if fields.iter().any(|f| f == "*") || vals.iter().any(|v| v == "*") {
118 return Ok("*".to_string());
119 }
120
121 for field in fields {
122 let fld = lowercase(field);
123 if !vals.contains(&fld) {
124 vals.push(fld);
125 val = if val.is_empty() {
126 field.clone()
127 } else {
128 format!("{val}, {field}")
129 };
130 }
131 }
132
133 Ok(val)
134}
135
136/// Tokenize a header into comma-separated fields, trimming surrounding spaces from
137/// each (mirroring the reference's `parse`; note it splits only on `,` and trims only
138/// ASCII space).
139fn parse(header: &str) -> Vec<String> {
140 let chars: Vec<char> = header.chars().collect();
141 let mut list = Vec::new();
142 let mut start = 0;
143 let mut end = 0;
144
145 for (i, &c) in chars.iter().enumerate() {
146 match c {
147 ' ' => {
148 if start == end {
149 start = i + 1;
150 end = i + 1;
151 }
152 }
153 ',' => {
154 list.push(chars[start..end].iter().collect());
155 start = i + 1;
156 end = i + 1;
157 }
158 _ => end = i + 1,
159 }
160 }
161 list.push(chars[start..end].iter().collect());
162
163 list
164}
165
166fn lowercase(s: &str) -> String {
167 s.chars().flat_map(char::to_lowercase).collect()
168}
169
170/// Whether `s` is a valid field-name token (RFC 7230 `1*tchar`).
171fn is_field_name(s: &str) -> bool {
172 !s.is_empty() && s.chars().all(is_tchar)
173}
174
175/// A token character per RFC 7230 (ASCII letters, digits, and the `tchar` symbols).
176fn is_tchar(c: char) -> bool {
177 c.is_ascii_alphanumeric()
178 || matches!(
179 c,
180 '!' | '#'
181 | '$'
182 | '%'
183 | '&'
184 | '\''
185 | '*'
186 | '+'
187 | '-'
188 | '.'
189 | '^'
190 | '_'
191 | '`'
192 | '|'
193 | '~'
194 )
195}