Code generation tricks

JS js.mdnq at gmail.com
Sun Jul 21 10:24:09 PDT 2013


This seems to be a somewhat efficient string splitter

http://dpaste.dzfl.pl/4307aa5f

The basic idea is

for(int j = 0; j < s.length; j++)
	{
		mixin(ExpandVariadicIf!("??Cs[j]??s[j..min(s.length-1, j + 
%%L)]::", "d", "
			if (r.length <= i) r.length += 5;
			if (j != 0)
			{
				r[i++] = s[oldj..j];
				oldj = j + %%L;
			}
			else
				oldj = %%L;
		 j += %%L; continue;", T));
		
	}

ExpandVariadicIf creates a series of if's for each variadic 
argument. There is some strange formatting(just some crap I threw 
together to get something working) but it boils down to 
generating compile time code that minimizes computations and 
lookups by directly using the known compile time literals passed.

IMO these types of functions seem useful but ATM are just hacks. 
Hopefully there is a better way to do these sorts of things as I 
find them pretty useful.

One of the big issues not being able to pass a variadic variable 
to a template directly which is why the formatting string is 
necessary(You can pass the typetuple to get the types and size 
but not the compile time values if they exist.

I think int this case a variadic alias would be very useful.

alias T... => alias T0, alias T1, etc....
(e.g. T[0] is an alias, T.length is number of aliases, etc...)

In any case, maybe someone has a good way to make these things 
easier and more useful. Being able to handle variadic types and 
values in a consistent and simple way will make them moreful.




More information about the Digitalmars-d-learn mailing list