Search code examples
swiftunsafe-pointers

Is it possible to get from Any type his UnsafeRawPointer and length?


I just want call C function

static  inline  uint64_t  wyhash(const void* key,  uint64_t  len, uint64_t  seed)

from Swift like that

func hash<T: Any>(key: T, seed: UInt64) -> UInt64 { wyhash(...) }

Is it possible? And how?


Solution

  • To compute the size, use MemoryLayout:

    func hash<T>(key: T, seed: UInt64) -> UInt64 {
        let len = UInt64(MemoryLayout.size(ofValue: key))
        return withUnsafePointer(to: key) { myhash($0, len, seed) }
    }
    

    Keep in mind that structural types may have internal padding, and I don't believe Swift promises that to be initialized. So you may wind up hashing random values if you're not careful what you pass here. And of course types may have non-obvious internal state that can cause "equal" values to hash differently or vice versa. Given the likelihood of difficult-to-diagnose bugs, I would typically suggest writing specific overloads for types you know are acceptable to this function rather than trying to hash over Any. At a minimum, I'd constrain T to some protocol (with no syntactic requirements) that expresses "I've checked that this type is myhash-able."