Thread overview
Turn GC allocated string into a scoped heap allocation
Dec 13, 2018
Per Nordlöw
Dec 13, 2018
Per Nordlöw
December 13, 2018
How do I turn the GC-allocation in toLower() to a scoped heap allocation together with toLowerInPlace() in

void f(const scope const(char)[] expr)
{
    import std.uni : toLower;
    loweredExpr = toLower(expr); // temporary
    // use loweredExpr as key in hash table
}

when `loweredExpr` is used as a temporary inside `f`?
December 13, 2018
On 12/13/18 4:38 AM, Per Nordlöw wrote:
> How do I turn the GC-allocation in toLower() to a scoped heap allocation together with toLowerInPlace() in
> 
> void f(const scope const(char)[] expr)
> {
>      import std.uni : toLower;
>      loweredExpr = toLower(expr); // temporary
>      // use loweredExpr as key in hash table
> }
> 
> when `loweredExpr` is used as a temporary inside `f`?

If you use loweredExpr as a key in a builtin AA, then you need to make it a heap allocation, because the GC cleans up AAs.

-Steve
December 13, 2018
On Thursday, 13 December 2018 at 13:46:47 UTC, Steven Schveighoffer wrote:
> If you use loweredExpr as a key in a builtin AA, then you need to make it a heap allocation, because the GC cleans up AAs.
>
> -Steve

I only need it for lookup not for storage.
December 13, 2018
On 12/13/18 9:06 AM, Per Nordlöw wrote:
> On Thursday, 13 December 2018 at 13:46:47 UTC, Steven Schveighoffer wrote:
>> If you use loweredExpr as a key in a builtin AA, then you need to make it a heap allocation, because the GC cleans up AAs.
>>
> I only need it for lookup not for storage.

I guess what I meant is that the GC will clean up the AA. But I forgot that you could free the key early, as long as you never use the AA again.

However, if you are using it ONLY to lookup, and not store keys, this means you have to take care not to assign values to new keys.

The right way to do this is to check if the key exists when doing the lookup, and then idup'ing the key before you store it.

something like:

if(auto v = tmpKey in AA)
{
   // use *v to deal with the value
}
else
{
   // store a new value
   AA[tmpKey.idup] = newValue;
}

If you are never storing, then you can probably use the .get feature of AAs.

If you want to scope destroy, you have to be wary that toLower will return the original string if it's already lowercase.

Something like:

auto tmpKey = s.toLower;
auto toFree = s is tmpKey ? null : tmpKey;
scope(exit) GC.free(toFree.ptr);

-Steve