]> Untitled Git - lemmy.git/blob - crates/apub_lib/src/values.rs
Federate with Peertube (#2244)
[lemmy.git] / crates / apub_lib / src / values.rs
1 //! The enums here serve to limit a json string value to a single, hardcoded value which can be
2 //! verified at compilation time. When using it as the type of a struct field, the struct can only
3 //! be constructed or deserialized if the field has the exact same value.
4 //!
5 //! If we used String as the field type, any value would be accepted, and we would have to check
6 //! manually at runtime that it contains the expected value.
7 //!
8 //! The enums in [`activitystreams::activity::kind`] work in the same way, and can be used to
9 //! distinguish different activity types.
10 //!
11 //! In the example below, `MyObject` can only be constructed or
12 //! deserialized if `media_type` is `text/markdown`, but not if it is `text/html`.
13 //!
14 //! ```
15 //! use lemmy_apub_lib::values::MediaTypeMarkdown;
16 //! use serde_json::from_str;
17 //! use serde::{Deserialize, Serialize};
18 //!
19 //! #[derive(Deserialize, Serialize)]
20 //! struct MyObject {
21 //!   content: String,
22 //!   media_type: MediaTypeMarkdown,
23 //! }
24 //!
25 //! let markdown_json = r#"{"content": "**test**", "media_type": "text/markdown"}"#;
26 //! let from_markdown = from_str::<MyObject>(markdown_json);
27 //! assert!(from_markdown.is_ok());
28 //!
29 //! let markdown_html = r#"{"content": "<b>test</b>", "media_type": "text/html"}"#;
30 //! let from_html = from_str::<MyObject>(markdown_html);
31 //! assert!(from_html.is_err());
32 //! ```
33
34 use serde::{Deserialize, Serialize};
35
36 /// Media type for markdown text.
37 ///
38 /// <https://www.iana.org/assignments/media-types/media-types.xhtml>
39 #[derive(Clone, Debug, Deserialize, Serialize)]
40 pub enum MediaTypeMarkdown {
41   #[serde(rename = "text/markdown")]
42   Markdown,
43 }
44
45 /// Media type for HTML text.
46 ///
47 /// <https://www.iana.org/assignments/media-types/media-types.xhtml>
48 #[derive(Clone, Debug, Deserialize, Serialize)]
49 pub enum MediaTypeHtml {
50   #[serde(rename = "text/html")]
51   Html,
52 }
53 /// Media type which allows both markdown and HTML.
54 #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
55 pub enum MediaTypeMarkdownOrHtml {
56   #[serde(rename = "text/markdown")]
57   Markdown,
58   #[serde(rename = "text/html")]
59   Html,
60 }