///|
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")
}///|
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)")
}///|
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")
}
}///|
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")
}
}///|
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")
}///|
test "arrays" {
// Dynamic arrays
let arr1 = Array::new()
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")
}///|
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")
}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]"///|
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)
}///|
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")
}///|
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!")
}///|
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")
),
)
}///|
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")
}///|
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
}///|
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")
}pub(open) trait Add {
fn add(Self, Self) -> Self
}fn add(self : Byte, that : Byte) -> Bytefn add(self : Int, other : Int) -> Inttest {
inspect(42 + 1, content="43")
inspect(2147483647 + 1, content="-2147483648") // Overflow wraps around to minimum value
}fn add(self : Int64, other : Int64) -> Int64test {
let a = 9223372036854775807L // Int64 maximum value
let b = 1L
inspect(a + b, content="-9223372036854775808") // Wraps around to minimum value
inspect(42L + -42L, content="0")
}fn add(self : UInt, other : UInt) -> UInttest {
let a = 42U
let b = 100U
inspect(a + b, content="142")
// Demonstrate overflow behavior
let max = 4294967295U // UInt::max_value
inspect(max + 1U, content="0")
}fn add(self : UInt64, other : UInt64) -> UInt64test {
let a = 42UL
let b = 100UL
inspect(a + b, content="142")
// Demonstrate overflow behavior
let max = 18446744073709551615UL
inspect(max + 1UL, content="0")
}fn add(self : Double, other : Double) -> Doubletest {
inspect(2.5 + 3.7, content="6.2")
inspect(1.0 / 0.0 + -1.0 / 0.0, content="NaN") // Infinity + -Infinity = NaN
}fn add(self : String, other : String) -> Stringtest {
let hello = "Hello"
let world = " World!"
inspect(hello + world, content="Hello World!")
inspect("" + "abc", content="abc") // concatenating with empty string
}impl Add for FixedArray[T]fn[T] add(self : FixedArray[T], other : FixedArray[T]) -> FixedArray[T]test {
let arr1 : FixedArray[Int] = [1, 2, 3]
let arr2 : FixedArray[Int] = [4, 5, 6]
debug_inspect(
arr1 + arr2,
content=(
#|<FixedArray: [1, 2, 3, 4, 5, 6]>
),
)
}fn add(self : Bytes, other : Bytes) -> Bytesimpl Add for StringViewfn add(self : StringView, other : StringView) -> StringViewpub(open) trait BitAnd {
fn land(Self, Self) -> Self
}fn land(self : Byte, that : Byte) -> Bytefn land(self : Int, other : Int) -> Inttest {
let x = 0xF0 // 11110000
let y = 0xAA // 10101010
inspect(x & y, content="160") // 10100000 = 160
}fn land(self : Int64, other : Int64) -> Int64test {
let a = 0xFF00FF00L
let b = 0x0F0F0F0FL
inspect(a & b, content="251662080") // 0x0F000F00
}fn land(self : UInt, other : UInt) -> UInttest {
let a = 0xF0F0U // 1111_0000_1111_0000
let b = 0xFF00U // 1111_1111_0000_0000
inspect(a & b, content="61440") // 1111_0000_0000_0000 = 61440
}fn land(self : UInt64, other : UInt64) -> UInt64test {
let a = 0xF0F0F0F0F0F0F0F0UL
let b = 0xFF00FF00FF00FF00UL
inspect(a & b, content="17294086455919964160") // 0xF000F000F000F000
}pub(open) trait BitOr {
fn lor(Self, Self) -> Self
}fn lor(self : Byte, that : Byte) -> Bytefn lor(self : Int, other : Int) -> Inttest {
let x = 0xF0F0 // 1111_0000_1111_0000
let y = 0x0F0F // 0000_1111_0000_1111
inspect(x | y, content="65535") // 1111_1111_1111_1111 = 65535
}fn lor(self : Int64, other : Int64) -> Int64test {
let a = 0xFF00L // 1111_1111_0000_0000
let b = 0x0FF0L // 0000_1111_1111_0000
inspect(a | b, content="65520") // 1111_1111_1111_0000 = 65520
}fn lor(self : UInt, other : UInt) -> UInttest {
let a = 0xF0F0U // Binary: 1111_0000_1111_0000
let b = 0x0F0FU // Binary: 0000_1111_0000_1111
inspect(a | b, content="65535") // Binary: 1111_1111_1111_1111
}fn lor(self : UInt64, other : UInt64) -> UInt64test {
let a = 0xF0F0F0F0UL
let b = 0x0F0F0F0FUL
inspect(a | b, content="4294967295") // All bits set to 1
}pub(open) trait BitXOr {
fn lxor(Self, Self) -> Self
}fn lxor(self : Byte, that : Byte) -> Bytefn lxor(self : Int, other : Int) -> Inttest {
let x = 0xF0F0 // 1111_0000_1111_0000
let y = 0x0F0F // 0000_1111_0000_1111
inspect(x ^ y, content="65535") // 1111_1111_1111_1111
inspect(x ^ x, content="0") // XOR with self gives 0
}fn lxor(self : Int64, other : Int64) -> Int64test {
let a = 0xF0F0F0F0F0F0F0F0L
let b = 0x0F0F0F0F0F0F0F0FL
inspect(a ^ b, content="-1") // All bits set to 1
inspect(a ^ a, content="0") // XOR with self gives 0
}fn lxor(self : UInt, other : UInt) -> UInttest {
let a = 0xFF00U // Binary: 1111_1111_0000_0000
let b = 0x0F0FU // Binary: 0000_1111_0000_1111
inspect(a ^ b, content="61455") // Binary: 1111_0000_0000_1111
}fn lxor(self : UInt64, other : UInt64) -> UInt64test {
let a = 0xF0F0F0F0UL
let b = 0x0F0F0F0FUL
inspect(a ^ b, content="4294967295") // 0xFFFFFFFF
}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 = _
}fn compare(self : Bool, other : Bool) -> Inttest {
inspect(true.compare(false), content="1") // true > false
inspect(false.compare(true), content="-1") // false < true
inspect(true.compare(true), content="0") // true = true
}fn compare(self : Byte, that : Byte) -> Intfn op_ge(x : Byte, y : Byte) -> Boolfn op_gt(x : Byte, y : Byte) -> Boolfn op_le(x : Byte, y : Byte) -> Boolfn op_lt(x : Byte, y : Byte) -> Boolfn compare(self : Char, other : Char) -> Inttest {
inspect('a'.compare('b'), content="-1")
inspect('b'.compare('a'), content="1")
inspect('a'.compare('a'), content="0")
}fn op_ge(x : Char, y : Char) -> Boolfn op_gt(x : Char, y : Char) -> Boolfn op_le(x : Char, y : Char) -> Boolfn op_lt(x : Char, y : Char) -> Boolfn compare(self : Int, other : Int) -> Inttest {
let a = 42
let b = 24
inspect(a.compare(b), content="1") // 42 > 24
inspect(b.compare(a), content="-1") // 24 < 42
inspect(a.compare(a), content="0") // 42 = 42
}fn op_ge(x : Int, y : Int) -> Boolfn op_gt(x : Int, y : Int) -> Boolfn op_le(x : Int, y : Int) -> Boolfn op_lt(x : Int, y : Int) -> Boolfn compare(self : Int64, other : Int64) -> Inttest {
let a = 42L
let b = 24L
let c = -42L
inspect(a.compare(b), content="1") // 42 > 24
inspect(b.compare(a), content="-1") // 24 < 42
inspect(c.compare(a), content="-1") // -42 < 42
inspect(a.compare(a), content="0") // 42 = 42
}fn op_ge(x : Int64, y : Int64) -> Boolfn op_gt(x : Int64, y : Int64) -> Boolfn op_le(x : Int64, y : Int64) -> Boolfn op_lt(x : Int64, y : Int64) -> Boolfn compare(self : UInt, other : UInt) -> Inttest {
let a = 42U
let b = 24U
inspect(a.compare(b), content="1") // 42 > 24
inspect(b.compare(a), content="-1") // 24 < 42
inspect(a.compare(a), content="0") // 42 = 42
}fn op_ge(x : UInt, y : UInt) -> Boolfn op_gt(x : UInt, y : UInt) -> Boolfn op_le(x : UInt, y : UInt) -> Boolfn op_lt(x : UInt, y : UInt) -> Boolfn compare(self : UInt64, other : UInt64) -> Inttest {
let a = 42UL
let b = 24UL
inspect(a.compare(b), content="1") // 42 > 24
inspect(b.compare(a), content="-1") // 24 < 42
inspect(a.compare(a), content="0") // 42 = 42
}fn op_ge(x : UInt64, y : UInt64) -> Boolfn op_gt(x : UInt64, y : UInt64) -> Boolfn op_le(x : UInt64, y : UInt64) -> Boolfn op_lt(x : UInt64, y : UInt64) -> Boolfn compare(self : Double, other : Double) -> Inttest {
let a = 3.14
let b = 2.718
inspect(a.compare(b), content="1") // 3.14 > 2.718
inspect(b.compare(a), content="-1") // 2.718 < 3.14
inspect(a.compare(a), content="0") // 3.14 = 3.14
}fn op_ge(x : Double, y : Double) -> Boolfn op_gt(x : Double, y : Double) -> Boolfn op_le(x : Double, y : Double) -> Boolfn op_lt(x : Double, y : Double) -> Boolfn compare(self : String, other : String) -> Intimpl Compare for FixedArray[T]test {
let arr1 = [1, 2, 3]
let arr2 = [1, 2, 4]
let arr3 = [1, 2]
inspect(arr1.compare(arr2), content="-1") // arr1 < arr2
inspect(arr2.compare(arr1), content="1") // arr2 > arr1
inspect(arr1.compare(arr3), content="1") // arr1 > arr3 (longer)
inspect(arr1.compare(arr1), content="0") // arr1 = arr1
}impl Compare for ReadOnlyArray[T]fn compare(self : Bytes, other : Bytes) -> Inttest {
let a = b"\x01\x02\x03"
let b = b"\x01\x02\x04"
inspect(a.compare(b), content="-1") // a < b
inspect(b.compare(a), content="1") // b > a
inspect(a.compare(a), content="0") // a = a
let a = b"\x01\x02"
let b = b"\x01\x02\x03"
inspect(a.compare(b), content="-1") // shorter sequence is less
inspect(b.compare(a), content="1") // longer sequence is greater
}fn[T0 : Compare + Eq, T1 : Compare + Eq, T2 : Compare + Eq, T3 : Compare + Eq, T4 : Compare + Eq, T5 : Compare + Eq, T6 : Compare + Eq, T7 : Compare + Eq, T8 : Compare + Eq, T9 : Compare + Eq] compare(self : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9), other : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9)) -> Intfn[T0 : Compare + Eq, T1 : Compare + Eq, T2 : Compare + Eq, T3 : Compare + Eq, T4 : Compare + Eq, T5 : Compare + Eq, T6 : Compare + Eq, T7 : Compare + Eq, T8 : Compare + Eq, T9 : Compare + Eq, T10 : Compare + Eq] compare(self : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10), other : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)) -> Intfn[T0 : Compare + Eq, T1 : Compare + Eq, T2 : Compare + Eq, T3 : Compare + Eq, T4 : Compare + Eq, T5 : Compare + Eq, T6 : Compare + Eq, T7 : Compare + Eq, T8 : Compare + Eq, T9 : Compare + Eq, T10 : Compare + Eq, T11 : Compare + Eq] compare(self : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11), other : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11)) -> Intfn[T0 : Compare + Eq, T1 : Compare + Eq, T2 : Compare + Eq, T3 : Compare + Eq, T4 : Compare + Eq, T5 : Compare + Eq, T6 : Compare + Eq, T7 : Compare + Eq, T8 : Compare + Eq, T9 : Compare + Eq, T10 : Compare + Eq, T11 : Compare + Eq, T12 : Compare + Eq] compare(self : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12), other : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12)) -> Intfn[T0 : Compare + Eq, T1 : Compare + Eq, T2 : Compare + Eq, T3 : Compare + Eq, T4 : Compare + Eq, T5 : Compare + Eq, T6 : Compare + Eq, T7 : Compare + Eq, T8 : Compare + Eq, T9 : Compare + Eq, T10 : Compare + Eq, T11 : Compare + Eq, T12 : Compare + Eq, T13 : Compare + Eq] compare(self : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13), other : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13)) -> Intfn[T0 : Compare + Eq, T1 : Compare + Eq, T2 : Compare + Eq, T3 : Compare + Eq, T4 : Compare + Eq, T5 : Compare + Eq, T6 : Compare + Eq, T7 : Compare + Eq, T8 : Compare + Eq, T9 : Compare + Eq, T10 : Compare + Eq, T11 : Compare + Eq, T12 : Compare + Eq, T13 : Compare + Eq, T14 : Compare + Eq] compare(self : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14), other : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14)) -> Intfn[T0 : Compare + Eq, T1 : Compare + Eq, T2 : Compare + Eq, T3 : Compare + Eq, T4 : Compare + Eq, T5 : Compare + Eq, T6 : Compare + Eq, T7 : Compare + Eq, T8 : Compare + Eq, T9 : Compare + Eq, T10 : Compare + Eq, T11 : Compare + Eq, T12 : Compare + Eq, T13 : Compare + Eq, T14 : Compare + Eq, T15 : Compare + Eq] compare(self : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15), other : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15)) -> Intfn compare(self : BytesView, other : BytesView) -> Inttest {
let bytes = b"abcabc"
inspect(bytes[0:3].compare(bytes[3:6]), content="0") // abc = abc
inspect(bytes[0:3].compare(bytes[2:5]), content="-1") // abc < cab
inspect(bytes[1:4].compare(bytes[3:6]), content="1") // bca > abc
inspect(bytes[0:3].compare(bytes[0:4]), content="-1") // abc < abca
inspect(bytes[1:5].compare(bytes[2:5]), content="1") // bcab > cab
}impl Compare for StringViewfn compare(self : StringView, other : StringView) -> Intpub(open) trait Default {
fn default() -> Self
}fn default() -> Booltest {
let b : Bool = false
inspect(b, content="false")
}fn default() -> Bytefn default() -> Chartest {
assert_true((Default::default() : Char).to_string() == "\u0000")
}fn default() -> Inttest {
let x : Int = 0
inspect(x, content="0")
}fn default() -> Int64test {
inspect(0L, content="0")
}fn default() -> Doubletest {
inspect(0.0, content="0")
}impl Default for FixedArray[X]fn[X] default() -> FixedArray[X]test {
let arr : FixedArray[Int] = ([] : FixedArray[_])
inspect(arr.length(), content="0")
inspect(arr.is_empty(), content="true")
}impl Default for ReadOnlyArray[T]fn[T] default() -> ReadOnlyArray[T]fn default() -> Bytestest {
let bytes = (Default::default() : Bytes)
inspect(bytes, content="b\"\"")
inspect(bytes.length(), content="0")
}impl Default for StringViewfn default() -> StringViewpub(open) trait Div {
fn div(Self, Self) -> Self
}fn div(self : Byte, that : Byte) -> Bytetest {
let a = b'\xFF' // 255
let b = b'\x03' // 3
inspect(a / b, content="b'\\x55'") // 255 / 3 = 85 (0x55)
}fn div(self : Int, other : Int) -> Inttest {
inspect(10 / 3, content="3") // truncates towards zero
inspect(-10 / 3, content="-3")
inspect(10 / -3, content="-3")
}fn div(self : Int64, other : Int64) -> Int64test {
let a = 42L
let b = 5L
inspect(a / b, content="8")
let c = -42L
let d = 5L
inspect(c / d, content="-8")
}fn div(self : UInt, other : UInt) -> UInttest {
let a = 42U
let b = 5U
inspect(a / b, content="8") // Using infix operator
}fn div(self : UInt64, other : UInt64) -> UInt64test {
let a = 100UL
let b = 20UL
inspect(a / b, content="5") // Using infix operator
}fn div(self : Double, other : Double) -> Doubletest {
inspect(6.0 / 2.0, content="3")
inspect(-6.0 / 2.0, content="-3")
inspect(1.0 / 0.0, content="Infinity")
}pub(open) trait Eq {
fn equal(Self, Self) -> Bool
fn not_equal(Self, Self) -> Bool = _
}fn equal(self : Bool, other : Bool) -> Booltest {
inspect(true == true, content="true")
inspect(false == true, content="false")
inspect(true == false, content="false")
inspect(false == false, content="true")
}fn equal(self : Byte, that : Byte) -> Boolfn not_equal(self : Byte, that : Byte) -> Boolfn equal(self : Char, other : Char) -> Booltest {
let a = 'A'
let b = 'A'
let c = 'B'
inspect(a == b, content="true")
inspect(a == c, content="false")
}fn not_equal(self : Char, other : Char) -> Booltest {
let a = 'A'
let b = 'A'
let c = 'B'
inspect(a != b, content="false")
inspect(a != c, content="true")
}fn equal(self : Int, other : Int) -> Booltest {
inspect(42 == 42, content="true")
inspect(42 == -42, content="false")
}fn not_equal(self : Int, other : Int) -> Booltest {
inspect(42 != 42, content="false")
inspect(42 != -42, content="true")
}fn equal(self : Int64, other : Int64) -> Booltest {
let a = 42L
let b = 42L
let c = -42L
inspect(a == b, content="true")
inspect(a == c, content="false")
}fn not_equal(self : Int64, other : Int64) -> Booltest {
let a = 42L
let b = 42L
let c = -42L
inspect(a != b, content="false")
inspect(a != c, content="true")
}fn equal(self : UInt, other : UInt) -> Booltest {
let a = 42U
let b = 42U
let c = 24U
inspect(a == b, content="true")
inspect(a == c, content="false")
}fn not_equal(self : UInt, other : UInt) -> Booltest {
let a = 42U
let b = 42U
let c = 24U
inspect(a != b, content="false")
inspect(a != c, content="true")
}fn equal(self : UInt64, other : UInt64) -> Booltest {
let a = 42UL
let b = 42UL
let c = 24UL
inspect(a == b, content="true")
inspect(a == c, content="false")
}fn not_equal(self : UInt64, other : UInt64) -> Booltest {
let a = 42UL
let b = 42UL
let c = 24UL
inspect(a != b, content="false")
inspect(a != c, content="true")
}fn equal(self : Double, other : Double) -> Booltest {
let a = 3.14
let b = 3.14
let c = 2.718
inspect(a == b, content="true")
inspect(a == c, content="false")
let nan = 0.0 / 0.0 // NaN
inspect(nan == nan, content="false") // NaN != NaN
}fn not_equal(self : Double, other : Double) -> Booltest {
let a = 3.14
let b = 3.14
let c = 2.718
inspect(a != b, content="false")
inspect(a != c, content="true")
let nan = 0.0 / 0.0 // NaN
inspect(nan != nan, content="true") // NaN != NaN is true
}fn equal(self : String, other : String) -> Booltest {
let str1 = "hello"
let str2 = "hello"
let str3 = "world"
inspect(str1 == str2, content="true")
inspect(str1 == str3, content="false")
}impl Eq for FixedArray[T]test {
let arr1 : FixedArray[Int] = [1, 2, 3]
let arr2 : FixedArray[Int] = [1, 2, 3]
let arr3 : FixedArray[Int] = [1, 2, 4]
inspect(arr1 == arr2, content="true")
inspect(arr1 == arr3, content="false")
}impl Eq for ReadOnlyArray[T]fn equal(self : Bytes, other : Bytes) -> Booltest {
let bytes1 = b"\x01\x02\x03"
let bytes2 = b"\x01\x02\x03"
let bytes3 = b"\x01\x02\x04"
inspect(bytes1 == bytes2, content="true")
inspect(bytes1 == bytes3, content="false")
}fn[T0 : Eq, T1 : Eq, T2 : Eq, T3 : Eq, T4 : Eq, T5 : Eq, T6 : Eq, T7 : Eq, T8 : Eq, T9 : Eq, T10 : Eq, T11 : Eq, T12 : Eq, T13 : Eq, T14 : Eq] equal(self : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14), other : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14)) -> Boolfn[T0 : Eq, T1 : Eq, T2 : Eq, T3 : Eq, T4 : Eq, T5 : Eq, T6 : Eq, T7 : Eq, T8 : Eq, T9 : Eq, T10 : Eq, T11 : Eq, T12 : Eq, T13 : Eq, T14 : Eq, T15 : Eq] equal(self : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15), other : (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15)) -> Boolfn equal(self : BytesView, other : BytesView) -> Booltest {
let bytes = b"abcabc"
inspect(bytes[0:3] == bytes[3:6], content="true")
inspect(bytes[0:3] == bytes[2:5], content="false")
inspect(bytes[0:4] == bytes[3:6], content="false")
}impl Eq for StringViewfn equal(self : StringView, other : StringView) -> Booltest {
let hasher = Hasher(seed=0)
hasher.combine_byte(b'\xFF')
inspect(hasher.finalize(), content="1955036104")
}fn hash(self : Int) -> Inttest {
let hasher = Hasher(seed=0)
hasher.combine_int(42)
inspect(hasher.finalize(), content="1161967057")
}fn hash(self : UInt) -> Inttest {
let hasher = Hasher(seed=0)
hasher.combine_uint(42U)
inspect(hasher.finalize(), content="1161967057")
}fn hash(self : UInt64) -> Inttest {
let hasher = Hasher(seed=0)
hasher.combine_uint64(42UL)
inspect(hasher.finalize(), content="-1962516083")
}fn hash(self : String) -> Inttest {
let s1 = "hello"
let s2 = "hello"
let s3 = "world"
inspect(Hash::hash(s1) == Hash::hash(s2), content="true")
inspect(Hash::hash(s1) == Hash::hash(s3), content="false")
}test {
let hasher = Hasher(seed=0)
let some_value : Int? = Some(42)
let none_value : Int? = None
hasher.combine(some_value)
inspect(hasher.finalize(), content="2103260413")
let hasher2 = Hasher(seed=0)
hasher2.combine(none_value)
inspect(hasher2.finalize(), content="148298089")
}test {
let hasher = Hasher(seed=0)
let ok_result : Result[Int, String] = Ok(42)
let err_result : Result[Int, String] = Err("error")
hasher.combine(ok_result)
inspect(hasher.finalize(), content="-1948635851")
let hasher = Hasher(seed=0)
hasher.combine(err_result)
inspect(hasher.finalize(), content="1953766574")
}impl Hash for FixedArray[T]impl Hash for ReadOnlyArray[T]impl Hash for StringViewpub(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 = _
}pub(open) trait Mod {
fn mod(Self, Self) -> Self
}fn mod(self : Int, other : Int) -> Inttest {
inspect(7 % 3, content="1")
inspect(-7 % 3, content="-1")
inspect(7 % -3, content="1")
}fn mod(self : Int64, other : Int64) -> Int64test {
inspect(7L % 3L, content="1")
inspect(-7L % 3L, content="-1")
inspect(7L % -3L, content="1")
}fn mod(self : UInt, other : UInt) -> UInttest {
let a = 17U
let b = 5U
inspect(a % b, content="2") // 17 divided by 5 gives quotient 3 and remainder 2
inspect(7U % 4U, content="3")
}fn mod(self : UInt64, other : UInt64) -> UInt64test {
let a = 17UL
let b = 5UL
inspect(a % b, content="2") // 17 divided by 5 gives quotient 3 and remainder 2
inspect(7UL % 4UL, content="3")
}fn mod(self : Double, other : Double) -> Doubletest {
inspect(5.0.mod(3.0), content="2")
inspect((-5.0).mod(3.0), content="-2")
inspect(5.0.mod(@double.not_a_number), content="NaN")
inspect(@double.infinity.mod(3.0), content="NaN")
}pub(open) trait Mul {
fn mul(Self, Self) -> Self
}fn mul(self : Byte, that : Byte) -> Bytetest {
let a = b'\x02'
let b = b'\x03'
inspect(a * b, content="b'\\x06'") // 2 * 3 = 6
let c = b'\xFF'
inspect(c * c, content="b'\\x01'") // 255 * 255 = 65025, truncated to 1
}fn mul(self : Int, other : Int) -> Inttest {
inspect(42 * 2, content="84")
inspect(-10 * 3, content="-30")
let max = 2147483647 // Int.max_value
inspect(max * 2, content="-2") // Overflow wraps around
}fn mul(self : Int64, other : Int64) -> Int64test {
let a = 42L
let b = 100L
inspect(a * b, content="4200")
let c = -42L
inspect(c * b, content="-4200")
}fn mul(self : UInt, other : UInt) -> UInttest {
let a = 3U
let b = 4U
inspect(a * b, content="12")
let max = 4294967295U
inspect(max * 2U, content="4294967294") // Wraps around to max * 2 % 2^32
}fn mul(self : UInt64, other : UInt64) -> UInt64test {
let a = 2UL
let b = 3UL
inspect(a * b, content="6")
// Demonstrate wrapping behavior
let max = 18446744073709551615UL
inspect(max * 2UL, content="18446744073709551614") // Wraps around to max - 1
}fn mul(self : Double, other : Double) -> Doubletest {
inspect(2.5 * 2.0, content="5")
inspect(-2.0 * 3.0, content="-6")
let nan = 0.0 / 0.0 // NaN
inspect(nan * 1.0, content="NaN")
}pub(open) trait Neg {
fn neg(Self) -> Self
}fn neg(self : Int) -> Inttest {
inspect(-42, content="-42")
inspect(42, content="42")
inspect(2147483647, content="2147483647") // negating near min value
}fn neg(self : Int64) -> Int64test {
inspect(-42L, content="-42")
inspect(42L, content="42")
inspect(-9223372036854775808L, content="-9223372036854775808") // negating min value
}fn neg(self : Double) -> Doubletest {
inspect(-42.0, content="-42")
inspect(42.0, content="42")
inspect(-(0.0 / 0.0), content="NaN") // Negating NaN returns NaN
}pub(open) trait Shl {
fn shl(Self, Int) -> Self
}fn shl(self : Byte, count : Int) -> Bytefn shl(self : Int, other : Int) -> Inttest {
let x = 1
inspect(x << 3, content="8") // Binary: 1 -> 1000
let y = -4
inspect(y << 2, content="-16") // Binary: 100 -> 10000
}fn shl(self : Int64, other : Int) -> Int64test {
let n = 1L
inspect(n << 3, content="8") // 1 shifted left by 3 positions becomes 8
let m = -4L
inspect(m << 2, content="-16") // -4 shifted left by 2 positions becomes -16
}fn shl(self : UInt, shift : Int) -> UInttest {
let x = 1U
inspect(x << 3, content="8") // Binary: 1 -> 1000
let y = 0xFFFFFFFFU
inspect(y << 16, content="4294901760") // All bits after position 16 are discarded
}fn shl(self : UInt64, shift : Int) -> UInt64test {
let x = 1UL
inspect(x << 3, content="8") // 1 shifted left by 3 positions becomes 8
inspect(x << 63, content="9223372036854775808") // 1 shifted left by 63 positions
}#must_implement_one(output, to_string)
pub(open) trait Show {
fn output(Self, &Logger) -> Unit = _
fn to_string(Self) -> String = _
}fn to_string(self : Char) -> Stringfn to_string(self : String) -> Stringtest {
let str = "Hello \n"
inspect(str.to_string(), content="Hello \n")
inspect(str.escape(quote=true), content="\"Hello \\n\"")
}impl Show for FixedArray[X]impl Show for ReadOnlyArray[T]impl Show for StringViewpub(open) trait Shr {
fn shr(Self, Int) -> Self
}fn shr(self : Byte, count : Int) -> Bytefn shr(self : Int, other : Int) -> Inttest {
let n = -16
inspect(n >> 2, content="-4") // Sign bit is preserved during shift
let p = 16
inspect(p >> 2, content="4") // Regular right shift for positive numbers
}fn shr(self : Int64, other : Int) -> Int64test {
let n = -1024L
inspect(n >> 3, content="-128") // Preserves sign bit
let p = 1024L
inspect(p >> 3, content="128") // Regular right shift for positive numbers
}fn shr(self : UInt, shift : Int) -> UInttest {
let x = 0xFF000000U
inspect(x >> 8, content="16711680") // 0x00FF0000
inspect(x >> 24, content="255") // 0x000000FF
let x = 0xFF000000U
inspect(x >> 32, content="4278190080") // Same as x >> 0 due to masking
}fn shr(self : UInt64, shift : Int) -> UInt64test {
let x = 0xFF00FF00FF00FF00UL
inspect(x >> 8, content="71777214294589695") // Shifted right by 8 bits
inspect(x >> 64, content="18374966859414961920") // Equivalent to x >> 0 due to masking
}pub(open) trait Sub {
fn sub(Self, Self) -> Self
}fn sub(self : Byte, that : Byte) -> Bytefn sub(self : Int, other : Int) -> Inttest {
let a = 42
let b = 10
inspect(a - b, content="32")
let max = 2147483647 // Int maximum value
inspect(max - -1, content="-2147483648") // Overflow case
}fn sub(self : Int64, other : Int64) -> Int64test {
let a = 9223372036854775807L // Int64 maximum value
let b = 1L
inspect(a - b, content="9223372036854775806")
let c = -9223372036854775808L // Int64 minimum value
let d = 1L
inspect(c - d, content="9223372036854775807")
}fn sub(self : UInt, other : UInt) -> UInttest {
let a = 5U
let b = 3U
inspect(a - b, content="2")
let c = 3U
let d = 5U
inspect(c - d, content="4294967294") // wraps around to 2^32 - 2
}fn sub(self : UInt64, other : UInt64) -> UInt64test {
let a = 5UL
let b = 3UL
inspect(a - b, content="2")
let c = 3UL
let d = 5UL
inspect(c - d, content="18446744073709551614") // wraps around to 2^64 - 2
}fn sub(self : Double, other : Double) -> Doubletest {
let a = 5.0
let b = 3.0
inspect(a - b, content="2")
inspect(0.0 / 0.0 - 1.0, content="NaN") // NaN - anything = NaN
}impl ToJson for FixedArray[X]impl ToJson for ReadOnlyArray[T]impl ToJson for StringViewpub trait ToStringView {
fn to_string_view(Self) -> StringView
}impl ToStringView for Stringfn to_string_view(self : String) -> StringViewimpl ToStringView for StringViewfn to_string_view(self : StringView) -> StringView#deprecated("This type is deprecated.")
pub(all) suberror BenchError {
BenchError(String)
}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"])
}pub(all) suberror InspectError {
InspectError(String)
}test {
let x : Int = 42
inspect(x, content="42") // Raises InspectError with detailed failure message
}pub(all) suberror SnapshotError {
SnapshotError(String)
}test {
let err : SnapshotError = SnapshotError("failed to load snapshot")
match err {
SnapshotError(msg) => @test.assert_eq(msg, "failed to load snapshot")
}
}type Array[T]test {
let a = [1, 2, 3]
let b = [4, 5]
debug_inspect(a + b, content="[1, 2, 3, 4, 5]")
}test {
let arr1 = [1, 2, 3]
let arr2 = [1, 2, 4]
let arr3 = [1, 2]
inspect(arr1.compare(arr2), content="-1") // arr1 < arr2
inspect(arr2.compare(arr1), content="1") // arr2 > arr1
inspect(arr1.compare(arr3), content="1") // arr1 > arr3 (longer)
inspect(arr1.compare(arr1), content="0") // arr1 = arr1
}test {
let arr1 = [1, 2, 3]
let arr2 = [1, 2, 3]
let arr3 = [1, 2, 4]
inspect(arr1 == arr2, content="true")
inspect(arr1 == arr3, content="false")
}test {
let arr = [1, 2, 3, 4, 5]
assert_true(arr.all(x => x < 6))
assert_false(arr.all(x => x < 5))
}test {
let arr = [1, 2, 3, 4, 5]
assert_true(arr.any(x => x < 6))
assert_false(arr.any(x => x < 1))
}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]")
}test {
let arr : ReadOnlyArray[Int] = [1, 2, 3]
inspect(arr[1], content="2")
}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
}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)")
}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]")
}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="[]")
}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="[]")
}test {
let v = [3, 4, 5]
v.clear()
@test.assert_eq(v.length(), 0)
}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")
}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")
}test {
let arr = [1, 2, 1, 3, 1]
inspect(arr.count(1), content="3")
inspect(arr.count(4), content="0")
}test {
let arr = [1, 2, 3, 4, 5]
inspect(arr.count_if(x => x % 2 == 0), content="2")
}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="[]")
}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])
}test {
let arr = [1, 2, 3]
let mut sum = 0
arr.each(x => sum x)
inspect(sum, content="6")
}test {
let v = [3, 4, 5]
let mut sum = 0
v.eachi((i, x) => sum x + i)
inspect(sum, content="15")
}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")
}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]")
}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"]
),
)
}test {
let arr = [1, 2, 3, 4, 5]
let evens = arr.filter(x => x % 2 == 0)
debug_inspect(evens, content="[2, 4]")
}test {
let v = [[3, 4], [5, 6]].flatten()
@test.assert_eq(v, [3, 4, 5, 6])
}test {
let sum = [1, 2, 3, 4, 5].fold(init=0, (sum, elem) => sum + elem)
@test.assert_eq(sum, 15)
}test {
let sum = [1, 2, 3, 4, 5].foldi(init=0, (index, sum, _elem) => sum + index)
@test.assert_eq(sum, 10)
}test {
let fixed = FixedArray::make(3, 42)
let dynamic = Array::from_fixed_array(fixed)
debug_inspect(dynamic, content="[42, 42, 42]")
}test {
let iter = Iter::singleton(42)
let arr = Array::from_iter(iter)
debug_inspect(arr, content="[42]")
}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")
}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")
}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]")
}test {
let empty : Array[Int] = []
inspect(empty.is_empty(), content="true")
let non_empty = [1, 2, 3]
inspect(non_empty.is_empty(), content="false")
}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")
}test {
let arr = [1, 2, 3]
let mut sum = 0
arr.iter().each(x => sum x)
inspect(sum, content="6")
}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
}test {
let s = "hello world"
inspect(s.split(" ").to_array().join(":"), content="hello:world")
}test {
let arr = [1, 2, 3]
debug_inspect(arr.last(), content="Some(3)")
let empty : Array[Int] = []
debug_inspect(empty.last(), content="None")
}test {
let arr : ReadOnlyArray[Int] = [1, 2, 3]
inspect(arr.length(), content="3")
let empty : ReadOnlyArray[Int] = []
inspect(empty.length(), content="0")
}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")
}test {
let arr = Array::make(3, 42)
debug_inspect(arr, content="[42, 42, 42]")
}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)
}test {
let arr = Array::makei(3, i => i * 2)
debug_inspect(arr, content="[0, 2, 4]")
}test {
let v = [3, 4, 5]
let v2 = v.map(x => x + 1)
@test.assert_eq(v2, [4, 5, 6])
}test {
let v = [3, 4, 5]
v.map_in_place(x => x + 1)
@test.assert_eq(v, [4, 5, 6])
}test {
let v = [3, 4, 5]
let v2 = v.mapi((i, x) => x + i)
@test.assert_eq(v2, [3, 5, 7])
}test {
let v = [3, 4, 5]
v.mapi_in_place((i, x) => x + i)
@test.assert_eq(v, [3, 5, 7])
}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
}test {
let arr : Array[Int] = Array::new(capacity=10)
inspect(arr.length(), content="0")
inspect(arr.capacity(), content="10")
let arr : Array[Int] = Array::new()
inspect(arr.length(), content="0")
}test {
let v = [1, 2, 3]
@test.assert_eq(v.pop(), Some(3))
@test.assert_eq(v, [1, 2])
}test {
let v = []
v.push(3)
}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])
}test {
let v = [3, 4, 5]
@test.assert_eq(v.remove(1), 4)
@test.assert_eq(v, [3, 5])
}test {
let v = [3, 4].repeat(2)
@test.assert_eq(v, [3, 4, 3, 4])
}test {
let v = [1]
v.reserve_capacity(10)
@test.assert_eq(v.capacity(), 10)
}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]")
}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]")
}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]")
}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
}test {
let v = [3, 4, 5]
let mut sum = 0
v.rev_each(x => sum = sum - x)
@json.json_inspect(sum, content=-12)
}test {
let v = [3, 4, 5]
let mut sum = 0
v.rev_eachi((i, x) => sum x + i)
@test.assert_eq(sum, 15)
}test {
let sum = [1, 2, 3, 4, 5].rev_fold(init=0, (sum, elem) => sum + elem)
@test.assert_eq(sum, 15)
}test {
let sum = [1, 2, 3, 4, 5].rev_foldi(init=0, (index, sum, _elem) => sum + index)
@test.assert_eq(sum, 10)
}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="[]")
}test {
let arr = [1, 2, 3]
let result = []
arr.rev_iter().each(x => result.push(x))
debug_inspect(result, content="[3, 2, 1]")
}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
}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")
}
}test {
let arr = [1, 2, 3]
arr[1] = 42
debug_inspect(arr, content="[1, 42, 3]")
}test {
let v = Array::new(capacity=10)
v.push(1)
v.push(2)
v.push(3)
v.shrink_to_fit()
@test.assert_eq(v.capacity(), 3)
}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~)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~)
}test {
let arr = [5, 4, 3, 2, 1]
arr.sort()
@test.assert_eq(arr, [1, 2, 3, 4, 5])
}test {
let arr = [5, 3, 2, 4, 1]
arr.sort_by((a, b) => a - b)
@test.assert_eq(arr, [1, 2, 3, 4, 5])
}test {
let arr = [5, 3, 2, 4, 1]
arr.sort_by_key(x => -x)
@test.assert_eq(arr, [5, 4, 3, 2, 1])
}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]]")
}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")
}test {
let v = [1, 2, 3, 4, 5]
let v2 = v.strip_prefix([1, 2])
debug_inspect(
v2,
content=(
#|Some(<ArrayView: [3, 4, 5]>)
),
)
}test {
let v = [3, 4, 5]
let v2 = v.strip_suffix([5])
debug_inspect(
v2,
content=(
#|Some(<ArrayView: [3, 4]>)
),
)
}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: []>]
),
)
}test {
let arr = [1, 2, 3]
arr.swap(0, 2)
debug_inspect(arr, content="[3, 2, 1]")
}test {
let arr = [1, 2, 3, 4, 5]
arr.truncate(3)
debug_inspect(arr, content="[1, 2, 3]")
}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]")
}test {
let arr : Array[Int] = [1, 2, 3]
inspect(arr.unsafe_get(1), content="2")
}test {
let arr = [1, 2, 3]
arr.unsafe_set(1, 99)
debug_inspect(arr, content="[1, 99, 3]")
}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\"]")
}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
}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="[]")
}test {
let arr1 = [1, 2, 3]
let arr2 = ['a', 'b', 'c']
debug_inspect(arr1.zip(arr2), content="[(1, 'a'), (2, 'b'), (3, 'c')]")
}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')]",
)
}type ArrayView[T]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)
}test {
let a = [1, 2, 3, 4, 5][1:4]
let b = [10, 20, 30][:2]
debug_inspect(
a + b,
content=(
#|<ArrayView: [2, 3, 4, 10, 20]>
),
)
}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))
}test {
let v = [1, 2, 3, 4, 5][:]
assert_true(v.any(ele => ele < 6))
assert_false(v.any(ele => ele < 1))
}test {
let arr = [1, 2, 3, 4, 5]
let view = arr[2:4]
inspect(view[0], content="3")
inspect(view[1], content="4")
}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)")
}test {
let view = [1, 3, 5, 7, 9][:]
let result = view.binary_search_by(x => x.compare(5))
debug_inspect(result, content="Ok(2)")
}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]")
}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]>,
#|]
),
)
}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]>]
),
)
}test {
let arr = [1, 2, 3, 4, 5][:]
inspect(arr.contains(3), content="true")
inspect(arr.contains(6), content="false")
}test {
let view = [1, 2, 1, 3, 1][:]
inspect(view.count(1), content="3")
inspect(view.count(4), content="0")
}test {
let view = [1, 2, 3, 4, 5][:]
inspect(view.count_if(x => x % 2 == 0), content="2")
}test {
let arr = [1, 2, 3][:]
let mut sum = 0
arr.each(x => sum x)
inspect(sum, content="6")
}test {
let v = [3, 4, 5][:]
let mut sum = 0
v.eachi((i, x) => sum x + i)
inspect(sum, content="15")
}test {
let view = [1, 2, 3, 4, 5][:]
inspect(view.ends_with([4, 5]), content="true")
inspect(view.ends_with([3, 4]), content="false")
}test {
let arr = [1, 2, 3, 4, 5, 6]
let v = arr[2:].filter(x => x % 2 == 0)
@test.assert_eq(v, [4, 6])
}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]",
)
}test {
let sum = [1, 2, 3, 4, 5][:].fold(init=0, (sum, elem) => sum + elem)
inspect(sum, content="15")
}test {
let sum = [1, 2, 3, 4, 5][:].foldi(init=0, (index, sum, _elem) => sum + index)
inspect(sum, content="10")
}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")
}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")
}test {
let view = [1, 2, 3][:]
inspect(view.is_empty(), content="false")
let empty = [1, 2][0:0]
inspect(empty.is_empty(), content="true")
}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")
}test {
let arr = [1, 2, 3]
let view = arr[1:]
let mut sum = 0
view.iter().each(x => sum x)
inspect(sum, content="5")
}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")
}test {
let a : Array[String] = ["1", "2", "3"]
let array_view = a[:]
inspect(array_view.join(","), content="1,2,3")
}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")
}test {
let arr = [1, 2, 3, 4, 5]
let view = arr[2:4]
inspect(view.length(), content="2")
}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")
}test {
let v = [3, 4, 5]
let v2 = v[1:].map(x => x + 1)
@test.assert_eq(v2, [5, 6])
}test {
let v = [3, 4, 5]
let v2 = v[1:].mapi((i, x) => x + i)
@test.assert_eq(v2, [4, 6])
}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]>
),
)
}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]")
}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)]")
}test {
let sum = [1, 2, 3, 4, 5][:].rev_fold(init=0, (sum, elem) => sum + elem)
inspect(sum, content="15")
}test {
let sum = [1, 2, 3, 4, 5][:].rev_foldi(init=0, (index, sum, _elem) => {
sum + index
})
inspect(sum, content="10")
}test {
let values = [1, 2, 3][:].rev_iter().collect()
debug_inspect(values, content="[3, 2, 1]")
}test {
let view = [1, 2, 3, 2, 4][:]
debug_inspect(view.search(2), content="Some(1)")
debug_inspect(view.search(5), content="None")
}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")
}test {
let arr = [10, 20, 30]
let v = arr[1:]
inspect(v.start_offset(), content="1")
}test {
let view = [1, 2, 3, 4, 5][:]
inspect(view.starts_with([1, 2]), content="true")
inspect(view.starts_with([2, 3]), content="false")
}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")
}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")
}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: []>]
),
)
}test {
let view = [1, 2, 3, 4, 5, 6][2:4]
let arr = view.to_owned()
@test.assert_eq(arr, [3, 4])
}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")
}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]>,
#|]
),
)
}type Hashertest {
let hasher = Hasher(seed=0)
hasher.combine_int(42)
hasher.combine_string("hello")
inspect(hasher.finalize(), content="860601284")
}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
}test {
let hasher = Hasher(seed=0)
hasher.combine(42)
hasher.combine("hello")
inspect(hasher.finalize(), content="860601284")
}test {
let hasher = Hasher(seed=0)
hasher.combine_bool(true)
inspect(hasher.finalize(), content="-205818221")
}test {
let hasher = Hasher(seed=0)
hasher.combine_byte(b'\xFF')
inspect(hasher.finalize(), content="1955036104")
}test {
let hasher = Hasher(seed=0)
hasher.combine_bytes(b"\xFF\x00\xFF\x00")
inspect(hasher.finalize(), content="-686861102")
}test {
let hasher = Hasher(seed=0)
hasher.combine_char('A')
inspect(hasher.finalize(), content="-1625495534")
}test {
let hasher = Hasher(seed=0)
hasher.combine_double(3.14)
inspect(hasher.finalize(), content="-428265677")
}test {
let hasher = Hasher(seed=0)
hasher.combine(3.14F)
inspect(hasher.finalize(), content="635116317") // Hash of the bits of 3.14
}test {
let hasher = Hasher(seed=0)
hasher.combine_int(42)
inspect(hasher.finalize(), content="1161967057")
}test {
let hasher = Hasher(seed=0)
hasher.combine_int64(42L)
inspect(hasher.finalize(), content="-1962516083")
}test {
let hasher = Hasher(seed=0)
hasher.combine_string("hello")
inspect(hasher.finalize(), content="-655549713")
}test {
let hasher = Hasher(seed=0)
hasher.combine_uint(42U)
inspect(hasher.finalize(), content="1161967057")
}test {
let hasher = Hasher(seed=0)
hasher.combine_uint64(42UL)
inspect(hasher.finalize(), content="-1962516083")
}test {
let hasher = Hasher(seed=0)
hasher.combine_unit()
inspect(hasher.finalize(), content="148298089")
}test {
let hasher = Hasher(seed=0)
hasher.combine_byte(b'\xFF')
inspect(hasher.finalize(), content="1955036104")
}#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]test {
let iter = [1, 2, 3, 4, 5].iter()
inspect(iter.contains(3), content="true")
inspect(iter.contains(6), content="false")
let iter = Iter::empty()
inspect(iter.contains(1), content="false")
}test {
let arr = []
[1, 2, 3].iter().intersperse(0).each(i => arr.push(i))
@test.assert_eq(arr, [1, 0, 2, 0, 3])
}test {
let numbers = (1).until(5)
let letters = ["a", "b", "c"].iter()
debug_inspect(
numbers.zip(letters).collect(),
content="[(1, \"a\"), (2, \"b\"), (3, \"c\")]",
)
}#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)])test {
let value : Json = Json::array([Json::number(1.0), Json::null()])
inspect(value.stringify(), content="[1,null]")
}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)])")
}test {
let values : Array[Json] = [1.0, "hello"]
@debug.debug_inspect(
Json::array(values),
content="Array([Number(1), String(\"hello\")])",
)
}test {
@debug.debug_inspect(Json::boolean(true), content="True")
@debug.debug_inspect(Json::boolean(false), content="False")
}test {
@debug.debug_inspect(Json::number(3.14), content="Number(3.14)")
inspect(
Json::number(@double.infinity, repr="1e9999999999999999999999999999999").stringify(),
content="1e9999999999999999999999999999999",
)
}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) })",
)
}test {
@debug.debug_inspect(Json::string("hello"), content="String(\"hello\")")
}type Map[K, V]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"))
}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")
}test {
let map = { "key": 42 }
debug_inspect(map.get("key"), content="Some(42)")
debug_inspect(map.get("nonexistent"), content="None")
}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)")
}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)")
}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")
}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 })
}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 })
}test {
let map = { "a": 1, "b": 2 }
map.remove("a")
debug_inspect(map.get("a"), content="None")
inspect(map.length(), content="1")
}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)")
}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)")
}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 }
),
)
}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)")
}type MutArrayView[T]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]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")
}test {
let view = [1, 2, 3].mut_view(start=1, end=1)
inspect(view.is_empty(), content="true")
}#alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
fn[X] MutArrayView::iter(self : MutArrayView[X]) -> Iter[X]#alias(iterator2, deprecated="`iterator2` is deprecated, use `iter2` instead")
fn[X] MutArrayView::iter2(self : MutArrayView[X]) -> Iter2[Int, X]test {
let arr = [1, 2, 3, 4, 5]
let view = arr.mut_view(start=2, end=4)
inspect(view.length(), content="2")
}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")
}#alias(rev_iterator, deprecated="`rev_iterator` is deprecated, use `rev_iter` instead")
fn[X] MutArrayView::rev_iter(self : MutArrayView[X]) -> Iter[X]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")
}test {
let arr = [5, 4, 3, 2, 1]
arr.mut_view().sort()
@test.assert_eq(arr, [1, 2, 3, 4, 5])
}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])
}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])
}test {
let arr : FixedArray[Int] = [5, 4, 3, 2, 1]
arr.mut_view().stable_sort()
@test.assert_eq(arr, [1, 2, 3, 4, 5])
}#alias(to_array, deprecated="`to_array` is deprecated, use `to_owned` instead")
fn[T] MutArrayView::to_owned(self : MutArrayView[T]) -> Array[T]#internal(unsafe, "Panic if index is out of bounds")
fn[T] MutArrayView::unsafe_get(self : MutArrayView[T], index : Int) -> Ttest {
let arr = [1, 2, 3, 4, 5]
let view = arr.mut_view(start=1, end=4)
inspect(view.unsafe_get(1), content="3")
}#internal(unsafe, "Panic if index is out of bounds")
fn[T] MutArrayView::unsafe_set(self : MutArrayView[T], index : Int, value : T) -> Unittest {
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")
}#alias(sub, deprecated="Use _[_:_] instead")
#alias("_[_:_]")
fn[T] MutArrayView::view(self : MutArrayView[T], start? : Int, end? : Int) -> ArrayView[T]pub(all) type SourceLoctype StringBuilderimpl Logger for StringBuildertest {
let sb = StringBuilder()
sb.write_view("Hello, world!"[:5])
@test.assert_eq(sb.to_string(), "Hello")
}impl Show for StringBuildertest {
let sb = StringBuilder()
let chars = "Hello🤣".iter()
sb.write_iter(chars)
@test.assert_eq(sb.to_string(), "Hello🤣")
}#alias(write_string_interpolation)
#alias(write)
fn[T : Show] StringBuilder::write_object(self : StringBuilder, obj : T) -> Unittest {
let sb = StringBuilder()
let str = "Hello, world!"
let view = str[7:12] // "world"
sb.write_stringview(view)
@test.assert_eq(sb.to_string(), "world")
}fn StringBuilder::write_substring(self : StringBuilder, value : String, start : Int, len : Int) -> Unittype UninitializedArray[T]fn[T] UninitializedArray::make_and_blit(src : UninitializedArray[T], allocate_len~ : Int, len~ : Int, src_offset? : Int, dst_offset? : Int) -> UninitializedArray[T]#alias("_[_]=_")
fn[T] UninitializedArray::set(self : UninitializedArray[T], index : Int, value : T) -> Unit#alias("_[_:_]")
fn[T] UninitializedArray::sub(self : UninitializedArray[T], start? : Int, end? : Int) -> ArrayView[T]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.
#deprecated("Use `compare` instead")
fn Bool::op_compare(self : Bool, other : Bool) -> Inttest {
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")
}fn Bool::to_int(self : Bool) -> Inttest {
inspect(true.to_int(), content="1")
inspect(false.to_int(), content="0")
}fn Bool::to_int16(self : Bool) -> Int16test {
inspect(true.to_int16(), content="1")
inspect(false.to_int16(), content="0")
}fn Bool::to_int64(self : Bool) -> Int64test {
inspect(true.to_int64(), content="1")
inspect(false.to_int64(), content="0")
}fn Bool::to_uint(self : Bool) -> UInttest {
inspect(true.to_uint(), content="1")
inspect(false.to_uint(), content="0")
}fn Bool::to_uint16(self : Bool) -> UInt16test {
inspect(true.to_uint16(), content="1")
inspect(false.to_uint16(), content="0")
}fn Bool::to_uint64(self : Bool) -> UInt64test {
inspect(true.to_uint64(), content="1")
inspect(false.to_uint64(), content="0")
}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.
fn Byte::Byte(self : Byte) -> Bytetest {
inspect(Byte(3), content="b'\\x03'")
}fn Byte::lnot(self : Byte) -> Byte#deprecated("Use infix operator `<<` instead")
fn Byte::lsl(self : Byte, count : Int) -> Byte#deprecated("Use infix operator `>>` instead")
fn Byte::lsr(self : Byte, count : Int) -> Bytefn Byte::popcnt(self : Byte) -> Inttest {
let b = b'\x0F'
inspect(b.popcnt(), content="4")
}fn Byte::to_char(self : Byte) -> Char#deprecated("Use `Float::from_byte` instead")
fn Byte::to_float(self : Byte) -> Floatfn Byte::to_hex(b : Byte) -> Stringtest {
inspect(Byte::to_hex(b'\x0f'), content="0f")
}fn Byte::to_int(self : Byte) -> Inttest {
let b = b'\xFF' // byte with value 255
inspect(b.to_int(), content="255")
let zero = b'\x00'
inspect(zero.to_int(), content="0")
}#deprecated("Use `Int16::from_byte` instead")
fn Byte::to_int16(self : Byte) -> Int16fn Byte::to_int64(self : Byte) -> Int64test {
let b = b'\xFF'
inspect(b.to_int64(), content="255")
}fn Byte::to_string(self : Byte) -> Stringfn Byte::to_uint(self : Byte) -> UIntfn Byte::to_uint16(self : Byte) -> UInt16test {
let b = b'\xFF' // byte with value 255
inspect(b.to_uint16(), content="255")
let zero = b'\x00'
inspect(zero.to_uint16(), content="0")
}fn Byte::to_uint64(self : Byte) -> UInt64test {
let b = b'\xFF'
inspect(b.to_uint64(), content="255")
}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.
#alias("_[_]")
fn Bytes::at(self : Bytes, idx : Int) -> Bytetest {
let bytes = b"\x01\x02\x03"
inspect(bytes[1], content="b'\\x02'")
}fn Bytes::chop_prefix(self : Bytes, prefix : BytesView) -> BytesView?fn Bytes::chop_suffix(self : Bytes, suffix : BytesView) -> BytesView?#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) -> Bytestest {
let a = b"abc"
let b = Bytes::makei(a.length(), i => a[i])
inspect(a == b, content="true")
}fn Bytes::find(target : Bytes, pattern : BytesView) -> Int?#alias(of, deprecated="`of` is deprecated, use `from_array` instead")
fn Bytes::from_array(arr : ArrayView[Byte]) -> Bytestest {
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"
),
)
}#deprecated("Use Bytes::from_array instead")
fn Bytes::from_fixedarray(arr : FixedArray[Byte], len? : Int) -> Bytestest {
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"
),
)
}#alias(from_iterator, deprecated="`from_iterator` is deprecated, use `from_iter` instead")
fn Bytes::from_iter(iter : Iter[Byte]) -> Bytestest {
let iter = Iter::singleton(b'h')
let bytes = Bytes::from_iter(iter)
inspect(
bytes,
content=(
#|b"h"
),
)
}fn Bytes::get(self : Bytes, index : Int) -> Byte?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")
}fn Bytes::get_view(self : Bytes, start? : Int, end? : Int) -> BytesView?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")
}fn Bytes::has_prefix(self : Bytes, prefix : BytesView) -> Boolfn Bytes::has_suffix(self : Bytes, suffix : BytesView) -> Boolfn Bytes::is_empty(self : Bytes) -> Booltest {
inspect(b"".is_empty(), content="true")
inspect(b"\x00".is_empty(), content="false")
}#alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
fn Bytes::iter(self : Bytes) -> Iter[Byte]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
}#alias(iterator2, deprecated="`iterator2` is deprecated, use `iter2` instead")
fn Bytes::iter2(self : Bytes) -> Iter2[Int, Byte]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]")
}fn Bytes::length(self : Bytes) -> Inttest {
let bytes = b"\x01\x02\x03"
inspect(bytes.length(), content="3")
let empty = b""
inspect(empty.length(), content="0")
}fn Bytes::lexical_compare(self : Bytes, other : Bytes) -> Inttest {
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")
}fn Bytes::make(len : Int, init : Byte) -> Bytestest {
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\"\"")
}fn Bytes::makei(length : Int, value : (Int) -> Byte raise?) -> Bytes raise?test {
let bytes = Bytes::makei(3, i => (i + 65).to_byte())
@test.assert_eq(bytes, b"ABC")
}fn Bytes::new(len : Int) -> Bytestest {
let bytes = Bytes::new(3)
inspect(bytes, content="b\"\\x00\\x00\\x00\"")
let bytes = Bytes::new(0)
inspect(bytes, content="b\"\"")
}#deprecated("check `@encoding/utf8.encode`")
fn Bytes::of_string(str : String) -> Bytestest {
let bytes = Bytes::from_array([b'A'])
inspect(bytes.length(), content="1")
}fn Bytes::repeat(self : Bytes, count : Int) -> Bytestest {
inspect(
b"ab".repeat(3),
content=(
#|b"ababab"
),
)
inspect(
b"xyz".repeat(0),
content=(
#|b""
),
)
}fn Bytes::rev_find(target : Bytes, pattern : BytesView) -> Int?test {
let bytes = b"hello"
let arr = bytes.to_array()
debug_inspect(
arr,
content=(
#|[0x68, 0x65, 0x6c, 0x6c, 0x6f]
),
)
}fn Bytes::to_fixedarray(self : Bytes, len? : Int) -> FixedArray[Byte]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]>
),
)
}fn Bytes::to_unchecked_string(self : Bytes, offset? : Int, length? : Int) -> String#alias(sub, deprecated="Use _[_:_ instead")
#alias("_[_:_]")
fn Bytes::view(self : Bytes, start? : Int, end? : Int) -> BytesViewtest {
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')
}#alias("_[_]")
fn BytesView::at(self : BytesView, index : Int) -> Bytetest {
let bytes = b"\x01\x02\x03\x04\x05"
let view = bytes[1:4] // view contains [0x02, 0x03, 0x04]
inspect(view[1], content="b'\\x03'")
}fn BytesView::chop_prefix(self : BytesView, prefix : BytesView) -> BytesView?fn BytesView::chop_suffix(self : BytesView, suffix : BytesView) -> BytesView?fn BytesView::data(self : BytesView) -> Bytesfn BytesView::equal_to_bytes(self : BytesView, other : Bytes) -> Booltest {
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")
}fn BytesView::find(target : BytesView, pattern : BytesView) -> Int?fn BytesView::get(self : BytesView, index : Int) -> Byte?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")
}fn BytesView::get_view(self : BytesView, start? : Int, end? : Int) -> BytesView?fn BytesView::has_prefix(self : BytesView, prefix : BytesView) -> Boolfn BytesView::has_suffix(self : BytesView, suffix : BytesView) -> Boolfn BytesView::is_empty(self : BytesView) -> Booltest {
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")
}#alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
fn BytesView::iter(self : BytesView) -> Iter[Byte]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")
}#alias(iterator2, deprecated="`iterator2` is deprecated, use `iter2` instead")
fn BytesView::iter2(self : BytesView) -> Iter2[Int, Byte]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]")
}fn BytesView::length(self : BytesView) -> Inttest {
let bytes = b"\x00\x01\x02\x03\x04"
let view = bytes[2:4]
inspect(view.length(), content="2")
}fn BytesView::lexical_compare(self : BytesView, other : BytesView) -> Inttest {
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")
}fn BytesView::rev_find(target : BytesView, pattern : BytesView) -> Int?fn BytesView::start_offset(self : BytesView) -> Inttest {
let arr = b"ab"[:].to_array()
inspect(arr.length(), content="2")
inspect(arr[0], content="b'\\x61'")
}fn BytesView::to_fixedarray(self : BytesView) -> FixedArray[Byte]test {
let arr = b"abcd"[1:3].to_fixedarray()
debug_inspect(
arr,
content=(
#|<FixedArray: [0x62, 0x63]>
),
)
}#alias(to_bytes, deprecated="Use `to_owned` to allocate an owned `Bytes` from a `BytesView`")
fn BytesView::to_owned(self : BytesView) -> Bytestest {
let b = b"hello"
inspect(b[1:4].to_owned().length(), content="3")
}#alias(sub, deprecated="Use _[_:_] instead")
#alias("_[_:_]")
fn BytesView::view(self : BytesView, start? : Int, end? : Int) -> BytesViewtest {
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 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.
fn Char::escape(self : Char, quote? : Bool) -> Stringtest {
inspect('a'.escape(), content="'a'")
inspect('a'.escape(quote=false), content="a")
inspect('\n'.escape(), content="'\\n'")
inspect('\n'.escape(quote=false), content="\\n")
}#deprecated("Use `Int::unsafe_to_char` instead, and use `Int::to_char` for safe conversion")
fn Char::from_int(val : Int) -> Charfn Char::is_ascii(self : Char) -> Boolfn Char::is_ascii_alphabetic(self : Char) -> Boolfn Char::is_ascii_control(self : Char) -> Boolfn Char::is_ascii_digit(self : Char) -> Boolfn Char::is_ascii_graphic(self : Char) -> Boolfn Char::is_ascii_hexdigit(self : Char) -> Boolfn Char::is_ascii_lowercase(self : Char) -> Boolfn Char::is_ascii_octdigit(self : Char) -> Boolfn Char::is_ascii_punctuation(self : Char) -> Boolfn Char::is_ascii_uppercase(self : Char) -> Boolfn Char::is_ascii_whitespace(self : Char) -> Boolfn Char::is_bmp(self : Char) -> Booltest {
inspect('A'.is_bmp(), content="true")
inspect('🌟'.is_bmp(), content="false")
}fn Char::is_control(self : Char) -> Boolfn Char::is_digit(self : Char, radix : UInt) -> Boolfn Char::is_numeric(self : Char) -> Boolfn Char::is_printable(self : Char) -> Boolfn Char::is_whitespace(self : Char) -> Boolfn Char::to_ascii_lowercase(self : Char) -> Charfn Char::to_ascii_uppercase(self : Char) -> Charfn Char::to_int(self : Char) -> Inttest {
inspect('A'.to_int(), content="65") // ASCII value of 'A'
inspect('あ'.to_int(), content="12354") // Unicode code point of 'あ'
}fn Char::to_uint(self : Char) -> UInttest {
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
}fn Char::utf16_len(self : Char) -> Inttest {
inspect('A'.utf16_len(), content="1")
inspect('🌟'.utf16_len(), content="2")
}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.
fn Double::Double(self : Double) -> Doubletest {
inspect(Double(3.2), content="3.2")
}fn Double::abs(self : Double) -> Doubletest {
inspect((-2.5).abs(), content="2.5")
inspect(3.14.abs(), content="3.14")
inspect(0.0.abs(), content="0")
}fn Double::ceil(self : Double) -> Doubletest {
inspect(3.7.ceil(), content="4")
inspect((-3.7).ceil(), content="-3")
inspect(42.0.ceil(), content="42")
}fn Double::clamp(self : Double, min~ : Double, max~ : Double) -> Doubletest {
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")
}fn Double::convert_uint(val : UInt) -> Doubletest {
let n = 42U
inspect(Double::convert_uint(n), content="42")
let max = 4294967295U // maximum value of UInt
inspect(Double::convert_uint(max), content="4294967295")
}fn Double::convert_uint64(val : UInt64) -> Double let n = 12345678901234567890UL
inspect(Double::convert_uint64(n), content="12345678901234567000")fn Double::floor(self : Double) -> Doubletest {
inspect(3.7.floor(), content="3")
inspect((-3.7).floor(), content="-4")
inspect(0.0.floor(), content="0")
}fn Double::from_int(i : Int) -> Doubletest {
inspect(Double::from_int(42), content="42")
inspect(Double::from_int(-1), content="-1")
}fn Double::is_close(self : Double, other : Double, relative_tolerance? : Double, absolute_tolerance? : Double) -> Booltest {
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")
}fn Double::is_inf(self : Double) -> Booltest {
inspect(@double.infinity.is_inf(), content="true")
inspect(@double.neg_infinity.is_inf(), content="true")
inspect(42.0.is_inf(), content="false")
}fn Double::is_nan(self : Double) -> Booltest {
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")
}fn Double::is_neg_inf(self : Double) -> Booltest {
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
}fn Double::is_pos_inf(self : Double) -> Booltest {
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
}fn Double::lerp(self : Double, target~ : Double, t~ : Double) -> Doubletest {
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")
}fn Double::max(self : Double, other : Double) -> Doublefn Double::min(self : Double, other : Double) -> Double#deprecated("Use `@math.pow` instead")
fn Double::pow(self : Double, other : Double) -> Doubletest {
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")
}#deprecated("Use `reinterpret_as_int64` instead")
fn Double::reinterpret_as_i64(self : Double) -> Int64test {
let d = 1.0
// 1.0 in IEEE 754 double format has the bit pattern 0x3FF0000000000000
inspect(d.reinterpret_as_int64(), content="4607182418800017408")
}fn Double::reinterpret_as_int64(self : Double) -> Int64test {
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
}#deprecated("Use `reinterpret_as_uint64` instead")
fn Double::reinterpret_as_u64(self : Double) -> UInt64test {
let zero = 0.0
let positive = 1.0
inspect(zero.reinterpret_as_uint64(), content="0")
inspect(positive.reinterpret_as_uint64(), content="4607182418800017408")
}fn Double::reinterpret_as_uint64(self : Double) -> UInt64test {
let d = 1.0
inspect(d.reinterpret_as_uint64(), content="4607182418800017408") // Binary: 0x3FF0000000000000
}fn Double::round(self : Double) -> Doubletest {
inspect(3.7.round(), content="4")
inspect(3.2.round(), content="3")
inspect(3.5.round(), content="4")
inspect((-3.5).round(), content="-3")
}fn Double::signum(self : Double) -> Doublefn Double::sqrt(self : Double) -> Doubletest {
inspect(4.0.sqrt(), content="2")
inspect(0.0.sqrt(), content="0")
inspect((-1.0).sqrt(), content="NaN")
}#deprecated("Use `Float::from_double` instead")
fn Double::to_float(self : Double) -> Floatfn Double::to_int(self : Double) -> Inttest {
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
}fn Double::to_int64(self : Double) -> Int64test {
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
}fn Double::to_string(self : Double) -> Stringtest {
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")
}fn Double::to_uint(self : Double) -> UInttest {
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
}fn Double::to_uint64(self : Double) -> UInt64test {
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
}fn Double::trunc(self : Double) -> Doubletest {
inspect(3.7.trunc(), content="3")
inspect((-3.7).trunc(), content="-3")
inspect(0.0.trunc(), content="0")
}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.
fn[T] FixedArray::add(self : FixedArray[T], other : FixedArray[T]) -> FixedArray[T]#alias(every)
fn[T] FixedArray::all(self : FixedArray[T], f : (T) -> Bool raise?) -> Bool raise?test {
let arr : FixedArray[Int] = [1, 2, 3, 4, 5]
assert_true(arr.all(ele => ele < 6))
assert_false(arr.all(ele => ele < 5))
}#alias(exists)
fn[T] FixedArray::any(self : FixedArray[T], f : (T) -> Bool raise?) -> Bool raise?test {
let arr : FixedArray[Int] = [1, 2, 3, 4, 5]
assert_true(arr.any(ele => ele < 6))
assert_true(arr.any(ele => ele < 5))
}#alias("_[_]")
fn[T] FixedArray::at(self : FixedArray[T], idx : Int) -> Ttest {
let arr = FixedArray::make(3, 42)
inspect(arr[1], content="42")
}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
}fn[T] FixedArray::binary_search_by(self : FixedArray[T], cmp : (T) -> Int raise?) -> Result[Int, Int] raise?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)")
}fn FixedArray::blit_from_bytes(self : FixedArray[Byte], bytes_offset : Int, src : Bytes, src_offset : Int, length : Int) -> Unitfn FixedArray::blit_from_bytesview(self : FixedArray[Byte], bytes_offset : Int, src : BytesView) -> Unittest {
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]>
),
)
}fn FixedArray::blit_from_string(self : FixedArray[Byte], bytes_offset : Int, str : String, str_offset : Int, length : Int) -> Unittest {
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]) // '😈'
}fn[A] FixedArray::blit_to(self : FixedArray[A], dst : FixedArray[A], len~ : Int, src_offset? : Int, dst_offset? : Int) -> Unittest {
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]>
),
)
}test {
let arr : FixedArray[Int] = [3, 4, 5]
assert_true(arr.contains(3))
}#alias(clone, deprecated="`clone` is deprecated, use `copy` instead")
fn[T] FixedArray::copy(self : FixedArray[T]) -> FixedArray[T]test {
let original = [1, 2, 3]
let copied = original.copy()
debug_inspect(copied, content="[1, 2, 3]")
inspect(physical_equal(original, copied), content="false")
}fn[T] FixedArray::each(self : FixedArray[T], f : (T) -> Unit raise?) -> Unit raise?test {
let arr = []
[1, 2, 3, 4, 5].each(x => arr.push(x))
@test.assert_eq(arr, [1, 2, 3, 4, 5])
}fn[T] FixedArray::eachi(self : FixedArray[T], f : (Int, T) -> Unit raise?) -> Unit raise?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)])
}test {
let v : FixedArray[Int] = [3, 4, 5]
assert_true(v.ends_with([5]))
}fn[T] FixedArray::fill(self : FixedArray[T], value : T, start? : Int, end? : Int) -> Unittest {
// 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"]>
),
)
}fn[A, B] FixedArray::fold(self : FixedArray[A], init~ : B, f : (B, A) -> B raise?) -> B raise?test {
let sum = [1, 2, 3, 4, 5].fold(init=0, (sum, elem) => sum + elem)
inspect(sum, content="15")
}fn[A, B] FixedArray::foldi(self : FixedArray[A], init~ : B, f : (Int, B, A) -> B raise?) -> B raise?test {
let sum = [1, 2, 3, 4, 5].foldi(init=0, (index, sum, _elem) => sum + index)
inspect(sum, content="10")
}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]>
),
)
}#alias(from_iterator, deprecated="`from_iterator` is deprecated, use `from_iter` instead")
fn[T] FixedArray::from_iter(iter : Iter[T]) -> FixedArray[T]test {
let arr = [1, 2, 3]
let fixed_arr = FixedArray::from_iter(arr.iter())
debug_inspect(
fixed_arr,
content=(
#|<FixedArray: [1, 2, 3]>
),
)
}fn[T] FixedArray::get(self : FixedArray[T], idx : Int) -> T?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")
}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")
}fn[T] FixedArray::is_empty(self : FixedArray[T]) -> Booltest {
let empty : FixedArray[Int] = []
inspect(empty.is_empty(), content="true")
let non_empty = [1, 2, 3]
inspect(non_empty.is_empty(), content="false")
}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")
}#alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
fn[X] FixedArray::iter(self : FixedArray[X]) -> Iter[X]test {
debug_inspect(
([1, 2, 3] : FixedArray[Int]).iter().collect(),
content="[1, 2, 3]",
)
}#alias(iterator2, deprecated="`iterator2` is deprecated, use `iter2` instead")
fn[X] FixedArray::iter2(self : FixedArray[X]) -> Iter2[Int, X]test {
debug_inspect(
([10, 20] : FixedArray[Int]).iter2().to_array(),
content="[(0, 10), (1, 20)]",
)
}test {
let fixed_array : FixedArray[String] = ["1", "2", "3"]
inspect(fixed_array.join(","), content="1,2,3")
}fn[A] FixedArray::last(self : FixedArray[A]) -> A?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")
}fn[T] FixedArray::length(self : FixedArray[T]) -> Inttest {
let arr = FixedArray::make(3, 42)
inspect(arr.length(), content="3")
}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")
}fn[T] FixedArray::make(len : Int, init : T) -> FixedArray[T]test {
let arr = FixedArray::make(3, 42)
inspect(arr[0], content="42")
inspect(arr.length(), content="3")
}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)
}fn[T] FixedArray::make_and_blit(src : FixedArray[T], allocate_len~ : Int, init~ : T, len~ : Int, src_offset? : Int, dst_offset? : Int) -> FixedArray[T]fn[T] FixedArray::makei(length : Int, value : (Int) -> T raise?) -> FixedArray[T] raise?test {
let arr = FixedArray::makei(3, i => i * 2)
debug_inspect(
arr,
content=(
#|<FixedArray: [0, 2, 4]>
),
)
}fn[T, U] FixedArray::map(self : FixedArray[T], f : (T) -> U raise?) -> FixedArray[U] raise?test {
let arr = [1, 2, 3, 4, 5]
let doubled = arr.map(x => x * 2)
@test.assert_eq(doubled, [2, 4, 6, 8, 10])
}fn[T, U] FixedArray::mapi(self : FixedArray[T], f : (Int, T) -> U raise?) -> FixedArray[U] raise?test {
let arr = [3, 4, 5]
let added = arr.mapi((i, x) => x + i)
@test.assert_eq(added, [3, 5, 7])
}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")
}fn[T] FixedArray::rev(self : FixedArray[T]) -> FixedArray[T]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]>
),
)
}fn[T] FixedArray::rev_each(self : FixedArray[T], f : (T) -> Unit raise?) -> Unit raise?test {
let arr = []
[1, 2, 3, 4, 5].rev_each(x => arr.push(x))
@test.assert_eq(arr, [5, 4, 3, 2, 1])
}fn[T] FixedArray::rev_eachi(self : FixedArray[T], f : (Int, T) -> Unit raise?) -> Unit raise?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)])
}fn[A, B] FixedArray::rev_fold(self : FixedArray[A], init~ : B, f : (B, A) -> B raise?) -> B raise?test {
let sum = [1, 2, 3, 4, 5].rev_fold(init=0, (sum, elem) => sum + elem)
inspect(sum, content="15")
}fn[A, B] FixedArray::rev_foldi(self : FixedArray[A], init~ : B, f : (Int, B, A) -> B raise?) -> B raise?test {
let sum = [1, 2, 3, 4, 5].rev_foldi(init=0, (index, sum, _elem) => sum + index)
inspect(sum, content="10")
}#alias(rev_inplace, deprecated="`rev_inplace` is deprecated, use `rev_in_place` instead")
fn[T] FixedArray::rev_in_place(self : FixedArray[T]) -> Unittest {
let arr : FixedArray[_] = [1, 2, 3, 4, 5]
arr.rev_in_place()
debug_inspect(
arr,
content=(
#|<FixedArray: [5, 4, 3, 2, 1]>
),
)
}test {
let arr : FixedArray[Int] = [3, 4, 5]
@test.assert_eq(arr.search(3), Some(0))
}#alias("_[_]=_")
fn[T] FixedArray::set(self : FixedArray[T], idx : Int, val : T) -> Unittest {
let arr = FixedArray::make(3, 0)
arr.set(1, 42)
inspect(arr[1], content="42")
}fn FixedArray::set_utf16be_char(self : FixedArray[Byte], offset : Int, value : Char) -> Intfn FixedArray::set_utf16le_char(self : FixedArray[Byte], offset : Int, value : Char) -> Intfn FixedArray::set_utf8_char(self : FixedArray[Byte], offset : Int, value : Char) -> Inttest {
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'")
}test {
let arr = [5, 4, 3, 2, 1]
arr.sort()
@test.assert_eq(arr, [1, 2, 3, 4, 5])
}fn[T] FixedArray::sort_by(self : FixedArray[T], cmp : (T, T) -> Int) -> Unittest {
let arr = [5, 3, 2, 4, 1]
arr.sort_by((a, b) => a - b)
@test.assert_eq(arr, [1, 2, 3, 4, 5])
}test {
let arr = [5, 3, 2, 4, 1]
arr.sort_by_key(x => -x)
@test.assert_eq(arr, [5, 4, 3, 2, 1])
}test {
let arr : FixedArray[Int] = [5, 4, 3, 2, 1]
arr.stable_sort()
@test.assert_eq(arr, [1, 2, 3, 4, 5])
}test {
let arr : FixedArray[Int] = [3, 4, 5]
assert_true(arr.starts_with([3, 4]))
}fn[T] FixedArray::swap(self : FixedArray[T], i : Int, j : Int) -> Unittest {
let arr = [1, 2, 3, 4, 5]
arr.swap(0, 1)
@test.assert_eq(arr, [2, 1, 3, 4, 5])
}fn[A] FixedArray::unsafe_blit(dst : FixedArray[A], dst_offset : Int, src : FixedArray[A], src_offset : Int, len : Int) -> Unittest {
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]))
}fn FixedArray::unsafe_write_uint16_be(bytes : FixedArray[Byte], index : Int, value : UInt16) -> Unitfn FixedArray::unsafe_write_uint16_le(bytes : FixedArray[Byte], index : Int, value : UInt16) -> Unitfn FixedArray::unsafe_write_uint32_be(bytes : FixedArray[Byte], index : Int, value : UInt) -> Unitfn FixedArray::unsafe_write_uint32_le(bytes : FixedArray[Byte], index : Int, value : UInt) -> Unitfn FixedArray::unsafe_write_uint64_be(bytes : FixedArray[Byte], index : Int, value : UInt64) -> Unitfn FixedArray::unsafe_write_uint64_le(bytes : FixedArray[Byte], index : Int, value : UInt64) -> Unit#alias(sub, deprecated="Use _[_:_] instead")
#alias("_[_:_]")
fn[T] FixedArray::view(self : FixedArray[T], start? : Int, end? : Int) -> ArrayView[T]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 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.
fn Int::Int(self : Int) -> Inttest {
inspect(Int(3), content="3")
}fn Int::abs(self : Int) -> Inttest {
inspect(Int::abs(42), content="42")
inspect(Int::abs(-42), content="42")
inspect(Int::abs(0), content="0")
}#deprecated("Use infix operator `>>` instead")
fn Int::asr(self : Int, other : Int) -> Inttest {
let x = -16
inspect(x >> 2, content="-4") // Right shift preserves sign bit
}fn Int::clamp(self : Int, min~ : Int, max~ : Int) -> Inttest {
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")
}fn Int::ctz(self : Int) -> Inttest {
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
}fn Int::is_leading_surrogate(self : Int) -> Booltest {
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'
}fn Int::is_neg(self : Int) -> Booltest {
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")
}fn Int::is_non_neg(self : Int) -> Boolfn Int::is_non_pos(self : Int) -> Boolfn Int::is_surrogate(self : Int) -> Booltest {
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
}fn Int::is_trailing_surrogate(self : Int) -> Booltest {
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'
}fn Int::lnot(self : Int) -> Inttest {
let a = -1 // All bits are 1
let b = 0 // All bits are 0
inspect(a.lnot(), content="0")
inspect(b.lnot(), content="-1")
}#deprecated("Use infix operator `<<` instead")
fn Int::lsl(self : Int, other : Int) -> Inttest {
let x = 1
inspect(x << 3, content="8") // Binary: 1 -> 1000
let y = 42
inspect(y << 2, content="168") // Binary: 101010 -> 10101000
}#deprecated("Use UInt type and infix operator `>>` instead")
fn Int::lsr(self : Int, other : Int) -> Inttest {
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
}fn Int::max(self : Int, other : Int) -> Inttest {
inspect((1).max(2), content="2")
inspect((2).max(1), content="2")
}fn Int::min(self : Int, other : Int) -> Inttest {
inspect((1).min(2), content="1")
inspect((2).min(1), content="1")
}fn Int::next_power_of_two(self : Int) -> Inttest {
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")
}fn Int::popcnt(self : Int) -> Inttest {
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")
}#deprecated("Use `Float::reinterpret_from_int` instead")
fn Int::reinterpret_as_float(self : Int) -> Floatfn Int::reinterpret_as_uint(self : Int) -> UInt#deprecated("Use infix operator `<<` instead")
fn Int::shl(self : Int, other : Int) -> Inttest {
let x = 1
inspect(x << 3, content="8") // Equivalent to x << 3
}#deprecated("Use infix operator `>>` instead")
fn Int::shr(self : Int, other : Int) -> Inttest {
let n = -1024
inspect(n >> 3, content="-128") // Preserves sign bit during right shift
}fn Int::to_byte(self : Int) -> Bytetest {
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
}fn Int::to_char(self : Int) -> Char?fn Int::to_double(self : Int) -> Doubletest {
let n = 42
inspect(n.to_double(), content="42")
let neg = -42
inspect(neg.to_double(), content="-42")
}#deprecated("Use `Float::from_int` instead")
fn Int::to_float(self : Int) -> Float#deprecated("Use `Int16::from_int` instead")
fn Int::to_int16(self : Int) -> Int16fn Int::to_int64(self : Int) -> Int64test {
let n = 42
inspect(n.to_int64(), content="42")
let neg = -42
inspect(neg.to_int64(), content="-42")
}fn Int::to_string(self : Int, radix? : Int) -> Stringinspect((255).to_string(radix=16), content="ff")
inspect((-255).to_string(radix=16), content="-ff")#deprecated("Use `reinterpret_as_uint` instead")
fn Int::to_uint(self : Int) -> UInttest {
let pos = 42
let neg = -1
inspect(pos.reinterpret_as_uint(), content="42")
inspect(neg.reinterpret_as_uint(), content="4294967295") // 2^32 - 1
}fn Int::to_uint16(self : Int) -> UInt16test {
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
}fn Int::to_uint64(self : Int) -> UInt64test {
let pos = 42
inspect(pos.to_uint64(), content="42")
let neg = -1
inspect(neg.to_uint64(), content="18446744073709551615") // 2^64 - 1
}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.
fn Int64::Int64(self : Int64) -> Int64test {
inspect(Int64(3), content="3")
}fn Int64::abs(self : Int64) -> Int64test {
inspect(42L.abs(), content="42")
inspect((-42L).abs(), content="42")
inspect(0L.abs(), content="0")
}#deprecated("Use infix operator `>>` instead")
fn Int64::asr(self : Int64, other : Int) -> Int64test {
let x = -240L // 0b1111_1111_0001_0000 in two's complement
inspect(x >> 4, content="-15") // 0b1111_1111_1111_0001, using recommended syntax
}fn Int64::clamp(self : Int64, min~ : Int64, max~ : Int64) -> Int64fn Int64::clz(self : Int64) -> Inttest {
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
}fn Int64::ctz(self : Int64) -> Inttest {
inspect(0x8000000000000000L.ctz(), content="63") // Binary: 1000...0000
inspect(0x0000000000000001L.ctz(), content="0") // Binary: ...0001
inspect(0L.ctz(), content="64") // All zeros
}fn Int64::from_int(i : Int) -> Int64test {
inspect(Int64::from_int(42), content="42")
}fn Int64::lnot(self : Int64) -> Int64test {
let a = -1L // All bits are 1
let b = 0L // All bits are 0
inspect(a.lnot(), content="0")
inspect(b.lnot(), content="-1")
}#deprecated("Use infix operator `<<` instead")
fn Int64::lsl(self : Int64, other : Int) -> Int64test {
let x = 1L
inspect(x << 2, content="4") // Binary: 1 -> 100
}#deprecated("Use UInt64 type and infix operator `>>` instead")
fn Int64::lsr(self : Int64, other : Int) -> Int64test {
let x = (-4L).reinterpret_as_uint64() // Convert to UInt64 first
inspect(x >> 1, content="9223372036854775806") // Using the recommended operator
}fn Int64::max(self : Int64, other : Int64) -> Int64fn Int64::min(self : Int64, other : Int64) -> Int64fn Int64::popcnt(self : Int64) -> Inttest {
let x = 0x7000_0001_1F00_100FL // 0111000000000000000000000001000111110000000100001111
inspect(x.popcnt(), content="14")
}test {
inspect((-1L).popcnt(), content="64") // All bits set
inspect(0L.popcnt(), content="0") // No bits set
}fn Int64::reinterpret_as_double(self : Int64) -> Doubletest {
let n = 4607182418800017408L // Bit pattern for 1.0
inspect(n.reinterpret_as_double(), content="1")
}fn Int64::reinterpret_as_uint64(self : Int64) -> UInt64test {
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
}#deprecated("Use infix operator `<<` instead")
fn Int64::shl(self : Int64, other : Int) -> Int64test {
let x = 1L
inspect(x << 3, content="8") // Equivalent to x << 3
}#deprecated("Use infix operator `>>` instead")
fn Int64::shr(self : Int64, other : Int) -> Int64test {
let n = -1024L
inspect(n >> 3, content="-128") // Preserves sign bit
}fn Int64::to_byte(self : Int64) -> Bytetest {
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
}fn Int64::to_double(self : Int64) -> Doubletest {
let big = 9223372036854775807L // max value of Int64
inspect(big.to_double(), content="9223372036854776000")
let neg = -42L
inspect(neg.to_double(), content="-42")
}#deprecated("Use `Float::from_int64` instead")
fn Int64::to_float(self : Int64) -> Floatfn Int64::to_int(self : Int64) -> Inttest {
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
}fn Int64::to_string(self : Int64, radix? : Int) -> Stringfn Int64::to_uint16(self : Int64) -> UInt16test {
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
}#deprecated("Use `reinterpret_as_uint64` instead")
fn Int64::to_uint64(self : Int64) -> UInt64test {
let pos = 42L
let neg = -1L
inspect(pos.reinterpret_as_uint64(), content="42")
inspect(neg.reinterpret_as_uint64(), content="18446744073709551615") // 2^64 - 1
}fn[T, U] Option::bind(self : T?, f : (T) -> U? raise?) -> U? raise?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)
}fn[T] Option::filter(self : T?, f : (T) -> Bool raise?) -> T? raise?test {
let x = Some(3)
@test.assert_eq(x.filter(x => x > 5), None)
@test.assert_eq(x.filter(x => x < 5), Some(3))
}#deprecated("use `option.bind(x => x)` instead")
fn[T] Option::flatten(self : T??) -> T?#deprecated("use `x is None` instead")
fn[T] Option::is_empty(self : T?) -> Bool#deprecated("use `x is None` instead")
fn[T] Option::is_none(self : T?) -> Bool#deprecated("use `x is Some(_)` instead")
fn[T] Option::is_some(self : T?) -> Bool#alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
fn[T] Option::iter(self : T?) -> Iter[T]fn[T, U] Option::map(self : T?, f : (T) -> U raise?) -> U? raise?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)
}fn[T, U] Option::map_or(self : T?, default : U, f : (T) -> U raise?) -> U raise?test {
let a = Some(5)
@test.assert_eq(a.map_or(3, x => x * 2), 10)
}fn[T, U] Option::map_or_else(self : T?, default : () -> U raise?, f : (T) -> U raise?) -> U raise?test {
let a = Some(5)
@test.assert_eq(a.map_or_else(() => 3, x => x * 2), 10)
}#deprecated("Option does not have a meaningful string representation")
fn[X : Show] Option::to_string(self : X?) -> Stringfn[X] Option::unwrap(self : X?) -> X#alias(or, deprecated="`or` is deprecated, use `unwrap_or` instead")
fn[T] Option::unwrap_or(self : T?, default : T) -> T#alias(or_default, deprecated="`or_default` is deprecated, use `unwrap_or_default` instead")
fn[T : Default] Option::unwrap_or_default(self : T?) -> T#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?#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#alias(every)
fn[T] ReadOnlyArray::all(self : ReadOnlyArray[T], f : (T) -> Bool raise?) -> Bool raise?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")
}#alias(exists)
fn[T] ReadOnlyArray::any(self : ReadOnlyArray[T], f : (T) -> Bool raise?) -> Bool raise?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")
}#alias("_[_]")
fn[T] ReadOnlyArray::at(self : ReadOnlyArray[T], index : Int) -> Ttest {
let a : ReadOnlyArray[Int] = [10, 20, 30]
inspect(a.at(1), content="20")
}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)")
}fn[T] ReadOnlyArray::binary_search_by(self : ReadOnlyArray[T], cmp : (T) -> Int raise?) -> Result[Int, Int] raise?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)")
}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]>,
#|]
),
)
}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]>]
),
)
}test {
let arr : ReadOnlyArray[Int] = [1, 2, 3]
inspect(arr.contains(2), content="true")
inspect(arr.contains(4), content="false")
}fn[T] ReadOnlyArray::each(self : ReadOnlyArray[T], f : (T) -> Unit raise?) -> Unit raise?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]")
}fn[T] ReadOnlyArray::eachi(self : ReadOnlyArray[T], f : (Int, T) -> Unit raise?) -> Unit raise?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)]")
}test {
let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
inspect(arr.ends_with([4, 5]), content="true")
}fn[T] ReadOnlyArray::filter(self : ReadOnlyArray[T], f : (T) -> Bool raise?) -> ReadOnlyArray[T] raise?test {
let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
debug_inspect(
arr.filter(x => x % 2 == 0),
content=(
#|<ReadOnlyArray: [2, 4]>
),
)
}fn[A, B] ReadOnlyArray::filter_map(self : ReadOnlyArray[A], f : (A) -> B? raise?) -> ReadOnlyArray[B] raise?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]>
),
)
}fn[A, B] ReadOnlyArray::fold(self : ReadOnlyArray[A], init~ : B, f : (B, A) -> B raise?) -> B raise?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")
}fn[A, B] ReadOnlyArray::foldi(self : ReadOnlyArray[A], init~ : B, f : (Int, B, A) -> B raise?) -> B raise?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
}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")
}#alias(from_iterator, deprecated="`from_iterator` is deprecated, use `from_iter` instead")
fn[T] ReadOnlyArray::from_iter(iter : Iter[T]) -> ReadOnlyArray[T]test {
let iter = [1, 2, 3].iter()
let immut_array = ReadOnlyArray::from_iter(iter)
inspect(immut_array[0], content="1")
}fn[T] ReadOnlyArray::get(self : ReadOnlyArray[T], index : Int) -> T?test {
let arr : ReadOnlyArray[Int] = [1, 2, 3]
debug_inspect(arr.get(1), content="Some(2)")
debug_inspect(arr.get(5), content="None")
}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")
}fn[T] ReadOnlyArray::is_empty(self : ReadOnlyArray[T]) -> Booltest {
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")
}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")
}#alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
fn[T] ReadOnlyArray::iter(self : ReadOnlyArray[T]) -> Iter[T]test {
let arr : ReadOnlyArray[Int] = [1, 2, 3]
let mut sum = 0
arr.iter().each(fn(x) { sum x })
inspect(sum, content="6")
}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
}test {
let arr : ReadOnlyArray[String] = ["hello", "world", "moon"]
inspect(arr.join(","), content="hello,world,moon")
inspect(arr.join(" "), content="hello world moon")
}fn[T] ReadOnlyArray::last(self : ReadOnlyArray[T]) -> T?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")
}fn[T] ReadOnlyArray::length(self : ReadOnlyArray[T]) -> Inttest {
let arr : ReadOnlyArray[Int] = [1, 2, 3]
inspect(arr.length(), content="3")
}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")
}fn[T] ReadOnlyArray::makei(length : Int, value : (Int) -> T raise?) -> ReadOnlyArray[T] raise?test {
let immut_array = ReadOnlyArray::makei(3, fn(i) { i * 2 })
inspect(immut_array[1], content="2")
}fn[T, U] ReadOnlyArray::map(self : ReadOnlyArray[T], f : (T) -> U raise?) -> ReadOnlyArray[U] raise?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")
}fn[T, U] ReadOnlyArray::mapi(self : ReadOnlyArray[T], f : (Int, T) -> U raise?) -> ReadOnlyArray[U] raise?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
}fn[T] ReadOnlyArray::rev(self : ReadOnlyArray[T]) -> ReadOnlyArray[T]test {
let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
let reversed = arr.rev()
inspect(reversed[0], content="5")
inspect(reversed[4], content="1")
}fn[T] ReadOnlyArray::rev_each(self : ReadOnlyArray[T], f : (T) -> Unit raise?) -> Unit raise?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]")
}fn[T] ReadOnlyArray::rev_eachi(self : ReadOnlyArray[T], f : (Int, T) -> Unit raise?) -> Unit raise?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)]")
}fn[A, B] ReadOnlyArray::rev_fold(self : ReadOnlyArray[A], init~ : B, f : (B, A) -> B raise?) -> B raise?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
}fn[A, B] ReadOnlyArray::rev_foldi(self : ReadOnlyArray[A], init~ : B, f : (Int, B, A) -> B raise?) -> B raise?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 + (1*3) + (0*2) = 3
}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]")
}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")
}fn[T] ReadOnlyArray::search_by(self : ReadOnlyArray[T], f : (T) -> Bool raise?) -> Int? raise?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")
}test {
let arr : ReadOnlyArray[Int] = [1, 2, 3, 4, 5]
inspect(arr.starts_with([1, 2]), content="true")
}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")
}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")
}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: []>]
),
)
}#alias(sub, deprecated="Use _[_:_] instead")
#alias("_[_:_]")
fn[T] ReadOnlyArray::view(self : ReadOnlyArray[T], start? : Int, end? : Int) -> ArrayView[T]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")
}test {
let arr : ReadOnlyArray[Int] = [1, 2, 3, 4]
debug_inspect(
arr.windows(2),
content=(
#|[<ArrayView: [1, 2]>, <ArrayView: [2, 3]>, <ArrayView: [3, 4]>]
),
)
}fn[T, E, U] Result::bind(self : Result[T, E], g : (T) -> Result[U, E]) -> Result[U, E]test {
let x : Result[Int, String] = Ok(6)
let y = x.bind((v : Int) => Ok(v * 7))
@test.assert_eq(y, Ok(42))
}fn[T, E] Result::flatten(self : Result[Result[T, E], E]) -> Result[T, E]test {
let x : Result[Result[Int, String], String] = Ok(Ok(6))
let y = x.flatten()
@test.assert_eq(y, Ok(6))
}fn[T, E, U] Result::map(self : Result[T, E], f : (T) -> U) -> Result[U, E]test {
let x : Result[Int, Unit] = Ok(6)
let y = x.map((v : Int) => v * 7)
@test.assert_eq(y, Ok(42))
}fn[T, E, F] Result::map_err(self : Result[T, E], f : (E) -> F) -> Result[T, F]test {
let x : Result[Int, String] = Err("error")
let y = x.map_err((v : String) => v + "!")
@test.assert_eq(y, Err("error!"))
}fn[T, E] Result::to_option(self : Result[T, E]) -> T?test {
let x : Result[Int, String] = Ok(6)
let y = x.to_option()
@test.assert_eq(y, Some(6))
}fn[T, E] Result::unwrap(self : Result[T, E]) -> Tfn[T, E] Result::unwrap_err(self : Result[T, E]) -> Etest {
let err : Result[Int, String] = Err("error message")
inspect(err.unwrap_err(), content="error message")
}#alias(or)
fn[T, E] Result::unwrap_or(self : Result[T, E], default : T) -> Ttest {
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)
}#alias(or_else)
fn[T, E] Result::unwrap_or_else(self : Result[T, E], default : () -> T raise?) -> T raise?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)
}fn[T, E : Error] Result::unwrap_or_error(self : Result[T, E]) -> T raise EString 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.
fn String::after(self : String, needle : StringView) -> StringView?#alias(every)
fn String::all(self : String, f : (Char) -> Bool raise?) -> Bool raise?test {
assert_true("abc".all(c => c.is_ascii_lowercase()))
assert_false("abc1".all(c => c.is_ascii_lowercase()))
}#alias(exists)
fn String::any(self : String, f : (Char) -> Bool raise?) -> Bool raise?test {
assert_true("abc1".any(c => c.is_ascii_digit()))
assert_false("abc".any(c => c.is_ascii_digit()))
}#alias(code_unit_at)
#alias("_[_]")
fn String::at(self : String, idx : Int) -> UInt16fn String::before(self : String, needle : StringView) -> StringView?#alias(codepoint_length, deprecated="`codepoint_length` is deprecated, use `char_length` instead")
fn String::char_length(self : String, start_offset? : Int, end_offset? : Int) -> Inttest {
let s = "Hello🤣"
inspect(s.char_length(), content="6") // 6 actual characters
inspect(s.length(), content="7")
} // 5 ASCII chars + 2 surrogate pairsfn String::char_length_eq(self : String, len : Int, start_offset? : Int, end_offset? : Int) -> Boolfn String::char_length_ge(self : String, len : Int, start_offset? : Int, end_offset? : Int) -> Boolfn String::clamped_view(self : String, start? : Int, end? : Int) -> StringViewtest {
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
}fn String::compare_ignore_ascii_case(self : String, other : String) -> Inttest {
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")
}fn String::contains(self : String, str : StringView) -> Boolfn String::contains_any(self : String, chars~ : StringView) -> Boolfn String::contains_char(self : String, c : Char) -> Boolfn String::contains_code_unit(self : String, code : UInt16) -> Boolfn String::equal_ignore_ascii_case(self : String, other : String) -> Booltest {
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")
}fn String::escape(self : String, quote? : Bool) -> Stringtest {
inspect("Hello \n".escape(), content="\"Hello \\n\"")
inspect("Hello \n".escape(quote=false), content="Hello \\n")
}fn String::find(self : String, str : StringView) -> Int?fn String::find_by(self : String, pred : (Char) -> Bool) -> Int?fn[A] String::fold(self : String, init~ : A, f : (A, Char) -> A raise?) -> A raise?test {
let s = String::from_array(['H', 'e', 'l', 'l', 'o'])
@test.assert_eq(s, "Hello")
}#alias(from_iterator, deprecated="`from_iterator` is deprecated, use `from_iter` instead")
fn String::from_iter(iter : Iter[Char]) -> Stringfn String::get(self : String, idx : Int) -> UInt16?fn String::get_char(self : String, idx : Int) -> Char?fn String::get_view(self : String, start? : Int, end? : Int) -> StringView?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")
}#alias(starts_with, deprecated="`starts_with` is deprecated, use `has_prefix` instead")
fn String::has_prefix(self : String, str : StringView) -> Bool#alias(ends_with, deprecated="`ends_with` is deprecated, use `has_suffix` instead")
fn String::has_suffix(self : String, str : StringView) -> Boolfn String::is_blank(self : String) -> Boolfn String::is_empty(self : String) -> Bool#alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
fn String::iter(self : String) -> Iter[Char]test {
let s = "Hello, World!🤣"
@test.assert_eq(s.iter().count(), 14) // Unicode characters
@test.assert_eq(s.length(), 15)
} // Utf16 code units#alias(iterator2, deprecated="`iterator2` is deprecated, use `iter2` instead")
fn String::iter2(self : String) -> Iter2[Int, Char]#alias(charcode_length, deprecated="`charcode_length` is deprecated, use `length` instead")
fn String::length(self : String) -> Inttest {
inspect("hello".length(), content="5")
inspect("🤣".length(), content="2") // Emoji uses two UTF-16 code units
inspect("".length(), content="0") // Empty string
}fn String::lexical_compare(self : String, other : String) -> Inttest {
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")
}fn String::make(length : Int, value : Char) -> Stringtest {
@test.assert_eq(String::make(5, 'S'), "SSSSS")
}fn String::offset_of_nth_char(self : String, i : Int, start_offset? : Int, end_offset? : Int) -> Int?fn String::pad_end(self : String, total_width : Int, padding_char : Char) -> Stringfn String::pad_start(self : String, total_width : Int, padding_char : Char) -> Stringfn String::repeat(self : String, n : Int) -> Stringfn String::replace(self : String, old~ : StringView, new~ : StringView) -> Stringfn String::replace_all(self : String, old~ : StringView, new~ : StringView) -> Stringfn String::rev(self : String) -> Stringfn String::rev_after(self : String, needle : StringView) -> StringView?test {
assert_true("a/b/c.txt".rev_after("/") == Some("c.txt"))
}fn String::rev_before(self : String, needle : StringView) -> StringView?test {
assert_true("a/b/c.txt".rev_before("/") == Some("a/b"))
}fn String::rev_find(self : String, str : StringView) -> Int?fn[A] String::rev_fold(self : String, init~ : A, f : (A, Char) -> A raise?) -> A raise?#alias(rev_iterator, deprecated="`rev_iterator` is deprecated, use `rev_iter` instead")
fn String::rev_iter(self : String) -> Iter[Char]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',
])
}fn String::rev_split_once(self : String, needle : StringView) -> (StringView, StringView)?test {
assert_true("a::b::c".rev_split_once("::") == Some(("a::b", "c")))
}fn String::split_at(self : String, at : Int) -> (StringView, StringView)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="")
}fn String::split_once(self : String, needle : StringView) -> (StringView, StringView)?#alias(chop_prefix)
fn String::strip_prefix(self : String, prefix : StringView) -> StringView?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(""))
}#alias(chop_suffix)
fn String::strip_suffix(self : String, suffix : StringView) -> StringView?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(""))
}#alias("_[_:_]")
fn String::sub(self : String, start? : Int, end? : Int) -> StringViewtest {
let str = "Hello🤣World"
let view1 = str[0:5]
inspect(view1, content="Hello")
let view2 = str[7:]
inspect(view2, content="World")
}#deprecated("Use `str[:]` or `str[:].to_string()` instead")
fn String::substring(self : String, start? : Int, end? : Int) -> String#deprecated("Check `@encoding/utf8.encode`")
fn String::to_bytes(self : String) -> Bytesfn String::to_lower(self : String) -> Stringfn String::to_upper(self : String) -> Stringfn String::trim(self : String, chars? : StringView) -> StringViewfn String::trim_end(self : String, chars? : StringView) -> StringView#deprecated("Use `trim` with default whitespace characters instead")
fn String::trim_space(self : String) -> StringViewfn String::trim_start(self : String, chars? : StringView) -> StringView#deprecated("Use `s.get_char(i).unwrap()` instead")
fn String::unsafe_char_at(self : String, index : Int) -> Charfn String::unsafe_substring(str : String, start~ : Int, end~ : Int) -> Stringfn String::view(self : String, start_offset? : Int, end_offset? : Int) -> StringViewtest {
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🤣")
}fn StringView::after(self : StringView, needle : StringView) -> StringView?#alias(every)
fn StringView::all(self : StringView, f : (Char) -> Bool raise?) -> Bool raise?test {
let view = "zabc!"[1:4]
assert_true(view.all(c => c.is_ascii_lowercase()))
assert_false(view.all(c => c == 'a'))
}#alias(exists)
fn StringView::any(self : StringView, f : (Char) -> Bool raise?) -> Bool raise?test {
let view = "zabc!"[1:4]
assert_true(view.any(c => c == 'b'))
assert_false(view.any(c => c.is_ascii_digit()))
}#alias(code_unit_at)
#alias("_[_]")
fn StringView::at(self : StringView, index : Int) -> UInt16fn StringView::before(self : StringView, needle : StringView) -> StringView?fn StringView::char_length(self : StringView) -> Intfn StringView::char_length_eq(self : StringView, len : Int) -> Boolfn StringView::char_length_ge(self : StringView, len : Int) -> Boolfn StringView::clamped_view(self : StringView, start? : Int, end? : Int) -> StringViewtest {
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")
}fn StringView::compare_ignore_ascii_case(self : StringView, other : StringView) -> Inttest {
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")
}fn StringView::contains(self : StringView, str : StringView) -> Boolfn StringView::contains_any(self : StringView, chars~ : StringView) -> Boolfn StringView::contains_char(self : StringView, c : Char) -> Boolfn StringView::contains_code_unit(self : StringView, code : UInt16) -> Boolfn StringView::data(self : StringView) -> Stringfn StringView::equal_ignore_ascii_case(self : StringView, other : StringView) -> Booltest {
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")
}fn StringView::equal_to_string(self : StringView, other : String) -> Booltest {
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",
)
}fn StringView::escape(self : StringView, quote? : Bool) -> StringViewtest {
inspect("Hello\nWorld"[:6].escape(), content="\"Hello\\n\"")
inspect("Hello\nWorld"[:6].escape(quote=false), content="Hello\\n")
}fn StringView::find(self : StringView, str : StringView) -> Int?fn StringView::find_by(self : StringView, pred : (Char) -> Bool) -> Int?fn[A] StringView::fold(self : StringView, init~ : A, f : (A, Char) -> A raise?) -> A raise?#alias(from_iterator, deprecated="`from_iterator` is deprecated, use `from_iter` instead")
fn StringView::from_iter(iter : Iter[Char]) -> StringViewfn StringView::get(self : StringView, idx : Int) -> UInt16?fn StringView::get_char(self : StringView, idx : Int) -> Char?fn StringView::get_view(self : StringView, start? : Int, end? : Int) -> StringView?#alias(starts_with, deprecated="`starts_with` is deprecated, use `has_prefix` instead")
fn StringView::has_prefix(self : StringView, str : StringView) -> Bool#alias(ends_with, deprecated="`ends_with` is deprecated, use `has_suffix` instead")
fn StringView::has_suffix(self : StringView, str : StringView) -> Boolfn StringView::is_blank(self : StringView) -> Boolfn StringView::is_empty(self : StringView) -> Bool#alias(iterator, deprecated="`iterator` is deprecated, use `iter` instead")
fn StringView::iter(self : StringView) -> Iter[Char]#alias(iterator2, deprecated="`iterator2` is deprecated, use `iter2` instead")
fn StringView::iter2(self : StringView) -> Iter2[Int, Char]fn StringView::length(self : StringView) -> Intfn StringView::lexical_compare(self : StringView, other : StringView) -> Inttest {
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",
)
}fn StringView::make(length : Int, value : Char) -> StringViewfn StringView::offset_of_nth_char(self : StringView, i : Int) -> Int?fn StringView::pad_end(self : StringView, total_width : Int, padding_char : Char) -> Stringfn StringView::pad_start(self : StringView, total_width : Int, padding_char : Char) -> Stringfn StringView::repeat(self : StringView, n : Int) -> StringViewfn StringView::replace(self : StringView, old~ : StringView, new~ : StringView) -> StringViewfn StringView::replace_all(self : StringView, old~ : StringView, new~ : StringView) -> StringViewfn StringView::rev(self : StringView) -> Stringfn StringView::rev_after(self : StringView, needle : StringView) -> StringView?test {
assert_true("a/b/c.txt".rev_after("/") == Some("c.txt"))
}fn StringView::rev_before(self : StringView, needle : StringView) -> StringView?test {
assert_true("a/b/c.txt".rev_before("/") == Some("a/b"))
}fn StringView::rev_find(self : StringView, str : StringView) -> Int?fn[A] StringView::rev_fold(self : StringView, init~ : A, f : (A, Char) -> A raise?) -> A raise?#alias(rev_iterator, deprecated="`rev_iterator` is deprecated, use `rev_iter` instead")
fn StringView::rev_iter(self : StringView) -> Iter[Char]fn StringView::rev_split_once(self : StringView, needle : StringView) -> (StringView, StringView)?test {
assert_true("a::b::c".rev_split_once("::") == Some(("a::b", "c")))
assert_true("nope".rev_split_once("::") == None)
}fn StringView::split_at(self : StringView, at : Int) -> (StringView, StringView)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")
}fn StringView::split_once(self : StringView, needle : StringView) -> (StringView, StringView)?fn StringView::start_offset(self : StringView) -> Int#alias(chop_prefix)
fn StringView::strip_prefix(self : StringView, prefix : StringView) -> StringView?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(""))
}#alias(chop_suffix)
fn StringView::strip_suffix(self : StringView, suffix : StringView) -> StringView?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(""))
}#alias("_[_:_]")
fn StringView::sub(self : StringView, start? : Int, end? : Int) -> StringViewtest {
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")
}test {
let view = "Hello🤣xa"[1:8]
let chars = view.to_array()
@debug.debug_inspect(chars, content="['e', 'l', 'l', 'o', '🤣', 'x']")
}#deprecated("Check `@encoding/utf8.encode`")
fn StringView::to_bytes(self : StringView) -> Bytesfn StringView::to_lower(self : StringView) -> StringView#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) -> Stringtest {
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")
}fn StringView::to_upper(self : StringView) -> StringViewfn StringView::trim(self : StringView, chars? : StringView) -> StringViewfn StringView::trim_end(self : StringView, chars? : StringView) -> StringView#deprecated("Use `trim` with default whitespace characters instead")
fn StringView::trim_space(self : StringView) -> StringViewfn StringView::trim_start(self : StringView, chars? : StringView) -> StringView#deprecated("Use `StringView::unsafe_get` instead")
fn StringView::unsafe_charcode_at(self : StringView, index : Int) -> Inttest {
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")
}#internal(unsafe, "Undefined behavior if index is out of bounds.")
fn StringView::unsafe_get(self : StringView, index : Int) -> UInt16fn StringView::view(self : StringView, start_offset? : Int, end_offset? : Int) -> StringViewUInt 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.
fn UInt::UInt(self : UInt) -> UInttest {
inspect(UInt(3), content="3")
}fn UInt::clamp(self : UInt, min~ : UInt, max~ : UInt) -> UIntfn UInt::clz(self : UInt) -> Inttest {
inspect(0U.clz(), content="32")
inspect(1U.clz(), content="31")
inspect(0x80000000U.clz(), content="0")
}fn UInt::ctz(self : UInt) -> Inttest {
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
}fn UInt::lnot(self : UInt) -> UInttest {
let x = 0xFF00U // Binary: 1111_1111_0000_0000
inspect(x.lnot(), content="4294902015") // Binary: ...0000_0000_1111_1111
}#deprecated("Use infix operator `<<` instead")
fn UInt::lsl(self : UInt, shift : Int) -> UInttest {
let x = 1U
inspect(x << 3, content="8") // Using the recommended operator
let y = 8U
inspect(y << 1, content="16") // Using the recommended operator
}#deprecated("Use infix operator `>>` instead")
fn UInt::lsr(self : UInt, shift : Int) -> UInttest {
let x = 0xF0000000U
inspect(x >> 4, content="251658240") // Using the recommended operator
}fn UInt::max(self : UInt, other : UInt) -> UIntfn UInt::min(self : UInt, other : UInt) -> UIntfn UInt::popcnt(self : UInt) -> Inttest {
let x = 0xF0F0U // Binary: 1111 0000 1111 0000
inspect(x.popcnt(), content="8") // Has 8 bits set to 1
}#deprecated("Use `Float::reinterpret_from_uint` instead")
fn UInt::reinterpret_as_float(self : UInt) -> Floatfn UInt::reinterpret_as_int(self : UInt) -> Int#deprecated("Use infix operator `<<` instead")
fn UInt::shl(self : UInt, shift : Int) -> UInttest {
let x = 1U
inspect(x << 3, content="8") // Binary: 1 -> 1000
}#deprecated("Use infix operator `>>` instead")
fn UInt::shr(self : UInt, shift : Int) -> UInttest {
let x = 0xFF000000U
inspect(x >> 8, content="16711680") // 0x00FF0000
}fn UInt::to_byte(self : UInt) -> Bytetest {
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
}fn UInt::to_double(self : UInt) -> Doubletest {
let n = 42U
inspect(n.to_double(), content="42")
let max = 4294967295U // maximum value of UInt
inspect(max.to_double(), content="4294967295")
}#deprecated("Use `Float::from_uint` instead")
fn UInt::to_float(self : UInt) -> Float#deprecated("Use `reinterpret_as_int` instead")
fn UInt::to_int(self : UInt) -> Inttest {
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
}fn UInt::to_string(self : UInt, radix? : Int) -> Stringfn UInt::to_uint16(self : UInt) -> UInt16test {
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
}fn UInt::to_uint64(self : UInt) -> UInt64test {
let n = 42U
inspect(n.to_uint64(), content="42")
let max = 4294967295U // Maximum value of UInt
inspect(max.to_uint64(), content="4294967295")
}fn UInt::trunc_double(val : Double) -> UInttest {
inspect(UInt::trunc_double(42.75), content="42")
}fn UInt16::UInt16(self : UInt16) -> UInt16test {
inspect(UInt16(3), content="3")
}fn UInt16::is_leading_surrogate(self : UInt16) -> Booltest {
inspect((0xD800 : UInt16).is_leading_surrogate(), content="true")
inspect((0xDBFF : UInt16).is_leading_surrogate(), content="true")
inspect((0xDC00 : UInt16).is_leading_surrogate(), content="false")
inspect((0x41 : UInt16).is_leading_surrogate(), content="false") // 'A'
}fn UInt16::is_surrogate(self : UInt16) -> Booltest {
inspect((0xD800 : UInt16).is_surrogate(), content="true") // leading surrogate
inspect((0xDC00 : UInt16).is_surrogate(), content="true") // trailing surrogate
inspect((0xDFFF : UInt16).is_surrogate(), content="true") // trailing surrogate
inspect((0x41 : UInt16).is_surrogate(), content="false") // 'A'
}fn UInt16::is_trailing_surrogate(self : UInt16) -> Booltest {
inspect((0xDC00 : UInt16).is_trailing_surrogate(), content="true")
inspect((0xDFFF : UInt16).is_trailing_surrogate(), content="true")
inspect((0xD800 : UInt16).is_trailing_surrogate(), content="false")
inspect((0x41 : UInt16).is_trailing_surrogate(), content="false") // 'A'
}fn UInt16::lnot(self : UInt16) -> UInt16test {
inspect((0x0000 : UInt16).lnot().to_int(), content="65535")
inspect((0xFFFF : UInt16).lnot().to_int(), content="0")
}fn UInt16::to_byte(self : UInt16) -> Bytetest {
let x = Int::to_uint16(258) // Binary: 0000_0001_0000_0010
inspect(x.to_byte(), content="b'\\x02'") // Only keeps 0000_0010
}fn UInt16::to_int(self : UInt16) -> Inttest {
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")
}fn UInt16::to_int64(self : UInt16) -> Int64test {
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")
}fn UInt16::to_string(self : UInt16, radix? : Int) -> Stringtest {
inspect((255 : UInt16).to_string(), content="255")
inspect((255 : UInt16).to_string(radix=16), content="ff")
}fn UInt64::UInt64(self : UInt64) -> UInt64test {
inspect(UInt64(3), content="3")
}fn UInt64::clz(self : UInt64) -> Inttest {
inspect(0UL.clz(), content="64")
inspect(1UL.clz(), content="63")
inspect(0x8000_0000_0000_0000UL.clz(), content="0")
}fn UInt64::ctz(self : UInt64) -> Inttest {
let x = 0x8000000000000000UL // Binary: 1000...0000 (63 trailing zeros)
inspect(x.ctz(), content="63")
let y = 0UL
inspect(y.ctz(), content="64")
}fn UInt64::extend_uint(val : UInt) -> UInt64test {
let n = 42U
inspect(UInt64::extend_uint(n), content="42")
let max = 4294967295U // Maximum value of UInt
inspect(UInt64::extend_uint(max), content="4294967295")
}fn UInt64::lnot(self : UInt64) -> UInt64test {
let x = 0xFFFF_FFFF_0000_0000UL
inspect(x.lnot(), content="4294967295") // 0x0000_0000_FFFF_FFFF
}#deprecated("Use infix operator `<<` instead")
fn UInt64::lsl(self : UInt64, shift : Int) -> UInt64test {
let x = 1UL
inspect(x << 4, content="16") // 1 << 4 = 16
}#deprecated("Use infix operator `>>` instead")
fn UInt64::lsr(self : UInt64, shift : Int) -> UInt64test {
let x = 0xF000000000000000UL
inspect(x >> 4, content="1080863910568919040") // 0x0F00000000000000
}fn UInt64::popcnt(self : UInt64) -> Inttest {
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
}fn UInt64::reinterpret_as_double(self : UInt64) -> Doubletest {
// 0x4045000000000000 represents 42.0 in IEEE 754 double format
let n = 4636737291354636288UL
inspect(n.reinterpret_as_double(), content="100")
}fn UInt64::reinterpret_as_int64(self : UInt64) -> Int64test {
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
}#deprecated("Use infix operator `<<` instead")
fn UInt64::shl(self : UInt64, shift : Int) -> UInt64test {
let x = 1UL
inspect(x << 2, content="4") // 1 << 2 = 4
}#deprecated("Use infix operator `>>` instead")
fn UInt64::shr(self : UInt64, shift : Int) -> UInt64test {
let x = 0xFF00000000000000UL
inspect(x >> 8, content="71776119061217280")
}fn UInt64::to_be_bytes(self : UInt64) -> Bytesfn UInt64::to_byte(self : UInt64) -> Bytetest {
let n = 258UL // In binary: 100000010
inspect(n.to_byte(), content="b'\\x02'") // Only keeps 00000010
}fn UInt64::to_double(self : UInt64) -> Double let n = 12345678901234567890UL
inspect(n.to_double(), content="12345678901234567000") // Note the slight precision loss
let small = 42UL
inspect(small.to_double(), content="42")#deprecated("Use `Float::from_uint64` instead")
fn UInt64::to_float(self : UInt64) -> Floatfn UInt64::to_int(self : UInt64) -> Inttest {
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
}#deprecated("Use `reinterpret_as_int64` instead")
fn UInt64::to_int64(self : UInt64) -> Int64test {
let max = 18446744073709551615UL
inspect(max.reinterpret_as_int64(), content="-1")
}fn UInt64::to_le_bytes(self : UInt64) -> Bytesfn UInt64::to_string(self : UInt64, radix? : Int) -> Stringfn UInt64::to_uint(self : UInt64) -> UInttest {
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")
}fn UInt64::to_uint16(self : UInt64) -> UInt16test {
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
}fn UInt64::trunc_double(val : Double) -> UInt64test {
inspect(UInt64::trunc_double(42.75), content="42")
}#callsite(autofill(loc))
fn assert_false(x : Bool, msg? : StringView, loc~ : SourceLoc) -> Unit raisetest {
assert_false(false)
assert_false(1 > 2)
}test {
assert_true(true)
}test {
inspect(compare(1, 2).is_neg(), content="true")
inspect(compare("abc", "abc"), content="0")
}fn debug_assert(x : () -> Bool) -> Unittest {
inspect(hash(42) == hash(42), content="true")
}fn[T] ignore(t : T) -> Unittest {
let x = 42
ignore(x) // Explicitly ignore the value
let mut sum = 0
ignore([1, 2, 3].iter().each(x => sum x)) // Ignore the Unit return value of each()
inspect(sum, content="6")
}#callsite(autofill(args_loc, loc))
fn inspect(obj : &Show, content? : String, loc~ : SourceLoc, args_loc~ : ArgsLoc) -> Unit raise InspectErrortest {
inspect(42, content="42")
inspect("hello", content="hello")
debug_inspect([1, 2, 3], content="[1, 2, 3]")
}#deprecated("This function is deprecated.")
fn not(x : Bool) -> Booltest {
inspect(null.stringify(), content="null")
}fn[T] physical_equal(a : T, b : T) -> Booltest {
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
}Install
Installed by default