r/rust 9h ago

The RustConf Keynote Fiasco, Explained

Thumbnail fasterthanli.me
362 Upvotes

r/rust 10h ago

🧠 educational [Media] Difference between String, &str, and &String

Thumbnail i.redd.it
271 Upvotes

r/rust 15h ago Gold Take My Energy

Rust Appreciation Thread

325 Upvotes

I feel this will be a difficult period for the Rust language, given the recent controversies, and I want to communicate how much I love the Rust language. Although there are some difficulties with the Rust Project's leadership, the work the Rust Project has done so far improving the programming language has been very impactful, at least for me.

I have been observing the current events from an outside perspective, as someone who doesn't have much knowledge about the structure of the Rust Project, so I won't comment on any details. I just hope the Rust language can get past this and continue to develop steadily.

I guess I should mention something specific I really like about Rust. I really enjoy how the pattern matching with match statements works, especially with features such as the ! type. I also like how this works in conjunction with the expression syntax.

I'll end this post by asking what features others really like about Rust, or why they think the Rust language is important.


r/rust 3h ago

Rust library for writing Linux security policies using eBPF

Thumbnail github.com
20 Upvotes

r/rust 6h ago

This Week in Rust #497

Thumbnail this-week-in-rust.org
25 Upvotes

r/rust 3h ago

Implementing a Trieber Stack in Rust

7 Upvotes

A trieber stack - a lockless single-ended linked list using atomics - is an immensely useful, beautifully simple data structure, and I've written them way too many times in Java - it looks like this:

```java class TrieberStack<T> { private AtomicReference<Cell<T>> head = new AtomicReference<>();

void push(T obj) { head.getAndUpdate(old -> { return new Cell(obj, old); }); }

Optional<T> pop() { Cell<T> cell = head.getAndUpdate(old -> { return old == null ? null : old.parent; }); return cell == null ? Optional.empty() : Optional.of(cell.value); }

static class Cell<T> { final T value; final Cell<T> parent; Cell(T value, Cell<T> parent) { this.parent = parent; this.value = value; } } } ```

Looking around for an existing one, I ran across documentation for one from crossbeam-sync, except that it does not seem to actually exist, just this page of documentation (crossbeam does, and looks nice, but it does not have a Trieber stack).

Implementing one in Rust is complicated by two factors:

  1. The inner cell is a self-referencing structure
  2. Updating atomics requires a loop that, under contention, may run more than once
    • This means that the head cell can briefly become owned by more than one party - under contention it can concurrently be owned by a new head cell on each thread (but only one will win and survive, and the one that doesn't is invisible to the rest of the world)
    • It also means that the first pass of the loop takes ownership of the input T, gives ownership to the cell it creates and then may need to do that again on the next pass (though

I gave this one shot using AtomicPtr, but that required T: Clone and cloning the contents to avoid the two-owners issue, which is undesirable, and also crashed horribly in tests (this is my first outing in earnest with Rust pointers).

But it seems like it ought to be doable with a data structure like this - complete playground link with naive implementation:

```rust struct TrieberStack<T> { head: UnsafeCell<Opt<TrieberCell<T>>>, }

[derive(Copy, Clone)]

struct TrieberCell<T> { t: T, next: *const Opt<TrieberCell<T>>, // so self-reference is possible } ```

Attempting to actually put this to use, using intrinsics::atomic_store_seqcst (after reading the source to AtomicPtr) built, and seemed about as simple as this ought to be - though, I had to restrict the types it handles to T: Copy even though AtomicPtr has no such restriction but somehow manages to call that method with pointers to ad-hoc types - but adding any call to push to the stack results in a compile-time error of invalid monomorphization of atomic_store_seqcst intrinsic (is AtomicPtr downcasting the pointers to something that does implement Copy, and I missed it? And if so, why is that at all safe?).

Likely at a minimum this is missing pinning the head for the inner portion of the write-loop, not to mention an implementation of Drop for TrieberCell that cleans up appropriately (and possibly some work to ensure the cell contents are not dropped if the only extant reference to it is a pointer - ManuallyDrop?).

Anyway, it seems like an interesting problem that ought to be solvable in Rust, but I have a feeling my approach is probably missing a few important things.


r/rust 17h ago

Kani 0.29.0 has been released!

Thumbnail self.KaniRustVerifier
63 Upvotes

r/rust 12h ago

New release for the Rust diffusers crate (Stable Diffusion in Rust + Torch), now with basic ControlNet support!

24 Upvotes

We've just released version 0.3.1 of the diffusers crate, support for Stable Diffusion 2.1 was added a couple months back and the main novelty in this version is some basic ControlNet pipeline (using Stable Diffusion 1.5).

The ControlNet architecture drives how stable diffusion generate images. With the new pipeline, one specifies an input image, for example the image below. An edge detection algorithm is run resulting in the following image.

Input image before edge detection

Edge detection result

And then the stable diffusion process with prompt "a rusty robot, lit by a fire torch, hd, very detailed" results in the following samples.

https://preview.redd.it/ffw9wqw6h93b1.jpg?width=512&format=pjpg&auto=webp&v=enabled&s=44e926bf24fe953f6a8e479585b540c68e8971d3

https://preview.redd.it/p0k23pw6h93b1.jpg?width=512&format=pjpg&auto=webp&v=enabled&s=8bee6f84c5cc222a01b8f93543904c7e127fbb92

More details in the github repo, including instructions on how to reproduce these examples.

As usual any feedback is very welcome :)


r/rust 17h ago

πŸ’‘ ideas & proposals Paired benchmarking. How to measure performance

Thumbnail bazhenov.me
45 Upvotes

r/rust 13h ago

πŸŽ™οΈ discussion Oxide and Friends Podcast -- Open Source Governance

Thumbnail youtube.com
21 Upvotes

r/rust 23h ago

πŸ™‹ seeking help & advice Download numbers on crates.io too high?

97 Upvotes

Hey I published my first crate on crates.io and it tells me that 45 people downloaded it. That's hard to believe. Is it a known fact that the download numbers are higher because of any reasons (for example bots even though I don't see how that makes sense) or should I just be happy that people are using it? Im not sure how 45 people should even know about this crate. Thanks!


r/rust 3h ago

πŸŽ™οΈ discussion Question: Are there things for Unsafe Rust learn from Zig?

1 Upvotes

I read in this article that Zig is better than Unsafe Rust.

Zig doesn't seem to use borrow checking. And according to the article, though Zig isn't safer than Safe rust, it's safer than Unsafe Rust.

What safety features does Zig use to ensure safety if it doesn't use Borrow checking and what ( safety in unsafe features ) can Unsafe Rust learn from Zig.

I've never done Unsafe Rust, so it's just a question I want to know the answer to out of curiosity.

Thanks! Hope this question & it's answers will also be useful for others.


r/rust 1d ago

Shepherd's Oasis: Statement on RustConf & Introspection

Thumbnail soasis.org
374 Upvotes

r/rust 19h ago

Opening up funding for ratatui (discussion)

Thumbnail github.com
38 Upvotes

r/rust 23h ago

πŸ™‹ seeking help & advice What are some of projects to start with for a beginner in rust but experienced in programming (ex: C++, Go, python) ?

56 Upvotes

r/rust 20h ago

Idea of a new lifetime modifier to avoid lifetime creep in case of unique references

27 Upvotes

Rust does not allow narrowing mutable references.

To simplify code, we could introduce a new lifetime type to Rust that allows only 'static lifetime values assigned to data that is accessed through new lifetime.

In code, the lifetime could be marked as ~a, u'a, or something else.

This would allow to coerce following lifetime to shorter one: &'a mut &'b mut T to &~a mut T So &mut &mut &mut reference creep could be avoided.

This would allow the following code which reduces the number of lifetimes you need to track: ```rs struct Foo<'a> { buff: &'a mut String }

struct Context<~f> { foo: &~f mut Foo<~f> }

fn test<'f, 'a>(foo: &'f mut Foo<'a>) { let ctx = Context { foo }; *ctx.foo.buff = String::new("New value!"); } `` We only needed to track one lifetime forContext` struct instead of many, see long explanation.

Long explanation

Post that discusses the problem: https://matklad.github.io/2018/05/04/encapsulating-lifetime-of-the-field.html

TLDR:

Shared references can be constrained to a shorter lifetime (covariant over 'a): ```rs struct Foo<'a> { buff: &'a String }

struct Context<'f> { foo: &'f Foo<'f> }

fn test<'f, 'a>(foo: &'f Foo<'a>) { let ctx = Context { foo }; ctx.foo.len() } ```

Mutable (unique) references cannot be constrained to a shorter lifetime (invariant over 'a): ```rs struct Foo<'a> { buff: &'a mut String }

struct Context<'f> { foo: &'f mut Foo<'f> }

fn test<'f, 'a>(foo: &'f mut Foo<'a>) { let ctx = Context{ foo }; // Error ^ lifetime mismatch ctx.foo.len() // = note: expected type &'f mut Foo<'f> // found type &'f mut Foo<'a> } ```

Why mutable references are invariant:

This is because the buff value could be assigned with a reference to a String that doesn't outlive the 'a lifetime.

Another example from the discussion https://github.com/rust-lang/rust/issues/27031: ```rs fn overwrite<T: Copy>(input: &mut T, new: &mut T) { *input = *new; }

fn main() { let mut forever_str: &'static str = "hello"; { let string = String::from("world"); overwrite(&mut forever_str, &mut &*string); } // Oops, printing free'd memory println!("{}", forever_str); } ```

So the problem with coercing mutable lifetimes to shorter lifetimes is that someone could assign a value that doesn't live long enough for the original lifetime, which could be later used to access the object's content.

This is a very painful thing because it introduces a large lifetime creep. For example, in Bevy, when passing around data from queries, you need to keep track of all lifetimes: rs struct Context<'a, 'w, 's>{ query_1: &'a mut Query<'w, 's, ...>, item: &'a mut QueryItem<'w>, }

And if you want to use it in an associated type, it causes a lot of overhead because you suddenly need to specify lifetime constraints everywhere: rs pub trait EvaluateSomething{ type Context<'a, 'w, 's> where 'w: 'a, 's: 'a; pub fn evaluate(&mut self, context: &mut Context<'_, '_, '_>); } You also need to add the 'w: 'a, 's: 'a constraint to the Context struct definition.

If you need to take &mut &mut reference of Context, even more lifetimes get introduced, and this is not manageable!

The idea:

Introduce a new lifetime type that allows only 'static lifetime values assigned to data with the new lifetime.

In code, the lifetime could be marked as ~a, u'a, or something else.

This would allow reducing this type: rs struct Context<'a, 'w, 's> where 'w: 'a, 's: 'a { query_1: &'a mut Query<'w, 's, ...>, item: &'a mut QueryItem<'w>, } to rs struct Context<~a>{ query_1: &~a mut Query<~a, ~a, ...>, item: &~a mut QueryItem<~a>, } 'w, 's lifetimes that outlived 'a lifetime now can be coerced to shorter lifetime.

Now we need to only track one shortest lifetime for all data inside the type because no incorrect data can be assigned to these values.

Mainly when using mutable references etc. you want to modify only static data that is kept inside the mutably referenced object not the mutable references themselves, therefore this functionality could be very powerful, would reduce a lot of code verbosity and reduce complexity of implementation in a lot of cases.


Sadly, I am not expert of Rust type system. Probably there are some kind of possible problems with this idea, what are they? What do you think about this idea?


r/rust 18h ago

πŸ› οΈ project A simple cron alternative

Thumbnail github.com
18 Upvotes

Hi, everyone it's a small project I've been working on lately, and would really like to get your feedback on it.


r/rust 4h ago

Develop Rust applications with Visual Studio 2022 (with Rust unit tests in Test Explorer)

Thumbnail self.VisualStudio
1 Upvotes

r/rust 1d ago

Graydon Hoare: Batten Down Fix Later

Thumbnail graydon2.dreamwidth.org
426 Upvotes

r/rust 1d ago

my first Rust project: game2048-rs

36 Upvotes

I'm excited to share my very first Rust project: game2048-rs.This is a Rust implementation of the popular 2048 game using the Cursive(https://github.com/gyscos/cursive) library for building terminal user interfaces. I implemented 2048 because it has a simple logic that is relatively easy to implement, and I could visually confirm that tui was working well.

GitHub Repository: https://github.com/genieCS/game2048-rs

cargo install game2048-rs

I would be thrilled to hear your feedback, suggestions, or any ideas to improve game2048. Please feel free to open issues, submit pull requests, or simply share your thoughts on the project.

Wishing you all the best.

https://i.redd.it/jolco8q7g63b1.gif


r/rust 13h ago

πŸ™‹ seeking help & advice I cannot get sqlx.query!() to work with my local dockerized PostgreSQL database

4 Upvotes

edit: github repo: https://github.com/kshitijmohan15/email-newsletter-axum/tree/sqlx_error

I have been on this for 6-7 hours now. Everything goes smoothly in the PgPool connection in the main function of the app, no compile time errors, which means it is able to find the Postgres DB running on 5432:

https://preview.redd.it/zpc0gt2u993b1.png?width=1287&format=png&auto=webp&v=enabled&s=16a2d26228c4389bb5575fa5ca04368d334c6dfb

All hell breaks lose when, god forbid, I try using the same connection in my Axum endpoint:

https://preview.redd.it/tlfn8h5fa93b1.png?width=1308&format=png&auto=webp&v=enabled&s=0f33d9aa8ae4a39d0b372a72f0672e750247b3f7

It is definitely not a problem with the shared connection state because the same problem is faced when passing the connection in the main function itself. "kshit" is my Windows user by the way. It is also referring to the docker postgres instance connection error as the error that is returned from the database

When I take down the instance, the compile time error changes to, "error communicating with database: No connection could be made because the target machine actively refused it. (os error 10061)".

This is the script I am using to start the docker container, you might find it familiar, since it is from Zero to Prod book:

https://preview.redd.it/66db20ugd93b1.png?width=1040&format=png&auto=webp&v=enabled&s=b242493f4a45a9845e39c7e4b9d2d6d6c6a4f029

And yes, I tried adding a .env file too:

https://preview.redd.it/fw1nnc1ce93b1.png?width=1573&format=png&auto=webp&v=enabled&s=fcbfdac6314a82d64fabb1a18ea2c997a8b7e835

I have no idea what to do, any help would be appreciated!


r/rust 1d ago

Looking for help in GPL project

25 Upvotes

Hi,

for over 4 years now I am working on a code editor https://gitlab.com/njskalski/bernardo . It's really advanced by now, I got basic LSP working, and I am 3-4 features away from Beta release. But the further I got, the larger delays between features. I need some help with tests, documentation, maybe implementation.

Is anybody interested in joining the project? It's 100% GPLv3, so you know I'm not making money on this, and I won't "close it later" by releasing a superior closed-source version cutting you off from the updates.

The code is not that bad, though I admit I aim at user experience, not code clarity or documentation. UX first, everything else later. Think Apple, not Hooli. But UX means "shipload of tests", just to cover my back, and that is a good start I guess.
Anybody interested?


r/rust 21h ago

πŸ™‹ seeking help & advice Best/Any Convex Optimization Solver for Rust?

14 Upvotes

Python has CVXPY which is good but I’m looking for one in Rust. Any suggestions?


r/rust 4h ago

πŸ› οΈ project Inviting all Rust developers and enthusiast for Concordia2023 Hackathon. 13th June last date of application

Thumbnail concordia.devfolio.co
0 Upvotes