### Justfile example Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md An example of a 'justfile' demonstrating how to define default commands, install tools, and clean build artifacts. ```just default: just --list install-tools: cargo install mdbook cargo install mdbook-yapp clean: doc-clean cargo clean doc-clean: rm -rf out ``` -------------------------------- ### Install and Verify Rustmax CLI Source: https://github.com/brson/rustmax/blob/master/book/src/cli.md Install the CLI via cargo and display the help menu to verify the installation. ```bash cargo install rustmax-cli rustmax --help ``` -------------------------------- ### Install basic-http-server Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Installs 'basic-http-server', a simple command-line tool for serving static files over HTTP. ```bash cargo install basic-http-server ``` -------------------------------- ### Install tokei Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Installs 'tokei', a fast tool for counting lines of code. ```bash cargo install tokei ``` -------------------------------- ### Install gist Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Installs 'gist', a command-line utility for uploading code snippets to GitHub Gist. ```bash cargo install gist ``` -------------------------------- ### Install jsonxf Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Installs 'jsonxf', a command-line tool for transforming and formatting JSON data. ```bash cargo install jsonxf ``` -------------------------------- ### Install jaq Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Installs 'jaq', a command-line JSON processor focused on correctness, speed, and simplicity, similar to jq. ```bash cargo install jaq ``` -------------------------------- ### Execute a build command with just Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Shows an example of running the 'build' recipe defined in a 'justfile'. ```bash $ just build Compiling rustmax-cli v0.0.5 (…/rustmax/crates/rustmax-cli) … ``` -------------------------------- ### Install Rust with rustup Source: https://github.com/brson/rustmax/blob/master/book/src/easy-mode-rust.md Installs Rust using the rustup tool. Run this in your shell and follow the on-screen instructions. ```shell curl -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Install cargo-clean-all Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Install the cargo-clean-all plugin to recursively clean all Cargo projects within a directory tree. ```bash cargo install cargo-clean-all ``` -------------------------------- ### Install sd Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Installs 'sd', an intuitive command-line tool for find and replace operations, serving as a modern alternative to 'sed'. ```bash cargo install sd ``` -------------------------------- ### Compile and Run Example Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/fetched/rust-and-csv-parsing/extracted.html Demonstrates how to compile a Rust program using Cargo and run it with a command-line argument and input redirection. This example shows filtering CSV data based on a population threshold. ```bash $ cargo build $ ./target/debug/csvtutor 100000 < uspop.csv ``` -------------------------------- ### Install just command runner Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Installs 'just', a command runner with make-like syntax for simplifying project-specific tasks. Place a 'justfile' in your project root. ```bash cargo install just ``` -------------------------------- ### Install mold linker via Rustmax Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Installs the mold linker using the rustmax tool, which automates configuration for faster Rust builds on Linux. ```bash rustmax install-tool mold ``` -------------------------------- ### Install fd-find Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Installs 'fd', a user-friendly and fast alternative to the 'find' command for recursive file searching. ```bash cargo install fd-find ``` -------------------------------- ### Install cargo-deny Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Install the cargo-deny plugin for linting dependencies, checking for security vulnerabilities and license compliance. ```bash cargo install cargo-deny ``` -------------------------------- ### Install cargo-license Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Install the cargo-license plugin to easily display the licenses of your project's dependencies. ```bash cargo install cargo-license ``` -------------------------------- ### Compile and Run Serde CSV Example Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/book/src/rust-and-csv-parsing.md Commands to compile and run the Rust CSV example using Serde. This demonstrates the build and execution process for a Serde-based CSV deserialization program. ```bash $ cargo build --release $ time ./target/release/csvtutor < worldcitiespop.csv 2176 ``` -------------------------------- ### C Storage Examples Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/book/src/rust-for-functional-programmers.md Examples of C variable declarations corresponding to different memory storage types. ```c static int i; ``` ```c int i; ``` ```c int *i = malloc(sizeof(int)); ``` ```c _Thread_local int i; ``` -------------------------------- ### Install clippy-control Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Installs clippy-control, a utility for temporarily managing Clippy linting rules from the command line. ```bash cargo install clippy-control ``` -------------------------------- ### Install bindgen-cli Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Install the bindgen-cli tool with cargo to automatically generate Rust FFI bindings for C libraries. ```bash cargo install bindgen-cli ``` -------------------------------- ### Install cargo-edit Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Install the cargo-edit plugin to gain extra cargo subcommands for editing Cargo.toml, such as managing dependencies. ```bash cargo install cargo-edit ``` -------------------------------- ### Compile and Run CSV Performance Example Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/book/src/rust-and-csv-parsing.md Commands to compile and run the Rust CSV performance optimization example using Cargo. This shows the typical workflow for building and executing Rust programs, including release builds for performance. ```bash $ cargo build --release $ time ./target/release/csvtutor < worldcitiespop.csv 2176 real 0m0.308s user 0m0.283s sys 0m0.023s ``` -------------------------------- ### Install mdbook Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Install mdbook using cargo to create modern online books from Markdown files. This is useful for project documentation. ```bash cargo install mdbook ``` -------------------------------- ### Run program output example Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/book/src/rust-and-csv-parsing.md Shows the output of the program when encountering invalid CSV data. ```text $ cat invalid header1,header2 foo,bar quux,baz,foobar $ ./target/debug/csvtutor < invalid StringRecord { position: Some(Position { byte: 16, line: 2, record: 1 }), fields: ["foo", "bar"] } error reading CSV from : CSV error: record 2 (line: 3, byte: 24): found record with 3 fields, but the previous record has 2 fields ``` -------------------------------- ### Build and Run csv-core Example Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/book/src/rust-and-csv-parsing.md Commands to compile and execute the Rust program that counts records using csv-core. ```Shell $ cargo build --release $ time ./target/release/csvtutor < worldcitiespop.csv 2176 real 0m0.572s user 0m0.513s sys 0m0.057s ``` -------------------------------- ### Install rustfmt Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Use this command to add the rustfmt component to your Rust toolchain for code formatting. ```bash rustup component add rustfmt ``` -------------------------------- ### Define Crate Topic Entry Source: https://github.com/brson/rustmax/blob/master/botdocs/topic-index-format.md Example TOML configuration for a crate topic. ```toml [topics.serde] name = "serde" aliases = ["serialization framework", "serialize deserialize"] category = "crate" tags = ["serialization", "derive"] brief = "Framework for serializing and deserializing Rust data structures" [[topics.serde.relations]] kind = "implements" target = "serialization" [[topics.serde.relations]] kind = "related" target = "serde-json" [[topics.serde.relations]] kind = "related" target = "toml" ``` -------------------------------- ### Define and Use Macros Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/fetched/rust-for-functional-programmers/extracted.html Examples of macro definitions using macro_rules!, including recursive and variadic macros. ```Rust macro_rules! pfor ( ($x:ident = $s:expr to $e:expr $body:expr) => (match $e { e => { let mut $x = $s; loop { $body; $x += 1; if $x > e { break; } } }}); ); // Example use: fn main() { pfor!(i = 0 to 10 { println!("{}", i); }); } ``` ```Rust macro_rules! pfor ( ($x:ident = $s:expr to $e:expr step $st:expr $body:expr) => (match $e,$st { e, st => { let mut $x = $s; loop { $body; $x += st; if $x > e { break; } } }}); ($x:ident = $s:expr to $e:expr $body:expr) => (pfor!($x = $s to $e step 1 $body)); ); // Example use: fn main() { pfor!(i = 0 to 10 step 2 { println!("{}", i); }); } ``` ```Rust macro_rules! printall ( ( $( $arg:expr ),* ) => ( $( println!("{}", $arg) );* ); ); // example use: fn main() { printall!("hello", 42, 3.14); } ``` -------------------------------- ### Initialize env_logger in Rust Source: https://github.com/brson/rustmax/blob/master/crates/rustmax/doc-src/crate-env_logger.md Initialize the logger at the start of your program. This setup reads the RUST_LOG environment variable to filter messages. ```rust use log::info; fn main() { env_logger::init(); info!("Starting application"); } ``` -------------------------------- ### Minimal Axum Server Setup Source: https://github.com/brson/rustmax/blob/master/crates/rustmax/doc-src/crate-axum.md Sets up a basic Axum server with two routes: one for a static "Hello, World!" message and another for a dynamic greeting that extracts a name from the URL path. Requires tokio for async runtime and axum for the web framework. ```rust use axum::{Router, routing::get, extract::Path}; use tokio::net::TcpListener; async fn hello() -> &'static str { "Hello, World!" } async fn greet(Path(name): Path) -> String { format!("Hello, {name}!") } #[tokio::main] async fn main() { let app = Router::new() .route("/", get(hello)) .route("/greet/{name}", get(greet)); let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); } ``` -------------------------------- ### List available recipes with just Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Demonstrates how to list all available commands defined in a 'justfile' using the '--list' flag. ```bash $ just --list Available recipes: build check clean default doc-book doc-build doc-clean doc-crates install-tools lint maint-audit maint-duplicates maint-lock-minimum-versions # useful prior to running `cargo audit` maint-outdated maint-upgrade prebuild publish publish-dry replace-version old new test test-min-version-build ``` -------------------------------- ### Build and Run Basic Project Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/book/src/rust-and-csv-parsing.md Build the Rust project using Cargo and run the default binary. ```bash cargo build ./target/debug/csvtutor ``` -------------------------------- ### Install cargo-generate Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Installs cargo-generate, a tool for creating new Rust projects from templates. ```bash cargo install cargo-generate ``` -------------------------------- ### Rustmax Prelude and Extras Source: https://context7.com/brson/rustmax/llms.txt Demonstrates the usage of `rustmax`'s prelude for common imports and the extras module for convenience utilities like logging initialization, default value creation, and a `bug!` macro. Ensure `rustmax` is added as a dependency. ```rust use rustmax as rmx; // The prelude includes common imports use rmx::prelude::*; // Extras module provides convenience functions use rmx::extras::{default, init, AnyResult, AnyError}; // Initialize logging (env_logger) rmx::extras::init(); // Create default values easily let vec: Vec = default(); // The bug! macro for unexpected cases // rmx::bug!("this should never happen"); ``` -------------------------------- ### Initialize UI and Control Strip Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/fetched/things-rust-shipped-without/raw.html Initializes the Foundation framework and fetches the control strip via JSON if it does not exist. ```javascript jQuery(function(jQ){ if (jQ("#lj\_controlstrip").length == 0) { jQ.getJSON("/graydon2/__rpc_controlstrip?user=graydon2&host=graydon2.dreamwidth.org&uri=/218040.html&args=&view=entry", {}, function(data) { jQ("
").html(data.control\_strip).prependTo("body"); } ); } }) $(document).foundation(); ``` -------------------------------- ### Run Default Rust Project Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/fetched/rust-and-csv-parsing/raw.html Executes the compiled binary. At this stage, it will print 'Hello, world!'. ```bash ./target/debug/csvtutor ``` -------------------------------- ### Install cargo-audit Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Install the cargo-audit plugin to audit Cargo.lock files for known security vulnerabilities in your dependencies. ```bash cargo install cargo-audit ``` -------------------------------- ### List all posts using rustmax-anthology CLI Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/README.md Lists all curated posts by utilizing the rustmax-anthology CLI. Ensure the CLI is built before execution. ```bash ./target/debug/anthology --metadata-dir crates/rustmax-anthology/metadata \ --fetched-dir crates/rustmax-anthology/fetched \ list ``` -------------------------------- ### Create and Use Temporary Directory Source: https://github.com/brson/rustmax/blob/master/crates/rustmax/doc-src/crate-tempfile.md Demonstrates creating a temporary directory with a custom prefix, writing a file into it, and verifying its existence. The directory and its contents are automatically removed when the `TempDir` object is dropped. ```rust use tempfile::TempDir; use std::fs::File; use std::io::Write; let dir = TempDir::with_prefix("myapp-tests")?; // Create files inside the temporary directory let file_path = dir.path().join("test.txt"); let mut file = File::create(&file_path)?; writeln!(file, "temporary data")?; assert!(file_path.exists()); // Directory and all contents are deleted when dropped drop(dir); assert!(!file_path.exists()); # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### Install ripgrep Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Installs ripgrep, a fast, line-oriented search tool that recursively searches directories for regex patterns and respects .gitignore. ```bash cargo install ripgrep ``` -------------------------------- ### Query System Configuration with libc Source: https://github.com/brson/rustmax/blob/master/crates/rustmax/doc-src/crate-libc.md Use `libc::sysconf` to query system configuration like page size, and `libc::getuid` and `libc::getpid` to get user and process IDs. These operations are unsafe and require careful handling. ```rust let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; assert!(page_size > 0); let uid = unsafe { libc::getuid() }; let pid = unsafe { libc::getpid() }; assert!(pid > 0); ``` -------------------------------- ### Build mdbook presentation with rustmax-anthology CLI Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/README.md Builds the mdbook presentation for the curated posts using the rustmax-anthology CLI. This generates a navigable web book. ```bash ./target/debug/anthology --metadata-dir crates/rustmax-anthology/metadata \ --fetched-dir crates/rustmax-anthology/fetched \ --book-dir crates/rustmax-anthology/book \ build ``` -------------------------------- ### Make a Simple GET Request (Blocking) Source: https://github.com/brson/rustmax/blob/master/crates/rustmax/doc-src/crate-reqwest.md Use the blocking API for simple GET requests when asynchronous execution is not required. Ensure the request and text reading operations are handled. ```rust use reqwest::blocking; let body = blocking::get("https://httpbin.org/get") .expect("request failed") .text() .expect("failed to read body"); println!("Response: {}", body); ``` -------------------------------- ### Install Dust CLI Tool Source: https://github.com/brson/rustmax/blob/master/book/src/tools.md Install the 'dust' command-line tool using Cargo, Rust's package manager. This command is used to add the utility to your system for subsequent use. ```bash cargo install du-dust ``` -------------------------------- ### Rustmax CLI Usage and Commands Source: https://github.com/brson/rustmax/blob/master/book/src/cli.md Displays the full list of available commands and options for the rustmax utility. ```text Usage: rustmax Commands: list-tools List all available tools install-tools Install all tools update-tools Update all tools uninstall-tools Uninstall all tools tools-status Show status of all tools install-tool Install a specific tool update-tool Update a specific tool uninstall-tool Uninstall a specific tool tool-status Show status of a specific tool list-library List books in the library build-library Build the library or a specific book refresh-library Refresh the library or a specific book rmxbook Build a book using the rmxbook renderer new-project Create a new project from template write-fmt-config Write rustfmt.toml configuration file write-cargo-deny-config Write deny.toml configuration file write-clippy-control-config Write clippy-control.toml configuration file run-all-checks Run all code quality checks help Print this message or the help of the given subcommand(s) Options: -h, --help Print help -V, --version Print version ``` -------------------------------- ### Create New Rustmax Project Source: https://github.com/brson/rustmax/blob/master/src/posts/20260326A-rustmax-0.0.9.md Alternative command to create a new project with the rustmax template. ```bash rustmax new-project ``` -------------------------------- ### CLI Application with Subcommands using Derive API Source: https://github.com/brson/rustmax/blob/master/crates/rustmax/doc-src/crate-clap.md This example demonstrates how to structure a CLI application with subcommands using Clap's derive API. It includes a file management tool with 'create' and 'list' subcommands, each with its own arguments. ```rust use clap::{Parser, Subcommand}; #[derive(Parser)] #[command(version, about = "File management tool")] struct Cli { #[command(subcommand)] command: Commands, } #[derive(Subcommand)] enum Commands { /// Create a new file Create { /// File name to create name: String, }, /// List files List { /// Show hidden files #[arg(short, long)] all: bool, }, } fn main() { // Parse from custom args for testing let cli = Cli::parse_from(&["prog", "create", "test.txt"]); match cli.command { Commands::Create { name } => { println!("Creating file: {}", name); } Commands::List { all } => { if all { println!("Listing all files including hidden"); } else { println!("Listing visible files"); } } } } ``` -------------------------------- ### Make an Async GET Request Source: https://github.com/brson/rustmax/blob/master/crates/rustmax/doc-src/crate-reqwest.md Utilize the asynchronous API with a Client for making GET requests. This requires an async runtime like Tokio. Handle potential errors during the request and response processing. ```rust use reqwest::Client; #[tokio::main] async fn main() -> Result<(), reqwest::Error> { let client = Client::new(); let resp = client.get("https://httpbin.org/get") .send() .await?; println!("Status: {}", resp.status()); println!("Body: {}", resp.text().await?); Ok(()) } ``` -------------------------------- ### Initialize a Rustmax project Source: https://github.com/brson/rustmax/blob/master/book/src/how-do-i.md Use the cargo generate command to scaffold a new project from the Rustmax template. ```bash cargo generate brson/rustmax ``` -------------------------------- ### Rust Immutable and Mutable Reference Example Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/fetched/rust-ownership-hard-way/raw.html Demonstrates the behavior of immutable and mutable references in Rust, illustrating how multiple immutable references can coexist, while mutable references have stricter scoping rules. This example highlights the concept of reference reborrowing. ```rust fn take_ref(_: &T) { } fn take_mut(_: &mut T) { } fn main() { let mut a = 6; { let a_ref = &a; take_ref(a_ref); // Naturally this will work, for &T is Copy. take_ref(a_ref); } { let a_mut = &mut a; take_mut(a_mut); // Surely a_mut should have been consumed by the by the line above? take_mut(a_mut); } } ``` -------------------------------- ### Build and Inspect HTTP Request and Response Source: https://github.com/brson/rustmax/blob/master/crates/rustmax/doc-src/crate-http.md Demonstrates how to construct an HTTP request with a method, URI, and headers, and then inspect its components. Also shows building an HTTP response with a status code and headers. ```rust use http::{Request, Method, StatusCode, Response}; let req = Request::builder() .method(Method::GET) .uri("https://example.com/path?q=1") .header("Accept", "application/json") .body(()) .unwrap(); assert_eq!(req.method(), Method::GET); assert_eq!(req.uri().path(), "/path"); assert_eq!(req.uri().query(), Some("q=1")); assert_eq!( req.headers()["Accept"], "application/json", ); let resp = Response::builder() .status(StatusCode::NOT_FOUND) .header("Content-Type", "text/plain") .body(()) .unwrap(); assert_eq!(resp.status(), StatusCode::NOT_FOUND); assert_eq!(resp.status().as_u16(), 404); ``` -------------------------------- ### Create New Cargo Project Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/book/src/rust-and-csv-parsing.md Use Cargo to create a new binary project. Navigate into the project directory. ```bash cargo new --bin csvtutor cd csvtutor ``` -------------------------------- ### Pointer-based equality comparison Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/fetched/rewriting-enjarify-in-rust/content.md Example of comparing pointers to determine if two objects are the same instance. ```rust fn ptr(p: Option<&Rc>>) -> *const CopySet { match p { Some(p) => p.deref().borrow().deref() as *const _, None => null(), }}// ... let s_set = ptr(self.0.get(&src)); let d_set = ptr(self.0.get(&dest)); if !s_set.is_null() && s_set == d_set { // src and dest are copies of same value, so we can remove return false; } ``` -------------------------------- ### Create and configure a TCP listener Source: https://github.com/brson/rustmax/blob/master/crates/rustmax/doc-src/crate-socket2.md Demonstrates creating a TCP socket, setting SO_REUSEADDR, binding to an address, and converting it into a standard library TcpListener. ```rust use socket2::{Socket, Domain, Type, Protocol, SockAddr}; use std::net::SocketAddr; // Create a TCP socket. let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP))?; // Set SO_REUSEADDR so the port can be reused immediately after close. socket.set_reuse_address(true)?; // Bind to a local address. let address: SocketAddr = "127.0.0.1:0".parse().unwrap(); socket.bind(&SockAddr::from(address))?; // Start listening. socket.listen(128)?; // Convert to a std TcpListener for use with normal APIs. let listener: std::net::TcpListener = socket.into(); let local_addr = listener.local_addr()?; assert_eq!(local_addr.ip(), std::net::Ipv4Addr::LOCALHOST); # Ok::<(), std::io::Error>(()) ``` -------------------------------- ### List all posts using just command Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/README.md Executes the 'anthology-list' command via 'just' to list all curated posts. This command builds automatically if needed. ```bash just anthology-list ``` -------------------------------- ### Integer Literals Source: https://github.com/brson/rustmax/blob/master/crates/rustmax-anthology/fetched/rust-for-functional-programmers/raw.html Examples of Rust integer literals with various type suffixes and type annotations. ```rust 123 :: Int ``` ```rust 123i32 ``` ```rust 123l ``` ```rust 123 :: Int32 ``` ```rust 123i64 ``` ```rust 123L ``` ```rust 123 :: Int64 ``` ```rust 123u ``` ```rust 123 :: Word ```