Debian Codegraph @

debian/rust-vendor/icu_segmenter/src/grapheme.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 use alloc::vec::Vec;
6 use icu_provider::prelude::*;
7
8 use crate::indices::*;
9 use crate::provider::*;
10 use crate::scaffold::*;
11
12 /// Implements the [`Iterator`] trait over the grapheme cluster boundaries of the given string.
13 ///
14 /// Lifetimes:
15 ///
16 /// - `'data` = lifetime of the segmenter object from which this iterator was created
17 /// - `'s` = lifetime of the string being segmented
18 ///
19 /// The [`Iterator::Item`] is an [`usize`] representing index of a code unit
20 /// _after_ the boundary (for a boundary at the end of text, this index is the length
21 /// of the [`str`] or array of code units).
22 ///
23 /// For examples of use, see [`GraphemeClusterSegmenter`].
24 #[derive(Debug)]
25 pub struct GraphemeClusterBreakIterator<'data, 's, Y: RuleBreakType>(
26 pub(crate) GraphemeClusterBreakIteratorInner<'data, 's, Y>,
27 );
28
29 #[derive(Debug)]
30 pub(crate) enum GraphemeClusterBreakIteratorInner<'data, 's, Y: RuleBreakType> {
31 V1(crate::rule_segmenter_v1::RuleBreakIterator<'data, 's, Y>),
32 #[cfg(feature = "unstable")]
33 V2(crate::rule_segmenter_v2::RuleBreakIterator<'data, 's, Y>),
34 }
35
36 impl<'data, 's, Y: RuleBreakType> GraphemeClusterBreakIterator<'data, 's, Y> {
37 /// TODO(#8196): do we want to expose clone on this?
38 pub(crate) fn clone_internal(&self) -> Self {
39 let inner = match &self.0 {
40 GraphemeClusterBreakIteratorInner::V1(iter) => {
41 GraphemeClusterBreakIteratorInner::V1(crate::rule_segmenter_v1::RuleBreakIterator {
42 iter: iter.iter.clone(),
43 len: iter.len,
44 current_pos_data: iter.current_pos_data,
45 result_cache: iter.result_cache.clone(),
46 data: iter.data,
47 complex: iter.complex,
48 boundary_property: iter.boundary_property,
49 locale_override: iter.locale_override,
50 handle_complex: iter.handle_complex,
51 })
52 }
53 #[cfg(feature = "unstable")]
54 GraphemeClusterBreakIteratorInner::V2(iter) => {
55 GraphemeClusterBreakIteratorInner::V2(crate::rule_segmenter_v2::RuleBreakIterator {
56 data: iter.data,
57 pseudo_symbol_map: iter.pseudo_symbol_map,
58 cache: iter.cache.clone(),
59 lookahead_positions: iter.lookahead_positions.clone(),
60 remaining_input: iter.remaining_input.clone(),
61 last_accepting_status: iter.last_accepting_status,
62 complex: iter.complex,
63 })
64 }
65 };
66 Self(inner)
67 }
68 }
69
70 impl<Y: RuleBreakType> Iterator for GraphemeClusterBreakIterator<'_, '_, Y> {
71 type Item = usize;
72 #[inline]
73 fn next(&mut self) -> Option<Self::Item> {
74 match &mut self.0 {
75 GraphemeClusterBreakIteratorInner::V1(iter) => iter.next(),
76 #[cfg(feature = "unstable")]
77 GraphemeClusterBreakIteratorInner::V2(iter) => iter.next(),
78 }
79 }
80 }
81
82 /// Segments a string into grapheme clusters.
83 ///
84 /// Supports loading grapheme cluster break data, and creating grapheme cluster break iterators for
85 /// different string encodings.
86 ///
87 /// Most segmentation methods live on [`GraphemeClusterSegmenterBorrowed`], which can be obtained via
88 /// [`GraphemeClusterSegmenter::new()`] or [`GraphemeClusterSegmenter::as_borrowed()`].
89 ///
90 /// Grapheme cluster segmenter is currently compatible with [Unicode Standard Annex #29][UAX29] (Version 17.0.0).
91 ///
92 /// [UAX29]: https://www.unicode.org/reports/tr29/tr29-47.html
93 ///
94 /// # Examples
95 ///
96 /// Segment a string:
97 ///
98 /// ```rust
99 /// use icu::segmenter::GraphemeClusterSegmenter;
100 /// let segmenter = GraphemeClusterSegmenter::new();
101 ///
102 /// let breakpoints: Vec<usize> = segmenter.segment_str("Hello 🗺").collect();
103 /// // World Map (U+1F5FA) is encoded in four bytes in UTF-8.
104 /// assert_eq!(&breakpoints, &[0, 1, 2, 3, 4, 5, 6, 10]);
105 /// ```
106 ///
107 /// Segment a Latin1 byte string:
108 ///
109 /// ```rust
110 /// use icu::segmenter::GraphemeClusterSegmenter;
111 /// let segmenter = GraphemeClusterSegmenter::new();
112 ///
113 /// let breakpoints: Vec<usize> =
114 /// segmenter.segment_latin1(b"Hello World").collect();
115 /// assert_eq!(&breakpoints, &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
116 /// ```
117 ///
118 /// Successive boundaries can be used to retrieve the grapheme clusters.
119 /// In particular, the first boundary is always 0, and the last one is the
120 /// length of the segmented text in code units.
121 ///
122 /// ```rust
123 /// # use icu::segmenter::GraphemeClusterSegmenter;
124 /// # let segmenter =
125 /// # GraphemeClusterSegmenter::new();
126 /// use itertools::Itertools;
127 /// let text = "मांजर";
128 /// let grapheme_clusters: Vec<&str> = segmenter
129 /// .segment_str(text)
130 /// .tuple_windows()
131 /// .map(|(i, j)| &text[i..j])
132 /// .collect();
133 /// assert_eq!(&grapheme_clusters, &["मां", "ज", "र"]);
134 /// ```
135 ///
136 /// This segmenter applies all rules provided to the constructor.
137 /// Thus, if the data supplied by the provider comprises all
138 /// [grapheme cluster boundary rules][Rules] from Unicode Standard Annex #29,
139 /// _Unicode Text Segmentation_, which is the case of default data
140 /// (both test data and data produced by `icu_provider_source`), the `segment_*`
141 /// functions return extended grapheme cluster boundaries, as opposed to
142 /// legacy grapheme cluster boundaries. See [_Section 3, Grapheme Cluster
143 /// Boundaries_][GC], and [_Table 1a, Sample Grapheme Clusters_][Sample_GC],
144 /// in Unicode Standard Annex #29, _Unicode Text Segmentation_.
145 ///
146 /// [Rules]: https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules
147 /// [GC]: https://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
148 /// [Sample_GC]: https://www.unicode.org/reports/tr29/#Table_Sample_Grapheme_Clusters
149 ///
150 /// ```rust
151 /// use icu::segmenter::GraphemeClusterSegmenter;
152 /// let segmenter =
153 /// GraphemeClusterSegmenter::new();
154 ///
155 /// // நி (TAMIL LETTER NA, TAMIL VOWEL SIGN I) is an extended grapheme cluster,
156 /// // but not a legacy grapheme cluster.
157 /// let ni = "நி";
158 /// let egc_boundaries: Vec<usize> = segmenter.segment_str(ni).collect();
159 /// assert_eq!(&egc_boundaries, &[0, ni.len()]);
160 /// ```
161 #[derive(Debug)]
162 pub struct GraphemeClusterSegmenter(GraphemeClusterSegmenterInner);
163
164 #[derive(Debug)]
165 enum GraphemeClusterSegmenterInner {
166 V1(DataPayload<SegmenterBreakGraphemeClusterV1>),
167 #[cfg(feature = "unstable")]
168 V2(DataPayload<SegmenterBreakGraphemeClusterV2>),
169 }
170
171 /// Segments a string into grapheme clusters (borrowed version).
172 ///
173 /// See [`GraphemeClusterSegmenter`] for examples.
174 #[derive(Clone, Debug, Copy)]
175 pub struct GraphemeClusterSegmenterBorrowed<'data>(
176 pub(crate) GraphemeClusterSegmenterBorrowedInner<'data>,
177 );
178
179 #[derive(Clone, Debug, Copy)]
180 pub(crate) enum GraphemeClusterSegmenterBorrowedInner<'data> {
181 V1(&'data RuleBreakData<'data>),
182 #[cfg(feature = "unstable")]
183 V2(&'data SegmenterStateMachine<'data>),
184 }
185
186 impl GraphemeClusterSegmenter {
187 /// Constructs a [`GraphemeClusterSegmenterBorrowed`] with an invariant locale from compiled data.
188 ///
189 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
190 ///
191 /// [📚 Help choosing a constructor](icu_provider::constructors)
192 #[cfg(feature = "compiled_data")]
193 #[expect(clippy::new_ret_no_self)] // Deliberate choice, see #5554
194 pub const fn new() -> GraphemeClusterSegmenterBorrowed<'static> {
195 GraphemeClusterSegmenterBorrowed(GraphemeClusterSegmenterBorrowedInner::V1(
196 Baked::SINGLETON_SEGMENTER_BREAK_GRAPHEME_CLUSTER_V1,
197 ))
198 }
199
200 icu_provider::gen_buffer_data_constructors!(() -> error: DataError,
201 functions: [
202 new: skip,
203 try_new_with_buffer_provider,
204 try_new_unstable,
205 Self,
206 ]);
207
208 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new)]
209 pub fn try_new_unstable<D>(provider: &D) -> Result<Self, DataError>
210 where
211 D: DataProvider<SegmenterBreakGraphemeClusterV1> + ?Sized,
212 {
213 let payload = provider.load(Default::default())?.payload;
214 Ok(Self(GraphemeClusterSegmenterInner::V1(payload)))
215 }
216
217 /// Constructs a [`GraphemeClusterSegmenterBorrowed`] with an invariant locale from compiled data.
218 ///
219 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
220 ///
221 /// [📚 Help choosing a constructor](icu_provider::constructors)
222 #[cfg(feature = "compiled_data")]
223 #[cfg(feature = "unstable")]
224 pub const fn new_neo() -> GraphemeClusterSegmenterBorrowed<'static> {
225 GraphemeClusterSegmenterBorrowed(GraphemeClusterSegmenterBorrowedInner::V2(
226 Baked::SINGLETON_SEGMENTER_BREAK_GRAPHEME_CLUSTER_V2,
227 ))
228 }
229
230 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new_neo)]
231 #[cfg(feature = "unstable")]
232 pub fn try_new_neo_unstable<D>(provider: &D) -> Result<Self, DataError>
233 where
234 D: DataProvider<SegmenterBreakGraphemeClusterV2> + ?Sized,
235 {
236 let payload = provider.load(Default::default())?.payload;
237 Ok(Self(GraphemeClusterSegmenterInner::V2(payload)))
238 }
239
240 /// Constructs a borrowed version of this type for more efficient querying.
241 ///
242 /// Most useful methods for segmentation are on this type.
243 pub fn as_borrowed(&self) -> GraphemeClusterSegmenterBorrowed<'_> {
244 GraphemeClusterSegmenterBorrowed(match &self.0 {
245 GraphemeClusterSegmenterInner::V1(payload) => {
246 GraphemeClusterSegmenterBorrowedInner::V1(payload.get())
247 }
248 #[cfg(feature = "unstable")]
249 GraphemeClusterSegmenterInner::V2(payload) => {
250 GraphemeClusterSegmenterBorrowedInner::V2(payload.get())
251 }
252 })
253 }
254 }
255
256 impl<'data> GraphemeClusterSegmenterBorrowed<'data> {
257 pub(crate) fn segment<'s, Y: RuleBreakType>(
258 self,
259 iter: Y::IterAttr<'s>,
260 len: usize,
261 ) -> GraphemeClusterBreakIterator<'data, 's, Y> {
262 GraphemeClusterBreakIterator(match self.0 {
263 GraphemeClusterSegmenterBorrowedInner::V1(data) => {
264 GraphemeClusterBreakIteratorInner::V1(crate::rule_segmenter_v1::RuleBreakIterator {
265 iter,
266 len,
267 current_pos_data: None,
268 result_cache: Vec::new(),
269 data,
270 complex: None,
271 boundary_property: 0,
272 locale_override: None,
273 handle_complex: crate::rule_segmenter_v1::empty_handle_complex,
274 })
275 }
276 #[cfg(feature = "unstable")]
277 GraphemeClusterSegmenterBorrowedInner::V2(data) => {
278 GraphemeClusterBreakIteratorInner::V2(
279 crate::rule_segmenter_v2::RuleBreakIterator::new(iter, data, None, None),
280 )
281 }
282 })
283 }
284
285 /// Creates a grapheme cluster break iterator for an `str` (a UTF-8 string).
286 pub fn segment_str<'s>(self, input: &'s str) -> GraphemeClusterBreakIterator<'data, 's, Utf8> {
287 self.segment(input.char_indices(), input.len())
288 }
289 /// Creates a grapheme cluster break iterator for a potentially ill-formed UTF8 string
290 ///
291 /// Invalid characters are treated as REPLACEMENT CHARACTER
292 ///
293 /// There are always breakpoints at 0 and the string length, or only at 0 for the empty string.
294 pub fn segment_utf8<'s>(
295 self,
296 input: &'s [u8],
297 ) -> GraphemeClusterBreakIterator<'data, 's, PotentiallyIllFormedUtf8> {
298 self.segment(Utf8CharIndices::new(input), input.len())
299 }
300
301 /// Creates a grapheme cluster break iterator for a Latin-1 (8-bit) string.
302 ///
303 /// There are always breakpoints at 0 and the string length, or only at 0 for the empty string.
304 pub fn segment_latin1<'s>(
305 self,
306 input: &'s [u8],
307 ) -> GraphemeClusterBreakIterator<'data, 's, Latin1> {
308 self.segment(Latin1Indices::new(input), input.len())
309 }
310
311 /// Creates a grapheme cluster break iterator for a UTF-16 string.
312 ///
313 /// There are always breakpoints at 0 and the string length, or only at 0 for the empty string.
314 pub fn segment_utf16<'s>(
315 self,
316 input: &'s [u16],
317 ) -> GraphemeClusterBreakIterator<'data, 's, Utf16> {
318 self.segment(Utf16Indices::new(input), input.len())
319 }
320 }
321
322 impl GraphemeClusterSegmenterBorrowed<'static> {
323 /// Cheaply converts a [`GraphemeClusterSegmenterBorrowed<'static>`] into a [`GraphemeClusterSegmenter`].
324 ///
325 /// Note: Due to branching and indirection, using [`GraphemeClusterSegmenter`] might inhibit some
326 /// compile-time optimizations that are possible with [`GraphemeClusterSegmenterBorrowed`].
327 pub const fn static_to_owned(self) -> GraphemeClusterSegmenter {
328 GraphemeClusterSegmenter(match self.0 {
329 GraphemeClusterSegmenterBorrowedInner::V1(data) => {
330 GraphemeClusterSegmenterInner::V1(DataPayload::from_static_ref(data))
331 }
332 #[cfg(feature = "unstable")]
333 GraphemeClusterSegmenterBorrowedInner::V2(data) => {
334 GraphemeClusterSegmenterInner::V2(DataPayload::from_static_ref(data))
335 }
336 })
337 }
338 }
339
340 #[cfg(test)]
341 mod test {
342 use crate::*;
343
344 include!("../tests/helpers.rs.raw");
345
346 #[test]
347 fn empty_string() {
348 let segmenter = GraphemeClusterSegmenter::new();
349 let breaks: Vec<usize> = segmenter.segment_str("").collect();
350 assert_eq!(breaks, [0]);
351 }
352
353 #[test]
354 fn emoji_flags() {
355 // https://github.com/unicode-org/icu4x/issues/4780
356 check_grapheme("🇺🇸🏴󠁧󠁢󠁥󠁮󠁧󠁿", &["🇺🇸", "🏴󠁧󠁢󠁥󠁮󠁧󠁿"], GraphemeClusterSegmenter::new());
357 }
358 #[test]
359 fn empty_string_neo() {
360 let segmenter = GraphemeClusterSegmenter::new_neo();
361 let breaks: Vec<usize> = segmenter.segment_str("").collect();
362 assert_eq!(breaks, [0]);
363 }
364
365 #[test]
366 fn emoji_flags_neo() {
367 // https://github.com/unicode-org/icu4x/issues/4780
368 check_grapheme("🇺🇸🏴", &["🇺🇸", "🏴"], GraphemeClusterSegmenter::new_neo());
369 }
370 }