3 ms·
In the graphics programming I've done as a hobby, if I have a struct that contains a buffer for an image (say 1024px x 1024px = a buffer array of length 1048576
by brundolf 6y ago
In the graphics programming I've done as a hobby, if I have a struct that contains a buffer for an image (say 1024px x 1024px = a buffer array of length 1048576), and have functions that operate on that buffer, etc, I either have to:
1) Create a Vec (separate allocation)
2) Make 1024 or 1048576 a global constant that every relevant struct and function references directly (whole program must use the same size at once; forget about exposing it as a library)
With const generics I can make all that code generic over the buffer resolution, meaning I can trivially use multiple different versions within the same build, without doing extra allocations, and I could even expose that code as a library for others to use at whatever resolution they wish
- adamch 6y agoThis is, literally, the exact same reason I use const generics. I was so excited when I started using them on Rust beta and could shave off some allocations!
- nullc 6y agoYou're allocating a megabyte on the stack? Does rust have compile time protection against stack overflow? (... and what about recursion? is the stack dynamically resized at runtime?)
- steveklabnik 6y agoWe do not, runtime mitigation only (stack probes). Recursion can blow your stack.
- brundolf 6y agoI'm allocating a megabyte inline. I can put the containing struct on the heap if I need to (I may be doing that; can't remember), but I don't want that to be the concern of the struct itself. For example: what if I decide at some point to create a Vec of this struct? I don't want each of those elements then also putting their internal buffers into separate allocations on the heap, when the Vec itself is already on the heap. I want the struct to be as "flat" as possible, and to only allocate for the sake of the stack as a final step when the use-case demands it
- OrangeTux 6y agoThanks for the answer.