Skip to main content

mail_builder/headers/
url.rs

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