diff --git a/Sources/RopeModule/BString/Basics/_BString+Contents.swift b/Sources/RopeModule/BString/Basics/_BString+Contents.swift index 97ec728f..20e822b7 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Contents.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Contents.swift @@ -154,6 +154,10 @@ extension _BString { in metric: some _StringMetric ) -> Index { precondition(i <= endIndex, "Index out of bounds") + if isEmpty { + precondition(distance == 0, "Index out of bounds") + return startIndex + } let i = resolve(i, preferEnd: i == endIndex || distance < 0) var ri = i._rope! var ci = i._chunkIndex @@ -265,7 +269,7 @@ extension _BString { let i = resolve(i, preferEnd: false) let ri = i._rope! var ci = i._chunkIndex - var chunk = rope[ri] + let chunk = rope[ri] chunk.string.utf8.formIndex(after: &ci) if ci == chunk.string.endIndex { return Index( @@ -360,9 +364,10 @@ extension _BString { func utf8Index(roundingDown i: Index) -> Index { precondition(i <= endIndex, "Index out of bounds") + guard i < endIndex else { return endIndex } var r = i r._clearUTF16TrailingSurrogate() - return r + return resolve(r, preferEnd: false) } func utf16Index(roundingDown i: Index) -> Index { diff --git a/Sources/RopeModule/BString/Basics/_BString+Index.swift b/Sources/RopeModule/BString/Basics/_BString+Index.swift index b232fd39..d16c7521 100644 --- a/Sources/RopeModule/BString/Basics/_BString+Index.swift +++ b/Sources/RopeModule/BString/Basics/_BString+Index.swift @@ -151,7 +151,7 @@ extension _BString { func resolve(_ i: Index, preferEnd: Bool) -> Index { if var ri = i._rope, rope.isValid(ri) { if preferEnd { - guard i._utf8ChunkOffset == 0 else { return i } + guard i._utf8ChunkOffset == 0, i._utf8Offset > 0 else { return i } rope.formIndex(before: &ri) let length = rope[ri].utf8Count let ci = String.Index(_utf8Offset: length) diff --git a/Sources/RopeModule/Rope/Operations/_Rope+Find.swift b/Sources/RopeModule/Rope/Operations/_Rope+Find.swift index 3da974d9..bac1fa54 100644 --- a/Sources/RopeModule/Rope/Operations/_Rope+Find.swift +++ b/Sources/RopeModule/Rope/Operations/_Rope+Find.swift @@ -17,7 +17,7 @@ extension _Rope { ) -> (index: Index, remaining: Int) { let wholeSize = _root == nil ? 0 : metric.size(of: root.summary) precondition(position >= 0 && position <= wholeSize, "Position out of bounds") - guard preferEnd || position < wholeSize else { + guard !isEmpty, preferEnd || position < wholeSize else { return (endIndex, position) } var position = position