Skip to main content

layout/flow/inline/
text_transform.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! # Logic for text transform in inline formatting contexts
6//!
7//! Inline formatting contexts do a variety of text transformations on their text content
8//! including white space collapsing, application of the `text-transform` CSS property,
9//! and application of the `-webkit-text-security` property. This module contains code to
10//! handle this as well as code to map from offsets in the original DOM node to the final
11//! IFC text and vice-versa.
12
13use arrayvec::ArrayVec;
14use icu_segmenter::WordSegmenter;
15use malloc_size_of_derive::MallocSizeOf;
16use servo_base::text::Utf32CodeUnits;
17use style::computed_values::_webkit_text_security::T as WebKitTextSecurity;
18use style::computed_values::white_space_collapse::T as WhiteSpaceCollapse;
19use style::properties::ComputedValues;
20use style::values::specified::text::{TextTransform, TextTransformCase};
21
22use crate::flow::inline::construct::InlineFormattingContextBuilder;
23
24/// <https://github.com/rust-lang/rust/blob/1.97.1/library/core/src/char/mod.rs#L523>
25///
26/// This is the maximum amount of characters that can be produced from case mapping,
27/// and by consequence the maximum amount of characters that can be produced during
28/// inline formatting context text transformation.
29const MAX_CASE_MAPPING_LENGTH: usize = 3;
30
31/// A single iteration in a pipeline of character iterators, that handle things like
32/// whitespace collapse and `text-transform` processing for text in an
33/// [`InlineFormattingContext`]. Each iteration can consume multiple characters and
34/// produce zero or more characters (up to 3). Consumption of characters greater than the
35/// characters produced by [`CharacterTransformIteration`] indicate that those characters
36/// have been collapsed.
37#[derive(Clone)]
38pub struct CharacterTransformIteration {
39    /// The number of characters consumed during this iteration of character transformation.
40    consumed: Utf32CodeUnits,
41    /// The characters that were produced during this iteration.
42    characters: ArrayVec<char, MAX_CASE_MAPPING_LENGTH>,
43}
44
45impl CharacterTransformIteration {
46    fn case_mapped(iterator: impl ExactSizeIterator<Item = char>) -> Self {
47        debug_assert!(iterator.len() <= MAX_CASE_MAPPING_LENGTH);
48        Self {
49            consumed: Utf32CodeUnits(1),
50            characters: iterator.collect(),
51        }
52    }
53
54    fn one_to_one(character: char) -> Self {
55        Self {
56            consumed: Utf32CodeUnits(1),
57            characters: std::iter::once(character).collect(),
58        }
59    }
60
61    fn collapse(amount_collapsed: usize, character: Option<char>) -> Self {
62        Self {
63            consumed: Utf32CodeUnits(amount_collapsed),
64            characters: character.into_iter().collect(),
65        }
66    }
67
68    fn is_one_to_one(&self) -> bool {
69        self.characters.len() == 1 && self.consumed.0 == 1
70    }
71
72    pub fn characters(&self) -> &[char] {
73        &self.characters
74    }
75}
76
77pub struct WhitespaceCollapse<InputIterator> {
78    input_iterator: InputIterator,
79    white_space_collapse: WhiteSpaceCollapse,
80
81    /// Whether or not we are in the process of collapse leading white space. This is true
82    /// when the last character handled in our owning [`super::InlineFormattingContext`]
83    /// was collapsible white space and we have not seen any non-whitespace characters
84    /// during processing of this iterator's input.
85    trimming_leading_white_space: bool,
86
87    /// Whether or not the last character produced was newline. There is special behavior
88    /// we do after each newline.
89    following_newline: bool,
90
91    /// When whitespace collapses before a non-whitespace character, the iterator returns
92    /// the collapsed whitespace and in the next iteration the non-whitespace character
93    /// must be returned. This value caches it until the next iteration.
94    character_pending_to_return: Option<char>,
95}
96
97impl<InputIterator: Iterator<Item = char>> WhitespaceCollapse<InputIterator> {
98    pub fn new(
99        input_iterator: InputIterator,
100        white_space_collapse: WhiteSpaceCollapse,
101        should_trim_leading_white_space: bool,
102    ) -> Self {
103        Self {
104            input_iterator,
105            white_space_collapse,
106            following_newline: false,
107            trimming_leading_white_space: should_trim_leading_white_space,
108            character_pending_to_return: None,
109        }
110    }
111
112    /// In some cases, white space is replaced by a single character (when not
113    /// following a newline and when leading whitespace is not being trimmed). In all
114    /// other cases, the white space is simply removed. This method handles that.
115    fn iteration_for_collapsed_whitespace(
116        &self,
117        collapsed_whitespace: usize,
118    ) -> CharacterTransformIteration {
119        if !self.following_newline && !self.trimming_leading_white_space {
120            CharacterTransformIteration::collapse(collapsed_whitespace, Some(' '))
121        } else {
122            CharacterTransformIteration::collapse(collapsed_whitespace, None)
123        }
124    }
125
126    fn iteration_for_collected_white_space(
127        &self,
128        collected_whitespace: usize,
129    ) -> Option<CharacterTransformIteration> {
130        (collected_whitespace != 0)
131            .then(|| self.iteration_for_collapsed_whitespace(collected_whitespace))
132    }
133}
134
135impl<InputIterator: Iterator<Item = char>> Iterator for WhitespaceCollapse<InputIterator> {
136    type Item = CharacterTransformIteration;
137
138    fn next(&mut self) -> Option<Self::Item> {
139        // Point 4.1.1 first bullet:
140        // > If white-space is set to normal, nowrap, or pre-line, whitespace
141        // > characters are considered collapsible
142        // If whitespace is not considered collapsible, it is preserved entirely, which
143        // means that we can simply return the input string exactly.
144        if self.white_space_collapse == WhiteSpaceCollapse::Preserve ||
145            self.white_space_collapse == WhiteSpaceCollapse::BreakSpaces
146        {
147            // From <https://drafts.csswg.org/css-text-3/#white-space-processing>:
148            // > Carriage returns (U+000D) are treated identically to spaces (U+0020) in all respects.
149            //
150            // In the non-preserved case these are converted to space below.
151            return match self.input_iterator.next() {
152                Some('\r') => Some(CharacterTransformIteration::one_to_one(' ')),
153                next => next.map(CharacterTransformIteration::one_to_one),
154            };
155        }
156
157        if let Some(character) = self.character_pending_to_return.take() {
158            // Once we produce a non-whitespace character, we are no longer trimming leading whitespace.
159            self.trimming_leading_white_space = false;
160            self.following_newline = false;
161            return Some(CharacterTransformIteration::one_to_one(character));
162        }
163
164        // When we enter a collapsible white space region, we may need to wait to produce
165        // a single white space character as soon as we encounter a non-white space
166        // character. When that happens we queue up the non-white space character for the
167        // next iterator call.
168        let mut collected_whitespace = 0;
169
170        while let Some(character) = self.input_iterator.next() {
171            // Don't push non-newline whitespace immediately. Instead wait to push it until we
172            // know that it isn't followed by a newline. See `push_pending_whitespace_if_needed`
173            // above.
174            if InlineFormattingContextBuilder::is_document_white_space(character) &&
175                character != '\n'
176            {
177                collected_whitespace += 1;
178                continue;
179            }
180
181            // Point 4.1.1:
182            // > 2. Collapsible segment breaks are transformed for rendering according to the
183            // >    segment break transformation rules.
184            if character == '\n' {
185                // From <https://drafts.csswg.org/css-text-3/#line-break-transform>
186                // (4.1.3 -- the segment break transformation rules):
187                //
188                // > When white-space is pre, pre-wrap, or pre-line, segment breaks are not
189                // > collapsible and are instead transformed into a preserved line feed"
190                //
191                // > 1. First, any collapsible segment break immediately following another
192                // >    collapsible segment break is removed.
193                // > 2. Then any remaining segment break is either transformed into a space (U+0020)
194                // >    or removed depending on the context before and after the break.
195                let iteration = if self.white_space_collapse != WhiteSpaceCollapse::Collapse {
196                    CharacterTransformIteration::collapse(collected_whitespace + 1, Some('\n'))
197                } else {
198                    self.iteration_for_collapsed_whitespace(collected_whitespace + 1)
199                };
200
201                self.following_newline = true;
202                return Some(iteration);
203            }
204
205            // Non-whitespace character
206
207            // Point 4.1.1:
208            // > 2. Any sequence of collapsible spaces and tabs immediately preceding or
209            // >    following a segment break is removed.
210            // > 3. Every collapsible tab is converted to a collapsible space (U+0020).
211            // > 4. Any collapsible space immediately following another collapsible space—even
212            // >    one outside the boundary of the inline containing that space, provided both
213            // >    spaces are within the same inline formatting context—is collapsed to have zero
214            // >    advance width.
215            if let Some(iteration) = self.iteration_for_collected_white_space(collected_whitespace)
216            {
217                self.character_pending_to_return = Some(character);
218                return Some(iteration);
219            }
220
221            // Once we produce a non-whitespace character, we are no longer trimming leading whitespace.
222            self.trimming_leading_white_space = false;
223            self.following_newline = false;
224            return Some(CharacterTransformIteration::one_to_one(character));
225        }
226
227        self.iteration_for_collected_white_space(collected_whitespace)
228    }
229}
230
231pub(crate) struct TextTransformationIterator<'a>(
232    Box<dyn Iterator<Item = CharacterTransformIteration> + 'a>,
233);
234
235impl<'a> TextTransformationIterator<'a> {
236    pub(crate) fn new(
237        text: &'a str,
238        style: &ComputedValues,
239        trim_leading_white_space: bool,
240        on_word_boundary: bool,
241    ) -> Self {
242        let text_security = style.clone__webkit_text_security();
243
244        // <https://drafts.csswg.org/css-text-4/#text-transform-property>
245        let text_transform = style.clone_text_transform();
246        let full_size_kana = text_transform.intersects(TextTransform::FULL_SIZE_KANA);
247        // TODO: Implement `full-width` here
248        let _full_width = text_transform.intersects(TextTransform::FULL_WIDTH);
249        // TODO: Enable `math-auto` in Stylo and implement it here
250
251        let chars = text.chars().map(move |character| {
252            let character = map_character_for_webkit_text_security(text_security, character);
253            map_character_for_full_size_kana(full_size_kana, character)
254        });
255        let white_space_collapse = style.clone_white_space_collapse();
256        let iterator =
257            WhitespaceCollapse::new(chars, white_space_collapse, trim_leading_white_space);
258
259        let iterator = match text_transform.case() {
260            TextTransformCase::None => {
261                Box::new(iterator) as Box<dyn Iterator<Item = CharacterTransformIteration>>
262            },
263            TextTransformCase::Lowercase => {
264                Box::new(simple_case_transform_iterator(iterator, |character| {
265                    CharacterTransformIteration::case_mapped(character.to_lowercase())
266                }))
267            },
268            TextTransformCase::Uppercase => {
269                Box::new(simple_case_transform_iterator(iterator, |character| {
270                    CharacterTransformIteration::case_mapped(character.to_uppercase())
271                }))
272            },
273            TextTransformCase::Capitalize => Box::new(capitalization_iterator(
274                iterator,
275                text.len(),
276                on_word_boundary,
277            )),
278        };
279
280        Self(iterator)
281    }
282}
283
284impl Iterator for TextTransformationIterator<'_> {
285    type Item = CharacterTransformIteration;
286    fn next(&mut self) -> Option<Self::Item> {
287        self.0.next()
288    }
289}
290
291fn simple_case_transform_iterator(
292    input_iterator: impl Iterator<Item = CharacterTransformIteration>,
293    mapping: impl Fn(char) -> CharacterTransformIteration,
294) -> impl Iterator<Item = CharacterTransformIteration> {
295    input_iterator.map(move |iteration| {
296        if iteration.is_one_to_one() {
297            mapping(iteration.characters[0])
298        } else {
299            iteration
300        }
301    })
302}
303
304/// Given an input iterator, a size hint for the number items in the iterator,
305/// and a boolean determining whether the start of the input represents a word
306/// boundary, return an iterator that capitalizes one-to-one mapped characters
307/// from the input iterator.
308pub(crate) fn capitalization_iterator(
309    input_iterator: impl Iterator<Item = CharacterTransformIteration>,
310    size_hint: usize,
311    allow_word_at_start: bool,
312) -> impl Iterator<Item = CharacterTransformIteration> {
313    let mut iterations: Vec<_> = input_iterator.collect();
314    let mut string = String::with_capacity(size_hint);
315    for iteration in &iterations {
316        string.extend(iteration.characters());
317    }
318
319    let word_segmenter = WordSegmenter::new_auto();
320    let mut bounds = word_segmenter.segment_str(&string).peekable();
321
322    let mut current_byte_index = 0;
323    for iteration in iterations.iter_mut() {
324        let bytes_to_advance: usize = iteration
325            .characters()
326            .iter()
327            .map(|character| character.len_utf8())
328            .sum();
329        if bytes_to_advance == 0 {
330            continue;
331        }
332
333        let at_word_start = bounds.peek() == Some(&current_byte_index);
334        if at_word_start {
335            bounds.next();
336        }
337
338        // TODO: currently we titlecase the first `char` of each word,
339        // instead it should be the first typographic letter unit:
340        // https://drafts.csswg.org/css-text-4/#typographic-letter-unit
341        // WPT /css/css-text/text-transform/text-transform-capitalize-026.html
342        if iteration.is_one_to_one() &&
343            at_word_start &&
344            (current_byte_index != 0 || allow_word_at_start)
345        {
346            // TODO: Replace this with a call to `character.to_titlecase()` when available:
347            // See: https://github.com/rust-lang/rust/issues/153892
348            // See: https://doc.rust-lang.org/stable/std/primitive.char.html#difference-from-uppercase
349            *iteration =
350                CharacterTransformIteration::case_mapped(iteration.characters[0].to_uppercase());
351        }
352
353        current_byte_index += bytes_to_advance;
354    }
355
356    iterations.into_iter()
357}
358
359/// Map a character according to the rules of the `-webkit-text-security` CSS property.
360///
361/// Note: The behavior of `-webkit-text-security` isn't specified, so we have some
362/// flexibility in the implementation. We just need to maintain a rough compatibility with
363/// other browsers.
364fn map_character_for_webkit_text_security(mode: WebKitTextSecurity, character: char) -> char {
365    if let WebKitTextSecurity::None = mode {
366        return character;
367    }
368
369    // TODO: When MSRV is 1.95+ use std::hint::cold_path().
370    match character {
371        // This is not ideal, but zero width space is used for some special reasons in
372        // `<input>` fields, so these remain untransformed, otherwise they would show up
373        // in empty text fields.
374        '\u{200B}' => '\u{200B}',
375        // Newlines are preserved, so that `<br>` keeps working as expected.
376        '\n' => '\n',
377        _ => match mode {
378            WebKitTextSecurity::None => character, // unreachable
379            WebKitTextSecurity::Circle => '○',
380            WebKitTextSecurity::Disc => '●',
381            WebKitTextSecurity::Square => '■',
382        },
383    }
384}
385
386fn map_character_for_full_size_kana(full_size_kana_enabled: bool, character: char) -> char {
387    if !full_size_kana_enabled {
388        character
389    } else {
390        // TODO: When MSRV is 1.95+ use std::hint::cold_path().
391        super::small_kana::SMALL_KANA_MAPPINGS
392            .get(&character)
393            .copied()
394            .unwrap_or(character)
395    }
396}
397
398#[derive(MallocSizeOf, Clone, Copy)]
399struct OffsetMapKnownPosition {
400    original_offset: Utf32CodeUnits,
401    final_offset: Utf32CodeUnits,
402}
403
404#[derive(Default, MallocSizeOf)]
405pub struct OffsetMap {
406    /// Not including `IMPLICIT_KNOWN_POSITION_AT_START`
407    known_positions: Vec<OffsetMapKnownPosition>,
408    /// `Default` initializes to `false`
409    last_range_maps_one_to_one: bool,
410}
411
412impl std::fmt::Debug for OffsetMap {
413    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
414        f.debug_struct("OffsetMap")
415            .field("total_original_size", &self.total_original_size())
416            .field("total_final_size", &self.total_final_size())
417            .finish()
418    }
419}
420
421static IMPLICIT_KNOWN_POSITION_AT_START: OffsetMapKnownPosition = OffsetMapKnownPosition {
422    original_offset: Utf32CodeUnits(0),
423    final_offset: Utf32CodeUnits(0),
424};
425
426impl OffsetMap {
427    fn last_known_position(&self) -> &OffsetMapKnownPosition {
428        self.known_positions
429            .last()
430            .unwrap_or(&IMPLICIT_KNOWN_POSITION_AT_START)
431    }
432
433    pub fn total_original_size(&self) -> Utf32CodeUnits {
434        self.last_known_position().original_offset
435    }
436
437    pub fn total_final_size(&self) -> Utf32CodeUnits {
438        self.last_known_position().final_offset
439    }
440
441    pub fn push_range(
442        &mut self,
443        additional_original_length: Utf32CodeUnits,
444        additional_final_length: Utf32CodeUnits,
445    ) {
446        let this_range_maps_one_to_one = additional_original_length == additional_final_length;
447        if this_range_maps_one_to_one &&
448            self.last_range_maps_one_to_one &&
449            let Some(last) = self.known_positions.last_mut()
450        {
451            last.original_offset += additional_original_length;
452            last.final_offset += additional_final_length;
453        } else {
454            let last = self.last_known_position();
455            self.known_positions.push(OffsetMapKnownPosition {
456                original_offset: last.original_offset + additional_original_length,
457                final_offset: last.final_offset + additional_final_length,
458            });
459        }
460        self.last_range_maps_one_to_one = this_range_maps_one_to_one;
461    }
462
463    pub(crate) fn push_iteration(&mut self, iteration: &CharacterTransformIteration) {
464        self.push_range(
465            iteration.consumed,
466            Utf32CodeUnits(iteration.characters.len()),
467        );
468    }
469
470    pub fn map(&self, target_original_offset: Utf32CodeUnits) -> Utf32CodeUnits {
471        self.map_common(
472            target_original_offset,
473            |position| position.original_offset,
474            |position| position.final_offset,
475        )
476    }
477
478    pub fn reverse_map(&self, target_final_offset: Utf32CodeUnits) -> Utf32CodeUnits {
479        self.map_common(
480            target_final_offset,
481            |position| position.final_offset,
482            |position| position.original_offset,
483        )
484    }
485
486    fn map_common(
487        &self,
488        target_offset: Utf32CodeUnits,
489        get_input_offset: impl Copy + Fn(&OffsetMapKnownPosition) -> Utf32CodeUnits,
490        get_output_offset: impl Fn(&OffsetMapKnownPosition) -> Utf32CodeUnits,
491    ) -> Utf32CodeUnits {
492        if target_offset.0 == 0 {
493            // Implict known position
494            return Utf32CodeUnits(0);
495        }
496        match self
497            .known_positions
498            .binary_search_by_key(&target_offset, get_input_offset)
499        {
500            Ok(index) => {
501                // Exact known position
502                get_output_offset(&self.known_positions[index])
503            },
504            Err(index) => {
505                // `index` is where inserting a new position would keep the `Vec` sorted
506                if let Some(position_after) = self.known_positions.get(index) {
507                    let position_before = if index > 0 {
508                        &self.known_positions[index - 1]
509                    } else {
510                        &IMPLICIT_KNOWN_POSITION_AT_START
511                    };
512                    debug_assert!(target_offset > get_input_offset(position_before));
513                    debug_assert!(target_offset < get_input_offset(position_after));
514                    let offset_within_range = target_offset - get_input_offset(position_before);
515                    let candidate = get_output_offset(position_before) + offset_within_range;
516                    // If the output range is shorter, to go beyond it
517                    let upper_bound = get_output_offset(position_after);
518                    upper_bound.min(candidate)
519                } else {
520                    // `target_offset` at or past the end of the text covered by this map
521                    get_output_offset(self.last_known_position())
522                }
523            },
524        }
525    }
526}
527
528#[test]
529fn test_offsetmap_basic_expansion() {
530    let original_string = "aßΰb";
531    let final_string = "ASS\u{3a5}\u{308}\u{301}B";
532    assert_eq!(original_string.to_uppercase(), final_string);
533
534    let mut offset_map = OffsetMap::default();
535    offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
536        'a'.to_uppercase(),
537    ));
538    offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
539        'ß'.to_uppercase(),
540    ));
541    offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
542        'ΰ'.to_uppercase(),
543    ));
544    offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
545        'b'.to_uppercase(),
546    ));
547
548    assert_eq!(offset_map.map(Utf32CodeUnits(0)).0, 0);
549    assert_eq!(offset_map.map(Utf32CodeUnits(1)).0, 1);
550    assert_eq!(offset_map.map(Utf32CodeUnits(2)).0, 3);
551    assert_eq!(offset_map.map(Utf32CodeUnits(3)).0, 6);
552    assert_eq!(offset_map.map(Utf32CodeUnits(4)).0, 7);
553
554    // Beyond the last index should always map to the index after the last character
555    // (for handling selections).
556    assert_eq!(offset_map.map(Utf32CodeUnits(5)).0, 7);
557    assert_eq!(offset_map.map(Utf32CodeUnits(100)).0, 7);
558
559    let map_substring = |offset: usize, length: usize| {
560        let start = offset_map
561            .map(Utf32CodeUnits(offset))
562            .to_utf8_code_units_in(final_string);
563        let end = offset_map
564            .map(Utf32CodeUnits(offset + length))
565            .to_utf8_code_units_in(final_string);
566        &final_string[start.0..end.0]
567    };
568    assert_eq!(map_substring(0, 1), "A");
569    assert_eq!(map_substring(0, 2), "ASS");
570    assert_eq!(map_substring(0, 3), "ASS\u{3a5}\u{308}\u{301}");
571    assert_eq!(map_substring(0, 4), "ASS\u{3a5}\u{308}\u{301}B");
572    assert_eq!(map_substring(1, 1), "SS");
573}
574
575#[test]
576fn test_offsetmap_basic_collapse() {
577    let _original_string = "  aaa  b \nc";
578    let final_string = "aaa b\nc";
579
580    let mut offset_map = OffsetMap::default();
581    offset_map.push_iteration(&CharacterTransformIteration::collapse(2, None));
582    offset_map.push_iteration(&CharacterTransformIteration::one_to_one('a'));
583    offset_map.push_iteration(&CharacterTransformIteration::one_to_one('a'));
584    offset_map.push_iteration(&CharacterTransformIteration::one_to_one('a'));
585    assert_eq!(
586        offset_map.known_positions.len(),
587        2,
588        "Consecutive one-to-one mappings are merged"
589    );
590
591    offset_map.push_iteration(&CharacterTransformIteration::collapse(2, Some(' ')));
592    offset_map.push_iteration(&CharacterTransformIteration::one_to_one('b'));
593    offset_map.push_iteration(&CharacterTransformIteration::collapse(2, Some('\n')));
594    offset_map.push_iteration(&CharacterTransformIteration::one_to_one('c'));
595
596    assert_eq!(offset_map.map(Utf32CodeUnits(0)).0, 0);
597    assert_eq!(offset_map.map(Utf32CodeUnits(1)).0, 0);
598    assert_eq!(offset_map.map(Utf32CodeUnits(2)).0, 0);
599    assert_eq!(offset_map.map(Utf32CodeUnits(3)).0, 1);
600    assert_eq!(offset_map.map(Utf32CodeUnits(4)).0, 2);
601    assert_eq!(offset_map.map(Utf32CodeUnits(5)).0, 3);
602    // Mapping from the middle of the collapsed sequence should map to after the replacement.
603    assert_eq!(offset_map.map(Utf32CodeUnits(6)).0, 4);
604    assert_eq!(offset_map.map(Utf32CodeUnits(7)).0, 4);
605    assert_eq!(offset_map.map(Utf32CodeUnits(8)).0, 5);
606    // Mapping from the middle of the collapsed sequence should map to after the replacement.
607    assert_eq!(offset_map.map(Utf32CodeUnits(9)).0, 6);
608    assert_eq!(offset_map.map(Utf32CodeUnits(10)).0, 6);
609    assert_eq!(offset_map.map(Utf32CodeUnits(11)).0, 7);
610
611    // Beyond the last index should always map to the index after the last character
612    // (for handling selections).
613    assert_eq!(offset_map.map(Utf32CodeUnits(12)).0, 7);
614    assert_eq!(offset_map.map(Utf32CodeUnits(100)).0, 7);
615
616    let map_substring = |offset: usize, length: usize| {
617        let start = offset_map.map(Utf32CodeUnits(offset)).0;
618        let end = offset_map.map(Utf32CodeUnits(offset + length)).0;
619        &final_string[start..end]
620    };
621    assert_eq!(map_substring(0, 1), "");
622    assert_eq!(map_substring(0, 3), "a");
623    assert_eq!(map_substring(0, 5), "aaa");
624    assert_eq!(map_substring(0, 6), "aaa ");
625    assert_eq!(map_substring(0, 7), "aaa ");
626    assert_eq!(map_substring(0, 8), "aaa b");
627    assert_eq!(map_substring(0, 11), "aaa b\nc");
628}