Array length : size_t

Dicebot public at dicebot.lv
Wed Sep 18 15:16:08 PDT 2013


On Wednesday, 18 September 2013 at 20:46:21 UTC, Namespace wrote:
> D's Array length is currently of type size_t, which means on 32 
> bit it's an uint and on 64 bit an ulong. This is difficult: 
> What if I want to give the length of an array as parameter to 
> some C functions which accepts only an int?
> What is the right/safe way to do this? A cast? Or is there 
> something better?
> I like to avoid cast's if they aren't necessary.

Perfectly safe way is to do run-time range check followed by a 
cast. Maybe using a wrapper:

auto shrinkTo(Target, Source)(Source source)
     if (is(Target : Source)) // is implicitly convertable other 
way around
{
     assert(source <= Target.max);
     static if (is(typeof(Taget.min)))
         assert(source >= Target.min);
     return cast(Target)source;
}

void main()
{
	import std.stdio;
	long a = 50;
	long b = int.max; b++;
	writeln(shrinkTo!int(a));
	writeln(shrinkTo!int(b));
}


More information about the Digitalmars-d-learn mailing list