gh_emoji/
lib.rs

1
2use crate::data_generated::EMOJI;
3use std::borrow::Cow;
4use regex::{
5    Regex,
6    Captures,
7};
8
9mod data_generated;
10
11/// Find Unicode representation for given emoji name
12///
13/// The name should be without `:`, e.g. `smile`.
14///
15/// Case sensitive. Returns `None` if the name is not recognized.
16pub fn get(name: &str) -> Option<&str> {
17    EMOJI.get(name).map(|s| *s)
18}
19
20/// List all known emoji
21///
22/// Returns iterator of `(name, unicode)`
23pub fn all() -> impl Iterator<Item=(&'static str, &'static str)> {
24    EMOJI.entries.iter().map(|&x| x)
25}
26
27/// Replaces `:emoji:` in strings
28///
29/// ```rust
30/// let r = gh_emoji::Replacer::new();
31/// let unicode_text = r.replace_all("Hello :cat:!");
32/// ```
33pub struct Replacer {
34    regex: Regex
35}
36
37impl Replacer {
38    /// There is some small setup cost
39    pub fn new() -> Self {
40        Self {
41            regex: Regex::new(r":([a-z1238+-][a-z0-9_-]*):").unwrap(),
42        }
43    }
44
45    /// Replaces all occurrences of `:emoji_names:` in the string
46    ///
47    /// It may return `Cow::Borrowed` if there were no emoji-like
48    /// patterns in the string. Call `.to_string()` if you need
49    /// `String` or `.as_ref()` to get `&str`.
50    pub fn replace_all<'a>(&self, text: &'a str) -> Cow<'a, str> {
51        self.regex.replace_all(text, EmojiRegexReplacer)
52    }
53}
54
55struct EmojiRegexReplacer;
56impl regex::Replacer for EmojiRegexReplacer {
57    fn replace_append(&mut self, capts: &Captures<'_>, dst: &mut String) {
58        dst.push_str(EMOJI.get(&capts[1]).copied().unwrap_or_else(|| &capts[0]));
59    }
60}
61
62#[test]
63fn replacer() {
64    let r = Replacer::new();
65    assert_eq!("hello 😄 :not_emoji_404:", r.replace_all("hello :smile: :not_emoji_404:"));
66    assert_eq!(Replacer::new().replace_all(":cat: make me :smile:"), "\u{01F431} make me \u{01F604}");
67}
68
69#[test]
70fn get_existing() {
71    assert_eq!(get("smile"), Some("\u{01F604}"));
72    assert_eq!(get("poop"),  Some("\u{01F4A9}"));
73    assert_eq!(get("cat"),   Some("\u{01F431}"));
74    assert_eq!(get("+1"),    Some("👍"));
75    assert_eq!(get("-1"),    Some("\u{01F44E}"));
76    assert_eq!(get("8ball"), Some("\u{01F3B1}"));
77}
78
79#[test]
80fn get_nonexistent() {
81    assert_eq!(get("stuff"), None);
82    assert_eq!(get("++"), None);
83    assert_eq!(get("--"), None);
84    assert_eq!(get("666"), None);
85}