What's the fastest way to check if a slice points to static data

Stefan Koch via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Jun 24 06:11:02 PDT 2017


On Saturday, 24 June 2017 at 12:22:54 UTC, Petar Kirov 
[ZombineDev] wrote:
> [ ... ]
>
> /**
>  * Returns:
>  * A pointer to a null-terminated string in O(1) time,
>  * (with regards to the length of the string and the required
>  * memory, if any) or `null` if  * the time constraint
>  * can't be met.
>  */
> immutable(T)* fastStringZ(T)(return immutable(T)[] s) @trusted
> if (isSomeChar!T)
> {
>     if (isStaticallyAllocated(s) && s.ptr[s.length] == 0)
>         return s.ptr;
>     else
>         return null;
> }
> ---
>
> (Without `isStaticallyAllocated`, `fastStringZ` may *appear* to
> work but if you pass the pointer to e.g. a C library and that
> library keeps it after the call has completed, good luck 
> tracking
> memory corruption if the slice was pointing to automatic/dynamic
> memory - e.g. static array buffer on the stack or GC / RC * heap
> allocation.
> * malloc or custom allocator + smart pointer wrapper)

Please note that not all static immutable strings have to be null 
terminated.
It is possible to generate a string at ctfe which may appear the 
same as string literal, but does not have the \0 at the end.


More information about the Digitalmars-d-learn mailing list