Equality, comparison and hashing of Unix.file_descr

I cannot find anything in the docs but would like to assume I can do equality, comparison and hashing of values of the Unix.file_descr type, e.g. use them as keys in a hash table. Is that ok or criminal?

The source code says it’s an int, so at least nothing should blow up: https://github.com/ocaml/ocaml/blob/6a12ddb222874713b69b181416159ca2653405cb/otherlibs/unix/unix.ml#L219

Now as for whether it means the right thing–I would probably do some experiments in utop, i.e. if I open the same file twice and get two fds, how do they compare, etc.

1 Like

Note that this is only true under Unix. On Windows it is something else entirely. Having said that using them as keys in a hash table with equality defined by == should be fine.

Cheers,
Nicolas

1 Like

It looks that this entire “other thing” is a custom block (and we have an int on unix). Therefore wouldn’t it better to simply use polymorphic hash, equality and comparison functions ?

That means nothing special needs to be done for using them as keys in polymorphic hash tables.

On presume, “not equal”. B/c otherwise, it wouldn’t match UNIX semantics at all. [and sure, on Winders, something else might happen]

1 Like

Yes, good point.

Cheers,
Nicolas

You’re right that this fact is not documented, but: you can safely compare file descriptors using generic equality = or generic comparison compare, hash them using Hashtbl.hash, and use them as keys in hash tables, both under Unix and under Windows.

2 Likes