1use teloxide_core::types::{User, UserId};
6
7pub(super) const ESCAPE_CHARS: [char; 19] = [
8 '\\', '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!',
9];
10
11#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
16 without using its output does nothing useful"]
17pub fn bold(s: &str) -> String {
18 format!("*{s}*")
19}
20
21#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
26 without using its output does nothing useful"]
27pub fn blockquote(s: &str) -> String {
28 format!("**>{}", s.replace('\n', "\n>"))
29}
30
31#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
36 without using its output does nothing useful"]
37pub fn expandable_blockquote(s: &str) -> String {
38 format!("**>{}||", s.replace('\n', "\n>"))
39}
40
41#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
47 without using its output does nothing useful"]
48pub fn italic(s: &str) -> String {
49 if s.starts_with("__") && s.ends_with("__") {
50 format!(r"_{}\r__", &s[..s.len() - 1])
51 } else {
52 format!("_{s}_")
53 }
54}
55
56#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
62 without using its output does nothing useful"]
63pub fn underline(s: &str) -> String {
64 if s.starts_with('_') && s.ends_with('_') {
70 format!(r"__{s}\r__")
71 } else {
72 format!("__{s}__")
73 }
74}
75
76#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
81 without using its output does nothing useful"]
82pub fn strike(s: &str) -> String {
83 format!("~{s}~")
84}
85
86#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
90 without using its output does nothing useful"]
91pub fn link(url: &str, text: &str) -> String {
92 format!("[{}]({})", text, escape_link_url(url))
93}
94
95#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
97 without using its output does nothing useful"]
98pub fn user_mention(user_id: UserId, text: &str) -> String {
99 link(format!("tg://user?id={user_id}").as_str(), text)
100}
101
102#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
106 without using its output does nothing useful"]
107pub fn code_block(code: &str) -> String {
108 format!("```\n{}\n```", escape_code(code))
109}
110
111#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
115 without using its output does nothing useful"]
116pub fn code_block_with_lang(code: &str, lang: &str) -> String {
117 format!("```{}\n{}\n```", escape(lang), escape_code(code))
118}
119
120#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
124 without using its output does nothing useful"]
125pub fn code_inline(s: &str) -> String {
126 format!("`{}`", escape_code(s))
127}
128
129#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
134 without using its output does nothing useful"]
135pub fn escape(s: &str) -> String {
136 s.chars().fold(String::with_capacity(s.len()), |mut s, c| {
137 if ESCAPE_CHARS.contains(&c) {
138 s.push('\\');
139 }
140 s.push(c);
141 s
142 })
143}
144
145#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
148 without using its output does nothing useful"]
149pub fn escape_link_url(s: &str) -> String {
150 s.chars().fold(String::with_capacity(s.len()), |mut s, c| {
151 if ['`', ')'].contains(&c) {
152 s.push('\\');
153 }
154 s.push(c);
155 s
156 })
157}
158
159#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
162 without using its output does nothing useful"]
163pub fn escape_code(s: &str) -> String {
164 s.chars().fold(String::with_capacity(s.len()), |mut s, c| {
165 if ['`', '\\'].contains(&c) {
166 s.push('\\');
167 }
168 s.push(c);
169 s
170 })
171}
172
173#[must_use = "This function returns a new string, rather than mutating the argument, so calling it \
174 without using its output does nothing useful"]
175pub fn user_mention_or_link(user: &User) -> String {
176 match user.mention() {
177 Some(mention) => escape(&mention),
178 None => link(user.url().as_str(), &escape(&user.full_name())),
179 }
180}
181
182#[cfg(test)]
183mod tests {
184 use super::*;
185
186 #[test]
187 fn test_bold() {
188 assert_eq!(bold(" foobar "), "* foobar *");
189 assert_eq!(bold(" _foobar_ "), "* _foobar_ *");
190 assert_eq!(bold("~(`foobar`)~"), "*~(`foobar`)~*");
191 }
192
193 #[test]
194 fn test_italic() {
195 assert_eq!(italic(" foobar "), "_ foobar _");
196 assert_eq!(italic("*foobar*"), "_*foobar*_");
197 assert_eq!(italic("~(foobar)~"), "_~(foobar)~_");
198 }
199
200 #[test]
201 fn test_underline() {
202 assert_eq!(underline(" foobar "), "__ foobar __");
203 assert_eq!(underline("*foobar*"), "__*foobar*__");
204 assert_eq!(underline("~(foobar)~"), "__~(foobar)~__");
205 }
206
207 #[test]
208 fn test_strike() {
209 assert_eq!(strike(" foobar "), "~ foobar ~");
210 assert_eq!(strike("*foobar*"), "~*foobar*~");
211 assert_eq!(strike("*(foobar)*"), "~*(foobar)*~");
212 }
213
214 #[test]
215 fn test_italic_with_underline() {
216 assert_eq!(underline(italic("foobar").as_str()), r"___foobar_\r__");
217 assert_eq!(italic(underline("foobar").as_str()), r"___foobar_\r__");
218 }
219
220 #[test]
221 fn test_link() {
222 assert_eq!(
223 link("https://www.google.com/(`foobar`)", "google"),
224 r"[google](https://www.google.com/(\`foobar\`\))",
225 );
226 }
227
228 #[test]
229 fn test_user_mention() {
230 assert_eq!(
231 user_mention(UserId(123_456_789), "pwner666"),
232 "[pwner666](tg://user?id=123456789)"
233 );
234 }
235
236 #[test]
237 fn test_blockquote() {
238 assert_eq!(blockquote("foobar\n\nfoo\nbar"), "**>foobar\n>\n>foo\n>bar");
239 }
240
241 #[test]
242 fn test_expandable_blockquote() {
243 assert_eq!(expandable_blockquote("foobar\n\nfoo\nbar"), "**>foobar\n>\n>foo\n>bar||");
244 }
245
246 #[test]
247 fn test_code_block() {
248 assert_eq!(
249 code_block("pre-'formatted'\nfixed-width \\code `block`"),
250 "```\npre-'formatted'\nfixed-width \\\\code \\`block\\`\n```"
251 );
252 }
253
254 #[test]
255 fn test_code_block_with_lang() {
256 assert_eq!(
257 code_block_with_lang("pre-'formatted'\nfixed-width \\code `block`", "[python]"),
258 "```\\[python\\]\npre-'formatted'\nfixed-width \\\\code \\`block\\`\n```"
259 );
260 }
261
262 #[test]
263 fn test_code_inline() {
264 assert_eq!(code_inline(" let x = (1, 2, 3); "), "` let x = (1, 2, 3); `");
265 assert_eq!(code_inline("<html>foo</html>"), "`<html>foo</html>`");
266 assert_eq!(code_inline(r" `(code inside code \ )` "), r"` \`(code inside code \\ )\` `");
267 }
268
269 #[test]
270 fn test_escape() {
271 assert_eq!(escape("\\!"), r"\\\!");
272 assert_eq!(escape("* foobar *"), r"\* foobar \*");
273 assert_eq!(
274 escape(r"_ * [ ] ( ) ~ \ ` > # + - = | { } . !"),
275 r"\_ \* \[ \] \( \) \~ \\ \` \> \# \+ \- \= \| \{ \} \. \!",
276 );
277 }
278
279 #[test]
280 fn test_escape_link_url() {
281 assert_eq!(
282 escape_link_url(r"https://en.wikipedia.org/wiki/Development+(Software)"),
283 r"https://en.wikipedia.org/wiki/Development+(Software\)"
284 );
285 assert_eq!(
286 escape_link_url(r"https://en.wikipedia.org/wiki/`"),
287 r"https://en.wikipedia.org/wiki/\`"
288 );
289 assert_eq!(escape_link_url(r"_*[]()~`#+-=|{}.!\"), r"_*[](\)~\`#+-=|{}.!\");
290 }
291
292 #[test]
293 fn test_escape_code() {
294 assert_eq!(escape_code(r"` \code inside the code\ `"), r"\` \\code inside the code\\ \`");
295 assert_eq!(escape_code(r"_*[]()~`#+-=|{}.!\"), r"_*[]()~\`#+-=|{}.!\\");
296 }
297
298 #[test]
299 fn user_mention_link() {
300 let user_with_username = User {
301 id: UserId(0),
302 is_bot: false,
303 first_name: "".to_string(),
304 last_name: None,
305 username: Some("abcd".to_string()),
306 language_code: None,
307 is_premium: false,
308 added_to_attachment_menu: false,
309 };
310 assert_eq!(user_mention_or_link(&user_with_username), "@abcd");
311 let user_with_username_underscore =
314 User { username: Some("Abcd_Efg".to_string()), ..user_with_username };
315 assert_eq!(user_mention_or_link(&user_with_username_underscore), "@Abcd\\_Efg");
316 let user_without_username = User {
317 id: UserId(123_456_789),
318 is_bot: false,
319 first_name: "Name".to_string(),
320 last_name: None,
321 username: None,
322 language_code: None,
323 is_premium: false,
324 added_to_attachment_menu: false,
325 };
326 assert_eq!(user_mention_or_link(&user_without_username), "[Name](tg://user/?id=123456789)")
327 }
328}