parley_engine 0.14.0

Parley Engine provides low level APIs for implementing text layout.
Documentation
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
// Copyright 2026 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Reshaping of lines.
//!
//! See [`Reshaper`].

use core::{mem, ops::Range};

use alloc::{string::String, vec::Vec};
use harfrust::ShapeOptions as HarfShapeOptions;

use crate::{
    Glyph, ShapedRun, ShapedSlice, ShapedText,
    itemize::TextRange,
    lru_cache::{LruCache, LruStore},
    shape::{
        ShapedCluster, cache,
        shaped_text::push_glyph_buffer,
        shaper::{features_to_harfrust, language_to_harfrust, script_to_harfrust},
    },
};

/// A mark created by [`ReshapedText::mark`] that [`ReshapedText`] can be
/// [truncated](ReshapedText::truncate) back to.
///
/// [`ReshapedTextMark::default`] is the empty start of a [`ReshapedText`].
#[derive(Clone, Copy, Debug, Default)]
pub struct ReshapedTextMark {
    runs_len: u32,
    shaped_clusters_len: u32,
    glyphs_len: u32,
}

/// One run of reshaped text, belonging to a [`ReshapedText`].
#[derive(Clone, Debug, PartialEq)]
pub struct ReshapedRun {
    run: ShapedRun,
    source_run: u32,
}

impl ReshapedRun {
    /// The reshaped run.
    ///
    /// Its [`ShapedRun::shaped_clusters_range`] and [`ShapedRun::glyphs_range`] index into
    /// [`ReshapedText`]; use [`ReshapedText::run_slice`] to access them. Its other indices index
    /// the source [`ShapedText`].
    pub fn shaped_run(&self) -> &ShapedRun {
        &self.run
    }

    /// The source run this run was reshaped from, as an index into [`ShapedText::runs`].
    #[inline(always)]
    pub fn source_run(&self) -> u32 {
        self.source_run
    }
}

/// Storage for reshaped runs.
///
/// See [`Reshaper::push_line`].
///
/// If you're implementing a line breaker that revises lines already pushed to this storage, you can
/// use [`Self::mark`] and [`Self::truncate`] to trim.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ReshapedText {
    runs: Vec<ReshapedRun>,
    shaped_clusters: Vec<ShapedCluster>,
    glyphs: Vec<Glyph>,
}

impl ReshapedText {
    /// Create an empty [`ReshapedText`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Drop all reshaped runs while retaining capacity.
    #[inline]
    pub fn clear(&mut self) {
        self.runs.clear();
        self.shaped_clusters.clear();
        self.glyphs.clear();
    }

    /// Mark the current state, which you can truncate back to using [`Self::truncate`].
    #[inline(always)]
    pub fn mark(&self) -> ReshapedTextMark {
        ReshapedTextMark {
            runs_len: self.runs.len() as u32,
            shaped_clusters_len: self.shaped_clusters.len() as u32,
            glyphs_len: self.glyphs.len() as u32,
        }
    }

    /// Truncate back to a mark created by [`Self::mark`].
    ///
    /// This drops everything reshaped since the mark was taken. [`ReshapedLine`]s and marks created
    /// after it must not be used anymore.
    #[inline]
    pub fn truncate(&mut self, mark: ReshapedTextMark) {
        self.runs.truncate(mark.runs_len as usize);
        self.shaped_clusters
            .truncate(mark.shaped_clusters_len as usize);
        self.glyphs.truncate(mark.glyphs_len as usize);
    }

    /// Get the reshaped run at the given index.
    #[inline(always)]
    pub fn run(&self, reshaped_run_idx: u32) -> &ReshapedRun {
        &self.runs[reshaped_run_idx as usize]
    }

    /// Get a [`ShapedSlice`] of the reshaped run at the given index.
    ///
    /// `source` must be the [`ShapedText`] the run was reshaped from.
    #[inline(always)]
    pub fn run_slice<'a>(
        &'a self,
        source: &'a ShapedText,
        reshaped_run_idx: u32,
    ) -> ShapedSlice<'a> {
        let run = &self.runs[reshaped_run_idx as usize].run;
        ShapedSlice {
            characters: source.characters(),
            shaped_clusters: &self.shaped_clusters,
            glyphs: &self.glyphs,
            clusters: run.shaped_clusters_range,
        }
    }

    /// Append copies of `other`'s runs, returning the index of the first.
    fn extend_from(&mut self, other: &Self) -> u32 {
        let first_run = self.runs.len() as u32;
        let clusters_start = self.shaped_clusters.len() as u32;
        let glyphs_start = self.glyphs.len();

        self.runs.extend(other.runs.iter().map(|reshaped_run| {
            let mut reshaped_run = reshaped_run.clone();
            let run = &mut reshaped_run.run;
            run.shaped_clusters_range.start += clusters_start;
            run.shaped_clusters_range.end += clusters_start;
            run.glyphs_range.start += glyphs_start;
            run.glyphs_range.end += glyphs_start;
            reshaped_run
        }));
        self.shaped_clusters
            .extend(other.shaped_clusters.iter().map(|&cluster| {
                let mut cluster = cluster;
                if !cluster.has_inline_glyph() {
                    cluster.glyph_offset += glyphs_start as u32;
                }
                cluster
            }));
        self.glyphs.extend_from_slice(&other.glyphs);
        first_run
    }
}

/// The start of a line, measured by [`Reshaper::measure_start`].
#[derive(Clone, Copy, Debug)]
pub struct LineStart<'a> {
    line_start_char: u32,
    start_edit: Option<Edit<'a>>,
    /// The reshaped fragment starting the line, if the start needed reshaping.
    start_fragment: Option<Fragment>,
    /// The start of the range of shaped clusters this reshaped line takes from the paragraph-wide
    /// shaped text.
    source_clusters_start: u32,
    /// The change in advance between the reshaped line's start and the original glyphs.
    ///
    /// Source clusters' advances are counted on the line that contains its first character.
    advance_delta: f32,
}

impl LineStart<'_> {
    /// How much reshaping the line's start changed the advance; see [advances](Reshaper#advances).
    pub fn advance_delta(&self) -> f32 {
        self.advance_delta
    }
}

/// The end of a line, measured by [`Reshaper::measure_end`].
#[derive(Clone, Copy, Debug)]
pub struct LineEnd<'a> {
    line_end_char: u32,
    end_edit: Option<Edit<'a>>,
    /// The reshaped fragment ending the line, if the end needed reshaping.
    end_fragment: Option<Fragment>,
    /// The end of the range of shaped clusters this reshaped line takes from the paragraph-wide
    /// shaped text.
    source_clusters_end: u32,
    /// The change in advance between the reshaped line's end and the original glyphs.
    ///
    /// Source clusters' advances are counted on the line that contains its first character.
    advance_delta: f32,
}

impl LineEnd<'_> {
    /// How much reshaping the line's end changed the advance; see [advances](Reshaper#advances).
    pub fn advance_delta(&self) -> f32 {
        self.advance_delta
    }
}

/// A line from a [`LineStart`] to a [`LineEnd`].
///
/// The line's reshaped runs are not stored until you hand this to [`Reshaper::push_line`].
#[derive(Clone, Copy, Debug)]
pub struct PendingLine<'a> {
    start: LineStart<'a>,
    end: LineEnd<'a>,
}

impl PendingLine<'_> {
    /// How much reshaping the line changed the advance; see [advances](Reshaper#advances).
    ///
    /// This is the line's advance minus its source advance.
    #[inline(always)]
    pub fn advance_delta(&self) -> f32 {
        self.start.advance_delta + self.end.advance_delta
    }
}

/// A reshaped line stored in a [`ReshapedText`].
///
/// In logical order, the line consists of [`Self::start_run`], shaped clusters taken from the
/// source [`ShapedText`] in [`Self::source_shaped_clusters_range`], and [`Self::end_run`].
///
/// Note that this is not necessarily the visual order. A reshaped run belongs to one source run
/// ([`ReshapedRun::source_run`]) and has that run's bidi level.
#[derive(Clone, Copy, Debug)]
pub struct ReshapedLine {
    /// The index into [`ReshapedText::runs`] that starts this line, if the start needed reshaping.
    reshaped_start_run: Option<u32>,
    /// The range of shaped clusters this reshaped line takes from the paragraph-wide shaped text.
    source_clusters: (u32, u32),
    /// The index into [`ReshapedText::runs`] that ends this line, if the end needed reshaping.
    reshaped_end_run: Option<u32>,
    /// The change in advance between the reshaped line and the original glyphs.
    ///
    /// Source clusters' advances are counted on the line that contains its first character.
    advance_delta: f32,
}

impl ReshapedLine {
    /// The reshaped run the line starts with, as an index into [`ReshapedText::run`].
    ///
    /// `None` if the line's start was not reshaped.
    #[inline(always)]
    pub fn start_run(&self) -> Option<u32> {
        self.reshaped_start_run
    }

    /// The shaped clusters this line keeps from the source [`ShapedText`], as a range into
    /// [`ShapedText::shaped_clusters`].
    #[inline(always)]
    pub fn source_shaped_clusters_range(&self) -> Range<u32> {
        self.source_clusters.0..self.source_clusters.1
    }

    /// The reshaped run ending this line, as an index into [`ReshapedText::run`].
    ///
    /// `None` if the line ends with source clusters or with [`Self::start_run`].
    #[inline(always)]
    pub fn end_run(&self) -> Option<u32> {
        self.reshaped_end_run
    }

    /// How much reshaping the line changed the advance; see [advances](Reshaper#advances).
    ///
    /// This is the line's advance minus its source advance.
    #[inline(always)]
    pub fn advance_delta(&self) -> f32 {
        self.advance_delta
    }
}

/// How to determine the boundary at which to splice a reshaped line edge to the line's source
/// glyphs.
///
/// Reshaping a line edge reshapes a fragment of the original line. The glyphs beyond the reshaped
/// fragment are the glyphs from the original [`ShapedText`] (or the reshaped glyphs from the other
/// end of the line). This splice mode trades speed for exactness in where that boundary may be.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SpliceMode {
    /// Splice at the nearest cluster that is marked [`ShapedCluster::is_safe_to_break_before`].
    Fast,

    /// Splice at the nearest cluster that is marked [`ShapedCluster::is_safe_to_concat_before`] in
    /// both the source and the reshaped fragment.
    Exact,
}

impl SpliceMode {
    fn is_safe_to_splice_before(self, cluster: ShapedCluster) -> bool {
        if !cluster.is_grapheme_start() {
            // We do not add new shaped run boundaries inside graphemes. The reason is that users
            // may want to assume grapheme and shaped run boundaries line up, for simplicity.
            //
            // Technically a shaped run boundary inside a grapheme is fine, but such boundaries
            // otherwise only occur either in edge cases (like a grapheme spanning a bidi boundary)
            // or when the user themselves asked for such a boundary by breaking inside a grapheme.
            //
            // In any case, boundaries inside graphemes are rarely safe to break, so this should not
            // normally lead to any appreciable additional work.
            false
        } else {
            match self {
                Self::Fast => cluster.is_safe_to_break_before(),
                Self::Exact => cluster.is_safe_to_concat_before(),
            }
        }
    }
}

/// The source characters a reshaped fragment of a line covers.
#[derive(Clone, Copy, Debug)]
struct Fragment {
    /// The source run the characters are in, as an index into [`ShapedText::runs`].
    run: u32,
    /// The range of characters covered, including those replaced by an [`Edit`].
    chars: (u32, u32),
}

#[derive(Debug, Default)]
struct FragmentCache {
    /// Slots 0 and 1 hold fragments starting lines, slots 2 and 3 fragments ending lines, including
    /// whole lines.
    ///
    /// Eviction of these pairs' cache entries is done separately to have a relatively good chance
    /// of a cache hit under common patterns of line breakers. Note in particular that a line
    /// breaker, after measuring the line's new start, may need to measure multiple candidates for
    /// the line's end. We can't simply us a single [`ReshapedText`] as a cache, because there'd be
    /// no way to evict older entries.
    ///
    /// This is a single array holding both pairs so that slots are just an index (otherwise we'd
    /// need to carry something like a tuple or a `&mut CachedFragment`), and this shape also allows
    /// us to find fragments with a scan over just this one array.
    slots: [CachedFragment; 4],
    /// For each of those pairs, which of its two slots was used last.
    recent: [usize; 2],
}

impl FragmentCache {
    const STARTS: usize = 0;
    const ENDS: usize = 1;

    /// The slot holding the fragment shaped from `chars` with `edits`, if any.
    fn find(&self, chars: (u32, u32), edits: [Option<Edit<'_>>; 2]) -> Option<usize> {
        self.slots.iter().position(|slot| {
            slot.chars == Some(chars)
                && (slot.edits.iter().zip(edits)).all(|((replaced, inserted), edit)| {
                    *replaced == edit.map(Edit::replaced_chars)
                        && inserted == edit.map_or("", |edit| edit.inserted)
                })
        })
    }
}

#[derive(Debug, Default)]
struct CachedFragment {
    /// The characters `fragment` was shaped from, or `None` for an empty slot.
    chars: Option<(u32, u32)>,
    /// The replaced character count and inserted text of the edits `fragment` was shaped with.
    edits: [(Option<u32>, String); 2],
    /// The fragment, as the only run.
    fragment: ReshapedText,
}

/// Reshapes lines of a [`ShapedText`].
///
/// Breaking shaped text into lines can require its glyphs to change. For example, a font may shape
/// the Latin character sequence "ffi" into a ligature, and breaking somewhere in that ligature
/// breaks it up. Furthermore, you may want to insert hyphens or perform replacements near the edge:
/// e.g., the Dutch word "skiën" once broken could be written as "ski-en" (see [`Edit`]).
///
/// You can use this as follows.
///
/// 1. Measure the effect of breaking at candidate line edges using [`Self::measure_start`] and
///    [`Self::measure_end`].
/// 2. Create a line from a start and end using [`Self::line`].
/// 3. Store the line using [`Self::push_line`].
///
/// Line edges can be at any character boundary, including inside a grapheme. [`Reshaper`] itself
/// does not introduce new boundaries inside graphemes.
///
/// The text passed to [`Reshaper`]'s methods must be the text [`ShapedText`] was shaped from, and
/// [`Reshaper::clear`] must be called when reusing the [`Reshaper`] on a different [`ShapedText`]
/// (including the same [`ShapedText`] if it was shaped again).
///
/// # Advances
///
/// Reshaping can change the shaped advances. For example, a kerned "VA" broken in the middle will
/// drop the kerning once reshaped, and [`Edit`]s can replace text. The reshaper returns advance
/// deltas, which are the change in advance due to reshaping. These are relative to a line's source
/// advance: the summed advance of the source shaped clusters whose first character is on the line.
/// If, e.g., "ffi" ligated into a single source shaped cluster, its whole advance is counted on the
/// line the first "f" is on.
///
/// [`LineStart::advance_delta`] and [`LineEnd::advance_delta`] sum to
/// [`PendingLine::advance_delta`], unless the line is so short that its reshaped start and end
/// overlap (see [`Self::line`]). Making the line [exact](Self#exactness) may change the line's
/// delta again.
///
/// # Exactness
///
/// A line created by [`Self::line`] splices reshaped fragments to the source glyphs at the nearest
/// cluster that is marked [`ShapedCluster::is_safe_to_break_before`]. These reshaped fragments tend
/// to be short, and the result almost always matches [`Self::make_exact`]. However, this method of
/// splicing is based only on the source text, and a change within the reshaped clusters could
/// technically require reshaping past the splice point. For example, Fira Code gives the hyphen in
/// "down-town" a lowercase form because of the "t" after it. A line ending in "down-" should keep
/// that form because of the "n" before it, but measuring reshapes only the hyphen, which then takes
/// its default form.
///
/// [`Self::make_exact`] can be slow. It cannot splice at points that shaping looked across, even if
/// that changed nothing. In fonts that kern many characters, almost no point qualifies (e.g.,
/// Roboto, which even kerns spaces). That may then require reshaping most of the line, with the
/// result rarely differing from [`Self::line`].
pub struct Reshaper {
    shape_data_cache: LruCache<cache::ShapeDataKey, harfrust::Font>,
    shape_plan_cache: LruStore<(cache::ShapeDataKey, harfrust::ShapePlan)>,

    buffer: harfrust::Buffer,
    features: Vec<harfrust::Feature>,

    cache: FragmentCache,
}

impl Default for Reshaper {
    fn default() -> Self {
        const MAX_ENTRIES: usize = 16;
        Self {
            shape_data_cache: LruCache::new(MAX_ENTRIES),
            shape_plan_cache: LruStore::new(MAX_ENTRIES),

            buffer: harfrust::Buffer::new(),
            features: Vec::new(),

            cache: FragmentCache::default(),
        }
    }
}

impl core::fmt::Debug for Reshaper {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("Reshaper").finish_non_exhaustive()
    }
}

impl Reshaper {
    /// Clear the reshaper's cache.
    ///
    /// You must call this after having reshaped parts of a [`ShapedText`] before starting work on a
    /// new [`ShapedText`] (including the same [`ShapedText`] if it was shaped again).
    pub fn clear(&mut self) {
        for slot in &mut self.cache.slots {
            slot.chars = None;
        }
    }

    /// Measure the effect of starting a line at character index `line_start_char` with the given
    /// `edit`.
    ///
    /// This also returns the reshaped clusters starting the line, or `None` if the line's start
    /// needed no reshaping. Note this slice's shaped cluster indices index only into this slice
    /// itself (and in particular, they don't index into `shaped`).
    ///
    /// # Panics
    ///
    /// Panics if `edit` replaces characters past the end of the [`ShapedRun`] at the line's edge.
    #[inline]
    pub fn measure_start<'a, 'e>(
        &'a mut self,
        text: &str,
        shaped: &'a ShapedText,
        line_start_char: u32,
        edit: Option<Edit<'e>>,
    ) -> (LineStart<'e>, Option<ShapedSlice<'a>>) {
        let start = self
            .reshape_line_start(text, shaped, line_start_char, edit, SpliceMode::Fast, None)
            .unwrap();
        let cache = &self.cache;
        let slice = start.start_fragment.map(|fragment| {
            let slot = (cache.find(fragment.chars, [edit, None]))
                .expect("measuring the start just reshaped its fragment");
            cache.slots[slot].fragment.run_slice(shaped, 0)
        });
        (start, slice)
    }

    /// Measure the effect of ending a line at character index `line_end_char` with the given
    /// `edit`.
    ///
    /// # Panics
    ///
    /// Panics if `edit` replaces characters before the start of the [`ShapedRun`] at the line's
    /// edge.
    #[inline]
    pub fn measure_end<'e>(
        &mut self,
        text: &str,
        shaped: &ShapedText,
        line_end_char: u32,
        edit: Option<Edit<'e>>,
    ) -> LineEnd<'e> {
        self.reshape_line_end(text, shaped, line_end_char, edit, SpliceMode::Fast, None)
            .expect("an unbounded line end can't overlap a line start")
    }

    /// Create the line from `start` to `end`.
    ///
    /// Store the resulting line using [`Self::push_line`].
    ///
    /// `end` must not be before `start`. If the line is so short that its reshaped start and end
    /// overlap, the whole line is reshaped as one piece. An empty line drops the edits, as it has
    /// no characters for inserted text to attach to.
    ///
    /// The line is not necessarily [exact](Self#exactness).
    ///
    /// # Panics
    ///
    /// Panics if the characters replaced by the line's two edits overlap, or one edit replaces more
    /// characters than the line has (unless the line is empty, in which case the edits are
    /// dropped).
    #[inline]
    pub fn line<'e>(
        &mut self,
        text: &str,
        shaped: &ShapedText,
        start: &LineStart<'e>,
        end: &LineEnd<'e>,
    ) -> PendingLine<'e> {
        if end.line_end_char == start.line_start_char {
            let source_clusters = shaped
                .shaped_clusters()
                .partition_point(|cluster| cluster.chars_range().start < end.line_end_char)
                as u32;
            return PendingLine {
                start: LineStart {
                    start_fragment: None,
                    source_clusters_start: source_clusters,
                    advance_delta: 0.,
                    ..*start
                },
                end: LineEnd {
                    end_fragment: None,
                    source_clusters_end: source_clusters,
                    advance_delta: 0.,
                    ..*end
                },
            };
        }
        if end.source_clusters_end < start.source_clusters_start {
            // The reshaped start and end would overlap, so reshape the whole line as one piece.
            return self.reshape_whole_line(text, shaped, *start, *end);
        }
        PendingLine {
            start: *start,
            end: *end,
        }
    }

    /// Make `line` identical to reshaping the whole line.
    ///
    /// See the note about [exactness](Self#exactness).
    ///
    /// The result is guaranteed to be identical to reshaping the whole line, but for some fonts,
    /// like those that kern many characters, this process may be relatively slow. In case the line
    /// created by [`Self::line`] turned out to not already be exact, the line's
    /// [advance](PendingLine::advance_delta) may change.
    ///
    /// This splices the line's reshaped fragments to the source glyphs at the nearest cluster that
    /// is marked [`ShapedCluster::is_safe_to_concat_before`] in both the source and the reshaped
    /// fragment, extending the fragments until such a splice point is found, or reshaping the whole
    /// line if they would overlap. Note this repeatedly reshapes the fragments.
    ///
    /// # Panics
    ///
    /// Panics if the [`ShapedText`] lacks [`ShapedText::has_safe_to_concat_flags`].
    #[must_use]
    pub fn make_exact<'e>(
        &mut self,
        text: &str,
        shaped: &ShapedText,
        mut line: PendingLine<'e>,
    ) -> PendingLine<'e> {
        assert!(
            shaped.has_safe_to_concat_flags(),
            "`make_exact` requires text shaped with `produce_safe_to_concat_flags`"
        );

        let PendingLine { start, end } = line;
        if end.end_fragment.is_none() && start.source_clusters_start == end.source_clusters_end {
            // The line is empty, or reshaped as one piece.
            return line;
        }

        if end.end_fragment.is_some() {
            match self.reshape_line_end(
                text,
                shaped,
                end.line_end_char,
                end.end_edit,
                SpliceMode::Exact,
                Some(&start),
            ) {
                Some(end) => line.end = end,
                // The reshaped start and end would overlap, so reshape the whole line as one piece.
                None => return self.reshape_whole_line(text, shaped, start, end),
            }
        }
        if start.start_fragment.is_some() {
            match self.reshape_line_start(
                text,
                shaped,
                start.line_start_char,
                start.start_edit,
                SpliceMode::Exact,
                Some(&line.end),
            ) {
                Some(start) => line.start = start,
                // The reshaped start and end would overlap, so reshape the whole line as one piece.
                None => return self.reshape_whole_line(text, shaped, start, end),
            }
        }
        line
    }

    /// Store `line` in `reshaped`.
    ///
    /// Note that [`Reshaper`] caches the fragments it reshaped most recently (separately for the
    /// starts and ends), and copies `line`'s fragments from there if they're still in the cache.
    /// Otherwise, the line is reshaped again.
    pub fn push_line(
        &mut self,
        text: &str,
        shaped: &ShapedText,
        line: &PendingLine<'_>,
        reshaped: &mut ReshapedText,
    ) -> ReshapedLine {
        debug_assert!(
            line.start.source_clusters_start <= line.end.source_clusters_end,
            "a line's reshaped start and end must not overlap"
        );
        ReshapedLine {
            reshaped_start_run: (line.start.start_fragment)
                .map(|fragment| self.push_fragment(text, shaped, line, fragment, reshaped)),
            source_clusters: (
                line.start.source_clusters_start,
                line.end.source_clusters_end,
            ),
            reshaped_end_run: (line.end.end_fragment)
                .map(|fragment| self.push_fragment(text, shaped, line, fragment, reshaped)),
            advance_delta: line.advance_delta(),
        }
    }

    /// Reshape the start of a line at `line_start_char` with the given `edit`.
    ///
    /// With a `line_end`, returns `None` if the reshaped start and end would overlap.
    fn reshape_line_start<'e>(
        &mut self,
        text: &str,
        shaped: &ShapedText,
        line_start_char: u32,
        edit: Option<Edit<'e>>,
        splice: SpliceMode,
        line_end: Option<&LineEnd<'_>>,
    ) -> Option<LineStart<'e>> {
        let mut line_start = LineStart {
            line_start_char,
            start_edit: edit,
            start_fragment: None,
            source_clusters_start: shaped
                .shaped_clusters()
                .partition_point(|cluster| cluster.chars_range().start < line_start_char)
                as u32,
            advance_delta: 0.,
        };

        if line_start_char as usize == shaped.characters().len() {
            // Be graceful about a caller trying to shape the empty line at the end of text.
            return Some(line_start);
        }

        let run_index = shaped
            .runs()
            .partition_point(|run| run.characters_range.end <= line_start_char);
        let run = &shaped.runs()[run_index];

        let run_start_cluster = run.shaped_clusters_range.start as usize;
        let run_end_cluster = run.shaped_clusters_range.end as usize;
        let run_clusters = &shaped.shaped_clusters()[run_start_cluster..run_end_cluster];
        let first_char_idx_of_cluster = |i: usize| {
            if i == run_end_cluster {
                run.characters_range.end
            } else {
                shaped.shaped_clusters()[i].chars_range().start
            }
        };
        let can_splice_before = |i: usize, splice: SpliceMode| {
            // Note that separate runs are shaped separately, so a run's edge is a safe splice
            // point.
            i == run_start_cluster
                || i == run_end_cluster
                || splice.is_safe_to_splice_before(shaped.shaped_clusters()[i])
        };

        // The reshaped start can't end after the reshaped end starts, which is where the source
        // clusters end.
        let max_splice_cluster =
            line_end.map_or(usize::MAX, |line_end| line_end.source_clusters_end as usize);

        let mut splice_cluster = run_start_cluster
            + match edit {
                None => run_clusters
                    .partition_point(|cluster| cluster.chars_range().start < line_start_char),
                // The edit may kern or join with the neighboring unchanged character, so at the
                // very least that neighbor is included in the reshaped fragment.
                Some(edit) => run_clusters.partition_point(|cluster| {
                    cluster.chars_range().start <= line_start_char + edit.replaced_chars()
                }),
            };

        // With no `edit`, no reshaping is necessary when at a cluster that is safe to break before.
        if edit.is_none()
            && first_char_idx_of_cluster(splice_cluster) == line_start_char
            && can_splice_before(splice_cluster, SpliceMode::Fast)
        {
            return Some(line_start);
        }

        while !can_splice_before(splice_cluster, splice) {
            splice_cluster += 1;
        }

        let advance = loop {
            if splice == SpliceMode::Fast || splice_cluster == run_end_cluster {
                if splice_cluster > max_splice_cluster {
                    return None;
                }
                let fragment = Fragment {
                    run: run_index as u32,
                    chars: (line_start_char, first_char_idx_of_cluster(splice_cluster)),
                };
                line_start.start_fragment = Some(fragment);
                break self
                    .shape(text, shaped, FragmentCache::STARTS, fragment, [edit, None])
                    .1;
            }

            // Note that fragments don't carry an unsafe-to-concat flag for their ends, but if the
            // fragment is safe to concat at a splice point before its end, we know the fragment and
            // the source glyphs will match from that point on (we could in principle trim the
            // fragment back to that point).
            let mut next_splice_cluster = splice_cluster + 1;
            while !can_splice_before(next_splice_cluster, splice) {
                next_splice_cluster += 1;
            }
            if next_splice_cluster > max_splice_cluster {
                return None;
            }
            let fragment = Fragment {
                run: run_index as u32,
                chars: (
                    line_start_char,
                    first_char_idx_of_cluster(next_splice_cluster),
                ),
            };
            let (slot, advance) =
                self.shape(text, shaped, FragmentCache::STARTS, fragment, [edit, None]);
            let fragment_clusters = self.cache.slots[slot]
                .fragment
                .run_slice(shaped, 0)
                .shaped_clusters();
            let is_safe = next_splice_cluster == run_end_cluster
                // A fragment up to an unreshaped line end is the whole line.
                || line_end.is_some_and(|line_end| {
                    line_end.end_fragment.is_none() && next_splice_cluster == max_splice_cluster
                })
                || fragment_clusters
                    .binary_search_by_key(&first_char_idx_of_cluster(splice_cluster), |c| {
                        c.chars_range().start
                    })
                    .is_ok_and(|i| fragment_clusters[i].is_safe_to_concat_before());
            splice_cluster = next_splice_cluster;
            if is_safe {
                line_start.start_fragment = Some(fragment);
                break advance;
            }
            // Let the next attempt take this slot.
            self.cache.recent[slot / 2] = 1 - slot % 2;
        };

        let line_start_cluster = line_start.source_clusters_start as usize;
        let source_advance: f32 = shaped.shaped_clusters()[line_start_cluster..splice_cluster]
            .iter()
            .map(|c| c.advance)
            .sum();
        line_start.source_clusters_start = splice_cluster as u32;
        line_start.advance_delta = advance - source_advance;
        Some(line_start)
    }

    /// Reshape the end of a line at `line_end_char` with the given `edit`.
    ///
    /// With a `line_start`, returns `None` if the reshaped start and end would overlap.
    fn reshape_line_end<'e>(
        &mut self,
        text: &str,
        shaped: &ShapedText,
        line_end_char: u32,
        edit: Option<Edit<'e>>,
        splice: SpliceMode,
        line_start: Option<&LineStart<'_>>,
    ) -> Option<LineEnd<'e>> {
        let source_clusters_end = shaped
            .shaped_clusters()
            .partition_point(|cluster| cluster.chars_range().start < line_end_char)
            as u32;
        let mut line_end = LineEnd {
            line_end_char,
            end_edit: edit,
            end_fragment: None,
            source_clusters_end,
            advance_delta: 0.,
        };

        if line_end_char == 0 {
            // Be graceful about a caller trying to shape the empty line at the start of text.
            return Some(line_end);
        }

        let run_index = shaped
            .runs()
            .partition_point(|run| run.characters_range.end < line_end_char);
        let run = &shaped.runs()[run_index];

        let run_start_cluster = run.shaped_clusters_range.start as usize;
        let run_end_cluster = run.shaped_clusters_range.end as usize;
        let run_clusters = &shaped.shaped_clusters()[run_start_cluster..run_end_cluster];
        let first_char_idx_of_cluster = |i: usize| {
            if i == run_end_cluster {
                run.characters_range.end
            } else {
                shaped.shaped_clusters()[i].chars_range().start
            }
        };
        let can_splice_before = |i: usize, splice: SpliceMode| {
            // Note that separate runs are shaped separately, so a run's edge is a safe splice
            // point.
            i == run_start_cluster
                || i == run_end_cluster
                || splice.is_safe_to_splice_before(shaped.shaped_clusters()[i])
        };

        // The reshaped end can't start before the reshaped start ends, which is where the source
        // clusters start.
        let min_splice_cluster =
            line_start.map_or(0, |line_start| line_start.source_clusters_start as usize);

        let mut splice_cluster = run_start_cluster
            + match edit {
                None if line_end_char == run.characters_range.end => run_clusters.len(),
                None => {
                    run_clusters
                        .partition_point(|cluster| cluster.chars_range().start <= line_end_char)
                        - 1
                }
                // The edit may kern or join with the neighboring unchanged character, so at the
                // very least that neighbor is included in the reshaped fragment.
                Some(edit) => run_clusters
                    .partition_point(|cluster| {
                        cluster.chars_range().start
                            < line_end_char.saturating_sub(edit.replaced_chars())
                    })
                    .saturating_sub(1),
            };

        // With no `edit`, the line end needs no reshaping when at a cluster that is safe to break
        // before.
        if edit.is_none()
            && first_char_idx_of_cluster(splice_cluster) == line_end_char
            && can_splice_before(splice_cluster, SpliceMode::Fast)
        {
            return Some(line_end);
        }

        while !can_splice_before(splice_cluster, splice) {
            splice_cluster -= 1;
        }

        let advance = loop {
            if splice_cluster < min_splice_cluster {
                // The reshaped start and end would overlap.
                return None;
            }

            let fragment = Fragment {
                run: run_index as u32,
                chars: (first_char_idx_of_cluster(splice_cluster), line_end_char),
            };
            let (slot, advance) =
                self.shape(text, shaped, FragmentCache::ENDS, fragment, [None, edit]);

            let reshaped = &self.cache.slots[slot].fragment;
            let first_cluster = reshaped.runs[0].run.shaped_clusters_range.start;
            if splice == SpliceMode::Fast
                || splice_cluster == run_start_cluster
                || line_start.is_some_and(|line_start| {
                    first_char_idx_of_cluster(splice_cluster) == line_start.line_start_char
                })
                || reshaped.shaped_clusters[first_cluster as usize].is_safe_to_concat_before()
            {
                line_end.end_fragment = Some(fragment);
                break advance;
            }
            // Let the next attempt take this slot.
            self.cache.recent[slot / 2] = 1 - slot % 2;
            splice_cluster -= 1;
            while !can_splice_before(splice_cluster, splice) {
                splice_cluster -= 1;
            }
        };

        let source_advance: f32 = shaped.shaped_clusters()
            [splice_cluster..source_clusters_end as usize]
            .iter()
            .map(|c| c.advance)
            .sum();
        line_end.source_clusters_end = splice_cluster as u32;
        line_end.advance_delta = advance - source_advance;
        Some(line_end)
    }

    /// Reshape the whole line from `start` to `end` as one piece.
    fn reshape_whole_line<'e>(
        &mut self,
        text: &str,
        shaped: &ShapedText,
        start: LineStart<'e>,
        end: LineEnd<'e>,
    ) -> PendingLine<'e> {
        let line_start_cluster = shaped
            .shaped_clusters()
            .partition_point(|cluster| cluster.chars_range().start < start.line_start_char);
        let source_clusters_end = shaped
            .shaped_clusters()
            .partition_point(|cluster| cluster.chars_range().start < end.line_end_char)
            as u32;
        let fragment = Fragment {
            run: shaped
                .runs()
                .partition_point(|run| run.characters_range.end <= start.line_start_char)
                as u32,
            chars: (start.line_start_char, end.line_end_char),
        };
        let (_, advance) = self.shape(
            text,
            shaped,
            FragmentCache::ENDS,
            fragment,
            [start.start_edit, end.end_edit],
        );
        let source_advance: f32 = shaped.shaped_clusters()
            [line_start_cluster..source_clusters_end as usize]
            .iter()
            .map(|c| c.advance)
            .sum();
        PendingLine {
            start: LineStart {
                start_fragment: Some(fragment),
                source_clusters_start: source_clusters_end,
                advance_delta: advance - source_advance,
                ..start
            },
            end: LineEnd {
                end_fragment: None,
                source_clusters_end,
                advance_delta: 0.,
                ..end
            },
        }
    }

    /// Copy `fragment` of `line` to `reshaped` from the cache if present; if not present, it's
    /// reshaped again.
    fn push_fragment(
        &mut self,
        text: &str,
        shaped: &ShapedText,
        line: &PendingLine<'_>,
        fragment: Fragment,
        reshaped: &mut ReshapedText,
    ) -> u32 {
        // A fragment is shaped with the edits of the line's edges it touches.
        let edits = [
            (line.start.start_edit).filter(|_| fragment.chars.0 == line.start.line_start_char),
            (line.end.end_edit).filter(|_| fragment.chars.1 == line.end.line_end_char),
        ];
        match self.cache.find(fragment.chars, edits) {
            Some(slot) => {
                let cached = &self.cache.slots[slot].fragment;
                debug_assert_eq!(cached.runs.len(), 1, "a cache slot holds one fragment");
                reshaped.extend_from(cached)
            }
            None => self.reshape(
                text,
                shaped,
                fragment.run,
                fragment.chars.0..fragment.chars.1,
                edits[0],
                edits[1],
                reshaped,
            ),
        }
    }

    /// Reshape `fragment` with `edits` into one of the cache slots of `pair`, unless the cache
    /// already holds it.
    ///
    /// Returns the slot and the fragment's advance.
    fn shape(
        &mut self,
        text: &str,
        shaped: &ShapedText,
        pair: usize,
        fragment: Fragment,
        edits: [Option<Edit<'_>>; 2],
    ) -> (usize, f32) {
        let slot = match self.cache.find(fragment.chars, edits) {
            Some(slot) => slot,
            None => {
                // Take the slot of the pair that wasn't used last.
                let slot = 2 * pair + 1 - self.cache.recent[pair];
                let mut reshaped_fragment = mem::take(&mut self.cache.slots[slot].fragment);
                reshaped_fragment.clear();
                self.reshape(
                    text,
                    shaped,
                    fragment.run,
                    fragment.chars.0..fragment.chars.1,
                    edits[0],
                    edits[1],
                    &mut reshaped_fragment,
                );
                let cached = &mut self.cache.slots[slot];
                cached.fragment = reshaped_fragment;
                cached.chars = Some(fragment.chars);
                for ((replaced, inserted), edit) in cached.edits.iter_mut().zip(edits) {
                    *replaced = edit.map(Edit::replaced_chars);
                    inserted.clear();
                    inserted.push_str(edit.map_or("", |edit| edit.inserted));
                }
                slot
            }
        };
        self.cache.recent[slot / 2] = slot % 2;
        let clusters = &self.cache.slots[slot].fragment.shaped_clusters;
        (slot, clusters.iter().map(|c| c.advance).sum())
    }

    /// Shape the characters `chars` of the run `run_index` again.
    ///
    /// Returns the new run's index in [`ReshapedText::runs`].
    ///
    /// `start_edit` and `end_edit` edit the first and last characters of `chars`.
    fn reshape(
        &mut self,
        text: &str,
        shaped: &ShapedText,
        run_index: u32,
        chars: Range<u32>,
        start_edit: Option<Edit<'_>>,
        end_edit: Option<Edit<'_>>,
        reshaped: &mut ReshapedText,
    ) -> u32 {
        let run = &shaped.runs()[run_index as usize];
        let char_count = chars.len() as u32;

        let start_num_chars_replaced = start_edit.map_or(0, Edit::replaced_chars);
        let end_num_chars_replaced = end_edit.map_or(0, Edit::replaced_chars);
        assert!(
            start_num_chars_replaced + end_num_chars_replaced <= char_count,
            "the edits must lie in the run and must not overlap"
        );

        let characters = shaped.characters();
        let bytes = characters[chars.start as usize].text_byte_start as usize
            ..characters[chars.end as usize - 1].text_byte_range().end;

        self.buffer.clear();

        // Fill the characters into the `HarfRust` buffer with the start and end edits applied.
        if let Some(edit) = start_edit {
            edit.inserted()
                .chars()
                .for_each(|ch| self.buffer.push(ch.into(), 0));
        }
        for (ch, cluster_value) in text[bytes.clone()]
            .chars()
            .zip(0..)
            .take((char_count - end_num_chars_replaced) as usize)
            .skip(start_num_chars_replaced as usize)
        {
            self.buffer.push(ch.into(), cluster_value);
        }
        if let Some(edit) = end_edit {
            let cluster_value = char_count - end_num_chars_replaced.max(1);
            edit.inserted
                .chars()
                .for_each(|ch| self.buffer.push(ch.into(), cluster_value));
        }
        self.buffer.set_pre_context(&text[..bytes.start]);
        self.buffer.set_post_context(&text[bytes.end..]);

        let font_unit_scale = self.shape_like_run(shaped, run);
        let (shaped_clusters_range, glyphs_range) = push_glyph_buffer(
            &mut reshaped.shaped_clusters,
            &mut reshaped.glyphs,
            &self.buffer,
            font_unit_scale,
            run.bidi_level.is_rtl(),
            characters,
            (chars.start as usize..chars.end as usize).into(),
            shaped.has_safe_to_concat_flags,
        );

        reshaped.runs.push(ReshapedRun {
            run: ShapedRun {
                range: TextRange {
                    byte_range: bytes.into(),
                    char_range: (chars.start as usize..chars.end as usize).into(),
                },
                characters_range: chars.into(),
                shaped_clusters_range,
                glyphs_range,
                ..*run
            },
            source_run: run_index,
        });

        reshaped.runs.len() as u32 - 1
    }

    /// Shape `self.buffer` in-place with the font, normalized coordinates, direction, script,
    /// language, features and font size, that `run` of `shaped` was shaped with.
    ///
    /// The buffer's characters and pre/post context must already be set.
    ///
    /// Returns the font unit scale.
    fn shape_like_run(&mut self, shaped: &ShapedText, run: &ShapedRun) -> f32 {
        let font = &shaped.fonts()[run.font_index];
        let face = cache::ShapeDataKey::new(font.font.data.id(), font.font.index);
        let base_font = self.shape_data_cache.entry(face, || {
            let (data, _) = font.font.data.clone().into_raw_parts();
            // TODO: How do we want to handle errors like this?
            harfrust::Font::new(data, font.font.index).unwrap()
        });
        // The run's coordinates already include the synthesis's and the item's variations.
        let instance = base_font
            .instance_builder()
            .normalized_coords(
                shaped.normalized_coords()[run.normalized_coords_range]
                    .iter()
                    .map(|coord| harfrust::font::NormalizedCoord::from_bits(coord.to_bits())),
            )
            .build();

        let direction = if run.bidi_level.is_rtl() {
            harfrust::Direction::RightToLeft
        } else {
            harfrust::Direction::LeftToRight
        };
        let hb_script = script_to_harfrust(run.script);
        let language = language_to_harfrust(run.language.as_ref());
        features_to_harfrust(&shaped.features()[run.features_range], &mut self.features);
        // Ensure that this logic is the same as in parley_engine/src/shape/shaper.rs
        let plan_key = harfrust::ShapePlanKey::new(&instance, Some(hb_script), direction)
            .language(language.as_ref())
            .features(&self.features);
        let (_, shaper_plan) = self
            .shape_plan_cache
            .entry(|(cached_face, plan)| face == *cached_face && plan_key.matches(plan))
            .or_insert_with(|| {
                let plan = harfrust::ShapePlan::new(
                    &instance,
                    direction,
                    Some(hb_script),
                    language.as_ref(),
                    &self.features,
                );
                (face, plan)
            });

        let buffer = &mut self.buffer;
        buffer.set_cluster_level(harfrust::ClusterLevel::MonotoneCharacters);
        buffer.set_flags(if shaped.has_safe_to_concat_flags {
            harfrust::BufferFlags::PRODUCE_UNSAFE_TO_CONCAT
        } else {
            harfrust::BufferFlags::empty()
        });
        buffer.set_direction(direction);
        buffer.set_script(Some(hb_script));
        buffer.set_language(language);

        harfrust::shape(
            &harfrust::ShaperFont::new(&instance),
            buffer,
            HarfShapeOptions::new()
                .plan(Some(shaper_plan))
                .features(&self.features)
                .point_size(Some(run.font_size)),
        )
        .expect("buffer direction and script match the shape plan");
        run.font_size / instance.units_per_em() as f32
    }
}

/// An edit made to one edge of a line.
///
/// This replaces the characters at that edge by other text.
///
/// - In Dutch, "skiën" written with hyphenation can become "ski-en". The first line ends with
///   `Edit::new(0, "-")`, and the second line starts with `Edit::new(1, "e")`.
/// - In Norwegian, "bussjåfør" can become "buss-sjåfør". The first line ends with
///   `Edit::new(0, "-")`, and the second line starts with `Edit::new(0, "s")`.
///
/// Note that inserted text is shaped with the font of the [`ShapedRun`] at that edge, without font
/// fallback. The glyphs of the inserted text belong to the logically first replaced character, or,
/// if no characters are replaced, to the character at the line's edge.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Edit<'a> {
    /// The number of source characters dropped and replaced by [`Self::inserted`].
    ///
    /// This number can be zero if no source text is dropped or substituted, so in particular this
    /// is also zero if characters were only inserted.
    replaced_chars: u32,

    /// The inserted text.
    ///
    /// Inserted text takes the character index of the logically-first replaced character. If there
    /// are no replaced characters, it attaches to the character at the edge. For a line spanning
    /// character indices `[p, q)` this is `p` for the start, and `q - max(replaced_chars, 1)` for
    /// the end.
    inserted: &'a str,
}

impl<'a> Edit<'a> {
    /// Replace the `replaced_chars` source characters at the line's edge by `inserted`.
    ///
    /// The replaced characters must lie in the [`ShapedRun`] at that edge of the line.
    ///
    /// For an edit at the line's logical start, the replaced characters are the line's first
    /// characters. For an edit at a line's logical end, these are the line's last characters.
    /// `replaced_chars` may be zero, in which case `inserted` is only inserted. With an empty
    /// `inserted`, the characters are only dropped.
    #[inline(always)]
    pub const fn new(replaced_chars: u32, inserted: &'a str) -> Self {
        Self {
            replaced_chars,
            inserted,
        }
    }

    /// The number of characters replaced by this [`Edit`].
    #[inline(always)]
    pub fn replaced_chars(self) -> u32 {
        self.replaced_chars
    }

    /// The characters inserted by this [`Edit`].
    #[inline(always)]
    pub fn inserted(&self) -> &'a str {
        self.inserted
    }
}

#[cfg(test)]
mod tests {
    use alloc::vec::Vec;

    use super::{Edit, Range, ReshapedLine, ReshapedText, Reshaper};
    use crate::{Glyph, ShapedSlice, ShapedText, shape::shaped_text::tests::*};

    type Cluster = (Range<u32>, f32, Vec<Glyph>);

    fn clusters(slice: ShapedSlice<'_>) -> impl Iterator<Item = Cluster> {
        slice.shaped_clusters_range().map(move |i| {
            let cluster = slice.shaped_clusters[i as usize];
            let glyphs = slice.shaped_cluster_glyphs(i).collect();
            (cluster.chars_range(), cluster.advance, glyphs)
        })
    }

    /// The clusters of `line` in logical order.
    fn line_clusters(shaped: &ShapedText, out: &ReshapedText, line: ReshapedLine) -> Vec<Cluster> {
        let range = line.source_shaped_clusters_range();
        let source = ShapedSlice {
            clusters: range.into(),
            ..shaped.run_slice(0)
        };
        let [start, end] =
            [line.start_run(), line.end_run()].map(|run| run.map(|run| out.run_slice(shaped, run)));
        let slices = start.into_iter().chain([source]).chain(end);
        slices.flat_map(clusters).collect()
    }

    /// The clusters of reshaping `chars` with the edits at its start and end, by reshaping runs as
    /// a whole.
    fn reshape_whole(
        text: &str,
        shaped: &ShapedText,
        chars: Range<u32>,
        [start_edit, end_edit]: [Option<Edit<'_>>; 2],
    ) -> Vec<Cluster> {
        let (mut reshaper, mut out, mut result) =
            (Reshaper::default(), ReshapedText::new(), Vec::new());
        for (i, run) in (0..).zip(shaped.runs()) {
            let a = chars.start.max(run.characters_range.start);
            let b = chars.end.min(run.characters_range.end);
            if a < b {
                let start = start_edit.filter(|_| a == chars.start);
                let end = end_edit.filter(|_| b == chars.end);
                let run = reshaper.reshape(text, shaped, i, a..b, start, end, &mut out);
                result.extend(clusters(out.run_slice(shaped, run)));
            }
        }
        result
    }

    #[test]
    fn reshaped_lines() {
        // The following font selector attempts to shape 'س' with Roboto to split the Arabic text
        // into runs mid-word, so we can exercise shaping that depends on context.
        let fonts = |font| FontForChar {
            ch: 'س',
            font: font_instance(ROBOTO),
            other_font: font_instance(font),
        };
        let mut reshaper = Reshaper::default();
        let mut fast_misses = 0;
        for (text, font) in [("office AVA", ROBOTO), ("كتب وهب بسلاسة", NOTO_KUFI_ARABIC)]
        {
            let shaped = shape_with_font_selector(text, fonts(font), true);
            let chars = shaped.characters();
            let len = u32::try_from(chars.len()).unwrap();

            // An edit where the character is replaced by itself.
            let same = |i: u32| Edit::new(1, &text[chars[i as usize].text_byte_range()]);

            reshaper.clear();
            let mut out = ReshapedText::new();

            let boundaries = || (0..=len).filter(|&i| i == len || chars[i as usize].grapheme_start);
            for p in boundaries() {
                for q in boundaries().filter(|&q| q >= p) {
                    let source: f32 = (shaped.shaped_clusters().iter())
                        .filter(|c| (p..q).contains(&c.chars_range().start))
                        .map(|c| c.advance)
                        .sum();
                    let none = [None; 2];
                    let insert = [Some(Edit::new(0, "s")), Some(Edit::new(0, "-"))];
                    // Replacing a character by itself is no edit at all (and empty lines drop their
                    // edits).
                    let same = [Some(same(p.min(len - 1))), Some(same(q.max(1) - 1))];
                    for (edits, equivalent_edits) in [(none, none), (insert, insert), (same, none)]
                    {
                        let replaced = edits.map(|edit| edit.map_or(0, Edit::replaced_chars));
                        if p < q && replaced[0] + replaced[1] > q - p {
                            continue;
                        }
                        let whole = reshape_whole(text, &shaped, p..q, equivalent_edits);
                        let (start, start_slice) =
                            reshaper.measure_start(text, &shaped, p, edits[0]);
                        let splice = (shaped.shaped_clusters())
                            .get(start.source_clusters_start as usize)
                            .map_or(len, |c| c.chars_range().start);
                        assert_eq!(start_slice.map_or(p..p, |s| s.char_range()), p..splice);
                        if let Some(slice) = start_slice {
                            let edits = [equivalent_edits[0], None];
                            let whole = reshape_whole(text, &shaped, slice.char_range(), edits);
                            assert_eq!(clusters(slice).collect::<Vec<_>>(), whole);
                        }
                        let end = reshaper.measure_end(text, &shaped, q, edits[1]);
                        let fast = reshaper.line(text, &shaped, &start, &end);
                        for (line, exact) in [
                            (fast, false),
                            (reshaper.make_exact(text, &shaped, fast), true),
                        ] {
                            let pushed = reshaper.push_line(text, &shaped, &line, &mut out);
                            let clusters = line_clusters(&shaped, &out, pushed);
                            let advance: f32 = clusters.iter().map(|c| c.1).sum();
                            assert!((advance - source - line.advance_delta()).abs() < 1e-3);
                            assert_eq!(pushed.advance_delta(), line.advance_delta());
                            if exact {
                                assert_eq!(clusters, whole, "{text} {p}..{q} {edits:?}");
                            } else {
                                fast_misses += usize::from(clusters != whole);
                            }
                        }
                    }
                }
            }
        }
        assert!(
            fast_misses > 0,
            "We expect some misses for the 'fast' reshaping, so that we're actually exercising `make_exact`"
        );
    }
}