Scoop API

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.
2internal fun coreStringLength(value: String): Long {
3 val length = coreStringByteLength(value)
4 var cursor = 0L
5 var count = 0L
6 while (cursor < length) {
7 val size = if (length - cursor >= 64L) 64L else length - cursor
8 count += coreStringCountBlock(value, cursor, size)
9 cursor += size
10 }
11 return count
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.
16private fun coreStringCountBlock(value: String, start: Long, size: Long): Long {
17 @Unsafe {
18 var index = 0L
19 var count = 0.toUByte()
20 while (index < size) {
21 if (coreStringByteAtUnchecked(value, start + index).toUByte().and(192u) != 128u) { count += 1u }
22 index += 1L
23 }
24 return count.toLong()
25 }
28internal fun coreStringGet(value: String, index: Long): Char? {
29 @Unsafe {
30 if (index < 0L) { return None }
31 val length = coreStringByteLength(value)
32 var cursor = 0L
33 var scalar = 0L
34 while (cursor < length) {
35 if (coreStringByteAtUnchecked(value, cursor).toUByte().and(192u) != 128u) {
36 if (scalar == index) { return Some(coreStringCharacterAtByte(value, cursor)) }
37 scalar += 1L
38 }
39 cursor += 1L
40 }
41 return None
42 }
45internal 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 = 0L
50 var scalar = 0L
51 var startByte = 0L
52 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 += 1L
57 }
58 cursor += 1L
59 }
60 if (scalar != endExclusive) { return None }
61 return Some((if (start == endExclusive) length else startByte, length))
62 }