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        let chars = text
244            .chars()
245            .map(move |character| map_character_for_webkit_text_security(text_security, character));
246        let white_space_collapse = style.clone_white_space_collapse();
247        let iterator =
248            WhitespaceCollapse::new(chars, white_space_collapse, trim_leading_white_space);
249
250        // TODO: Not all text transforms are about case, this logic should stop ignoring
251        // TextTransform::FULL_WIDTH and TextTransform::FULL_SIZE_KANA.
252        let text_transform = style.clone_text_transform();
253        let iterator = match text_transform.case() {
254            TextTransformCase::None => {
255                Box::new(iterator) as Box<dyn Iterator<Item = CharacterTransformIteration>>
256            },
257            TextTransformCase::Lowercase => {
258                Box::new(simple_case_transform_iterator(iterator, |character| {
259                    CharacterTransformIteration::case_mapped(character.to_lowercase())
260                }))
261            },
262            TextTransformCase::Uppercase => {
263                Box::new(simple_case_transform_iterator(iterator, |character| {
264                    CharacterTransformIteration::case_mapped(character.to_uppercase())
265                }))
266            },
267            TextTransformCase::Capitalize => Box::new(capitalization_iterator(
268                iterator,
269                text.len(),
270                on_word_boundary,
271            )),
272            // TODO: implement `math-auto` and enable it in Stylo
273        };
274        if text_transform.intersects(TextTransform::FULL_WIDTH) {
275            // TODO: implement `full-width`
276        }
277        if text_transform.intersects(TextTransform::FULL_SIZE_KANA) {
278            // TODO: implement `full-size-kana`
279        }
280
281        Self(iterator)
282    }
283}
284
285impl Iterator for TextTransformationIterator<'_> {
286    type Item = CharacterTransformIteration;
287    fn next(&mut self) -> Option<Self::Item> {
288        self.0.next()
289    }
290}
291
292fn simple_case_transform_iterator(
293    input_iterator: impl Iterator<Item = CharacterTransformIteration>,
294    mapping: impl Fn(char) -> CharacterTransformIteration,
295) -> impl Iterator<Item = CharacterTransformIteration> {
296    input_iterator.map(move |iteration| {
297        if iteration.is_one_to_one() {
298            mapping(iteration.characters[0])
299        } else {
300            iteration
301        }
302    })
303}
304
305/// Given an input iterator, a size hint for the number items in the iterator,
306/// and a boolean determining whether the start of the input represents a word
307/// boundary, return an iterator that capitalizes one-to-one mapped characters
308/// from the input iterator.
309pub(crate) fn capitalization_iterator(
310    input_iterator: impl Iterator<Item = CharacterTransformIteration>,
311    size_hint: usize,
312    allow_word_at_start: bool,
313) -> impl Iterator<Item = CharacterTransformIteration> {
314    let mut iterations: Vec<_> = input_iterator.collect();
315    let mut string = String::with_capacity(size_hint);
316    for iteration in &iterations {
317        string.extend(iteration.characters());
318    }
319
320    let word_segmenter = WordSegmenter::new_auto();
321    let mut bounds = word_segmenter.segment_str(&string).peekable();
322
323    let mut current_byte_index = 0;
324    for iteration in iterations.iter_mut() {
325        let bytes_to_advance: usize = iteration
326            .characters()
327            .iter()
328            .map(|character| character.len_utf8())
329            .sum();
330        if bytes_to_advance == 0 {
331            continue;
332        }
333
334        let at_word_start = bounds.peek() == Some(&current_byte_index);
335        if at_word_start {
336            bounds.next();
337        }
338
339        // TODO: currently we titlecase the first `char` of each word,
340        // instead it should be the first typographic letter unit:
341        // https://drafts.csswg.org/css-text-4/#typographic-letter-unit
342        // WPT /css/css-text/text-transform/text-transform-capitalize-026.html
343        if iteration.is_one_to_one() &&
344            at_word_start &&
345            (current_byte_index != 0 || allow_word_at_start)
346        {
347            // TODO: Replace this with a call to `character.to_titlecase()` when available:
348            // See: https://github.com/rust-lang/rust/issues/153892
349            // See: https://doc.rust-lang.org/stable/std/primitive.char.html#difference-from-uppercase
350            *iteration =
351                CharacterTransformIteration::case_mapped(iteration.characters[0].to_uppercase());
352        }
353
354        current_byte_index += bytes_to_advance;
355    }
356
357    iterations.into_iter()
358}
359
360/// Map a character according to the rules of the `-webkit-text-security` CSS property.
361///
362/// Note: The behavior of `-webkit-text-security` isn't specified, so we have some
363/// flexibility in the implementation. We just need to maintain a rough compatibility with
364/// other browsers.
365fn map_character_for_webkit_text_security(mode: WebKitTextSecurity, character: char) -> char {
366    if let WebKitTextSecurity::None = mode {
367        return character;
368    }
369
370    // TODO: When MSRV is 1.95+ use std::hint::cold_path().
371    match character {
372        // This is not ideal, but zero width space is used for some special reasons in
373        // `<input>` fields, so these remain untransformed, otherwise they would show up
374        // in empty text fields.
375        '\u{200B}' => '\u{200B}',
376        // Newlines are preserved, so that `<br>` keeps working as expected.
377        '\n' => '\n',
378        _ => match mode {
379            WebKitTextSecurity::None => character, // unreachable
380            WebKitTextSecurity::Circle => '○',
381            WebKitTextSecurity::Disc => '●',
382            WebKitTextSecurity::Square => '■',
383        },
384    }
385}
386
387#[derive(MallocSizeOf, Clone, Copy)]
388struct OffsetMapKnownPosition {
389    original_offset: Utf32CodeUnits,
390    final_offset: Utf32CodeUnits,
391}
392
393#[derive(Default, MallocSizeOf)]
394pub struct OffsetMap {
395    /// Not including `IMPLICIT_KNOWN_POSITION_AT_START`
396    known_positions: Vec<OffsetMapKnownPosition>,
397    /// `Default` initializes to `false`
398    last_range_maps_one_to_one: bool,
399}
400
401impl std::fmt::Debug for OffsetMap {
402    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
403        f.debug_struct("OffsetMap")
404            .field("total_original_size", &self.total_original_size())
405            .field("total_final_size", &self.total_final_size())
406            .finish()
407    }
408}
409
410static IMPLICIT_KNOWN_POSITION_AT_START: OffsetMapKnownPosition = OffsetMapKnownPosition {
411    original_offset: Utf32CodeUnits(0),
412    final_offset: Utf32CodeUnits(0),
413};
414
415impl OffsetMap {
416    fn last_known_position(&self) -> &OffsetMapKnownPosition {
417        self.known_positions
418            .last()
419            .unwrap_or(&IMPLICIT_KNOWN_POSITION_AT_START)
420    }
421
422    pub fn total_original_size(&self) -> Utf32CodeUnits {
423        self.last_known_position().original_offset
424    }
425
426    pub fn total_final_size(&self) -> Utf32CodeUnits {
427        self.last_known_position().final_offset
428    }
429
430    pub fn push_range(
431        &mut self,
432        additional_original_length: Utf32CodeUnits,
433        additional_final_length: Utf32CodeUnits,
434    ) {
435        let this_range_maps_one_to_one = additional_original_length == additional_final_length;
436        if this_range_maps_one_to_one &&
437            self.last_range_maps_one_to_one &&
438            let Some(last) = self.known_positions.last_mut()
439        {
440            last.original_offset += additional_original_length;
441            last.final_offset += additional_final_length;
442        } else {
443            let last = self.last_known_position();
444            self.known_positions.push(OffsetMapKnownPosition {
445                original_offset: last.original_offset + additional_original_length,
446                final_offset: last.final_offset + additional_final_length,
447            });
448        }
449        self.last_range_maps_one_to_one = this_range_maps_one_to_one;
450    }
451
452    pub(crate) fn push_iteration(&mut self, iteration: &CharacterTransformIteration) {
453        self.push_range(
454            iteration.consumed,
455            Utf32CodeUnits(iteration.characters.len()),
456        );
457    }
458
459    pub fn map(&self, target_original_offset: Utf32CodeUnits) -> Utf32CodeUnits {
460        self.map_common(
461            target_original_offset,
462            |position| position.original_offset,
463            |position| position.final_offset,
464        )
465    }
466
467    pub fn reverse_map(&self, target_final_offset: Utf32CodeUnits) -> Utf32CodeUnits {
468        self.map_common(
469            target_final_offset,
470            |position| position.final_offset,
471            |position| position.original_offset,
472        )
473    }
474
475    fn map_common(
476        &self,
477        target_offset: Utf32CodeUnits,
478        get_input_offset: impl Copy + Fn(&OffsetMapKnownPosition) -> Utf32CodeUnits,
479        get_output_offset: impl Fn(&OffsetMapKnownPosition) -> Utf32CodeUnits,
480    ) -> Utf32CodeUnits {
481        if target_offset.0 == 0 {
482            // Implict known position
483            return Utf32CodeUnits(0);
484        }
485        match self
486            .known_positions
487            .binary_search_by_key(&target_offset, get_input_offset)
488        {
489            Ok(index) => {
490                // Exact known position
491                get_output_offset(&self.known_positions[index])
492            },
493            Err(index) => {
494                // `index` is where inserting a new position would keep the `Vec` sorted
495                if let Some(position_after) = self.known_positions.get(index) {
496                    let position_before = if index > 0 {
497                        &self.known_positions[index - 1]
498                    } else {
499                        &IMPLICIT_KNOWN_POSITION_AT_START
500                    };
501                    debug_assert!(target_offset > get_input_offset(position_before));
502                    debug_assert!(target_offset < get_input_offset(position_after));
503                    let offset_within_range = target_offset - get_input_offset(position_before);
504                    let candidate = get_output_offset(position_before) + offset_within_range;
505                    // If the output range is shorter, to go beyond it
506                    let upper_bound = get_output_offset(position_after);
507                    upper_bound.min(candidate)
508                } else {
509                    // `target_offset` at or past the end of the text covered by this map
510                    get_output_offset(self.last_known_position())
511                }
512            },
513        }
514    }
515}
516
517#[test]
518fn test_offsetmap_basic_expansion() {
519    let original_string = "aßΰb";
520    let final_string = "ASS\u{3a5}\u{308}\u{301}B";
521    assert_eq!(original_string.to_uppercase(), final_string);
522
523    let mut offset_map = OffsetMap::default();
524    offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
525        'a'.to_uppercase(),
526    ));
527    offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
528        'ß'.to_uppercase(),
529    ));
530    offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
531        'ΰ'.to_uppercase(),
532    ));
533    offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
534        'b'.to_uppercase(),
535    ));
536
537    assert_eq!(offset_map.map(Utf32CodeUnits(0)).0, 0);
538    assert_eq!(offset_map.map(Utf32CodeUnits(1)).0, 1);
539    assert_eq!(offset_map.map(Utf32CodeUnits(2)).0, 3);
540    assert_eq!(offset_map.map(Utf32CodeUnits(3)).0, 6);
541    assert_eq!(offset_map.map(Utf32CodeUnits(4)).0, 7);
542
543    // Beyond the last index should always map to the index after the last character
544    // (for handling selections).
545    assert_eq!(offset_map.map(Utf32CodeUnits(5)).0, 7);
546    assert_eq!(offset_map.map(Utf32CodeUnits(100)).0, 7);
547
548    let map_substring = |offset: usize, length: usize| {
549        let start = offset_map
550            .map(Utf32CodeUnits(offset))
551            .to_utf8_code_units_in(final_string);
552        let end = offset_map
553            .map(Utf32CodeUnits(offset + length))
554            .to_utf8_code_units_in(final_string);
555        &final_string[start.0..end.0]
556    };
557    assert_eq!(map_substring(0, 1), "A");
558    assert_eq!(map_substring(0, 2), "ASS");
559    assert_eq!(map_substring(0, 3), "ASS\u{3a5}\u{308}\u{301}");
560    assert_eq!(map_substring(0, 4), "ASS\u{3a5}\u{308}\u{301}B");
561    assert_eq!(map_substring(1, 1), "SS");
562}
563
564#[test]
565fn test_offsetmap_basic_collapse() {
566    let _original_string = "  aaa  b \nc";
567    let final_string = "aaa b\nc";
568
569    let mut offset_map = OffsetMap::default();
570    offset_map.push_iteration(&CharacterTransformIteration::collapse(2, None));
571    offset_map.push_iteration(&CharacterTransformIteration::one_to_one('a'));
572    offset_map.push_iteration(&CharacterTransformIteration::one_to_one('a'));
573    offset_map.push_iteration(&CharacterTransformIteration::one_to_one('a'));
574    assert_eq!(
575        offset_map.known_positions.len(),
576        2,
577        "Consecutive one-to-one mappings are merged"
578    );
579
580    offset_map.push_iteration(&CharacterTransformIteration::collapse(2, Some(' ')));
581    offset_map.push_iteration(&CharacterTransformIteration::one_to_one('b'));
582    offset_map.push_iteration(&CharacterTransformIteration::collapse(2, Some('\n')));
583    offset_map.push_iteration(&CharacterTransformIteration::one_to_one('c'));
584
585    assert_eq!(offset_map.map(Utf32CodeUnits(0)).0, 0);
586    assert_eq!(offset_map.map(Utf32CodeUnits(1)).0, 0);
587    assert_eq!(offset_map.map(Utf32CodeUnits(2)).0, 0);
588    assert_eq!(offset_map.map(Utf32CodeUnits(3)).0, 1);
589    assert_eq!(offset_map.map(Utf32CodeUnits(4)).0, 2);
590    assert_eq!(offset_map.map(Utf32CodeUnits(5)).0, 3);
591    // Mapping from the middle of the collapsed sequence should map to after the replacement.
592    assert_eq!(offset_map.map(Utf32CodeUnits(6)).0, 4);
593    assert_eq!(offset_map.map(Utf32CodeUnits(7)).0, 4);
594    assert_eq!(offset_map.map(Utf32CodeUnits(8)).0, 5);
595    // Mapping from the middle of the collapsed sequence should map to after the replacement.
596    assert_eq!(offset_map.map(Utf32CodeUnits(9)).0, 6);
597    assert_eq!(offset_map.map(Utf32CodeUnits(10)).0, 6);
598    assert_eq!(offset_map.map(Utf32CodeUnits(11)).0, 7);
599
600    // Beyond the last index should always map to the index after the last character
601    // (for handling selections).
602    assert_eq!(offset_map.map(Utf32CodeUnits(12)).0, 7);
603    assert_eq!(offset_map.map(Utf32CodeUnits(100)).0, 7);
604
605    let map_substring = |offset: usize, length: usize| {
606        let start = offset_map.map(Utf32CodeUnits(offset)).0;
607        let end = offset_map.map(Utf32CodeUnits(offset + length)).0;
608        &final_string[start..end]
609    };
610    assert_eq!(map_substring(0, 1), "");
611    assert_eq!(map_substring(0, 3), "a");
612    assert_eq!(map_substring(0, 5), "aaa");
613    assert_eq!(map_substring(0, 6), "aaa ");
614    assert_eq!(map_substring(0, 7), "aaa ");
615    assert_eq!(map_substring(0, 8), "aaa b");
616    assert_eq!(map_substring(0, 11), "aaa b\nc");
617}