Can I get (portable) access to the C++ standard library's hash implementation?

573 views Asked by At

The GNU C++ standard library has:

  struct _Hash_impl
  {
    static size_t
    hash(const void* __ptr, size_t __clength,
     size_t __seed = static_cast<size_t>(0xc70f6907UL))
    { return _Hash_bytes(__ptr, __clength, __seed); }
    /* etc. */
  }

as part of its implementation (and that's what it uses on strings, for example). Now, I want to use that code too... how can I access it, in a portable way (i.e. in a way which would work with clang's libc++, say)?

2

There are 2 answers

0
Christian Hackl On

No. You cannot access your compiler's internal implementation details in a portable way. How could that possibly work?

You cannot even be sure that the implementation will still be there after the next compiler update by the very same compiler vendor. Or worse, it may still compile fine but have different run-time behaviour. That's a maintainability nightmare and an endless debugging session waiting to happen.

If you need portability or backward compatibility in the future, implement your own hash function and mimic the behaviour of _Hash_impl.

6
einpoklum On

I've been thinking maybe I can get the effect of boring down to the implementation without actually doing so. I haven't implemented this yet, but I believe it should work:

  1. Write a custom allocator my_allocator which does not allow reallocation
  2. We can now use the class std::vector<char, my_allocator> which wraps a raw buffer with an std::vector of sorts.
  3. Given void* buf and size in bytes n, we instantiate a wrapper vector: std::vector<int, my_allocator<int>> vec(n, {}, buf);
  4. Now std::hash(vec) FTW!

Due credit to @hvd for instructing me about this wrapping trick last year.