### Using the prompt function Source: https://kestrel-lang.com/reference/stdlib/std.io.stdio/prompt This example demonstrates how to use the prompt function to get user input and then print a greeting. It uses 'try' to handle potential IoErrors. ```Kestrel let name = try prompt("Name: "); try println("Hello, " + name); ``` -------------------------------- ### Convert UInt32 to Bytes (Host Order) Example Source: https://kestrel-lang.com/reference/stdlib/std.numeric/UInt32 Example of converting a UInt32 maximum value to bytes in host order. ```kestrel let bytes = UInt32.maxValue.toBytes(); // 4 bytes, host order ``` -------------------------------- ### Array Usage Example Source: https://kestrel-lang.com/reference/stdlib/std.collections/Array Demonstrates array creation, appending, copying with copy-on-write, and partitioning. ```kestrel let evens = [2, 4, 6, 8]; var names = Array[String](); names.append("Alice"); names.append("Bob"); let copy = names; // O(1) — shares storage with `names` names.append("Carol"); // O(1) clone happens here, `copy` is unchanged for n in names.iter() { ... } let pivot = names.partition(by: { (n) in n.count > 3 }); ``` -------------------------------- ### starts(with: String) Source: https://kestrel-lang.com/reference/stdlib/std.text/StringSlice Returns true if this string starts with prefix. Empty prefix always returns true. Comparison is byte-wise. ```APIDOC ## starts(with: String) ### Description Returns true if this string starts with `prefix`. Empty prefix always returns true. Comparison is byte-wise. ### Method `starts(with: String)` ### Parameters #### Path Parameters - **prefix** (String) - Required - The prefix to check for. ### Returns - `Bool`: True if the string starts with the prefix, false otherwise. ``` -------------------------------- ### starts Source: https://kestrel-lang.com/reference/stdlib/std.text/Str Returns true if this string starts with `prefix`. Empty prefix always returns true. Comparison is byte-wise. ```APIDOC ## starts ### Description Returns true if this string starts with `prefix`. Empty prefix always returns true. Comparison is byte-wise. ### Method (Implicitly GET or similar, as it returns a boolean) ### Endpoint (Not applicable for SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **prefix** (String) - Required - The prefix to check for. ### Request Example ``` "hello".starts(with: "hel") "hello".starts(with: "xyz") ``` ### Response #### Success Response - **Bool** - True if the string starts with the prefix, false otherwise. #### Response Example ```json { "example": true } ``` ```json { "example": false } ``` ``` -------------------------------- ### SystemAllocator Example Source: https://kestrel-lang.com/reference/stdlib/std.memory/Allocator Demonstrates basic usage of SystemAllocator to allocate and deallocate memory for an Int64 layout. ```kestrel var alloc = SystemAllocator() if let .Some(p) = alloc.allocate(Layout.of[Int64]()) { // ... use p ... alloc.deallocate(p, Layout.of[Int64]()) } ``` -------------------------------- ### writeAll Function Example Source: https://kestrel-lang.com/reference/stdlib/std.io.write Example of using the writeAll function to write a slice of data to a file. This function ensures all bytes are consumed by the writer. ```kestrel var file = try File.create("output.bin"); try writeAll(file, from: data.asSlice()); ``` -------------------------------- ### UInt32 initializer example Source: https://kestrel-lang.com/reference/stdlib/std.text/Char Creates a Char from a UInt32 scalar value, validating it. ```kestrel let c = Char(65); // Some('A') let bad = Char(0xD800); // None (surrogate) ``` -------------------------------- ### Capacity Property Example Source: https://kestrel-lang.com/reference/stdlib/std.collections/Set Shows how to initialize a Set with a specific capacity and access its capacity property. ```kestrel let set = Set[String](capacity: 100); set.capacity; // 128 ``` -------------------------------- ### isInfinite Property Examples Source: https://kestrel-lang.com/reference/stdlib/std.numeric/Float64 Examples showing the usage of the isInfinite property on positive infinity, negative infinity, and NaN. ```kestrel Float64.infinity.isInfinite; // true Float64.infinity.negate().isInfinite; // true (1.0 / 0.0).isInfinite; // true Float64.nan.isInfinite; // false ``` -------------------------------- ### String Iteration Example Source: https://kestrel-lang.com/reference/stdlib/std.text/Str Demonstrates iterating over the characters of a string. ```Kestrel for c in "abc" { ... } // iterates 'a', 'b', 'c' ``` -------------------------------- ### Kestrel stdio print usage example Source: https://kestrel-lang.com/reference/stdlib/std.io.stdio/print Example demonstrating the use of the print function to output text and a number to stdout. Requires 'try' for handling the Result. ```kestrel try print("count: "); try println(42); ``` -------------------------------- ### fromDigit initializer example Source: https://kestrel-lang.com/reference/stdlib/std.text/Char Creates an ASCII digit Char from a numeric value. ```kestrel Char(fromDigit: 7); // Some('7') Char(fromDigit: 12); // None ``` -------------------------------- ### Float32 Parsing Examples Source: https://kestrel-lang.com/reference/stdlib/std.numeric/Float32 Provides examples of parsing various string formats into Float32 values, including valid numbers, special tokens, and invalid inputs. ```swift Float32(parsing: "3.14"); // Some(3.14) Float32(parsing: "-2.5e10"); // Some(-2.5e10) Float32(parsing: "inf"); // Some(infinity) Float32(parsing: "nan"); // Some(nan) Float32(parsing: "abc"); // None Float32(parsing: ""); // None ``` -------------------------------- ### Character literal initializer example Source: https://kestrel-lang.com/reference/stdlib/std.text/Char Illustrates the compiler-emitted initializer for character literals. ```kestrel let c: Char = 'a'; // lowers to Char(charLiteral: ...) ``` -------------------------------- ### String Formatting Example Source: https://kestrel-lang.com/reference/stdlib/std.text/Str Formats a string with specified options, such as width, padding with spaces. ```Kestrel "hi".format(FormatOptions(width: 5)); // "hi " ``` -------------------------------- ### isEmpty Property Examples Source: https://kestrel-lang.com/reference/stdlib/std.collections/Set Illustrates checking if a Set is empty using the isEmpty property. ```kestrel Set[Int64]().isEmpty; // true Set([1]).isEmpty; // false ``` -------------------------------- ### Character literal examples Source: https://kestrel-lang.com/reference/stdlib/std.text/Char Demonstrates the creation of Char values using character literals and checking their properties. ```kestrel let a: Char = 'a'; a.isAsciiLetter; // true a.utf8Length(); // 1 let smile: Char = '\u{1F600}'; smile.utf8Length(); // 4 ``` -------------------------------- ### digitValue method example Source: https://kestrel-lang.com/reference/stdlib/std.text/Char Gets the numeric value of an ASCII digit character. ```kestrel let val = '7'.digitValue(); // Some(7) let nonDigit = 'a'.digitValue(); // None ``` -------------------------------- ### SplitWhereView Example Source: https://kestrel-lang.com/reference/stdlib/std.text/SplitWhereView Demonstrates splitting a string by a space character and accessing the first segment and count. ```kestrel let view = "hello world".asSlice().split { (c) in c == Char(" ") }; view.first(); // Some("hello") view.count; // 2 ``` -------------------------------- ### Heap Creation and Basic Operations Source: https://kestrel-lang.com/reference/stdlib/std.collections/Heap Demonstrates creating a Heap from an array, cloning it, pushing new elements, and peeking at the top element without modifying the original heap. ```kestrel let h = Heap(from: [3, 1, 2]); var h2 = h.clone(); h2.push(0); h.peek(); // .Some(1) -- original unchanged h2.peek(); // .Some(0) ``` -------------------------------- ### Get start line index Source: https://kestrel-lang.com/reference/stdlib/std.text/LinesView Represents the line index at byte 0. ```Kestrel public var startIndex: LineIndex { get } ``` -------------------------------- ### Get StringSlice for a byte range Source: https://kestrel-lang.com/reference/stdlib/std.text/LinesView Returns a StringSlice covering the specified byte range [start, end). ```Kestrel public func slice(from: LineIndex, to: LineIndex) -> StringSlice ``` -------------------------------- ### Heap Initialization from Iterable Source: https://kestrel-lang.com/reference/stdlib/std.collections/Heap Demonstrates building a min-heap efficiently in O(n) time by collecting elements from an iterable source. ```kestrel let h = Heap(from: [5, 3, 1, 4, 2]); h.peek(); // .Some(1) h.count; // 5 ``` -------------------------------- ### Position Method Source: https://kestrel-lang.com/reference/stdlib/std.io.file/File Gets the current file position relative to the start of the file. This is a convenience method for `seek(.Current(0))`. ```kestrel public mutating func position() -> Result[Int64, IoError] ``` -------------------------------- ### Buffer Initialization and Usage Example Source: https://kestrel-lang.com/reference/stdlib/std.memory/Buffer Demonstrates creating a Buffer, writing values to specific indices, reading values, and resizing the buffer. Note that reading from an uninitialized slot is undefined behavior. ```kestrel var buf = Buffer[Int64, SystemAllocator](capacity: 4, allocator: SystemAllocator()); buf.write(at: 0, value: 10); buf.write(at: 1, value: 20); buf.read(at: 0) // .Some(10) buf.resize(to: 8); // grow in place if possible ``` -------------------------------- ### Create a single directory Source: https://kestrel-lang.com/reference/stdlib/std.os/mkdir Use `mkdir` to create a directory. This example shows how to handle the `Result` returned by `mkdir`, printing a success message or the error message if creation fails. ```kestrel match mkdir("/tmp/foo") { .Ok(_) => print("created"), .Err(e) => print(e.message) } ``` -------------------------------- ### Count Property Examples Source: https://kestrel-lang.com/reference/stdlib/std.collections/Set Demonstrates the usage of the count property to get the number of elements in a Set, including an empty set. ```kestrel Set([1, 2, 3]).count; // 3 Set[Int64]().count; // 0 ``` -------------------------------- ### Dictionary Initialization and Usage Example Source: https://kestrel-lang.com/reference/stdlib/std.collections/Dictionary Demonstrates basic dictionary operations including initialization, insertion, retrieval, and iteration. ```kestrel var ages: [String: Int64] = [:]; ages("Alice") = 30; ages("Bob") = 25; ages("Alice"); // Some(30) ages("Carol", default: 0); // 0 for (name, age) in ages.iter() { ... } let sum = ages.values.iter().sum(); ``` -------------------------------- ### Range IsEmpty Example Source: https://kestrel-lang.com/reference/stdlib/std.core/Range Checks if a range is empty. An empty range occurs when the start value is greater than or equal to the end value. ```kestrel (0..<0).isEmpty() ``` -------------------------------- ### String Byte Count Example Source: https://kestrel-lang.com/reference/stdlib/std.text/StringSlice Demonstrates getting the byte count of a String, showing that multi-byte UTF-8 characters contribute more than one byte. ```kestrel "hello".byteCount; // 5 "\u{00E9}".byteCount; // 2 (é is two UTF-8 bytes) ``` -------------------------------- ### Heap Initialization with Capacity Source: https://kestrel-lang.com/reference/stdlib/std.collections/Heap Shows how to create an empty heap with pre-allocated capacity to avoid reallocations when pushing elements. ```kestrel var h = Heap[Int64](capacity: 100); h.count; // 0 ``` -------------------------------- ### Accessing BytesView Properties Source: https://kestrel-lang.com/reference/stdlib/std.text/BytesView Demonstrates how to get the byte count, check for emptiness, and access start and end indices of a BytesView. The count is in bytes, not characters. ```Kestrel let s = "hi"; s.bytes.count; // 2 s.bytes(checked: 0); // Some(104) s.bytes(checked: 5); // None (out of bounds) ``` -------------------------------- ### Example: Advancing GraphemeIndex Source: https://kestrel-lang.com/reference/stdlib/std.text/GraphemeIndex Demonstrates how to advance a GraphemeIndex by a specified number of grapheme clusters within a string. ```kestrel let s = "héllo"; let idx = s.graphemes.startIndex; // byte 0 let next = idx.advance(by: 2, from: s.asSlice()); // Skipped 'h' (1 byte) and 'é' (2 bytes) → byte 3 ``` -------------------------------- ### Uppercase Expansion Example Source: https://kestrel-lang.com/reference/stdlib/std.text/Char Shows how to get the uppercase expansion for characters like 'ß', which expands to 'SS'. Returns an empty string for characters without an expansion. ```kestrel '\u{00DF}'.uppercaseExpansion(); // "SS" 'a'.uppercaseExpansion(); // "" ``` -------------------------------- ### Addable Example Usage Source: https://kestrel-lang.com/reference/stdlib/std.core/Addable Demonstrates basic addition using the '+' operator and accessing the 'zero' property. ```kestrel 2 + 3 // 5 Int64.zero // 0 ``` -------------------------------- ### Convert UInt16 to bytes example (host order) Source: https://kestrel-lang.com/reference/stdlib/std.numeric/UInt16 Demonstrates converting a UInt16 to its byte representation in host byte order. ```Kestrel let bytes = UInt16.maxValue.toBytes(); // 2 bytes, host order ``` -------------------------------- ### Float32 Infinity Check Examples Source: https://kestrel-lang.com/reference/stdlib/std.numeric/Float32 Examples demonstrating the usage of the `isInfinite` property for Float32 values. ```kestrel Float64.infinity.isInfinite; // true Float64.infinity.negate().isInfinite; // true (1.0 / 0.0).isInfinite; // true Float64.nan.isInfinite; // false ``` -------------------------------- ### Empty String Initialization and Properties Source: https://kestrel-lang.com/reference/stdlib/std.text/String Demonstrates creating an empty string and checking its initial properties. ```kestrel let s = String(); s.isEmpty; // true s.byteCount; // 0 ``` -------------------------------- ### Float32 NaN Examples Source: https://kestrel-lang.com/reference/stdlib/std.numeric/Float32 Examples demonstrating NaN behavior, including its inequality to itself and how it results from undefined operations. ```kestrel Float64.nan.isNaN; // true Float64.nan == Float64.nan; // false (!) 0.0 / 0.0; // nan ``` -------------------------------- ### String Initializers Source: https://kestrel-lang.com/reference/stdlib/std.text/String Demonstrates how to create new String instances using various initialization methods. ```APIDOC ## String Initializers ### Description Methods for constructing `String` objects. ### Initializers - **init()** Constructs an empty string. Allocates no buffer; the empty string is represented by a null pointer with zero length and capacity. Required by `Defaultable`. - **init(from: CString)** Builds a `String` by copying the bytes out of `cstring`, excluding the null terminator. O(n) — `cstring.length` walks to the terminator and the byte copy is linear. Empty `CString`s (length zero) yield the default empty `String` without touching the pointer. # Safety `cstring.raw` must be valid for at least `length` readable bytes plus a terminator. The conversion does not free the `CString`'s buffer — caller still owns it. - **init[I](from: I) where I: Iterable, I.Item == Char** Builds a string by encoding each character of `chars` as UTF-8. Mirrors `Array.init(from:)` and `Set.init(from:)` — accepts any `Iterable` whose `Item` is `Char`. Useful for materializing the result of an iterator chain back into a `String`. - **init(storage: CowBox[StringStorage])** Wraps an existing `CowBox[StringStorage]` as a new `String`. Module-internal — used by `clone()`, `StringBuilder.build()`, and other std.text code that constructs strings from raw storage. - **init[S](fromUtf8: S) where S: Slice[UInt8]** Constructs a string from validated UTF-8 bytes, returning `null` if the input is not valid UTF-8. - **init[S](fromUtf8Lossy: S) where S: Slice[UInt8]** Constructs a string from bytes, replacing invalid UTF-8 sequences with the Unicode replacement character (U+FFFD). - **init[S](fromUtf8Unchecked: S) where S: Slice[UInt8]** Constructs a string by copying bytes without UTF-8 validation. ``` -------------------------------- ### RangeFrom Start Property Source: https://kestrel-lang.com/reference/stdlib/std.core/RangeFrom Accesses the 'start' property of a RangeFrom, which represents the lower bound of the range and is included in the range. ```kestrel public var start: T ``` -------------------------------- ### Dictionary Initialization from Literal Source: https://kestrel-lang.com/reference/stdlib/std.collections/Dictionary Shows the dictionary-literal syntax for creating a Dictionary. Duplicate keys are handled by the last write. ```kestrel // Triggered by the dictionary-literal syntax: let dict: [String: Int64] = ["a": 1, "b": 2]; ``` -------------------------------- ### Int16 Formatting Examples Source: https://kestrel-lang.com/reference/stdlib/std.numeric/Int16 Shows how to format an Int16 into a string with various options, including radix, case, alternate representation, and padding. ```kestrel public func format(into: mutating StringBuilder, FormatOptions) (42).format(); // "42" (255).format(.{radix: 16}); // "ff" (255).format(.{radix: 16, uppercase: true}); // "FF" (255).format(.{radix: 16, alternate: true}); // "0xff" (42).format(.{radix: 2, alternate: true}); // "0b101010" (42).format(.{width: .Some(5), fill: '0'}); // "00042" (-42).format(.{sign: .Always}); // "-42" ``` ```kestrel public func formatted(FormatOptions) -> String ``` -------------------------------- ### isNaN Property Examples Source: https://kestrel-lang.com/reference/stdlib/std.numeric/Float64 Illustrates the isNaN property with examples of NaN generated from division by zero and square root of a negative number. ```kestrel (0.0 / 0.0).isNaN; // true Float64.nan.isNaN; // true (1.0).isNaN; // false Float64.infinity.isNaN; // false ``` -------------------------------- ### Float32 and Float64 Examples Source: https://kestrel-lang.com/reference/stdlib/std.numeric Demonstrates creating Float32 and Float64 values, calculating area using pi, formatting floats, and type annotation. ```swift let pi = Float64.pi; let area = pi * radius * radius; let s = area.format(.{precision: 2}); // "314.16" ``` ```swift let x = 3.14; // Float64 let y: Float32 = 3.14; // Float32 ``` -------------------------------- ### ExpressibleByArrayLiteral conformance example Source: https://kestrel-lang.com/reference/stdlib/std.memory/LiteralSlice Example of a custom vector type conforming to ExpressibleByArrayLiteral, using LiteralSlice to initialize its elements from an array literal. ```kestrel public struct MyVec[T]: ExpressibleByArrayLiteral { type Element = T public init(arrayLiteral lit: LiteralSlice[T]) { var v = MyVec() for x in lit { v.push(x) } self = v } } ``` -------------------------------- ### Convert to Bytes (Host Order) Source: https://kestrel-lang.com/reference/stdlib/std.numeric/UInt64 Demonstrates converting a UInt64 to an array of bytes in native host byte order. ```kestrel let bytes = UInt64.maxValue.toBytes(); // 8 bytes, host order ``` -------------------------------- ### Example Usage of RcBox Cloning and Deep Cloning Source: https://kestrel-lang.com/reference/stdlib/std.memory/RcBox Demonstrates how to clone an RcBox to share storage and how to perform a deep clone to create a private copy for mutation. It also shows checking for uniqueness before potential mutation. ```kestrel let a = RcBox(value: [1, 2, 3]); let b = a.clone(); // shares storage; refCount == 2 if b.isUnique() { ... } else { let c = b.deepClone(); /* ... */ } ``` -------------------------------- ### Hashable Struct Example Source: https://kestrel-lang.com/reference/stdlib/std.core/Hashable Example of a struct conforming to Hashable. It implements isEqual for equality checks and hash(into:) to feed its properties into the hasher. ```kestrel public struct Tag: Hashable { public var name: String public func isEqual(to other: Tag) -> Bool { self.name == other.name } public func hash[H](mutating into hasher: H) where H: Hasher { self.name.hash(into: hasher) } } ``` -------------------------------- ### Float32 NaN Check Examples Source: https://kestrel-lang.com/reference/stdlib/std.numeric/Float32 Examples showing how to use the `isNaN` property to detect NaN values, including results of undefined operations. ```kestrel (0.0 / 0.0).isNaN; // true Float64.nan.isNaN; // true (1.0).isNaN; // false Float64.infinity.isNaN; // false ``` -------------------------------- ### Initializing and Reading from Cursor Source: https://kestrel-lang.com/reference/stdlib/std.io.read/Cursor Demonstrates how to initialize a Cursor with byte data and read a specified number of bytes into a buffer. The position is updated after reading. ```kestrel var c = Cursor(data: [10, 20, 30].asArray()); var buf = Array[UInt8](repeating: 0, count: 2); try c.read(into: buf.asSlice()); // .Ok(2); buf == [10, 20] c.position() // 2 ``` -------------------------------- ### Initializing FormatOptions with Custom Width and Alignment Source: https://kestrel-lang.com/reference/stdlib/std.text/FormatOptions Shows how to create a FormatOptions instance and modify its width and alignment properties for custom string formatting. ```kestrel var opts = FormatOptions(); opts.width = .Some(6); opts.alignment = .Right; "hi".format(options: opts); // " hi" ``` -------------------------------- ### isNormal Property Examples Source: https://kestrel-lang.com/reference/stdlib/std.numeric/Float64 Examples demonstrating the isNormal property for a standard number, zero, the minimum positive normal number, and a subnormal number. ```kestrel (1.0).isNormal; // true (0.0).isNormal; // false Float64.minPositive.isNormal; // true (Float64.minPositive / 2.0).isNormal; // false (subnormal) ``` -------------------------------- ### File Seek Examples Source: https://kestrel-lang.com/reference/stdlib/std.io.file/Seek Demonstrates seeking to the beginning, back by a specified number of bytes from the current position, and to the end of the file. ```kestrel try file.seek(to: .Start(0)); // beginning try file.seek(to: .Current(-10)); // back 10 bytes try file.seek(to: .End(0)); // end of file ``` -------------------------------- ### Array Initializers Source: https://kestrel-lang.com/reference/stdlib/std.collections/Array Demonstrates various ways to initialize an Array. ```APIDOC ## Initializers ### `init(arrayLiteral:)` - **Description**: Creates an array containing every element of the supplied literal slice. Allocates a buffer sized exactly to the literal's element count. - **Example**: `let arr: Array[Int64] = [10, 20, 30];` ### `init()` - **Description**: Creates an empty array with no allocation. Capacity starts at zero; the first `append` allocates a small buffer. - **Example**: `var arr = Array[Int64]();` ### `init(of:generatedBy:)` - **Description**: Creates an array of `count` elements computed by a per-index closure. - **Parameters**: - `count` (Int64) - The number of elements to create. - `generatedBy` ((Int64) -> T) - A closure that generates each element based on its index. - **Example**: `let squares = Array(of: 5, generatedBy: { (i) in i * i }); // [0, 1, 4, 9, 16]` ### `init(from:)` - **Description**: Creates an array by collecting every element produced by an iterable. - **Parameters**: - `iterable` (I: Iterable) - An iterable collection to populate the array from. - **Example**: `let newArray = Array(from: someIterable);` ``` -------------------------------- ### RangeFrom Iterator Source: https://kestrel-lang.com/reference/stdlib/std.core/RangeFrom Returns a new, infinite iterator for the RangeFrom, starting from its defined 'start' value. This is used for iterating over the range's elements. ```kestrel public func iter() -> RangeFromIterator[T] ``` -------------------------------- ### Bool Formatting Example Source: https://kestrel-lang.com/reference/stdlib/std.core/Bool Shows how to format Bool values into strings. Demonstrates default formatting and debug formatting. ```kestrel true.format() // "true" false.format(FormatOptions.debug()) // "Bool(false)" ``` -------------------------------- ### Float32 Normal Number Check Examples Source: https://kestrel-lang.com/reference/stdlib/std.numeric/Float32 Examples illustrating the `isNormal` property for Float32, distinguishing normal numbers from zero, subnormals, and other special values. ```kestrel (1.0).isNormal; // true (0.0).isNormal; // false Float64.minPositive.isNormal; // true (Float64.minPositive / 2.0).isNormal; // false (subnormal) ``` -------------------------------- ### Basic Dictionary Iteration Example Source: https://kestrel-lang.com/reference/stdlib/std.collections/DictionaryIterator Demonstrates how to create and use a DictionaryIterator to traverse key-value pairs. Note that the iteration order is unspecified. ```kestrel let dict = ["a": 1, "b": 2]; var it = dict.iter(); it.next(); // Some(("a", 1)) — order is unspecified it.next(); // Some(("b", 2)) it.next(); // None ``` -------------------------------- ### Pointer Initialization and Basic Operations Source: https://kestrel-lang.com/reference/stdlib/std.memory/Pointer Demonstrates initializing a Pointer to an existing variable and performing read/write operations. The variable must outlive the pointer. ```kestrel var x = 42 let p = Pointer(to: x) p.read() // 42 p.write(100) // x is now 100 p.pointee = 7 // x is now 7 ``` -------------------------------- ### Empty Heap Initialization Source: https://kestrel-lang.com/reference/stdlib/std.collections/Heap Illustrates creating a new, empty heap without allocating memory until the first element is pushed. ```kestrel var h = Heap[Int64](); h.isEmpty; // true ``` -------------------------------- ### Check if Slice Starts with a Prefix Source: https://kestrel-lang.com/reference/stdlib/std.collections/Slice Use the `starts(with:)` method to determine if a slice begins with a specific sequence of elements. An empty prefix is always considered to be contained. ```kestrel [1, 2, 3].starts(with: [1, 2]); // true [1, 2, 3].starts(with: [2, 3]); // false [1, 2, 3].starts(with: []); // true (vacuous) ``` -------------------------------- ### Grapheme Cluster Example Source: https://kestrel-lang.com/reference/stdlib/std.text/GraphemesView Demonstrates the difference between counting characters (code points) and grapheme clusters using an example of a flag emoji. Use graphemes.count for user-perceived characters. ```kestrel let flag = "\u{1F1FA}\u{1F1F8}"; // 🇺🇸 flag.chars.count; // 2 (regional indicators) flag.graphemes.count; // 1 (one flag) ``` -------------------------------- ### NaN Examples and Comparison Behavior Source: https://kestrel-lang.com/reference/stdlib/std.numeric/Float64 Demonstrates how NaN is generated and highlights its peculiar comparison behavior where NaN is not equal to itself. ```kestrel Float64.nan.isNaN; // true Float64.nan == Float64.nan; // false (!) 0.0 / 0.0; // nan ``` -------------------------------- ### Dictionary Capacity Initialization Source: https://kestrel-lang.com/reference/stdlib/std.collections/Dictionary Shows how to initialize a Dictionary with a specified initial capacity. The actual capacity will be rounded up to the next power of two. ```kestrel let d = Dictionary[String, Int64](capacity: 100); d.capacity; // 128 ``` -------------------------------- ### Writable Protocol Conformance Example Source: https://kestrel-lang.com/reference/stdlib/std.io.write Example of a struct conforming to the Writable protocol. It tracks the number of bytes written and always reports success for the number of bytes provided. ```kestrel public struct CountingSink: Writable { var written: Int64 = 0 public mutating func write(from buf: ArraySlice[UInt8]) -> Result[Int64, IoError] { self.written = self.written + buf.count; .Ok(buf.count) } public mutating func flush() -> Result[(), IoError] { .Ok(()) } } ``` -------------------------------- ### Format Options Examples Source: https://kestrel-lang.com/reference/stdlib/std.text/Formattable Demonstrates various formatting options for string interpolation, including alignment, width, zero-padding, hexadecimal representation, precision, and debug formatting. ```kestrel "\{name}"; // "Alice" (default formatting) ``` ```kestrel "\{name:>10}"; // " Alice" (right-align, width 10) ``` ```kestrel "\{n:08x}"; // "0000002a" (zero-pad, hex, width 8) ``` ```kestrel "\{pi:.2}"; // "3.14" (precision 2) ``` ```kestrel "\{value:?}"; // debug representation ``` -------------------------------- ### flatMap Method Examples Source: https://kestrel-lang.com/reference/stdlib/std.iter/RepeatIterator Illustrates 'flatMap', which maps each element to an iterator and concatenates the results. It's the monadic bind operation for iterators. The second example shows conditional expansion. ```swift [[1, 2], [3, 4], [5]].iter() .flatMap { $0.iter() } .collect(); // [1, 2, 3, 4, 5] // Conditional expand — drop odd, double even [1, 2, 3].iter() .flatMap { if $0 % 2 == 0 { [$0, $0].iter() } else { [].iter() } } .collect(); // [2, 2] ``` -------------------------------- ### Infinity Arithmetic Examples Source: https://kestrel-lang.com/reference/stdlib/std.numeric/Float64 Demonstrates basic arithmetic operations involving Float64.infinity, including addition and division by zero. ```kestrel Float64.infinity; // inf Float64.infinity + 1; // inf 1.0 / 0.0; // inf Float64.infinity.negate(); // -inf ``` -------------------------------- ### Kestrel caseFoldExpansion Examples Source: https://kestrel-lang.com/reference/stdlib/std.text.unicode/caseFoldExpansion Demonstrates the usage of caseFoldExpansion with different characters. It shows examples of characters with multi-codepoint expansions ('ß', 'ffi') and a character with no expansion ('a'). Use this to understand how the function handles various Unicode characters. ```kestrel caseFoldExpansion('ß') // "ss" caseFoldExpansion('ffi') // "ffi" caseFoldExpansion('a') // "" (no expansion; caseFold('a') == 'a') ``` -------------------------------- ### Basic String Construction Example Source: https://kestrel-lang.com/reference/stdlib/std.text/StringBuilder Demonstrates the basic usage of StringBuilder for constructing a string by appending multiple parts. The `build()` method creates the final string without copying. ```kestrel var b = StringBuilder(); b.append("hello"); b.append(char: ' '); b.append("world"); let s = b.build(); // "hello world", zero-copy ``` -------------------------------- ### String Emptiness Check Example Source: https://kestrel-lang.com/reference/stdlib/std.text/StringSlice Checks if a String contains any bytes. ```kestrel "".isEmpty; // true "hello".isEmpty; // false ``` -------------------------------- ### Rotate bits right example Source: https://kestrel-lang.com/reference/stdlib/std.numeric/UInt16 Rotates bits of a UInt16 to the right. ```Kestrel public func rotateRight(by: Int64) -> UInt16 ``` -------------------------------- ### Rotate bits left example Source: https://kestrel-lang.com/reference/stdlib/std.numeric/UInt16 Rotates bits of a UInt16 to the left. ```Kestrel public func rotateLeft(by: Int64) -> UInt16 ``` -------------------------------- ### String Interpolation Examples with Format Options Source: https://kestrel-lang.com/reference/stdlib/std.text/FormatOptions Demonstrates various format specifiers used within string interpolation for different data types and formatting needs. ```kestrel "\{n:>8}"; // right-align, width 8 ``` ```kestrel "\{n:08x}"; // zero-pad, width 8, hex ``` ```kestrel "\{n:#X}"; // hex upper with 0x prefix ``` ```kestrel "\{pi:.2}"; // precision 2 decimal places ``` ```kestrel "\{pi:.2e}"; // scientific with 2 decimal places ``` ```kestrel "\{ratio:%"; // as percentage (0.5 -> "50%") ``` ```kestrel "\{name:^10}"; // center, width 10 ``` ```kestrel "\{value:?}"; // debug format ``` -------------------------------- ### Initializers Source: https://kestrel-lang.com/reference/stdlib/std.numeric/UInt64 Initializers for creating UInt64 instances from literals, default values, and other types. ```APIDOC ## Initializers ### `init(intLiteral: lang.i64)` - **Description**: Builds an instance from an integer literal. - **Signature**: `init(intLiteral: lang.i64)` ### `init()` - **Description**: Builds the default-valued instance (0). - **Signature**: `init()` ### `init(from: From)` - **Description**: Creates an instance from a convertible type `From`. - **Signature**: `init(from: From)` ``` -------------------------------- ### Scan Iterator Example Source: https://kestrel-lang.com/reference/stdlib/std.iter/ScanIterator Calculates a running sum of elements in an iterator. ```kestrel Running sum [1, 2, 3, 4].iter() .scan(from: 0) { (acc, x) in acc + x } .collect(); // [1, 3, 6, 10] ``` -------------------------------- ### Deque Initialization with Capacity Source: https://kestrel-lang.com/reference/stdlib/std.collections/Deque Shows how to initialize a Deque with a specific capacity, reserving space for elements without adding any initially. ```kestrel var d = Deque[Int64](capacity: 16); d.capacity; // 16 ``` -------------------------------- ### Iterator Scan Example Source: https://kestrel-lang.com/reference/stdlib/std.iter/FusedIterator Calculates a running sum of elements in an iterator. ```kestrel [1, 2, 3, 4].iter() .scan(from: 0) { (acc, x) in acc + x } .collect(); // [1, 3, 6, 10] ``` -------------------------------- ### Format Options with Different Signs Source: https://kestrel-lang.com/reference/stdlib/std.text/Sign Demonstrates how to set and use different sign rendering options with the format function. Requires FormatOptions to be initialized. ```kestrel var opts = FormatOptions(); opts.sign = .Always; (3).format(options: opts); // "+3" (-3).format(options: opts); // "-3" opts.sign = .Space; (3).format(options: opts); // " 3" ``` -------------------------------- ### Multiplication Example Source: https://kestrel-lang.com/reference/stdlib/std.core/Multipliable Demonstrates the use of the multiplication operator with the Multipliable protocol. ```kestrel 6 * 7 // 42 Int64.one // 1 ``` -------------------------------- ### ArraySliceIterator Initializer Source: https://kestrel-lang.com/reference/stdlib/std.memory/ArraySliceIterator Builds an iterator from a starting pointer and remaining count. ```APIDOC ## init(ptr: Pointer[T], remaining: Int64) ### Description Builds an iterator from a starting pointer and remaining count. ### Parameters #### Path Parameters - **ptr** (Pointer[T]) - Required - The starting pointer. - **remaining** (Int64) - Required - The remaining count of elements. ``` -------------------------------- ### Int32.init(intLiteral:) Source: https://kestrel-lang.com/reference/stdlib/std.numeric/Int32 Initializes an Int32 instance from an i64 integer literal. ```APIDOC ## Int32.init(intLiteral:) ### Description Initializes an instance from an integer literal. ### Initializer `init(intLiteral: lang.i64)` ### Parameters - **intLiteral** (lang.i64) - The integer literal value. ``` -------------------------------- ### stepBy Source: https://kestrel-lang.com/reference/stdlib/std.core/ClosedRangeIterator Yields every n-th element from the iterator, starting with the first. ```APIDOC ## stepBy ### Description Yields every `n`-th element, starting at the first. `n == 0` is undefined (the adapter will spin forever). ### Method func ### Parameters #### Path Parameters - **n** (Int64) - Required - The step interval. ### Examples `[0, 1, 2, 3, 4, 5, 6].iter().stepBy(2).collect(); // [0, 2, 4, 6]` ``` -------------------------------- ### Get lines iterator Source: https://kestrel-lang.com/reference/stdlib/std.text/LinesView Returns a LinesIterator positioned at byte 0. ```Kestrel public func iter() -> LinesIterator ``` -------------------------------- ### Float64 Literal and Formatting Example Source: https://kestrel-lang.com/reference/stdlib/std.numeric/Float64 Demonstrates creating a Float64 constant for pi, calculating area, and formatting the result to a specific precision. ```kestrel let pi = Float64.pi; let area = pi * radius * radius; let s = area.format(.{precision: 2}); // "314.16" ``` -------------------------------- ### Basic Bool Usage Example Source: https://kestrel-lang.com/reference/stdlib/std.core/Bool Demonstrates basic usage of Bool variables and conditional statements. Shows how to declare a boolean and use it in an if statement. ```kestrel let alive = true if alive { greet() } ``` -------------------------------- ### isControl property example Source: https://kestrel-lang.com/reference/stdlib/std.text/Char Checks if a character is a C0 control character or DEL. ```kestrel '\n'.isControl; // true '\x7F'.isControl; // true 'a'.isControl; // false ``` -------------------------------- ### init(intLiteral: lang.i64) Source: https://kestrel-lang.com/reference/stdlib/std.core/ExpressibleByIntLiteral Initializes an instance of a conforming type from an integer literal of type lang.i64. ```APIDOC ## init(intLiteral: lang.i64) ### Description Builds an instance from an integer literal. ### Parameters #### Path Parameters - **intLiteral** (lang.i64) - Required - The integer literal value to initialize the instance with. ``` -------------------------------- ### isAsciiUppercase property example Source: https://kestrel-lang.com/reference/stdlib/std.text/Char Checks if a character is an ASCII uppercase letter ('A' through 'Z'). ```kestrel 'A'.isAsciiUppercase; // true 'a'.isAsciiUppercase; // false '\u{00C9}'.isAsciiUppercase; // false (É — non-ASCII) ``` -------------------------------- ### isAsciiLowercase property example Source: https://kestrel-lang.com/reference/stdlib/std.text/Char Checks if a character is an ASCII lowercase letter ('a' through 'z'). ```kestrel 'a'.isAsciiLowercase; // true 'A'.isAsciiLowercase; // false ``` -------------------------------- ### isAsciiDigit property example Source: https://kestrel-lang.com/reference/stdlib/std.text/Char Checks if a character is an ASCII digit ('0' through '9'). ```kestrel '7'.isAsciiDigit; // true 'a'.isAsciiDigit; // false ``` -------------------------------- ### isAsciiAlphanumeric property example Source: https://kestrel-lang.com/reference/stdlib/std.text/Char Checks if a character is an ASCII letter or an ASCII digit. ```kestrel 'a'.isAsciiAlphanumeric; // true '7'.isAsciiAlphanumeric; // true '_'.isAsciiAlphanumeric; // false ``` -------------------------------- ### Initializer with Capacity Source: https://kestrel-lang.com/reference/stdlib/std.collections/Set Creates an empty Set pre-sized to hold a specified number of elements without immediate resizing. ```kestrel var set = Set[String](capacity: 1000); set.capacity; // 1024 set.count; // 0 ``` -------------------------------- ### Range Contains Example Source: https://kestrel-lang.com/reference/stdlib/std.core/Range Checks if a value is within the specified half-open range. ```kestrel (0..<10).contains(5) ``` -------------------------------- ### Kestrel readByte Example Source: https://kestrel-lang.com/reference/stdlib/std.io.read/readByte Demonstrates how to use readByte to read a single byte and handle success, EOF, or errors. ```kestrel match try readByte(reader) { .Some(b) => use(b), .None => /* EOF */ break } ```