#Builtin Package Documentation

    This package provides the core built-in types, functions, and utilities that are fundamental to MoonBit programming. It includes basic data structures, iterators, assertions, and core language features.

    #Core Types and Functions

    #Assertions and Testing

    MoonBit provides built-in assertion functions for testing:

    ///|
    test "assertions" {
    // Basic equality assertion
    @test.assert_eq(1 + 1, 2)
    @test.assert_eq("hello", "hello")

    // Boolean assertions
    assert_true(5 > 3)
    assert_false(2 > 5)

    // Inequality assertion
    @test.assert_not_eq(1, 2)
    @test.assert_not_eq("foo", "bar")
    }

    #Inspect Function

    The inspect function is used for testing and debugging:

    ///|
    test "inspect usage" {
    let value = 42
    inspect(value, content="42")
    let list = [1, 2, 3]
    debug_inspect(list, content="[1, 2, 3]")
    let result : Result[Int, String] = Ok(100)
    debug_inspect(result, content="Ok(100)")
    }

    #Result Type

    The Result[T, E] type represents operations that can succeed or fail:

    ///|
    test "result type" {
    fn divide(a : Int, b : Int) -> Result[Int, String] {
    if b == 0 {
    Err("Division by zero")
    } else {
    Ok(a / b)
    }
    }

    // Success case
    let result1 = divide(10, 2)
    debug_inspect(result1, content="Ok(5)")

    // Error case
    let result2 = divide(10, 0)
    debug_inspect(result2, content="Err(\"Division by zero\")")

    // Pattern matching on Result
    match result1 {
    Ok(value) => inspect(value, content="5")
    Err(_) => inspect(false, content="true")
    }
    }

    #Option Type

    The Option[T] type represents values that may or may not exist:

    ///|
    test "option type" {
    fn find_first_even(numbers : Array[Int]) -> Int? {
    for num in numbers {
    if num % 2 == 0 {
    return Some(num)
    }
    }
    None
    }

    // Found case
    let result1 = find_first_even([1, 3, 4, 5])
    debug_inspect(result1, content="Some(4)")

    // Not found case
    let result2 = find_first_even([1, 3, 5])
    debug_inspect(result2, content="None")

    // Pattern matching on Option
    match result1 {
    Some(value) => inspect(value, content="4")
    None => inspect(false, content="true")
    }
    }

    #Iterator Type

    The Iter[T] type provides lazy iteration over sequences:

    ///|
    test "iterators" {
    // Create iterator from array
    let numbers = [1, 2, 3, 4, 5]
    let iter = numbers.iter()

    // Collect back to array
    let collected = iter.collect()
    debug_inspect(collected, content="[1, 2, 3, 4, 5]")

    // Map transformation
    let doubled = numbers.iter().map(fn(x) { x * 2 }).collect()
    debug_inspect(doubled, content="[2, 4, 6, 8, 10]")

    // Filter elements
    let evens = numbers.iter().filter(fn(x) { x % 2 == 0 }).collect()
    debug_inspect(evens, content="[2, 4]")

    // Fold (reduce) operation
    let sum = numbers.iter().fold(init=0, fn(acc, x) { acc + x })
    inspect(sum, content="15")
    }

    #Array and FixedArray

    Built-in array types for storing collections:

    ///|
    test "arrays" {
    // Dynamic arrays
    let arr1 = Array()
    arr1.push(1)
    arr1.push(2)
    arr1.push(3)
    debug_inspect(arr1, content="[1, 2, 3]")

    // Array from literal
    let arr2 = [10, 20, 30]
    debug_inspect(arr2, content="[10, 20, 30]")

    // Array operations
    let length = arr2.length()
    inspect(length, content="3")
    let first = arr2[0]
    inspect(first, content="10")
    }

    Fixed-size array for storing collections of constant size:

    ///|
    test "fixed arrays" {
    // FixedArray from literal
    let fixed_arr : FixedArray[Int] = [10, 20, 30]
    debug_inspect(
    fixed_arr,
    content=(
    #|<FixedArray: [10, 20, 30]>
    ),
    )

    // FixedArray operations
    let length = fixed_arr.length()
    inspect(length, content="3")
    let first = fixed_arr[0]
    inspect(first, content="10")
    }

    #Views (Zero-Copy Slices)

    Each owning container has a matching view type created with the a[start:end] slice syntax. A view is a small record holding a reference to the shared storage plus its window bounds, so slicing never copies the elements:

    direction: right owners: "Owning containers" { arr: "Array[T] / FixedArray[T] / ReadOnlyArray[T]" bytes: "Bytes" str: "String" } views: "Zero-copy views (shared storage + window bounds)" { arrview: "ArrayView[T]" bytesview: "BytesView" strview: "StringView" } owners.arr -> views.arrview: "a[start:end]" owners.bytes -> views.bytesview: "b[start:end]" owners.str -> views.strview: "s[start:end]"

    Views are ideal for rest patterns ([first, .. rest]) and for passing sub-sequences without allocation; functions taking a view also accept the owning container through implicit conversion. Note that the s[start:end] slice syntax on String panics when a boundary would split a UTF-16 surrogate pair:

    ///|
    test "views are zero copy" {
    let arr = [1, 2, 3, 4, 5]
    let view = arr[1:4]
    @test.assert_eq(view.length(), 3)
    @test.assert_eq(view[0], 2)
    view is [first, .. rest]
    @test.assert_eq(first, 2)
    @test.assert_eq(rest.length(), 2)
    }

    #String Operations

    Basic string functionality:

    ///|
    test "strings" {
    let text = "Hello, World!"

    // String length
    let len = text.length()
    inspect(len, content="13")

    // String concatenation
    let greeting = "Hello" + ", " + "World!"
    inspect(greeting, content="Hello, World!")

    // String comparison
    let equal = "test" == "test"
    inspect(equal, content="true")
    }

    #StringBuilder

    Efficient string building:

    ///|
    test "string builder" {
    let builder = StringBuilder()
    builder.write_string("Hello")
    builder.write_string(", ")
    builder.write_string("World!")
    let result = builder.to_string()
    inspect(result, content="Hello, World!")
    }

    #JSON Support

    Basic JSON operations:

    ///|
    test "json" {
    // JSON values
    let json_null = null
    @debug.debug_inspect(json_null, content="Null")
    let json_bool = true.to_json()
    @debug.debug_inspect(json_bool, content="True")
    let json_number = (42 : Int).to_json()
    @debug.debug_inspect(json_number, content="Number(42)")
    let json_string = "hello".to_json()
    @debug.debug_inspect(
    json_string,
    content=(
    #|String("hello")
    ),
    )
    }

    #Comparison Operations

    Built-in comparison operators:

    ///|
    test "comparisons" {
    // Equality
    inspect(5 == 5, content="true")
    inspect(5 != 3, content="true")

    // Ordering
    inspect(3 < 5, content="true")
    inspect(5 > 3, content="true")
    inspect(5 >= 5, content="true")
    inspect(3 <= 5, content="true")

    // String comparison
    inspect("apple" < "banana", content="true")
    inspect("hello" == "hello", content="true")
    }

    #Utility Functions

    Helpful utility functions:

    ///|
    test "utilities" {
    // Identity and ignore
    let value = 42
    ignore(value) // Discards the value

    // Boolean negation
    let result = !false
    inspect(result, content="true")

    // Physical equality (reference equality)
    let arr1 = [1, 2, 3]
    let arr2 = [1, 2, 3]
    let same_ref = arr1
    inspect(physical_equal(arr1, arr2), content="false") // Different objects
    inspect(physical_equal(arr1, same_ref), content="true") // Same reference
    }

    #Error Handling

    Basic error handling with panic and abort:

    ///|
    test "error handling" {
    // This would panic in a real scenario, but we demonstrate the concept
    fn safe_divide(a : Int, b : Int) -> Int {
    if b == 0 {
    // In real code: panic()
    // For testing, we return a default value
    0
    } else {
    a / b
    }
    }

    let result = safe_divide(10, 2)
    inspect(result, content="5")
    let safe_result = safe_divide(10, 0)
    inspect(safe_result, content="0")
    }

    #Best Practices

    1. Use assertions liberally in tests: They help catch bugs early and document expected behavior
    2. Prefer Result over exceptions: For recoverable errors, use Result[T, E] instead of panicking
    3. Use Option for nullable values: Instead of null pointers, use Option[T]
    4. Leverage iterators for data processing: They provide composable and efficient data transformations
    5. Use StringBuilder for string concatenation: More efficient than repeated string concatenation
    6. Pattern match on Result and Option: Handle both success and failure cases explicitly

    #Performance Notes

    • Arrays have O(1) access and O(1) amortized append
    • Iterators are lazy and don't allocate intermediate collections
    • StringBuilder is more efficient than string concatenation for building large strings
    • Physical equality is faster than structural equality but should be used carefully

    Add

    pub(open) trait Add {
    fn add(Self, Self) -> Self
    }

    types implementing this trait can use the + operator
    impl Add for Byte
    impl Add for Int
    impl Add for Int64
    impl Add for UInt
    impl Add for UInt16
    impl Add for UInt64
    impl Add for Double
    impl Add for String
    impl Add for FixedArray[T]
    impl Add for Bytes
    impl Add for StringView

    BitAnd

    pub(open) trait BitAnd {
    fn land(Self, Self) -> Self
    }

    types implementing this trait can use the & operator
    impl BitAnd for Byte
    impl BitAnd for Int
    impl BitAnd for Int64
    impl BitAnd for UInt
    impl BitAnd for UInt16
    impl BitAnd for UInt64

    BitOr

    pub(open) trait BitOr {
    fn lor(Self, Self) -> Self
    }

    types implementing this trait can use the | operator
    impl BitOr for Byte
    impl BitOr for Int
    impl BitOr for Int64
    impl BitOr for UInt
    impl BitOr for UInt16
    impl BitOr for UInt64

    BitXOr

    pub(open) trait BitXOr {
    fn lxor(Self, Self) -> Self
    }

    types implementing this trait can use the ^ operator
    impl BitXOr for Byte
    impl BitXOr for Int
    impl BitXOr for Int64
    impl BitXOr for UInt
    impl BitXOr for UInt16
    impl BitXOr for UInt64

    Compare

    pub(open) trait Compare : Eq {
    fn compare(Self, Self) -> Int
    fn op_lt(Self, Self) -> Bool = _
    fn op_gt(Self, Self) -> Bool = _
    fn op_le(Self, Self) -> Bool = _
    fn op_ge(Self, Self) -> Bool = _
    }

    Trait for types whose elements are ordered

    The return value of [compare] is:
    • zero, if the two arguments are equal
    • negative, if the first argument is smaller
    • positive, if the first argument is greater
    impl Compare for Unit
    impl Compare for Bool
    impl Compare for Byte
    impl Compare for Char
    impl Compare for Int
    impl Compare for Int64
    impl Compare for UInt
    impl Compare for UInt16
    impl Compare for UInt64
    impl Compare for Double
    impl Compare for String
    impl Compare for Option[X]
    impl Compare for Result[T, E]
    impl Compare for FixedArray[T]
    impl Compare for Bytes
    impl Compare for Tuple2[T0, T1]
    impl Compare for Tuple3[T0, T1, T2]
    impl Compare for Tuple4[T0, T1, T2, T3]
    impl Compare for Tuple5[T0, T1, T2, T3, T4]
    impl Compare for Tuple6[T0, T1, T2, T3, T4, T5]
    impl Compare for Tuple7[T0, T1, T2, T3, T4, T5, T6]
    impl Compare for Tuple8[T0, T1, T2, T3, T4, T5, T6, T7]
    impl Compare for Tuple9[T0, T1, T2, T3, T4, T5, T6, T7, T8]
    impl Compare for Tuple10[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9]
    impl Compare for Tuple11[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]
    impl Compare for Tuple12[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11]
    impl Compare for Tuple13[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12]
    impl Compare for Tuple14[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13]
    impl Compare for Tuple15[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14]
    impl Compare for Tuple16[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15]

    Default

    pub(open) trait Default {
    fn default() -> Self
    }

    Trait for types with a default value
    impl Default for Unit
    impl Default for Bool
    impl Default for Byte
    impl Default for Char
    impl Default for Int
    impl Default for Int64
    impl Default for UInt16
    impl Default for UInt64
    impl Default for Double
    impl Default for String
    impl Default for Option[X]
    impl Default for FixedArray[X]
    impl Default for Bytes

    Div

    pub(open) trait Div {
    fn div(Self, Self) -> Self
    }

    types implementing this trait can use the / operator
    impl Div for Byte
    impl Div for Int
    impl Div for Int64
    impl Div for UInt
    impl Div for UInt16
    impl Div for UInt64
    impl Div for Double
    pub(open) trait Eq {
    fn equal(Self, Self) -> Bool
    fn not_equal(Self, Self) -> Bool = _
    }

    Trait for types whose elements can test for equality
    impl Eq for Unit
    impl Eq for Bool
    impl Eq for Byte
    impl Eq for Char
    impl Eq for Int
    impl Eq for Int64
    impl Eq for UInt
    impl Eq for UInt16
    impl Eq for UInt64
    impl Eq for Double
    impl Eq for String
    impl Eq for Option[X]
    impl Eq for Result[T, E]
    impl Eq for FixedArray[T]
    impl Eq for ReadOnlyArray[T]
    impl Eq for Bytes
    impl Eq for Tuple2[T0, T1]
    impl Eq for Tuple3[T0, T1, T2]
    impl Eq for Tuple4[T0, T1, T2, T3]
    impl Eq for Tuple5[T0, T1, T2, T3, T4]
    impl Eq for Tuple6[T0, T1, T2, T3, T4, T5]
    impl Eq for Tuple7[T0, T1, T2, T3, T4, T5, T6]
    impl Eq for Tuple8[T0, T1, T2, T3, T4, T5, T6, T7]
    impl Eq for Tuple9[T0, T1, T2, T3, T4, T5, T6, T7, T8]
    impl Eq for Tuple10[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9]
    impl Eq for Tuple11[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]
    impl Eq for Tuple12[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11]
    impl Eq for Tuple13[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12]
    impl Eq for Tuple14[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13]
    impl Eq for Tuple15[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14]
    impl Eq for Tuple16[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15]
    impl Eq for BytesView
    impl Eq for StringView

    Hash

    pub(open) trait Hash {
    fn hash_combine(Self, Hasher) -> Unit
    fn hash(Self) -> Int = _
    }

    Trait for types that can be hashed

    The hash method should return a hash value for the type, which is used in hash tables and other data structures. The hash_combine method is used to combine the hash of the current value with another hash value, typically used to hash composite types.

    When two values are equal according to the Eq trait, they should produce the same hash value.

    The hash method does not need to be implemented if hash_combine is implemented, When implemented separately, hash does not need to produce a hash value that is consistent with hash_combine.
    impl Hash for Unit
    impl Hash for Bool
    impl Hash for Byte
    impl Hash for Char
    impl Hash for Int
    impl Hash for Int64
    impl Hash for UInt
    impl Hash for UInt16
    impl Hash for UInt64
    impl Hash for Double
    impl Hash for String
    impl Hash for Option[X]
    impl Hash for Result[T, E]
    impl Hash for FixedArray[T]
    impl Hash for ReadOnlyArray[T]
    impl Hash for Bytes
    impl Hash for Tuple2[A, B]
    impl Hash for Tuple3[A, B, C]
    impl Hash for Tuple4[A, B, C, D]
    impl Hash for Tuple5[A, B, C, D, E]
    impl Hash for Tuple6[A, B, C, D, E, F]
    impl Hash for Tuple7[A, B, C, D, E, F, G]
    impl Hash for BytesView
    impl Hash for StringView

    Logger

    pub(open) trait Logger {
    fn write_string(Self, String) -> Unit = _
    #deprecated("use `write_view` instead")
    fn write_substring(Self, String, Int, Int) -> Unit = _
    fn write_view(Self, StringView) -> Unit = _
    fn write_char(Self, Char) -> Unit = _
    fn write_string_interpolation(Self, &Show) -> Unit = _
    fn write(Self, &Show) -> Unit = _
    }

    Trait for append-only text sinks used by Show implementations.

    A logger receives formatted output without requiring callers to allocate a complete String first.

    Mod

    pub(open) trait Mod {
    fn mod(Self, Self) -> Self
    }

    types implementing this trait can use the % operator
    impl Mod for Byte
    impl Mod for Int
    impl Mod for Int64
    impl Mod for UInt
    impl Mod for UInt16
    impl Mod for UInt64
    impl Mod for Double

    Mul

    pub(open) trait Mul {
    fn mul(Self, Self) -> Self
    }

    types implementing this trait can use the * operator
    impl Mul for Byte
    impl Mul for Int
    impl Mul for Int64
    impl Mul for UInt
    impl Mul for UInt16
    impl Mul for UInt64
    impl Mul for Double

    Neg

    pub(open) trait Neg {
    fn neg(Self) -> Self
    }

    types implementing this trait can use the unary - operator
    impl Neg for Int
    impl Neg for Int64
    impl Neg for Double

    Shl

    pub(open) trait Shl {
    fn shl(Self, Int) -> Self
    }

    types implementing this trait can use the << operator
    impl Shl for Byte
    impl Shl for Int
    impl Shl for Int64
    impl Shl for UInt
    impl Shl for UInt16
    impl Shl for UInt64

    Show

    #must_implement_one(output, to_string)
    pub(open) trait Show {
    fn output(Self, &Logger) -> Unit = _
    fn to_string(Self) -> String = _
    }

    Trait for types that can be converted to String
    impl Show for Unit
    impl Show for Bool
    impl Show for Byte
    impl Show for Char
    impl Show for Int
    impl Show for Int64
    impl Show for UInt
    impl Show for UInt16
    impl Show for UInt64
    impl Show for Double
    impl Show for String
    impl Show for Option[X]
    impl Show for Result[T, E]
    impl Show for FixedArray[X]
    impl Show for ReadOnlyArray[T]
    impl Show for Bytes
    impl Show for Tuple2[A, B]
    impl Show for Tuple3[A, B, C]
    impl Show for Tuple4[A, B, C, D]
    impl Show for Tuple5[A, B, C, D, E]
    impl Show for Tuple6[A, B, C, D, E, F]
    impl Show for Tuple7[A, B, C, D, E, F, G]
    impl Show for Tuple8[T0, T1, T2, T3, T4, T5, T6, T7]
    impl Show for Tuple9[T0, T1, T2, T3, T4, T5, T6, T7, T8]
    impl Show for Tuple10[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9]
    impl Show for Tuple11[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]
    impl Show for Tuple12[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11]
    impl Show for Tuple13[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12]
    impl Show for Tuple14[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13]
    impl Show for Tuple15[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14]
    impl Show for Tuple16[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15]
    impl Show for BytesView
    impl Show for StringView

    Shr

    pub(open) trait Shr {
    fn shr(Self, Int) -> Self
    }

    types implementing this trait can use the >> operator
    impl Shr for Byte
    impl Shr for Int
    impl Shr for Int64
    impl Shr for UInt
    impl Shr for UInt16
    impl Shr for UInt64

    Sub

    pub(open) trait Sub {
    fn sub(Self, Self) -> Self
    }

    types implementing this trait can use the - operator
    impl Sub for Byte
    impl Sub for Int
    impl Sub for Int64
    impl Sub for UInt
    impl Sub for UInt16
    impl Sub for UInt64
    impl Sub for Double

    ToJson

    pub(open) trait ToJson {
    fn to_json(Self) -> Json
    }

    Trait for types that can be converted to Json
    impl ToJson for Unit
    impl ToJson for Bool
    impl ToJson for Byte
    impl ToJson for Char
    impl ToJson for Int
    impl ToJson for Int64
    impl ToJson for UInt
    impl ToJson for UInt16
    impl ToJson for UInt64
    impl ToJson for Double
    impl ToJson for String
    impl ToJson for Option[T]
    impl ToJson for Result[Ok, Err]
    impl ToJson for FixedArray[X]
    impl ToJson for ReadOnlyArray[T]
    impl ToJson for Bytes
    impl ToJson for Tuple2[A, B]
    impl ToJson for Tuple3[A, B, C]
    impl ToJson for Tuple4[A, B, C, D]
    impl ToJson for Tuple5[A, B, C, D, E]
    impl ToJson for Tuple6[A, B, C, D, E, F]
    impl ToJson for Tuple7[A, B, C, D, E, F, G]
    impl ToJson for Tuple8[A, B, C, D, E, F, G, H]
    impl ToJson for Tuple9[A, B, C, D, E, F, G, H, I]
    impl ToJson for Tuple10[A, B, C, D, E, F, G, H, I, J]
    impl ToJson for Tuple11[A, B, C, D, E, F, G, H, I, J, K]
    impl ToJson for Tuple12[A, B, C, D, E, F, G, H, I, J, K, L]
    impl ToJson for Tuple13[A, B, C, D, E, F, G, H, I, J, K, L, M]
    impl ToJson for Tuple14[A, B, C, D, E, F, G, H, I, J, K, L, M, N]
    impl ToJson for Tuple15[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O]
    impl ToJson for Tuple16[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P]
    impl ToJson for BytesView

    ToStringView

    pub trait ToStringView {
    fn to_string_view(Self) -> StringView
    }

    Trait for values that can be viewed as StringView.

    Types implementing this trait provide zero-copy access to string-like data.

    BenchError

    #deprecated("This type is deprecated.")
    pub(all) suberror BenchError {
    BenchError(String)
    }

    Failure

    pub(all) suberror Failure {
    Failure(String)
    } derive(Show, ToJson)

    Represents a generic test failure type used primarily in test assertions and validations.

    Since this is a type definition using suberror syntax, it creates an error type Failure that wraps a String value containing the failure message.

    Parameters:

    • message : A string describing the nature of the failure.

    Example:

    test {
    let err : Failure = Failure("Test assertion failed")
    match err {
    Failure(msg) => inspect(msg, content="Test assertion failed")
    }
    @json.json_inspect(err, content=["Failure", "Test assertion failed"])
    }

    Failure::to_json

    fn Failure::to_json(Failure) -> Json

    Failure::to_string

    fn Failure::to_string(self : Failure) -> String

    InspectError

    pub(all) suberror InspectError {
    InspectError(String)
    }

    Represents an error type used by the inspect function to indicate failures in value inspection. Contains a string message describing the nature of the inspection failure.

    Returns a type constructor that creates an error type from a string message.

    Example:

    test {
    let x : Int = 42
    inspect(x, content="42") // A mismatch would raise InspectError with a detailed message
    }

    SnapshotError

    pub(all) suberror SnapshotError {
    SnapshotError(String)
    }

    Represents an error that occurs during snapshot testing. Contains a string message describing the error.

    Used internally by the test driver to handle snapshot-related errors. Not intended for direct use by end users.

    Example:

    test {
    let err : SnapshotError = SnapshotError("failed to load snapshot")
    match err {
    SnapshotError(msg) => @test.assert_eq(msg, "failed to load snapshot")
    }
    }

    ArgsLoc

    pub(all) struct ArgsLoc(Array[SourceLoc?])

    Represents a type for storing argument locations in source code. It is an array of optional source locations, where each element corresponds to an argument's location in the source code. Used internally by the compiler for error reporting and debugging purposes.
    impl Show for ArgsLoc

    ArgsLoc::to_json

    fn ArgsLoc::to_json(self : ArgsLoc) -> String

    Converts an array of optional source locations to its JSON string representation. Each location in the array is either represented as a JSON object with filename, start_line, start_column, end_line and end_column fields if present, or "null" if absent.

    Parameters:

    • self : The array of optional source locations to be converted.

    Returns a JSON array string where each element is either a JSON object describing a source location or "null".

    ArgsLoc::to_string

    fn ArgsLoc::to_string(self : ArgsLoc) -> String

    Array

    type Array[T]

    An Array is a collection of values that supports random access and can grow in size.
    impl Add for Array[T]
    impl Compare for Array[T]
    impl Default for Array[T]
    impl Eq for Array[T]
    impl Hash for Array[T]
    impl Show for Array[X]
    impl ToJson for Array[X]

    Array::Array

    fn[T] Array::Array(capacity? : Int) -> Array[T]

    Creates a new empty array with an optional initial capacity.

    Parameters:

    • capacity : The initial capacity of the array. If 0 (default), creates an array with minimum capacity. Must be non-negative.

    Returns a new empty array of type Array[T] with the specified initial capacity.

    Example:

    test {
    let arr : Array[Int] = Array(capacity=10)
    inspect(arr.length(), content="0")
    inspect(arr.capacity(), content="10")
    let arr : Array[Int] = Array()
    inspect(arr.length(), content="0")
    }

    Array::add

    fn[T] Array::add(self : Array[T], other : Array[T]) -> Array[T]

    Array::all

    #alias(every)
    fn[T] Array::all(self : Array[T], f : (T) -> Bool raise?) -> Bool raise?

    Checks whether all elements satisfy the predicate.

    Example

    test {
    let arr = [1, 2, 3, 4, 5]
    assert_true(arr.all(x => x < 6))
    assert_false(arr.all(x => x < 5))
    }

    Array::any

    #alias(exists)
    fn[T] Array::any(self : Array[T], f : (T) -> Bool raise?) -> Bool raise?

    Checks whether any element satisfies the predicate.

    Example

    test {
    let arr = [1, 2, 3, 4, 5]
    assert_true(arr.any(x => x < 6))
    assert_false(arr.any(x => x < 1))
    }

    Array::append

    fn[T] Array::append(self : Array[T], other : ArrayView[T]) -> Unit

    Appends all elements from one array to the end of another array. The elements are added in-place, modifying the original array.

    Parameters:

    • self : The array to append to.
    • other : The array whose elements will be appended.

    Example:

    test {
    let v1 = [1, 2, 3]
    let v2 : ReadOnlyArray[Int] = [4, 5, 6]
    v1.append(v2)
    debug_inspect(v1, content="[1, 2, 3, 4, 5, 6]")
    let v1 = [1, 2, 3]
    let v2 : ReadOnlyArray[Int] = []
    v1.append(v2)
    debug_inspect(v1, content="[1, 2, 3]")
    }

    Array::at

    #alias("_[_]")
    fn[T] Array::at(self : Array[T], index : Int) -> T

    Retrieves an element from the array at the specified index.

    Parameters:

    • array : The array to get the element from.
    • index : The position in the array from which to retrieve the element.

    Returns the element at the specified index.

    Throws a panic if the index is negative or greater than or equal to the length of the array.

    Example:

    test {
    let arr : Array[Int] = [1, 2, 3]
    inspect(arr[1], content="2")
    }

    fn[T : Compare + Eq] Array::binary_search(self : Array[T], value : T) -> Result[Int, Int]

    Performs a binary search on a sorted array to find the index of a given element.

    Example

    test {
    let v = [3, 4, 5]
    let result = v.binary_search(3)
    @test.assert_eq(result, Ok(0)) // The element 3 is found at index 0
    }

    Arguments

    • self: The array in which to perform the search.
    • value: The element to search for in the array.

    Returns

    • Result[Int, Int]: If the element is found, an Ok variant is returned, containing the index of the matching element in the array. If there are multiple matches, the leftmost match will be returned. If the element is not found, an Err variant is returned, containing the index where the element could be inserted to maintain the sorted order.

    Notes

    • Ensure that the array is sorted in increasing order before calling this function.
    • If the array is not sorted, the returned result is undefined and should not be relied on.

    Array::binary_search_by

    fn[T] Array::binary_search_by(self : Array[T], cmp : (T) -> Int raise?) -> Result[Int, Int] raise?

    Performs a binary search on a sorted array using a custom comparison function. Returns the position of the matching element if found, or the position where the element could be inserted while maintaining the sorted order.

    Parameters:

    • array : The sorted array to search in.
    • comparator : A function that compares each element with the target value, returning:
    • A negative integer if the element is less than the target
    • Zero if the element equals the target
    • A positive integer if the element is greater than the target

    Returns a Result containing either:

    • Ok(index) if a matching element is found at position index
    • Err(index) if no match is found, where index is the position where the element could be inserted

    Example:

    test {
    let arr = [1, 3, 5, 7, 9]
    let find_3 = arr.binary_search_by(x => x.compare(3))
    debug_inspect(find_3, content="Ok(1)")
    let find_4 = arr.binary_search_by(x => x.compare(4))
    debug_inspect(find_4, content="Err(2)")
    }

    Notes:

    • Assumes the array is sorted according to the ordering implied by the comparison function
    • For multiple matches, returns the leftmost matching position
    • Returns an insertion point that maintains the sort order when no match is found

    Array::blit_to

    fn[A] Array::blit_to(self : Array[A], dst : Array[A], len? : Int, src_offset? : Int, dst_offset? : Int) -> Unit

    Copies elements from one array to another array, with support for growing the destination array if needed. The arrays may overlap, in which case the copy is performed in a way that preserves the data.

    Parameters:

    • self : The array to copy elements from.
    • dst : The array to copy elements to. Will be automatically grown if needed to accommodate the copied elements.
    • len : The number of elements to copy.
    • src_offset : Starting index in the source array. Defaults to 0.
    • dst_offset : Starting index in the destination array. Defaults to

    Example:

    test {
    let src = [1, 2, 3, 4, 5]
    let dst = [0, 0]
    src[:3].blit_to(dst, dst_offset=1)
    @debug.debug_inspect(dst, content="[0, 1, 2, 3]")
    }

    Panics if:

    • len is negative
    • src_offset is negative
    • dst_offset is negative
    • dst_offset exceeds the length of destination array
    • src_offset + len exceeds the length of source array

    Array::capacity

    fn[T] Array::capacity(self : Array[T]) -> Int

    Returns the total capacity of the array, which is the number of elements that the array can hold without requiring reallocation of its internal buffer.

    Parameters:

    • array : The array whose capacity is to be determined.

    Returns the current capacity of the array as an integer.

    NOTE: The capacity of an array may not be consistent across different backends and/or different versions of the MoonBit compiler/core.

    Array::chunk_by

    fn[T] Array::chunk_by(self : Array[T], pred : (T, T) -> Bool raise?) -> Array[ArrayView[T]] raise?

    Groups consecutive elements of the array into chunks where adjacent elements satisfy the given predicate function.

    Parameters:

    • array : The array to be chunked.
    • predicate : A function that takes two adjacent elements and returns true if they should be in the same chunk, false otherwise.

    Returns an array of views, where each view is a chunk of consecutive elements that satisfy the predicate with their adjacent elements.

    Example:

    test {
    let v = [1, 1, 2, 3, 2, 3, 2, 3, 4]
    let chunks = v.chunk_by((x, y) => x <= y)
    debug_inspect(
    chunks,
    content=(
    #|[
    #| <ArrayView: [1, 1, 2, 3]>,
    #| <ArrayView: [2, 3]>,
    #| <ArrayView: [2, 3, 4]>,
    #|]
    ),
    )
    let v : Array[Int] = []
    debug_inspect(v.chunk_by((x, y) => x <= y), content="[]")
    }

    Array::chunks

    fn[T] Array::chunks(self : Array[T], size : Int) -> Array[ArrayView[T]]

    Divides an array into chunks (views) of the specified size.

    Parameters:

    • array : The array to be divided into chunks.
    • size : The size of each chunk. Must be a positive integer, otherwise it will panic.

    Returns an array of views, where each view is a chunk containing consecutive elements of the original array. If the length of the original array is not divisible by the chunk size, the last chunk will contain fewer elements.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let chunks = arr.chunks(2)
    debug_inspect(
    chunks,
    content=(
    #|[<ArrayView: [1, 2]>, <ArrayView: [3, 4]>, <ArrayView: [5]>]
    ),
    )
    let arr : Array[Int] = []
    debug_inspect(arr.chunks(3), content="[]")
    }

    Array::clear

    fn[T] Array::clear(self : Array[T]) -> Unit

    Clears the array, removing all values.

    This method has no effect on the allocated capacity of the array, only setting the length to 0.

    Emptying an array is a removal like any other: the buffer keeps referring to the elements that were in it, and they are released once later pushes reuse those slots, the buffer grows, or the array is dropped. Call Array::release_unused to overwrite them at once, or Array::shrink_to_fit to hand the buffer back entirely. On the JavaScript backend the removed elements are released right away and Array::release_unused is a no-op.

    Example

    test {
    let v = [3, 4, 5]
    v.clear()
    @test.assert_eq(v.length(), 0)
    }

    Array::compare

    fn[T : Compare + Eq] Array::compare(self : Array[T], other : Array[T]) -> Int

    Array::contains

    fn[T : Eq] Array::contains(self : Array[T], value : T) -> Bool

    Checks whether the array contains an element equal to the given value.

    Parameters:

    • array : The array to search in.
    • value : The value to search for.

    Returns true if the array contains an element equal to the given value, false otherwise.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    inspect(arr.contains(3), content="true")
    inspect(arr.contains(6), content="false")
    let arr : Array[Int] = []
    inspect(arr.contains(1), content="false")
    }

    Array::copy

    #alias(clone, deprecated="`clone` is deprecated, use `copy` instead")
    fn[T] Array::copy(self : Array[T]) -> Array[T]

    Creates and returns a new array with a copy of all elements from the input array.

    Parameters:

    • array : The array to be copied.

    Returns a new array containing all elements from the original array.

    Example:

    test {
    let original = [1, 2, 3]
    let copied = original.copy()
    @debug.debug_inspect(copied, content="[1, 2, 3]")
    inspect(physical_equal(original, copied), content="false")
    }

    Array::count

    fn[T : Eq] Array::count(self : Array[T], value : T) -> Int

    Counts how many elements in the array are equal to value.

    Example

    test {
    let arr = [1, 2, 1, 3, 1]
    inspect(arr.count(1), content="3")
    inspect(arr.count(4), content="0")
    }

    Array::count_if

    fn[T] Array::count_if(self : Array[T], f : (T) -> Bool raise?) -> Int raise?

    Counts how many elements in the array satisfy the predicate.

    Example

    test {
    let arr = [1, 2, 3, 4, 5]
    inspect(arr.count_if(x => x % 2 == 0), content="2")
    }

    Array::dedup

    fn[T : Eq] Array::dedup(self : Array[T]) -> Unit

    Removes consecutive duplicate elements from an array in-place, using equality comparison. The first occurrence of each element is retained while subsequent equal elements are removed.

    Parameters:

    • array : The array to remove duplicates from. Must contain elements that implement the Eq trait for equality comparison.

    Example:

    test {
    let arr = [1, 2, 2, 3, 3, 3, 2]
    arr.dedup()
    debug_inspect(arr, content="[1, 2, 3, 2]")
    let arr = [1, 2, 2, 2, 3, 3]
    arr.dedup()
    debug_inspect(arr, content="[1, 2, 3]")
    let arr : Array[Int] = []
    arr.dedup()
    debug_inspect(arr, content="[]")
    }

    Note: For best results when removing all duplicates regardless of position, sort the array before calling this function. When used on an unsorted array, this function only removes consecutive duplicates.

    Array::drain

    fn[T] Array::drain(self : Array[T], begin : Int, end : Int) -> Array[T]

    Removes the specified range from the array and returns it.

    This functions returns an array range from begin to end [begin, end)

    This function will panic if the index is out of bounds.

    Example

    test {
    let v = [3, 4, 5]
    let vv = v.drain(1, 2) // vv = [4], v = [3, 5]
    @test.assert_eq(vv, [4])
    @test.assert_eq(v, [3, 5])
    }

    The end - begin slots vacated at the end of the array are not cleared: each keeps whatever it held before the survivors were shifted down, so a drained element or a duplicate reference to a survivor stays reachable there until the slot is reused, the buffer grows, or the array is dropped. Call Array::release_unused to overwrite them at once, or Array::shrink_to_fit to move the survivors into an exact-size buffer.

    Array::each

    fn[T] Array::each(self : Array[T], f : (T) -> Unit raise?) -> Unit raise?

    Iterates through each element of the array in order, applying the given function to each element.

    Parameters:

    • array : The array to iterate over.
    • function : A function that takes a single element of type T as input and returns Unit. This function is applied to each element of the array in order.

    Example:

    test {
    let arr = [1, 2, 3]
    let mut sum = 0
    arr.each(x => sum x)
    inspect(sum, content="6")
    }
    This method uses the array iterator. Structural mutations during traversal are unsupported: appended elements are not visited, and shrinking the array with operations such as remove, truncate, clear, or drain may cause later iterator steps to fail.

    Array::eachi

    fn[T] Array::eachi(self : Array[T], f : (Int, T) -> Unit raise?) -> Unit raise?

    Iterates over the elements of the array with index.

    Example

    test {
    let v = [3, 4, 5]
    let mut sum = 0
    v.eachi((i, x) => sum x + i)
    inspect(sum, content="15")
    }

    Array::ends_with

    fn[T : Eq] Array::ends_with(self : Array[T], suffix : ArrayView[T]) -> Bool

    Tests if an array ends with the given suffix.

    Parameters:

    • self : The array to check.
    • suffix : The array to test against.

    Returns true if the array ends with the given suffix, false otherwise.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    inspect(arr.ends_with([4, 5]), content="true")
    inspect(arr.ends_with([3, 4]), content="false")
    inspect(arr.ends_with([]), content="true")
    let arr : Array[Int] = []
    inspect(arr.ends_with([]), content="true")
    inspect(arr.ends_with([1]), content="false")
    }

    Array::equal

    fn[T : Eq] Array::equal(self : Array[T], other : Array[T]) -> Bool

    Array::extract_if

    fn[T] Array::extract_if(self : Array[T], f : (T) -> Bool raise?) -> Array[T] raise?

    Extracts elements from an array that satisfy a given predicate function. The extracted elements are removed from the original array and returned as a new array. The relative order of the extracted elements is preserved.

    Parameters:

    • array : The array to extract elements from.
    • predicate : A function that takes an element and returns true if the element should be extracted, false otherwise.

    Returns a new array containing all elements that satisfy the predicate function, in the order they appeared in the original array.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let extracted = arr.extract_if(x => x % 2 == 0)
    debug_inspect(extracted, content="[2, 4]")
    debug_inspect(arr, content="[1, 3, 5]")
    }

    Array::fill

    fn[A] Array::fill(self : Array[A], value : A, start? : Int, end? : Int) -> Unit

    Fills an Array with a specified value.

    This method fills all or part of an Array with the given value.

    Parameters

    • value: The value to fill the array with
    • start: The starting index (inclusive, default: 0)
    • end: The ending index (exclusive, optional)

    If end is not provided, fills from start to the end of the array. If start equals end, no elements are modified.

    Panics

    • Panics if start is negative or greater than or equal to the array length
    • Panics if end is provided and is less than start or greater than array length
    • Does nothing if the array is empty

    Example

    test {
    // Fill entire array
    let arr = [1, 2, 3, 4, 5]
    arr.fill(0)
    @debug.debug_inspect(arr, content="[0, 0, 0, 0, 0]")

    // Fill from index 1 to 3 (exclusive)
    let arr2 = [1, 2, 3, 4, 5]
    arr2.fill(99, start=1, end=3)
    @debug.debug_inspect(arr2, content="[1, 99, 99, 4, 5]")

    // Fill from index 2 to end
    let arr3 = ["a", "b", "c", "d"]
    arr3.fill("x", start=2)
    @debug.debug_inspect(
    arr3,
    content=(
    #|["a", "b", "x", "x"]
    ),
    )
    }

    Array::filter

    fn[T] Array::filter(self : Array[T], f : (T) -> Bool raise?) -> Array[T] raise?

    Creates a new array containing all elements from the input array that satisfy the given predicate function.

    Parameters:

    • array : The array to filter.
    • predicate : A function that takes an element and returns a boolean indicating whether the element should be included in the result.

    Returns a new array containing only the elements for which the predicate function returns true. The relative order of the elements is preserved.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let evens = arr.filter(x => x % 2 == 0)
    debug_inspect(evens, content="[2, 4]")
    }

    Array::filter_map

    fn[A, B] Array::filter_map(self : Array[A], f : (A) -> B? raise?) -> Array[B] raise?

    Applies a function to each element of the array and collects the results that are Some, discarding the elements for which the function returns None.

    Arguments

    • self - The array to filter and map.
    • f - The function applied to each element, returning Some(value) to keep the mapped value, or None to drop the element.

    Returns

    A new array containing the unwrapped Some results, in the order the corresponding elements appeared in the original array.

    Array::flatten

    fn[T] Array::flatten(self : Array[Array[T]]) -> Array[T]

    Flattens an array of arrays into an array.

    Example:

    test {
    let v = [[3, 4], [5, 6]].flatten()
    @test.assert_eq(v, [3, 4, 5, 6])
    }

    Array::fold

    #alias(fold_left, deprecated="`fold_left` is deprecated, use `fold` instead")
    fn[A, B] Array::fold(self : Array[A], init~ : B, f : (B, A) -> B raise?) -> B raise?

    Fold out values from an array according to certain rules. This method traverses the array through self.iter(), so the traversal bounds are fixed when folding starts.

    Structural mutations to self inside f are unsupported. Appended elements are not visited, and shrinking the array with operations such as remove, truncate, clear, or drain may cause later fold steps to fail.

    Example:

    test {
    let sum = [1, 2, 3, 4, 5].fold(init=0, (sum, elem) => sum + elem)
    @test.assert_eq(sum, 15)
    }

    Array::foldi

    #alias(fold_lefti, deprecated="`fold_lefti` is deprecated, use `foldi` instead")
    fn[A, B] Array::foldi(self : Array[A], init~ : B, f : (Int, B, A) -> B raise?) -> B raise?

    Fold out values from an array according to certain rules with index.

    Example:

    test {
    let sum = [1, 2, 3, 4, 5].foldi(init=0, (index, sum, _elem) => sum + index)
    @test.assert_eq(sum, 10)
    }

    Array::from_fixed_array

    fn[T] Array::from_fixed_array(arr : FixedArray[T]) -> Array[T]

    Creates a new dynamic array from a fixed-size array.

    Parameters:

    • arr : The fixed-size array to convert. The elements of this array will be copied to the new array.

    Returns a new dynamic array containing all elements from the input fixed-size array.

    Example:

    test {
    let fixed = FixedArray::make(3, 42)
    let dynamic = Array::from_fixed_array(fixed)
    debug_inspect(dynamic, content="[42, 42, 42]")
    }

    Array::from_iter

    #alias(from_iterator, deprecated="`from_iterator` is deprecated, use `from_iter` instead")
    fn[T] Array::from_iter(iter : Iter[T]) -> Array[T]

    Creates a new array containing all elements from an iterator.

    Parameters:

    • iterator : An iterator containing elements of type T.

    Returns a new array containing all elements from the iterator in the same order.

    Example:

    test {
    let iter = 42
    let arr = Array::from_iter(iter)
    debug_inspect(arr, content="[42]")
    }

    Array::get

    fn[T] Array::get(self : Array[T], index : Int) -> T?

    Retrieves the element at the specified index from the array.

    Parameters:

    • self : The array to get the element from.
    • index : The position in the array from which to retrieve the element.

    Returns Some(element) if the index is within bounds, or None if the index is out of bounds.

    Example:

    test {
    let arr = [1, 2, 3]
    debug_inspect(arr.get(-1), content="None")
    debug_inspect(arr.get(0), content="Some(1)")
    debug_inspect(arr.get(3), content="None")
    }

    Array::get_view

    fn[T] Array::get_view(self : Array[T], start? : Int, end? : Int) -> ArrayView[T]?

    Creates a view of a portion of the array, returning None when indices are invalid.

    Parameters:

    • array : The array to create a view from.
    • start : The starting index of the view (inclusive). Defaults to 0.
    • end : The ending index of the view (exclusive). If not provided, defaults to the length of the array.

    Returns Some(ArrayView) that provides a window into the specified portion of the array, or None when the indices are invalid.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let start = 1
    let end = 4
    debug_inspect(
    arr.get_view(start~, end~),
    content=(
    #|Some(<ArrayView: [2, 3, 4]>)
    ),
    )
    let start = 3
    let end = 10
    debug_inspect(arr.get_view(start~, end~), content="None")
    }

    Array::hash

    fn[T : Hash] Array::hash(self : Array[T]) -> Int

    Array::insert

    fn[T] Array::insert(self : Array[T], index : Int, value : T) -> Unit

    Inserts an element at a given index within the array. This function will panic if the index is out of bounds.

    Example

    test {
    let a = [1, 2, 3]
    a.insert(1, 4)
    @debug.debug_inspect(a, content="[1, 4, 2, 3]")
    let b = [1, 2, 3]
    b.insert(0, 5)
    @debug.debug_inspect(b, content="[5, 1, 2, 3]")
    let c = [1, 2, 3]
    c.insert(3, 6)
    @debug.debug_inspect(c, content="[1, 2, 3, 6]")
    }

    Array::is_empty

    fn[T] Array::is_empty(self : Array[T]) -> Bool

    Tests whether the array contains no elements.

    Parameters:

    • array : The array to check.

    Returns true if the array has no elements, false otherwise.

    Example:

    test {
    let empty : Array[Int] = []
    inspect(empty.is_empty(), content="true")
    let non_empty = [1, 2, 3]
    inspect(non_empty.is_empty(), content="false")
    }

    Array::is_sorted

    fn[T : Compare + Eq] Array::is_sorted(self : Array[T]) -> Bool

    Tests whether the array is sorted in ascending order.

    Parameters:

    • self : The array to be tested.
    • T : The type of elements in the array. Must implement the Compare trait.

    Returns a boolean value indicating whether the array is sorted in ascending order:

    • true if the array is empty, contains only one element, or all elements are in ascending order.
    • false if any element is greater than the element that follows it.

    Example:

    test {
    let ascending = [1, 2, 3, 4, 5]
    let descending = [5, 4, 3, 2, 1]
    let unsorted = [1, 3, 2, 4, 5]
    inspect(ascending.is_sorted(), content="true")
    inspect(descending.is_sorted(), content="false")
    inspect(unsorted.is_sorted(), content="false")
    }

    Array::iter

    #alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
    fn[T] Array::iter(self : Array[T]) -> Iter[T]

    Creates an iterator over the elements of the array.

    Parameters:

    • array : The array to create an iterator from.

    Returns an iterator that yields each element of the array in order. This iterator is created from self[:], so the traversal bounds are fixed when iteration starts.

    Structural mutations after the iterator is created are unsupported. Appended elements are not visited, and shrinking the array with operations such as remove, truncate, clear, or drain may cause later iterator steps to fail. The same caveat applies to rev_iter(), iter2(), and helpers built on top of them such as each(), eachi(), and fold().

    Example:

    test {
    let arr = [1, 2, 3]
    let mut sum = 0
    arr.iter().each(x => sum x)
    inspect(sum, content="6")
    }

    Array::iter2

    #alias(iterator2, deprecated="`iterator2` is deprecated, use `iter2` instead")
    fn[A] Array::iter2(self : Array[A]) -> Iter2[Int, A]

    Returns an iterator that provides both indices and values of the array in order.

    Parameters:

    • self : The array to iterate over.

    Returns an iterator that yields tuples of index and value pairs, where indices start from 0.

    Example:

    test {
    let arr = [10, 20, 30]
    let mut sum = 0
    arr.iter2().each((i, x) => sum i + x)
    inspect(sum, content="63") // (0 + 10) + (1 + 20) + (2 + 30) = 63
    }

    Array::join

    fn[A : ToStringView] Array::join(self : Array[A], separator : StringView) -> String

    Join an array of strings using the provided separator.

    Parameters:
    • separator : The string inserted between each element.

    Returns a single concatenated String.

    Example:

    test {
    let s = "hello world"
    inspect(s.split(" ").to_array().join(":"), content="hello:world")
    }

    Array::last

    fn[A] Array::last(self : Array[A]) -> A?

    Returns the last element of the array, or None if the array is empty.

    Parameters:

    • array : The array to get the last element from.

    Returns an optional value containing the last element of the array. The result is None if the array is empty, or Some(x) where x is the last element of the array.

    Example:

    test {
    let arr = [1, 2, 3]
    debug_inspect(arr.last(), content="Some(3)")
    let empty : Array[Int] = []
    debug_inspect(empty.last(), content="None")
    }

    Array::length

    fn[T] Array::length(self : Array[T]) -> Int

    Returns the number of elements in the array.

    Parameters:

    • array : The array whose length is to be determined.

    Returns the number of elements in the array as an integer.

    Example:

    test {
    let arr : Array[Int] = [1, 2, 3]
    inspect(arr.length(), content="3")
    let empty : Array[Int] = []
    inspect(empty.length(), content="0")
    }

    Array::lexical_compare

    fn[T : Compare + Eq] Array::lexical_compare(self : Array[T], other : Array[T]) -> Int

    Performs a lexicographical comparison of two arrays.

    This method compares the arrays element by element until a difference is found or one array is exhausted. Unlike the Compare trait implementation which uses shortlex order (shorter arrays come first), this method compares based purely on element values until a difference is found.

    Returns

    • A negative integer if self is lexicographically less than other
    • Zero if self is lexicographically equal to other
    • A positive integer if self is lexicographically greater than other

    Example

    test {
    inspect([1, 2].lexical_compare([1, 2, 3]), content="-1")
    inspect([1, 2, 3].lexical_compare([1, 2]), content="1")
    inspect([1, 2, 3].lexical_compare([1, 2, 3]), content="0")
    inspect([1, 2, 3].lexical_compare([1, 2, 4]), content="-1")
    }

    Array::make

    fn[T] Array::make(len : Int, elem : T) -> Array[T]

    Creates a new array with a specified length and initializes all elements with the given value.

    Parameters:

    • length : The length of the array to create. Must be a non-negative integer.
    • initial_value : The value used to initialize all elements in the array.

    Returns a new array of type Array[T] with length elements, where each element is initialized to initial_value.

    Throws an error if length is negative.

    Example:

    test {
    let arr = Array::make(3, 42)
    debug_inspect(arr, content="[42, 42, 42]")
    }

    WARNING: A common pitfall is creating with the same initial value, for example:
    test {
    let two_dimension_array = Array::make(10, Array::make(10, 0))
    two_dimension_array[0][5] = 10
    @test.assert_eq(two_dimension_array[5][5], 10)
    }
    This is because all the cells reference to the same object (the Array[Int] in this case). One should use makei() instead which creates an object for each index.

    Array::makei

    fn[T] Array::makei(length : Int, f : (Int) -> T raise?) -> Array[T] raise?

    Creates a new array of the specified length, where each element is initialized using an index-based initialization function.

    Parameters:

    • length : The length of the new array. If length is less than or equal to 0, returns an empty array.
    • initializer : A function that takes an index (starting from 0) and returns a value of type T. This function is called for each index to initialize the corresponding element.

    Returns a new array of type Array[T] with the specified length, where each element is initialized using the provided function.

    Example:

    test {
    let arr = Array::makei(3, i => i * 2)
    debug_inspect(arr, content="[0, 2, 4]")
    }

    Array::map

    fn[T, U] Array::map(self : Array[T], f : (T) -> U raise?) -> Array[U] raise?

    Maps a function over the elements of the array.

    Example

    test {
    let v = [3, 4, 5]
    let v2 = v.map(x => x + 1)
    @test.assert_eq(v2, [4, 5, 6])
    }

    Array::map_in_place

    #alias(map_inplace, deprecated="`map_inplace` is deprecated, use `map_in_place` instead")
    fn[T] Array::map_in_place(self : Array[T], f : (T) -> T raise?) -> Unit raise?

    Maps a function over the elements of the array in place.

    Example

    test {
    let v = [3, 4, 5]
    v.map_in_place(x => x + 1)
    @test.assert_eq(v, [4, 5, 6])
    }

    Array::mapi

    fn[T, U] Array::mapi(self : Array[T], f : (Int, T) -> U raise?) -> Array[U] raise?

    Maps a function over the elements of the array with index.

    Example

    test {
    let v = [3, 4, 5]
    let v2 = v.mapi((i, x) => x + i)
    @test.assert_eq(v2, [3, 5, 7])
    }

    Array::mapi_in_place

    #alias(mapi_inplace, deprecated="`mapi_inplace` is deprecated, use `mapi_in_place` instead")
    fn[T] Array::mapi_in_place(self : Array[T], f : (Int, T) -> T raise?) -> Unit raise?

    Maps a function over the elements of the array with index in place.

    Example

    test {
    let v = [3, 4, 5]
    v.mapi_in_place((i, x) => x + i)
    @test.assert_eq(v, [3, 5, 7])
    }

    Array::mut_view

    fn[T] Array::mut_view(self : Array[T], start? : Int, end? : Int) -> MutArrayView[T]

    Creates a mutable view of a portion of the array. The view provides read-write access to the underlying array without copying the elements.

    Parameters:

    • array : The array to create a view from.
    • start : The starting index of the view (inclusive). Defaults to 0.
    • end : The ending index of the view (exclusive). If not provided, defaults to the length of the array.

    Returns a MutArrayView that provides a window into the specified portion of the array.

    Throws a panic if the indices are invalid (i.e., start is negative, end is greater than the array length, or start is greater than end).

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr.mut_view(start=1, end=4) // Create a view of elements at indices 1, 2, and 3
    inspect(view[0], content="2") // First element of view is arr[1]
    inspect(view.length(), content="3") // View contains 3 elements
    }

    Array::new

    #deprecated("Use `Array(capacity=...)` instead")
    fn[T] Array::new(capacity? : Int) -> Array[T]

    Creates a new empty array with an optional initial capacity.

    Deprecated: use Array(capacity=...) instead.

    Array::pop

    fn[T] Array::pop(self : Array[T]) -> T?

    Removes the last element from an array and returns it, or None if it is empty.

    The vacated slot goes on referring to the returned element, so an ArrayView created beforehand keeps observing that element, and it is released only once a later push reuses the slot, the buffer grows, or the buffer is dropped. Call Array::release_unused to release it at once.

    Example

    test {
    let v = [1, 2, 3]
    @test.assert_eq(v.pop(), Some(3))
    @test.assert_eq(v, [1, 2])
    }

    Array::push

    fn[T] Array::push(self : Array[T], value : T) -> Unit

    Adds an element to the end of the array.

    If the array is at capacity, it will be reallocated.

    Example

    test {
    let v = []
    v.push(3)
    }

    Array::push_iter

    fn[T] Array::push_iter(self : Array[T], iter : Iter[T]) -> Unit

    Adds all elements from an iterator to the end of the array.

    This function iterates over each element in the provided iterator and adds them to the array using the push method.

    Example

    test {
    let u = [1, 2, 3]
    let v = [4, 5, 6]
    u.push_iter(v.iter())
    @test.assert_eq(u, [1, 2, 3, 4, 5, 6])
    }

    Array::release_unused

    fn[T] Array::release_unused(self : Array[T], placeholder~ : T) -> Unit

    Overwrites the array's unused capacity -- every slot from length() up to capacity() -- with placeholder, releasing whatever those slots held.

    Shrinking an array never clears the slots it vacates, so whatever they held -- a removed element, or a duplicate reference to a survivor that was shifted over it -- stays reachable from the buffer and unreleased until later pushes reuse those slots, the buffer grows, or the array is dropped. This releases them on demand without reallocating, which is what Array::pop, Array::remove, Array::retain and the other operations that take no placeholder leave outstanding. Array::shrink_to_fit releases them too, but by allocating an exact-size buffer and copying every survivor into it; this costs one pass over the unused region and no allocation.

    An ArrayView created before the call observes placeholder in that region afterwards, in place of whatever it held.

    This only matters for element types holding references -- for types such as Int there is nothing to release and the call merely costs a pass over the buffer.

    Example:

    test {
    let arr = ["a", "b", "c"]
    let _ = arr.pop()
    arr.release_unused(placeholder="")
    debug_inspect(arr, content="[\"a\", \"b\"]")
    }

    Array::remove

    fn[T] Array::remove(self : Array[T], index : Int) -> T

    Removes and returns the element at position index within the array, shifting all elements after it to the left.

    This function will panic if the index is out of bounds.

    Example

    test {
    let v = [3, 4, 5]
    @test.assert_eq(v.remove(1), 4)
    @test.assert_eq(v, [3, 5])
    }

    Array::repeat

    fn[T] Array::repeat(self : Array[T], times : Int) -> Array[T]

    Create an array by repeating self times times.

    Aborts if times is negative. When times is 0, returns an empty array.

    Example:

    test {
    let v = [3, 4].repeat(2)
    @test.assert_eq(v, [3, 4, 3, 4])
    }

    Array::reserve_capacity

    fn[T] Array::reserve_capacity(self : Array[T], capacity : Int) -> Unit

    Reserves capacity to ensure that it can hold at least the number of elements specified by the capacity argument.

    Example

    test {
    let v = [1]
    v.reserve_capacity(10)
    @test.assert_eq(v.capacity(), 10)
    }

    Array::resize

    fn[T] Array::resize(self : Array[T], new_len : Int, f : T) -> Unit

    Resizes an array to a specified length, either by truncating if the new length is smaller, or by appending copies of a default value if the new length is larger.

    Parameters:

    • array : The array to be resized.
    • new_length : The desired length of the array after resizing.
    • default_value : The value to append when extending the array.

    Throws a panic if new_length is negative.

    Examples:

    test {
    let arr = [1, 2, 3, 4, 5]
    arr.resize(3, 0)
    debug_inspect(arr, content="[1, 2, 3]")
    let arr = [1, 2, 3]
    arr.resize(5, 0)
    debug_inspect(arr, content="[1, 2, 3, 0, 0]")
    }

    Array::retain

    fn[T] Array::retain(self : Array[T], f : (T) -> Bool raise?) -> Unit raise?

    Removes all elements from the array that do not satisfy the predicate function, modifying the array in place. The order of remaining elements is preserved.

    Parameters:

    • array : The array to be filtered.
    • predicate : A function that takes an element and returns true if the element should be kept, false if it should be removed.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    arr.retain(x => x % 2 == 0)
    debug_inspect(arr, content="[2, 4]")
    let arr = [1, 2, 3]
    arr.retain(x => x > 10)
    debug_inspect(arr, content="[]")
    let arr = [1, 2, 3]
    arr.retain(_ => true)
    debug_inspect(arr, content="[1, 2, 3]")
    }

    Array::retain_map

    fn[A] Array::retain_map(self : Array[A], f : (A) -> A? raise?) -> Unit raise?

    In-place filter and map for Array

    Example

    test {
    let arr = [1, 2, 3, 4, 5]
    arr.retain_map(fn(x) { if x % 2 == 0 { Some(x * 2) } else { None } })
    debug_inspect(arr, content="[4, 8]")
    }

    Array::rev

    fn[T] Array::rev(self : Array[T]) -> Array[T]

    Creates a new array with elements in reversed order.

    Parameters:

    • self : The array to be reversed.

    Returns a new array containing the same elements as the input array but in reverse order. The original array remains unchanged.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    debug_inspect(arr.rev(), content="[5, 4, 3, 2, 1]")
    debug_inspect(arr, content="[1, 2, 3, 4, 5]") // original array unchanged
    }

    Array::rev_each

    fn[T] Array::rev_each(self : Array[T], f : (T) -> Unit raise?) -> Unit raise?

    Iterates over the elements of the array in reverse order, applying the given function to each element.

    Parameters:

    • array : The array to iterate over.
    • f : A function that takes an element of type T and returns Unit. This function is applied to each element of the array in reverse order.

    Example:

    test {
    let v = [3, 4, 5]
    let mut sum = 0
    v.rev_each(x => sum = sum - x)
    @json.json_inspect(sum, content=-12)
    }

    Array::rev_eachi

    fn[T] Array::rev_eachi(self : Array[T], f : (Int, T) -> Unit raise?) -> Unit raise?

    Iterates over the elements of the array with index in reversed order.

    Example

    test {
    let v = [3, 4, 5]
    let mut sum = 0
    v.rev_eachi((i, x) => sum x + i)
    @test.assert_eq(sum, 15)
    }

    Array::rev_fold

    #alias(fold_right, deprecated="`fold_right` is deprecated, use `rev_fold` instead")
    fn[A, B] Array::rev_fold(self : Array[A], init~ : B, f : (B, A) -> B raise?) -> B raise?

    Fold out values from an array according to certain rules in reversed turn.

    Example:

    test {
    let sum = [1, 2, 3, 4, 5].rev_fold(init=0, (sum, elem) => sum + elem)
    @test.assert_eq(sum, 15)
    }

    Array::rev_foldi

    #alias(fold_righti, deprecated="`fold_righti` is deprecated, use `rev_foldi` instead")
    fn[A, B] Array::rev_foldi(self : Array[A], init~ : B, f : (Int, B, A) -> B raise?) -> B raise?

    Fold out values from an array according to certain rules in reversed turn with index.

    Example:

    test {
    let sum = [1, 2, 3, 4, 5].rev_foldi(init=0, (index, sum, _elem) => sum + index)
    @test.assert_eq(sum, 10)
    }

    Array::rev_in_place

    #alias(rev_inplace, deprecated="`rev_inplace` is deprecated, use `rev_in_place` instead")
    fn[T] Array::rev_in_place(self : Array[T]) -> Unit

    Reverses the order of elements in an array in place, modifying the original array.

    Parameters:

    • self : The array to be reversed.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    arr.rev_in_place()
    debug_inspect(arr, content="[5, 4, 3, 2, 1]")
    let arr : Array[Int] = []
    arr.rev_in_place()
    debug_inspect(arr, content="[]")
    }

    Array::rev_iter

    #alias(rev_iterator, deprecated="`rev_iterator` is deprecated, use `rev_iter` instead")
    fn[T] Array::rev_iter(self : Array[T]) -> Iter[T]

    Returns an iterator that yields elements from the array in reverse order, from the last element to the first.

    Parameters:

    • array : The array to iterate over in reverse order.

    Returns an iterator that yields each element of the array, starting from the last element and moving towards the first.

    Example:

    test {
    let arr = [1, 2, 3]
    let result = []
    arr.rev_iter().each(x => result.push(x))
    debug_inspect(result, content="[3, 2, 1]")
    }

    Array::search

    fn[T : Eq] Array::search(self : Array[T], value : T) -> Int?

    Searches for the first occurrence of a value in the array and returns its index.

    Parameters:

    • self : The array to search in.
    • value : The value to search for.

    Returns an Option containing the index of the first occurrence of value if found, or None if the value is not present in the array.

    Example:

    test {
    let arr = [1, 2, 3, 2, 4]
    debug_inspect(arr.search(2), content="Some(1)") // first occurrence
    debug_inspect(arr.search(5), content="None") // not found
    }

    Array::search_by

    #alias(find_index, deprecated="`find_index` is deprecated, use `search_by` instead")
    fn[T] Array::search_by(self : Array[T], f : (T) -> Bool raise?) -> Int? raise?

    Search the index of the first element that satisfies the predicate.

    Example

    test {
    let v = [1, 2, 3, 4, 5]
    match v.search_by(x => x == 3) {
    Some(index) => @test.assert_eq(index, 2) // 2
    None => println("Not found")
    }
    }

    Array::set

    #alias("_[_]=_")
    fn[T] Array::set(self : Array[T], index : Int, value : T) -> Unit

    Sets the element at the specified index in the array to a new value. The original value at that index is overwritten.

    Parameters:

    • array : The array to modify.
    • index : The position in the array where the value will be set.
    • value : The new value to assign at the specified index.

    Throws an error if index is negative or greater than or equal to the length of the array.

    Example:

    test {
    let arr = [1, 2, 3]
    arr[1] = 42
    debug_inspect(arr, content="[1, 42, 3]")
    }

    Array::shrink_to_fit

    fn[T] Array::shrink_to_fit(self : Array[T]) -> Unit

    Shrinks the capacity of the array as much as possible.

    Example

    test {
    let v = Array(capacity=10)
    v.push(1)
    v.push(2)
    v.push(3)
    v.shrink_to_fit()
    @test.assert_eq(v.capacity(), 3)
    }

    The survivors are copied into the new buffer and the old one is released with them, so this also releases whatever earlier removals left in the unused capacity. It pays an allocation plus a copy of every survivor to do so; Array::release_unused releases the same elements in one pass over the unused region and no allocation, at the cost of leaving the capacity alone.

    Array::shuffle

    fn[T] Array::shuffle(self : Array[T], rand~ : (Int) -> Int) -> Array[T]

    Shuffle the array using Knuth shuffle

    To use this function, you need to provide a rand function, which takes an integer as it upper bound and returns an integer. rand n is expected to returns a uniformly distribution integer between 0 and n - 1

    Example

    let arr = [1, 2, 3, 4, 5]

    fn rand(upper : Int) -> Int {
    let rng = @random.Rand::new()
    rng.int(limit=upper)
    }

    let _shuffled = Array::shuffle(arr, rand~)

    Array::shuffle_in_place

    fn[T] Array::shuffle_in_place(self : Array[T], rand~ : (Int) -> Int) -> Unit

    Shuffle the array using Knuth shuffle

    To use this function, you need to provide a rand function, which takes an integer as it upper bound and returns an integer. rand n is expected to returns a uniformly distribution integer between 0 and n - 1

    Example

    test {
    let arr = [1, 2, 3, 4, 5]
    fn rand(upper : Int) -> Int {
    let rng = @random.Rand::new()
    rng.int(limit=upper)
    }

    Array::shuffle_in_place(arr, rand~)
    }

    Array::sort

    fn[T : Compare + Eq] Array::sort(self : Array[T]) -> Unit

    Sorts the array in place.

    It's an in-place, unstable sort(it will reorder equal elements). The time complexity is O(n log n) in the worst case.

    Example

    test {
    let arr = [5, 4, 3, 2, 1]
    arr.sort()
    @test.assert_eq(arr, [1, 2, 3, 4, 5])
    }

    Array::sort_by

    fn[T] Array::sort_by(self : Array[T], cmp : (T, T) -> Int) -> Unit

    Sorts the array with a custom comparison function.

    It's an in-place, unstable sort(it will reorder equal elements). The time complexity is O(n log n) in the worst case.

    Example

    test {
    let arr = [5, 3, 2, 4, 1]
    arr.sort_by((a, b) => a - b)
    @test.assert_eq(arr, [1, 2, 3, 4, 5])
    }

    Array::sort_by_key

    fn[T, K : Compare + Eq] Array::sort_by_key(self : Array[T], map : (T) -> K) -> Unit

    Sorts the array with a key extraction function.

    It's an in-place, unstable sort(it will reorder equal elements). The time complexity is O(n log n) in the worst case.

    Example

    test {
    let arr = [5, 3, 2, 4, 1]
    arr.sort_by_key(x => -x)
    @test.assert_eq(arr, [5, 4, 3, 2, 1])
    }

    Array::split

    fn[T] Array::split(self : Array[T], pred : (T) -> Bool raise?) -> Array[Array[T]] raise?

    Splits an array into chunks using a predicate function. Creates chunks by grouping consecutive elements that do not satisfy the predicate function. Elements that satisfy the predicate function are excluded from the resulting chunks and act as delimiters.

    Parameters:

    • array : The array to be split into chunks.
    • predicate : A function that takes an element and returns true if the element should be used as a delimiter.

    Returns an array of arrays, where each inner array is a chunk of consecutive elements that do not satisfy the predicate.

    Example:

    test {
    let arr = [1, 0, 2, 0, 3, 0, 4]
    debug_inspect(arr.split(x => x == 0), content="[[1], [2], [3], [4]]")
    let arr = [0, 1, 0, 0, 2, 0]
    debug_inspect(arr.split(x => x == 0), content="[[], [1], [], [2]]")
    }

    Array::starts_with

    fn[T : Eq] Array::starts_with(self : Array[T], prefix : ArrayView[T]) -> Bool

    Checks if the array begins with all elements of the provided prefix array in order.

    Parameters:

    • self : The array to check against.
    • prefix : The array containing the sequence of elements to look for at the beginning.

    Returns true if the array starts with all elements in prefix in the same order, false otherwise. An empty prefix array always returns true, and a prefix longer than the array always returns false.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    inspect(arr.starts_with([1, 2]), content="true")
    inspect(arr.starts_with([2, 3]), content="false")
    inspect(arr.starts_with([]), content="true")
    inspect(arr.starts_with([1, 2, 3, 4, 5, 6]), content="false")
    }

    Array::strip_prefix

    fn[T : Eq] Array::strip_prefix(self : Array[T], prefix : ArrayView[T]) -> ArrayView[T]?

    Strip a prefix from the array.

    If the array starts with the prefix, return a view of the array after the prefix, otherwise return None. The returned view shares the original backing array — no allocation.

    Example

    test {
    let v = [1, 2, 3, 4, 5]
    let v2 = v.strip_prefix([1, 2])
    debug_inspect(
    v2,
    content=(
    #|Some(<ArrayView: [3, 4, 5]>)
    ),
    )
    }

    Array::strip_suffix

    fn[T : Eq] Array::strip_suffix(self : Array[T], suffix : ArrayView[T]) -> ArrayView[T]?

    Strip a suffix from the array.

    If the array ends with the suffix, return a view of the array before the suffix, otherwise return None. The returned view shares the original backing array — no allocation.

    Example

    test {
    let v = [3, 4, 5]
    let v2 = v.strip_suffix([5])
    debug_inspect(
    v2,
    content=(
    #|Some(<ArrayView: [3, 4]>)
    ),
    )
    }

    Array::suffixes

    fn[T] Array::suffixes(self : Array[T], include_empty? : Bool) -> Iter[ArrayView[T]]

    Return an iterator over all suffix views of this array.

    Suffixes are yielded from longest to shortest. Set include_empty=true to include the final empty suffix.

    Example:

    test {
    let xs = [1, 2]
    debug_inspect(
    xs.suffixes().collect(),
    content=(
    #|[<ArrayView: [1, 2]>, <ArrayView: [2]>]
    ),
    )
    debug_inspect(
    xs.suffixes(include_empty=true).collect(),
    content=(
    #|[<ArrayView: [1, 2]>, <ArrayView: [2]>, <ArrayView: []>]
    ),
    )
    }

    Array::swap

    fn[T] Array::swap(self : Array[T], i : Int, j : Int) -> Unit

    Swaps the values at two positions in the array.

    Parameters:

    • array : The array in which to swap elements.
    • index1 : The index of the first element to be swapped.
    • index2 : The index of the second element to be swapped.

    This function will panic if either index is negative or greater than or equal to the length of the array.

    Example:

    test {
    let arr = [1, 2, 3]
    arr.swap(0, 2)
    debug_inspect(arr, content="[3, 2, 1]")
    }

    Array::to_json

    fn[X : ToJson] Array::to_json(self : Array[X]) -> Json

    Array::truncate

    fn[A] Array::truncate(self : Array[A], len : Int) -> Unit

    Truncates the array in-place to the specified length.

    If len is greater than or equal to the current array length, the function does nothing. If len is 0, the array is cleared. Otherwise, removes elements from the end until the array reaches the given length.

    Parameters:

    • self : The target array (modified in-place).
    • len : The new desired length (must be non-negative).

    Important:
    • If len is negative, the function does nothing.
    • If len exceeds current length, the array remains unchanged.

    Elements beyond len are removed from the array, but the backing buffer keeps referring to them: they are released once those slots are reused by later pushes, once the buffer grows, or once the array is dropped. Call Array::release_unused to overwrite them at once, or Array::shrink_to_fit to move the survivors into an exact-size buffer. On the JavaScript backend the removed elements are released right away and Array::release_unused is a no-op.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    arr.truncate(3)
    debug_inspect(arr, content="[1, 2, 3]")
    }

    Array::unsafe_blit_fixed

    fn[A] Array::unsafe_blit_fixed(dst : Array[A], dst_offset : Int, src : FixedArray[A], src_offset : Int, len : Int) -> Unit

    Copies elements from a fixed-size array to a dynamic array. The arrays may overlap, in which case the copy is performed in a way that preserves the data.

    Parameters:

    • dst : The destination dynamic array where elements will be copied to.
    • dst_offset : The starting index in the destination array where copying begins.
    • src : The source fixed-size array from which elements will be copied.
    • src_offset : The starting index in the source array from which copying begins.
    • len : The number of elements to copy.

    Example:

    test {
    let src = FixedArray::make(5, 0)
    let dst = Array::make(5, 0)
    for i in 0..<5 {
    src[i] = i + 1
    }
    Array::unsafe_blit_fixed(dst, 1, src, 0, 2)
    @debug.debug_inspect(dst, content="[0, 1, 2, 0, 0]")
    }

    Array::unsafe_get

    fn[T] Array::unsafe_get(self : Array[T], idx : Int) -> T

    Retrieves the element at the specified index from an array without bounds checking.

    Parameters:

    • array : The array from which to retrieve the element.
    • index : The position in the array from which to retrieve the element.

    Returns the element at the specified index.

    Example:

    test {
    let arr : Array[Int] = [1, 2, 3]
    inspect(arr.unsafe_get(1), content="2")
    }

    Array::unsafe_set

    fn[T] Array::unsafe_set(self : Array[T], idx : Int, val : T) -> Unit

    Write val to idx without bounds checking.

    This is unsafe: caller must ensure 0 <= idx < self.length().

    Example:

    test {
    let arr = [1, 2, 3]
    arr.unsafe_set(1, 99)
    debug_inspect(arr, content="[1, 99, 3]")
    }

    Array::unzip

    fn[T1, T2] Array::unzip(self : Array[(T1, T2)]) -> (Array[T1], Array[T2])

    Splits an array of pairs into two arrays, separating the first and second elements.

    Example

    test {
    let arr = [(1, "a"), (2, "b"), (3, "c")]
    let (nums, strs) = arr.unzip()
    debug_inspect(nums, content="[1, 2, 3]")
    debug_inspect(strs, content="[\"a\", \"b\", \"c\"]")
    }

    Array::view

    #alias(sub, deprecated="Use _[_:_] instead")
    #alias("_[_:_]")
    fn[T] Array::view(self : Array[T], start? : Int, end? : Int) -> ArrayView[T]

    Creates a view of a portion of the array. The view provides read-only access to the underlying array without copying the elements.

    Parameters:

    • array : The array to create a view from.
    • start : The starting index of the view (inclusive). Defaults to 0.
    • end : The ending index of the view (exclusive). If not provided, defaults to the length of the array.

    Returns an ArrayView that provides a window into the specified portion of the array.

    Throws a panic if the indices are invalid (i.e., start is negative, end is greater than the array length, or start is greater than end).

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr[1:4] // Create a view of elements at indices 1, 2, and 3
    inspect(view[0], content="2") // First element of view is arr[1]
    inspect(view.length(), content="3") // View contains 3 elements
    }

    Array::windows

    fn[T] Array::windows(self : Array[T], size : Int) -> Array[ArrayView[T]]

    Generates overlapping subslices (sliding windows) of the specified size.

    Parameters:

    • array : The array to be processed with sliding windows.
    • size : The window length. Must be a positive integer, otherwise it will panic.

    Returns an array of slices, where each inner slice is a contiguous subslice of the original array. Windows are produced with a step size of 1. If the original array's length is less than the specified window size, the result will be an empty array.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let windows = arr.windows(2)
    debug_inspect(
    windows,
    content=(
    #|[
    #| <ArrayView: [1, 2]>,
    #| <ArrayView: [2, 3]>,
    #| <ArrayView: [3, 4]>,
    #| <ArrayView: [4, 5]>,
    #|]
    ),
    )
    let arr = [1, 2]
    debug_inspect(arr.windows(3), content="[]")
    }

    Array::zip

    fn[A, B] Array::zip(self : Array[A], other : Array[B]) -> Array[(A, B)]

    Zips two arrays into a single array of tuples.

    Parameters:

    • self : The first array.
    • other : The second array.

    Returns an array of tuples, where each tuple contains corresponding elements from the two input arrays.

    Example:

    test {
    let arr1 = [1, 2, 3]
    let arr2 = ['a', 'b', 'c']
    debug_inspect(arr1.zip(arr2), content="[(1, 'a'), (2, 'b'), (3, 'c')]")
    }

    Array::zip_to_iter2

    fn[A, B] Array::zip_to_iter2(self : Array[A], other : Array[B]) -> Iter2[A, B]

    Zips two arrays into an iterator that yields corresponding elements.

    Parameters:

    • self : The first array.
    • other : The second array.

    Returns an Iter2 iterator that produces corresponding elements from both arrays. The iteration continues until the shorter array is exhausted.

    Example:

    test {
    let arr1 = [1, 2, 3]
    let arr2 = ['a', 'b', 'c']
    debug_inspect(
    arr1.zip_to_iter2(arr2).to_array(),
    content="[(1, 'a'), (2, 'b'), (3, 'c')]",
    )
    }

    ArrayView

    type ArrayView[T]

    An ArrayView represents a view into a section of an array without copying the data. It stores its own start offset and length when it is created, so iteration over a view keeps using those bounds even if the underlying array is later structurally modified.

    Mutating an array while a view of it is alive is a program error. Because a view keeps its original bounds and does not track the array, after such a mutation it may observe elements that have since been removed, a value handed to Array::release_unused, or the contents of a buffer the array has stopped using. What it yields is always a valid value of T -- never uninitialized memory -- but is otherwise unspecified.

    No removal writes to the slots it vacates, so the removed elements stay reachable, and so unreleased, until a later push reuses the slot, until the buffer grows, or until the buffer itself is dropped. That holds uniformly: clear empties an array the same way pop shortens it. Two operations release those elements on demand -- Array::release_unused overwrites the unused capacity in place, and Array::shrink_to_fit moves the survivors into an exact-size buffer and lets the old one go.

    On the JavaScript backend this guarantee does not yet hold: operations such as Array::pop shrink the underlying JavaScript array, so a view reaching past the array's current length observes undefined.

    Example

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr[1:4] // Creates a view of elements at indices 1,2,3
    @test.assert_eq(view[0], 2)
    @test.assert_eq(view.length(), 3)
    }
    impl Add for ArrayView[T]
    impl Compare for ArrayView[T]
    impl Eq for ArrayView[T]
    impl Hash for ArrayView[A]
    impl Show for ArrayView[X]
    impl ToJson for ArrayView[X]

    ArrayView::add

    fn[T] ArrayView::add(self : ArrayView[T], other : ArrayView[T]) -> ArrayView[T]

    ArrayView::all

    #alias(every)
    fn[T] ArrayView::all(self : ArrayView[T], f : (T) -> Bool raise?) -> Bool raise?

    Checks if all elements in the array view match the condition.

    Example

    test {
    let v = [1, 4, 6, 8, 9]
    assert_false(v[:].all(elem => elem % 2 == 0))
    assert_true(v[1:4].all(elem => elem % 2 == 0))
    }

    ArrayView::any

    #alias(exists)
    fn[T] ArrayView::any(self : ArrayView[T], f : (T) -> Bool raise?) -> Bool raise?

    Check if any of the elements in the array view match the condition.

    Example

    test {
    let v = [1, 2, 3, 4, 5][:]
    assert_true(v.any(ele => ele < 6))
    assert_false(v.any(ele => ele < 1))
    }

    ArrayView::at

    #alias("_[_]")
    fn[T] ArrayView::at(self : ArrayView[T], index : Int) -> T

    Retrieves an element at the specified index from the array view.

    Parameters:

    • self : The array view to access.
    • index : The position in the array view from which to retrieve the element.

    Returns the element at the specified index.

    Throws a runtime error if the index is out of bounds (less than 0 or greater than or equal to the length of the array view).

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr[2:4]
    inspect(view[0], content="3")
    inspect(view[1], content="4")
    }
    fn[T : Compare + Eq] ArrayView::binary_search(self : ArrayView[T], value : T) -> Result[Int, Int]

    Performs a binary search on a sorted array view.

    Example

    test {
    let view = [1, 3, 5, 7, 9][:]
    debug_inspect(view.binary_search(5), content="Ok(2)")
    debug_inspect(view.binary_search(6), content="Err(3)")
    }

    ArrayView::binary_search_by

    fn[T] ArrayView::binary_search_by(self : ArrayView[T], cmp : (T) -> Int raise?) -> Result[Int, Int] raise?

    Performs a binary search using a custom comparison function.

    Example

    test {
    let view = [1, 3, 5, 7, 9][:]
    let result = view.binary_search_by(x => x.compare(5))
    debug_inspect(result, content="Ok(2)")
    }

    ArrayView::blit_to

    fn[A] ArrayView::blit_to(self : ArrayView[A], dst : Array[A], dst_offset? : Int) -> Unit

    Copies all elements from an array view to a destination array, with support for growing the destination array if needed.

    Parameters:

    • self : The array view to copy elements from.
    • dst : The array to copy elements to. Will be automatically grown if needed to accommodate the copied elements.
    • dst_offset : Starting index in the destination array. Defaults to 0.

    Example:

    test {
    let src = [1, 2, 3, 4, 5]
    let view = src[1:4] // view = [2, 3, 4]
    let dst = [0, 0]
    view.blit_to(dst, dst_offset=1)
    @debug.debug_inspect(dst, content="[0, 2, 3, 4]")
    }

    Panics if:

    • dst_offset is negative
    • dst_offset exceeds the length of destination array

    ArrayView::chunk_by

    fn[T] ArrayView::chunk_by(self : ArrayView[T], pred : (T, T) -> Bool raise?) -> Array[ArrayView[T]] raise?

    Groups consecutive elements of the view into chunks where adjacent elements satisfy the given predicate. Each returned sub-view shares the original backing array.

    Example:

    test {
    let v = [1, 1, 2, 2, 2, 3, 1][:]
    debug_inspect(
    v.chunk_by((a, b) => a == b),
    content=(
    #|[
    #| <ArrayView: [1, 1]>,
    #| <ArrayView: [2, 2, 2]>,
    #| <ArrayView: [3]>,
    #| <ArrayView: [1]>,
    #|]
    ),
    )
    }

    ArrayView::chunks

    fn[T] ArrayView::chunks(self : ArrayView[T], size : Int) -> Array[ArrayView[T]]

    Split the array view into contiguous sub-views of length size. The last sub-view may be shorter if the view length is not a multiple of size. The returned sub-views share the original backing array — no elements are copied.

    Panics if size <= 0.

    Example:

    test {
    let v = [1, 2, 3, 4, 5, 6, 7][:]
    debug_inspect(
    v.chunks(3),
    content=(
    #|[<ArrayView: [1, 2, 3]>, <ArrayView: [4, 5, 6]>, <ArrayView: [7]>]
    ),
    )
    }

    ArrayView::compare

    fn[T : Compare + Eq] ArrayView::compare(self : ArrayView[T], other : ArrayView[T]) -> Int

    ArrayView::contains

    fn[T : Eq] ArrayView::contains(self : ArrayView[T], value : T) -> Bool

    Checks whether the array view contains a specific element by comparing each element with the target value using the equality operator.

    Parameters:

    • view : The array view to search in.
    • target : The value to search for in the array view.

    Returns a boolean value indicating whether the target value exists in the array view.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5][:]
    inspect(arr.contains(3), content="true")
    inspect(arr.contains(6), content="false")
    }

    ArrayView::count

    fn[T : Eq] ArrayView::count(self : ArrayView[T], value : T) -> Int

    Counts how many elements in the array view are equal to value.

    Example

    test {
    let view = [1, 2, 1, 3, 1][:]
    inspect(view.count(1), content="3")
    inspect(view.count(4), content="0")
    }

    ArrayView::count_if

    fn[T] ArrayView::count_if(self : ArrayView[T], f : (T) -> Bool raise?) -> Int raise?

    Counts how many elements in the array view satisfy the predicate.

    Example

    test {
    let view = [1, 2, 3, 4, 5][:]
    inspect(view.count_if(x => x % 2 == 0), content="2")
    }

    ArrayView::each

    fn[T] ArrayView::each(self : ArrayView[T], f : (T) -> Unit raise?) -> Unit raise?

    Iterates over each element in the array view and applies a function to it.

    Parameters:

    • self : The array view to iterate over.
    • function : A function that takes an element of type T and returns nothing. This function will be applied to each element in the array view.

    Example:

    test {
    let arr = [1, 2, 3][:]
    let mut sum = 0
    arr.each(x => sum x)
    inspect(sum, content="6")
    }

    ArrayView::eachi

    fn[T] ArrayView::eachi(self : ArrayView[T], f : (Int, T) -> Unit raise?) -> Unit raise?

    Iterates over the elements of the array view with index.

    Example

    test {
    let v = [3, 4, 5][:]
    let mut sum = 0
    v.eachi((i, x) => sum x + i)
    inspect(sum, content="15")
    }

    ArrayView::ends_with

    fn[T : Eq] ArrayView::ends_with(self : ArrayView[T], suffix : ArrayView[T]) -> Bool

    Checks if the array view ends with the given suffix.

    Example

    test {
    let view = [1, 2, 3, 4, 5][:]
    inspect(view.ends_with([4, 5]), content="true")
    inspect(view.ends_with([3, 4]), content="false")
    }

    ArrayView::equal

    fn[T : Eq] ArrayView::equal(self : ArrayView[T], other : ArrayView[T]) -> Bool

    ArrayView::filter

    fn[T] ArrayView::filter(self : ArrayView[T], f : (T) -> Bool raise?) -> Array[T] raise?

    Filters the array view with a predicate function.

    Example

    test {
    let arr = [1, 2, 3, 4, 5, 6]
    let v = arr[2:].filter(x => x % 2 == 0)
    @test.assert_eq(v, [4, 6])
    }

    ArrayView::filter_map

    fn[A, B] ArrayView::filter_map(self : ArrayView[A], f : (A) -> B? raise?) -> Array[B] raise?

    Apply a function to each element of the view, keeping only the Some results. Returns a freshly allocated Array.

    Example:

    test {
    let v = [1, 2, 3, 4, 5][1:4]
    debug_inspect(
    v.filter_map(x => if x % 2 == 0 { Some(x * 10) } else { None }),
    content="[20, 40]",
    )
    }

    ArrayView::fold

    fn[A, B] ArrayView::fold(self : ArrayView[A], init~ : B, f : (B, A) -> B raise?) -> B raise?

    Fold out values from an ArrayView according to certain rules.

    Example

    test {
    let sum = [1, 2, 3, 4, 5][:].fold(init=0, (sum, elem) => sum + elem)
    inspect(sum, content="15")
    }

    ArrayView::foldi

    fn[A, B] ArrayView::foldi(self : ArrayView[A], init~ : B, f : (Int, B, A) -> B raise?) -> B raise?

    Fold out values from an ArrayView according to certain rules with index.

    Example

    test {
    let sum = [1, 2, 3, 4, 5][:].foldi(init=0, (index, sum, _elem) => sum + index)
    inspect(sum, content="10")
    }

    ArrayView::get

    fn[T] ArrayView::get(self : ArrayView[T], index : Int) -> T?

    Retrieves an element from the array view at the specified index.

    Parameters:

    • self : The array view to retrieve the element from.
    • index : The position in the array view from which to retrieve the element.

    Returns Some(element) if the index is within bounds, or None if the index is out of bounds.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr[1:4]
    debug_inspect(view.get(0), content="Some(2)")
    debug_inspect(view.get(1), content="Some(3)")
    debug_inspect(view.get(2), content="Some(4)")
    debug_inspect(view.get(5), content="None")
    }

    ArrayView::get_view

    fn[T] ArrayView::get_view(self : ArrayView[T], start? : Int, end? : Int) -> ArrayView[T]?

    Creates a new view into a portion of the array view, returning None when indices are invalid.

    Parameters:

    • self : The array view to create a new view from.
    • start : The starting index in the current view (inclusive). Defaults to
    • end : The ending index in the current view (exclusive). Defaults to the length of the current view.

    Returns Some(ArrayView) that provides a window into the specified portion of the original array view, or None when the indices are invalid.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr[1:4] // view = [2, 3, 4]
    let start = 1
    let end = 2
    debug_inspect(
    view.get_view(start~, end~),
    content=(
    #|Some(<ArrayView: [3]>)
    ),
    )
    let start = 4
    let end = 5
    debug_inspect(view.get_view(start~, end~), content="None")
    }

    ArrayView::hash

    fn[A : Hash] ArrayView::hash(self : ArrayView[A]) -> Int

    ArrayView::is_empty

    fn[T] ArrayView::is_empty(self : ArrayView[T]) -> Bool

    Returns whether the array view is empty.

    Example:

    test {
    let view = [1, 2, 3][:]
    inspect(view.is_empty(), content="false")
    let empty = [1, 2][0:0]
    inspect(empty.is_empty(), content="true")
    }

    ArrayView::is_sorted

    fn[T : Compare + Eq] ArrayView::is_sorted(self : ArrayView[T]) -> Bool

    Tests whether the array view is sorted in ascending order.

    Parameters:

    • self : The array view to be tested.
    • T : The type of elements in the array view. Must implement the Compare trait.

    Returns a boolean value indicating whether the array view is sorted in ascending order:

    • true if the array view is empty, contains only one element, or all elements are in ascending order.
    • false if any element is greater than the element that follows it.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr[1:4]
    inspect(view.is_sorted(), content="true")
    let descending : ReadOnlyArray[Int] = [5, 4, 3, 2, 1]
    inspect(descending[:].is_sorted(), content="false")
    }

    ArrayView::iter

    #alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
    fn[X] ArrayView::iter(self : ArrayView[X]) -> Iter[X]

    Returns an iterator that yields each element of the array view in sequence from start to end.

    Parameters:

    • array_view : The array view to iterate over.

    Returns an iterator that yields elements of type A from the array view. The iterator uses the view's stored length, so structural mutations to the underlying array after the view is created do not change how many steps the iterator attempts to take.

    Structural shrinking of the underlying array is unsupported and may cause later iterator steps to fail. The same caveat applies to rev_iter() and iter2().

    Example:

    test {
    let arr = [1, 2, 3]
    let view = arr[1:]
    let mut sum = 0
    view.iter().each(x => sum x)
    inspect(sum, content="5")
    }

    ArrayView::iter2

    #alias(iterator2, deprecated="`iterator2` is deprecated, use `iter2` instead")
    fn[X] ArrayView::iter2(self : ArrayView[X]) -> Iter2[Int, X]

    Returns an iterator that yields tuples of index and value indices start from 0.

    Example:
    test {
    let arr = [1, 2, 3]
    let view = arr[1:]
    let mut sum = 0
    let mut sum_keys = 0
    view
    .iter2()
    .each((i, x) => {
    sum x
    sum_keys i
    })
    inspect(sum, content="5")
    inspect(sum_keys, content="1")
    }

    ArrayView::join

    fn[A : ToStringView] ArrayView::join(self : ArrayView[A], separator : StringView) -> String

    Concatenate strings within an array into a single complete string.

    Example:

    test {
    let a : Array[String] = ["1", "2", "3"]
    let array_view = a[:]
    inspect(array_view.join(","), content="1,2,3")
    }

    ArrayView::last

    fn[T] ArrayView::last(self : ArrayView[T]) -> T?

    Returns the last element of the array view, if any.

    Example:

    test {
    let view = [1, 2, 3][:]
    debug_inspect(view.last(), content="Some(3)")
    let empty = [1, 2][0:0]
    debug_inspect(empty.last(), content="None")
    }

    ArrayView::length

    fn[T] ArrayView::length(self : ArrayView[T]) -> Int

    Returns the length (number of elements) of an array view.

    Parameters:

    • array_view : The array view whose length is to be determined.

    Returns an integer representing the number of elements in the array view.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr[2:4]
    inspect(view.length(), content="2")
    }

    ArrayView::lexical_compare

    fn[T : Compare + Eq] ArrayView::lexical_compare(self : ArrayView[T], other : ArrayView[T]) -> Int

    Performs a lexicographical comparison of two array views.

    This method compares the array views element by element until a difference is found or one view is exhausted. Unlike the Compare trait implementation which uses shortlex order (shorter views come first), this method compares based purely on element values until a difference is found.

    Returns

    • A negative integer if self is lexicographically less than other
    • Zero if self is lexicographically equal to other
    • A positive integer if self is lexicographically greater than other

    Example

    test {
    inspect([1, 2][:].lexical_compare([1, 2, 3]), content="-1")
    inspect([1, 2, 3][:].lexical_compare([1, 2]), content="1")
    inspect([1, 2, 3][:].lexical_compare([1, 2, 3]), content="0")
    inspect([1, 2, 3][:].lexical_compare([1, 2, 4]), content="-1")
    }

    ArrayView::map

    fn[T, U] ArrayView::map(self : ArrayView[T], f : (T) -> U raise?) -> Array[U] raise?

    Maps a function over the elements of the array view.

    Example

    test {
    let v = [3, 4, 5]
    let v2 = v[1:].map(x => x + 1)
    @test.assert_eq(v2, [5, 6])
    }

    ArrayView::mapi

    fn[T, U] ArrayView::mapi(self : ArrayView[T], f : (Int, T) -> U raise?) -> Array[U] raise?

    Maps a function over the elements of the array view with index.

    Example

    test {
    let v = [3, 4, 5]
    let v2 = v[1:].mapi((i, x) => x + i)
    @test.assert_eq(v2, [4, 6])
    }

    ArrayView::rev

    fn[T] ArrayView::rev(self : ArrayView[T]) -> Array[T]

    Reverses the elements of the array view, returning a freshly allocated array containing the elements in reverse order. The original view is not modified.

    Example:

    test {
    let v = [1, 2, 3, 4, 5][1:4]
    debug_inspect(v.rev(), content="[4, 3, 2]")
    // The view itself is unchanged.
    debug_inspect(
    v,
    content=(
    #|<ArrayView: [2, 3, 4]>
    ),
    )
    }

    ArrayView::rev_each

    fn[T] ArrayView::rev_each(self : ArrayView[T], f : (T) -> Unit raise?) -> Unit raise?

    Iterates over the elements of the array view in reverse order (last to first).

    Example:

    test {
    let v = [1, 2, 3, 4, 5][1:4]
    let out = []
    v.rev_each(x => out.push(x))
    debug_inspect(out, content="[4, 3, 2]")
    }

    ArrayView::rev_eachi

    fn[T] ArrayView::rev_eachi(self : ArrayView[T], f : (Int, T) -> Unit raise?) -> Unit raise?

    Iterates over the elements of the array view in reverse order, passing the view-relative index of each element (0 for the first element yielded, the last position of the view).

    Example:

    test {
    let v = [10, 20, 30][:]
    let out = []
    v.rev_eachi((i, x) => out.push((i, x)))
    debug_inspect(out, content="[(0, 30), (1, 20), (2, 10)]")
    }

    ArrayView::rev_fold

    fn[A, B] ArrayView::rev_fold(self : ArrayView[A], init~ : B, f : (B, A) -> B raise?) -> B raise?

    Fold out values from an ArrayView according to certain rules in reversed turn.

    Example

    test {
    let sum = [1, 2, 3, 4, 5][:].rev_fold(init=0, (sum, elem) => sum + elem)
    inspect(sum, content="15")
    }

    ArrayView::rev_foldi

    fn[A, B] ArrayView::rev_foldi(self : ArrayView[A], init~ : B, f : (Int, B, A) -> B raise?) -> B raise?

    Fold out values from an ArrayView according to certain rules in reversed turn with index.

    Example

    test {
    let sum = [1, 2, 3, 4, 5][:].rev_foldi(init=0, (index, sum, _elem) => {
    sum + index
    })
    inspect(sum, content="10")
    }

    ArrayView::rev_iter

    #alias(rev_iterator, deprecated="`rev_iterator` is deprecated, use `rev_iter` instead")
    fn[X] ArrayView::rev_iter(self : ArrayView[X]) -> Iter[X]

    Return a reverse iterator over elements of this view.

    rev_iterator is a deprecated alias for this function.

    Example:

    test {
    let values = [1, 2, 3][:].rev_iter().collect()
    debug_inspect(values, content="[3, 2, 1]")
    }

    ArrayView::search

    fn[T : Eq] ArrayView::search(self : ArrayView[T], value : T) -> Int?

    Searches for the first occurrence of a value in the array view.

    Example

    test {
    let view = [1, 2, 3, 2, 4][:]
    debug_inspect(view.search(2), content="Some(1)")
    debug_inspect(view.search(5), content="None")
    }

    ArrayView::search_by

    fn[T] ArrayView::search_by(self : ArrayView[T], f : (T) -> Bool raise?) -> Int? raise?

    Searches for the first element in the view that satisfies the predicate f and returns its (view-relative) index, or None if no element matches.

    Example:

    test {
    let view = [1, 2, 3, 4, 5][1:]
    debug_inspect(view.search_by(x => x > 3), content="Some(2)")
    debug_inspect(view.search_by(x => x > 99), content="None")
    }

    ArrayView::start_offset

    fn[T] ArrayView::start_offset(self : ArrayView[T]) -> Int

    Return the starting index of this view in the underlying array.

    Example:

    test {
    let arr = [10, 20, 30]
    let v = arr[1:]
    inspect(v.start_offset(), content="1")
    }

    ArrayView::starts_with

    fn[T : Eq] ArrayView::starts_with(self : ArrayView[T], prefix : ArrayView[T]) -> Bool

    Checks if the array view starts with the given prefix.

    Example

    test {
    let view = [1, 2, 3, 4, 5][:]
    inspect(view.starts_with([1, 2]), content="true")
    inspect(view.starts_with([2, 3]), content="false")
    }

    ArrayView::strip_prefix

    fn[T : Eq] ArrayView::strip_prefix(self : ArrayView[T], prefix : ArrayView[T]) -> ArrayView[T]?

    Returns a sub-view with prefix removed from the start, or None if the view does not start with prefix. The returned view shares the original backing array — no allocation.

    Example:

    test {
    let v = [1, 2, 3, 4, 5][:]
    debug_inspect(
    v.strip_prefix([1, 2]),
    content=(
    #|Some(<ArrayView: [3, 4, 5]>)
    ),
    )
    debug_inspect(v.strip_prefix([2, 3]), content="None")
    }

    ArrayView::strip_suffix

    fn[T : Eq] ArrayView::strip_suffix(self : ArrayView[T], suffix : ArrayView[T]) -> ArrayView[T]?

    Returns a sub-view with suffix removed from the end, or None if the view does not end with suffix. The returned view shares the original backing array — no allocation.

    Example:

    test {
    let v = [1, 2, 3, 4, 5][:]
    debug_inspect(
    v.strip_suffix([4, 5]),
    content=(
    #|Some(<ArrayView: [1, 2, 3]>)
    ),
    )
    debug_inspect(v.strip_suffix([3, 4]), content="None")
    }

    ArrayView::suffixes

    fn[T] ArrayView::suffixes(self : ArrayView[T], include_empty? : Bool) -> Iter[ArrayView[T]]

    Return an iterator over suffix views of this array view.

    Set include_empty=true to include the empty suffix at the end.

    Example:

    test {
    let v = [1, 2][:]
    debug_inspect(
    v.suffixes().collect(),
    content=(
    #|[<ArrayView: [1, 2]>, <ArrayView: [2]>]
    ),
    )
    debug_inspect(
    v.suffixes(include_empty=true).collect(),
    content=(
    #|[<ArrayView: [1, 2]>, <ArrayView: [2]>, <ArrayView: []>]
    ),
    )
    }

    ArrayView::to_json

    fn[X : ToJson] ArrayView::to_json(self : ArrayView[X]) -> Json

    ArrayView::to_owned

    #alias(to_array, deprecated="`to_array` is deprecated, use `to_owned` instead")
    fn[T] ArrayView::to_owned(self : ArrayView[T]) -> Array[T]

    Copy the view elements into a newly allocated Array.

    Example

    test {
    let view = [1, 2, 3, 4, 5, 6][2:4]
    let arr = view.to_owned()
    @test.assert_eq(arr, [3, 4])
    }

    ArrayView::view

    #alias(sub, deprecated="Use _[_:_] instead")
    #alias("_[_:_]")
    fn[T] ArrayView::view(self : ArrayView[T], start? : Int, end? : Int) -> ArrayView[T]

    Creates a new view into a portion of the array view.

    Parameters:

    • self : The array view to create a new view from.
    • start : The starting index in the current view (inclusive). Defaults to
    • end : The ending index in the current view (exclusive). Defaults to the length of the current view.

    Returns a new ArrayView that provides a window into the specified portion of the original array view. The indices are relative to the start of the current view.

    Throws a panic if:

    • start is negative
    • end is greater than the length of the current view
    • start is greater than end

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr[1:4] // view = [2, 3, 4]
    let subview = view[1:2] // subview = [3]
    inspect(subview[0], content="3")
    }

    ArrayView::windows

    fn[T] ArrayView::windows(self : ArrayView[T], size : Int) -> Array[ArrayView[T]]

    Return all contiguous sub-views of the given size, stepping by one element. Returns an empty array if size exceeds the view length. Each returned sub-view shares the original backing array.

    Panics if size <= 0.

    Example:

    test {
    let v = [1, 2, 3, 4, 5][:]
    debug_inspect(
    v.windows(3),
    content=(
    #|[
    #| <ArrayView: [1, 2, 3]>,
    #| <ArrayView: [2, 3, 4]>,
    #| <ArrayView: [3, 4, 5]>,
    #|]
    ),
    )
    }

    Hasher

    type Hasher

    Represents a hasher that implements the xxHash32 algorithm. The hasher maintains a mutable accumulator that is updated with each value added to the hash computation.

    This struct provides methods for combining different types of values into a single hash value, making it suitable for implementing hash functions for custom types.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine_int(42)
    hasher.combine_string("hello")
    inspect(hasher.finalize(), content="860601284")
    }

    Hasher::Hasher

    #alias(new, deprecated="Use `Hasher()` instead")
    fn Hasher::Hasher(seed? : Int) -> Hasher

    Creates a new hasher with an optional seed value. Enables the constructor call syntax Hasher() and Hasher(seed=...).

    Parameters:

    • seed : An integer value used to initialize the hasher's internal state. When omitted, a randomly chosen process-wide seed is used on native, LLVM, and JavaScript targets. Wasm targets default to 0. Pass 0 explicitly when deterministic output is required.

    Returns a new Hasher instance initialized with the given seed value.

    Example:

    test {
    let h1 = Hasher(seed=0) // Create a hasher with default seed
    let h2 = Hasher(seed=42) // Create a hasher with custom seed
    let x = 123
    h1.combine(x)
    h2.combine(x)
    inspect(h1.finalize() != h2.finalize(), content="true") // Different seeds produce different hashes
    }

    Hasher::new remains available as a deprecated alias.

    Hasher::combine

    fn[T : Hash] Hasher::combine(self : Hasher, value : T) -> Unit

    Combines a hashable value with the current state of the hasher. This is typically used to incrementally build a hash value from multiple components.

    Parameters:

    • self : The hasher instance to update.
    • value : The value to be combined with the current hash state. Must implement the Hash trait.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine(42)
    hasher.combine("hello")
    inspect(hasher.finalize(), content="860601284")
    }

    Hasher::combine_bool

    fn Hasher::combine_bool(self : Hasher, value : Bool) -> Unit

    Combines a boolean value into the current hash state. The boolean value is converted to an integer (1 for true, 0 for false) before being combined with the hash.

    Parameters:

    • self : The hasher instance to update.
    • value : The boolean value to be combined into the hash state.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine_bool(true)
    inspect(hasher.finalize(), content="-205818221")
    }

    Hasher::combine_byte

    fn Hasher::combine_byte(self : Hasher, value : Byte) -> Unit

    Combines a byte value into the hash state.

    Parameters:

    • hasher : The hasher object to update with the byte value.
    • byte : The byte value to be combined into the hash.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine_byte(b'\xFF')
    inspect(hasher.finalize(), content="1955036104")
    }

    Hasher::combine_bytes

    fn Hasher::combine_bytes(self : Hasher, value : Bytes) -> Unit

    Combines a byte sequence into the hasher's internal state using xxHash32 algorithm. Processes the input bytes in chunks of 4 bytes for efficiency, with remaining bytes processed individually.

    Parameters:

    • hasher : The hasher object to update with the byte sequence.
    • bytes : The byte sequence to be combined into the hash.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine_bytes(b"\xFF\x00\xFF\x00")
    inspect(hasher.finalize(), content="-686861102")
    }

    Hasher::combine_char

    fn Hasher::combine_char(self : Hasher, value : Char) -> Unit

    Combines a character value into the hasher's internal state. The character is first converted to its Unicode code point (as an integer) before being combined.

    Parameters:

    • self : The hasher instance to update.
    • value : The character value to be combined into the hash state.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine_char('A')
    inspect(hasher.finalize(), content="-1625495534")
    }

    Hasher::combine_double

    fn Hasher::combine_double(self : Hasher, value : Double) -> Unit

    Combines a double-precision floating-point number into the hasher's internal state by reinterpreting its bits as a 64-bit integer. Maintains consistent hashing behavior regardless of the floating-point value's representation.

    Parameters:

    • hasher : The hasher to combine the value into.
    • value : The double-precision floating-point number to be combined into the hash.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine_double(3.14)
    inspect(hasher.finalize(), content="-428265677")
    }

    Hasher::combine_float

    #deprecated("This function is deprecated.")
    fn Hasher::combine_float(self : Hasher, value : Float) -> Unit

    Combines a 32-bit floating-point value into the hasher by reinterpreting its bit pattern as a 32-bit integer. The operation maintains the same hash result regardless of the floating-point value's representation.

    Parameters:

    • hasher : The hasher object that maintains the internal state of the hashing operation.
    • value : The 32-bit floating-point value to be combined into the hash.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine(3.14F)
    inspect(hasher.finalize(), content="635116317") // Hash of the bits of 3.14
    }

    Hasher::combine_int

    fn Hasher::combine_int(self : Hasher, value : Int) -> Unit

    Combines a 32-bit integer value into the hasher's internal state. The value is processed as a 4-byte sequence, and the internal accumulator is updated accordingly.

    Parameters:

    • self : The hasher instance to update.
    • value : A 32-bit integer value to be incorporated into the hash.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine_int(42)
    inspect(hasher.finalize(), content="1161967057")
    }

    Hasher::combine_int64

    fn Hasher::combine_int64(self : Hasher, value : Int64) -> Unit

    Combines a 64-bit integer value into the hash state by splitting it into two 32-bit parts and processing them separately. This method is used internally by the hash implementation to incorporate 64-bit integers into the hash computation.

    Parameters:

    • hasher : The hasher object whose internal state will be updated.
    • value : The 64-bit integer value to be incorporated into the hash state.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine_int64(42L)
    inspect(hasher.finalize(), content="-1962516083")
    }

    Hasher::combine_string

    fn Hasher::combine_string(self : Hasher, value : String) -> Unit

    Combines a string value into the current hash state by processing each character in the string sequentially.

    Parameters:

    • self : The hasher object whose state will be updated.
    • value : The string value to be combined into the hash state.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine_string("hello")
    inspect(hasher.finalize(), content="-655549713")
    }

    Hasher::combine_uint

    fn Hasher::combine_uint(self : Hasher, value : UInt) -> Unit

    Combines an unsigned 32-bit integer into the hasher's internal state by reinterpreting it as a signed integer and incorporating it into the hash computation.

    Parameters:

    • hasher : The hasher object to update.
    • value : The unsigned 32-bit integer value to be combined into the hash.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine_uint(42U)
    inspect(hasher.finalize(), content="1161967057")
    }

    Hasher::combine_uint64

    fn Hasher::combine_uint64(self : Hasher, value : UInt64) -> Unit

    Combines a 64-bit unsigned integer into the hasher's internal state. Useful for hashing UInt64 values as part of a larger composite structure.

    Parameters:

    • self : The hasher instance to update.
    • value : The 64-bit unsigned integer value to be incorporated into the hash.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine_uint64(42UL)
    inspect(hasher.finalize(), content="-1962516083")
    }

    Hasher::combine_unit

    fn Hasher::combine_unit(self : Hasher) -> Unit

    Combines the unit value (i.e., ()) into the hasher's internal state by hashing it as an integer value of 0.

    Parameters:

    • hasher : The hasher object to combine the unit value into.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine_unit()
    inspect(hasher.finalize(), content="148298089")
    }

    Hasher::finalize

    fn Hasher::finalize(self : Hasher) -> Int

    Finalizes the hashing process and returns the computed hash value. Applies an avalanche function to improve the distribution of the hash value.

    Parameters:

    • hasher : The hasher object containing the accumulated hash state.

    Returns a 32-bit integer representing the final hash value.

    Example:

    test {
    let hasher = Hasher(seed=0)
    hasher.combine_byte(b'\xFF')
    inspect(hasher.finalize(), content="1955036104")
    }

    Iter

    #alias(Iterator, deprecated="The name `Iterator` is deprecated, use `Iter` instead. Note that if you have defined `iterator()` method to support `for .. in` loop, you should also rename `iterator()` to `iter()`. See https://github.com/moonbitlang/core/pull/3127 for more details.")
    type Iter[X]

    External iterator type. Iterator[X] is a mutable type: iterators internally maintain mutable state to advance iteration. All read operations on Iterator will advance the iterator, and would give different result when called multiple times.
    impl Add for Iter[T]
    impl Show for Iter[X]
    impl ToJson for Iter[X]

    Iter::add

    fn[T] Iter::add(self : Iter[T], other : Iter[T]) -> Iter[T]

    Iter::all

    fn[X] Iter::all(self : Iter[X], f : (X) -> Bool) -> Bool

    Return true if all elements satisfy predicate f. Function all.

    Iter::any

    fn[X] Iter::any(self : Iter[X], f : (X) -> Bool) -> Bool

    Return true if any element satisfies predicate f. Function any.

    Iter::concat

    fn[X] Iter::concat(self : Iter[X], other : Iter[X]) -> Iter[X]

    Combines two iterators into one by appending the elements of the second iterator to the first.

    Type Parameters

    • X: The type of the elements in the iterators.

    Arguments

    • self - The first input iterator.
    • other - The second input iterator to be appended to the first.

    Returns

    Returns a new iterator that contains the elements of self followed by the elements of other.

    Note

    The old iterators self and other must not be used again after calling concat.

    Iter::contains

    fn[X : Eq] Iter::contains(self : Iter[X], value : X) -> Bool

    Checks if the iterator contains an element equal to the given value.

    Parameters:

    • self : The iterator to search in.
    • value : The value to search for.

    Returns true if the iterator contains an element equal to the given value, false otherwise.

    Example:

    test {
    let iter = 1, 2, 3, 4, 5
    inspect(iter.contains(3), content="true")
    inspect(iter.contains(6), content="false")
    let iter =
    inspect(iter.contains(1), content="false")
    }

    Note

    The old iterator self will advance past the searched element.

    Iter::count

    #alias(length)
    fn[X] Iter::count(self : Iter[X]) -> Int

    Counts the number of elements in the iterator.

    Type Parameters

    • X: The type of the elements in the iterator.

    Arguments

    • self: The iterator to consume.

    Returns

    Returns the number of elements in the iterator.

    Iter::count_if

    fn[X] Iter::count_if(self : Iter[X], f : (X) -> Bool) -> Int

    Counts the number of elements in the iterator that satisfy the predicate.

    Type Parameters

    • X: The type of the elements in the iterator.

    Arguments

    • self: The iterator to consume.
    • f: A predicate function applied to each element.

    Returns

    Returns the number of elements for which f returns true.

    Iter::drop

    fn[X] Iter::drop(self : Iter[X], n : Int) -> Iter[X]

    Skips the first n elements from the iterator.

    Type Parameters

    • X: The type of the elements in the iterator.

    Arguments

    • self - The input iterator.
    • n - The number of elements to skip.

    Returns

    A new iterator that starts after skipping the first n elements.

    Note

    The old iterator self must not be used again after calling drop.

    Iter::drop_while

    fn[X] Iter::drop_while(self : Iter[X], f : (X) -> Bool) -> Iter[X]

    Skips elements from the iterator as long as the predicate function returns true.

    Type Parameters

    • X: The type of the elements in the iterator.

    Arguments

    • self - The input iterator.
    • f - The predicate function that determines whether an element should be skipped.

    Returns

    A new iterator that starts after skipping the elements as long as the predicate function returns true.

    Note

    The old iterator self must not be used again after calling drop_while.

    Iter::each

    fn[X] Iter::each(self : Iter[X], f : (X) -> Unit raise?) -> Unit raise?

    Iterates over each element in the iterator, applying the function f to each element.

    Type Parameters

    • X: The type of the elements in the iterator.

    Arguments

    • self: The iterator to consume.
    • f: A function that takes an element of type X and returns Unit. This function is applied to each element of the iterator.

    Iter::eachi

    fn[X] Iter::eachi(self : Iter[X], f : (Int, X) -> Unit raise?) -> Unit raise?

    Iterates over each element in the iterator, applying the function f to each element with index.

    Type Parameters

    • X: The type of the elements in the iterator.

    Arguments

    • self: The iterator to consume.
    • f: A function that takes an index of type Int and an element of type X and returns Unit. This function is applied to each element of the iterator.

    Iter::empty

    fn[X] Iter::empty() -> Iter[X]

    Creates an empty iterator.

    Prefer the iterator literal [||], which is equivalent and shorter.

    Type Parameters

    • X: The type of the elements in the iterator.

    Returns

    Returns an empty iterator of type Iter[X].

    Iter::filter

    fn[X] Iter::filter(self : Iter[X], f : (X) -> Bool) -> Iter[X]

    Filters the elements of the iterator based on a predicate function.

    Type Parameters

    • X: The type of the elements in the iterator.

    Arguments

    • self - The input iterator.
    • f - The predicate function that determines whether an element should be included in the filtered iterator.

    Returns

    A new iterator that only contains the elements for which the predicate function returns true.

    Note

    The old iterator self must not be used again after calling filter.

    Iter::filter_map

    fn[X, Y] Iter::filter_map(self : Iter[X], f : (X) -> Y?) -> Iter[Y]

    Transforms the elements of the iterator using a mapping function that returns an Option. The elements for which the function returns None are filtered out.

    The old iterator self must not be used again after calling filter_map.

    Iter::find_first

    fn[X] Iter::find_first(self : Iter[X], f : (X) -> Bool) -> X?

    Finds the first element in the iterator that satisfies the predicate function.

    Type Parameters

    • X: The type of the elements in the iterator.

    Arguments

    • self - The input iterator.
    • f - The predicate function that determines whether an element is the first element to be found.

    Returns

    An Option that contains the first element that satisfies the predicate function, or None if no such element is found.

    Note

    The iterator self will advance past the returned element.

    Iter::flat_map

    fn[X, Y] Iter::flat_map(self : Iter[X], f : (X) -> Iter[Y]) -> Iter[Y]

    Transforms each element of the iterator into an iterator and flattens the resulting iterators into a single iterator.

    Type Parameters

    • X: The type of the elements in the iterator.
    • Y: The type of the transformed elements.

    Arguments

    • self - The input iterator.
    • f - The function that transforms each element of the iterator into an iterator.

    Returns

    A new iterator that contains the flattened elements.

    Note

    The old iterator self and the iterators returned by f must not be used again after calling flat_map.

    Iter::flatten

    fn[X] Iter::flatten(self : Iter[Iter[X]]) -> Iter[X]

    iter.map(f).flatten() == iter.flat_map(f)

    Iter::fold

    fn[X, R] Iter::fold(self : Iter[X], init~ : R, f : (R, X) -> R raise?) -> R raise?

    Folds the elements of the iterator using the given function, starting with the given initial value.

    Type Parameters

    • X: The type of the elements in the iterator.
    • R: The type of the accumulator (result) value.

    Arguments

    • self: The iterator to consume.
    • f: A function that takes an accumulator of type R and an element of type X, and returns a new accumulator value.
    • init: The initial value for the fold operation.

    Returns

    Returns the final accumulator value after folding all elements of the iterator.

    Iter::intersperse

    fn[X] Iter::intersperse(self : Iter[X], sep : X) -> Iter[X]

    Inserts a separator element sep between each element of the iterator.

    Parameters

    • self : The iterator to intersperse the separator into.
    • sep : The separator element to insert between each element of the iterator.

    Examples

    test {
    let arr = []
    1, 2, 3.intersperse(0).each(i => arr.push(i))
    @test.assert_eq(arr, [1, 0, 2, 0, 3])
    }

    Note

    The old iterator self must not be used again after calling intersperse.

    Iter::iter

    #alias(iterator)
    fn[X] Iter::iter(self : Iter[X]) -> Iter[X]

    Return this iterator itself. Return an iterator via iter.

    Iter::iter2

    #alias(iterator2)
    fn[X] Iter::iter2(self : Iter[X]) -> Iter2[Int, X]

    Return an indexed view of this iterator. Return an iterator via iter2.

    Iter::join

    fn[A : ToStringView] Iter::join(self : Iter[A], sep : StringView) -> String

    Collects the string-renderable elements of the iterator into a single string, separated by sep. The old iterator self must not be used again after calling join.

    Iter::last

    fn[X] Iter::last(self : Iter[X]) -> X?

    Returns the last element of the iterator, or None if the iterator is empty. The old iterator self must not be used again after calling last.

    Iter::map

    fn[X, Y] Iter::map(self : Iter[X], f : (X) -> Y) -> Iter[Y]

    Transforms the elements of the iterator using a mapping function.

    Type Parameters

    • X: The type of the elements in the iterator.
    • Y: The type of the transformed elements.

    Arguments

    • self - The input iterator.
    • f - The mapping function that transforms each element of the iterator.

    Returns

    A new iterator that contains the transformed elements.

    Note

    The old iterator self must not be used again after calling map.

    Iter::map_while

    fn[X, Y] Iter::map_while(self : Iter[X], f : (X) -> Y?) -> Iter[Y]

    Transforms the elements of the iterator using a mapping function upto the function returns None. The old iterator self must not be used again after calling map_while.

    Iter::mapi

    fn[X, Y] Iter::mapi(self : Iter[X], f : (Int, X) -> Y) -> Iter[Y]

    Transforms the elements of the iterator using a mapping function.

    Type Parameters

    • X: The type of the elements in the iterator.
    • Y: The type of the transformed elements.

    Arguments

    • self - The input iterator.
    • f - The mapping function that transforms each element of the iterator with index.

    Returns

    A new iterator that contains the transformed elements.

    Note

    The old iterator self must not be used again after calling mapi.

    Iter::maximum

    fn[X : Compare + Eq] Iter::maximum(self : Iter[X]) -> X?

    Return the maximum element, or None if empty.

    Iter::minimum

    fn[X : Compare + Eq] Iter::minimum(self : Iter[X]) -> X?

    Return the minimum element, or None if empty.

    Iter::new

    fn[X] Iter::new(f : () -> X?, size_hint? : Int) -> Iter[X]

    Create a new iterator by supplying a next function directly. The supplied function should output the next element being iterated everytime it is called. If the number of remaining elements is known, pass it as size_hint.

    This function is intended for use by data structure authors, and should not be called by end users in general.

    Iter::next

    #alias(head)
    #alias(peek, deprecated="`peek` is deprecated, use `next` instead")
    fn[X] Iter::next(self : Iter[X]) -> X?

    Get the next element from an iterator, or return None if no more element exists. The returned element will be consumed from the iterator. Calling next repeatedly will iterate through all elements in the iterator.

    Iter::nth

    fn[X] Iter::nth(self : Iter[X], n : Int) -> X?

    Returns the n-th element of the iterator, counting from zero, or None if n is negative or the iterator has fewer than n + 1 elements. The iterator self will advance past the returned element.

    Iter::repeat

    fn[X] Iter::repeat(x : X) -> Iter[X]

    Creates an iterator that repeats the given element indefinitely.

    Type Parameters

    • X: The type of the elements in the iterator.

    Arguments

    • x: The element to be repeated.

    Returns

    Returns an iterator of type Iter[X] that repeats the element x indefinitely.

    Iter::singleton

    fn[X] Iter::singleton(elem : X) -> Iter[X]

    Creates an iterator that contains a single element.

    Prefer the iterator literal [|elem|], which is equivalent and shorter.

    Type Parameters

    • X: The type of the element in the iterator.

    Arguments

    • elem: The single element to be contained in the iterator.

    Returns

    Returns an iterator of type Iter[X] that contains the single element elem.

    Iter::size_hint

    fn[X] Iter::size_hint(self : Iter[X]) -> Int?

    Returns the hinted number of remaining elements if it is known.

    The hint is intended to be exact for iterators produced by trusted collection APIs and adapters, but it must not be used for correctness.

    Iter::take

    fn[X] Iter::take(self : Iter[X], n : Int) -> Iter[X]

    Takes the first n elements from the iterator.

    Type Parameters

    • X: The type of the elements in the iterator.

    Arguments

    • self - The input iterator.
    • n - The number of elements to take.

    Returns

    A new iterator that contains the first n elements.

    Note

    The old iterator self must not be used again after calling take.

    Iter::take_while

    fn[X] Iter::take_while(self : Iter[X], f : (X) -> Bool) -> Iter[X]

    Takes elements from the iterator as long as the predicate function returns true.

    Type Parameters

    • X: The type of the elements in the iterator.

    Arguments

    • self - The input iterator.
    • f - The predicate function that determines whether an element should be taken.

    Returns

    A new iterator that contains the elements as long as the predicate function returns true.

    Note

    The old iterator self must not be used again after calling take_while.

    Iter::tap

    fn[X] Iter::tap(self : Iter[X], f : (X) -> Unit) -> Iter[X]

    Applies a function to each element of the iterator without modifying the iterator.

    Type Parameters

    • X: The type of the elements in the iterator.

    Arguments

    • self - The input iterator.
    • f - The function to apply to each element of the iterator.

    Returns

    The same iterator.

    Note

    The old iterator self must not be used again after calling tap.

    Iter::to_array

    #alias(collect)
    fn[X] Iter::to_array(self : Iter[X]) -> Array[X]

    Collects the elements of the iterator into an array. The old iterator self must not be used again.

    Iter::to_json

    fn[X : ToJson] Iter::to_json(self : Iter[X]) -> Json

    Iter::view

    #alias(sub, deprecated="Use _[_:_] instead")
    #alias("_[_:_]")
    fn[X] Iter::view(self : Iter[X], start? : Int, end? : Int) -> Iter[X]

    Return a sliced iterator view in range [start, end). Function view.

    Iter::zip

    #alias(combine)
    fn[X, Y] Iter::zip(self : Iter[X], other : Iter[Y]) -> Iter[(X, Y)]

    Combines two iterators element-wise into an iterator of pairs.

    The resulting iterator stops as soon as either input iterator is exhausted.

    Type Parameters

    • X: The element type of self.
    • Y: The element type of other.

    Arguments

    • self - The first input iterator.
    • other - The second input iterator.

    Returns

    Returns a new iterator yielding tuples (x, y) where x comes from self and y comes from other.

    Example

    test {
    let numbers = (1).until(5)
    let letters = "a", "b", "c"
    debug_inspect(
    numbers.zip(letters).collect(),
    content="[(1, \"a\"), (2, \"b\"), (3, \"c\")]",
    )
    }

    Note

    The old iterators self and other must not be used again after calling zip.

    Iter2

    #alias(Iterator2, deprecated="The name `Iterator2` is deprecated, use `Iter2` instead. Note that if you have defined `iterator2()` method to support `for .. in` loop, you should also rename `iterator2()` to `iter2()`. See https://github.com/moonbitlang/core/pull/3127 for more details.")
    pub(all) struct Iter2[X, Y](Iter[(X, Y)])

    This type is used for for _, _ in .. loop (for .. in loop with two loop variables), and should not be used directly in general.

    Iter2::concat

    fn[X, Y] Iter2::concat(self : Iter2[X, Y], other : Iter2[X, Y]) -> Iter2[X, Y]

    Concatenate two Iter2 streams.

    Iter2::each

    fn[X, Y] Iter2::each(self : Iter2[X, Y], f : (X, Y) -> Unit) -> Unit

    Apply callback to each pair.

    Iter2::iter

    #alias(iterator)
    fn[X, Y] Iter2::iter(self : Iter2[X, Y]) -> Iter[(X, Y)]

    Convert to plain iterator of pairs. Return an iterator via iter.

    Iter2::iter2

    #alias(iterator2)
    fn[X, Y] Iter2::iter2(self : Iter2[X, Y]) -> Iter2[X, Y]

    Return this two-variable iterator itself. Return an iterator via iter2.

    Iter2::new

    fn[X, Y] Iter2::new(f : () -> (X, Y)?, size_hint? : Int) -> Iter2[X, Y]

    Construct an Iter2 from a pair-producing function. If the number of remaining pairs is known, pass it as size_hint.

    Iter2::next

    fn[X, Y] Iter2::next(self : Iter2[X, Y]) -> (X, Y)?

    Get the next pair from the iterator.

    Iter2::to_array

    fn[X, Y] Iter2::to_array(self : Iter2[X, Y]) -> Array[(X, Y)]

    Collect all pairs into an array.

    Json

    pub enum Json {
    Null
    True
    False
    Number(Double, repr~ : String?)
    String(String)
    Array(Array[Json])
    Object(Map[String, Json])
    }

    JSON value type used by core serialization APIs.

    Example:

    test {
    let value : Json = Json::array([Json::number(1.0), Json::null()])
    inspect(value.stringify(), content="[1,null]")
    }
    impl Default for Json
    impl Eq for Json

    Json::Json

    fn[T : ToJson] Json::Json(value : T) -> Json

    Converts any value implementing ToJson into a Json.

    This is the constructor of Json, so it is written Json(value), and it is re-exported by the prelude — no import is needed. Prefer it over calling ToJson::to_json directly.

    Parameters:

    • value : The value to convert.

    Returns the Json representation of value.

    Example:

    test {
    @debug.debug_inspect(Json(42), content="Number(42)")
    @debug.debug_inspect(Json("hello"), content="String(\"hello\")")
    @debug.debug_inspect(Json([1, 2]), content="Array([Number(1), Number(2)])")
    }

    Json::array

    fn Json::array(array : Array[Json]) -> Json

    Creates a JSON array value from a MoonBit array.

    Parameters:

    • values : An array of JSON values to be converted to a JSON array value.

    Returns a JSON value representing the given array.

    Example:

    test {
    let values : Array[Json] = [1.0, "hello"]
    @debug.debug_inspect(
    Json::array(values),
    content="Array([Number(1), String(\"hello\")])",
    )
    }

    Json::boolean

    fn Json::boolean(boolean : Bool) -> Json

    Creates a JSON boolean value from a MoonBit boolean.

    Parameters:

    • boolean : A MoonBit boolean to be converted to a JSON boolean value.

    Returns a JSON value representing the given boolean.

    Example:

    test {
    @debug.debug_inspect(Json::boolean(true), content="True")
    @debug.debug_inspect(Json::boolean(false), content="False")
    }

    Json::empty_object

    fn Json::empty_object() -> Json

    JSON {} constant.

    Json::equal

    fn Json::equal(a : Json, b : Json) -> Bool

    Json::null

    fn Json::null() -> Json

    Creates a JSON null value.

    Returns a JSON value representing null.

    Json::number

    fn Json::number(number : Double, repr? : String) -> Json

    Creates a JSON number value from a double-precision floating-point number.

    Parameters:

    • value : A double-precision floating-point number to be converted to a JSON number.

    Returns a JSON value representing the given number.

    Example:

    test {
    @debug.debug_inspect(Json::number(3.14), content="Number(3.14)")
    inspect(
    Json::number(@double.infinity, repr="1e9999999999999999999999999999999").stringify(),
    content="1e9999999999999999999999999999999",
    )
    }

    Json::object

    fn Json::object(object : Map[String, Json]) -> Json

    Creates a JSON object value from a MoonBit map.

    Parameters:

    • map : A map from strings to JSON values to be converted to a JSON object value.

    Returns a JSON value representing the given map.

    Example:

    test {
    let map : Map[String, Json] = { "name": "John", "age": 42.0 }
    @debug.debug_inspect(
    Json::object(map),
    content="Object({ \"name\": String(\"John\"), \"age\": Number(42) })",
    )
    }

    Json::string

    fn Json::string(string : String) -> Json

    Creates a JSON string value from a MoonBit string.

    Parameters:

    • string : A MoonBit string to be converted to a JSON string value.

    Returns a JSON value representing the given string.

    Example:

    test {
    @debug.debug_inspect(Json::string("hello"), content="String(\"hello\")")
    }

    Map

    type Map[K, V]

    Mutable linked hash map that maintains the order of insertion, not thread safe.

    Example

    test {
    let map = { 3: "three", 8: "eight", 1: "one" }
    @test.assert_eq(map.get(2), None)
    @test.assert_eq(map.get(3), Some("three"))
    map.set(3, "updated")
    @test.assert_eq(map.get(3), Some("updated"))
    }
    impl Default for Map[K, V]
    impl Eq for Map[K, V]
    impl Show for Map[K, V]
    impl ToJson for Map[K, V]

    Map::Map

    #alias(from_array)
    fn[K : Hash + Eq, V] Map::Map(arr : ArrayView[(K, V)], capacity? : Int) -> Map[K, V]

    Create a hash map from an array. The optional capacity is treated as a minimum initial capacity and will be rounded up to the smallest power of 2 that can hold the requested capacity.

    Map::at

    #alias("_[_]")
    fn[K : Hash + Eq, V] Map::at(self : Map[K, V], key : K) -> V

    Get value with at access semantics.

    Map::capacity

    fn[K, V] Map::capacity(self : Map[K, V]) -> Int

    Get the capacity of the map.

    Map::clear

    fn[K, V] Map::clear(self : Map[K, V]) -> Unit

    Clears the map, removing all key-value pairs. Keeps the allocated space.

    Map::contains

    fn[K : Hash + Eq, V] Map::contains(self : Map[K, V], key : K) -> Bool

    Check if the hash map contains a key.

    Map::contains_kv

    fn[K : Hash + Eq, V : Eq] Map::contains_kv(self : Map[K, V], key : K, value : V) -> Bool

    Checks if a map contains a specific key-value pair.

    Parameters:

    • map : A map of type Map[K, V] to search in.
    • key : The key to look up in the map.
    • value : The value to be compared with the value associated with the key.

    Returns true if the map contains the specified key and its associated value equals the given value, false otherwise.

    Example:

    test {
    let map = { "a": 1, "b": 2 }
    inspect(map.contains_kv("a", 1), content="true")
    inspect(map.contains_kv("a", 2), content="false")
    inspect(map.contains_kv("c", 3), content="false")
    }

    Map::copy

    #alias(clone, deprecated="`clone` is deprecated, use `copy` instead")
    fn[K, V] Map::copy(self : Map[K, V]) -> Map[K, V]

    Copy the map, creating a new map with the same key-value pairs and order of insertion.

    Map::each

    fn[K, V] Map::each(self : Map[K, V], f : (K, V) -> Unit raise?) -> Unit raise?

    Iterate over all key-value pairs of the map in the order of insertion.

    Map::eachi

    fn[K, V] Map::eachi(self : Map[K, V], f : (Int, K, V) -> Unit raise?) -> Unit raise?

    Iterate over all key-value pairs of the map in the order of insertion, with index.

    Map::equal

    fn[K : Hash + Eq, V : Eq] Map::equal(self : Map[K, V], that : Map[K, V]) -> Bool

    Map::from_iter

    #alias(from_iterator, deprecated="`from_iterator` is deprecated, use `from_iter` instead")
    fn[K : Hash + Eq, V] Map::from_iter(iter : Iter[(K, V)]) -> Map[K, V]

    Create from iter.

    Map::get

    fn[K : Hash + Eq, V] Map::get(self : Map[K, V], key : K) -> V?

    Retrieves the value associated with a given key in the hash map.

    Parameters:

    • self : The hash map to search in.
    • key : The key to look up in the map.

    Returns Some(value) if the key exists in the map, None otherwise.

    Example:

    test {
    let map = { "key": 42 }
    debug_inspect(map.get("key"), content="Some(42)")
    debug_inspect(map.get("nonexistent"), content="None")
    }

    Map::get_from_bytes

    fn[V] Map::get_from_bytes(map : Map[Bytes, V], key : BytesView) -> V?

    Retrieves the value associated with a BytesView key in a map with Bytes keys.

    This function allows efficient lookups using BytesView without creating a new Bytes object. It's particularly useful when working with byte slices or subranges of existing byte arrays.

    Parameters:

    • map : The hash map with Bytes keys to search in.
    • key : A BytesView representing the key to look up.

    Returns Some(value) if a matching key exists in the map, None otherwise.

    Example:

    test {
    let map = { b"hello": 1, b"world": 2 }
    let bytes = b"prefix_hello_suffix"
    let view = bytes[7:12] // view of "hello"
    debug_inspect(map.get_from_bytes(view), content="Some(1)")
    }

    Map::get_from_string

    fn[V] Map::get_from_string(map : Map[String, V], key : StringView) -> V?

    Retrieves the value associated with a StringView key in a map with String keys.

    This function allows efficient lookups using StringView without creating a new String object. It's particularly useful when working with substrings or string slices.

    Parameters:

    • map : The hash map with String keys to search in.
    • key : A StringView representing the key to look up.

    Returns Some(value) if a matching key exists in the map, None otherwise.

    Example:

    test {
    let map = { "hello": 1, "world": 2 }
    let str = "say hello to everyone"
    let view = str.view(start_offset=4, end_offset=9) // view of "hello"
    debug_inspect(map.get_from_string(view), content="Some(1)")
    }

    Map::get_or_default

    fn[K : Hash + Eq, V] Map::get_or_default(self : Map[K, V], key : K, default : V) -> V

    Returns the value associated with the key in the map, or computes and returns a default value if the key does not exist.

    Parameters:

    • map : The map to search in.
    • key : The key to look up in the map.
    • default : A function that returns a default value when the key is not found.

    Returns either the value associated with the key if it exists, or the result of calling the default function.

    Example:

    test {
    let map = { "a": 1, "b": 2 }
    inspect(map.get_or_default("a", 0), content="1")
    inspect(map.get_or_default("c", 42), content="42")
    }

    Map::get_or_init

    fn[K : Hash + Eq, V] Map::get_or_init(self : Map[K, V], key : K, default : () -> V) -> V

    Returns the value for the given key, or sets and returns a default value if the key does not exist.

    Map::is_empty

    fn[K, V] Map::is_empty(self : Map[K, V]) -> Bool

    Check if the hash map is empty.

    Map::iter

    #alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
    fn[K, V] Map::iter(self : Map[K, V]) -> Iter[(K, V)]

    Returns the iterator of the hash map, provide elements in the order of insertion.

    Map::iter2

    #alias(iterator2, deprecated="`iterator2` is deprecated, use `iter2` instead")
    fn[K, V] Map::iter2(self : Map[K, V]) -> Iter2[K, V]

    Return an iterator via iter2.

    Map::keys

    fn[K, V] Map::keys(self : Map[K, V]) -> Iter[K]

    Return an iterator of keys.

    Map::length

    #alias(size, deprecated="`size` is deprecated, use `length` instead")
    fn[K, V] Map::length(self : Map[K, V]) -> Int

    Get the number of key-value pairs in the map.

    Map::map

    fn[K, V, V2] Map::map(self : Map[K, V], f : (K, V) -> V2) -> Map[K, V2]

    Applies a function to each key-value pair in the map and returns a new map with the results, using the original keys.

    Map::merge

    fn[K : Eq, V] Map::merge(self : Map[K, V], other : Map[K, V]) -> Map[K, V]

    Merges two maps into a new map. Returns a new map containing all key-value pairs from both maps. When both maps contain the same key, the value from other takes precedence. The iteration order follows the order of self followed by new entries from other.

    This is a pure operation - it does not modify either of the input maps.

    Parameters:

    • self : The first map.
    • other : The second map whose values take precedence in case of key conflicts.

    Returns a new linked hash map containing all entries from both maps.

    Example:

    test {
    let map1 : Map[String, Int] = { "a": 1, "b": 2 }
    let map2 : Map[String, Int] = { "b": 3, "c": 4 }
    let merged = map1.merge(map2)
    @json.json_inspect(merged, content={ "a": 1, "b": 3, "c": 4 })
    }

    Map::merge_in_place

    fn[K : Eq, V] Map::merge_in_place(self : Map[K, V], other : Map[K, V]) -> Unit

    Merges another map into this map in-place. Updates the current map by adding all key-value pairs from other. When both maps contain the same key, the value from other overwrites the value in this map. New entries from other are added at the end, preserving the original order of self and appending new keys from other.

    This is a mutating operation - it modifies the receiver map.

    Parameters:

    • self : The map to be modified.
    • other : The map whose entries will be added to self.

    Example:

    test {
    let map1 : Map[String, Int] = { "a": 1, "b": 2 }
    let map2 : Map[String, Int] = { "b": 3, "c": 4 }
    map1.merge_in_place(map2)
    @json.json_inspect(map1, content={ "a": 1, "b": 3, "c": 4 })
    }

    Map::new

    #deprecated("Use `Map([], capacity=...)` instead")
    fn[K, V] Map::new(capacity? : Int) -> Map[K, V]

    Create a hash map. The capacity of the map will be the smallest power of 2 that is greater than or equal to the provided [capacity].

    Deprecated: use Map([], capacity=...) instead.

    Map::of

    #deprecated("Use `Map([(k, v), ...])` or `Map::from_array` instead")
    fn[K : Hash + Eq, V] Map::of(arr : FixedArray[(K, V)]) -> Map[K, V]

    Function of.

    Map::remove

    fn[K : Hash + Eq, V] Map::remove(self : Map[K, V], key : K) -> Unit

    Removes the entry for the specified key from the hash map. If the key exists in the map, removes its entry and adjusts the probe sequence length (PSL) of subsequent entries to maintain the Robin Hood hashing invariant. If the key does not exist, the map remains unchanged.

    Parameters:

    • self : The hash map to remove the entry from.
    • key : The key to remove from the map.

    Example:

    test {
    let map = { "a": 1, "b": 2 }
    map.remove("a")
    debug_inspect(map.get("a"), content="None")
    inspect(map.length(), content="1")
    }

    Map::retain

    fn[K, V] Map::retain(self : Map[K, V], f : (K, V) -> Bool) -> Unit

    Retains only the key-value pairs that satisfy the given predicate function. This method modifies the map in-place, removing all entries for which the predicate returns false. The order of remaining elements is preserved.

    Parameters:

    • self : The map to be filtered.
    • predicate : A function that takes a key and value as arguments and returns true if the key-value pair should be kept, false if it should be removed.

    Example:

    test {
    let map = { "a": 1, "b": 2, "c": 3, "d": 4 }
    map.retain((_k, v) => v % 2 == 0) // Keep only even values
    inspect(map.length(), content="2")
    debug_inspect(map.get("a"), content="None")
    debug_inspect(map.get("b"), content="Some(2)")
    debug_inspect(map.get("c"), content="None")
    debug_inspect(map.get("d"), content="Some(4)")
    }

    Map::set

    #alias("_[_]=_")
    fn[K : Hash + Eq, V] Map::set(self : Map[K, V], key : K, value : V) -> Unit

    Sets a key-value pair into the hash map. If the key already exists, updates its value. If the hash map is near full capacity, automatically grows the internal storage to accommodate more entries.

    Parameters:

    • map : The hash map to modify.
    • key : The key to insert or update. Must implement Hash and Eq traits.
    • value : The value to associate with the key.

    Example:

    test {
    let map : Map[String, Int] = Map([])
    map.set("key", 42)
    debug_inspect(map.get("key"), content="Some(42)")
    map.set("key", 24) // update existing key
    debug_inspect(map.get("key"), content="Some(24)")
    }

    Map::to_array

    fn[K, V] Map::to_array(self : Map[K, V]) -> Array[(K, V)]

    Converts the hash map to an array.

    Map::to_json

    fn[K : Show, V : ToJson] Map::to_json(self : Map[K, V]) -> Json

    Map::update

    fn[K : Hash + Eq, V] Map::update(self : Map[K, V], key : K, f : (V?) -> V?) -> Unit

    Updates a value in the map based on the existing value.

    This method allows you to conditionally update, insert, or remove a key-value pair based on whether the key already exists in the map. The provided function f is called with Some(current_value) if the key exists, or None if it doesn't.

    Parameters:

    • self : The map to update.
    • key : The key to update.
    • f : A function that takes the current value (wrapped in Option) and returns the new value (wrapped in Option). Returning None will remove the key-value pair from the map.

    Behavior:

    • If the key exists and f returns Some(new_value), the value is updated.
    • If the key exists and f returns None, the key-value pair is removed.
    • If the key doesn't exist and f returns Some(new_value), a new pair is inserted.
    • If the key doesn't exist and f returns None, no operation is performed.

    Example:

    test {
    let map = { "a": 1, "b": 2 }

    // Update existing value
    map.update("a", fn(v) {
    match v {
    Some(x) => Some(x + 10)
    None => Some(0)
    }
    })
    debug_inspect(
    map,
    content=(
    #|{ "a": 11, "b": 2 }
    ),
    )

    // Insert new value
    map.update("c", fn(v) {
    match v {
    Some(x) => Some(x)
    None => Some(3)
    }
    })
    debug_inspect(
    map,
    content=(
    #|{ "a": 11, "b": 2, "c": 3 }
    ),
    )

    // Remove existing value
    map.update("b", fn(_) { None })
    debug_inspect(
    map,
    content=(
    #|{ "a": 11, "c": 3 }
    ),
    )
    }

    Map::update_or_default

    fn[K : Hash + Eq, V] Map::update_or_default(self : Map[K, V], key : K, default : V, f : (V) -> V) -> Unit

    Inserts default for key if it is absent, otherwise replaces the existing value with f(existing). The pairing of an eager default value with a modifier function lets the canonical counter pattern read literally:

    test {
    let counts : Map[String, Int] = Map([])
    counts.update_or_default("a", 1, x => x + 1)
    counts.update_or_default("a", 1, x => x + 1)
    counts.update_or_default("b", 1, x => x + 1)
    debug_inspect(counts.get("a"), content="Some(2)")
    debug_inspect(counts.get("b"), content="Some(1)")
    }

    Note: f is not applied to default on first insertion — default is the value stored when the key is absent. This mirrors Java's Map.merge and Rust's Entry::and_modify(f).or_insert(default).

    Map::values

    fn[K, V] Map::values(self : Map[K, V]) -> Iter[V]

    Return an iterator of values.

    MutArrayView

    type MutArrayView[T]

    A MutArrayView represents a view into a section of an array without copying the data. The view provides read-write access to elements of the underlying array.

    Example

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr.mut_view(start=1, end=4) // Creates a view of elements at indices 1,2,3
    @test.assert_eq(view[0], 2)
    @test.assert_eq(view.length(), 3)
    }
    impl Compare for MutArrayView[T]
    impl Eq for MutArrayView[T]
    impl Hash for MutArrayView[A]
    impl Show for MutArrayView[X]

    MutArrayView::at

    #alias("_[_]")
    fn[T] MutArrayView::at(self : MutArrayView[T], index : Int) -> T

    Retrieves an element at the specified index from the mutable array view.

    Parameters:

    • self : The mutable array view to access.
    • index : The position in the array view from which to retrieve the element.

    Returns the element at the specified index.

    Throws a runtime error if the index is out of bounds (less than 0 or greater than or equal to the length of the array view).

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr.mut_view(start=2, end=4)
    inspect(view[0], content="3")
    inspect(view[1], content="4")
    }

    MutArrayView::compare

    fn[T : Compare + Eq] MutArrayView::compare(self : MutArrayView[T], other : MutArrayView[T]) -> Int

    MutArrayView::equal

    fn[T : Eq] MutArrayView::equal(self : MutArrayView[T], other : MutArrayView[T]) -> Bool

    MutArrayView::hash

    fn[A : Hash] MutArrayView::hash(self : MutArrayView[A]) -> Int

    MutArrayView::is_empty

    fn[T] MutArrayView::is_empty(self : MutArrayView[T]) -> Bool

    Returns whether the mutable array view is empty.

    Example:

    test {
    let view = [1, 2, 3].mut_view(start=1, end=1)
    inspect(view.is_empty(), content="true")
    }

    MutArrayView::iter

    #alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
    fn[X] MutArrayView::iter(self : MutArrayView[X]) -> Iter[X]

    Return an iterator via iter.

    MutArrayView::iter2

    #alias(iterator2, deprecated="`iterator2` is deprecated, use `iter2` instead")
    fn[X] MutArrayView::iter2(self : MutArrayView[X]) -> Iter2[Int, X]

    Return an iterator via iter2.

    MutArrayView::length

    fn[T] MutArrayView::length(self : MutArrayView[T]) -> Int

    Returns the length (number of elements) of a mutable array view.

    Parameters:

    • array_view : The mutable array view whose length is to be determined.

    Returns an integer representing the number of elements in the mutable array view.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr.mut_view(start=2, end=4)
    inspect(view.length(), content="2")
    }

    MutArrayView::mut_view

    fn[T] MutArrayView::mut_view(self : MutArrayView[T], start? : Int, end? : Int) -> MutArrayView[T]

    Creates a new mutable view into a portion of the mutable array view.

    Parameters:

    • self : The mutable array view to create a new view from.
    • start : The starting index in the current view (inclusive). Defaults to
    • end : The ending index in the current view (exclusive). Defaults to the length of the current view.

    Returns a new MutArrayView that provides a window into the specified portion of the original mutable array view. The indices are relative to the start of the current view.

    Throws a panic if:

    • start is negative
    • end is greater than the length of the current view
    • start is greater than end

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr.mut_view(start=1, end=4) // view = [2, 3, 4]
    let subview = view.mut_view(start=1, end=2) // subview = [3]
    inspect(subview[0], content="3")
    }

    MutArrayView::rev_iter

    #alias(rev_iterator, deprecated="`rev_iterator` is deprecated, use `rev_iter` instead")
    fn[X] MutArrayView::rev_iter(self : MutArrayView[X]) -> Iter[X]

    Function rev_iter.

    MutArrayView::set

    #alias("_[_]=_")
    fn[T] MutArrayView::set(self : MutArrayView[T], index : Int, value : T) -> Unit

    Sets an element at the specified index in the mutable array view.

    Parameters:

    • self : The mutable array view to modify.
    • index : The position in the array view at which to set the element.
    • value : The value to set at the specified index.

    Throws a runtime error if the index is out of bounds (less than 0 or greater than or equal to the length of the array view).

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr.mut_view(start=2, end=4)
    view[0] = 10
    inspect(view[0], content="10")
    inspect(arr[2], content="10")
    }

    MutArrayView::sort

    fn[T : Compare + Eq] MutArrayView::sort(self : MutArrayView[T]) -> Unit

    Sorts the array in place.

    It's an in-place, unstable sort(it will reorder equal elements). The time complexity is O(n log n) in the worst case.

    Example

    test {
    let arr = [5, 4, 3, 2, 1]
    arr.mut_view().sort()
    @test.assert_eq(arr, [1, 2, 3, 4, 5])
    }

    MutArrayView::sort_by

    fn[T] MutArrayView::sort_by(self : MutArrayView[T], cmp : (T, T) -> Int) -> Unit

    Sorts the array with a custom comparison function.

    It's an in-place, unstable sort(it will reorder equal elements). The time complexity is O(n log n) in the worst case.

    Example

    test {
    let arr = [5, 3, 2, 4, 1]
    arr.mut_view().sort_by((a, b) => a - b)
    @test.assert_eq(arr, [1, 2, 3, 4, 5])
    }

    MutArrayView::sort_by_key

    fn[T, K : Compare + Eq] MutArrayView::sort_by_key(self : MutArrayView[T], map : (T) -> K) -> Unit

    Sorts the array with a key extraction function.

    It's an in-place, unstable sort(it will reorder equal elements). The time complexity is O(n log n) in the worst case.

    Example

    test {
    let arr = [5, 3, 2, 4, 1]
    arr.mut_view().sort_by_key(x => -x)
    @test.assert_eq(arr, [5, 4, 3, 2, 1])
    }

    MutArrayView::stable_sort

    fn[T : Compare + Eq] MutArrayView::stable_sort(self : MutArrayView[T]) -> Unit

    Sorts the array

    It's an stable sort(it will not reorder equal elements). The time complexity is O(n * log(n)) in the worst case.

    Example

    test {
    let arr : FixedArray[Int] = [5, 4, 3, 2, 1]
    arr.mut_view().stable_sort()
    @test.assert_eq(arr, [1, 2, 3, 4, 5])
    }

    MutArrayView::start_offset

    fn[T] MutArrayView::start_offset(self : MutArrayView[T]) -> Int

    Returns the start offset of the mutable array view in its backing array.

    MutArrayView::to_owned

    #alias(to_array, deprecated="`to_array` is deprecated, use `to_owned` instead")
    fn[T] MutArrayView::to_owned(self : MutArrayView[T]) -> Array[T]

    Copies the elements of the mutable array view into a newly allocated Array.

    MutArrayView::unsafe_get

    #internal(unsafe, "Panic if index is out of bounds")
    fn[T] MutArrayView::unsafe_get(self : MutArrayView[T], index : Int) -> T

    Retrieves an element from the mutable array view at the specified index without performing bounds checking.

    Parameters:

    • array_view : The mutable array view to retrieve the element from.
    • index : The position in the array view from which to retrieve the element.

    Returns the element at the specified index in the array view.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr.mut_view(start=1, end=4)
    inspect(view.unsafe_get(1), content="3")
    }

    MutArrayView::unsafe_set

    #internal(unsafe, "Panic if index is out of bounds")
    fn[T] MutArrayView::unsafe_set(self : MutArrayView[T], index : Int, value : T) -> Unit

    Sets an element at the specified index in the mutable array view without performing bounds checking.

    Parameters:

    • self : The mutable array view to modify.
    • index : The position in the array view at which to set the element.
    • value : The value to set at the specified index.

    Example:

    test {
    let arr = [1, 2, 3, 4, 5]
    let view = arr.mut_view(start=1, end=4)
    view.unsafe_set(1, 10)
    inspect(view[1], content="10")
    }

    MutArrayView::view

    #alias(sub, deprecated="Use _[_:_] instead")
    #alias("_[_:_]")
    fn[T] MutArrayView::view(self : MutArrayView[T], start? : Int, end? : Int) -> ArrayView[T]

    Creates a new ArrayView from a MutArrayView.

    Parameters:

    • self : The mutable array view to create a new view from.
    • start : The starting index in the current view (inclusive). Defaults to
    • end : The ending index in the current view (exclusive). Defaults to the length of the current view.

    SourceLoc

    pub(all) type SourceLoc

    Represents a source code location in a MoonBit program, containing information about the file path, line number, and column number. Used internally by the compiler for error reporting and debugging purposes.

    This type is public to all packages but its internal representation is opaque. Users cannot construct values of this type directly; they are automatically created by the compiler when needed. TODO: can not make a dummy loc
    impl Show for SourceLoc

    SourceLoc::to_json_string

    fn SourceLoc::to_json_string(self : SourceLoc) -> String

    Convert a source location to a JSON string

    SourceLoc::to_string

    fn SourceLoc::to_string(self : SourceLoc) -> String

    StringBuilder

    type StringBuilder

    StringBuilder::StringBuilder

    #alias(new, deprecated="Use `StringBuilder()` instead")
    fn StringBuilder::StringBuilder(size_hint? : Int) -> StringBuilder

    Creates a new string builder with an optional initial capacity hint.

    Parameters:

    • size_hint : An optional initial capacity hint for the internal buffer. If less than 1, a minimum capacity of 1 is used. Defaults to 0. It is the size of bytes, not the size of characters. size_hint may be ignored on some platforms, JS for example.

    Returns a new StringBuilder instance with the specified initial capacity.

    StringBuilder::is_empty

    fn StringBuilder::is_empty(self : StringBuilder) -> Bool

    Return whether the given buffer is empty.

    StringBuilder::reset

    fn StringBuilder::reset(self : StringBuilder) -> Unit

    Resets the string builder to an empty state.

    StringBuilder::to_string

    fn StringBuilder::to_string(self : StringBuilder) -> String

    Returns the current content of the StringBuilder as a string.

    StringBuilder::write_char

    fn StringBuilder::write_char(self : StringBuilder, ch : Char) -> Unit

    StringBuilder::write_iter

    fn StringBuilder::write_iter(self : StringBuilder, iter : Iter[Char]) -> Unit

    Writes characters from an iterator to the StringBuilder.

    Parameters:

    • self : The StringBuilder to write to.
    • iter : An iterator yielding characters to write.

    Example:

    test {
    let sb = StringBuilder()
    let chars = "Hello🤣".iter()
    sb.write_iter(chars)
    @test.assert_eq(sb.to_string(), "Hello🤣")
    }

    StringBuilder::write_object

    #alias(write_string_interpolation)
    #alias(write)
    fn[T : Show] StringBuilder::write_object(self : StringBuilder, obj : T) -> Unit

    Writes the string representation of an object to the StringBuilder.

    StringBuilder::write_string

    fn StringBuilder::write_string(self : StringBuilder, str : String) -> Unit

    StringBuilder::write_stringview

    fn StringBuilder::write_stringview(self : StringBuilder, view : StringView) -> Unit

    Writes a StringView to the StringBuilder.

    This is more efficient than converting the StringView to a String first, as it directly writes the viewed portion without creating intermediate strings.

    Parameters:

    • self : The StringBuilder to write to.
    • view : The StringView to write.

    Example:

    test {
    let sb = StringBuilder()
    let str = "Hello, world!"
    let view = str[7:12] // "world"
    sb.write_stringview(view)
    @test.assert_eq(sb.to_string(), "world")
    }

    StringBuilder::write_substring

    fn StringBuilder::write_substring(self : StringBuilder, value : String, start : Int, len : Int) -> Unit

    StringBuilder::write_view

    fn StringBuilder::write_view(self : StringBuilder, str : StringView) -> Unit

    UninitializedArray

    type UninitializedArray[T]

    UninitializedArray::at

    #alias("_[_]")
    fn[T] UninitializedArray::at(self : UninitializedArray[T], index : Int) -> T

    Retrieves the element at the specified index from an uninitialized array.

    Parameters:

    • array : The uninitialized array from which to retrieve the element.
    • index : The index of the element to retrieve.

    Returns the element at the specified index.

    UninitializedArray::length

    fn[A] UninitializedArray::length(self : UninitializedArray[A]) -> Int

    Returns the length of an uninitialized array.

    Parameters:

    • array : The uninitialized array whose length is to be determined.

    Returns the length of the uninitialized array as an integer.

    UninitializedArray::make

    fn[T] UninitializedArray::make(size : Int) -> UninitializedArray[T]

    Creates an uninitialized array of the specified size.

    Parameters:

    • size : The number of elements the array should hold.

    Returns an uninitialized array of type T with the specified size.

    UninitializedArray::make_and_blit

    fn[T] UninitializedArray::make_and_blit(src : UninitializedArray[T], allocate_len~ : Int, len~ : Int, src_offset? : Int, dst_offset? : Int) -> UninitializedArray[T]

    Checked variant of unsafe_make_and_blit.

    UninitializedArray::set

    #alias("_[_]=_")
    fn[T] UninitializedArray::set(self : UninitializedArray[T], index : Int, value : T) -> Unit

    Sets the value at the specified index in an uninitialized array.

    Parameters:

    • array : The uninitialized array where the value will be set.
    • index : The position in the array where the value will be set.
    • value : The value to be set at the specified index.

    UninitializedArray::sub

    #alias("_[_:_]")
    fn[T] UninitializedArray::sub(self : UninitializedArray[T], start? : Int, end? : Int) -> ArrayView[T]

    Creates a view into a portion of the uninitialized array.

    Parameters:

    • array : The uninitialized array to create a view from.
    • start : The starting index of the view (inclusive). Defaults to 0.
    • end : The ending index of the view (exclusive). If not provided, defaults to the length of the array.

    Returns an ArrayView that provides a window into the specified portion of the array.

    Throws an error if the indices are out of bounds or if start is greater than end.

    Bool

    Note

    Bool is a built-in type. The documentation may not be complete here. You can find all methods and implementations in the core/builtin and core/bool package.

    Bool::compare

    fn Bool::compare(self : Bool, other : Bool) -> Int

    Bool::equal

    fn Bool::equal(self : Bool, other : Bool) -> Bool

    Bool::hash

    fn Bool::hash(self : Bool) -> Int

    Bool::op_compare

    #deprecated("Use `compare` instead")
    fn Bool::op_compare(self : Bool, other : Bool) -> Int

    Compares two boolean values and returns their relative order. This is a deprecated method and users should use compare instead.

    Parameters:

    • self : The first boolean value to compare.
    • other : The second boolean value to compare against.

    Returns an integer indicating the relative order:

    • A negative value if self is less than other (i.e., self is false and other is true)
    • Zero if self equals other
    • A positive value if self is greater than other (i.e., self is true and other is false)

    Example:

    test {
    let t = true
    let f = false
    // This usage is deprecated, use compare() instead
    inspect(t.compare(f), content="1")
    inspect(f.compare(t), content="-1")
    inspect(t.compare(t), content="0")
    }

    Bool::to_int

    fn Bool::to_int(self : Bool) -> Int

    Converts a boolean value to its integer representation.

    Parameters:

    • self : The boolean value to convert.

    Returns 1 if the boolean is true, 0 if it is false.

    Example:

    test {
    inspect(true.to_int(), content="1")
    inspect(false.to_int(), content="0")
    }

    Bool::to_int16

    fn Bool::to_int16(self : Bool) -> Int16

    Converts a boolean value to a 16-bit integer representation.

    Parameters:

    • self : The boolean value to be converted.

    Returns a 16-bit integer, where true is converted to 1 and false is converted to 0.

    Example:

    test {
    inspect(true.to_int16(), content="1")
    inspect(false.to_int16(), content="0")
    }

    Bool::to_int64

    fn Bool::to_int64(self : Bool) -> Int64

    Converts a boolean value to a 64-bit integer. Returns 1 for true and 0 for false.

    Parameters:

    • bool : The boolean value to be converted.

    Returns a 64-bit integer representation of the boolean value.

    Example:

    test {
    inspect(true.to_int64(), content="1")
    inspect(false.to_int64(), content="0")
    }

    Bool::to_json

    fn Bool::to_json(self : Bool) -> Json

    Bool::to_string

    fn Bool::to_string(self : Bool) -> String

    Bool::to_uint

    fn Bool::to_uint(self : Bool) -> UInt

    Converts a boolean value to an unsigned integer.

    Parameters:

    • value : The boolean value to be converted.

    Returns an unsigned integer, where true is converted to 1 and false is converted to 0.

    Example:

    test {
    inspect(true.to_uint(), content="1")
    inspect(false.to_uint(), content="0")
    }

    Bool::to_uint16

    fn Bool::to_uint16(self : Bool) -> UInt16

    Converts a boolean value to an unsigned 16-bit integer.

    Parameters:

    • self : The boolean value to be converted.

    Returns an unsigned 16-bit integer, where true is converted to 1 and false is converted to 0.

    Example:

    test {
    inspect(true.to_uint16(), content="1")
    inspect(false.to_uint16(), content="0")
    }

    Bool::to_uint64

    fn Bool::to_uint64(self : Bool) -> UInt64

    Converts a boolean value to an unsigned 64-bit integer. Returns 1 for true and 0 for false.

    Parameters:

    • bool : The boolean value to convert.

    Returns an unsigned 64-bit integer representation of the boolean value.

    Example:

    test {
    inspect(true.to_uint64(), content="1")
    inspect(false.to_uint64(), content="0")
    }

    Byte

    Note

    Byte is a built-in type. The documentation may not be complete here. You can find all methods and implementations in the core/builtin and core/byte package.

    Byte::Byte

    fn Byte::Byte(self : Byte) -> Byte

    The identity constructor for Byte, allowing values to be written using constructor syntax, e.g. Byte(3).

    Example:

    test {
    inspect(Byte(3), content="b'\\x03'")
    }

    Byte::add

    fn Byte::add(self : Byte, that : Byte) -> Byte

    Byte::compare

    fn Byte::compare(self : Byte, that : Byte) -> Int

    Byte::default

    fn Byte::default() -> Byte

    Byte::div

    fn Byte::div(self : Byte, that : Byte) -> Byte

    Byte::equal

    fn Byte::equal(self : Byte, that : Byte) -> Bool

    Byte::hash

    fn Byte::hash(self : Byte) -> Int

    Byte::land

    fn Byte::land(self : Byte, that : Byte) -> Byte

    Byte::lnot

    fn Byte::lnot(self : Byte) -> Byte

    Performs a bitwise NOT operation on the given Byte value.

    Parameters:

    • value : The Byte value to apply the bitwise NOT operation on.

    Returns the result of the bitwise NOT operation as a Byte.

    Byte::lor

    fn Byte::lor(self : Byte, that : Byte) -> Byte

    Byte::lsl

    #deprecated("Use infix operator `<<` instead")
    fn Byte::lsl(self : Byte, count : Int) -> Byte

    Shifts the bits of a Byte value to the left by the given number of bit positions.

    Parameters:

    • self : The Byte value whose bits are to be shifted.
    • count : The number of bit positions to shift self to the left.

    Returns the resulting Byte value after the bitwise left shift operation.

    Byte::lsr

    #deprecated("Use infix operator `>>` instead")
    fn Byte::lsr(self : Byte, count : Int) -> Byte

    Performs a logical (zero-filling) right shift of a Byte value by the given number of bits.

    Parameters:

    • self : The Byte value to be shifted.
    • count : The number of bits to shift self to the right.

    Returns the result of the logical shift right operation as a Byte.

    Byte::lxor

    fn Byte::lxor(self : Byte, that : Byte) -> Byte

    Byte::mod

    fn Byte::mod(self : Byte, that : Byte) -> Byte

    Byte::mul

    fn Byte::mul(self : Byte, that : Byte) -> Byte

    Byte::popcnt

    fn Byte::popcnt(self : Byte) -> Int

    Counts the number of 1-bits (population count) in the byte using bitwise operations.

    Parameters:

    • self : The byte value whose 1-bits are to be counted.

    Returns the number of 1-bits in the byte.

    Example:

    test {
    let b = b'\x0F'
    inspect(b.popcnt(), content="4")
    }

    Byte::shl

    fn Byte::shl(self : Byte, count : Int) -> Byte

    Byte::shr

    fn Byte::shr(self : Byte, count : Int) -> Byte

    Byte::sub

    fn Byte::sub(self : Byte, that : Byte) -> Byte

    Byte::to_char

    fn Byte::to_char(self : Byte) -> Char

    Converts a byte value to a character.

    Parameters:

    • byte : The byte value to be converted.

    Returns the character corresponding to the byte value.

    Byte::to_double

    fn Byte::to_double(self : Byte) -> Double

    TODO: use intrinsics implement this

    Byte::to_float

    #deprecated("Use `Float::from_byte` instead")
    fn Byte::to_float(self : Byte) -> Float

    Convert Byte to Float (deprecated alias). Convert to float.

    Byte::to_hex

    fn Byte::to_hex(b : Byte) -> String

    Convert a byte to a two-digit lowercase hexadecimal string.

    Example:

    test {
    inspect(Byte::to_hex(b'\x0f'), content="0f")
    }

    Byte::to_int

    fn Byte::to_int(self : Byte) -> Int

    Converts a byte value to a 32-bit signed integer. The resulting integer will have the same binary representation as the byte value, preserving the numerical value in the range [0, 255].

    Parameters:

    • byte : The byte value to be converted to an integer.

    Returns a 32-bit signed integer representing the same numerical value as the input byte.

    Example:

    test {
    let b = b'\xFF' // byte with value 255
    inspect(b.to_int(), content="255")
    let zero = b'\x00'
    inspect(zero.to_int(), content="0")
    }

    Byte::to_int16

    #deprecated("Use `Int16::from_byte` instead")
    fn Byte::to_int16(self : Byte) -> Int16

    Converts a byte value to a 16-bit signed integer. The byte value is zero-extended to 16 bits during the conversion, so the result is always in the range [0, 255].

    Parameters:

    • byte : The byte value to be converted to an Int16.

    Returns a 16-bit signed integer representing the same value as the input byte.

    Byte::to_int64

    fn Byte::to_int64(self : Byte) -> Int64

    Converts a byte value to a 64-bit signed integer by first converting it to a 32-bit integer and then extending it to a 64-bit integer.

    Parameters:

    • byte : The byte value to be converted.

    Returns a 64-bit signed integer representing the same numerical value as the input byte.

    Example:

    test {
    let b = b'\xFF'
    inspect(b.to_int64(), content="255")
    }

    Byte::to_json

    fn Byte::to_json(self : Byte) -> Json

    Byte::to_string

    fn Byte::to_string(self : Byte) -> String

    Converts a Byte to its string representation in hexadecimal format.

    Parameters:

    • byte : The Byte value to be converted.

    Returns a String representing the Byte in the format b'\xHH', where HH is the hexadecimal representation of the byte.

    Byte::to_uint

    fn Byte::to_uint(self : Byte) -> UInt

    Converts a Byte to a UInt.

    Parameters:

    • byte : The Byte value to be converted.

    Returns the UInt representation of the Byte.

    Byte::to_uint16

    fn Byte::to_uint16(self : Byte) -> UInt16

    Converts a byte value to a 16-bit unsigned integer by zero-extending it.

    Parameters:

    • byte : The byte value to be converted.

    Returns a 16-bit unsigned integer (UInt16) representing the same value as the input byte.

    Example:

    test {
    let b = b'\xFF' // byte with value 255
    inspect(b.to_uint16(), content="255")
    let zero = b'\x00'
    inspect(zero.to_uint16(), content="0")
    }

    Byte::to_uint64

    fn Byte::to_uint64(self : Byte) -> UInt64

    Converts a byte value to an unsigned 64-bit integer.

    Parameters:

    • byte : The byte value to be converted.

    Returns an unsigned 64-bit integer representation of the byte value.

    Example:

    test {
    let b = b'\xFF'
    inspect(b.to_uint64(), content="255")
    }

    Bytes

    Note

    Bytes is a built-in type. The documentation may not be complete here. You can find all methods and implementations in the core/builtin and core/bytes package.

    Bytes::add

    fn Bytes::add(self : Bytes, other : Bytes) -> Bytes

    Bytes::at

    #alias("_[_]")
    fn Bytes::at(self : Bytes, idx : Int) -> Byte

    Retrieves a byte at the specified index from a byte sequence.

    Parameters:

    • bytes : The byte sequence to access.
    • index : The position in the byte sequence from which to retrieve the byte.

    Returns a byte value from the specified position in the sequence.

    Throws a panic if the index is negative or greater than or equal to the length of the byte sequence.

    Example:

    test {
    let bytes = b"\x01\x02\x03"
    inspect(bytes[1], content="b'\\x02'")
    }

    Bytes::chop_prefix

    fn Bytes::chop_prefix(self : Bytes, prefix : BytesView) -> BytesView?

    Removes the given prefix from the bytes if it exists.

    Bytes::chop_suffix

    fn Bytes::chop_suffix(self : Bytes, suffix : BytesView) -> BytesView?

    Removes the given suffix from the bytes if it exists.

    Bytes::compare

    fn Bytes::compare(self : Bytes, other : Bytes) -> Int

    Bytes::copy

    #alias(clone, deprecated="`clone` is deprecated, use `copy` instead")
    #deprecated("Bytes are immutable. Use `FixedArray::blit_from_bytes` if it's really necessary.")
    fn Bytes::copy(self : Bytes) -> Bytes

    Return a copied Bytes value.

    Deprecated because Bytes is immutable and copying is usually unnecessary.

    Example:

    test {
    let a = b"abc"
    let b = Bytes::makei(a.length(), i => a[i])
    inspect(a == b, content="true")
    }

    Bytes::equal

    fn Bytes::equal(self : Bytes, other : Bytes) -> Bool

    Bytes::find

    fn Bytes::find(target : Bytes, pattern : BytesView) -> Int?

    Returns the offset of the first occurrence of the given bytes substring.

    If the substring is not found, None is returned.

    Bytes::from_array

    #alias(of, deprecated="`of` is deprecated, use `from_array` instead")
    fn Bytes::from_array(arr : ArrayView[Byte]) -> Bytes

    Creates a new bytes sequence from a byte array.

    Parameters:

    • array : An array of bytes to be converted.

    Returns a new bytes sequence containing the same bytes as the input array.

    Example:

    test {
    let arr : ReadOnlyArray[Byte] = [b'h', b'i']
    let bytes = Bytes::from_array(arr)
    inspect(
    bytes,
    content=(
    #|b"hi"
    ),
    )
    }

    test {
    let arr : FixedArray[Byte] = [b'h', b'e', b'l', b'l', b'o']
    let bytes = Bytes::from_array(arr)
    inspect(
    bytes,
    content=(
    #|b"hello"
    ),
    )
    }

    Bytes::from_fixedarray

    #deprecated("Use Bytes::from_array instead")
    fn Bytes::from_fixedarray(arr : FixedArray[Byte], len? : Int) -> Bytes

    Creates a new bytes sequence from a fixed-size array of bytes with an optional length parameter.

    Parameters:

    • arr : A fixed-size array of bytes to be converted into a bytes sequence.
    • len : (Optional) The length of the resulting bytes sequence. If not provided, uses the full length of the input array.

    Returns a new bytes sequence containing the bytes from the input array. If a length is specified, only includes up to that many bytes.

    Example:

    test {
    let arr : FixedArray[Byte] = [b'h', b'e', b'l', b'l', b'o']
    let bytes = Bytes::from_array(arr[0:3])
    inspect(
    bytes,
    content=(
    #|b"hel"
    ),
    )
    }

    Panics if the length is invalid

    Bytes::from_iter

    #alias(from_iterator, deprecated="`from_iterator` is deprecated, use `from_iter` instead")
    fn Bytes::from_iter(iter : Iter[Byte]) -> Bytes

    Creates a new bytes sequence from an iterator of bytes.

    Parameters:

    • iterator : An iterator that yields bytes.

    Returns a new bytes sequence containing all the bytes from the iterator.

    Example:

    test {
    let iter = b'h'
    let bytes = Bytes::from_iter(iter)
    inspect(
    bytes,
    content=(
    #|b"h"
    ),
    )
    }

    Bytes::get

    fn Bytes::get(self : Bytes, index : Int) -> Byte?

    Retrieves a byte from the byte sequence at the specified index.

    Parameters:

    • self : The byte sequence to retrieve the byte from.
    • index : The position in the byte sequence from which to retrieve the byte.

    Returns the byte at the specified index, or None if the index is out of bounds.

    Example:

    test {
    let bytes = b"\x01\x02\x03"
    let byte = bytes.get(1)
    debug_inspect(
    byte,
    content=(
    #|Some(0x02)
    ),
    )
    let bytes = b"\x01\x02\x03"
    let byte = bytes.get(3)
    debug_inspect(byte, content="None")
    }

    Bytes::get_view

    fn Bytes::get_view(self : Bytes, start? : Int, end? : Int) -> BytesView?

    Returns a view of the bytes between start and end, or None if the range is invalid. Unlike Bytes::view (a.k.a. b[start:end]), this variant does not abort on out-of-bounds indices, making it suitable for composition with pattern matching:

    test {
    let bs = b"\x00\x01\x02\x03\x04\x05"
    if bs.get_view(start=1) is Some([b'\x01', b'\x02', ..]) {
    ()
    } else {
    abort("unreachable")
    }
    debug_inspect(bs.get_view(start=10), content="None")
    }

    Bytes::has_prefix

    fn Bytes::has_prefix(self : Bytes, prefix : BytesView) -> Bool

    Returns true if this bytes starts with the given prefix.

    Bytes::has_suffix

    fn Bytes::has_suffix(self : Bytes, suffix : BytesView) -> Bool

    Returns true if this bytes ends with the given suffix.

    Bytes::hash

    fn Bytes::hash(self : Bytes) -> Int

    Bytes::is_empty

    fn Bytes::is_empty(self : Bytes) -> Bool

    Returns whether the byte sequence is empty.

    Example:

    test {
    inspect(b"".is_empty(), content="true")
    inspect(b"\x00".is_empty(), content="false")
    }

    Bytes::iter

    #alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
    fn Bytes::iter(self : Bytes) -> Iter[Byte]

    Creates an iterator over the bytes in the sequence.

    Parameters:

    • bytes : A byte sequence to iterate over.

    Returns an iterator that yields each byte in the sequence in order.

    Example:

    test {
    let bytes = Bytes::from_array([b'h', b'i'])
    let mut sum = 0
    bytes.iter().each(b => sum b.to_int())
    inspect(sum, content="209") // ASCII values: 'h'(104) + 'i'(105) = 209
    }

    Bytes::iter2

    #alias(iterator2, deprecated="`iterator2` is deprecated, use `iter2` instead")
    fn Bytes::iter2(self : Bytes) -> Iter2[Int, Byte]

    Creates an iterator that yields tuples of index and byte, indices start from 0.

    Example:

    test {
    let buf = StringBuilder(size_hint=5)
    let keys = []
    let it = b"abcde".iter2()
    while it.next() is Some((i, x)) {
    buf.write_string(x.to_string())
    keys.push(i)
    }
    inspect(buf, content="b'\\x61'b'\\x62'b'\\x63'b'\\x64'b'\\x65'")
    debug_inspect(keys, content="[0, 1, 2, 3, 4]")
    }

    Bytes::length

    fn Bytes::length(self : Bytes) -> Int

    Returns the number of bytes in a byte sequence.

    Parameters:

    • bytes : The byte sequence whose length is to be determined.

    Returns an integer representing the length (number of bytes) of the sequence.

    Example:

    test {
    let bytes = b"\x01\x02\x03"
    inspect(bytes.length(), content="3")
    let empty = b""
    inspect(empty.length(), content="0")
    }

    Bytes::lexical_compare

    fn Bytes::lexical_compare(self : Bytes, other : Bytes) -> Int

    Performs a lexicographical comparison of two byte sequences.

    This method compares the sequences byte by byte until a difference is found or one sequence is exhausted. Unlike the Compare trait implementation which uses shortlex order (shorter sequences come first), this method compares based purely on byte values until a difference is found.

    Returns

    • A negative integer if self is lexicographically less than other
    • Zero if self is lexicographically equal to other
    • A positive integer if self is lexicographically greater than other

    Example

    test {
    inspect(b"\x01\x02".lexical_compare(b"\x01\x02\x03"), content="-1")
    inspect(b"\x01\x02\x03".lexical_compare(b"\x01\x02"), content="1")
    inspect(b"\x01\x02\x03".lexical_compare(b"\x01\x02\x03"), content="0")
    inspect(b"\x01\x02\x03".lexical_compare(b"\x01\x02\x04"), content="-1")
    }

    Bytes::make

    fn Bytes::make(len : Int, init : Byte) -> Bytes

    Creates a new byte sequence of the specified length, where each byte is initialized to the given value. Returns an empty byte sequence if the length is negative.

    Parameters:

    • length : The length of the byte sequence to create. A negative value produces an empty byte sequence.
    • initial_value : The byte value used to initialize each position in the sequence.

    Example:

    test {
    let bytes = Bytes::make(3, b'\xFF')
    inspect(
    bytes,
    content=(
    #|b"\xff\xff\xff"
    ),
    )
    let empty = Bytes::make(0, b'\x00')
    inspect(empty, content="b\"\"")
    }

    Bytes::makei

    fn Bytes::makei(length : Int, value : (Int) -> Byte raise?) -> Bytes raise?

    Creates a new byte sequence of the specified length, where each byte is initialized using a function that maps indices to bytes.

    Parameters:

    • length : The length of the byte sequence to create. If length is less than or equal to 0, returns an empty byte sequence.
    • value : A function that takes an index (from 0 to length - 1) and returns a byte for that position.

    Returns a new byte sequence containing the bytes produced by applying the value function to each index.

    Example:

    test {
    let bytes = Bytes::makei(3, i => (i + 65).to_byte())
    @test.assert_eq(bytes, b"ABC")
    }

    Bytes::new

    fn Bytes::new(len : Int) -> Bytes

    Creates a new byte sequence filled with zero bytes.

    Parameters:

    • length : The length of the byte sequence to create. Must be a non-negative integer.

    Returns a new byte sequence of the specified length, with all bytes initialized to zero.

    Example:

    test {
    let bytes = Bytes::new(3)
    inspect(bytes, content="b\"\\x00\\x00\\x00\"")
    let bytes = Bytes::new(0)
    inspect(bytes, content="b\"\"")
    }

    Bytes::of_string

    #deprecated("check `@encoding/utf8.encode`")
    fn Bytes::of_string(str : String) -> Bytes

    Encode a UTF-16 string into raw bytes.

    Deprecated: use @encoding/utf8.encode for text encoding.

    Example:

    test {
    let bytes = Bytes::from_array([b'A'])
    inspect(bytes.length(), content="1")
    }

    Bytes::repeat

    fn Bytes::repeat(self : Bytes, count : Int) -> Bytes

    Returns a new Bytes consisting of self repeated count times.

    Aborts if count is negative. If count == 0 or self is empty, an empty Bytes is returned. When count == 1, self is returned directly without allocation.

    This implementation performs a single allocation sized exactly to the result and fills it using an exponential copy (doubling) strategy so the number of blit operations is O(log count).

    Example:

    test {
    inspect(
    b"ab".repeat(3),
    content=(
    #|b"ababab"
    ),
    )
    inspect(
    b"xyz".repeat(0),
    content=(
    #|b""
    ),
    )
    }

    Bytes::rev_find

    fn Bytes::rev_find(target : Bytes, pattern : BytesView) -> Int?

    Returns the offset of the last occurrence of the given bytes substring. If the substring is not found, None is returned.

    Bytes::to_array

    fn Bytes::to_array(self : Bytes) -> Array[Byte]

    Converts a bytes sequence into an array of bytes.

    Parameters:

    • bytes : A sequence of bytes to be converted into an array.

    Returns an array containing the same bytes as the input sequence.

    Example:

    test {
    let bytes = b"hello"
    let arr = bytes.to_array()
    debug_inspect(
    arr,
    content=(
    #|[0x68, 0x65, 0x6c, 0x6c, 0x6f]
    ),
    )
    }

    Bytes::to_fixedarray

    fn Bytes::to_fixedarray(self : Bytes, len? : Int) -> FixedArray[Byte]

    Converts a bytes sequence into a fixed-size array of bytes. If an optional length is provided, the resulting array will have exactly that length, otherwise it will match the length of the input bytes.

    Parameters:

    • self : The bytes sequence to convert.
    • len : Optional. The desired length of the output array. If specified, the resulting array will have this length. If not specified, the length of the input bytes sequence will be used.

    Returns a fixed-size array containing the bytes from the input sequence.

    Example:

    test {
    let bytes = b"hello"
    let arr = bytes.to_fixedarray()
    debug_inspect(
    arr,
    content=(
    #|<FixedArray: [0x68, 0x65, 0x6c, 0x6c, 0x6f]>
    ),
    )
    let arr2 = bytes[:3].to_fixedarray()
    debug_inspect(
    arr2,
    content=(
    #|<FixedArray: [0x68, 0x65, 0x6c]>
    ),
    )
    }

    Panics if the length is invalid

    Bytes::to_json

    fn Bytes::to_json(self : Bytes) -> Json

    Bytes::to_string

    fn Bytes::to_string(self : Bytes) -> String

    Bytes::to_unchecked_string

    fn Bytes::to_unchecked_string(self : Bytes, offset? : Int, length? : Int) -> String

    Return an unchecked string, containing the subsequence of self that starts at offset and has length length. Both offset and length are indexed by byte.

    Note this function does not validate the encoding of the byte sequence, it simply copy the bytes into a new String.

    Bytes::view

    #alias(sub, deprecated="Use _[_:_] instead")
    #alias("_[_:_]")
    fn Bytes::view(self : Bytes, start? : Int, end? : Int) -> BytesView

    Creates a new View from the given Bytes.

    Example

    test {
    let bs = b"\x00\x01\x02\x03\x04\x05"
    let bv = bs[1:4]
    inspect(bv.length(), content="3")
    @test.assert_eq(bv[0], b'\x01')
    @test.assert_eq(bv[1], b'\x02')
    @test.assert_eq(bv[2], b'\x03')
    }

    BytesView

    BytesView::at

    #alias("_[_]")
    fn BytesView::at(self : BytesView, index : Int) -> Byte

    Retrieves a byte from the view at the specified index.

    Parameters:

    • self : The bytes view to retrieve the byte from.
    • index : The position in the view from which to retrieve the byte.

    Returns the byte at the specified index.

    Throws a runtime error if the index is out of bounds (less than 0 or greater than or equal to the length of the view).

    Example:

    test {
    let bytes = b"\x01\x02\x03\x04\x05"
    let view = bytes[1:4] // view contains [0x02, 0x03, 0x04]
    inspect(view[1], content="b'\\x03'")
    }

    BytesView::chop_prefix

    fn BytesView::chop_prefix(self : BytesView, prefix : BytesView) -> BytesView?

    Removes the given prefix from the view if it exists.

    Returns Some(suffix) if the view starts with the given prefix. Returns None otherwise.

    BytesView::chop_suffix

    fn BytesView::chop_suffix(self : BytesView, suffix : BytesView) -> BytesView?

    Removes the given suffix from the view if it exists.

    Returns Some(prefix) if the view ends with the given suffix. Returns None otherwise.

    BytesView::compare

    fn BytesView::compare(self : BytesView, other : BytesView) -> Int

    BytesView::data

    fn BytesView::data(self : BytesView) -> Bytes

    Retrieves the underlying Bytes from a View.

    BytesView::equal

    fn BytesView::equal(self : BytesView, other : BytesView) -> Bool

    BytesView::equal_to_bytes

    fn BytesView::equal_to_bytes(self : BytesView, other : Bytes) -> Bool

    Compares a BytesView to a Bytes byte-for-byte.

    This is the cross-type equivalent of == and avoids materializing a fresh Bytes (or a wrapping BytesView) when probing an owned-Bytes-keyed container with a view-shaped key.

    Returns true if the lengths match and every byte in self equals the byte at the same index in other.

    Example:
    test {
    let buf = b"prefix_hello_suffix"
    inspect(buf[7:12].equal_to_bytes(b"hello"), content="true")
    inspect(buf[7:12].equal_to_bytes(b"world"), content="false")
    }

    BytesView::find

    fn BytesView::find(target : BytesView, pattern : BytesView) -> Int?

    Returns the offset of the first occurrence of the given bytes substring.

    If the substring is not found, None is returned.

    BytesView::get

    fn BytesView::get(self : BytesView, index : Int) -> Byte?

    Retrieves a byte from the view at the specified index.

    Parameters:

    • self : The bytes view to retrieve the byte from.
    • index : The position in the view from which to retrieve the byte.

    Returns the byte at the specified index, or None if the index is out of bounds.

    Example:

    test {
    let bytes = b"\x01\x02\x03\x04\x05"
    let view = bytes[1:4]
    let result = view.get(1)
    debug_inspect(
    result,
    content=(
    #|Some(0x03)
    ),
    )
    let bytes = b"\x01\x02\x03\x04\x05"
    let view = bytes[1:4]
    let result = view.get(5)
    debug_inspect(result, content="None")
    }

    BytesView::get_view

    fn BytesView::get_view(self : BytesView, start? : Int, end? : Int) -> BytesView?

    Returns a sub-view of the view between start and end, or None if the range is invalid. The optional variant of BytesView::view (a.k.a. bv[start:end]).

    BytesView::has_prefix

    fn BytesView::has_prefix(self : BytesView, prefix : BytesView) -> Bool

    Returns true if this bytes view starts with the given prefix.

    BytesView::has_suffix

    fn BytesView::has_suffix(self : BytesView, suffix : BytesView) -> Bool

    Returns true if this bytes view ends with the given suffix.

    BytesView::hash

    fn BytesView::hash(self : BytesView) -> Int

    BytesView::is_empty

    fn BytesView::is_empty(self : BytesView) -> Bool

    Returns whether the bytes view is empty.

    Example:

    test {
    let view = b"\x00\x01"[1:1]
    inspect(view.is_empty(), content="true")
    let view = b"\x00\x01"[0:1]
    inspect(view.is_empty(), content="false")
    }

    BytesView::iter

    #alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
    fn BytesView::iter(self : BytesView) -> Iter[Byte]

    Returns an iterator over the View.

    Example

    test {
    let bv = b"\x00\x01\x02\x03\x04\x05"[:]
    let mut sum = 0
    bv.iter().each(x => sum x.to_int())
    inspect(sum, content="15")
    }

    BytesView::iter2

    #alias(iterator2, deprecated="`iterator2` is deprecated, use `iter2` instead")
    fn BytesView::iter2(self : BytesView) -> Iter2[Int, Byte]

    Returns an iterator over the View with index.

    Example:

    test {
    let buf = StringBuilder(size_hint=5)
    let keys = []
    let it = b"abcde"[:].iter2()
    while it.next() is Some((i, x)) {
    buf.write_string(x.to_string())
    keys.push(i)
    }
    inspect(buf, content="b'\\x61'b'\\x62'b'\\x63'b'\\x64'b'\\x65'")
    debug_inspect(keys, content="[0, 1, 2, 3, 4]")
    }

    BytesView::length

    fn BytesView::length(self : BytesView) -> Int

    Returns the number of bytes in the view.

    Parameters:

    • bytes_view : The view of a byte sequence.

    Returns an integer representing the length of the view.

    Example:

    test {
    let bytes = b"\x00\x01\x02\x03\x04"
    let view = bytes[2:4]
    inspect(view.length(), content="2")
    }

    BytesView::lexical_compare

    fn BytesView::lexical_compare(self : BytesView, other : BytesView) -> Int

    Performs a lexicographical comparison of two byte views.

    This method returns the lexicographical ordering by byte value. Unlike the Compare trait implementation which uses shortlex order (shorter views come first), this method compares based purely on byte values until a difference is found.

    Returns

    • A negative integer if self is lexicographically less than other
    • Zero if self is lexicographically equal to other
    • A positive integer if self is lexicographically greater than other

    Example

    test {
    inspect(b"\x01\x02"[:].lexical_compare(b"\x01\x02\x03"), content="-1")
    inspect(b"\x01\x02\x03"[:].lexical_compare(b"\x01\x02"), content="1")
    inspect(b"\x01\x02\x03"[:].lexical_compare(b"\x01\x02\x03"), content="0")
    inspect(b"\x01\x02\x03"[:].lexical_compare(b"\x01\x02\x04"), content="-1")
    }

    BytesView::rev_find

    fn BytesView::rev_find(target : BytesView, pattern : BytesView) -> Int?

    Returns the offset of the last occurrence of the given bytes substring. If the substring is not found, None is returned.

    BytesView::start_offset

    fn BytesView::start_offset(self : BytesView) -> Int

    Retrieves the start index of the view.

    BytesView::to_array

    fn BytesView::to_array(self : BytesView) -> Array[Byte]

    Copy this bytes view into a new mutable array.

    Example:

    test {
    let arr = b"ab"[:].to_array()
    inspect(arr.length(), content="2")
    inspect(arr[0], content="b'\\x61'")
    }

    BytesView::to_fixedarray

    fn BytesView::to_fixedarray(self : BytesView) -> FixedArray[Byte]

    Copy this bytes view into a new fixed array.

    Example:

    test {
    let arr = b"abcd"[1:3].to_fixedarray()
    debug_inspect(
    arr,
    content=(
    #|<FixedArray: [0x62, 0x63]>
    ),
    )
    }

    BytesView::to_json

    fn BytesView::to_json(self : BytesView) -> Json

    BytesView::to_owned

    #alias(to_bytes, deprecated="Use `to_owned` to allocate an owned `Bytes` from a `BytesView`")
    fn BytesView::to_owned(self : BytesView) -> Bytes

    Return a Bytes value containing exactly this view's range.

    If the view spans the full underlying bytes, this returns the original value without copying; otherwise it allocates and copies.

    Example:

    test {
    let b = b"hello"
    inspect(b[1:4].to_owned().length(), content="3")
    }

    BytesView::to_string

    fn BytesView::to_string(self : BytesView) -> String

    BytesView::view

    #alias(sub, deprecated="Use _[_:_] instead")
    #alias("_[_:_]")
    fn BytesView::view(self : BytesView, start? : Int, end? : Int) -> BytesView

    Creates a new View from the given View.

    Example

    test {
    let bv = b"\x00\x01\x02\x03\x04\x05"[:]
    let bv2 = bv[1:4]
    inspect(bv2.length(), content="3")
    @test.assert_eq(bv2[1], b'\x02')
    }

    Char

    Note

    Char is a built-in type. The documentation may not be complete here. You can find all methods and implementations in the core/builtin and core/char package.

    Char::compare

    fn Char::compare(self : Char, other : Char) -> Int

    Char::equal

    fn Char::equal(self : Char, other : Char) -> Bool

    Char::escape

    fn Char::escape(self : Char, quote? : Bool) -> String

    Returns the escaped representation of a character.

    When quote is true (default), the result is wrapped in single quotes like a MoonBit character literal.

    Escape rules:
    • Single quote and backslash are backslash-escaped: \', \\
    • Common control characters use named escapes: \n, \r, \b, \t
    • ASCII printable characters (U+0020 to U+007E) are displayed as-is
    • Printable Unicode characters outside ASCII are displayed as-is
    • Non-printable characters use \u{hex} format

    test {
    inspect('a'.escape(), content="'a'")
    inspect('a'.escape(quote=false), content="a")
    inspect('\n'.escape(), content="'\\n'")
    inspect('\n'.escape(quote=false), content="\\n")
    }

    Char::from_int

    #deprecated("Use `Int::unsafe_to_char` instead, and use `Int::to_char` for safe conversion")
    fn Char::from_int(val : Int) -> Char

    Deprecated constructor from raw code point. Create from int.

    Char::hash

    fn Char::hash(self : Char) -> Int

    Char::is_ascii

    fn Char::is_ascii(self : Char) -> Bool

    Checks if the value is within the ASCII range.

    Char::is_ascii_alphabetic

    fn Char::is_ascii_alphabetic(self : Char) -> Bool

    Checks if the value is an ASCII alphabetic character:
    • U+0041 'A' ..= U+005A 'Z'
    • U+0061 'a' ..= U+007A 'z'

    Char::is_ascii_control

    fn Char::is_ascii_control(self : Char) -> Bool

    Checks if the value is an ASCII control character: U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE. Note that most ASCII whitespace characters are control characters, but SPACE is not.

    Char::is_ascii_digit

    fn Char::is_ascii_digit(self : Char) -> Bool

    Checks if the value is an ASCII decimal digit: U+0030 '0' ..= U+0039 '9'

    Char::is_ascii_graphic

    fn Char::is_ascii_graphic(self : Char) -> Bool

    Checks if the value is an ASCII graphic character: U+0021 '!' ..= U+007E '~'

    Char::is_ascii_hexdigit

    fn Char::is_ascii_hexdigit(self : Char) -> Bool

    Checks if the value is an ASCII hexadecimal digit:
    • U+0030 '0' ..= U+0039 '9'
    • U+0041 'A' ..= U+0046 'F'
    • U+0061 'a' ..= U+0066 'f'

    Char::is_ascii_lowercase

    fn Char::is_ascii_lowercase(self : Char) -> Bool

    Checks if the value is an ASCII lowercase character: U+0061 'a' ..= U+007A 'z'.

    Char::is_ascii_octdigit

    fn Char::is_ascii_octdigit(self : Char) -> Bool

    Checks if the value is an ASCII octal digit: U+0030 '0' ..= U+0037 '7'

    Char::is_ascii_punctuation

    fn Char::is_ascii_punctuation(self : Char) -> Bool

    Checks if the value is an ASCII punctuation character:
    • U+0021 ..= U+002F ! " # $ % & ' ( ) * + , - . /
    • U+003A ..= U+0040 : ; < = > ? @
    • U+005B ..= U+0060 [ \ ] ^ _ `
    • U+007B ..= U+007E { | } ~

    Char::is_ascii_uppercase

    fn Char::is_ascii_uppercase(self : Char) -> Bool

    Checks if the value is an ASCII uppercase character: U+0041 'A' ..= U+005A 'Z'

    Char::is_ascii_whitespace

    fn Char::is_ascii_whitespace(self : Char) -> Bool

    Checks if the value is an ASCII whitespace character: U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED, U+000B VERTICAL TAB, U+000C FORM FEED, or U+000D CARRIAGE RETURN.

    Char::is_bmp

    fn Char::is_bmp(self : Char) -> Bool

    Returns true if this character is in the Basic Multilingual Plane (BMP).

    The BMP (Basic Multilingual Plane) contains 65,536 code points (U+0000 to U+FFFF) distributed as follows:

    • ~57,022 actual Unicode character positions (87% of BMP)
    • 2,048 surrogate code points (U+D800-U+DFFF) - reserved for UTF-16 encoding
      • High surrogates: U+D800-U+DBFF (1,024 code points)
      • Low surrogates: U+DC00-U+DFFF (1,024 code points)
    • 6,400 private use area (U+E000-U+F8FF) - for custom characters
    • 66 permanent noncharacters (including U+FFFE, U+FFFF, U+FDD0-U+FDEF)

    Note: Surrogate code points are not actual characters but encoding mechanisms for representing characters outside the BMP in UTF-16.

    Example:

    test {
    inspect('A'.is_bmp(), content="true")
    inspect('🌟'.is_bmp(), content="false")
    }

    Char::is_control

    fn Char::is_control(self : Char) -> Bool

    Returns true if this char has the general category for control codes.

    Char::is_digit

    fn Char::is_digit(self : Char, radix : UInt) -> Bool

    Checks if a char is a digit in the given radix (range from 2 to 36).

    panic if the radix is invalid.

    Char::is_numeric

    fn Char::is_numeric(self : Char) -> Bool

    Returns true if this char has one of the general categories for numbers.

    Char::is_printable

    fn Char::is_printable(self : Char) -> Bool

    Returns true if this character is printable (visible when displayed). Aligns with Unicode standard categories for printable characters. Characters are considered printable if they are:
    • Letters (L*)
    • Marks (M*)
    • Numbers (N*)
    • Punctuation (P*)
    • Symbols (S*)
    • Spaces (Zs), with some exceptions Characters are considered non-printable if they are:
    • Control characters (Cc)
    • Format characters (Cf)
    • Line/paragraph separators (Zl, Zp)
    • Private use (Co)
    • Noncharacters (U+FDD0-U+FDEF and the U+nFFFE/U+nFFFF pairs)
    • Surrogates (Cs)

    Char::is_whitespace

    fn Char::is_whitespace(self : Char) -> Bool

    Returns true if this char has the White_Space property.

    Char::to_ascii_lowercase

    fn Char::to_ascii_lowercase(self : Char) -> Char

    Makes a copy of the value in its ASCII lower case equivalent. ASCII letters 'A' to 'Z' are mapped to 'a' to 'z', but non-ASCII letters are unchanged.

    Char::to_ascii_uppercase

    fn Char::to_ascii_uppercase(self : Char) -> Char

    Makes a copy of the value in its ASCII upper case equivalent. ASCII letters 'a' to 'z' are mapped to 'A' to 'Z', but non-ASCII letters are unchanged.

    Char::to_int

    fn Char::to_int(self : Char) -> Int

    Converts a character to its Unicode code point value as an integer.

    Parameters:

    • self : The character to be converted.

    Returns an integer representing the Unicode code point value of the character.

    Example:

    test {
    inspect('A'.to_int(), content="65") // ASCII value of 'A'
    inspect('あ'.to_int(), content="12354") // Unicode code point of 'あ'
    }

    Char::to_json

    fn Char::to_json(self : Char) -> Json

    Char::to_string

    fn Char::to_string(self : Char) -> String

    Char::to_uint

    fn Char::to_uint(self : Char) -> UInt

    Converts a Unicode character to its unsigned 32-bit integer code point representation. The character's code point value is first converted to a signed integer and then reinterpreted as an unsigned integer.

    Parameters:

    • character : The Unicode character to be converted.

    Returns an unsigned 32-bit integer representing the character's Unicode code point.

    Example:

    test {
    let c = 'A'
    inspect(c.to_uint(), content="65") // ASCII value of 'A'
    let emoji = '🤣'
    inspect(emoji.to_uint(), content="129315") // Unicode code point U+1F923
    }

    Char::utf16_len

    #alias(length, deprecated="Use `utf16_len` instead")
    fn Char::utf16_len(self : Char) -> Int

    Returns the number of UTF-16 code units required to encode this character.

    Parameters:

    • self : The character to analyze.

    Returns the number of UTF-16 code units (1 or 2) needed to represent this character. Note surrogate pairs are counted as 2, it should not happen in general since surrogate pair is Int instead of Char. Example:

    test {
    inspect('A'.utf16_len(), content="1")
    inspect('🌟'.utf16_len(), content="2")
    }

    Double

    Note

    Double is a built-in type. The documentation may not be complete here. You can find all methods and implementations in the core/builtin and core/double package.

    Double::Double

    fn Double::Double(self : Double) -> Double

    The identity constructor for Double, allowing values to be written using constructor syntax, e.g. Double(3.2).

    Example:

    test {
    inspect(Double(3.2), content="3.2")
    }

    Double::abs

    fn Double::abs(self : Double) -> Double

    Returns the absolute value of a double-precision floating-point number.

    Parameters:

    • value : The double-precision floating-point number to compute the absolute value of.

    Returns the absolute value of the input number by clearing its sign bit, so the result is never negative. In particular, (-0.0).abs() is 0.0.

    Example:

    test {
    inspect((-2.5).abs(), content="2.5")
    inspect(3.14.abs(), content="3.14")
    inspect(0.0.abs(), content="0")
    }

    Double::add

    fn Double::add(self : Double, other : Double) -> Double

    Double::ceil

    fn Double::ceil(self : Double) -> Double

    Returns the smallest integer greater than or equal to the given number.

    Parameters:

    • self : The floating point number to find the ceiling of.

    Returns the ceiling value of the input number.

    Example:

    test {
    inspect(3.7.ceil(), content="4")
    inspect((-3.7).ceil(), content="-3")
    inspect(42.0.ceil(), content="42")
    }

    Double::clamp

    fn Double::clamp(self : Double, min~ : Double, max~ : Double) -> Double

    Clamps the value between min and max (inclusive).

    Parameters:

    • self : The value to clamp.
    • min : The lower bound of the range.
    • max : The upper bound of the range.

    Returns min if self < min, max if self > max, and self otherwise. Aborts if min is greater than max.

    Example:

    test {
    inspect(0.5.clamp(min=0.0, max=1.0), content="0.5")
    inspect((-1.0).clamp(min=0.0, max=1.0), content="0")
    inspect(2.0.clamp(min=0.0, max=1.0), content="1")
    }

    Double::compare

    fn Double::compare(self : Double, other : Double) -> Int

    Double::convert_uint

    fn Double::convert_uint(val : UInt) -> Double

    Converts an unsigned 32-bit integer to a double-precision floating-point number. Since the range of unsigned 32-bit integers is smaller than what can be precisely represented by a double-precision floating-point number, this conversion is guaranteed to be exact.

    Parameters:

    • value : The unsigned 32-bit integer to be converted.

    Returns a double-precision floating-point number that exactly represents the input value.

    Example:

    test {
    let n = 42U
    inspect(Double::convert_uint(n), content="42")
    let max = 4294967295U // maximum value of UInt
    inspect(Double::convert_uint(max), content="4294967295")
    }

    Double::convert_uint64

    fn Double::convert_uint64(val : UInt64) -> Double

    Converts an unsigned 64-bit integer to a double-precision floating-point number. The conversion is exact for integers up to 53 bits (the size of the mantissa in a double-precision number), but may lose precision for larger values.

    Parameters:

    • value : The unsigned 64-bit integer to be converted.

    Returns a double-precision floating-point number representing the same numerical value as the input.

    Example:

    let n = 12345678901234567890UL inspect(Double::convert_uint64(n), content="12345678901234567000")

    Double::div

    fn Double::div(self : Double, other : Double) -> Double

    Double::equal

    fn Double::equal(self : Double, other : Double) -> Bool

    Double::floor

    fn Double::floor(self : Double) -> Double

    Returns the largest integer less than or equal to the given number.

    Parameters:

    • number : A floating-point number to be rounded down.

    Returns a double-precision floating-point number representing the largest integer less than or equal to the input.

    Example:

    test {
    inspect(3.7.floor(), content="3")
    inspect((-3.7).floor(), content="-4")
    inspect(0.0.floor(), content="0")
    }

    Double::from_int

    fn Double::from_int(i : Int) -> Double

    Converts an integer to a double-precision floating-point number.

    Parameters:

    • integer : The integer value to be converted.

    Returns a double-precision floating-point number representing the given integer value.

    Example:

    test {
    inspect(Double::from_int(42), content="42")
    inspect(Double::from_int(-1), content="-1")
    }

    Double::hash

    fn Double::hash(self : Double) -> Int

    Double::is_close

    fn Double::is_close(self : Double, other : Double, relative_tolerance? : Double, absolute_tolerance? : Double) -> Bool

    Determines whether two floating-point numbers are approximately equal within specified tolerances. The implementation follows the algorithm described in PEP 485 for Python's math.isclose().

    Parameters:

    • self : The first floating-point number to compare.
    • other : The second floating-point number to compare.
    • relative_tolerance : The relative tolerance for the comparison. Must be non-negative. Defaults to 1e-9.
    • absolute_tolerance : The absolute tolerance for the comparison. Must be non-negative. Defaults to 0.0.

    Returns whether the two numbers are considered approximately equal. Returns true if the numbers are exactly equal or if they are within either the relative or absolute tolerance. Returns false if the numbers are not exactly equal and either of them is infinite.

    Example:

    test {
    let x = 1.0
    let y = 1.000000001
    inspect(x.is_close(y), content="false")
    inspect(x.is_close(y, relative_tolerance=1.0e-10), content="false")
    inspect(@double.infinity.is_close(@double.infinity), content="true")
    }

    Double::is_inf

    fn Double::is_inf(self : Double) -> Bool

    Checks whether a double-precision floating-point number represents positive or negative infinity.

    Parameters:

    • value : The double-precision floating-point number to check.

    Returns true if the value is either positive or negative infinity, false otherwise.

    Example:

    test {
    inspect(@double.infinity.is_inf(), content="true")
    inspect(@double.neg_infinity.is_inf(), content="true")
    inspect(42.0.is_inf(), content="false")
    }

    Double::is_nan

    fn Double::is_nan(self : Double) -> Bool

    Checks whether a double-precision floating-point number represents a "Not a Number" (NaN) value.

    Parameters:

    • number : A double-precision floating-point value to be checked.

    Returns true if the number is NaN, false otherwise.

    Example:

    test {
    inspect(@double.not_a_number.is_nan(), content="true")
    inspect(42.0.is_nan(), content="false")
    inspect((0.0 / 0.0).is_nan(), content="true")
    }

    Double::is_neg_inf

    fn Double::is_neg_inf(self : Double) -> Bool

    Checks whether a double-precision floating-point number is negative infinity.

    Parameters:

    • self : The double-precision floating-point number to check.

    Returns a boolean value indicating whether the number is negative infinity.

    Example:

    test {
    inspect((-1.0 / 0.0).is_neg_inf(), content="true")
    inspect(42.0.is_neg_inf(), content="false")
    inspect((1.0 / 0.0).is_neg_inf(), content="false") // positive infinity
    }

    Double::is_pos_inf

    fn Double::is_pos_inf(self : Double) -> Bool

    Checks whether a double-precision floating-point number is positive infinity.

    Parameters:

    • value : The double-precision floating-point number to check.

    Returns true if the number is positive infinity, false otherwise.

    Example:

    test {
    inspect(@double.infinity.is_pos_inf(), content="true")
    inspect(@double.neg_infinity.is_pos_inf(), content="false")
    inspect(42.0.is_pos_inf(), content="false") // TODO: better formatter
    }

    Double::lerp

    fn Double::lerp(self : Double, target~ : Double, t~ : Double) -> Double

    Performs linear interpolation from self to target by factor t.

    The interpolation formula is self + (target - self) * t.

    Parameters:

    • self : The start value.
    • target : The end value.
    • t : The interpolation factor.

    Returns the interpolated value.

    Example:

    test {
    inspect(0.0.lerp(target=10.0, t=0.25), content="2.5")
    inspect(5.0.lerp(target=15.0, t=0.0), content="5")
    inspect(5.0.lerp(target=15.0, t=1.0), content="15")
    }

    Double::max

    fn Double::max(self : Double, other : Double) -> Double

    Returns the maximum of two double-precision floating-point values.

    If exactly one argument is NaN, returns the other argument.

    Double::min

    fn Double::min(self : Double, other : Double) -> Double

    Returns the minimum of two double-precision floating-point values.

    If exactly one argument is NaN, returns the other argument.

    Double::mod

    fn Double::mod(self : Double, other : Double) -> Double

    Double::mul

    fn Double::mul(self : Double, other : Double) -> Double

    Double::neg

    fn Double::neg(self : Double) -> Double

    Double::pow

    #deprecated("Use `@math.pow` instead")
    fn Double::pow(self : Double, other : Double) -> Double

    Calculates the power of a number by raising the base to the specified exponent. Handles special cases and edge conditions according to IEEE 754 standards.

    Parameters:

    • base : The base number to be raised to a power.
    • exponent : The power to raise the base number to.

    Returns the result of raising base to the power of exponent.

    Example:

    test {
    let x = 2.0
    inspect(@math.pow(x, 3.0), content="8")
    inspect(@math.pow(x, 0.5), content="1.4142135623730951")
    inspect(@math.pow(x, 0.0), content="1")
    inspect(@math.pow(-1.0, 2.0), content="1")
    inspect(@math.pow(0.0, 0.0), content="1")
    inspect(@math.pow(@double.infinity, -1.0), content="0")
    }

    Double::reinterpret_as_i64

    #deprecated("Use `reinterpret_as_int64` instead")
    fn Double::reinterpret_as_i64(self : Double) -> Int64

    Reinterprets the bits of a double-precision floating-point number as a 64-bit signed integer without any conversion. This is a low-level operation that simply reinterprets the bit pattern of the input value.

    Parameters:

    • value : The double-precision floating-point number whose bits are to be reinterpreted.

    Returns a 64-bit signed integer that has the same bit pattern as the input double-precision floating-point number.

    Example:

    test {
    let d = 1.0
    // 1.0 in IEEE 754 double format has the bit pattern 0x3FF0000000000000
    inspect(d.reinterpret_as_int64(), content="4607182418800017408")
    }

    Double::reinterpret_as_int64

    fn Double::reinterpret_as_int64(self : Double) -> Int64

    Reinterprets the bits of a double-precision floating-point number as a 64-bit signed integer without performing any conversion. Preserves the exact bit pattern of the input value.

    Parameters:

    • number : The double-precision floating-point number whose bits will be reinterpreted.

    Returns a 64-bit signed integer containing the same bit pattern as the input floating-point number.

    Example:

    test {
    let d = 1.0
    inspect(d.reinterpret_as_int64(), content="4607182418800017408") // IEEE 754 representation of 1.0
    let neg = -0.0
    inspect(neg.reinterpret_as_int64(), content="-9223372036854775808") // Sign bit set
    }

    Double::reinterpret_as_u64

    #deprecated("Use `reinterpret_as_uint64` instead")
    fn Double::reinterpret_as_u64(self : Double) -> UInt64

    Reinterprets the bits of a double-precision floating-point number as an unsigned 64-bit integer. The bit pattern is preserved during the conversion, with no mathematical conversion performed.

    Parameters:

    • self : The double-precision floating-point number to be reinterpreted.

    Returns an unsigned 64-bit integer containing the same bit pattern as the input floating-point number.

    Example:

    test {
    let zero = 0.0
    let positive = 1.0
    inspect(zero.reinterpret_as_uint64(), content="0")
    inspect(positive.reinterpret_as_uint64(), content="4607182418800017408")
    }

    Double::reinterpret_as_uint64

    fn Double::reinterpret_as_uint64(self : Double) -> UInt64

    Reinterprets the bits of a double-precision floating-point number as an unsigned 64-bit integer, preserving the exact bit pattern without performing any numerical conversion.

    Parameters:

    • self : The double-precision floating-point number whose bits will be reinterpreted.

    Returns an unsigned 64-bit integer that has the same bit pattern as the input floating-point number.

    Example:

    test {
    let d = 1.0
    inspect(d.reinterpret_as_uint64(), content="4607182418800017408") // Binary: 0x3FF0000000000000
    }

    Double::round

    fn Double::round(self : Double) -> Double

    Rounds a floating-point number to the nearest integer using "round half up" rule. In this rule, when a number is halfway between two integers (like 3.5), it is rounded up to the next integer.

    Parameters:

    • value : The floating-point number to be rounded.

    Returns the rounded value as a double-precision floating-point number.

    Example:

    test {
    inspect(3.7.round(), content="4")
    inspect(3.2.round(), content="3")
    inspect(3.5.round(), content="4")
    inspect((-3.5).round(), content="-3")
    }

    Double::signum

    fn Double::signum(self : Double) -> Double

    Returns the sign of the double.
    • If the double is positive, returns 1.0.
    • If the double is negative, returns -1.0.
    • Otherwise, returns the double itself (0.0, -0.0 and NaN).

    Double::sqrt

    fn Double::sqrt(self : Double) -> Double

    Calculates the square root of a double-precision floating-point number. For non-negative numbers, returns the positive square root. For negative numbers or NaN, returns NaN.

    Parameters:

    • self : The double-precision floating-point number whose square root is to be calculated.

    Returns the square root of the input number, or NaN if the input is negative or NaN.

    Example:

    test {
    inspect(4.0.sqrt(), content="2")
    inspect(0.0.sqrt(), content="0")
    inspect((-1.0).sqrt(), content="NaN")
    }

    Double::sub

    fn Double::sub(self : Double, other : Double) -> Double

    Double::to_float

    #deprecated("Use `Float::from_double` instead")
    fn Double::to_float(self : Double) -> Float

    TODO: enable skip_current_package=false Convert Double to Float (deprecated alias).

    Double::to_int

    fn Double::to_int(self : Double) -> Int

    Converts a double-precision floating-point number to a 32-bit integer. Handles special cases including NaN and numbers outside the valid Int range.

    Parameters:

    • self : The double-precision floating-point number to be converted.

    Returns an 32-bit integer value according to the following rules:

    • Returns 0 if the input is NaN
    • Returns @int.MAX_VALUE (2147483647) if the input is greater than or equal to @int.MAX_VALUE
    • Returns @int.MIN_VALUE (-2147483648) if the input is less than or equal to @int.MIN_VALUE
    • Otherwise returns the integer part of the input by truncating towards zero

    Example:

    test {
    inspect(42.0.to_int(), content="42")
    inspect((-42.5).to_int(), content="-42")
    inspect((0.0 / 0.0).to_int(), content="0") // NaN
    inspect((1.0 / 0.0).to_int(), content="2147483647") // Infinity
    inspect((-1.0 / 0.0).to_int(), content="-2147483648") // -Infinity
    }

    Double::to_int64

    fn Double::to_int64(self : Double) -> Int64

    Converts a double-precision floating-point number to a 64-bit integer. Handles special cases including NaN and numbers outside the valid Int range.

    Parameters:

    • self : The double-precision floating-point number to be converted.

    Returns an 64-bit integer value according to the following rules:

    • Returns 0 if the input is NaN
    • Returns @int64.MAX_VALUE (9223372036854775807L) if the input is greater than or equal to @int64.MAX_VALUE
    • Returns @int64.MIN_VALUE (-9223372036854775808L) if the input is less than or equal to @int64.MIN_VALUE
    • Otherwise returns the integer part of the input by truncating towards zero

    Example:

    test {
    inspect(42.0.to_int64(), content="42")
    inspect((-42.5).to_int64(), content="-42")
    inspect((0.0 / 0.0).to_int64(), content="0") // NaN
    inspect((1.0 / 0.0).to_int64(), content="9223372036854775807") // Infinity
    inspect((-1.0 / 0.0).to_int64(), content="-9223372036854775808") // -Infinity
    }

    Double::to_json

    fn Double::to_json(self : Double) -> Json

    Double::to_string

    fn Double::to_string(self : Double) -> String

    Converts a double-precision floating-point number to its string representation.

    Parameters:

    • self: The double-precision floating-point number to be converted.

    Returns a string representation of the double-precision floating-point number.

    Example:

    test {
    inspect(42.0.to_string(), content="42")
    inspect(3.14159.to_string(), content="3.14159")
    inspect((-0.0).to_string(), content="0")
    inspect(@double.not_a_number.to_string(), content="NaN")
    }

    Double::to_uint

    fn Double::to_uint(self : Double) -> UInt

    Converts a double-precision floating-point number to a 32-bit unsigned integer. Handles special cases including NaN and numbers outside the valid UInt range.

    Parameters:

    • self : The double-precision floating-point number to be converted.

    Returns a 32-bit unsigned integer value according to the following rules:

    • Returns 0 if the input is NaN
    • Returns @uint.MAX_VALUE (4294967295U) if the input is greater than or equal to @uint.MAX_VALUE
    • Returns @uint.MIN_VALUE (0U) if the input is less than or equal to @uint.MIN_VALUE
    • Otherwise returns the integer part of the input by truncating towards zero

    Example:

    test {
    inspect(42.0.to_uint(), content="42")
    inspect((-42.5).to_uint(), content="0")
    inspect((0.0 / 0.0).to_uint(), content="0") // NaN
    inspect((1.0 / 0.0).to_uint(), content="4294967295") // Infinity
    inspect((-1.0 / 0.0).to_uint(), content="0") // -Infinity
    }

    Double::to_uint64

    fn Double::to_uint64(self : Double) -> UInt64

    Converts a double-precision floating-point number to a 64-bit unsigned integer. Handles special cases including NaN and numbers outside the valid UInt64 range.

    Parameters:

    • self : The double-precision floating-point number to be converted.

    Returns a 64-bit unsigned integer value according to the following rules:

    • Returns 0 if the input is NaN
    • Returns @uint64.MAX_VALUE (18446744073709551615UL) if the input is greater than or equal to 9223372036854775807
    • Returns 0 if the input is less than or equal to 0
    • Otherwise returns the integer part of the input by truncating towards zero

    Example:

    test {
    inspect(42.0.to_uint64(), content="42")
    inspect((0.0 / 0.0).to_uint64(), content="0") // NaN
    inspect((1.0 / 0.0).to_uint64(), content="18446744073709551615") // Infinity
    inspect((-1.0 / 0.0).to_uint64(), content="0") // -Infinity
    }

    Double::trunc

    fn Double::trunc(self : Double) -> Double

    Returns an integer value by discarding the decimal part of the floating-point number (truncation toward zero).

    Parameters:

    • self : The floating-point number to be truncated.

    Returns a floating-point number representing the integer part of the input.

    Example:

    test {
    inspect(3.7.trunc(), content="3")
    inspect((-3.7).trunc(), content="-3")
    inspect(0.0.trunc(), content="0")
    }

    Double::until

    fn Double::until(self : Double, end : Double, step? : Double, inclusive? : Bool) -> Iter[Double]

    Creates an iterator that iterates over a range of Double with default step 1.0 . To grow the range downward, set the step parameter to a negative value.

    Arguments

    • start - The starting value of the range (inclusive).
    • end - The ending value of the range (exclusive by default).
    • step - The step size of the range (default 1.0).
    • inclusive - Whether the ending value is inclusive (default false).

    Returns

    Returns an iterator that iterates over the range of Double from start to end - 1.

    FixedArray

    Note

    FixedArray is a built-in type. The documentation may not be complete here. You can find all methods and implementations in the core/builtin and core/fixedarray package.

    FixedArray::add

    fn[T] FixedArray::add(self : FixedArray[T], other : FixedArray[T]) -> FixedArray[T]

    FixedArray::all

    #alias(every)
    fn[T] FixedArray::all(self : FixedArray[T], f : (T) -> Bool raise?) -> Bool raise?

    Check if all the elements in the array match the condition.

    Example

    test {
    let arr : FixedArray[Int] = [1, 2, 3, 4, 5]
    assert_true(arr.all(ele => ele < 6))
    assert_false(arr.all(ele => ele < 5))
    }

    FixedArray::any

    #alias(exists)
    fn[T] FixedArray::any(self : FixedArray[T], f : (T) -> Bool raise?) -> Bool raise?

    Check if any of the elements in the array match the condition.

    Example

    test {
    let arr : FixedArray[Int] = [1, 2, 3, 4, 5]
    assert_true(arr.any(ele => ele < 6))
    assert_true(arr.any(ele => ele < 5))
    }

    FixedArray::at

    #alias("_[_]")
    fn[T] FixedArray::at(self : FixedArray[T], idx : Int) -> T

    Retrieves an element at the specified index from a fixed-size array. This function implements the array indexing operator [].

    Parameters:

    • array : The fixed-size array to access.
    • index : The position in the array from which to retrieve the element.

    Returns the element at the specified index.

    Panics if the index is out of bounds.

    Example:

    test {
    let arr = FixedArray::make(3, 42)
    inspect(arr[1], content="42")
    }
    fn[T : Compare + Eq] FixedArray::binary_search(self : FixedArray[T], value : T) -> Result[Int, Int]

    Performs a binary search on a sorted array to find the index of a given element.

    Example

    test {
    let v : FixedArray[Int] = [3, 4, 5]
    let result = v.binary_search(3)
    @test.assert_eq(result, Ok(0)) // The element 3 is found at index 0
    }

    Arguments

    • self: The array in which to perform the search.
    • value: The element to search for in the array.

    Returns

    • Result[Int, Int]: If the element is found, an Ok variant is returned, containing the index of the matching element in the array. If there are multiple matches, the leftmost match will be returned. If the element is not found, an Err variant is returned, containing the index where the element could be inserted to maintain the sorted order.

    Notes

    • Ensure that the array is sorted in increasing order before calling this function.
    • If the array is not sorted, the returned result is undefined and should not be relied on.

    FixedArray::binary_search_by

    fn[T] FixedArray::binary_search_by(self : FixedArray[T], cmp : (T) -> Int raise?) -> Result[Int, Int] raise?

    Performs a binary search on a sorted array using a custom comparison function. Returns the position of the matching element if found, or the position where the element could be inserted while maintaining the sorted order.

    Parameters:

    • array : The sorted array to search in.
    • comparator : A function that compares each element with the target value, returning:
    • A negative integer if the element is less than the target
    • Zero if the element equals the target
    • A positive integer if the element is greater than the target

    Returns a Result containing either:

    • Ok(index) if a matching element is found at position index
    • Err(index) if no match is found, where index is the position where the element could be inserted

    Example:

    test {
    let arr : FixedArray[Int] = [1, 3, 5, 7, 9]
    let find_3 = arr.binary_search_by(x => x.compare(3))
    debug_inspect(find_3, content="Ok(1)")
    let find_4 = arr.binary_search_by(x => x.compare(4))
    debug_inspect(find_4, content="Err(2)")
    }

    Notes:

    • Assumes the array is sorted according to the ordering implied by the comparison function
    • For multiple matches, returns the leftmost matching position
    • Returns an insertion point that maintains the sort order when no match is found

    FixedArray::blit_from_bytes

    fn FixedArray::blit_from_bytes(self : FixedArray[Byte], bytes_offset : Int, src : Bytes, src_offset : Int, length : Int) -> Unit

    Copy length bytes from byte sequence src, starting at src_offset, into byte sequence self, starting at bytes_offset.

    FixedArray::blit_from_bytesview

    fn FixedArray::blit_from_bytesview(self : FixedArray[Byte], bytes_offset : Int, src : BytesView) -> Unit

    Copy bytes from a BytesView into a fixed array of bytes.

    Parameters:

    • self : The destination fixed array of bytes.
    • bytes_offset : The starting position in the destination array where bytes will be copied.
    • src : The source View to copy from.

    Throws a panic if:
    • bytes_offset is negative
    • The destination array is too small to hold all bytes from the source View

    Example:

    test {
    let arr = FixedArray::make(4, b'\x00')
    let view = b"\x01\x02\x03"[1:]
    arr.blit_from_bytesview(1, view)
    debug_inspect(
    arr,
    content=(
    #|<FixedArray: [0x00, 0x02, 0x03, 0x00]>
    ),
    )
    }

    FixedArray::blit_from_string

    fn FixedArray::blit_from_string(self : FixedArray[Byte], bytes_offset : Int, str : String, str_offset : Int, length : Int) -> Unit

    Copies characters from a string to a byte sequence in UTF-16LE encoding. Each character is converted into two bytes, with the lower byte stored first.

    Parameters:

    • self : The destination byte array to copy the characters into.
    • bytes_offset : The starting position in the destination array where bytes will be written.
    • str : The source string containing the characters to copy.
    • str_offset : The starting position in the source string from which characters will be read.
    • length : The number of characters to copy.

    Throws a runtime error if:

    • length is negative
    • bytes_offset is negative
    • str_offset is negative
    • The range [bytes_offset, bytes_offset + length * 2) exceeds the length of the destination array
    • The range [str_offset, str_offset + length) exceeds the length of the source string

    Example:

    test {
    let bytes = FixedArray::make(6, b'\x00')
    bytes.blit_from_string(0, "ABC", 0, 3)
    @json.json_inspect(bytes, content=[65, 0, 66, 0, 67, 0]) // 'A'
    bytes.blit_from_string(0, "你好啊", 0, 3)
    @json.json_inspect(bytes, content=[96, 79, 125, 89, 74, 85]) // '你好啊'
    bytes.blit_from_string(0, "😈", 0, 2)
    @json.json_inspect(bytes, content=[61, 216, 8, 222, 74, 85]) // '😈'
    }

    FixedArray::blit_to

    fn[A] FixedArray::blit_to(self : FixedArray[A], dst : FixedArray[A], len~ : Int, src_offset? : Int, dst_offset? : Int) -> Unit

    Copies a sequence of elements from the source fixed array to a destination fixed array. The arrays may overlap, in which case the copy is performed in a way that preserves the data.

    Parameters:

    • self : The source fixed array from which elements will be copied.
    • dst : The destination fixed array where elements will be copied to.
    • len : The number of elements to copy.
    • src_offset : The starting position in the source array. Defaults to 0.
    • dst_offset : The starting position in the destination array. Defaults to

    Throws a panic if:

    • src_offset + len exceeds the length of the source array
    • dst_offset + len exceeds the length of the destination array

    Example:

    test {
    let src = FixedArray::make(5, 1)
    let dst = FixedArray::make(5, 0)
    src.blit_to(dst, len=3, src_offset=1, dst_offset=2)
    debug_inspect(
    dst,
    content=(
    #|<FixedArray: [0, 0, 1, 1, 1]>
    ),
    )
    }

    FixedArray::compare

    fn[T : Compare + Eq] FixedArray::compare(self : FixedArray[T], other : FixedArray[T]) -> Int

    FixedArray::contains

    fn[T : Eq] FixedArray::contains(self : FixedArray[T], value : T) -> Bool

    Checks if the array contains an element.

    Example

    test {
    let arr : FixedArray[Int] = [3, 4, 5]
    assert_true(arr.contains(3))
    }

    FixedArray::copy

    #alias(clone, deprecated="`clone` is deprecated, use `copy` instead")
    fn[T] FixedArray::copy(self : FixedArray[T]) -> FixedArray[T]

    Creates a new array that is a copy of the original array.

    Parameters:

    • self : The array to be copied. The type of elements in the array must be T.

    Returns a new array containing all elements from the original array in the same order.

    Example:

    test {
    let original = [1, 2, 3]
    let copied = original.copy()
    debug_inspect(copied, content="[1, 2, 3]")
    inspect(physical_equal(original, copied), content="false")
    }

    FixedArray::each

    fn[T] FixedArray::each(self : FixedArray[T], f : (T) -> Unit raise?) -> Unit raise?

    Iterates over each element.

    Arguments

    • self: The array to iterate over.
    • f: The function to apply to each element.

    Example

    test {
    let arr = []
    [1, 2, 3, 4, 5].each(x => arr.push(x))
    @test.assert_eq(arr, [1, 2, 3, 4, 5])
    }

    FixedArray::eachi

    fn[T] FixedArray::eachi(self : FixedArray[T], f : (Int, T) -> Unit raise?) -> Unit raise?

    Iterates over the array with index.

    Arguments

    • self: The array to iterate over.
    • f: A function that takes an Int representing the index and a T representing the element of the array, and returns Unit.

    Example

    test {
    let arr = []
    [1, 2, 3, 4, 5].eachi((index, elem) => arr.push((index, elem)))
    @test.assert_eq(arr, [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)])
    }

    FixedArray::ends_with

    fn[T : Eq] FixedArray::ends_with(self : FixedArray[T], suffix : ArrayView[T]) -> Bool

    Check if the array ends with a given suffix.

    Example

    test {
    let v : FixedArray[Int] = [3, 4, 5]
    assert_true(v.ends_with([5]))
    }

    FixedArray::equal

    fn[T : Eq] FixedArray::equal(self : FixedArray[T], that : FixedArray[T]) -> Bool

    FixedArray::fill

    fn[T] FixedArray::fill(self : FixedArray[T], value : T, start? : Int, end? : Int) -> Unit

    Fill the array with a given value.

    This method fills all or part of a FixedArray with the given value.

    Parameters

    • value: The value to fill the array with
    • start: The starting index (inclusive, default: 0)
    • end: The ending index (exclusive, optional)

    If end is not provided, fills from start to the end of the array. If start equals end, no elements are modified.

    Panics

    • Panics if start is negative or greater than or equal to the array length
    • Panics if end is provided and is less than start or greater than array length
    • Does nothing if the array is empty

    Example

    test {
    // Fill entire array
    let fa : FixedArray[Int] = [0, 0, 0, 0, 0]
    fa.fill(3)
    debug_inspect(
    fa,
    content=(
    #|<FixedArray: [3, 3, 3, 3, 3]>
    ),
    )

    // Fill from index 1 to 3 (exclusive)
    let fa2 : FixedArray[Int] = [0, 0, 0, 0, 0]
    fa2.fill(9, start=1, end=3)
    debug_inspect(
    fa2,
    content=(
    #|<FixedArray: [0, 9, 9, 0, 0]>
    ),
    )

    // Fill from index 2 to end
    let fa3 : FixedArray[String] = ["a", "b", "c", "d"]
    fa3.fill("x", start=2)
    debug_inspect(
    fa3,
    content=(
    #|<FixedArray: ["a", "b", "x", "x"]>
    ),
    )
    }

    FixedArray::fold

    fn[A, B] FixedArray::fold(self : FixedArray[A], init~ : B, f : (B, A) -> B raise?) -> B raise?

    Fold out values from an array according to certain rules.

    Example

    test {
    let sum = [1, 2, 3, 4, 5].fold(init=0, (sum, elem) => sum + elem)
    inspect(sum, content="15")
    }

    FixedArray::foldi

    fn[A, B] FixedArray::foldi(self : FixedArray[A], init~ : B, f : (Int, B, A) -> B raise?) -> B raise?

    Fold out values from an array according to certain rules with index.

    Example

    test {
    let sum = [1, 2, 3, 4, 5].foldi(init=0, (index, sum, _elem) => sum + index)
    inspect(sum, content="10")
    }

    FixedArray::from_array

    fn[T] FixedArray::from_array(array : ArrayView[T]) -> FixedArray[T]

    Creates a new fixed-size array from a dynamic array. The resulting fixed array will have the same length and elements as the input array.

    Parameters:

    • array : A dynamic array containing elements of type T that will be converted to a fixed array.

    Returns a new fixed array containing the same elements as the input array.

    Example:

    test {
    let dynamic_array : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
    let fixed_array = FixedArray::from_array(dynamic_array)
    debug_inspect(
    fixed_array,
    content=(
    #|<FixedArray: [1, 2, 3, 4, 5]>
    ),
    )
    }

    FixedArray::from_iter

    #alias(from_iterator, deprecated="`from_iterator` is deprecated, use `from_iter` instead")
    fn[T] FixedArray::from_iter(iter : Iter[T]) -> FixedArray[T]

    Creates a new fixed array from an iterator.

    Parameters:

    • iterator : An iterator of type Iter[T] from which elements will be collected into a fixed array.

    Returns a new fixed array containing all elements from the iterator.

    Example:

    test {
    let arr = [1, 2, 3]
    let fixed_arr = FixedArray::from_iter(arr.iter())
    debug_inspect(
    fixed_arr,
    content=(
    #|<FixedArray: [1, 2, 3]>
    ),
    )
    }

    FixedArray::get

    fn[T] FixedArray::get(self : FixedArray[T], idx : Int) -> T?

    Retrieves an element at the specified index from a fixed-size array.

    Parameters:

    • array : The fixed-size array to access.
    • index : The position in the array from which to retrieve the element.

    Returns Some(element) if the index is within bounds, or None if the index is out of bounds.

    Example:

    test {
    let arr : FixedArray[Int] = [1, 2, 3]
    debug_inspect(arr.get(1), content="Some(2)")
    let arr : FixedArray[Int] = [1, 2, 3]
    debug_inspect(arr.get(3), content="None")
    }

    FixedArray::get_view

    fn[T] FixedArray::get_view(self : FixedArray[T], start? : Int, end? : Int) -> ArrayView[T]?

    Creates a new ArrayView from a FixedArray, returning None when indices are invalid.

    Parameters:

    • self : The fixed array to create a new view from.
    • start : The starting index in the array (inclusive). Defaults to 0.
    • end : The ending index in the array (exclusive). Defaults to the length of the array.

    Returns Some(ArrayView) that provides a window into the specified portion of the original fixed array, or None when the indices are invalid.

    Example:

    test {
    let arr : FixedArray[Int] = [1, 2, 3, 4, 5]
    let start = 1
    let end = 4
    debug_inspect(
    arr.get_view(start~, end~),
    content=(
    #|Some(<ArrayView: [2, 3, 4]>)
    ),
    )
    let start = 2
    let end = 10
    debug_inspect(arr.get_view(start~, end~), content="None")
    }

    FixedArray::hash

    fn[T : Hash] FixedArray::hash(self : FixedArray[T]) -> Int

    FixedArray::is_empty

    fn[T] FixedArray::is_empty(self : FixedArray[T]) -> Bool

    Tests whether the FixedArray contains no elements.

    Parameters:

    • FixedArray : The FixedArray to check.

    Returns true if the FixedArray has no elements, false otherwise.

    Example:

    test {
    let empty : FixedArray[Int] = []
    inspect(empty.is_empty(), content="true")
    let non_empty = [1, 2, 3]
    inspect(non_empty.is_empty(), content="false")
    }

    FixedArray::is_sorted

    fn[T : Compare + Eq] FixedArray::is_sorted(arr : FixedArray[T]) -> Bool

    Checks if the elements in the array are sorted in ascending order according to their natural ordering.

    Parameters:

    • array : A fixed array of type T, where T must implement the Compare trait.

    Returns true if the array is sorted in ascending order, false otherwise. An empty array or an array with a single element is considered sorted.

    Example:

    test {
    let sorted : FixedArray[Int] = [1, 2, 3, 4, 5]
    let unsorted : FixedArray[Int] = [5, 4, 3, 2, 1]
    inspect(FixedArray::is_sorted(sorted), content="true")
    inspect(FixedArray::is_sorted(unsorted), content="false")
    }

    FixedArray::iter

    #alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
    fn[X] FixedArray::iter(self : FixedArray[X]) -> Iter[X]

    Return an iterator over elements of the fixed array.

    iterator is a deprecated alias for this function.

    Example:

    test {
    debug_inspect(
    ([1, 2, 3] : FixedArray[Int]).iter().collect(),
    content="[1, 2, 3]",
    )
    }

    FixedArray::iter2

    #alias(iterator2, deprecated="`iterator2` is deprecated, use `iter2` instead")
    fn[X] FixedArray::iter2(self : FixedArray[X]) -> Iter2[Int, X]

    Return an index-value iterator over the fixed array.

    iterator2 is a deprecated alias for this function.

    Example:

    test {
    debug_inspect(
    ([10, 20] : FixedArray[Int]).iter2().to_array(),
    content="[(0, 10), (1, 20)]",
    )
    }

    FixedArray::join

    fn[A : ToStringView] FixedArray::join(self : FixedArray[A], separator : StringView) -> String

    Concatenate the string-renderable elements of the array into a single complete string, separated by separator.

    Example:

    test {
    let fixed_array : FixedArray[String] = ["1", "2", "3"]
    inspect(fixed_array.join(","), content="1,2,3")
    }

    FixedArray::last

    fn[A] FixedArray::last(self : FixedArray[A]) -> A?

    Returns the last element of a fixed array if it exists.

    Parameters:

    • self : The fixed array to get the last element from.

    Returns Some(element) containing the last element if the array is not empty, or None if the array is empty.

    Example:

    test {
    let array : FixedArray[Int] = [1, 2, 3]
    debug_inspect(array.last(), content="Some(3)")
    let empty : FixedArray[Int] = []
    debug_inspect(empty.last(), content="None")
    }

    FixedArray::length

    fn[T] FixedArray::length(self : FixedArray[T]) -> Int

    Returns the number of elements in a fixed-size array.

    Parameters:

    • array : The fixed-size array whose length is to be determined.

    Returns an integer representing the number of elements in the array.

    Example:

    test {
    let arr = FixedArray::make(3, 42)
    inspect(arr.length(), content="3")
    }

    FixedArray::lexical_compare

    fn[T : Compare + Eq] FixedArray::lexical_compare(self : FixedArray[T], other : FixedArray[T]) -> Int

    Performs a lexicographical comparison of two fixed arrays.

    This method compares the arrays element by element until a difference is found or one array is exhausted. Unlike the Compare trait implementation which uses shortlex order (shorter arrays come first), this method compares based purely on element values until a difference is found.

    Returns

    • A negative integer if self is lexicographically less than other
    • Zero if self is lexicographically equal to other
    • A positive integer if self is lexicographically greater than other

    Example

    test {
    let a : FixedArray[Int] = [1, 2]
    let b : FixedArray[Int] = [1, 2, 3]
    inspect(a.lexical_compare(b), content="-1")
    inspect(b.lexical_compare(a), content="1")
    let c : FixedArray[Int] = [1, 2, 3]
    inspect(b.lexical_compare(c), content="0")
    let d : FixedArray[Int] = [1, 2, 4]
    inspect(b.lexical_compare(d), content="-1")
    }

    FixedArray::make

    fn[T] FixedArray::make(len : Int, init : T) -> FixedArray[T]

    Creates a new fixed-size array with the specified length, initializing all elements with the given value.

    Parameters:

    • length : The length of the array to create. Must be non-negative.
    • initial_value : The value used to initialize all elements in the array.

    Returns a new fixed-size array of type FixedArray[T] with length elements, where each element is initialized to initial_value.

    Throws a panic if length is negative.

    Example:

    test {
    let arr = FixedArray::make(3, 42)
    inspect(arr[0], content="42")
    inspect(arr.length(), content="3")
    }

    WARNING: A common pitfall is creating with the same initial value, for example:
    test {
    let two_dimension_array = FixedArray::make(10, FixedArray::make(10, 0))
    two_dimension_array[0][5] = 10
    @test.assert_eq(two_dimension_array[5][5], 10)
    }
    This is because all the cells reference to the same object (the FixedArray[Int] in this case). One should use makei() instead which creates an object for each index.

    FixedArray::make_and_blit

    fn[T] FixedArray::make_and_blit(src : FixedArray[T], allocate_len~ : Int, init~ : T, len~ : Int, src_offset? : Int, dst_offset? : Int) -> FixedArray[T]

    Creates a fixed array initialized with init, then blits len elements from src into it.

    FixedArray::makei

    fn[T] FixedArray::makei(length : Int, value : (Int) -> T raise?) -> FixedArray[T] raise?

    Creates a new fixed-size array of the specified length, where each element is initialized using a function that maps indices to values.

    Parameters:

    • length : The length of the array to create. If length is less than or equal to 0, returns an empty array.
    • initializer : A function that takes an index (from 0 to length - 1) and returns a value of type T for that position.

    Returns a new fixed array containing the values produced by applying the initializer function to each index.

    Example:

    test {
    let arr = FixedArray::makei(3, i => i * 2)
    debug_inspect(
    arr,
    content=(
    #|<FixedArray: [0, 2, 4]>
    ),
    )
    }

    FixedArray::map

    fn[T, U] FixedArray::map(self : FixedArray[T], f : (T) -> U raise?) -> FixedArray[U] raise?

    Applies a function to each element of the array and returns a new array with the results.

    Example

    test {
    let arr = [1, 2, 3, 4, 5]
    let doubled = arr.map(x => x * 2)
    @test.assert_eq(doubled, [2, 4, 6, 8, 10])
    }

    FixedArray::mapi

    fn[T, U] FixedArray::mapi(self : FixedArray[T], f : (Int, T) -> U raise?) -> FixedArray[U] raise?

    Maps a function over the elements of the arr with index.

    Example

    test {
    let arr = [3, 4, 5]
    let added = arr.mapi((i, x) => x + i)
    @test.assert_eq(added, [3, 5, 7])
    }

    FixedArray::mut_view

    fn[T] FixedArray::mut_view(self : FixedArray[T], start? : Int, end? : Int) -> MutArrayView[T]

    Creates a new mutable ArrayView from a FixedArray.

    Parameters:

    • self : The fixed array to create a new view from.
    • start : The starting index in the array (inclusive). Defaults to 0.
    • end : The ending index in the array (exclusive). Defaults to the length of the array.

    Returns a new MutArrayView that provides a window into the specified portion of the original fixed array.

    Throws a panic if:

    • start is negative
    • end is greater than the length of the array
    • start is greater than end

    Example:

    test {
    let arr : FixedArray[Int] = [1, 2, 3, 4, 5]
    let view = arr.mut_view(start=1, end=4) // view = [2, 3, 4]
    inspect(view[0], content="2")
    }

    FixedArray::rev

    fn[T] FixedArray::rev(self : FixedArray[T]) -> FixedArray[T]

    Returns a new array containing all elements in reverse order. The original array remains unchanged.

    Parameters:

    • self : The array to be reversed.

    Returns a new array with the same elements but in reverse order.

    Example:

    test {
    let arr : FixedArray[Int] = [1, 2, 3, 4, 5]
    debug_inspect(
    arr.rev(),
    content=(
    #|<FixedArray: [5, 4, 3, 2, 1]>
    ),
    )
    // Original array remains unchanged
    debug_inspect(
    arr,
    content=(
    #|<FixedArray: [1, 2, 3, 4, 5]>
    ),
    )
    }

    FixedArray::rev_each

    fn[T] FixedArray::rev_each(self : FixedArray[T], f : (T) -> Unit raise?) -> Unit raise?

    Iterates over each element in reversed turn.

    Arguments

    • self: The array to iterate over.
    • f: The function to apply to each element.

    Example

    test {
    let arr = []
    [1, 2, 3, 4, 5].rev_each(x => arr.push(x))
    @test.assert_eq(arr, [5, 4, 3, 2, 1])
    }

    FixedArray::rev_eachi

    fn[T] FixedArray::rev_eachi(self : FixedArray[T], f : (Int, T) -> Unit raise?) -> Unit raise?

    Iterates over the array with index in reversed turn.

    Arguments

    • self: The array to iterate over.
    • f: A function that takes an Int representing the index and a T representing the element of the array, and returns Unit.

    Example

    test {
    let arr = []
    [1, 2, 3, 4, 5].rev_eachi((index, elem) => arr.push((index, elem)))
    @test.assert_eq(arr, [(0, 5), (1, 4), (2, 3), (3, 2), (4, 1)])
    }

    FixedArray::rev_fold

    fn[A, B] FixedArray::rev_fold(self : FixedArray[A], init~ : B, f : (B, A) -> B raise?) -> B raise?

    Fold out values from an array according to certain rules in reversed turn.

    Example

    test {
    let sum = [1, 2, 3, 4, 5].rev_fold(init=0, (sum, elem) => sum + elem)
    inspect(sum, content="15")
    }

    FixedArray::rev_foldi

    fn[A, B] FixedArray::rev_foldi(self : FixedArray[A], init~ : B, f : (Int, B, A) -> B raise?) -> B raise?

    Fold out values from an array according to certain rules in reversed turn with index.

    Example

    test {
    let sum = [1, 2, 3, 4, 5].rev_foldi(init=0, (index, sum, _elem) => sum + index)
    inspect(sum, content="10")
    }

    FixedArray::rev_in_place

    #alias(rev_inplace, deprecated="`rev_inplace` is deprecated, use `rev_in_place` instead")
    fn[T] FixedArray::rev_in_place(self : FixedArray[T]) -> Unit

    Reverses the array in place by swapping elements from both ends until reaching the middle.

    Parameters:

    • array : The array to be reversed. The array will be modified in place.

    Example:

    test {
    let arr : FixedArray[_] = [1, 2, 3, 4, 5]
    arr.rev_in_place()
    debug_inspect(
    arr,
    content=(
    #|<FixedArray: [5, 4, 3, 2, 1]>
    ),
    )
    }

    FixedArray::search

    fn[T : Eq] FixedArray::search(self : FixedArray[T], value : T) -> Int?

    Search the array index for a given element.

    Example

    test {
    let arr : FixedArray[Int] = [3, 4, 5]
    @test.assert_eq(arr.search(3), Some(0))
    }

    FixedArray::set

    #alias("_[_]=_")
    fn[T] FixedArray::set(self : FixedArray[T], idx : Int, val : T) -> Unit

    Sets the value at the specified index in a fixed-size array.

    Parameters:

    • array : The fixed-size array to be modified.
    • index : The index at which to set the value. Must be non-negative and less than the array's length.
    • value : The value to be set at the specified index.

    Throws a runtime error if the index is out of bounds (less than 0 or greater than or equal to the array's length).

    Example:

    test {
    let arr = FixedArray::make(3, 0)
    arr.set(1, 42)
    inspect(arr[1], content="42")
    }

    FixedArray::set_utf16be_char

    fn FixedArray::set_utf16be_char(self : FixedArray[Byte], offset : Int, value : Char) -> Int

    Fill UTF16BE encoded char value into byte sequence self, starting at offset. It return the length of bytes has been written.

    This function will panic if the value is out of range.

    FixedArray::set_utf16le_char

    fn FixedArray::set_utf16le_char(self : FixedArray[Byte], offset : Int, value : Char) -> Int

    Fill UTF16LE encoded char value into byte sequence self, starting at offset. It return the length of bytes has been written.

    This function will panic if the value is out of range.

    FixedArray::set_utf8_char

    fn FixedArray::set_utf8_char(self : FixedArray[Byte], offset : Int, value : Char) -> Int

    Encodes a Unicode character into UTF-8 bytes and writes them into a fixed array of bytes at the specified offset.

    Parameters:

    • array : The fixed array of bytes to write into.
    • offset : The starting position in the array where the encoded bytes will be written.
    • char : The Unicode character to be encoded.

    Returns the number of bytes written (1 to 4 bytes depending on the character's code point).

    Throws a panic if:

    • The character's code point is greater than 0x10FFFF.
    test {
    let buf = FixedArray::make(4, b'\x00')
    let written = buf.set_utf8_char(0, '€') // Euro symbol (U+20AC)
    inspect(written, content="3") // UTF-8 encoding takes 3 bytes
    inspect(buf[0], content="b'\\xE2'")
    inspect(buf[1], content="b'\\x82'")
    inspect(buf[2], content="b'\\xAC'")
    }

    FixedArray::sort

    fn[T : Compare + Eq] FixedArray::sort(self : FixedArray[T]) -> Unit

    Sorts the array

    It's an in-place, unstable sort(it will reorder equal elements). The time complexity is O(n log n) in the worst case.

    Example

    test {
    let arr : FixedArray[Int] = [5, 4, 3, 2, 1]
    arr.sort()
    @test.assert_eq(arr, [1, 2, 3, 4, 5])
    }

    FixedArray::sort_by

    fn[T] FixedArray::sort_by(self : FixedArray[T], cmp : (T, T) -> Int) -> Unit

    Sorts the array with a custom comparison function.

    It's an in-place, unstable sort(it will reorder equal elements). The time complexity is O(n log n) in the worst case.

    Example

    test {
    let arr : FixedArray[Int] = [5, 3, 2, 4, 1]
    arr.sort_by((a, b) => a - b)
    @test.assert_eq(arr, [1, 2, 3, 4, 5])
    }

    FixedArray::sort_by_key

    fn[T, K : Compare + Eq] FixedArray::sort_by_key(self : FixedArray[T], map : (T) -> K) -> Unit

    Sorts the array with a key extraction function.

    It's an in-place, unstable sort(it will reorder equal elements). The time complexity is O(n log n) in the worst case.

    Example

    test {
    let arr : FixedArray[Int] = [5, 3, 2, 4, 1]
    arr.sort_by_key(x => -x)
    @test.assert_eq(arr, [5, 4, 3, 2, 1])
    }

    FixedArray::stable_sort

    fn[T : Compare + Eq] FixedArray::stable_sort(self : FixedArray[T]) -> Unit

    Sorts the array

    It's a stable sort(it will not reorder equal elements). The time complexity is O(n * log(n)) in the worst case.

    Example

    test {
    let arr : FixedArray[Int] = [5, 4, 3, 2, 1]
    arr.stable_sort()
    @test.assert_eq(arr, [1, 2, 3, 4, 5])
    }

    FixedArray::starts_with

    fn[T : Eq] FixedArray::starts_with(self : FixedArray[T], prefix : ArrayView[T]) -> Bool

    Check if the array starts with a given prefix.

    Example

    test {
    let arr : FixedArray[Int] = [3, 4, 5]
    assert_true(arr.starts_with([3, 4]))
    }

    FixedArray::swap

    fn[T] FixedArray::swap(self : FixedArray[T], i : Int, j : Int) -> Unit

    Swap two elements in the array.

    Example

    test {
    let arr = [1, 2, 3, 4, 5]
    arr.swap(0, 1)
    @test.assert_eq(arr, [2, 1, 3, 4, 5])
    }

    FixedArray::to_json

    fn[X : ToJson] FixedArray::to_json(self : FixedArray[X]) -> Json

    FixedArray::unsafe_blit

    fn[A] FixedArray::unsafe_blit(dst : FixedArray[A], dst_offset : Int, src : FixedArray[A], src_offset : Int, len : Int) -> Unit

    Copies a slice of elements from one fixed array to another.

    This function copies len elements from src starting at src_offset to dst starting at dst_offset. The arrays may overlap, in which case the copy is performed in a way that preserves the data.

    Example

    test {
    let src = FixedArray::from_array([1, 2, 3, 4, 5])
    let dst = FixedArray::from_array([0, 0, 0, 0, 0])
    FixedArray::unsafe_blit(dst, 0, src, 0, 3)
    @test.assert_eq(dst, FixedArray::from_array([1, 2, 3, 0, 0]))
    }

    The behavior is undefined and platform-specific if:
    • len < 0
    • src_offset < 0
    • dst_offset < 0
    • dst_offset + len > dst.length()
    • src_offset + len > src.length()

    FixedArray::unsafe_write_uint16_be

    fn FixedArray::unsafe_write_uint16_be(bytes : FixedArray[Byte], index : Int, value : UInt16) -> Unit

    UNSAFE: Writes a UInt16 to the FixedArray[Byte] in big-endian byte order.

    ⚠️ Warning: This function is unsafe and can cause undefined behavior!

    Safety

    • No bounds checking: This function does not verify that index + 1 < bytes.length()
    • Buffer overrun risk: Writing beyond the array boundary may corrupt memory
    • Alignment: No alignment requirements, but misaligned access may be slower on some architectures
    • Responsibility: Caller must ensure sufficient space is available

    Parameters

    • bytes: The FixedArray[Byte] to write to
    • index: Starting byte index (0-based)
    • value: The UInt16 value to write

    Behavior

    Writes 2 bytes starting at index in big-endian order:
    • bytes[index] ← bits 8-15 (most significant)
    • bytes[index+1] ← bits 0-7 (least significant)

    FixedArray::unsafe_write_uint16_le

    fn FixedArray::unsafe_write_uint16_le(bytes : FixedArray[Byte], index : Int, value : UInt16) -> Unit

    UNSAFE: Writes a UInt16 to the FixedArray[Byte] in little-endian byte order.

    ⚠️ Warning: This function is unsafe and can cause undefined behavior!

    Safety

    • No bounds checking: This function does not verify that index + 1 < bytes.length()
    • Buffer overrun risk: Writing beyond the array boundary may corrupt memory
    • Alignment: No alignment requirements, but misaligned access may be slower on some architectures
    • Responsibility: Caller must ensure sufficient space is available

    Parameters

    • bytes: The FixedArray[Byte] to write to
    • index: Starting byte index (0-based)
    • value: The UInt16 value to write

    Behavior

    Writes 2 bytes starting at index in little-endian order:
    • bytes[index] ← bits 0-7 (least significant)
    • bytes[index+1] ← bits 8-15 (most significant)

    FixedArray::unsafe_write_uint32_be

    fn FixedArray::unsafe_write_uint32_be(bytes : FixedArray[Byte], index : Int, value : UInt) -> Unit

    UNSAFE: Writes a UInt32 to the FixedArray[Byte] in big-endian byte order.

    ⚠️ Warning: This function is unsafe and can cause undefined behavior!

    Safety

    • No bounds checking: This function does not verify that index + 3 < bytes.length()
    • Buffer overrun risk: Writing beyond the array boundary may corrupt memory
    • Alignment: No alignment requirements, but misaligned access may be slower on some architectures
    • Responsibility: Caller must ensure sufficient space is available

    Parameters

    • bytes: The FixedArray[Byte] to write to
    • index: Starting byte index (0-based)
    • value: The UInt32 value to write

    Behavior

    Writes 4 bytes starting at index in big-endian order:
    • bytes[index] ← bits 24-31 (most significant)
    • bytes[index+1] ← bits 16-23
    • bytes[index+2] ← bits 8-15
    • bytes[index+3] ← bits 0-7 (least significant)

    FixedArray::unsafe_write_uint32_le

    fn FixedArray::unsafe_write_uint32_le(bytes : FixedArray[Byte], index : Int, value : UInt) -> Unit

    UNSAFE: Writes a UInt32 to the FixedArray[Byte] in little-endian byte order.

    ⚠️ Warning: This function is unsafe and can cause undefined behavior!

    Safety

    • No bounds checking: This function does not verify that index + 3 < bytes.length()
    • Buffer overrun risk: Writing beyond the array boundary may corrupt memory
    • Alignment: No alignment requirements, but misaligned access may be slower on some architectures
    • Responsibility: Caller must ensure sufficient space is available

    Parameters

    • bytes: The FixedArray[Byte] to write to
    • index: Starting byte index (0-based)
    • value: The UInt32 value to write

    Behavior

    Writes 4 bytes starting at index in little-endian order:
    • bytes[index] ← bits 0-7 (least significant)
    • bytes[index+1] ← bits 8-15
    • bytes[index+2] ← bits 16-23
    • bytes[index+3] ← bits 24-31 (most significant)

    FixedArray::unsafe_write_uint64_be

    fn FixedArray::unsafe_write_uint64_be(bytes : FixedArray[Byte], index : Int, value : UInt64) -> Unit

    UNSAFE: Writes a UInt64 to the FixedArray[Byte] in big-endian byte order.

    ⚠️ Warning: This function is unsafe and can cause undefined behavior!

    Safety

    • No bounds checking: This function does not verify that index + 7 < bytes.length()
    • Buffer overrun risk: Writing beyond the array boundary may corrupt memory
    • Alignment: No alignment requirements, but misaligned access may be slower on some architectures
    • Responsibility: Caller must ensure sufficient space is available

    Parameters

    • bytes: The FixedArray[Byte] to write to
    • index: Starting byte index (0-based)
    • value: The UInt64 value to write

    Behavior

    Writes 8 bytes starting at index in big-endian order:
    • bytes[index] ← bits 56-63 (most significant)
    • bytes[index+1] ← bits 48-55
    • ...
    • bytes[index+7] ← bits 0-7 (least significant)

    FixedArray::unsafe_write_uint64_le

    fn FixedArray::unsafe_write_uint64_le(bytes : FixedArray[Byte], index : Int, value : UInt64) -> Unit

    UNSAFE: Writes a UInt64 to the FixedArray[Byte] in little-endian byte order.

    ⚠️ Warning: This function is unsafe and can cause undefined behavior!

    Safety

    • No bounds checking: This function does not verify that index + 7 < bytes.length()
    • Buffer overrun risk: Writing beyond the array boundary may corrupt memory
    • Alignment: No alignment requirements, but misaligned access may be slower on some architectures
    • Responsibility: Caller must ensure sufficient space is available

    Parameters

    • bytes: The FixedArray[Byte] to write to
    • index: Starting byte index (0-based)
    • value: The UInt64 value to write

    Behavior

    Writes 8 bytes starting at index in little-endian order:
    • bytes[index] ← bits 0-7 (least significant)
    • bytes[index+1] ← bits 8-15
    • ...
    • bytes[index+7] ← bits 56-63 (most significant)

    FixedArray::view

    #alias(sub, deprecated="Use _[_:_] instead")
    #alias("_[_:_]")
    fn[T] FixedArray::view(self : FixedArray[T], start? : Int, end? : Int) -> ArrayView[T]

    Creates a new ArrayView from a FixedArray.

    Parameters:

    • self : The fixed array to create a new view from.
    • start : The starting index in the array (inclusive). Defaults to 0.
    • end : The ending index in the array (exclusive). Defaults to the length of the array.

    Returns a new ArrayView that provides a window into the specified portion of the original fixed array.

    Throws a panic if:

    • start is negative
    • end is greater than the length of the array
    • start is greater than end

    Example:

    test {
    let arr : FixedArray[Int] = [1, 2, 3, 4, 5]
    let view = arr[1:4] // view = [2, 3, 4]
    inspect(view[0], content="2")
    }

    Int

    Note

    Int is a built-in type. The documentation may not be complete here. You can find all methods and implementations in the core/builtin and core/int package.

    Int::Int

    fn Int::Int(self : Int) -> Int

    The identity constructor for Int, allowing values to be written using constructor syntax, e.g. Int(3).

    Example:

    test {
    inspect(Int(3), content="3")
    }

    Int::abs

    fn Int::abs(self : Int) -> Int

    Computes the absolute value of an integer.

    Parameters:

    • self : The integer whose absolute value is to be computed.

    Returns the absolute value of the integer. When the input is @int.min_value (-2147483648), returns @int.min_value itself, since its absolute value is not representable as an Int.

    Example:

    test {
    inspect(Int::abs(42), content="42")
    inspect(Int::abs(-42), content="42")
    inspect(Int::abs(0), content="0")
    }

    Int::add

    fn Int::add(self : Int, other : Int) -> Int

    Int::asr

    #deprecated("Use infix operator `>>` instead")
    fn Int::asr(self : Int, other : Int) -> Int

    Performs an arithmetic right shift operation on a 32-bit integer value, preserving the sign bit by replicating it into the positions vacated by the shift. This is a deprecated function; use the infix operator >> instead.

    Parameters:

    • self : The integer value to be shifted.
    • shift : The number of positions to shift right. Must be non-negative.

    Returns a new integer value that is the result of arithmetically shifting self right by shift positions.

    Example:

    test {
    let x = -16
    inspect(x >> 2, content="-4") // Right shift preserves sign bit
    }

    Int::clamp

    fn Int::clamp(self : Int, min~ : Int, max~ : Int) -> Int

    Clamps the value self between min and max. Aborts if min is greater than max.

    Example:
    test {
    inspect((1).clamp(min=0, max=2), content="1")
    inspect((-1).clamp(min=0, max=2), content="0")
    inspect((3).clamp(min=0, max=2), content="2")
    inspect((-1).clamp(min=0, max=2), content="0")
    }

    Int::clz

    fn Int::clz(self : Int) -> Int

    Counts the number of consecutive zero bits at the most significant end of the integer's binary representation.

    Parameters:

    • self : The integer value whose leading zeros are to be counted.

    Returns the number of leading zero bits (0 to 32). For example, returns 0 if the value is negative (the sign bit is 1), returns 32 if the value is 0 (all bits are zeros).

    Example:

    test {
    let x = 0
    inspect(x.clz(), content="32") // All bits are zero
    let y = -1
    inspect(y.clz(), content="0") // The sign bit is set
    let z = 16
    inspect(z.clz(), content="27") // Binary: ...00010000
    }

    Int::compare

    fn Int::compare(self : Int, other : Int) -> Int

    Int::ctz

    fn Int::ctz(self : Int) -> Int

    Counts the number of consecutive zero bits at the least significant end of the integer's binary representation.

    Parameters:

    • self : The integer value whose trailing zeros are to be counted.

    Returns the number of trailing zero bits (0 to 32). For example, returns 0 if the value is odd (least significant bit is 1), returns 32 if the value is 0 (all bits are zeros).

    Example:

    test {
    let x = 0
    inspect(x.ctz(), content="32") // All bits are zero
    let y = 1
    inspect(y.ctz(), content="0") // No trailing zeros
    let z = 16
    inspect(z.ctz(), content="4") // Binary: ...10000
    }

    Int::div

    fn Int::div(self : Int, other : Int) -> Int

    Int::equal

    fn Int::equal(self : Int, other : Int) -> Bool

    Int::hash

    fn Int::hash(self : Int) -> Int

    Int::is_leading_surrogate

    fn Int::is_leading_surrogate(self : Int) -> Bool

    Checks if the integer value represents a UTF-16 leading surrogate. Leading surrogates are in the range 0xD800 to 0xDBFF.

    Example:
    test {
    inspect((0xD800).is_leading_surrogate(), content="true")
    inspect((0xDBFF).is_leading_surrogate(), content="true")
    inspect((0xDC00).is_leading_surrogate(), content="false")
    inspect((0x41).is_leading_surrogate(), content="false") // 'A'
    }

    Int::is_neg

    fn Int::is_neg(self : Int) -> Bool

    Tests whether an integer is negative.

    Parameters:

    • self : The integer to test.

    Returns true if the integer is negative, false otherwise.

    Example:

    test {
    let neg = -42
    let zero = 0
    let pos = 42
    inspect(neg.is_neg(), content="true")
    inspect(zero.is_neg(), content="false")
    inspect(pos.is_neg(), content="false")
    }

    Int::is_non_neg

    fn Int::is_non_neg(self : Int) -> Bool

    Tests whether an integer is non-negative (greater than or equal to zero).

    Parameters:

    • self : The integer to test.

    Returns true if the integer is greater than or equal to zero, false otherwise.

    Example:

    test {
    let neg = -42
    let zero = 0
    let pos = 42
    inspect(neg.is_non_neg(), content="false")
    inspect(zero.is_non_neg(), content="true")
    inspect(pos.is_non_neg(), content="true")
    }

    Int::is_non_pos

    fn Int::is_non_pos(self : Int) -> Bool

    Tests whether an integer is non-positive (less than or equal to zero).

    Parameters:

    • self : The integer to test.

    Returns true if the integer is less than or equal to zero, false otherwise.

    Example:

    test {
    let neg = -42
    let zero = 0
    let pos = 42
    inspect(neg.is_non_pos(), content="true")
    inspect(zero.is_non_pos(), content="true")
    inspect(pos.is_non_pos(), content="false")
    }

    Int::is_pos

    fn Int::is_pos(self : Int) -> Bool

    Tests whether an integer is strictly positive.

    Parameters:

    • self : The integer to test.

    Returns true if the integer is strictly positive, false otherwise.

    Example:

    test {
    let neg = -42
    let zero = 0
    let pos = 42
    inspect(neg.is_pos(), content="false")
    inspect(zero.is_pos(), content="false")
    inspect(pos.is_pos(), content="true")
    }

    Int::is_surrogate

    fn Int::is_surrogate(self : Int) -> Bool

    Checks if the integer value represents any UTF-16 surrogate (leading or trailing). Surrogates are in the range 0xD800 to 0xDFFF.

    Example:
    test {
    inspect((0xD800).is_surrogate(), content="true") // leading surrogate
    inspect((0xDC00).is_surrogate(), content="true") // trailing surrogate
    inspect((0xDFFF).is_surrogate(), content="true") // trailing surrogate
    inspect((0x41).is_surrogate(), content="false") // 'A'
    inspect((0x1F600).is_surrogate(), content="false") // 😀 emoji codepoint
    }

    Int::is_trailing_surrogate

    fn Int::is_trailing_surrogate(self : Int) -> Bool

    Checks if the integer value represents a UTF-16 trailing surrogate. Trailing surrogates are in the range 0xDC00 to 0xDFFF.

    Example:
    test {
    inspect((0xDC00).is_trailing_surrogate(), content="true")
    inspect((0xDFFF).is_trailing_surrogate(), content="true")
    inspect((0xD800).is_trailing_surrogate(), content="false")
    inspect((0x41).is_trailing_surrogate(), content="false") // 'A'
    }

    Int::land

    fn Int::land(self : Int, other : Int) -> Int

    Int::lnot

    fn Int::lnot(self : Int) -> Int

    Performs a bitwise NOT operation on a 32-bit integer. Flips each bit in the integer's binary representation (0 becomes 1 and 1 becomes 0).

    Parameters:

    • value : The 32-bit integer on which to perform the bitwise NOT operation.

    Returns a new integer with all bits flipped from the input value.

    Example:

    test {
    let a = -1 // All bits are 1
    let b = 0 // All bits are 0
    inspect(a.lnot(), content="0")
    inspect(b.lnot(), content="-1")
    }

    Int::lor

    fn Int::lor(self : Int, other : Int) -> Int

    Int::lsl

    #deprecated("Use infix operator `<<` instead")
    fn Int::lsl(self : Int, other : Int) -> Int

    Performs a left shift operation on a 32-bit integer. Shifts each bit in the integer to the left by the specified number of positions, filling the vacated bit positions with zeros.

    Parameters:

    • self : The integer value to be shifted.
    • shift : The number of positions to shift the bits to the left.

    Returns an integer containing the result of shifting self left by shift positions.

    Example:

    test {
    let x = 1
    inspect(x << 3, content="8") // Binary: 1 -> 1000
    let y = 42
    inspect(y << 2, content="168") // Binary: 101010 -> 10101000
    }

    Int::lsr

    #deprecated("Use UInt type and infix operator `>>` instead")
    fn Int::lsr(self : Int, other : Int) -> Int

    Performs a logical right shift operation on a signed 32-bit integer. In a logical right shift, zeros are shifted in from the left, regardless of the sign bit. This function is DEPRECATED and users should use UInt type with the infix operator >> instead.

    Parameters:

    • self : The signed 32-bit integer value to be shifted.
    • shift : The number of positions to shift right. Must be non-negative.

    Returns a signed 32-bit integer containing the same bits as if the input were treated as an unsigned integer and shifted right logically.

    Example:

    test {
    let x = -4 // Binary: 11111...11100
    let unsigned = x.reinterpret_as_uint() // Convert to UInt first
    inspect(unsigned >> 1, content="2147483646") // Using the recommended operator
    }

    Int::lxor

    fn Int::lxor(self : Int, other : Int) -> Int

    Int::max

    fn Int::max(self : Int, other : Int) -> Int

    Returns the maximum of two integers.

    Example:
    test {
    inspect((1).max(2), content="2")
    inspect((2).max(1), content="2")
    }

    Int::min

    fn Int::min(self : Int, other : Int) -> Int

    Returns the minimum of two integers.

    Example:
    test {
    inspect((1).min(2), content="1")
    inspect((2).min(1), content="1")
    }

    Int::mod

    fn Int::mod(self : Int, other : Int) -> Int

    Int::mul

    fn Int::mul(self : Int, other : Int) -> Int

    Int::neg

    fn Int::neg(self : Int) -> Int

    Int::next_power_of_two

    fn Int::next_power_of_two(self : Int) -> Int

    Returns the smallest power of two greater than or equal to self. This function will panic if self is negative. For values greater than the largest representable power of two (2^30 = 1073741824), it returns the largest representable power of two.

    Example:
    test {
    inspect((0).next_power_of_two(), content="1")
    inspect((1).next_power_of_two(), content="1")
    inspect((2).next_power_of_two(), content="2")
    inspect((3).next_power_of_two(), content="4")
    inspect((8).next_power_of_two(), content="8")
    inspect((1073741824).next_power_of_two(), content="1073741824")
    inspect((2000000000).next_power_of_two(), content="1073741824")
    }

    Int::popcnt

    fn Int::popcnt(self : Int) -> Int

    Counts the number of set bits (1s) in the binary representation of a 32-bit integer.

    Parameters:

    • self : The 32-bit integer whose bits are to be counted.

    Returns the number of bits set to 1 in the binary representation of the input integer.

    Example:

    test {
    let x = 0b1011 // Binary: 1011 (3 bits set)
    inspect(x.popcnt(), content="3")
    let y = -1 // All bits set in two's complement
    inspect(y.popcnt(), content="32")
    }

    Int::reinterpret_as_float

    #deprecated("Use `Float::reinterpret_from_int` instead")
    fn Int::reinterpret_as_float(self : Int) -> Float

    Reinterpret Int bit pattern as Float (deprecated alias). Function reinterpret_as_float.

    Int::reinterpret_as_uint

    fn Int::reinterpret_as_uint(self : Int) -> UInt

    reinterpret the signed int as unsigned int, when the value is non-negative, i.e, 0..=2^31-1, the value is the same. When the value is negative, it turns into a large number, for example, -1 turns into 2^32-1

    Int::shl

    #deprecated("Use infix operator `<<` instead")
    fn Int::shl(self : Int, other : Int) -> Int

    Performs a left shift operation on a 32-bit integer. Shifts the bits of the first operand to the left by the specified number of positions. The rightmost positions are filled with zeros.

    Parameters:

    • value : The integer value to be shifted.
    • shift : The number of positions to shift left. Must be non-negative and less than 32.

    Returns a new integer value after performing the left shift operation. The value is equal to multiplying the input by 2 raised to the power of the shift count.

    Example:

    test {
    let x = 1
    inspect(x << 3, content="8") // Equivalent to x << 3
    }

    Int::shr

    #deprecated("Use infix operator `>>` instead")
    fn Int::shr(self : Int, other : Int) -> Int

    Performs an arithmetic right shift operation on a 32-bit integer by the specified number of positions. The operation preserves the sign bit, replicating it into the positions vacated by the shift.

    Parameters:

    • self : The integer value to be shifted.
    • shift : The number of positions to shift right.

    Returns a new integer representing the result of shifting self right by shift positions.

    Example:

    test {
    let n = -1024
    inspect(n >> 3, content="-128") // Preserves sign bit during right shift
    }

    Int::sub

    fn Int::sub(self : Int, other : Int) -> Int

    Int::to_byte

    fn Int::to_byte(self : Int) -> Byte

    Converts a 32-bit signed integer to a byte by taking its least significant 8 bits. Any bits beyond the first 8 bits are truncated.

    Parameters:

    • value : The 32-bit signed integer to be converted. Only the least significant 8 bits will be used.

    Returns a byte containing the least significant 8 bits of the input integer.

    Example:

    test {
    let n = 258 // In binary: 100000010
    inspect(n.to_byte(), content="b'\\x02'") // Only keeps 00000010
    let neg = -1 // In binary: all 1's
    inspect(neg.to_byte(), content="b'\\xFF'") // Only keeps 11111111
    }

    Int::to_char

    fn Int::to_char(self : Int) -> Char?

    Convert integer to Char if it is a valid Unicode scalar value.

    Int::to_double

    fn Int::to_double(self : Int) -> Double

    Converts a 32-bit integer to a double-precision floating-point number. The conversion preserves the exact value since all integers in the range of Int can be represented exactly as Double values.

    Parameters:

    • self : The 32-bit integer to be converted.

    Returns a double-precision floating-point number that represents the same numerical value as the input integer.

    Example:

    test {
    let n = 42
    inspect(n.to_double(), content="42")
    let neg = -42
    inspect(neg.to_double(), content="-42")
    }

    Int::to_float

    #deprecated("Use `Float::from_int` instead")
    fn Int::to_float(self : Int) -> Float

    Convert Int to Float (deprecated alias). Convert to float.

    Int::to_int16

    #deprecated("Use `Int16::from_int` instead")
    fn Int::to_int16(self : Int) -> Int16

    Convert Int to Int16 (deprecated alias). Convert to int16.

    Int::to_int64

    fn Int::to_int64(self : Int) -> Int64

    Converts a 32-bit signed integer to a 64-bit signed integer. All 32-bit integers can be represented exactly in 64-bit integer format, so the conversion is lossless.

    Parameters:

    • self : The 32-bit signed integer to be converted.

    Returns a 64-bit signed integer that represents the same numerical value as the input.

    Example:

    test {
    let n = 42
    inspect(n.to_int64(), content="42")
    let neg = -42
    inspect(neg.to_int64(), content="-42")
    }

    Int::to_json

    fn Int::to_json(self : Int) -> Json

    Int::to_string

    fn Int::to_string(self : Int, radix? : Int) -> String

    Converts an integer to its string representation in the specified radix (base). Example:
    inspect((255).to_string(radix=16), content="ff") inspect((-255).to_string(radix=16), content="-ff")

    Int::to_uint

    #deprecated("Use `reinterpret_as_uint` instead")
    fn Int::to_uint(self : Int) -> UInt

    Reinterprets a signed 32-bit integer as an unsigned 32-bit integer. For numbers within the range [0, 2^31-1], the value remains the same. For negative numbers, they are reinterpreted as large positive numbers in the range [2^31, 2^32-1].

    Parameters:

    • value : The signed 32-bit integer to be reinterpreted.

    Returns an unsigned 32-bit integer that has the same bit pattern as the input.

    Example:

    test {
    let pos = 42
    let neg = -1
    inspect(pos.reinterpret_as_uint(), content="42")
    inspect(neg.reinterpret_as_uint(), content="4294967295") // 2^32 - 1
    }

    Int::to_uint16

    fn Int::to_uint16(self : Int) -> UInt16

    Converts a 32-bit signed integer to a 16-bit unsigned integer by truncating its value to fit within the range of 0 to 65535.

    Parameters:

    • integer : The 32-bit signed integer to be converted. Values outside the range of UInt16 will be truncated to fit.

    Returns a 16-bit unsigned integer containing the lower 16 bits of the input value.

    Example:

    test {
    let n = 42
    inspect(n.to_uint16(), content="42")
    let neg = -1
    inspect(neg.to_uint16(), content="65535") // -1 becomes max value of UInt16
    let large = 65536
    inspect(large.to_uint16(), content="0") // Values wrap around
    }

    Int::to_uint64

    fn Int::to_uint64(self : Int) -> UInt64

    Converts a 32-bit signed integer to an unsigned 64-bit integer by first converting it to a signed 64-bit integer and then reinterpreting the bits as an unsigned value.

    Parameters:

    • value : The 32-bit signed integer to be converted.

    Returns an unsigned 64-bit integer representing the same bit pattern as the input value when extended to 64 bits.

    Example:

    test {
    let pos = 42
    inspect(pos.to_uint64(), content="42")
    let neg = -1
    inspect(neg.to_uint64(), content="18446744073709551615") // 2^64 - 1
    }

    Int::until

    fn Int::until(self : Int, end : Int, step? : Int, inclusive? : Bool) -> Iter[Int]

    Creates an iterator that iterates over a range of Int with default step 1. To grow the range downward, set the step parameter to a negative value.

    Arguments

    • start - The starting value of the range (inclusive).
    • end - The ending value of the range (exclusive by default).
    • step - The step size of the range (default 1).
    • inclusive - Whether the ending value is inclusive (default false).

    Returns

    Returns an iterator that iterates over the range of Int from start to end - 1.

    Int64

    Note

    Int64 is a built-in type. The documentation may not be complete here. You can find all methods and implementations in the core/builtin and core/int64 package.

    Int64::Int64

    fn Int64::Int64(self : Int64) -> Int64

    The identity constructor for Int64, allowing values to be written using constructor syntax, e.g. Int64(3).

    Example:

    test {
    inspect(Int64(3), content="3")
    }

    Int64::abs

    fn Int64::abs(self : Int64) -> Int64

    Computes the absolute value of a 64-bit integer.

    Parameters:

    • self : The 64-bit integer whose absolute value is to be computed.

    Returns the absolute value of the input integer. When the input is @int64.MIN_VALUE (-9223372036854775808), returns @int64.MIN_VALUE itself, since its absolute value is not representable as an Int64.

    Example:

    test {
    inspect(42L.abs(), content="42")
    inspect((-42L).abs(), content="42")
    inspect(0L.abs(), content="0")
    }

    Int64::add

    fn Int64::add(self : Int64, other : Int64) -> Int64

    Int64::asr

    #deprecated("Use infix operator `>>` instead")
    fn Int64::asr(self : Int64, other : Int) -> Int64

    DEPRECATED: Use the infix operator >> instead.

    Performs an arithmetic right shift operation on a 64-bit integer. In an arithmetic right shift, the leftmost bit (sign bit) is copied to fill in from the left. This preserves the sign of the number.

    Parameters:

    • self : The 64-bit integer to be shifted.
    • positions : The number of positions to shift right. Must be non-negative.

    Returns a new 64-bit integer that is the result of shifting self right by positions bits, with sign extension.

    Example:

    test {
    let x = -240L // 0b1111_1111_0001_0000 in two's complement
    inspect(x >> 4, content="-15") // 0b1111_1111_1111_0001, using recommended syntax
    }

    Int64::clamp

    fn Int64::clamp(self : Int64, min~ : Int64, max~ : Int64) -> Int64

    Clamps a 64-bit signed integer into the inclusive range [min, max].

    Parameters:

    • self : The value to clamp.
    • min : The lower bound of the range.
    • max : The upper bound of the range.

    Returns min if self is less than min, max if self is greater than max, and self otherwise. Aborts if min is greater than max.

    Example:

    test {
    inspect(5L.clamp(min=0L, max=10L), content="5")
    inspect((-5L).clamp(min=0L, max=10L), content="0")
    inspect(15L.clamp(min=0L, max=10L), content="10")
    }

    Int64::clz

    fn Int64::clz(self : Int64) -> Int

    Counts the number of leading zero bits in a 64-bit signed integer, starting from the most significant bit.

    Parameters:

    • number : The 64-bit signed integer whose leading zeros are to be counted.

    Returns the number of leading zero bits (0 to 64).

    Example:

    test {
    let a = 0x0000_0001_0000_0000L
    inspect(a.clz(), content="31") // 31 leading zeros before the first 1 bit
    let b = 0L
    inspect(b.clz(), content="64") // All bits are zero
    }

    Int64::compare

    fn Int64::compare(self : Int64, other : Int64) -> Int

    Int64::ctz

    fn Int64::ctz(self : Int64) -> Int

    Returns the number of trailing zero bits in a 64-bit integer. For zero input, returns 64.

    Parameters:

    • value : The 64-bit integer to count trailing zeros in.

    Returns the number of trailing zero bits (0 to 64).

    Example:

    test {
    inspect(0x8000000000000000L.ctz(), content="63") // Binary: 1000...0000
    inspect(0x0000000000000001L.ctz(), content="0") // Binary: ...0001
    inspect(0L.ctz(), content="64") // All zeros
    }

    Int64::div

    fn Int64::div(self : Int64, other : Int64) -> Int64

    Int64::equal

    fn Int64::equal(self : Int64, other : Int64) -> Bool

    Int64::from_int

    fn Int64::from_int(i : Int) -> Int64

    Converts a 32-bit integer (Int) to a 64-bit integer (Int64).

    Parameters:

    • i : The integer value to be converted.

    Returns the converted 64-bit integer (Int64) value.

    Example:

    test {
    inspect(Int64::from_int(42), content="42")
    }

    Int64::hash

    fn Int64::hash(self : Int64) -> Int

    Int64::land

    fn Int64::land(self : Int64, other : Int64) -> Int64

    Int64::lnot

    fn Int64::lnot(self : Int64) -> Int64

    Performs a bitwise NOT operation on a 64-bit integer. Each bit in the input value is flipped (0 becomes 1 and 1 becomes 0).

    Parameters:

    • self : The 64-bit integer on which to perform the bitwise NOT operation.

    Returns a new 64-bit integer where each bit is the inverse of the corresponding bit in the input value.

    Example:

    test {
    let a = -1L // All bits are 1
    let b = 0L // All bits are 0
    inspect(a.lnot(), content="0")
    inspect(b.lnot(), content="-1")
    }

    Int64::lor

    fn Int64::lor(self : Int64, other : Int64) -> Int64

    Int64::lsl

    #deprecated("Use infix operator `<<` instead")
    fn Int64::lsl(self : Int64, other : Int) -> Int64

    Performs a left shift operation on a 64-bit signed integer. Shifts each bit in the integer to the left by the specified number of positions, filling the vacated bit positions with zeros.

    Parameters:

    • self : The 64-bit signed integer to be shifted.
    • shift : The number of positions to shift. Must be non-negative and less than 64.

    Returns a new 64-bit integer with bits shifted left by the specified number of positions.

    Example:

    test {
    let x = 1L
    inspect(x << 2, content="4") // Binary: 1 -> 100
    }

    Int64::lsr

    #deprecated("Use UInt64 type and infix operator `>>` instead")
    fn Int64::lsr(self : Int64, other : Int) -> Int64

    DEPRECATED: Use UInt64 type and infix operator >> instead.

    Performs a logical right shift on a 64-bit integer value. In a logical right shift, zeros are shifted in from the left, regardless of the sign bit.

    Parameters:

    • value : The 64-bit integer value to be shifted.
    • shift : The number of positions to shift right. Must be non-negative.

    Returns a new 64-bit integer value that is the result of shifting the bits of value right by shift positions.

    Example:

    test {
    let x = (-4L).reinterpret_as_uint64() // Convert to UInt64 first
    inspect(x >> 1, content="9223372036854775806") // Using the recommended operator
    }

    Int64::lxor

    fn Int64::lxor(self : Int64, other : Int64) -> Int64

    Int64::max

    fn Int64::max(self : Int64, other : Int64) -> Int64

    Returns the larger of two 64-bit signed integers.

    Parameters:

    • self : The first integer to compare.
    • other : The second integer to compare.

    Returns self if it is not less than other, other otherwise.

    Example:

    test {
    inspect(1L.max(2L), content="2")
    inspect(2L.max(1L), content="2")
    inspect((-1L).max(0L), content="0")
    }

    Int64::min

    fn Int64::min(self : Int64, other : Int64) -> Int64

    Returns the smaller of two 64-bit signed integers.

    Parameters:

    • self : The first integer to compare.
    • other : The second integer to compare.

    Returns self if it is not greater than other, other otherwise.

    Example:

    test {
    inspect(1L.min(2L), content="1")
    inspect(2L.min(1L), content="1")
    inspect((-1L).min(0L), content="-1")
    }

    Int64::mod

    fn Int64::mod(self : Int64, other : Int64) -> Int64

    Int64::mul

    fn Int64::mul(self : Int64, other : Int64) -> Int64

    Int64::neg

    fn Int64::neg(self : Int64) -> Int64

    Int64::popcnt

    fn Int64::popcnt(self : Int64) -> Int

    Returns the number of 1 bits ('population count') in the 64-bit integer's binary representation.

    Parameters:

    • value : The 64-bit integer whose bits are to be counted.

    Returns an integer representing the number of set bits (1s) in the binary representation of the input.

    Example:

    test {
    let x = 0x7000_0001_1F00_100FL // Binary: 0111 0000 ... 0001 1111 0000 0000 0001 0000 0000 1111
    inspect(x.popcnt(), content="14")
    }

    test {
    inspect((-1L).popcnt(), content="64") // All bits set
    inspect(0L.popcnt(), content="0") // No bits set
    }

    Int64::reinterpret_as_double

    fn Int64::reinterpret_as_double(self : Int64) -> Double

    Reinterprets the bits of a 64-bit signed integer as a double-precision floating-point number (IEEE 754). The bit pattern is preserved exactly, only the type interpretation changes.

    Parameters:

    • value : The 64-bit signed integer whose bits are to be reinterpreted as a double-precision floating-point number.

    Returns a double-precision floating-point number whose bit pattern is identical to the input integer.

    Example:

    test {
    let n = 4607182418800017408L // Bit pattern for 1.0
    inspect(n.reinterpret_as_double(), content="1")
    }

    Int64::reinterpret_as_uint64

    fn Int64::reinterpret_as_uint64(self : Int64) -> UInt64

    Reinterprets a 64-bit signed integer as an unsigned 64-bit integer without changing its bit pattern. The reinterpretation follows the standard two's complement representation rules.

    Parameters:

    • self : The 64-bit signed integer to be reinterpreted.

    Returns a 64-bit unsigned integer that has the same bit pattern as the input.

    Example:

    test {
    let neg = -1L
    inspect(neg.reinterpret_as_uint64(), content="18446744073709551615") // All bits set to 1
    let pos = 42L
    inspect(pos.reinterpret_as_uint64(), content="42") // Positive numbers remain unchanged
    }

    Int64::shl

    #deprecated("Use infix operator `<<` instead")
    fn Int64::shl(self : Int64, other : Int) -> Int64

    Performs a left shift operation on a 64-bit integer value. Shifts the bits of the integer to the left by a specified number of positions, filling the rightmost positions with zeros.

    Parameters:

    • self : The 64-bit integer value to be shifted.
    • shift : The number of positions to shift the bits to the left.

    Returns a new 64-bit integer value after performing the left shift operation.

    Example:

    test {
    let x = 1L
    inspect(x << 3, content="8") // Equivalent to x << 3
    }

    Int64::shr

    #deprecated("Use infix operator `>>` instead")
    fn Int64::shr(self : Int64, other : Int) -> Int64

    Performs an arithmetic right shift operation on a 64-bit integer value, shifting the bits to the right by the specified number of positions. The sign bit is copied to fill the leftmost positions.

    Parameters:

    • self : The 64-bit integer value to be shifted.
    • shift : The number of bit positions to shift right. Must be non-negative.

    Returns a new Int64 value representing the result of the arithmetic right shift operation.

    Example:

    test {
    let n = -1024L
    inspect(n >> 3, content="-128") // Preserves sign bit
    }

    Int64::sub

    fn Int64::sub(self : Int64, other : Int64) -> Int64

    Int64::to_byte

    fn Int64::to_byte(self : Int64) -> Byte

    Converts a 64-bit signed integer to a byte by taking its least significant 8 bits. Any bits beyond the first 8 bits are truncated.

    Parameters:

    • self : The 64-bit signed integer to be converted. Only the least significant 8 bits will be used.

    Returns a byte containing the least significant 8 bits of the input integer.

    Example:

    test {
    let n = 258L // In binary: 100000010
    inspect(n.to_byte(), content="b'\\x02'") // Only keeps 00000010
    let neg = -1L // In binary: all 1's
    inspect(neg.to_byte(), content="b'\\xFF'") // Only keeps 11111111
    }

    Int64::to_double

    fn Int64::to_double(self : Int64) -> Double

    Converts a 64-bit signed integer to a double-precision floating-point number.

    Parameters:

    • self : The 64-bit signed integer to be converted.

    Returns a double-precision floating-point number that represents the same value as the input integer.

    Example:

    test {
    let big = 9223372036854775807L // max value of Int64
    inspect(big.to_double(), content="9223372036854776000")
    let neg = -42L
    inspect(neg.to_double(), content="-42")
    }

    Int64::to_float

    #deprecated("Use `Float::from_int64` instead")
    fn Int64::to_float(self : Int64) -> Float

    Convert Int64 to Float (deprecated alias).

    Int64::to_int

    fn Int64::to_int(self : Int64) -> Int

    Converts a 64-bit signed integer to a 32-bit signed integer by truncating higher bits.

    Parameters:

    • value : The 64-bit signed integer (Int64) to be converted.

    Returns a 32-bit signed integer (Int). Note that values outside the range of 32-bit integers will be truncated, potentially leading to loss of information.

    Example:

    test {
    let small = 42L
    let big = 2147483648L // 2^31
    inspect(small.to_int(), content="42")
    inspect(big.to_int(), content="-2147483648") // Truncated to Int.min_value
    }

    Int64::to_json

    fn Int64::to_json(self : Int64) -> Json

    Int64::to_string

    fn Int64::to_string(self : Int64, radix? : Int) -> String

    Converts a 64-bit integer to its string representation in the specified radix (base).

    Int64::to_uint16

    fn Int64::to_uint16(self : Int64) -> UInt16

    Converts a 64-bit signed integer to a 16-bit unsigned integer by truncating the value to fit within the range of UInt16 (0 to 65535).

    Parameters:

    • value : The 64-bit signed integer to be converted to UInt16.

    Returns a 16-bit unsigned integer representing the lower 16 bits of the input value.

    Example:

    test {
    inspect(42L.to_uint16(), content="42")
    inspect((-1L).to_uint16(), content="65535") // Wraps around to maximum UInt16 value
    inspect(70000L.to_uint16(), content="4464") // Value is truncated
    }

    Int64::to_uint64

    #deprecated("Use `reinterpret_as_uint64` instead")
    fn Int64::to_uint64(self : Int64) -> UInt64

    Reinterprets a 64-bit signed integer as an unsigned 64-bit integer without changing its bits. When the value is non-negative, i.e., within the range [0, 2^63-1], the value remains the same. When the value is negative, it becomes a large number in the range [2^63, 2^64-1].

    Parameters:

    • value : The 64-bit signed integer (Int64) to be reinterpreted.

    Returns an unsigned 64-bit integer (UInt64) containing the same bit pattern as the input.

    Example:

    test {
    let pos = 42L
    let neg = -1L
    inspect(pos.reinterpret_as_uint64(), content="42")
    inspect(neg.reinterpret_as_uint64(), content="18446744073709551615") // 2^64 - 1
    }

    Int64::until

    fn Int64::until(self : Int64, end : Int64, step? : Int64, inclusive? : Bool) -> Iter[Int64]

    Creates an iterator that iterates over a range of Int64 with default step 1L. To grow the range downward, set the step parameter to a negative value.

    Arguments

    • start - The starting value of the range (inclusive).
    • end - The ending value of the range (exclusive by default).
    • step - The step size of the range (default 1L).
    • inclusive - Whether the ending value is inclusive (default false).

    Returns

    Returns an iterator that iterates over the range of Int64 from start to end - 1.

    Option

    Option::bind

    fn[T, U] Option::bind(self : T?, f : (T) -> U? raise?) -> U? raise?

    Binds an option to a function that returns another option.

    Example

    test {
    let a = Option::Some(5)
    let r1 = a.bind(x => Some(x * 2))
    @test.assert_eq(r1, Some(10))
    let b : Int? = None
    let r2 = b.bind(x => Some(x * 2))
    @test.assert_eq(r2, None)
    }

    Option::compare

    fn[X : Compare + Eq] Option::compare(self : X?, other : X?) -> Int

    Option::equal

    fn[X : Eq] Option::equal(self : X?, other : X?) -> Bool

    Option::filter

    fn[T] Option::filter(self : T?, f : (T) -> Bool raise?) -> T? raise?

    Filters the option by applying the given predicate function f.

    If the predicate function f returns true for the value contained in the option, the same option is returned. Otherwise, None is returned.

    Example

    test {
    let x = Some(3)
    @test.assert_eq(x.filter(x => x > 5), None)
    @test.assert_eq(x.filter(x => x < 5), Some(3))
    }

    Option::flatten

    #deprecated("use `option.bind(x => x)` instead")
    fn[T] Option::flatten(self : T??) -> T?

    Flatten nested option/result value.

    Option::hash

    fn[X : Hash] Option::hash(self : X?) -> Int

    Option::is_empty

    #deprecated("use `x is None` instead")
    fn[T] Option::is_empty(self : T?) -> Bool

    Checks if the option is empty.

    Option::is_none

    #deprecated("use `x is None` instead")
    fn[T] Option::is_none(self : T?) -> Bool

    Checks if the option is None.

    Option::is_some

    #deprecated("use `x is Some(_)` instead")
    fn[T] Option::is_some(self : T?) -> Bool

    Checks if the option contains a value.

    Option::iter

    #alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
    fn[T] Option::iter(self : T?) -> Iter[T]

    Return an iterator via iter.

    Option::map

    fn[T, U] Option::map(self : T?, f : (T) -> U raise?) -> U? raise?

    Maps the value of an Option using a provided function.

    Example

    test {
    let a = Some(5)
    @test.assert_eq(a.map(x => x * 2), Some(10))
    let b = None
    @test.assert_eq(b.map(x => x * 2), None)
    }

    Option::map_or

    fn[T, U] Option::map_or(self : T?, default : U, f : (T) -> U raise?) -> U raise?

    Returns the provided default result (if none), or applies a function to the contained value (if any). Arguments passed to map_or are eagerly evaluated; if you are passing the result of a function call, it is recommended to use map_or_else, which is lazily evaluated.

    Example

    test {
    let a = Some(5)
    @test.assert_eq(a.map_or(3, x => x * 2), 10)
    }

    Option::map_or_else

    fn[T, U] Option::map_or_else(self : T?, default : () -> U raise?, f : (T) -> U raise?) -> U raise?

    Computes a default function result (if none), or applies a different function to the contained value (if any).

    Example

    test {
    let a = Some(5)
    @test.assert_eq(a.map_or_else(() => 3, x => x * 2), 10)
    }

    Option::to_json

    fn[T : ToJson] Option::to_json(self : T?) -> Json

    Option::to_string

    #deprecated("Option does not have a meaningful string representation")
    fn[X : Show] Option::to_string(self : X?) -> String

    Convert to string.

    Option::unwrap

    fn[X] Option::unwrap(self : X?) -> X

    Extract the value in Some.

    If the value is None, it throws a panic.

    Option::unwrap_or

    #alias(or, deprecated="`or` is deprecated, use `unwrap_or` instead")
    fn[T] Option::unwrap_or(self : T?, default : T) -> T

    Return the contained Some value or the provided default.

    Option::unwrap_or_default

    #alias(or_default, deprecated="`or_default` is deprecated, use `unwrap_or_default` instead")
    fn[T : Default] Option::unwrap_or_default(self : T?) -> T

    Return the contained Some value or the result of the T::default().

    Option::unwrap_or_else

    #alias(or_else, deprecated="`or_else` is deprecated, use `unwrap_or_else` instead")
    fn[T] Option::unwrap_or_else(self : T?, default : () -> T raise?) -> T raise?

    Return the contained Some value or the provided default.

    Default is lazily evaluated

    Option::unwrap_or_error

    #alias(or_error, deprecated="`or_error` is deprecated, use `unwrap_or_error` instead")
    fn[T, Err : Error] Option::unwrap_or_error(self : T?, err : Err) -> T raise Err

    Extract the wrapped value with unwrap_or_error semantics.

    ReadOnlyArray

    ReadOnlyArray::all

    #alias(every)
    fn[T] ReadOnlyArray::all(self : ReadOnlyArray[T], f : (T) -> Bool raise?) -> Bool raise?

    Checks if all elements satisfy the given predicate.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [2, 4, 6]
    inspect(arr.all(fn(x) { x % 2 == 0 }), content="true")
    let arr2 : ReadOnlyArray[Int] = [1, 2, 3]
    inspect(arr2.all(fn(x) { x % 2 == 0 }), content="false")
    }

    ReadOnlyArray::any

    #alias(exists)
    fn[T] ReadOnlyArray::any(self : ReadOnlyArray[T], f : (T) -> Bool raise?) -> Bool raise?

    Checks if any element satisfies the given predicate.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 3, 5]
    inspect(arr.any(fn(x) { x % 2 == 0 }), content="false")
    let arr2 : ReadOnlyArray[Int] = [1, 2, 3]
    inspect(arr2.any(fn(x) { x % 2 == 0 }), content="true")
    }

    ReadOnlyArray::at

    #alias("_[_]")
    fn[T] ReadOnlyArray::at(self : ReadOnlyArray[T], index : Int) -> T

    Access element at index in a read-only array.

    Panics if index is out of bounds.

    Example:

    test {
    let a : ReadOnlyArray[Int] = [10, 20, 30]
    inspect(a.at(1), content="20")
    }
    fn[T : Compare + Eq] ReadOnlyArray::binary_search(self : ReadOnlyArray[T], value : T) -> Result[Int, Int]

    Performs binary search on a sorted ReadOnlyArray.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 3, 5, 7, 9]
    debug_inspect(arr.binary_search(5), content="Ok(2)")
    debug_inspect(arr.binary_search(6), content="Err(3)")
    }

    ReadOnlyArray::binary_search_by

    fn[T] ReadOnlyArray::binary_search_by(self : ReadOnlyArray[T], cmp : (T) -> Int raise?) -> Result[Int, Int] raise?

    Performs binary search using a custom comparison function.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 3, 5, 7, 9]
    let result = arr.binary_search_by(fn(x) { x.compare(5) })
    debug_inspect(result, content="Ok(2)")
    }

    ReadOnlyArray::chunk_by

    fn[T] ReadOnlyArray::chunk_by(self : ReadOnlyArray[T], pred : (T, T) -> Bool raise?) -> Array[ArrayView[T]] raise?

    Groups consecutive elements into chunks where each adjacent pair satisfies pred. A new chunk starts as soon as pred(prev, cur) is false. Each returned sub-view shares the original backing storage.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 1, 2, 2, 2, 3, 1]
    debug_inspect(
    arr.chunk_by((a, b) => a == b),
    content=(
    #|[
    #| <ArrayView: [1, 1]>,
    #| <ArrayView: [2, 2, 2]>,
    #| <ArrayView: [3]>,
    #| <ArrayView: [1]>,
    #|]
    ),
    )
    }

    ReadOnlyArray::chunks

    fn[T] ReadOnlyArray::chunks(self : ReadOnlyArray[T], size : Int) -> Array[ArrayView[T]]

    Splits the array into consecutive non-overlapping chunks of length size, from left to right. The final chunk is shorter when length is not a multiple of size. Each returned sub-view shares the original backing storage — no allocation per chunk.

    Panics if size <= 0.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5, 6, 7]
    debug_inspect(
    arr.chunks(3),
    content=(
    #|[<ArrayView: [1, 2, 3]>, <ArrayView: [4, 5, 6]>, <ArrayView: [7]>]
    ),
    )
    }

    ReadOnlyArray::compare

    fn[T : Compare + Eq] ReadOnlyArray::compare(self : ReadOnlyArray[T], other : ReadOnlyArray[T]) -> Int

    ReadOnlyArray::contains

    fn[T : Eq] ReadOnlyArray::contains(self : ReadOnlyArray[T], value : T) -> Bool

    Checks if the ReadOnlyArray contains a specific value.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3]
    inspect(arr.contains(2), content="true")
    inspect(arr.contains(4), content="false")
    }

    ReadOnlyArray::each

    fn[T] ReadOnlyArray::each(self : ReadOnlyArray[T], f : (T) -> Unit raise?) -> Unit raise?

    Iterates over each element in the ReadOnlyArray.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3]
    let result = []
    arr.each(fn(x) { result.push(x * 2) })
    debug_inspect(result, content="[2, 4, 6]")
    }

    ReadOnlyArray::eachi

    fn[T] ReadOnlyArray::eachi(self : ReadOnlyArray[T], f : (Int, T) -> Unit raise?) -> Unit raise?

    Iterates over each element with its index.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [10, 20, 30]
    let result = []
    arr.eachi(fn(i, x) { result.push((i, x)) })
    debug_inspect(result, content="[(0, 10), (1, 20), (2, 30)]")
    }

    ReadOnlyArray::ends_with

    fn[T : Eq] ReadOnlyArray::ends_with(self : ReadOnlyArray[T], suffix : ArrayView[T]) -> Bool

    Checks if the ReadOnlyArray ends with the given suffix.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
    inspect(arr.ends_with([4, 5]), content="true")
    }

    ReadOnlyArray::equal

    fn[T : Eq] ReadOnlyArray::equal(self : ReadOnlyArray[T], other : ReadOnlyArray[T]) -> Bool

    ReadOnlyArray::filter

    fn[T] ReadOnlyArray::filter(self : ReadOnlyArray[T], f : (T) -> Bool raise?) -> ReadOnlyArray[T] raise?

    Returns a new ReadOnlyArray containing the elements for which f returns true, in original order.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
    debug_inspect(
    arr.filter(x => x % 2 == 0),
    content=(
    #|<ReadOnlyArray: [2, 4]>
    ),
    )
    }

    ReadOnlyArray::filter_map

    fn[A, B] ReadOnlyArray::filter_map(self : ReadOnlyArray[A], f : (A) -> B? raise?) -> ReadOnlyArray[B] raise?

    Returns a new ReadOnlyArray that maps and filters in one pass: for each element, Some(new_value) includes the mapped value and None drops it.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
    let out = arr.filter_map(x => if x % 2 == 0 { Some(x * 10) } else { None })
    debug_inspect(
    out,
    content=(
    #|<ReadOnlyArray: [20, 40]>
    ),
    )
    }

    ReadOnlyArray::fold

    fn[A, B] ReadOnlyArray::fold(self : ReadOnlyArray[A], init~ : B, f : (B, A) -> B raise?) -> B raise?

    Folds the ReadOnlyArray from left to right.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
    let sum = arr.fold(init=0, fn(acc, x) { acc + x })
    inspect(sum, content="15")
    }

    ReadOnlyArray::foldi

    fn[A, B] ReadOnlyArray::foldi(self : ReadOnlyArray[A], init~ : B, f : (Int, B, A) -> B raise?) -> B raise?

    Folds the ReadOnlyArray from left to right with index.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [2, 3]
    let sum = arr.foldi(init=0, fn(i, acc, x) { acc + i * x })
    inspect(sum, content="3") // 0 + (0*2) + (1*3) = 3
    }

    ReadOnlyArray::from_array

    fn[T] ReadOnlyArray::from_array(array : ArrayView[T]) -> ReadOnlyArray[T]

    Creates an ReadOnlyArray from a dynamic Array.

    Example

    test {
    let dynamic_array : Array[Int] = [1, 2, 3, 4, 5]
    let immut_array = ReadOnlyArray::from_array(dynamic_array)
    inspect(immut_array[0], content="1")
    }

    ReadOnlyArray::from_iter

    #alias(from_iterator, deprecated="`from_iterator` is deprecated, use `from_iter` instead")
    fn[T] ReadOnlyArray::from_iter(iter : Iter[T]) -> ReadOnlyArray[T]

    Creates an ReadOnlyArray from an iterator.

    Example

    test {
    let iter = 1, 2, 3
    let immut_array = ReadOnlyArray::from_iter(iter)
    inspect(immut_array[0], content="1")
    }

    ReadOnlyArray::get

    fn[T] ReadOnlyArray::get(self : ReadOnlyArray[T], index : Int) -> T?

    Safely retrieves an element at the specified index. Returns Some(element) if the index is valid, None otherwise.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3]
    debug_inspect(arr.get(1), content="Some(2)")
    debug_inspect(arr.get(5), content="None")
    }

    ReadOnlyArray::get_view

    fn[T] ReadOnlyArray::get_view(self : ReadOnlyArray[T], start? : Int, end? : Int) -> ArrayView[T]?

    Creates a view of a subarray, returning None when indices are invalid.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
    let start = 1
    let end = 4
    debug_inspect(
    arr.get_view(start~, end~),
    content=(
    #|Some(<ArrayView: [2, 3, 4]>)
    ),
    )
    let start = 4
    let end = 10
    debug_inspect(arr.get_view(start~, end~), content="None")
    }

    ReadOnlyArray::hash

    fn[T : Hash] ReadOnlyArray::hash(self : ReadOnlyArray[T]) -> Int

    ReadOnlyArray::is_empty

    fn[T] ReadOnlyArray::is_empty(self : ReadOnlyArray[T]) -> Bool

    Checks if the ReadOnlyArray is empty.

    Example

    test {
    let empty_arr : ReadOnlyArray[Int] = []
    inspect(empty_arr.is_empty(), content="true")
    let arr : ReadOnlyArray[Int] = [1, 2, 3]
    inspect(arr.is_empty(), content="false")
    }

    ReadOnlyArray::is_sorted

    fn[T : Compare + Eq] ReadOnlyArray::is_sorted(self : ReadOnlyArray[T]) -> Bool

    Checks if the ReadOnlyArray is sorted in non-decreasing order.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3]
    inspect(arr.is_sorted(), content="true")
    let arr2 : ReadOnlyArray[Int] = [2, 1]
    inspect(arr2.is_sorted(), content="false")
    }

    ReadOnlyArray::iter

    #alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
    fn[T] ReadOnlyArray::iter(self : ReadOnlyArray[T]) -> Iter[T]

    Creates an iterator over the elements of the ReadOnlyArray.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3]
    let mut sum = 0
    arr.iter().each(fn(x) { sum x })
    inspect(sum, content="6")
    }

    ReadOnlyArray::iter2

    fn[T] ReadOnlyArray::iter2(self : ReadOnlyArray[T]) -> Iter2[Int, T]

    Creates an iterator that yields both indices and values.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [10, 20, 30]
    let mut sum = 0
    arr.iter2().each(fn(i, x) { sum i + x })
    inspect(sum, content="63") // (0+10) + (1+20) + (2+30) = 63
    }

    ReadOnlyArray::join

    fn[A : ToStringView] ReadOnlyArray::join(self : ReadOnlyArray[A], separator : StringView) -> String

    Joins the string-renderable elements with a separator.

    Example

    test {
    let arr : ReadOnlyArray[String] = ["hello", "world", "moon"]
    inspect(arr.join(","), content="hello,world,moon")
    inspect(arr.join(" "), content="hello world moon")
    }

    ReadOnlyArray::last

    fn[T] ReadOnlyArray::last(self : ReadOnlyArray[T]) -> T?

    Returns the last element of the ReadOnlyArray, if any.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3]
    debug_inspect(arr.last(), content="Some(3)")
    let empty_arr : ReadOnlyArray[Int] = []
    debug_inspect(empty_arr.last(), content="None")
    }

    ReadOnlyArray::length

    fn[T] ReadOnlyArray::length(self : ReadOnlyArray[T]) -> Int

    Returns the length of the ReadOnlyArray.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3]
    inspect(arr.length(), content="3")
    }

    ReadOnlyArray::lexical_compare

    fn[T : Compare + Eq] ReadOnlyArray::lexical_compare(self : ReadOnlyArray[T], other : ReadOnlyArray[T]) -> Int

    Performs a lexicographical comparison of two arrays.

    Unlike the Compare trait implementation (shortlex — shorter arrays come first), this method compares purely by element values; length only breaks ties when one array is a prefix of the other.

    Example

    test {
    let a : ReadOnlyArray[Int] = [1, 2]
    let b : ReadOnlyArray[Int] = [1, 2, 3]
    inspect(a.lexical_compare(b), content="-1")
    inspect(b.lexical_compare(a), content="1")
    inspect(b.lexical_compare(b), content="0")
    let c : ReadOnlyArray[Int] = [1, 2, 4]
    inspect(b.lexical_compare(c), content="-1")
    }

    ReadOnlyArray::makei

    fn[T] ReadOnlyArray::makei(length : Int, value : (Int) -> T raise?) -> ReadOnlyArray[T] raise?

    Creates an ReadOnlyArray by applying a function to each index.

    Example

    test {
    let immut_array = ReadOnlyArray::makei(3, fn(i) { i * 2 })
    inspect(immut_array[1], content="2")
    }

    ReadOnlyArray::map

    fn[T, U] ReadOnlyArray::map(self : ReadOnlyArray[T], f : (T) -> U raise?) -> ReadOnlyArray[U] raise?

    Creates a new ReadOnlyArray by applying a function to each element.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3]
    let doubled = arr.map(fn(x) { x * 2 })
    inspect(doubled[0], content="2")
    inspect(doubled[2], content="6")
    }

    ReadOnlyArray::mapi

    fn[T, U] ReadOnlyArray::mapi(self : ReadOnlyArray[T], f : (Int, T) -> U raise?) -> ReadOnlyArray[U] raise?

    Creates a new ReadOnlyArray by applying a function to each element with its index.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [10, 20, 30]
    let result = arr.mapi(fn(i, x) { i + x })
    inspect(result[1], content="21") // index 1 + value 20 = 21
    }

    ReadOnlyArray::rev

    fn[T] ReadOnlyArray::rev(self : ReadOnlyArray[T]) -> ReadOnlyArray[T]

    Returns a new ReadOnlyArray with elements in reverse order.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
    let reversed = arr.rev()
    inspect(reversed[0], content="5")
    inspect(reversed[4], content="1")
    }

    ReadOnlyArray::rev_each

    fn[T] ReadOnlyArray::rev_each(self : ReadOnlyArray[T], f : (T) -> Unit raise?) -> Unit raise?

    Iterates over each element in reverse order.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3]
    let result = []
    arr.rev_each(fn(x) { result.push(x) })
    debug_inspect(result, content="[3, 2, 1]")
    }

    ReadOnlyArray::rev_eachi

    fn[T] ReadOnlyArray::rev_eachi(self : ReadOnlyArray[T], f : (Int, T) -> Unit raise?) -> Unit raise?

    Iterates over each element in reverse order with its index.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [10, 20, 30]
    let result = []
    arr.rev_eachi(fn(i, x) { result.push((i, x)) })
    debug_inspect(result, content="[(0, 30), (1, 20), (2, 10)]")
    }

    ReadOnlyArray::rev_fold

    fn[A, B] ReadOnlyArray::rev_fold(self : ReadOnlyArray[A], init~ : B, f : (B, A) -> B raise?) -> B raise?

    Folds the ReadOnlyArray from right to left.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3]
    let result = arr.rev_fold(init="", fn(acc, x) { acc + x.to_string() })
    inspect(result, content="321") // Processed in reverse order
    }

    ReadOnlyArray::rev_foldi

    fn[A, B] ReadOnlyArray::rev_foldi(self : ReadOnlyArray[A], init~ : B, f : (Int, B, A) -> B raise?) -> B raise?

    Folds the ReadOnlyArray from right to left with index.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [2, 3]
    let sum = arr.rev_foldi(init=0, fn(i, acc, x) { acc + i * x })
    inspect(sum, content="2") // 0 + (0*3) + (1*2) = 2
    }

    ReadOnlyArray::rev_iter

    fn[T] ReadOnlyArray::rev_iter(self : ReadOnlyArray[T]) -> Iter[T]

    Returns an iterator that yields each element from the last to the first.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3]
    let result = []
    arr.rev_iter().each(x => result.push(x))
    debug_inspect(result, content="[3, 2, 1]")
    }

    ReadOnlyArray::search

    fn[T : Eq] ReadOnlyArray::search(self : ReadOnlyArray[T], value : T) -> Int?

    Searches for an element and returns its index if found.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3, 2, 4]
    debug_inspect(arr.search(2), content="Some(1)") // Returns first occurrence
    debug_inspect(arr.search(5), content="None")
    }

    ReadOnlyArray::search_by

    fn[T] ReadOnlyArray::search_by(self : ReadOnlyArray[T], f : (T) -> Bool raise?) -> Int? raise?

    Returns the index of the first element satisfying f, or None.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
    debug_inspect(arr.search_by(x => x > 3), content="Some(3)")
    debug_inspect(arr.search_by(x => x > 99), content="None")
    }

    ReadOnlyArray::starts_with

    fn[T : Eq] ReadOnlyArray::starts_with(self : ReadOnlyArray[T], prefix : ArrayView[T]) -> Bool

    Checks if the ReadOnlyArray starts with the given prefix.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
    inspect(arr.starts_with([1, 2]), content="true")
    }

    ReadOnlyArray::strip_prefix

    fn[T : Eq] ReadOnlyArray::strip_prefix(self : ReadOnlyArray[T], prefix : ArrayView[T]) -> ArrayView[T]?

    If the array starts with prefix, returns a view of the remainder. Otherwise returns None. The returned view shares the backing storage — no allocation.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
    debug_inspect(
    arr.strip_prefix([1, 2]),
    content=(
    #|Some(<ArrayView: [3, 4, 5]>)
    ),
    )
    debug_inspect(arr.strip_prefix([2, 3]), content="None")
    }

    ReadOnlyArray::strip_suffix

    fn[T : Eq] ReadOnlyArray::strip_suffix(self : ReadOnlyArray[T], suffix : ArrayView[T]) -> ArrayView[T]?

    If the array ends with suffix, returns a view of the leading portion. Otherwise returns None. The returned view shares the backing storage — no allocation.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
    debug_inspect(
    arr.strip_suffix([4, 5]),
    content=(
    #|Some(<ArrayView: [1, 2, 3]>)
    ),
    )
    debug_inspect(arr.strip_suffix([3, 4]), content="None")
    }

    ReadOnlyArray::suffixes

    fn[T] ReadOnlyArray::suffixes(self : ReadOnlyArray[T], include_empty? : Bool) -> Iter[ArrayView[T]]

    Yields all suffix views from the longest down to length 1 (and the empty view if include_empty=true). Each suffix shares the original backing storage.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2]
    debug_inspect(
    arr.suffixes().collect(),
    content=(
    #|[<ArrayView: [1, 2]>, <ArrayView: [2]>]
    ),
    )
    debug_inspect(
    arr.suffixes(include_empty=true).collect(),
    content=(
    #|[<ArrayView: [1, 2]>, <ArrayView: [2]>, <ArrayView: []>]
    ),
    )
    }

    ReadOnlyArray::to_json

    fn[T : ToJson] ReadOnlyArray::to_json(self : ReadOnlyArray[T]) -> Json

    ReadOnlyArray::view

    #alias(sub, deprecated="Use _[_:_] instead")
    #alias("_[_:_]")
    fn[T] ReadOnlyArray::view(self : ReadOnlyArray[T], start? : Int, end? : Int) -> ArrayView[T]

    Creates a view of a subarray.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
    let view = arr[1:4]
    inspect(view[0], content="2")
    inspect(view[2], content="4")
    }

    ReadOnlyArray::windows

    fn[T] ReadOnlyArray::windows(self : ReadOnlyArray[T], size : Int) -> Array[ArrayView[T]]

    Returns all contiguous sub-views of length size, from left to right. The result has length - size + 1 entries when size <= length, and is empty otherwise. Each sub-view shares the original backing storage.

    Panics if size <= 0.

    Example

    test {
    let arr : ReadOnlyArray[Int] = [1, 2, 3, 4]
    debug_inspect(
    arr.windows(2),
    content=(
    #|[<ArrayView: [1, 2]>, <ArrayView: [2, 3]>, <ArrayView: [3, 4]>]
    ),
    )
    }

    Result

    Result::bind

    fn[T, E, U] Result::bind(self : Result[T, E], g : (T) -> Result[U, E]) -> Result[U, E]

    Binds a result to a function that returns another result.

    Example

    test {
    let x : Result[Int, String] = Ok(6)
    let y = x.bind((v : Int) => Ok(v * 7))
    @test.assert_eq(y, Ok(42))
    }

    Result::compare

    fn[T : Compare + Eq, E : Compare + Eq] Result::compare(self : Result[T, E], other : Result[T, E]) -> Int

    Result::equal

    fn[T : Eq, E : Eq] Result::equal(self : Result[T, E], other : Result[T, E]) -> Bool

    Result::flatten

    fn[T, E] Result::flatten(self : Result[Result[T, E], E]) -> Result[T, E]

    Flatten a Result of Result into a single Result.

    If the outer Result is an Ok, the inner Result is returned. If the outer Result is an Err, the inner Result is ignored and the Err is returned.

    Example

    test {
    let x : Result[Result[Int, String], String] = Ok(Ok(6))
    let y = x.flatten()
    @test.assert_eq(y, Ok(6))
    }

    Result::hash

    fn[T : Hash, E : Hash] Result::hash(self : Result[T, E]) -> Int

    Result::map

    fn[T, E, U] Result::map(self : Result[T, E], f : (T) -> U) -> Result[U, E]

    Maps the value of a Result if it is Ok into another, otherwise returns the Err value unchanged.

    Example

    test {
    let x : Result[Int, Unit] = Ok(6)
    let y = x.map((v : Int) => v * 7)
    @test.assert_eq(y, Ok(42))
    }

    Result::map_err

    fn[T, E, F] Result::map_err(self : Result[T, E], f : (E) -> F) -> Result[T, F]

    Maps the value of a Result if it is Err into another, otherwise returns the Ok value unchanged.

    Example

    test {
    let x : Result[Int, String] = Err("error")
    let y = x.map_err((v : String) => v + "!")
    @test.assert_eq(y, Err("error!"))
    }

    Result::to_json

    fn[Ok : ToJson, Err : ToJson] Result::to_json(self : Result[Ok, Err]) -> Json

    Result::to_option

    fn[T, E] Result::to_option(self : Result[T, E]) -> T?

    Converts a Result to an Option.

    Converts Ok to Some and Err to None.

    Example

    test {
    let x : Result[Int, String] = Ok(6)
    let y = x.to_option()
    @test.assert_eq(y, Some(6))
    }

    Result::unwrap

    fn[T, E] Result::unwrap(self : Result[T, E]) -> T

    Extract the wrapped value with unwrap semantics.

    Result::unwrap_err

    fn[T, E] Result::unwrap_err(self : Result[T, E]) -> E

    Extracts the error value from a Result[T, E]. If the Result is Ok, aborts with a runtime error message.

    Parameters:

    • self : The Result value to extract the error from.

    Returns the error value of type E if self is Err(e).

    Example:

    test {
    let err : Result[Int, String] = Err("error message")
    inspect(err.unwrap_err(), content="error message")
    }

    Result::unwrap_or

    #alias(or)
    fn[T, E] Result::unwrap_or(self : Result[T, E], default : T) -> T

    Return the contained Ok value or the provided default.

    Example

    test {
    let x : Result[Int, String] = Ok(3)
    let y : Result[Int, String] = Err("error")
    @test.assert_eq(x.unwrap_or(5), 3)
    @test.assert_eq(y.unwrap_or(5), 5)
    }

    Result::unwrap_or_default

    fn[T : Default, E] Result::unwrap_or_default(self : Result[T, E]) -> T

    Return the contained Ok value or the result of the T::default().

    Result::unwrap_or_else

    #alias(or_else)
    fn[T, E] Result::unwrap_or_else(self : Result[T, E], default : () -> T raise?) -> T raise?

    Return the contained Ok value or the provided default.

    Default is lazily evaluated.

    Example

    test {
    let x : Result[Int, String] = Ok(3)
    let y : Result[Int, String] = Err("error")
    @test.assert_eq(x.unwrap_or_else(() => 5), 3)
    @test.assert_eq(y.unwrap_or_else(() => 5), 5)
    }

    Result::unwrap_or_error

    fn[T, E : Error] Result::unwrap_or_error(self : Result[T, E]) -> T raise E

    Extract the wrapped value with unwrap_or_error semantics.

    String

    Note

    String is a built-in type. The documentation may not be complete here. You can find all methods and implementations in the core/builtin and core/string package.

    String::add

    fn String::add(self : String, other : String) -> String

    String::after

    fn String::after(self : String, needle : StringView) -> StringView?

    Returns the substring after the first occurrence of the separator.

    Returns None if the separator is not found.

    If the separator is empty, it returns the full string.

    String::all

    #alias(every)
    fn String::all(self : String, f : (Char) -> Bool raise?) -> Bool raise?

    Checks if all characters in the string match the condition.

    Example

    test {
    assert_true("abc".all(c => c.is_ascii_lowercase()))
    assert_false("abc1".all(c => c.is_ascii_lowercase()))
    }

    String::any

    #alias(exists)
    fn String::any(self : String, f : (Char) -> Bool raise?) -> Bool raise?

    Checks if any character in the string matches the condition.

    Example

    test {
    assert_true("abc1".any(c => c.is_ascii_digit()))
    assert_false("abc".any(c => c.is_ascii_digit()))
    }

    String::at

    #alias(code_unit_at)
    #alias("_[_]")
    fn String::at(self : String, idx : Int) -> UInt16

    Returns the UTF-16 code unit at the given index.

    This method has O(1) complexity. Panics if the index is out of bounds.

    String::before

    fn String::before(self : String, needle : StringView) -> StringView?

    Returns the substring before the first occurrence of the separator.

    Returns None if the separator is not found.

    If the separator is empty, it returns an empty string.

    String::char_length

    #alias(codepoint_length, deprecated="`codepoint_length` is deprecated, use `char_length` instead")
    fn String::char_length(self : String, start_offset? : Int, end_offset? : Int) -> Int

    Returns the number of Unicode code points (characters) in the string.

    This method counts actual Unicode characters, properly handling surrogate pairs that represent single characters like emojis. For the raw UTF-16 code unit count, use length() instead.

    Examples

    test {
    let s = "Hello🤣"
    inspect(s.char_length(), content="6") // 6 actual characters
    inspect(s.length(), content="7")
    } // 5 ASCII chars + 1 surrogate pair (2 code units)

    String::char_length_eq

    fn String::char_length_eq(self : String, len : Int, start_offset? : Int, end_offset? : Int) -> Bool

    Test if the length of the string is equal to the given length.

    This has O(n) complexity where n is the length in the parameter.

    String::char_length_ge

    fn String::char_length_ge(self : String, len : Int, start_offset? : Int, end_offset? : Int) -> Bool

    Test if the length of the string is greater than or equal to the given length.

    This has O(n) complexity where n is the length in the parameter.

    String::clamped_view

    fn String::clamped_view(self : String, start? : Int, end? : Int) -> StringView

    Returns the largest well-formed view contained in the requested range. Total: out-of-range offsets are clamped to the string, an offset that would split a surrogate pair is snapped inward (start forward, end backward), and an inverted range yields an empty view — this function never aborts and never cuts a surrogate pair in half.

    Intended for truncation where the exact cut point does not matter, such as short summaries: the result is at most one character shorter than the requested range on each side. Unpaired surrogates already present in the input are treated as boundaries and pass through unchanged.

    See s[start:end] for the aborting variant and String::get_view for the exact Option-returning variant.

    Example

    test {
    let s = "ab😀cd"
    inspect(s.clamped_view(end=3), content="ab") // 3 splits 😀: snapped to 2
    inspect(s.clamped_view(start=3), content="cd") // snapped to 4
    inspect(s.clamped_view(end=100), content="ab😀cd") // clamped
    inspect(s.clamped_view(start=3, end=3), content="") // inside the pair
    }

    String::code_units

    fn String::code_units(self : String) -> ArrayView[UInt16]

    Returns an ArrayView containing the UTF-16 code units of the string.

    This method yields code units, not Unicode characters. Surrogate pairs are represented as two UInt16 values.

    String::compare

    fn String::compare(self : String, other : String) -> Int

    String::compare_ignore_ascii_case

    fn String::compare_ignore_ascii_case(self : String, other : String) -> Int

    Performs a lexicographical comparison of two strings, treating ASCII letters as case-insensitive.

    Each pair of UTF-16 code units is compared after folding ASCII 'A'..'Z' onto 'a'..'z'. Non-ASCII code units are compared by their raw value, so this function does not perform Unicode case folding (e.g. 'Ä' and 'ä' are still considered different). Use this when you only need to match ASCII identifiers, headers, file extensions, or similar protocol text — not for human-language text where locale-dependent folding matters.

    Aside from case folding, the semantics match lexical_compare: characters are compared one by one and, when one string is a prefix of the other, the shorter string is considered less. The result is independent of which string is self.

    Returns

    • A negative integer if self is less than other
    • Zero if self is equal to other under ASCII case folding
    • A positive integer if self is greater than other

    Example

    test {
    inspect("Hello".compare_ignore_ascii_case("hello"), content="0")
    inspect("ABC".compare_ignore_ascii_case("abd"), content="-1")
    inspect("abc".compare_ignore_ascii_case("AB"), content="1")
    // Non-ASCII letters are NOT folded
    inspect("Ä".compare_ignore_ascii_case("ä") != 0, content="true")
    }

    String::contains

    fn String::contains(self : String, str : StringView) -> Bool

    Returns true if this string contains the given substring.

    String::contains_any

    fn String::contains_any(self : String, chars~ : StringView) -> Bool

    Returns true if this string contains any character from the given set.

    String::contains_char

    fn String::contains_char(self : String, c : Char) -> Bool

    Returns true if this string contains the given character.

    String::contains_code_unit

    fn String::contains_code_unit(self : String, code : UInt16) -> Bool

    Returns true if this string contains the given UTF-16 code unit.

    This searches raw UTF-16 code units and does not combine surrogate pairs. Use contains_char when searching for a Unicode character.

    String::equal

    fn String::equal(self : String, other : String) -> Bool

    String::equal_ignore_ascii_case

    fn String::equal_ignore_ascii_case(self : String, other : String) -> Bool

    Tests two strings for equality, treating ASCII letters as case-insensitive.

    ASCII 'A'..'Z' are folded onto 'a'..'z' before comparison; all other code units (including non-ASCII letters like 'Ä') are compared by their raw UTF-16 value. Use this for ASCII-only protocol text — HTTP headers, file extensions, identifiers — not for human-language text where Unicode case folding matters.

    Equivalent to self.compare_ignore_ascii_case(other) == 0 but short- circuits on length mismatch and on the first differing code unit, so it is preferred when only equality is needed.

    Example

    test {
    inspect("Hello".equal_ignore_ascii_case("hello"), content="true")
    inspect("Hello".equal_ignore_ascii_case("world"), content="false")
    inspect("abc".equal_ignore_ascii_case("ab"), content="false")
    // Non-ASCII letters are NOT folded
    inspect("Ä".equal_ignore_ascii_case("ä"), content="false")
    }

    String::escape

    fn String::escape(self : String, quote? : Bool) -> String

    Returns the escaped representation of a string.

    When quote is true (default), the result is wrapped in double quotes like a MoonBit string literal.

    Escape rules:
    • Double quote and backslash are backslash-escaped: \", \\
    • Common control characters use named escapes: \n, \r, \b, \t
    • Other control characters (< U+0020) use \u{hex} format
    • All other characters are displayed as-is

    test {
    inspect("Hello \n".escape(), content="\"Hello \\n\"")
    inspect("Hello \n".escape(quote=false), content="Hello \\n")
    }

    String::find

    fn String::find(self : String, str : StringView) -> Int?

    Returns the offset of the first occurrence of the given substring. If the substring is not found, it returns None.

    String::find_by

    fn String::find_by(self : String, pred : (Char) -> Bool) -> Int?

    Returns the UTF-16 code-unit offset, relative to the beginning of this string, of the first character that satisfies the given predicate. If no such character is found, it returns None.

    String::fold

    fn[A] String::fold(self : String, init~ : A, f : (A, Char) -> A raise?) -> A raise?

    Folds the characters of the string into a single value.

    String::from_array

    fn String::from_array(chars : ArrayView[Char]) -> String

    Convert char array to string.

    test {
    let s = String::from_array(['H', 'e', 'l', 'l', 'o'])
    @test.assert_eq(s, "Hello")
    }

    Do not convert large data to Array[Char] and build a string with String::from_array.

    For efficiency considerations, it's recommended to use Buffer instead.

    String::from_iter

    #alias(from_iterator, deprecated="`from_iterator` is deprecated, use `from_iter` instead")
    fn String::from_iter(iter : Iter[Char]) -> String

    Convert char iterator to string,

    String::get

    fn String::get(self : String, idx : Int) -> UInt16?

    Returns the UTF-16 code unit at the given index. Returns None if the index is out of bounds.

    String::get_char

    fn String::get_char(self : String, idx : Int) -> Char?

    Returns the character at the given index. Returns None if the index is out of bounds or the index splits a surrogate pair.

    String::get_view

    fn String::get_view(self : String, start? : Int, end? : Int) -> StringView?

    Returns a view of the string between start and end, or None if the range is invalid — either out of bounds or splitting a UTF-16 surrogate pair. Unlike String::sub (a.k.a. s[start:end]), this variant does not abort, making it suitable for composition with pattern matching:

    test {
    let s = "Hello🤣World"
    debug_inspect(
    s.get_view(end=5).map(v => v.to_owned()),
    content="Some(\"Hello\")",
    )
    // Splitting a surrogate pair is rejected rather than panicking.
    debug_inspect(s.get_view(end=6), content="None")
    debug_inspect(s.get_view(start=100), content="None")
    }

    String::has_prefix

    #alias(starts_with, deprecated="`starts_with` is deprecated, use `has_prefix` instead")
    fn String::has_prefix(self : String, str : StringView) -> Bool

    Returns true if this string starts with the given substring.

    String::has_suffix

    #alias(ends_with, deprecated="`ends_with` is deprecated, use `has_suffix` instead")
    fn String::has_suffix(self : String, str : StringView) -> Bool

    Returns true if the given substring is suffix of this string.

    String::hash

    fn String::hash(self : String) -> Int

    String::is_blank

    fn String::is_blank(self : String) -> Bool

    Returns true if this string is blank.

    String::is_empty

    fn String::is_empty(self : String) -> Bool

    Returns true if this string is empty.

    String::iter

    #alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
    fn String::iter(self : String) -> Iter[Char]

    Returns an iterator over the Unicode characters in the string.

    Note: This iterator yields Unicode characters, not Utf16 code units. As a result, the count of characters returned by iter().count() may not be equal to the length of the string returned by length().

    test {
    let s = "Hello, World!🤣"
    @test.assert_eq(s.iter().count(), 14) // Unicode characters
    @test.assert_eq(s.length(), 15)
    } // Utf16 code units

    String::iter2

    #alias(iterator2, deprecated="`iterator2` is deprecated, use `iter2` instead")
    fn String::iter2(self : String) -> Iter2[Int, Char]

    Return an iterator via iter2.

    String::length

    #alias(charcode_length, deprecated="`charcode_length` is deprecated, use `length` instead")
    fn String::length(self : String) -> Int

    Returns the number of UTF-16 code units in the string. Note that this is not necessarily equal to the number of Unicode characters (code points) in the string, as some characters may be represented by multiple UTF-16 code units.

    Parameters:

    • string : The string whose length is to be determined.

    Returns the number of UTF-16 code units in the string.

    Example:

    test {
    inspect("hello".length(), content="5")
    inspect("🤣".length(), content="2") // Emoji uses two UTF-16 code units
    inspect("".length(), content="0") // Empty string
    }

    String::lexical_compare

    fn String::lexical_compare(self : String, other : String) -> Int

    Performs a lexicographical comparison of two strings.

    This method compares the strings character by character (UTF-16 code unit by code unit), similar to Java's String.compareTo(). Unlike the Compare trait implementation which uses shortlex order (shorter strings come first), this method compares based purely on character values until a difference is found or one string is exhausted.

    Returns

    • A negative integer if self is lexicographically less than other
    • Zero if self is lexicographically equal to other
    • A positive integer if self is lexicographically greater than other

    Example

    test {
    inspect("ab".lexical_compare("abc"), content="-1")
    inspect("abc".lexical_compare("ab"), content="1")
    inspect("abc".lexical_compare("abc"), content="0")
    inspect("abc".lexical_compare("abd"), content="-1")
    }

    Note

    Since MoonBit strings are UTF-16 encoded (like Java), this comparison operates on UTF-16 code units, not Unicode code points. Surrogate pairs (used for characters outside the Basic Multilingual Plane) are compared as individual code units.

    String::make

    fn String::make(length : Int, value : Char) -> String

    Create new string of length, where each character is value

    test {
    @test.assert_eq(String::make(5, 'S'), "SSSSS")
    }

    String::offset_of_nth_char

    fn String::offset_of_nth_char(self : String, i : Int, start_offset? : Int, end_offset? : Int) -> Int?

    Returns the UTF-16 index of the i-th (zero-indexed) Unicode character within the range [start, end). If i is negative, it returns the index of the (n + i)-th character where n is the number of Unicode characters in the range [start, end).

    This functions assumes that the string is valid UTF-16.

    String::pad_end

    fn String::pad_end(self : String, total_width : Int, padding_char : Char) -> String

    Returns a new string with padding_chars appended to self if self.length() < total_width. The threshold and the pad count are measured in UTF-16 code units: total_width - self.length() copies of padding_char are appended. Characters outside the BMP count as two code units, so with such characters in self the result has fewer than total_width characters, and with a non-BMP padding_char the result's UTF-16 length exceeds total_width.

    String::pad_start

    fn String::pad_start(self : String, total_width : Int, padding_char : Char) -> String

    Returns a new string with padding_chars prefixed to self if self.length() < total_width. The threshold and the pad count are measured in UTF-16 code units: total_width - self.length() copies of padding_char are prefixed. Characters outside the BMP count as two code units, so with such characters in self the result has fewer than total_width characters, and with a non-BMP padding_char the result's UTF-16 length exceeds total_width.

    String::repeat

    fn String::repeat(self : String, n : Int) -> String

    Returns a new string with self repeated n times.

    Aborts if n is negative. When n is 0, returns the empty string.

    String::replace

    fn String::replace(self : String, old~ : StringView, new~ : StringView) -> String

    Replaces the first occurrence of old with new in self.

    If old is empty, it matches the beginning of the string, and new is prepended to the string.

    String::replace_all

    fn String::replace_all(self : String, old~ : StringView, new~ : StringView) -> String

    Replaces all non-overlapping occurrences of old with new in self.

    If old is empty, it matches at the beginning of the string and after each character in the string, so new is inserted at the beginning of the string and after each character.

    String::rev

    fn String::rev(self : String) -> String

    Returns a new string with the characters in reverse order. It respects Unicode characters and surrogate pairs but not grapheme clusters.

    String::rev_after

    fn String::rev_after(self : String, needle : StringView) -> StringView?

    Returns the substring after the last occurrence of the separator.

    Returns None if the separator is not found.

    Example:

    test {
    assert_true("a/b/c.txt".rev_after("/") == Some("c.txt"))
    }

    String::rev_before

    fn String::rev_before(self : String, needle : StringView) -> StringView?

    Returns the substring before the last occurrence of the separator.

    Returns None if the separator is not found.

    Example:

    test {
    assert_true("a/b/c.txt".rev_before("/") == Some("a/b"))
    }

    String::rev_find

    fn String::rev_find(self : String, str : StringView) -> Int?

    Returns the offset (charcode index) of the last occurrence of the given substring. If the substring is not found, it returns None.

    String::rev_fold

    fn[A] String::rev_fold(self : String, init~ : A, f : (A, Char) -> A raise?) -> A raise?

    Function rev_fold.

    String::rev_iter

    #alias(rev_iterator, deprecated="`rev_iterator` is deprecated, use `rev_iter` instead")
    fn String::rev_iter(self : String) -> Iter[Char]

    Returns an iterator that yields characters from the end to the start of the string. This function handles Unicode surrogate pairs correctly, ensuring that characters are not split across surrogate pairs.

    Parameters

    • self : The input String to be iterated in reverse.

    Returns

    • An Iter[Char] that yields characters from the end to the start of the string.

    Behavior

    • The function iterates over the string in reverse order.
    • If a trailing surrogate is encountered, it checks for a preceding leading surrogate to form a complete Unicode code point.
    • Yields each character or combined code point to the iterator.
    • Stops once the beginning of the string is reached, after which the iterator yields None.

    Examples

    test {
    let input = "Hello, World!"
    let reversed = input.rev_iter().collect()
    @test.assert_eq(reversed, [
    '!', 'd', 'l', 'r', 'o', 'W', ' ', ',', 'o', 'l', 'l', 'e', 'H',
    ])
    }

    String::rev_split_once

    fn String::rev_split_once(self : String, needle : StringView) -> (StringView, StringView)?

    Splits the string into a pair at the last occurrence of the separator.

    Returns None if the separator is not found.

    Example:

    test {
    assert_true("a::b::c".rev_split_once("::") == Some(("a::b", "c")))
    }

    String::split

    fn String::split(self : String, sep : StringView) -> Iter[StringView]

    Splits the string into all substrings separated by the given separator.

    If the string does not contain the separator and the separator is not empty, the returned iterator will contain only one element, which is the original string.

    If the separator is empty, the returned iterator will contain all the characters in the string as single elements.

    String::split_at

    fn String::split_at(self : String, at : Int) -> (StringView, StringView)

    Splits the string into a well-formed (prefix, suffix) pair at the given code-unit offset: the cut point is at clamped to the string and snapped down to the nearest character boundary, so the prefix never exceeds at units and a character straddling the cut goes to the suffix.

    Total, O(1), and lossless: prefix + suffix == self always holds — unlike composing two clamped_view calls, which would drop a character straddling the cut from both halves. Unpaired surrogates are treated as boundaries and pass through unchanged.

    Example

    test {
    let s = "ab😀cd"
    let (p, q) = s.split_at(3) // 3 splits 😀: the cut snaps down to 2
    inspect(p, content="ab")
    inspect(q, content="😀cd")
    let (p2, q2) = s.split_at(100) // clamped
    inspect(p2, content="ab😀cd")
    inspect(q2, content="")
    }

    String::split_once

    fn String::split_once(self : String, needle : StringView) -> (StringView, StringView)?

    Splits the string into a pair at the first occurrence of the separator.

    Returns None if the separator is not found.

    If the separator is empty, it splits at the start of the string, returning an empty prefix and the full string as the suffix.

    String::strip_prefix

    #alias(chop_prefix)
    fn String::strip_prefix(self : String, prefix : StringView) -> StringView?

    Removes the given prefix from the string if it exists.

    Returns Some(suffix) if the string starts with the given prefix, where suffix is the string without the prefix. Returns None if the string does not start with the prefix.

    Example

    test {
    assert_true("hello world".strip_prefix("hello ") == Some("world"))
    assert_true("hello world".strip_prefix("hi ") == None)
    assert_true("hello".strip_prefix("hello") == Some(""))
    }

    String::strip_suffix

    #alias(chop_suffix)
    fn String::strip_suffix(self : String, suffix : StringView) -> StringView?

    Removes the given suffix from the string if it exists.

    Returns Some(prefix) if the string ends with the given suffix, where prefix is the string without the suffix. Returns None if the string does not end with the suffix.

    Example

    test {
    assert_true("hello world".strip_suffix(" world") == Some("hello"))
    assert_true("hello world".strip_suffix(" moon") == None)
    assert_true("hello".strip_suffix("hello") == Some(""))
    }

    String::sub

    #alias("_[_:_]")
    fn String::sub(self : String, start? : Int, end? : Int) -> StringView

    Creates a view of a string with proper UTF-16 boundary validation.

    Parameters

    • start : Starting UTF-16 code unit index (default: 0), counting from the beginning of the string
    • end : Ending UTF-16 code unit index (optional)
      • If None: extends to the end of the string
      • Otherwise: counts from the beginning of the string

    Returns

    • A View representing the specified substring range

    Panics

    • If start or end indices are out of valid range
    • If start or end position would split a UTF-16 surrogate pair

    This prevents creating views that would split surrogate pairs, which would result in invalid Unicode characters.

    Performance

    This function has O(1) complexity as it only performs boundary checks without scanning the string content.

    Examples

    test {
    let str = "Hello🤣World"
    let view1 = str[0:5]
    inspect(view1, content="Hello")
    let view2 = str[7:]
    inspect(view2, content="World")
    }

    String::substring

    #deprecated("Use `str[:]` or `str[:].to_string()` instead")
    fn String::substring(self : String, start? : Int, end? : Int) -> String

    Returns a new string containing characters from the original string starting at start index up to (but not including) end index.

    Parameters:

    • string : The source string from which to extract the substring.
    • start : The starting index of the substring (inclusive). Defaults to 0.
    • end : The ending index of the substring (exclusive). Defaults to the length of the string.

    Returns a new string containing the specified substring.

    String::suffixes

    fn String::suffixes(self : String, include_empty? : Bool) -> Iter[StringView]

    Iterates over all suffixes of the string as views that reuse the original storage. Surrogate pairs stay intact while advancing.

    String::to_array

    fn String::to_array(self : String) -> Array[Char]

    Converts the String into an array of Chars.

    String::to_bytes

    #deprecated("Check `@encoding/utf8.encode`")
    fn String::to_bytes(self : String) -> Bytes

    String holds a sequence of UTF-16 code units encoded in little endian format

    String::to_json

    fn String::to_json(self : String) -> Json

    String::to_lower

    fn String::to_lower(self : String) -> String

    Converts the ASCII uppercase letters ('A' to 'Z') in this string to lowercase. All other characters, including non-ASCII letters, are left unchanged.

    String::to_string

    fn String::to_string(self : String) -> String

    String::to_string_view

    fn String::to_string_view(self : String) -> StringView

    String::to_upper

    fn String::to_upper(self : String) -> String

    Converts the ASCII lowercase letters ('a' to 'z') in this string to uppercase. All other characters, including non-ASCII letters, are left unchanged.

    String::trim

    fn String::trim(self : String, chars? : StringView) -> StringView

    Returns the view of the string without the leading and trailing characters that are in the given string.

    String::trim_end

    fn String::trim_end(self : String, chars? : StringView) -> StringView

    Returns the view of the string without the trailing characters that are in the given string.

    String::trim_space

    #deprecated("Use `trim` with default whitespace characters instead")
    fn String::trim_space(self : String) -> StringView

    Returns the view of the string without the leading and trailing spaces.

    String::trim_start

    fn String::trim_start(self : String, chars? : StringView) -> StringView

    Returns the view of the string without the leading characters that are in the given string.

    String::unsafe_char_at

    #deprecated("Use `s.get_char(i).unwrap()` instead")
    fn String::unsafe_char_at(self : String, index : Int) -> Char

    Returns the Unicode code point at the given index without bounds checking.

    String::unsafe_substring

    fn String::unsafe_substring(str : String, start~ : Int, end~ : Int) -> String

    Unsafe variant of substring.

    String::view

    fn String::view(self : String, start_offset? : Int, end_offset? : Int) -> StringView

    Creates a View into a String.

    Example

    test {
    let str = "Hello🤣🤣🤣"
    let view1 = str.view()
    inspect(view1, content="Hello🤣🤣🤣")
    let start_offset = str.offset_of_nth_char(1).unwrap()
    let end_offset = str.offset_of_nth_char(6).unwrap() // the second emoji
    let view2 = str.view(start_offset~, end_offset~)
    inspect(view2, content="ello🤣")
    }

    StringView

    StringView::add

    fn StringView::add(self : StringView, other : StringView) -> StringView

    StringView::after

    fn StringView::after(self : StringView, needle : StringView) -> StringView?

    Returns the substring after the first occurrence of the separator.

    Returns None if the separator is not found.

    If the separator is empty, it returns the full string.

    StringView::all

    #alias(every)
    fn StringView::all(self : StringView, f : (Char) -> Bool raise?) -> Bool raise?

    Checks if all characters in the string view match the condition.

    Example

    test {
    let view = "zabc!"[1:4]
    assert_true(view.all(c => c.is_ascii_lowercase()))
    assert_false(view.all(c => c == 'a'))
    }

    StringView::any

    #alias(exists)
    fn StringView::any(self : StringView, f : (Char) -> Bool raise?) -> Bool raise?

    Checks if any character in the string view matches the condition.

    Example

    test {
    let view = "zabc!"[1:4]
    assert_true(view.any(c => c == 'b'))
    assert_false(view.any(c => c.is_ascii_digit()))
    }

    StringView::at

    #alias(code_unit_at)
    #alias("_[_]")
    fn StringView::at(self : StringView, index : Int) -> UInt16

    Returns the UTF-16 code unit at the given index.

    This method has O(1) complexity. Panics if the index is out of bounds.

    StringView::before

    fn StringView::before(self : StringView, needle : StringView) -> StringView?

    Returns the substring before the first occurrence of the separator.

    Returns None if the separator is not found.

    If the separator is empty, it returns an empty string.

    StringView::char_length

    fn StringView::char_length(self : StringView) -> Int

    Returns the number of Unicode characters in this view.

    Note this has O(n) complexity where n is the length of the code points in the view.

    StringView::char_length_eq

    fn StringView::char_length_eq(self : StringView, len : Int) -> Bool

    Test if the length of the view is equal to the given length.

    This has O(n) complexity where n is the length in the parameter.

    StringView::char_length_ge

    fn StringView::char_length_ge(self : StringView, len : Int) -> Bool

    Test if the length of the view is greater than or equal to the given length.

    This has O(n) complexity where n is the length in the parameter.

    StringView::clamped_view

    fn StringView::clamped_view(self : StringView, start? : Int, end? : Int) -> StringView

    Returns the largest well-formed sub-view contained in the requested range of this view; offsets are relative to the view. Total like String::clamped_view: clamps out-of-range offsets, snaps surrogate-splitting offsets inward, and yields an empty view for an inverted range.

    Example

    test {
    let v = "xx ab😀cd".view(start_offset=3)
    inspect(v.clamped_view(end=3), content="ab")
    inspect(v.clamped_view(start=3), content="cd")
    }

    StringView::code_units

    fn StringView::code_units(self : StringView) -> ArrayView[UInt16]

    Returns an ArrayView containing the UTF-16 code units of the string view.

    This method yields code units, not Unicode characters. Surrogate pairs are represented as two UInt16 values.

    Note: the default implementation copies the entire underlying string into a fresh FixedArray and then slices it, so the returned view does not alias the original string's storage. Some backends lower the intrinsic to a zero-copy view instead.

    StringView::compare

    fn StringView::compare(self : StringView, other : StringView) -> Int

    StringView::compare_ignore_ascii_case

    fn StringView::compare_ignore_ascii_case(self : StringView, other : StringView) -> Int

    Performs a lexicographical comparison of two string views, treating ASCII letters as case-insensitive.

    Each pair of UTF-16 code units is compared after folding ASCII 'A'..'Z' onto 'a'..'z'. Non-ASCII code units are compared by their raw value, so this function does not perform Unicode case folding (e.g. 'Ä' and 'ä' are still considered different). Use this when you only need to match ASCII identifiers, headers, file extensions, or similar protocol text — not for human-language text where locale-dependent folding matters.

    Aside from case folding, the semantics match lexical_compare: characters are compared one by one (UTF-16 code unit by code unit) and, when one view is a prefix of the other, the shorter view is considered less. The result is independent of which view is self.

    Returns

    • A negative integer if self is less than other
    • Zero if self is equal to other under ASCII case folding
    • A positive integer if self is greater than other

    Example

    test {
    inspect("Hello".view().compare_ignore_ascii_case("hello".view()), content="0")
    inspect("ABC".view().compare_ignore_ascii_case("abd".view()), content="-1")
    inspect("abc".view().compare_ignore_ascii_case("AB".view()), content="1")
    }

    StringView::contains

    fn StringView::contains(self : StringView, str : StringView) -> Bool

    Returns true if this string contains the given substring.

    StringView::contains_any

    fn StringView::contains_any(self : StringView, chars~ : StringView) -> Bool

    Returns true if this string contains any character from the given set.

    StringView::contains_char

    fn StringView::contains_char(self : StringView, c : Char) -> Bool

    Returns true if this string contains the given character.

    StringView::contains_code_unit

    fn StringView::contains_code_unit(self : StringView, code : UInt16) -> Bool

    Returns true if this string view contains the given UTF-16 code unit.

    This searches raw UTF-16 code units and does not combine surrogate pairs. Use contains_char when searching for a Unicode character.

    StringView::data

    fn StringView::data(self : StringView) -> String

    Returns the original string that is being viewed.

    StringView::equal

    fn StringView::equal(self : StringView, other : StringView) -> Bool

    StringView::equal_ignore_ascii_case

    fn StringView::equal_ignore_ascii_case(self : StringView, other : StringView) -> Bool

    Tests two string views for equality, treating ASCII letters as case-insensitive.

    ASCII 'A'..'Z' are folded onto 'a'..'z' before comparison; all other code units (including non-ASCII letters like 'Ä') are compared by their raw UTF-16 value. Use this for ASCII-only protocol text — HTTP headers, file extensions, identifiers — not for human-language text where Unicode case folding matters.

    Equivalent to self.compare_ignore_ascii_case(other) == 0 but short- circuits on length mismatch and on the first differing code unit, so it is preferred when only equality is needed.

    Example

    test {
    inspect(
    "Hello".view().equal_ignore_ascii_case("hello".view()),
    content="true",
    )
    inspect(
    "Hello".view().equal_ignore_ascii_case("world".view()),
    content="false",
    )
    inspect("abc".view().equal_ignore_ascii_case("ab".view()), content="false")
    }

    StringView::equal_to_string

    fn StringView::equal_to_string(self : StringView, other : String) -> Bool

    Compares a StringView to a String code-unit-for-code-unit.

    This is the cross-type equivalent of == and avoids materializing a fresh String (or a wrapping StringView) when probing an owned-String-keyed container with a view-shaped key. When the view spans an entire backing string that is physically the same as other, this short-circuits.

    Returns true if the lengths match and every UTF-16 code unit in self equals the code unit at the same index in other.

    Example:
    test {
    let s = "say hello to everyone"
    inspect(
    s.view(start_offset=4, end_offset=9).equal_to_string("hello"),
    content="true",
    )
    inspect(
    s.view(start_offset=4, end_offset=9).equal_to_string("world"),
    content="false",
    )
    }

    StringView::escape

    fn StringView::escape(self : StringView, quote? : Bool) -> StringView

    Returns the escaped representation of a string view.

    When quote is true (default), the result is wrapped in double quotes like a MoonBit string literal.

    Escape rules:
    • Double quote and backslash are backslash-escaped: \", \\
    • Common control characters use named escapes: \n, \r, \b, \t
    • Other control characters (< U+0020) use \u{hex} format
    • All other characters are displayed as-is

    test {
    inspect("Hello\nWorld"[:6].escape(), content="\"Hello\\n\"")
    inspect("Hello\nWorld"[:6].escape(quote=false), content="Hello\\n")
    }

    StringView::find

    fn StringView::find(self : StringView, str : StringView) -> Int?

    Returns the offset (charcode index) of the first occurrence of the given substring. If the substring is not found, it returns None.

    StringView::find_by

    fn StringView::find_by(self : StringView, pred : (Char) -> Bool) -> Int?

    Returns the UTF-16 code-unit offset, relative to the beginning of this view, of the first character that satisfies the given predicate. If no such character is found, it returns None.

    StringView::fold

    fn[A] StringView::fold(self : StringView, init~ : A, f : (A, Char) -> A raise?) -> A raise?

    Folds the characters of the string into a single value.

    StringView::from_array

    fn StringView::from_array(chars : ArrayView[Char]) -> StringView

    Convert char array to string view.

    StringView::from_iter

    #alias(from_iterator, deprecated="`from_iterator` is deprecated, use `from_iter` instead")
    fn StringView::from_iter(iter : Iter[Char]) -> StringView

    Convert char iterator to string view.

    StringView::get

    fn StringView::get(self : StringView, idx : Int) -> UInt16?

    Returns the UTF-16 code unit at the given index. Returns None if the index is out of bounds.

    StringView::get_char

    fn StringView::get_char(self : StringView, idx : Int) -> Char?

    Returns the character at the given index. Returns None if the index is out of bounds or the index splits a surrogate pair.

    StringView::get_view

    fn StringView::get_view(self : StringView, start? : Int, end? : Int) -> StringView?

    Returns a sub-view of the view between start and end, or None if the range is invalid — either out of bounds or splitting a UTF-16 surrogate pair. The optional variant of StringView::sub (a.k.a. sv[start:end]).

    StringView::has_prefix

    #alias(starts_with, deprecated="`starts_with` is deprecated, use `has_prefix` instead")
    fn StringView::has_prefix(self : StringView, str : StringView) -> Bool

    Returns true if this string starts with the given substring.

    StringView::has_suffix

    #alias(ends_with, deprecated="`ends_with` is deprecated, use `has_suffix` instead")
    fn StringView::has_suffix(self : StringView, str : StringView) -> Bool

    Returns true if the given substring is suffix of this string.

    StringView::hash

    fn StringView::hash(self : StringView) -> Int

    StringView::is_blank

    fn StringView::is_blank(self : StringView) -> Bool

    Returns true if this string is blank.

    StringView::is_empty

    fn StringView::is_empty(self : StringView) -> Bool

    Returns true if this string is empty.

    StringView::iter

    #alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
    fn StringView::iter(self : StringView) -> Iter[Char]

    Returns an iterator over the Unicode characters in the string view.

    StringView::iter2

    #alias(iterator2, deprecated="`iterator2` is deprecated, use `iter2` instead")
    fn StringView::iter2(self : StringView) -> Iter2[Int, Char]

    Returns an iterator over the Unicode characters in the string view, yielding pairs of (character index, character).

    StringView::length

    fn StringView::length(self : StringView) -> Int

    Returns the length of the view.

    This method counts the charcodes(code unit) in the view and has O(1) complexity.

    StringView::lexical_compare

    fn StringView::lexical_compare(self : StringView, other : StringView) -> Int

    Performs a lexicographical comparison of two string views.

    This method compares the views character by character (UTF-16 code unit by code unit), similar to Java's String.compareTo(). Unlike the Compare trait implementation which uses shortlex order (shorter strings come first), this method compares based purely on character values until a difference is found or one view is exhausted.

    Returns

    • A negative integer if self is lexicographically less than other
    • Zero if self is lexicographically equal to other
    • A positive integer if self is lexicographically greater than other

    Example

    test {
    let str = "abc"
    inspect(
    str
    .view(start_offset=0, end_offset=2)
    .lexical_compare(str.view(start_offset=0, end_offset=3)),
    content="-1",
    )
    inspect(
    str
    .view(start_offset=0, end_offset=3)
    .lexical_compare(str.view(start_offset=0, end_offset=2)),
    content="1",
    )
    inspect(
    str
    .view(start_offset=0, end_offset=2)
    .lexical_compare(str.view(start_offset=1, end_offset=3)),
    content="-1",
    )
    }

    Note

    Since MoonBit strings are UTF-16 encoded (like Java), this comparison operates on UTF-16 code units, not Unicode code points. Surrogate pairs (used for characters outside the Basic Multilingual Plane) are compared as individual code units.

    StringView::make

    fn StringView::make(length : Int, value : Char) -> StringView

    Create a new string by repeating the given character value length times.

    StringView::offset_of_nth_char

    fn StringView::offset_of_nth_char(self : StringView, i : Int) -> Int?

    Returns the UTF-16 index of the i-th (zero-indexed) Unicode character of the view. If i is negative, it returns the index of the (n + i)-th character where n is the total number of Unicode characters in the view.

    StringView::pad_end

    fn StringView::pad_end(self : StringView, total_width : Int, padding_char : Char) -> String

    Returns a new string with padding_chars appended to self if self.length() < total_width. The threshold and the pad count are measured in UTF-16 code units: total_width - self.length() copies of padding_char are appended. Characters outside the BMP count as two code units, so with such characters in self the result has fewer than total_width characters, and with a non-BMP padding_char the result's UTF-16 length exceeds total_width.

    StringView::pad_start

    fn StringView::pad_start(self : StringView, total_width : Int, padding_char : Char) -> String

    Returns a new string with padding_chars prefixed to self if self.length() < total_width. The threshold and the pad count are measured in UTF-16 code units: total_width - self.length() copies of padding_char are prefixed. Characters outside the BMP count as two code units, so with such characters in self the result has fewer than total_width characters, and with a non-BMP padding_char the result's UTF-16 length exceeds total_width.

    StringView::repeat

    fn StringView::repeat(self : StringView, n : Int) -> StringView

    Returns a new string with self repeated n times.

    Aborts if n is negative. When n is 0, returns the empty string.

    StringView::replace

    fn StringView::replace(self : StringView, old~ : StringView, new~ : StringView) -> StringView

    Replaces the first occurrence of old with new in self.

    If old is empty, it matches the beginning of the string, and new is prepended to the string.

    StringView::replace_all

    fn StringView::replace_all(self : StringView, old~ : StringView, new~ : StringView) -> StringView

    Replaces all non-overlapping occurrences of old with new in self.

    If old is empty, it matches at the beginning of the string and after each character in the string, so new is inserted at the beginning of the string and after each character.

    StringView::rev

    fn StringView::rev(self : StringView) -> String

    Returns a new string with the characters in reverse order. It respects Unicode characters and surrogate pairs but not grapheme clusters.

    StringView::rev_after

    fn StringView::rev_after(self : StringView, needle : StringView) -> StringView?

    Returns the substring after the last occurrence of the separator.

    Returns None if the separator is not found.

    Example:

    test {
    assert_true("a/b/c.txt".rev_after("/") == Some("c.txt"))
    }

    StringView::rev_before

    fn StringView::rev_before(self : StringView, needle : StringView) -> StringView?

    Returns the substring before the last occurrence of the separator.

    Returns None if the separator is not found.

    Example:

    test {
    assert_true("a/b/c.txt".rev_before("/") == Some("a/b"))
    }

    StringView::rev_find

    fn StringView::rev_find(self : StringView, str : StringView) -> Int?

    Returns the offset of the last occurrence of the given substring. If the substring is not found, it returns None.

    StringView::rev_fold

    fn[A] StringView::rev_fold(self : StringView, init~ : A, f : (A, Char) -> A raise?) -> A raise?

    Function rev_fold.

    StringView::rev_iter

    #alias(rev_iterator, deprecated="`rev_iterator` is deprecated, use `rev_iter` instead")
    fn StringView::rev_iter(self : StringView) -> Iter[Char]

    Returns an iterator over the Unicode characters in the string view in reverse order.

    StringView::rev_split_once

    fn StringView::rev_split_once(self : StringView, needle : StringView) -> (StringView, StringView)?

    Splits the string into a pair at the last occurrence of the separator.

    Returns None if the separator is not found.

    Example:

    test {
    assert_true("a::b::c".rev_split_once("::") == Some(("a::b", "c")))
    assert_true("nope".rev_split_once("::") == None)
    }

    StringView::split

    fn StringView::split(self : StringView, sep : StringView) -> Iter[StringView]

    Splits the string into all substrings separated by the given separator.

    If the string does not contain the separator and the separator is not empty, the returned iterator will contain only one element, which is the original string.

    If the separator is empty, the returned iterator will contain all the characters in the string as single elements.

    StringView::split_at

    fn StringView::split_at(self : StringView, at : Int) -> (StringView, StringView)

    Splits the view into a well-formed (prefix, suffix) pair at the given view-relative code-unit offset; same contract as String::split_at.

    Example

    test {
    let v = "xx ab😀cd".view(start_offset=3)
    let (p, q) = v.split_at(3)
    inspect(p, content="ab")
    inspect(q, content="😀cd")
    }

    StringView::split_once

    fn StringView::split_once(self : StringView, needle : StringView) -> (StringView, StringView)?

    Splits the string into a pair at the first occurrence of the separator.

    Returns None if the separator is not found.

    If the separator is empty, it splits at the start of the string, returning an empty prefix and the full string as the suffix.

    StringView::start_offset

    fn StringView::start_offset(self : StringView) -> Int

    Returns the starting offset (in UTF-16 code units) of this view into its underlying string.

    StringView::strip_prefix

    #alias(chop_prefix)
    fn StringView::strip_prefix(self : StringView, prefix : StringView) -> StringView?

    Removes the given prefix from the view if it exists.

    Returns Some(suffix) if the view starts with the given prefix, where suffix is the view without the prefix. Returns None if the view does not start with the prefix.

    Example

    test {
    let view = "hello world"[:]
    assert_true(view.strip_prefix("hello ") == Some("world"))
    assert_true(view.strip_prefix("hi ") == None)
    assert_true(view.strip_prefix("hello world") == Some(""))
    }

    StringView::strip_suffix

    #alias(chop_suffix)
    fn StringView::strip_suffix(self : StringView, suffix : StringView) -> StringView?

    Removes the given suffix from the view if it exists.

    Returns Some(prefix) if the view ends with the given suffix, where prefix is the view without the suffix. Returns None if the view does not end with the suffix.

    Example

    test {
    let view = "hello world"[:]
    assert_true(view.strip_suffix(" world") == Some("hello"))
    assert_true(view.strip_suffix(" moon") == None)
    assert_true(view.strip_suffix("hello world") == Some(""))
    }

    StringView::sub

    #alias("_[_:_]")
    fn StringView::sub(self : StringView, start? : Int, end? : Int) -> StringView

    Creates a subview of an existing view with proper UTF-16 boundary validation.

    Parameters

    • start : Starting UTF-16 code unit index relative to this view (default: 0), counting from the beginning of this view
    • end : Ending UTF-16 code unit index relative to this view (optional)
      • If None: extends to the end of this view
      • Otherwise: counts from the beginning of this view

    Returns

    • A View representing the specified subrange of this view

    Panics

    • If start or end indices are out of this view's range
    • If start or end position would split a UTF-16 surrogate pair

    This prevents creating views that would split surrogate pairs, which would result in invalid Unicode characters.

    Performance

    This function has O(1) complexity as it only performs boundary checks without scanning the string content.

    Examples

    test {
    let str = "Hello🤣World"[1:11] // "ello🤣Worl"
    let view1 = str[0:6]
    inspect(view1, content="ello🤣")
    let view2 = str[8:]
    inspect(view2, content="rl")
    }

    StringView::suffixes

    fn StringView::suffixes(self : StringView, include_empty? : Bool) -> Iter[StringView]

    Iterates over all suffixes of the view, advancing by a Unicode character at a time. Each yielded suffix is itself a view into the original string.

    StringView::to_array

    fn StringView::to_array(self : StringView) -> Array[Char]

    Converts the View into an array of Chars.

    Example

    test {
    let view = "Hello🤣xa"[1:8]
    let chars = view.to_array()
    @debug.debug_inspect(chars, content="['e', 'l', 'l', 'o', '🤣', 'x']")
    }

    StringView::to_bytes

    #deprecated("Check `@encoding/utf8.encode`")
    fn StringView::to_bytes(self : StringView) -> Bytes

    Convert to bytes.

    StringView::to_json

    fn StringView::to_json(self : StringView) -> Json

    StringView::to_lower

    fn StringView::to_lower(self : StringView) -> StringView

    Converts the ASCII uppercase letters ('A' to 'Z') in this string to lowercase. All other characters, including non-ASCII letters, are left unchanged.

    StringView::to_owned

    #alias(to_string, deprecated="Use `to_owned` to allocate an owned String from a StringView; use `Show::to_string` or format strings for display")
    fn StringView::to_owned(self : StringView) -> String

    Materialize this view into an owned String.

    This crosses an ownership boundary and generally allocates. Use format strings ("\{view}") or Show::to_string(view) when you only need a display representation — those paths go through the Show trait and are not flagged.

    Examples

    test {
    let str = "Hello World"
    let view = str.view(
    start_offset=str.offset_of_nth_char(0).unwrap(),
    end_offset=str.offset_of_nth_char(5).unwrap(),
    ) // "Hello"
    inspect(view.to_owned(), content="Hello")
    }

    StringView::to_string_view

    fn StringView::to_string_view(self : StringView) -> StringView

    StringView::to_upper

    fn StringView::to_upper(self : StringView) -> StringView

    Converts the ASCII lowercase letters ('a' to 'z') in this string to uppercase. All other characters, including non-ASCII letters, are left unchanged.

    StringView::trim

    fn StringView::trim(self : StringView, chars? : StringView) -> StringView

    Returns the view of the string without the leading and trailing characters that are in the given string.

    StringView::trim_end

    fn StringView::trim_end(self : StringView, chars? : StringView) -> StringView

    Returns the view of the string without the trailing characters that are in the given string.

    StringView::trim_space

    #deprecated("Use `trim` with default whitespace characters instead")
    fn StringView::trim_space(self : StringView) -> StringView

    Returns the view of the string without the leading and trailing spaces.

    StringView::trim_start

    fn StringView::trim_start(self : StringView, chars? : StringView) -> StringView

    Returns the view of the string without the leading characters that are in the given string.

    StringView::unsafe_charcode_at

    #deprecated("Use `StringView::unsafe_get` instead")
    fn StringView::unsafe_charcode_at(self : StringView, index : Int) -> Int

    Returns the charcode(code unit) at the given index without checking if the index is within bounds.

    This method has O(1) complexity.

    Example

    test {
    let str = "B🤣🤣C"
    let view = str[:]
    inspect(view.unsafe_get(0), content="66")
    inspect(view.unsafe_get(1), content="55358")
    inspect(view.unsafe_get(2), content="56611")
    inspect(view.unsafe_get(3), content="55358")
    inspect(view.unsafe_get(4), content="56611")
    inspect(view.unsafe_get(5), content="67")
    }

    StringView::unsafe_get

    #internal(unsafe, "Undefined behavior if index is out of bounds.")
    fn StringView::unsafe_get(self : StringView, index : Int) -> UInt16

    Returns the UTF-16 code unit at the given index without checking if the index is within bounds.

    This method has O(1) complexity.

    StringView::view

    fn StringView::view(self : StringView, start_offset? : Int, end_offset? : Int) -> StringView

    Returns a new view of the view with the given start and end offsets.

    UInt

    Note

    UInt is a built-in type. The documentation may not be complete here. You can find all methods and implementations in the core/builtin and core/uint package.

    UInt::UInt

    fn UInt::UInt(self : UInt) -> UInt

    The identity constructor for UInt, allowing values to be written using constructor syntax, e.g. UInt(3).

    Example:

    test {
    inspect(UInt(3), content="3")
    }

    UInt::add

    fn UInt::add(self : UInt, other : UInt) -> UInt

    UInt::clamp

    fn UInt::clamp(self : UInt, min~ : UInt, max~ : UInt) -> UInt

    Clamps an unsigned integer into the inclusive range [min, max].

    Parameters:

    • self : The value to clamp.
    • min : The lower bound of the range.
    • max : The upper bound of the range.

    Returns min if self is less than min, max if self is greater than max, and self otherwise. Aborts if min is greater than max.

    Example:

    test {
    inspect(UInt(5).clamp(min=UInt(0), max=UInt(10)), content="5")
    inspect(UInt(0).clamp(min=UInt(2), max=UInt(10)), content="2")
    inspect(UInt(15).clamp(min=UInt(0), max=UInt(10)), content="10")
    }

    UInt::clz

    fn UInt::clz(self : UInt) -> Int

    Counts the number of leading zero bits in an unsigned 32-bit integer, starting from the most significant bit.

    Parameters:

    • value : The unsigned 32-bit integer whose leading zeros are to be counted.

    Returns the number of consecutive zeros starting from the most significant bit. For a zero value, returns 32.

    Example:

    test {
    inspect(0U.clz(), content="32")
    inspect(1U.clz(), content="31")
    inspect(0x80000000U.clz(), content="0")
    }

    UInt::compare

    fn UInt::compare(self : UInt, other : UInt) -> Int

    UInt::ctz

    fn UInt::ctz(self : UInt) -> Int

    Counts the number of trailing zero bits in an unsigned 32-bit integer, starting from the least significant bit. For a zero input, returns 32.

    Parameters:

    • self : The unsigned 32-bit integer whose trailing zeros are to be counted.

    Returns the number of consecutive zeros at the least significant end of the binary representation. Returns 32 if the input is zero.

    Example:

    test {
    let x = 24U // Binary: ...011000
    inspect(x.ctz(), content="3") // 3 trailing zeros
    let y = 0U
    inspect(y.ctz(), content="32") // All bits are zero
    }

    UInt::div

    fn UInt::div(self : UInt, other : UInt) -> UInt

    UInt::equal

    fn UInt::equal(self : UInt, other : UInt) -> Bool

    UInt::hash

    fn UInt::hash(self : UInt) -> Int

    UInt::land

    fn UInt::land(self : UInt, other : UInt) -> UInt

    UInt::lnot

    fn UInt::lnot(self : UInt) -> UInt

    Performs a bitwise NOT operation on an unsigned 32-bit integer. Flips all bits in the number (changes each 0 to 1 and each 1 to 0).

    Parameters:

    • self : The unsigned 32-bit integer value on which to perform the bitwise NOT operation.

    Returns a new unsigned 32-bit integer where each bit is inverted from the input value.

    Example:

    test {
    let x = 0xFF00U // Binary: 1111_1111_0000_0000
    inspect(x.lnot(), content="4294902015") // Binary: ...0000_0000_1111_1111
    }

    UInt::lor

    fn UInt::lor(self : UInt, other : UInt) -> UInt

    UInt::lsl

    #deprecated("Use infix operator `<<` instead")
    fn UInt::lsl(self : UInt, shift : Int) -> UInt

    Performs a left shift operation on an unsigned 32-bit integer. Shifts each bit in the number to the left by the specified number of positions, filling the rightmost positions with zeros.

    Parameters:

    • self : The unsigned 32-bit integer to be shifted.
    • shift : The number of positions to shift the bits. Must be non-negative and less than 32. Values outside this range are wrapped to fit within it (i.e., shift & 31).

    Returns a new UInt value representing the result of shifting the bits left by the specified number of positions. Each position shifted multiplies the number by 2.

    Example:

    test {
    let x = 1U
    inspect(x << 3, content="8") // Using the recommended operator
    let y = 8U
    inspect(y << 1, content="16") // Using the recommended operator
    }

    UInt::lsr

    #deprecated("Use infix operator `>>` instead")
    fn UInt::lsr(self : UInt, shift : Int) -> UInt

    Performs a logical right shift on an unsigned 32-bit integer. Each bit in the input value is shifted right by the specified number of positions, with zeros shifted in from the left. DEPRECATED: Use the >> operator instead.

    Parameters:

    • self : The unsigned 32-bit integer to be shifted.
    • shift : The number of positions to shift right. Must be non-negative.

    Returns a new UInt value representing the result of the logical right shift operation.

    Example:

    test {
    let x = 0xF0000000U
    inspect(x >> 4, content="251658240") // Using the recommended operator
    }

    UInt::lxor

    fn UInt::lxor(self : UInt, other : UInt) -> UInt

    UInt::max

    fn UInt::max(self : UInt, other : UInt) -> UInt

    Returns the larger of two unsigned integers.

    Parameters:

    • self : The first integer to compare.
    • other : The second integer to compare.

    Returns self if it is not less than other, other otherwise.

    Example:

    test {
    inspect(UInt(1).max(UInt(2)), content="2")
    inspect(UInt(2).max(UInt(1)), content="2")
    inspect(UInt(0).max(UInt(0)), content="0")
    }

    UInt::min

    fn UInt::min(self : UInt, other : UInt) -> UInt

    Returns the smaller of two unsigned integers.

    Parameters:

    • self : The first integer to compare.
    • other : The second integer to compare.

    Returns self if it is not greater than other, other otherwise.

    Example:

    test {
    inspect(UInt(1).min(UInt(2)), content="1")
    inspect(UInt(2).min(UInt(1)), content="1")
    inspect(UInt(0).min(UInt(0)), content="0")
    }

    UInt::mod

    fn UInt::mod(self : UInt, other : UInt) -> UInt

    UInt::mul

    fn UInt::mul(self : UInt, other : UInt) -> UInt

    UInt::popcnt

    fn UInt::popcnt(self : UInt) -> Int

    Counts the number of 1 bits (population count) in the binary representation of an unsigned 32-bit integer.

    Parameters:

    • self : The unsigned 32-bit integer whose bits are to be counted.

    Returns an integer representing the count of set bits (1s) in the binary representation.

    Example:

    test {
    let x = 0xF0F0U // Binary: 1111 0000 1111 0000
    inspect(x.popcnt(), content="8") // Has 8 bits set to 1
    }

    UInt::reinterpret_as_float

    #deprecated("Use `Float::reinterpret_from_uint` instead")
    fn UInt::reinterpret_as_float(self : UInt) -> Float

    Reinterpret UInt bit pattern as Float (deprecated alias). Function reinterpret_as_float.

    UInt::reinterpret_as_int

    fn UInt::reinterpret_as_int(self : UInt) -> Int

    reinterpret the unsigned int as signed int For number within the range of 0..=2^31-1, the value is the same. For number within the range of 2^31..=2^32-1, the value is negative

    UInt::shl

    #deprecated("Use infix operator `<<` instead")
    fn UInt::shl(self : UInt, shift : Int) -> UInt

    Performs a left shift operation on an unsigned 32-bit integer. Shifts each bit in the integer to the left by the specified number of positions, filling the rightmost positions with zeros.

    Parameters:

    • self : The unsigned 32-bit integer to be shifted.
    • shift : The number of positions to shift left. Must be between 0 and 31 inclusive. Values outside this range will be masked with & 31.

    Returns a new UInt value containing the result of the left shift operation.

    Example:

    test {
    let x = 1U
    inspect(x << 3, content="8") // Binary: 1 -> 1000
    }

    UInt::shr

    #deprecated("Use infix operator `>>` instead")
    fn UInt::shr(self : UInt, shift : Int) -> UInt

    Performs a logical right shift operation on an unsigned 32-bit integer by a specified number of positions. All bits shifted in from the left are zeros.

    Parameters:

    • number : The unsigned 32-bit integer to be shifted.
    • shift : The number of positions to shift right. Must be non-negative.

    Returns a new UInt value that represents the result of shifting all bits in number to the right by shift positions.

    Example:

    test {
    let x = 0xFF000000U
    inspect(x >> 8, content="16711680") // 0x00FF0000
    }

    UInt::sub

    fn UInt::sub(self : UInt, other : UInt) -> UInt

    UInt::to_byte

    fn UInt::to_byte(self : UInt) -> Byte

    Converts an unsigned 32-bit integer to a byte by taking its least significant 8 bits. Any bits beyond the first 8 bits are truncated.

    Parameters:

    • self : The unsigned 32-bit integer to be converted. Only the least significant 8 bits will be used.

    Returns a byte containing the least significant 8 bits of the input integer.

    Example:

    test {
    let n = 258U // In binary: 100000010
    inspect(n.to_byte(), content="b'\\x02'") // Only keeps 00000010
    let big = 4294967295U // Maximum value of UInt
    inspect(big.to_byte(), content="b'\\xFF'") // Only keeps 11111111
    }

    UInt::to_double

    fn UInt::to_double(self : UInt) -> Double

    Converts an unsigned 32-bit integer to a double-precision floating-point number. Since the range of unsigned 32-bit integers is smaller than what can be precisely represented by a double-precision floating-point number, this conversion is guaranteed to be exact.

    Parameters:

    • value : The unsigned 32-bit integer to be converted.

    Returns a double-precision floating-point number that exactly represents the input value.

    Example:

    test {
    let n = 42U
    inspect(n.to_double(), content="42")
    let max = 4294967295U // maximum value of UInt
    inspect(max.to_double(), content="4294967295")
    }

    UInt::to_float

    #deprecated("Use `Float::from_uint` instead")
    fn UInt::to_float(self : UInt) -> Float

    Convert UInt to Float (deprecated alias). Convert to float.

    UInt::to_int

    #deprecated("Use `reinterpret_as_int` instead")
    fn UInt::to_int(self : UInt) -> Int

    Reinterprets an unsigned 32-bit integer as a signed 32-bit integer. For values within the range of 0 to 2^31-1, the value remains the same. For values within the range of 2^31 to 2^32-1, the value becomes negative due to two's complement representation.

    Parameters:

    • self : The unsigned 32-bit integer to be reinterpreted.

    Returns a signed 32-bit integer that has the same bit pattern as the input unsigned integer.

    Example:

    test {
    let a = 42U
    inspect(a.reinterpret_as_int(), content="42")
    let b = 4294967295U // maximum value of UInt (2^32 - 1)
    inspect(b.reinterpret_as_int(), content="-1") // becomes -1 when reinterpreted as Int
    }

    UInt::to_json

    fn UInt::to_json(self : UInt) -> Json

    UInt::to_string

    fn UInt::to_string(self : UInt, radix? : Int) -> String

    Converts an unsigned integer to its string representation in the specified radix (base).

    UInt::to_uint16

    fn UInt::to_uint16(self : UInt) -> UInt16

    Converts a 32-bit unsigned integer to a 16-bit unsigned integer by truncating its value to fit within the range of 0 to 65535.

    Parameters:

    • integer : The 32-bit unsigned integer to be converted. Values outside the range of UInt16 will be truncated to fit.

    Returns a 16-bit unsigned integer containing the lower 16 bits of the input value.

    Example:

    test {
    let n = 42U
    inspect(n.to_uint16(), content="42")
    let max = 4294967295U
    inspect(max.to_uint16(), content="65535") // -1 becomes max value of UInt16
    let large = 65536U
    inspect(large.to_uint16(), content="0") // Values wrap around
    }

    UInt::to_uint64

    fn UInt::to_uint64(self : UInt) -> UInt64

    Converts an unsigned 32-bit integer to an unsigned 64-bit integer by zero-extending it. The resulting value preserves the original number's magnitude while using 64 bits to represent it.

    Parameters:

    • self : The unsigned 32-bit integer (UInt) to be converted.

    Returns an unsigned 64-bit integer (UInt64) representing the same numerical value as the input.

    Example:

    test {
    let n = 42U
    inspect(n.to_uint64(), content="42")
    let max = 4294967295U // Maximum value of UInt
    inspect(max.to_uint64(), content="4294967295")
    }

    UInt::trunc_double

    fn UInt::trunc_double(val : Double) -> UInt

    Converts a double-precision floating-point number to an unsigned 32-bit integer by truncating the decimal part. When the input is NaN or negative, returns 0. When the input exceeds the maximum value of UInt (4294967295), returns 4294967295.

    Parameters:

    • value : The double-precision floating-point number to be converted.

    Returns an unsigned 32-bit integer representing the truncated value.

    Example:

    test {
    inspect(UInt::trunc_double(42.75), content="42")
    }

    UInt16

    UInt16::UInt16

    fn UInt16::UInt16(self : UInt16) -> UInt16

    The identity constructor for UInt16, allowing values to be written using constructor syntax, e.g. UInt16(3).

    Example:

    test {
    inspect(UInt16(3), content="3")
    }

    UInt16::add

    fn UInt16::add(self : UInt16, that : UInt16) -> UInt16

    UInt16::compare

    fn UInt16::compare(self : UInt16, that : UInt16) -> Int

    UInt16::div

    fn UInt16::div(self : UInt16, that : UInt16) -> UInt16

    UInt16::equal

    fn UInt16::equal(self : UInt16, that : UInt16) -> Bool

    UInt16::hash

    fn UInt16::hash(self : UInt16) -> Int

    UInt16::is_leading_surrogate

    fn UInt16::is_leading_surrogate(self : UInt16) -> Bool

    Checks if the integer value represents a UTF-16 leading surrogate. Leading surrogates are in the range 0xD800 to 0xDBFF.

    Example:
    test {
    inspect(UInt16(0xD800).is_leading_surrogate(), content="true")
    inspect(UInt16(0xDBFF).is_leading_surrogate(), content="true")
    inspect(UInt16(0xDC00).is_leading_surrogate(), content="false")
    inspect(UInt16(0x41).is_leading_surrogate(), content="false") // 'A'
    }

    UInt16::is_surrogate

    fn UInt16::is_surrogate(self : UInt16) -> Bool

    Checks if the integer value represents any UTF-16 surrogate (leading or trailing). Surrogates are in the range 0xD800 to 0xDFFF.

    Example:
    test {
    inspect(UInt16(0xD800).is_surrogate(), content="true") // leading surrogate
    inspect(UInt16(0xDC00).is_surrogate(), content="true") // trailing surrogate
    inspect(UInt16(0xDFFF).is_surrogate(), content="true") // trailing surrogate
    inspect(UInt16(0x41).is_surrogate(), content="false") // 'A'
    }

    UInt16::is_trailing_surrogate

    fn UInt16::is_trailing_surrogate(self : UInt16) -> Bool

    Checks if the integer value represents a UTF-16 trailing surrogate. Trailing surrogates are in the range 0xDC00 to 0xDFFF.

    Example:
    test {
    inspect(UInt16(0xDC00).is_trailing_surrogate(), content="true")
    inspect(UInt16(0xDFFF).is_trailing_surrogate(), content="true")
    inspect(UInt16(0xD800).is_trailing_surrogate(), content="false")
    inspect(UInt16(0x41).is_trailing_surrogate(), content="false") // 'A'
    }

    UInt16::land

    fn UInt16::land(self : UInt16, that : UInt16) -> UInt16

    UInt16::lnot

    fn UInt16::lnot(self : UInt16) -> UInt16

    Performs a bitwise NOT operation on a UInt16 value, flipping every bit within its 16-bit width.

    Parameters:

    • self : The UInt16 value to apply the bitwise NOT operation on.

    Returns the result of the bitwise NOT operation as a UInt16.

    Example:

    test {
    inspect(UInt16(0x0000).lnot().to_int(), content="65535")
    inspect(UInt16(0xFFFF).lnot().to_int(), content="0")
    }

    UInt16::lor

    fn UInt16::lor(self : UInt16, that : UInt16) -> UInt16

    UInt16::lxor

    fn UInt16::lxor(self : UInt16, that : UInt16) -> UInt16

    UInt16::mod

    fn UInt16::mod(self : UInt16, that : UInt16) -> UInt16

    UInt16::mul

    fn UInt16::mul(self : UInt16, that : UInt16) -> UInt16

    UInt16::shl

    fn UInt16::shl(self : UInt16, that : Int) -> UInt16

    UInt16::shr

    fn UInt16::shr(self : UInt16, that : Int) -> UInt16

    UInt16::sub

    fn UInt16::sub(self : UInt16, that : UInt16) -> UInt16

    UInt16::to_byte

    fn UInt16::to_byte(self : UInt16) -> Byte

    Converts a 16-bit unsigned integer to an 8-bit byte by truncating the higher bits.

    Parameters:

    • value : The 16-bit unsigned integer to be converted.

    Returns a byte containing the least significant 8 bits of the input value.

    Example:

    test {
    let x = Int::to_uint16(258) // Binary: 0000_0001_0000_0010
    inspect(x.to_byte(), content="b'\\x02'") // Only keeps 0000_0010
    }

    UInt16::to_char

    fn UInt16::to_char(self : UInt16) -> Char?

    Convert to char.

    UInt16::to_int

    fn UInt16::to_int(self : UInt16) -> Int

    Converts an unsigned 16-bit integer to a 32-bit signed integer. The value is zero-extended to fill the higher bits.

    Parameters:

    • value : The unsigned 16-bit integer to be converted.

    Returns a 32-bit signed integer. Since the input value is always non-negative and less than 65536, the conversion never results in overflow.

    Example:

    test {
    let x = Int::to_uint16(42)
    inspect(x.to_int(), content="42")
    let max = Int::to_uint16(65535) // maximum value of UInt16
    inspect(max.to_int(), content="65535")
    }

    UInt16::to_int64

    fn UInt16::to_int64(self : UInt16) -> Int64

    Converts an unsigned 16-bit integer to a signed 64-bit integer. The resulting value will always be non-negative since the input is unsigned.

    Parameters:

    • value : The unsigned 16-bit integer to be converted.

    Returns a 64-bit signed integer representing the same numerical value as the input.

    Example:

    test {
    let x = Int::to_uint16(42)
    inspect(x.to_int64(), content="42")
    let max = Int::to_uint16(65535) // maximum value of UInt16
    inspect(max.to_int64(), content="65535")
    }

    UInt16::to_json

    fn UInt16::to_json(self : UInt16) -> Json

    UInt16::to_string

    fn UInt16::to_string(self : UInt16, radix? : Int) -> String

    Convert UInt16 to string with optional radix.

    Example:

    test {
    inspect((255 : UInt16).to_string(), content="255")
    inspect((255 : UInt16).to_string(radix=16), content="ff")
    }

    UInt16::to_uint

    fn UInt16::to_uint(self : UInt16) -> UInt

    Convert to uint.

    UInt16::to_uint64

    fn UInt16::to_uint64(self : UInt16) -> UInt64

    Convert to uint64.

    UInt64

    UInt64::UInt64

    fn UInt64::UInt64(self : UInt64) -> UInt64

    The identity constructor for UInt64, allowing values to be written using constructor syntax, e.g. UInt64(3).

    Example:

    test {
    inspect(UInt64(3), content="3")
    }

    UInt64::add

    fn UInt64::add(self : UInt64, other : UInt64) -> UInt64

    UInt64::clz

    fn UInt64::clz(self : UInt64) -> Int

    Counts the number of leading zero bits in a 64-bit unsigned integer, starting from the most significant bit.

    Parameters:

    • value : The 64-bit unsigned integer to count leading zeros in.

    Returns the number of consecutive zeros starting from the most significant bit. For a zero value, returns 64.

    Example:

    test {
    inspect(0UL.clz(), content="64")
    inspect(1UL.clz(), content="63")
    inspect(0x8000_0000_0000_0000UL.clz(), content="0")
    }

    UInt64::compare

    fn UInt64::compare(self : UInt64, other : UInt64) -> Int

    UInt64::ctz

    fn UInt64::ctz(self : UInt64) -> Int

    Counts the number of trailing zero bits in a 64-bit unsigned integer. The trailing zeros are the contiguous zeros at the least significant end of the binary representation.

    Parameters:

    • value : The 64-bit unsigned integer to count trailing zeros in.

    Returns the number of trailing zero bits in the input value. If the input is 0, returns 64.

    Example:

    test {
    let x = 0x8000000000000000UL // Binary: 1000...0000 (63 trailing zeros)
    inspect(x.ctz(), content="63")
    let y = 0UL
    inspect(y.ctz(), content="64")
    }

    UInt64::div

    fn UInt64::div(self : UInt64, other : UInt64) -> UInt64

    UInt64::equal

    fn UInt64::equal(self : UInt64, other : UInt64) -> Bool

    UInt64::extend_uint

    fn UInt64::extend_uint(val : UInt) -> UInt64

    Converts an unsigned 32-bit integer to an unsigned 64-bit integer by zero-extending it. The resulting value preserves the original number's magnitude while using 64 bits to represent it.

    Parameters:

    • value : The unsigned 32-bit integer (UInt) to be converted.

    Returns an unsigned 64-bit integer (UInt64) representing the same numerical value as the input.

    Example:

    test {
    let n = 42U
    inspect(UInt64::extend_uint(n), content="42")
    let max = 4294967295U // Maximum value of UInt
    inspect(UInt64::extend_uint(max), content="4294967295")
    }

    UInt64::hash

    fn UInt64::hash(self : UInt64) -> Int

    UInt64::land

    fn UInt64::land(self : UInt64, other : UInt64) -> UInt64

    UInt64::lnot

    fn UInt64::lnot(self : UInt64) -> UInt64

    Performs a bitwise NOT operation on a 64-bit unsigned integer. Flips all bits in the number, changing each 0 to 1 and each 1 to 0.

    Parameters:

    • self : The 64-bit unsigned integer value on which to perform the bitwise NOT operation.

    Returns a new UInt64 value with all bits flipped from the input value.

    Example:

    test {
    let x = 0xFFFF_FFFF_0000_0000UL
    inspect(x.lnot(), content="4294967295") // 0x0000_0000_FFFF_FFFF
    }

    UInt64::lor

    fn UInt64::lor(self : UInt64, other : UInt64) -> UInt64

    UInt64::lsl

    #deprecated("Use infix operator `<<` instead")
    fn UInt64::lsl(self : UInt64, shift : Int) -> UInt64

    Performs a left shift operation on a 64-bit unsigned integer by a specified number of bits.

    Parameters:

    • value : The 64-bit unsigned integer to be shifted.
    • shift : The number of positions to shift left. Only the lowest 6 bits are used, effectively making the shift value wrap around at 64.

    Returns a new UInt64 value representing the result of shifting the bits left by the specified number of positions. Bits shifted beyond the 64-bit boundary are discarded, and zeros are shifted in from the right.

    Example:

    test {
    let x = 1UL
    inspect(x << 4, content="16") // 1 << 4 = 16
    }

    UInt64::lsr

    #deprecated("Use infix operator `>>` instead")
    fn UInt64::lsr(self : UInt64, shift : Int) -> UInt64

    Performs a logical right shift operation on a 64-bit unsigned integer. Moves all bits to the right by a specified number of positions, filling the leftmost bits with zeros.

    Parameters:

    • self : The 64-bit unsigned integer to be shifted.
    • shift : The number of positions to shift right. If this value is negative or greater than 63, the behavior is undefined.

    Returns a new UInt64 value containing the result of the right shift operation.

    Example:

    test {
    let x = 0xF000000000000000UL
    inspect(x >> 4, content="1080863910568919040") // 0x0F00000000000000
    }

    UInt64::lxor

    fn UInt64::lxor(self : UInt64, other : UInt64) -> UInt64

    UInt64::mod

    fn UInt64::mod(self : UInt64, other : UInt64) -> UInt64

    UInt64::mul

    fn UInt64::mul(self : UInt64, other : UInt64) -> UInt64

    UInt64::popcnt

    fn UInt64::popcnt(self : UInt64) -> Int

    Counts the number of bits set to 1 in the binary representation of an unsigned 64-bit integer.

    Parameters:

    • self : The unsigned 64-bit integer whose bits are to be counted.

    Returns an integer representing the number of 1 bits (population count) in the binary representation of the input.

    Example:

    test {
    let n = 0x7000_0001_1F00_100FUL // Binary: 0111 0000 ... 0001 1111 0000 0000 0001 0000 0000 1111
    inspect(n.popcnt(), content="14") // Has 14 bits set to 1
    }

    UInt64::reinterpret_as_double

    fn UInt64::reinterpret_as_double(self : UInt64) -> Double

    Reinterprets the bits of an unsigned 64-bit integer as a double-precision floating-point number according to IEEE 754 standard. The bit pattern of the input is preserved, only the type interpretation changes.

    Parameters:

    • value : The unsigned 64-bit integer whose bits are to be reinterpreted as a double-precision floating-point number.

    Returns a double-precision floating-point number that has the same bit pattern as the input unsigned 64-bit integer.

    Example:

    test {
    // 0x4059000000000000 represents 100.0 in IEEE 754 double format
    let n = 4636737291354636288UL
    inspect(n.reinterpret_as_double(), content="100")
    }

    UInt64::reinterpret_as_int64

    fn UInt64::reinterpret_as_int64(self : UInt64) -> Int64

    Reinterprets the bits of an unsigned 64-bit integer as a signed 64-bit integer. The bits remain the same, but their interpretation changes. This operation is useful for low-level bit manipulation and type conversions where you want to preserve the exact bit pattern.

    Parameters:

    • value : The unsigned 64-bit integer (UInt64) to be reinterpreted.

    Returns a signed 64-bit integer (Int64) that has the same bit pattern as the input value.

    Example:

    test {
    let max = 18446744073709551615UL // Maximum value of UInt64
    inspect(max.reinterpret_as_int64(), content="-1") // All bits set to 1 represents -1 in two's complement
    }

    UInt64::shl

    #deprecated("Use infix operator `<<` instead")
    fn UInt64::shl(self : UInt64, shift : Int) -> UInt64

    Performs a left shift operation on an unsigned 64-bit integer value, shifting bits to the left by the specified number of positions.

    Parameters:

    • number : The unsigned 64-bit integer to be shifted.
    • shift : The number of positions to shift the bits left. Must be non-negative.

    Returns an unsigned 64-bit integer representing the result of the left shift operation.

    Example:

    test {
    let x = 1UL
    inspect(x << 2, content="4") // 1 << 2 = 4
    }

    UInt64::shr

    #deprecated("Use infix operator `>>` instead")
    fn UInt64::shr(self : UInt64, shift : Int) -> UInt64

    Performs a logical right shift on an unsigned 64-bit integer by a specified number of bit positions. All bits shifted in from the left are zeros.

    Parameters:

    • self : The unsigned 64-bit integer to be shifted.
    • shift : The number of positions to shift right.

    Returns the result of shifting the bits in self right by shift positions.

    Example:

    test {
    let x = 0xFF00000000000000UL
    inspect(x >> 8, content="71776119061217280")
    }

    UInt64::sub

    fn UInt64::sub(self : UInt64, other : UInt64) -> UInt64

    UInt64::to_be_bytes

    fn UInt64::to_be_bytes(self : UInt64) -> Bytes

    Converts the UInt64 to a Bytes of 8 bytes in big-endian byte order (most significant byte first).

    Parameters:

    • self : The 64-bit unsigned integer to convert.

    Returns a Bytes of length 8 whose first element is the most significant byte of self and whose last element is the least significant byte.

    Example:

    test {
    // 0x41..0x48 are the ASCII codes for 'A'..'H'
    inspect(
    0x4142_4344_4546_4748UL.to_be_bytes(),
    content=(
    #|b"ABCDEFGH"
    ),
    )
    }

    UInt64::to_byte

    fn UInt64::to_byte(self : UInt64) -> Byte

    Converts an unsigned 64-bit integer to a byte by truncating it to fit within the byte range (0 to 255).

    Parameters:

    • self : The unsigned 64-bit integer to be converted.

    Returns a byte containing the least significant 8 bits of the input integer.

    Example:

    test {
    let n = 258UL // In binary: 100000010
    inspect(n.to_byte(), content="b'\\x02'") // Only keeps 00000010
    }

    UInt64::to_double

    fn UInt64::to_double(self : UInt64) -> Double

    Converts an unsigned 64-bit integer to a double-precision floating-point number.

    Parameters:

    • self : The unsigned 64-bit integer (UInt64) to be converted.

    Returns a double-precision floating-point number (Double) that represents the same numerical value as the input. Note that due to the limited precision of double-precision floating-point numbers, values larger than 2^53 may lose precision during the conversion.

    Example:

    let n = 12345678901234567890UL inspect(n.to_double(), content="12345678901234567000") // Note the slight precision loss let small = 42UL inspect(small.to_double(), content="42")

    UInt64::to_float

    #deprecated("Use `Float::from_uint64` instead")
    fn UInt64::to_float(self : UInt64) -> Float

    Convert UInt64 to Float (deprecated alias).

    UInt64::to_int

    fn UInt64::to_int(self : UInt64) -> Int

    Converts an unsigned 64-bit integer to a 32-bit signed integer. The conversion truncates the value to fit within the 32-bit range, possibly losing information if the input value is too large.

    Parameters:

    • self : The unsigned 64-bit integer to be converted.

    Returns a 32-bit signed integer representing the lower 32 bits of the input value. If the input value is larger than the maximum value of a 32-bit signed integer (2147483647), the result will be the truncated value interpreted as a signed integer.

    Example:

    test {
    let a = 42UL
    inspect(a.to_int(), content="42")
    let b = 18446744073709551615UL // max value of UInt64
    inspect(b.to_int(), content="-1") // truncated to 32 bits
    }

    UInt64::to_int64

    #deprecated("Use `reinterpret_as_int64` instead")
    fn UInt64::to_int64(self : UInt64) -> Int64

    Reinterprets a 64-bit unsigned integer as a 64-bit signed integer. The bits of the number remain unchanged; only the interpretation of these bits changes. This function is deprecated; use reinterpret_as_int64 instead.

    Parameters:

    • value : The 64-bit unsigned integer to be reinterpreted.

    Returns a 64-bit signed integer representing the same bit pattern as the input.

    Example:

    test {
    let max = 18446744073709551615UL
    inspect(max.reinterpret_as_int64(), content="-1")
    }

    UInt64::to_json

    fn UInt64::to_json(self : UInt64) -> Json

    UInt64::to_le_bytes

    fn UInt64::to_le_bytes(self : UInt64) -> Bytes

    Converts the UInt64 to a Bytes of 8 bytes in little-endian byte order (least significant byte first).

    Parameters:

    • self : The 64-bit unsigned integer to convert.

    Returns a Bytes of length 8 whose first element is the least significant byte of self and whose last element is the most significant byte.

    Example:

    test {
    // The same value as `to_be_bytes`, with the byte order reversed
    inspect(
    0x4142_4344_4546_4748UL.to_le_bytes(),
    content=(
    #|b"HGFEDCBA"
    ),
    )
    }

    UInt64::to_string

    fn UInt64::to_string(self : UInt64, radix? : Int) -> String

    Converts an unsigned 64-bit integer to its string representation in the specified radix (base).

    UInt64::to_uint

    fn UInt64::to_uint(self : UInt64) -> UInt

    Converts a 64-bit unsigned integer to a 32-bit unsigned integer by truncating the higher 32 bits.

    Parameters:

    • self : The 64-bit unsigned integer to be converted.

    Returns a 32-bit unsigned integer containing the lower 32 bits of the input value.

    Example:

    test {
    let big = 0xFFFFFFFFFFFFFFFFUL // max value of UInt64
    inspect(big.to_uint(), content="4294967295") // 0xFFFFFFFF, max value of UInt
    let small = 42UL
    inspect(small.to_uint(), content="42")
    }

    UInt64::to_uint16

    fn UInt64::to_uint16(self : UInt64) -> UInt16

    Converts a 64-bit unsigned integer to a 16-bit unsigned integer by truncating the value to fit within the range of UInt16 (0 to 65535).

    Parameters:

    • value : The 64-bit unsigned integer to be converted to UInt16.

    Returns a 16-bit unsigned integer representing the lower 16 bits of the input value.

    Example:

    test {
    inspect(42UL.to_uint16(), content="42")
    inspect(18446744073709551615UL.to_uint16(), content="65535") // Wraps around to maximum UInt16 value
    inspect(70000UL.to_uint16(), content="4464") // Value is truncated
    }

    UInt64::trunc_double

    fn UInt64::trunc_double(val : Double) -> UInt64

    Converts a double-precision floating-point number to an unsigned 64-bit integer by truncating its decimal part. This is a raw conversion function that does not handle special cases like NaN or infinity.

    Parameters:

    • value : The double-precision floating-point number to be truncated and converted.

    Returns an unsigned 64-bit integer. The decimal part of the input is discarded (truncated towards zero).

    Example:

    test {
    inspect(UInt64::trunc_double(42.75), content="42")
    }

    Unit

    Unit::compare

    fn Unit::compare(_ : Unit, _ : Unit) -> Int

    Unit::equal

    fn Unit::equal(_ : Unit, _ : Unit) -> Bool

    Unit::hash

    fn Unit::hash(self : Unit) -> Int

    Unit::to_json

    fn Unit::to_json(_self : Unit) -> Json

    Unit::to_string

    fn Unit::to_string(_self : Unit) -> String

    abort

    fn[T] abort(_ : String) -> T

    assert_false

    #callsite(autofill(loc))
    fn assert_false(x : Bool, msg? : StringView, loc~ : SourceLoc) -> Unit raise

    Tests whether a boolean condition is false, throwing an error if the condition is true.

    Parameters:

    • condition : The boolean condition to test.
    • location : The source location where the assertion is made. Used in error messages.

    Throws a Failure error if the condition is true. The error message includes the source location and the value that was expected to be false.

    Example:

    test {
    assert_false(false)
    assert_false(1 > 2)
    }

    assert_true

    #callsite(autofill(loc))
    fn assert_true(x : Bool, msg? : StringView, loc~ : SourceLoc) -> Unit raise

    Asserts that the given boolean value is true. Throws an error with source location information if the assertion fails.

    Parameters:

    • condition : The boolean value to be checked.
    • location : The source location where the assertion is made. Defaults to the current location.

    Throws a Failure error with a descriptive message including the source location if the condition is false.

    Example:

    test {
    assert_true(true)
    }

    compare

    fn[A : Compare + Eq] compare(x : A, y : A) -> Int

    Three-way comparison of two values, returning a negative integer, zero, or a positive integer when x is less than, equal to, or greater than y.

    This is the free-function form of the Compare::compare trait method, symmetric with hash. Being a plain function, it can also be passed as a function value, e.g. array.sort_by(compare).

    test {
    inspect(compare(1, 2).is_neg(), content="true")
    inspect(compare("abc", "abc"), content="0")
    }

    debug_assert

    fn debug_assert(x : () -> Bool) -> Unit

    Asserts that a condition is true in debug mode.

    The condition is provided as a thunk and is evaluated only when assertions are enabled. If the condition evaluates to false, this function do panic.

    In release mode, debug_assert is a no-op and does not evaluate the thunk.

    Parameters:

    • x : A thunk that computes the condition to check.

    Panic in debug mode when x() returns false.

    fail

    #callsite(autofill(loc))
    fn[T] fail(msg : StringView, loc~ : SourceLoc) -> T raise Failure

    Raises a Failure error with a given message and source location.

    Parameters:

    • message : A string containing the error message to be included in the failure.
    • location : The source code location where the failure occurred. Automatically provided by the compiler when not specified.

    Returns a value of type T wrapped in a Failure error type.

    Throws an error of type Failure with a message that includes both the source location and the provided error message.

    hash

    fn[T : Hash] hash(value : T) -> Int

    Compute the hash of value.

    This is the free-function form of the Hash::hash trait method, symmetric with @json.to_json. Prefer it over the promoted value.hash() method.

    test {
    inspect(hash(42) == hash(42), content="true")
    }

    ignore

    fn[T] ignore(t : T) -> Unit

    Evaluates an expression and discards its result. This is useful when you want to execute an expression for its side effects but don't care about its return value, or when you want to explicitly indicate that a value is intentionally unused.

    Parameters:

    • value : The value to be ignored. Can be of any type.

    Example:

    test {
    let x = 42
    ignore(x) // Explicitly ignore the value
    let mut sum = 0
    ignore(1, 2, 3.each(x => sum x)) // Ignore the Unit return value of each()
    inspect(sum, content="6")
    }

    inspect

    #callsite(autofill(args_loc, loc))
    fn inspect(obj : &Show, content? : String, loc~ : SourceLoc, args_loc~ : ArgsLoc) -> Unit raise InspectError

    Tests if the string representation of an object matches the expected content. Used primarily in test cases to verify the correctness of Show implementations and program outputs.

    Parameters:

    • object : The object to be inspected. Must implement the Show trait.
    • content : The expected string representation of the object. Defaults to an empty string.
    • location : Source code location information for error reporting. Automatically provided by the compiler.
    • arguments_location : Location information for function arguments in source code. Automatically provided by the compiler.

    Throws an InspectError if the actual string representation of the object does not match the expected content. The error message includes detailed information about the mismatch, including source location and both expected and actual values.

    Example:

    test {
    inspect(42, content="42")
    inspect("hello", content="hello")
    debug_inspect([1, 2, 3], content="[1, 2, 3]")
    }

    not

    #deprecated("This function is deprecated.")
    fn not(x : Bool) -> Bool

    Performs logical negation on a boolean value.

    Parameters:

    • value : The boolean value to negate.

    Returns the logical NOT of the input value: true if the input is false, and false if the input is true.

    null

    let null : Json

    JSON null constant.

    Equivalent to Json::null().

    Example:

    test {
    inspect(null.stringify(), content="null")
    }

    op_notequal

    fn[T : Eq] op_notequal(x : T, y : T) -> Bool

    Operator helper op_notequal.

    panic

    fn[T] panic() -> T

    Raise a panic with no payload.

    This function never returns.

    physical_equal

    fn[T] physical_equal(a : T, b : T) -> Bool

    Tests whether two values are physically equal.

    This function is intended only for performance optimizations. Do not depend on its result for program semantics.

    NOTE: The result of physical_equal may not be consistent across different backends and/or different compiler optimization settings.

    Parameters:

    • first : The first value to compare.
    • second : The second value to compare.
    • T : The type parameter representing the type of values being compared.

    Returns a backend- and optimization-dependent result indicating whether the two values are physically equal.

    Example:

    test {
    let arr1 = [1, 2, 3]
    let arr2 = arr1
    let arr3 = [1, 2, 3]
    inspect(physical_equal(arr1, arr2), content="true") // Same object
    inspect(physical_equal(arr1, arr3), content="false") // Different objects with same content
    }

    println

    fn[T : Show] println(input : T) -> Unit

    Prints any value that implements the Show trait to the standard output, followed by a newline.

    Parameters:

    • value : The value to be printed. Must implement the Show trait.

    Example:

    test {
    if false {
    println(42)
    println("Hello, World!")
    }
    }