Repository navigation
Make len and is_empty of Vec and String const - #700
sundew-sensing-admin wants to merge 1 commit into
Conversation
`Vec` and `String` had no `len` of their own. Calls went through `Deref` to the slice or `str` inside, and `deref` is a trait method, which can't be called in const contexts. Both methods now read the stored length directly, so they can be used in const contexts, including on `VecView` and `StringView`. This adds a const `as_usize` helper, because the existing `into_usize` that `LenType` provides is a trait method, which can't be called in const either. As with `to_len_type` and `from_usize`, the two are kept side by side.
|
Author is me, logged in on the wrong account :) |
|
This PR dosn't solev any problem until |
|
I made this because I do have a use case for it. Non-empty strings can already be built in const without push (#698 and #701 make that possible). What's missing is reading them, which matters when the code that checks a value isn't the code that writes it. Of course, if you create the value yourself then you already know the length, but in my use case that's not the case, the values are written by users of my type. Simplified usecase: pub struct Name(String<32>);
impl Name {
pub const fn new(s: String<32>) -> Self {
assert!(s.len() >= 3);
Name(s)
}
}
// Written by a user of `Name`, possibly in another crate:
pub const DEFAULT: Name = Name::new(String::try_from_str("sensor").unwrap());Today I'm also working on const Regarding the new unsafe block: it is very close to the already existing What do you think? |
|
That's a decent use case. I'll look into it. |
Builds on #698, so the first commit is duplicate. Probably easiest to wait until that is merged.
VecandStringhad nolenof their own. Calls went throughDerefto the slice orstrinside, andderefis a trait method, which can't be called in const contexts. Both methods now read the stored length directly, so they can be used in const contexts, including onVecViewandStringView.This adds a const
as_usizehelper, because the existinginto_usizethatLenTypeprovides is a trait method, which can't be called in const either. As withto_len_typeandfrom_usize, the two are kept side by side.I considered not doing this and just waiting for const deref to become stable, but heapless aims to support older compilers to, so I thought this would be nice. Also not all boards I'm supporting have an up to date nightly compiler :) I guess in the far future this PR becomes obsolete.
Related: #515 (same as with #698)
AI disclosure
Same as with #698.
I used Claude (Opus 5.5 extra-high) to
I manually verified and adjusted of course :)