scoop:scoop.core:0.1.0
src/string_scans.scoop
Selected production source · src/string_scans.scoop
1
// Valid UTF-8 has exactly one non-continuation byte per scalar.2
internal fun coreStringLength(value: String): Long {3
val length = coreStringByteLength(value)4
var cursor = 0L5
var count = 0L6
while (cursor < length) {7
val size = if (length - cursor >= 64L) 64L else length - cursor8
count += coreStringCountBlock(value, cursor, size)9
cursor += size10
}11
return count12
}14
// The sole caller limits size to 64, so the byte counter cannot overflow.15
// Ordinary poll chunking bounds uninterrupted work; widen after the reduction.16
private fun coreStringCountBlock(value: String, start: Long, size: Long): Long {17
@Unsafe {18
var index = 0L19
var count = 0.toUByte()20
while (index < size) {21
if (coreStringByteAtUnchecked(value, start + index).toUByte().and(192u) != 128u) { count += 1u }22
index += 1L23
}24
return count.toLong()25
}26
}28
internal fun coreStringGet(value: String, index: Long): Char? {29
@Unsafe {30
if (index < 0L) { return None }31
val length = coreStringByteLength(value)32
var cursor = 0L33
var scalar = 0L34
while (cursor < length) {35
if (coreStringByteAtUnchecked(value, cursor).toUByte().and(192u) != 128u) {36
if (scalar == index) { return Some(coreStringCharacterAtByte(value, cursor)) }37
scalar += 1L38
}39
cursor += 1L40
}41
return None42
}43
}45
internal fun coreStringSliceBounds(value: String, start: Long, endExclusive: Long): (Long, Long)? {46
@Unsafe {47
if (start < 0L || endExclusive < start) { return None }48
val length = coreStringByteLength(value)49
var cursor = 0L50
var scalar = 0L51
var startByte = 0L52
while (cursor < length) {53
if (coreStringByteAtUnchecked(value, cursor).toUByte().and(192u) != 128u) {54
if (scalar == start) { startByte = cursor }55
if (scalar == endExclusive) { return Some((startByte, cursor)) }56
scalar += 1L57
}58
cursor += 1L59
}60
if (scalar != endExclusive) { return None }61
return Some((if (start == endExclusive) length else startByte, length))62
}63
}