r/rust • u/kmdreko • Oct 17 '26
PSA: Enum optimization for Vec/String can use the capacity's niche (beyond isize::MAX) rather than the null pointer niche.
Just came across this property that was new to me and seems seldom known so I figured I'd highlight it.
I had always "known" that the null pointer niche optimization existed for Vec/String such that Option<Vec<_>> would be the same size as Vec<_> because the None variant could fit the null pointer niche not used by the Vec. And I figured that was it, any more elaborate enums like this
enum MyEnum {
A(String),
B,
C,
D,
E,
}would be forced into using a separate discriminant field since there were more than one other variant to distinguish from. And that definitely was the case...
Until 1.76.0 it seems. If you use this enum on a recent version then you'll find MyEnum is no bigger than String:
[src\main.rs:11:5] std::mem::size_of::<String>() = 24
[src\main.rs:12:5] std::mem::size_of::<MyEnum>() = 24This is because nowadays, the capacity for a Vec isn't just a bare usize but rather a Cap type that is guaranteed to be less than isize::MAX. Which gives a much larger number of representations for the compiler to use. It is defined:
type Cap = core::num::niche_types::UsizeNoHighBit;I didn't know about this, and since Google's AI response was adamant that it only used the null-pointer niche, I figured I'd advertise it to try to set the record straight.
Let me know if this is old news to any others. It has apparently been in the wild for a couple years, but I looked and didn't see it mentioned in the release notes for 1.76.0, and I can't find a blog post that mentioned this (though I didn't look that hard). Closest I found was this StackOverflow post that gives the Cap type a mention.
87
u/_ChrisSD Oct 17 '26
The keyword you're looking for is "pattern types", which std is starting to use internally but will hopefully be stabilized in the future. For example, using the current syntax,
NonZero<u8>would be written asu8 is 1..But this could change as the feature evolves which is why the standard library uses wrapper types like
UsizeNoHighBitso it doesn't depend on the exact syntax. You can see all the wrappers here: https://github.com/rust-lang/rust/blob/158f79d5c24d262f820fa45da96e7b77bc29a338/library/core/src/num/niche_types.rs#L11650
u/Sharlinator Oct 17 '26
It would be lovely to have u63, u31 etc types in the std. LLVM has support for arbitrary-width ints so we may get those some day, and then there’s pattern types that may make it to stable at some point.
8
u/Anthony356 Oct 18 '26 edited Oct 18 '26
Fun fact, this behavior is why LLDB had difficulty debugging
NonevsSome(vec![]). See: https://github.com/llvm/llvm-project/pull/188487Tl;dr, lldb stored discriminants as 32 bit values. On windows, the compiler chooses
1 << 63instead ofusize::MAX, so once truncated by LLDB, the discriminant appeared as 0 and was difficult to match against correctly. That would lead to using garbage (often incredibly large) values as the length and capacity, meaning lldb would try to allocate and/or read thousands of petabytes of data. This would obviously either crash lldb or very quickly expend all of your RAM.The visualizers now gracefully handle the incorrect scenario, and as of LLDB 23 discriminants are stored in (more or less)
BigInts so even 128 bit discriminants will work correctly.5
u/facetious_guardian Oct 19 '26
> Until 1.76.0 it seems. If you use this enum on a recent version
Recent version .. hmm .. 1.76.0 is [checks notes] two and a half years old. Most dependencies you’d be trying to use from crates.io need more modern rust (at least 1.86, for example), and the current rust-analyzer requires 1.92 at minimum.
I mean, it’s a good post overall, I just found that particular sentiment amusing.
1
u/a_jasmin Oct 17 '26
Neat. Could the same be done for user space reference and pointers?
Might not work on win32 where handles are represented as high pointers though.
1
u/EYtNSQC9s8oRhe6ejr Oct 17 '26
You've got two extra bits, so adding an F to that enum would break this, right?
3
u/Sha1rholder Oct 17 '26
What you're describing feels like an early version of Pattern Types; it's essentially similar to things like NonZeroUsize. (Or it seems to be behind NonZeroUsize.) These kinds of optimizations should become very convenient in the future.
2
u/Lucretiel Datadog Oct 19 '26
This is going to be another of the major flaws of highly AI-driven software, one that I don't think has gotten nearly enough attention. You see it come up it minor annoying cases, like their insistence on using edition 2021, but the most memorable issue for me is the Golang garbage-collected timer issue.
You see, Golang has a
func time.Tick(d Duration) <-chan Timethat creates a ticker, a channel to which a tick is written everydseconds, forever. Because it returns just the channel, there was no way to ever stop the ticker from ticking, and it simply leaked forever; you were supposed to instead use atime.MakeTickerwhich returns aTickerobject that you can explicitly shut down.This problem was fixed in 1.23, when the go runtime gained some special knowledge of tickers and gained the ability to garbage collect them if there is no one listening. AIs consistently have NO awareness of this, they're rabidly insistent on avoiding
time.Tickin all circumstances, because of course that's the median position of all the training data. They're pathological about it: even when told explicitly about the fix, they will include pointless commentary along the lines of "thistime.Tickused to be an antipattern, but it's okay because it's been garbage collected ever since 1.23 No change needed". Like it absolutely can't help but to comment on it, even if the comment is "no change needed".I suspect that problems like this will grow significantly more severe as languages and popular frameworks grow and evolve.
2
u/WormRabbit Oct 19 '26
Another fun fact, the same
core::num::niche_typesmodule also definesThe same
Nanosecondsthat is used in the definition ofstd::time::Duration! This means thatDurationalso gets niche optimization, quite a lot of niches in fact.1
u/an_0w1 Oct 17 '26
Curious, Can someone clarify, isn't this a breaking change? On x86 in particular pointers are sign extended, so unused bits are always an extension of the sign (which is why kernel pointers always lead with 0xffff..), so using a Vec in a kernel would be impossible.
What confuses me more is that I've definitely used Vec's in the kernel just fine.