Auto merge of #114065 - lukas-code:u16_from_char, r=dtolnay · rust-lang/rust@361f8ba (original) (raw)

`@@ -87,20 +87,54 @@ impl From for u128 {

`

87

87

`}

`

88

88

`}

`

89

89

``

90

``

`` -

/// Map char with code point in U+0000..=U+00FF to byte in 0x00..=0xFF with same value, failing

``

91

``

`-

/// if the code point is greater than U+00FF.

`

``

90

`` +

/// Maps a char with code point in U+0000..=U+00FF to a byte in 0x00..=0xFF with same value,

``

``

91

`+

/// failing if the code point is greater than U+00FF.

`

92

92

`///

`

93

93

`` /// See impl From<u8> for char for details on the encoding.

``

94

94

`#[stable(feature = "u8_from_char", since = "1.59.0")]

`

95

95

`impl TryFrom for u8 {

`

96

96

`type Error = TryFromCharError;

`

97

97

``

``

98

`` +

/// Tries to convert a [char] into a [u8].

``

``

99

`+

///

`

``

100

`+

/// # Examples

`

``

101

`+

///

`

``

102


/// ```

``

103

`+

/// let a = 'ÿ'; // U+00FF

`

``

104

`+

/// let b = 'Ā'; // U+0100

`

``

105

`+

/// assert_eq!(u8::try_from(a), Ok(0xFF_u8));

`

``

106

`+

/// assert!(u8::try_from(b).is_err());

`

``

107


/// ```

98

108

`#[inline]

`

99

109

`fn try_from(c: char) -> Result<u8, Self::Error> {

`

100

110

` u8::try_from(u32::from(c)).map_err(|_| TryFromCharError(()))

`

101

111

`}

`

102

112

`}

`

103

113

``

``

114

`` +

/// Maps a char with code point in U+0000..=U+FFFF to a u16 in 0x0000..=0xFFFF with same value,

``

``

115

`+

/// failing if the code point is greater than U+FFFF.

`

``

116

`+

///

`

``

117

`+

/// This corresponds to the UCS-2 encoding, as specified in ISO/IEC 10646:2003.

`

``

118

`+

#[stable(feature = "u16_from_char", since = "CURRENT_RUSTC_VERSION")]

`

``

119

`+

impl TryFrom for u16 {

`

``

120

`+

type Error = TryFromCharError;

`

``

121

+

``

122

`` +

/// Tries to convert a [char] into a [u16].

``

``

123

`+

///

`

``

124

`+

/// # Examples

`

``

125

`+

///

`

``

126


/// ```

``

127

`+

/// let trans_rights = '⚧'; // U+26A7

`

``

128

`+

/// let ninjas = '🥷'; // U+1F977

`

``

129

`+

/// assert_eq!(u16::try_from(trans_rights), Ok(0x26A7_u16));

`

``

130

`+

/// assert!(u16::try_from(ninjas).is_err());

`

``

131


/// ```

``

132

`+

#[inline]

`

``

133

`+

fn try_from(c: char) -> Result<u16, Self::Error> {

`

``

134

`+

u16::try_from(u32::from(c)).map_err(|_| TryFromCharError(()))

`

``

135

`+

}

`

``

136

`+

}

`

``

137

+

104

138

`` /// Maps a byte in 0x00..=0xFF to a char whose code point has the same value, in U+0000..=U+00FF.

``

105

139

`///

`

106

140

`/// Unicode is designed such that this effectively decodes bytes

`