Skip to content

Add macro nob_da_swap to swap elements in a dynamic array #61

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

auribuo
Copy link

@auribuo auribuo commented Apr 30, 2025

I implemented a da_swap macro to swap two elements by index in a da. I think swapping is something that might be useful in more than one case (especially when using nob.h also as library and not only as build tool) and as such it would be a nice feature to come with nob.

Instead of using a temp variable I chose to use the da itself as temporary storage. The main advantage of this comes in a nice UX where the caller does not have to supply the type of the elements in the array.

There is obviously a bit of an overhead when calling da_append but in my opinion it's totally negligible.

@rexim
Copy link
Member

rexim commented May 15, 2025

Tbh, how often do you really need to swap specifically elements of an array unless you are implementing a yet another sort? A more general swap that swaps two variables would be much more useful. But it's much harder to implement without using any special extensions isn't it? :)

@auribuo
Copy link
Author

auribuo commented May 16, 2025

That makes sense. In my use case, I needed da_swap for a "deletion that keeps the data" so basically, you remove something, but by incrementing count it's still there (My use case). It can also easily help when needing to reverse an array. Honestly though both use cases are kinda rarely needed when using nob to build. They are a convenience more needed when using nob in the main code, though that would be the same with a general swap I guess?

If we want to have a swap for two variables, my first approach (I still need to test if it really works) would be to do it similarly to the da_swap where we could use the nob_temp_alloc with sizeof then do a memcpy. That would lead to a similar UX but also have a bit of an overhead (which imo is totally fine). Let me know what you think of this, and if you find it a good idea, I can work on the implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants