Skip to content

Instantly share code, notes, and snippets.

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save graphitemaster/45561d0387911c1995c07653fde79b72 to your computer and use it in GitHub Desktop.
Here's an example. I have this data structure which represents a rectangle
struct Rectangle {
uint32_t x, y, w, h;
};
I have myself an unspecified size of these in a vector.
Vector<Rectangle> rectangles;
There is this other data structure which represents a rounded rectangle, looks something like this.
struct RoundedRectangle {
uint32_t x, y, w, h, roundness;
};
And I'd like to "transmute" my rectangles vector to be RoundedRectangle instead, but all with a roundness of 1. I happen to know that my Vector<Rectangle> is being allocated from some block of memory and can do in-place reallocations. I also know that the size of Rectangle is 16 and the alignment is 4, I also know that the size of RoundedRectangle is 20 and alignment is 4. If my array has N Rectangle then the data store needed to make it into RoundedRectangle needs to be expanded by N*4 bytes. So in-place I can reallocate the store, now all I have to do is write a simple routine that shifts 4 bytes from N*16th byte of every Rectangle forward to make room for the roundness field and then just set it to 1, which I know I can do with the move of the data rather than writing a full 4-byte integer of value 1 there, because I know that during the move all I have to do is mask away the single bit needed to represent a value of 1 in a uint32_t, such that it'll have a value of 1 after the move.
The simple way of doing it is to just copy everything over, write the full 4-byte field, dispose the other vector and then you're good to go, except a) that has twice as much memory utilization to do, b) it fragments my allocator (what if I have this on a bump point allocator?) c) and it's just not how I solve problems, generally.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment