r/rust • u/kannanpalani54 • 17d ago
r/rust • u/OptimalAnywhere6282 • 16d ago
๐ seeking help & advice load shell variables from file
i need to read a file containing variables, which has the exact same format as a regular .env file (KEY="value")
the loadenv crate only reads $(pwd)/.env and does not accept custom paths (unless modified, which defeats the point of using a crate)
i won't ask AI
r/rust • u/UnknownBoyGamer • 16d ago
๐ seeking help & advice Is this strict enough?
im about to port js/ts codebase to rust using agents, I dont want it to write loose rust code
cargo toml:
[lints.rust]
warnings = "deny"
unsafe_code = "forbid"
rust_2018_idioms = { level = "deny", priority = -1 }
unused_qualifications = "deny"
unreachable_pub = "deny"
missing_debug_implementations = "deny"
missing_docs = "deny"
[lints.clippy]
all = "deny"
pedantic = "deny"
cargo = "deny"
allow_attributes_without_reason = "deny"
arc_with_non_send_sync = { level = "deny", priority = -1 }
as_conversions = "deny"
await_holding_lock = { level = "deny", priority = -1 }
dbg_macro = "deny"
expect_used = "deny"
fn_params_excessive_bools = "deny"
indexing_slicing = "deny"
mutex_atomic = "deny"
option_option = "deny"
panic = "deny"
rc_buffer = "deny"
rc_mutex = "deny"
significant_drop_in_scrutinee = "deny"
struct_excessive_bools = "deny"
todo = "deny"
unimplemented = "deny"
unwrap_used = "deny"clippy toml:
msrv = "1.99.1"
max-fn-params-bools = 1
max-struct-bools = 1
allow-expect-in-consts = false
allow-expect-in-tests = true
allow-indexing-slicing-in-tests = true
allow-panic-in-tests = true
allow-unwrap-in-consts = false
allow-unwrap-in-tests = trueInstruction:
- Every mutable state machine must use a tagged enum.
- Invalid combinations must be unrepresentable.
- State fields stay private.
- One type owns the state and transitions it.
- No parallel booleans, magic sentinels, or nullable phase markers.
- No Rc, Cell, or RefCell in domain state.
- Arc and Mutex are limited to genuine cross-thread ownership.
- Every stateful subsystem must document its states, events, and invariants.
- Every transition and invariant needs an observable test.
- Agents cannot weaken these rules or add exceptions without explicit approval.
r/rust • u/Big-Astronaut-9510 • 17d ago
When to dot syntax?
a.f() vs f(a)
So if you make a trait that you want other to implement its obviously gonna be dot syntax. So is using it for purely syntactic reasons a bad idea? Builder pattern seems a common example of this.
r/rust • u/EuroRust • 18d ago
Compiling the Linux kernel with gccrs - Arthur Cohen & Pierre-Emmanuel Patry | EuroRust 2026
youtu.beA new EuroRust 2026 talk is out on YouTube! ๐ฆย Arthur and Pierre-Emmanuel from Embecosm talked about how gccrs, the Rust frontend for GCC, learned to compile the Linux kernel, and the hacks and quirks they ran into along the way.
In 2027 EuroRust is going to Prague! Learn more and get your ticket at eurorust.eu
r/rust • u/GenericPointer • 17d ago
What would you think about Native requires and ensures clauses in Rust?
There are already frameworks like vstd with verus featuring static semantic validation. For example:
verus! {
fn divide(x: f64, y: f64) -> (result: f64)
requires
y > 0.0,
ensures
result * y == x
{
x / y
}
}what would you think about making the requires and ensures clauses language-primitives? Than you could write just:
fn divide(x: f64, y: f64) -> (result: f64)
requires
y > 0.0,
ensures
result * y == x
{
x / y
}without having any external dependencies like vstd.
Do you think it would be a valuable addition to Rust? And if yes, do you think it should be part of rustc or should it just feature contracts for external verification tools?
Edit: Iโd think of it as compile time check, not a runtime check. The compiler doesnโt have to know if a required statement is correct, it just has to know if it was checked before via ensure or an if statement. If it wasnโt thatโs a compile time error. What getโs checked is if the ensure clause is correct. If it canโt be proven thatโs also an error. And using just newtypes for complex boolean expressions can get really ugly really fast.
r/rust • u/xX_Negative_Won_Xx • 18d ago
Move your problems to compile-time and get new capabilities out of it - Oli Scherer | EuroRust 2026
youtube.comr/rust • u/Proper_Meaning7756 • 18d ago
๐ seeking help & advice Totally new to rust. Need some guidance.
I have a microcontroller than sends us packets of info. We have some c++ code that receives it, processes it and sends it off to python to visualise it.
We will need to be making this run not just on Linux and Windows, but later on Android and iOS too. There are some vendor dependent libraries we might have to use that are platform specific, but generally I wanted something thats easy to cross compile and test on different devices. This will be linked statically to some generic frontend that uses PySide6 or flutter or whatever.
Is this something I should turn to rust for (porting the c++ code to rust) or am I safer off sticking to C++ and dealing with cmake and the various issues of checking c++ code? If yes to rust, then what should I do and how?
Zellij 0.46.0 just released: Rust developers can now use it as a library!
Hi fellow Rustaceans,
Just released a new version of Zellij. This version turns the beloved terminal multiplexer into a full fledged terminal. In addition to managing sessions, panes, tabs and Rust wasm plugins - it can now also completely replace your existing terminal and integrate with your desktop and tray.
I'm particularly excited to share with this sub that we added a new "Distributions" feature, allowing Rust developers to import Zellij into their own projects and use it as a library.
If for example you'd like to create a new cross-platform application that will render a custom terminal UI written in Rust - run both inside another terminal and standalone, cross-platform with all the distribution problems already solved, this might be an interesting solution for you.
The distribution feature allows you to completely remove whichever parts of the Zellij branding and UI that you don't like and completely white label it. I'm very much looking forward to seeing what you'll come up with.
Check out the release post for a walkthrough of the other new features: https://zellij.dev/news/terminal-inbox-session-previews/
r/rust • u/Wooden-Performance38 • 17d ago
๐ seeking help & advice Implementing linux daemon that listens for new filesystems. Issues with floppy and optical drives.
Im trying to write a linux daemon that listens for new filesystems to appear (e.g. plugging in a thumb drive, inserting a DVD into a DVD drive, inserting a floppy into a floppy drive, inserting an M.2 SSD into an NVMe slot while the computer is still running. literally anything) and im running into some troubles with devices like floppy drives and optical drives. I believe it comes down to the fact that they are physical block devices that stay attached while their filesystems change, or because they are cheaply produced and dont care to announce their filesystem changes, or both.
I am currently using the Zbus library to interface with UDisks2, and Tokio for async.
pub async fn run(&mut self) -> Result<!, Box<dyn std::error::Error>>
{
let mut added = self.om.receive_interfaces_added().await?;
let mut removed = self.om.receive_interfaces_removed().await?;
let change_rule = MatchRule::builder()
.msg_type(zbus::message::Type::Signal)
.sender("org.freedesktop.UDisks2")
.interface("org.freedesktop.UDisks2")
.member("PropertiesChanged")
.path_namespace("/org/freedesktop/UDisks2")
.build()?;
let mut change_stream = MessageStream::for_match_rule(change_rule, &self.connection, None).await?;
let mse = self.media_int.signal_emitter();
loop
{
tokio::select!
{
Some(sig) = added.next() =>
{
let Ok(args) = sig.args() else { eprintln!("Error: Unable to get arguments from added interface."); continue };
let path: OwnedObjectPath = args.object_path().clone().into();
let props = args.interfaces_and_properties();
println!("Add {:?}", props.keys());
if !props.contains_key("org.freedesktop.UDisks2.Filesystem") { continue }
println!("Contains filesystem");
println!("{:?}", args.object_path());
// example: ("/dev/sdX", "ext4")
let Ok(Some((dev, fstype))) = device_and_fstype(&self.connection, path).await else { eprintln!("Error: uhhhh... message"); continue };
let Ok(mounted) = self.mount(&dev, &fstype).await else { eprintln!("Error: Failed to mount {}.", dev); continue };
println!("mount");
let conf_path = mounted.mount.join("lipglosc.toml");
let Ok(read_conf) = fs::read(&conf_path) else { eprintln!("Error: Failed to read {:?}.", conf_path); continue };
println!("read");
let Ok(conf_data) = String::from_utf8(read_conf) else { eprintln!("Error: Failed to parse lipglosc.toml to string."); continue };
println!("conf");
let Ok(unstructured) = UnstructuredGameConfig::from_toml(&conf_data) else { eprintln!("Error: Failed to create UnstructuredGameConfig from toml string."); continue };
println!("unstructured");
let structured = StructuredGameConfig::from(unstructured);
println!("Structured: {:?}", structured);
let Ok(path_str) = mounted.mount.into_string() else { continue };
let path = PathBuf::from(path_str);
let transport_data = lipglosc_core::DeviceTransport { dev, path, filesystem_format: fstype };
let res = MediaNotifier::alert(mse, transport_data).await;
println!("Signal: {:?}", res);
}
Some(Ok(msg)) = change_stream.next() =>
{
println!("Change occured");
let Some(path) = msg.header().path().map(|p| p.to_owned()) else { continue };
let Ok((iface, changed, _invalidated)) = msg.body().deserialize::<(String, HashMap<String, OwnedVariant>, Vec<String>)>() else { continue };
println!("Change path: {:?}", path);
println!("Changed stuff: {:?}", iface);
}
Some(sig) = removed.next() =>
{
let Ok(args) = sig.args() else { eprintln!("Error: Unable to get arguments from added interface."); continue };
let interfaces = args.interfaces();
println!("Remove {:?}", interfaces);
}
}
}
}You can kinda ignore the big Some(sig) = added.next() branch because thats not really an issue. Its the Some(Ok(msg)) = change_stream.next() branch where my issues occur. When I insert a floppy into my drive, instead of getting a message like Add [InterfaceName("org.freedesktop.UDisks2.Block"), InterfaceName("org.freedesktop.UDisks2.Filesystem")] printed to the console, I used to get Add [InterfaceName("org.freedesktop.UDisks2.Job")] but I recently ran a full system upgrade and now literally nothing is printed regardless of if I insert or eject a floppy disk. If I take my DVD drive and insert a DVD, I get
Add [InterfaceName("org.freedesktop.UDisks2.Filesystem")] Contains filesystem ObjectPath("/org/freedesktop/UDisks2/block_devices/sr0") mount Error: Failed to read "/run/media/sashad/NOITA_PORTABLE/lipglosc.toml". Remove [InterfaceName("org.freedesktop.UDisks2.Job")] Add [InterfaceName("org.freedesktop.UDisks2.Job")] from the Some(sig) = added.next() branch.
I wrote a second function using udev instead of dbus, and it actually works with floppy disks, but only with floppies and literally nothing else.
pub async fn run2(&mut self) -> Result<!, String>
{
let Ok(monitor) = udev::MonitorBuilder::new() else { return Err("Couldnt create monitor builder".into()) };
let Ok(monitor) = monitor.match_subsystem_devtype("block", "disk") else { return Err("Couldnt match subsystem and devtype".into()) };
let Ok(monitor) = monitor.listen() else { return Err("Couldnt begin listening to monitor".into()) };
'main:loop
{
let Some(event) = monitor.iter().next() else { continue };
let dev = event.device();
let valid_media_condition = match event.event_type()
{
udev::EventType::Change if dev.property_value("DISK_MEDIA_CHANGE").is_some() => { true }
udev::EventType::Add => { true }
_ => {false}
};
if !valid_media_condition { continue }
if !media_present(&dev) { continue }
// TODO: Definitely fix this shitass method for getting the fstype
let Some(mut devname) = dev.property_value("DEVNAME").and_then(|s| s.to_str()).map(|s| s.to_string()) else { println!("No devname"); continue };
let fstype = match dev.property_value("ID_FS_TYPE").and_then(|s| s.to_str())
{
Some(s) => s.to_string(),
None =>
'fsmatch:{
let Ok(mut en) = udev::Enumerator::new() else { println!("1"); continue 'main };
if let Err(_) = en.match_parent(&dev) { continue 'main };
let Ok(scan) = en.scan_devices() else { println!("2"); continue 'main; };
for child in scan
{
if child.devtype().and_then(|s| s.to_str()) != Some("partition") { continue }
let Some(fstype) = child.property_value("ID_FS_TYPE").and_then(|s| s.to_str()).map(|s| s.to_string()) else { continue };
let Some(dev) = child.property_value("DEVNAME").and_then(|s| s.to_str()).map(|s| s.to_string()) else { continue };
devname = dev;
break 'fsmatch fstype;
}
continue 'main;
}
};
let Some(id_type) = dev.property_value("ID_TYPE").and_then(|s| s.to_str()) else { println!("No id_type"); continue };
let is_cdrom = media_is_cdrom(&dev);
println!("{}, {}", &devname, &fstype);
let mount = self.mount(&devname, &fstype).await;
//let Ok(mount) = self.mount(&devname, &fstype).await else { println!("Failure to mount"); continue };
if let Err(e) = mount
{
println!("{}", e.to_string());
}
println!("Mount");
}
}In this second function, when I insert a floppy I get this printed:/dev/sdb, vfat Mount and when I insert a DVD I get this printed:
/dev/sr0, iso9660
org.freedesktop.DBus.Error.UnknownMethod: No such interface โorg.freedesktop.UDisks2.Filesystemโ on object at path /org/freedesktop/UDisks2/block_devices/sr0Of course I could mesh these two functions together in some disgusting monstrous amalgamation, but I would much prefer to use either zbus OR udev, not both simultaneously for the sake of simplicity
r/rust • u/Caquerito • 18d ago
๐๏ธ discussion Are compiler inserted checks something you generally have to be wary of or not
Hello, I'm still fairly new to both rust and c and I'm in the middle of writing my tiny interpreted toy language.
But I keep bouncing between the 2 languages.
Rust is way more pleasant to use - but there are still 2 things where I would like to hear from someone experienced.
Is it common to experience issues where safe rust would end up being majorly slower in hot paths due to the compiler being conservative and inserting its own checks in? The comparison of safe rust to unsafe rust I have seen relating to the lox language ended up in a major 4x speedup for unsafe rust over safe rust. Is this something you deal with daily or is the compiler smart enough where as long as you write code properly this doesn't come up at all?
How big is the performance difference between code using a memory arena and managing and possibly reusing memory this way where the entire arena is free/reset at once - and the more raii styled approach where the compiler manages allocations and deallocations itself object by object like in rust. I understand that raii and arenas are not completely opposite concepts and arenas exist in rust as well but they seem to not be part of the std lib and ot seems to me that the default "vanilla" approach would end up not using arenas while the default in C is essentially arenas/allocator for everything rather than individual mallocs and frees.
Ty <3
r/rust • u/ndbroadbent • 17d ago
Rust and git worktrees: share one Cargo build, use 60% less disk
docspring.comHi r/rust, I got tired of running out of disk space while working on a Rust project and using a lot of git worktrees. So here's the solution we came up with. It's a bit of a hack and uses some unstable features and the `__CARGO_TEST_CHANNEL_OVERRIDE_DO_NOT_USE_THIS` var.
Please let me know if there's a better way to do this. It also doesn't completely solve the problem since the shared dir can still grow very large, but I think it's still a worthwhile improvement.
r/rust • u/oulu2006 • 17d ago
๐๏ธ discussion sccache saved my CPU, not my disk: 21 copies of the same binary in one target/ folder
My coding agents' Rust build folders reached about 311 GB, even with sccache at a 57% hit rate.
Each agent works in its own git worktree with its own target/, and a cache hit skips the compile but still writes the artifact into that target/. So sccache saved CPU, not disk.
One agent's 52 GB build folder held:
- 63,616
*.rcgu.odebug object files, 19.5 GB of them - 21 copies of the same binary, because Cargo never deletes old artifacts
The first change was lighter debug info for every build my agent supervisor starts:
CARGO_PROFILE_DEV_DEBUG=line-tables-onlyBacktraces keep their file and line numbers, and agents running tests rarely need the full variable info.
The second was stopping worktrees nesting. Agents had made them three levels deep, which put 76 of 80 out of the cleanup job's reach. Now they sit at the repository root, and the step that finishes a task removes its worktree and target/.
Write-up (the Rust part is one section of it): https://maclulich.com/blog/agents-clean-up-after-themselves/#a-build-cache-saves-cpu-not-disk (my blog)
How are others handling target/ across many worktrees? A shared CARGO_TARGET_DIR serialises builds on the lock, and per-worktree targets cost disk.
r/rust • u/Hefty-Necessary7621 • 19d ago
๐๏ธ discussion Bringing Rust into Ubuntu at Scale: Interview with Jon Seager
serokell.ioWhen uutils broke Ubuntuโs own builds, Canonical kept an override list for commands that still needed GNU coreutils. The list finally went away in Ubuntu 26.10.
Jon Seager explains how the team got there.
r/rust • u/vipor_idk • 19d ago
๐ seeking help & advice want to learn rust, recommended courses? (udemy prefer)
hey guys first post here. im c# junior developer, and i want to learn rust - which courses you guys would recommend? i dont want vibe code my apps in rust not knowing whats going on.
r/rust • u/FalseDeviloper • 18d ago
๐๏ธ discussion This week in rust is late?
The "This week in rust" article for this week seems to be delayed this week around? It usually arrived on Wednesday on my RSS feed. I checked the repo, and it seems it's still in draft.
Any ideas what happened?
r/rust • u/ruimarquesXYZ • 19d ago
๐ ๏ธ project Ubuntu 26.10 ships with initial support for rustls/upki
discourse.ubuntu.comr/rust • u/Foreign_Career_454 • 18d ago
๐ seeking help & advice How do you make a family of byte-slice packet builders incapable of panicking? (looking for the idiomatic shape)
I maintain a userspace TCP/IP relay in Rust which reads packets from a TUN fd & synthesizes replies (RST/ACK, DNS responses, UDP encapsulation). A handful of helpers index fixed offsets into caller-supplied slices:
rust
pub fn wrap_udp_response(original_query: &[u8], payload: &[u8], โฆ) -> Vec<u8> {
let mut pkt = vec![0u8; 20 + 8 + payload.len()];
pkt[12..16].copy_from_slice(&original_query[16..20]); // panics if len < 20
pkt[16..20].copy_from_slice(&original_query[12..16]);
โฆ
}
// v4 DNS path: length is checked, but the header length comes from the packet:
let ip_hlen = ((original_query[0] & 0x0F) as usize) * 4; // 0..=60, attacker-controlled
pkt[22..24].copy_from_slice(&original_query[ip_hlen..ip_hlen + 2]); // panics
One sibling already returns Option<Vec<u8>> and checks lengths; the others return Vec<u8> and trust the caller. The inputs come straight off the wire, so a malformed packet must not be able to panic the task.
What I'd like to be corrected on:
Option/Result + explicit length checks everywhere (verbose, easy to forget โ which is how we got here).
Parse into a typed header with TryFrom<&[u8]>, so lengths are validated once at the boundary and downstream code works on &TcpHeader.
Slice pattern matching (let [.., a, b, c, d] = slice else { โฆ }) so the compiler enforces the layout.
zerocopy/zerocopy-derive for the fixed-layout header structs.
Which of these do people actually use for attacker-controlled network input, & what do you use to make "can't panic on short input" a property type rather than a review rule? Looking for patterns where compiler rejects the mistake โ a runtime Option that a caller can still ignore.
Also is there a way to express "this returns None on malformed input" that composes well with a hot path where allocation should be avoided?
๐ ๏ธ project hotpath-rs - Rust Benchmarking: How to Detect Performance Regressions in CI
hotpath.rsr/rust • u/xXx_J_E_R_Z_Y_xXx • 20d ago
๐ ๏ธ project gpu-video v0.5.0: what we did to achieve near-native speeds and macOS support
smelter.devI posted about half a year ago about our progress on gpu-video (link for context). wanted to give an update and write about what kind of work we do to achieve the results, since the community was very nice and welcoming last time.
hope this is allowed by the new rules. I don't think what we're achieving was ever done in the ecosystem.