Is mimicking a reference type with a struct reliable?

Steven Schveighoffer schveiguy at yahoo.com
Sat Oct 16 09:35:35 PDT 2010


On Sat, 16 Oct 2010 12:23:50 -0400, Denis Koroskin <2korden at gmail.com>  
wrote:

> No, it doesn't use capacity, it uses length as a capacity instead:
>  void ensureCapacity(T)(ref T[] array, size_t minCapacity)
> {
> 	size_t capacity = array.length;
> 	if (minCapacity < capacity) {
> 		return;
> 	}
> 	
> 	// need resize
> 	capacity *= 2;
> 	
> 	if (capacity < 16) {
> 		capacity = 16;
> 	}
>  	if (capacity < minCapacity) {
> 		capacity = minCapacity;
> 	}
>  	array.length = capacity;
> }
>  The usage pattern is as follows:
>  dchar[] toUTF32(string s, dchar[] buffer = null)
> {
> 	size_t size = 0;
> 	foreach (dchar d; s) {
> 		buffer.put(size, d);
> 	}
>  	return buffer[0..size];
> }

Oh, ok.  So you are keeping track of the length in a local variable.  That  
certainly works for specific applications, but Appender is supposed to be  
generally useful.

Like I said, An unsafe appender could be added to phobos which does the  
same.

-Steve


More information about the Digitalmars-d mailing list