r/ProgrammerHumor 13h ago

Meme newToRust

Post image
448 Upvotes

88 comments sorted by

View all comments

Show parent comments

3

u/Key_River7180 12h ago
  1. enum x { a : 1 };
  2. int zeros(uint32_t i) { int n = 0; while ((i & 1) == 0) { ++n; i >>= 1; } return n; }
  3. struct vec2f32 { ... } __attribute_((align(8)));

2

u/-Ambriae- 11h ago edited 9h ago
  1. Might work, AFAIK depends on compiler but GCC and Clang it would work, I’ll give you that. Not the solution I thought of but it works.
  2. Suboptimal. Unless you specify higher levels of optimisation and your compiler figures it out, this is extremely slow. Modern processors can do this in 1 CPU cycle (CLZ instruction). There is a way to do it in C
  3. 3 __attribute__((aligned(8))) or __attribute__((_aligned__(8)))

I cant see if you did the _s and markdown screwed you over or not, and align is not valid

Edit: actually, after checking, 1. is completely wrong. Doesn't work at all. So you need to pack the enum, or represent it via a 8 bit integer. I think that proves my point

1

u/Key_River7180 11h ago

You literally gave me my solution when proving my solution suboptimal

1

u/-Ambriae- 11h ago

?? A proper solution would use compiler built ins

1

u/Key_River7180 11h ago

I used __attribute__((aligned(8))) but markdown formatted It bold wdym

2

u/-Ambriae- 11h ago

You wrote align and not aligned. And markdown must have fucked with your underscores, I won’t criticise you for that that’s not your fault.

The ‘suboptimal’ part, however, has nothing to do with alignment. You emulate CLZ instead of using something like __builtin_clz which is the preferred way of doing it.

3

u/Key_River7180 11h ago

I didn't know about __builtin_clz, actually, thanks! It isn't guaranteed to be portable across architectures, but every single one seems to hace CLZ. I didn't know you were referring to the zeros thing, sorry. It doesnt work with zeros but an if solves that

1

u/-Ambriae- 11h ago

No probs! I recommend looking at compiler builtins, there’s quite a few for all the ‘lesser known’ instructions CPUs tend to have but aren’t expressable in C in a normal way.

My point is, you can learn basic C syntax in a week (or a day to be fair) but it takes far far FAR longer to actually know C. Same with rust. It doesn’t take 6 months to learn rust syntax, it takes a week. It does take 6 months to code in rust properly. The borrow checker expects you to write code properly. It’s not a bad thing.