Skip to content

Add const String::try_from_const - #701

Merged
sgued merged 2 commits into
rust-embedded:mainfrom
sundew-sensing:const-try-from-const
Nov 24, 2026
Merged

sgued merged 2 commits into
rust-embedded:mainfrom
sundew-sensing:const-try-from-const

Conversation

@sundew-sensing-admin

@sundew-sensing-admin sundew-sensing-admin commented Nov 7, 2026 •

Copy link
Copy Markdown

Related to #698 #700, #515, all on adding const

Adds String::try_from_const, which creates a String from a &str in a const context:

static S: String<8> = String::try_from_const("abcd").expect("fits in 8 bytes");

It returns an Option, because on stable a Result holding a String can't be unwrapped in const. std does the same with char::from_u32 next to TryFrom<u32> for char. The name follows Queue::split_const.

I'm open to suggestions for a better function name, but I think this is reasonable. Of course it would be nice if stable support const Results, but AFAIK that is not possible currently. For obvious compatibility reasons I chose to not change the return type of the existing function to Option.

from_slice_unchecked could also be public API, but I chose not to so the PR is focused. Can easily change that later. Also, now we don't have to discuss the signature and name for that so much because it's not public and people won't depend.

AI disclosure
As with #698 and #700, I used Claude Opus 5.5 to assist with basically everything, but as a tool, not blindly trusted.

@sundew-sensing-admin
sundew-sensing-admin marked this pull request as ready for review November 7, 2026 16:45
@surgura

surgura commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Author is me, logged in on the wrong account :)

@sgued

sgued commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Please rename it to try_from_str (this seems to match what the ecosystem does), modify the TryFrom impl to use the new function to reduce code duplication,

Please also make Vec::from_array use the new from_slice_unchecked to reduce code duplication

@surgura

surgura commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the review. I made the following changes to address your feedback (each a separate commit):

  • Renamed to try_from_str
  • TryFrom<&str> uses it (as well as FromStr, same-same)
  • Vec::from_array now shares the code with try_from_str. However, for that I needed to drop the Copy restriction, as vec doesn't have that. So I created a new function that takes a raw pointer, so I don't fake-promise to only borrow the slice, while secretly we are moving out of it. This is used by vec directly. The original helper is now just a simple wrapper around it, and string keeps the original slice safety.

@sgued sgued left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some small nits again sorry.

Comment thread src/string/mod.rs Outdated
Self { vec: Vec::new() }
}

/// Creates a `String` from a `&str`, returning [`None`] if `s` doesn't fit.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/// Creates a `String` from a `&str`, returning [`None`] if `s` doesn't fit.
/// Creates a `String` from a `&str`, returning [`None`] if it doesn't fit.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Accepted

Comment thread src/string/mod.rs Outdated
return None;
}

// SAFETY: We just checked that `s.len() <= N`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// SAFETY: We just checked that `s.len() <= N`.
// SAFETY: We just checked that `s.len() <= N`, and `s.as_bytes()` is known to be valid UTF-8.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Accepted

Comment thread src/vec/mod.rs Outdated
Comment on lines +401 to +406
let src = ManuallyDrop::new(src);

let len: LenT = to_len_type(M);

let mut v = Self::new();

// MaybeUninit::deref is non-const, so we just cast to it's internal value.
let src_ptr: *const T = ptr::from_ref(&src).cast();

// Cast from buffer's [MaybeUninit<T>] to [T].
let dst_ptr: *mut T = v.buffer.buffer.as_mut_ptr().cast();

// SAFETY: Move/copy data from src to v's internal buffer.
// * Using src_ptr as `*const T` is safe since src's ManuallyDrop<[T; M]> is transparent.
// * Using dst_ptr as `*mut T` is safe since v's [MaybeUninit<T>; N] is an array of
// transparent types.
unsafe { ptr::copy_nonoverlapping(src_ptr, dst_ptr, M) };
v.len = len;

v
// SAFETY: `M <= N` by the assertion above. `ManuallyDrop<[T; M]>` is `repr(transparent)`
// around `[T; M]`, so the pointer is valid for reading its `M` elements, and `src` is never
// used or dropped again.
unsafe { Self::from_ptr_unchecked(ptr::from_ref(&src).cast::<T>(), M) }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is a slightly better way to do it. No pointer cast needed.

Suggested change
let src = ManuallyDrop::new(src);
let len: LenT = to_len_type(M);
let mut v = Self::new();
// MaybeUninit::deref is non-const, so we just cast to it's internal value.
let src_ptr: *const T = ptr::from_ref(&src).cast();
// Cast from buffer's [MaybeUninit<T>] to [T].
let dst_ptr: *mut T = v.buffer.buffer.as_mut_ptr().cast();
// SAFETY: Move/copy data from src to v's internal buffer.
// * Using src_ptr as `*const T` is safe since src's ManuallyDrop<[T; M]> is transparent.
// * Using dst_ptr as `*mut T` is safe since v's [MaybeUninit<T>; N] is an array of
// transparent types.
unsafe { ptr::copy_nonoverlapping(src_ptr, dst_ptr, M) };
v.len = len;
v
// SAFETY: `M <= N` by the assertion above. `ManuallyDrop<[T; M]>` is `repr(transparent)`
// around `[T; M]`, so the pointer is valid for reading its `M` elements, and `src` is never
// used or dropped again.
unsafe { Self::from_ptr_unchecked(ptr::from_ref(&src).cast::<T>(), M) }
// SAFETY: `M <= N` by the assertion above. `src` is forgotten without `drop` just afterwards.
let this = unsafe { Self::from_ptr_unchecked(src.as_ptr(), M) };
core::mem::forget(src);
this

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Accepted

@sgued

sgued commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Please fix the formatting and it's good to go.

@surgura

surgura commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Please fix the formatting and it's good to go.

Should be good now

@sgued sgued left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please also squash the commits, ideally keeping the vec changes in its own commit.

Comment thread CHANGELOG.md Outdated
- Fixed `SortedLinkedList` Zeroize implementation.
- Fixed possible integer overflow in `VecInner::extend_from_slice`.
- Allow `bytes::BufMut::advance_mut` implementation on `VecInner` to advance to the end of the buffer.
- Added `String::try_from_const`, a const version of `String::try_from(&str)` that returns an `Option`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
- Added `String::try_from_const`, a const version of `String::try_from(&str)` that returns an `Option`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

both done. There are two commits now. The first one with all the vector changes doesn't compile because one part is considered dead code, which is only used in the second commit.

Comment thread src/vec/mod.rs Resolved
@sgued
sgued enabled auto-merge November 24, 2026 21:36
@sgued
sgued added this pull request to the merge queue Nov 24, 2026
Merged via the queue into rust-embedded:main with commit dd2e3af Nov 24, 2026
23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants