### Getting Template Installation Source or Empty String in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/main/src/spin_templates/template.rs.html This method is intended to return a human-readable description of where the template was installed from. The provided snippet shows the start of a `match` statement on the `installed_from` field, which would typically handle different `InstalledFrom` variants to produce a string. ```Rust pub fn installed_from_or_empty(&self) -> &str { match &self.installed_from { ``` -------------------------------- ### Pre-instantiating a Spin Wasm Component in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.0/src/spin_core/lib.rs.html This method prepares a WebAssembly component for efficient instantiation by creating an `InstancePre` object. This pre-instantiation step performs initial linking and setup once, allowing multiple `Instance`s to be created quickly and efficiently from the pre-compiled state. ```Rust pub fn instantiate_pre(&self, component: &Component) -> Result> { let inner = Arc::new(self.linker.instantiate_pre(component)?); Ok(InstancePre { inner }) } ``` -------------------------------- ### Splitting Slice into Right-Aligned Chunks (as_rchunks) - Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.3/spin_sdk/http/type.Params.html This example demonstrates the `as_rchunks` method, which splits a slice into `N`-element chunks starting from the end, returning a remainder and the chunks. It requires the `slice_as_chunks` feature. The example shows how to use `as_rchunks` to get a remainder and the chunks, then asserts their values. ```Rust #![feature(slice_as_chunks)] let slice = ['l', 'o', 'r', 'e', 'm']; let (remainder, chunks) = slice.as_rchunks(); assert_eq!(remainder, &['l']); assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]); ``` -------------------------------- ### Creating New EngineBuilder in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.0.0/src/spin_core/lib.rs.html This associated function creates a new `EngineBuilder` instance, which is used to configure and construct an `Engine`. It takes a `Config` reference as input, allowing for initial setup of the engine's properties. This is the entry point for building a Spin engine. ```Rust pub fn builder(config: &Config) -> Result> { EngineBuilder::new(config) } ``` -------------------------------- ### Getting Template Source Repository in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/main/src/spin_templates/template.rs.html Returns an `Option<&str>` representing the Git repository URL from which the template was installed, if applicable. If the template was not installed from Git, it returns `None`. ```Rust pub fn source_repo(&self) -> Option<&str> { // TODO: this is kind of specialised - should we do the discarding of // non-Git sources at the application layer? match &self.installed_from { InstalledFrom::Git(url) => Some(url), _ => None, } } ``` -------------------------------- ### Internal WASI Directory Preopening Implementation (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.0.1/src/spin_core/store.rs.html This is an internal helper function that handles the core logic for mounting a host directory into the WASI filesystem. It opens the host directory using `cap_std::fs::Dir` and prepares the guest path for WASI context, supporting both Preview 1 and Preview 2. ```Rust fn preopened_dir_impl( &mut self, host_path: impl AsRef, guest_path: PathBuf, writable: bool, ) -> Result<()> { let cap_std_dir = cap_std::fs::Dir::open_ambient_dir(host_path.as_ref(), cap_std::ambient_authority())?; let path = guest_path .to_str() .ok_or_else(|| anyhow!("non-utf8 path: {}", guest_path.display()))?; self.try_with_wasi(|wasi| { match wasi { WasiCtxBuilder::Preview1(ctx) => { let mut dir = ``` -------------------------------- ### Building an Engine Instance in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.1/src/spin_core/lib.rs.html This method constructs an `Engine` instance from the `EngineBuilder`. It spawns an optional epoch ticker, builds the host components, and then initializes the `Engine` struct with its internal Wasmtime engine, linkers, host components, epoch tick interval, and the epoch ticker signal sender. ```Rust pub fn build(self) -> Engine { let epoch_ticker_signal = self.maybe_spawn_epoch_ticker(); let host_components = self.host_components_builder.build(); Engine { inner: self.engine, linker: self.linker, module_linker: self.module_linker, host_components, epoch_tick_interval: self.epoch_tick_interval, _epoch_ticker_signal: epoch_ticker_signal, } } ``` -------------------------------- ### Creating a GET RequestBuilder in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.2/src/spin_sdk/http.rs.html This method provides a convenient way to start building a GET request. It takes a URI as input and returns a `RequestBuilder` pre-configured for a GET operation to that specific URI, ready for additional modifications like adding headers. ```Rust pub fn get(uri: impl Into) -> RequestBuilder { RequestBuilder::new(Method::Get, uri) } ``` -------------------------------- ### Registering Handler for HTTP GET Method with Router - Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.2.1/spin_sdk/http/struct.Router.html This method is a convenience function to register a handler specifically for HTTP GET requests at a given `path`. The handler closure takes a `Request` and `Params` and should return a `Result`, simplifying the setup for common GET endpoints. ```Rust pub fn get(&mut self, path: &[str], handler: F)where F: Fn(Request, Params) -> Result + 'static, ``` -------------------------------- ### Instantiating Component Pre-Instance - Spin Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/main/src/spin_factors_executor/lib.rs.html This snippet demonstrates how a Spin component is prepared for instantiation by loading it and then calling `instantiate_pre` on the core engine. It takes the engine and an `AppComponent` as input, returning a pre-instantiated component ready for further configuration. ```Rust engine: &spin_core::Engine>, component: &AppComponent, ) -> anyhow::Result>> { let component = self.load_component(engine.as_ref(), component).await?; engine.instantiate_pre(&component) ``` -------------------------------- ### Getting Package Manager Data Directory in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/main/src/spin_common/data_dir.rs.html This helper function attempts to identify a package manager-specific data directory for Spin. Currently, it checks for a Homebrew installation by inspecting the `HOMEBREW_PREFIX` environment variable and verifying if the current executable path starts with the Homebrew prefix. If found, it constructs a specific data directory path within the Homebrew structure; otherwise, it returns `None`. ```Rust fn package_manager_data_dir() -> Option { if let Ok(brew_prefix) = std::env::var("HOMEBREW_PREFIX") { if std::env::current_exe() .map(|p| p.starts_with(&brew_prefix)) .unwrap_or(false) { let data_dir = Path::new(&brew_prefix) .join("etc") .join("spinframework-spin"); return Some(data_dir); } } None } ``` -------------------------------- ### Building Spin Engine with Host Data (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.0/src/spin_core/lib.rs.html This method constructs an `Engine` instance using provided host state data (`instance_pre_data`). It initializes internal components like the `host_components` and a pre-instance store, which is essential for `Engine::instantiate_pre`. This is the more flexible build method when custom host data is required. ```Rust pub fn build_with_data(self, instance_pre_data: T) -> Engine { let epoch_ticker_signal = self.maybe_spawn_epoch_ticker(); let host_components = self.host_components_builder.build(); let instance_pre_store = Arc::new(Mutex::new( StoreBuilder::new(self.engine.clone(), Duration::ZERO, &host_components) .build_with_data(instance_pre_data) .expect("instance_pre_store build should not fail"), )); Engine { inner: self.engine, linker: self.linker, host_components, instance_pre_store, epoch_tick_interval: self.epoch_tick_interval, _epoch_ticker_signal: epoch_ticker_signal, } } ``` -------------------------------- ### Setting Up Spin Component Test Environment in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/main/src/spin_oci/client.rs.html This snippet defines an asynchronous test function that initializes a temporary working directory and populates it with dummy Spin components and their associated files. It simulates the creation of WASM modules and their static assets, including components with dependencies defined via WIT (WebAssembly Interface Type) files, to prepare for component layer assembly tests. ```Rust #[tokio::test] async fn can_assemble_layers() { use spin_locked_app::locked::LockedComponent; use tokio::io::AsyncWriteExt; let working_dir = tempfile::tempdir().unwrap(); // Set up component/file directory tree // // create component1 and component2 dirs let _ = tokio::fs::create_dir(working_dir.path().join("component1").as_path()).await; let _ = tokio::fs::create_dir(working_dir.path().join("component2").as_path()).await; // create component "wasm" files let mut c1 = tokio::fs::File::create(working_dir.path().join("component1.wasm")) .await .expect("should create component wasm file"); c1.write_all(b"c1") .await .expect("should write component wasm contents"); let mut c2 = tokio::fs::File::create(working_dir.path().join("component2.wasm")) .await .expect("should create component wasm file"); c2.write_all(b"c2") .await .expect("should write component wasm contents"); // component1 files let mut c1f1 = tokio::fs::File::create(working_dir.path().join("component1").join("bar")) .await .expect("should create component file"); c1f1.write_all(b"bar") .await .expect("should write file contents"); let mut c1f2 = tokio::fs::File::create(working_dir.path().join("component1").join("baz")) .await .expect("should create component file"); c1f2.write_all(b"baz") .await .expect("should write file contents"); // component2 files let mut c2f1 = tokio::fs::File::create(working_dir.path().join("component2").join("baz")) .await .expect("should create component file"); c2f1.write_all(b"baz") .await .expect("should write file contents"); // create a component with dependencies const TEST_WIT: &str = "\n package test:test;\n\n interface a {\n a: func();\n }\n\n world dep-a {\n export a;\n }\n\n world root {\n import a;\n }\n "; let root = generate_dummy_component(TEST_WIT, "root"); let dep_a = generate_dummy_component(TEST_WIT, "dep-a"); let mut r = tokio::fs::File::create(working_dir.path().join("root.wasm")) .await .expect("should create component wasm file"); r.write_all(&root) .await .expect("should write component wasm contents"); let mut a = tokio::fs::File::create(working_dir.path().join("dep_a.wasm")) .await .expect("should create component wasm file"); a.write_all(&dep_a) .await .expect("should write component wasm contents"); } ``` -------------------------------- ### Spin Key-Value Store Module Overview and Example - Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.0.1/src/spin_core/store.rs.html Provides an overview of the Spin key-value store module, explaining its purpose as a durable, persistent store. Includes a basic example demonstrating how to open a default store, set, get, and delete keys. ```Rust //! This module contains the public API for the Spin key-value store. //! //! The key-value store is a durable, persistent store that can be used to //! store data across component invocations. //! //! # Example //! //! ```rust //! use spin_sdk::key_value::{Store, Error}; //! //! fn main() -> Result<(), Error> { //! let store = Store::open("default")?; //! store.set("key", b"value")?; //! let value = store.get("key")?; //! println!("{:?}", value); //! store.delete("key")?; //! Ok(()) //! } //! ``` use anyhow::{anyhow, Result}; use spin_sdk::key_value::{Error, Store}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; use std::time::SystemTime; pub(crate) type StoreResult = Result; ``` -------------------------------- ### Asynchronously Instantiating InstancePre in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.0.0/src/spin_core/lib.rs.html This asynchronous method instantiates the pre-initialized component instance with a given `Store`. It leverages the pre-computation done during `InstancePre` creation to quickly create a live `Instance`. This is a key method for running WebAssembly components within the Spin environment. ```Rust #[instrument(skip_all)] pub async fn instantiate_async(&self, store: &mut Store) -> Result { self.inner.instantiate_async(store).await } ``` -------------------------------- ### Getting a Raw Pointer to Vector Data in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.3.0/spin_sdk/http/type.Params.html This example shows how to use the `as_ptr` method to get a raw, immutable pointer to the underlying buffer of a `Vec`. It then demonstrates iterating through the vector's elements using pointer arithmetic in an `unsafe` block, asserting their values based on their index. ```Rust let x = vec![1, 2, 4]; let x_ptr = x.as_ptr(); unsafe { for i in 0..x.len() { assert_eq!(*x_ptr.add(i), 1 << i); } } ``` -------------------------------- ### Accessing Slice Elements or Subslice with `get` in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.5.1/spin_sdk/http/type.Params.html This example demonstrates the `get` method for safely accessing elements or subslices of a slice. It returns an `Option` containing a reference to the element or subslice if the index or range is within bounds, otherwise `None`. This prevents panics from out-of-bounds access. ```Rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### Creating a New Instance in Spin Framework (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.0.0-rc.1/spin_core/struct.Instance.html This function instantiates a WebAssembly module, running its start function if present. It requires a mutable store context (`store`), a compiled module (`module`), and a list of external imports (`imports`). Instantiation can fail due to import mismatches, type errors, traps, or resource limits. It's a low-level API; for easier import linking, consider using the `Linker` struct. ```Rust pub fn new( store: impl AsContextMut, module: &[Module], imports: &[Extern] ) -> Result ``` -------------------------------- ### Creating a RequestBuilder in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/variables-test/src/spin_sdk/http.rs.html Provides a convenient way to start building a `Request` using the `RequestBuilder` pattern. It initializes a builder for a GET request to the root path ('/'). ```Rust /// Creates a [`RequestBuilder`] pub fn builder() -> RequestBuilder { RequestBuilder::new(Method::Get, "/") } ``` -------------------------------- ### Building Spin Engine with Custom Host Data (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v0.9.0/src/spin_core/lib.rs.html This method constructs an `Engine` instance using provided host state data (`instance_pre_data`). It initializes host components, sets up an `instance_pre_store` (a `Store` for pre-instantiated modules), and configures epoch ticking. This is useful when the host state `T` does not implement `Default`. ```Rust pub fn build_with_data(self, instance_pre_data: T) -> Engine { let epoch_ticker_signal = self.maybe_spawn_epoch_ticker(); let host_components = self.host_components_builder.build(); let instance_pre_store = Arc::new(Mutex::new( StoreBuilder::new(self.engine.clone(), Duration::ZERO, &host_components) .build_with_data(instance_pre_data) .expect("instance_pre_store build should not fail"), )); Engine { inner: self.engine, linker: self.linker, host_components, instance_pre_store, epoch_tick_interval: self.epoch_tick_interval, _epoch_ticker_signal: epoch_ticker_signal, } } ``` -------------------------------- ### Getting Raw Mutable Pointer to Slice Buffer with as_mut_ptr in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.5.0/spin_sdk/http/type.Params.html This snippet demonstrates how to get an unsafe mutable raw pointer to a slice's buffer using `as_mut_ptr`. The caller is responsible for ensuring the slice's lifetime and handling potential reallocations. The example uses the raw pointer to increment each element in the slice by 2. ```Rust let x = &mut [1, 2, 4]; let x_ptr = x.as_mut_ptr(); unsafe { for i in 0..x.len() { *x_ptr.add(i) += 2; } } assert_eq!(x, &[3, 4, 6]); ``` -------------------------------- ### Pre-instantiating Spin Component Instance (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.3.0/src/spin_core/lib.rs.html Creates a new `InstancePre` for a given Spin `Component`. This pre-initializes the instance, making it ready for efficient instantiation with a `Store`. It uses the engine's internal linker to prepare the component. ```Rust #[instrument(skip_all)] pub fn instantiate_pre(&self, component: &Component) -> Result> { let inner = Arc::new(self.linker.instantiate_pre(component)?); Ok(InstancePre { inner }) } ``` -------------------------------- ### Getting Vector Length with `len` in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.5/spin_sdk/http/type.Params.html This example demonstrates how to use the `len` method to retrieve the number of elements currently stored in a Rust `Vec`. ```Rust let a = vec![1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Testing WASI Preview 2 Command Execution in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/main/src/spin_componentize/lib.rs.html This asynchronous test function demonstrates how to set up a Wasmtime `Linker` and `Store` with WASI Preview 2 support, instantiate a Wasm component, provide custom stdin/stdout, and execute a WASI command. It verifies the output against expected values. ```Rust let mut linker = Linker::::new(&engine); wasmtime_wasi::p2::add_to_linker_async(&mut linker)?; let mut ctx = WasiCtxBuilder::new(); let stdout = MemoryOutputPipe::new(1024); ctx.stdin(MemoryInputPipe::new("So rested he by the Tumtum tree")) .stdout(stdout.clone()) .args(&["Jabberwocky"]); let table = ResourceTable::new(); let wasi = Wasi { ctx: ctx.build(), table, }; let mut store = Store::new(&engine, wasi); let component = Component::new(&engine, crate::componentize_command(module)?)?; let wasi = Command::instantiate_async(&mut store, &component, &linker).await?; wasi.wasi_cli_run() .call_run(&mut store) .await? .map_err(|()| anyhow!("command returned with failing exit status"))?; drop(store); let stdout = stdout.try_into_inner().unwrap().to_vec(); assert_eq!( b"Jabberwocky\nSo rested he by the Tumtum tree" as &[_], &stdout ); Ok(()) ``` -------------------------------- ### Creating a New WASI Preview 1 Context in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.2.1/src/spin_core/store.rs.html This function constructs and returns a new `Wasi::Preview1` context. It initializes a `WasiCtx` using `wasmtime_wasi_preview1::WasiCtxBuilder::new().build()`, providing a standard way to set up a WASI Preview 1 environment for Wasm modules. ```Rust pub fn new_preview1() -> Self { Self::Preview1(wasmtime_wasi_preview1::WasiCtxBuilder::new().build()) } ``` -------------------------------- ### Creating a RequestBuilder in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.0.1/src/spin_sdk/http.rs.html Returns a new `RequestBuilder` instance, initialized with a GET method and a root ('/') URI. This is the starting point for fluently building a request. ```Rust pub fn builder() -> RequestBuilder { RequestBuilder::new(Method::Get, "/") } ``` -------------------------------- ### Instantiating Spin Component InstancePre Asynchronously (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.2/src/spin_core/lib.rs.html This asynchronous method instantiates the pre-initialized component instance within a provided `Store`. It leverages the underlying `wasmtime::component::InstancePre` to create a live `Instance`, making the component ready for execution. ```Rust impl InstancePre { /// Instantiates this instance with the given [`Store`]. #[instrument(skip_all)] pub async fn instantiate_async(&self, store: &mut Store) -> Result { self.inner.instantiate_async(store).await } } ``` -------------------------------- ### Getting Slice Length in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.5.1/spin_sdk/http/type.Params.html This example shows how to use the `len()` method to retrieve the number of elements in a slice. It initializes a slice `a` and then asserts that its length is 3. ```Rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Getting Vector Length in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.3/spin_sdk/http/type.Params.html This simple example demonstrates the `len()` method, which returns the number of elements currently in the vector, also known as its length. It initializes a vector and then asserts its length. ```Rust let a = vec![1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Applying Store Configuration (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.2.0/src/spin_app/lib.rs.html This asynchronous function applies component-specific configurations to a `StoreBuilder`. It sets up WASI environment variables and preloaded directories, and configures any dynamic host components, ensuring the runtime environment is correctly prepared. ```Rust /// Updates the given [`StoreBuilder`] with configuration for this component. /// /// In particular, the WASI 'env' and "preloaded dirs" are set up, and any /// [`DynamicHostComponent`]s associated with the source [`AppLoader`] are /// configured. pub async fn apply_store_config(&self, builder: &mut StoreBuilder) -> Result<()> { builder.env(&self.locked.env).map_err(Error::CoreError)?; let loader = self.app.loader; loader .inner .mount_files(builder, self) .await .map_err(Error::LoaderError)?; loader .dynamic_host_components .update_data(builder.host_components_data(), self) .map_err(Error::HostComponentError)?; Ok(()) } ``` -------------------------------- ### Getting Project Root Path - Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/main/src/spin_templates/manager.rs.html Returns the absolute path to the project's root directory. It constructs the path by starting from the `CARGO_MANIFEST_DIR` environment variable and navigating up two levels. ```Rust fn project_root() -> PathBuf { let crate_dir = env!("CARGO_MANIFEST_DIR"); PathBuf::from(crate_dir).join("..\").join("..\") } ``` -------------------------------- ### Creating a New StoreBuilder Instance (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.5/src/spin_core/store.rs.html Initializes a new `StoreBuilder` instance with the specified Wasmtime engine, epoch tick interval, host components, and WASI version. This constructor sets up the foundational WASI context and default store limits for subsequent configuration. ```Rust pub(crate) fn new( engine: wasmtime::Engine, epoch_tick_interval: Duration, host_components: &HostComponents, wasi: WasiVersion, ) -> Self { Self { engine, epoch_tick_interval, wasi: Ok(wasi.into()), host_components_data: host_components.new_data(), store_limits: StoreLimitsAsync::default(), } } ``` -------------------------------- ### Pre-instantiating Component in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.0.0/src/spin_core/lib.rs.html This method creates a pre-initialized `InstancePre` for a given WebAssembly `Component`. Pre-instantiation optimizes performance by performing initial linking and validation steps once, allowing for faster subsequent instantiations. It takes a `Component` reference and returns a `Result` containing the `InstancePre`. ```Rust #[instrument(skip_all)] pub fn instantiate_pre(&self, component: &Component) -> Result> { let inner = Arc::new(self.linker.instantiate_pre(component)?); Ok(InstancePre { inner }) } ``` -------------------------------- ### Splitting Slices from End with `as_rchunks` in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.5/spin_sdk/http/type.Params.html This example shows the `as_rchunks` method, which splits a slice into N-element arrays starting from the end of the slice, returning any remainder at the beginning. It requires the `slice_as_chunks` feature and panics if N is 0. The snippet demonstrates splitting a 5-element slice into 2-element chunks from the right, leaving one element as remainder at the start. ```Rust #![feature(slice_as_chunks)] let slice = ['l', 'o', 'r', 'e', 'm']; let (remainder, chunks) = slice.as_rchunks(); assert_eq!(remainder, &['l']); assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]); ``` -------------------------------- ### Preparing WASI Instance Builder in Spin Runtime (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/main/src/spin_factor_wasi/lib.rs.html The `prepare` function initializes a `WasiCtxBuilder` and an `InstanceBuilder`. It handles mounting files via a `FilesMounter` and applies environment variables from the application component, preparing the context for a WebAssembly instance. ```Rust fn prepare( &self, ctx: PrepareContext, ) -> anyhow::Result { let mut wasi_ctx = WasiCtxBuilder::new(); // Mount files let mount_ctx = MountFilesContext { ctx: &mut wasi_ctx }; self.files_mounter .mount_files(ctx.app_component(), mount_ctx)?; let mut builder = InstanceBuilder { ctx: wasi_ctx }; // Apply environment variables builder.env(ctx.app_component().environment()); Ok(builder) } ``` -------------------------------- ### Mutably Splitting Inclusively with `split_inclusive_mut` in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.5.1/spin_sdk/http/type.Params.html This example uses `split_inclusive_mut` to get mutable subslices, where the matched element is included as the terminator. It then modifies the terminator element of each subslice in place. ```Rust let mut v = [10, 40, 30, 20, 60, 50]; for group in v.split_inclusive_mut(|num| *num % 3 == 0) { let terminator_idx = group.len()-1; group[terminator_idx] = 1; } assert_eq!(v, [10, 40, 1, 20, 1, 1]); ``` -------------------------------- ### Creating a RequestBuilder Instance in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.0.0-rc.1/src/spin_sdk/http.rs.html Provides a convenient way to start building a `Request` using the `RequestBuilder` fluent API. It initializes a `RequestBuilder` with a default GET method and root URI ('/'). ```Rust /// Creates a [`RequestBuilder`] pub fn builder() -> RequestBuilder { RequestBuilder::new(Method::Get, "/") } ``` -------------------------------- ### Internal WASI Preopened Directory Implementation in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.0/src/spin_core/store.rs.html This private helper function implements the core logic for 'mounting' a host directory into the WASI filesystem. It opens the host path using `cap_std` and prepares the guest path, then attempts to configure the WASI context (Preview 1 or Preview 2) with the preopened directory, respecting the `writable` flag. The provided code snippet is incomplete, but it shows the initial setup for directory handling. ```Rust fn preopened_dir_impl( &mut self, host_path: impl AsRef, guest_path: PathBuf, writable: bool, ) -> Result<()> { let cap_std_dir = cap_std::fs::Dir::open_ambient_dir(host_path.as_ref(), cap_std::ambient_authority())?; let path = guest_path .to_str() .ok_or_else(|| anyhow!("non-utf8 path: {}", guest_path.display()))?; self.try_with_wasi(|wasi| { match wasi { WasiCtxBuilder::Preview1(ctx) => { let mut dir = ``` -------------------------------- ### Retrieving Function Locations in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.0.0-rc.1/spin_core/struct.Module.html Gets an iterator over the locations of functions within the module's `.text` section. Each location is represented as a (`.text` section offset, length) pair, indicating the start and size of a function. ```Rust pub fn function_locations<'a>(&'a self) -> impl ExactSizeIterator + 'a ``` -------------------------------- ### Creating Spin Engine Builder (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.0/src/spin_core/lib.rs.html This static method creates a new `EngineBuilder` instance, configured with the provided `Config`. The builder allows for a fluent API to set up various engine parameters before finally building the `Engine`. ```Rust pub fn builder(config: &Config) -> Result> { EngineBuilder::new(config) } ``` -------------------------------- ### Building Spin Engine with Host Data (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v0.10.0/src/spin_core/lib.rs.html This function builds an `Engine` instance from the `EngineBuilder`, incorporating specific host state data. It initializes the host components and a pre-instance store, which is crucial for `Engine::instantiate_pre`. ```Rust pub fn build_with_data(self, instance_pre_data: T) -> Engine { let epoch_ticker_signal = self.maybe_spawn_epoch_ticker(); let host_components = self.host_components_builder.build(); let instance_pre_store = Arc::new(Mutex::new( StoreBuilder::new(self.engine.clone(), Duration::ZERO, &host_components) .build_with_data(instance_pre_data) .expect("instance_pre_store build should not fail"), )); Engine { inner: self.engine, linker: self.linker, host_components, instance_pre_store, epoch_tick_interval: self.epoch_tick_interval, _epoch_ticker_signal: epoch_ticker_signal, } } ``` -------------------------------- ### Defining WASI File Descriptor and Capability Constants in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.3/src/spin_core/store.rs.html These constants define the starting file descriptor for preopened directories in WASI and specify read-only capabilities for directories and files. `WASI_FIRST_PREOPENED_DIR_FD` indicates that preopened directories start at FD 3, while `READ_ONLY_DIR_CAPS` and `READ_ONLY_FILE_CAPS` define the allowed operations for read-only access, such as opening, reading, seeking, and getting file statistics. ```Rust const WASI_FIRST_PREOPENED_DIR_FD: u32 = 3; const READ_ONLY_DIR_CAPS: DirCaps = DirCaps::from_bits_truncate( DirCaps::OPEN.bits() | DirCaps::READDIR.bits() | DirCaps::READLINK.bits() | DirCaps::PATH_FILESTAT_GET.bits() | DirCaps::FILESTAT_GET.bits(), ); const READ_ONLY_FILE_CAPS: FileCaps = FileCaps::from_bits_truncate( FileCaps::READ.bits() | FileCaps::SEEK.bits() | FileCaps::TELL.bits() | FileCaps::FILESTAT_GET.bits() | FileCaps::POLL_READWRITE.bits(), ); ``` -------------------------------- ### Creating New WASI Preview 1 Context in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.1.0/src/spin_core/store.rs.html This method constructs and returns a new `Wasi::Preview1` context. It initializes the WASI Preview 1 context using `wasmtime_wasi_preview1::WasiCtxBuilder::new().build()`, providing a default configuration for Preview 1 environments. ```Rust pub fn new_preview1() -> Self { Self::Preview1(wasmtime_wasi_preview1::WasiCtxBuilder::new().build()) } ``` -------------------------------- ### Getting Mutable First Element of Slice in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.5.0/spin_sdk/http/type.Params.html This example illustrates the `first_mut` method, which provides a mutable reference to the first element of a slice. If the slice is not empty, it returns `Some(&mut T)`, allowing in-place modification. ```Rust let x = &mut [0, 1, 2]; if let Some(first) = x.first_mut() { *first = 5; } assert_eq!(x, &[5, 1, 2]); ``` -------------------------------- ### Initializing PluginStore with Default Data Directory in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/main/src/spin_plugins/store.rs.html This method attempts to create a `PluginStore` instance using the default Spin data directory for plugins. It provides a convenient way to get a store configured for standard installations. ```Rust pub fn try_default() -> Result { Ok(Self::new(data_dir()?.join("plugins"))) } ``` -------------------------------- ### Creating a New WASI Preview 1 Context in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.3.0/src/spin_core/store.rs.html This function creates and returns a new `Wasi::Preview1` context. It initializes a `WasiCtx` using `wasmtime_wasi_preview1::WasiCtxBuilder::new().build()`, providing a default WASI Preview 1 environment suitable for WAGI applications. ```Rust pub fn new_preview1() -> Self { Self::Preview1(wasmtime_wasi_preview1::WasiCtxBuilder::new().build()) } ``` -------------------------------- ### Attempting to Get a Non-Existent Export (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.0/spin_core/struct.Module.html This example demonstrates using `Module::get_export()` to look up an export by name when the export does not exist. It creates a simple WASM module with no exports and asserts that the `get_export` call returns `None`. ```Rust let module = Module::new(&engine, "(module)")?; assert!(module.get_export("foo").is_none()); ``` -------------------------------- ### Creating Spin EngineBuilder (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.0.0-rc.2/src/spin_core/lib.rs.html This method provides a static factory for creating a new `EngineBuilder` instance. It takes a `Config` object, which specifies the Wasmtime engine's configuration, allowing for customized engine setup before building the final `Engine` instance. ```Rust pub fn builder(config: &Config) -> Result> { EngineBuilder::new(config) } ``` -------------------------------- ### Getting Mutable Last Element of Slice in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.5.0/spin_sdk/http/type.Params.html This example demonstrates the `last_mut` method, which provides a mutable reference to the last element in a slice. If the slice is not empty, it returns `Some(&mut T)`, allowing direct modification of the element. ```Rust let x = &mut [0, 1, 2]; if let Some(last) = x.last_mut() { *last = 10; } assert_eq!(x, &[0, 1, 10]); ``` -------------------------------- ### Creating a New StoreBuilder Instance (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.1.0/src/spin_core/store.rs.html This `new` constructor initializes a `StoreBuilder` with the provided Wasmtime engine, epoch tick interval, host components, and WASI context. It sets up the initial state for configuring a Wasmtime store, including default store limits and the starting preopen index. ```Rust pub(crate) fn new( engine: wasmtime::Engine, epoch_tick_interval: Duration, host_components: &HostComponents, wasi: Wasi, ) -> Self { Self { engine, epoch_tick_interval, wasi: Ok(wasi), host_components_data: host_components.new_data(), store_limits: StoreLimitsAsync::default(), next_preopen_index: WASI_FIRST_PREOPENED_DIR_FD, } } ``` -------------------------------- ### Applying AppComponent Store Configuration (Spin Framework, Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v0.8.0/src/spin_app/lib.rs.html This asynchronous function applies the component's configuration to a given `StoreBuilder`. It sets up WASI environment variables and preloaded directories, and configures any dynamic host components. It returns `Ok(())` on success or an `Err` if any configuration step fails. ```Rust pub async fn apply_store_config(&self, builder: &mut StoreBuilder) -> Result<()> { builder.env(&self.locked.env).map_err(Error::CoreError)?; let loader = self.app.loader; loader .inner .mount_files(builder, self) .await .map_err(Error::LoaderError)?; loader .dynamic_host_components .update_data(builder.host_components_data(), self) .map_err(Error::HostComponentError)?; Ok(()) } ``` -------------------------------- ### Getting Slice Length in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.5/spin_sdk/http/type.Params.html This example shows how to use the `len()` method to retrieve the number of elements present in a slice. The method returns a `usize` value representing the total count of elements. ```Rust let a = [1, 2, 3]; assert_eq!(a.len(), 3); ``` -------------------------------- ### Creating a Mutable Iterator over a Rust Slice with `iter_mut` Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.3.0/spin_sdk/http/type.Params.html This example shows how to get a mutable iterator over a Rust slice using the `iter_mut` method. This iterator yields mutable references to the elements, enabling in-place modification of each value. ```Rust let x = &mut [1, 2, 4]; for elem in x.iter_mut() { *elem += 2; } assert_eq!(x, &[3, 4, 6]); ``` -------------------------------- ### Creating a Spin Engine Builder in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.1.0/src/spin_core/lib.rs.html This associated function provides a convenient way to create a new `EngineBuilder` instance. It takes a `Config` reference as input, which is used to initialize the builder, and returns a `Result` containing the `EngineBuilder` or an error if initialization fails. This is the entry point for configuring and constructing a Spin `Engine`. ```Rust pub fn builder(config: &Config) -> Result> { EngineBuilder::new(config) } ``` -------------------------------- ### Pre-instantiating Wasm Component with Linker (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/main/src/spin_core/lib.rs.html This method creates a pre-instantiated Wasmtime `InstancePre` for a given `Component`. It utilizes the internal `linker` to prepare the instance, which can optimize subsequent instantiations. It requires a `&Component` object as input and returns a `Result>`. ```Rust /// Creates a new [`InstancePre`] for the given [`Component`]. #[instrument(skip_all, level = "debug")] pub fn instantiate_pre(&self, component: &Component) -> Result> { self.linker.instantiate_pre(component) } ``` -------------------------------- ### Creating a RequestBuilder (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.2.0/src/spin_sdk/http.rs.html Provides a static method `builder` to create a new `RequestBuilder` instance, initialized with a GET method and root path ("/"). This is a starting point for fluent request construction. ```Rust pub fn builder() -> RequestBuilder { RequestBuilder::new(Method::Get, "/") } ``` -------------------------------- ### Building Spin Engine with Custom Host Data (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.0.0-rc.2/src/spin_core/lib.rs.html This method constructs an `Engine` instance from the `EngineBuilder`, incorporating custom host state data (`instance_pre_data`). It initializes host components, sets up a pre-store for instances, and configures epoch ticking, returning a fully configured `Engine` ready for Wasm component execution. ```Rust pub fn build_with_data(self, instance_pre_data: T) -> Engine { let epoch_ticker_signal = self.maybe_spawn_epoch_ticker(); let host_components = self.host_components_builder.build(); let instance_pre_store = Arc::new(Mutex::new( StoreBuilder::new(self.engine.clone(), Duration::ZERO, &host_components) .build_with_data(instance_pre_data) .expect("instance_pre_store build should not fail"), )); Engine { inner: self.engine, linker: self.linker, host_components, instance_pre_store, epoch_tick_interval: self.epoch_tick_interval, _epoch_ticker_signal: epoch_ticker_signal, } } ``` -------------------------------- ### Creating a Default RequestBuilder in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.0/src/spin_sdk/http.rs.html Creates a new `RequestBuilder` initialized with a GET method and a root ('/') URI. This function provides a convenient starting point for fluently building HTTP requests. ```Rust pub fn builder() -> RequestBuilder { RequestBuilder::new(Method::Get, "/") } ``` -------------------------------- ### Pre-instantiating Wasm Module (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.0/src/spin_core/lib.rs.html This method creates a pre-initialized `InstancePre` for a given Wasm `Module`. Pre-instantiation optimizes subsequent instantiations of the same module by performing initial setup once. It acquires a lock on the `instance_pre_store` to perform the operation. ```Rust pub fn instantiate_pre(&self, module: &Module) -> Result> { let mut store = self.instance_pre_store.lock().unwrap(); let inner = self.linker.instantiate_pre(&mut *store, module)?; Ok(InstancePre { inner }) } ``` -------------------------------- ### Getting Function Locations in Rust Module Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.2.1/spin_core/struct.Module.html Retrieves an iterator over the locations of functions within the module's `.text` section. Each location is represented as an offset and length pair, indicating the start and size of the function in the text segment. ```Rust pub fn function_locations<'a>(&'a self) -> impl ExactSizeIterator + 'a ``` -------------------------------- ### Get Initial CWD - WASI CLI Environment - Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/main/src/spin_factor_wasi/wasi_2023_11_10.rs.html Implements the `initial_cwd` method for `WasiImpl`, retrieving the initial current working directory of the host. This provides the WebAssembly module with information about its starting directory context. ```Rust latest::cli::environment::Host::initial_cwd(self) ``` -------------------------------- ### Creating a New WebAssembly Instance (Instance::new) in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.1.0/spin_core/struct.ModuleInstance.html The `Instance::new` function instantiates a WebAssembly module. It takes a mutable store context (`store`), a compiled `Module`, and a slice of `Extern` imports. It returns a `Result` containing the new `Instance` on success or an `Error` on failure. Instantiation includes running the module's start function if present. This is a low-level API; for easier import linking, consider using the `Linker` struct. ```Rust pub fn new( store: impl AsContextMut, module: &[Module], imports: &[Extern] ) -> Result ``` -------------------------------- ### Asynchronously Instantiating Wasm Module (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.0.0-rc.2/src/spin_core/lib.rs.html This asynchronous method instantiates the pre-initialized Wasm module represented by `InstancePre` into a given `Store`. It leverages the underlying `wasmtime::InstancePre::instantiate_async` to efficiently create a live Wasm `Instance`, ready for execution. ```Rust #[instrument(skip_all)] pub async fn instantiate_async(&self, store: &mut Store) -> Result { self.inner.instantiate_async(store).await } ``` -------------------------------- ### Consuming HTTP Response to Get Body in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.0/spin_sdk/http/struct.Response.html This method consumes the `Response` object and returns its underlying body as a `Vec`. This is useful when you need to take ownership of the body data, for example, to pass it to another function or process it further. ```Rust pub fn into_body(self) -> Vec ``` -------------------------------- ### Getting Incoming Request URI in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.1.0/src/spin_sdk/http.rs.html This method of `IncomingRequest` begins to construct the full URI string. It starts by checking for the scheme and authority components, specifically handling the `Http` scheme. The provided snippet is incomplete. ```Rust pub fn uri(&self) -> String { let scheme_and_authority = if let (Some(scheme), Some(authority)) = (self.scheme(), self.authority()) { let scheme = match &scheme { Scheme::Http => "http://", ``` -------------------------------- ### Pre-instantiating a Spin Component - Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.0/spin_core/struct.Engine.html This method prepares a `Component` for instantiation by creating an `InstancePre` object. This pre-instantiation step allows for setup and validation before the component is fully loaded and executed. It takes a reference to a `Component` and returns a `Result` containing the `InstancePre` or an error. ```Rust pub fn instantiate_pre(&self, component: &Component) -> Result> ``` -------------------------------- ### Asynchronously Instantiating a Spin Component (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.1.0/src/spin_core/lib.rs.html This asynchronous method instantiates the pre-initialized component represented by `InstancePre` into a live `Instance` within the provided `Store`. It delegates the actual instantiation to the underlying `wasmtime::component::InstancePre`, awaiting its completion. This is the final step to run a WebAssembly component. ```Rust #[instrument(skip_all)] pub async fn instantiate_async(&self, store: &mut Store) -> Result { self.inner.instantiate_async(store).await } ``` -------------------------------- ### Creating a Generic RequestBuilder in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v2.1/src/spin_sdk/http.rs.html This function provides a convenient way to create a new `RequestBuilder` instance, initialized with a GET method and a root path ('/'). It serves as a starting point for building more complex requests. ```Rust /// Creates a [`RequestBuilder`] pub fn builder() -> RequestBuilder { RequestBuilder::new(Method::Get, "/") } ``` -------------------------------- ### Creating Spin EngineBuilder from Engine (Rust) Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.5.1/src/spin_core/lib.rs.html This associated function on the `Engine` struct provides a convenient way to create a new `EngineBuilder` instance. It takes a `Config` reference, which is used to initialize the builder with specific Wasmtime engine configurations. This method is the entry point for configuring and constructing a Spin `Engine`. ```Rust pub fn builder(config: &Config) -> Result> { EngineBuilder::new(config) } ``` -------------------------------- ### Iterating Reverse Chunks with `rchunks` in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/v1.3.0/spin_sdk/http/type.Params.html This example demonstrates the `slice::rchunks` method, which iterates over a slice in non-overlapping chunks starting from the end. It shows how the last chunk might be smaller if the `chunk_size` does not evenly divide the slice length. ```Rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` -------------------------------- ### Retrieving Module Name in Rust Source: https://github.com/spinframework/rust-docs/blob/main/docs/spin/vault-test/spin_core/struct.Module.html This example demonstrates how to use the `name()` method of the `spin_core::Module` struct to get the identifier of a WebAssembly module. It illustrates scenarios where a module has a name (e.g., `$foo`) and where it does not, showing the expected `Option<&str>` return values. ```Rust let module = Module::new(&engine, "(module $foo)")?; assert_eq!(module.name(), Some("foo")); let module = Module::new(&engine, "(module)")?; assert_eq!(module.name(), None); ```