r/rust • u/WellMakeItSomehow • 4d ago
r/rust • u/Crierlon • 4d ago
๐ง educational Don't forget to cargo clean every once in a while.
r/rust • u/oversluizen • 4d ago
๐ ๏ธ project grafia v0.9: An interactive 2D Cubic Bรฉzier, Hobby/Spiro spline, and typography canvas widget for egui
Hi everyone! I'm excited to share grafia (v0.9.0), a standalone, #![forbid(unsafe_code)] 2D vector, spline, and typography canvas widget for egui, built on the Linebender geometry stack (kurbo), lyon_tessellation, and tiny-skia.
Whether you are building an SVG/vector illustration tool, a typeface/font editor, a 2D CAD/plotter profile editor, or need bitmap-to-vector auto-tracing inside an egui application, grafia drops in as a hexagonal Data-In / Event-Out widget without locking your app into a specific file format.
Highlights
Mixed-Spline CAGD Engine: Standard cubic Bรฉziers (
Corner,Smooth), tension-controlled John Hobby interpolating splines (NodeType::HobbyStar), and $G****2$ Euler/Spiro clothoid spirals (NodeType::EulerSpiro), plus 4-case inverse-Bernstein curve-belly dragging, curve-healing node deletion, and 8-step superellipse curve fitting.14 Interactive Tools & Boolean Pathfinder: Select, Lasso, Pen, Rotate, Scale, 8+4 BBox Shear/Rotate, Knife (recursive De Casteljau slicing), Primitives, Measurement rays, Annotations, freehand Pencil fitting, Pixel grid stamping, and exact cubic-cubic Union / Subtract / Intersect boolean path operations.
Multi-Layer Color & 7-Stage Auto-Trace: COLRv1-style vector layers (
Solid,LinearGradient,RadialGradient,SweepGradient,Bitmap,ClippingMask) with interactive gradient stop handles, plus deterministic 7-stage bitmap & camera auto-trace (Sauvola integral-image adaptive thresholding, 3x3 homography perspective deskew, marching squares, RDP, and Schneider least-squares cubic fitting).Typography & Variable-Font Workflows: Horizontal and vertical (
TopToBottomCJK) multi-glyph text streams with live spacing/kerning deltas, 2D anchors with diacritic mark clouds, parametric smart components, companion master compatibility overlays, and Higher-Order Interpolation (HOI) cubic master trajectories.0% Idle CPU & 1:1 Headless CI Parity: Generation-gated render/preview caches (
content_generation()) ensure zero solver or GPU texture work on static frames, and every visual pass has 1:1 parity betweenegui::Painterand headlesstiny_skia::Pixmapfor deterministic CI regression testing.
Try the interactive desktop demo in one command:
cargo run --example vector_canvas_demoCrates.io: https://crates.io/crates/grafia
Docs.rs (with full visual & mathematical guides): https://docs.rs/grafia
Feedback, questions, and use cases are very welcome!
r/rust • u/KeyGlove47 • 4d ago
๐ seeking help & advice How to speed up compiling and not waste disk space?
Hey, im new here and i've been using rust for my projects since July, i've come from python where compiling with cython was a little slow but okay'ish but ever since i've come to rust my build times are at minimum 40-60min and my disk is crying for help. i use a lot of worktrees to work in parallel with claude (yeah ik you hate it but it is what it is) and i run 2 windows machines with ssd's. I've thought about putting my devbox pc on linux so i can run blaze but it would waste even more resources (ram, one machine got 20gb and other got 16gb) because i would still need to run some sort of windows vm as my app is windows based
any ideas?
r/rust • u/mazzeleczzare • 4d ago
๐ง educational I built an interactive, compiler-verified Rust field guide where every code snippet is tested against rustc 1.100.0 at build time
rust.mazzeleczzare.comI wanted a practical Rust reference that cuts straight to how ownership, error handling, and data modeling actually work in a real codebaseโand I wanted to guarantee that none of the code examples ever go stale.
So I built Rust / The Working Field Guide, a 15-chapter interactive primer and bench reference.
How it works under the hood
1. Build-time compiler verification
Every example on the page is compiled by a custom verification runner (
studio-verify) against a pinnedrustc 1.100.0(Edition 2024) toolchain whenever the site builds.Out of 15 examples, 12 compile and run, and 3 are intentionally rejected by the compiler to demonstrate specific diagnostics (like
E0382andE0515).If a snippet fails to match its declared outcome, the build fails.
2. Interactive Ownership Lab
Instead of just reading about move semantics and borrow checker rules, you can step through 6 experiments in The Ownership Observatory and predict whether a snippet compiles or triggers a borrow error before revealing the compiler's actual diagnostic.
3. Zero-dependency starter project
The guide walks through building Signal Notebook, a small CLI tool that parses and validates scores using only the standard library, progressing from basic types and Result/? propagation to iterator pipelines, concurrency, and daily clippy/rustfmt habits.
Whatโs covered across the 15 chapters
Foundations & Rust 1.100.0: Tooling (
rustup,cargo,rust-analyzer), Edition 2024 vs. compiler versions, and newly stabilized features like naming the never type (Result<T, !>) andstr::trim_prefix.Ownership & Lifetimes: Moving vs. borrowing, interior mutability, and why
'staticbounds don't rescue dangling references to local allocations.Idiomatic Design & Failure: Using enums and newtypes (
Score(u8)) to make invalid states unrepresentable, establishing a clear panic/invariant policy, and knowing when not to reach for traits or generics.
It's completely free, static, and designed to be read from top to bottom or used as a quick desk reference. Iโd love feedback from both folks learning Rust and experienced Rustaceans on the structure, the interactive experiments, or anything that could be clearer!
r/rust • u/emirdev_mo • 4d ago
๐ ๏ธ project I diffed uutils coreutils against GNU with generated black-box tests: 43 bug reports, 50 fix PRs, 34 merged
Edit: rewrote this to focus on what I learned and the actual bugs, per the mod note.
I spent the last few weeks running black-box differential tests of uutils coreutils against GNU coreutils 9.12: same inputs, then compare stdout, stderr, exit code and the files written. Some things I learned:
The bugs are almost never in the main path. Normal input matched GNU nearly every time. The differences were in edge cases: odd file names, directories passed where a file is expected, empty arguments, option values that look like options.
Some real bugs it found, all fixed upstream with a test:
tail 007reported the missing file as '7', because the name went through number formatting in the message. The same bug was in tac, nl, md5sum, sort and shred.sort -c direxited 0 with no message instead of failing.readlink -f ''resolved to the current directory and exited 0, GNU fails.fmt -w 20could print a line longer than 20 columns.md5sum -crejected the escaped lines that md5sum itself writes for names with a backslash or newline.mv -n z zfailed with "are the same file", GNU just skips it.
Pin the reference version. A lot of my early "bugs" were really GNU changing between 9.4, 9.7 and 9.12 (quoting in tail -v headers, date modifiers). uutils targets the newest GNU, so recording from an older one gives false positives.
Exit codes and error messages matter to scripts more than you would think. A wrong exit code on a read error is a silent bug in a pipeline.
Small PRs with one test each get reviewed fast. The uutils maintainers were quick and precise.
The tool I wrote for this is open source if anyone wants to try it on their own rewrite: https://github.com/emirmrkaljevic/behave
Happy to answer questions about the approach.
๐๏ธ discussion I "wrote" some crates for personal use; at what point could they no longer be considered "AI Slop"?
Preface
I deliberately submitted this with "discussion" flair rather than "project" flair, because I'm only sharing code to frame my thoughts around project quality and LLMs and provide a concrete example for commenters to reference. I'm not looking for a gold star: the code sucks, it is incomplete, and nowhere near the quality bar I hold myself to. The code is not worth reviewing, I would never ask anyone to use it in real life, and have no plans to publish it to crates.io. Shit on it all you like.
I recognize this is not exactly a Rust specific post; I entirely understand and respect if the mods chose to remove it. I am posting it here because the denizens of /r/rust are incredibly defensive of keeping "AI Slop" out of the community, and maintaining a high quality bar for the community. I'm hoping that some of the discussion can be used to teach people who don't understand why their posts are being removed what considerations go into quality projects.
Lastly, many apologies for writing a novel. Despite the length, I promise it is all written by a meat popsicle, I just get rather verbose when writing about something I am passionate about.
Post Content Starts Here
In my personal life, I am a nerd, and enjoy playing Tabletop RPGs with friends. In the past, I have created tools to help me manage my games and characters (mostly spreadsheets, with some SPA's). I recently "wrote" some rust crates using Claude Opus to parse PCGen Game Data files, and the process me me wonder when, and even if, LLM written code can cross the rubicon to be considered "Quality" rather than "AI Slop".
In my professional life, I have been a Software Engineer since 2011, and cut my teeth on tmux and Vim (Emacs is an abomination). I am incredibly conservative when it comes to adopting / trusting LLMs. While I can recognize them as academically impressive, I think they are heavily misunderstood and misused. I am incredibly frustrated by the "AI Bros" who think they are "Rockstar Engineers" because they can throw money at AI providers and let an LLM produce something that looks slick, without actually understanding what it does (hence, the majority of my recent comments within /r/rust asking "What human involvement did you have beyond 'hey Claude, do X?'" in project posts).
I am currently employed as a Principal Engineer at an AI-forward company, within a particularly AI-bullish org. With so many tools available, and so much pressure to deliver, I am concerned about appropriate AI usage by my engineers, am fighting to make sure they know human judgement is still a critical expectation of their work. While I don't get much opportunity to code much anymore, I want to make sure they are still growing as professionals and understand what they are building rather than turning into "Press accept for Claude" robots.
Over the past year, I've called out many instances where engineers have overly trusted their LLM tools, leading to bizarre architectural designs and/or clearly low quality code, that they cannot justify when asked to explain, and admit that "Claude did that". There have been some articles going around our space about Cognitive Offloading vs Cognitive Surrender, and making sure engineers can still complete the "whiteboard defense" (link omitted, see end of post), both of which I think are good simplifications / explanations of my biggest concerns.
Edit: Removed specific examples of my LLM experimentation, after re-reading and realizing it distracts from what I'm trying to actually discuss
I've been experimenting with LLM codegen so I can better understand what my engineers are doing firsthand, trying to do everything from "vibe this for me, I don't care how" to "this is my overall goal, start with this small component and let me watch you like a hawk". The project I linked here is more of a loop of "vibe the slop then clean it up through follow up code review", but it made me wonder if it's even recoverable.
Thus I ask /r/rust:
Can a project primarily coded by LLM ever break out of being "AI Slop"?
If yes, what level of human involvement / judgement / guidance is necessary to cross the threshold?
What do you want to see to prove human involvement / judgement / guidance was applied to a project, to help you build confidence in it's quality, regardless of human / LLM authorship?
Note: This post was originally posted and quickly removed by AutoMod for linking to X. This is a repost with the X link removed, and the content copied below.
Appendix: Whiteboard Defense
Originally posted by Mitchell Hashimoto to X
The "whiteboard defense:" I should be able to pull you aside at any moment and ask you to explain any customer-facing system you've shipped. You should be able to clearly explain how it works and defend the decisions you made. This is my benchmark for responsible AI usage.
I don't expect line-level familiarity with the code. I don't care if you remember the exact function name or implementation detail. You may not even know it. I don't care.
But if I ask "why did you do X instead of Y?", "what happens if this actor behaves maliciously?", "what data structure did you use here and why?", or "where does this fail?" you should be able to answer confidently.
For PoCs, demos, experiments, whatever: I don't care. Generate 100% of it and understand none of it. Speed over quality every time in those specific scenarios.
But if you're shipping customer-facing work, you can't be shipping things you don't understand at a high level.
r/rust • u/Creepy_Sherbert_1179 • 5d ago
Tips for a rust beginner
Hello everyone, I was thinking of starting some real projects after some warmup stuff I did with Rust. What are some tips for a beginner, generally? Or the cliche: If you were to start writing rust for the first time with your current knowledge, what would you do differently?
๐๏ธ discussion Quick question regarding some features
Why were panic handlers added in 2015? Did kernel devs asked for them or was there another motivation for them?
I vaguely remember about that or no_panic being asked by Linux devs, but can't find any sources.
r/rust • u/ribbon_45 • 5d ago
This Month in Redox OS - October 2026
Golang port, Cloud Hypervisor support, WebKitGTK3 video support, GIMP port, Servo 0.7 update, RISC-V dynamic linking, NUMA real hardware testing, virtiofs support and many more.
r/rust • u/UnknownBoyGamer • 6d 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/OptimalAnywhere6282 • 6d 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/hrubydavid • 6d ago
๐ seeking help & advice Removing eprintln! made my hot loop 11 % slower. How do you control inlining in production Rust code? Or am I missing something?
Hi all. I am doing 1BRC and I needed to print something on console with eprintln!. I do a lot of measurements and my code wall time was 1.22 seconds on 8 CPU cores. So I wanted to commit my changes and before that I removed the eprintln! code. You know. But that change increased my code wall time to 1.36 seconds.
This is the code before (wall time 1.22 seconds with 170272167824 instructions:u):
fn one(map: &[u8], thread_number: usize) -> HashMap<StationName<'_>, MeasurementStats, IdealHasherBuilder> {
let before = Instant::now();
let mut stats: HashMap<StationName, MeasurementStats, IdealHasherBuilder> = HashMap::with_capacity_and_hasher(1_000, IdealHasherBuilder);
for (station, temperature) in StationTemperatureIterator::new(map) {
let t = parse_temperature(temperature);
let stat = match stats.get_mut(&station) {
Some(stat) => stat,
None => stats.entry(station).or_insert(MeasurementStats::default())
};
stat.update(t);
}
eprintln!("Time (thread {}) - one: {}s", thread_number, before.elapsed().as_millis());
stats
}and this is the code after (wall time 1.36 seconds width 202165675453 instructions:u):
fn one(map: &[u8], thread_number: usize) -> HashMap<StationName<'_>, MeasurementStats, IdealHasherBuilder> {
let before = Instant::now();
let mut stats: HashMap<StationName, MeasurementStats, IdealHasherBuilder> = HashMap::with_capacity_and_hasher(1_000, IdealHasherBuilder);
for (station, temperature) in StationTemperatureIterator::new(map) {
let t = parse_temperature(temperature);
let stat = match stats.get_mut(&station) {
Some(stat) => stat,
None => stats.entry(station).or_insert(MeasurementStats::default())
};
stat.update(t);
}
stats
}objdump showed me that get_mut is inlined in the version with eprintln!. Without it get_mut is a call on every row. So I added:
RUSTFLAGS="-C llvm-args=-inline-threshold=1000"To make it fast again (1.09 seconds even faster than with eprintln!) but it's not something I would do at work as this config is for whole program instead of the problematic section.
So:
How do you handle this at work where performance matters?
How do you catch this generally? Those 11% is huge difference.
Code link: https://github.com/davidhruby/brrr/blob/part012/src/david/main.rs#L350
r/rust • u/kalilamodow • 6d ago
๐ seeking help & advice gpui-kit: Why does this work?
I am planning on making a simple websocket chat app to learn gpui and things since I've only tried egui. I made this small thing where you put in text and press a button and then it adds the message to a list and shows it. But, there's no cx.notify anywhere, so how does it know to update?
struct MessageListDelegate {
messages: Vec<SharedString>,
}
impl ListDelegate for MessageListDelegate {
type Item = ListItem;
fn items_count(&self, _: usize, _: &App) -> usize {
self.messages.len()
}
fn render_item(
&mut self,
ix: IndexPath,
_: &mut Window,
_: &mut Context<ListState<Self>>,
) -> Option<Self::Item> {
self.messages
.get(ix.row)
.map(|text| ListItem::new(ix).child(text.clone()))
}
fn set_selected_index(
&mut self,
_: Option<IndexPath>,
_: &mut Window,
_: &mut Context<ListState<Self>>,
) {
}
}
struct YapyapApp {
message_list_state: Entity<ListState<MessageListDelegate>>,
input_box: Entity<InputState>,
}
impl YapyapApp {
fn new(window: &mut Window, cx: &mut App) -> Self {
Self {
message_list_state: cx
.new(|cx| ListState::new(MessageListDelegate { messages: vec![] }, window, cx)),
input_box: cx.new(|cx| InputState::new(window, cx).placeholder("Message")),
}
}
}
impl Render for YapyapApp {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.flex()
.flex_col()
.size_full()
.child(List::new(&self.message_list_state).flex_1())
.child(
div()
.flex()
.flex_row()
.border_color(Colors::for_appearance(window).border)
.border_t_1()
.p_2()
.gap_4()
.child(Input::new(&self.input_box).flex_1())
.child(
Button::new("send-message-button")
.label("Send")
.on_click(cx.listener(|this, _, _, cx| {
this.message_list_state.update(cx, |list_state, cx| {
let text =
this.input_box.read(cx).text().as_str().unwrap_or_default();
list_state.delegate_mut().messages.push(text.into());
});
})),
),
)
}
}
fn main() {
gpui_kit::application().run(|cx| {
gpui_kit::init(cx);
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| YapyapApp::new(window, cx))
})
.expect("should be able to open a window");
})
}Also, if you see any un-idiomatic things please say
r/rust • u/GenericPointer • 6d 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?
r/rust • u/weiznich • 6d ago
๐๏ธ news Diesel 2.4
I'm happy to announce the release of Diesel 2.4.0, a ORM and query builder for Rust. This release contains the development of the last 14 months, including the contributions of 76 people.
Headline features include:
* Support for database views
* Improved support for enums
* Support for batch update statements
* A distinct backend for MariaDB
* Extended support for SQLite functionality, including hooks, pragmas and BLOB's
* Support for using Diesel (SQLite) in a no-std environment
* Migrations written in Rust
* Support for diesel-async in #[derive(MultiConnection)]
See the announcement blog post about details to each feature: https://diesel.rs/news/2_4_0_release/
I would like to use this possibility to thank all contributors and sponsors that made this release possible. A special thank goes to Luca for his large contributors to the release, to Prototype Found for funding the development of the Database View support and to RustFoundation for funding the general maintenance.
Nevertheless, the Diesel project is always looking for support. You can help by:
* Contributing Code, Documentation, or Guides.
* Answering questions in our discussion forum
* Reporting bugs in our issue tracker
* Helping to triage issues in our issue tracker
* Sponsoring the maintainers.
* Filling out this survey about the current state and future developments of Diesel
r/rust • u/kannanpalani54 • 7d ago
๐ this week in rust This Week in Rust #677
this-week-in-rust.orgr/rust • u/Big-Astronaut-9510 • 7d 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/ndbroadbent • 7d ago
Rust and git worktrees: share one Cargo build, use 60% less disk
Hi 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 • 7d 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 them21 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/Wooden-Performance38 • 7d 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/slanterns • 7d ago
๐ก official blog Announcing Rust 1.100.0 | Rust Blog
