emojis/lib.rs
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 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
//! ✨ Lookup emoji in *O(1)* time, access metadata and GitHub shortcodes,
//! iterate over all emoji.
//!
//! # Features
//!
//! - Lookup up emoji by Unicode value
//! - Lookup up emoji by GitHub shortcode ([gemoji] v4.1.0)
//! - Access emoji metadata: name, unicode version, group, skin tone, [gemoji] shortcodes
//! - Iterate over emojis in Unicode CLDR order
//! - Iterate over emojis in an emoji group, e.g. "Smileys & Emotion" or "Flags"
//! - Iterate over the skin tones for an emoji
//! - Select a specific skin tone for an emoji
//! - Uses [Unicode v16.0](https://unicode.org/emoji/charts-16.0/emoji-released.html) emoji specification
//!
//! [gemoji]: https://github.com/github/gemoji
//!
//! # Getting started
//!
//! First, add the `emojis` crate to your Cargo manifest.
//!
//! ```sh
//! cargo add emojis
//! ```
//!
//! Simply use the `get()` function to lookup emojis by Unicode value.
//! ```
//! let rocket = emojis::get("🚀").unwrap();
//! ```
//!
//! Or the `get_by_shortcode()` function to lookup emojis by [gemoji] shortcode.
//!
//! ```
//! let rocket = emojis::get_by_shortcode("rocket").unwrap();
//! ```
//!
//! These operations take *Ο(1)* time.
//!
//! # MSRV
//!
//! Currently the minimum supported Rust version is 1.60 due to the dependency
//! on [`phf`]. The policy of this crate is to only increase the MSRV in a
//! breaking release.
//!
//! # Breaking changes
//!
//! When [gemoji] or the Unicode version is upgraded this is not considered a
//! breaking change, instead you should make sure to use
//! [`unicode_version()`][Emoji::unicode_version] to filter out newer versions.
//!
//! # Examples
//!
//! See [examples/replace.rs] for an example that replaces `:gemoji:` names with
//! real emojis in text.
//!
//! ```sh
//! $ echo "launch :rocket:" | cargo run --example replace
//! launch 🚀
//! ```
//!
//! [`get()`][get] and [`get_by_shortcode()`][get_by_shortcode] return an
//! [`Emoji`] struct which contains various metadata regarding the emoji.
//! ```
//! let hand = emojis::get("🤌").unwrap();
//! assert_eq!(hand.as_str(), "\u{1f90c}");
//! assert_eq!(hand.as_bytes(), &[0xf0, 0x9f, 0xa4, 0x8c]);
//! assert_eq!(hand.name(), "pinched fingers");
//! assert_eq!(hand.unicode_version(), emojis::UnicodeVersion::new(13, 0));
//! assert_eq!(hand.group(), emojis::Group::PeopleAndBody);
//! assert_eq!(hand.skin_tone(), Some(emojis::SkinTone::Default));
//! assert_eq!(hand.shortcode(), Some("pinched_fingers"));
//! ```
//!
//! Use [`skin_tones()`][Emoji::skin_tones] to iterate over the skin tones of an
//! emoji.
//! ```
//! let raised_hands = emojis::get("🙌🏼").unwrap();
//! let skin_tones: Vec<_> = raised_hands.skin_tones().unwrap().map(|e| e.as_str()).collect();
//! assert_eq!(skin_tones, ["🙌", "🙌🏻", "🙌🏼", "🙌🏽", "🙌🏾", "🙌🏿"]);
//! ```
//!
//! You can use the [`iter()`] function to iterate over all emojis. This only
//! includes the default skin tone versions.
//! ```
//! let faces: Vec<_> = emojis::iter().map(|e| e.as_str()).take(5).collect();
//! assert_eq!(faces, ["😀", "😃", "😄", "😁", "😆"]);
//! ```
//!
//! It is recommended to filter the list by the maximum Unicode version that you
//! wish to support.
//! ```
//! let iter = emojis::iter().filter(|e| {
//! e.unicode_version() < emojis::UnicodeVersion::new(13, 0)
//! });
//! ```
//!
//! Using the [`Group`] enum you can iterate over all emojis in a group.
//! ```
//! let fruit: Vec<_> = emojis::Group::FoodAndDrink.emojis().map(|e| e.as_str()).take(5).collect();
//! assert_eq!(fruit, ["🍇", "🍈", "🍉", "🍊", "🍋"]);
//! ```
//!
//! [examples/replace.rs]: https://github.com/rossmacarthur/emojis/blob/trunk/examples/replace.rs
//! [gemoji]: https://github.com/github/gemoji
#![no_std]
#[cfg(test)]
extern crate alloc;
mod gen;
use core::cmp;
use core::convert;
use core::fmt;
use core::hash;
pub use crate::gen::Group;
/// Represents an emoji.
///
/// See [Unicode.org](https://unicode.org/emoji/charts/full-emoji-list.html) for
/// more information.
#[derive(Debug)]
pub struct Emoji {
emoji: &'static str,
name: &'static str,
unicode_version: UnicodeVersion,
group: Group,
// Stores the id of the emoji with the default skin tone, the number of
// skin tones and then the skin tone of the current emoji.
//
// (<id>, <n>, <skin_tone>)
//
skin_tone: Option<(u16, u8, SkinTone)>,
aliases: Option<&'static [&'static str]>,
}
/// A Unicode version.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct UnicodeVersion {
major: u32,
minor: u32,
}
/// The skin tone of an emoji.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum SkinTone {
Default,
Light,
MediumLight,
Medium,
MediumDark,
Dark,
LightAndMediumLight,
LightAndMedium,
LightAndMediumDark,
LightAndDark,
MediumLightAndLight,
MediumLightAndMedium,
MediumLightAndMediumDark,
MediumLightAndDark,
MediumAndLight,
MediumAndMediumLight,
MediumAndMediumDark,
MediumAndDark,
MediumDarkAndLight,
MediumDarkAndMediumLight,
MediumDarkAndMedium,
MediumDarkAndDark,
DarkAndLight,
DarkAndMediumLight,
DarkAndMedium,
DarkAndMediumDark,
}
impl UnicodeVersion {
/// Construct a new version.
#[inline]
pub const fn new(major: u32, minor: u32) -> Self {
Self { major, minor }
}
#[inline]
pub const fn major(self) -> u32 {
self.major
}
#[inline]
pub const fn minor(self) -> u32 {
self.minor
}
}
impl Emoji {
/// Returns this emoji as a string.
///
/// # Examples
///
/// ```
/// let rocket = emojis::get("🚀").unwrap();
/// assert_eq!(rocket.as_str(), "🚀")
/// ```
#[inline]
pub const fn as_str(&self) -> &str {
self.emoji
}
/// Returns this emoji as slice of UTF-8 encoded bytes.
///
/// # Examples
///
/// ```
/// let rocket = emojis::get("🚀").unwrap();
/// assert_eq!(rocket.as_bytes(), &[0xf0, 0x9f, 0x9a, 0x80]);
/// ```
#[inline]
pub const fn as_bytes(&self) -> &[u8] {
self.emoji.as_bytes()
}
/// Returns the CLDR name for this emoji.
///
/// # Examples
///
/// ```
/// let cool = emojis::get("😎").unwrap();
/// assert_eq!(cool.name(), "smiling face with sunglasses");
/// ```
#[inline]
pub const fn name(&self) -> &str {
self.name
}
/// Returns the Unicode version this emoji first appeared in.
///
/// # Examples
///
/// ```
/// use emojis::UnicodeVersion;
///
/// let villain = emojis::get("🦹").unwrap();
/// assert_eq!(villain.unicode_version(), UnicodeVersion::new(11, 0));
/// ```
#[inline]
pub const fn unicode_version(&self) -> UnicodeVersion {
self.unicode_version
}
/// Returns the group this emoji belongs to.
///
/// # Examples
///
/// ```
/// use emojis::Group;
///
/// let flag = emojis::get("🇿🇦").unwrap();
/// assert_eq!(flag.group(), Group::Flags);
/// ```
#[inline]
pub const fn group(&self) -> Group {
self.group
}
/// Returns the skin tone of this emoji.
///
/// # Examples
///
/// ```
/// use emojis::SkinTone;
///
/// let peace = emojis::get("✌️").unwrap();
/// assert_eq!(peace.skin_tone(), Some(SkinTone::Default));
///
/// let peace = emojis::get("✌🏽").unwrap();
/// assert_eq!(peace.skin_tone(), Some(SkinTone::Medium));
/// ```
///
/// For emojis where skin tones are not applicable this will be `None`.
///
/// ```
/// let cool = emojis::get("😎").unwrap();
/// assert!(cool.skin_tone().is_none());
/// ```
#[inline]
pub fn skin_tone(&self) -> Option<SkinTone> {
self.skin_tone.map(|(_, _, v)| v)
}
/// Returns an iterator over the emoji and all the related skin tone emojis.
///
/// # Examples
///
/// ```
/// use emojis::Emoji;
///
/// let luck = emojis::get("🤞🏼").unwrap();
/// let skin_tones: Vec<_> = luck.skin_tones().unwrap().map(Emoji::as_str).collect();
/// assert_eq!(skin_tones, ["🤞", "🤞🏻", "🤞🏼", "🤞🏽", "🤞🏾", "🤞🏿"]);
/// ```
///
/// Some emojis have 26 skin tones!
///
/// ```
/// use emojis::SkinTone;
///
/// let couple = emojis::get("👩🏿❤️👨🏼").unwrap();
/// let skin_tones = couple.skin_tones().unwrap().count();
/// assert_eq!(skin_tones, 26);
/// ```
///
/// For emojis where skin tones are not applicable this will return `None`.
///
/// ```
/// let cool = emojis::get("😎").unwrap();
/// assert!(cool.skin_tones().is_none());
/// ```
#[inline]
pub fn skin_tones(&self) -> Option<impl Iterator<Item = &Self> + Clone> {
let (i, n, _) = self.skin_tone?;
Some(crate::gen::EMOJIS[i as usize..].iter().take(n as usize))
}
/// Returns a version of this emoji that has the given skin tone.
///
/// # Examples
///
/// ```
/// use emojis::SkinTone;
///
/// let raised_hands = emojis::get("🙌🏼")
/// .unwrap()
/// .with_skin_tone(SkinTone::MediumDark)
/// .unwrap();
/// assert_eq!(raised_hands, emojis::get("🙌🏾").unwrap());
/// ```
///
/// ```
/// use emojis::SkinTone;
///
/// let couple = emojis::get("👩❤️👨")
/// .unwrap()
/// .with_skin_tone(SkinTone::DarkAndMediumLight)
/// .unwrap();
/// assert_eq!(couple, emojis::get("👩🏿❤️👨🏼").unwrap());
/// ```
///
/// For emojis where the skin tone is not applicable this will return
/// `None`.
///
/// ```
/// use emojis::SkinTone;
///
/// let cool = emojis::get("😎").unwrap();
/// assert!(cool.with_skin_tone(SkinTone::Medium).is_none());
/// ```
#[inline]
pub fn with_skin_tone(&self, skin_tone: SkinTone) -> Option<&Self> {
self.skin_tones()?
.find(|emoji| emoji.skin_tone().unwrap() == skin_tone)
}
/// Returns the first GitHub shortcode for this emoji.
///
/// Most emojis only have zero or one shortcode but for a few there are
/// multiple. Use the [`shortcodes()`][Emoji::shortcodes] method to return
/// all the shortcodes. See [gemoji] for more information.
///
/// For emojis that have zero shortcodes this will return `None`.
///
/// # Examples
///
/// ```
/// let thinking = emojis::get("🤔").unwrap();
/// assert_eq!(thinking.shortcode().unwrap(), "thinking");
/// ```
///
/// [gemoji]: https://github.com/github/gemoji
#[inline]
pub fn shortcode(&self) -> Option<&str> {
self.aliases.and_then(|aliases| aliases.first().copied())
}
/// Returns an iterator over the GitHub shortcodes for this emoji.
///
/// Most emojis only have zero or one shortcode but for a few there are
/// multiple. Use the [`shortcode()`][Emoji::shortcode] method to return the
/// first shortcode. See [gemoji] for more information.
///
/// For emojis that have zero shortcodes this will return an empty iterator.
///
/// # Examples
///
/// ```
/// let laughing = emojis::get("😆").unwrap();
/// assert_eq!(
/// laughing.shortcodes().collect::<Vec<_>>(),
/// vec!["laughing", "satisfied"]
/// );
/// ```
///
/// [gemoji]: https://github.com/github/gemoji
#[inline]
pub fn shortcodes(&self) -> impl Iterator<Item = &str> + Clone {
self.aliases.into_iter().flatten().copied()
}
}
impl cmp::PartialEq<Emoji> for Emoji {
#[inline]
fn eq(&self, other: &Emoji) -> bool {
self.emoji == other.emoji
}
}
impl cmp::PartialEq<str> for Emoji {
#[inline]
fn eq(&self, s: &str) -> bool {
self.as_str() == s
}
}
impl cmp::PartialEq<&str> for Emoji {
#[inline]
fn eq(&self, s: &&str) -> bool {
self.as_str() == *s
}
}
impl cmp::Eq for Emoji {}
impl hash::Hash for Emoji {
#[inline]
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.emoji.hash(state);
}
}
impl convert::AsRef<str> for Emoji {
#[inline]
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl convert::AsRef<[u8]> for Emoji {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl fmt::Display for Emoji {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.as_str().fmt(f)
}
}
#[cfg(feature = "serde")]
impl serde::Serialize for &'static Emoji {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.as_str())
}
}
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for &'static Emoji {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct Visitor;
impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = &'static Emoji;
fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
formatter.write_str("a string representing an emoji")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
crate::get(value).ok_or_else(|| E::custom("invalid emoji"))
}
}
deserializer.deserialize_str(Visitor)
}
}
impl Group {
/// Returns an iterator over all groups.
///
/// # Examples
///
/// ```
/// let mut iter = emojis::Group::iter();
/// assert_eq!(iter.next().unwrap(), emojis::Group::SmileysAndEmotion);
/// assert_eq!(iter.next().unwrap(), emojis::Group::PeopleAndBody);
/// ```
#[inline]
pub fn iter() -> impl Iterator<Item = Group> + Clone {
[
Self::SmileysAndEmotion,
Self::PeopleAndBody,
Self::AnimalsAndNature,
Self::FoodAndDrink,
Self::TravelAndPlaces,
Self::Activities,
Self::Objects,
Self::Symbols,
Self::Flags,
]
.iter()
.copied()
}
/// Returns an iterator over all emojis in this group.
///
/// # Examples
///
/// ```
/// let flags: Vec<_> = emojis::Group::Flags.emojis().map(|e| e.as_str()).take(5).collect();
/// assert_eq!(flags, ["🏁", "🚩", "🎌", "🏴", "🏳️"]);
/// ```
#[inline]
pub fn emojis(&self) -> impl Iterator<Item = &'static Emoji> {
let group = *self;
iter()
.skip_while(move |emoji| emoji.group != group)
.take_while(move |emoji| emoji.group == group)
}
}
/// Returns an iterator over all emojis.
///
/// - Ordered by Unicode CLDR data.
/// - Excludes non-default skin tones.
///
/// # Examples
///
/// ```
/// let faces: Vec<_> = emojis::iter().map(|e| e.as_str()).take(5).collect();
/// assert_eq!(faces, ["😀", "😃", "😄", "😁", "😆"]);
/// ```
#[inline]
pub fn iter() -> impl Iterator<Item = &'static Emoji> + Clone {
crate::gen::EMOJIS
.iter()
.filter(|emoji| matches!(emoji.skin_tone(), Some(SkinTone::Default) | None))
}
/// Lookup an emoji by Unicode value.
///
/// This take *Ο(1)* time.
///
/// # Note
///
/// If passed a minimally qualified or unqualified emoji this will return the
/// emoji struct containing the fully qualified version.
///
/// # Examples
///
/// In the ordinary case.
///
/// ```
/// let emoji = "🚀";
/// let rocket = emojis::get(emoji).unwrap();
/// assert!(rocket.as_str() == emoji);
/// assert_eq!(rocket.shortcode().unwrap(), "rocket");
/// ```
///
/// For a minimally qualified or unqualified emoji.
///
/// ```
/// let unqualified = "\u{1f43f}";
/// let fully_qualified = "\u{1f43f}\u{fe0f}";
/// let chipmunk = emojis::get(unqualified).unwrap();
/// assert_eq!(chipmunk.as_str(), fully_qualified);
/// assert_eq!(chipmunk.shortcode().unwrap(), "chipmunk");
/// ```
#[inline]
pub fn get(s: &str) -> Option<&'static Emoji> {
crate::gen::unicode::MAP
.get(s)
.map(|&i| &crate::gen::EMOJIS[i])
}
/// Lookup an emoji by GitHub shortcode.
///
/// This take *Ο(1)* time.
///
/// # Examples
///
/// ```
/// let rocket = emojis::get_by_shortcode("rocket").unwrap();
/// assert_eq!(rocket, "🚀");
/// ```
#[inline]
pub fn get_by_shortcode(s: &str) -> Option<&'static Emoji> {
crate::gen::shortcode::MAP
.get(s)
.map(|&i| &crate::gen::EMOJIS[i])
}