r_rust🦀 – Telegram
r_rust🦀
62 subscribers
565 photos
65 videos
36.1K links
Posts top submissions from the rust subreddit every hour.

Powered by: @reddit2telegram
Chat: @r_channels
Download Telegram
How do you handle std/nostd in Cargo workspaces?

I am working on a dual-platform library (Tokio + Embassy). Feature unification kills me - when my std adapter enables `std` on the core crate, it leaks into my no
std Embassy builds even with default-features = false.

My fix: Makefile that builds each crate individually with explicit --package and --no-default-features. Also build.rs noscripts that panic on invalid feature combos.

Is everyone doing this? Are there any better patterns?

https://redd.it/1pvlqic
@r_rust
I got tired of writing bad code repeatedly, so I learned Rust to do it only once and made a concurrent processing library - sandl

I'm a game designer and programmer - Sometimes (i.e., every time) I need to do some Monte Carlo simulations for esoteric dice/card systems. Of course, I could copy and paste from older files, but that's an annoying workflow to change up when I come up with new random number generators. To solve this and other problems, I made this:

Repo, Crate. It's called sandl and it's pronounced just like you think it is. The name stands for "Slices and Layers", the key abstraction of the program.

Per the docs, it's a library for building parallel execution engines with dependency management, type-safe method dispatch, and event observation. Layers define behavior via methods, Slices provides args for each method they want to call.

This way, I can configure several thousand RNG workflows, simulate them all concurrently and collect the results neatly and fast-ly.

I'm also currently using it to make a TypeScript code generator so I don't have to write bog-standard CRUDslop routes and DTOs ever again. I also used it to solve the One Billion Rows Challenge a couple of months late.

It's my first real Rust code base and it has some real stinky hacks in it, but I'm overall happy with the result - Being able to make something actually useful (for myself) with a new language has been a nice surprise. I published it because, maybe, it's useful to you, too.

https://redd.it/1pvt6ax
@r_rust
Idiomatic Iterators and their performance

So, I've been going through rustlings and once I've reached the iterators section, the questions came in.

I have C and Go background, I also like digging into "how many instructions does this operation takes? is it optimal?", and I would like to clarify a couple of things related to Rust's iterators.

Here's the first question: what exactly output I will get compared to the for loop in this case? Will this iterate over a map again on each method call, or iterators are pretty smart to wrap into a single loop when compiled?

fn countcollectioniterator(collection: &HashMap<String, Progress>, value: Progress) -> usize {
    // collection is a slice of hash maps.
    // collection = { "variables1": Complete, "from_str": None, … },
    //               { "variables2": Complete, … }, …
    // ---
    // let mut result = 0;
    // collection
    //     .iter()
    //     .foreach(|m| result += m.values().filter(|&&v| v == value).count());
    // result
    // ---
    //
    // or
    //
    // ---
    collection
        .iter()
        .flat
map(|m| m.values().filter(|&&v| v == value))
        .count()
}

What about "Idiomatic Iterators" in the noscript of this post: how would you write these two pieces of code (one above and the one that is below)? Which variant would be more idiomatic in Rust, or all of them are being respected the same way?

fn main() {
let word = "hello";

let mut chars = word.chars();
let result = match chars.next() {
None => "None".toowned(),
Some(first) => {
let mut s = first.to
uppercase().collect::<String>();

s.pushstr(chars.asstr());

s
}
};
println!("{result}");

// or

let mut chars = word.chars();
let result = match chars.next() {
None => "None".toowned(),
Some(first) => {
first
.to
uppercase()
.chain(chars)
.collect::<String>()
}
};
println!("{result}");
}

And the last question: which variant of ones provided above is optimised the best under the hood? Does a call to `chain()` method requires some additional allocations that are less performant than a simple vector of characters? (I think this way because I deem Iterators are more complicated data structure than Vectors.)

Thanks y'all in advance!

https://redd.it/1pvzmsa
@r_rust
4 months later: update on my journey toward the Rust compiler team

Hi everyone,

some of you might remember my post from a few months ago where I wrote about contributing full-time to the Rust compiler, being close to team membership, but struggling to make it financially sustainable while living in Russia

A lot has happened since then, so here is a short update and a link to a longer blog post with details, numbers and answers to common questions

TLDR

I kept contributing consistently (171 contributions so far)
I could not relocate or take full-time offers
I officially became a member of the Rust compiler team
I returned to my previous job teaching IT to kids - it gives me enough financial stability and time to keep working on the compiler

Full blog post: https://kivooeo.github.io/blog/first/

If you are interested, feel free to ask questions in the comments

I want to collect questions that come up here and add them to the blog over time (feel free to ask in DM as well), especially if they might help others who want to contribute to the open source or find themselves in similar life situations

Thanks again to everyone who supported me back then. Your comments helped more than you probably imagine

Happy holidays and happy New Year to all of you! <3

https://redd.it/1pw5i9y
@r_rust
Looking for feedback - TUI text editor toy project

I wrote a TUI text editor with regex-based syntax highlighting, basic theming, and some Vim motions. It is very incomplete and not intended to be actually used; it was more a learning experience for getting to know Ratatui and a more OOP approach with mutable state.

I'd like to know what was done right and what is absolutely unidiomatic in the code.

https://github.com/AfkaraLP/sexditor

https://redd.it/1pwbep2
@r_rust
I built an immutable, content-addressed Python environment manager in Rust

px (Python eXact) is an experimental CLI for managing Python dependencies using immutable, content-addressed environment profiles (no venv).

👉 https://github.com/ck-zhang/px

It is now in alpha, feedback is welcome :)



https://redd.it/1pwawtm
@r_rust
I built a simple terminal Snake game in Rust

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

I wanted to build a simple project while reading the book, so i decided to go for the classic choice
Link to the github repo

https://redd.it/1pwccjc
@r_rust
Pow(x, n) leetcode passes rust playground but time line exceeded in leetcode console

Hey guy I have a leetcode here that fails in the leetcode console but passes in rust playground. I have provided two links below.

I'm doing a recursive / exhaustive algorithm ... honestly as I write this I do not know my time complexity ... will probably think about that after I press save here.

Could anyone lend a hand?


rust play ground

leet code

https://redd.it/1pw8x76
@r_rust
My Rust Rewriting Journey

I replaced my C++ only Coding Journey with Rust

Like for example i have so far 2 Programs in C++ that i have both finished (well the second is still getting maintained so technically not finished yet lol)

but man does Rust feel so much better!

For my Non Game Dev Projects ive basically decided to switch from C++ to Rust and since its made such a Huge Jump in recent Years im very Proud to be Part of the Rust Community now!

https://redd.it/1pwmq8a
@r_rust
What is the current recommended way to install Emacs with Rust?

I searched for Rust and Emacs, and I found something that recommended installing rustic. When I tried installing rustic, Emacs told me that "rustic is unavailable". Now I find a post somewhere that tells me that rustic is obsolete and no longer maintained.

So, how do I get Emacs to work with Rust these days (and presumably with Rust Analyzer). I'm looking for something hands-on, like some lines to paste into my ~/.emacs, please.

No doubt, I'm not the first person to ask this, but I cannot find anything recent and actionable.

https://redd.it/1pwq1b7
@r_rust
pdfium-bind: easiest way to add PDF rendering in your Rust app

I got frustrated trying to figure out a way to ship Kiorg with PDFium embedded so its PDF preview feature can just work out of the box in all environments.

That experience resulted in **pdfium-bind**. A high-level pdfium binding that embeds a pre-built PDFium library into your application directly when static library is not available.

I hope some of you would find this useful as well.

https://redd.it/1pwryik
@r_rust
Small wordle project I made!

So I just started learning rust, and am just about to get to tests, but to consolidate everything that I have learnt so far, I decided to write a wordle clone! It includes colored text for each letter, accurate letter position guides (Green if correct, yellow if its in the word, with correct number of letters although there may be an issue with guessing something with letter pattern xxllx when the word has the pattern xxxlx (replace x with anything) as it checks in order, and would wrap the u8 I use round. There are of course solutions, but I can't think of one), both lowercse an upper case support, validation of it being in the alphabet and 5 letters long!
```rust
use std::{collections::HashMap, io};
use colored::*;

struct Guess {
word: String,
guess_info: ([char;5],HashMap<char,u8>)
}

impl Guess{
fn new() -> Guess{
let mut input = loop{
let mut input= String::new();
io::stdin().read_line(&mut input).expect("FAILED TO READ LINE!");
input = String::from(input.trim());
println!("{}",input);
if ! input.chars().all(char::is_alphabetic){
println!("Please only use letters in the english alphabet!");
continue;
}
if input.len() != 5{
println!("Please only use words of length 5!");
continue;
}
break input;
};
input = input.to_uppercase();
let guess_info = get_word_info(&input);
Guess { word: input, guess_info}
}

fn compare(&self, word:&str) -> [i32; 5]{
let word_info = get_word_info(&word);
let mut result = [0,0,0,0,0];
let mut word_char_count = word_info.1.clone();
if word_info.0 == self.guess_info.0{
result = [2,2,2,2,2];
}
else {
for i in 0..5{
let remaining_ref = word_char_count.get(&self.guess_info.0[i]);
let mut remaining: u8;
match remaining_ref{
Some(_t) => {
remaining = *remaining_ref.unwrap() as u8;
if remaining > 0{
if word_info.0[i] == self.guess_info.0[i]{
result[i] = 2;
} else{ result[i] = 1;}

remaining -= 1;
word_char_count.insert(self.guess_info.0[i], remaining);
} else{ result[i] = 0; }
},
None => {
result[i] = 0;
}
}
}
}

result

}

fn display(&self, result: [i32; 5]){
let mut display = ["".red(),"".red(),"".red(),"".red(),"".red()];
for i in 0..5{
let letter: &str = &self.word[i..i+1];
match result[i]{
2 => {display[i] = letter.green()},
1 => {display[i] = letter.yellow()},
_ => {display[i] = letter.red()}
}
}
println!("{}{}{}{}{}", display[0], display[1], display[2], display[3], display[4])
}
}
fn main() {
// init
const WORDS: [&str; 7] = ["HELLO","WORKS","TESTS","ADIEU","AUDIO","CRANE","PLANE"];
let word = WORDS[rand::random_range(0..WORDS.len())];

println!("----------WORDLE-----------");
println!("-----Terminal Edition------");

let mut win = false;
for _ in 0..6{
let guess = Guess::new();
let result = guess.compare(word);
guess.display(result);
if result == [2,2,2,2,2,]{
win = true;
break;
}
}

println!("---------GAME OVER---------");
if win{
println!("{}","You Win!".bright_cyan());
} else{
println!("{}","You Lose :(".red());
println!("The Word Was: {}",word.yellow())
}
println!("----------------------------")



}

fn get_word_info(word:&str) -> ([char;5], HashMap<char,u8>){
let mut chars = [' ',' ',' ',' ',' '];
let mut i = 0;
let mut chars_count: HashMap<char, u8> = HashMap::new();
for chara in word.chars(){
chars[i] = chara;
let char_count = chars_count.entry(chara).or_insert(0);
*char_count += 1;
i += 1;
}
(chars, chars_count)
}
```

This is the file and I am very happy with it for a first project with minimal docs usage (I used them to double check hashmaps, and I used SO for checking if its alphabetical). Any way I could improve (other than fixing that one issue, which for now I might just use i8, and just deal with the fact that players might think that there is an extra of a letter)

EDIT: switching to i8 does not change anything, IDK why I thought it would

https://redd.it/1pwsq9n
@r_rust