@@ -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 {
@@ -3649,6 +3679,12 @@ impl PartialEq<str> for JsString {
3649
3679
}
3650
3680
}
3651
3681
3682
+ impl PartialEq < char > for JsString {
3683
+ fn eq ( & self , other : & char ) -> bool {
3684
+ self . as_char ( ) == Some ( * other)
3685
+ }
3686
+ }
3687
+
3652
3688
impl < ' a > PartialEq < & ' a str > for JsString {
3653
3689
fn eq ( & self , other : & & ' a str ) -> bool {
3654
3690
<JsString as PartialEq < str > >:: eq ( self , other)
@@ -3679,6 +3715,13 @@ impl From<String> for JsString {
3679
3715
}
3680
3716
}
3681
3717
3718
+ impl From < char > for JsString {
3719
+ #[ inline]
3720
+ fn from ( c : char ) -> Self {
3721
+ JsString :: from_code_point1 ( c as u32 ) . unwrap_throw ( )
3722
+ }
3723
+ }
3724
+
3682
3725
impl < ' a > From < & ' a JsString > for String {
3683
3726
fn from ( s : & ' a JsString ) -> Self {
3684
3727
s. obj . as_string ( ) . unwrap_throw ( )
0 commit comments