-
Notifications
You must be signed in to change notification settings - Fork 131
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Const constructors from str, from slice for ArrayString, ArrayVec #205
base: master
Are you sure you want to change the base?
Conversation
We can't make these generic, not even where T: Copy, so they are just templated out with macros for the integer types, quite limited.
Neat! About compile-time const, for pre-1.57, you can use a hack like this btw: pub(crate) struct Assert<const L: usize, const R: usize>;
impl<const L: usize, const R: usize> Assert<L, R> {
pub const LENGTH_LT_CAPACITY: usize = R - L - 1;
}
macro_rules! assert_length_lt_capacity_const {
($len:expr, $cap:expr) => {
#[allow(path_statements)]
{ Assert::<$len, $cap>::LENGTH_LT_CAPACITY; }
}
}
fn main() {
assert_length_lt_capacity_const!(2, 3);
// assert_length_lt_capacity_const!(3, 3); // compile-time error
} |
I see. That's similar to what I already added for it to work on stable, but maybe your version has better error messages |
It's not perfect, but quite readable. Perhaps could be improved by something like impl<const LEN: usize, const CAP: usize> Assert<LEN, CAP> {
pub const OK: usize = CAP - LEN - 1; /* insufficient array capacity */
} This yields:
|
It seems like the length - coming from |
Ah, yea, indeed, it would only work with "true consts"... So what's the plan then, wait till MSRV >= 1.57 bump for the crate eventually? (assuming passing s.len() to const assert works there) |
It won't work there either (I'm developing on nightly locally, so that's the first behaviour I see). I'm not sure what the missing feature would be called. But I'll elaborate - on Rust 1.57 we can panic in constants, so that's better than the current solutions. Not a reason to bump on its own, though (?) |
Sorry for bringing the old issue back from the dead :) Wonder if this would be feasible, given we can panic in constants? Const constructors are still a big missing piece... |
Bump |
Is there a reason to use slices instead of an Array I would argue this const constructor for |
Is there any reason this is not currently in yet. |
Is this still Work in Progress? Or are we just waiting for a feature to stabilize? |
Add from_str_const constructor for ArrayString
Add from_slice_const constructor for ArrayVec
We can't make the ArrayVec constructors generic, not even where T: Copy,
so they are just templated out with macros for the integer types, quite limited.
These use "const error" for error handling - using panic would need Rust 1.57 (not yet released).
Closes #204