terminal_emoji/lib.rs
1use std::fmt;
2use terminal_supports_emoji::{supports_emoji, Stream};
3
4/// An emoji with safety fallback.
5///
6/// The struct wraps an emoji and only renders it on platforms that actually
7/// support it. On non-supported platforms the fallback value is being rendered.
8///
9/// Support is determined by two factors:
10///
11/// 1) The processes stdout has to be a tty.
12/// 2) Platform dependent:
13/// - macOS has emoji support by default
14/// - Unix systems have support if the active language supports them.
15/// - Windows machines running the new Terminal app support emojis.
16#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
17#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
18pub struct Emoji<'a>(pub &'a str, pub &'a str);
19
20impl<'a> Emoji<'a> {
21 /// Create a new emoji.
22 ///
23 /// # Arguments
24 ///
25 /// - `emoji`: The unicode emoji to display.
26 /// - `fallback`: The fallback value to use on non-supported platforms.
27 pub const fn new(emoji: &'a str, fallback: &'a str) -> Self {
28 Self(emoji, fallback)
29 }
30}
31
32impl fmt::Display for Emoji<'_> {
33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 if supports_emoji(Stream::Stdout) {
35 write!(f, "{}", self.0)
36 } else {
37 write!(f, "{}", self.1)
38 }
39 }
40}
41
42impl<'a> From<(&'a str, &'a str)> for Emoji<'a> {
43 fn from(v: (&'a str, &'a str)) -> Self {
44 Emoji(v.0, v.1)
45 }
46}