Skip to main content

mail_builder/headers/
url.rs

1use std::borrow::Cow;
2
3use super::{
4    Header,
5    fold::{FoldWriter, write_control_free},
6};
7use crate::writer::Writer;
8
9/// URL header, used mostly on List-* headers
10#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
11pub struct URL<'x> {
12    pub url: Vec<Cow<'x, str>>,
13}
14
15impl<'x> URL<'x> {
16    /// Create a new URL header
17    pub fn new(url: impl Into<Cow<'x, str>>) -> Self {
18        Self {
19            url: vec![url.into()],
20        }
21    }
22
23    /// Create a new multi-value URL header
24    pub fn new_list<T, U>(urls: T) -> Self
25    where
26        T: Iterator<Item = U>,
27        U: Into<Cow<'x, str>>,
28    {
29        Self {
30            url: urls.map(|s| s.into()).collect(),
31        }
32    }
33}
34
35impl<'x> From<&'x str> for URL<'x> {
36    fn from(value: &'x str) -> Self {
37        Self::new(value)
38    }
39}
40
41impl From<String> for URL<'_> {
42    fn from(value: String) -> Self {
43        Self::new(value)
44    }
45}
46
47impl<'x> From<&[&'x str]> for URL<'x> {
48    fn from(value: &[&'x str]) -> Self {
49        URL {
50            url: value.iter().map(|&s| s.into()).collect(),
51        }
52    }
53}
54
55impl<'x> From<&'x [String]> for URL<'x> {
56    fn from(value: &'x [String]) -> Self {
57        URL {
58            url: value.iter().map(|s| s.into()).collect(),
59        }
60    }
61}
62
63impl<'x, T> From<Vec<T>> for URL<'x>
64where
65    T: Into<Cow<'x, str>>,
66{
67    fn from(value: Vec<T>) -> Self {
68        URL {
69            url: value.into_iter().map(|s| s.into()).collect(),
70        }
71    }
72}
73
74impl Header for URL<'_> {
75    fn write_header(&self, output: &mut impl Writer, column: usize) {
76        let mut folder = FoldWriter::new(output, column);
77
78        if let Some((last, head)) = self.url.split_last() {
79            for url in head {
80                folder.begin_atom(url.len() + 3);
81                folder.write_byte(b'<');
82                write_control_free(&mut folder, url.as_bytes());
83                folder.write(b">,");
84                folder.space();
85            }
86            folder.begin_atom(last.len() + 2);
87            folder.write_byte(b'<');
88            write_control_free(&mut folder, last.as_bytes());
89            folder.write(b">\r\n");
90            return;
91        }
92
93        folder.finish();
94    }
95}