Scoop API

scoop:scoop.core:0.1.0

src/char_range.scoop

Selected production source · src/char_range.scoop

1private const val SURROGATE_START: Int = 0xD800
3private const val SURROGATE_COUNT: Int = 0x800
5/**
6 * An immutable range of Unicode scalar values. Iteration and step alignment skip the surrogate
7 * interval, so U+D7FF and U+E000 are adjacent.
8 */
9public class CharRange private constructor(private val indices: IntRange) :
10 Iterable<Char>,
11 Contains<Char> {
12 internal constructor(
13 first: Char,
14 endpoint: Char,
15 descending: Boolean = false,
16 inclusive: Boolean = true
17 ) : this(IntRange(first.scalarIndex(), endpoint.scalarIndex(), 1, descending, inclusive)) {}
19 /** Creates a fresh cursor over the range's scalar values. */
20 public override operator fun iterator(): Iterator<Char> = CharRangeIterator(indices.iterator())
22 /**
23 * Replaces the step in scalar positions, preserving the start, direction, and endpoint policy.
24 * Zero or negative steps throw [IllegalArgumentException].
25 */
26 public infix fun step(value: Int): CharRange = CharRange(indices step value)
28 /** Returns whether iteration with this range's bounds and step yields [value]. */
29 public override operator fun contains(value: Char): Boolean = value.scalarIndex() in indices
32private class CharRangeIterator(private val indices: Iterator<Int>) : Iterator<Char> {
33 public override fun next(): Option<Char> = when (indices.next()) {
34 case Some(val index) -> Some(scalarAt(index))
35 case None -> None
36 }
39private fun Char.scalarIndex(): Int {
40 val code = this.code
41 return if (code < SURROGATE_START) code else code - SURROGATE_COUNT
44private fun scalarAt(index: Int): Char {
45 val code = if (index < SURROGATE_START) index else index + SURROGATE_COUNT
46 // The integer cursor only yields indices between the two valid scalar endpoints.
47 @Unsafe {
48 return code.characterUnchecked()
49 }