Skip to content

std/codepoint

Unicode scalar values. String iterates by grapheme cluster for text workflows; use String.codepoints when code needs to inspect the scalar values that make up a string.

Import with import std/codepoint.

Types

type Codepoint Int

opaque — construction surface is private to its defining module

A Unicode code point / scalar value: 0..=0x10FFFF, excluding UTF-16 surrogate code points. Backed by Int, but validated at construction.

fn from_int(n: Int): Maybe<Codepoint>

type function on Codepoint

Validates n and wraps it as a Codepoint.

Interactive Tests

assert Codepoint.from_int(65) == Some(Codepoint(65))
assert Codepoint.from_int(55_296) == None
fn to_int(Codepoint(n)): Int

type function on Codepoint

Returns the numeric Unicode scalar value.

Interactive Tests

assert Codepoint.to_int(try Codepoint.from_int(65)) == 65

impl Display

fn to_string(cp: Codepoint): String

impl Display.to_string

Returns a one-codepoint string containing cp.

Interactive Tests

assert Codepoint.to_string(try Codepoint.from_int(65)) == "A"

impl Debug

fn inspect(cp: Codepoint): String

impl Debug.inspect

Returns the developer-facing representation, e.g. Codepoint(65).

Interactive Tests

assert Codepoint.inspect(try Codepoint.from_int(65)) == "Codepoint(65)"

impl Discrete

fn next(cp: Codepoint): Maybe<Codepoint>

impl Discrete.next

Returns the next valid Codepoint, skipping the UTF-16 surrogate block. Returns None after the largest Unicode scalar value.

Interactive Tests

assert Codepoint.next(try Codepoint.from_int(65)) == Some(Codepoint(66))
assert Codepoint.next(try Codepoint.from_int(0x10FFFF)) == None

impl Discrete

fn steps_between(Codepoint(a), Codepoint(b)): Maybe<Int>

impl Discrete.steps_between

Counts how many next steps move from the first Codepoint to the second, skipping invalid surrogate values without walking the range.

Interactive Tests

assert Codepoint.steps_between(
  try Codepoint.from_int(97),
  try Codepoint.from_int(100),
) == Some(3)

impl Steppable

fn step_by(cp: Codepoint, by: Int): Maybe<Codepoint>

impl Steppable.step_by

Steps by a count of valid Unicode scalar values, skipping the UTF-16 surrogate block. Returns None if the destination is outside the Codepoint domain.

Interactive Tests

assert Codepoint.step_by(try Codepoint.from_int(65), 2) == Some(Codepoint(67))

impl Equatable

fn equal?(a: Codepoint, b: Codepoint): Bool

impl Equatable.equal?

impl Hashable

fn hash(value: Codepoint): Int

impl Hashable.hash

impl Comparable

fn compare(a: Codepoint, b: Codepoint): Ordering

impl Comparable.compare