Skip to content

Instantly share code, notes, and snippets.

@zewt
Created June 19, 2020 01:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save zewt/8c8ea3f0589b3235e1f09f6173e4ad07 to your computer and use it in GitHub Desktop.
namespace std
{
// Compare two MObjects. This allows them to be used as keys in std::map.
template<>
struct less<MObject>
{
size_t operator()(const MObject &lhs, const MObject &rhs) const;
};
// A hash for MObject. This allows them to be used as keys in std::unordered_map.
template<>
struct hash<MObject>
{
size_t operator()(const MObject &obj) const;
};
}
namespace {
// Return the internal implementation pointer for an MObject.
//
// This is used to implement comparing MObjects. This isn't a "safe" operation
// since it's accessing an internal API, but MObject hasn't changed significantly
// in living memory, so it's safe enough.
//
// We're only using this for comparisons, so return it as an integer rather than
// a pointer.
//
// We can't use MObjectHandle::objectHashCode, because that only returns a 32-bit
// hash. We need the 64-bit pointer value to guarantee that two values are never
// the same for this to work with ordered sets. It would be trivial for objectHashCode
// to just return the pointer.
const size_t getMObjectPointer(const MObject &obj)
{
const void **p = (const void **) &obj;
return (size_t) p[0];
}
}
size_t std::less<MObject>::operator()(const MObject &lhs, const MObject &rhs) const
{
return getMObjectPointer(lhs) < getMObjectPointer(rhs);
}
size_t std::hash<MObject>::operator()(const MObject &obj) const
{
return getMObjectPointer(obj);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment