### ARM Switch Case Example Setup Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Sets up constants for Linux system calls (exit, write, read) and their parameters for ARM assembly. ```s // ./examples/aarch64/switch_case.s // GNU Assembler, ARM syntax, aarch64 Linux .data // exit(code) .equ SYS_EXIT, 93 .equ EXIT_CODE, 0 // write(fd, buf_adr, buf_len) .equ SYS_WRITE, 64 .equ STDOUT, 1 // read(fd, buf_adr, buf_len) .equ SYS_READ, 63 .equ STDIN, 0 ``` -------------------------------- ### Running x86_64 Examples with 'just carx' Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Demonstrates how to compile and run x86_64 assembly examples using the 'just carx' command. Shows input and output for the case switching example. ```shell # reads char from stdin, switches its case, prints to stdout > just carx switch_case a A Exit code: 0 > just carx switch_case A a Exit code: 0 ``` -------------------------------- ### Example .env file Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Example content for the .env file to configure environment variables. ```bash # .env LOG_LEVEL=INFO LOG_FILE=server.log DATABASE_URL=postgres://postgres@localhost:5432/postgres ``` -------------------------------- ### Install sqlx-cli Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Installs the sqlx-cli tool globally. Ensure you have Rust and Cargo installed. ```bash cargo install sqlx-cli ``` -------------------------------- ### Install Development Libraries (Ubuntu) Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Installs PostgreSQL development libraries on Ubuntu using apt-get, required for sqlx-cli if facing installation issues. ```bash # ubuntu apt-get install pkg-config libssl-dev postgresql libpq-dev ``` -------------------------------- ### x86_64 Assembly: Example with Control Flow Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md A practical example demonstrating the use of 'mov', 'add', 'cmp', and conditional jumps for basic program logic. ```assembly mov rax, 5 # store 5 in rax mov r12, 10 # store 10 in r12 add rax, r12 # rax <- rax + r12 = 15 cmp rax, r12 # set flags in rflags jge RAX_IS_LARGER # read flags in rflags, jump to RAX_IS_LARGER R12_IS_LARGER: # some instructions jmp END RAX_IS_LARGER: # some other instructions END: # more instructions ``` -------------------------------- ### Install 100 Exercises to Learn Rust Runner Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/learning-rust-in-2024.md Installs the workshop-runner tool for the '100 Exercises to Learn Rust' project. This tool is used to verify your solutions to the exercises. ```sh cargo install --locked workshop-runner ``` -------------------------------- ### Install sqlx-cli for PostgreSQL Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Installs sqlx-cli with only PostgreSQL support, useful if you only intend to use PostgreSQL. ```bash cargo install sqlx-cli --no-default-features --features postgres ``` -------------------------------- ### Main Function Setup Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/chat-server.md Initializes the Rooms manager and spawns a task to handle user connections within the main function. ```rust #[tokio::main] async fn main() -> anyhow::Result<()> { // ... let rooms = Rooms::new(); // ... tokio::spawn(handle_user(tcp, names.clone(), rooms.clone())); } ``` -------------------------------- ### Compile and Run WebAssembly Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Command to compile and run a WebAssembly example using the 'just' tool. ```shell just carw {{name}} ``` -------------------------------- ### Actix-web GET Request Handlers Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Example GET request handlers for fetching boards, board summaries, and cards, including error mapping and JSON responses. ```rust use actix_web::web::{Data, Json, Path}; use actix_web::error::InternalError; use actix_web::http::StatusCode; use crate::StdErr; use crate::db::Db; use crate::models::{Board, Card, BoardSummary}; // convenience functions fn to_internal_error(e: StdErr) -> InternalError { InternalError::new(e, StatusCode::INTERNAL_SERVER_ERROR) } // GET requests #[actix_web::get("/boards")] async fn boards(db: Data) -> Result>, InternalError> { db.boards() .await .map(Json) .map_err(to_internal_error) } #[actix_web::get("/boards/{board_id}/summary")] async fn board_summary( db: Data, Path(board_id): Path, ) -> Result, InternalError> { db.board_summary(board_id) .await .map(Json) .map_err(to_internal_error) } #[actix_web::get("/boards/{board_id}/cards")] async fn cards( db: Data, Path(board_id): Path, ) -> Result>, InternalError> { db.cards(board_id) .await .map(Json) .map_err(to_internal_error) } ``` -------------------------------- ### x86_64 Write Syscall Example Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Demonstrates the x86_64 write syscall to output data to standard output. It sets up the necessary registers for the syscall. ```assembly # syscall returns number of bytes read in rax mov rax, 1 # syscall number for write(fd, buf_adr, buf_len) mov rdi, 1 # file descriptor for stdout mov rsi, 1234 # memory address to some buffer mov rdx, 1 # buffer's length in bytes syscall # make system call # syscall returns number of bytes written in rax ``` -------------------------------- ### Chat Server Client Interaction Example Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/chat-server.md Demonstrates a typical client interaction with the chat server, including joining rooms and sending messages. This is a console output example. ```console $ just chat Server commands /help - prints this message /name {name} - change name /join {room} - joins room /quit - quits server You are ElasticBonobo ElasticBonobo joined main BlondCyclops joined main > /join pizza # new command ElasticBonobo joined pizza BlondCyclops joined pizza > let's have a pizza party ElasticBonobo: let's have a pizza party BlondCyclops: 🍕🥳 ``` -------------------------------- ### Install diesel-cli Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Installs the diesel-cli command-line tool using cargo. Ensure Rust and Cargo are installed and configured. ```bash cargo install diesel_cli ``` -------------------------------- ### WebAssembly Function with Local Variable (With Labels) Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Similar to the previous example, but uses labels for parameters and local variables, enhancing code clarity. ```wat (func $add_and_double (param $first i32) (param $second i32) (result i32) (local $local i32) local.get $first local.get $second i32.add local.tee $local local.get $local i32.add ) ``` -------------------------------- ### Example Log Output Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Demonstrates the expected output when running the application with the default INFO log level. This shows how log messages are formatted and displayed. ```bash $ cargo run [08:36:30][kanban::logger][INFO] INFO output enabled [08:36:30][kanban::logger][WARN] WARN output enabled [08:36:30][kanban::logger][ERROR] ERROR output enabled ``` -------------------------------- ### Install Rustlings Exercise Tool Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/learning-rust-in-2024.md Installs the rustlings command-line tool, which provides a collection of small Rust exercises to help you learn the language. ```sh cargo install rustlings ``` -------------------------------- ### Install Diesel CLI for PostgreSQL Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Installs the Diesel command-line interface with support specifically for PostgreSQL. Ensure PostgreSQL and libpq-dev are installed first. ```bash cargo install diesel_cli --no-default-features --features postgres ``` -------------------------------- ### Brainfuck 'Hello World!' Program Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md The standard 'Hello World!' program written in Brainfuck. This serves as a basic example of Brainfuck syntax and program structure. ```bf ++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>. ``` -------------------------------- ### Basic Diesel Setup and Connection Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Sets up the necessary imports for Diesel and establishes a connection to a PostgreSQL database using environment variables. This is a prerequisite for performing database operations. ```rust use diesel::prelude::*; use diesel::PgConnection; // generated by diesel-cli from DB schema use crate::schema::boards; // handwritten by us use crate::models::Board; // example of connecting to PostgreSQL fn get_connection() -> PgConnection { dotenv::dotenv().unwrap(); let db_url = env::var("DATABASE_URL").unwrap(); PgConnection::establish(&db_url).unwrap() } ``` -------------------------------- ### Sizedness Examples in Rust Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/sizedness-in-rust.md Demonstrates the compile-time size determination for various sized and unsized types in Rust using `std::mem::size_of`. ```rust use std::mem::size_of; fn main() { // primitives assert_eq!(4, size_of::()); assert_eq!(8, size_of::()); // tuples assert_eq!(8, size_of::<(i32, i32)>()); // arrays assert_eq!(0, size_of::<[i32; 0]>()); assert_eq!(12, size_of::<[i32; 3]>()); struct Point { x: i32, y: i32, } // structs assert_eq!(8, size_of::()); // enums assert_eq!(8, size_of::>()); // get pointer width, will be // 4 bytes wide on 32-bit targets or // 8 bytes wide on 64-bit targets const WIDTH: usize = size_of::<&()>(); // pointers to sized types are 1 width assert_eq!(WIDTH, size_of::<&i32>()); assert_eq!(WIDTH, size_of::<&mut i32>()); assert_eq!(WIDTH, size_of::>()); assert_eq!(WIDTH, size_of:: i32>()); const DOUBLE_WIDTH: usize = 2 * WIDTH; // unsized struct struct Unsized { unsized_field: [i32], } // pointers to unsized types are 2 widths assert_eq!(DOUBLE_WIDTH, size_of::<&str>()); // slice assert_eq!(DOUBLE_WIDTH, size_of::<&[i32]>()); // slice assert_eq!(DOUBLE_WIDTH, size_of::<&dyn ToString>()); // trait object assert_eq!(DOUBLE_WIDTH, size_of::>()); // trait object assert_eq!(DOUBLE_WIDTH, size_of::<&Unsized>()); // user-defined unsized type // unsized types size_of::(); // compile error size_of::<[i32]>(); // compile error size_of::(); // compile error size_of::(); // compile error } ``` -------------------------------- ### Structured Control Flow: Loop Branching Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Shows how to use 'loop' with 'br' and 'br_if' instructions for creating loops that branch back to the start of the loop. ```wat ;; branching within loops loop br 0 ;; unconditionally branches to start of loop br_if 0 ;; conditionally branches to start of loop end ``` -------------------------------- ### Output of Tokio Select Example Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/chat-server.md This output shows the result of running the `tokio::select!` example. It demonstrates that only the first `count_to` future to complete (in this case, `count_to(3)`) finishes its execution and prints its message, while the other is effectively cancelled. ```text start counting 1 1 2 2 3 3 counted to 3 stop counting ``` -------------------------------- ### WebAssembly Module with Exports Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md An example of a WebAssembly module that exports its memory segment and a function named '_start'. Exports make module components accessible from outside. ```wat (module ;; zero-initialized 65536 byte linear memory segment (memory 1) (func $_start ;; instructions ) ;; export our only defined memory segment by index as "memory" (export "memory" (memory 0)) ;; export our $_start function as "_start" (export "_start" (func $_start)) ) ``` -------------------------------- ### Connect to PostgreSQL Pool in Rust Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Example of establishing a connection pool to a PostgreSQL database using sqlx and dotenv for configuration. Demonstrates passing the pool directly to queries. ```rust use sqlx::{Connection, PgConnection, Pool, Postgres}; use sqlx::postgres::PgPoolOptions; async fn get_pool() -> Pool { dotenv::dotenv().unwrap(); let db_url = std::env::var("DATABASE_URL").unwrap(); PgPoolOptions::new().connect(&db_url).await.unwrap() } async fn use_pool(pool: &Pool) { sqlx::query_as::<_,(String,)>("SELECT version()") .fetch_one(pool) .await .unwrap(); } ``` -------------------------------- ### Manual Wasm Bindings Example Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/rust-in-non-rust-servers.md Illustrates the low-level memory buffer manipulation for Wasm exports, similar to what libraries like wasm-bindgen generate. ```rust qrWasmInstance.exports.memory.buffer, outputMemOffset, wroteBytes, ); }; ``` -------------------------------- ### Run Brainfuck Programs Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Examples of running compiled Brainfuck programs for common tasks like printing 'Hello World!', Fibonacci sequence, and ROT13 encryption. ```sh # prints "Hello world!" > just carbw hello_world Hello World! # prints fibonacci numbers under 100 > just carbw fibonacci 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 # encrypts lines from stdin using rot13 cipher > just carbw rot13 unencrypted text harapelcgrq grkg ``` -------------------------------- ### Chat Server Client Interaction with /rooms Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/chat-server.md Demonstrates a client using the `/rooms` command to see available chat rooms and then joining one. This is a console output example. ```console $ just chat Server commands /help - prints this message /name {name} - change name /rooms - list rooms /join {room} - joins room /quit - quits server You are SilentYeti SilentYeti joined main > /rooms # new command Rooms - pizza (2), main (1) > /join pizza SilentYeti joined pizza > can i be part of this pizza party? 🥺 SilentYeti: can i be part of this pizza party? 🥺 BulkyApe: of course ❤️ AmazingDragon: 🔥🔥🔥 ``` -------------------------------- ### Async DB Operations: Inserting Data with sqlx Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Inserts a new user into the database using sqlx. Requires sqlx setup with a database pool. ```rust use sqlx::PgPool; // ... inside an async function ... // let user = sqlx::query("INSERT INTO users (username) VALUES ($1)") // .bind(new_user.username) // .execute(pool) // .await?; ``` -------------------------------- ### Generate Database Migration Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Creates a new migration file pair (up.sql and down.sql) for schema changes. This example generates a migration to create a 'boards' table. ```bash diesel migration generate create_boards ``` -------------------------------- ### Storing Data to Memory in WAT Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Demonstrates instructions for storing values from the stack into memory addresses also provided on the stack. Includes an example of storing a 4-byte value. ```wat ;; all instructions below pop a memory address & value from the stack ;; and then store that value at that memory address i32.store8 ;; stores byte at memory address i32.store16 ;; stores 2 bytes at memory address i32.store ;; stores 4 bytes at memory address ;; example i32.const 1000 ;; push memory address 1000 onto stack i32.const 123 ;; push value 123 onto stack i32.store ;; stores 123 at memory address 1000 ``` -------------------------------- ### Setup Tracing Logging to Stdout Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/chat-server.md Configures the 'tracing' crate to log messages to standard output. Customize logging levels using the RUST_LOG environment variable. ```rust use std::io; use tracing_subscriber::{fmt, EnvFilter, layer::SubscriberExt}; fn setup_logging() { let subscriber = tracing_subscriber::registry() .with(EnvFilter::from_default_env()) .with(fmt::Layer::new() .without_time() .compact() .with_ansi(true) .with_writer(io::stdout) ); tracing::subscriber::set_global_default(subscriber) .expect("Unable to set a global subscriber"); } ``` -------------------------------- ### Define Basic Routes in Rocket Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Use Rocket's procedural macros to define simple GET routes for your API. Each macro corresponds to an HTTP method and a path. ```rust #[rocket::get("/")] fn index() -> &'static str { "I'm the index route!" } #[rocket::get("/nested/route")] fn index() -> &'static str { "I'm some nested route!" } ``` -------------------------------- ### Rocket Hello World Example Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md A basic "Hello, world!" endpoint using the Rocket framework. This snippet includes the necessary imports and the main function to launch the server. ```rust // required for rocket macros to work #![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate diesel; mod db; mod logger; mod models; mod routes; mod schema; type StdErr = Box; #[rocket::get("/")] fn hello_world() -> &'static str { "Hello, world!" } fn main() -> Result<(), StdErr> { dotenv::dotenv()?; logger::init()?; rocket::ignite() .mount("/", rocket::routes![hello_world]) .launch(); Ok(()) } ``` -------------------------------- ### WebAssembly Function Call Example Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Shows how to call defined functions by pushing arguments onto the stack and using the 'call' instruction. 'drop' is used to discard unwanted return values. ```wat i32.const 4 i32.const 5 call $my_add ;; pops 4 & 5 off stack & pushes 9 onto stack drop ;; discard result i32.const 4 i32.const 5 call $add_and_double ;; pops 4 & 5 off stack & pushes 18 onto stack ``` -------------------------------- ### Initialize Diesel Project Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Sets up a new Diesel project, creating the necessary 'migrations' directory and configuring the database connection via the DATABASE_URL environment variable. ```bash diesel setup ``` -------------------------------- ### Install PostgreSQL Development Libraries Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Installs PostgreSQL development libraries on macOS using Homebrew, required for diesel-cli to function correctly with PostgreSQL. ```bash # macOS brew install postgresql ``` -------------------------------- ### x86_64 Exit Syscall Example Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md A minimal x86_64 program that exits with a specified code using the exit syscall. This is a foundational example for program termination. ```assembly # ./examples/x86_64/exit.s # GNU Assembler, Intel syntax, x86_64 Linux .data .equ SYS_EXIT, 60 .equ EXIT_CODE, 0 .text .global _start _start: # exit(code) mov rax, SYS_EXIT mov rdi, EXIT_CODE syscall ``` -------------------------------- ### Example Usage of Rust QR CLI Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/rust-in-non-rust-servers.md Demonstrates how to execute the compiled Rust QR code CLI tool from the command line, redirecting its output to a PNG file. This shows the direct usage of the compiled binary. ```bash qr-cli https://youtu.be/cE0wfjsybIQ?t=74 > crab-rave.png ``` -------------------------------- ### Install Specific Nightly Rust Compiler Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md This command installs the `1.53.0-nightly` Rust compiler, which is required by Rocket v0.4 due to its reliance on certain nightly features. ```bash # install rustc 1.53.0-nightly (07e0e2ec2 2021-03-24) rustup install nightly-2021-03-24 ``` -------------------------------- ### Get Board Summary Route Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Defines the GET /boards/{board_id}/summary endpoint to retrieve a summary of a specific board. Requires authentication and returns the board summary. ```rust #[actix_web::get("/boards/{board_id}/summary")] async fn board_summary( db: Data, Path(board_id): Path, _t: Token, ) -> Result, InternalError> { db.board_summary(board_id) .await .map(Json) .map_err(to_internal_error) } ``` -------------------------------- ### WebAssembly _start Function Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md This WebAssembly function serves as the entry point, setting up the exit code for the process. ```WebAssembly (module ;; drop error_num (assume success) ;; $proc_exit(0) i32.const 0 call $proc_exit ) ;; export "memory" & "_start" to runtime (export "memory" (memory 0)) (export "_start" (func $_start)) ``` -------------------------------- ### Async HTTP Routing: GET Requests with actix-web Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Defines an actix-web route for handling GET requests to retrieve a user by ID. Demonstrates async handlers and state management. ```rust use actix_web::{get, web, App, HttpServer, Responder}; use sqlx::PgPool; #[get("/users/{id}")] async fn get_user(pool: web::Data, id: web::Path) -> impl Responder { let user_id = id.into_inner(); // ... database query logic using pool and user_id ... web::Json(format!("User with id {}", user_id)) } ``` -------------------------------- ### Sync HTTP Routing: GET Requests with Rocket Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Defines a Rocket route for handling GET requests to retrieve a user by ID. Demonstrates basic routing and parameter extraction. ```rust #[macro_use] extern crate rocket; use rocket::State; use rocket_sync_db_pools::database; #[database("my_db")] struct MyDb(diesel::PgConnection); #[get("/users/")] fn get_user(conn: MyDb, id: i32) -> Option { // ... database query logic using conn and id ... Some(format!("User with id {}", id)) } ``` -------------------------------- ### LLVM IR Load and Store Instructions Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Demonstrates the basic 'load' and 'store' instructions for reading from and writing to memory in LLVM IR. An example shows atomically loading, modifying, and storing a byte value. ```ll ; load %val = load , * %ptr ; store store , * %ptr ; example ; assume %byte is some i8* ; below we add 1 to the value at %byte %b.0 = load i8, i8* %byte %b.1 = add i8 %b.0, 1 store i8 %b.1, i8* %byte ``` -------------------------------- ### Basic main.rs Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Initial main.rs file for the project. ```rust // src/main.rs fn main() { println!("Hello, world!"); } ``` -------------------------------- ### Brainfuck Nested Loop Start to x86 Assembly Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Illustrates the x86_64 assembly translation for a nested Brainfuck loop start command ('[['). It uses conditional jumps and specific label naming conventions. ```assembly # loops # [[ cmpb [r12], 0 je LOOP_END_1 LOOP_START_0: ``` -------------------------------- ### Rocket GET Request Handlers for Boards and Cards Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Implements GET request handlers for retrieving boards, board summaries, and cards. These handlers access the managed `Db` state and return JSON responses. ```rust use rocket::State; use rocket_contrib::json::Json; use crate::StdErr; use crate::db::Db; use crate::models::{Board, Card, BoardSummary}; // GET requests #[rocket::get("/boards")] fn boards(db: State) -> Result>, StdErr> { db.boards().map(Json) } #[rocket::get("/boards//summary")] fn board_summary(db: State, board_id: i64) -> Result, StdErr> { db.board_summary(board_id).map(Json) } #[rocket::get("/boards//cards")] fn cards(db: State, board_id: i64) -> Result>, StdErr> { db.cards(board_id).map(Json) } ``` -------------------------------- ### Basic HTTP Server with actix-web Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md This Rust code demonstrates a minimal "Hello, world!" HTTP server using actix-web. It sets up a basic route for the root path and starts the server on port 8000. The main function is made asynchronous and uses the `actix_web::main` macro. ```diff mod db; mod logger; mod models; type StdErr = Box; +#[actix_web::get("/")] +async fn hello_world() -> &'static str { + "Hello, world!" +} +#[actix_web::main] -fn main() -> Result<(), StdErr> { +async fn main() -> Result<(), StdErr> { dotenv::dotenv().ok(); logger::init()?; + actix_web::HttpServer::new(move || actix_web::App::new().service(hello_world)) + .bind(("127.0.0.1", 8000))? + .run() + .await?; Ok(()) } ``` -------------------------------- ### GET Requests Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Endpoints for retrieving board and card information. ```APIDOC ## GET /boards ### Description Retrieves a list of all boards. ### Method GET ### Endpoint /boards ### Response #### Success Response (200) - **boards** (array) - A list of board objects. #### Response Example { "example": "[{"id": 1, "name": "Board 1"}, {"id": 2, "name": "Board 2"}]" } ``` ```APIDOC ## GET /boards//summary ### Description Retrieves a summary of a specific board. ### Method GET ### Endpoint /boards//summary ### Parameters #### Path Parameters - **board_id** (i64) - Required - The ID of the board to retrieve the summary for. ### Response #### Success Response (200) - **board_summary** (object) - An object containing the board's summary. #### Response Example { "example": "{"board_id": 1, "name": "Board 1", "card_count": 5}" } ``` ```APIDOC ## GET /boards//cards ### Description Retrieves a list of cards for a specific board. ### Method GET ### Endpoint /boards//cards ### Parameters #### Path Parameters - **board_id** (i64) - Required - The ID of the board whose cards to retrieve. ### Response #### Success Response (200) - **cards** (array) - A list of card objects belonging to the specified board. #### Response Example { "example": "[{"id": 1, "board_id": 1, "title": "Card 1", "content": "Content 1"}, {"id": 2, "board_id": 1, "title": "Card 2", "content": "Content 2"}]" } ``` -------------------------------- ### Run Hello World in Brainfuck Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Executes a Brainfuck program that prints 'Hello World!'. ```Brainfuck > just carbl hello_world ``` -------------------------------- ### Iterating Over Path Parts Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/tour-of-rusts-standard-library-traits.md Example showing how `Path` types in Rust can be iterated over to access their individual components. ```rust use std::path::Path; fn paths_can_be_iterated(path: &Path) { for part in path { // iterate over parts of a path } } ``` -------------------------------- ### BufWriter Drop Implementation Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/tour-of-rusts-standard-library-traits.md Example of BufWriter implementing the Drop trait to ensure its buffer is flushed before being destroyed. ```rust impl Drop for BufWriter { fn drop(&mut self) { self.flush_buf(); } } ``` -------------------------------- ### Loading Data from Memory in WAT Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Shows various instructions for loading data of different sizes (byte, word, dword) from memory addresses on the stack into the stack. Includes an example of loading a 4-byte value. ```wat ;; all instructions below pop a memory address from the stack ;; then push the i32 value at that memory address onto the stack i32.load8_u ;; loads unsigned byte value from memory i32.load8_s ;; loads signed byte value from memory i32.load16_u ;; loads unsigned 2-byte value from memory i32.load16_s ;; loads signed 2-byte value from memory i32.load ;; loads 4-byte value from memory ;; example i32.const 1000 ;; push memory address 1000 onto stack i32.load ;; loads 4-byte value from memory address 1000 ;; loaded result pushed onto stack ``` -------------------------------- ### Using assert_eq! with PartialEq and Debug Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/tour-of-rusts-standard-library-traits.md Demonstrates how to use the `assert_eq!` macro with types that implement both `PartialEq` and `Debug`. Also shows how to compare collections of `PartialEq` types. ```rust #[derive(PartialEq, Debug)] struct Point { x: i32, y: i32, } fn example_assert(p1: Point, p2: Point) { assert_eq!(p1, p2); } fn example_compare_collections(vec1: Vec, vec2: Vec) { // if T: PartialEq this now works! if vec1 == vec2 { // some code } else { // other code } } ``` -------------------------------- ### Range Struct Definition Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/tour-of-rusts-standard-library-traits.md Defines a Range struct with start and end points, intended to implement an Iterator. ```rust struct Range { start: usize, end: usize, } impl Iterator for Range { type Item = usize; fn next(&mut self) -> Option { let current = self.start; self.start += 1; if current < self.end { Some(current) } else { None } } } ``` -------------------------------- ### Interpreting Brainfuck Programs with 'just' Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Examples of using the 'just interpret' command to run Brainfuck programs. Demonstrates interpreting 'Hello World!', a Fibonacci sequence generator, and a ROT13 cipher. ```sh # prints "Hello world!" > just interpret hello_world Hello World! # prints fibonacci numbers under 100 > just interpret fibonacci 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 # encrypts lines from stdin using rot13 cipher > just interpret rot13 unencrypted text harapelcgrq grkg ``` -------------------------------- ### MutexGuard Drop Implementation Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/tour-of-rusts-standard-library-traits.md Example of MutexGuard implementing the Drop trait to automatically unlock a mutex when the guard goes out of scope. ```rust impl Drop for MutexGuard<'_, T> { fn drop(&mut self) { unsafe { self.lock.inner.raw_unlock(); } } } ``` -------------------------------- ### Copy Trait Declaration Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/tour-of-rusts-standard-library-traits.md Example of the `Copy` trait declaration, which inherits from the `Clone` trait. This illustrates how a subtrait can refine its supertrait. ```rust trait Copy: Clone {} ``` -------------------------------- ### Rust Using Default for Struct Initialization Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/tour-of-rusts-standard-library-traits.md Demonstrates using `Color::default()` to get a default instance of the `Color` struct. ```rust fn main() { // just give me some color! let color = Color::default(); } ``` -------------------------------- ### Create SQL Migration Files Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Generates new SQL migration files for creating 'boards' and 'cards' tables using sqlx-cli. ```bash sqlx migrate add create_boards sqlx migrate add create_cards ``` -------------------------------- ### Collecting Iterator Items into a String Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/tour-of-rusts-standard-library-traits.md Example of using the collect method to create a String from an Iterator of characters, filtering for alphabetic characters. ```rust fn filter_letters(string: &str) -> String { string.chars().filter(|c| c.is_alphabetic()).collect() } ``` -------------------------------- ### Cargo Run Output Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md The output from running the Rocket application using `cargo run`. It shows the server starting up and logging information. ```bash $ cargo run [13:07:21][launch][INFO] Configured for development. [13:07:21][launch_][INFO] address: localhost [13:07:21][launch_][INFO] port: 8000 [13:07:21][launch_][INFO] log: normal [13:07:21][launch_][INFO] workers: 32 [13:07:21][launch_][INFO] secret key: generated [13:07:21][launch_][INFO] limits: forms = 32KiB [13:07:21][launch_][INFO] keep-alive: 5s [13:07:21][launch_][INFO] read timeout: 5s [13:07:21][launch_][INFO] write timeout: 5s [13:07:21][launch_][INFO] tls: disabled [13:07:21][rocket::rocket][INFO] Mounting /: [13:07:21][_][INFO] GET / (hello_world) [13:07:21][launch][INFO] Rocket has launched from http://localhost:8000 ``` -------------------------------- ### Connect to PostgreSQL Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Establishes an asynchronous connection to a PostgreSQL database using a connection URL from environment variables. Ensure the `DATABASE_URL` is set in your `.env` file. ```rust use sqlx::{Connection, PgConnection}; use crate::models::Board; // example of connecting to PostgreSQL async fn get_connection() -> PgConnection { dotenv::dotenv().unwrap(); let db_url = std::env::var("DATABASE_URL").unwrap(); PgConnection::connect(&db_url).await.unwrap() } ``` -------------------------------- ### LLVM IR: Switch Case Example with libc Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Demonstrates character case conversion (uppercase/lowercase) using LLVM IR and calls to C standard library functions like putchar and getchar. ```llvm ; ./examples/llvm_ir/switch_case.ll ; libc functions declare i8 @putchar(i8) declare i8 @getchar() ; main function called by libc ; the return value is set as program's exit code define i8 @main() { %switched = alloca i8 %char = call i8 @getchar() %bool = icmp uge i8 %char, 97 ; %char >= 97 ? br i1 %bool, label %MAKE_UPPERCASE, label %MAKE_LOWERCASE MAKE_UPPERCASE: %upper = sub i8 %char, 32 store i8 %upper, i8* %switched br label %WRITE MAKE_LOWERCASE: %lower = add i8 %char, 32 store i8 %lower, i8* %switched br label %WRITE WRITE: %result = load i8, i8* %switched call i8 @putchar(i8 %result) ret i8 0 } ``` -------------------------------- ### Compile and Run Brainfuck with 'just carba' Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Demonstrates the command-line usage for compiling and running Brainfuck programs using the 'just carba' command, specifying the input file name. ```Shell # prints "Hello world!" > just carba hello_world Hello World! # prints fibonacci numbers under 100 > just carba fibonacci 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 # encrypts lines from stdin using rot13 cipher > just carba rot13 unencrypted text harapelcgrq grkg ``` -------------------------------- ### Using Display and ToString with Point Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/tour-of-rusts-standard-library-traits.md Demonstrates how to use the `Display` trait with `println!` and `format!`, and how `ToString` can be used. ```rust fn main() { println!("origin: {}", Point::default()); // prints "origin: (0, 0)" // get Point's Display representation as a String let stringified_point = format!("{}", Point::default()); assert_eq!("(0, 0)", stringified_point); // ✅ } ``` ```rust trait ToString { fn to_string(&self) -> String; } ``` ```rust impl ToString for T; ``` ```rust #[test] // ✅ fn display_point() { let origin = Point::default(); assert_eq!(format!("{}", origin), "(0, 0)"); } ``` ```rust #[test] // ✅ fn point_to_string() { let origin = Point::default(); assert_eq!(origin.to_string(), "(0, 0)"); } ``` ```rust #[test] // ✅ fn display_equals_to_string() { let origin = Point::default(); assert_eq!(format!("{}", origin), origin.to_string()); } ``` -------------------------------- ### Passing Function Pointers to Iterators Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/tour-of-rusts-standard-library-traits.md Example of passing a function pointer (specifically `i32::abs`) to an iterator's `map` method to transform elements. ```rust fn main() { let nums = vec![-1, 1, -2, 2, -3, 3]; let absolutes: Vec = nums.into_iter().map(i32::abs).collect(); assert_eq!(vec![1, 1, 2, 2, 3, 3], absolutes); // ✅ } ``` -------------------------------- ### Copy Semantics Example Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/tour-of-rusts-standard-library-traits.md Illustrates copy semantics where the source variable remains valid after assignment. This applies to types implementing Copy, such as Option. ```rust // a "copy", src: Copy let dest = src; ``` ```rust { is_valid: bool, data: i32 } ``` ```rust src = { is_valid: bool, data: i32 } dest = { is_valid: bool, data: i32 } ``` -------------------------------- ### Integer Comparison Instructions Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/too-many-brainfuck-compilers.md Provides a comprehensive list of i32 comparison instructions for checking equality, inequality, and ordering (both signed and unsigned). These instructions pop two values and push a boolean result. ```wat ;; instructions below pop 2 values from the stack ;; then push the result of the comparison onto the stack i32.eq ;; equal i32.ne ;; not equal i32.lt_u ;; less than (unsigned) i32.lt_s ;; less than (signed) i32.gt_u ;; greater than (unsigned) i32.gt_s ;; greater than (signed) i32.le_u ;; less than or equal (unsigned) i32.le_s ;; less than or equal (signed) i32.ge_u ;; greater than or equal (unsigned) i32.ge_s ;; greater than or equal (signed) ;; instruction below pops 1 value from the stack ;; then pushes the result onto the stack i32.eqz ;; equal to zero ``` -------------------------------- ### Unit Testing File Handling with String and Vec Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/tour-of-rusts-standard-library-traits.md Demonstrates how to unit test I/O functions using `String` as a `Read` source and `Vec` as a `Write` destination, leveraging their implementations of `Read` and `Write` respectively. ```rust use std::path::Path; use std::fs::File; use std::io::Read; use std::io::Write; use std::io; // function we want to test fn uppercase(mut read: R, mut write: W) -> Result<(), io::Error> { let mut buffer = String::new(); read.read_to_string(&mut buffer)?; let uppercase = buffer.to_uppercase(); write.write_all(uppercase.as_bytes())?; write.flush()?; Ok(()) } // in actual program we'd pass Files fn example(in_path: &Path, out_path: &Path) -> Result<(), io::Error> { let in_file = File::open(in_path)?; let out_file = File::open(out_path)?; uppercase(in_file, out_file) } // however in unit tests we can use Strings! #[test] // ✅ fn example_test() { let in_file: String = "i am screaming".into(); let mut out_file: Vec = Vec::new(); uppercase(in_file.as_bytes(), &mut out_file).unwrap(); let out_result = String::from_utf8(out_file).unwrap(); assert_eq!(out_result, "I AM SCREAMING"); } ``` -------------------------------- ### Move Semantics Example Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/tour-of-rusts-standard-library-traits.md Demonstrates move semantics where the source variable is invalidated after assignment. This occurs for types that do not implement Copy, like Vec. ```rust // a "move", src: !Copy let dest = src; ``` ```rust { data: *mut [i32], length: usize, capacity: usize } ``` ```rust src = { data: *mut [i32], length: usize, capacity: usize } dest = { data: *mut [i32], length: usize, capacity: usize } ``` -------------------------------- ### Auto Trait Definitions Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/tour-of-rusts-standard-library-traits.md Provides examples of auto traits like `Send` and `Sync`, which are automatically implemented if their members satisfy the trait's requirements. ```Rust // implemented for types which are safe to send between threads unsafe auto trait Send {} // implemented for types whose references are safe to send between threads unsafe auto trait Sync {} ``` -------------------------------- ### Insert Board using CreateBoard Model Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Inserts a new board into the database using the `CreateBoard` model and returns the inserted board. Requires `diesel::prelude::*`, `diesel::PgConnection`, and relevant models/schema. ```rust use diesel::prelude::*; use diesel::PgConnection; use crate::schema::boards; use crate::models::{Board, CreateBoard}; // create and return new board from CreateBoard model fn create_board(conn: &PgConnection, create_board: CreateBoard) -> Board { diesel::insert_into(boards::table) .values(&create_board) .get_result(conn) // return inserted board result .unwrap() } ``` -------------------------------- ### Use Connection from Pool Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/restful-api-in-sync-and-async-rust.md Demonstrates how to obtain a database connection from an r2d2 connection pool. ```rust use diesel::prelude::*; use diesel::PgConnection; use diesel::r2d2; type PgPool = r2d2::Pool>; fn use_pool(pool: &PgPool) { let connection = pool.get().unwrap(); // use connection } ``` -------------------------------- ### Rust Convenience Constructor Using Default Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/tour-of-rusts-standard-library-traits.md Demonstrates creating convenience constructors for `Color` that use struct update syntax with `Color::default()` to initialize only specific fields. ```rust impl Color { fn red(r: u8) -> Self { Color { r, ..Color::default() } } fn green(g: u8) -> Self { Color { g, ..Color::default() } } fn blue(b: u8) -> Self { Color { b, ..Color::default() } } } ``` -------------------------------- ### Async Stream Iteration Example Source: https://github.com/pretzelhammer/rust-blog/blob/master/posts/chat-server.md This Rust code illustrates how to asynchronously iterate over a stream using `StreamExt::next`. It contrasts with synchronous iteration over an `Iterator`. ```rust use futures::{Stream, StreamExt}; async fn iterate(mut items: impl Stream + Unpin) { while let Some(item) = items.next().await { todo!() } } ```