Skip to content

Commit ced1582

Browse files
committed
Protect word segmentation from changes
Concurrent changes will no longer crash the word segmentation algorithm
1 parent c8705b9 commit ced1582

1 file changed

Lines changed: 11 additions & 3 deletions

File tree

ComposeTextEditor/src/commonMain/kotlin/com/darkrockstudios/texteditor/state/WordSegmentationUtils.kt

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@ import com.darkrockstudios.texteditor.CharLineOffset
44
import com.darkrockstudios.texteditor.TextEditorRange
55

66
fun TextEditorState.wordSegments(): Sequence<WordSegment> = sequence {
7-
textLines.asSequence().withIndex().forEach { (lineIndex, line) ->
7+
// Take a snapshot of all text lines to avoid crashes if textLines changes during iteration
8+
val linesSnapshot = textLines.toList()
9+
10+
linesSnapshot.asSequence().withIndex().forEach { (lineIndex, line) ->
811
var wordStart = -1
912
var currentChar = 0
1013

@@ -203,8 +206,13 @@ fun TextEditorState.wordSegmentsInRange(range: TextEditorRange): List<WordSegmen
203206

204207
val segments = mutableListOf<WordSegment>()
205208

206-
for (lineIndex in range.start.line..range.end.line) {
207-
val lineText = textLines[lineIndex].text
209+
// Take a snapshot of the lines we need to avoid crashes if textLines changes during iteration
210+
val linesToProcess = (range.start.line..range.end.line).map { lineIndex ->
211+
lineIndex to textLines[lineIndex]
212+
}
213+
214+
for ((lineIndex, line) in linesToProcess) {
215+
val lineText = line.text
208216
if (lineText.isEmpty()) continue
209217

210218
// Determine the character range within the line to check

0 commit comments

Comments
 (0)