Add niche to ColdString to make Option<ColdString> the same size as ColdString#8
Conversation
|
Can this handle "\0\0\0\0\0\0\0\0"? |
|
I see, it represents |
c23dcc2 to
7b44bc8
Compare
|
Since rust doesn't support custom niches in types NonNull is the only reasonable internal type. That means that we can't store an 8 byte all NUL str inline, so it has to be that value that is special cased. |
|
I'm with you there. But, is Self::TAG_PTR the only reasonable 8-nul representation? I'm suggesting fn new_eight_nul() -> Self {
// SAFETY: PTR_TAG is non-zero
unsafe { Self::from_inline_buf(usize::MAX.to_ne_bytes()) }
}
fn inline_len(&self) -> usize {
let addr = self.addr();
match addr & Self::INLINE_TAG {
Self::INLINE_TAG if addr != usize::MAX => (addr & Self::LEN_MASK).rotate_right(Self::ROT),
_ => WIDTH,
}
}so Would that work? |
|
And having an invalid utf8 string as representation for 8NUL means that we can't return an &str to it, so some kind of tag and indirection is needed. I don't see any disadvantage of considering as a pointer, and then doing null ptr checks, as compared to having a completely different codepath for the niches. |
|
The advantage of using the internal |
|
Ok, I'll try to implement it that way and see how it looks. I might have some time this evening. |
|
I think you should be able to merge luksan#1 into your branch, and then it will update this PR automatically. |
bf305e5 to
9e6237a
Compare
Use internal mapping for 8 null bytes
|
Why did you remove the packed attribute? |
@luksan If I'm understanding https://doc.rust-lang.org/std/option/index.html#representation right, Rust does not guarantee niche optimizations (e.g across all platforms and Rust versions) for
Users who still want to use a packed version of use std::ptr::NonNull;
#[repr(transparent)]
struct ColdString {
inner: NonNull<u8>,
}
#[repr(packed)]
struct PackedColdString {
inner: ColdString,
x: u8,
}
fn main() {
assert_eq!(9, std::mem::size_of::<PackedColdString>());
} |
This changes the type of the internal "encdoded" from *const u8 to NonNull in order to create a niche so that Option has the same size as ColdString. To handle storing of WIDTH NUL bytes the NULL pointer is mapped to a static [0u8; WIDTH] array.