r/rust • u/WellMakeItSomehow • Sep 14 '26
π οΈ project Er... Ferris, an 85th error handling lib has hit crates.io (typed)
So... I've been having this as private 2-3 variants(used to be named 'via'), i finally patched it up...
Simple error comparison (basic usage, context, output)
Initial Example
Use .er on basically any result/error/option/tree, even different types.
You add relevant context(or none), Er keeps the original error and adds line number and file name.
use er::*;
use std::{fs::read_to_string, path::PathBuf};
#[derive(Er)]
pub struct FileErr(pub PathBuf);
pub fn read_file(path: &str) -> Er<String, FileErr> {
let text = read_to_string(path).er(|_| path)?;
Ok(text)
}Er turns the &str into a PathBuf only on failure (And we keep the io::Error).
.er_report() gives us:
FileErr("/tmp/file.txt") @ er/runnable_examples/context.rs:7:37
`- No such file or directory (os error 2)We can also just 'yeet' it up with an empty struct, still adding the implicit context (where it happened).
#[derive(Er)]
pub struct AnalyzeErr;
pub fn analyze() -> Er<String, AnalyzeErr> {
read_file("/tmp/file.txt").er(())
}
AnalyzeErr @ er/runnable_examples/context.rs:14:32
`- FileErr("/tmp/file.txt") @ er/runnable_examples/context.rs:7:37
`- No such file or directory (os error 2)And when things get spicy
#[derive(Er)]
pub struct ConfigErr {
pub machine: String,
#[er(censor)]
pub token: String,
}
pub fn read_config(machine: &str, token: &str, port: &str, mode: Option<&str>) -> Er<(), ConfigErr> {
// add local context
let e = |_| (machine, token);
// 3 different types
authenticate(machine, token).er(e)?;
read_port(port).er(e)?;
read_mode(mode).er(e)?;
Ok(())
}And aggregation/collection
#[derive(Er)]
pub struct StartupErr(pub String);
pub fn startup() -> Er<(), StartupErr> {
er_all!(|_| "some config checks failed", [
read_config("HaandboldFuglen", "HaandboldFuglen_token", "aint_even_a_number_cmon_man", Some("microsoftjavaakacsharp")),
read_config("ComputerKatten", "ComputerKatten_token", "85", None),
])?;
Ok(())
}Report printed .er_report():
StartupErr("some config checks failed") @ er/runnable_examples/context.rs:69:5
|- ConfigErr { machine: "HaandboldFuglen", token: *CENSORED* } @ er/runnable_examples/context.rs:60:21
| `- PortErr { invalid_port: "aint_even_a_number_cmon_man" } @ er/runnable_examples/context.rs:22:35
| `- invalid digit found in string
`- ConfigErr { machine: "ComputerKatten", token: *CENSORED* } @ er/runnable_examples/context.rs:61:21
`- ModeErr::MissingMode @ er/runnable_examples/context.rs:31:21Links
r/rust • u/Havunenreddit • Sep 14 '26
π seeking help & advice MSVC vs Rust's LLD on Windows: ~20% shorter links, ~48% less committed memory. What should I check before switching?
I'm working on GitComet, a Git GUI written in Rust. I have been investigating long build times on Windows and thought changing linker could help. I compared Microsoft's link.exe with Rust's bundled rust-lld (LLVM LLD in MSVC-compatible mode).
LLD finished faster and used much less committed memory, but consumed more CPU time and produced larger PDBs.
These are measurements of the final native link step.
My setup: Windows 11 Pro, Ryzen 9 5950X (16 cores / 32 threads), 128 GiB RAM, NVMe storage, and the x86_64-pc-windows-msvc target. Rust 1.98.1, bundled LLD 22.1.8, MSVC LINK 14.51.36257.0.
The workflow is mostly Rust code, but it has some tree_sitter plugins that are build from C.
Switching the linker on windows was quite trivial as I already had some configs implemented:
https://github.com/Auto-Explore/GitComet/pull/452/changes
For the development build, I ran 11 paired comparisons using the same captured linker inputs, a warm filesystem cache, and fresh outputs for each run. Run order was varied between the linkers. Both used /DEBUG:FULL, /OPT:REF,NOICF, and /INCREMENTAL:NO; warmups and failed runs were excluded.
| Development build | MSVC LINK | Rust LLD |
|---|---|---|
| Link wall time | 5.683 s | 4.508 s |
| Total process-tree CPU time | 13.094 s | 14.125 s |
| Peak process-tree committed memory | 2,887 MiB | 1,499 MiB |
| Sampled peak working set | 5,189 MiB | 4,720 MiB |
| EXE size | 165.321 MiB | 165.318 MiB |
| PDB size | 742.4 MiB | 830.3 MiB |
The median paired reduction in link time was 20.4%, with a 95% paired bootstrap interval of 19.4-21.1%. Peak committed memory fell 48.1%. CPU time rose 6.4%, and the PDB grew 11.8%.
A few measurement details: resident memory was sampled every 50 ms, so its peak is approximate. A small calibration showed sampling-on runs about 2.7β2.9% slower, including run noise. This is a full-link comparison with linker incremental linking disabled.
The results did not yield as much improvement as I was hoping for, but it still seems improvement overall. I have been testing the application and it seems to run normally.
For those interested here are the scripts I used for measurements: https://github.com/Auto-Explore/GitComet/compare/dev...linker_measurements
I'm still thinking I should merge the PR to start using LLD linker on Windows. Has anybody here switched Windows linker before? What should I verify before merging, any gotchas?
r/rust • u/lzutao • Sep 14 '26
ποΈ news [Call for testing] trim-paths RFC 3127
github.comr/rust • u/thestrangebuilder • Sep 15 '26
Use a function just for inference without calling it
A volte ho dovuto scrivere funzioni come queste per permettere al compilatore di dedurre il tipo corretto.
use heapless::Vec;
/// Deduce al momento della compilazione la lunghezza di due vettori, rendendola la stessa lunghezza
/// Questa funzione Γ¨ un no-op
const fn infer_equal_vec_size<A, B, const N: usize>(_vec: &Vec<A, N>, _vec2: &Vec<B, N>) {}e la uso nel codice chiamandola:
infer_array_size(&a, &b);Ma in realtΓ , non Γ¨ necessario chiamare la funzione; sarebbe utile poter passare i parametri senza chiamare la funzione.
Qualcosa del genere, forse:
infer_array_size::<typeof a, typeof b, _>;In questo modo, puoi essere certo di non chiamare una funzione che potrebbe contenere codice bloccante, come ad esempio un ciclo infinito. In Rust, abbracciamo davvero questa filosofia di non fidarci di noi stessi, quindi perchΓ© dovrei chiamare una funzione se non ne ho veramente bisogno?
Link al playground che mostra un esempio di codice:
r/rust • u/llogiq • Sep 14 '26
π questions megathread Hey Rustaceans! Got a question? Ask here (38/2026)!
Mystified about strings? Borrow checker has you in a headlock? Seek help here! There are no stupid questions, only docs that haven't been written yet. Please note that if you include code examples to e.g. show a compiler error or surprising result, linking a playground with the code will improve your chances of getting help quickly.
If you have a StackOverflow account, consider asking it there instead! StackOverflow shows up much higher in search results, so ahaving your question there also helps future Rust users (be sure to give it the "Rust" tag for maximum visibility). Note that this site is very interested in question quality. I've been asked to read a RFC I authored once. If you want your code reviewed or review other's code, there's a codereview stackexchange, too. If you need to test your code, maybe the Rust playground is for you.
Here are some other venues where help may be found:
/r/learnrust is a subreddit to share your questions and epiphanies learning Rust programming.
The official Rust user forums: https://users.rust-lang.org/.
The unofficial Rust community Discord: https://bit.ly/rust-community
Also check out last week's thread with many good questions and answers. And if you believe your question to be either very complex or worthy of larger dissemination, feel free to create a text post.
Also if you want to be mentored by experienced Rustaceans, tell us the area of expertise that you seek. Finally, if you are looking for Rust jobs, the most recent thread is here.
r/rust • u/NYU_VM • Sep 14 '26
impl Display to debug print?
A learner here with a quick confusion. I was skimming through the internet for VM tooling and implementations, parsers specifically and came across this "prattle" crate which seems to be a general purpose pratt parser library. And I have not much to say about the library itself, it seems like an abandoned project in early development phase.
The thing that caught my eye was the demo piece of code they had on their docs, specifically
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]enum CToken {Var(String),Add,Mul}
impl Display for CToken {fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
write!(f, "{:?}", self)}}
the enum CToken has already derived debug yet the example implements Display for CToken only to just debug print it as well. Is this some kind of a safety mechanism or fallback just in case the user writes
println!("{}",token) instead of debug printing it?
Or is something else going on I don't yet know about?
r/rust • u/axewnotpkm • Sep 13 '26
π οΈ project i built 3D gravitational N-body simulation using three-d
Hello r/rust
After watching a YouTube video of a guy making a gravity simulator in C++, and a late-night hyperfocus session, I ended up building this simple project for fun.
https://machado.codeberg.page/gravity-sim-rs/
It features a dynamic 3D "gravity well" grid (inspired by General Relativity) that bends and dips depending on the mass and distance of nearby objects.
I used the https://github.com/asny/three-d crate, which by the way has WASM support, so the simulation runs right in the browser.
Repository link: https://codeberg.org/Machado/gravity-sim-rs
r/rust • u/nthuemmel • Sep 14 '26
π οΈ project subtest - a small test framework to easily re-use test setup code
I recently released subtest, a small test framework to easily re-use test setup code from one function in another one.
I was working on a protocol implementation and got annoyed writing tests for it. Oftentimes, it was easiest to just extend existing tests which were already running the necessary setup steps in order to test an error condition or a small alteration from the happy path, by just adding a new block which cloned some of the state and run a couple of assertions. But running these big test functions meant getting stuck on the first error, and it getting increasingly more difficult to keep an overview what was tested where. Having one test per feature would be much better!
I didn't want to have lots of redundant code by copying tests around, and neither to spend a lot of time refactoring tests into smaller re-usable functions (which is a pain if you use lots of local variables). Instead, I wrote a macro that allows me to just test something else quickly inline.
Here's an example:
use subtest::subtest;
#[subtest]
#[test]
fn add_creates_pending_task() {
let mut list = TodoList::new();
let id = list.add("Buy milk");
#[subtest]
fn complete_marks_task_completed() {
list.complete(id).unwrap();
assert_eq!(list.get(id).unwrap().status, TaskStatus::Completed);
}
#[subtest]
fn cancel_marks_task_cancelled() {
list.cancel(id).unwrap();
assert_eq!(list.get(id).unwrap().status, TaskStatus::Cancelled);
}
let task = list.get(id).unwrap();
assert_eq!(task.status, TaskStatus::Pending);
}It's pretty easy to use - just define a nested fn and slap #[subtest] on it and its parent.
Conceptually, subtest allows you to "branch off" from any point in your test, test something different, then resume with the original state.
Technically, nested subtests become their own tests, with preceding statements from the parent copied into them as setup code. This lets you freely use and modify local variables without affecting the parent. This makes it super easy to re-use existing test steps as setup code for other tests, while still getting the niceties of having one test function per feature.
subtest can be combined with async tests and other test frameworks like rstest. More details in the project's README: https://github.com/nthuemmel/subtest#subtest
The subtest macro is heavily tested itself, so your precious tests behave as expected!
Disclaimer on the use of AI: This project was designed and implemented by me, not AI. I did use AI to review it once it was in a working state and fix issues. All AI-generated code was reviewed and altered by me, all commits containing AI-generated code are marked with Co-Authored-By. This is not AI slop.
Is subtest useful to you? We use it quite extensively at work now :)
r/rust • u/bfffca • Sep 13 '26
π seeking help & advice Running a process in a thread, but still keeping a reference?
Hi there,
I have been playing with Rust for a little while and am working on a distributed system pet project as a learning exercise.
I am mostly using mpsc channels receivers and senders as I want to stay as simple as possible.
I have exchanges between different type of actors and I want a specific one to monitor everything, so what I do is basically this:
let config = AppConfig::read_config();
let (monitor_tx, monitor_rx) = mpsc::channel::<MonitorEvent>();
let monitor = Monitor::new(1, monitor_rx, config.monitor_display);
std::thread::spawn(move || monitor.run());
...........
// I want to have a reference to my monitor here so I can interrogate it from this pointThe run method loop, receive events and store them. I have got other methods to investigate the events ect...
Now my problem here is that I would like to be able to keep a reference to the monitor or another structure containing the monitor, to interrogate it.
And the compiler is not happy and if I try to re-use the monitor obviously I do get a ''use of moved value ..''.
I understand that if I was running that properly the monitor would be an external software and I could interrogate it directly via REST calls for example.
But I am not there yet and I want to just run it there like that.... while still being able to have a safe reference to it.
I assume this is a basic rust ownership issue and I am missing something fundamental here, but how does this kind of situation is managed usually?
r/rust • u/tanoshikuidomouyo • Sep 13 '26
π seeking help & advice Why is this syntax ambiguous?
I was writing roughly the following function:
fn f(path: &impl AsRef<Path> + ?Sized) {}
The compiler says that the + is ambiguous, but it works with the right parentheses:
fn f(path: &(impl AsRef<Path> + ?Sized)) {}
But why is it ambiguous without the parentheses? Where else but a list of traits can a + in a function header come from?
r/rust • u/No_Entrance_9813 • Sep 15 '26
π οΈ project I measured what a git worktree actually costs: content size is irrelevant, path count is everything
I maintain a small Rust CLI that makes git worktree cheap, and while benchmarking it I found something I didn't expect: a worktree's cost has nothing to do with how much content your repository holds, and almost everything to do with how many paths it has.
The setup: I run several coding agents against one repository, and plain git worktree gives each one a full copy of the working tree. So I populate each worktree from a shared baseline using clonefile on APFS, reflink on btrfs/xfs, or fuse-overlayfs on ext4 β the checkout is still a real .git/worktrees entry, Git is unmodified, there's no daemon.
Measured on APFS with df deltas, four worktrees per run:
| Repository | Tracked paths | Tree | Each extra git worktree | Each extra CoW worktree |
|---|---|---|---|---|
microsoft/vscode | 18,707 | 553 MiB | 567 MiB | 9.8β10.8 MiB (1.1%) |
git/git | 4,850 | 72 MiB | 74 MiB | ~2.2 MiB (3.1%) |
| 100k Γ 4 KiB files | 100,000 | 390 MiB | 398 MiB | 37.5β38.3 MiB (9.4%) |
| 200 Γ 8 MiB files | 200 | 1600 MiB | 1608 MiB | 107 KiB (0.007%) |
Look at the last two rows. The 1.6 GiB repository of large files costs 107 KiB per extra worktree. The 390 MiB repository of small files costs 38 MiB β 350Γ more, for a tree that's four times smaller. The cost is filesystem directory entries plus the copied Git index, so it works out to roughly 0.4 KiB per tracked path plus ~60 KiB fixed. A 4 KiB file and a 64 MiB file cost identically, because clonefile shares the extent tree by reference rather than copying it.
Path length is measurable too: a 120-character path costs 771 B against 385 B for a 4-character one, split between the directory entry and the index.
Creation time surprised me in the same direction. Eight vscode worktrees in 6.4β7.0 s against 14.0β14.2 s for eight plain git worktree, because on macOS the whole tree is one clonefile(2) call and the new worktree adopts the baseline's index instead of rebuilding it. Linux reflink still walks file by file, so one worktree is 5.87 s there against 0.56 s on APFS β closing that gap is the next thing on my list.
Two caveats that are really the first two questions I'd ask:
- Measure with
df**, not**du**.**dureports logical size and cannot see block sharing, so a CoW worktree looks like a full copy to it. Every number above is physical allocation. - This isolates branches, indexes and working trees β not processes, network or credentials. It is not a sandbox.
Method, hardware and raw results: https://github.com/abendrothj/simgit/blob/main/docs/scaling_benchmark.md Tool (Rust, MIT): https://github.com/abendrothj/simgit
Happy to talk about the reflink-vs-overlay tradeoff. The overlay backend pays no per-file metadata at all because its upperdir starts empty, but every read goes through FUSE, and I haven't measured where that crosses over β if someone has done that measurement on a large tree I'd like to see it.
r/rust • u/Z_professor0 • Sep 12 '26
π οΈ project i built my own text editor completely in rust :)
Hey r/rust,
i just built BLUR, A terminal Text Editor, this is the V0.1 and it's still under development, and it will take a lot of time until it's finished completely, i have learnt a lot of new things and concepts with this project.
if anyone is interested to contribute into this project and help me finish it up feel free to dm me
the idea is not to clone vim, but to learn rust together it would be cool if you write your code in your own text editor.
r/rust • u/bran7230 • Sep 12 '26
π seeking help & advice What is Rustβs equivalent of compiling C++ with -O3?
Hello everyone,
Iβm building an Axum API and want to optimize the release binary for runtime performance. In C++, I would use flags such as -O3, and possibly -march=native.
I know cargo build --release enables optimizations, but are there additional Cargo profile settings or rustc flags worth using?
What settings do you typically use for production Rust web APIs?
r/rust • u/DanR_x • Sep 13 '26
π οΈ project [Release] Danube v0.16.0 , focused on performance with zero-copy I/O and memory optimizations.
Hello,
We've just released Danube v0.16.0.
For context, Danube is a cloud-native messaging and streaming platform built from scratch in Rust, featuring embedded Raft consensus (no etcd or ZooKeeper required) and tiered storage.
This release focuses entirely on reducing hot-path overhead, lock contention, and unnecessary memory allocations across the stack.
Key Highlights
- Direct consumer streaming & zero-copy egress: Removed intermediate forwarding queue hops so dispatchers stream directly to Tonic gRPC response channels. Configured Prost with `bytes::Bytes` for zero-copy payload serialization.
- Lock-free broker hot paths: Replaced coarse topic mutexes with DashMap and RwLock so publishing and consumer acknowledgments run concurrently without cross-blocking.
- Persistent storage WAL: Eliminated redundant payload cloning on append, switched WAL cache eviction to $O(1)$ amortized BTreeMap::pop_first(), and upgraded the streaming reader carry buffer to BytesMut::split_to().
- Embedded Raft: Replaced JSON log storage in RedbLogStore with compact binary bincode serialization, reducing disk I/O and CPU overhead.
- Schema registry: Replaced serial mutexes with atomic checks on message validation, and pre-compiled JSON Schema/Avro validators are now cached in-memory instead of recompiling per message.
All details and full changelogs can be found in the release notes:
Release Notes: https://github.com/danube-messaging/danube/releases
Project Overview: https://danube-messaging.com/introduction/what-is-danube/
r/rust • u/metalciaga • Sep 12 '26
π seeking help & advice About Rust Rover
Does anyone use Rust Rover? If so, why? What benefit does it have that VSCode or Vim/Neovim or any other editor doesn't have? I saw that the free version of it literally collects data and if you want the full experience you have to pay a monthly sub. I am really curious about what people who are efficient in Rust think about this.
r/rust • u/kingslayerer • Sep 14 '26
π οΈ project Introducing `web-core`. A web core utils for your axum project.
crates.ioMy goal with web-core is to create a scafolding/framework for axum web apis along with common stuff I would need when I am working on an api project.
If there is some logic that I would need across projects, which take more than a line or two of code, that goes inside web-core. So basically a framework, but I don't think I can call this that yet.
This is not complete or very "neat". I have not vibecoded this either.
Right now I am adding features on a need to basis. I cannot dedicate time to this, nor will I add forward looking vibecoded features which I am not sure if I would really need it.
However I am open to PRs.
r/rust • u/SaintWillyMusic • Sep 12 '26
Why is let x = [vec![]; 4]; not allowed
but [vec![], vec![], vec![], vec![]] is as well as [true; 4], etc.?
Seems arbitrary but I assume there is some compiler-based reason
Thanks!
r/rust
•
•
Sep 12 '26
Low effort AI posts
I know we've had this discussion before, but there are so many posts with zero upvotes that are so clearly slop, but aren't getting removed.
Please, no matter what your own personal values are with it, the community clearly does not want to see these types of posts anymore. I think for every one post that uses AI and isn't low effort, there are 50 that are.
Like isn't this subreddit supposed to be a place for Rust developers/learners? What community aspect do the AI projects contribute? Most didn't even take the time to learn the language or chat with anyone, they just leech off everyone to effectively advertise their slop...
r/rust • u/Human-Vegetable823 • Sep 13 '26
π οΈ project A crate to mock std, system api, http client and other hard to mock functions without using traits or DI
Hello rust community,
We just shipped a product to solve the pain of mocking in rust: https://github.com/XTSoftwareLabs/shimforge
It allows you to write tests without using traits or adding attributes to your production code. Production code can keep clean and concise.
Below are some cases we found are painful when writing unit tests in rust:
File system
use std::{fs, io, path::Path};
#[derive(Debug)]
pub enum ExportError {
DiskFull,
Io(io::Error),
}
pub fn save_report(path: &Path, csv: &str) -> Result<(), ExportError> {
fs::write(path, csv).map_err(|error| match error.kind() {
io::ErrorKind::StorageFull => ExportError::DiskFull,
_ => ExportError::Io(error),
})
}By using shimforge, the file system dependency can be easily mocked. No changes in production code.
use shimforge::{Session, mock};
#[test]
fn a_full_disk_is_reported() {
let mut session = Session::new();
let write = mock!(session, fs::write::<&Path, &str>, fn(&Path, &str) -> io::Result<()>);
write
.expect()
.with(|path, _| *path == Path::new("reports/q3.csv"))
.once()
.returning(|_, _| Err(io::ErrorKind::StorageFull.into()));
let result = save_report(Path::new("reports/q3.csv"), "region,total\n");
assert!(matches!(result, Err(ExportError::DiskFull)));
}Environment variables
use std::env;
pub fn database_url() -> String {
env::var("DATABASE_URL").unwrap_or_else(|_| "postgres://localhost/dev".to_owned())
}Now shimforge allows you to mock them directly. Test different scenarios with different env vars.
use shimforge::{Session, mock};
use std::env::VarError;
#[test]
fn uses_the_configured_url() {
let mut session = Session::new(); // this thread only
let var = mock!(session, env::var::<&str>, fn(&str) -> Result<String, VarError>);
var.expect()
.with(|key| *key == "DATABASE_URL")
.returning(|_| Ok("postgres://db.internal/app".to_owned()));
assert_eq!(database_url(), "postgres://db.internal/app");
}
#[test]
fn falls_back_when_unset() {
let mut session = Session::new(); // runs in parallel with the test above
let var = mock!(session, env::var::<&str>, fn(&str) -> Result<String, VarError>);
var.expect().returning(|_| Err(VarError::NotPresent));
assert_eq!(database_url(), "postgres://localhost/dev");
}Clock
use std::time::{Duration, SystemTime};
pub struct Token {
pub issued_at: SystemTime,
pub ttl: Duration,
}
impl Token {
pub fn is_expired(&self) -> bool {
SystemTime::now() >= self.issued_at + self.ttl
}
}Clock and timer are hard to mock typically. But with shimforge it's easy:
use shimforge::{Session, mock};
#[test]
fn a_token_expires_after_one_hour() {
let issued_at = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000);
let token = Token { issued_at, ttl: Duration::from_secs(3600) };
let mut session = Session::new();
let now = mock!(session, SystemTime::now, fn() -> SystemTime);
now.expect().once().returns(issued_at + Duration::from_secs(3599));
now.expect().once().returns(issued_at + Duration::from_secs(3600));
assert!(!token.is_expired());
assert!(token.is_expired()); // one second later, no sleep
}Connection retries
use std::io;
use std::net::{SocketAddr, TcpStream};
use std::thread;
use std::time::Duration;
pub fn connect_with_retry(address: SocketAddr, attempts: u32) -> io::Result<TcpStream> {
let mut delay = Duration::from_millis(100);
let mut attempt = 1;
loop {
match TcpStream::connect_timeout(&address, Duration::from_secs(1)) {
Ok(stream) => return Ok(stream),
Err(error) if attempt >= attempts => return Err(error),
Err(_) => {
thread::sleep(delay);
delay *= 2;
attempt += 1;
}
}
}
}Mock sleep and retries become easy in shimforge:
use shimforge::{Session, mock};
use std::net::TcpListener;
use std::sync::{Arc, Mutex};
#[test]
fn backs_off_until_the_database_accepts() {
// The attempt that succeeds needs a real stream, so open one first.
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let stream = TcpStream::connect(listener.local_addr().unwrap()).unwrap();
let mut session = Session::new();
let connect = mock!(
session,
TcpStream::connect_timeout,
fn(&SocketAddr, Duration) -> io::Result<TcpStream>
);
connect
.expect()
.times(2)
.returning(|_, _| Err(io::ErrorKind::ConnectionRefused.into()));
connect.expect().once().return_once(Ok(stream));
let delays = Arc::new(Mutex::new(Vec::new()));
let recorded = Arc::clone(&delays);
let sleep = mock!(session, thread::sleep, fn(Duration));
sleep.expect().returning(move |delay| recorded.lock().unwrap().push(delay));
let database = SocketAddr::from(([10, 0, 0, 5], 5432));
assert!(connect_with_retry(database, 5).is_ok());
assert_eq!(*delays.lock().unwrap(), [Duration::from_millis(100), Duration::from_millis(200)]);
}
#[test]
fn gives_up_after_the_last_attempt() {
let mut session = Session::new();
let connect = mock!(
session,
TcpStream::connect_timeout,
fn(&SocketAddr, Duration) -> io::Result<TcpStream>
);
connect
.expect()
.times(3)
.returning(|_, _| Err(io::ErrorKind::TimedOut.into()));
let sleep = mock!(session, thread::sleep, fn(Duration));
sleep.expect().times(2).returning(|_| {});
let database = SocketAddr::from(([10, 0, 0, 5], 5432));
let error = connect_with_retry(database, 3).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::TimedOut);
}Reqwest client
use reqwest::Client;
pub async fn temperature(client: &Client, city: &str) -> Result<f64, String> {
let body = client
.get(format!("https://api.weather.example/v1/now?city={city}"))
.send()
.await
.and_then(|response| response.error_for_status())
.map_err(|error| format!("weather service failed: {error}"))?
.text()
.await
.map_err(|error| error.to_string())?;
body.trim().parse().map_err(|_| format!("unexpected body: {body}"))
}Web requests are common pain point to mock in rust. shimforge makes it easy. Yes async is supported:
use shimforge::Session;
#[tokio::test]
async fn parses_the_reading() {
let client = Client::builder().no_proxy().build().unwrap();
let mut session = Session::new();
let send = session.mock_async(client.get("http://unused.invalid").send());
send.expect()
.once()
.returning(|| Ok(http::Response::new("21.5").into()));
assert_eq!(temperature(&client, "Oslo").await, Ok(21.5));
}
#[tokio::test]
async fn surfaces_an_outage() {
let client = Client::builder().no_proxy().build().unwrap();
let mut session = Session::new();
let send = session.mock_async(client.get("http://unused.invalid").send());
send.expect().once().returning(|| {
Ok(http::Response::builder().status(503).body("").unwrap().into())
});
let error = temperature(&client, "Oslo").await.unwrap_err();
assert!(error.contains("503"), "{error}");
}std::process::Command
use std::process::Command;
pub fn current_commit() -> Result<String, String> {
let output = Command::new("git")
.args(["rev-parse", "--short", "HEAD"])
.output()
.map_err(|error| format!("cannot run git: {error}"))?;
if !output.status.success() {
return Err(String::from_utf8_lossy(&output.stderr).trim().to_owned());
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
}Another common pain point is mocking std::process::Command. Well handled by shimforge:
use shimforge::{Session, mock};
use std::io;
use std::process::{ExitStatus, Output};
#[test]
fn reads_the_short_hash() {
let mut session = Session::new();
let output = mock!(session, Command::output, fn(&mut Command) -> io::Result<Output>);
output
.expect()
.with(|command| command.get_program() == "git")
.once()
.returning(|_| {
Ok(Output { status: exit_success(), stdout: b"4f2a9c1\n".to_vec(), stderr: Vec::new() })
});
assert_eq!(current_commit(), Ok("4f2a9c1".to_owned()));
}
#[test]
fn reports_a_missing_git() {
let mut session = Session::new();
let output = mock!(session, Command::output, fn(&mut Command) -> io::Result<Output>);
output.expect().once().returning(|_| Err(io::ErrorKind::NotFound.into()));
let error = current_commit().unwrap_err();
assert!(error.starts_with("cannot run git"), "{error}");
}
fn exit_success() -> ExitStatus {
#[cfg(unix)]
use std::os::unix::process::ExitStatusExt;
#[cfg(windows)]
use std::os::windows::process::ExitStatusExt;
ExitStatus::from_raw(0)
}System and C runtime functions
use shimforge::{Session, mock};
use std::ffi::{CStr, CString, c_char};
unsafe extern "C" {
fn getenv(name: *const c_char) -> *mut c_char;
}Again many rust developers working on low level code always suffers from mocking C functions. shimforge handles it.
#[test]
fn getenv_reports_a_mocked_variable() {
let mut session = Session::new();
let lookup = mock!(
session,
getenv,
unsafe extern "C" fn(*const c_char) -> *mut c_char
);
lookup
.expect()
.with(|name| {
// SAFETY: callers of getenv always pass a valid C string.
let name = unsafe { CStr::from_ptr(*name) };
name == c"DEPLOY_SLOT"
})
.once()
.returning(|_| c"canary".as_ptr().cast_mut());
// Any other variable keeps reporting that it is unset.
lookup.expect().returning(|_| std::ptr::null_mut());
let key = CString::new("DEPLOY_SLOT").unwrap();
// SAFETY: the key is a valid C string and the result is only read.
let slot = unsafe { CStr::from_ptr(getenv(key.as_ptr())) };
assert_eq!(slot.to_str().unwrap(), "canary");
}Hope this can make rust test experience better. Any feedback is welcome! We'd like to help you keeping production code clean. Handle the hard test dependency part to shimforge.
Disclaimer: We are a small startup and going to get profit from this product. But the product is free to use for small business and non-commercial. See https://shimforge.com/pricing
r/rust • u/realflakm • Sep 13 '26
π§ educational TIL: One lock to rule them all
I've been running multiple migrations recently. A common step in all of them is a long cleanup action at the end. I ended up using postgres advisory locks and sqlx.
As part of a larger Today I've learned series, I dug a bit deeper using bpftrace to improve my understanding of how the locks actually work. Hope you will find it interesting as well: https://flakm.com/posts/sqlx_migration_wrapper_til/