[fpc-devel] 2 Ideas for generic TDictionary and other hash containers
Stefan Glienke
sglienke at dsharp.org
Thu Mar 27 16:05:39 CET 2025
It does not violate the contract imho.
In a TDictionary<K,V> it would return a pointer to V which is valid because it either retrieved an existing entry or added a new one with default(v).
I implemented this a while ago in Spring4D roughly following the API that was introduced in .NET some time ago.
I called it GetValueOrAddDefault and recently renamed it to GetValueRefOrAddDefault. It has three overloads:
function GetValueRefOrAddDefault(const key: TKey): Ref<TValue>.PT; overload;
function GetValueRefOrAddDefault(const key: TKey; const defaultValue: TValue): Ref<TValue>.PT; overload;
function GetValueRefOrAddDefault(const key: TKey; const defaultValue: TValue; out exists: Boolean): Ref<TValue>.PT; overload;
Ref<TValue>.PT is ^TValue - I had to write it that way because this method is part of my IDictionary<TKey,TValue> interface and pointers to generic type parameters in Delphi are just ugh...
Yes the pointer is just valid as long as no other modifications happen to the dictionary but regardless the implementation (I have a hashtable and a rb tree based one) you always can return the location where the value is stored.
You just need to keep in mind though that any notify events on the dictionary will not receive any value that was changed in such a way - but that's a rather corner case when using such an optimization.
> On 27/03/2025 12:33 CET Marco van de Voort via fpc-devel <fpc-devel at lists.freepascal.org> wrote:
>
>
> Op 27-3-2025 om 12:28 schreef Martin Frb via fpc-devel:
> >
> > which returns True, if Akey was found and therefore APtr points to
> > existing Data, while otherwise APtr points to the empty slot, where
> > the data can be copied to.
> >
> Without a key, you can't find the bucket or whatever where to allocate,
> so this is not possible for all dictionaries IMHO. IOW, it violates the
> contract with implementation details.
>
>
> _______________________________________________
> fpc-devel maillist - fpc-devel at lists.freepascal.org
> https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-devel
More information about the fpc-devel
mailing list