Skip to main content

http_type/cookie/
impl.rs

1use super::*;
2
3/// Implements the `std::error::Error` trait for `CookieError`.
4impl Error for CookieError {}
5
6/// Implements the `Display` trait for `CookieError`.
7impl Display for CookieError {
8    /// Formats the `CookieError` variant into a human-readable string.
9    ///
10    /// # Arguments
11    ///
12    /// - `&mut Formatter<'_>` - The formatter used for writing the formatted string.
13    ///
14    /// # Returns
15    ///
16    /// - `fmt::Result` - The formatting result.
17    #[inline(always)]
18    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
19        match self {
20            Self::InvalidName => write!(f, "Invalid cookie name"),
21            Self::InvalidValue => write!(f, "Invalid cookie value"),
22            Self::InvalidAttribute => write!(f, "Invalid cookie attribute"),
23            Self::Unknown => write!(f, "Unknown cookie error"),
24        }
25    }
26}
27
28/// Implementation for `CookieBuilder`.
29impl CookieBuilder {
30    /// Creates a new cookie builder instance.
31    ///
32    /// # Arguments
33    ///
34    /// - `N` - The cookie name, which requires the `AsRef<str>` bound.
35    /// - `V` - The cookie value, which requires the `AsRef<str>` bound.
36    ///
37    /// # Returns
38    ///
39    /// - `CookieBuilder` - A new builder instance.
40    #[inline(always)]
41    pub fn new<N, V>(name: N, value: V) -> Self
42    where
43        N: AsRef<str>,
44        V: AsRef<str>,
45    {
46        Self {
47            name: name.as_ref().to_owned(),
48            value: value.as_ref().to_owned(),
49            expires: None,
50            max_age: None,
51            domain: None,
52            path: None,
53            secure: None,
54            http_only: None,
55            same_site: None,
56        }
57    }
58
59    /// Parses a `Set-Cookie` header string into a `CookieBuilder`.
60    ///
61    /// This method takes a `Set-Cookie` header string and extracts the various
62    /// attributes of a cookie, populating a `CookieBuilder` instance.
63    ///
64    /// A name that is not a token and a value that carries a control byte are
65    /// refused, because RFC 6265 Section 4.1.1 admits neither in a cookie
66    /// pair, and a name that carries a separator would turn the rest of the
67    /// name into an attribute. An attribute whose value carries a control byte
68    /// or a semicolon is skipped rather than kept, for the same reason.
69    ///
70    /// # Arguments
71    ///
72    /// - `C` - The `Set-Cookie` header string to parse, which requires the `AsRef<str>` bound.
73    ///
74    /// # Returns
75    ///
76    /// A `CookieBuilder` instance populated with the parsed cookie attributes.
77    pub fn parse<C>(cookie: C) -> Self
78    where
79        C: AsRef<str>,
80    {
81        let mut cookie_builder: Self = Self::default();
82        let mut parts: Split<'_, &str> = cookie.as_ref().split(SEMICOLON);
83        let Some(first_part) = parts.next() else {
84            return cookie_builder;
85        };
86        let name_value_pair: &str = first_part.trim();
87        if let Some((name, value)) = name_value_pair.split_once(EQUAL) {
88            let name: &str = name.trim();
89            let value: &str = value.trim();
90            if is_cookie_name_valid(name) && !value.bytes().any(is_control_byte) {
91                cookie_builder.set_name(name);
92                cookie_builder.set_value(value);
93            }
94        }
95        for part in parts {
96            let part: &str = part.trim();
97            if part.is_empty() {
98                continue;
99            }
100            if let Some((key, value)) = part.split_once(EQUAL) {
101                let key: &str = key.trim();
102                let value: &str = value.trim();
103                if !is_cookie_attribute_valid(value) {
104                    continue;
105                }
106                if key.eq_ignore_ascii_case(COOKIE_EXPIRES_LOWERCASE) {
107                    cookie_builder.set_expires(value);
108                } else if key.eq_ignore_ascii_case(COOKIE_MAX_AGE_LOWERCASE) {
109                    if let Ok(max_age_value) = value.parse::<i64>() {
110                        cookie_builder.set_max_age(max_age_value);
111                    }
112                } else if key.eq_ignore_ascii_case(COOKIE_DOMAIN_LOWERCASE) {
113                    cookie_builder.set_domain(value);
114                } else if key.eq_ignore_ascii_case(COOKIE_PATH_LOWERCASE) {
115                    cookie_builder.set_path(value);
116                } else if key.eq_ignore_ascii_case(COOKIE_SAME_SITE_LOWERCASE) {
117                    cookie_builder.set_same_site(value);
118                }
119            } else if part.eq_ignore_ascii_case(COOKIE_SECURE_LOWERCASE) {
120                cookie_builder.secure();
121            } else if part.eq_ignore_ascii_case(COOKIE_HTTP_ONLY_LOWERCASE) {
122                cookie_builder.http_only();
123            }
124        }
125        cookie_builder
126    }
127
128    /// Sets the expiration date for the cookie.
129    ///
130    /// # Arguments
131    ///
132    /// - `E` - The expiration date, which requires the `AsRef<str>` bound.
133    ///
134    /// # Returns
135    ///
136    /// The `CookieBuilder` instance for method chaining.
137    #[inline(always)]
138    pub fn set_expires<E>(&mut self, expires: E) -> &mut Self
139    where
140        E: AsRef<str>,
141    {
142        self.expires = Some(expires.as_ref().to_owned());
143        self
144    }
145
146    /// Sets the maximum age for the cookie in seconds.
147    ///
148    /// # Arguments
149    ///
150    /// - `M` - The maximum age in seconds, which requires the `Into<i64>` bound.
151    ///
152    /// # Returns
153    ///
154    /// The `CookieBuilder` instance for method chaining.
155    #[inline(always)]
156    pub fn set_max_age<M>(&mut self, max_age: M) -> &mut Self
157    where
158        M: Into<i64>,
159    {
160        self.max_age = Some(max_age.into());
161        self
162    }
163
164    /// Sets the domain for the cookie.
165    ///
166    /// # Arguments
167    ///
168    /// - `D` - The domain for the cookie, which requires the `AsRef<str>` bound.
169    ///
170    /// # Returns
171    ///
172    /// The `CookieBuilder` instance for method chaining.
173    #[inline(always)]
174    pub fn set_domain<D>(&mut self, domain: D) -> &mut Self
175    where
176        D: AsRef<str>,
177    {
178        self.domain = Some(domain.as_ref().to_owned());
179        self
180    }
181
182    /// Sets the path for the cookie.
183    ///
184    /// # Arguments
185    ///
186    /// - `T` - The path for the cookie, which requires the `AsRef<str>` bound.
187    ///
188    /// # Returns
189    ///
190    /// The `CookieBuilder` instance for method chaining.
191    #[inline(always)]
192    pub fn set_path<T>(&mut self, path: T) -> &mut Self
193    where
194        T: AsRef<str>,
195    {
196        self.path = Some(path.as_ref().to_owned());
197        self
198    }
199
200    /// Sets the `Secure` flag for the cookie.
201    ///
202    /// This flag indicates that the cookie should only be transmitted over secure (HTTPS) connections.
203    ///
204    /// # Returns
205    ///
206    /// The `CookieBuilder` instance for method chaining.
207    #[inline(always)]
208    pub fn secure(&mut self) -> &mut Self {
209        *self.get_mut_secure() = Some(true);
210        self
211    }
212
213    /// Sets the `HttpOnly` flag for the cookie.
214    ///
215    /// This flag prevents client-side JavaScript from accessing the cookie.
216    ///
217    /// # Returns
218    ///
219    /// The `CookieBuilder` instance for method chaining.
220    #[inline(always)]
221    pub fn http_only(&mut self) -> &mut Self {
222        *self.get_mut_http_only() = Some(true);
223        self
224    }
225
226    /// Explicitly disables the `Secure` flag for the cookie.
227    ///
228    /// This method explicitly sets the `Secure` flag to `false`, which may be useful
229    /// for overriding default secure settings or for testing purposes.
230    ///
231    /// # Returns
232    ///
233    /// The `CookieBuilder` instance for method chaining.
234    #[inline(always)]
235    pub fn disable_secure(&mut self) -> &mut Self {
236        *self.get_mut_secure() = Some(false);
237        self
238    }
239
240    /// Explicitly disables the `HttpOnly` flag for the cookie.
241    ///
242    /// This method explicitly sets the `HttpOnly` flag to `false`, which may be useful
243    /// for overriding default HttpOnly settings or for testing purposes.
244    ///
245    /// # Returns
246    ///
247    /// The `CookieBuilder` instance for method chaining.
248    #[inline(always)]
249    pub fn disable_http_only(&mut self) -> &mut Self {
250        *self.get_mut_http_only() = Some(false);
251        self
252    }
253
254    /// Sets the `SameSite` policy for the cookie.
255    ///
256    /// # Arguments
257    ///
258    /// - `T` - The `SameSite` policy, which requires the `AsRef<str>` bound.
259    ///
260    /// # Returns
261    ///
262    /// The `CookieBuilder` instance for method chaining.
263    #[inline(always)]
264    pub fn set_same_site<T>(&mut self, same_site: T) -> &mut Self
265    where
266        T: AsRef<str>,
267    {
268        self.same_site = Some(same_site.as_ref().to_owned());
269        self
270    }
271
272    /// Builds the cookie string according to the `Set-Cookie` header format.
273    ///
274    /// The name, the value and every attribute are checked against the
275    /// grammar of RFC 6265 Section 4.1.1 first, so a value that carries a
276    /// control byte cannot end the header line and turn the rest of the
277    /// cookie into a second header. A cookie that fails the check is not
278    /// emitted at all, which is safer than emitting a truncated one.
279    ///
280    /// # Returns
281    ///
282    /// - `String` - A formatted cookie string ready to be sent in a `Set-Cookie` header.
283    pub fn build(&self) -> String {
284        self.try_build().unwrap_or_default()
285    }
286
287    /// Builds the cookie string, reporting why a cookie may not be built.
288    ///
289    /// The name, the value and every attribute are checked against the
290    /// grammar of RFC 6265 Section 4.1.1. A name that is not a token would
291    /// end early and turn the rest of it into an attribute, a value that
292    /// carries a control byte would end the header line, and an attribute
293    /// that carries a semicolon would start another attribute.
294    ///
295    /// # Returns
296    ///
297    /// - `Result<String, CookieError>` - The formatted cookie string, or the
298    ///   reason the cookie cannot be represented.
299    pub fn try_build(&self) -> Result<String, CookieError> {
300        if self.get_name().is_empty() {
301            return Err(CookieError::InvalidName);
302        }
303        if !is_cookie_name_valid(self.get_name()) {
304            return Err(CookieError::InvalidName);
305        }
306        if !is_cookie_value_valid(self.get_value()) {
307            return Err(CookieError::InvalidValue);
308        }
309        if let Some(expires_value) = self.try_get_expires()
310            && !is_cookie_attribute_valid(expires_value)
311        {
312            return Err(CookieError::InvalidAttribute);
313        }
314        if let Some(domain_value) = self.try_get_domain()
315            && !is_cookie_attribute_valid(domain_value)
316        {
317            return Err(CookieError::InvalidAttribute);
318        }
319        if let Some(path_value) = self.try_get_path()
320            && !is_cookie_attribute_valid(path_value)
321        {
322            return Err(CookieError::InvalidAttribute);
323        }
324        if let Some(same_site_value) = self.try_get_same_site()
325            && !is_cookie_attribute_valid(same_site_value)
326        {
327            return Err(CookieError::InvalidAttribute);
328        }
329        let mut max_age_buf: [u8; 20] = [0u8; 20];
330        let mut max_age_start: usize = max_age_buf.len();
331        let has_max_age: bool = if let Some(max_age_value) = self.try_get_max_age() {
332            let mut num: u64 = max_age_value.unsigned_abs();
333            loop {
334                max_age_start -= 1;
335                max_age_buf[max_age_start] = ZERO_STR_U8 + (num % 10) as u8;
336                num /= 10;
337                if num == 0 {
338                    break;
339                }
340            }
341            if max_age_value < 0 {
342                max_age_start -= 1;
343                max_age_buf[max_age_start] = COOKIE_MINUS_SIGN;
344            }
345            true
346        } else {
347            false
348        };
349        let mut total_len: usize = self.get_name().len() + 1 + self.get_value().len();
350        if let Some(expires_value) = self.try_get_expires() {
351            total_len += COOKIE_EXPIRES_ATTRIBUTE_LOWERCASE.len() + expires_value.len();
352        }
353        if has_max_age {
354            total_len +=
355                COOKIE_MAX_AGE_ATTRIBUTE_LOWERCASE.len() + (max_age_buf.len() - max_age_start);
356        }
357        if let Some(domain_value) = self.try_get_domain() {
358            total_len += COOKIE_DOMAIN_ATTRIBUTE_LOWERCASE.len() + domain_value.len();
359        }
360        if let Some(path_value) = self.try_get_path() {
361            total_len += COOKIE_PATH_ATTRIBUTE_LOWERCASE.len() + path_value.len();
362        }
363        if let Some(true) = self.try_get_secure() {
364            total_len += COOKIE_SECURE_ATTRIBUTE_LOWERCASE.len();
365        }
366        if let Some(true) = self.try_get_http_only() {
367            total_len += COOKIE_HTTP_ONLY_ATTRIBUTE_LOWERCASE.len();
368        }
369        if let Some(same_site_value) = self.try_get_same_site() {
370            total_len += COOKIE_SAME_SITE_ATTRIBUTE_LOWERCASE.len() + same_site_value.len();
371        }
372        let mut cookie_string: String = String::with_capacity(total_len);
373        cookie_string.push_str(self.get_name());
374        cookie_string.push_str(EQUAL);
375        cookie_string.push_str(self.get_value());
376        if let Some(expires_value) = self.try_get_expires() {
377            cookie_string.push_str(COOKIE_EXPIRES_ATTRIBUTE_LOWERCASE);
378            cookie_string.push_str(expires_value);
379        }
380        if has_max_age {
381            cookie_string.push_str(COOKIE_MAX_AGE_ATTRIBUTE_LOWERCASE);
382            // SAFETY: `max_age_buf[max_age_start..]` contains only ASCII digits and optional '-'.
383            let max_age_str: &str = unsafe { from_utf8_unchecked(&max_age_buf[max_age_start..]) };
384            cookie_string.push_str(max_age_str);
385        }
386        if let Some(domain_value) = self.try_get_domain() {
387            cookie_string.push_str(COOKIE_DOMAIN_ATTRIBUTE_LOWERCASE);
388            cookie_string.push_str(domain_value);
389        }
390        if let Some(path_value) = self.try_get_path() {
391            cookie_string.push_str(COOKIE_PATH_ATTRIBUTE_LOWERCASE);
392            cookie_string.push_str(path_value);
393        }
394        if let Some(true) = self.try_get_secure() {
395            cookie_string.push_str(COOKIE_SECURE_ATTRIBUTE_LOWERCASE);
396        }
397        if let Some(true) = self.try_get_http_only() {
398            cookie_string.push_str(COOKIE_HTTP_ONLY_ATTRIBUTE_LOWERCASE);
399        }
400        if let Some(same_site_value) = self.try_get_same_site() {
401            cookie_string.push_str(COOKIE_SAME_SITE_ATTRIBUTE_LOWERCASE);
402            cookie_string.push_str(same_site_value);
403        }
404        Ok(cookie_string)
405    }
406}
407
408/// Implementation for `Cookie`.
409impl Cookie {
410    /// Finds the first valid cookie value matching `target_name` without allocating a map.
411    ///
412    /// Applies the exact same RFC 6265 validation and first-match precedence as [`Cookie::parse`].
413    ///
414    /// # Arguments
415    ///
416    /// - `&'a str` - Raw `Cookie` header string.
417    /// - `&str` - Cookie name to search for.
418    ///
419    /// # Returns
420    ///
421    /// - `Option<&'a str>` - Borrowed cookie value slice if found and valid.
422    #[inline]
423    pub fn find_value<'a>(cookie: &'a str, target_name: &str) -> Option<&'a str> {
424        if target_name.is_empty() || !is_cookie_name_valid(target_name) {
425            return None;
426        }
427        for part in cookie.split(SEMICOLON) {
428            let trimmed: &str = part.trim();
429            if trimmed.is_empty() {
430                continue;
431            }
432            if let Some((name, value)) = trimmed.split_once(EQUAL) {
433                let name: &str = name.trim();
434                if name == target_name {
435                    let value: &str = value.trim();
436                    if !value.bytes().any(is_control_byte) {
437                        return Some(value);
438                    }
439                }
440            }
441        }
442        None
443    }
444
445    /// Parses a `Cookie` header string into a collection of key-value pairs.
446    ///
447    /// This method takes a `Cookie` header string (typically from a `Cookie` request header)
448    /// and parses it into a map of cookie names to their values.
449    ///
450    /// A pair whose name is not a token and a pair whose value carries a
451    /// control byte are skipped, because RFC 6265 Section 4.1.1 admits
452    /// neither, and a name that carries a separator would let the rest of
453    /// the name be read as part of the value.
454    ///
455    /// # Arguments
456    ///
457    /// - `C` - The `Cookie` header string to parse, which requires the `AsRef<str>` bound.
458    ///
459    /// # Returns
460    ///
461    /// A `HashMapXxHash3_64<String, String>` collection (a hash map) containing all parsed cookie key-value pairs.
462    pub fn parse<C>(cookie: C) -> HashMapXxHash3_64<String, String>
463    where
464        C: AsRef<str>,
465    {
466        let cookie_ref: &str = cookie.as_ref();
467        if cookie_ref.trim().is_empty() {
468            return hash_map_xx_hash3_64();
469        }
470        let estimated: usize = cookie_ref
471            .as_bytes()
472            .iter()
473            .filter(|byte: &&u8| **byte == SEMICOLON_U8)
474            .count()
475            + 1;
476        let mut cookies: HashMapXxHash3_64<String, String> =
477            HashMap::with_capacity_and_hasher(estimated, BuildHasherDefault::default());
478        for part in cookie_ref.split(SEMICOLON) {
479            let part: &str = part.trim();
480            if part.is_empty() {
481                continue;
482            }
483            if let Some((name, value)) = part.split_once(EQUAL) {
484                let name: &str = name.trim();
485                let value: &str = value.trim();
486                if is_cookie_name_valid(name)
487                    && !value.bytes().any(is_control_byte)
488                    && !cookies.contains_key(name)
489                {
490                    cookies.insert(name.to_owned(), value.to_owned());
491                }
492            }
493        }
494        cookies
495    }
496}