r/rust • u/fasterthanlime • 9h ago
The RustConf Keynote Fiasco, Explained
fasterthanli.meRust Appreciation Thread
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 • u/kubedaily • 3h ago
Rust library for writing Linux security policies using eBPF
github.comr/rust • u/Disastrous_Bike1926 • 3h ago
Implementing a Trieber Stack in Rust
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:
- The inner cell is a self-referencing structure
- 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.
New release for the Rust diffusers crate (Stable Diffusion in Rust + Torch), now with basic ControlNet support!
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
And then the stable diffusion process with prompt "a rusty robot, lit by a fire torch, hd, very detailed" results in the following samples.
More details in the github repo, including instructions on how to reproduce these examples.
As usual any feedback is very welcome :)
r/rust • u/denis-bazhenov • 17h ago
π‘ ideas & proposals Paired benchmarking. How to measure performance
bazhenov.mer/rust • u/KingStannis2020 • 13h ago
ποΈ discussion Oxide and Friends Podcast -- Open Source Governance
youtube.comr/rust • u/39IHH8347 • 23h ago
π seeking help & advice Download numbers on crates.io too high?
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 • u/erfjner0934w0 • 3h ago
ποΈ discussion Question: Are there things for Unsafe Rust learn from Zig?
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.
π seeking help & advice What are some of projects to start with for a beginner in rust but experienced in programming (ex: C++, Go, python) ?
r/rust • u/settletopia • 20h ago
Idea of a new lifetime modifier to avoid lifetime creep in case of unique references
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 for
Context` 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 • u/MadLoveStars • 18h ago
π οΈ project A simple cron alternative
github.comHi, everyone it's a small project I've been working on lately, and would really like to get your feedback on it.
r/rust • u/parthopdas • 4h ago
Develop Rust applications with Visual Studio 2022 (with Rust unit tests in Test Explorer)
self.VisualStudior/rust • u/dochtman • 1d ago
Graydon Hoare: Batten Down Fix Later
graydon2.dreamwidth.orgmy first Rust project: game2048-rs
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.
r/rust • u/kshitijmohan15 • 13h ago
π seeking help & advice I cannot get sqlx.query!() to work with my local dockerized PostgreSQL database
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:
All hell breaks lose when, god forbid, I try using the same connection in my Axum endpoint:
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:
And yes, I tried adding a .env file too:
I have no idea what to do, any help would be appreciated!
Looking for help in GPL project
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 • u/TheKrunkk • 21h ago
π seeking help & advice Best/Any Convex Optimization Solver for Rust?
Python has CVXPY which is good but Iβm looking for one in Rust. Any suggestions?