11//! impl char {}
22
33use super :: * ;
4+ use crate :: intrinsics:: const_eval_select;
45use crate :: slice;
56use crate :: str:: from_utf8_unchecked_mut;
67use crate :: unicode:: printable:: is_printable;
@@ -1762,6 +1763,18 @@ const fn len_utf8(code: u32) -> usize {
17621763#[ doc( hidden) ]
17631764#[ inline]
17641765pub const fn encode_utf8_raw ( code : u32 , dst : & mut [ u8 ] ) -> & mut [ u8 ] {
1766+ const fn panic_at_const ( _code : u32 , _len : usize , _dst_len : usize ) {
1767+ // Note that we cannot format in constant expressions.
1768+ panic ! ( "encode_utf8: buffer does not have enough bytes to encode code point" ) ;
1769+ }
1770+ fn panic_at_rt ( code : u32 , len : usize , dst_len : usize ) {
1771+ panic ! (
1772+ "encode_utf8: need {} bytes to encode U+{:04X} but buffer has just {}" ,
1773+ len,
1774+ code,
1775+ dst_len,
1776+ ) ;
1777+ }
17651778 let len = len_utf8 ( code) ;
17661779 match ( len, & mut * dst) {
17671780 ( 1 , [ a, ..] ) => {
@@ -1782,8 +1795,8 @@ pub const fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] {
17821795 * c = ( code >> 6 & 0x3F ) as u8 | TAG_CONT ;
17831796 * d = ( code & 0x3F ) as u8 | TAG_CONT ;
17841797 }
1785- // Note that we cannot format in constant expressions .
1786- _ => panic ! ( "encode_utf8: buffer does not have enough bytes to encode code point" ) ,
1798+ // FIXME(const-hack): We would prefer to have streamlined panics when formatters become const-friendly .
1799+ _ => const_eval_select ( ( code , len , dst . len ( ) ) , panic_at_const , panic_at_rt ) ,
17871800 } ;
17881801 // SAFETY: `<&mut [u8]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds.
17891802 unsafe { slice:: from_raw_parts_mut ( dst. as_mut_ptr ( ) , len) }
0 commit comments