How to get ref TValue from Native/UnsafeHashMap ?

Hi, unity team:

Collections ver: 2.2.0

For performance reason, I want to get value from a UnsafeHashMap by reference.

I’ve digged into source code and found
UnsafeHashMap.TryGetValue() calls
HashMapHelper.TryGetValue() calls
HashMapHelper.Find()

HashMapHelper.Find returns the index of value in the value array.

But all functions listed above is internal.

Is is possible to get value by ref ? Maybe something like UnsafeList.ElementAt() ?

Thanks :smile:

UnsafeHashMapAsRef.asmref

{
    "reference": "Unity.Collections"
}

UnsafeHashMapAsRefExtensions.cs

using System;

namespace Unity.Collections.LowLevel.Unsafe
{
    public static class UnsafeHashMapAsRefExtensions
    {
        public static ref TValue TryGetValueAsRef<TKey, TValue>(
            this ref UnsafeHashMap<TKey, TValue> hashMap,
            in TKey key,
            ref TValue defaultRef)
            where TValue : unmanaged
            where TKey : unmanaged, IEquatable<TKey>
        {
            ref var data = ref hashMap.m_Data;
            int idx = data.Find(key);

            if (-1 != idx)
                return ref data.GetElementAt<TValue>(idx);
           
            return ref defaultRef;
        }
    }
}

What do you think?

@apkdev

That’s exactly what I want. Thanks !

Didn’t know there is something called “Assembly Definition Reference”.

For me there was no GetElementAt<TValue>(idx) method in the UnsafeHashMapHelper struct. It may have gotten removed at some point so I replaced that line with the following:

if (-1 != idx)
    return ref UnsafeUtility.ArrayElementAsRef<TValue>(data.Ptr, idx);