### GET Request Source: https://rune-rs.github.io/docs/http/Client Constructs a builder to perform a GET request to the specified URL. ```APIDOC ## GET /api/request ### Description Constructs a builder to GET the given `url`. ### Method GET ### Endpoint `/api/request/{url}` ### Parameters #### Path Parameters - **url** (String) - Required - The URL to send the GET request to. #### Query Parameters None #### Request Body None ### Request Example ```rust let client = http::Client::new(); let response = client.get("http://example.com") .send() .await?; let response_text = response.text().await?; ``` ### Response #### Success Response (200) - **response** (reqwest::Response) - The response from the GET request. #### Response Example ```rust // Example response content would be here, depending on the URL ``` ``` -------------------------------- ### Perform HTTP GET Request Source: https://rune-rs.github.io/docs/http/Client Creates a request builder for performing an HTTP GET request to a specified URL. It demonstrates sending the request and processing the response body as text. ```rust let client = http::Client::new(); let response = client.get("http://example.com") .send() .await?; let response = response.text().await?; ``` -------------------------------- ### Rune Vec Initialization and Access Examples Source: https://rune-rs.github.io/docs/std/vec Provides examples of initializing Vec dynamic vectors in Rune, including empty, single-element, and multiple-element vectors. It also shows how to check if a vector is empty and access its elements by index. ```rune let empty = []; let one = [10]; let two = [10, 20]; assert!(empty.is_empty()); assert_eq!(one.0, 10); assert_eq!(two.0, 10); assert_eq!(two.1, 20); ``` -------------------------------- ### Create and Use Interval Timer with time::interval_at Source: https://rune-rs.github.io/docs/time/interval_at This example demonstrates how to create an `Interval` using `time::interval_at`. The interval is configured to start at a specific future `Instant` and repeat with a given `Duration`. It shows how to await ticks from the interval and highlights that subsequent ticks occur at the specified `period`. ```rust use time::{Duration, Instant}; let start = Instant::now() + Duration::from_millis(50); let interval = time::interval_at(start, Duration::from_millis(10)); interval.tick().await; // ticks after 50ms interval.tick().await; // ticks after 10ms interval.tick().await; // ticks after 10ms println!("approximately 70ms have elapsed..."); ``` -------------------------------- ### String Display Formatting Example (Rust) Source: https://rune-rs.github.io/docs/std/string/String Provides an example of displaying a string in Rust using the `{}` format specifier with `println!`. This utilizes the `Display` trait to format the string for human-readable output. ```Rust println!("{}", "Hello"); ``` -------------------------------- ### Rune Minimum (MIN) Protocol Example Source: https://rune-rs.github.io/docs/http/Version Illustrates the Rune protocol implementation for the `PartialOrd::min` method. This example shows how to find the minimum of two values, `$a` and `$b`, using the `.min()` method. It's essential for operations requiring the smaller of two values. ```rune $a.min($b) ``` -------------------------------- ### Get Range Start Protocol - Rune Script Source: https://rune-rs.github.io/docs/std/ops/Range Illustrates accessing the start value of a range using the `GET` protocol. The result is assigned to `$out`. ```Rune Script let $out = value.start ``` -------------------------------- ### String Cloning Example (Rust) Source: https://rune-rs.github.io/docs/std/string/String Provides a practical example of string cloning in Rust. It shows how `clone()` creates an independent copy, allowing modifications to the new string without altering the original. Demonstrates usage with `push` and `clone`. ```Rust let a = "h"; let b = a; b.push('i'); // `a` and `b` refer to the same underlying string. assert_eq!(a, b); let c = b.clone(); c.push('!'); assert_ne!(a, c); ``` -------------------------------- ### Rune Maximum (MAX) Protocol Example Source: https://rune-rs.github.io/docs/http/Version Demonstrates the Rune protocol implementation for the `PartialOrd::max` method. This example showcases how to determine the maximum of two values, `$a` and `$b`, by calling the `.max()` method. It is useful for scenarios needing the larger of two values. ```rune $a.max($b) ``` -------------------------------- ### RangeInclusive Partial Equality Example (Rune) Source: https://rune-rs.github.io/docs/std/ops/RangeInclusive Provides examples of using the `PARTIAL_EQ` protocol to compare character and float ranges for equality and inequality in Rune. ```rune let range = 'a'..='e'; assert!(range == ('a'..='e')); assert!(range != ('b'..='e')); let range = 1.0..=2.0; assert!(range == (1.0..=2.0)); assert!(range != (f64::NAN..=2.0)); assert!((f64::NAN..=2.0) != (f64::NAN..=2.0)); ``` -------------------------------- ### Make HTTP GET Request with Rune Source: https://rune-rs.github.io/docs/http Demonstrates how to perform an asynchronous HTTP GET request using Rune's http module. It shows fetching a response and accessing its text content. This requires the `http` module to be available. ```rune let res = http::get("https://httpstat.us/200?sleep=100").await; dbg!(res.text().await?); ``` -------------------------------- ### SIZE_HINT Protocol Example Source: https://rune-rs.github.io/docs/std/collections/hash_map/Iter Shows how to use the SIZE_HINT protocol to get a size hint from an iterator. This can provide an estimate of the number of elements remaining. ```rune let $out = value.size_hint() ``` -------------------------------- ### Get Current Instant using time::Instant::now() Source: https://rune-rs.github.io/docs/time/Instant Retrieves the current monotonic time as an `Instant`. This method is crucial for establishing a starting point for time measurements. It does not take any arguments and returns an `Instant` value. ```rust use time::{Duration, Instant}; let instant = Instant::now(); ``` -------------------------------- ### Rust: RangeToInclusive Protocol Examples Source: https://rune-rs.github.io/docs/std/ops/RangeToInclusive Provides examples illustrating the usage of various protocols for `RangeToInclusive`, including GET/SET for `end`, PARTIAL_EQ, EQ, PARTIAL_CMP, CMP, LT, LE, GT, GE, MIN, and MAX. ```rust protocol GET end ``` let $out = value.end ``` Allows a get operation to work. ``` ```rust protocol SET end ``` value.end = $input ``` Allows a set operation to work. ``` ```rust protocol PARTIAL_EQ ``` if value == b { } ``` Test the range for partial equality. # Examples ``` let range = ..='e'; assert!(range == (..='e')); assert!(range != (..='f')); let range = ..=2.0; assert!(range == (..=2.0)); assert!(range != (..=f64::NAN)); assert!((..=f64::NAN) != (..=f64::NAN)); ``` ``` ```rust protocol EQ ``` if value == b { } ``` Test the range for total equality. # Examples ``` use std::ops::eq; let range = ..='e'; assert!(eq(range, ..='e')); assert!(!eq(range, ..='f')); ``` ``` ```rust protocol PARTIAL_CMP ``` if value < b { } ``` Test the range for partial ordering. # Examples ``` assert!((..='a') < (..='b')); assert!((..='d') > (..='b')); assert!(!((..=f64::NAN) > (..=f64::INFINITY))); assert!(!((..=f64::NAN) < (..=f64::INFINITY))); ``` ``` ```rust protocol CMP ``` if value < b { } ``` Test the range for total ordering. # Examples ``` use std::ops::cmp; use std::cmp::Ordering; assert_eq!(cmp(..='a', ..='b'), Ordering::Less); assert_eq!(cmp(..='c', ..='b'), Ordering::Greater); ``` ``` ```rust protocol LT ``` if $a < $b { } ``` The protocol behind the `<` operator. ``` ```rust protocol LE ``` if $a <= $b { } ``` The protocol behind the `<=` operator. ``` ```rust protocol GT ``` if $a > $b { } ``` The protocol behind the `>` operator. ``` ```rust protocol GE ``` if $a >= $b { } ``` The protocol behind the `>=` operator. ``` ```rust protocol MIN ``` $a.min($b) ``` The implementation protocol for the `PartialOrd::min` method. ``` ```rust protocol MAX ``` $a.max($b) ``` The implementation protocol for the `PartialOrd::max` method. ``` -------------------------------- ### Rust HashMap Creation Methods Source: https://rune-rs.github.io/docs/std/collections/hash_map/HashMap Provides examples for creating a HashMap using different methods: `new()` for an empty map and `with_capacity()` to pre-allocate space. The `capacity()` method is shown to verify the allocated space. ```Rust use std::collections::HashMap; // Create an empty HashMap let map_new = HashMap::new(); // Create a HashMap with a specified capacity let map_capacity = HashMap::with_capacity(10); assert!(map_capacity.capacity() >= 10); ``` -------------------------------- ### Rune: Partial Ordered Comparison with PARTIAL_CMP Source: https://rune-rs.github.io/docs/std/i64 This example illustrates performing a partial ordered comparison between two integers using the PARTIAL_CMP protocol in Rune. The `std::ops::partial_cmp` function returns an `Option`, indicating if one value is less than, greater than, or equal to another, or if they are not comparable. The examples show Less, Greater, and Equal orderings for integers. ```rune use std::cmp::Ordering; use std::ops::partial_cmp; assert_eq!(partial_cmp(5i64, 10i64), Some(Ordering::Less)); assert_eq!(partial_cmp(10i64, 5i64), Some(Ordering::Greater)); assert_eq!(partial_cmp(5i64, 5i64), Some(Ordering::Equal)); ``` -------------------------------- ### Set Range Start Protocol - Rune Script Source: https://rune-rs.github.io/docs/std/ops/Range Shows how to set the start value of a range using the `SET` protocol. The input value is assigned to `value.start`. ```Rune Script value.start = $input ``` -------------------------------- ### Rust String from_utf8 Conversion Example Source: https://rune-rs.github.io/docs/std/string/String Shows how to convert a `Bytes` vector into a `String` using `from_utf8`. It includes examples for both valid UTF-8 input and invalid byte sequences, demonstrating error handling. ```rust // some bytes, in a vector let sparkle_heart = Bytes::from_vec([240u8, 159u8, 146u8, 150u8]); // We know these bytes are valid, so we'll use `unwrap()`. let sparkle_heart = String::from_utf8(sparkle_heart).unwrap(); assert_eq!("💖", sparkle_heart); ``` ```rust // some invalid bytes, in a vector let sparkle_heart = Bytes::from_vec([0u8, 159u8, 146u8, 150u8]); assert!(String::from_utf8(sparkle_heart).is_err()); ``` -------------------------------- ### Rune: Clone Protocol Example Source: https://rune-rs.github.io/docs/std/result/Result Demonstrates the `CLONE` protocol in Rune, which allows for creating a copy of a value. It includes an example of cloning a `Result` and verifying that modifications to the original do not affect the clone. ```Rune let a = Ok(b"hello world"); let b = clone(a); a?.extend(b"!"); assert_eq!(a, Ok(b"hello world!")); assert_eq!(b, Ok(b"hello world")); ``` -------------------------------- ### Instant Creation and Timing Source: https://rune-rs.github.io/docs/time/Instant This section covers how to get the current instant and measure elapsed time. ```APIDOC ## GET /now ### Description Returns an instant corresponding to the current time. ### Method GET ### Endpoint `/now` ### Parameters None ### Request Example None ### Response #### Success Response (200) - **instant** (Instant) - An opaque measurement of the current time. #### Response Example ```json { "instant": "" } ``` ## POST /duration_since ### Description Calculates the duration between two instants. ### Method POST ### Endpoint `/duration_since` ### Parameters #### Request Body - **self** (Instant) - The later instant. - **earlier** (Instant) - The earlier instant. ### Request Example ```json { "self": "", "earlier": "" } ``` ### Response #### Success Response (200) - **duration** (Duration) - The time elapsed between the two instants. #### Response Example ```json { "duration": "" } ``` ## POST /elapsed ### Description Returns the time elapsed since an instant was created. ### Method POST ### Endpoint `/elapsed` ### Parameters #### Request Body - **self** (Instant) - The instant to measure elapsed time from. ### Request Example ```json { "self": "" } ``` ### Response #### Success Response (200) - **duration** (Duration) - The time elapsed since the instant was created. #### Response Example ```json { "duration": "" } ``` ``` -------------------------------- ### String::starts_with Source: https://rune-rs.github.io/docs/std/string/String Checks if the String starts with a given pattern. ```APIDOC ## String::starts_with ### Description Returns `true` if the given pattern matches a prefix of this string slice. Returns `false` if it does not. The pattern can be a `&str`, `char`, a slice of `char`s, or a function or closure that determines if a character matches. ### Method `fn starts_with(self, other: String) -> bool` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **other** (String) - The pattern to check against the prefix. ### Request Example ```json { "example": "bananas", "other": "bana" } ``` ### Response #### Success Response (200) - **result** (bool) - `true` if the string starts with the pattern, `false` otherwise. #### Response Example ```json { "example": true } ``` ``` -------------------------------- ### HTTP Client Initialization Source: https://rune-rs.github.io/docs/http/Client Constructs a new asynchronous HTTP client instance. ```APIDOC ## POST /api/client ### Description Constructs a new http client. ### Method GET ### Endpoint Not applicable (this is a constructor) ### Parameters None ### Request Body None ### Request Example ```rust let client = http::Client::new(); ``` ### Response #### Success Response (200) - **client** (http::Client) - An instance of the http client. #### Response Example ```rust let client = http::Client::new(); ``` ``` -------------------------------- ### Create http::Client Instance Source: https://rune-rs.github.io/docs/http/Client Constructs a new asynchronous HTTP client instance. This client is used to initiate various HTTP requests. ```rust let client = http::Client::new(); ``` -------------------------------- ### GET Protocol Example for ControlFlow Source: https://rune-rs.github.io/docs/std/ops/ControlFlow Showcases the GET protocol applied to the ControlFlow enum. This allows accessing the inner value of a ControlFlow variant, typically used for `Continue` variants, by indexing with `.0`. ```rune let $out = value.0 ``` -------------------------------- ### RangeInclusive Iteration Example (Rune) Source: https://rune-rs.github.io/docs/std/ops/RangeInclusive Provides a practical example of iterating over a character range ('a'..='e') using the `INTO_ITER` protocol in Rune and collecting the values into a vector. ```rune let vec = []; for value in 'a'..='e' { vec.push(value); } assert_eq!(vec, ['a', 'b', 'c', 'd', 'e']); ``` -------------------------------- ### Rust HashSet: Initialize an Empty Set Source: https://rune-rs.github.io/docs/std/collections/hash_set/HashSet Shows how to create a new, empty HashSet. This method is useful when you need to start with a fresh set and add elements later. ```rust use std::collections::HashSet; let set = HashSet::new(); ``` -------------------------------- ### Rust String split Method Example (Deprecated) Source: https://rune-rs.github.io/docs/std/string/String Provides an example of using the deprecated `split` method to create an iterator over substrings separated by a pattern. It notes that `String::split` should be used instead. ```rust let s = "hello world"; // This is a conceptual example as the actual split method is deprecated // and the return type 'any' is not directly usable in a snippet. // In practice, you would use `s.split(' ')` which returns an iterator. ``` -------------------------------- ### Rust String shrink_to_fit Example Source: https://rune-rs.github.io/docs/std/string/String Shows how `shrink_to_fit` reduces the capacity of a `String` to match its current length, potentially freeing up memory. ```rust let s = "foo"; s.reserve(100); assert!(s.capacity() >= 100); s.shrink_to_fit(); assert_eq!(3, s.capacity()); ``` -------------------------------- ### NEXT Protocol Example Source: https://rune-rs.github.io/docs/std/collections/hash_map/Iter Demonstrates the usage of the NEXT protocol for advancing an iterator and retrieving the next element. This is fundamental for iteration. ```rune let $out = value.next() ``` -------------------------------- ### Rust: Using http::Version Constants Source: https://rune-rs.github.io/docs/http/Version Demonstrates how to use the `Version` constants from the `http` crate to represent and compare different HTTP versions. It shows basic instantiation and comparison operations. ```rust use http::Version; let http11 = Version::HTTP_11; let http2 = Version::HTTP_2; assert!(http11 != http2); println!("{:?}", http2); ``` -------------------------------- ### Hashing Example with std::ops::hash Source: https://rune-rs.github.io/docs/std/ops/hash This example demonstrates the usage of the std::ops::hash function to compare hash values of different data structures (an array and a tuple) within the same virtual machine invocation. It relies on the `std::ops::hash` function. ```Rust use std::ops::hash; assert_eq!(hash([1, 2]), hash((1, 2))); ``` -------------------------------- ### ExactSizeIterator len() Method Example - Rust Source: https://rune-rs.github.io/docs/std/iter/ExactSizeIterator Illustrates the functionality of the len() method for an ExactSizeIterator. It shows how to get the initial length of the iterator and how the length updates after consuming an element. ```rust let range = (0..5).iter(); assert_eq!(range.len(), 5); let _ = range.next(); assert_eq!(range.len(), 4); ``` -------------------------------- ### Rust: Spawn Process and Wait for Completion Source: https://rune-rs.github.io/docs/process/Child Illustrates spawning a child process with a piped stdin and then waiting for it to complete. This example shows how to explicitly manage the stdin handle before waiting. ```rust use process::{Command, Stdio}; let child = Command::new("cat"); child.stdin(Stdio::piped()); let child = child.spawn()?; let stdin = child.stdin()?; // wait for the process to complete let _ = child.wait().await?; ``` -------------------------------- ### Constructing a New Command - Rune Process Source: https://rune-rs.github.io/docs/process/Command Creates a new `Command` instance for executing a program. It initializes with default settings for arguments, environment, and working directory. If the program path is not absolute, the system's PATH environment variable will be searched. ```Rust use process::Command; let command = Command::new("sh"); ``` -------------------------------- ### Test Range Total Equality - Rust Source: https://rune-rs.github.io/docs/std/ops/Range Provides an example of testing for total equality between two ranges using the `eq` function. This ensures that both start and end values are identical. ```Rust use std::ops::eq; let range = 'a'..'e'; assert!(eq(range, 'a'..'e')); assert!(!eq(range, 'b'..'e')); ``` -------------------------------- ### Process Command Builder API Source: https://rune-rs.github.io/docs/process/Command Documentation for methods used to build and configure an asynchronous command. ```APIDOC ## `process::Command` ### Description This structure mimics the API of `std::process::Command` found in the standard library, but replaces functions that create a process with an asynchronous variant. The main provided asynchronous functions are `spawn`, `status`, and `output`. `Command` uses asynchronous versions of some `std` types (for example `Child`). ### Methods #### `new(program: String) -> Command` Constructs a new `Command` for launching the program at path `program`, with the following default configuration: * No arguments to the program * Inherit the current process's environment * Inherit the current process's working directory * Inherit stdin/stdout/stderr for `spawn` or `status`, but create pipes for `output` Builder methods are provided to change these defaults and otherwise configure the process. If `program` is not an absolute path, the `PATH` will be searched in an OS-defined way. The search path to be used may be controlled by setting the `PATH` environment variable on the Command, but this has some implementation limitations on Windows (see issue rust-lang/rust#37519). ##### Example ```rust use process::Command; let command = Command::new("sh"); ``` #### `arg(self, arg: String) -> Command` Adds an argument to pass to the program. Only one argument can be passed per use. ##### Example ```rust use process::Command; let command = Command::new("ls"); command.arg("-l"); command.arg("-a"); // To pass multiple arguments use `args` // let output = command.output().await?; ``` #### `args(self, args: Vec) -> Command` Adds multiple arguments to pass to the program. ##### Example ```rust use process::Command; let command = Command::new("ls"); command.args(vec!["-l", "-a"]); // let output = command.output().await?; ``` #### `arg0(self, arg: String) -> Command` Sets executable argument. Sets the first process argument, `argv[0]`, to something other than the default executable path. #### `stdin(self, stdio: Stdio) -> Command` Sets configuration for the child process's standard input (stdin) handle. Defaults to `inherit`. ##### Example ```rust use process::{Command, Stdio}; let command = Command::new("ls"); command.stdin(Stdio::null()); // let output = command.output().await?; ``` #### `stdout(self, stdio: Stdio) -> Command` Sets configuration for the child process's standard output (stdout) handle. Defaults to `inherit` when used with `spawn` or `status`, and defaults to `piped` when used with `output`. ##### Example ```rust use process::{Command, Stdio}; let command = Command::new("ls"); command.stdout(Stdio::null()); // let output = command.output().await?; ``` #### `stderr(self, stdio: Stdio) -> Command` Sets configuration for the child process's standard error (stderr) handle. Defaults to `inherit` when used with `spawn` or `status`, and defaults to `piped` when used with `output`. ##### Example ```rust use process::{Command, Stdio}; let command = Command::new("ls"); command.stderr(Stdio::null()); // let output = command.output().await?; ``` #### `kill_on_drop(self, kill_on_drop: bool) -> Command` Controls whether a `kill` operation should be invoked on a spawned child process when its corresponding `Child` handle is dropped. By default, this value is assumed to be `false`, meaning the next spawned process will not be killed on drop, similar to the behavior of the standard library. ``` -------------------------------- ### Rust: Fold Iterator Elements (Summation) Source: https://rune-rs.github.io/docs/std/iter/Empty The `fold()` method applies a closure to each element of an iterator, accumulating a result. This example demonstrates summing all elements of an array, starting with an initial value of 0. ```rust let a = [1, 2, 3]; // the sum of all of the elements of the array let sum = a.iter().fold(0, |acc, x| acc + x); assert_eq!(sum, 6); ``` -------------------------------- ### Basic Comparisons with Operators Source: https://rune-rs.github.io/docs/std/option/Option Provides examples of basic comparison operators `<`, `>`, `<=`, and `>=` which are syntactic sugar for underlying comparison protocols. ```rust assert!(Some(b"a") < Some(b"ab")); assert!(Some(b"ab") > Some(b"a")); assert!(Some(b"a") == Some(b"a")); ``` -------------------------------- ### Rust String Reserve Capacity Example Source: https://rune-rs.github.io/docs/std/string/String Demonstrates how to reserve a minimum capacity for a Rust String. It shows that calling `reserve` might not always increase capacity if it's already sufficient. ```rust let s = String::new(); s.reserve(10); assert!(s.capacity() >= 10); ``` ```rust let s = String::with_capacity(10); s.push('a'); s.push('b'); // s now has a length of 2 and a capacity of at least 10 let capacity = s.capacity(); assert_eq!(2, s.len()); assert!(capacity >= 10); // Since we already have at least an extra 8 capacity, calling this... s.reserve(8); // ... doesn't actually increase. assert_eq!(capacity, s.capacity()); ``` -------------------------------- ### Rust Skip Iterator Example Source: https://rune-rs.github.io/docs/std/collections/hash_set/Union Shows how to use the `skip(n)` iterator adapter to create an iterator that skips the first `n` elements. It's useful for processing data starting from a specific offset. ```rust let a = [1, 2, 3]; let iter = a.iter().skip(2); assert_eq!(iter.next(), Some(&3)); assert_eq!(iter.next(), None); ``` -------------------------------- ### Rust HashMap Initialization and Usage Source: https://rune-rs.github.io/docs/std/collections/hash_map/HashMap Demonstrates basic usage of HashMap including creating a new map, inserting key-value pairs, and retrieving values. It also shows how to access values using index notation. ```Rust use std::collections::HashMap; enum Tile { Wall, } let mut m = HashMap::new(); m.insert((0, 1), Tile::Wall); m[(0, 3)] = 5; assert_eq!(m.get(&(0, 1)), Some(&Tile::Wall)); assert_eq!(m.get(&(0, 2)), None); assert_eq!(m[&(0, 3)], 5); ``` -------------------------------- ### Tuple Debug Formatting Example (Rust) Source: https://rune-rs.github.io/docs/std/tuple/Tuple Shows how to print the debug representation of a tuple using the `{:?}` format specifier in Rust. This is useful for inspecting tuple contents during development. ```rust let a = (1, 2, 3); println!("{a:?}"); ``` -------------------------------- ### Rune Greater Than or Equal To (GE) Protocol Example Source: https://rune-rs.github.io/docs/http/Version Provides an example of the Rune protocol for the greater than or equal to operator (`>=`). The code within the `if` block executes if the left operand is greater than or equal to the right operand. This covers inclusive upper-bound comparisons. ```rune if $a >= $b { } ``` -------------------------------- ### RangeInclusive with Character Types (Rust) Source: https://rune-rs.github.io/docs/std/ops/RangeInclusive Illustrates creating an inclusive range with character types (e.g., 'a'..='f') and modifying its start and end values. This example highlights the flexibility of `RangeInclusive` with different data types. ```rust let range = 'a'..='f'; assert_eq!(range.start, 'a'); range.start = 'b'; assert_eq!(range.start, 'b'); assert_eq!(range.end, 'f'); range.end = 'g'; assert_eq!(range.end, 'g'); ``` -------------------------------- ### Rust Iterator Fold Example - String Concatenation Source: https://rune-rs.github.io/docs/std/collections/hash_set/Intersection Demonstrates the left-associative nature of Rust's `fold()` method by building a string. It starts with an initial string value and concatenates each element from the iterator, showing how the order of operations affects the final result. ```rust let numbers = [1, 2, 3, 4, 5]; let zero = "0"; let result = numbers.iter().fold(zero, |acc, x| { format!("({} + {})", acc, x) }); assert_eq!(result, "(((((0 + 1) + 2) + 3) + 4) + 5)"); ``` -------------------------------- ### Rust String into_bytes Method Example Source: https://rune-rs.github.io/docs/std/string/String Illustrates the `into_bytes` method, which consumes the `String` and returns its contents as a `Bytes` vector. This is the inverse of `from_utf8` and moves ownership. ```rust let s = "hello"; assert_eq!(b"hello", s.into_bytes()); assert!(!is_readable(s)); ``` -------------------------------- ### Rust: Object Equality Comparison Source: https://rune-rs.github.io/docs/std/object/Object Shows how the `PartialEq` and `Eq` traits are used to compare Rune objects for equality. The examples demonstrate comparing identical and different objects. ```rust let a = #{a: 42}; let b = #{a: 43}; assert_eq!(a, a); assert_ne!(a, b); assert_ne!(b, a); ``` ```rust use std::ops::eq; let a = #{a: 42}; let b = #{a: 43}; assert_eq!(eq(a, a), true); assert_eq!(eq(a, b), false); assert_eq!(eq(b, a), false); ``` -------------------------------- ### Rust: Spawn and Manage Child Process Lifecycle Source: https://rune-rs.github.io/docs/process/Child A comprehensive example showcasing spawning a child process, conditionally killing it based on external events using `select!`, and managing its lifecycle. It demonstrates interaction between asynchronous tasks. ```rust use process::Command; let child = Command::new("sleep"); child.arg("1"); let child = child.spawn(); let recv = wait_for_something(); select { _ = child.wait() => {} _ = recv => child.kill().await.expect("kill failed"), } ``` -------------------------------- ### Rune Greater Than (GT) Protocol Example Source: https://rune-rs.github.io/docs/http/Version Shows the Rune protocol for the greater than operator (`>`). This example includes a conditional block that runs when the first operand is strictly greater than the second. It's a core part of ordering logic in programming. ```rune if $a > $b { } ``` -------------------------------- ### Rust: Instantiating RangeFull Source: https://rune-rs.github.io/docs/std/ops/RangeFull Shows how to create an instance of `RangeFull` using its `new` method in Rust. ```rust use rune::runtime::RangeFull; let _ = RangeFull::new(); ``` -------------------------------- ### Rust HashMap Get and Contains Key Source: https://rune-rs.github.io/docs/std/collections/hash_map/HashMap Shows how to retrieve a value associated with a key using `get()` and how to check for the existence of a key using `contains_key()`. `get()` returns an `Option` containing the value or `None` if the key is not found. ```Rust use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); assert!(map.contains_key(&1)); assert!(!map.contains_key(&2)); ``` -------------------------------- ### Rust: Iterating Over Object Keys Source: https://rune-rs.github.io/docs/std/object/Object Shows how to iterate specifically over the keys of an object using the `keys()` method. The example sorts the keys for predictable output. ```rust let object = #{a: 1, b: 2, c: 3}; let vec = []; for key in object.keys() { vec.push(key); } vec.sort_by(|a, b| a.cmp(b)); assert_eq!(vec, ["a", "b", "c"]); ``` -------------------------------- ### Exponentiation Source: https://rune-rs.github.io/docs/std/i64 Methods for performing exponentiation with i64. ```APIDOC ## fn pow(self, pow: u64) -> i64 ### Description Raises self to the power of `pow`, using exponentiation by squaring. This function will wrap on overflow. ### Method `POST` (conceptual, not a true HTTP endpoint) ### Endpoint `/websites/rune-rs_github_io/i64/pow` (conceptual) ### Parameters #### Query Parameters - **pow** (u64) - The exponent to raise the number to. ### Request Body None ### Response #### Success Response (200) - **result** (i64) - The result of the exponentiation. ### Response Example ```json { "result": 32 } ``` ``` ```APIDOC ## fn saturating_pow(self, rhs: u64) -> i64 ### Description Saturating integer exponentiation. Computes `self.pow(exp)`, saturating at the numeric bounds instead of overflowing. ### Method `POST` (conceptual, not a true HTTP endpoint) ### Endpoint `/websites/rune-rs_github_io/i64/saturating_pow` (conceptual) ### Parameters #### Query Parameters - **rhs** (u64) - The exponent to raise the number to. ### Request Body None ### Response #### Success Response (200) - **result** (i64) - The result of the saturating exponentiation. ### Response Example ```json { "result": 1000000 } ``` ``` -------------------------------- ### Indexing Get operation (INDEX_GET) Source: https://rune-rs.github.io/docs/std/collections/vec_deque/VecDeque Shows how to use indexing get operation. ```rust let $out = value[index] ``` -------------------------------- ### Rust: Object Construction and Insertion Source: https://rune-rs.github.io/docs/std/object/Object Illustrates different ways to construct a Rune Object: using `new()` for an empty object and `with_capacity()` to pre-allocate space. It also shows the basic `insert` method for adding key-value pairs. ```rust let object = Object::new(); object.insert("Hello", "World"); ``` ```rust let object = Object::with_capacity(16); object.insert("Hello", "World"); ``` -------------------------------- ### Get Value from GeneratorState Source: https://rune-rs.github.io/docs/std/ops/generator/GeneratorState Shows how to retrieve the value from a GeneratorState using the GET protocol. This is applicable when the generator yields a value. ```rust let $out = value.0 ``` -------------------------------- ### Accessing Process Stdout with Rune Protocol Source: https://rune-rs.github.io/docs/process/Output This protocol enables fetching the standard output (stdout) of a process using a GET operation. It provides access to the captured output stream. ```rune let $out = value.stdout ``` -------------------------------- ### POST Request Source: https://rune-rs.github.io/docs/http/Client Constructs a builder to perform a POST request to the specified URL. ```APIDOC ## POST /api/request ### Description Constructs a builder to POST to the given `url`. ### Method POST ### Endpoint `/api/request/{url}` ### Parameters #### Path Parameters - **url** (String) - Required - The URL to send the POST request to. #### Query Parameters None #### Request Body - **data** (bytes) - Required - The data to send in the request body. ### Request Example ```rust let client = http::Client::new(); let response = client.post("https://postman-echo.com/post") .body_bytes(b"My post data...") .send() .await?; let response_json = response.json().await?; ``` ### Response #### Success Response (200) - **response** (reqwest::Response) - The response from the POST request. #### Response Example ```json { "json": { "data": "My post data..." } } ``` ``` -------------------------------- ### Rust Iterator collect() into HashMap Example Source: https://rune-rs.github.io/docs/std/iter/Once Shows how to collect iterator elements into a `HashMap` using `collect::()`. This example maps numbers to their string representations. ```Rust use std::collections::HashMap; let actual = (0..3).iter().map(|n| (n, n.to_string())).collect::(); let expected = HashMap::from_iter([ (0, "0".to_string()), (1, "1".to_string()), (2, "2".to_string()), ]); assert_eq!(actual, expected); ``` -------------------------------- ### Rune: Hash Protocol Example Source: https://rune-rs.github.io/docs/std/result/Result Illustrates the `HASH` protocol in Rune for hashing `Result` values. It shows how to use the `hash` function and verifies that equal values produce the same hash. ```Rune use std::ops::hash; let a = Ok("hello"); let b = Ok("hello"); assert_eq!(hash(a), hash(b)); ``` -------------------------------- ### INTO_ITER Protocol Example Source: https://rune-rs.github.io/docs/std/collections/hash_map/Iter Demonstrates the INTO_ITER protocol, which allows a value to be converted into an iterator, enabling its use in for-loops. ```rune for item in value { } ``` -------------------------------- ### Rust String as_bytes Method Example Source: https://rune-rs.github.io/docs/std/string/String Demonstrates the `as_bytes` method, which returns a byte slice (`Bytes`) representing the contents of a `String`. This is the inverse of `from_utf8`. ```rust let s = "hello"; assert_eq!(b"hello", s.as_bytes()); assert!(is_readable(s)); ``` -------------------------------- ### Rune Vec Pattern Matching Example Source: https://rune-rs.github.io/docs/std/vec Demonstrates how to use native pattern matching with the Rune Vec type to destructure its elements into variables. This allows for concise extraction of values from ordered collections. ```rune let value = [1, 2]; if let [a, b] = value { assert_eq!(a, 1); assert_eq!(b, 2); } ``` -------------------------------- ### Rust HashSet: Get Current Capacity Source: https://rune-rs.github.io/docs/std/collections/hash_set/HashSet Shows how to get the current capacity of a HashSet, which is the number of elements it can hold before needing to reallocate memory. This can be useful for performance tuning. ```rust use std::collections::HashSet; let set = HashSet::with_capacity(100); assert!(set.capacity() >= 100); ``` -------------------------------- ### Rust: Debug Formatting HashSet using DEBUG_FMT Source: https://rune-rs.github.io/docs/std/collections/hash_set/HashSet Shows how to format a HashSet for debugging using the `DEBUG_FMT` protocol. The `println!` macro with `{:?}` formatting utilizes this protocol to display the set's contents in a readable format. This example creates a set and prints its debug representation. ```rust use std::collections::HashSet; let set = HashSet::from_iter([1, 2, 3]); println!("{:?}", set); ``` -------------------------------- ### Rune PARTIAL_CMP Protocol Example Source: https://rune-rs.github.io/docs/std/u64 Illustrates the PARTIAL_CMP protocol in Rune for performing partial ordered comparisons between two integers using comparison operators like `<`. It returns an Option. ```Rune if value < b { } use std::cmp::Ordering; use std::ops::partial_cmp; assert_eq!(partial_cmp(5u64, 10u64), Some(Ordering::Less)); assert_eq!(partial_cmp(10u64, 5u64), Some(Ordering::Greater)); assert_eq!(partial_cmp(5u64, 5u64), Some(Ordering::Equal)); ``` -------------------------------- ### Get Range End Protocol - Rune Script Source: https://rune-rs.github.io/docs/std/ops/Range Demonstrates accessing the end value of a range using the `GET` protocol. The result is assigned to `$out`. ```Rune Script let $out = value.end ``` -------------------------------- ### HEAD Request Source: https://rune-rs.github.io/docs/http/Client Constructs a builder to perform a HEAD request to the specified URL. ```APIDOC ## HEAD /api/request ### Description Constructs a builder to HEAD to the given `url`. ### Method HEAD ### Endpoint `/api/request/{url}` ### Parameters #### Path Parameters - **url** (String) - Required - The URL to send the HEAD request to. #### Query Parameters None #### Request Body - **data** (bytes) - Required - The data to send in the request body. ### Request Example ```rust let client = http::Client::new(); let response = client.head("https://postman-echo.com/head") .body_bytes(b"My head data...") .send() .await?; let response_json = response.json().await?; ``` ### Response #### Success Response (200) - **response** (reqwest::Response) - The response from the HEAD request. #### Response Example ```json { "json": { "data": "My head data..." } } ``` ``` -------------------------------- ### Rune EQ Protocol Example Source: https://rune-rs.github.io/docs/std/u64 Demonstrates the EQ protocol in Rune for testing total equality between two integers. This protocol is typically implemented for types where equality is fully defined and transitive. ```Rune if value == b { } use std::ops::eq; assert_eq!(eq(5u64, 5u64), true); assert_eq!(eq(5u64, 10u64), false); assert_eq!(eq(10u64, 5u64), false); ``` -------------------------------- ### Object Creation and Manipulation Source: https://rune-rs.github.io/docs/std/object/Object This section covers the creation of new Object instances and basic manipulation methods. ```APIDOC ## Object Creation and Manipulation ### Methods #### `fn new() -> Object` **Description**: Constructs a new, empty object. **Method**: Associated function (like a static method) **Endpoint**: N/A (Object method) **Request Body**: N/A **Response Example**: ```rust let object = Object::new(); ``` #### `fn with_capacity(capacity: u64) -> Object` **Description**: Constructs a new object with a pre-allocated capacity. **Method**: Associated function (like a static method) **Endpoint**: N/A (Object method) **Parameters**: * `capacity` (u64) - Required - The initial capacity for the object. **Response Example**: ```rust let object = Object::with_capacity(16); ``` #### `fn insert(self, k: String, v: any) -> Option` **Description**: Inserts a key-value pair into the object. Returns `None` if the key was not previously present, otherwise returns the old value. **Method**: Instance method **Endpoint**: N/A (Object method) **Parameters**: * `k` (String) - Required - The key to insert. * `v` (any) - Required - The value to associate with the key. **Response Example**: ```rust let mut object = Object::new(); let old_value = object.insert(String::try_from("key")?, 1); assert_eq!(old_value, None); let overwritten_value = object.insert(String::try_from("key")?, 2); assert_eq!(overwritten_value, Some(1)); ``` #### `fn remove(self, key: String) -> Option` **Description**: Removes a key from the object, returning the associated value if the key was present. **Method**: Instance method **Endpoint**: N/A (Object method) **Parameters**: * `key` (String) - Required - The key to remove. **Response Example**: ```rust let mut object = Object::new(); object.insert(String::try_from("a")?, 42); let removed_value = object.remove(String::try_from("a")?); assert_eq!(removed_value, Some(42)); let non_existent = object.remove(String::try_from("b")?); assert_eq!(non_existent, None); ``` #### `fn clear(self)` **Description**: Clears the object, removing all key-value pairs. Retains allocated memory for potential reuse. **Method**: Instance method **Endpoint**: N/A (Object method) **Response Example**: ```rust let mut object = Object::new(); object.insert(String::try_from("a")?, 1); object.clear(); assert!(object.is_empty()); ``` ``` -------------------------------- ### String Debug Formatting Example (Rust) Source: https://rune-rs.github.io/docs/std/string/String Illustrates debug formatting for strings in Rust using `println!` with the `{:?}` format specifier. This utilizes the `Debug` trait to format the string for inspection during development. ```Rust println!("{:?}", "Hello"); ``` -------------------------------- ### Rune MIN Protocol Example Source: https://rune-rs.github.io/docs/std/u64 Illustrates the MIN protocol in Rune, providing a concise way to compare and return the minimum of two values. It aligns with the behavior of the `min` function from the Ord trait. ```Rune $a.min($b) assert_eq!(1u64.min(2u64), 1u64); assert_eq!(2u64.min(2u64), 2u64); ``` -------------------------------- ### Rust Iterator collect() into Vec Example Source: https://rune-rs.github.io/docs/std/iter/Once Shows how to use the `collect::()` method to gather elements from an iterator into a `Vec`. The example uses a range iterator and collects its elements. ```Rust use std::iter::range; assert_eq!((0..3).iter().collect::(), vec![0, 1, 2]); ```