@@ -467,6 +467,37 @@ impl char {
467467 }
468468 }
469469
470+ /// Encodes this character as UTF-8 into the provided byte buffer,
471+ /// and then returns the subslice of the buffer that contains the encoded character.
472+ /// Returns `None` if buffer too short.
473+ ///
474+ /// # Examples
475+ ///
476+ /// In both of these examples, 'ß' takes two bytes to encode.
477+ ///
478+ /// ```
479+ /// let mut b = [0; 2];
480+ ///
481+ /// let result = 'ß'.encode_utf8(&mut b).unwrap();
482+ ///
483+ /// assert_eq!(result, "ß");
484+ ///
485+ /// assert_eq!(result.len(), 2);
486+ /// ```
487+ ///
488+ /// A buffer that's too small:
489+ ///
490+ /// ```
491+ /// let mut b = [0; 1];
492+ ///
493+ /// assert_eq!(None, 'ß'.encode_utf8(&mut b));
494+ /// ```
495+ #[ unstable( feature = "try_unicode_encode_char" , issue = "52579" ) ]
496+ #[ inline]
497+ pub fn try_encode_utf8 ( self , dst : & mut [ u8 ] ) -> Option < & mut str > {
498+ if dst. len ( ) < self . len_utf8 ( ) { None } else { Some ( self . encode_utf8 ( dst) ) }
499+ }
500+
470501 /// Encodes this character as UTF-16 into the provided `u16` buffer,
471502 /// and then returns the subslice of the buffer that contains the encoded character.
472503 ///
@@ -525,6 +556,37 @@ impl char {
525556 }
526557 }
527558
559+ /// Encodes this character as UTF-16 into the provided `u16` buffer,
560+ /// and then returns the subslice of the buffer that contains the encoded character.
561+ /// Returns `None` if buffer too short.
562+ ///
563+ /// # Examples
564+ ///
565+ /// In both of these examples, '𝕊' takes two `u16`s to encode.
566+ ///
567+ /// ```
568+ /// let mut b = [0; 2];
569+ ///
570+ /// let result = '𝕊'.encode_utf16(&mut b).unwrap();
571+ ///
572+ /// assert_eq!(result, "𝕊");
573+ ///
574+ /// assert_eq!(result.len(), 2);
575+ /// ```
576+ ///
577+ /// A buffer that's too small:
578+ ///
579+ /// ```
580+ /// let mut b = [0; 1];
581+ ///
582+ /// assert_eq!(None, '𝕊'.encode_utf16(&mut b));
583+ /// ```
584+ #[ unstable( feature = "try_unicode_encode_char" , issue = "52579" ) ]
585+ #[ inline]
586+ pub fn try_encode_utf16 ( self , dst : & mut [ u16 ] ) -> Option < & mut [ u16 ] > {
587+ if dst. len ( ) < self . len_utf16 ( ) { None } else { Some ( self . encode_utf16 ( dst) ) }
588+ }
589+
528590 /// Returns true if this `char` is an alphabetic code point, and false if not.
529591 ///
530592 /// # Examples
0 commit comments