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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
Copyright (C) 2021 Kunal Mehta <legoktm@debian.org>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

use crate::private::Sealed;
use crate::Wikicode;

/// An immutable version of `Wikicode` that implements [`Send`](https://doc.rust-lang.org/std/marker/trait.Send.html)
/// and [`Sync`](https://doc.rust-lang.org/std/marker/trait.Sync.html). It
/// can be used interchangably with a normal `Wikicode` for API methods.
///
/// You can also use `From`/`Into` in both directions between `Wikicode`
/// and `ImmutableWikicode`.
#[derive(Clone, Debug)]
pub struct ImmutableWikicode {
    pub(crate) html: String,
    pub(crate) title: Option<String>,
    pub(crate) etag: Option<String>,
    pub(crate) revid: Option<u64>,
}

impl ImmutableWikicode {
    pub fn new(html: &str) -> Self {
        Self {
            html: html.to_string(),
            title: None,
            etag: None,
            revid: None,
        }
    }

    pub fn html(&self) -> &str {
        &self.html
    }

    pub fn title(&self) -> Option<String> {
        self.title.clone()
    }

    pub fn etag(&self) -> Option<&str> {
        self.etag.as_deref()
    }

    pub fn revision_id(&self) -> Option<u64> {
        self.revid
    }

    pub fn into_mutable(self) -> Wikicode {
        self.into()
    }
}

impl From<Wikicode> for ImmutableWikicode {
    fn from(code: Wikicode) -> Self {
        Self {
            html: code.to_string(),
            revid: code.revision_id(),
            title: code.title,
            etag: code.etag,
        }
    }
}

impl From<ImmutableWikicode> for Wikicode {
    fn from(immutable: ImmutableWikicode) -> Self {
        let mut code = Wikicode::new(&immutable.html);
        code.etag = immutable.etag;
        code.title = immutable.title;
        code
    }
}

impl Sealed for ImmutableWikicode {}

#[cfg(test)]
mod tests {
    use super::*;

    fn assert_sync_send<T: Sync + Send>() {}

    #[test]
    fn test_immutable() {
        assert_sync_send::<ImmutableWikicode>();
    }
}