~skeeto/public-inbox

Re: Dynamic arrays w/ custom allocators

Details
Message ID
<yw5acis3sc47i7lo4nn4i7tfngpfq6dukpw3lpnuxrmy3tt6li@3eyuv4ot6hj4>
DKIM signature
pass
Download raw message
On Thu, May 09, 2024 at 03:28:34PM +0200, Thomas Voss wrote:
> Perhaps I didn’t explain it well, but the Unicode handling and the
> dynamic array stuff are separate parts of my library.  The Unicode
> functions (normalization, casemapping, etc.) do support custom allocators
> (and it works really well) but they don’t use dynamic arrays or anything;
> the dynamic arrays are just another thing I use in almost all of my
> projects so I saw fit to include it so I can stop reimplementing it every
> time.

Ah, that makes a lot more sense. I was under the wrong impression that
the unicode library is using dynamic array for the output.

> I actually tried to use this trick as well, but it falls short the moment
> you’re using a compound type.  Imagine the following example:
> 
>     #define _(x) &(typeof(x)){x}
> 
>     struct foo {
>         int x, y;
>     };
> 
>     struct foo f = {};
>     some_function(_(f)); /* error! */

Also forgot to mention, but I've tried to use trick like this before and
came to the conclusion that it's better to use a single element array
instead of `&(T){..}` for the same reason.

Here's a small demo, works for both integer and the Vec2 struct:

	#include <stdio.h>
	
	#define _(X) ( (typeof(X) [1]){ X } )
	
	typedef struct { int x, y; } Vec2;
	void vprint(Vec2 *v) { printf("%d, %d\n", v->x, v->y); }
	void iprint(int *p) { printf("%d\n", *p); }
	
	int main(void)
	{
		Vec2 v = { 4, 8 };
		vprint(_(v));
		iprint(_(16));
	}

I wasn't sure if the `typeof(X) [1]` part would work or not since I only
tried this with hard-coded types before but both clang and gcc seems to
accept it.

- NRK
Reply to thread Export thread (mbox)