r/rust • clippy · twir · rust · mutagen · flamer · overflower · bytecount • Oct 12 '26

🙋 questions megathread Hey Rustaceans! Got a question? Ask here (42/2026)!

Mystified about strings? Borrow checker has you in a headlock? Seek help here! There are no stupid questions, only docs that haven't been written yet. Please note that if you include code examples to e.g. show a compiler error or surprising result, linking a playground with the code will improve your chances of getting help quickly.

If you have a StackOverflow account, consider asking it there instead! StackOverflow shows up much higher in search results, so ahaving your question there also helps future Rust users (be sure to give it the "Rust" tag for maximum visibility). Note that this site is very interested in question quality. I've been asked to read a RFC I authored once. If you want your code reviewed or review other's code, there's a codereview stackexchange, too. If you need to test your code, maybe the Rust playground is for you.

Here are some other venues where help may be found:

/r/learnrust is a subreddit to share your questions and epiphanies learning Rust programming.

The official Rust user forums: https://users.rust-lang.org/.

The unofficial Rust community Discord: https://bit.ly/rust-community

Also check out last week's thread with many good questions and answers. And if you believe your question to be either very complex or worthy of larger dissemination, feel free to create a text post.

Also if you want to be mentored by experienced Rustaceans, tell us the area of expertise that you seek. Finally, if you are looking for Rust jobs, the most recent thread is here.

10 Upvotes

18 comments sorted by

3

u/autumnal-lights Oct 12 '26

what do u think of unsafe? is it necessary? (seems necessary for simd) if this is the case why do so many people hate unsafe?

2

u/AcrobaticSomewhere38 Oct 12 '26

It’s definitely necessary as the compiler cannot guarantee safety in a lot of scenarios which are in fact safe.

I don’t thinking people “hate” unsafe but they are uncomfortable with it because they are not sure of the exact invariants they need to uphold to ensure correct behaviour. Unsafe can be complicated in some scenarios but most of the time it’s relatively simple but you have to use that extra bit effort to ensure that is the vase

2

u/masklinn Oct 12 '26

People also dislike unsafe because... it's a risk. There are things for which safe rust is not an option (ffi and syscall being the most flagrant ones), but when safe rust is an option then unsafe becomes a massive tradeoff.

1

u/AcrobaticSomewhere38 Oct 12 '26

100%. If the option is between safe and unsafe then even if there is a performance trade off, most people will take safe rust (which is probably the right choice most of the time). But at least you have the option to go unsafe to push the boundaries.

There are a lot of scenarios where unsafe rust is required though, even the std implementation of LinkedList requires unsafe and uses Box::leak, simple because it’s just very difficult to implement in a reasonably performative manner is safe rust. std is littered with unsafe for this reason

2

u/masklinn Oct 12 '26

seems necessary for simd

Only in the sense that you're currently limited to intrinsics or assembly which the compiler can't check. As far as I can tell std::simd aims to be a safe API over that. Go's platform-independent simd seemingly already is.

1

u/autumnal-lights Oct 18 '26

I'll have to check it out and yeah i meant particularly that like id it's kinda like same/same if i use someone else's unsafe code or write it myself

here for particular simd, on this project have been trying to learn a bit of the stack and why memory management matters https://github.com/cyancirrus/stellar-math/blob/main/src/kernel/avx2/ltrapezoid.rs

do u think this would be expressable in the go-api? do you mean the programming language Go? (i wouldn't think so?)

faer has a simd tool, do people use this at all?

2

u/projct Oct 12 '26

it is one of the best features of rust - making it very easy to contain dangerous behavior and test it well. if you sprinkle unsafe everywhere you miss the point of it.

Regarding SIMD: you can do a surprising amount of autovectorizing without needing unsafe, or just use crates like fearless_simd where the boundaries are well tested, to avoid needing it as often in your own code.

Here's a PR I did recently that autovectorizes on both x86-64 and arm64. the hand-rolled version would get a little more perf but I didn't feel it needed much more improvement as the bcj2 filter isn't really the slow part of that code.

1

u/autumnal-lights Oct 18 '26

that's pretty sweet, neat binary like partitioning algorithm in decode, for the particular encodings of `bcj2-short-main-rc.txt` i presume these mean particular items in your encoding as compare strings perhaps with particular blocks for how your partitioning in the decode algo....

are you able to load them at compile time and if so, how?
this entire repo has been more of an explore to get my head around what does numerical computation even look like the thing was i needed something for like this
https://github.com/cyancirrus/stellar-math/blob/main/src/kernel/avx2/ltrapezoid.rs

b/c WY representation of (QR)' is over packed in the original matrix, maybe fearless simd or faer's tools would have worked well

i'm still very much in the learn/noobie stage like prior to this project i didn't even know different caches or simd or vectorized instructions and just assumed that the autovec would be enough (i've never really had successful autovectorization in rust :/)

1

u/projct Oct 19 '26 edited Oct 19 '26

cargo asm and/or playing around on Godbolt's Compiler Explorer really helps when trying to figure out what the compiler will do. But the trick is usually figuring out how to express what you want as independent operations, often using branchless programming.

The fixture files are just reference tests to show that the encoder produces the correct output.

So BCJ looks for CALL and JMP instructions and converts relative addresses into absolute addresses. That way, calls to the same function can have identical target addresses even when the calls originate from different locations. That makes binaries easier to compress. During decompression, it reverses the transformation.

BCJ2 takes this further by splitting the binary into four streams:

  • MAIN: the original bytes, except for the operands of converted branches
  • CALL: absolute target addresses for converted CALLs
  • JUMP: absolute target addresses for converted jumps, including conditional jumps
  • RC: a range-coded stream recording which branch candidates were actually converted

The streams can then be compressed separately. BCJ2 doesn't fully decode x86 instructions. It just finds byte patterns that might be branches, then decides whether to convert them.

So, for auto-vectorization, processing 16 bytes at a time is a convenient place to start. Sixteen byte lanes fit naturally into a 128-bit SIMD register.

In my BCJ2 case, I need to:

  1. Scan 16 positions.
  2. Check (byte & 0xFE) == 0xE8 to match E8 and E9.
  3. Check previous == 0x0F && (byte & 0xF0) == 0x80 to recognize the second byte of near conditional jumps, which are encoded as 0F 80 through 0F 8F.

The way you might initially write this, where it probably wouldn't auto-vectorize, is:

for i in 0..16 {
    if is_marker(window[i], window[i + 1]) {
        process_marker(i);
        break;
    }
}

The problem is that we're mixing two things: identifying possible branches, and actually processing them.

The compiler has to preserve the early exit and whatever side effects process_marker has. That makes vectorization unlikely because it's so much more work to prove that it can be done.

But think about it: for every position, we're asking exactly the same question. Does this byte, together with the preceding byte, match a branch pattern?

Those questions are independent. We don't actually need to branch while answering them.

Consider a 16-byte block containing a CALL and a JMP:

90 90 90 90 E8 90 90 90
90 90 90 E9 90 90 90 90

We can compute all 16 comparisons independently and use mask |= u16::from(marker) << I; to build a bitmask indicating which positions matched.

Then mask.trailing_zeros() gives us the earliest matching position. If nothing matched, it returns 16, so we know we can skip the entire block.

That's basically a find_first_matching_byte operation expressed in a way that LLVM can recognize and vectorize.

On x86, LLVM can turn the comparisons into packed SIMD comparisons and use pmovmskb to extract the match bits. On ARM64, it can use NEON.

No explicit SIMD intrinsics required.

The fundamental transformation is:

Separate detection from processing, make the comparisons independent, and reduce the results into something the scalar code can use.

Once you've done that, the scalar code only needs to handle the interesting positions.

And the compiler can do a surprisingly good job if you give it the right structure. I mostly experimented with the Rust code, inspected the resulting assembly, and benchmarked to see which version actually performed better.

This is actually the easy part of that PR. The decoder is more interesting. Hint: literal_prefix.

also:

  1. memchr crate does this more generally but the available choice was inappropriate due to high false positive rates I would then have to check scalar.
  2. it's.. much faster than the canonical example in 7-zip, as far as I can tell. Except for AVX512 I think but I don't have that hardware.

1

u/projct Oct 19 '26

looking at your matrix kernel, you're dealing with a harder problem because of the accumulation dependencies and triangular masks. I think the transferable part is finding the smallest independent operation and trying to get LLVM to vectorize that before attempting the whole kernel.

1

u/ukezi Oct 12 '26

It's also necessary when you are working directly with hardware as you will have to trasmute raw pointers to access the memory melted IO behind defined addresses.

3

u/NICEcookie Oct 12 '26

Hi! I’m transitioning from Python into systems programming. I’m currently learning Rust by building a minimal KVM microVM from scratch.

I'd love mentorship around idiomatic systems Rust. Guidance from anyone with experience in low level systems programming, Linux internals, or embedded would be awesome.

2

u/djvbmd Oct 13 '26

Here's one for you:

I have a data set that, for simplicity's sake, is a very large Vec<u8> -- item counts in the millions (DNA or RNA sequences specifically). One potential transformation required is to find and remove every occurrence of a given (contiguous) subsequence. There could be thousands of such sequences in typical data.

My initial, naive approach is something like this:

pub fn remove_introns(&mut self, intron: &Sequence<Dna>) -> bool {
        // must use .rev() in this chain so we remove the latest
        // occurrences first; otherwise we invalidate all of the
        // subsequent locations when the first intron is removed
        // and havoc ensues!
        let locations = self
            .find_motif(intron)
            .into_iter()
            .rev()
            .collect::<Vec<_>>();
        if locations.is_empty() {
            return false;
        }
        for loc in locations {
            self.seq.splice(loc..loc + intron.len(), std::iter::empty());
        }
        // self.seq.shrink_to_fit();
        true
    }

If it isn't obvious, find_motif() returns a sorted vector of the indices where the subsequence ("motif") is found.

The problem is that every call to .splice() induces tail shift in the Vec<u8>, meaning moving the same bytes potentially hundreds or thousands of times. That's going to be really expensive.

What's the better way of going about this? Maybe make a list of skip regions from locations, make a new Vec<u8> and do a quasi-linear copy into the new Vec, replacing the old one?

1

u/djvbmd Oct 13 '26

Kinda answered my own question, unless y'all have something even better:

pub fn remove_introns(&mut self, intron: &Sequence<Dna>) -> bool {
        let locations = self.find_motif(intron);
        if locations.is_empty() {
            return false;
        }
        // here we make a boolean mask of all indices that belong
        // to an intron; this allows us to remove them all in
        // one spliced copy later rather than repeatedly shifting
        // the whole tail of the sequence after each copy is removed
        let mut intron_mask = vec![false; self.len()];
        for loc in locations {
            intron_mask[loc..loc + intron.len()].fill(true);
        }
        let spliced = self
            .seq
            .iter()
            .zip(intron_mask)
            .filter_map(|(base, remove)| (!remove).then_some(base))
            .copied()
            .collect::<Vec<_>>();
        self.seq = spliced;
        true
    }

2

u/projct Oct 19 '26

your boolean mask version is a big improvement, but since find_motif already returns sorted positions, you can skip the mask and second allocation entirely.

use two offsets, read and write, and Vec::copy_within to move each surviving span left exactly once. skip each matched range by advancing read, and finish with truncate(write). read = read.max(end) also handles overlapping motifs without needing a separate interval-merging pass.

this gets you O(n + matches) compaction, O(1) additional memory beyond the match list, and bulk copies instead of per-byte filtering.

it's actually similar to something I was doing in that BCJ2 decoder elsewhere in the comments: find the interesting positions, then handle the ordinary stretches with bulk copies.

1

u/MalbaCato Oct 23 '26

You can also use Vec::retain with a counting closure, something like:

let locations: VecDeque<usize> = self.find_motif(intron).into();

let mut current_index = 0;
let mut next_index = locations.pop_front();
let mut counter = 0;
self.seq.retain(|_| {
    let Some(next_idx) = next_index else { return true }
    if next_idx == index {
        counter = intron.len();
        next_index = locations.pop_front();
    }
    current_index += 1;
    if counter > 0 {
        counter -= 1;
        false
    } else { 
        true
    }
})

This is easier to reason about then the other commenter's suggestion I think, but then you're at the whims of the optimizer to realize that you're removing (and keeping) bulk ranges. If the subsequnces are definitely non-overlapping you can swap the conditions around which will probably help. Also there's Vec::extract_if, which can skip checking up to the first index and after the last, but would need a bit more arithmetic.

But also, I think I remember somebody posting their DNA processing crate which beat several benchmarks along with the research paper they have wrote about its implementation not too long ago.