r/rust

lazydiff — a terminal-native diff reviewer with semantic diffs, persistent notes, and 60fps rendering
▲ 25 r/rust

lazydiff — a terminal-native diff reviewer with semantic diffs, persistent notes, and 60fps rendering

When I need to review a lot of ai generated code or code in general, I either open a browser tab and lose my context, or pipe it through git diff and scroll through a wall of red and green that forgets everything the moment I close it. No way to leave notes, no way to jump between files, no way to come back later and pick up where I left off.

So I built lazydiff. The core idea was simple, a diff reviewer that lives in the terminal, remembers state, and actually understands code structure.

The first decision was rendering. I went with ratatui and virtualized scrolling — only the visible rows get drawn each frame. This matters because agent-generated diffs can be massive. The benchmark fixture I test against is an 11k-line Node.js PR diff, and it renders at 60fps with sub-2ms frame times. I didn't want to build something that felt sluggish on real-world diffs.

For syntax highlighting I use tree-sitter(a thing I have been loving for so long now), but the tricky part with diffs is that deleted code needs to be highlighted in its original language context, not just painted red. So lazydiff reconstructs both sides of the file independently and maps highlights back through the diff. Inline diffs tokenize each changed line pair and run LCS to show exactly which words changed, you immediately see the meaningful difference without scanning the whole line.

The part I'm most excited about is semantic diffs. lazydiff uses https://github.com/Ataraxy-Labs/sem, which I open-sourced separately and got a lot of love from the Rust community. Instead of just showing line by line level diffs, it parses changes into semantically meaningful entity graphs for functions added, methods modified, classes moved. You see the structure of your changes and how they connect to each other. This is the same engine behind https://github.com/Ataraxy-Labs/weave, the semantic merge driver I built

The agent workflow is what motivated the whole project. You can leave threaded comments anchored to exact lines questions, instructions, notes and review quite fast, which was the utmost desire of the community. Agents also read them via lazydiff agent list and reply via CLI. The whole review session persists to SQLite locally, so you can close the terminal, come back the next day, and everything is exactly where you left it.

License:MIT Licensed

Open Source Repo: https://github.com/Ataraxy-Labs/lazydiff

u/Wise_Reflection_8340 — 7 hours ago
▲ 36 r/rust

I built a TSO (timestamp oracle) that can work with OpenRaft

I’ve been building distributed compute/database infrastructure in Rust and realized there doesn’t seem to be a clean standalone Timestamp Oracle (TSO) library in the ecosystem (or at least, not a solid one to my knowledge).

So I built one: https://github.com/prisma-risk/tsoracle

The initial use case was OpenRaft-based systems where multiple nodes need:

  • globally ordered timestamps
  • snapshot isolation / MVCC-style semantics
  • deterministic event ordering
  • monotonic IDs
  • causality/version tracking

One thing I specifically wanted was a pluggable consensus layer, so I added an OpenRaft cluster example here: https://github.com/prisma-risk/tsoracle/tree/main/examples/openraft-cluster

The basic idea:

  • OpenRaft elects a leader
  • leader allocates timestamp batches
  • timestamps remain strictly monotonic
  • persistence guarantees survive failover/restart
  • clients fetch timestamps over gRPC

Example use cases: MVCC storage engines, distributed schedulers, event sourcing, CDC pipelines, globally ordered audit logs,...

Welcoming any feedback and contributions 😄

reddit.com
u/sebb_prisma — 5 hours ago
▲ 173 r/rust

Interactive Matrix Visualiser, written in Rust

This is a project to visualise and evaluate matrix transformations / expressions involving 2x2 matrices, 2D vectors, and floats, such as multiplication, inversing, scaling, addition, determinant, dot product and more.

I've had intuition for this kind of thing for a long time, but never really got the chance to share it with people, so I thought as one of my first bigger rust projects, why not give it a go? And then I realised I could put it on a website and share it with everyone else without them having to download an executable, so I compiled it for WASM.

I'd love to see what others think of this and what they might want to add, so contributions, issues and any feedback is completely welcome!

Github

Website (www.fullw.me)

u/fullwoodenshovel — 14 hours ago
▲ 42 r/rust

Perry: native TypeScript compiler to executable, written in Rust, using SWC and LLVM.

github.com
u/zxyzyxz — 13 hours ago
▲ 113 r/rust+2 crossposts

Announcing iceoryx2 v0.9: Fast and Robust Inter-Process Communication (IPC) Library

ekxide.io
u/elfenpiff — 16 hours ago
▲ 594 r/rust

Phonto - GPU-accelerated live wallpapers for Wayland and macOS, written in Rust

I've been using mpv-paper on Hyprland for a couple months but ran into really high CPU usage, so I decided to write my own solution.

Phonto uses GStreamer and EGL to keep the entire decoding and rendering pipeline on the GPU, making much better use of resources compared to CPU-based approaches.

A friend also jumped in and added MacOS support, including playing live wallpapers on the lock screen which was a nice bonus.

Still missing a few things like multi-monitor support but that's coming soon. Other feature requests and contributions are welcome!

GitHub: https://github.com/museslabs/phonto

u/ploMP4 — 20 hours ago
▲ 211 r/rust

What are Rust's hidden implementation details that most devs never see?

I've been working with Rust for couple years now and really love how clean the abstraction layers are compared to other languages I use

The thing that got me thinking about this - every language has those moments where you dig deeper and suddenly realize "oh wait, this thing I thought worked one way actually works completely different under the hood"

Like in Python when you discover that `len()` isn't just a regular method call but uses magic methods because of all the mutability stuff happening behind scenes. Or how C lets you do weird things like `5[array]` instead of `array[5]` because it's all just pointer arithmetic anyway

Rust seems really good at keeping these implementation details hidden from daily programming, but I'm curious what kinds of things are happening under surface that most people never run into

What are some examples where Rust's abstractions start showing their seams if you look close enough? The kind of stuff that works fine 99% of time but then you hit some edge case and suddenly need to understand what's really going on

reddit.com
u/Fluid_Job623 — 1 day ago
▲ 30 r/rust

is Rust's philosophy what I've been looking for ?

Greetings,

I started programming pretty intensively about a year and a half ago. I come mostly from data analysis, so I naturally started with Python / SQL. Which has been great for the first self-built stuff I pushed to production. Users loved what I built, I was enjoying my new full time programming job, etc. (Note that i don't have any CS degree, i'm not gifted, i'm mostly very dedicated / hardworking.)

Then I started to meet "Python inherent problems" in terms of:

  • Space and time complexity
  • Really too many lib dependencies
  • Too much "magic" or "abstraction"

When I talk about abstraction, I mean deeply nested OOP hierarchies where every method call goes through 5 layers of indirection you can't easily trace. I don't mind explicit contracts (I actually love strong typing and schemas), what I dislike is implicit magic: dependency injection containers, hidden decorators, frameworks where you have to "just know" how things wire together. I prefer sequential, traceable code: data pipelines where you can follow the flow from top to bottom. I don't mind complex steps as long as what they do is written in the code.

I never wrote a single line of Rust, but I think I'm starting to understand its philosophy by using Polars (sweet lord I love pl.LazyFrame).

I don't mind complexity, I'd just like to spend time learning something that I'd still be using in the long run. Instead of learning abstract stuff built in a library or a framework that I'll be using in one or two projects and then just forget.

I don't have any "Rust" friends, most of my contacts in programming come from Java / PHP Symfony.

On paper, Rust sounds like a very promising language to learn and master that combines with my natural need of understanding what's under the hood. But maybe i'm writing fantasy in my own mind, so i'd love to know if you understand my needs and if Rust could help me 😄

Thanks

reddit.com
u/Automatic_Creme_955 — 23 hours ago
▲ 52 r/rust

What is rust best for?

I'm starting to learn rust, and I plan to develop a small project as I'm learning, but I'm undecided about which one to do. I already have a list of projects I want to develop in different programming languages, so I want to know what kind of projects rust is better for. If anyone wants to show me a project they've made that could be an example, it would be pretty nice.

I have already learned C/C++ if that helps tou give me better recommendations

reddit.com
u/De5kOfManyThing — 1 day ago
▲ 1 r/rust

Curious about learning Rust

Disclaimer: This is not a where to learn / find learning material post, but rather a question on practicality of using Rust.

I was hoping to hear opinions/anecdotes on your current experience in using Rust in practice.

Context:

I am a Typescript developer who runs and manages a web-dev/web-design agency, have some free-time during the weekends + evenings and wanted to pick up a new programming language (I dove deep for years into TS/JS and ignored everything else).

At first, I've looked at Ruby.

It's pretty close to home (we use AdonisJS) and Rails has proven itself over the years.

However, Loco and Tokio seemed even more interesting, but the counter-point to that - is that the practicality of eventually integrating it in a web-dev shop is a big question mark.

These are the main reasons that I've had in mind for learning Rust:

  1. To build side-projects / hobby-projects / and (if feasible) even internal tooling / plugins for node.
  2. Spread out from Typescript and Node to try something new, broaden my horizons, and sharpen my skills.
  3. We usually work with low-resource servers and rather optimize around the hardware limitations. I've seen people saying on Reddit that Loco and Rust backends are so low on resource use, that it naturally sparked my interest.
  4. Because at times, there are projects where I have to overlook a team - we always NEED a conventions over configurations frameworks (AdonisJS, Rails, Laravel). Loco seems to hit the spot.

Obviously, this is with a very generous timeline in mind and is thinking almost a year in advance. However, there are considerations that I am unable to find a concrete answer on:

  1. Long term maintainability and stability is a big concern. How likely is it for current libraries/frameworks to be abandoned? Chances of major vulnerabilities popping-up (i.e: NextJS every once in a while is too much).
  2. Practicality: Does it make sense to learn Rust to build internal tooling and plugins, when NodeJS itself would suffice?
  3. (Expanding on 2): Would learning Rust improve my current knowledge and capabilities enough to warrant, say, the worst case scenario of never having to use Tokio or Loco or WASM?
  4. Scaling: Not infrastructure or code-wise, rather, finding the relevant talent in GCC, with sufficient capabilities, at a reasonable price?

Apologies for the weird title, I stared at it for around 5 minutes and couldn't come up with a better one.

And thank you in advance, any answer is greatly appreciated.

reddit.com
u/v-and-bruno — 18 hours ago
▲ 3 r/rust

Is it worth Rewriting a high performance Go web crawler in rust for RAG data ingestion? (update)

Appreciate the feedback on my last post about whether I should rewrite the web crawler layer of my local RAG system from Go to Rust. Someone rightfully called me out for not explicitly defining my project goals and looking for a "how" in search of a "why."

To clear up the confusion: this isn't just a textbook learning project for fun (Goal A), nor is it an enterprise application with thousands of active users that I'm terrified of breaking (Goal B).

This is a self-hosted, personal production stack designed to ingest thousands of dynamic, JS-heavy data sources. My operational goals are system reliability, predictable long-term maintenance, and memory efficiency under heavy parallel loads.

Right now, the architecture is split:

Ingestion Layer: Built on Lyzr-Crawl (github.com/LyzrCore/lyzr-crawl). It’s a dedicated open-source Go engine that handles the heavy lifting—headless JS rendering, parallel URL discovery, and clean Markdown extraction so my LLM context windows don't get flooded with raw HTML/CSS bloat.

Core Pipeline Layer: A custom Rust stack utilizing tokio for heavy async coordination, text splitting, chunk embeddings, and streaming updates to a local vector store.

The Go binary is incredibly fast out of the box due to native goroutines, and it successfully saves me from paying insane per-page SaaS scraping API fees. But running a split-language stack introduces a lot of micro-frustrations that are pushing me toward a full Rust unification:

The Maintenance "Why": Debugging across a language boundary sucks. Passing structured data from Go's runtime over IPC/gRPC into Rust's async environment introduces extra serialization overhead and means I'm maintaining two completely different error_handling mental models. If a network timeout or headless crash occurs inside the crawler, bubbling that up deterministically to my Rust logic is clunky.embedding models.

The Resource "Why": Since I run this pipeline locally on a single machine alongside the LLM/Vector store, every megabyte counts. Go’s garbage collector is aggressive under high concurrent I/O, causing random memory spikes. I want Rust's zero-cost abstractions and strict memory predictability so the ingestion layer doesn't choke out the resources needed for local embedding models.

So my specific technical question for the sub remains:

If my goal is long-term stability and rock-solid error handling across the entire pipeline, is it worth writing a custom, production-grade equivalent to Lyzr-Crawl using reqwest + headless_chrome in Rust? Or will the sheer development overhead of rebuilding highly optimized, multi-threaded Go crawling primitives from scratch outweigh any performance and architectural synchronization gains I get from a single-language stack?

Also likes being efficient is good overall

Like I need a good mixture of efficiency and reliability

English isn't my first language as u can tell from my previous post where I messed up some verbs so I first wrote my post in a notepad and then ran it through grammarly this time around

Oh also what would happen if I switch over to watercrawl from lyzrcrawl?

reddit.com
u/MrBemz — 23 hours ago
▲ 3 r/rust

Can Regex crate beat Python's RE?

Hello, I've been learning PyO3 to rewrite some python functions in Rust.

I have one project intensive in regex parsing, and I thought that switching to Rust could bring improvements.

Yet, I haven't been able to beat Python's RE (yes, I know it's written in C). Parsing 1 single line, RE(2 microseconds), PyO3+Rust's regex (3 microseconds).

What I have tried:

* Using OnceLock to emulate Python's re.compile. (As expected this was important)
* Return a tuple instead of a struct. (The same)
* Try adding Rayon and testing in batch. (No luck)

If you had any idea it would be appreciated.

Below is my rust code, the python's side it's just a pytest source file that imports the rust library. I use pytest-benchmark for the benchmarking:

use pyo3::prelude::*;

/// A Python module implemented in Rust.

#[pymodule]

mod sysadmindb_rs {

use pyo3::exceptions::PyValueError;

use pyo3::prelude::*;

use rayon::prelude::*;

use regex::Regex;

use std::sync::OnceLock;

fn log_pattern() -> &'static Regex {

static RE: OnceLock<Regex> = OnceLock::new();

RE.get_or_init(|| Regex::new(r"<(?<prival>[0-9]+)>(?<version>[0-9])?\s?(?<date>([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]+(Z|[+-][0-9]{2}:[0-9]{2})|\w{3}\s[0-9]{2}\s[0-9]{2}:[0-9]{2}:[0-9]{2}))\s(?<hostname>[\w.]+)\s(?<appname>[\w.]+)\s?\[?(?<procid>[0-9-]+)?\]?\:?\s?(?<msgid>(-|\w{2}[0-9]{2}))?\s?(?<structureddata>(\[.+\]|-))?\s?(BOM)?(?<msg>.+)?").unwrap())

}

#[pyclass]

struct Log {

#[pyo3(get)]

version: Option<u32>,

#[pyo3(get)]

prival: u32,

#[pyo3(get)]

date: String,

#[pyo3(get)]

hostname: String,

#[pyo3(get)]

appname: String,

#[pyo3(get)]

procid: String,

#[pyo3(get)]

msgid: String,

#[pyo3(get)]

structureddata: String,

#[pyo3(get)]

msg: String,

}

#[pymethods]

impl Log {

#[new]

fn new(line: &str) -> PyResult<Self> {

match parse_log(line) {

Ok(log) => Ok(log),

Err(_) => Err(PyValueError::new_err("Cannot parse")),

}

}

}

fn parse_log(line: &str) -> Result<Log, String> {

let Some(caps) = log_pattern().captures(&line) else {

return Err("sorry".to_string());

};

Ok(Log {

prival: caps["prival"].parse().unwrap(),

version: caps.name("version").map(|m| m.as_str().parse().unwrap()),

date: caps["date"].to_owned(),

hostname: caps["hostname"].to_owned(),

appname: caps["appname"].to_owned(),

procid: caps["procid"].to_owned(),

msgid: caps["msgid"].to_owned(),

structureddata: caps["structureddata"].to_owned(),

msg: caps

.name("msg")

.map(|m| m.as_str().to_owned())

.unwrap_or_default(),

})

}

reddit.com
u/colombiangary — 20 hours ago
▲ 35 r/rust

Decimal Crates Comparison and Benchmark

I selected several Rust decimal crates, discussed and compared their features, and conducted extensive benchmarking on them.

If you think there are other better decimal crates, feel free to suggest them. We can discuss them or add them to this benchmark comparison.

wubingzheng.github.io
u/hellowub — 1 day ago
▲ 13 r/rust

Built a Shamir Secret Sharing implementation in Rust (splits encryption keys across shards)

I've been working on a Rust implementation of Shamir's Secret Sharing for the past few days. Take a 32-byte encryption key, split it into N shards using polynomial math over a prime field, and require any T of those shards to reconstruct it.

The repo has the full flow: encrypt a file, split the key into shards, then reconstruct and decrypt using only a threshold of them. Uses num-bigint for the field arithmetic and aes-gcm for AEAD encryption.

repo: https://github.com/owlpharoah/shamirsecret

I built this mostly to understand the math properly. The polynomial evaluation and reconstruction logic was trickier than I expected, especially getting the modular inverses right.

Theres still some edge cases and error handling for me to fix and some bugs (with the random coeff sampling) i need to squash.

u/Putrid-Ad-3768 — 23 hours ago
▲ 5 r/rust

[project]holt: an experimental Rust metadata index built around persistent ART blobs, WAL, and checkpointing

Hi r/rust,

I’m the author of `holt`, an experimental storage-engine project written in Rust.

The goal is to explore a metadata index for object-store / filesystem-like namespaces, not a general SQL database. The current design stores keys in an ART-like tree where each durable blob is a fixed-size 512 KiB page. When a blob fills up, a subtree can spill into another blob through a `BlobNode`. Persistence is handled through a WAL, dirty blob tracking, and checkpointing.

Repo: https://github.com/feichai0017/holt

What exists today:

- fixed-size blob/page layout

- ART-style nodes: Leaf, Prefix, Node4/16/48/256, BlobNode

- persistent backend over a packed `blobs.dat` file

- manifest mapping BlobGuid -> physical slot

- WAL replay for logical operations

- write-back buffer manager

- background checkpoint prototype

- range iterator and metadata stats

What I’m trying to get feedback on:

  1. Whether the WAL / checkpoint / dirty-blob protocol is the right direction.

  2. How to evolve spillover into a scalable page split / routing model.

  3. Whether this layout makes sense for object storage or filesystem metadata, where values are small metadata records or external data references.

  4. What failure cases you would test before trusting the design further.

This is not production-ready. I’m mainly looking for storage-engine and Rust systems feedback, especially around crash recovery and large-scale layout.

u/Thick-Bar1279 — 20 hours ago
▲ 233 r/rust

cargo-crap: Finding Untested Complexity in AI-Generated Rust Code

Change Risk Anti-Patterns (CRAP) metric for Rust projects.

minikin.me
u/djminikin — 1 day ago
▲ 33 r/rust+1 crossposts

hsrs -- PyO3-style bindings generator for Haskell

Hey everyone! I recently needed an ergonomic Haskell bindings generator for Rust code and realized one doesn't really exist, so I decided to build my own! hsrs is an ergonomic bindings generator which will take your Rust code, with hsrs annotations, and generate a Haskell bindings for you.

hsrs allows you to take this code

#[hsrs::module(safety = unsafe)]
mod quecto_vm {

/// CPU register identifiers.
#[derive(Debug, PartialEq, Eq)]
#[hsrs::enumeration]
pub enum Register {
  /// First general-purpose register.
  Reg0,
  /// Second general-purpose register.
  Reg1,
}

/// An error produced by the VM.
#[derive(Debug, PartialEq, Eq)]
#[hsrs::enumeration]
pub enum VmError {
  /// Division by zero.
  DivisionByZero,
}


/// A tiny VM with support for addition.
#[hsrs::data_type]
pub struct QuectoVm { registers: [i64; 2] }

impl QuectoVm {
  /// Create a new instance of the VM.
  #[hsrs::function]
  pub fn new() -> Self { ... }

  /// Adds register `b` into register `a` (a += b).
  #[hsrs::function]
  pub fn add(&mut self, a: Register, b: Register) { ... }

  /// Divides register `a` by register `b`, returning an error on division by zero.
  ///
  /// Demonstrates `Result<T, E>` → `Either E T` mapping across the FFI boundary.
  #[hsrs::function]
  pub fn safe_div(&mut self, a: Register, b: Register) -> Result<i64, VmError> { ... }
}

}

and generate

-- | CPU register identifiers.
newtype Register = Register Word8
  deriving newtype (Eq, Show, Storable)
  deriving (BorshSize, ToBorsh, FromBorsh) via Word8

pattern Reg0 = Register 0
pattern Reg1 = Register 1

-- | An error produced by the VM.
newtype VmError = VmError Word8
  deriving newtype (Eq, Show, Storable)
  deriving (BorshSize, ToBorsh, FromBorsh) via Word8

data QuectoVmRaw

-- | A tiny VM with support for addition.
newtype QuectoVm = QuectoVm (ForeignPtr QuectoVmRaw)

-- | Create a new instance of the VM.
new :: IO QuectoVm
new = do
  ptr <- c_quectoVmNew
  fp <- newForeignPtr c_quectoVmFree ptr
  pure (QuectoVm fp)

-- | Adds register `b` into register `a` (a += b).
add :: QuectoVm -> Register -> Register -> IO ()
add (QuectoVm fp) a b = withForeignPtr fp $ \ptr -> c_quectoVmAdd ptr (let (Register a') = a in a') (let (Register b') = b in b')

-- | Divides register `a` by register `b`, returning an error on division by zero.
--
-- Demonstrates `Result<T, E>` → `Either E T` mapping across the FFI boundary.
safeDiv :: QuectoVm -> Register -> Register -> IO (Either VmError Int64)
safeDiv (QuectoVm fp) a b = withForeignPtr fp $ \ptr ->
  fromBorshBuffer =<< c_quectoVmSafeDiv ptr (let (Register a') = a in a') (let (Register b') = b in b')

hsrs will generate both the Haskell side and the necessary C FFI bridges in Rust. The way I achieved rich type-semantics across both implementations is through borsh which serializes types in the Rust-side of things, and then deserializes it on the Haskell end.

For a full example, I'd recommend you look at the QuectoVM example in the hsrs repo.

Prior Art

hs-bindgen

A relatively popular project is hs-bindgen, https://github.com/yvan-sraka/hs-bindgen. My understanding for this crate is that only primitive C types are supported, which did not suit my ergonomics requirements. hsrs supports serializable value types, mapping between String and Text, Vec&lt;T&gt; <-> [T], Result&lt;T, E&gt; <-> Either E T, etc.

Purgatory

I stumbled upon Calling Purgatory from Heaven -- https://well-typed.com/blog/2023/03/purgatory/ -- after writing hsrs, which describes a similar approach to what hsrs employs. The system described in that article outlines two packages -- foreign-rust, https://github.com/BeFunctional/haskell-foreign-rust, and haskell-ffi, https://github.com/BeFunctional/haskell-rust-ffi. From now, I will refer to these two packages as Purgatory. Similar ideas and differences are:

  • Both hsrs and Purgatory use borsh as the underlying serialization scheme for sharing value types across the FFI boundary.
  • hsrs, unlike Purgatory, automatically does Haskell codegen for you from your Rust types. hsrs automatically emits extern functions and automatically generates binding files. We support automatic .hs codegen and have some nifty features:
    • Automatic value-type serialization/deserialization.
    • Automatic Haddock codegen from your Rust codegen.
    • Automatic Derive propagation -- things that you marked as Eq in Rust automatically get Eq in Haskell, etc.

Feedback is very welcome -- I want hsrs to solve for your needs as well as it does for mine. I commit to supporting this project for the next year, or so, to the best of my abilities.


Note: This has been cross-posted on discourse.haskell.org

u/siva_sokolica — 1 day ago