Every type the language has built in - see Type Expression for how types are written, and Interfaces for the builtin interfaces. Each card lists the interfaces the type implements and the functions (called on the type) and methods (called on a value) it comes with; free functions are on Builtin Functions.
#unknownA value whose type isn't known - it has to be checked before it can be used as anything more specific.
Sourceown members
#neverThe type of an expression that never produces a value, e.g. one that always exits through !!.
Sourceown members
no values, so no methods - Never fits every type
#undefinedThe type of the undefined literal - no value.
Sourceown members, Equatable, Hashable, ToString, Default, Copy
Implements Equatable, Hashable, ToString, Default (undefined), Copy
#typeA type itself, used as a value.
Sourceown members, Equatable, Hashable, ToString
Implements Equatable, Hashable, ToString
Functions
of(value: Unknown): Typethe type value actually has - value.typeOf() source named(name: String): Typethe type written as name - "Point", "Shape.Circle" source Methods
name(): String"Array<U8>" source generics(): Array<Type>its type arguments - [U8] for Array<U8> source implements(interface: Interface): Booleanit has an implement of interface source isAssignableFrom(other: Type): Booleana value of other fits here source fields(): Map<String, Type>empty unless Struct / Tuple source variants(): Array<Type>empty unless Enum / Union source size(): U64bytes a value occupies source #booleantrue or false.
Sourceown members, Equatable, Hashable, Comparable, ToString, FromString, Logical, Default, Copy
Implements Equatable, Hashable, Comparable (false < true), ToString, FromString, Logical (short-circuiting), Default (false), Copy
Functions
parse(text: String): ParseError ! Boolean"true" | "false" source Methods
not(): Booleannot a source and(other: Boolean): Booleana and b source or(other: Boolean): Booleana or b source xor(other: Boolean): Booleana xor b source iff(other: Boolean): Booleana iff b source implies(other: Boolean): Booleannot a or b source toTrilean(): Trileantrue or false as a Trilean source #trileanThree-valued logic: true, false, or null for unknown.
Sourceown members, Equatable, Hashable, ToString, FromString, Logical, Default, Copy
Implements Equatable, Hashable, ToString, FromString, Logical (Kleene), Default (null), Copy
Functions
parse(text: String): ParseError ! Trilean"true" | "false" | "null" source Methods
not(): TrileanKleene: not null is null source and(other: Trilean): Trileanfalse wins over null source or(other: Trilean): Trileantrue wins over null source xor(other: Trilean): Trileannull when either side is source iff(other: Trilean): Trileannull when either side is source isKnown(): Booleannot null source toBoolean(): Boolean?undefined for null source orElse(fallback: Boolean): Booleanfallback for null source #orderingHow two values compare - what Comparable's compare returns.
Sourceown members, Equatable, Hashable, Comparable, ToString, Copy
Implements Equatable, Hashable, Comparable (Less < Equal < Greater), ToString, Copy
Functions
of<T: Comparable>(a: T, b: T): Orderinga.compare(b) source Methods
reverse(): OrderingLess <-> Greater source then(other: Ordering): Orderingself unless Equal, then other - chains comparisons source thenBy(next: Lambda<(), Ordering>): Orderinglazy then source isLess(): Booleanself is Less source isEqual(): Booleanself is Equal source isGreater(): Booleanself is Greater source toInteger(): S8-1 | 0 | 1 source #integerA whole number - an alias for SignedInteger.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Bitwise, Steppable, Castable, Default, Copy
An alias - has every member of S64.
U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256(51)U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256 (and Integer, UnsignedInteger, SignedInteger through their aliases)
+ - * // ^ and `as` give an OverflowError for a result that doesn't fit; +% -% *% wrap around and
+| -| *| fill up to min() / max() instead (the wrapping / saturating methods)
Implements Equatable, Hashable, Comparable, Bounded, ToString, FromString (radix 10), Numeric, Bitwise, Steppable, Castable<every numeric type>, Default (0), Copy
Functions
min(): Selfsmallest value source max(): Selflargest value source bits(): U168, 16, 32, 64, 128, 256 source parse(text: String, radix: U8 := 10): ParseError ! Selfin the given radix (2 to 36), optional sign, _ separators allowed source fromBytes(bytes: Bytes): ParseError ! Selflittle-endian, exactly bits() / 8 bytes source Methods
abs(): SelfS*.min().abs() is an OverflowError source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: Self): Selfthe smaller of the two source max(other: Self): Selfthe larger of the two source clamp(range: Range<Self>): Selfself kept within range source pow(exponent: U32): Selfself raised to exponent - an OverflowError when it doesn't fit source sqrt(): CastError ! Selffloor of the square root - a CastError below zero source gcd(other: Self): Selfgreatest common divisor - 0 when both are 0 source lcm(other: Self): Selfleast common multiple - 0 when either is 0 source divMod(other: Self): (Self, Self)(a // b, a % b) source modulo(other: Self): Selfalways the divisor's sign, unlike % source checkedAdd(other: Self): OverflowError ! Selfa + b - the OverflowError as a value to handle source checkedSubtract(other: Self): OverflowError ! Selfa - b - the OverflowError as a value to handle source checkedMultiply(other: Self): OverflowError ! Selfa * b - the OverflowError as a value to handle source wrappingAdd(other: Self): Selfa +% b source wrappingSubtract(other: Self): Selfa -% b source wrappingMultiply(other: Self): Selfa *% b source saturatingAdd(other: Self): Selfa +| b source saturatingSubtract(other: Self): Selfa -| b source saturatingMultiply(other: Self): Selfa *| b source bor(other: Self): Selfa bor b source bxor(other: Self): Selfa bxor b source band(other: Self): Selfa band b source bnot(): Self~a source shl(count: U64): Selfa shl b source shr(count: U64): Selfa shr b (arithmetic for S*, logical for U*) source rotateLeft(count: U8): Selfbits shifted left, those falling off the top coming back at the bottom source rotateRight(count: U8): Selfbits shifted right, those falling off the bottom coming back at the top source countOnes(): U8bits set source countZeros(): U8bits clear source leadingZeros(): U8clear bits above the highest set one - bits() when zero source trailingZeros(): U8clear bits below the lowest set one - bits() when zero source isPowerOfTwo(): Booleanexactly one bit set source bit(index: U8): Booleanbit index is set - 0 the least significant source withBit(index: U8, value: Boolean): Selfself with bit index set or cleared source toString(radix: U8 := 10): StringToString, with an optional radix source toBytes(): Byteslittle-endian source toFloat(): Floatnearest F64 - `as Float` source toBigInteger(): BigIntegerthe same number, as a BigInteger source toCodepoint(): CastError ! Codepointthe codepoint with this value - a CastError for surrogates, negatives and above 0x10FFFF source checkedCast<Target>(): CastError ! Target`as`, with a CastError where `as` gives an OverflowError source #unsignedintegerA whole number that can't be negative.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Bitwise, Steppable, Castable, Default, Copy
An alias - has every member of U64.
U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256(51)U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256 (and Integer, UnsignedInteger, SignedInteger through their aliases)
+ - * // ^ and `as` give an OverflowError for a result that doesn't fit; +% -% *% wrap around and
+| -| *| fill up to min() / max() instead (the wrapping / saturating methods)
Implements Equatable, Hashable, Comparable, Bounded, ToString, FromString (radix 10), Numeric, Bitwise, Steppable, Castable<every numeric type>, Default (0), Copy
Functions
min(): Selfsmallest value source max(): Selflargest value source bits(): U168, 16, 32, 64, 128, 256 source parse(text: String, radix: U8 := 10): ParseError ! Selfin the given radix (2 to 36), optional sign, _ separators allowed source fromBytes(bytes: Bytes): ParseError ! Selflittle-endian, exactly bits() / 8 bytes source Methods
abs(): SelfS*.min().abs() is an OverflowError source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: Self): Selfthe smaller of the two source max(other: Self): Selfthe larger of the two source clamp(range: Range<Self>): Selfself kept within range source pow(exponent: U32): Selfself raised to exponent - an OverflowError when it doesn't fit source sqrt(): CastError ! Selffloor of the square root - a CastError below zero source gcd(other: Self): Selfgreatest common divisor - 0 when both are 0 source lcm(other: Self): Selfleast common multiple - 0 when either is 0 source divMod(other: Self): (Self, Self)(a // b, a % b) source modulo(other: Self): Selfalways the divisor's sign, unlike % source checkedAdd(other: Self): OverflowError ! Selfa + b - the OverflowError as a value to handle source checkedSubtract(other: Self): OverflowError ! Selfa - b - the OverflowError as a value to handle source checkedMultiply(other: Self): OverflowError ! Selfa * b - the OverflowError as a value to handle source wrappingAdd(other: Self): Selfa +% b source wrappingSubtract(other: Self): Selfa -% b source wrappingMultiply(other: Self): Selfa *% b source saturatingAdd(other: Self): Selfa +| b source saturatingSubtract(other: Self): Selfa -| b source saturatingMultiply(other: Self): Selfa *| b source bor(other: Self): Selfa bor b source bxor(other: Self): Selfa bxor b source band(other: Self): Selfa band b source bnot(): Self~a source shl(count: U64): Selfa shl b source shr(count: U64): Selfa shr b (arithmetic for S*, logical for U*) source rotateLeft(count: U8): Selfbits shifted left, those falling off the top coming back at the bottom source rotateRight(count: U8): Selfbits shifted right, those falling off the bottom coming back at the top source countOnes(): U8bits set source countZeros(): U8bits clear source leadingZeros(): U8clear bits above the highest set one - bits() when zero source trailingZeros(): U8clear bits below the lowest set one - bits() when zero source isPowerOfTwo(): Booleanexactly one bit set source bit(index: U8): Booleanbit index is set - 0 the least significant source withBit(index: U8, value: Boolean): Selfself with bit index set or cleared source toString(radix: U8 := 10): StringToString, with an optional radix source toBytes(): Byteslittle-endian source toFloat(): Floatnearest F64 - `as Float` source toBigInteger(): BigIntegerthe same number, as a BigInteger source toCodepoint(): CastError ! Codepointthe codepoint with this value - a CastError for surrogates, negatives and above 0x10FFFF source checkedCast<Target>(): CastError ! Target`as`, with a CastError where `as` gives an OverflowError source #signedintegerA whole number that can be negative.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Bitwise, Steppable, Castable, Default, Copy
An alias - has every member of S64.
U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256(51)U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256 (and Integer, UnsignedInteger, SignedInteger through their aliases)
+ - * // ^ and `as` give an OverflowError for a result that doesn't fit; +% -% *% wrap around and
+| -| *| fill up to min() / max() instead (the wrapping / saturating methods)
Implements Equatable, Hashable, Comparable, Bounded, ToString, FromString (radix 10), Numeric, Bitwise, Steppable, Castable<every numeric type>, Default (0), Copy
Functions
min(): Selfsmallest value source max(): Selflargest value source bits(): U168, 16, 32, 64, 128, 256 source parse(text: String, radix: U8 := 10): ParseError ! Selfin the given radix (2 to 36), optional sign, _ separators allowed source fromBytes(bytes: Bytes): ParseError ! Selflittle-endian, exactly bits() / 8 bytes source Methods
abs(): SelfS*.min().abs() is an OverflowError source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: Self): Selfthe smaller of the two source max(other: Self): Selfthe larger of the two source clamp(range: Range<Self>): Selfself kept within range source pow(exponent: U32): Selfself raised to exponent - an OverflowError when it doesn't fit source sqrt(): CastError ! Selffloor of the square root - a CastError below zero source gcd(other: Self): Selfgreatest common divisor - 0 when both are 0 source lcm(other: Self): Selfleast common multiple - 0 when either is 0 source divMod(other: Self): (Self, Self)(a // b, a % b) source modulo(other: Self): Selfalways the divisor's sign, unlike % source checkedAdd(other: Self): OverflowError ! Selfa + b - the OverflowError as a value to handle source checkedSubtract(other: Self): OverflowError ! Selfa - b - the OverflowError as a value to handle source checkedMultiply(other: Self): OverflowError ! Selfa * b - the OverflowError as a value to handle source wrappingAdd(other: Self): Selfa +% b source wrappingSubtract(other: Self): Selfa -% b source wrappingMultiply(other: Self): Selfa *% b source saturatingAdd(other: Self): Selfa +| b source saturatingSubtract(other: Self): Selfa -| b source saturatingMultiply(other: Self): Selfa *| b source bor(other: Self): Selfa bor b source bxor(other: Self): Selfa bxor b source band(other: Self): Selfa band b source bnot(): Self~a source shl(count: U64): Selfa shl b source shr(count: U64): Selfa shr b (arithmetic for S*, logical for U*) source rotateLeft(count: U8): Selfbits shifted left, those falling off the top coming back at the bottom source rotateRight(count: U8): Selfbits shifted right, those falling off the bottom coming back at the top source countOnes(): U8bits set source countZeros(): U8bits clear source leadingZeros(): U8clear bits above the highest set one - bits() when zero source trailingZeros(): U8clear bits below the lowest set one - bits() when zero source isPowerOfTwo(): Booleanexactly one bit set source bit(index: U8): Booleanbit index is set - 0 the least significant source withBit(index: U8, value: Boolean): Selfself with bit index set or cleared source toString(radix: U8 := 10): StringToString, with an optional radix source toBytes(): Byteslittle-endian source toFloat(): Floatnearest F64 - `as Float` source toBigInteger(): BigIntegerthe same number, as a BigInteger source toCodepoint(): CastError ! Codepointthe codepoint with this value - a CastError for surrogates, negatives and above 0x10FFFF source checkedCast<Target>(): CastError ! Target`as`, with a CastError where `as` gives an OverflowError source #numberAn alias for Float - a number written without a more specific type is a float.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Castable, Default, Copy
An alias - has every member of F64.
F16 F32 F64(52)F16 F32 F64 (and Number, Float through their aliases)
Implements Equatable (IEEE-754 equality, NaN != NaN), Hashable (agrees with ==), Comparable (NaN last, == values Equal), Bounded (finite values), ToString, FromString, Numeric, Castable<every numeric type>, Default (0.0), Copy
Functions
min(): Selfmost negative finite value source max(): Selflargest finite value source epsilon(): Selfdistance from 1 to the next value source infinity(): Selfpositive infinity - negate() for the negative one source nan(): Selfnot a number source pi(): Selfπ, the ratio of a circle's circumference to its diameter source e(): Selfe, the base of the natural logarithm source tau(): Selfτ = 2π, a full turn in radians source parse(text: String): ParseError ! Selfdecimal or scientific notation, "inf", "-inf", "nan" - correctly rounded source fromBits(bits: Bits): Selfthe value raw IEEE-754 bits hold - toBits the other way source Methods
abs(): Selfvalue without its sign source sign(): Self-1.0 | 0.0 | 1.0 (NaN for NaN) source isNaN(): BooleanNaN - the one value != itself source isInfinite(): Booleanpositive or negative infinity source isFinite(): Booleanneither infinite nor NaN source isInteger(): Booleanfinite with no fractional part source min(other: Self): Selfthe smaller of the two - NaN when either is source max(other: Self): Selfthe larger of the two - NaN when either is source clamp(range: Range<Self>): Selfself kept within range source approxEquals(other: Self, tolerance: Self := Self.epsilon()): Boolean|a - b| <= tolerance source ulpDistance(other: Self): U256?representable values between the two (0.0 and -0.0 are 0 apart) - undefined for NaN source floor(): Selflargest integral value <= self source ceil(): Selfsmallest integral value >= self source round(): Selfhalf away from zero source roundHalfEven(): Selfnearest integral value, ties to even source truncate(): Selfintegral part - toward zero source fraction(): Selfself - self.truncate() source roundTo(digits: U8): Selfdecimal places source sqrt(): Selfsquare root - NaN below zero source cbrt(): Selfcube root source exp(): Selfe raised to self source ln(): Selfnatural logarithm source log(base: Self): Selflogarithm in base source log2(): Selfbase 2 logarithm source log10(): Selfbase 10 logarithm source hypot(other: Self): Selfsqrt(self² + other²), without overflow on the way source sin(): Selfsine, self in radians source cos(): Selfcosine, self in radians source tan(): Selftangent, self in radians source asin(): Selfarc sine, in radians source acos(): Selfarc cosine, in radians source atan(): Selfarc tangent, in radians source atan2(x: Self): Selfself is y source sinh(): Selfhyperbolic sine source cosh(): Selfhyperbolic cosine source tanh(): Selfhyperbolic tangent source toRadians(): Selfdegrees to radians source toDegrees(): Selfradians to degrees source lerp(to: Self, t: Self): Selfself + (to - self) * t - self at t = 0, to at t = 1 source toString(precision: U8?): StringToString, with optional fixed decimals source toInteger(): CastError ! Integer`as Integer` - toward zero; NaN, infinity and out of range are a CastError source toBits(): Bitsraw IEEE-754 bits - Bits is U16 for F16, U32 for F32, U64 for F64 source #floatA binary floating-point number - an alias for F64.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Castable, Default, Copy
An alias - has every member of F64.
F16 F32 F64(52)F16 F32 F64 (and Number, Float through their aliases)
Implements Equatable (IEEE-754 equality, NaN != NaN), Hashable (agrees with ==), Comparable (NaN last, == values Equal), Bounded (finite values), ToString, FromString, Numeric, Castable<every numeric type>, Default (0.0), Copy
Functions
min(): Selfmost negative finite value source max(): Selflargest finite value source epsilon(): Selfdistance from 1 to the next value source infinity(): Selfpositive infinity - negate() for the negative one source nan(): Selfnot a number source pi(): Selfπ, the ratio of a circle's circumference to its diameter source e(): Selfe, the base of the natural logarithm source tau(): Selfτ = 2π, a full turn in radians source parse(text: String): ParseError ! Selfdecimal or scientific notation, "inf", "-inf", "nan" - correctly rounded source fromBits(bits: Bits): Selfthe value raw IEEE-754 bits hold - toBits the other way source Methods
abs(): Selfvalue without its sign source sign(): Self-1.0 | 0.0 | 1.0 (NaN for NaN) source isNaN(): BooleanNaN - the one value != itself source isInfinite(): Booleanpositive or negative infinity source isFinite(): Booleanneither infinite nor NaN source isInteger(): Booleanfinite with no fractional part source min(other: Self): Selfthe smaller of the two - NaN when either is source max(other: Self): Selfthe larger of the two - NaN when either is source clamp(range: Range<Self>): Selfself kept within range source approxEquals(other: Self, tolerance: Self := Self.epsilon()): Boolean|a - b| <= tolerance source ulpDistance(other: Self): U256?representable values between the two (0.0 and -0.0 are 0 apart) - undefined for NaN source floor(): Selflargest integral value <= self source ceil(): Selfsmallest integral value >= self source round(): Selfhalf away from zero source roundHalfEven(): Selfnearest integral value, ties to even source truncate(): Selfintegral part - toward zero source fraction(): Selfself - self.truncate() source roundTo(digits: U8): Selfdecimal places source sqrt(): Selfsquare root - NaN below zero source cbrt(): Selfcube root source exp(): Selfe raised to self source ln(): Selfnatural logarithm source log(base: Self): Selflogarithm in base source log2(): Selfbase 2 logarithm source log10(): Selfbase 10 logarithm source hypot(other: Self): Selfsqrt(self² + other²), without overflow on the way source sin(): Selfsine, self in radians source cos(): Selfcosine, self in radians source tan(): Selftangent, self in radians source asin(): Selfarc sine, in radians source acos(): Selfarc cosine, in radians source atan(): Selfarc tangent, in radians source atan2(x: Self): Selfself is y source sinh(): Selfhyperbolic sine source cosh(): Selfhyperbolic cosine source tanh(): Selfhyperbolic tangent source toRadians(): Selfdegrees to radians source toDegrees(): Selfradians to degrees source lerp(to: Self, t: Self): Selfself + (to - self) * t - self at t = 0, to at t = 1 source toString(precision: U8?): StringToString, with optional fixed decimals source toInteger(): CastError ! Integer`as Integer` - toward zero; NaN, infinity and out of range are a CastError source toBits(): Bitsraw IEEE-754 bits - Bits is U16 for F16, U32 for F32, U64 for F64 source #f16A 16-bit (half precision) float - about 3 significant digits, up to 65504. For GPU buffers and data stored in bulk, not for calculating in.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Castable, Default, Copy
F16 F32 F64(52)F16 F32 F64 (and Number, Float through their aliases)
Implements Equatable (IEEE-754 equality, NaN != NaN), Hashable (agrees with ==), Comparable (NaN last, == values Equal), Bounded (finite values), ToString, FromString, Numeric, Castable<every numeric type>, Default (0.0), Copy
Functions
min(): Selfmost negative finite value source max(): Selflargest finite value source epsilon(): Selfdistance from 1 to the next value source infinity(): Selfpositive infinity - negate() for the negative one source nan(): Selfnot a number source pi(): Selfπ, the ratio of a circle's circumference to its diameter source e(): Selfe, the base of the natural logarithm source tau(): Selfτ = 2π, a full turn in radians source parse(text: String): ParseError ! Selfdecimal or scientific notation, "inf", "-inf", "nan" - correctly rounded source fromBits(bits: Bits): Selfthe value raw IEEE-754 bits hold - toBits the other way source Methods
abs(): Selfvalue without its sign source sign(): Self-1.0 | 0.0 | 1.0 (NaN for NaN) source isNaN(): BooleanNaN - the one value != itself source isInfinite(): Booleanpositive or negative infinity source isFinite(): Booleanneither infinite nor NaN source isInteger(): Booleanfinite with no fractional part source min(other: Self): Selfthe smaller of the two - NaN when either is source max(other: Self): Selfthe larger of the two - NaN when either is source clamp(range: Range<Self>): Selfself kept within range source approxEquals(other: Self, tolerance: Self := Self.epsilon()): Boolean|a - b| <= tolerance source ulpDistance(other: Self): U256?representable values between the two (0.0 and -0.0 are 0 apart) - undefined for NaN source floor(): Selflargest integral value <= self source ceil(): Selfsmallest integral value >= self source round(): Selfhalf away from zero source roundHalfEven(): Selfnearest integral value, ties to even source truncate(): Selfintegral part - toward zero source fraction(): Selfself - self.truncate() source roundTo(digits: U8): Selfdecimal places source sqrt(): Selfsquare root - NaN below zero source cbrt(): Selfcube root source exp(): Selfe raised to self source ln(): Selfnatural logarithm source log(base: Self): Selflogarithm in base source log2(): Selfbase 2 logarithm source log10(): Selfbase 10 logarithm source hypot(other: Self): Selfsqrt(self² + other²), without overflow on the way source sin(): Selfsine, self in radians source cos(): Selfcosine, self in radians source tan(): Selftangent, self in radians source asin(): Selfarc sine, in radians source acos(): Selfarc cosine, in radians source atan(): Selfarc tangent, in radians source atan2(x: Self): Selfself is y source sinh(): Selfhyperbolic sine source cosh(): Selfhyperbolic cosine source tanh(): Selfhyperbolic tangent source toRadians(): Selfdegrees to radians source toDegrees(): Selfradians to degrees source lerp(to: Self, t: Self): Selfself + (to - self) * t - self at t = 0, to at t = 1 source toString(precision: U8?): StringToString, with optional fixed decimals source toInteger(): CastError ! Integer`as Integer` - toward zero; NaN, infinity and out of range are a CastError source toBits(): Bitsraw IEEE-754 bits - Bits is U16 for F16, U32 for F32, U64 for F64 source #f32A 32-bit float.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Castable, Default, Copy
F16 F32 F64(52)F16 F32 F64 (and Number, Float through their aliases)
Implements Equatable (IEEE-754 equality, NaN != NaN), Hashable (agrees with ==), Comparable (NaN last, == values Equal), Bounded (finite values), ToString, FromString, Numeric, Castable<every numeric type>, Default (0.0), Copy
Functions
min(): Selfmost negative finite value source max(): Selflargest finite value source epsilon(): Selfdistance from 1 to the next value source infinity(): Selfpositive infinity - negate() for the negative one source nan(): Selfnot a number source pi(): Selfπ, the ratio of a circle's circumference to its diameter source e(): Selfe, the base of the natural logarithm source tau(): Selfτ = 2π, a full turn in radians source parse(text: String): ParseError ! Selfdecimal or scientific notation, "inf", "-inf", "nan" - correctly rounded source fromBits(bits: Bits): Selfthe value raw IEEE-754 bits hold - toBits the other way source Methods
abs(): Selfvalue without its sign source sign(): Self-1.0 | 0.0 | 1.0 (NaN for NaN) source isNaN(): BooleanNaN - the one value != itself source isInfinite(): Booleanpositive or negative infinity source isFinite(): Booleanneither infinite nor NaN source isInteger(): Booleanfinite with no fractional part source min(other: Self): Selfthe smaller of the two - NaN when either is source max(other: Self): Selfthe larger of the two - NaN when either is source clamp(range: Range<Self>): Selfself kept within range source approxEquals(other: Self, tolerance: Self := Self.epsilon()): Boolean|a - b| <= tolerance source ulpDistance(other: Self): U256?representable values between the two (0.0 and -0.0 are 0 apart) - undefined for NaN source floor(): Selflargest integral value <= self source ceil(): Selfsmallest integral value >= self source round(): Selfhalf away from zero source roundHalfEven(): Selfnearest integral value, ties to even source truncate(): Selfintegral part - toward zero source fraction(): Selfself - self.truncate() source roundTo(digits: U8): Selfdecimal places source sqrt(): Selfsquare root - NaN below zero source cbrt(): Selfcube root source exp(): Selfe raised to self source ln(): Selfnatural logarithm source log(base: Self): Selflogarithm in base source log2(): Selfbase 2 logarithm source log10(): Selfbase 10 logarithm source hypot(other: Self): Selfsqrt(self² + other²), without overflow on the way source sin(): Selfsine, self in radians source cos(): Selfcosine, self in radians source tan(): Selftangent, self in radians source asin(): Selfarc sine, in radians source acos(): Selfarc cosine, in radians source atan(): Selfarc tangent, in radians source atan2(x: Self): Selfself is y source sinh(): Selfhyperbolic sine source cosh(): Selfhyperbolic cosine source tanh(): Selfhyperbolic tangent source toRadians(): Selfdegrees to radians source toDegrees(): Selfradians to degrees source lerp(to: Self, t: Self): Selfself + (to - self) * t - self at t = 0, to at t = 1 source toString(precision: U8?): StringToString, with optional fixed decimals source toInteger(): CastError ! Integer`as Integer` - toward zero; NaN, infinity and out of range are a CastError source toBits(): Bitsraw IEEE-754 bits - Bits is U16 for F16, U32 for F32, U64 for F64 source #f64A 64-bit float.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Castable, Default, Copy
F16 F32 F64(52)F16 F32 F64 (and Number, Float through their aliases)
Implements Equatable (IEEE-754 equality, NaN != NaN), Hashable (agrees with ==), Comparable (NaN last, == values Equal), Bounded (finite values), ToString, FromString, Numeric, Castable<every numeric type>, Default (0.0), Copy
Functions
min(): Selfmost negative finite value source max(): Selflargest finite value source epsilon(): Selfdistance from 1 to the next value source infinity(): Selfpositive infinity - negate() for the negative one source nan(): Selfnot a number source pi(): Selfπ, the ratio of a circle's circumference to its diameter source e(): Selfe, the base of the natural logarithm source tau(): Selfτ = 2π, a full turn in radians source parse(text: String): ParseError ! Selfdecimal or scientific notation, "inf", "-inf", "nan" - correctly rounded source fromBits(bits: Bits): Selfthe value raw IEEE-754 bits hold - toBits the other way source Methods
abs(): Selfvalue without its sign source sign(): Self-1.0 | 0.0 | 1.0 (NaN for NaN) source isNaN(): BooleanNaN - the one value != itself source isInfinite(): Booleanpositive or negative infinity source isFinite(): Booleanneither infinite nor NaN source isInteger(): Booleanfinite with no fractional part source min(other: Self): Selfthe smaller of the two - NaN when either is source max(other: Self): Selfthe larger of the two - NaN when either is source clamp(range: Range<Self>): Selfself kept within range source approxEquals(other: Self, tolerance: Self := Self.epsilon()): Boolean|a - b| <= tolerance source ulpDistance(other: Self): U256?representable values between the two (0.0 and -0.0 are 0 apart) - undefined for NaN source floor(): Selflargest integral value <= self source ceil(): Selfsmallest integral value >= self source round(): Selfhalf away from zero source roundHalfEven(): Selfnearest integral value, ties to even source truncate(): Selfintegral part - toward zero source fraction(): Selfself - self.truncate() source roundTo(digits: U8): Selfdecimal places source sqrt(): Selfsquare root - NaN below zero source cbrt(): Selfcube root source exp(): Selfe raised to self source ln(): Selfnatural logarithm source log(base: Self): Selflogarithm in base source log2(): Selfbase 2 logarithm source log10(): Selfbase 10 logarithm source hypot(other: Self): Selfsqrt(self² + other²), without overflow on the way source sin(): Selfsine, self in radians source cos(): Selfcosine, self in radians source tan(): Selftangent, self in radians source asin(): Selfarc sine, in radians source acos(): Selfarc cosine, in radians source atan(): Selfarc tangent, in radians source atan2(x: Self): Selfself is y source sinh(): Selfhyperbolic sine source cosh(): Selfhyperbolic cosine source tanh(): Selfhyperbolic tangent source toRadians(): Selfdegrees to radians source toDegrees(): Selfradians to degrees source lerp(to: Self, t: Self): Selfself + (to - self) * t - self at t = 0, to at t = 1 source toString(precision: U8?): StringToString, with optional fixed decimals source toInteger(): CastError ! Integer`as Integer` - toward zero; NaN, infinity and out of range are a CastError source toBits(): Bitsraw IEEE-754 bits - Bits is U16 for F16, U32 for F32, U64 for F64 source #complexA number with a real and an imaginary part - an alias for C64.
Sourceown members, Equatable, Hashable, ToString, FromString, Numeric, Scalable, Castable, Default, Copy
An alias - has every member of C64.
C32 C64(18)C32 C64 (and Complex through its alias) - parts are F32, F64 respectively (Part below)
Implements Equatable (part by part), Hashable, ToString, FromString, Numeric, Scalable<Part>, Castable<every other complex type>, Default (0), Copy - not Comparable
Functions
new(real: Part, imaginary: Part): Selfreal + imaginary·i source fromPolar(magnitude: Part, angle: Part): Selfmagnitude·(cos angle + i·sin angle) - angle in radians source i(): Selfthe imaginary unit source parse(text: String): ParseError ! Self"1+2i" source Methods
real(): Partreal part source imaginary(): Partimaginary part source magnitude(): Part|z| source magnitudeSquared(): Part|z|² - no square root source argument(): Partangle in radians source toPolar(): (Part, Part)(magnitude, angle) source conjugate(): Selfreal - imaginary·i source reciprocal(): Self1 / z source sqrt(): Selfprincipal square root source exp(): Selfe raised to self source ln(): Selfprincipal natural logarithm source isReal(): Booleanimaginary part is 0 source isNaN(): Booleaneither part is NaN source approxEquals(other: Self, tolerance: Part := Part.epsilon()): Booleanevery part within tolerance of other's source #c32A 32-bit complex number.
Sourceown members, Equatable, Hashable, ToString, FromString, Numeric, Scalable, Castable, Default, Copy
C32 C64(18)C32 C64 (and Complex through its alias) - parts are F32, F64 respectively (Part below)
Implements Equatable (part by part), Hashable, ToString, FromString, Numeric, Scalable<Part>, Castable<every other complex type>, Default (0), Copy - not Comparable
Functions
new(real: Part, imaginary: Part): Selfreal + imaginary·i source fromPolar(magnitude: Part, angle: Part): Selfmagnitude·(cos angle + i·sin angle) - angle in radians source i(): Selfthe imaginary unit source parse(text: String): ParseError ! Self"1+2i" source Methods
real(): Partreal part source imaginary(): Partimaginary part source magnitude(): Part|z| source magnitudeSquared(): Part|z|² - no square root source argument(): Partangle in radians source toPolar(): (Part, Part)(magnitude, angle) source conjugate(): Selfreal - imaginary·i source reciprocal(): Self1 / z source sqrt(): Selfprincipal square root source exp(): Selfe raised to self source ln(): Selfprincipal natural logarithm source isReal(): Booleanimaginary part is 0 source isNaN(): Booleaneither part is NaN source approxEquals(other: Self, tolerance: Part := Part.epsilon()): Booleanevery part within tolerance of other's source #c64A 64-bit complex number.
Sourceown members, Equatable, Hashable, ToString, FromString, Numeric, Scalable, Castable, Default, Copy
C32 C64(18)C32 C64 (and Complex through its alias) - parts are F32, F64 respectively (Part below)
Implements Equatable (part by part), Hashable, ToString, FromString, Numeric, Scalable<Part>, Castable<every other complex type>, Default (0), Copy - not Comparable
Functions
new(real: Part, imaginary: Part): Selfreal + imaginary·i source fromPolar(magnitude: Part, angle: Part): Selfmagnitude·(cos angle + i·sin angle) - angle in radians source i(): Selfthe imaginary unit source parse(text: String): ParseError ! Self"1+2i" source Methods
real(): Partreal part source imaginary(): Partimaginary part source magnitude(): Part|z| source magnitudeSquared(): Part|z|² - no square root source argument(): Partangle in radians source toPolar(): (Part, Part)(magnitude, angle) source conjugate(): Selfreal - imaginary·i source reciprocal(): Self1 / z source sqrt(): Selfprincipal square root source exp(): Selfe raised to self source ln(): Selfprincipal natural logarithm source isReal(): Booleanimaginary part is 0 source isNaN(): Booleaneither part is NaN source approxEquals(other: Self, tolerance: Part := Part.epsilon()): Booleanevery part within tolerance of other's source #quaternionA four-part number (one real, three imaginary parts), e.g. for 3D rotations - an alias for Q64.
Sourceown members, Equatable, Hashable, ToString, FromString, Numeric, Scalable, Castable, Default, Copy
An alias - has every member of Q64.
Q32 Q64(22)Q32 Q64 (and Quaternion through its alias) - parts are F32, F64 respectively (Part below)
Implements Equatable (part by part), Hashable, ToString, FromString, Numeric (multiply isn't commutative), Scalable<Part>, Castable<every other quaternion type>, Default (0), Copy - not Comparable
Functions
new(w: Part, x: Part, y: Part, z: Part): Selfw + xi + yj + zk source identity(): Self1 + 0i + 0j + 0k source fromAxisAngle(axis: Vector<Part, 3>, angle: Part): Selfrotation by angle (radians) around axis - a unit quaternion source fromEuler(roll: Part, pitch: Part, yaw: Part): Selfrotation from Euler angles in radians - roll about x, pitch about y, yaw about z source parse(text: String): ParseError ! Self"1+2i+3j+4k" source Methods
w(): Partreal part source x(): Parti part source y(): Partj part source z(): Partk part source scalar(): Partw source vector(): Vector<Part, 3>(x, y, z) source magnitude(): Partlength - sqrt(w² + x² + y² + z²) source normalize(): Selfsame direction, magnitude 1 source conjugate(): Selfw - xi - yj - zk source inverse(): Selfmultiplicative inverse - conjugate / magnitude² source dot(other: Self): Partsum of the parts' products source rotate(point: Vector<Part, 3>): Vector<Part, 3>point rotated by self (a unit quaternion) source slerp(to: Self, t: Part): Selfspherical interpolation - self at t = 0, to at t = 1 source toAxisAngle(): (Vector<Part, 3>, Part)the rotation's axis and angle in radians source toEuler(): (Part, Part, Part)(roll, pitch, yaw) source toMatrix(): Matrix<Part, 3, 3>the same rotation as a matrix source approxEquals(other: Self, tolerance: Part = Part.epsilon()): Booleanevery part within tolerance of other's source #q32A 32-bit quaternion.
Sourceown members, Equatable, Hashable, ToString, FromString, Numeric, Scalable, Castable, Default, Copy
Q32 Q64(22)Q32 Q64 (and Quaternion through its alias) - parts are F32, F64 respectively (Part below)
Implements Equatable (part by part), Hashable, ToString, FromString, Numeric (multiply isn't commutative), Scalable<Part>, Castable<every other quaternion type>, Default (0), Copy - not Comparable
Functions
new(w: Part, x: Part, y: Part, z: Part): Selfw + xi + yj + zk source identity(): Self1 + 0i + 0j + 0k source fromAxisAngle(axis: Vector<Part, 3>, angle: Part): Selfrotation by angle (radians) around axis - a unit quaternion source fromEuler(roll: Part, pitch: Part, yaw: Part): Selfrotation from Euler angles in radians - roll about x, pitch about y, yaw about z source parse(text: String): ParseError ! Self"1+2i+3j+4k" source Methods
w(): Partreal part source x(): Parti part source y(): Partj part source z(): Partk part source scalar(): Partw source vector(): Vector<Part, 3>(x, y, z) source magnitude(): Partlength - sqrt(w² + x² + y² + z²) source normalize(): Selfsame direction, magnitude 1 source conjugate(): Selfw - xi - yj - zk source inverse(): Selfmultiplicative inverse - conjugate / magnitude² source dot(other: Self): Partsum of the parts' products source rotate(point: Vector<Part, 3>): Vector<Part, 3>point rotated by self (a unit quaternion) source slerp(to: Self, t: Part): Selfspherical interpolation - self at t = 0, to at t = 1 source toAxisAngle(): (Vector<Part, 3>, Part)the rotation's axis and angle in radians source toEuler(): (Part, Part, Part)(roll, pitch, yaw) source toMatrix(): Matrix<Part, 3, 3>the same rotation as a matrix source approxEquals(other: Self, tolerance: Part = Part.epsilon()): Booleanevery part within tolerance of other's source #q64A 64-bit quaternion.
Sourceown members, Equatable, Hashable, ToString, FromString, Numeric, Scalable, Castable, Default, Copy
Q32 Q64(22)Q32 Q64 (and Quaternion through its alias) - parts are F32, F64 respectively (Part below)
Implements Equatable (part by part), Hashable, ToString, FromString, Numeric (multiply isn't commutative), Scalable<Part>, Castable<every other quaternion type>, Default (0), Copy - not Comparable
Functions
new(w: Part, x: Part, y: Part, z: Part): Selfw + xi + yj + zk source identity(): Self1 + 0i + 0j + 0k source fromAxisAngle(axis: Vector<Part, 3>, angle: Part): Selfrotation by angle (radians) around axis - a unit quaternion source fromEuler(roll: Part, pitch: Part, yaw: Part): Selfrotation from Euler angles in radians - roll about x, pitch about y, yaw about z source parse(text: String): ParseError ! Self"1+2i+3j+4k" source Methods
w(): Partreal part source x(): Parti part source y(): Partj part source z(): Partk part source scalar(): Partw source vector(): Vector<Part, 3>(x, y, z) source magnitude(): Partlength - sqrt(w² + x² + y² + z²) source normalize(): Selfsame direction, magnitude 1 source conjugate(): Selfw - xi - yj - zk source inverse(): Selfmultiplicative inverse - conjugate / magnitude² source dot(other: Self): Partsum of the parts' products source rotate(point: Vector<Part, 3>): Vector<Part, 3>point rotated by self (a unit quaternion) source slerp(to: Self, t: Part): Selfspherical interpolation - self at t = 0, to at t = 1 source toAxisAngle(): (Vector<Part, 3>, Part)the rotation's axis and angle in radians source toEuler(): (Part, Part, Part)(roll, pitch, yaw) source toMatrix(): Matrix<Part, 3, 3>the same rotation as a matrix source approxEquals(other: Self, tolerance: Part = Part.epsilon()): Booleanevery part within tolerance of other's source #decimalAn exact decimal number - 0.1 + 0.2 is 0.3 - for money and anything else counted in tenths or hundredths. It keeps its places: + and - keep the larger side's, * adds them up, and / keeps at least 16; round and divideTo pick the places and a RoundingMode.
Sourceown members, Numeric, Comparable, Equatable, Hashable, ToString, FromString, Default, Copy
an exact decimal number: a whole coefficient and how many of its digits are after the point - 12.50 is
1250 with 2 places. + and - keep the larger side's places and * adds them up, so nothing is ever
rounded unasked; / keeps at least 16 places, rounded half to even (divideTo picks the places and the
rounding). The coefficient is an S128 - up to 38 digits; a result needing more overflows like an S128
Implements Equatable (the same number, 12.50 == 12.5), Hashable, Comparable, ToString ("12.50", its places kept), FromString, Numeric (power takes a whole exponent), Default (0), Copy
Functions
of(value: S64): Decimalthe whole number source fromParts(coefficient: S128, places: U8): Decimalcoefficient with places digits after the point - (1250, 2) is 12.50 source fromF64(value: F64, places: U8): ParseError ! Decimalvalue rounded to places, half to even - a ParseError for NaN and infinities source parse(text: String): ParseError ! Decimal"12.50", "-3", "1_000.5", "1.5e3" - the places written are kept source Methods
coefficient(): S128the digits as a whole number - 1250 for 12.50 source places(): U8how many digits are after the point - 2 for 12.50 source round(places: U8, mode: RoundingMode := RoundingMode.HalfEven): Decimalto places digits after the point - more places pad with zeros source divideTo(other: Decimal, places: U8, mode: RoundingMode := RoundingMode.HalfEven): Decimalself / other to places digits source normalize(): Decimaltrailing zeros dropped - 12.50 is 12.5 source abs(): Decimalwithout its sign source sign(): S8-1, 0 or 1 source isZero(): Boolean== 0 source isNegative(): Boolean< 0 source isWhole(): Booleannothing after the point but zeros source toF64(): F64the nearest F64 source toS64(): OverflowError ! S64the whole part, the rest dropped source #roundingmodeHow a Decimal drops the digits it can't keep - HalfEven (banker's rounding) unless you say otherwise.
Sourceown members, Equatable, Hashable, ToString, Copy
how Decimal drops the digits it can't keep - HalfEven (to the nearest, a tie to the even digit) unless
told otherwise; Up and Down go away from and toward zero, Ceiling and Floor toward the larger and smaller
Implements Equatable, Hashable, ToString ("HalfEven"), Copy
#bigintegerA whole number of any size - it grows as it needs, so +, -, * and ^ never overflow. /, // and % round the way the fixed integers do. Make one with BigInteger.of, BigInteger.parse or any integer's toBigInteger(), and get a fixed integer back with toInteger<Target>().
Sourceown members, Numeric, Comparable, Equatable, Hashable, ToString, FromString, Default
a whole number of any size: it grows as it needs, so + - * and ^ never overflow. / rounds toward zero
and // down, and % takes self's sign, as with the fixed integers; dividing by zero panics. It's
slower than a fixed integer and has no bit operations - for results that may not fit an S128 or a U256
Implements Equatable, Hashable, Comparable, ToString, FromString, Numeric (power takes an exponent of 0 or more), Default (0)
Functions
of(value: S64): BigIntegerthe same number - any integer type's toBigInteger() too source parse(text: String): ParseError ! BigIntegerdecimal digits, optional sign, _ separators allowed source Methods
abs(): BigIntegerwithout its sign source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: BigInteger): BigIntegerthe smaller of the two source max(other: BigInteger): BigIntegerthe larger of the two source pow(exponent: U32): BigIntegerself raised to exponent source sqrt(): CastError ! BigIntegerfloor of the square root - a CastError below zero source gcd(other: BigInteger): BigIntegergreatest common divisor - 0 when both are 0 source lcm(other: BigInteger): BigIntegerleast common multiple - 0 when either is 0 source divMod(other: BigInteger): (BigInteger, BigInteger)(a // b, a % b) source modulo(other: BigInteger): BigIntegeralways the divisor's sign, unlike % source digitCount(): U64decimal digits, the sign not counted - 1 for 0 source toF64(): F64the nearest F64 - an infinity past F64.max() source toInteger<Target>(): OverflowError ! TargetTarget is any U* / S* - an OverflowError when it doesn't fit source #rationalAn exact fraction - a BigInteger numerator over a BigInteger denominator, always in lowest terms, so 1/3 + 1/6 is exactly 1/2. floor, ceil, round and toDecimal leave the exact world when you ask.
Sourceown members, Numeric, Comparable, Equatable, Hashable, ToString, FromString, Default
an exact fraction: a BigInteger numerator over a BigInteger denominator, always in lowest terms with the
denominator positive - 2/4 is 1/2, and 1/3 + 1/6 is exactly 1/2. Every operation is exact; ^ takes a
whole exponent, and dividing by zero panics
Implements Equatable (lowest terms, so 2/4 == 1/2), Hashable, Comparable, ToString ("1/3", "2" when whole), FromString, Numeric (power takes a whole exponent), Default (0)
Functions
of(numerator: S64, denominator: S64 := 1): Rationalnumerator / denominator in lowest terms - a zero denominator panics source fromParts(numerator: BigInteger, denominator: BigInteger): Rationalthe same, from BigIntegers source fromDecimal(value: Decimal): Rationalexactly - 0.75 is 3/4 source parse(text: String): ParseError ! Rational"1/3", "-6/4", "2", "0.75" source Methods
numerator(): BigIntegerthe top, in lowest terms - carries the sign source denominator(): BigIntegerthe bottom, in lowest terms - always positive source reciprocal(): Rational1 / self - zero panics source abs(): Rationalwithout its sign source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isNegative(): Boolean< 0 source isWhole(): Booleanthe denominator is 1 source floor(): BigIntegerthe whole number at or below source ceil(): BigIntegerthe whole number at or above source truncate(): BigIntegerthe whole part - toward zero source round(mode: RoundingMode := RoundingMode.HalfEven): BigIntegerto a whole number source toDecimal(places: U8, mode: RoundingMode := RoundingMode.HalfEven): OverflowError ! Decimalto places digits - 1/3 to 2 is 0.33 source toF64(): F64the nearest F64 source #quantityA number in a unit - Quantity<F64, Meter>.of(3.5), where the unit is one of the language's (each in #builtin.unit, by what it measures, brought out with type Meter ≔ #builtin.unit.length.Meter) or an empty struct of your own. The unit lives only in the type, so the checker keeps meters and seconds apart: +, - and comparisons work only within one unit, * and / scale by plain numbers, and between two quantities make the units that combine them - meters * meters is a Quantity<F64, Product<Meter, Meter>>, written Meter², meters / seconds a Per<Meter, Second>. Units that come to the same are one type - Product<Meter, Meter> is SquareMeter - and as or convert changes a quantity into another unit of what it measures. See Numbers.
Sourceown members, Castable, Scalable, Equatable, Hashable, Comparable, ToString, Copy
a number in a unit. A unit is a type - one of the units in types, reached through its group of
#builtin.unit and brought out with a type alias (`type Meter := #builtin.unit.length.Meter`, as the
examples here are), or the program's own: an empty struct, a base unit of its own, or one made of
others with @unit - and lives only in the type, so
the checker keeps quantities of different units apart. Units are compared by what they come to:
their base units, each to a power, a scale and an offset - Product<Meter, Meter> is SquareMeter,
Per<Joule, Second> is Watt, Per<SquareMeter, Meter> is Meter, Product<Second, Meter> is
Product<Meter, Second> - but Kilometer isn't Meter, its scale is 1000. + - and comparisons only
between quantities of one unit, * and / by a plain number, and * and / between two quantities (or
times and per) make the unit that combines them - a * b is in Product<A, B>, a / b in Per<A, B>,
and a plain number when the units cancel (2 Kilometer / 500 Meter is 4). A quantity changes into
another unit of the same dimension with as or convert - Quantity<F64, Kilometer>.of(1.5) as
Quantity<F64, Meter> is 1500 Meter, 20 Celsius as Fahrenheit 68 - keeping 12 significant digits,
past which is the scales' rounding, and an integer quantity's amount rounded to the nearest. Between dimensions (Meter into Second) it's an error. A unit is
written the way it's named - "Meter/Second", "Newton·Meter", and one times itself as its power -
Product<Meter, Meter>.of is "Meter²". In a generic function a unit parameter has no definition to
read - Quantity<F64, Unit>.of there is in Unit, a base unit
Implements Equatable, Hashable, Comparable, ToString ("3.5 Meter", "2 Meter/Second", "6 Newton·Meter", "4 Meter²"), Castable<Quantity of the same dimension>, Scalable<Type>, Copy
Functions
of(value: Type): Quantity<Type, Unit>value in Unit - Quantity<F64, Meter>.of(3.5) source Methods
value(): Typethe number, without its unit source unitName(): Stringhow its unit is written - "Meter/Second" source add(other: Quantity<Type, Unit>): Quantity<Type, Unit>a + b source subtract(other: Quantity<Type, Unit>): Quantity<Type, Unit>a - b source negate(): Quantity<Type, Unit>-a source ratio(other: Quantity<Type, Unit>): Typea / b - how many of other fit in self source times<Other>(other: Quantity<Type, Other>): Quantity<Type, Product<Unit, Other>>the product, in both units - force.times(distance), force * distance source per<Other>(other: Quantity<Type, Other>): Quantity<Type, Per<Unit, Other>>the quotient, in Unit per Other - distance.per(time), distance / time source convert<Target>(factor: Type? := undefined): Quantity<Type, Target>self in Target - kilometers.convert<Meter>() - where Target is a unit of the same dimension; with a factor, factor Targets making one Unit, between any units - steps.convert<Meter>(0.75) source #productThe unit a * b and Quantity.times give - Product<Newton, Meter>. A unit times itself is written as its power - Meter².
#perThe unit a / b and Quantity.per give - Per<Meter, Second>.
#meterA base unit of length - its own dimension. Written #builtin.unit.length.Meter.
#kilometerOne Kilometer is 1000 * Meter.
#centimeterOne Centimeter is 0.01 * Meter.
#millimeterOne Millimeter is 0.001 * Meter.
#micrometerOne Micrometer is 0.000001 * Meter.
#nanometerOne Nanometer is 0.000000001 * Meter.
#inchOne Inch is 0.0254 * Meter.
#footOne Foot is 12 * Inch.
#yardOne Yard is 3 * Foot.
#mileOne Mile is 1760 * Yard.
#nauticalmileOne NauticalMile is 1852 * Meter.
#kilogramA base unit of mass - its own dimension. Written #builtin.unit.mass.Kilogram.
#gramOne Gram is 0.001 * Kilogram.
#milligramOne Milligram is 0.001 * Gram.
#microgramOne Microgram is 0.000001 * Gram.
#tonneOne Tonne is 1000 * Kilogram.
#poundOne Pound is 0.45359237 * Kilogram.
#ounceOne Ounce is Pound / 16.
#stoneOne Stone is 14 * Pound.
#tonOne Ton is 2000 * Pound - the US short ton.
#secondA base unit of time - its own dimension. Written #builtin.unit.time.Second.
#millisecondOne Millisecond is 0.001 * Second.
#microsecondOne Microsecond is 0.000001 * Second.
#nanosecondOne Nanosecond is 0.000000001 * Second.
#minuteOne Minute is 60 * Second.
#hourOne Hour is 60 * Minute.
#dayOne Day is 24 * Hour.
#weekOne Week is 7 * Day.
#durationA length of time.
Sourceown members, Equatable, Hashable, Comparable, ToString, FromString, Numeric, Scalable, Default, Copy
signed span of time, nanosecond precision
Implements Equatable, Hashable, Comparable, ToString ("1h 2m 3.5s"), FromString, Numeric, Scalable<F64>, Default (zero), Copy
Functions
zero(): Durationno time source nanoseconds(count: S64): Durationcount nanoseconds source microseconds(count: S64): Durationcount microseconds source milliseconds(count: S64): Durationcount milliseconds source seconds(count: F64): Durationcount seconds source minutes(count: F64): Durationcount minutes source hours(count: F64): Durationcount hours source days(count: F64): Durationcount days of 24 hours source parse(text: String): ParseError ! Duration"1h30m", "250ms", ISO-8601 "PT1H30M" source Methods
toNanoseconds(): S128whole nanoseconds source toMilliseconds(): F64in milliseconds, fractional source toSeconds(): F64in seconds, fractional source toMinutes(): F64in minutes, fractional source toHours(): F64in hours, fractional source toDays(): F64in days of 24 hours, fractional source parts(): (days: S64, hours: U8, minutes: U8, seconds: U8, nanoseconds: U32)split into days down to nanoseconds source scale(factor: F64): Durationself times factor source abs(): Durationwithout its sign source isNegative(): Boolean< zero source isZero(): Boolean== zero source roundTo(unit: Duration): Durationnearest multiple of unit source toIsoString(): StringISO-8601 - "PT1H30M" source #instantA point in time - what &clock reads.
Sourceown members, ToString, Equatable, Hashable, Comparable, FromString, Copy
a point in time (UTC, nanosecond precision) - Instant - Instant is a Duration, Instant + Duration is an Instant
Implements Equatable, Hashable, Comparable, ToString (ISO-8601), FromString (ISO-8601 / RFC 3339), Copy
Functions
epoch(): Instant1970-01-01T00:00:00Z source fromUnixSeconds(seconds: F64): Instantseconds since the epoch source fromUnixMilliseconds(milliseconds: S64): Instantmilliseconds since the epoch source parse(text: String): ParseError ! InstantISO-8601 / RFC 3339 source Methods
add(duration: Duration): Instanta + b source subtract(duration: Duration): Instanta - b source since(earlier: Instant): Durationa - b source until(later: Instant): Durationlater - self source isBefore(other: Instant): Booleanearlier than other source isAfter(other: Instant): Booleanlater than other source toUnixSeconds(): F64seconds since the epoch, fractional source toUnixMilliseconds(): S64whole milliseconds since the epoch source truncate(unit: Duration): Instantfloor to a multiple of unit since epoch source format(pattern: String, offset: Duration := Duration.zero()): String"YYYY-MM-DD hh:mm:ss" source toDateTime(zone: TimeZone := &timeZone): DateTimethe wall-clock time in zone at self source toDate(zone: TimeZone := &timeZone): Datethe day it is in zone at self source #dateA day on the calendar - 2026-10-07 - with no time of day and no zone. Months add the way people expect: January 31st plus a month is February's last day.
Sourceown members, Equatable, Hashable, Comparable, ToString, FromString, Steppable, Copy
a day on the proleptic Gregorian calendar - no time of day, no zone. `format` patterns here and below
use YYYY MM DD (and hh mm ss SSS for times), the rest as written
Implements Equatable, Hashable, Comparable, ToString ("2026-10-07"), FromString ("2026-10-07"), Steppable (one day), Copy
Functions
of(year: S32, month: U8, day: U8): DateError ! Datea DateError for a day the month doesn't have source fromDays(days: S64): Datedays since 1970-01-01 source @reads(&clock, &timeZone)today(): Date&clock's day in &timeZone source parse(text: String): ParseError ! Date"2026-10-07" source Methods
year(): S322026 source month(): U81 to 12 source day(): U81 to 31 source weekday(): WeekdayMonday to Sunday source dayOfYear(): U161 to 366 source isLeapYear(): Booleanits year has a February 29th source daysInMonth(): U828 to 31 source addDays(days: S64): Datedays later - earlier when negative source addMonths(months: S64): Datemonths later, the day kept when the month has it, its last day otherwise - Jan 31 + 1 month is Feb 28 source addYears(years: S64): Dateyears later - Feb 29 becomes Feb 28 when that year has none source daysUntil(later: Date): S64how many days from self to later - negative when it's before source toDays(): S64days since 1970-01-01 source startOfMonth(): Datethe 1st of its month source endOfMonth(): Datethe last day of its month source at(time: TimeOfDay): DateTimetime on this day source format(pattern: String): String"DD.MM.YYYY" source #timeofdayA time on a clock - 09:30:00 - with no date and no zone.
Sourceown members, Equatable, Hashable, Comparable, ToString, FromString, Copy
a time on a clock, from midnight up to just before the next - no date, no zone
Implements Equatable, Hashable, Comparable, ToString ("09:30:00", "09:30:00.250" with a fraction), FromString ("09:30", "09:30:00.250"), Copy
Functions
of(hour: U8, minute: U8, second: U8 := 0, nanosecond: U32 := 0): DateError ! TimeOfDaya DateError past 23:59:59.999999999 source midnight(): TimeOfDay00:00:00 source noon(): TimeOfDay12:00:00 source parse(text: String): ParseError ! TimeOfDay"09:30", "09:30:15", "09:30:15.250" source Methods
hour(): U80 to 23 source minute(): U80 to 59 source second(): U80 to 59 source nanosecond(): U32within the second source sinceMidnight(): Durationhow long after midnight it is source add(duration: Duration): TimeOfDayduration later on the clock - wraps past midnight source format(pattern: String): String"hh:mm" source #datetimeA date and a time of day on a wall clock - what a calendar entry says - in no zone until toInstant puts it in one. A time skipped by a daylight-saving jump moves forward by the jump; one shown twice is the earlier.
Sourceown members, Equatable, Hashable, Comparable, ToString, FromString, Copy
a date and a time of day on a wall clock, in no zone - what a calendar entry says. toInstant puts it
in a zone; + and - with a Duration move the wall clock, ignoring what the zone's clocks do
Implements Equatable, Hashable, Comparable, ToString ("2026-10-07T09:30:00"), FromString ("2026-10-07T09:30:00", "2026-10-07 09:30"), Copy
Functions
of(date: Date, time: TimeOfDay): DateTimetime on date source @reads(&clock, &timeZone)now(): DateTime&clock's time in &timeZone source parse(text: String): ParseError ! DateTimeISO-8601 without a zone source Methods
date(): Dateits day source time(): TimeOfDayits time of day source add(duration: Duration): DateTimeduration later on the wall clock - a + b source subtract(duration: Duration): DateTimeduration earlier on the wall clock - a - b source since(earlier: DateTime): Durationhow far apart the two wall-clock times are source addDays(days: S64): DateTimethe same time, days later source addMonths(months: S64): DateTimethe same time, months later (see Date.addMonths) source toInstant(zone: TimeZone := &timeZone): Instantthe instant zone's clocks show self - a time skipped by a jump forward is moved forward by the jump, one shown twice is the earlier source format(pattern: String): String"YYYY-MM-DD hh:mm" source #timezoneHow far a place's clocks are from UTC at each instant - UTC, a fixed offset like +02:00, or a named zone like Europe/Warsaw, whose offset changes with daylight saving. Named zones come from the host: a JavaScript host knows them all, a WASI runtime none. &timeZone is the one local dates and times are in.
Sourceown members, Equatable, Hashable, ToString, FromString, Copy
how far a place's clocks are from UTC, at each instant - UTC itself, a fixed offset, or a named IANA
zone ("Europe/Warsaw") whose offset changes with daylight saving. Named zones come from the host: a
JavaScript host knows them all; a WASI runtime knows none, and named(...) is a DateError there
Implements Equatable, Hashable, ToString ("Europe/Warsaw", "UTC", "+02:00"), FromString, Copy
Functions
utc(): TimeZoneUTC - an offset of zero, always source fixed(offset: Duration): TimeZoneclocks offset ahead of UTC, always - "+02:00" source named(name: String): DateError ! TimeZonean IANA zone - a DateError for one the host doesn't know source host(): TimeZonethe host's own zone - &timeZone's default; UTC where the host has none source parse(text: String): ParseError ! TimeZone"UTC", "Z", "+02:00", "-05:30", or a zone's name source Methods
#weekdayA day of the week - what Date.weekday() gives.
Sourceown members, Equatable, Hashable, Comparable, ToString, Copy
a day of the week, Monday first - as ISO 8601 numbers them
Implements Equatable, Hashable, Comparable (Monday first), ToString ("Wednesday"), Copy
Methods
number(): U81 for Monday to 7 for Sunday source #ampereA base unit of electric current - its own dimension. Written #builtin.unit.current.Ampere.
#milliampereOne Milliampere is Ampere / 1000.
#kelvinA base unit of temperature - its own dimension. Written #builtin.unit.temperature.Kelvin.
#celsiusA degree Celsius - the size of a Kelvin, with its zero at 273.15 Kelvin: Quantity<F64, Celsius>.of(20.0) as Quantity<F64, Kelvin> is 293.15 Kelvin.
#fahrenheitA degree Fahrenheit - five ninths of a Kelvin, with its zero at 255.37... Kelvin: 20 Celsius is 68 Fahrenheit.
#moleA base unit of amount of substance - its own dimension. Written #builtin.unit.amount.Mole.
#millimoleOne Millimole is Mole / 1000.
#candelaA base unit of luminous intensity - its own dimension. Written #builtin.unit.light.Candela.
#lumenA candela in every steradian - steradians count as plain numbers, so a Lumen is a Candela.
#luxOne Lux is Lumen / Meter ^ 2.
#radianA base unit of angle - kept apart from plain numbers - its own dimension. Written #builtin.unit.angle.Radian.
#degreeOne Degree is 0.017453292519943295 * Radian.
#arcminuteOne Arcminute is Degree / 60.
#arcsecondOne Arcsecond is Arcminute / 60.
#turnOne Turn is 6.283185307179586 * Radian.
#bitA base unit of information - its own dimension. Written #builtin.unit.information.Bit.
#byteOne Byte is 8 * Bit.
#kilobitOne Kilobit is 1000 * Bit.
#megabitOne Megabit is 1000 * Kilobit.
#gigabitOne Gigabit is 1000 * Megabit.
#kilobyteOne Kilobyte is 1000 * Byte.
#megabyteOne Megabyte is 1000 * Kilobyte.
#gigabyteOne Gigabyte is 1000 * Megabyte.
#terabyteOne Terabyte is 1000 * Gigabyte.
#petabyteOne Petabyte is 1000 * Terabyte.
#kibibyteOne Kibibyte is 1024 * Byte.
#mebibyteOne Mebibyte is 1024 * Kibibyte.
#gibibyteOne Gibibyte is 1024 * Mebibyte.
#tebibyteOne Tebibyte is 1024 * Gibibyte.
#megabitpersecondOne MegabitPerSecond is Megabit / Second.
#squaremeterOne SquareMeter is Meter ^ 2.
#squarecentimeterOne SquareCentimeter is Centimeter ^ 2.
#squarekilometerOne SquareKilometer is Kilometer ^ 2.
#hectareOne Hectare is 10000 * SquareMeter.
#squareinchOne SquareInch is Inch ^ 2.
#squarefootOne SquareFoot is Foot ^ 2.
#squaremileOne SquareMile is Mile ^ 2.
#acreOne Acre is 4840 * Yard ^ 2.
#cubicmeterOne CubicMeter is Meter ^ 3.
#cubiccentimeterOne CubicCentimeter is Centimeter ^ 3.
#cubicfootOne CubicFoot is Foot ^ 3.
#literOne Liter is 0.001 * CubicMeter.
#milliliterOne Milliliter is 0.001 * Liter.
#gallonOne Gallon is 3.785411784 * Liter - the US gallon.
#quartOne Quart is Gallon / 4.
#pintOne Pint is Quart / 2.
#cupOne Cup is Pint / 2.
#fluidounceOne FluidOunce is Pint / 16.
#meterpersecondOne MeterPerSecond is Meter / Second.
#kilometerperhourOne KilometerPerHour is Kilometer / Hour.
#mileperhourOne MilePerHour is Mile / Hour.
#footpersecondOne FootPerSecond is Foot / Second.
#knotOne Knot is NauticalMile / Hour.
#meterpersecondsquaredOne MeterPerSecondSquared is Meter / Second ^ 2.
#standardgravityOne StandardGravity is 9.80665 * MeterPerSecondSquared.
#hertzOne Hertz is 1 / Second.
#kilohertzOne Kilohertz is 1000 * Hertz.
#megahertzOne Megahertz is 1000000 * Hertz.
#gigahertzOne Gigahertz is 1000000000 * Hertz.
#revolutionperminuteOne RevolutionPerMinute is Turn / Minute.
#newtonOne Newton is Kilogram * Meter / Second ^ 2.
#kilonewtonOne Kilonewton is 1000 * Newton.
#poundforceOne PoundForce is Pound * StandardGravity.
#pascalOne Pascal is Newton / Meter ^ 2.
#hectopascalOne Hectopascal is 100 * Pascal.
#kilopascalOne Kilopascal is 1000 * Pascal.
#megapascalOne Megapascal is 1000000 * Pascal.
#barOne Bar is 100000 * Pascal.
#millibarOne Millibar is Bar / 1000.
#atmosphereOne Atmosphere is 101325 * Pascal.
#poundpersquareinchOne PoundPerSquareInch is PoundForce / Inch ^ 2.
#millimeterofmercuryOne MillimeterOfMercury is 133.322387415 * Pascal.
#jouleOne Joule is Newton * Meter.
#kilojouleOne Kilojoule is 1000 * Joule.
#megajouleOne Megajoule is 1000000 * Joule.
#calorieOne Calorie is 4.184 * Joule.
#kilocalorieOne Kilocalorie is 1000 * Calorie.
#electronvoltOne Electronvolt is 1.602176634e-19 * Joule.
#britishthermalunitOne BritishThermalUnit is 1055.05585262 * Joule.
#watthourOne WattHour is Watt * Hour.
#kilowatthourOne KilowattHour is 1000 * WattHour.
#wattOne Watt is Joule / Second.
#milliwattOne Milliwatt is Watt / 1000.
#kilowattOne Kilowatt is 1000 * Watt.
#megawattOne Megawatt is 1000000 * Watt.
#gigawattOne Gigawatt is 1000000000 * Watt.
#horsepowerOne Horsepower is 745.69987158227022 * Watt.
#coulombOne Coulomb is Ampere * Second.
#amperehourOne AmpereHour is Ampere * Hour.
#milliamperehourOne MilliampereHour is Milliampere * Hour.
#voltOne Volt is Watt / Ampere.
#millivoltOne Millivolt is Volt / 1000.
#kilovoltOne Kilovolt is 1000 * Volt.
#ohmOne Ohm is Volt / Ampere.
#kiloohmOne Kiloohm is 1000 * Ohm.
#megaohmOne Megaohm is 1000000 * Ohm.
#siemensOne Siemens is Ampere / Volt.
#faradOne Farad is Coulomb / Volt.
#microfaradOne Microfarad is Farad / 1000000.
#nanofaradOne Nanofarad is Farad / 1000000000.
#picofaradOne Picofarad is Farad / 1000000000000.
#henryOne Henry is Weber / Ampere.
#weberOne Weber is Volt * Second.
#teslaOne Tesla is Weber / Meter ^ 2.
#molarOne Molar is Mole / Liter.
#u8An 8-bit unsigned integer: 0 to 2^8 - 1.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Bitwise, Steppable, Castable, Default, Copy
U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256(51)U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256 (and Integer, UnsignedInteger, SignedInteger through their aliases)
+ - * // ^ and `as` give an OverflowError for a result that doesn't fit; +% -% *% wrap around and
+| -| *| fill up to min() / max() instead (the wrapping / saturating methods)
Implements Equatable, Hashable, Comparable, Bounded, ToString, FromString (radix 10), Numeric, Bitwise, Steppable, Castable<every numeric type>, Default (0), Copy
Functions
min(): Selfsmallest value source max(): Selflargest value source bits(): U168, 16, 32, 64, 128, 256 source parse(text: String, radix: U8 := 10): ParseError ! Selfin the given radix (2 to 36), optional sign, _ separators allowed source fromBytes(bytes: Bytes): ParseError ! Selflittle-endian, exactly bits() / 8 bytes source Methods
abs(): SelfS*.min().abs() is an OverflowError source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: Self): Selfthe smaller of the two source max(other: Self): Selfthe larger of the two source clamp(range: Range<Self>): Selfself kept within range source pow(exponent: U32): Selfself raised to exponent - an OverflowError when it doesn't fit source sqrt(): CastError ! Selffloor of the square root - a CastError below zero source gcd(other: Self): Selfgreatest common divisor - 0 when both are 0 source lcm(other: Self): Selfleast common multiple - 0 when either is 0 source divMod(other: Self): (Self, Self)(a // b, a % b) source modulo(other: Self): Selfalways the divisor's sign, unlike % source checkedAdd(other: Self): OverflowError ! Selfa + b - the OverflowError as a value to handle source checkedSubtract(other: Self): OverflowError ! Selfa - b - the OverflowError as a value to handle source checkedMultiply(other: Self): OverflowError ! Selfa * b - the OverflowError as a value to handle source wrappingAdd(other: Self): Selfa +% b source wrappingSubtract(other: Self): Selfa -% b source wrappingMultiply(other: Self): Selfa *% b source saturatingAdd(other: Self): Selfa +| b source saturatingSubtract(other: Self): Selfa -| b source saturatingMultiply(other: Self): Selfa *| b source bor(other: Self): Selfa bor b source bxor(other: Self): Selfa bxor b source band(other: Self): Selfa band b source bnot(): Self~a source shl(count: U64): Selfa shl b source shr(count: U64): Selfa shr b (arithmetic for S*, logical for U*) source rotateLeft(count: U8): Selfbits shifted left, those falling off the top coming back at the bottom source rotateRight(count: U8): Selfbits shifted right, those falling off the bottom coming back at the top source countOnes(): U8bits set source countZeros(): U8bits clear source leadingZeros(): U8clear bits above the highest set one - bits() when zero source trailingZeros(): U8clear bits below the lowest set one - bits() when zero source isPowerOfTwo(): Booleanexactly one bit set source bit(index: U8): Booleanbit index is set - 0 the least significant source withBit(index: U8, value: Boolean): Selfself with bit index set or cleared source toString(radix: U8 := 10): StringToString, with an optional radix source toBytes(): Byteslittle-endian source toFloat(): Floatnearest F64 - `as Float` source toBigInteger(): BigIntegerthe same number, as a BigInteger source toCodepoint(): CastError ! Codepointthe codepoint with this value - a CastError for surrogates, negatives and above 0x10FFFF source checkedCast<Target>(): CastError ! Target`as`, with a CastError where `as` gives an OverflowError source #u16A 16-bit unsigned integer: 0 to 2^16 - 1.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Bitwise, Steppable, Castable, Default, Copy
U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256(51)U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256 (and Integer, UnsignedInteger, SignedInteger through their aliases)
+ - * // ^ and `as` give an OverflowError for a result that doesn't fit; +% -% *% wrap around and
+| -| *| fill up to min() / max() instead (the wrapping / saturating methods)
Implements Equatable, Hashable, Comparable, Bounded, ToString, FromString (radix 10), Numeric, Bitwise, Steppable, Castable<every numeric type>, Default (0), Copy
Functions
min(): Selfsmallest value source max(): Selflargest value source bits(): U168, 16, 32, 64, 128, 256 source parse(text: String, radix: U8 := 10): ParseError ! Selfin the given radix (2 to 36), optional sign, _ separators allowed source fromBytes(bytes: Bytes): ParseError ! Selflittle-endian, exactly bits() / 8 bytes source Methods
abs(): SelfS*.min().abs() is an OverflowError source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: Self): Selfthe smaller of the two source max(other: Self): Selfthe larger of the two source clamp(range: Range<Self>): Selfself kept within range source pow(exponent: U32): Selfself raised to exponent - an OverflowError when it doesn't fit source sqrt(): CastError ! Selffloor of the square root - a CastError below zero source gcd(other: Self): Selfgreatest common divisor - 0 when both are 0 source lcm(other: Self): Selfleast common multiple - 0 when either is 0 source divMod(other: Self): (Self, Self)(a // b, a % b) source modulo(other: Self): Selfalways the divisor's sign, unlike % source checkedAdd(other: Self): OverflowError ! Selfa + b - the OverflowError as a value to handle source checkedSubtract(other: Self): OverflowError ! Selfa - b - the OverflowError as a value to handle source checkedMultiply(other: Self): OverflowError ! Selfa * b - the OverflowError as a value to handle source wrappingAdd(other: Self): Selfa +% b source wrappingSubtract(other: Self): Selfa -% b source wrappingMultiply(other: Self): Selfa *% b source saturatingAdd(other: Self): Selfa +| b source saturatingSubtract(other: Self): Selfa -| b source saturatingMultiply(other: Self): Selfa *| b source bor(other: Self): Selfa bor b source bxor(other: Self): Selfa bxor b source band(other: Self): Selfa band b source bnot(): Self~a source shl(count: U64): Selfa shl b source shr(count: U64): Selfa shr b (arithmetic for S*, logical for U*) source rotateLeft(count: U8): Selfbits shifted left, those falling off the top coming back at the bottom source rotateRight(count: U8): Selfbits shifted right, those falling off the bottom coming back at the top source countOnes(): U8bits set source countZeros(): U8bits clear source leadingZeros(): U8clear bits above the highest set one - bits() when zero source trailingZeros(): U8clear bits below the lowest set one - bits() when zero source isPowerOfTwo(): Booleanexactly one bit set source bit(index: U8): Booleanbit index is set - 0 the least significant source withBit(index: U8, value: Boolean): Selfself with bit index set or cleared source toString(radix: U8 := 10): StringToString, with an optional radix source toBytes(): Byteslittle-endian source toFloat(): Floatnearest F64 - `as Float` source toBigInteger(): BigIntegerthe same number, as a BigInteger source toCodepoint(): CastError ! Codepointthe codepoint with this value - a CastError for surrogates, negatives and above 0x10FFFF source checkedCast<Target>(): CastError ! Target`as`, with a CastError where `as` gives an OverflowError source #u32A 32-bit unsigned integer: 0 to 2^32 - 1.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Bitwise, Steppable, Castable, Default, Copy
U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256(51)U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256 (and Integer, UnsignedInteger, SignedInteger through their aliases)
+ - * // ^ and `as` give an OverflowError for a result that doesn't fit; +% -% *% wrap around and
+| -| *| fill up to min() / max() instead (the wrapping / saturating methods)
Implements Equatable, Hashable, Comparable, Bounded, ToString, FromString (radix 10), Numeric, Bitwise, Steppable, Castable<every numeric type>, Default (0), Copy
Functions
min(): Selfsmallest value source max(): Selflargest value source bits(): U168, 16, 32, 64, 128, 256 source parse(text: String, radix: U8 := 10): ParseError ! Selfin the given radix (2 to 36), optional sign, _ separators allowed source fromBytes(bytes: Bytes): ParseError ! Selflittle-endian, exactly bits() / 8 bytes source Methods
abs(): SelfS*.min().abs() is an OverflowError source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: Self): Selfthe smaller of the two source max(other: Self): Selfthe larger of the two source clamp(range: Range<Self>): Selfself kept within range source pow(exponent: U32): Selfself raised to exponent - an OverflowError when it doesn't fit source sqrt(): CastError ! Selffloor of the square root - a CastError below zero source gcd(other: Self): Selfgreatest common divisor - 0 when both are 0 source lcm(other: Self): Selfleast common multiple - 0 when either is 0 source divMod(other: Self): (Self, Self)(a // b, a % b) source modulo(other: Self): Selfalways the divisor's sign, unlike % source checkedAdd(other: Self): OverflowError ! Selfa + b - the OverflowError as a value to handle source checkedSubtract(other: Self): OverflowError ! Selfa - b - the OverflowError as a value to handle source checkedMultiply(other: Self): OverflowError ! Selfa * b - the OverflowError as a value to handle source wrappingAdd(other: Self): Selfa +% b source wrappingSubtract(other: Self): Selfa -% b source wrappingMultiply(other: Self): Selfa *% b source saturatingAdd(other: Self): Selfa +| b source saturatingSubtract(other: Self): Selfa -| b source saturatingMultiply(other: Self): Selfa *| b source bor(other: Self): Selfa bor b source bxor(other: Self): Selfa bxor b source band(other: Self): Selfa band b source bnot(): Self~a source shl(count: U64): Selfa shl b source shr(count: U64): Selfa shr b (arithmetic for S*, logical for U*) source rotateLeft(count: U8): Selfbits shifted left, those falling off the top coming back at the bottom source rotateRight(count: U8): Selfbits shifted right, those falling off the bottom coming back at the top source countOnes(): U8bits set source countZeros(): U8bits clear source leadingZeros(): U8clear bits above the highest set one - bits() when zero source trailingZeros(): U8clear bits below the lowest set one - bits() when zero source isPowerOfTwo(): Booleanexactly one bit set source bit(index: U8): Booleanbit index is set - 0 the least significant source withBit(index: U8, value: Boolean): Selfself with bit index set or cleared source toString(radix: U8 := 10): StringToString, with an optional radix source toBytes(): Byteslittle-endian source toFloat(): Floatnearest F64 - `as Float` source toBigInteger(): BigIntegerthe same number, as a BigInteger source toCodepoint(): CastError ! Codepointthe codepoint with this value - a CastError for surrogates, negatives and above 0x10FFFF source checkedCast<Target>(): CastError ! Target`as`, with a CastError where `as` gives an OverflowError source #u64A 64-bit unsigned integer: 0 to 2^64 - 1.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Bitwise, Steppable, Castable, Default, Copy
U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256(51)U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256 (and Integer, UnsignedInteger, SignedInteger through their aliases)
+ - * // ^ and `as` give an OverflowError for a result that doesn't fit; +% -% *% wrap around and
+| -| *| fill up to min() / max() instead (the wrapping / saturating methods)
Implements Equatable, Hashable, Comparable, Bounded, ToString, FromString (radix 10), Numeric, Bitwise, Steppable, Castable<every numeric type>, Default (0), Copy
Functions
min(): Selfsmallest value source max(): Selflargest value source bits(): U168, 16, 32, 64, 128, 256 source parse(text: String, radix: U8 := 10): ParseError ! Selfin the given radix (2 to 36), optional sign, _ separators allowed source fromBytes(bytes: Bytes): ParseError ! Selflittle-endian, exactly bits() / 8 bytes source Methods
abs(): SelfS*.min().abs() is an OverflowError source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: Self): Selfthe smaller of the two source max(other: Self): Selfthe larger of the two source clamp(range: Range<Self>): Selfself kept within range source pow(exponent: U32): Selfself raised to exponent - an OverflowError when it doesn't fit source sqrt(): CastError ! Selffloor of the square root - a CastError below zero source gcd(other: Self): Selfgreatest common divisor - 0 when both are 0 source lcm(other: Self): Selfleast common multiple - 0 when either is 0 source divMod(other: Self): (Self, Self)(a // b, a % b) source modulo(other: Self): Selfalways the divisor's sign, unlike % source checkedAdd(other: Self): OverflowError ! Selfa + b - the OverflowError as a value to handle source checkedSubtract(other: Self): OverflowError ! Selfa - b - the OverflowError as a value to handle source checkedMultiply(other: Self): OverflowError ! Selfa * b - the OverflowError as a value to handle source wrappingAdd(other: Self): Selfa +% b source wrappingSubtract(other: Self): Selfa -% b source wrappingMultiply(other: Self): Selfa *% b source saturatingAdd(other: Self): Selfa +| b source saturatingSubtract(other: Self): Selfa -| b source saturatingMultiply(other: Self): Selfa *| b source bor(other: Self): Selfa bor b source bxor(other: Self): Selfa bxor b source band(other: Self): Selfa band b source bnot(): Self~a source shl(count: U64): Selfa shl b source shr(count: U64): Selfa shr b (arithmetic for S*, logical for U*) source rotateLeft(count: U8): Selfbits shifted left, those falling off the top coming back at the bottom source rotateRight(count: U8): Selfbits shifted right, those falling off the bottom coming back at the top source countOnes(): U8bits set source countZeros(): U8bits clear source leadingZeros(): U8clear bits above the highest set one - bits() when zero source trailingZeros(): U8clear bits below the lowest set one - bits() when zero source isPowerOfTwo(): Booleanexactly one bit set source bit(index: U8): Booleanbit index is set - 0 the least significant source withBit(index: U8, value: Boolean): Selfself with bit index set or cleared source toString(radix: U8 := 10): StringToString, with an optional radix source toBytes(): Byteslittle-endian source toFloat(): Floatnearest F64 - `as Float` source toBigInteger(): BigIntegerthe same number, as a BigInteger source toCodepoint(): CastError ! Codepointthe codepoint with this value - a CastError for surrogates, negatives and above 0x10FFFF source checkedCast<Target>(): CastError ! Target`as`, with a CastError where `as` gives an OverflowError source #u128A 128-bit unsigned integer: 0 to 2^128 - 1.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Bitwise, Steppable, Castable, Default, Copy
U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256(51)U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256 (and Integer, UnsignedInteger, SignedInteger through their aliases)
+ - * // ^ and `as` give an OverflowError for a result that doesn't fit; +% -% *% wrap around and
+| -| *| fill up to min() / max() instead (the wrapping / saturating methods)
Implements Equatable, Hashable, Comparable, Bounded, ToString, FromString (radix 10), Numeric, Bitwise, Steppable, Castable<every numeric type>, Default (0), Copy
Functions
min(): Selfsmallest value source max(): Selflargest value source bits(): U168, 16, 32, 64, 128, 256 source parse(text: String, radix: U8 := 10): ParseError ! Selfin the given radix (2 to 36), optional sign, _ separators allowed source fromBytes(bytes: Bytes): ParseError ! Selflittle-endian, exactly bits() / 8 bytes source Methods
abs(): SelfS*.min().abs() is an OverflowError source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: Self): Selfthe smaller of the two source max(other: Self): Selfthe larger of the two source clamp(range: Range<Self>): Selfself kept within range source pow(exponent: U32): Selfself raised to exponent - an OverflowError when it doesn't fit source sqrt(): CastError ! Selffloor of the square root - a CastError below zero source gcd(other: Self): Selfgreatest common divisor - 0 when both are 0 source lcm(other: Self): Selfleast common multiple - 0 when either is 0 source divMod(other: Self): (Self, Self)(a // b, a % b) source modulo(other: Self): Selfalways the divisor's sign, unlike % source checkedAdd(other: Self): OverflowError ! Selfa + b - the OverflowError as a value to handle source checkedSubtract(other: Self): OverflowError ! Selfa - b - the OverflowError as a value to handle source checkedMultiply(other: Self): OverflowError ! Selfa * b - the OverflowError as a value to handle source wrappingAdd(other: Self): Selfa +% b source wrappingSubtract(other: Self): Selfa -% b source wrappingMultiply(other: Self): Selfa *% b source saturatingAdd(other: Self): Selfa +| b source saturatingSubtract(other: Self): Selfa -| b source saturatingMultiply(other: Self): Selfa *| b source bor(other: Self): Selfa bor b source bxor(other: Self): Selfa bxor b source band(other: Self): Selfa band b source bnot(): Self~a source shl(count: U64): Selfa shl b source shr(count: U64): Selfa shr b (arithmetic for S*, logical for U*) source rotateLeft(count: U8): Selfbits shifted left, those falling off the top coming back at the bottom source rotateRight(count: U8): Selfbits shifted right, those falling off the bottom coming back at the top source countOnes(): U8bits set source countZeros(): U8bits clear source leadingZeros(): U8clear bits above the highest set one - bits() when zero source trailingZeros(): U8clear bits below the lowest set one - bits() when zero source isPowerOfTwo(): Booleanexactly one bit set source bit(index: U8): Booleanbit index is set - 0 the least significant source withBit(index: U8, value: Boolean): Selfself with bit index set or cleared source toString(radix: U8 := 10): StringToString, with an optional radix source toBytes(): Byteslittle-endian source toFloat(): Floatnearest F64 - `as Float` source toBigInteger(): BigIntegerthe same number, as a BigInteger source toCodepoint(): CastError ! Codepointthe codepoint with this value - a CastError for surrogates, negatives and above 0x10FFFF source checkedCast<Target>(): CastError ! Target`as`, with a CastError where `as` gives an OverflowError source #u256A 256-bit unsigned integer: 0 to 2^256 - 1.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Bitwise, Steppable, Castable, Default, Copy
U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256(51)U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256 (and Integer, UnsignedInteger, SignedInteger through their aliases)
+ - * // ^ and `as` give an OverflowError for a result that doesn't fit; +% -% *% wrap around and
+| -| *| fill up to min() / max() instead (the wrapping / saturating methods)
Implements Equatable, Hashable, Comparable, Bounded, ToString, FromString (radix 10), Numeric, Bitwise, Steppable, Castable<every numeric type>, Default (0), Copy
Functions
min(): Selfsmallest value source max(): Selflargest value source bits(): U168, 16, 32, 64, 128, 256 source parse(text: String, radix: U8 := 10): ParseError ! Selfin the given radix (2 to 36), optional sign, _ separators allowed source fromBytes(bytes: Bytes): ParseError ! Selflittle-endian, exactly bits() / 8 bytes source Methods
abs(): SelfS*.min().abs() is an OverflowError source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: Self): Selfthe smaller of the two source max(other: Self): Selfthe larger of the two source clamp(range: Range<Self>): Selfself kept within range source pow(exponent: U32): Selfself raised to exponent - an OverflowError when it doesn't fit source sqrt(): CastError ! Selffloor of the square root - a CastError below zero source gcd(other: Self): Selfgreatest common divisor - 0 when both are 0 source lcm(other: Self): Selfleast common multiple - 0 when either is 0 source divMod(other: Self): (Self, Self)(a // b, a % b) source modulo(other: Self): Selfalways the divisor's sign, unlike % source checkedAdd(other: Self): OverflowError ! Selfa + b - the OverflowError as a value to handle source checkedSubtract(other: Self): OverflowError ! Selfa - b - the OverflowError as a value to handle source checkedMultiply(other: Self): OverflowError ! Selfa * b - the OverflowError as a value to handle source wrappingAdd(other: Self): Selfa +% b source wrappingSubtract(other: Self): Selfa -% b source wrappingMultiply(other: Self): Selfa *% b source saturatingAdd(other: Self): Selfa +| b source saturatingSubtract(other: Self): Selfa -| b source saturatingMultiply(other: Self): Selfa *| b source bor(other: Self): Selfa bor b source bxor(other: Self): Selfa bxor b source band(other: Self): Selfa band b source bnot(): Self~a source shl(count: U64): Selfa shl b source shr(count: U64): Selfa shr b (arithmetic for S*, logical for U*) source rotateLeft(count: U8): Selfbits shifted left, those falling off the top coming back at the bottom source rotateRight(count: U8): Selfbits shifted right, those falling off the bottom coming back at the top source countOnes(): U8bits set source countZeros(): U8bits clear source leadingZeros(): U8clear bits above the highest set one - bits() when zero source trailingZeros(): U8clear bits below the lowest set one - bits() when zero source isPowerOfTwo(): Booleanexactly one bit set source bit(index: U8): Booleanbit index is set - 0 the least significant source withBit(index: U8, value: Boolean): Selfself with bit index set or cleared source toString(radix: U8 := 10): StringToString, with an optional radix source toBytes(): Byteslittle-endian source toFloat(): Floatnearest F64 - `as Float` source toBigInteger(): BigIntegerthe same number, as a BigInteger source toCodepoint(): CastError ! Codepointthe codepoint with this value - a CastError for surrogates, negatives and above 0x10FFFF source checkedCast<Target>(): CastError ! Target`as`, with a CastError where `as` gives an OverflowError source #s8An 8-bit signed integer: -2^7 to 2^7 - 1.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Bitwise, Steppable, Castable, Default, Copy
U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256(51)U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256 (and Integer, UnsignedInteger, SignedInteger through their aliases)
+ - * // ^ and `as` give an OverflowError for a result that doesn't fit; +% -% *% wrap around and
+| -| *| fill up to min() / max() instead (the wrapping / saturating methods)
Implements Equatable, Hashable, Comparable, Bounded, ToString, FromString (radix 10), Numeric, Bitwise, Steppable, Castable<every numeric type>, Default (0), Copy
Functions
min(): Selfsmallest value source max(): Selflargest value source bits(): U168, 16, 32, 64, 128, 256 source parse(text: String, radix: U8 := 10): ParseError ! Selfin the given radix (2 to 36), optional sign, _ separators allowed source fromBytes(bytes: Bytes): ParseError ! Selflittle-endian, exactly bits() / 8 bytes source Methods
abs(): SelfS*.min().abs() is an OverflowError source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: Self): Selfthe smaller of the two source max(other: Self): Selfthe larger of the two source clamp(range: Range<Self>): Selfself kept within range source pow(exponent: U32): Selfself raised to exponent - an OverflowError when it doesn't fit source sqrt(): CastError ! Selffloor of the square root - a CastError below zero source gcd(other: Self): Selfgreatest common divisor - 0 when both are 0 source lcm(other: Self): Selfleast common multiple - 0 when either is 0 source divMod(other: Self): (Self, Self)(a // b, a % b) source modulo(other: Self): Selfalways the divisor's sign, unlike % source checkedAdd(other: Self): OverflowError ! Selfa + b - the OverflowError as a value to handle source checkedSubtract(other: Self): OverflowError ! Selfa - b - the OverflowError as a value to handle source checkedMultiply(other: Self): OverflowError ! Selfa * b - the OverflowError as a value to handle source wrappingAdd(other: Self): Selfa +% b source wrappingSubtract(other: Self): Selfa -% b source wrappingMultiply(other: Self): Selfa *% b source saturatingAdd(other: Self): Selfa +| b source saturatingSubtract(other: Self): Selfa -| b source saturatingMultiply(other: Self): Selfa *| b source bor(other: Self): Selfa bor b source bxor(other: Self): Selfa bxor b source band(other: Self): Selfa band b source bnot(): Self~a source shl(count: U64): Selfa shl b source shr(count: U64): Selfa shr b (arithmetic for S*, logical for U*) source rotateLeft(count: U8): Selfbits shifted left, those falling off the top coming back at the bottom source rotateRight(count: U8): Selfbits shifted right, those falling off the bottom coming back at the top source countOnes(): U8bits set source countZeros(): U8bits clear source leadingZeros(): U8clear bits above the highest set one - bits() when zero source trailingZeros(): U8clear bits below the lowest set one - bits() when zero source isPowerOfTwo(): Booleanexactly one bit set source bit(index: U8): Booleanbit index is set - 0 the least significant source withBit(index: U8, value: Boolean): Selfself with bit index set or cleared source toString(radix: U8 := 10): StringToString, with an optional radix source toBytes(): Byteslittle-endian source toFloat(): Floatnearest F64 - `as Float` source toBigInteger(): BigIntegerthe same number, as a BigInteger source toCodepoint(): CastError ! Codepointthe codepoint with this value - a CastError for surrogates, negatives and above 0x10FFFF source checkedCast<Target>(): CastError ! Target`as`, with a CastError where `as` gives an OverflowError source #s16A 16-bit signed integer: -2^15 to 2^15 - 1.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Bitwise, Steppable, Castable, Default, Copy
U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256(51)U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256 (and Integer, UnsignedInteger, SignedInteger through their aliases)
+ - * // ^ and `as` give an OverflowError for a result that doesn't fit; +% -% *% wrap around and
+| -| *| fill up to min() / max() instead (the wrapping / saturating methods)
Implements Equatable, Hashable, Comparable, Bounded, ToString, FromString (radix 10), Numeric, Bitwise, Steppable, Castable<every numeric type>, Default (0), Copy
Functions
min(): Selfsmallest value source max(): Selflargest value source bits(): U168, 16, 32, 64, 128, 256 source parse(text: String, radix: U8 := 10): ParseError ! Selfin the given radix (2 to 36), optional sign, _ separators allowed source fromBytes(bytes: Bytes): ParseError ! Selflittle-endian, exactly bits() / 8 bytes source Methods
abs(): SelfS*.min().abs() is an OverflowError source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: Self): Selfthe smaller of the two source max(other: Self): Selfthe larger of the two source clamp(range: Range<Self>): Selfself kept within range source pow(exponent: U32): Selfself raised to exponent - an OverflowError when it doesn't fit source sqrt(): CastError ! Selffloor of the square root - a CastError below zero source gcd(other: Self): Selfgreatest common divisor - 0 when both are 0 source lcm(other: Self): Selfleast common multiple - 0 when either is 0 source divMod(other: Self): (Self, Self)(a // b, a % b) source modulo(other: Self): Selfalways the divisor's sign, unlike % source checkedAdd(other: Self): OverflowError ! Selfa + b - the OverflowError as a value to handle source checkedSubtract(other: Self): OverflowError ! Selfa - b - the OverflowError as a value to handle source checkedMultiply(other: Self): OverflowError ! Selfa * b - the OverflowError as a value to handle source wrappingAdd(other: Self): Selfa +% b source wrappingSubtract(other: Self): Selfa -% b source wrappingMultiply(other: Self): Selfa *% b source saturatingAdd(other: Self): Selfa +| b source saturatingSubtract(other: Self): Selfa -| b source saturatingMultiply(other: Self): Selfa *| b source bor(other: Self): Selfa bor b source bxor(other: Self): Selfa bxor b source band(other: Self): Selfa band b source bnot(): Self~a source shl(count: U64): Selfa shl b source shr(count: U64): Selfa shr b (arithmetic for S*, logical for U*) source rotateLeft(count: U8): Selfbits shifted left, those falling off the top coming back at the bottom source rotateRight(count: U8): Selfbits shifted right, those falling off the bottom coming back at the top source countOnes(): U8bits set source countZeros(): U8bits clear source leadingZeros(): U8clear bits above the highest set one - bits() when zero source trailingZeros(): U8clear bits below the lowest set one - bits() when zero source isPowerOfTwo(): Booleanexactly one bit set source bit(index: U8): Booleanbit index is set - 0 the least significant source withBit(index: U8, value: Boolean): Selfself with bit index set or cleared source toString(radix: U8 := 10): StringToString, with an optional radix source toBytes(): Byteslittle-endian source toFloat(): Floatnearest F64 - `as Float` source toBigInteger(): BigIntegerthe same number, as a BigInteger source toCodepoint(): CastError ! Codepointthe codepoint with this value - a CastError for surrogates, negatives and above 0x10FFFF source checkedCast<Target>(): CastError ! Target`as`, with a CastError where `as` gives an OverflowError source #s32A 32-bit signed integer: -2^31 to 2^31 - 1.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Bitwise, Steppable, Castable, Default, Copy
U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256(51)U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256 (and Integer, UnsignedInteger, SignedInteger through their aliases)
+ - * // ^ and `as` give an OverflowError for a result that doesn't fit; +% -% *% wrap around and
+| -| *| fill up to min() / max() instead (the wrapping / saturating methods)
Implements Equatable, Hashable, Comparable, Bounded, ToString, FromString (radix 10), Numeric, Bitwise, Steppable, Castable<every numeric type>, Default (0), Copy
Functions
min(): Selfsmallest value source max(): Selflargest value source bits(): U168, 16, 32, 64, 128, 256 source parse(text: String, radix: U8 := 10): ParseError ! Selfin the given radix (2 to 36), optional sign, _ separators allowed source fromBytes(bytes: Bytes): ParseError ! Selflittle-endian, exactly bits() / 8 bytes source Methods
abs(): SelfS*.min().abs() is an OverflowError source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: Self): Selfthe smaller of the two source max(other: Self): Selfthe larger of the two source clamp(range: Range<Self>): Selfself kept within range source pow(exponent: U32): Selfself raised to exponent - an OverflowError when it doesn't fit source sqrt(): CastError ! Selffloor of the square root - a CastError below zero source gcd(other: Self): Selfgreatest common divisor - 0 when both are 0 source lcm(other: Self): Selfleast common multiple - 0 when either is 0 source divMod(other: Self): (Self, Self)(a // b, a % b) source modulo(other: Self): Selfalways the divisor's sign, unlike % source checkedAdd(other: Self): OverflowError ! Selfa + b - the OverflowError as a value to handle source checkedSubtract(other: Self): OverflowError ! Selfa - b - the OverflowError as a value to handle source checkedMultiply(other: Self): OverflowError ! Selfa * b - the OverflowError as a value to handle source wrappingAdd(other: Self): Selfa +% b source wrappingSubtract(other: Self): Selfa -% b source wrappingMultiply(other: Self): Selfa *% b source saturatingAdd(other: Self): Selfa +| b source saturatingSubtract(other: Self): Selfa -| b source saturatingMultiply(other: Self): Selfa *| b source bor(other: Self): Selfa bor b source bxor(other: Self): Selfa bxor b source band(other: Self): Selfa band b source bnot(): Self~a source shl(count: U64): Selfa shl b source shr(count: U64): Selfa shr b (arithmetic for S*, logical for U*) source rotateLeft(count: U8): Selfbits shifted left, those falling off the top coming back at the bottom source rotateRight(count: U8): Selfbits shifted right, those falling off the bottom coming back at the top source countOnes(): U8bits set source countZeros(): U8bits clear source leadingZeros(): U8clear bits above the highest set one - bits() when zero source trailingZeros(): U8clear bits below the lowest set one - bits() when zero source isPowerOfTwo(): Booleanexactly one bit set source bit(index: U8): Booleanbit index is set - 0 the least significant source withBit(index: U8, value: Boolean): Selfself with bit index set or cleared source toString(radix: U8 := 10): StringToString, with an optional radix source toBytes(): Byteslittle-endian source toFloat(): Floatnearest F64 - `as Float` source toBigInteger(): BigIntegerthe same number, as a BigInteger source toCodepoint(): CastError ! Codepointthe codepoint with this value - a CastError for surrogates, negatives and above 0x10FFFF source checkedCast<Target>(): CastError ! Target`as`, with a CastError where `as` gives an OverflowError source #s64A 64-bit signed integer: -2^63 to 2^63 - 1.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Bitwise, Steppable, Castable, Default, Copy
U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256(51)U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256 (and Integer, UnsignedInteger, SignedInteger through their aliases)
+ - * // ^ and `as` give an OverflowError for a result that doesn't fit; +% -% *% wrap around and
+| -| *| fill up to min() / max() instead (the wrapping / saturating methods)
Implements Equatable, Hashable, Comparable, Bounded, ToString, FromString (radix 10), Numeric, Bitwise, Steppable, Castable<every numeric type>, Default (0), Copy
Functions
min(): Selfsmallest value source max(): Selflargest value source bits(): U168, 16, 32, 64, 128, 256 source parse(text: String, radix: U8 := 10): ParseError ! Selfin the given radix (2 to 36), optional sign, _ separators allowed source fromBytes(bytes: Bytes): ParseError ! Selflittle-endian, exactly bits() / 8 bytes source Methods
abs(): SelfS*.min().abs() is an OverflowError source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: Self): Selfthe smaller of the two source max(other: Self): Selfthe larger of the two source clamp(range: Range<Self>): Selfself kept within range source pow(exponent: U32): Selfself raised to exponent - an OverflowError when it doesn't fit source sqrt(): CastError ! Selffloor of the square root - a CastError below zero source gcd(other: Self): Selfgreatest common divisor - 0 when both are 0 source lcm(other: Self): Selfleast common multiple - 0 when either is 0 source divMod(other: Self): (Self, Self)(a // b, a % b) source modulo(other: Self): Selfalways the divisor's sign, unlike % source checkedAdd(other: Self): OverflowError ! Selfa + b - the OverflowError as a value to handle source checkedSubtract(other: Self): OverflowError ! Selfa - b - the OverflowError as a value to handle source checkedMultiply(other: Self): OverflowError ! Selfa * b - the OverflowError as a value to handle source wrappingAdd(other: Self): Selfa +% b source wrappingSubtract(other: Self): Selfa -% b source wrappingMultiply(other: Self): Selfa *% b source saturatingAdd(other: Self): Selfa +| b source saturatingSubtract(other: Self): Selfa -| b source saturatingMultiply(other: Self): Selfa *| b source bor(other: Self): Selfa bor b source bxor(other: Self): Selfa bxor b source band(other: Self): Selfa band b source bnot(): Self~a source shl(count: U64): Selfa shl b source shr(count: U64): Selfa shr b (arithmetic for S*, logical for U*) source rotateLeft(count: U8): Selfbits shifted left, those falling off the top coming back at the bottom source rotateRight(count: U8): Selfbits shifted right, those falling off the bottom coming back at the top source countOnes(): U8bits set source countZeros(): U8bits clear source leadingZeros(): U8clear bits above the highest set one - bits() when zero source trailingZeros(): U8clear bits below the lowest set one - bits() when zero source isPowerOfTwo(): Booleanexactly one bit set source bit(index: U8): Booleanbit index is set - 0 the least significant source withBit(index: U8, value: Boolean): Selfself with bit index set or cleared source toString(radix: U8 := 10): StringToString, with an optional radix source toBytes(): Byteslittle-endian source toFloat(): Floatnearest F64 - `as Float` source toBigInteger(): BigIntegerthe same number, as a BigInteger source toCodepoint(): CastError ! Codepointthe codepoint with this value - a CastError for surrogates, negatives and above 0x10FFFF source checkedCast<Target>(): CastError ! Target`as`, with a CastError where `as` gives an OverflowError source #s128A 128-bit signed integer: -2^127 to 2^127 - 1.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Bitwise, Steppable, Castable, Default, Copy
U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256(51)U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256 (and Integer, UnsignedInteger, SignedInteger through their aliases)
+ - * // ^ and `as` give an OverflowError for a result that doesn't fit; +% -% *% wrap around and
+| -| *| fill up to min() / max() instead (the wrapping / saturating methods)
Implements Equatable, Hashable, Comparable, Bounded, ToString, FromString (radix 10), Numeric, Bitwise, Steppable, Castable<every numeric type>, Default (0), Copy
Functions
min(): Selfsmallest value source max(): Selflargest value source bits(): U168, 16, 32, 64, 128, 256 source parse(text: String, radix: U8 := 10): ParseError ! Selfin the given radix (2 to 36), optional sign, _ separators allowed source fromBytes(bytes: Bytes): ParseError ! Selflittle-endian, exactly bits() / 8 bytes source Methods
abs(): SelfS*.min().abs() is an OverflowError source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: Self): Selfthe smaller of the two source max(other: Self): Selfthe larger of the two source clamp(range: Range<Self>): Selfself kept within range source pow(exponent: U32): Selfself raised to exponent - an OverflowError when it doesn't fit source sqrt(): CastError ! Selffloor of the square root - a CastError below zero source gcd(other: Self): Selfgreatest common divisor - 0 when both are 0 source lcm(other: Self): Selfleast common multiple - 0 when either is 0 source divMod(other: Self): (Self, Self)(a // b, a % b) source modulo(other: Self): Selfalways the divisor's sign, unlike % source checkedAdd(other: Self): OverflowError ! Selfa + b - the OverflowError as a value to handle source checkedSubtract(other: Self): OverflowError ! Selfa - b - the OverflowError as a value to handle source checkedMultiply(other: Self): OverflowError ! Selfa * b - the OverflowError as a value to handle source wrappingAdd(other: Self): Selfa +% b source wrappingSubtract(other: Self): Selfa -% b source wrappingMultiply(other: Self): Selfa *% b source saturatingAdd(other: Self): Selfa +| b source saturatingSubtract(other: Self): Selfa -| b source saturatingMultiply(other: Self): Selfa *| b source bor(other: Self): Selfa bor b source bxor(other: Self): Selfa bxor b source band(other: Self): Selfa band b source bnot(): Self~a source shl(count: U64): Selfa shl b source shr(count: U64): Selfa shr b (arithmetic for S*, logical for U*) source rotateLeft(count: U8): Selfbits shifted left, those falling off the top coming back at the bottom source rotateRight(count: U8): Selfbits shifted right, those falling off the bottom coming back at the top source countOnes(): U8bits set source countZeros(): U8bits clear source leadingZeros(): U8clear bits above the highest set one - bits() when zero source trailingZeros(): U8clear bits below the lowest set one - bits() when zero source isPowerOfTwo(): Booleanexactly one bit set source bit(index: U8): Booleanbit index is set - 0 the least significant source withBit(index: U8, value: Boolean): Selfself with bit index set or cleared source toString(radix: U8 := 10): StringToString, with an optional radix source toBytes(): Byteslittle-endian source toFloat(): Floatnearest F64 - `as Float` source toBigInteger(): BigIntegerthe same number, as a BigInteger source toCodepoint(): CastError ! Codepointthe codepoint with this value - a CastError for surrogates, negatives and above 0x10FFFF source checkedCast<Target>(): CastError ! Target`as`, with a CastError where `as` gives an OverflowError source #s256A 256-bit signed integer: -2^255 to 2^255 - 1.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Numeric, Bitwise, Steppable, Castable, Default, Copy
U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256(51)U8 U16 U32 U64 U128 U256 S8 S16 S32 S64 S128 S256 (and Integer, UnsignedInteger, SignedInteger through their aliases)
+ - * // ^ and `as` give an OverflowError for a result that doesn't fit; +% -% *% wrap around and
+| -| *| fill up to min() / max() instead (the wrapping / saturating methods)
Implements Equatable, Hashable, Comparable, Bounded, ToString, FromString (radix 10), Numeric, Bitwise, Steppable, Castable<every numeric type>, Default (0), Copy
Functions
min(): Selfsmallest value source max(): Selflargest value source bits(): U168, 16, 32, 64, 128, 256 source parse(text: String, radix: U8 := 10): ParseError ! Selfin the given radix (2 to 36), optional sign, _ separators allowed source fromBytes(bytes: Bytes): ParseError ! Selflittle-endian, exactly bits() / 8 bytes source Methods
abs(): SelfS*.min().abs() is an OverflowError source sign(): S8-1 | 0 | 1 source isZero(): Boolean== 0 source isPositive(): Boolean> 0 source isNegative(): Boolean< 0 source isEven(): Booleandivisible by 2 source isOdd(): Booleannot divisible by 2 source min(other: Self): Selfthe smaller of the two source max(other: Self): Selfthe larger of the two source clamp(range: Range<Self>): Selfself kept within range source pow(exponent: U32): Selfself raised to exponent - an OverflowError when it doesn't fit source sqrt(): CastError ! Selffloor of the square root - a CastError below zero source gcd(other: Self): Selfgreatest common divisor - 0 when both are 0 source lcm(other: Self): Selfleast common multiple - 0 when either is 0 source divMod(other: Self): (Self, Self)(a // b, a % b) source modulo(other: Self): Selfalways the divisor's sign, unlike % source checkedAdd(other: Self): OverflowError ! Selfa + b - the OverflowError as a value to handle source checkedSubtract(other: Self): OverflowError ! Selfa - b - the OverflowError as a value to handle source checkedMultiply(other: Self): OverflowError ! Selfa * b - the OverflowError as a value to handle source wrappingAdd(other: Self): Selfa +% b source wrappingSubtract(other: Self): Selfa -% b source wrappingMultiply(other: Self): Selfa *% b source saturatingAdd(other: Self): Selfa +| b source saturatingSubtract(other: Self): Selfa -| b source saturatingMultiply(other: Self): Selfa *| b source bor(other: Self): Selfa bor b source bxor(other: Self): Selfa bxor b source band(other: Self): Selfa band b source bnot(): Self~a source shl(count: U64): Selfa shl b source shr(count: U64): Selfa shr b (arithmetic for S*, logical for U*) source rotateLeft(count: U8): Selfbits shifted left, those falling off the top coming back at the bottom source rotateRight(count: U8): Selfbits shifted right, those falling off the bottom coming back at the top source countOnes(): U8bits set source countZeros(): U8bits clear source leadingZeros(): U8clear bits above the highest set one - bits() when zero source trailingZeros(): U8clear bits below the lowest set one - bits() when zero source isPowerOfTwo(): Booleanexactly one bit set source bit(index: U8): Booleanbit index is set - 0 the least significant source withBit(index: U8, value: Boolean): Selfself with bit index set or cleared source toString(radix: U8 := 10): StringToString, with an optional radix source toBytes(): Byteslittle-endian source toFloat(): Floatnearest F64 - `as Float` source toBigInteger(): BigIntegerthe same number, as a BigInteger source toCodepoint(): CastError ! Codepointthe codepoint with this value - a CastError for surrogates, negatives and above 0x10FFFF source checkedCast<Target>(): CastError ! Target`as`, with a CastError where `as` gives an OverflowError source #stringText - an alias for UTF8.
Sourceown members, Equatable, Hashable, Comparable, ToString, Iterable, FromIterable, Collection, Sized, Indexable, Castable, Concatenable, Default, Clone
An alias - has every member of UTF8.
UTF8 UTF16 UTF32 ASCII(49)UTF8 UTF16 UTF32 ASCII (and String through its alias) - same members, differ in encoding
Implements Equatable, Hashable, Comparable (by codepoint), ToString, Iterable<Codepoint>, FromIterable<Codepoint>, Collection<Codepoint>, Sized<Codepoint> (in codepoints), Indexable<U64, Codepoint>, Concatenable, Castable<every other encoding> (lossy into ASCII errors), Default (""), Clone
Functions
fromCodepoints(codepoints: Array<Codepoint>): Selfthe text the codepoints make source decode(bytes: Bytes): ParseError ! Selfin this encoding source repeat(text: Self, count: U64): Selftext written count times source Methods
byteLength(): U64encoded bytes source codepoints(): Array<Codepoint>every codepoint, in order source graphemes(): Array<Self>user-perceived characters source lines(): Array<Self>split on \n and \r\n, without the terminators source The string split at each line break (\n or \r\n) - a final line break starts no empty line, and an empty string has no lines.
words(): Array<Self>split on whitespace runs source encode(): Bytesthe text in this encoding source contains(part: Self | Regex): Booleanpart occurs anywhere source Whether part appears anywhere in the string.
startsWith(prefix: Self | Regex): Booleanself begins with prefix source Whether the string starts with prefix.
endsWith(suffix: Self | Regex): Booleanself ends with suffix source Whether the string ends with suffix.
indexOf(part: Self | Regex, from: U64 = 0): U64?codepoint index of the first part at or after from source lastIndexOf(part: Self | Regex): U64?codepoint index of the last part source count(part: Self | Regex): U64non-overlapping occurrences of part source slice(range: Range<U64>): IndexError ! Selfcodepoint range source The characters from start up to, but not including, end.
charAt(index: U64): Codepoint?the codepoint at index, undefined past the end source The one-character string at index - an empty string when index is out of range, never an error.
split(separator: Self | Regex, limit: U64?): Array<Self>the pieces between separators - at most limit of them, the last holding the rest source The pieces between each separator.
splitOnce(separator: Self | Regex): (Self, Self)?the text before and after the first separator, undefined without one source join(parts: Iterable<Self>): Selfself is the separator source replace(part: Self | Regex, with: Self): Selffirst occurrence source replaceAll(part: Self | Regex, with: Self): Selfevery occurrence source The string with every part replaced by by.
repeat(count: U64): Selfself written count times source The string written count times over.
reverse(): Selfby grapheme source insert(index: U64, part: Self): IndexError ! Selfpart placed before codepoint index source remove(range: Range<U64>): IndexError ! Selfwithout the codepoints in range source trim(): Selfwithout whitespace at either end source The string without whitespace at either end.
trimStart(): Selfwithout leading whitespace source The string without whitespace at its start.
trimEnd(): Selfwithout trailing whitespace source The string without whitespace at its end.
stripPrefix(prefix: Self): Self?undefined when it doesn't start with prefix source stripSuffix(suffix: Self): Self?undefined when it doesn't end with suffix source padStart(length: U64, fill: Codepoint := ' '): Selffill added in front up to length codepoints source padEnd(length: U64, fill: Codepoint := ' '): Selffill added at the end up to length codepoints source toUpper(): Selffull Unicode uppercase - can change the length source The string with every letter in upper case.
toLower(): Selffull Unicode lowercase source The string with every letter in lower case.
capitalize(): Selffirst codepoint uppercased, the rest as it is source isBlank(): Booleanempty or only whitespace source Whether the string is empty or only whitespace.
isAscii(): Booleanevery codepoint is below 128 source normalize(form: NFC | NFD | NFKC | NFKD := NFC): Selfin the Unicode normalization form source compareIgnoreCase(other: Self): Orderingcompare after full case folding source editDistance(other: Self): U64the fewest codepoints inserted, removed or replaced to turn self into other (Levenshtein) source fuzzyScore(query: Self): U64?how well query's codepoints appear in self in order, ignoring case - higher for runs and word starts, undefined when they don't all appear source dedent(): Selfthe whitespace every non-blank line starts with taken off each, blank lines emptied source indent(prefix: Self := " "): Selfprefix put before every non-blank line source toNumber(): ParseError ! Numberthe number the text writes - integer, decimal or scientific source Decodes a number literal's text, exactly the way the language reads one in source - so "0x1F" and "1_000.5" both work.
toInteger(radix: U8 := 10): ParseError ! Integerthe integer the text writes, in radix source parse<Target: FromString>(): ParseError ! TargetTarget.parse(self) source matches(regex: Regex): Array<Match>every non-overlapping match, in order source format(values: Map<String, Unknown>): Self"{name}" placeholders source Methods
size(): NumberThe number of characters (UTF-16 code units).
isIdStart(): BooleanWhether the (single-character) string can start an identifier.
isIdContinue(): BooleanWhether the (single-character) string can continue an identifier.
isSpace(): BooleanWhether the (single-character) string is whitespace.
isSymbolChar(): BooleanWhether the (single-character) string can be part of an operator symbol, e.g. + or <.
isEmpty(): BooleanWhether the string has no characters.
#utf8Text stored as UTF-8.
Sourceown members, Equatable, Hashable, Comparable, ToString, Iterable, FromIterable, Collection, Sized, Indexable, Castable, Concatenable, Default, Clone
UTF8 UTF16 UTF32 ASCII(49)UTF8 UTF16 UTF32 ASCII (and String through its alias) - same members, differ in encoding
Implements Equatable, Hashable, Comparable (by codepoint), ToString, Iterable<Codepoint>, FromIterable<Codepoint>, Collection<Codepoint>, Sized<Codepoint> (in codepoints), Indexable<U64, Codepoint>, Concatenable, Castable<every other encoding> (lossy into ASCII errors), Default (""), Clone
Functions
fromCodepoints(codepoints: Array<Codepoint>): Selfthe text the codepoints make source decode(bytes: Bytes): ParseError ! Selfin this encoding source repeat(text: Self, count: U64): Selftext written count times source Methods
byteLength(): U64encoded bytes source codepoints(): Array<Codepoint>every codepoint, in order source graphemes(): Array<Self>user-perceived characters source lines(): Array<Self>split on \n and \r\n, without the terminators source words(): Array<Self>split on whitespace runs source encode(): Bytesthe text in this encoding source contains(part: Self | Regex): Booleanpart occurs anywhere source startsWith(prefix: Self | Regex): Booleanself begins with prefix source endsWith(suffix: Self | Regex): Booleanself ends with suffix source indexOf(part: Self | Regex, from: U64 = 0): U64?codepoint index of the first part at or after from source lastIndexOf(part: Self | Regex): U64?codepoint index of the last part source count(part: Self | Regex): U64non-overlapping occurrences of part source slice(range: Range<U64>): IndexError ! Selfcodepoint range source charAt(index: U64): Codepoint?the codepoint at index, undefined past the end source split(separator: Self | Regex, limit: U64?): Array<Self>the pieces between separators - at most limit of them, the last holding the rest source splitOnce(separator: Self | Regex): (Self, Self)?the text before and after the first separator, undefined without one source join(parts: Iterable<Self>): Selfself is the separator source replace(part: Self | Regex, with: Self): Selffirst occurrence source replaceAll(part: Self | Regex, with: Self): Selfevery occurrence source repeat(count: U64): Selfself written count times source reverse(): Selfby grapheme source insert(index: U64, part: Self): IndexError ! Selfpart placed before codepoint index source remove(range: Range<U64>): IndexError ! Selfwithout the codepoints in range source trim(): Selfwithout whitespace at either end source trimStart(): Selfwithout leading whitespace source trimEnd(): Selfwithout trailing whitespace source stripPrefix(prefix: Self): Self?undefined when it doesn't start with prefix source stripSuffix(suffix: Self): Self?undefined when it doesn't end with suffix source padStart(length: U64, fill: Codepoint := ' '): Selffill added in front up to length codepoints source padEnd(length: U64, fill: Codepoint := ' '): Selffill added at the end up to length codepoints source toUpper(): Selffull Unicode uppercase - can change the length source toLower(): Selffull Unicode lowercase source capitalize(): Selffirst codepoint uppercased, the rest as it is source isBlank(): Booleanempty or only whitespace source isAscii(): Booleanevery codepoint is below 128 source normalize(form: NFC | NFD | NFKC | NFKD := NFC): Selfin the Unicode normalization form source compareIgnoreCase(other: Self): Orderingcompare after full case folding source editDistance(other: Self): U64the fewest codepoints inserted, removed or replaced to turn self into other (Levenshtein) source fuzzyScore(query: Self): U64?how well query's codepoints appear in self in order, ignoring case - higher for runs and word starts, undefined when they don't all appear source dedent(): Selfthe whitespace every non-blank line starts with taken off each, blank lines emptied source indent(prefix: Self := " "): Selfprefix put before every non-blank line source toNumber(): ParseError ! Numberthe number the text writes - integer, decimal or scientific source toInteger(radix: U8 := 10): ParseError ! Integerthe integer the text writes, in radix source parse<Target: FromString>(): ParseError ! TargetTarget.parse(self) source matches(regex: Regex): Array<Match>every non-overlapping match, in order source format(values: Map<String, Unknown>): Self"{name}" placeholders source #utf16Text stored as UTF-16.
Sourceown members, Equatable, Hashable, Comparable, ToString, Iterable, FromIterable, Collection, Sized, Indexable, Castable, Concatenable, Default, Clone
UTF8 UTF16 UTF32 ASCII(49)UTF8 UTF16 UTF32 ASCII (and String through its alias) - same members, differ in encoding
Implements Equatable, Hashable, Comparable (by codepoint), ToString, Iterable<Codepoint>, FromIterable<Codepoint>, Collection<Codepoint>, Sized<Codepoint> (in codepoints), Indexable<U64, Codepoint>, Concatenable, Castable<every other encoding> (lossy into ASCII errors), Default (""), Clone
Functions
fromCodepoints(codepoints: Array<Codepoint>): Selfthe text the codepoints make source decode(bytes: Bytes): ParseError ! Selfin this encoding source repeat(text: Self, count: U64): Selftext written count times source Methods
byteLength(): U64encoded bytes source codepoints(): Array<Codepoint>every codepoint, in order source graphemes(): Array<Self>user-perceived characters source lines(): Array<Self>split on \n and \r\n, without the terminators source words(): Array<Self>split on whitespace runs source encode(): Bytesthe text in this encoding source contains(part: Self | Regex): Booleanpart occurs anywhere source startsWith(prefix: Self | Regex): Booleanself begins with prefix source endsWith(suffix: Self | Regex): Booleanself ends with suffix source indexOf(part: Self | Regex, from: U64 = 0): U64?codepoint index of the first part at or after from source lastIndexOf(part: Self | Regex): U64?codepoint index of the last part source count(part: Self | Regex): U64non-overlapping occurrences of part source slice(range: Range<U64>): IndexError ! Selfcodepoint range source charAt(index: U64): Codepoint?the codepoint at index, undefined past the end source split(separator: Self | Regex, limit: U64?): Array<Self>the pieces between separators - at most limit of them, the last holding the rest source splitOnce(separator: Self | Regex): (Self, Self)?the text before and after the first separator, undefined without one source join(parts: Iterable<Self>): Selfself is the separator source replace(part: Self | Regex, with: Self): Selffirst occurrence source replaceAll(part: Self | Regex, with: Self): Selfevery occurrence source repeat(count: U64): Selfself written count times source reverse(): Selfby grapheme source insert(index: U64, part: Self): IndexError ! Selfpart placed before codepoint index source remove(range: Range<U64>): IndexError ! Selfwithout the codepoints in range source trim(): Selfwithout whitespace at either end source trimStart(): Selfwithout leading whitespace source trimEnd(): Selfwithout trailing whitespace source stripPrefix(prefix: Self): Self?undefined when it doesn't start with prefix source stripSuffix(suffix: Self): Self?undefined when it doesn't end with suffix source padStart(length: U64, fill: Codepoint := ' '): Selffill added in front up to length codepoints source padEnd(length: U64, fill: Codepoint := ' '): Selffill added at the end up to length codepoints source toUpper(): Selffull Unicode uppercase - can change the length source toLower(): Selffull Unicode lowercase source capitalize(): Selffirst codepoint uppercased, the rest as it is source isBlank(): Booleanempty or only whitespace source isAscii(): Booleanevery codepoint is below 128 source normalize(form: NFC | NFD | NFKC | NFKD := NFC): Selfin the Unicode normalization form source compareIgnoreCase(other: Self): Orderingcompare after full case folding source editDistance(other: Self): U64the fewest codepoints inserted, removed or replaced to turn self into other (Levenshtein) source fuzzyScore(query: Self): U64?how well query's codepoints appear in self in order, ignoring case - higher for runs and word starts, undefined when they don't all appear source dedent(): Selfthe whitespace every non-blank line starts with taken off each, blank lines emptied source indent(prefix: Self := " "): Selfprefix put before every non-blank line source toNumber(): ParseError ! Numberthe number the text writes - integer, decimal or scientific source toInteger(radix: U8 := 10): ParseError ! Integerthe integer the text writes, in radix source parse<Target: FromString>(): ParseError ! TargetTarget.parse(self) source matches(regex: Regex): Array<Match>every non-overlapping match, in order source format(values: Map<String, Unknown>): Self"{name}" placeholders source #utf32Text stored as UTF-32.
Sourceown members, Equatable, Hashable, Comparable, ToString, Iterable, FromIterable, Collection, Sized, Indexable, Castable, Concatenable, Default, Clone
UTF8 UTF16 UTF32 ASCII(49)UTF8 UTF16 UTF32 ASCII (and String through its alias) - same members, differ in encoding
Implements Equatable, Hashable, Comparable (by codepoint), ToString, Iterable<Codepoint>, FromIterable<Codepoint>, Collection<Codepoint>, Sized<Codepoint> (in codepoints), Indexable<U64, Codepoint>, Concatenable, Castable<every other encoding> (lossy into ASCII errors), Default (""), Clone
Functions
fromCodepoints(codepoints: Array<Codepoint>): Selfthe text the codepoints make source decode(bytes: Bytes): ParseError ! Selfin this encoding source repeat(text: Self, count: U64): Selftext written count times source Methods
byteLength(): U64encoded bytes source codepoints(): Array<Codepoint>every codepoint, in order source graphemes(): Array<Self>user-perceived characters source lines(): Array<Self>split on \n and \r\n, without the terminators source words(): Array<Self>split on whitespace runs source encode(): Bytesthe text in this encoding source contains(part: Self | Regex): Booleanpart occurs anywhere source startsWith(prefix: Self | Regex): Booleanself begins with prefix source endsWith(suffix: Self | Regex): Booleanself ends with suffix source indexOf(part: Self | Regex, from: U64 = 0): U64?codepoint index of the first part at or after from source lastIndexOf(part: Self | Regex): U64?codepoint index of the last part source count(part: Self | Regex): U64non-overlapping occurrences of part source slice(range: Range<U64>): IndexError ! Selfcodepoint range source charAt(index: U64): Codepoint?the codepoint at index, undefined past the end source split(separator: Self | Regex, limit: U64?): Array<Self>the pieces between separators - at most limit of them, the last holding the rest source splitOnce(separator: Self | Regex): (Self, Self)?the text before and after the first separator, undefined without one source join(parts: Iterable<Self>): Selfself is the separator source replace(part: Self | Regex, with: Self): Selffirst occurrence source replaceAll(part: Self | Regex, with: Self): Selfevery occurrence source repeat(count: U64): Selfself written count times source reverse(): Selfby grapheme source insert(index: U64, part: Self): IndexError ! Selfpart placed before codepoint index source remove(range: Range<U64>): IndexError ! Selfwithout the codepoints in range source trim(): Selfwithout whitespace at either end source trimStart(): Selfwithout leading whitespace source trimEnd(): Selfwithout trailing whitespace source stripPrefix(prefix: Self): Self?undefined when it doesn't start with prefix source stripSuffix(suffix: Self): Self?undefined when it doesn't end with suffix source padStart(length: U64, fill: Codepoint := ' '): Selffill added in front up to length codepoints source padEnd(length: U64, fill: Codepoint := ' '): Selffill added at the end up to length codepoints source toUpper(): Selffull Unicode uppercase - can change the length source toLower(): Selffull Unicode lowercase source capitalize(): Selffirst codepoint uppercased, the rest as it is source isBlank(): Booleanempty or only whitespace source isAscii(): Booleanevery codepoint is below 128 source normalize(form: NFC | NFD | NFKC | NFKD := NFC): Selfin the Unicode normalization form source compareIgnoreCase(other: Self): Orderingcompare after full case folding source editDistance(other: Self): U64the fewest codepoints inserted, removed or replaced to turn self into other (Levenshtein) source fuzzyScore(query: Self): U64?how well query's codepoints appear in self in order, ignoring case - higher for runs and word starts, undefined when they don't all appear source dedent(): Selfthe whitespace every non-blank line starts with taken off each, blank lines emptied source indent(prefix: Self := " "): Selfprefix put before every non-blank line source toNumber(): ParseError ! Numberthe number the text writes - integer, decimal or scientific source toInteger(radix: U8 := 10): ParseError ! Integerthe integer the text writes, in radix source parse<Target: FromString>(): ParseError ! TargetTarget.parse(self) source matches(regex: Regex): Array<Match>every non-overlapping match, in order source format(values: Map<String, Unknown>): Self"{name}" placeholders source #asciiText limited to ASCII characters.
Sourceown members, Equatable, Hashable, Comparable, ToString, Iterable, FromIterable, Collection, Sized, Indexable, Castable, Concatenable, Default, Clone
UTF8 UTF16 UTF32 ASCII(49)UTF8 UTF16 UTF32 ASCII (and String through its alias) - same members, differ in encoding
Implements Equatable, Hashable, Comparable (by codepoint), ToString, Iterable<Codepoint>, FromIterable<Codepoint>, Collection<Codepoint>, Sized<Codepoint> (in codepoints), Indexable<U64, Codepoint>, Concatenable, Castable<every other encoding> (lossy into ASCII errors), Default (""), Clone
Functions
fromCodepoints(codepoints: Array<Codepoint>): Selfthe text the codepoints make source decode(bytes: Bytes): ParseError ! Selfin this encoding source repeat(text: Self, count: U64): Selftext written count times source Methods
byteLength(): U64encoded bytes source codepoints(): Array<Codepoint>every codepoint, in order source graphemes(): Array<Self>user-perceived characters source lines(): Array<Self>split on \n and \r\n, without the terminators source words(): Array<Self>split on whitespace runs source encode(): Bytesthe text in this encoding source contains(part: Self | Regex): Booleanpart occurs anywhere source startsWith(prefix: Self | Regex): Booleanself begins with prefix source endsWith(suffix: Self | Regex): Booleanself ends with suffix source indexOf(part: Self | Regex, from: U64 = 0): U64?codepoint index of the first part at or after from source lastIndexOf(part: Self | Regex): U64?codepoint index of the last part source count(part: Self | Regex): U64non-overlapping occurrences of part source slice(range: Range<U64>): IndexError ! Selfcodepoint range source charAt(index: U64): Codepoint?the codepoint at index, undefined past the end source split(separator: Self | Regex, limit: U64?): Array<Self>the pieces between separators - at most limit of them, the last holding the rest source splitOnce(separator: Self | Regex): (Self, Self)?the text before and after the first separator, undefined without one source join(parts: Iterable<Self>): Selfself is the separator source replace(part: Self | Regex, with: Self): Selffirst occurrence source replaceAll(part: Self | Regex, with: Self): Selfevery occurrence source repeat(count: U64): Selfself written count times source reverse(): Selfby grapheme source insert(index: U64, part: Self): IndexError ! Selfpart placed before codepoint index source remove(range: Range<U64>): IndexError ! Selfwithout the codepoints in range source trim(): Selfwithout whitespace at either end source trimStart(): Selfwithout leading whitespace source trimEnd(): Selfwithout trailing whitespace source stripPrefix(prefix: Self): Self?undefined when it doesn't start with prefix source stripSuffix(suffix: Self): Self?undefined when it doesn't end with suffix source padStart(length: U64, fill: Codepoint := ' '): Selffill added in front up to length codepoints source padEnd(length: U64, fill: Codepoint := ' '): Selffill added at the end up to length codepoints source toUpper(): Selffull Unicode uppercase - can change the length source toLower(): Selffull Unicode lowercase source capitalize(): Selffirst codepoint uppercased, the rest as it is source isBlank(): Booleanempty or only whitespace source isAscii(): Booleanevery codepoint is below 128 source normalize(form: NFC | NFD | NFKC | NFKD := NFC): Selfin the Unicode normalization form source compareIgnoreCase(other: Self): Orderingcompare after full case folding source editDistance(other: Self): U64the fewest codepoints inserted, removed or replaced to turn self into other (Levenshtein) source fuzzyScore(query: Self): U64?how well query's codepoints appear in self in order, ignoring case - higher for runs and word starts, undefined when they don't all appear source dedent(): Selfthe whitespace every non-blank line starts with taken off each, blank lines emptied source indent(prefix: Self := " "): Selfprefix put before every non-blank line source toNumber(): ParseError ! Numberthe number the text writes - integer, decimal or scientific source toInteger(radix: U8 := 10): ParseError ! Integerthe integer the text writes, in radix source parse<Target: FromString>(): ParseError ! TargetTarget.parse(self) source matches(regex: Regex): Array<Match>every non-overlapping match, in order source format(values: Map<String, Unknown>): Self"{name}" placeholders source #charA single character - an alias for Codepoint.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Steppable, Castable, Default, Copy
An alias - has every member of Codepoint.
Codepoint(21)single unicode scalar value
Implements Equatable, Hashable, Comparable, Bounded ('\0' to '\u{10FFFF}'), ToString, FromString, Steppable, Castable<U32 | String>, Default ('\0'), Copy
Functions
fromU32(value: U32): CastError ! Codepointerrors on surrogates and above 0x10FFFF source parse(text: String): ParseError ! Codepointexactly one codepoint source Methods
value(): U32the scalar value - 'A' is 65 source isLetter(): BooleanUnicode letter (L*) source isDigit(radix: U8 := 10): Booleana digit in radix - 0-9, then a-z / A-Z source isAlphanumeric(): Booleanletter or number source isWhitespace(): BooleanUnicode White_Space source isUpper(): Booleanuppercase letter source isLower(): Booleanlowercase letter source isPunctuation(): BooleanUnicode punctuation (P*) source isControl(): Booleancontrol character (Cc) source isAscii(): Booleanbelow 128 source isIdStart(): Booleancan start a name (see Syntax) source isIdContinue(): Booleancan continue a name source isSymbol(): Booleancan be part of an operator source toUpper(): StringString - some uppercase to several codepoints source toLower(): StringString - some lowercase to several codepoints source digitValue(radix: U8 := 10): U8?the digit's value in radix, undefined when it isn't one source utf8Length(): U8bytes it takes in UTF-8 - 1 to 4 source utf16Length(): U8code units it takes in UTF-16 - 1 or 2 source category(): StringUnicode general category, "Lu" source #codepointA single Unicode scalar value.
Sourceown members, Equatable, Hashable, Comparable, Bounded, ToString, FromString, Steppable, Castable, Default, Copy
single unicode scalar value
Implements Equatable, Hashable, Comparable, Bounded ('\0' to '\u{10FFFF}'), ToString, FromString, Steppable, Castable<U32 | String>, Default ('\0'), Copy
Functions
fromU32(value: U32): CastError ! Codepointerrors on surrogates and above 0x10FFFF source parse(text: String): ParseError ! Codepointexactly one codepoint source Methods
value(): U32the scalar value - 'A' is 65 source isLetter(): BooleanUnicode letter (L*) source isDigit(radix: U8 := 10): Booleana digit in radix - 0-9, then a-z / A-Z source isAlphanumeric(): Booleanletter or number source isWhitespace(): BooleanUnicode White_Space source isUpper(): Booleanuppercase letter source isLower(): Booleanlowercase letter source isPunctuation(): BooleanUnicode punctuation (P*) source isControl(): Booleancontrol character (Cc) source isAscii(): Booleanbelow 128 source isIdStart(): Booleancan start a name (see Syntax) source isIdContinue(): Booleancan continue a name source isSymbol(): Booleancan be part of an operator source toUpper(): StringString - some uppercase to several codepoints source toLower(): StringString - some lowercase to several codepoints source digitValue(radix: U8 := 10): U8?the digit's value in radix, undefined when it isn't one source utf8Length(): U8bytes it takes in UTF-8 - 1 to 4 source utf16Length(): U8code units it takes in UTF-16 - 1 or 2 source category(): StringUnicode general category, "Lu" source #bytesA raw byte sequence - an Array<U8> without text semantics.
Sourceown members, Equatable, Hashable, Comparable, ToString, Iterable, FromIterable, Collection, Sized, Indexable, Concatenable, Default, Clone
raw byte sequence
Implements Equatable, Hashable, Comparable (lexicographic), ToString (hex), Iterable<U8>, FromIterable<U8>, Collection<U8>, Sized<U8>, Indexable<U64, U8>, Concatenable, Default (empty), Clone
Functions
filled(size: U64, fill: U8 := 0): Bytessize bytes, each fill source fromArray(bytes: Array<U8>): Bytesthe same bytes source fromHex(text: String): ParseError ! Bytestwo hex digits a byte, either case source fromBase64(text: String): ParseError ! Bytesstandard base64 with padding source fromBase64Url(text: String): ParseError ! Bytesbase64url, with or without padding source Methods
slice(range: Range<U64>): IndexError ! Bytesa copy of the bytes in range source indexOf(part: Bytes, from: U64 := 0): U64?index of the first part at or after from source startsWith(prefix: Bytes): Booleanself begins with prefix source endsWith(suffix: Bytes): Booleanself ends with suffix source split(separator: Bytes): Array<Bytes>the pieces between separators source @writes(self)fill(value: U8, range: Range<U64>?): Undefinedsets every byte in range - all of them without one source copyFrom(source: Bytes, at: U64 := 0): IndexError ! Undefinedcopies source over self starting at at source reverse(): Bytesthe bytes in reverse order source toArray(): Array<U8>the same bytes as an Array source toHex(): Stringtwo lowercase hex digits a byte source toBase64(): Stringstandard base64 with padding source toBase64Url(): Stringbase64url - - and _ for + and /, no padding - safe in URLs and file names source crc32(): U32CRC-32 - the checksum zip files and PNG chunks carry source fnv1a(): U6464-bit FNV-1a - a fast hash, the same on every run, not for security source md5(): BytesMD5's 16 bytes - broken for security, still a common checksum source sha1(): BytesSHA-1's 20 bytes - broken for security, what git and older protocols use source sha256(): BytesSHA-256's 32 bytes source hmacSha256(key: Bytes): BytesHMAC-SHA-256 of self with key - 32 bytes that prove whoever made them knows key source compress(format: Compression := Compression.Gzip, level: U8 := 6): BytesDEFLATE-compressed - Gzip a .gz file's bytes, what an HTTP gzip body is; level 0 (stored, fastest) to 9 (smallest) source decompress(format: Compression := Compression.Gzip): ParseError ! Bytescompress the other way, for data any compressor made - a ParseError when it isn't format or its checksum is wrong source decode<Encoding: UTF8 | UTF16 | UTF32 | ASCII>(): ParseError ! Encodingthe text the bytes encode in Encoding source readInteger<Target>(at: U64, endian: Little | Big := Little): IndexError ! TargetTarget is any U* / S* source readFloat<Target>(at: U64, endian: Little | Big := Little): IndexError ! TargetTarget is any F* source @writes(self)writeInteger<Source>(at: U64, value: Source, endian: Little | Big := Little): IndexError ! UndefinedSource is any U* / S* source @writes(self)writeFloat<Source>(at: U64, value: Source, endian: Little | Big := Little): IndexError ! UndefinedSource is any F* source #stringbuilderText built a piece at a time: append each piece's #format text, then toString() once at the end - one copy rather than one per ++. See Working with Text.
Sourceown members, ToString, Default
text appended a piece at a time - each piece's text is #format's, joined once when toString() asks
Implements ToString (the text so far), Default (empty)
Functions
new(): StringBuilderno text yet source Methods
@writes(self)append(value: Unknown): StringBuildervalue's text added at the end - self, to chain source @writes(self)appendLine(value: Unknown := ""): StringBuildervalue's text and a line break - self, to chain source @writes(self)appendAll(values: Iterable<Unknown>, separator: String := ""): StringBuildereach value's text, separator between them - self, to chain source size(): U64codepoints so far source isEmpty(): Booleanno text yet source @writes(self)clear(): Undefinedback to no text source #compressionHow Bytes.compress wraps its DEFLATE data: raw, in a zlib stream, or as a .gz file (the default). decompress reads data any compressor made. See Data Formats.
Sourceown members, Equatable, Hashable, ToString, Copy
how compress wraps DEFLATE (RFC 1951) data: Deflate alone, Zlib (RFC 1950) with a header and an
Adler-32 checksum, Gzip (RFC 1952) with a header and a CRC-32
Implements Equatable, Hashable, ToString ("Gzip"), Copy
#maskA set of bits, each one on or off.
Sourceown members, Equatable, Hashable, ToString, FromString, Bitwise, Iterable, FromIterable, Sized, Indexable, Default, Clone
fixed-size set of bits
Implements Equatable, Hashable, ToString ("0b..."), FromString, Bitwise (sizes must match), Iterable<Boolean>, FromIterable<Boolean>, Sized<Boolean>, Indexable<U64, Boolean>, Default (no bits), Clone
Functions
filled(size: U64, value: Boolean := false): Masksize bits, each value source fromInteger<Source>(value: Source): MaskSource is any U* / S*, size is its bit count source parse(text: String): ParseError ! Mask"0b1010" or "1010" source Methods
test(index: U64): IndexError ! Booleanbit index is set source @writes(self)set(index: U64): IndexError ! Undefinedsets bit index source @writes(self)clear(index: U64): IndexError ! Undefinedclears bit index source @writes(self)toggle(index: U64): IndexError ! Undefinedflips bit index source @writes(self)setAll(): Undefinedsets every bit source @writes(self)clearAll(): Undefinedclears every bit source count(): U64bits set source any(): Booleanat least one bit set source all(): Booleanevery bit set source none(): Booleanno bit set source bor(other: Mask): Maska bor b source band(other: Mask): Maska band b source bxor(other: Mask): Maska bxor b source bnot(): Mask~a source shl(count: U64): Maskbits moved toward higher indices, zeros shifted in source shr(count: U64): Maskbits moved toward lower indices, zeros shifted in source ones(): Iterator<U64>indices of set bits source resize(size: U64): Maskbits kept up to size, new bits clear source toInteger<Target>(): CastError ! Targetthe bits as an integer, index 0 the least significant source #regexA compiled regular expression, made with the Regex(pattern, flags) free function.
Sourceown members, Equatable, Hashable, ToString, Clone
Implements Equatable (same source and flags), Hashable, ToString (the source), Clone
Functions
new(pattern: String, flags: String := ""): ParseError ! Regexalso written Regex(pattern, flags) source escape(text: String): Stringtext matched literally source Methods
source(): Stringthe pattern as written source flags(): Stringthe flags as written source test(text: String): Booleana match anywhere source Whether the pattern matches anywhere in s.
matchAt(text: String, start: U64): U64end of the match anchored at start, start if none source Tries the pattern starting exactly at start - the index just past the match on success, or start itself when there's no match there.
find(text: String, from: U64 := 0): Match?first match at or after from source findAll(text: String): Iterator<Match>every non-overlapping match, lazily source replace(text: String, with: String | Lambda<Match, String>): Stringfirst match, $1 / $name in with source replaceAll(text: String, with: String | Lambda<Match, String>): Stringevery match, $1 / $name in with source split(text: String, limit: U64?): Array<String>the pieces between matches - at most limit of them source groupNames(): Array<String>the named groups, in order source #queryA prepared SQL statement - what #SQL {{{ ... }}} makes - with its placeholders as bound parameters, run through the &database connection: run() gives the rows, execute() how many rows a change changed. See Servers and Browser Apps.
Sourceown members, ToString
#SQL {{{ ... }}} - its #{ } placeholders are bound parameters, never text in the statement. Run
through &database; a row is a Map of its columns - INTEGER columns as S64, REAL as F64, TEXT as
String, BLOB as Bytes, NULL as undefined - unless the query's Row is a struct: #SQL<Row> {{{ ... }}}'s,
or the @entity whose table a SELECT reads, when it selects every field of it that isn't optional (*,
or each by name). Each row is then decoded into Row, a Boolean field from SQLite's 0 or 1, and a row
that can't be one is an IOError
Implements ToString (the statement)
Methods
@effects(&database)run(): IOError ! Table<Row>every row it selects, as a Table - none for a statement that selects none source @effects(&database)first(): IOError ! Row?the first row, if there's one source @effects(&database)execute(): IOError ! U64a statement that changes rows - how many it changed source sql(): Stringthe statement, with ? for each placeholder source parameters(): Array<Unknown>the placeholders' values, in order source #wgslA shader's source in WGSL - what #WGSL {{{ ... }}} makes, its brackets checked when the program's compiled - for Gpu.shader. A Wgsl placed in another's #{ } is spliced in whole, so shaders can share pieces. See Graphics on the GPU.
Sourceown members, Equatable, ToString
#WGSL {{{ ... }}} - a shader's source, its brackets checked when it's compiled; Gpu.shader compiles the rest
Implements Equatable, ToString (the source)
Methods
source(): Stringthe WGSL, as text source #glslThe source of an OpenGL or Vulkan shader - what #GLSL {{{ ... }}} makes, its brackets checked when the program's compiled. A browser's WebGPU takes only WGSL, so it's for a host or tool that takes GLSL. A Glsl placed in another's #{ } is spliced in whole.
Sourceown members, Equatable, ToString
#GLSL {{{ ... }}} - an OpenGL / Vulkan shader's source, its brackets checked when it's compiled
Implements Equatable, ToString (the source)
Methods
source(): Stringthe GLSL, as text source #hlslThe source of a Direct3D shader - what #HLSL {{{ ... }}} makes, its brackets checked when the program's compiled. A browser's WebGPU takes only WGSL, so it's for a host or tool that takes HLSL. A Hlsl placed in another's #{ } is spliced in whole.
Sourceown members, Equatable, ToString
#HLSL {{{ ... }}} - a Direct3D shader's source, its brackets checked when it's compiled
Implements Equatable, ToString (the source)
Methods
source(): Stringthe HLSL, as text source #mslThe source of a Metal shader - what #MSL {{{ ... }}} makes, its brackets checked when the program's compiled. A browser's WebGPU takes only WGSL, so it's for a host or tool that takes MSL. A Msl placed in another's #{ } is spliced in whole.
Sourceown members, Equatable, ToString
#MSL {{{ ... }}} - a Metal shader's source, its brackets checked when it's compiled
Implements Equatable, ToString (the source)
Methods
source(): Stringthe Metal Shading Language, as text source #spirvThe source of a SPIR-V module, in its assembly text - what #SPIRV {{{ ... }}} makes, each line checked to be an instruction or a comment when the program's compiled. A browser's WebGPU takes only WGSL, so it's for a host or tool that takes SPIR-V. A Spirv placed in another's #{ } is spliced in whole.
Sourceown members, Equatable, ToString
#SPIRV {{{ ... }}} - a SPIR-V module in its assembly text, each line checked to be an instruction
(`%id = OpName ...` or `OpName ...`) or a ; comment when it's compiled
Implements Equatable, ToString (the source)
Methods
source(): Stringthe SPIR-V assembly, as text source #commandA command line - what #SHELL {{{ ... }}} makes, or Command.of(words) - its words already split, so no shell reads them again. run() runs it to its end and gives a CommandResult; attach() runs it on the program's own stdin, stdout and stderr and gives its exit code. Either needs a JavaScript host, as --run has.
Sourceown members, ToString
Implements ToString (the command line, each word quoted where it needs to be)
Functions
of(words: Array<String>): Commandthe program, then its arguments - no shell reads them source Methods
@effectsrun(): IOError ! CommandResultruns it to its end, its output kept - an IOError when it can't start source @effectsattach(): IOError ! S64runs it on this program's own stdin, stdout and stderr - its exit code source words(): Array<String>the program, then its arguments source withEnvironment(name: String, value: String): Commandthe same command, run with the variable name set to value on top of this program's own source pipe(next: Command): Commandself's output into next's input, the way a shell's | does - run, start and toString take the whole pipeline source @effectsstart(): IOError ! Processruns it beside this program - its input, output and exit read and written as it goes (see Process) source #commandresultWhat a Command run to its end gave: its exit code, and what it wrote to stdout and stderr.
Sourceown members
Fields
exitCode: S640 for successstdout: Stringeverything it wrote to standard output, as UTF-8stderr: Stringeverything it wrote to standard error, as UTF-8#processA Command running beside the program, from command.start(): write to its input, readLine its output as it comes, wait for its exit code. Reading waits a little at a time and asks &cancellation in between. Needs a JavaScript host. See Command-line Programs.
Sourceown members, ToString
a command running beside the program, started by Command.start. Reading waits for it to write, a
little at a time, asking &cancellation in between - undefined once it's cancelled. Its output is held
until it's read, so a line it wrote before exiting is still there after
Implements ToString ("Process sort running")
Methods
@effects(self)write(data: String | Bytes): IOError ! Undefinedto its standard input - an IOError once it's exited source @effects(self)closeInput(): Undefinedits standard input ends - what a command reading to the end waits for source @reads(&cancellation) @effects(self)readLine(): IOError ! String?its output's next line, without the line break, waiting for it - undefined once it's exited and every line's been read source @reads(&cancellation) @effects(self)readErrorLine(): IOError ! String?the same, from its standard error source @reads(&cancellation) @effects(self)read(): IOError ! Bytes?whatever it has written since the last read, waiting for some - undefined once it's exited and all of it's been read source @reads(&cancellation) @effects(self)wait(): IOError ! S64waits for it to exit - its exit code, -1 when a signal ended it source @effects(self)kill(): Undefinedends it now, and every command in its pipeline source @effects(self)isRunning(): Booleanit hasn't exited yet source #filewatcherChanges under a file or directory as they happen - next() waits for the next one, changes(within) gathers a burst of them. Needs a JavaScript host. See Command-line Programs.
Sourceown members, ToString
changes under a path as they happen - files created, changed and removed. Waiting asks &cancellation in
between. Needs a JavaScript host - Bun's or Node's
Implements ToString ("FileWatcher src")
Functions
@effectsnew(path: String | Path, recursive: Boolean := true): IOError ! FileWatcherwatches path - a directory's entries, and theirs too when recursive source Methods
@reads(&cancellation) @effects(self)next(): IOError ! FileChange?the next change, waiting for it - undefined once it's closed source @reads(&cancellation) @effects(self)changes(within: Duration): IOError ! Array<FileChange>every change in the next while, each once - what an editor saving a file several ways comes to source @effects(self)close(): Undefinedstops watching source #filechangeOne change a FileWatcher saw: the path, and its kind.
Sourceown members, ToString
Implements ToString ("Changed src/main.rfn")
Fields
path: Stringthe path that changed, from the watched onekind: FileChangeKindcreated, changed or removed#filechangekindWhat happened to a FileChange's path.
Sourceown members, Equatable, Hashable, ToString, Copy
Implements Equatable, Hashable, ToString ("Changed"), Copy
#definitionOne result of #comptime.definitionsWith("name") - a definition marked @name: its name, kind and file, the attribute's arguments, and the definition itself as a value. In ordinary code the results are a constant list; its syntax tree, ast(), is only there while compiling. See Compile-Time Code.
Sourceown members, ToString
Implements ToString (its kind and name)
Methods
name(): Stringas declared - "deploy" source kind(): DefinitionKindFunction, Struct, ... source file(): String"src/cli.rfn" source arguments(): Array<Unknown>the attribute's arguments, evaluated while compiling source ast(): Ast.Definitionwhile compiling - once the program runs, there's no syntax tree source value(): Unknownthe function, const or type itself - call it or use it source #definitionkindWhat kind of definition a Definition is: Function, Method, Struct, Enum, Union, Interface, Const, Type or Macro.
#matchOne match of a Regex in a string: where it is, what it matched, and its groups.
Sourceown members, Equatable, ToString, Clone
result of Regex.find / String.matches
Implements Equatable, ToString (the matched text), Clone
Methods
text(): Stringthe matched text source range(): Range<U64>codepoint range of the match source start(): U64codepoint index where it starts source end(): U64codepoint index just past it source group(index: U64): String?0 is the whole match source named(name: String): String?a named group's text, undefined when it didn't take part source groups(): Array<String?>every group's text, 1 first - undefined for one that didn't take part source namedGroups(): Map<String, String>every named group that took part source #websocketA WebSocket client: WebSocket.connect(url), then send and receive text or Bytes messages in either order, until close. Needs a JavaScript host. See Sending HTTP Requests.
Sourceown members, ToString
a WebSocket client: messages to and from a server, either way at any time. Receiving waits, asking
&cancellation in between. Needs a JavaScript host - Bun's or Node's
Implements ToString ("WebSocket wss://example.com/chat")
Functions
@reads(&cancellation) @effectsconnect(url: String | Url): IOError ! WebSocketopens a connection to a ws:// or wss:// URL - waiting until it's open source Methods
@effects(self)send(message: String | Bytes): IOError ! Undefineda text message, or a binary one for Bytes source @reads(&cancellation) @effects(self)receive(): IOError ! (String | Bytes)?the next message, waiting for it - text a String, binary Bytes; undefined once the connection's closed source @effects(self)close(code: U16 := 1000, reason: String := ""): Undefinedcloses it - 1000 is a normal close source isOpen(): Booleanneither side has closed it yet source #requestOne HTTP request - what &request is while a route runs: its method, path, the {name} segments of the route's path as params, the query string, a submitted form's fields, the headers (named in lower case) and the body. A struct whose fields all have defaults, so a test can inject one with only the parts it needs. See Servers and Browser Apps.
Sourceown members, Equatable, ToString, Clone
one HTTP request, as a route sees it through &request (see @serve). A struct - every field has a
default, so a test can inject one of its own with only the parts it needs:
inject request := Request{method := "POST", form := Map.of(("title", "Milk"))}
Implements Equatable, ToString, Clone
Fields
method: String := "GET""GET", "POST", ...path: String := "/"without the query string - "/api/todos/7"params: Map<String, String> := Map.of()each {name} segment of the route's path - "id" is "7"query: Map<String, String> := Map.of()the query string's valuesform: Map<String, String> := Map.of()a submitted form's fields (application/x-www-form-urlencoded)headers: Map<String, String> := Map.of()the request's headers, their names in lower casebody: String := ""the whole body, as text#responseWhat a route answers with - a status, headers and a body. Build one as a struct, Response{status := 404, body := "no such todo"}, or with one of its functions - Response.json, html, text, redirect, ... - which set the Content-Type for their kind of body - and what a server answers an HttpRequest with, its header names in lower case and its body text when its Content-Type is, Bytes otherwise; ok() says whether its status is a success, and bodyText() and bodyJson() read the body as UTF-8 text or as JSON. See Servers and Browser Apps.
Sourceown members, Equatable, ToString, Clone
what a route answers with (see @serve), and what a server answers an HttpRequest with. A struct -
Response{status := 404, body := "no such todo"} - or made by one of its functions, which set the
Content-Type header for their kind of body. Without a Content-Type, a String body is sent as text/plain
and Bytes as application/octet-stream
Implements Equatable, ToString, Clone
Fields
status: U16 := 200HTTP status codeheaders: Map<String, String> := Map.of()header names and values - Content-Type, Location, ...body: String | Bytes := ""what's sent backFunctions
text(body: String, status: U16 := 200): Responsetext/plain source html(page: Html, status: U16 := 200): Responsetext/html - #HTML {{{ ... }}} source json(value: Json, status: U16 := 200): Responseapplication/json - #JSON {{{ ... }}} source css(sheet: Stylesheet, status: U16 := 200): Responsetext/css - #CSS {{{ ... }}} source bytes(body: Bytes, status: U16 := 200): Responseapplication/octet-stream source redirect(to: String, status: U16 := 303): Responsea Location header, See Other by default - the usual answer to a form's POST source empty(status: U16 := 204): Responseno body, No Content by default source Methods
#httprequestA request to send to a server - a method, a url, headers and a body. Write one with #HTTP {{{ ... }}}, or as a struct, HttpRequest{url := "https://example.com/"} - with a timeout and followRedirects of its own; send() sends it through &http, giving a Promise<IOError ! Response> to await. See Sending HTTP Requests.
Sourceown members, Equatable, ToString, Clone
a request to send to a server - what #HTTP {{{ ... }}} makes, sent through &http. A struct, every field
but url with a default - HttpRequest{url := "https://example.com/"} is a GET. The Response a server
answers with has its header names in lower case, and its body as a String when its Content-Type is
text (text/*, JSON, XML, JavaScript, a form - or none), as Bytes otherwise
Implements Equatable, ToString ("GET https://example.com/"), Clone
Fields
method: String := "GET""GET", "POST", ...url: String := ""where it goes - "https://api.example.com/todos?done=false"headers: Map<String, String> := Map.of()header names and values - Content-Type, Authorization, ...body: String | Bytes := ""what's sent - nothing, for a GETfollowRedirects: Boolean := truea 3xx answer's Location followed - false gives the 3xx Response itself (a web page's browser always follows)timeout: Duration? := undefinedno answer within it is an IOError, the request given up - no limit when undefinedMethods
@effects(&http)send(): Promise<IOError ! Response>&http.send(self) - the server's answer, once it's come source #jsonJSON - Json.parse gives plain values (an object a Map<String, Unknown>), Json.decode<Order> the program's own types, field by field, and Json.encode writes any value back. Also what #JSON {{{ ... }}} makes. See Data Formats.
Sourceown members, ToString
what parse gives, for every format below: an object or table a Map<String, Unknown> of its members in
order, an array or sequence an Array<Unknown>, text a String, true and false Booleans, null undefined.
decode<Target> goes on into Target, the way its declarations say (see Type.fields): a struct from an
object, field by field (a missing field is an error unless its type takes undefined); Array, Set,
Map<String, ...> and Optional of any of these; numbers checked against their type's range (a U8 field
given 300 is an error); a unit enum case from its name; Decimal, Date, DateTime, Instant, Duration,
Url, Path, Uuid, Version and the other FromString types parsed from text. Every ParseError names where
in the document it went wrong - "the document.items[2].price is missing"
Implements ToString (the JSON text)
Functions
parse(text: String): ParseError ! Unknowna JSON document's value - a number an F64 source decode<Target>(text: String): ParseError ! Targeta JSON document as a Target - Json.decode<Array<Order>>(text) source encode(value: Unknown, indent: U64 := 0): Stringvalue as JSON - a struct an object of its fields, a Map of its entries, undefined null; with indent, each member on a line of its own, indent spaces deeper per level source #csvComma-separated values (RFC 4180): parse gives rows of fields, records maps by the header row, decode<Row> fills a Table<Row>, and write quotes what needs quoting. See Data Formats.
Sourceown members
RFC 4180 - fields separated by separator, rows by line breaks (\n or \r\n); a field in double quotes may
hold separators, line breaks and quotes written twice
Functions
parse(text: String, separator: Codepoint := ','): ParseError ! Array<Array<String>>every row's fields, the header row too source records(text: String, separator: Codepoint := ','): ParseError ! Array<Map<String, String>>each row after the first by the first row's names - a row with another number of fields is an error source decode<Row>(text: String, separator: Codepoint := ','): ParseError ! Table<Row>records() as Rows - each column by its header into the field of that name, parsed as the field's type; an empty field is undefined for an optional field source write(rows: Iterable<Iterable<Unknown>>, separator: Codepoint := ','): Stringeach value's text, quoted where it needs to be, a line break after every row source encode<Row>(rows: Table<Row>, separator: Codepoint := ','): Stringa header row of Row's fields, then each row's fields in that order, written as write does - what decode reads back; an undefined field is empty, and a table with no rows is just the header source #tomlTOML 1.0 - parse gives the root table, decode<Settings> a struct of the program's. Dates and times come back as Date, TimeOfDay, DateTime or Instant. See Data Formats.
Sourceown members
TOML 1.0 - integers S64, floats F64, a local date a Date, a local time a TimeOfDay, a local date-time a
DateTime, one with Z or an offset an Instant
Functions
#yamlThe YAML configuration files use: block mappings and sequences, flow collections, plain, quoted and block scalars. Anchors, aliases and tags are a ParseError. See Data Formats.
Sourceown members
the YAML configuration files are written in: block mappings and sequences by indentation, [flow] and
{flow} collections, plain, quoted and | > block scalars, comments; the first document of several.
Integers are S64, null ~ true false and numbers by YAML 1.2's core schema; anchors, aliases and tags
are a ParseError
Functions
#argumentsCommand-line flags filled into a struct: Arguments.parse(&args, defaults) reads --max-connections 5 into a field maxConnections, as the type it's declared with; help writes the usage text. A struct marked @args gets its own parse and help, which call parseFields and helpFields. See Command-line Programs.
Sourceown members
command-line flags filled into a struct: each field is a flag named after it - maxConnections is
--max-connections - and read as the type the field is declared with, the way decode reads text
(see Json). --name=value and --name value both work; a Boolean field is set by --name alone and
cleared by --no-name; an Array or Set field takes the flag again and again; -n value works for a field
that's alone in starting with n. Arguments that aren't flags (and everything after --) go to a field
named rest, when there is one - what follows -- to a field named passed instead, when there's one
Functions
parse<Options: Struct>(args: Array<String>, defaults: Options): ParseError ! Optionsdefaults with each flag given set - an unknown flag, a missing value or one that doesn't parse is a ParseError naming the flag source help<Options: Struct>(defaults: Options, usage: String := ""): Stringthe usage text - usage, then a line per flag with its type and default source parseFields<Options: Struct>(args: Array<String>, fields: Array<ArgumentField>): ParseError ! Optionswhat an @args struct's parse does - an Options with each flag given set, the rest their field's default; a required field left out is a ParseError source helpFields(fields: Array<ArgumentField>, usage: String := ""): Stringwhat an @args struct's help does - usage, then a line per flag with its type, description and default, wrapped at 100 columns source @effects(&stdout, &stderr)forMain<Options: Struct>(args: Array<String>, fields: Array<ArgumentField>, usage: String := ""): Optionswhat an @args @main parameter is given - --help (and -h, when no field takes h) writes the help to &stdout and exits with 0, a ParseError is written with the help to &stderr and exits with 2 source #argumentfieldOne flag of an @args struct - its field's name and declared type, its @arg description and short letter, its default and whether it has to be given - as the struct's argumentFields() lists them for Arguments.
Sourceown members
one flag of an @args struct, as the parse and help written for it give it to parseFields and helpFields
Fields
name: Stringthe field's name - maxConnections, the flag --max-connectionstype: Stringthe field's declared type, as writtendescription: Stringwhat @arg says the flag is for - "" without oneshort: String?@arg's short letter, -v - undefined for the usual one (the first letter, when no other field starts with it), "" for nonevalue: Unknownthe field's default - undefined without onerequired: Booleanno default and not optional - the flag has to be givenalone: Unknown := undefinedwhat the field is when its flag is given alone - undefined when it needs a value; one that can be alone takes a value only after =separator: String := ""what a list field's value is split on - --test=e2e,service - each piece trimmed#errorThe base of every error value - what !, !?, ?!, !!, !., !?., !(), !?(), ![] and !?[] work with (see Builtin Operators).
Sourceown members, Equatable, ToString, Clone
every error value, and every `X: Error` type
Implements Equatable, ToString (message and chain), Clone
Functions
new(message: String, cause: Error? := undefined): Erroran error with message, wrapping cause source Methods
message(): Stringwhat went wrong source cause(): Error?the error this one wraps source chain(): Array<Error>self, then each cause source root(): Errorinnermost cause source typeOf(): TypeIOError, ParseError, ... source is<Target: Error>(): Booleanself or any cause is Target source find<Target: Error>(): Target?first in chain that is Target source wrap(message: String): Errornew error with self as cause source location(): String?where it was created, when known source trace(): Array<String>frames it bubbled through with !! source #optionalA value that may be absent - what the postfix Type? desugars to.
Sourceown members, Equatable, Hashable, Comparable, ToString, Clone, Copy, Default
Type | Undefined - these work on any value whose type includes Undefined (postfix `Type?`)
Implements Default (undefined) - and Equatable, Hashable, Comparable, ToString, Clone, Copy when Type does
Methods
isDefined(): Booleana value, not undefined source isUndefined(): Booleanundefined source orElse(fallback: Type): Typea ?? b source orElseGet(fallback: Lambda<(), Type>): Typelazy a ?? b source orError<E: Error>(error: E): E ! Typea ?! b source map<Result>(f: Lambda<Type, Result>): Result?a?.b source flatMap<Result>(f: Lambda<Type, Result?>): Result?f's result, undefined when self is source filter(keep: Lambda<Type, Boolean>): Type?undefined when keep says no source ifDefined(f: Lambda<Type, Undefined>): Undefinedruns f on the value, when there is one source expect(message: String): Typepanics with message when undefined source toArray(): Array<Type>[] or [value] source #parseerrorText isn't a valid value of the type it's parsed into.
#indexerrorAn index or key is outside the collection.
#emptyerrorAn operation needs at least one element, and there are none.
#overflowerrorAn integer result doesn't fit its type - what +, -, *, //, ^, as and the checked arithmetic methods give then. +%, -%, *% wrap around instead, and +|, -|, *| fill up to the type's bounds.
#casterrorA value can't be represented in the type it's cast to.
#arrayAn ordered list - what a list literal ([1, 2, 3]) produces.
Sourceown members, Iterable, FromIterable, Collection, Sized, Indexable, Equatable, Hashable, Comparable, ToString, Concatenable, Default, Clone
Implements everything on Iterable<Type>, Indexable<U64, Type>, Concatenable<Iterable<Type>> (any Iterable on the right) - and Comparable (lexicographic) when Type does
Functions
filled(size: U64, fill: Type): Array<Type>size elements, each fill source generate(size: U64, f: Lambda<U64, Type>): Array<Type>f(0), f(1), ... f(size - 1) source of(items: ..Type): Array<Type>the items, in order - also written [a, b, c] source Methods
first(): Type?index 0, undefined when empty source The first element - undefined when the array is empty.
last(): Type?last element, undefined when empty source The last element - undefined when the array is empty.
at(index: S64): Type?negative counts from the end source indexOf(item: Type): U64?index of the first item ==, undefined when absent source lastIndexOf(item: Type): U64?index of the last item ==, undefined when absent source findIndex(where: Lambda<Type, Boolean>): U64?index of the first element where says yes to source slice(range: Range<U64>): IndexError ! Array<Type>a copy of the elements in range source @writes(self)push(item: Type): Undefinedappends at the end source Appends item in place, and returns the same array.
@writes(self)pop(): Type?removes and returns the last, undefined when empty source Removes and returns the last element - undefined when the array is empty.
@writes(self)pushFront(item: Type): Undefinedinserts at index 0 source @writes(self)popFront(): Type?removes and returns the first, undefined when empty source @writes(self)insert(index: U64, item: Type): IndexError ! Undefineditem placed before index - index == size() appends source @writes(self)removeAt(index: U64): IndexError ! Typeremoves and returns the element at index source @writes(self)remove(item: Type): Booleanfirst occurrence, false when absent source @writes(self)removeWhere(where: Lambda<Type, Boolean>): U64how many were removed source @writes(self)pushAll(items: Iterable<Type>): Undefinedappends every item, in order source @writes(self)swap(i: U64, j: U64): IndexError ! Undefinedexchanges the elements at i and j source @writes(self)fill(value: Type): Undefinedevery element set to value source @writes(self)resize(size: U64, fill: Type): Undefinedgrown with fill or cut down to size source @writes(self)truncate(size: U64): Undefinedcut down to size - nothing when already shorter source map<Result>(f: Lambda<Type, Result>): Array<Result>a ||> f source mapIndexed<Result>(f: Lambda<(U64, Type), Result>): Array<Result>f(index, element) for each source flatMap<Result>(f: Lambda<Type, Iterable<Result>>): Array<Result>f's results, one after another source filter(keep: Lambda<Type, Boolean>): Array<Type>elements keep says yes to, in order source filterMap<Result>(f: Lambda<Type, Result?>): Array<Result>f's results that aren't undefined source flatten<Inner>(): Array<Inner>Type is Iterable<Inner> source zip<Other>(other: Iterable<Other>): Array<(Type, Other)>pairs up to the shorter one's length source enumerate(): Array<(U64, Type)>(index, element) pairs source take(count: U64): Array<Type>the first count elements source drop(count: U64): Array<Type>without the first count elements source takeWhile(where: Lambda<Type, Boolean>): Array<Type>leading elements while where says yes source dropWhile(where: Lambda<Type, Boolean>): Array<Type>without the leading elements where says yes to source chunks(size: U64): Array<Array<Type>>consecutive runs of size - the last may be shorter source windows(size: U64): Iterator<Window<Type>>every run of size consecutive elements, overlapping, lazily source distinct(): Array<Type>Type: Hashable, keeps first source reverse(): Array<Type>elements in reverse order source rotate(count: S64): Array<Type>elements moved count places left, the first ones wrapping to the end - negative moves right source @writes(self)sort(): Undefinedin place, stable, Type: Comparable source @writes(self)sortBy<Key: Comparable>(key: Lambda<Type, Key>): Undefinedin place, stable, by key source @writes(self)sortWith(compare: Lambda<(Type, Type), Ordering>): Undefinedin place, stable, by compare source sorted(): Array<Type>copy source sortedBy<Key: Comparable>(key: Lambda<Type, Key>): Array<Type>copy, stable, by key source sortedWith(compare: Lambda<(Type, Type), Ordering>): Array<Type>copy, stable, by compare source isSorted(): Booleanin non-decreasing order - Type: Comparable source binarySearch(item: Type): U64 ! U64found index, or the error carries the insertion index source @writes(self, &random)shuffle(): Undefineduses &random source @writes(&random)sample(): Type?uses &random source cursor(): Cursor<Type>a Cursor at index 0 source toStack(): Stack<Type>last element on top source toQueue(): Queue<Type>first element at the front source toDeque(): Deque<Type>same order source Methods
contains(item: T): BooleanWhether any element equals item, compared structurally (the same way == compares), not by identity.
size(): NumberThe number of elements. A method call - there's no .size field to read.
#stackA last-in, first-out collection.
Sourceown members, Iterable, FromIterable, Collection, Sized, Equatable, Hashable, ToString, Concatenable, Default, Clone
last in, first out - no indexing
Implements everything on Iterable<Type> (iterates top to bottom), Concatenable (other's items on top)
Methods
@writes(self)push(item: Type): Undefinedputs item on top source @writes(self)pop(): Type?removes and returns the top, undefined when empty source peek(): Type?the top, undefined when empty source @writes(self)pushAll(items: Iterable<Type>): Undefinedpushes each item, in order - the last on top source @writes(self)drain(): Iterator<Type>pops until empty source #queueA first-in, first-out collection.
Sourceown members, Iterable, FromIterable, Collection, Sized, Equatable, Hashable, ToString, Concatenable, Default, Clone
first in, first out - no indexing
Implements everything on Iterable<Type> (iterates front to back), Concatenable (other's items behind)
Methods
@writes(self)enqueue(item: Type): Undefinedputs item at the back source @writes(self)dequeue(): Type?removes and returns the front, undefined when empty source peek(): Type?the front, undefined when empty source @writes(self)enqueueAll(items: Iterable<Type>): Undefinedenqueues each item, in order source @writes(self)drain(): Iterator<Type>dequeues until empty source @writes(self)onAdd(handler: Lambda<Type, Undefined>): Undefinedhandler runs with each item enqueued from now on, right after it's added - the item stays queued source @writes(self)setClearsAfterHandlers(clears: Boolean): Undefinedtrue empties the queue each time its handlers have run for an added item - off at first, and never without a handler source #dequeA double-ended queue: add and remove at both ends.
Sourceown members, Iterable, FromIterable, Collection, Sized, Indexable, Equatable, Hashable, ToString, Concatenable, Default, Clone
double-ended queue
Implements everything on Iterable<Type>, Indexable<U64, Type>, Concatenable
Methods
@writes(self)pushFront(item: Type): Undefinedputs item at the front source @writes(self)pushBack(item: Type): Undefinedputs item at the back source @writes(self)popFront(): Type?removes and returns the front, undefined when empty source @writes(self)popBack(): Type?removes and returns the back, undefined when empty source peekFront(): Type?the front, undefined when empty source peekBack(): Type?the back, undefined when empty source @writes(self)rotate(count: S64): Undefinedthe first count items moved to the back - negative moves the last ones to the front source toArray(): Array<Type>front to back source @writes(self)onAdd(handler: Lambda<Type, Undefined>): Undefinedhandler runs with each item pushed at either end from now on, right after it's added - the item stays source @writes(self)setClearsAfterHandlers(clears: Boolean): Undefinedtrue empties the deque each time its handlers have run for an added item - off at first, and never without a handler source #setAn unordered collection with no duplicates.
Sourceown members, Iterable, FromIterable, Collection, Sized, Equatable, Hashable, ToString, Concatenable, Default, Clone
Type: Hashable
Implements everything on Iterable<Type>, Equatable (same elements), Hashable, Concatenable (union)
Functions
of(items: ..Type): Set<Type>the distinct items - also written {a, b} source Methods
@writes(self)add(item: Type): Booleanfalse when already present source @writes(self)remove(item: Type): Booleanfalse when absent source @writes(self)addAll(items: Iterable<Type>): Undefinedadds each item source @writes(self)removeAll(items: Iterable<Type>): Undefinedremoves each item source @writes(self)retain(where: Lambda<Type, Boolean>): Undefinedkeeps only elements where says yes to source intersection(other: Set<Type>): Set<Type>in both source difference(other: Set<Type>): Set<Type>in self, not in other source symmetricDifference(other: Set<Type>): Set<Type>in exactly one of the two source isSubsetOf(other: Set<Type>): Booleanevery element is in other source isSupersetOf(other: Set<Type>): Booleanevery element of other is in self source isDisjointFrom(other: Set<Type>): Booleanno element in common source map<Result: Hashable>(f: Lambda<Type, Result>): Set<Result>f's results - equal ones merged source filter(keep: Lambda<Type, Boolean>): Set<Type>elements keep says yes to source #mapKeys of type Key to values of type Value.
Sourceown members, Iterable, FromIterable, Collection, Sized, Indexable, Equatable, Hashable, ToString, Concatenable, Default, Clone
Key: Hashable
Implements everything on Iterable<(Key, Value)>, Indexable<Key, Value>, Equatable (same entries), Concatenable (other's value wins) - and Hashable when Value does
Functions
of(entries: ..(Key, Value)): Map<Key, Value>the entries - a later key wins source fromKeys(keys: Iterable<Key>, value: Lambda<Key, Value>): Map<Key, Value>each key with value(key) source Methods
get(key: Key): Value?value at key, undefined when absent - a[b] source The value stored under key - undefined when there's none.
@writes(self)set(key: Key, value: Value): Undefinedkey now maps to value - set a[b] := value source Stores value under key in place, and returns the same map.
has(key: Key): Booleankey is present source Whether anything is stored under key.
getOr(key: Key, fallback: Value): Valuevalue at key, fallback when absent source @writes(self)getOrInsert(key: Key, value: Lambda<(), Value>): Valuevalue at key - inserted from value() first when absent source @writes(self)remove(key: Key): Value?the removed value source @writes(self)update(key: Key, f: Lambda<Value?, Value?>): Undefinedundefined result removes the key source @writes(self)merge(other: Map<Key, Value>, combine: Lambda<(Value, Value), Value>?): Undefinedother wins without combine source keys(): Iterator<Key>every key, in insertion order source values(): Iterator<Value>every value, in insertion order source entries(): Iterator<(Key, Value)>every (key, value), in insertion order source mapValues<Result>(f: Lambda<Value, Result>): Map<Key, Result>same keys, each value through f source filter(keep: Lambda<(Key, Value), Boolean>): Map<Key, Value>entries keep says yes to source invert(): Map<Value, Key>Value: Hashable, later keys win source #bimapA two-way map: look up a B by its A, or an A by its B.
Sourceown members, Iterable, FromIterable, Collection, Sized, Indexable, Equatable, Hashable, ToString, Default, Clone
one-to-one Map: every A maps to at most one B and back - A, B: Hashable
Implements everything on Iterable<(A, B)>, Indexable<A, B>, Equatable
Methods
@writes(self)set(a: A, b: B): Undefinedreplaces any pair containing a or b source getByLeft(a: A): B?the B paired with a source getByRight(b: B): A?the A paired with b source hasLeft(a: A): Booleana is paired source hasRight(b: B): Booleanb is paired source @writes(self)removeByLeft(a: A): B?removes a's pair - the B it had source @writes(self)removeByRight(b: B): A?removes b's pair - the A it had source lefts(): Iterator<A>every A source rights(): Iterator<B>every B source inverse(): BiMap<B, A>view, no copy source toMap(): Map<A, B>A to B, as a plain Map source #priorityqueueA heap: pop gives the smallest item - or the one withOrder's comparison puts first. See Collections.
Sourceown members, Iterable, FromIterable, Collection, Sized, Equatable, Hashable, ToString, Default, Clone
smallest first - Type: Comparable for new(), any Type for withOrder(compare)
Implements everything on Iterable<Type> (iterates in no set order; drain and toArray give the order)
Functions
new(): PriorityQueue<Type>smallest first - Type: Comparable source withOrder(compare: Lambda<(Type, Type), Ordering>): PriorityQueue<Type>the item compare calls Less comes out first - λ(a, b) b.compare(a) for largest first source Methods
@writes(self)push(item: Type): Undefinedadds item source @writes(self)pop(): Type?removes and returns the first, undefined when empty source peek(): Type?the first, undefined when empty source @writes(self)pushAll(items: Iterable<Type>): Undefinedpushes each item source @writes(self)drain(): Iterator<Type>pops until empty - every item, in order source toArray(): Array<Type>every item, in order - the queue unchanged source #sortedmapA map kept in key order - first, last, the nearest key with atOrBelow / atOrAbove, and a range of keys with between.
Sourceown members, Iterable, FromIterable, Collection, Sized, Indexable, Equatable, Hashable, ToString, Default, Clone
Key: Comparable - a Map whose keys stay in ascending order
Implements everything on Iterable<(Key, Value)> (ascending keys), Indexable<Key, Value>, Equatable (same entries)
Functions
new(): SortedMap<Key, Value>no entries source of(entries: ..(Key, Value)): SortedMap<Key, Value>the entries - a later key wins source Methods
get(key: Key): Value?value at key, undefined when absent - a[b] source @writes(self)set(key: Key, value: Value): Undefinedkey now maps to value - set a[b] := value source has(key: Key): Booleankey is present source getOr(key: Key, fallback: Value): Valuevalue at key, fallback when absent source @writes(self)remove(key: Key): Value?the removed value source first(): (Key, Value)?the entry with the smallest key source last(): (Key, Value)?the entry with the largest key source atOrBelow(key: Key): (Key, Value)?the entry with the largest key not above key source atOrAbove(key: Key): (Key, Value)?the entry with the smallest key not below key source between(range: Range<Key>): Iterator<(Key, Value)>the entries whose keys are in range, ascending source keys(): Iterator<Key>every key, ascending source values(): Iterator<Value>every value, by ascending key source entries(): Iterator<(Key, Value)>every (key, value), ascending source toMap(): Map<Key, Value>the same entries, as a plain Map source #trieString keys stored a codepoint at a time - every key with a prefix (withPrefix), and the longest key a text starts with (longestPrefixOf).
Sourceown members, Iterable, FromIterable, Collection, Sized, Indexable, Equatable, Hashable, ToString, Default, Clone
String keys stored a codepoint at a time - lookups by prefix
Implements everything on Iterable<(String, Value)> (keys in codepoint order, shorter first), Indexable<String, Value>, Equatable
Functions
new(): Trie<Value>no keys source of(entries: ..(String, Value)): Trie<Value>the entries - a later key wins source Methods
get(key: String): Value?value at key, undefined when absent - a[b] source @writes(self)set(key: String, value: Value): Undefinedkey now maps to value - set a[b] := value source has(key: String): Booleankey is present source @writes(self)remove(key: String): Value?the removed value source hasPrefix(prefix: String): Booleansome key starts with prefix source withPrefix(prefix: String): Iterator<(String, Value)>every entry whose key starts with prefix source longestPrefixOf(text: String): String?the longest key text starts with, undefined when none does source keys(): Iterator<String>every key, in codepoint order source #lrucacheA map of at most capacity entries - setting one more drops the least recently used. get only looks; use and getOrInsert mark an entry used.
Sourceown members, Iterable, FromIterable, Collection, Sized, Indexable, Equatable, Hashable, ToString, Default, Clone
Key: Hashable - a Map that keeps only the capacity entries used last
Implements everything on Iterable<(Key, Value)> (most recently used first), Indexable<Key, Value>
Functions
new(capacity: U64): LruCache<Key, Value>holds at most capacity entries - at least 1 source Methods
get(key: Key): Value?value at key, undefined when absent - the order as it is, so a[b] only looks source @writes(self)use(key: Key): Value?value at key, undefined when absent - the entry is now the most recently used source @writes(self)set(key: Key, value: Value): Undefinedkey now maps to value, the most recently used - the least recently used entry goes when it's full source has(key: Key): Booleankey is present - the order as it is source @writes(self)getOrInsert(key: Key, value: Lambda<(), Value>): Valuevalue at key, now the most recently used - made by value() and kept first when absent source @writes(self)remove(key: Key): Value?the removed value source capacity(): U64the most entries it keeps source entries(): Iterator<(Key, Value)>every (key, value), most recently used first source #networkA graph: nodes identified by Id, each carrying Data, and directed edges, each carrying Edge - Undefined when left out, for edges with nothing on them.
Sourceown members, Iterable, FromIterable, Collection, Sized, Indexable, Equatable, Hashable, ToString, Default, Clone
directed graph: nodes keyed by Id carrying Data, each edge carrying Edge - Id: Hashable
Implements everything on Iterable<(Id, Data)>, Indexable<Id, Data> - and Equatable when Data and Edge do
Methods
@writes(self)addNode(id: Id, data: Data): Undefinedadds a node, or replaces its data source @writes(self)removeNode(id: Id): Data?also removes its edges source hasNode(id: Id): Booleanid is a node source node(id: Id): Data?its data, undefined when absent source nodes(): Iterator<Id>every node's id source @writes(self)connect(from: Id, to: Id, edge: Edge := undefined): IndexError ! Undefinederrors when either node is missing - replaces the edge's data when it's already there source @writes(self)connectBoth(a: Id, b: Id, edge: Edge := undefined): IndexError ! Undefinedboth directions, each with edge source @writes(self)disconnect(from: Id, to: Id): Booleanremoves the edge - false when there wasn't one source hasEdge(from: Id, to: Id): Booleanan edge goes from from to to source edge(from: Id, to: Id): Edge?the edge's data, undefined when there's no edge source edges(): Iterator<(Id, Id)>every edge, (from, to) source edgeEntries(): Iterator<(Id, Id, Edge)>every edge with its data, (from, to, edge) source successors(id: Id): Iterator<Id>nodes an edge goes to from id source predecessors(id: Id): Iterator<Id>nodes with an edge to id source neighbors(id: Id): Iterator<Id>either direction source inDegree(id: Id): U64edges ending at id source outDegree(id: Id): U64edges starting at id source breadthFirst(from: Id): Iterator<Id>every node reachable from from, nearest first source depthFirst(from: Id): Iterator<Id>every node reachable from from, each branch to its end first source path(from: Id, to: Id): Array<Id>?fewest edges source isReachable(from: Id, to: Id): Booleana path of edges leads from from to to source hasCycle(): Booleansome path leads back to where it started source topologicalSort(): Error ! Array<Id>errors on a cycle source components(): Array<Set<Id>>weakly connected source stronglyConnected(): Array<Set<Id>>groups where every node reaches every other - a group before any it has edges into source cheapestPath(from: Id, to: Id, cost: Lambda<(Id, Id), Float>, estimate: Lambda<Id, Float>? := undefined): Array<Id>?least total cost (each at least 0) - Dijkstra, or A* when estimate (never above the true cost to to) is given source distances(from: Id, cost: Lambda<(Id, Id), Float>): Map<Id, Float>the least total cost to every node reachable from from - costs at least 0 source minimumSpanningTree(cost: Lambda<(Id, Id), Float>): Array<(Id, Id)>edges joining every node a path joins, edge directions ignored, at least total cost - a forest when it's in pieces source subnetwork(ids: Set<Id>): Network<Id, Data, Edge>only the nodes in ids, and edges between them source mapData<Result>(f: Lambda<Data, Result>): Network<Id, Result, Edge>same nodes and edges, each Data through f source mapEdges<Result>(f: Lambda<Edge, Result>): Network<Id, Data, Result>same nodes and edges, each edge's data through f source reverse(): Network<Id, Data, Edge>every edge flipped, keeping its data source #tableRows of a struct, like an SQL table: each field of Row is a column, and each value in the table is one row. key is optional and names the field that's the primary key - Table<User, id> holds at most one row per id, and rows are looked up by it. key is a field name rather than a type, like Vector's size.
Sourceown members, Iterable, FromIterable, Collection, Sized, Indexable, Equatable, Hashable, ToString, Concatenable, Default, Clone, own members, Indexable
Table<Row>(29)rows of a struct, like an SQL table - one from where, select, join, ... is a new Table, with no key
and no indexes
Implements everything on Iterable<Row>, Indexable<U64, Row>, Concatenable - and Equatable when Row does
Functions
fromRows(rows: Iterable<Row>): Table<Row>the rows, in order source Methods
@writes(self)insert(row: Row): Undefinedadds a row at the end source @writes(self)insertAll(rows: Iterable<Row>): Undefinedadds each row, in order source @writes(self)deleteWhere(where: Lambda<Row, Boolean>): U64how many were removed source @writes(self)updateWhere(where: Lambda<Row, Boolean>, f: Lambda<Row, Row>): U64f's row replaces each one where says yes to - how many changed source where(keep: Lambda<Row, Boolean>): Table<Row>rows keep says yes to - SQL WHERE source first(where: Lambda<Row, Boolean>): Row?first row where says yes to source select<Result: Struct>(f: Lambda<Row, Result>): Table<Result>f's result for each row - SQL SELECT source column<Field>(name: String): Array<Field>every value of one field source orderBy<Key: Comparable>(key: Lambda<Row, Key>, descending: Boolean = false): Table<Row>rows sorted by key, stable - SQL ORDER BY source groupBy<Key: Hashable>(key: Lambda<Row, Key>): Map<Key, Table<Row>>rows by key - SQL GROUP BY source summarize<Key: Hashable, Result: Struct>(key: Lambda<Row, Key>, f: Lambda<(Key, Table<Row>), Result>): Table<Result>f's result for each group of rows with the same key, groups in the order their first row comes - SQL GROUP BY with its SELECT source join<Other, Key: Hashable, Result: Struct>(other: Table<Other>, left: Lambda<Row, Key>, right: Lambda<Other, Key>, combine: Lambda<(Row, Other), Result>): Table<Result>combine(row, other) for each pair whose keys match - SQL INNER JOIN source leftJoin<Other, Key: Hashable, Result: Struct>(other: Table<Other>, left: Lambda<Row, Key>, right: Lambda<Other, Key>, combine: Lambda<(Row, Other?), Result>): Table<Result>join, and combine(row, undefined) for a row nothing matches - SQL LEFT JOIN source matching<Other, Key: Hashable>(other: Table<Other>, left: Lambda<Row, Key>, right: Lambda<Other, Key>): Table<Row>rows some row of other matches, each once - SQL WHERE EXISTS (a semi join) source notMatching<Other, Key: Hashable>(other: Table<Other>, left: Lambda<Row, Key>, right: Lambda<Other, Key>): Table<Row>rows no row of other matches - SQL WHERE NOT EXISTS (an anti join) source distinct(): Table<Row>without repeated rows, first kept source distinctBy<Key: Hashable>(key: Lambda<Row, Key>): Table<Row>the first row for each key source union(other: Table<Row>): Table<Row>self's rows then other's, without repeated rows - SQL UNION (concat, ++, keeps them - UNION ALL) source intersection(other: Table<Row>): Table<Row>self's rows that other has too, without repeats - SQL INTERSECT source difference(other: Table<Row>): Table<Row>self's rows other doesn't have, without repeats - SQL EXCEPT source limit(count: U64): Table<Row>at most the first count rows - SQL LIMIT source offset(count: U64): Table<Row>without the first count rows - SQL OFFSET source @writes(self)addIndex(field: String): Undefinedkeeps the rows by that field's value as they change, so lookup on it doesn't look at every row - SQL CREATE INDEX source lookup<Value: Hashable>(field: String, value: Value): Table<Row>rows whose field is value, in order - through the index on field when there is one source withKey(key: String): Error ! Table<Row, key>errors on duplicate keys source toArray(): Array<Row>rows in order source columns(): Array<String>Row's field names, in order - known when compiling, so there are some even with no rows source format(): Stringthe rows laid out as text: a header of columns(), a rule, then a line per row, each column as wide as its widest value and numbers on the right - just the header and rule with no rows source Table<Row, key>(8)Table with a primary key - everything on Table<Row>, plus lookups by key
Key below is the type of Row's `key` field
Implements everything on Table<Row>, Indexable<Key, Row>
Methods
get(key: Key): Row?the row with that key, undefined when absent source has(key: Key): Booleana row has that key source @writes(self)insert(row: Row): Error ! Undefinederrors when a row with that key exists source @writes(self)upsert(row: Row): Undefinedinsert or replace by key source @writes(self)update(key: Key, f: Lambda<Row, Row>): IndexError ! Undefinedf's row replaces the one with key - an IndexError when there's none source @writes(self)delete(key: Key): Row?removes the row with key, returning it source keys(): Iterator<Key>every row's key source withoutKey(): Table<Row>the same rows as a plain Table<Row> source #vectorA fixed-size vector of size elements.
Sourceown members, Equatable, Hashable, ToString, Numeric, Scalable, Iterable, Sized, Indexable, Default, Copy
fixed size - Type: Numeric
Implements Equatable, Hashable, ToString, Numeric (element-wise), Scalable<Type>, Iterable<Type>, Sized<Type>, Indexable<U64, Type>, Default (zero), Copy
Functions
zero(): Selfevery element 0 source filled(value: Type): Selfevery element value source unit(axis: U64): IndexError ! Self1 on axis, 0 elsewhere source fromArray(items: Array<Type>): Error ! Selferrors when length != size source Methods
x(): Typeindex 0 (size >= 1) source y(): Typeindex 1 (size >= 2) source z(): Typeindex 2 (size >= 3) source w(): Typeindex 3 (size >= 4) source dot(other: Self): Typesum of the elements' products source cross(other: Self): Selfsize is 3 source scale(factor: Type): Selfevery element times factor source magnitude(): Floatlength - sqrt(dot(self)) source magnitudeSquared(): Typedot(self) - no square root source normalize(): Vector<Float, size>same direction, length 1 source distance(other: Self): Floatlength of other - self source angle(other: Self): Floatradians source project(onto: Self): Vector<Float, size>component of self along onto source lerp(to: Self, t: Float): Vector<Float, size>self + (to - self) * t, element by element source map<Result>(f: Lambda<Type, Result>): Vector<Result, size>f on each element source zipWith<Result>(other: Self, f: Lambda<(Type, Type), Result>): Vector<Result, size>f on each pair of elements source toArray(): Array<Type>elements in order source toRow(): Matrix<Type, 1, size>as a one-row matrix source toColumn(): Matrix<Type, size, 1>as a one-column matrix source #matrixA fixed-size rows × cols matrix.
Sourceown members, Equatable, Hashable, ToString, Numeric, Scalable, Indexable, Default, Copy
fixed size - Type: Numeric
Implements Equatable, Hashable, ToString, Numeric (multiply is the matrix product, square only), Scalable<Type>, Indexable<(U64, U64), Type>, Default (zero), Copy
Functions
zero(): Selfevery element 0 source identity(): Selfrows == cols source filled(value: Type): Selfevery element value source fromRows(rows: Array<Array<Type>>): Error ! Selfone inner Array per row - errors when the shape isn't rows × cols source fromColumns(columns: Array<Array<Type>>): Error ! Selfone inner Array per column - errors when the shape isn't rows × cols source diagonal(values: Vector<Type, rows>): Selfrows == cols source Methods
row(index: U64): IndexError ! Vector<Type, cols>row index, as a Vector source column(index: U64): IndexError ! Vector<Type, rows>column index, as a Vector source rows(): Array<Vector<Type, cols>>every row, top to bottom source columns(): Array<Vector<Type, rows>>every column, left to right source transpose(): Matrix<Type, cols, rows>rows as columns source multiply<Other>(other: Matrix<Type, cols, Other>): Matrix<Type, rows, Other>a * b source apply(vector: Vector<Type, cols>): Vector<Type, rows>a * v source scale(factor: Type): Selfevery element times factor source determinant(): Typerows == cols source inverse(): Error ! Matrix<Float, rows, cols>errors when singular source trace(): Typerows == cols source rank(): U64linearly independent rows source power(exponent: U64): Selfrows == cols source isSquare(): Booleanrows == cols source isSymmetric(): Booleanequal to its transpose source map<Result>(f: Lambda<Type, Result>): Matrix<Result, rows, cols>f on each element source submatrix(rowRange: Range<U64>, colRange: Range<U64>): IndexError ! Matrix<Type, ?, ?>the elements within both ranges source toArray(): Array<Array<Type>>row-major source #colorOne pixel: red, green, blue and alpha, 0 to 255 each and not premultiplied - alpha 255 is opaque. Written Color.rgb(255, 136, 0), or parsed from CSS-style hex, "#ff8800".parse<Color>().
Sourceown members, Equatable, Hashable, ToString, FromString, Default, Copy
one pixel - red, green, blue and alpha, 0 to 255 each, not premultiplied (alpha 255 is opaque)
Implements Equatable, Hashable, ToString (toHex), FromString ("#rgb", "#rgba", "#rrggbb", "#rrggbbaa"), Default (transparent black), Copy
Functions
rgb(red: U8, green: U8, blue: U8): Coloropaque source rgba(red: U8, green: U8, blue: U8, alpha: U8): Colorred, green, blue and alpha source gray(value: U8): Coloropaque, red = green = blue = value source fromHsv(hue: F64, saturation: F64, value: F64): Colorhue in degrees, the others 0 to 1 - opaque source Methods
red(): U8red channel source green(): U8green channel source blue(): U8blue channel source alpha(): U8alpha channel - 255 is opaque source withAlpha(alpha: U8): Colorsame color, another alpha source lerp(to: Color, t: F64): Colorchannel by channel, t from 0 (self) to 1 (to) source over(background: Color): Colorself drawn on top of background, blended by self's alpha source luminance(): F640 to 1 - Rec. 709 weights on the channels as stored source toHex(): String"#rrggbb" when opaque, "#rrggbbaa" otherwise source #imageA bitmap: width × height Colors, with (0, 0) at the top-left, x growing right and y down - kept as RGBA bytes, which toRgba and Image.fromRgba hand over as they are. Image.decode reads any ImageFormat - PNG, JPEG, GIF, BMP, QOI, TGA, PNM - and encode (or encodePng, encodeJpeg, ...) writes one; pair them with &fs to load and save files. Gpu's readImage gives what the GPU drew as one.
Sourceown members, Equatable, Hashable, ToString, Indexable, Default, Clone
a bitmap - width × height Colors, row-major; (0, 0) is the top-left pixel, x grows right and y down
Implements Equatable, Hashable, ToString ("Image 640x480"), Indexable<(U64, U64), Color> (keyed x then y), Default (0x0), Clone
Functions
new(width: U64, height: U64, fill: Color := Color.default()): Imagewidth × height pixels, each fill source generate(width: U64, height: U64, f: Lambda<(U64, U64), Color>): Imagef(x, y) for each pixel source fromPixels(width: U64, height: U64, pixels: Array<Color>): Error ! Imagerow-major - errors when there aren't width * height source fromRgba(width: U64, height: U64, rgba: Bytes): Error ! Image4 bytes a pixel - red, green, blue, alpha - row-major; errors when there aren't width * height * 4 source decode(bytes: Bytes): ParseError ! Imageany ImageFormat, told by its first bytes - a GIF's first frame source Methods
width(): U64pixels across source height(): U64pixels down source pixel(x: U64, y: U64): IndexError ! Colorthe color at (x, y) source @writes(self)setPixel(x: U64, y: U64, color: Color): IndexError ! Undefinedsets the pixel at (x, y) source pixels(): Array<Color>row-major source toRgba(): Bytes4 bytes a pixel - red, green, blue, alpha - row-major source @writes(self)fill(color: Color): Undefinedevery pixel set to color source map(f: Lambda<Color, Color>): Imagef on each pixel source crop(x: U64, y: U64, width: U64, height: U64): IndexError ! Imageerrors when the region isn't all inside source resize(width: U64, height: U64, smooth: Boolean := false): Imagenearest neighbour - smooth averages when shrinking and blends (bilinear) when growing, weighting by alpha source flipHorizontal(): Imagemirrored left to right source flipVertical(): Imagemirrored top to bottom source rotate(quarterTurns: U8): Imageclockwise source @writes(self)draw(source: Image, x: S64, y: S64): Undefinedsource on top with its top-left at (x, y), blended by its alpha - clipped to self source encode(format: ImageFormat, quality: U8 := 90): Bytesin format - quality, 1 to 100, is JPEG's source encodePng(): Byteslossless - 8-bit gray, gray and alpha, RGB or RGBA, whichever holds the pixels in least source encodeJpeg(quality: U8 := 90): Bytesbaseline, 4:2:0 - quality 1 (smallest) to 100 (best); alpha dropped source encodeGif(): Bytesup to 256 colors, dithered when there are more; alpha under 128 is transparent source encodeBmp(): Bytes32-bit BGRA, uncompressed source encodeQoi(): Byteslossless - RGB, or RGBA when any pixel isn't opaque source encodeTga(): Bytesrun-length encoded - 24-bit, or 32-bit when any pixel isn't opaque source encodePnm(): Bytesraw - PGM for gray pixels, PPM for color, PAM when any pixel isn't opaque source #imageformatThe image file formats Image reads and writes. ImageFormat.detect(bytes) says which one some bytes are, by how they start.
Sourceown members, Equatable, Hashable, ToString, Copy
an image file format: PNG (any color type and bit depth, interlaced too), JPEG (baseline and
progressive), GIF, BMP (1 to 32 bits a pixel, uncompressed), QOI, TGA (plain and run-length
encoded) and PNM (PBM, PGM, PPM and PAM, plain and raw)
Implements Equatable, Hashable, ToString ("Png"), Copy
Functions
detect(bytes: Bytes): ImageFormat?the format the bytes are in, by their first bytes - undefined when it's none of these source #rectAn axis-aligned box - hit tests (containsPoint), overlaps (intersects, intersection), and bounding boxes (Rect.around, union). See Drawing and Animation.
Sourceown members, Equatable, Hashable, ToString, Copy
an axis-aligned box - x and y its top-left corner (the smallest of each, y growing downward as on
an Image), width and height never negative
Implements Equatable, Hashable, ToString (its corner and size), Copy
Functions
new(x: F64, y: F64, width: F64, height: F64): Rectfrom a corner and a size - a negative size counts back from that corner source fromCorners(x1: F64, y1: F64, x2: F64, y2: F64): Rectfrom two opposite corners, either way round source around(points: Iterable<(F64, F64)>): EmptyError ! Rectthe smallest Rect holding every point - its bounding box source Methods
x(): F64left edge source y(): F64top edge source width(): F64never negative source height(): F64never negative source right(): F64x() + width() source bottom(): F64y() + height() source center(): (F64, F64)the middle point source area(): F64width() * height() source isEmpty(): Booleanno area - a zero width or height source containsPoint(x: F64, y: F64): Booleanthe point is inside - the left and top edges count, the right and bottom don't source containsRect(other: Rect): Booleanother lies wholly inside source intersects(other: Rect): Booleanthe two share some area source intersection(other: Rect): Rect?the area both cover, undefined when none source union(other: Rect): Rectthe smallest Rect holding both source expand(by: F64): Rectby more on every side, around the same center - a negative by shrinks it, down to nothing source translate(dx: F64, dy: F64): Rectmoved by dx, dy source scale(factor: F64): Rectevery coordinate times factor - about (0, 0) source #noisePerlin noise - a smooth random value for each point, the same for the same seed: terrain, clouds, wobble. fractal layers finer detail on top.
Sourceown members
Perlin noise - for each point a value roughly between -1 and 1 that changes smoothly as the point
moves, the same for the same seed. Whole-number points are all 0, so sample between them
Functions
new(seed: U64): Noisethe noise this seed picks source Methods
at(x: F64, y: F64 := 0.0, z: F64 := 0.0): F64the value at (x, y, z) - in 1, 2 or 3 dimensions source fractal(x: F64, y: F64 := 0.0, z: F64 := 0.0, octaves: U64 := 4, persistence: F64 := 0.5): F64octaves layers at twice the frequency each, persistence times the strength - rougher detail on a smooth shape, still roughly -1 to 1 source #easingThe curves an animation follows from 0 to 1 - Easing.OutCubic.apply(t), or between(from, to, t).
Sourceown members, Equatable, Hashable, ToString, Copy
the curves of easings.net - progress t from 0 to 1 in, how far along the animation is out
Implements Equatable, Hashable, ToString ("InOutCubic"), Copy
Methods
#videoFrames of one size, each shown for its own time - read whole from an animated GIF, an APNG, a Y4M or a Motion JPEG AVI with Video.decode, GIF and APNG frames composed as their disposal says. encode writes one back; to write a long one a frame at a time, use VideoEncoder.
Sourceown members, ToString
frames of one size, each shown for its own time, played loops times (0 forever) - read whole from a
file; to write a long one a frame at a time, without holding every Image, see VideoEncoder
Implements ToString ("Video 640x480, 90 frames")
Functions
new(width: U64, height: U64, loops: U64 := 0): Videono frames yet source decode(bytes: Bytes): ParseError ! Videoany VideoFormat, told by its first bytes - GIF and APNG frames composed as their disposal and blending say; a PNG with no animation is one frame source Methods
width(): U64pixels across source height(): U64pixels down source frames(): Array<Image>in order source durations(): Array<F64>how long each frame shows, in seconds source frameCount(): U64how many frames source duration(): F64every frame's duration, added up - seconds source fps(): F64frames a second, on average - 0 when there are none source loops(): U64how many times it plays - 0 forever source frameAt(time: F64): Image?the frame showing time seconds in - undefined past the end source @writes(self)add(frame: Image, duration: F64 := 1.0 / 30.0): Error ! Undefineda frame at the end, shown for duration seconds - an Error when its size isn't the video's source encode(format: VideoFormat, quality: U8 := 90): Bytesin format - GIF and APNG keep each frame's duration, Y4M and AVI play at the average rate; quality is AVI's JPEG quality source #videoencoderA video being written a frame at a time - add each Image (frames the GPU renders, read back with readImage), then finish for the file. Each frame is kept only compressed, so a long render needn't hold every Image.
Sourceown members
a video being written a frame at a time - each frame kept only compressed (GIF's indices, APNG's
deflated rows, Y4M's YCbCr, AVI's JPEG), so a long render needn't hold every Image
Functions
new(format: VideoFormat, width: U64, height: U64, fps: F64 := 30.0, quality: U8 := 90, loops: U64 := 0): VideoEncoderquality is AVI's JPEG quality, 1 to 100; loops is GIF's and APNG's - 0 forever source Methods
@writes(self)add(frame: Image, duration: F64? := undefined): Error ! Undefinedthe next frame, shown for duration seconds (1 / fps when undefined - only GIF and APNG keep each frame's) - an Error when its size isn't the video's source frames(): U64how many have been added source finish(): Bytesthe whole file source #videoformatThe video formats: animated GIF (256 colors a frame), APNG (lossless), Y4M (raw YCbCr - what ffmpeg and video encoders take in) and AVI (Motion JPEG).
Sourceown members, Equatable, Hashable, ToString, Copy
a video file format: animated GIF (at most 256 colors a frame), APNG (lossless, any colors), Y4M
(raw YCbCr 4:2:0 - what ffmpeg and video encoders take in) and AVI (Motion JPEG)
Implements Equatable, Hashable, ToString ("Gif"), Copy
Functions
detect(bytes: Bytes): VideoFormat?the format the bytes are in, by their first bytes - a PNG is Apng source #soundAudio: samples from -1 to 1, each channel's taken sampleRate times a second - made with Sound.generate, read with Sound.decode (WAV, AIFF, AU, FLAC), then mixed, resampled, sliced and written back with encode.
Sourceown members, Equatable, ToString
audio: samples - floats, -1 to 1 at full scale - each channel's taken sampleRate times a second
Implements Equatable, ToString ("Sound 44100 Hz, 2 channels, 3.5 s")
Functions
new(sampleRate: U64 := 44100, channels: U64 := 2, duration: F64 := 0.0): Soundsilence, duration seconds of it source generate(sampleRate: U64, channels: U64, duration: F64, f: Lambda<(F64, U64), F64>): Soundf(time, channel) for each sample - time in seconds from the start source fromSamples(sampleRate: U64, channels: U64, samples: Array<F64>): Error ! Soundthe channels interleaved - an Error when they're not a whole number of frames source decode(bytes: Bytes): ParseError ! Soundany AudioFormat, told by its first bytes source Methods
sampleRate(): U64samples a second, each channel source channels(): U64how many source frames(): U64samples a channel source duration(): F64in seconds source sample(frame: U64, channel: U64): F64?one sample - undefined outside the sound source @writes(self)setSample(frame: U64, channel: U64, value: F64): IndexError ! Undefinedsets one sample source samples(): Array<F64>every sample, the channels interleaved source channel(index: U64): IndexError ! Soundone channel, alone source withChannels(count: U64): Soundas count channels - all averaged to 1, 1 copied to all, otherwise each its own (the extra ones repeating the first) source resample(sampleRate: U64): Soundat another rate - band-limited (windowed sinc), so nothing aliases source slice(start: F64, end: F64): Soundfrom start to end seconds - clipped to the sound source append(other: Sound): Soundother after self - made self's rate and channels first source mix(other: Sound, at: F64 := 0.0, gain: F64 := 1.0): Soundother times gain added in at seconds in - self's rate and channels, as long as whichever ends later source gain(factor: F64): Soundevery sample times factor source peak(): F64the largest magnitude of any sample - 1 is full scale source normalize(level: F64 := 1.0): Soundscaled so its peak is level source encode(format: AudioFormat, bits: U8 := 16): Bytesin format at bits a sample (see each encode below) source encodeWav(bits: U8 := 16): BytesPCM at 8, 16 or 24 bits; 32 is IEEE floats source encodeAiff(bits: U8 := 16): Bytesbig-endian PCM at 8, 16, 24 or 32 bits source encodeAu(bits: U8 := 16): BytesSun/NeXT: big-endian PCM at 8, 16, 24 or 32 bits source encodeFlac(bits: U8 := 16): Byteslossless at 8 to 24 bits - LPC and mid/side stereo, as compact as common encoders' default source #audioformatThe audio formats Sound reads and writes: WAV, AIFF (and AIFC), AU, and lossless FLAC.
Sourceown members, Equatable, Hashable, ToString, Copy
an audio file format: WAV (PCM, floats, A-law and mu-law), AIFF and AIFC, AU, and FLAC
Implements Equatable, Hashable, ToString ("Wav"), Copy
Functions
detect(bytes: Bytes): AudioFormat?the format the bytes are in, by their first bytes source #gpuThe host's GPU device, through its WebGPU - what every other GPU object is made with. Gpu.request() gives it: a browser's, or under Bun the webgpu package's (Dawn), which computes but has no canvas - or an IOError on a host without one (a WASI runtime, an older browser). Shaders are WGSL; a frame is drawn by recording GpuRenderPasses and handing them to submit, and animate has the host call a @js function on every frame the display draws. GpuComputePasses go to submit too, and read brings a buffer's bytes back. See Graphics on the GPU.
Sourceown members, ToString
the host's GPU, through its WebGPU - a web page's, in a browser that has it, or under Bun and Node the
`webgpu` package's (Dawn's), when it's installed: there it runs on a thread of its own, and there's no
canvas to draw on, only compute. A host without one (a WASI runtime, a native executable) has no
device: Gpu.request is an IOError there. The device is asked for ahead of the first call. Shaders are
WGSL; a shader that doesn't compile, or a pipeline that doesn't fit its shaders, is reported on the
host's console when the GPU gets to it, not as an error here
Implements ToString ("Gpu")
Functions
@effectsrequest(): IOError ! Gputhe host's device - an IOError when it has none source Methods
@effectscanvas(id: String): IOError ! GpuCanvasthe page's canvas element with that id, set up for drawing in the format the browser prefers - an IOError when there's none source @effectsoffscreen(width: U64, height: U64): GpuCanvasa target to draw into off any page - RGBA, width x height - what readImage reads back; under Bun the only kind there is source @effectsbuffer(size: U64, usage: Array<GpuBufferUsage>): GpuBuffersize bytes, zeroed - CopyDestination and CopySource are always added, so it can be written and read source @effectsfloatBuffer(values: Array<F64>, usage: Array<GpuBufferUsage>): GpuBuffera buffer holding values, each as an F32 source @effectsindexBuffer(indices: Array<U64>): GpuBufferan Index buffer holding indices, each as a U16 - for setIndexBuffer's Uint16 source @effectswrite(buffer: GpuBuffer, data: Bytes, offset: U64 := 0): Undefineddata copied into buffer at offset (a multiple of 4) source @effectswriteFloats(buffer: GpuBuffer, values: Array<F64>, offset: U64 := 0): Undefinedvalues copied in, each as an F32 source @effectswriteMatrix(buffer: GpuBuffer, matrix: Matrix<F64, 4, 4>, offset: U64 := 0): Undefinedcolumn by column, each value an F32 - what WGSL's mat4x4<f32> reads source @effectsshader(code: Wgsl | String): GpuShaderWGSL - #WGSL {{{ ... }}} - compiled for this device source @effectsdepthTexture(canvas: GpuCanvas): GpuTexturea Depth24Plus texture the canvas's size - for a GpuRenderPass's depth source @effectspipeline(options: GpuPipelineOptions): GpuPipelinea render pipeline - its bind group layouts taken from the shaders source @effectscomputePipeline(shader: GpuShader, entry: String := "computeMain"): GpuComputePipelinethe shader's @compute function named entry - its bind group layouts taken from the shader source @effectsbindGroup(pipeline: GpuPipeline | GpuComputePipeline, group: U32, buffers: Array<GpuBuffer>): GpuBindGroupbuffers[i] at @binding(i) of the shaders' @group(group) source @effectssubmit(passes: Array<GpuRenderPass | GpuComputePass>): Undefinedruns the passes, in order, and shows what they drew on their canvases source @effectsread(buffer: GpuBuffer): Promise<IOError ! Bytes>what buffer holds once the passes submitted before have run - an IOError when the GPU can't map it source @effectsreadFloats(buffer: GpuBuffer): Promise<IOError ! Array<F64>>the same, read as F32s - what floatBuffer wrote, or a shader's array<f32> source @effectsreadImage(target: GpuCanvas): Promise<IOError ! Image>what's been drawn into target, an offscreen one or a page's canvas - settled at once under Bun, once the GPU's done on a page source @effectsanimate(frame: String): Undefinedthe host calls the @js function named frame (time: F64) on every frame the display draws, time in milliseconds - until a call ends with an error source #gpucanvasA page's <canvas>, set up for the device - its width, height and the format a pipeline drawing on it writes. Made with gpu.canvas(id).
Sourceown members, ToString
a page's canvas, set up for the device
Implements ToString ("GpuCanvas 640x480")
Fields
format: GpuTextureFormatwhat its pixels are - what a pipeline drawing on it targetswidth: U64pixels acrossheight: U64pixels down#gpubufferMemory on the GPU - vertices, indices, uniforms or a compute shader's storage, by its usages. gpu.floatBuffer makes one holding numbers as F32s; writeFloats, writeMatrix and write change what it holds, and gpu.read / readFloats give it back.
Sourceown members, ToString
Implements ToString ("GpuBuffer of 64 bytes")
Fields
size: U64in bytes#gputextureAn image on the GPU - here the depth buffer gpu.depthTexture(canvas) makes, for a pipeline with depth := true.
Sourceown members, ToString
Implements ToString ("GpuTexture Depth24Plus")
Fields
format: GpuTextureFormatwhat its pixels are#gpushaderA WGSL module, compiled for the device by gpu.shader(code) - its @vertex and @fragment functions are what a pipeline runs. A shader that doesn't compile is reported on the host's console.
Sourceown members, ToString
Implements ToString ("GpuShader")
#gpupipelineHow vertices are drawn: the shaders, the layout of the vertex buffers, the topology, culling and the depth test - built once from GpuPipelineOptions, then set on each pass that draws with it.
Sourceown members, ToString
Implements ToString ("GpuPipeline")
#gpubindgroupBuffers bound to one of a pipeline's @groups - buffers[i] at @binding(i). Made with gpu.bindGroup(pipeline, group, buffers).
Sourceown members, ToString
Implements ToString ("GpuBindGroup")
#gpurenderpassOne pass's commands - the canvas cleared to a color, then pipelines, buffers, bind groups and draws, in order. It's recorded in Refingere and nothing reaches the GPU until gpu.submit, so a frame's passes cross to the host together.
Sourceown members, ToString
one render pass: the canvas cleared to a color, then its commands in order. Nothing reaches the GPU
until it's submitted - a frame's passes go together, in one Gpu.submit
Implements ToString ("GpuRenderPass with 3 commands")
Functions
new(target: GpuCanvas, clear: Color := Color.rgb(0, 0, 0), depth: GpuTexture? := undefined): GpuRenderPassdraws on target - cleared to clear, and depth to 1 when given source Methods
@writes(self)setPipeline(pipeline: GpuPipeline): Undefinedwhat the draws after it use source @writes(self)setVertexBuffer(slot: U32, buffer: GpuBuffer): Undefinedthe pipeline's buffers[slot] source @writes(self)setIndexBuffer(buffer: GpuBuffer, format: GpuIndexFormat := GpuIndexFormat.Uint16): Undefinedwhat drawIndexed reads source @writes(self)setBindGroup(index: U32, group: GpuBindGroup): Undefinedthe shaders' @group(index) source @writes(self)draw(vertices: U32, instances: U32 := 1, firstVertex: U32 := 0, firstInstance: U32 := 0): Undefinedvertices from the vertex buffers, in order source @writes(self)drawIndexed(indices: U32, instances: U32 := 1, firstIndex: U32 := 0): Undefinedvertices by the index buffer source #gpucomputepipelineA compute shader's @compute entry point, built once with gpu.computePipeline(shader) - computeMain unless another is named - then set on each pass that dispatches it.
Sourceown members, ToString
a compute shader's entry point, built once with Gpu.computePipeline and set on each pass that
dispatches it
Implements ToString ("GpuComputePipeline")
#gpucomputepassOne compute pass's commands - pipelines, bind groups and dispatches, in order. Each dispatch(x, y, z) runs the shader on a grid of workgroups. Recorded in Refingere like a GpuRenderPass, and sent with it in gpu.submit; gpu.read then brings the results back.
Sourceown members, ToString
one compute pass: its commands in order, each dispatch running the pipeline's @compute function on a
grid of workgroups. Like a GpuRenderPass, it's recorded here and reaches the GPU with Gpu.submit
Implements ToString ("GpuComputePass with 3 commands")
Functions
new(): GpuComputePassan empty pass source Methods
@writes(self)setPipeline(pipeline: GpuComputePipeline): Undefinedwhat the dispatches after it run source @writes(self)setBindGroup(index: U32, group: GpuBindGroup): Undefinedthe shader's @group(index) source @writes(self)dispatch(x: U32, y: U32 := 1, z: U32 := 1): Undefinedx × y × z workgroups - each of @workgroup_size invocations source #gpuvertexattributeOne value each vertex holds - its format, its offset in bytes and the shader's @location it's read at.
Sourceown members, Equatable, ToString, Clone
one value per vertex (or per instance) - read in the shader at @location(location)
Implements Equatable, ToString, Clone
Fields
format: GpuVertexFormathow many values, and of whatoffset: U64 := 0in bytes, from the start of each vertexlocation: U32the shader's @location#gpuvertexlayoutHow one vertex buffer is laid out: the bytes from one vertex to the next (stride) and the attributes each holds, advanced per vertex or per instance.
Sourceown members, Equatable, ToString, Clone
one vertex buffer's layout - setVertexBuffer's slot i is the pipeline's buffers[i]
Implements Equatable, ToString, Clone
Fields
stride: U64bytes from one vertex to the nextattributes: Array<GpuVertexAttribute>what each vertex holdsstep: GpuVertexStep := GpuVertexStep.Vertexper vertex, or per instance#gpupipelineoptionsWhat gpu.pipeline builds a pipeline from - a struct with defaults, so only what differs is written: GpuPipelineOptions{shader, target := canvas, buffers := [layout], depth := true}.
Sourceown members, ToString, Clone
what a pipeline is built from - a struct, so only what differs from the defaults is written:
GpuPipelineOptions{shader, target := canvas, buffers := [layout], depth := true}
Implements ToString, Clone
Fields
shader: GpuShaderits vertex and fragment entry pointstarget: GpuCanvaswhat it draws on - the format it writesbuffers: Array<GpuVertexLayout> := []the vertex buffers, by slotvertexEntry: String := "vertexMain"the shader's @vertex functionfragmentEntry: String := "fragmentMain"the shader's @fragment functiontopology: GpuTopology := GpuTopology.TriangleListhow vertices make shapescullMode: GpuCullMode := GpuCullMode.Nonewhich faces are left outdepth: Boolean := falsetested against, and written to, a Depth24Plus texture - nearer wins#gpuvertexformatWhat one vertex attribute is - one to four 32-bit floats, unsigned or signed integers.
#gpuvertexstepWhether a vertex buffer's attributes advance once per vertex or once per instance.
#gputopologyHow a pipeline makes shapes out of the vertices it's given.
#gpucullmodeWhich faces a pipeline leaves out - by the winding of their vertices, counter-clockwise facing front.
#gpuindexformatHow wide each index in an index buffer is.
#gputextureformatWhat a texture's pixels are - a canvas's format, or a depth buffer's.
#rangeWhat a..<b and a..=b produce. Type must be Steppable.
Sourceown members, Equatable, Hashable, ToString, Iterable, Collection, Sized, Copy
Type: Steppable
Implements Equatable, Hashable, ToString ("1..<5"), Iterable<Type>, Collection<Type>, Sized<Type>, Copy
Functions
new(start: Type, end: Type, inclusive: Boolean := false): Range<Type>start up to end - including end when inclusive source Methods
start(): Typefirst value source end(): Typewhere it stops - included only when isInclusive() source isInclusive(): Boolean..= vs ... / ..< source contains(value: Type): Booleana in b source step(by: U64): Iterator<Type>every by-th value, from start source reverse(): Iterator<Type>its values from the end back to start source overlaps(other: Range<Type>): Booleansome value is in both source intersection(other: Range<Type>): Range<Type>?the values in both, undefined when none are source clamp(value: Type): Typevalue kept within the range source toArray(): Array<Type>every value, in order source toInclusive(): Range<Type>a..<b as a..=previous(b) source #iteratorProduces a sequence of values one at a time, lazily - what an Iterable produces, and what calling a generator (a function that uses Yield) returns.
Sourceown members, Iterable
lazy, single pass - every Iterable method is available and lazy where it returns a sequence
also what calling a generator returns - a function whose body contains yield
Implements Iterable<Type> (returns itself)
Functions
empty(): Iterator<Type>no items source once(item: Type): Iterator<Type>item, then done source repeat(item: Type): Iterator<Type>infinite source iterate(seed: Type, next: Lambda<Type, Type>): Iterator<Type>infinite source countFrom(start: Type): Iterator<Type>start, start + 1, ... - infinite; start..<∞ source fromLambda(next: Lambda<(), Type?>): Iterator<Type>until undefined source Methods
@writes(self)next(): Type?the next item, undefined once exhausted source @writes(self)peek(): Type?the next item without consuming it source map<Result>(f: Lambda<Type, Result>): Iterator<Result>f on each item source flatMap<Result>(f: Lambda<Type, Iterable<Result>>): Iterator<Result>f's results, one after another source filter(keep: Lambda<Type, Boolean>): Iterator<Type>items keep says yes to source filterMap<Result>(f: Lambda<Type, Result?>): Iterator<Result>f's results that aren't undefined source take(count: U64): Iterator<Type>at most the first count items source drop(count: U64): Iterator<Type>without the first count items source takeWhile(where: Lambda<Type, Boolean>): Iterator<Type>leading items while where says yes source dropWhile(where: Lambda<Type, Boolean>): Iterator<Type>without the leading items where says yes to source stepBy(step: U64): Iterator<Type>every step-th item, starting with the first source chain(other: Iterable<Type>): Iterator<Type>self's items, then other's source zip<Other>(other: Iterable<Other>): Iterator<(Type, Other)>pairs, up to the shorter one source enumerate(): Iterator<(U64, Type)>(index, item) pairs source chunks(size: U64): Iterator<Array<Type>>consecutive runs of size - the last may be shorter source windows(size: U64): Iterator<Window<Type>>every run of size consecutive items, overlapping source scan<State>(initial: State, f: Lambda<(State, Type), State>): Iterator<State>each running state, f applied from initial source inspect(f: Lambda<Type, Undefined>): Iterator<Type>runs f on each item as it passes, unchanged source cycle(): Iterator<Type>infinite, buffers the first pass source distinct(): Iterator<Type>Type: Hashable source distinctBy<Key: Hashable>(key: Lambda<Type, Key>): Iterator<Type>the first item of each key source chunkBy<Key>(key: Lambda<Type, Key>): Iterator<Array<Type>>each run of neighbouring items with equal keys source @writes(self)nth(index: U64): Type?the item at index, consuming up to it source @writes(self)last(): Type?the final item, consuming every one source @writes(self)collect(): Array<Type>every remaining item, into an Array source @writes(self)collectInto<Target: FromIterable<Type>>(): TargetTarget.fromIterable(self) - into a Set, Map, String, ... source #cursorA position within a sequence that can move and read the value at it.
Sourceown members, Equatable, Clone
a movable position over an indexed sequence (Array, String, Bytes, Deque) - reading, lookahead, backtracking
Implements Equatable (same source and position), Clone (independent position, shared source)
Functions
over(source: Indexable<U64, Type> & Sized<Type>): Cursor<Type>a Cursor at index 0 of source source Methods
position(): U64index of the current item source current(): Type?undefined at the end source peek(offset: U64 := 1): Type?the item offset ahead, undefined past the end source previous(): Type?the item before the current one, undefined at the start source @writes(self)advance(count: U64 := 1): Undefinedmoves count items forward, stopping at the end source @writes(self)retreat(count: U64 := 1): Undefinedmoves count items back, stopping at the start source @writes(self)seek(position: U64): IndexError ! Undefinedjumps to position - an IndexError past the end source isAtStart(): Booleanposition() == 0 source isAtEnd(): Booleanno current item source remaining(): U64items from position to the end source @writes(self)consume(item: Type): Booleanadvances when current is item source @writes(self)consumeWhile(where: Lambda<Type, Boolean>): Array<Type>items while where says yes, advancing past them source mark(): U64same as position - for backtracking with seek source rest(): Array<Type>from position to the end source sliceFrom(start: U64): Array<Type>from start up to position source #windowA view of several neighbouring elements of a sequence at once.
Sourceown members, Iterable, Sized, Indexable, Equatable
fixed-length view into a sequence, as produced by windows(size)
Implements Iterable<Type>, Sized<Type>, Indexable<U64, Type>, Equatable
Methods
#urlA parsed absolute web address - its scheme, host, port, path, query and fragment - which resolves links the way a browser does and builds queries with their escapes.
Sourceown members, Equatable, Hashable, ToString, FromString, Copy
a parsed absolute URL - scheme://user@host:port/path?query#fragment. The scheme and host are kept in
lower case, the rest as written (percent-escapes and all); query() decodes. Two Urls are equal when
they're written the same
Implements Equatable, Hashable, ToString, FromString, Copy
Functions
parse(text: String): ParseError ! Url"https://example.com:8080/a/b?q=1#top" - a ParseError without a scheme source encode(text: String): Stringpercent-escapes every byte but A-Z a-z 0-9 - . _ ~ - for a path segment or query value source decode(text: String): ParseError ! Stringthe text the escapes stand for, as UTF-8 source Methods
scheme(): String"https" source user(): String?what's before the @ in the authority, when there's one source host(): String"example.com" - "" when there's no authority (mailto:x@y.org) source port(): U16?the port written, undefined when there's none source path(): String"/a/b" - "/" when there's a host and no path source query(): Map<String, String>the query's names and values, decoded ("+" is a space) - the last of a repeated name wins source fragment(): String?what's after "#" source origin(): String"https://example.com:8080" source resolve(reference: String): ParseError ! Urlreference read relative to self, as a browser follows a link - "../c" against https://x.org/a/b is https://x.org/c source withPath(path: String): Urlthe same with another path source withQuery(name: String, value: String): Urlthe same with name set to value in the query - replaced where it is, added at the end otherwise source #pathA file path as segments - joined, split into name, stem and extension, normalized and made relative - without asking the file system anything.
Sourceown members, Equatable, Hashable, Comparable, ToString, FromString, Copy
a file path - "/"-separated segments, rooted at "/" or relative. Only text: the file system isn't asked,
so nothing has to exist - &fs takes one wherever it takes a path's text. A backslash is read as "/", empty and "." segments are dropped as it's made; ".." stays
until normalize. An empty relative path is "."
Implements Equatable, Hashable, Comparable (by its text), ToString ("src/main.rfn"), FromString, Copy
Functions
of(text: String): Paththe path text writes source parse(text: String): ParseError ! Paththe same - a ParseError for empty text source Methods
join(child: String): Pathchild inside self - "src".join("lib/a.rfn") is src/lib/a.rfn; a rooted child replaces self source parent(): Path?self without its last segment - undefined for "/" and "." source name(): Stringthe last segment - "main.rfn" source stem(): Stringthe name without its extension - "main" source extension(): String?"rfn" - undefined when the name has no "." past its first character source withName(name: String): Paththe same folder, another last segment source withExtension(extension: String): Pathanother extension - "" drops it source segments(): Array<String>each segment in order source isAbsolute(): Booleanrooted at "/" source normalize(): Path"a/.." folded away - a leading ".." stays on a relative path source relativeTo(base: Path): Pathhow to get from base to self - "../lib/a.rfn" source startsWith(prefix: Path): Booleanprefix's segments begin self's - whole segments, not characters source matchesGlob(pattern: String): Booleanpattern's "/"-separated segments match the path's: * any run of characters but /, ? any one, [abc] [a-z] [!abc] one of a set, {a,b} either alternative, a whole ** segment any number of directories (none too) source #uuidA 128-bit unique id. v4() is random and v7() starts with the time, so v7s sort by when they were made - both from the context, so a test injecting a SeededRandom and a FixedClock gets the same ids every run.
Sourceown members, Equatable, Hashable, Comparable, ToString, FromString, Copy
a 128-bit unique id, RFC 9562 - written as 32 hex digits in groups of 8-4-4-4-12
Implements Equatable, Hashable, Comparable (v7s in the order they were made), ToString ("0b2b5c1e-8f3a-4c6d-9e0f-1a2b3c4d5e6f"), FromString, Copy
Functions
nil(): Uuidall zeros source @writes(&random)v4(): Uuidrandom - 122 bits from &random source @reads(&clock) @writes(&random)v7(): Uuid&clock's Unix milliseconds, then bits from &random - they sort by when they were made source parse(text: String): ParseError ! Uuideither case, with or without dashes or {braces} source fromBytes(bytes: Bytes): ParseError ! Uuidexactly 16 bytes source Methods
#versionA semantic version - 1.4.2-beta.1+build.7 - compared the way semver.org orders them, a pre-release before its release. satisfies("^1.2 || ~2.0.3") checks it against npm-style ranges.
Sourceown members, Comparable, Equatable, Hashable, ToString, FromString, Copy
a semantic version (semver.org) - major.minor.patch, a pre-release label after -, build metadata after +
Implements Equatable (build metadata included), Hashable, Comparable (semver precedence; a pre-release before its release, build metadata ignored), ToString ("1.4.2-beta.1+build.7"), FromString, Copy
Functions
new(major: U64, minor: U64 := 0, patch: U64 := 0): Versiona release version source parse(text: String): ParseError ! Version"1.4.2", "1.4.2-beta.1+build.7" - a leading v allowed source Methods
major(): U64the first number - an incompatible change bumps it source minor(): U64the second number - new features source patch(): U64the third number - fixes source preRelease(): String?"beta.1" - undefined for a release source build(): String?"build.7" - undefined without one source isPreRelease(): Booleanhas a pre-release label source nextMajor(): Version(major + 1).0.0 source nextMinor(): Versionmajor.(minor + 1).0 source nextPatch(): Versionmajor.minor.(patch + 1) - the release itself for a pre-release source satisfies(range: String): ParseError ! Booleannpm-style ranges - "^1.2", "~1.2.3", ">=1.0.0 <2.0.0", "1.x", "1.2 - 1.4", "*", alternatives joined by || - a pre-release only when the range names one of the same major.minor.patch source #promiseA Type that isn't ready yet - what calling an @async function returns. await pauses the @async function it's in until the promise settles, and gives its value; code that isn't @async uses block() instead. It settles once, with a value - errors travel in Type, so a failing call gives a Promise<IOError ! Bytes> and (await p)!! bubbles the error. See Async.
Sourceown members, ToString
a Type that isn't ready yet - what calling an @async function returns (its return statements give a Type).
Everything runs on one thread, one task at a time: calling an @async function starts its body at once,
up to its first await, then the caller carries on. await p pauses the @async function it's in until p
settles, and other tasks run meanwhile. A promise settles once, with a value - there's no separate
rejected state: errors travel in Type, so an @async function returning IOError ! Bytes gives a
Promise<IOError ! Bytes>, and (await p)!! bubbles the error like any other
Implements ToString when Type does ("Promise(pending)" until it settles)
Functions
resolved(value: Type): Promise<Type>already settled source withResolver(): (Promise<Type>, Lambda<Type, Undefined>)a pending promise and the lambda that settles it - for callback APIs source all(promises: Iterable<Promise<Type>>): Promise<Array<Type>>every value, in order, once all have settled - an error among them stays in its place source race(promises: Iterable<Promise<Type>>): Promise<Type>the first to settle - the rest keep running source firstOk(promises: Iterable<Promise<Type>>): Promise<Type>the first to settle with a value that isn't an error - the last error when every one gives one source allLimited<Item>(items: Iterable<Item>, limit: U64, start: Lambda<Item, Promise<Type>>): Promise<Array<Type>>start on each item, at most limit running at once - every value, in the items' order source @effectsretry(attempts: U64, start: Lambda<(), Promise<Type>>, wait: Duration := Duration.zero()): Promise<Type>start again while it gives an error, attempts times at most - waiting wait, then twice that each time; the last error once &cancellation is cancelled source parallel<Args, Result>(work: Function<Args, Result>, arguments: ..Unknown): Promise<Result>work(..arguments) on another thread (see @parallel) - work a self-contained function named there, arguments and result copied; at once where there are no threads source @effectsparallelUnsafe<Args, Result>(work: Function<Args, Result>, arguments: ..Unknown): Promise<Result>the same with nothing checked: the work gets copies of the caller's context values, does any I/O, and what it changes is its own copies' - or shared values' source @effectssleep(duration: Duration): Promise<Undefined>settles once duration has passed on &clock, without blocking - early when &cancellation is cancelled or reaches its deadline source @effectsnextFrame(): Promise<F64>settles with the time, in milliseconds, once the display draws its next frame - a web page's; elsewhere 16 ms on &clock source Methods
isSettled(): Booleanhas a value yet source peek(): Type?the value once settled, undefined before source map<Result>(f: Lambda<Type, Result>): Promise<Result>f's result once self settles source then<Result>(f: Lambda<Type, Promise<Result>>): Promise<Result>chains another @async step source zip<Other>(other: Promise<Other>): Promise<(Type, Other)>both values, once both have settled source inspect(f: Lambda<Type, Undefined>): Promise<Type>runs f on the value once it settles - an error too - and settles with the same source @effectstimeout(after: Duration): Promise<TimeoutError ! Type>TimeoutError when it hasn't settled within after - or when &cancellation is cancelled first, with the CancelledError as its cause source @effectsblock(): Typeruns the event loop until it settles - for code that isn't @async source #timerA task run later on &clock - once with Timer.after, again and again with Timer.every, or on each frame the display draws with Timer.eachFrame - until it's cancelled. It runs on the event loop between other tasks; in a web page the page runs it, the program carrying on meanwhile. See The Browser.
Sourceown members, ToString
a task run later on &clock - once (after), again and again (every), or on each frame the display draws
(eachFrame) - until it's cancelled. It runs on the event loop, between other tasks, never in the middle
of one, and an @app's components it changes render again after it. In a web page the page runs the
timers - the program doesn't wait for them, they come; anywhere else the event loop waits on &clock for
the next one, so a FixedClock (see Components) runs them as fast as they're due. A program ends once its
@main is done and nothing it waits for is left - a Timer that's still active keeps it going
Implements ToString ("Timer every 1s", "Timer once, stopped")
Functions
@effectsafter(delay: Duration, task: Lambda<(), Undefined>): Timertask run once delay has passed on &clock source @effectsevery(interval: Duration, task: Lambda<(), Undefined>): Timertask run every interval on &clock - each time an interval after the last was due, so they don't drift source @effectseachFrame(task: Lambda<F64, Undefined>): Timertask run with the time, in milliseconds, on each frame the display draws - a web page's; elsewhere every 16 ms on &clock source Methods
#channelValues sent from one thread to another, each received once, in the order they were sent. receive() waits for the next one, and gives undefined once the channel's closed and empty. Handed to another thread, it's the same channel there.
Sourceown members, ToString
values sent from one thread to another - each received once, in the order they were sent
Implements ToString ("Channel with 2 waiting")
Functions
new(): Channel<Type>an open one, with nothing sent yet source receiveAny(channels: Array<Channel<Type>>): (index: U64, value: Type)?the next value sent to any of them, waiting for one - with its channel's index; undefined once every one is closed and empty, or &cancellation is cancelled source Methods
@writes(self)send(value: Type): Booleana copy of value sent - false once closed source @writes(self)receive(): Type?the next value, waiting for one - undefined once closed and empty, or once &cancellation is cancelled while it waits source @writes(self)tryReceive(): Type?the next value when there's one already, undefined otherwise source @writes(self)close(): Undefinedno more sends - receive gives what's left, then undefined source size(): U64how many wait to be received source #mutexA lock every thread shares - locked(λ ...) runs a piece of work while no other thread holds it. Waiting asks &cancellation. See Async and Threads.
Sourceown members, ToString
a lock every thread shares - lock() waits while another thread holds it. Copied into a thread's work it
stays the same lock. Waiting asks &cancellation, like Channel.receive
Implements ToString ("Mutex locked")
Functions
new(): Mutexunlocked source Methods
@reads(&cancellation, &clock) @writes(self)lock(): CancelledError ! Undefinedwaits until no one holds it, then holds it - a CancelledError when &cancellation stops the wait source @writes(self)tryLock(): Booleanholds it when no one does - false, at once, when someone does source @writes(self)unlock(): Undefinedlets it go - nothing when it isn't held source isLocked(): Booleansomeone holds it source @reads(&cancellation, &clock) @writes(self)locked<Result>(f: Lambda<(), Result>): CancelledError ! Resultlock(), f(), unlock() - f's result source #semaphorePermits every thread shares - at most so many hold one at a time, so withPermit limits how much work runs at once.
Sourceown members, ToString
permits every thread shares - acquire() waits while every permit is held. Limits how many threads do
something at once - three downloads at a time
Implements ToString ("Semaphore with 2 of 3 free")
Functions
new(permits: U64): Semaphorepermits free permits source Methods
@reads(&cancellation, &clock) @writes(self)acquire(): CancelledError ! Undefinedwaits for a free permit, and holds it source @writes(self)tryAcquire(): Booleanholds a free permit - false, at once, when none is free source @writes(self)release(): Undefinedgives a permit back source @reads(&cancellation, &clock) @writes(self)withPermit<Result>(f: Lambda<(), Result>): CancelledError ! Resultacquire(), f(), release() - f's result source available(): U64how many permits are free source #cancellationA signal that work should stop. Nothing is stopped by force: the work asks between its steps, &cancellation.check()!!, and ends with a CancelledError error. Whoever starts the work injects one as &cancellation and cancels it - or gives it a deadline with after.
Sourceown members, ToString
a signal that work should stop. Nothing is stopped by force: the work asks between its steps -
`&cancellation.check()!!` - and ends with a CancelledError. Whoever starts work injects a Cancellation
as &cancellation for it, and cancels it - or gives it a deadline - when the work isn't wanted anymore.
Waiting notices it: Promise.sleep and timeout end early, and Channel.receive stops waiting
Implements ToString ("Cancellation running", "Cancellation cancelled: user left")
Functions
new(): Cancellationone not cancelled yet source never(): Cancellationone nothing cancels - cancel does nothing to it; &cancellation's default source @reads(&clock)after(duration: Duration): Cancellationone that cancels itself once duration has passed on &clock source Methods
child(): Cancellationone cancelled when self is, and cancellable on its own too source @writes(self)cancel(reason: String := "cancelled"): Undefinedasks the work to stop - the first reason given is kept, and every child is cancelled too source @writes(self)onCancel(f: Lambda<String, Undefined>): Undefinedf runs with the reason when cancel is called - at once when it already has been; never for one that can't be cancelled source @reads(&clock)isCancelled(): Booleancancelled, past its deadline, or its parent is source @reads(&clock)reason(): String?why it's cancelled - undefined while it isn't source @reads(&clock)check(): CancelledError ! Undefineda CancelledError with the reason once it's cancelled - nothing until then source #genRandom values for property tests - Gen.arrays(Gen.integers()).check(λ(xs) xs.sorted().size() = xs.size())!! runs the property on a hundred values, small ones first, and on a failure reports the smallest failing value it found. See Testing.
Sourceown members
random values for property tests. A Gen makes a value at a size from 0 to 100, reading &random for
its choices: small sizes make small values - numbers near zero, short strings and arrays. check runs
a property on values of growing size; when it finds one the property fails for, it shrinks it - it
replays the choices that made it, fewer and smaller (at smaller sizes, with some left out, zeroed or
halved), and keeps whatever still fails - so a Gen built with map or andThen shrinks too, and the
value reported is small: [0, 0, 0] rather than [-110, 37, 902]. Inject a SeededRandom as &random to
make the same values again
Implements (none)
Functions
from(make: Lambda<U64, Type>): Gen<Type>make(size) - one of your own, built from &random source constant(value: Type): Gen<Type>value, every time source integers(low: S64 := -1000, high: S64 := 1000): Gen<S64>within low..=high - near zero at small sizes, or near low when the range doesn't hold zero source floats(low: F64 := -1000.0, high: F64 := 1000.0): Gen<F64>within low..high, the same way source booleans(): Gen<Boolean>true or false source strings(alphabet: String := "abcdefghijklmnopqrstuvwxyz0123456789 ", maxLength: U64 := 20): Gen<String>characters from alphabet - longer at bigger sizes source arrays<Item>(items: Gen<Item>, maxLength: U64 := 20): Gen<Array<Item>>items' values - longer at bigger sizes source oneOf(values: Array<Type>): Gen<Type>one of values - a panic for none source Methods
map<Result>(f: Lambda<Type, Result>): Gen<Result>f of each value - to build a struct from simpler ones source filter(keep: Lambda<Type, Boolean>): Gen<Type>only values keep accepts - a panic after 100 refused in a row source andThen<Result>(f: Lambda<Type, Gen<Result>>): Gen<Result>the Gen f picks for each value, run at the same size source @writes(&random)sample(size: U64 := 10): Typeone value at size source @writes(&random)check(property: Lambda<Type, Boolean>, runs: U64 := 100): PropertyError ! Undefinedproperty for runs values - a PropertyError naming the smallest value it shrank a failure to source #jsvalueA JavaScript value held as it is - a DOM node, a function, a class instance, anything that has no Refingere type of its own to cross as. Refingere can keep it, compare it, print it and pass it to another @js function, which gets the very same object back - and reach into it: get and set its properties, call its methods, construct an instance, await a JavaScript promise with toPromise, or hand JavaScript a function with JsValue.callback. See JavaScript and TypeScript and The Browser.
Sourceown members, ToString
a JavaScript value held as it is (see @js and the browser's types above). What crosses into JavaScript -
a property set, a method's arguments - goes as @js's arguments do: numbers, text, Booleans, undefined,
Arrays, Maps, structs as plain objects, an Element as its element, a JsValue as itself. What comes back -
a property, a method's result - is a number, text, a Boolean, undefined (null too), or else a JsValue:
every object, an Array and a plain object too, so it stays the same object (items and toData copy one).
A Refingere function can't cross itself: JsValue.callback makes one JavaScript can call
Implements ToString ("JsValue #3")
Functions
global(): IOError ! JsValueJavaScript's globalThis - an IOError where there's no JavaScript (a WASI runtime) source @effectscallback(task: Lambda<Array<Unknown>, Unknown>): JsValuea JavaScript function running task with its arguments, giving back what task gives - an @app's components render again after it source Methods
get(name: String): Unknownthe property source @writes(self)set(name: String, value: Unknown): Undefinedthe property set - value crossing as an argument does source @effectscall(name: String, arguments: ..Unknown): Error ! Unknownits method name called - what it throws as an Error source @effectsinvoke(arguments: ..Unknown): Error ! Unknownit called, as a function source @effectsconstruct(arguments: ..Unknown): Error ! Unknown`new` it - an instance of the class it is source items(): Array<Unknown>an Array, or anything JavaScript can iterate - a NodeList, a Set - item by item, each as get gives it source toData(): Unknownit as plain data, all the way down - an Array an Array, a plain object a Map source typeOf(): StringJavaScript's typeof - "object", "function" ... source @effectstoPromise(): Promise<Error ! Unknown>a JavaScript promise's value once it settles - an Error when it's rejected; any other value at once source @effectson(kind: String, handler: Lambda<DomEvent, Undefined>): Listenerhandler run on each kind event of any JavaScript event target - a WebSocket, a MediaQueryList ... source @effectsevents(kind: String, limit: U64 := 1000): EventQueuethe same, queued source #pageThe web page the program runs in - its window and document together. Page.current() gives it, or an IOError where there's no page (Bun, a WASI runtime). It finds and creates Elements, reads and changes the address and history, and listens for the window's events. See The Browser.
Sourceown members, ToString
the web page the program runs in: its window and its document, through the host's own DOM - a
browser's, or happy-dom's in a test. A host with no page (Bun, Node, a WASI runtime) has none:
Page.current is an IOError there. Every Element, DomEvent, Listener and EventQueue below is the page's.
A call the page refuses - a selector that doesn't parse, a method an object doesn't have - is a
mistake in the program, so a panic with JavaScript's message
Implements ToString ("Page https://example.com/")
Functions
current(): IOError ! Pagethe page the program runs in - an IOError where there's none source Methods
body(): Elementthe <body> source head(): Elementthe <head> source root(): Elementthe <html> source find(selector: String): Element?the first element the CSS selector matches - undefined when none does source findAll(selector: String): Array<Element>every element it matches, in the page's order source byId(id: String): Element?the element with that id source create(tag: String): Elementa new <tag> - not on the page until it's appended somewhere source fromHtml(markup: Html): Array<Element>the elements markup makes - #HTML {{{ ... }}} - not on the page yet source focused(): Element?the element that has the keyboard's focus source @writes(self)addStyle(css: Stylesheet | String): Elementa <style> with css - #CSS {{{ ... }}} - added to the <head> source title(): Stringwhat the browser's tab shows source @writes(self)setTitle(title: String): Undefinedthe tab's title changed source url(): Urlthe page's address source @effectsreload(): Undefinedloads the page again source @effectspushHistory(url: String): Undefineda new entry in the history, its address url, without loading anything - going back to it is a "popstate" event source @effectsreplaceHistory(url: String): Undefinedthe current entry's address changed, without loading anything source @effectsback(): Undefinedone entry back in the history, as the browser's back button source @effectsforward(): Undefinedone entry forward source width(): F64the viewport's width, in CSS pixels source height(): F64the viewport's height, in CSS pixels source pixelRatio(): F64device pixels per CSS pixel - 2 on most phones source scrollX(): F64how far the page is scrolled across source scrollY(): F64how far the page is scrolled down source @effectsscrollTo(x: F64, y: F64): Undefinedscrolls the page there source @effectsalert(message: String): Undefinedthe browser's message box - the page waits until it's closed source @effectsconfirm(message: String): BooleanOK and Cancel - whether OK was chosen source @effectsprompt(message: String, value: String := ""): String?a line of text asked for, value already in - undefined when cancelled source localStorage(): WebStoragekept by the browser for this site, across visits source sessionStorage(): WebStoragekept for this tab, until it's closed source @effectson(kind: String, handler: Lambda<DomEvent, Undefined>): Listenerhandler run on each kind event the window hears - "resize", "popstate", and every element's events that bubble up: "keydown", "click", ... source @effectsevents(kind: String, limit: U64 := 1000): EventQueueeach kind event the window hears, queued - the oldest dropped past limit source window(): JsValueJavaScript's window - for what Page doesn't cover source document(): JsValueJavaScript's document source #elementOne element of the page - its text, attributes, classes and style, the elements around it, and its events. Text set on it is always text; markup goes in as Html, which #HTML {{{ }}} makes safely. on(kind, handler) runs a handler while each event happens; events(kind) queues them for an @async loop.
Sourceown members, Equatable, ToString
one element of a page - what Page.find, Page.create and an event's target give. Two are equal when
they're the same element. Text set or appended is always text, never parsed as markup - only an Html
(#HTML {{{ ... }}}, which escapes what it's given) is
Implements Equatable (the same element), ToString ("<button id=save>")
Functions
from(value: JsValue): Element?value when it's an element - undefined when it's anything else source Methods
tag(): String"div" - lowercase source id(): Stringits id attribute - "" when there's none source text(): Stringall the text inside it source @writes(self)setText(text: String): Undefinedits content replaced by text source html(): Htmlthe markup inside it source @writes(self)setHtml(markup: Html): Undefinedits content replaced by markup source attribute(name: String): String?an attribute's value - undefined when it hasn't got it source @writes(self)setAttribute(name: String, value: String): Undefinedan attribute set - added when it hasn't got it source @writes(self)removeAttribute(name: String): Undefinedan attribute taken away source hasAttribute(name: String): Booleanwhether it has the attribute, whatever its value source value(): Stringwhat an <input>, <select> or <textarea> holds - "" for other elements source @writes(self)setValue(value: String): Undefinedwhat an <input>, <select> or <textarea> holds changed - no "input" event source isChecked(): Booleana checkbox's or radio button's state source @writes(self)setChecked(checked: Boolean): Undefineda checkbox or radio button checked, or not source @writes(self)setDisabled(disabled: Boolean): Undefinedwhether it's disabled - an input or button that can't be used source classes(): Array<String>its classes, in order source hasClass(name: String): Booleanwhether name is one of its classes source @writes(self)addClass(name: String): Undefinedname added to its classes - once source @writes(self)removeClass(name: String): Undefinedname taken from its classes source @writes(self)toggleClass(name: String, on: Boolean? := undefined): Booleanadded when it's missing and removed when it's there - or added or removed as on says; whether it's there now source style(property: String): Stringits own style's value for a CSS property - "background-color" - "" when unset source @writes(self)setStyle(property: String, value: String): Undefinedits own style's value for a CSS property - "" removes it source computedStyle(property: String): Stringthe value the page ends up using, from every stylesheet source parent(): Element?the element it's in source children(): Array<Element>the elements directly in it, in order source next(): Element?the element after it, in the same parent source previous(): Element?the element before it source find(selector: String): Element?the first element inside it the CSS selector matches source findAll(selector: String): Array<Element>every element inside it it matches source closest(selector: String): Element?itself or the nearest element around it the selector matches source matches(selector: String): Booleanthe selector matches it source contains(other: Element): Booleanother is it, or inside it source @writes(self)append(child: Element | String | Html): Undefinedadded at the end inside it - an Element moved there, text as text, Html parsed source @writes(self)prepend(child: Element | String | Html): Undefinedadded at the start inside it source @writes(self)before(sibling: Element | String | Html): Undefinedadded just before it, in its parent source @writes(self)after(sibling: Element | String | Html): Undefinedadded just after it source @writes(self)replaceWith(other: Element | String | Html): Undefinedother in its place - it's off the page then source @writes(self)remove(): Undefinedtaken off the page - it can be appended again source @writes(self)clear(): Undefinedeverything inside it removed source clone(deep: Boolean := true): Elementa copy, not on the page - with everything inside it when deep source @effectsfocus(): Undefinedgives it the keyboard's focus source @effectsblur(): Undefinedtakes the focus away source @effectsclick(): Undefinedclicked, as if by the user - its "click" handlers run now source @effectsscrollIntoView(): Undefinedthe page scrolled until it can be seen source bounds(): Rectwhere it is in the viewport, in CSS pixels source @effectson(kind: String, handler: Lambda<DomEvent, Undefined>): Listenerhandler run on each kind event on it, or on what's inside it - "click", "input", "keydown", ... - while the event happens, so it can preventDefault source @effectsevents(kind: String, limit: U64 := 1000): EventQueueeach kind event on it queued, to be taken in order - the oldest dropped past limit source @effectsdispatch(kind: String, detail: Unknown := undefined): Booleana kind event that bubbles, happening on it now - a CustomEvent holding detail when given; false when a handler prevented its default source canvas(): IOError ! Canvas2da <canvas>'s 2D drawing - an IOError for any other element source js(): JsValuethe JavaScript element - for what Element doesn't cover source #domeventWhat happened on the page, read as it happened - its kind, target, the key pressed, where the pointer was, what the input held. While its handlers run it can preventDefault() and stopPropagation().
Sourceown members, ToString
what happened on the page, read as it happened: what a key event's key was, where a pointer was, what an
input held. Fields that don't apply to its kind are empty - "" text, 0, false or undefined
Implements ToString ("DomEvent click on <button id=save>")
Fields
kind: String"click", "keydown", "input" ...target: Element?the element it happened on - undefined when that's not an element (the window)key: Stringa key event's key - "a", "Enter", "ArrowUp"code: Stringa key event's physical key - "KeyA", whatever the keyboard's layoutx: F64a pointer's position across the viewport, in CSS pixelsy: F64a pointer's position down the viewportshift: Booleanwhether Shift was heldctrl: Booleanwhether Control was heldalt: Booleanwhether Alt (Option) was heldmeta: Booleanwhether Meta (Command, Windows) was helddeltaX: F64a wheel event's scroll acrossdeltaY: F64a wheel event's scroll downvalue: String?the target's value then - an <input>'s, when it has onechecked: Boolean?the target's checked state then - a checkbox'srepeat: Booleana key held down, repeatingtime: F64when it happened, in milliseconds since the page loadedMethods
@effectspreventDefault(): Undefinedthe browser doesn't do what it otherwise would - follow the link, submit the form - only while its handlers run (Element.on); a queued event's has passed source @effectsstopPropagation(): Undefinedelements further out don't hear it - while its handlers run source js(): JsValuethe JavaScript event - held only while its handlers run source #listenerA handler listening for an event, from on - remove() it to stop.
Sourceown members, ToString
#eventqueueA target's events, kept in the order they happened until taken - await queue.next() in an @async loop takes them one at a time while the page goes on. Holds at most its limit, the oldest dropped first.
Sourceown members, ToString
a target's events, kept in the order they happened until taken - for an @async loop that handles one
at a time: `for _ in inf { let key ≔ await keys.next() ... }`. The page goes on while
it waits; an @app's components render again after each event it takes. Keeps at most its limit, the
oldest dropped first
Implements ToString ("EventQueue click, 2 waiting")
Methods
@writes(self)next(): Promise<DomEvent>the oldest event not taken yet - settles when one comes, if none is waiting source @writes(self)take(): DomEvent?the oldest waiting, without waiting - undefined when none is source size(): U64how many are waiting source @writes(self)close(): Undefinedstops listening - what's waiting can still be taken source isClosed(): Booleanwhether close was called source #webstorageThe browser's localStorage or sessionStorage for the site - text by key. Store anything else as JSON.
Sourceown members, ToString
the browser's storage for this site - text by key. localStorage's lasts across visits, sessionStorage's
until the tab is closed. Write anything else as JSON - Builtin.toJson / Json.parse
Implements ToString ("WebStorage with 3 keys")
Methods
get(key: String): String?what's kept under key - undefined when nothing is source @writes(self)set(key: String, value: String): Undefinedvalue kept under key - in place of what was there source @writes(self)remove(key: String): Undefinedwhat's kept under key forgotten source @writes(self)clear(): Undefinedeverything removed source keys(): Array<String>every key, in the browser's order source size(): U64how many keys source #canvas2dA <canvas>'s 2D drawing, from element.canvas() - rectangles, paths, text, and an Image's pixels. For 3D, or a lot of shapes each frame, see Gpu.
Sourceown members, ToString
a <canvas>'s 2D drawing, from Element.canvas - (0, 0) at the top-left, x across and y down, in the
canvas's own pixels. Shapes are drawn with the fill or stroke set last; a path is begun, moved and
lined along, then filled or stroked
Implements ToString ("Canvas2d 640x480")
Methods
width(): U64pixels across source height(): U64pixels down source @writes(self)resize(width: U64, height: U64): Undefineda new size - which clears it source @writes(self)clear(): Undefinedevery pixel transparent source @writes(self)setFill(color: Color | String): Undefinedwhat shapes and text are filled with - a Color, or CSS: "tomato", "#336699" source @writes(self)setStroke(color: Color | String): Undefinedwhat outlines are drawn with source @writes(self)setLineWidth(width: F64): Undefinedhow thick outlines are source @writes(self)setFont(font: String): Undefinedtext's font, as CSS writes it - "16px sans-serif" source @writes(self)setAlpha(alpha: F64): Undefinedhow opaque what's drawn next is - 0 to 1 source @writes(self)fillRect(x: F64, y: F64, width: F64, height: F64): Undefineda rectangle filled - x, y its top-left corner source @writes(self)strokeRect(x: F64, y: F64, width: F64, height: F64): Undefineda rectangle's outline drawn source @writes(self)clearRect(x: F64, y: F64, width: F64, height: F64): Undefinedthose pixels transparent source @writes(self)fillText(text: String, x: F64, y: F64): Undefinedtext with its baseline's left end at x, y source measureText(text: String): F64how wide text is in the current font source @writes(self)beginPath(): Undefinedstarts a new path source @writes(self)moveTo(x: F64, y: F64): Undefinedthe path's pen lifted and put down at x, y source @writes(self)lineTo(x: F64, y: F64): Undefineda straight line to x, y source @writes(self)arc(x: F64, y: F64, radius: F64, start: F64 := 0.0, end: F64 := 6.283185307179586): Undefinedan arc around x, y from angle start to end, in radians - a full circle by default source @writes(self)closePath(): Undefineda line back to where the path started source @writes(self)fill(): Undefinedthe path filled source @writes(self)stroke(): Undefinedthe path's outline drawn source @writes(self)save(): Undefinedthe fill, stroke, transform ... kept, to restore source @writes(self)restore(): Undefinedback to what the last save kept source @writes(self)translate(x: F64, y: F64): Undefinedwhat's drawn next moved by x, y source @writes(self)rotate(angle: F64): Undefinedwhat's drawn next turned clockwise by angle, in radians, around (0, 0) source @writes(self)scale(x: F64, y: F64): Undefinedwhat's drawn next stretched source @writes(self)drawImage(image: Image, x: F64, y: F64): Undefinedimage's pixels put there as they are - its top-left at x, y source pixels(): Imagewhat the canvas shows now source js(): JsValuethe JavaScript CanvasRenderingContext2D source #pointerThe raw address of a Type value. It doesn't own what it points to: Pointer.allocate puts a value on &heapAllocator, and nothing frees it until free is called.
Sourceown members, Equatable, Hashable, Comparable, ToString, Copy
raw address of a Type value - doesn't own it, so nothing frees it but free()
Implements Equatable (same address), Hashable, Comparable (address order), ToString (hex address), Copy
Functions
to(value: Type): Pointer<Type>address of an existing value source allocate(value: Type): OutOfMemoryError ! Pointer<Type>copies value onto &heapAllocator source allocateMany(count: U64): OutOfMemoryError ! Pointer<Type>room for count Types in a row on &heapAllocator, not yet written source Methods
read(): Typethe value at the address source @writes(self)write(value: Type): Undefinedoverwrites the value at the address source offset(count: S64): Pointer<Type>count Types further along source address(): U64the address as a number source cast<Target>(): Pointer<Target>same address, read as Target source @writes(self)free(): Undefinedback to &heapAllocator - only for allocate() / allocateMany() pointers source #rcpointerA reference-counted pointer: shared ownership of a value on &heapAllocator. Each clone adds an owner, and the value is freed when the last one is dropped. weak gives a WeakPointer that doesn't count as one.
Sourceown members, Equatable, Hashable, ToString, Clone
shared ownership of a heap value - each clone is one more owner, the value is freed when the last one is dropped
Implements Equatable (same allocation), Hashable, ToString, Clone (one more owner, same value)
Functions
new(value: Type): OutOfMemoryError ! RcPointer<Type>on &heapAllocator, count 1 source Methods
read(): Typethe value source @writes(self)write(value: Type): Undefinedseen by every owner source count(): U64current number of owners source isUnique(): Booleancount() == 1 source pointer(): Pointer<Type>borrowed - valid while any owner is alive source weak(): WeakPointer<Type>a non-owning handle, doesn't add to count() source unwrap(): Type?the value when this is the only owner, undefined otherwise source #weakpointerA handle to an RcPointer's value that isn't one of its owners, so it doesn't keep the value alive. It breaks reference cycles, e.g. a child pointing back at its parent. upgrade gives a new owner while the value is alive and undefined once it's freed.
Sourceown members, Equatable, Hashable, Clone
a handle to an RcPointer's value that isn't an owner - breaks reference cycles (a child pointing back at its parent)
Implements Equatable (same allocation), Hashable, Clone (one more handle) - not Copy, every handle is counted
Methods
#structA value made of named fields - see Struct Definition. Combined with &&.
Sourceown members, Equatable, Hashable, ToString, Clone, Copy
struct with named fields
Implements Equatable, Hashable, ToString, Clone, Copy when every field does (@derive generates them)
Methods
fields(): Map<String, Unknown>name -> value source fieldNames(): Array<String>in declaration order source get(name: String): Unknown?by name, undefined when missing source with(changes: Map<String, Unknown>): Error ! Selfcopy with some fields replaced source merge<Other: Struct>(other: Other): Self && Othera && b as values source typeOf(): Typethe struct's own type source #enumA tagged union: exactly one of a fixed set of cases - see Enum Definition. Combined with ||.
Sourceown members, Equatable, Hashable, ToString, Clone, Copy
#tupleAn untagged, fixed-length group of values by position, e.g. (1, "a"). Combined with &.
Sourceown members, Equatable, Hashable, Comparable, ToString, Concatenable, Clone, Copy
untagged list of fields
Implements Equatable, Hashable, Comparable (lexicographic), ToString, Concatenable<Other, Self & Other> (both tuples' fields), Clone, Copy when every field does
Methods
size(): U64fields source get(index: U64): Unknown?a[b] with a literal index is typed exactly source first(): Unknown?field 0, undefined when empty source last(): Unknown?last field, undefined when empty source toArray(): Array<Unknown>fields in order source typeOf(): Typethe tuple's own type, every field's included source #unionAn untagged union, combined with |. Nothing records which member a value is - telling them apart is up to the user.
Sourceown members, Equatable, Hashable, ToString
untagged union - no tag to switch on, members work through a check
Implements Equatable, Hashable, ToString when every member does
Functions
members(): Array<Type>every member type source Methods
#wrapperA type wrapping another type.
Sourceown members, Equatable, Hashable, Comparable, ToString, Clone, Copy
single-field struct giving a type a new identity
Implements Equatable, Hashable, Comparable, ToString, Clone, Copy when the inner type does - opt-in, a Wrapper doesn't inherit the inner type's other interfaces
Functions
wrap(value: Inner): Selfthe new type holding value source Methods
#functionA named function - see Function Definition.
Sourceown members, Callable, Equatable, ToString, Copy
Function<Args, Result, Error:=undefined>(13)Function / Method / Lambda share these (Method is bound to its self, Lambda may capture)
Implements Callable<Args, Result>, Equatable (identity), ToString (signature), Copy
Functions
identity<T>(): Function<T, T>returns its argument source constant<T>(value: T): Function<Unknown, T>ignores its argument, always gives value source Methods
call(args: Args): Error ! Resultf(args) source arity(): U64how many arguments it takes source name(): String?undefined for a Lambda source signature(): Typeits type - parameters, result and error source compose<Next>(next: Function<Result, Next>): Function<Args, Next>next ∘ f source pipeInto(value: Args): Error ! Resultvalue |> f source partial(first: Head<Args>): Function<Tail<Args>, Result, Error>fix the first argument source curry(): Functionone argument at a time source flip(): Functionswap the first two arguments source memoize(): Function<Args, Result, Error>@memoize as a value source isPure(): Boolean@pure source #methodA function defined for a type and called on a value of it: value.method().
Sourceown members
#lambdaAn anonymous function written inline: λ(x) x + 1.
Sourceown members
Lambda<Args, Result, Error:=undefined>(1)everything on Function, plus its captures
Implements everything on Function<Args, Result, Error>
Methods
captures(): Map<String, Unknown>captured variables by name, as they are now source