Remix.run Logo
tialaramex 5 days ago

The compiler isn't ignoring your new types, as you'll see if you try to pass a OneVar when the function takes a Vec but yes, Rust really likes new types whose representation is identical yet their type is different.

My favourite as a Unix person is Option<OwnedFd>. In a way Option<OwnedFd> is the same as the classic C int file descriptor. It has the exact same representation, 32 bits of aligned integer. But Rust's type system means we know None isn't a file descriptor, whereas it's too easy for the C programmer to forget that -1 isn't a valid file descriptor. Likewise the Rust programmer can't mistakenly do arithmetic on file descriptors, if we intend to count up some file descriptors but instead sum them in C that compiles and isn't what you wanted, in Rust it won't compile.

Ygg2 5 days ago | parent [-]

> The compiler isn't ignoring your new types

True, I didn't meant to imply you can just ignore types; I meant to say that the equivalent operations on a naked vs wrapped value return equivalent assembly.

It's one of those zero cost abstraction. You can writ your newtype wrapper and it will be just as if you wrote implementations by hand.

> My favourite as a Unix person is Option<OwnedFd>.

Yeah, but that's a bit different. Compiler won't treat any Option<T> that way out of the box. You need a NonZero type or nightly feature to get that[1].

That relies on compiler "knowing" there are some values that will never be used.

[1] https://www.0xatticus.com/posts/understanding_rust_niche/

tialaramex 5 days ago | parent [-]

You can't make your own types with niches (in stable Rust, yet, though I am trying to change that and I think there's a chance we'll make that happen some day) except for enumerations.

So if you make an enumeration AlertLevel with values Ominous, Creepy, Terrifying, OMFuckingGoose then Option<AlertLevel> is a single byte, Rust will assign a bit pattern for AlertLevel::Ominous and AlertLevel::Creepy and so on, but the None just gets one of the bit patterns which wasn't used for a value of AlertLevel.

It is a bit trickier to have Color { Red, Green, Blue, Yellow } and Breed { Spaniel, Labrador, Poodle } and make a type DogOrHat where DogOrHat::Dog has a Breed but DogOrHat::Hat has a Color and yet the DogOrHat fits in a single byte. This is because Rust won't (by default) avoid clashes, so if it asssigned Color::Red bit pattern 0x01 and Breed::Spaniel bit pattern 0x01 as well, it won't be able to disambiguate without a separate dog-or-hat tag, however we can arrange that the bit patterns don't overlap and then it works. [This is not guaranteed by Rust unlike the Option<OwnedFd> niche which is guaranteed by the language]

Ygg2 4 days ago | parent [-]

> You can't make your own types with niches in stable Rust

You can, provided they are wrapper around NonZero types. See https://docs.rs/nonmax/latest/nonmax/

Hence my comment before NonZero types or Rust nightly.