scoop:scoop.regex:0.1.0
src/positions.scoop
Selected production source · src/positions.scoop
1
package scoop.regex3
// Checkpoints are scalar-aligned and contain no borrowed pointers. Each scanned byte is4
// visited once when extending the index; endpoint conversion scans at most one 64-scalar block.5
internal class RegexInput internal constructor(internal val text: String) {6
private val blocks: ArrayList<Long> = initialBlocks()7
private var scannedByte: Long = 0L8
private var scannedScalar: Long = 0L10
internal fun byteOffset(index: Long): Long {11
if (index < 0L) throw IndexOutOfBoundsException()12
@Unsafe {13
return text.withUtf8Bytes { bytes, count ->14
@Unsafe {15
while (scannedScalar < index && scannedByte < count) advance(bytes)16
if (scannedScalar < index) throw IndexOutOfBoundsException()17
var scalar = (index / 64L) * 64L18
var offset = blocks[index / 64L]19
while (scalar < index) { offset += utf8Step(bytes.load(offset)); scalar += 1L }20
return@withUtf8Bytes offset21
}22
}23
}24
}26
@Unsafe27
internal fun scalarOffset(offset: Long, bytes: Ptr<UInt8>, count: Long): Long {28
while (scannedByte < offset && scannedByte < count) advance(bytes)29
var low = 0L30
var high = blocks.size31
while (low + 1L < high) {32
val middle = low + (high - low) / 2L33
if (blocks[middle] <= offset) low = middle else high = middle34
}35
var cursor = blocks[low]36
var scalar = low * 64L37
while (cursor < offset && cursor < count) {38
cursor += utf8Step(bytes.load(cursor))39
scalar += 1L40
}41
return scalar42
}44
@Unsafe45
private fun advance(bytes: Ptr<UInt8>) {46
scannedByte += utf8Step(bytes.load(scannedByte))47
scannedScalar += 1L48
if (scannedScalar % 64L == 0L) blocks.add(scannedByte)49
}50
}52
private fun initialBlocks(): ArrayList<Long> {53
val result = ArrayList<Long>()54
result.add(0L)55
return result56
}58
private fun utf8Step(first: UInt8): Long {59
val value = first.toInt()60
if (value < 128) return 1L61
if (value < 224) return 2L62
if (value < 240) return 3L63
return 4L64
}