Skip to content

Commit 47bd3db

Browse files
committed
refactor: process text with entities by pangu
Signed-off-by: qwq233 <qwq233@qwq2333.top>
1 parent cae57e7 commit 47bd3db

File tree

1 file changed

+18
-30
lines changed

1 file changed

+18
-30
lines changed

TMessagesProj/src/main/java/top/qwq2333/nullgram/utils/StringUtils.kt

Lines changed: 18 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -112,42 +112,30 @@ object StringUtils {
112112
if (entities.isNullOrEmpty()) return Pair(pangu.spacingText(text), entities)
113113

114114
val panguText = pangu.spacingText(text)
115-
val panguEntities = arrayListOf<TLRPC.MessageEntity>()
116115

117116
if (panguText.length == text.length) return Pair(panguText, entities) // processed or unnecessary
118117

119-
entities.forEach {
118+
var skip = 0
119+
for (i in 0 until text.lastIndex) {
120+
if (i + skip >= panguText.length) break
121+
if (text[i] == panguText[i + skip]) continue
120122

121-
val char = mutableListOf<Char>().also { list ->
122-
for (i in it.offset until (it.offset + it.length).coerceAtMost(text.length)) {
123-
list.add(text[i])
124-
}
125-
}.also { list ->
126-
if (list.isEmpty()) return@forEach
123+
entities.forEach {
124+
if (it.offset >= i + skip) { // text is after this entity
125+
it.offset += 1
126+
} else if (it.offset + it.length >= i + skip) { // text is in this entity
127+
it.length += 1
128+
} // text is before this entity
127129
}
130+
skip += 1
131+
}
128132

129-
var length = 0
130-
var start = it.offset
131-
var matched = false // matched first character
132-
for (i in it.offset until panguText.length) {
133-
if (start > i) continue
134-
if (panguText[i] == char[0]) { // match
135-
char.removeAt(0)
136-
if (!matched) {
137-
start = i
138-
matched = true
139-
}
140-
}
141-
if (matched) length++
142-
if (char.isEmpty()) { // empty processing list
143-
panguEntities.add(it.apply {
144-
it.offset = start
145-
it.length = length.coerceAtMost(panguText.lastIndex)
146-
})
147-
break
148-
}
149-
}
133+
// ensure offset and length is valid
134+
entities.forEach {
135+
it.offset = it.offset.coerceAtLeast(0).coerceAtMost(panguText.length)
136+
it.length = it.length.coerceAtLeast(0).coerceAtMost(panguText.length - it.offset)
150137
}
151-
return Pair(panguText, panguEntities)
138+
139+
return Pair(panguText, entities)
152140
}
153141
}

0 commit comments

Comments
 (0)