aboutsummaryrefslogtreecommitdiff
path: root/src/xml.rs
blob: d3b088eb783d80a781b1b427ac53a7f8c843de6f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use std::{
  collections::HashMap,
  fmt::{Display, Write},
};

pub struct Item {
  fields: HashMap<String, String>,
}
impl Item {
  pub fn builder() -> Self { Self { fields: HashMap::new() } }

  pub fn add_field(&mut self, key: &str, value: &str) -> &mut Self {
    self.fields.insert(key.to_string(), value.to_string());

    self
  }
}
impl Display for Item {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(
      f,
      "<item>{}</item>",
      self.fields.iter().fold(String::new(), |mut acc, (k, v)| {
        let _ = write!(acc, "<{k}>{v}</{k}>");

        acc
      })
    )
  }
}

#[derive(Clone)]
pub struct Writer {
  content: String,
  fields:  HashMap<String, String>,
  link:    String,
}
impl Writer {
  pub fn builder() -> Self {
    Self {
      content: String::new(),
      fields:  HashMap::default(),
      link:    String::new(),
    }
  }

  pub fn add_link(&mut self, link: &str) -> &mut Self {
    self.link = link.to_string();

    self
  }

  pub fn add_field(&mut self, key: &str, value: &str) -> &mut Self {
    self.fields.insert(key.to_string(), value.to_string());

    self
  }

  pub fn add_item(&mut self, item: &Item) -> &mut Self {
    self.content.push_str(&item.to_string());

    self
  }
}
impl Display for Writer {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    write!(
      f,
      "<?xml version=\"1.0\" encoding=\"UTF-8\"?><rss xmlns:atom=\"http://www.w3.org/2005/Atom\" \
       version=\"2.0\"><channel>{}<atom:link href=\"{}\" rel=\"self\" \
       type=\"application/rss+xml\" />{}</channel></rss>",
      self.fields.iter().fold(String::new(), |mut acc, (k, v)| {
        let _ = write!(acc, "<{k}>{v}</{k}>");

        acc
      }),
      self.link,
      self.content
    )
  }
}