Closed
Description
Proposal
Problem statement
Implement TryFrom<char> for u16
, similar to the existing TryFrom<char> for u8
.
Motivation, use-cases
I have project, which (unfortunately) has to deal with UCS-2 encoded strings (UCS-2 is like UTF-16, but no surrogates). I am currently in the process of replacing as
casts with safer alternatives and found that this impl was missing.
One example of using this feature for collecting an iterator of chars into a preallocated UCS-2 string: (playground)
use core::mem::MaybeUninit;
use core::slice;
#[derive(Debug)]
struct Error;
fn collect_ucs2(iter: impl IntoIterator<Item = char>, buffer: &mut [MaybeUninit<u16>]) -> Result<&[u16], Error> {
let mut index = 0;
for ch in iter {
if index >= buffer.len() {
return Err(Error);
}
let ucs2 = ch.try_into().map_err(|_| Error)?; // <- doesn't work :(
buffer[index] = MaybeUninit::new(ucs2);
index += 1;
}
Ok(unsafe { slice::from_raw_parts(buffer.as_ptr().cast::<u16>(), index) })
}
fn main() {
let mut buffer = [MaybeUninit::uninit(); 16];
println!("{:X?}", collect_ucs2("hello".chars(), &mut buffer));
}
Solution sketches
Copy-paste the impl from u8
, but replace u8
with u16
:
impl TryFrom<char> for u16 {
type Error = TryFromCharError;
#[inline]
fn try_from(c: char) -> Result<u16, Self::Error> {
u16::try_from(u32::from(c)).map_err(|_| TryFromCharError(()))
}
}
Links and related work
impl TryFrom<char> for u8
: ImplementTryFrom<char>
foru8
rust#84640
What happens now?
This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals in its weekly meeting. You should receive feedback within a week or two.