1
Fork 0

Use associated items of char instead of freestanding items in core::char

This commit is contained in:
Lukas Markeffsky 2023-01-14 11:48:43 +01:00
parent c0b8735959
commit 76e216f29b
12 changed files with 21 additions and 45 deletions

View file

@ -22,7 +22,6 @@ use rustc_target::spec::abi::Abi;
use smallvec::SmallVec; use smallvec::SmallVec;
use std::cell::Cell; use std::cell::Cell;
use std::char;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::fmt::{self, Write as _}; use std::fmt::{self, Write as _};
use std::iter; use std::iter;

View file

@ -2,9 +2,8 @@ use super::*;
#[test] #[test]
fn test_lev_distance() { fn test_lev_distance() {
use std::char::{from_u32, MAX};
// Test bytelength agnosticity // Test bytelength agnosticity
for c in (0..MAX as u32).filter_map(from_u32).map(|i| i.to_string()) { for c in (0..char::MAX as u32).filter_map(char::from_u32).map(|i| i.to_string()) {
assert_eq!(lev_distance(&c[..], &c[..], usize::MAX), Some(0)); assert_eq!(lev_distance(&c[..], &c[..], usize::MAX), Some(0));
} }

View file

@ -42,8 +42,6 @@
#![stable(feature = "rust1", since = "1.0.0")] #![stable(feature = "rust1", since = "1.0.0")]
#[cfg(not(no_global_oom_handling))]
use core::char::{decode_utf16, REPLACEMENT_CHARACTER};
use core::error::Error; use core::error::Error;
use core::fmt; use core::fmt;
use core::hash; use core::hash;
@ -683,7 +681,7 @@ impl String {
// This isn't done via collect::<Result<_, _>>() for performance reasons. // This isn't done via collect::<Result<_, _>>() for performance reasons.
// FIXME: the function can be simplified again when #48994 is closed. // FIXME: the function can be simplified again when #48994 is closed.
let mut ret = String::with_capacity(v.len()); let mut ret = String::with_capacity(v.len());
for c in decode_utf16(v.iter().cloned()) { for c in char::decode_utf16(v.iter().cloned()) {
if let Ok(c) = c { if let Ok(c) = c {
ret.push(c); ret.push(c);
} else { } else {
@ -722,7 +720,9 @@ impl String {
#[inline] #[inline]
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
pub fn from_utf16_lossy(v: &[u16]) -> String { pub fn from_utf16_lossy(v: &[u16]) -> String {
decode_utf16(v.iter().cloned()).map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)).collect() char::decode_utf16(v.iter().cloned())
.map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
.collect()
} }
/// Decomposes a `String` into its raw components. /// Decomposes a `String` into its raw components.

View file

@ -3,8 +3,6 @@
use crate::error::Error; use crate::error::Error;
use crate::fmt; use crate::fmt;
use super::from_u32_unchecked;
/// An iterator that decodes UTF-16 encoded code points from an iterator of `u16`s. /// An iterator that decodes UTF-16 encoded code points from an iterator of `u16`s.
/// ///
/// This `struct` is created by the [`decode_utf16`] method on [`char`]. See its /// This `struct` is created by the [`decode_utf16`] method on [`char`]. See its
@ -49,7 +47,7 @@ impl<I: Iterator<Item = u16>> Iterator for DecodeUtf16<I> {
if !u.is_utf16_surrogate() { if !u.is_utf16_surrogate() {
// SAFETY: not a surrogate // SAFETY: not a surrogate
Some(Ok(unsafe { from_u32_unchecked(u as u32) })) Some(Ok(unsafe { char::from_u32_unchecked(u as u32) }))
} else if u >= 0xDC00 { } else if u >= 0xDC00 {
// a trailing surrogate // a trailing surrogate
Some(Err(DecodeUtf16Error { code: u })) Some(Err(DecodeUtf16Error { code: u }))
@ -69,7 +67,7 @@ impl<I: Iterator<Item = u16>> Iterator for DecodeUtf16<I> {
// all ok, so lets decode it. // all ok, so lets decode it.
let c = (((u & 0x3ff) as u32) << 10 | (u2 & 0x3ff) as u32) + 0x1_0000; let c = (((u & 0x3ff) as u32) << 10 | (u2 & 0x3ff) as u32) + 0x1_0000;
// SAFETY: we checked that it's a legal unicode value // SAFETY: we checked that it's a legal unicode value
Some(Ok(unsafe { from_u32_unchecked(c) })) Some(Ok(unsafe { char::from_u32_unchecked(c) }))
} }
} }

View file

@ -53,15 +53,13 @@ impl char {
/// Basic usage: /// Basic usage:
/// ///
/// ``` /// ```
/// use std::char::decode_utf16;
///
/// // 𝄞mus<invalid>ic<invalid> /// // 𝄞mus<invalid>ic<invalid>
/// let v = [ /// let v = [
/// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834, /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
/// ]; /// ];
/// ///
/// assert_eq!( /// assert_eq!(
/// decode_utf16(v) /// char::decode_utf16(v)
/// .map(|r| r.map_err(|e| e.unpaired_surrogate())) /// .map(|r| r.map_err(|e| e.unpaired_surrogate()))
/// .collect::<Vec<_>>(), /// .collect::<Vec<_>>(),
/// vec![ /// vec![
@ -77,16 +75,14 @@ impl char {
/// A lossy decoder can be obtained by replacing `Err` results with the replacement character: /// A lossy decoder can be obtained by replacing `Err` results with the replacement character:
/// ///
/// ``` /// ```
/// use std::char::{decode_utf16, REPLACEMENT_CHARACTER};
///
/// // 𝄞mus<invalid>ic<invalid> /// // 𝄞mus<invalid>ic<invalid>
/// let v = [ /// let v = [
/// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834, /// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
/// ]; /// ];
/// ///
/// assert_eq!( /// assert_eq!(
/// decode_utf16(v) /// char::decode_utf16(v)
/// .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER)) /// .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
/// .collect::<String>(), /// .collect::<String>(),
/// "𝄞mus<75>ic<69>" /// "𝄞mus<75>ic<69>"
/// ); /// );
@ -123,8 +119,6 @@ impl char {
/// Basic usage: /// Basic usage:
/// ///
/// ``` /// ```
/// use std::char;
///
/// let c = char::from_u32(0x2764); /// let c = char::from_u32(0x2764);
/// ///
/// assert_eq!(Some('❤'), c); /// assert_eq!(Some('❤'), c);
@ -133,8 +127,6 @@ impl char {
/// Returning `None` when the input is not a valid `char`: /// Returning `None` when the input is not a valid `char`:
/// ///
/// ``` /// ```
/// use std::char;
///
/// let c = char::from_u32(0x110000); /// let c = char::from_u32(0x110000);
/// ///
/// assert_eq!(None, c); /// assert_eq!(None, c);
@ -176,8 +168,6 @@ impl char {
/// Basic usage: /// Basic usage:
/// ///
/// ``` /// ```
/// use std::char;
///
/// let c = unsafe { char::from_u32_unchecked(0x2764) }; /// let c = unsafe { char::from_u32_unchecked(0x2764) };
/// ///
/// assert_eq!('❤', c); /// assert_eq!('❤', c);
@ -210,8 +200,6 @@ impl char {
/// Basic usage: /// Basic usage:
/// ///
/// ``` /// ```
/// use std::char;
///
/// let c = char::from_digit(4, 10); /// let c = char::from_digit(4, 10);
/// ///
/// assert_eq!(Some('4'), c); /// assert_eq!(Some('4'), c);
@ -225,8 +213,6 @@ impl char {
/// Returning `None` when the input is not a digit: /// Returning `None` when the input is not a digit:
/// ///
/// ``` /// ```
/// use std::char;
///
/// let c = char::from_digit(20, 10); /// let c = char::from_digit(20, 10);
/// ///
/// assert_eq!(None, c); /// assert_eq!(None, c);
@ -235,8 +221,6 @@ impl char {
/// Passing a large radix, causing a panic: /// Passing a large radix, causing a panic:
/// ///
/// ```should_panic /// ```should_panic
/// use std::char;
///
/// // this panics /// // this panics
/// let _c = char::from_digit(1, 37); /// let _c = char::from_digit(1, 37);
/// ``` /// ```
@ -1786,7 +1770,7 @@ pub fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
} else { } else {
panic!( panic!(
"encode_utf16: need {} units to encode U+{:X}, but the buffer has {}", "encode_utf16: need {} units to encode U+{:X}, but the buffer has {}",
from_u32_unchecked(code).len_utf16(), char::from_u32_unchecked(code).len_utf16(),
code, code,
dst.len(), dst.len(),
) )

View file

@ -189,7 +189,7 @@ impl Iterator for EscapeUnicode {
} }
EscapeUnicodeState::Value => { EscapeUnicodeState::Value => {
let hex_digit = ((self.c as u32) >> (self.hex_digit_idx * 4)) & 0xf; let hex_digit = ((self.c as u32) >> (self.hex_digit_idx * 4)) & 0xf;
let c = from_digit(hex_digit, 16).unwrap(); let c = char::from_digit(hex_digit, 16).unwrap();
if self.hex_digit_idx == 0 { if self.hex_digit_idx == 0 {
self.state = EscapeUnicodeState::RightBrace; self.state = EscapeUnicodeState::RightBrace;
} else { } else {

View file

@ -1,4 +1,3 @@
use crate::char;
use crate::convert::TryFrom; use crate::convert::TryFrom;
use crate::mem; use crate::mem;
use crate::ops::{self, Try}; use crate::ops::{self, Try};

View file

@ -1,6 +1,6 @@
//! Iterators for `str` methods. //! Iterators for `str` methods.
use crate::char; use crate::char as char_mod;
use crate::fmt::{self, Write}; use crate::fmt::{self, Write};
use crate::iter::{Chain, FlatMap, Flatten}; use crate::iter::{Chain, FlatMap, Flatten};
use crate::iter::{Copied, Filter, FusedIterator, Map, TrustedLen}; use crate::iter::{Copied, Filter, FusedIterator, Map, TrustedLen};
@ -1455,8 +1455,8 @@ impl FusedIterator for EncodeUtf16<'_> {}
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct EscapeDebug<'a> { pub struct EscapeDebug<'a> {
pub(super) inner: Chain< pub(super) inner: Chain<
Flatten<option::IntoIter<char::EscapeDebug>>, Flatten<option::IntoIter<char_mod::EscapeDebug>>,
FlatMap<Chars<'a>, char::EscapeDebug, CharEscapeDebugContinue>, FlatMap<Chars<'a>, char_mod::EscapeDebug, CharEscapeDebugContinue>,
>, >,
} }
@ -1464,14 +1464,14 @@ pub struct EscapeDebug<'a> {
#[stable(feature = "str_escape", since = "1.34.0")] #[stable(feature = "str_escape", since = "1.34.0")]
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct EscapeDefault<'a> { pub struct EscapeDefault<'a> {
pub(super) inner: FlatMap<Chars<'a>, char::EscapeDefault, CharEscapeDefault>, pub(super) inner: FlatMap<Chars<'a>, char_mod::EscapeDefault, CharEscapeDefault>,
} }
/// The return type of [`str::escape_unicode`]. /// The return type of [`str::escape_unicode`].
#[stable(feature = "str_escape", since = "1.34.0")] #[stable(feature = "str_escape", since = "1.34.0")]
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct EscapeUnicode<'a> { pub struct EscapeUnicode<'a> {
pub(super) inner: FlatMap<Chars<'a>, char::EscapeUnicode, CharEscapeUnicode>, pub(super) inner: FlatMap<Chars<'a>, char_mod::EscapeUnicode, CharEscapeUnicode>,
} }
macro_rules! escape_types_impls { macro_rules! escape_types_impls {

View file

@ -26,7 +26,6 @@ fn test_range() {
#[test] #[test]
fn test_char_range() { fn test_char_range() {
use std::char;
// Miri is too slow // Miri is too slow
let from = if cfg!(miri) { char::from_u32(0xD800 - 10).unwrap() } else { '\0' }; let from = if cfg!(miri) { char::from_u32(0xD800 - 10).unwrap() } else { '\0' };
let to = if cfg!(miri) { char::from_u32(0xDFFF + 10).unwrap() } else { char::MAX }; let to = if cfg!(miri) { char::from_u32(0xDFFF + 10).unwrap() } else { char::MAX };

View file

@ -1,7 +1,6 @@
//! Serialization for client-server communication. //! Serialization for client-server communication.
use std::any::Any; use std::any::Any;
use std::char;
use std::io::Write; use std::io::Write;
use std::num::NonZeroU32; use std::num::NonZeroU32;
use std::str; use std::str;

View file

@ -1,6 +1,5 @@
#![unstable(issue = "none", feature = "windows_stdio")] #![unstable(issue = "none", feature = "windows_stdio")]
use crate::char::decode_utf16;
use crate::cmp; use crate::cmp;
use crate::io; use crate::io;
use crate::mem::MaybeUninit; use crate::mem::MaybeUninit;
@ -369,7 +368,7 @@ fn read_u16s(handle: c::HANDLE, buf: &mut [MaybeUninit<u16>]) -> io::Result<usiz
#[allow(unused)] #[allow(unused)]
fn utf16_to_utf8(utf16: &[u16], utf8: &mut [u8]) -> io::Result<usize> { fn utf16_to_utf8(utf16: &[u16], utf8: &mut [u8]) -> io::Result<usize> {
let mut written = 0; let mut written = 0;
for chr in decode_utf16(utf16.iter().cloned()) { for chr in char::decode_utf16(utf16.iter().cloned()) {
match chr { match chr {
Ok(chr) => { Ok(chr) => {
chr.encode_utf8(&mut utf8[written..]); chr.encode_utf8(&mut utf8[written..]);

View file

@ -18,10 +18,10 @@
#[cfg(test)] #[cfg(test)]
mod tests; mod tests;
use core::char::{encode_utf16_raw, encode_utf8_raw};
use core::str::next_code_point; use core::str::next_code_point;
use crate::borrow::Cow; use crate::borrow::Cow;
use crate::char;
use crate::collections::TryReserveError; use crate::collections::TryReserveError;
use crate::fmt; use crate::fmt;
use crate::hash::{Hash, Hasher}; use crate::hash::{Hash, Hasher};
@ -235,7 +235,7 @@ impl Wtf8Buf {
/// This does **not** include the WTF-8 concatenation check or `is_known_utf8` check. /// This does **not** include the WTF-8 concatenation check or `is_known_utf8` check.
fn push_code_point_unchecked(&mut self, code_point: CodePoint) { fn push_code_point_unchecked(&mut self, code_point: CodePoint) {
let mut bytes = [0; 4]; let mut bytes = [0; 4];
let bytes = char::encode_utf8_raw(code_point.value, &mut bytes); let bytes = encode_utf8_raw(code_point.value, &mut bytes);
self.bytes.extend_from_slice(bytes) self.bytes.extend_from_slice(bytes)
} }
@ -939,7 +939,7 @@ impl<'a> Iterator for EncodeWide<'a> {
let mut buf = [0; 2]; let mut buf = [0; 2];
self.code_points.next().map(|code_point| { self.code_points.next().map(|code_point| {
let n = char::encode_utf16_raw(code_point.value, &mut buf).len(); let n = encode_utf16_raw(code_point.value, &mut buf).len();
if n == 2 { if n == 2 {
self.extra = buf[1]; self.extra = buf[1];
} }