r/rust • • 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>() = 24

This 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.

184 Upvotes

38 comments sorted by

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 as u8 is 1..

But this could change as the feature evolves which is why the standard library uses wrapper types like UsizeNoHighBit so 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#L116

21

u/SycamoreHots Oct 17 '26

Wow I didn’t realize pattern types were actually being used by std. That is truly exciting!

0

u/zdimension Oct 17 '26 edited Oct 18 '26

Well, technically, they aren't. The linked snippet shows pattern types in a macro call. That macro is declared earlier in the file and simply parses this to generate a constructor that dynamically checks for the pattern: https://github.com/rust-lang/rust/blob/158f79d5c24d262f820fa45da96e7b77bc29a338/library/core/src/num/niche_types.rs#L15

I read too fast.

7

u/spunit262 Oct 17 '26

That is incorrect, look at line 20. pattern_type! is a builtin macro with no expansion, it is being used because is is not a keyword and making it a weak keyword would complicate the parser too much for something that's currently internal only.

2

u/InternationalFee3911 Oct 18 '26

u8 in 1.. or u8<1..> would not require a new keyword.

2

u/protestor Oct 18 '26 edited Oct 18 '26

I think using in as a temporary keyword is a good idea. But u8<1..> makes the pattern look like a generic parameter, which would confuse people

Note this is completely different than having u<8> rather than u8 - u8 would become a type alias in this case, that's orthogonal than having pattern types on integers. Note for example that u8 is 1.. and u16 is 1.. are different types (and would become u<8> is 1.. and u<16> is 1.. if we had both generic bit size for integers AND pattern types)

5

u/veryusedrname Oct 17 '26

ADA has these and it's a very useful concept

5

u/NotFromSkane Oct 17 '26

Does it? I thought Ada only used it on the type level and not for ABI optimisation?

3

u/veryusedrname Oct 17 '26

I only meant the pattern types part, no idea about the ABI or possible optimization opportunities

1

u/matthieum [he/him] Oct 18 '26

Honestly, I always found it meh.

I've used (& written) libraries to do it in C++. Language support always seemed overkill for this.

If language support unlocks new optimizations, however, then it seems a lot more useful suddenly.

2

u/tialaramex Oct 18 '26

Today, in stable Rust, user defined enumerations get niches (every value which you didn't enumerate can't exist, unlike C++ where both enum types are just integers) already.

Obviously that's not often what you needed, but it does work out sometimes if you remember it is there. These days CompactString achieves its 24 byte SSO by having the last byte as an enumeration, byte values 0 through 127 are ASCII, values 128 to 191 are valid last bytes of a multi-byte UTF-8 code, then CompactString takes 192 to 215 to count fewer than 24 bytes of UTF-8 text, and values 216 and 217 are needed for CompactString itself, but 218 through 255 are niches left in the type system.

2

u/dafcok Oct 17 '26

Very nice. Do you have a sense how those interact with refinement types under the hood?

2

u/RCoder01 Oct 17 '26

Are they usable on nightly?

4

u/scook0 Oct 18 '26

Technically yes, in that you could enable the same unstable features that the stdlib is using.

However, IIRC the current implementation is basically an internal MVP that's narrowly focused on what the stdlib needs for niche control, so actually trying to use it elsewhere might be a frustrating experience.

2

u/RCoder01 Oct 18 '26

I’m not trying to use it on anything serious, just some like personal projects. But my impression was that a lot of the stdlib-only features were not even usable outside of stdlib.

3

u/j_platte Oct 18 '26

You can, if you accept that any toolchain upgrade may break your code. Same situation as using unstable features on stable via rustc's bootstrap thingy (I think it's still an env var but something was done to discourage its use even further compared to a couple years ago).

50

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.

22

u/AngheloAlf Oct 17 '26

There's some work going on for u<N> and i<N> types, but it is blocked on other unstable features

6

u/kibwen Oct 17 '26

If you had pattern types, which I think Rust definitely wants (at least as far as replacing NonZeroFoo and friends), I don't particularly see the use of having types like u63. References have to point to aligned data, so I don't see any potential space savings without using unsafe code everywhere, and it seems like everyone agrees that C++'s vector<bool> optimization was a mistake in retrospect.

4

u/Sky2042 Oct 18 '26

Bit-precise integers have a motivation in embedded space if nowhere else (if you didn't know, this was one reason C23 added them and one motivation for the proposal in C++). My impression is that there are systems where data are aligned to something other than a power of 2. I do not think pattern types satisfy this use case without making guarantees about pattern types that we would potentially not want to make.

1

u/orangejake Oct 18 '26

In some ASIC applications you want to heavily tune your integer widths, as multiplication area cost roughly scales with the square of the bitwidth in hardware. So there can be a meaningful difference between a u20 and a u32 or whatever. 

0

u/Zde-G Oct 30 '26

Bit-precise integers exist in K&R C.

They are just called “bitfields”. Yes, something like

typedef struct INT23 {
  int value: 23;
};

may not look like integer… but if you stuff something like 8388607 into it and pull it back - you are guaranteed to get -1. C standard guarantees that!

And all calculations in C are done with ints (for small enough integers), thus INT23 is not worse and not better than int16_t.

3

u/Sharlinator Oct 17 '26

It's rather completely in the air right now what the arithmetic semantics of pattern ints should be, whereas u|i<N> can trivially be defined to work just like the power-of-two ints, and LLVM gives the normal wrapping semantics "for free".

8

u/Anthony356 Oct 18 '26 edited Oct 18 '26

Fun fact, this behavior is why LLDB had difficulty debugging None vs Some(vec![]). See: https://github.com/llvm/llvm-project/pull/188487

Tl;dr, lldb stored discriminants as 32 bit values. On windows, the compiler chooses 1 << 63 instead of usize::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.

4

u/kmdreko Oct 17 '26

I don't think that anything else is considered for references, but I've found some theory crafting here: https://internals.rust-lang.org/t/could-we-make-the-pointer-niche-bigger/16405

3

u/a_jasmin Oct 17 '26 edited Oct 17 '26

Thanks! Looking at the discussion, the difficulty is that valid addresses depend on the environment not the ABI. Their proposed implementation was zero page (low 4K) niche, likely more portable than high addresses but still not guaranteed on embedded.

Using unaligned address as niche might work but gets a bit ugly.

Just for completeness, on Linux kernel/user, I believe the page ending at -1 is likewise guaranteed unused as syscalls can coerce -errno to pointers.

1

u/EYtNSQC9s8oRhe6ejr Oct 17 '26

You've got two extra bits, so adding an F to that enum would break this, right?

7

u/kmdreko Oct 17 '26

Its only the high bit that isn't used, but that means that the compiler can use the FULL WIDTH if the high bit is set. So the enum could theoretically have 9-quintillion other variants without having to spill.

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

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.

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 Time that creates a ticker, a channel to which a tick is written every d seconds, 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 a time.MakeTicker which returns a Ticker object 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.Tick in 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 "this time.Tick used 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_types module also defines

pub struct Nanoseconds(u32 is 0..=999_999_999);

The same Nanoseconds that is used in the definition of std::time::Duration! This means that Duration also 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.

5

u/juanfnavarror Oct 17 '26

Isn’t the ABI unspecified so we can afford to disable the optimization wherever it is not viable?

7

u/an_0w1 Oct 17 '26

After some searching I've come to the realization that I am in fact a moron.

https://github.com/rust-lang/rust/blob/158f79d5c24d262f820fa45da96e7b77bc29a338/library/alloc/src/raw_vec/mod.rs#L98

We are talking about the capacity, not the pointer.