@@ -3641,6 +3641,36 @@ impl JsString {
3641
3641
) -> impl ExactSizeIterator < Item = u16 > + DoubleEndedIterator < Item = u16 > + ' a {
3642
3642
( 0 ..self . length ( ) ) . map ( move |i| self . char_code_at ( i) as u16 )
3643
3643
}
3644
+
3645
+ /// If this string consists of a single Unicode code point, then this method
3646
+ /// converts it into a Rust `char` without doing any allocations.
3647
+ ///
3648
+ /// If this JS value is not a valid UTF-8 or consists of more than a single
3649
+ /// codepoint, then this returns `None`.
3650
+ ///
3651
+ /// Note that a single Unicode code point might be represented as more than
3652
+ /// one code unit on the JavaScript side. For example, a JavaScript string
3653
+ /// `"\uD801\uDC37"` is actually a single Unicode code point U+10437 which
3654
+ /// corresponds to a character '𐐷'.
3655
+ pub fn as_char ( & self ) -> Option < char > {
3656
+ let len = self . length ( ) ;
3657
+
3658
+ if len == 0 || len > 2 {
3659
+ return None ;
3660
+ }
3661
+
3662
+ // This will be simplified when definitions are fixed:
3663
+ // https://github.com/rustwasm/wasm-bindgen/issues/1362
3664
+ let cp = self . code_point_at ( 0 ) . as_f64 ( ) . unwrap_throw ( ) as u32 ;
3665
+
3666
+ let c = std:: char:: from_u32 ( cp) ?;
3667
+
3668
+ if c. len_utf16 ( ) as u32 == len {
3669
+ Some ( c)
3670
+ } else {
3671
+ None
3672
+ }
3673
+ }
3644
3674
}
3645
3675
3646
3676
impl PartialEq < str > for JsString {
@@ -3679,6 +3709,13 @@ impl From<String> for JsString {
3679
3709
}
3680
3710
}
3681
3711
3712
+ impl From < char > for JsString {
3713
+ #[ inline]
3714
+ fn from ( c : char ) -> Self {
3715
+ JsString :: from_code_point1 ( c as u32 ) . unwrap_throw ( )
3716
+ }
3717
+ }
3718
+
3682
3719
impl < ' a > From < & ' a JsString > for String {
3683
3720
fn from ( s : & ' a JsString ) -> Self {
3684
3721
s. obj . as_string ( ) . unwrap_throw ( )
0 commit comments