Skip to main content

grapheme_cluster_utils/
lib.rs

1//! # grapheme-cluster-utils
2//!
3//! Utilities for manipulating Rust `String`s at the level of
4//! **extended grapheme clusters**, as defined in [Unicode Standard Annex #29](https://www.unicode.org/reports/tr29/).
5//!
6//! Unlike `char` (Unicode scalar values), grapheme clusters
7//! correspond to *user-perceived characters*. For example:
8//!
9//! - `"πŸ‘©β€πŸš€"` is 3 code points but 1 grapheme cluster.
10//! - `"πŸ‡ΊπŸ‡Έ"` is 2 code points but 1 grapheme cluster.
11//! - `"é"` (e + combining accent) is 2 code points but 1 grapheme cluster.
12//!
13//! These helpers make it easy to remove, insert, or replace graphemes
14//! without accidentally splitting multi-codepoint clusters.
15
16use unicode_segmentation::UnicodeSegmentation;
17
18/// Extension trait providing Unicode-safe string manipulation
19/// at the level of extended grapheme clusters.
20pub trait GraphemeClusterUtils {
21    /// Remove the grapheme cluster at index `n`.
22    ///
23    /// Returns a new `String`.
24    fn remove_grapheme_at(&self, n: usize) -> String;
25
26    /// Insert a string slice at grapheme cluster index `n`.
27    ///
28    /// Returns a new `String`.
29    fn insert_grapheme_at(&self, n: usize, insert: &str) -> String;
30
31    /// Replace the grapheme cluster at index `n` with `replacement`.
32    ///
33    /// Returns a new `String`.
34    fn replace_grapheme_at(&self, n: usize, replacement: &str) -> String;
35}
36
37impl GraphemeClusterUtils for String {
38    fn remove_grapheme_at(&self, n: usize) -> String {
39        let mut graphemes: Vec<&str> = self.graphemes(true).collect();
40        if n < graphemes.len() {
41            graphemes.remove(n);
42        }
43        graphemes.concat()
44    }
45
46    fn insert_grapheme_at(&self, n: usize, insert: &str) -> String {
47        let mut graphemes: Vec<&str> = self.graphemes(true).collect();
48        if n <= graphemes.len() {
49            graphemes.insert(n, insert);
50        }
51        graphemes.concat()
52    }
53
54    fn replace_grapheme_at(&self, n: usize, replacement: &str) -> String {
55        let mut graphemes: Vec<&str> = self.graphemes(true).collect();
56        if n < graphemes.len() {
57            graphemes[n] = replacement;
58        }
59        graphemes.concat()
60    }
61}