3 ms·
Couldn't any negative number be used as a niche for file descriptors in Unix? Could Option<File> use -2 to specify None?
by cevans01 6y ago
Couldn't any negative number be used as a niche for file descriptors in Unix? Could Option<File> use -2 to specify None?
- baq 6y agoi don't know, but -1 has the prettiest two's complement representation of all negative ints :)
- duckerude 6y agoBased on https://internals.rust-lang.org/t/can-the-standard-library-shrink-option-file/12768 https://internals.rust-lang.org/t/can-the-standard-library-s... it looks like that's probably the case, but that it's not beyond all doubt that it holds across all Unix-likes. > On Linux, the answer is pretty obviously no. Linux file descriptors are stored in an array of structs that has its capacity bounded to INT_MAX, so any negative int would either be considered nonsense (if treated as negative) or be higher than INT_MAX (if it was bit-reinterpreted as an unsigned value). > The Single UNIX Specification explicitly says that open can't return a negative file descriptor, and says in the page for dup2 that you should get EBADF if you try to claim a negative file descriptor. > Unfortunately, their description of file descriptor allocation never explicitly says that the negative range is out of bounds, but open references this algorithm while simultaneously claiming that it never gives a negative result. > Also, Wikipedia says it can't be negative, but they don't give a source on that particular claim (urgh!). -1 was picked as a conservative choice that's enough for the common case of Option.