scoop:scoop.core:0.1.0
src/char_range.scoop
Selected production source · src/char_range.scoop
1
private const val SURROGATE_START: Int = 0xD8003
private const val SURROGATE_COUNT: Int = 0x8005
/**6
* An immutable range of Unicode scalar values. Iteration and step alignment skip the surrogate7
* interval, so U+D7FF and U+E000 are adjacent.8
*/9
public 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 = true17
) : 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 indices30
}32
private 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 -> None36
}37
}39
private fun Char.scalarIndex(): Int {40
val code = this.code41
return if (code < SURROGATE_START) code else code - SURROGATE_COUNT42
}44
private fun scalarAt(index: Int): Char {45
val code = if (index < SURROGATE_START) index else index + SURROGATE_COUNT46
// The integer cursor only yields indices between the two valid scalar endpoints.47
@Unsafe {48
return code.characterUnchecked()49
}50
}