@safe(bool)

bitwise via Digitalmars-d digitalmars-d at puremagic.com
Thu Aug 17 09:32:20 PDT 2017


This came to mind while working on a set of containers.

@safety often comes with a performance cost. For example, any 
container that wants to give out a range or iterator has to have 
a ref-counted or GC allocted payload to ensure safety. In a 
high-performance context though, the performance hit may be 
unacceptable.

It's fairly easy to make a container that toggles it's 
implementation between  ref-counted, GC, or raw pointers/arrays, 
based on a template parameter. This would allow a single 
container to be used in both performance sensitive and safe 
contexts (in theory). The only problem would be the lack of 
actual @safe annotations on the container, as they would only be 
applicable to one variant, and otherwise cause a compile-time 
error.

One solution could be this:

struct Container(T, bool safetyOn = true)
{
	static if(safe)
		RefCounted!(T[]) data;
	else
		T[] data;
		
	auto opSlice() @safe(safetyOn) {
		return Range(data, 0, data.length);
	}
}

A similar solution could be applied to @nogc as well.



More information about the Digitalmars-d mailing list