Scoop API

scoop:scoop.regex:0.1.0

src/positions.scoop

Selected production source · src/positions.scoop

1package scoop.regex
3// Checkpoints are scalar-aligned and contain no borrowed pointers. Each scanned byte is
4// visited once when extending the index; endpoint conversion scans at most one 64-scalar block.
5internal class RegexInput internal constructor(internal val text: String) {
6 private val blocks: ArrayList<Long> = initialBlocks()
7 private var scannedByte: Long = 0L
8 private var scannedScalar: Long = 0L
10 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) * 64L
18 var offset = blocks[index / 64L]
19 while (scalar < index) { offset += utf8Step(bytes.load(offset)); scalar += 1L }
20 return@withUtf8Bytes offset
21 }
22 }
23 }
24 }
26 @Unsafe
27 internal fun scalarOffset(offset: Long, bytes: Ptr<UInt8>, count: Long): Long {
28 while (scannedByte < offset && scannedByte < count) advance(bytes)
29 var low = 0L
30 var high = blocks.size
31 while (low + 1L < high) {
32 val middle = low + (high - low) / 2L
33 if (blocks[middle] <= offset) low = middle else high = middle
34 }
35 var cursor = blocks[low]
36 var scalar = low * 64L
37 while (cursor < offset && cursor < count) {
38 cursor += utf8Step(bytes.load(cursor))
39 scalar += 1L
40 }
41 return scalar
42 }
44 @Unsafe
45 private fun advance(bytes: Ptr<UInt8>) {
46 scannedByte += utf8Step(bytes.load(scannedByte))
47 scannedScalar += 1L
48 if (scannedScalar % 64L == 0L) blocks.add(scannedByte)
49 }
52private fun initialBlocks(): ArrayList<Long> {
53 val result = ArrayList<Long>()
54 result.add(0L)
55 return result
58private fun utf8Step(first: UInt8): Long {
59 val value = first.toInt()
60 if (value < 128) return 1L
61 if (value < 224) return 2L
62 if (value < 240) return 3L
63 return 4L