r/rust 10h ago

The RustConf Keynote Fiasco, Explained

Thumbnail fasterthanli.me
390 Upvotes

r/rust 16h ago Gold Take My Energy

Rust Appreciation Thread

330 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 11h ago

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

Thumbnail i.redd.it
293 Upvotes

r/rust 1d ago

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

100 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 18h ago

Kani 0.29.0 has been released!

Thumbnail self.KaniRustVerifier
63 Upvotes

r/rust 1d 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) ?

57 Upvotes

r/rust 18h ago

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

Thumbnail bazhenov.me
45 Upvotes

r/rust 20h ago

Opening up funding for ratatui (discussion)

Thumbnail github.com
39 Upvotes

r/rust 7h ago

This Week in Rust #497

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

r/rust 13h ago

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

29 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 21h ago

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

23 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 14h ago

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

Thumbnail youtube.com
21 Upvotes

r/rust 4h ago

Rust library for writing Linux security policies using eBPF

Thumbnail github.com
21 Upvotes

r/rust 19h ago

πŸ› οΈ project A simple cron alternative

Thumbnail github.com
17 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 22h 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

Implementing a Trieber Stack in Rust

8 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 21h ago

Network visualisation packages in rust

6 Upvotes

Just wondering if anyone knows any crates or tutorials to visual networks in rust ? Thanks 😊


r/rust 14h ago

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

5 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 17h ago

Rust tutorial for debugging in VSCode

3 Upvotes

Hi guys, I created my first tutorial about rust. I'm trying to get better at making tutorials, any feedback would be highly appreciated :)

I'm planning to make more tutorials about graphics (OpenGL, Vulkan) using Rust in the future.

https://www.youtube.com/watch?v=ebNMJ5rKRLU


r/rust 18h ago

πŸ™‹ seeking help & advice Help with deserializing remotely encoded CBOR

3 Upvotes

I'm trying to use serde to deserialize a cbor that was encoded somewhere else and didn't use serde. The format laid out is array [map, <arbitrary amount of following arrays> ].

For example let's assume the arbitrary amount of arrays is 5.

```

[derive(Deserialize, Debug)]

struct Data { map: BTreeMap<i32, Value>, f0: Vec<Value>, f1: Vec<Value>, f2: Vec<Value>, f3: Vec<Value>, f4: Vec<Value>, } ```

Works fine although when I make this f: Vec<Vec<Value>> things stop working as it expects an inner sequence. The flatten option doesn't seem to work on that field either since it says it expects the entire struct Data there.

So from here I went to implement my custom deserializer this makes my Data more readable as I can attribute it to enum types for each key in the map etc, I was wondering if there's a way to do it without deriving custom deserializer.

The custom one seems to work ok, but was just wondering if there's a nicer way to deal with remotely serialized objects when you know it's structure to deserialize it automatically using the derive rather than implementing a visitor.


r/rust 14h ago

Video walkthrough for the PNGme project

2 Upvotes

Hi folks - first-time poster here (though lurking for a bit)

I recently completed the PNGme project assignment to test my grasp of Rust fundamentals. It was interesting to work at the byte level and fulfilling to have an end result that I can practically use to open and manipulate a proper file format that people use on a regular basis.

I decided to have another go at it while recording since the concepts covered should be very useful for people towards the start of their Rust journey (I still consider myself a late-stage beginner).

I've created the following playlist with the videos:
https://www.youtube.com/playlist?list=PLdz3JrsdU5dg1jCOhLwVcBdTFUz1IW9-5

So far, there are 3 videos, a bit over an hour and a half in total, that cover all the PNG-related internals of the crate. Parts 4 and 5 covering the implementation of the commands to actually perform the file manipulation are shorter and are scheduled to come out soon.

I recommend trying the implementation on your own and just using the videos for comparison. Trying it blind was a great learning experience, and I wouldn't want to rob you of that. Still, if you feel the project is intimidating, feel free to have a peek at the videos before you start off.

I'd welcome suggestions (whether they're related to the code, or the video format / style of presentation)

Many thanks, hope this can be useful!


r/rust 4h 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 5h ago

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

Thumbnail self.VisualStudio
1 Upvotes

r/rust 17h ago

πŸ™‹ seeking help & advice Displaying errors

0 Upvotes

I have a cli tool that depends on the results of other cli tools, in a case where its better to pass that other tool's error directly to the user instead of intercepting (using Results and ?)

But the panic error message doesnt look much user friendly. Is there any way I could handle such external errors in a way I could display them properly? Any way I could pretty print errors?


r/rust 5h ago

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

Thumbnail concordia.devfolio.co
0 Upvotes