Should zig's stdlib use 32bit handles on windows?

Found out recently that handles on windows are always 32bits, reason being easy interop between 32bit and 64bit applications c++ - How can I share HWND between 32 and 64 bit applications in Win x64? - Stack Overflow.

So it is a documented fact that they can be safely truncated and extended back when it is time to use them.

That got me wondering if zig’s stdlib can use it to also save memory and have a consistent handle size across it’s supported platforms?

I typically don’t have many long-lived handles apart from window-handles so I’m not sure how beneficial it would be to save size across all handles considering you have to truncate and extend every so often, so thought I’d ask where people probably have more experience with that. Curious to hear your thoughts :slight_smile:

They can currently be safely truncated.
While they don’t need to be able to have more handles available, they might decide to encode some other information in those bits at any time.
I doubt that will happen any time soon, but taking advantage of that might break future compatibility.

It’s up to Andrew/the core team if they care more about a memory optimisation or keeping compatibility.

1 Like

It seems reasonable to have the default behavior be to use the “future-proof” solution (even if 32 bits never ends up breaking). If there is ever an application that really needs to save those 32 bits (or use them for something else)…they can always opt-in to doing the truncation themselves.

All the storage for the various windows handles should be completely in the application (not std) so it’s already mostly a “customizable” thing. Gets more complicated if you’re using libraries that participate in handle storage, solvable, but more complicated.

That’s an interesting tidbit. I think I’m going to use it.
About the 64-bit handles being more “future proof”, forget it, it’s never going to change. Remember that Portable Executable files still have a DOS header. If truncation is documented to be safe, Microsoft will never change this.
In any case, it would be trivial to implement truncation and then later change it back:

const Handle = u32;

// Do the truncation before returning the pointer to the user:
fn getHandle() Handle{
  return @truncate(actualGetHandle())
}

cons UserStruct = struct{
  //Use the Handle type wherever needed.
  handle: Handle,
};

If the sky falls down and Microsoft changes this behavior, you can just change Handle to be u64 and recompile.

3 Likes