### Fundle Quick Start Example Source: https://github.com/microsoft/oxidizer/blob/main/crates/fundle/README.md This Rust code snippet demonstrates the basic usage of the Fundle crate for setting up a dependency-injection pattern. It defines a service struct `AppState` with its dependencies (`Logger`, `Database`, `Config`) and then constructs an instance of `AppState` using the Fundle builder pattern, ensuring all dependencies are met at compile time. ```rust #[macro_use] extern crate lazy_static; use std::sync::Arc; // Mock implementations for demonstration struct Logger; impl Logger { fn new() -> Self { Logger } fn log(&self, message: &str) { println!("LOG: {}", message); } } struct Config { logger: Logger, } impl Config { fn new_with_logger(logger: Logger) -> Self { Config { logger } } fn get(&self, key: &str) -> String { format!("value for {}", key) } } struct Database { config: Config, } impl Database { fn connect(connection_string: &str, config: Config) -> Self { config.logger.log(&format!("Connecting to {}...", connection_string)); Database { config } } fn query(&self, query: &str) -> String { format!("Query result for: {}", query) } } // Fundle's generated structure and builder #[fundle::bundle] pub struct AppState { logger: Logger, database: Database, config: Config, } fn main() { // The AppState::builder() is generated by the #[fundle::bundle] macro. // Each closure receives dependencies that have already been constructed. let app = AppState::builder() .logger(|_| Logger::new()) // Logger doesn't depend on anything else yet. .config(|deps| Config::new_with_logger(deps.logger)) .database(|deps| Database::connect("postgresql://localhost", deps.config)) .build(); // Now you can use the built application state. let db_result = app.database.query("SELECT * FROM users"); println!("{}", db_result); // You can also access dependencies through other dependencies. let config_value = app.database.config.get("api_key"); println!("API Key (from config via db): {}", config_value); } ``` -------------------------------- ### Clone and Consume BytesView Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md Shows how to safely consume a BytesView by creating a clone first. Cloning is a cheap, zero-copy operation. This allows multiple independent consumers to process the same byte sequence without affecting each other. The example demonstrates cloning, consuming from the clone, and verifying the original remains unchanged. ```rust use bytes::Buf; use bytesbuf::BytesView; // Assuming 'sequence' is an existing BytesView instance // let mut sequence = BytesView::from(...); // assert_eq!(sequence.len(), 16); // Example initial length let mut sequence_clone = sequence.clone(); // assert_eq!(sequence_clone.len(), 16); _ = sequence_clone.get_u64(); // Consume some data from the clone // assert_eq!(sequence_clone.len(), 8); // Operations on the clone have no effect on the original sequence. // assert_eq!(sequence.len(), 16); ``` -------------------------------- ### Compile-Time Dependency Injection with Fundle in Rust Source: https://context7.com/microsoft/oxidizer/llms.txt This Rust code demonstrates compile-time dependency injection using the `fundle` crate. It allows building type-safe dependency graphs with zero runtime overhead. The example defines several structs (Config, Logger, Database, ApiServer) and uses the `#[bundle]` macro to construct an application state (`AppState`) with validated dependencies. The `build()` method constructs the application state by resolving dependencies. ```rust use fundle::bundle; #[derive(Clone, Debug)] struct Config { database_url: String, } impl Config { fn new() -> Self { Self { database_url: "postgresql://localhost".to_string(), } } } #[derive(Clone, Debug)] struct Logger { level: String, } impl Logger { fn new() -> Self { Self { level: "info".to_string() } } fn log(&self, msg: &str) { println!("[{}] {}", self.level, msg); } } #[derive(Clone, Debug)] struct Database { connection: String, } impl Database { fn connect(config: impl AsRef, logger: impl AsRef) -> Self { logger.as_ref().log("Connecting to database"); Self { connection: config.as_ref().database_url.clone(), } } } #[derive(Clone, Debug)] struct ApiServer { port: u16, } impl ApiServer { fn new(logger: impl AsRef, db: impl AsRef) -> Self { logger.as_ref().log("Starting API server"); println!("Connected to: {}", db.as_ref().connection); Self { port: 8080 } } } // Define the application state bundle with dependency injection #[bundle] pub struct AppState { logger: Logger, config: Config, database: Database, server: ApiServer, } fn main() { // Build with compile-time validated dependency graph let app = AppState::builder() .logger(|_| Logger::new()) .config(|_| Config::new()) .database(|deps| Database::connect(deps, deps)) .server(|deps| ApiServer::new(deps, deps)) .build(); // Output: // [info] Connecting to database // [info] Starting API server // Connected to: postgresql://localhost println!("App running on port {}", app.server.port); // Output: App running on port 8080 } ``` -------------------------------- ### Create Classified Containers and Redact Data with Rust Source: https://github.com/microsoft/oxidizer/blob/main/crates/data_privacy/README.md Shows how to define classified container types using the `classified` attribute macro, associate them with taxonomy data classes, and use a `RedactionEngine` to redact sensitive data. This example covers defining enums for taxonomies, structs for classified containers, and initializing a redaction engine with custom redactors. ```rust use data_privacy::{classified, RedactionEngine, taxonomy}; use data_privacy::simple_redactor::{SimpleRedactor, SimpleRedactorMode}; // A simple taxonomy definition for the Contoso organization. #[taxonomy(contoso)] enum ContosoTaxonomy { CustomerContent, CustomerIdentifier, OrganizationIdentifier, } // A classified container for customer names. #[classified(ContosoTaxonomy::CustomerIdentifier)] struct Name(String); // A classified container for customer addresses. #[classified(ContosoTaxonomy::CustomerIdentifier)] struct Address(String); // A classified container for customer content. #[classified(ContosoTaxonomy::CustomerContent)] struct Memo(String); // A customer record which contains a bunch of classified data. #[derive(Debug)] struct Customer { name: Name, address: Address, memo : Memo, } let c = Customer { name: Name("John Doe".to_string()), address: Address("123 Main St, Anytown, USA".to_string()), memo: Memo("Leave packages on the front porch.".to_string()), }; // Displaying the customer record will not leak sensitive data because the classified containers protect the data println!("Customer record: {:?}", c); // You can get redacted representations of classified data using a [`RedactionEngine`](redaction_engine::RedactionEngine). // Initialize some redactors let asterisk_redactor = SimpleRedactor::new(); let erasing_redactor = SimpleRedactor::with_mode(SimpleRedactorMode::Erase); // Create the redaction engine. This is typically done once when the application starts. let engine = RedactionEngine::builder() .add_class_redactor(ContosoTaxonomy::CustomerIdentifier.data_class(), asterisk_redactor) .set_fallback_redactor(erasing_redactor) .build(); let mut output_buffer = String::new(); _ = engine.redacted_display(&c.name, &mut output_buffer); // check that the data in the output buffer has indeed been redacted as expected. assert_eq!(output_buffer, "********"); ``` -------------------------------- ### Quick Start: Define and use ConfigError with error enrichment Source: https://github.com/microsoft/oxidizer/blob/main/crates/ohno/README.md Demonstrates how to define a custom error type `ConfigError` using `#[ohno::error]` and enrich it with file and line information using `#[ohno::enrich_err]`. It shows how to map underlying errors using `caused_by`. ```rust use std::path::{Path, PathBuf}; #[ohno::error] pub struct ConfigError(PathBuf); #[ohno::enrich_err("failed to open file {}", path.as_ref().display())] fn open_file(path: impl AsRef) -> Result { std::fs::read_to_string(path.as_ref()) .map_err(|e| ConfigError::caused_by(path.as_ref().to_path_buf(), e)) } ``` -------------------------------- ### ThreadAware: Rust Thread-Per-Core Optimizations Source: https://context7.com/microsoft/oxidizer/llms.txt Illustrates how to use the 'thread_aware' crate in Rust for thread-per-core runtimes, enabling efficient state migration across thread and NUMA boundaries. It demonstrates defining a 'Service' struct with thread-aware components using Arc for per-thread instances and Arc for globally shared instances. The example shows how `on_relocation()` triggers new instances for PerThread types when state is migrated. ```rust use thread_aware::{ThreadAware, Arc, PerThread, PerProcess}; // External type without ThreadAware implementation #[derive(Debug, Clone)] struct ConnectionPool { connections: Vec, } impl Default for ConnectionPool { fn default() -> Self { println!("Creating new connection pool"); Self { connections: vec!["conn1".to_string(), "conn2".to_string()], } } } // Define a service with thread-aware components #[derive(Debug, Clone, ThreadAware)] struct Service { name: String, // PerThread: creates new instance when crossing thread boundary thread_local_pool: Arc, // PerProcess: shared across all threads shared_cache: Arc, PerProcess>, } impl Service { fn new(name: String) -> Self { Self { name, thread_local_pool: Arc::new(|| ConnectionPool::default()), shared_cache: Arc::new(|| vec!["cached_data".to_string()]), } } fn process(&self, data: &str) { println!("{} processing: {}", self.name, data); println!("Pool size: {}", self.thread_local_pool.connections.len()); println!("Cache size: {}", self.shared_cache.len()); } } fn main() { let service = Service::new("MainService".to_string()); service.process("request_1"); // Output: // Creating new connection pool // MainService processing: request_1 // Pool size: 2 // Cache size: 1 // Simulate moving to another thread in a thread-per-core runtime let mut relocated = service.clone(); use thread_aware::ThreadAware as _; relocated.on_relocation(); // Output: // Creating new connection pool (PerThread creates new instance) relocated.process("request_2"); // Output: // MainService processing: request_2 // Pool size: 2 (new pool) // Cache size: 1 (same shared cache) } ``` -------------------------------- ### Enable ThreadAware with Arc in Rust Source: https://github.com/microsoft/oxidizer/blob/main/crates/thread_aware/README.md This example demonstrates how to enable ThreadAware for a struct that contains fields not inherently compatible with the trait. It utilizes `Arc` with a `PerThread` strategy to wrap such fields, allowing the overall struct to implement ThreadAware. This is useful for managing dependencies like `Client` that might have their own threading strategies. ```rust use thread_aware::{ThreadAware, Arc, PerThread}; #[derive(Debug, Clone, ThreadAware)] struct Service { name: String, client: Arc, } impl Service { fn new() -> Self { Self { name: "MyService".to_string(), client: Arc::new(|| Client::default()), } } } ``` -------------------------------- ### Inspect BytesView chunks using Buf trait Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md Illustrates inspecting the chunk structure of a BytesView without consuming it entirely. It repeatedly calls `chunk()` to get byte slices and `advance()` to move past them, recording the lengths of each chunk. This is useful for understanding the underlying memory layout of the BytesView. ```rust use bytes::Buf; use bytesbuf::BytesView; // Assuming 'sequence' is an existing BytesView instance // let mut sequence = BytesView::from(...); let len = sequence.len(); let mut chunk_lengths = Vec::new(); while sequence.has_remaining() { let chunk = sequence.chunk(); chunk_lengths.push(chunk.len()); // We have completed processing this chunk, all we wanted was to know its length. sequence.advance(chunk.len()); } println!("Inspected a sequence of {len} bytes with chunk lengths: {chunk_lengths:?}"); ``` -------------------------------- ### Define a Taxonomy with `taxonomy` Macro in Rust Source: https://github.com/microsoft/oxidizer/blob/main/crates/data_privacy/README.md Demonstrates how to define a taxonomy using the `taxonomy` attribute macro on an enum. Each enum variant represents a data class within the taxonomy. The `data_class` method can be called on an enum variant to get a `DataClass` instance. ```rust use data_privacy::taxonomy; // A simple taxonomy definition for the Contoso organization. #[taxonomy(contoso)] enum ContosoTaxonomy { CustomerContent, CustomerIdentifier, OrganizationIdentifier, } let dc = ContosoTaxonomy::CustomerIdentifier.data_class(); assert_eq!(dc.taxonomy(), "contoso"); assert_eq!(dc.name(), "customer_identifier"); ``` -------------------------------- ### Automatic Constructors: Generate `new` and `caused_by` methods Source: https://github.com/microsoft/oxidizer/blob/main/crates/ohno/README.md Explains that `#[derive(Error)]` automatically generates `new()` and `caused_by()` constructor methods for error types. It provides examples of how these constructors are used. ```rust #[ohno::error] struct ConfigError { path: String, } // The derive macro automatically generates: // - ConfigError::new(path: String) -> Self // - ConfigError::caused_by(path: String, error: impl Into>) -> Self let error = ConfigError::new("/etc/config.toml"); let error_with_cause = ConfigError::caused_by("/etc/config.toml", "File not found"); ``` -------------------------------- ### Reserve Memory for Byte Sequence in Rust Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md Demonstrates how to obtain a memory provider and reserve initial capacity for a byte sequence using BytesBuf. This is the first step in creating mutable byte sequences. ```rust use bytesbuf::Memory; let memory = connection.memory(); let mut sequence_builder = memory.reserve(100); ``` -------------------------------- ### Rust: Reserve and Append Memory with BytesBuf Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md Demonstrates reserving memory capacity and appending data using Rust's bytesbuf crate. It shows how to create a header and append it along with other data to a sequence builder. This method reuses memory capacity efficiently. ```rust use bytes::buf::BufMut; use bytesbuf::Memory; let memory = connection.memory(); let mut header_builder = memory.reserve(16); header_builder.put_u64(1234); let header = header_builder.consume_all(); let mut sequence_builder = memory.reserve(128); sequence_builder.append(header); sequence_builder.put(b"Hello, world!".as_slice()); ``` -------------------------------- ### Optimizing Memory Provider for Byte Sequence Consumption (Rust) Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md Shows how to implement `HasMemory` by returning a memory provider that reserves I/O memory with specific configurations for optimal performance. This is useful when the type can directly benefit from tailored memory settings. ```rust use bytesbuf::{CallbackMemory, HasMemory, MemoryShared, BytesView}; /// # Implementation strategy for `HasMemory` /// /// This type can benefit from optimal performance if specifically configured memory is used and /// the memory is reserved from the I/O memory pool. It uses the I/O context to reserve memory, /// providing a usage-specific configuration when reserving memory capacity. /// /// A delegating memory provider is used to attach the configuration to each memory reservation. #[derive(Debug)] struct UdpConnection { io_context: IoContext, } impl UdpConnection { pub fn new(io_context: IoContext) -> Self { Self { io_context } } } /// Represents the optimal memory configuration for a UDP connection when reserving I/O memory. const UDP_CONNECTION_OPTIMAL_MEMORY_CONFIGURATION: MemoryConfiguration = MemoryConfiguration { requires_page_alignment: false, zero_memory_on_release: false, requires_registered_memory: true, }; impl HasMemory for UdpConnection { fn memory(&self) -> impl MemoryShared { CallbackMemory::new({ // Cloning is cheap, as it is a service that shares resources between clones. let io_context = self.io_context.clone(); move |min_len| { io_context.reserve_io_memory(min_len, UDP_CONNECTION_OPTIMAL_MEMORY_CONFIGURATION) } }) } } ``` -------------------------------- ### Optimized I/O Path Determination in Rust with BytesView Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md Demonstrates how to determine if a `BytesView` message can use an optimized I/O path by checking its memory chunk metadata. It iterates through metadata, checks for `MemoryConfiguration`, and verifies if registered memory is required for the optimal path. Falls back to a generic implementation if conditions are not met. ```rust use bytesbuf::BytesView; pub fn write(&mut self, message: BytesView) { // We now need to identify whether the message actually uses memory that allows us to // ues the optimal I/O path. There is no requirement that the data passed to us contains // only memory with our preferred configuration. let use_optimal_path = message.iter_chunk_metas().all(|meta| { // If there is no metadata, the memory is not I/O memory. meta.is_some_and(|meta| { // If the type of metadata does not match the metadata // exposed by the I/O memory provider, the memory is not I/O memory. let Some(io_memory_configuration) = meta.downcast_ref::() else { return false; }; // If the memory is I/O memory but is not not pre-registered // with the operating system, we cannot use the optimal path. io_memory_configuration.requires_registered_memory }) }); if use_optimal_path { self.write_optimal(message); } else { self.write_fallback(message); } } ``` -------------------------------- ### Initialize Static Header Prefix BytesView with OnceLock (Rust) Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md This snippet demonstrates initializing a `BytesView` from a static byte slice using `std::sync::OnceLock`. It ensures that the `BytesView` is created only once and uses memory optimally configured for the given context, such as a network connection. Subsequent uses reuse the initialized `BytesView` through a cheap, zero-copy clone operation. ```rust use std::sync::OnceLock; use bytesbuf::BytesView; const HEADER_PREFIX: &[u8] = b"Unix-Milliseconds: "; // We transform the static data into a BytesView on first use, via OnceLock. // // You are expected to reuse this variable as long as the context does not change. // For example, it is typically fine to share this across multiple network connections // because they all likely use the same memory configuration. However, writing to files // may require a different memory configuration for optimality, so you would need a different // `BytesView` for that. Such details will typically be documented in the API documentation // of the type that consumes the `BytesView` (e.g. a network connection or a file writer). let header_prefix = OnceLock::::new(); for _ in 0..10 { let mut connection = Connection::accept(); // The static data is transformed into a BytesView on first use, // using memory optimally configured for a network connection. let header_prefix = header_prefix .get_or_init(|| BytesView::copied_from_slice(HEADER_PREFIX, &connection.memory())); // Now we can use the `header_prefix` BytesView in the connection logic. // Cloning a BytesView is a cheap zero-copy operation. connection.write(header_prefix.clone()); } ``` -------------------------------- ### Usage-Neutral Memory Provider for Byte Sequence Consumption (Rust) Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md Illustrates implementing `HasMemory` by using `GlobalPool` as the memory provider. This strategy is appropriate for types that do not have specific memory configuration needs and do not pass data to other types with such requirements. ```rust use bytesbuf::{GlobalPool, HasMemory, MemoryShared}; /// Calculates a checksum for a given byte sequence. /// /// # Implementation strategy for `HasMemory` /// /// This type does not benefit from any specific memory configuration - it consumes bytes no /// matter what sort of memory they are in. It also does not pass the bytes to some other type. /// /// Therefore, we simply use `GlobalPool` as the memory provider we publish, as this is /// the default choice when there is no specific provider to prefer. ``` -------------------------------- ### Forwarding Memory Provider for Byte Sequence Consumption (Rust) Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md Demonstrates implementing `HasMemory` by forwarding the memory provider of an underlying `Connection` type. This is suitable when a type only inspects byte sequences before passing them to another component that has specific memory requirements. ```rust use bytesbuf::{HasMemory, MemoryShared, BytesView}; /// Counts the number of 0x00 bytes in a sequence before /// writing that sequence to a network connection. /// /// # Implementation strategy for `HasMemory` /// /// This type merely inspects a byte sequence before passing it on. This means that it does not /// have a preference of its own for how that memory should be configured. /// /// However, the thing it passes the sequence to (the `Connection` type) may have a preference, /// so we forward the memory provider of the `Connection` type as our own memory provider, so the /// caller can use memory optimal for submission to the `Connection` instance. #[derive(Debug)] struct ConnectionZeroCounter { connection: Connection, } impl ConnectionZeroCounter { pub fn new(connection: Connection) -> Self { Self { connection, } } pub fn write(&mut self, sequence: BytesView) { // TODO: Count zeros. self.connection.write(sequence); } } impl HasMemory for ConnectionZeroCounter { fn memory(&self) -> impl MemoryShared { // We forward the memory provider of the connection, so that the caller can use // memory optimal for submission to the connection. self.connection.memory() } } ``` -------------------------------- ### Dynamic Byte Buffer Growth with Rust BytesBuf Source: https://context7.com/microsoft/oxidizer/llms.txt Demonstrates dynamic byte sequence construction using Rust's `bytesbuf` crate. It highlights automatic capacity extension and zero-copy append operations, suitable for network programming and I/O-intensive tasks. The `BytesBuf` allows for efficient manipulation of byte data with minimal memory allocations. ```rust use bytes::BufMut; use bytesbuf::{BytesBuf, BytesView, GlobalPool, Memory}; fn build_http_response(memory: &impl Memory) -> BytesView { // Start with initial capacity let mut response = memory.reserve(256); // Write HTTP headers response.put_slice(b"HTTP/1.1 200 OK\r\n"); response.put_slice(b"Content-Type: application/json\r\n"); // Check capacity and extend if needed let body = r#"{"status":"success","data":{"items":[1,2,3,4,5]}}"#; let needed = body.len() + 4; // +4 for \r\n\r\n if response.remaining_mut() < needed { response.reserve(needed, memory); } response.put_slice(b"\r\n"); response.put_slice(body.as_bytes()); // Zero-copy conversion to immutable sequence response.consume_all() } fn append_responses(memory: &impl Memory) -> BytesView { // Create first response let response1 = build_http_response(memory); // Create a builder and append existing sequence (zero-copy) let mut combined = memory.reserve(512); combined.append(response1); // Add separator combined.put_slice(b"\r\n---BATCH---\r\n"); // Append second response let response2 = build_http_response(memory); combined.append(response2); combined.consume_all() } fn main() { let memory = GlobalPool::new(); let batched = append_responses(&memory); println!("Total response size: {} bytes", batched.len()); println!("First 50 bytes: {:?}", &batched.chunk()[..50]); } ``` -------------------------------- ### Consume All Data from Byte Sequence Buffer in Rust Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md Demonstrates how to convert a fully populated `BytesBuf` into an immutable `BytesView` using `consume_all()`. This is useful when the entire buffer content is ready to be processed. ```rust use bytes::buf::BufMut; use bytesbuf::Memory; let memory = connection.memory(); let mut sequence_builder = memory.reserve(100); sequence_builder.put_u64(1234); sequence_builder.put_u64(5678); sequence_builder.put(b"Hello, world!".as_slice()); let message = sequence_builder.consume_all(); ``` -------------------------------- ### Write Data to Byte Sequence Buffer in Rust Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md Illustrates how to fill a reserved byte buffer using the `bytes::buf::BufMut` trait. This includes writing primitive types like u64 and byte slices. ```rust use bytes::buf::BufMut; use bytesbuf::Memory; let memory = connection.memory(); let mut sequence_builder = memory.reserve(100); sequence_builder.put_u64(1234); sequence_builder.put_u64(5678); sequence_builder.put(b"Hello, world!".as_slice()); ``` -------------------------------- ### Consume BytesView using Buf trait Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md Demonstrates consuming a BytesView by reading u64 words until the sequence is empty. It utilizes the `bytes::buf::Buf` trait for reading and advancing. This method is suitable for structured byte data where elements of known size are sequentially read. ```rust use bytes::Buf; use bytesbuf::BytesView; fn consume_message(mut message: BytesView) { // We read the message and calculate the sum of all the words in it. let mut sum: u64 = 0; while message.has_remaining() { let word = message.get_u64(); sum = sum.saturating_add(word); } println!("Message received. The sum of all words in the message is {sum}."); } ``` -------------------------------- ### Extend Byte Sequence Buffer Capacity in Rust Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md Shows how to dynamically increase the capacity of a byte sequence buffer when more memory is needed than initially reserved. It utilizes `BytesBuf::reserve()` and checks remaining capacity with `remaining_mut()`. ```rust use bytes::buf::BufMut; use bytesbuf::Memory; let memory = connection.memory(); let mut sequence_builder = memory.reserve(100); // .. write some data into the sequence builder .. // We discover that we need 80 additional bytes of memory! No problem. sequence_builder.reserve(80, &memory); // Remember that a memory provider can always provide more memory than requested. assert!(sequence_builder.capacity() >= 100 + 80); assert!(sequence_builder.remaining_mut() >= 80); ``` -------------------------------- ### BytesView: Zero-Copy Byte Sequence Manipulation in Rust Source: https://context7.com/microsoft/oxidizer/llms.txt Demonstrates how to create and manipulate non-contiguous byte sequences using `bytesbuf` for efficient, zero-copy I/O operations. It utilizes `GlobalPool` for memory management and `BytesView` for byte sequence representation. ```rust use bytes::{Buf, BufMut}; use bytesbuf::{BytesView, BytesBuf, GlobalPool, Memory}; fn main() { // Initialize memory provider let memory = GlobalPool::new(); // Producer: Create a byte sequence let mut builder = memory.reserve(1024); builder.put_u64(42); builder.put_u64(100); builder.put_slice(b"Hello, World!"); let message: BytesView = builder.consume_all(); // Consumer: Read the byte sequence let mut reader = message.clone(); let first = reader.get_u64(); // 42 let second = reader.get_u64(); // 100 let remaining = reader.chunk(); // b"Hello, World!" println!("Read: {}, {}, {:?}", first, second, remaining); // Output: Read: 42, 100, [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33] } ``` -------------------------------- ### Consume Data Piecewise from Byte Sequence Buffer in Rust Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md Explains how to consume data from a `BytesBuf` incrementally using `consume()` while still allowing further writes to the buffer. This is useful for processing data in chunks. ```rust use bytes::buf::BufMut; use bytesbuf::Memory; let memory = connection.memory(); let mut sequence_builder = memory.reserve(100); sequence_builder.put_u64(1234); sequence_builder.put_u64(5678); let first_8_bytes = sequence_builder.consume(8); let second_8_bytes = sequence_builder.consume(8); sequence_builder.put(b"Hello, world!".as_slice()); let final_contents = sequence_builder.consume_all(); ``` -------------------------------- ### BytesView to Bytes Conversion in Rust Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md Provides methods for converting between `BytesView` and the `bytes` crate's `Bytes` type. `BytesView::into_bytes()` is not always zero-copy and is discouraged for performance-critical paths. `BytesView::from(Bytes)` is an efficient, zero-copy operation that reuses the `Bytes` instance's memory. ```rust // Converts a `BytesView` into a `Bytes` instance. This is not always zero-copy. // let bytes = bytes_view.into_bytes(); // Converts a `Bytes` instance into a `BytesView`. This is an efficient zero-copy operation. // let bytes_view: BytesView = bytes.into(); ``` -------------------------------- ### Ohno: Rust Error Handling with Enrichment Source: https://context7.com/microsoft/oxidizer/llms.txt Demonstrates how to create custom error types with automatic backtraces, cause chains, and contextual enrichment using the 'ohno' crate in Rust. It shows defining error structs, annotating them with #[error] and #[display], and using #[enrich_err] for automatic context addition to errors during function execution. This helps in debugging by providing detailed error information. ```rust use std::path::{Path, PathBuf}; use ohno::{error, enrich_err}; // Define custom error types with fields #[error] #[display("Configuration error for file: {path}")] struct ConfigError { path: PathBuf, } #[error] #[display("Database connection failed: {host}:{port}")] struct DatabaseError { host: String, port: u16, } // Automatic error enrichment with context #[enrich_err("failed to load config file")] fn load_config(path: impl AsRef) -> Result { std::fs::read_to_string(path.as_ref()) .map_err(|e| ConfigError::caused_by(path.as_ref().to_path_buf(), e)) } #[enrich_err("failed to initialize database with config from {}", config_path.as_ref().display())] fn init_database(config_path: impl AsRef) -> Result<(), DatabaseError> { let _config = load_config(config_path)?; // Simulate database connection error Err(DatabaseError::new("localhost".to_string(), 5432)) } fn main() { match init_database("/etc/app/config.toml") { Ok(_) => println!("Success"), Err(e) => { println!("Error: {}", e); // Output shows full error chain with enrichment: // Error: Database connection failed: localhost:5432 // Caused by: // failed to initialize database with config from /etc/app/config.toml (at src/main.rs:22) // Configuration error for file: /etc/app/config.toml // failed to load config file (at src/main.rs:15) // No such file or directory (os error 2) // Access error chain programmatically if let Some(source) = std::error::Error::source(&e) { println!("Caused by: {}", source); } } } } ``` -------------------------------- ### Define Static Header Prefix Byte Slice (Rust) Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md This snippet defines a constant byte slice for a static header prefix. This is a fundamental building block for efficient static data handling, typically used in conjunction with mechanisms like `OnceLock` and `BytesView` for optimized processing. ```rust const HEADER_PREFIX: &[u8] = b"Unix-Milliseconds: "; ``` -------------------------------- ### ChecksumCalculator with GlobalPool Memory Provider in Rust Source: https://github.com/microsoft/oxidizer/blob/main/crates/bytesbuf/README.md Defines a `ChecksumCalculator` struct that depends on a `GlobalPool` for memory. It implements `new` for construction and `HasMemory` trait to provide access to the memory provider, emphasizing that cloning memory providers is efficient. ```rust #[derive(Debug)] struct ChecksumCalculator { // The application logic must provide this - it is our dependency. memory_provider: GlobalPool, } impl ChecksumCalculator { pub fn new(memory_provider: GlobalPool) -> Self { Self { memory_provider } } } impl HasMemory for ChecksumCalculator { fn memory(&self) -> impl MemoryShared { // Cloning a memory provider is a cheap operation, as clones reuse resources. self.memory_provider.clone() } } ``` -------------------------------- ### HasMemory Trait: Optimal Memory Configuration in Rust Source: https://context7.com/microsoft/oxidizer/llms.txt Illustrates the implementation of the `HasMemory` trait to provide optimized memory configuration for types that consume byte sequences. This allows for performance enhancements in memory allocation and access, using `GlobalPool` as a memory provider. ```rust use bytesbuf::{HasMemory, MemoryShared, BytesView, GlobalPool}; struct NetworkConnection { memory_provider: GlobalPool, } impl NetworkConnection { pub fn new(memory_provider: GlobalPool) -> Self { Self { memory_provider } } pub fn write(&mut self, data: BytesView) { // Use the data for network I/O println!("Writing {} bytes to network", data.len()); } } // Implement HasMemory to provide optimized memory for callers impl HasMemory for NetworkConnection { fn memory(&self) -> impl MemoryShared { self.memory_provider.clone() } } fn main() { let pool = GlobalPool::new(); let connection = NetworkConnection::new(pool.clone()); // Callers can now use optimal memory for this connection let memory = connection.memory(); let mut builder = memory.reserve(512); builder.put_slice(b"GET / HTTP/1.1\r\n"); let request = builder.consume_all(); // connection.write(request); } ``` -------------------------------- ### Rust: #[bundle] Macro for Type-Safe Builders Source: https://github.com/microsoft/oxidizer/blob/main/crates/fundle_macros/README.md The `#[bundle]` macro transforms a struct definition into a type-safe builder pattern. It automatically generates builder methods and a select macro for efficient dependency injection, simplifying the creation and management of application state. ```rust #[fundle::bundle] pub struct AppState { logger: Logger, database: Database, } ``` -------------------------------- ### Rust: #[deps] Macro for Dependency Parameter Structs Source: https://github.com/microsoft/oxidizer/blob/main/crates/fundle_macros/README.md The `#[deps]` macro generates dependency parameter structs, providing automatic `From` implementations. This simplifies the process of injecting dependencies into services or components by allowing them to be constructed from various compatible types. ```rust #[fundle::deps] pub struct ServiceDeps { logger: Logger, database: Database, } // Generates `From` where `T: AsRef + AsRef`. ``` -------------------------------- ### Derive ThreadAware Macro in Rust Source: https://github.com/microsoft/oxidizer/blob/main/crates/thread_aware/README.md This snippet shows how to automatically implement the ThreadAware trait for a struct using the `#[derive(ThreadAware)]` macro. This requires the `derive` feature to be enabled. It's a convenient way to apply the trait without manual implementation. ```rust use thread_aware::ThreadAware; #[derive(Debug, Clone, ThreadAware)] struct Point { x: i32, y: i32, } ``` -------------------------------- ### Ohno Error Macro: Define simple and complex error types Source: https://github.com/microsoft/oxidizer/blob/main/crates/ohno/README.md Illustrates the usage of the `#[ohno::error]` attribute macro to define error types. It shows how to create a simple `ParseError` and a more complex `NetworkError` with multiple fields, automatically including a `OhnoCore` field. ```rust // Simple error without extra fields #[ohno::error] pub struct ParseError; // Error with multiple fields #[ohno::error] pub struct NetworkError { host: String, port: u16, } ``` -------------------------------- ### Disable Constructors: Manually implement constructors with #[no_constructors] Source: https://github.com/microsoft/oxidizer/blob/main/crates/ohno/README.md Shows how to disable the automatic generation of `new()` and `caused_by()` methods using the `#[no_constructors]` attribute. This allows for custom constructor logic to be implemented manually. ```rust use ohno::{Error, OhnoCore}; #[derive(Error)] #[no_constructors] struct CustomError { inner_error: OhnoCore, } impl CustomError { pub fn new(custom_logic: bool) -> Self { // Your custom constructor logic here Self { inner_error: OhnoCore::default() } } } ``` -------------------------------- ### Derive Macro: Implement standard error traits for MyError Source: https://github.com/microsoft/oxidizer/blob/main/crates/ohno/README.md Shows how to use the `#[derive(Error)]` macro on a struct containing `OhnoCore`. This automatically implements `std::error::Error`, `Display`, `Debug`, and `From` conversions, simplifying error type creation. ```rust use ohno::{OhnoCore, Error}; #[derive(Error)] pub struct MyError { inner_error: OhnoCore, } ```