Skip to content

Commit

Permalink
Use associated items of char instead of freestanding items in `core…
Browse files Browse the repository at this point in the history
…::char`
  • Loading branch information
Lukas Markeffsky committed Jan 14, 2023
1 parent c0b8735 commit 76e216f
Show file tree
Hide file tree
Showing 12 changed files with 21 additions and 45 deletions.
1 change: 0 additions & 1 deletion compiler/rustc_middle/src/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ use rustc_target::spec::abi::Abi;
use smallvec::SmallVec;

use std::cell::Cell;
use std::char;
use std::collections::BTreeMap;
use std::fmt::{self, Write as _};
use std::iter;
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_span/src/lev_distance/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ use super::*;

#[test]
fn test_lev_distance() {
use std::char::{from_u32, MAX};
// 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));
}

Expand Down
8 changes: 4 additions & 4 deletions library/alloc/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@

#![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::fmt;
use core::hash;
Expand Down Expand Up @@ -683,7 +681,7 @@ impl String {
// This isn't done via collect::<Result<_, _>>() for performance reasons.
// FIXME: the function can be simplified again when #48994 is closed.
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 {
ret.push(c);
} else {
Expand Down Expand Up @@ -722,7 +720,9 @@ impl String {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
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.
Expand Down
6 changes: 2 additions & 4 deletions library/core/src/char/decode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@
use crate::error::Error;
use crate::fmt;

use super::from_u32_unchecked;

/// 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
Expand Down Expand Up @@ -49,7 +47,7 @@ impl<I: Iterator<Item = u16>> Iterator for DecodeUtf16<I> {

if !u.is_utf16_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 {
// a trailing surrogate
Some(Err(DecodeUtf16Error { code: u }))
Expand All @@ -69,7 +67,7 @@ impl<I: Iterator<Item = u16>> Iterator for DecodeUtf16<I> {
// all ok, so lets decode it.
let c = (((u & 0x3ff) as u32) << 10 | (u2 & 0x3ff) as u32) + 0x1_0000;
// 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) }))
}
}

Expand Down
24 changes: 4 additions & 20 deletions library/core/src/char/methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,13 @@ impl char {
/// Basic usage:
///
/// ```
/// use std::char::decode_utf16;
///
/// // 𝄞mus<invalid>ic<invalid>
/// let v = [
/// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
/// ];
///
/// assert_eq!(
/// decode_utf16(v)
/// char::decode_utf16(v)
/// .map(|r| r.map_err(|e| e.unpaired_surrogate()))
/// .collect::<Vec<_>>(),
/// vec![
Expand All @@ -77,16 +75,14 @@ impl char {
/// 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>
/// let v = [
/// 0xD834, 0xDD1E, 0x006d, 0x0075, 0x0073, 0xDD1E, 0x0069, 0x0063, 0xD834,
/// ];
///
/// assert_eq!(
/// decode_utf16(v)
/// .map(|r| r.unwrap_or(REPLACEMENT_CHARACTER))
/// char::decode_utf16(v)
/// .map(|r| r.unwrap_or(char::REPLACEMENT_CHARACTER))
/// .collect::<String>(),
/// "𝄞mus�ic�"
/// );
Expand Down Expand Up @@ -123,8 +119,6 @@ impl char {
/// Basic usage:
///
/// ```
/// use std::char;
///
/// let c = char::from_u32(0x2764);
///
/// assert_eq!(Some('❤'), c);
Expand All @@ -133,8 +127,6 @@ impl char {
/// Returning `None` when the input is not a valid `char`:
///
/// ```
/// use std::char;
///
/// let c = char::from_u32(0x110000);
///
/// assert_eq!(None, c);
Expand Down Expand Up @@ -176,8 +168,6 @@ impl char {
/// Basic usage:
///
/// ```
/// use std::char;
///
/// let c = unsafe { char::from_u32_unchecked(0x2764) };
///
/// assert_eq!('❤', c);
Expand Down Expand Up @@ -210,8 +200,6 @@ impl char {
/// Basic usage:
///
/// ```
/// use std::char;
///
/// let c = char::from_digit(4, 10);
///
/// assert_eq!(Some('4'), c);
Expand All @@ -225,8 +213,6 @@ impl char {
/// Returning `None` when the input is not a digit:
///
/// ```
/// use std::char;
///
/// let c = char::from_digit(20, 10);
///
/// assert_eq!(None, c);
Expand All @@ -235,8 +221,6 @@ impl char {
/// Passing a large radix, causing a panic:
///
/// ```should_panic
/// use std::char;
///
/// // this panics
/// let _c = char::from_digit(1, 37);
/// ```
Expand Down Expand Up @@ -1786,7 +1770,7 @@ pub fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] {
} else {
panic!(
"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,
dst.len(),
)
Expand Down
2 changes: 1 addition & 1 deletion library/core/src/char/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ impl Iterator for EscapeUnicode {
}
EscapeUnicodeState::Value => {
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 {
self.state = EscapeUnicodeState::RightBrace;
} else {
Expand Down
1 change: 0 additions & 1 deletion library/core/src/iter/range.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use crate::char;
use crate::convert::TryFrom;
use crate::mem;
use crate::ops::{self, Try};
Expand Down
10 changes: 5 additions & 5 deletions library/core/src/str/iter.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Iterators for `str` methods.

use crate::char;
use crate::char as char_mod;
use crate::fmt::{self, Write};
use crate::iter::{Chain, FlatMap, Flatten};
use crate::iter::{Copied, Filter, FusedIterator, Map, TrustedLen};
Expand Down Expand Up @@ -1455,23 +1455,23 @@ impl FusedIterator for EncodeUtf16<'_> {}
#[derive(Clone, Debug)]
pub struct EscapeDebug<'a> {
pub(super) inner: Chain<
Flatten<option::IntoIter<char::EscapeDebug>>,
FlatMap<Chars<'a>, char::EscapeDebug, CharEscapeDebugContinue>,
Flatten<option::IntoIter<char_mod::EscapeDebug>>,
FlatMap<Chars<'a>, char_mod::EscapeDebug, CharEscapeDebugContinue>,
>,
}

/// The return type of [`str::escape_default`].
#[stable(feature = "str_escape", since = "1.34.0")]
#[derive(Clone, Debug)]
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`].
#[stable(feature = "str_escape", since = "1.34.0")]
#[derive(Clone, Debug)]
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 {
Expand Down
1 change: 0 additions & 1 deletion library/core/tests/iter/range.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ fn test_range() {

#[test]
fn test_char_range() {
use std::char;
// Miri is too slow
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 };
Expand Down
1 change: 0 additions & 1 deletion library/proc_macro/src/bridge/rpc.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//! Serialization for client-server communication.

use std::any::Any;
use std::char;
use std::io::Write;
use std::num::NonZeroU32;
use std::str;
Expand Down
3 changes: 1 addition & 2 deletions library/std/src/sys/windows/stdio.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#![unstable(issue = "none", feature = "windows_stdio")]

use crate::char::decode_utf16;
use crate::cmp;
use crate::io;
use crate::mem::MaybeUninit;
Expand Down Expand Up @@ -369,7 +368,7 @@ fn read_u16s(handle: c::HANDLE, buf: &mut [MaybeUninit<u16>]) -> io::Result<usiz
#[allow(unused)]
fn utf16_to_utf8(utf16: &[u16], utf8: &mut [u8]) -> io::Result<usize> {
let mut written = 0;
for chr in decode_utf16(utf16.iter().cloned()) {
for chr in char::decode_utf16(utf16.iter().cloned()) {
match chr {
Ok(chr) => {
chr.encode_utf8(&mut utf8[written..]);
Expand Down
6 changes: 3 additions & 3 deletions library/std/src/sys_common/wtf8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@
#[cfg(test)]
mod tests;

use core::char::{encode_utf16_raw, encode_utf8_raw};
use core::str::next_code_point;

use crate::borrow::Cow;
use crate::char;
use crate::collections::TryReserveError;
use crate::fmt;
use crate::hash::{Hash, Hasher};
Expand Down Expand Up @@ -235,7 +235,7 @@ impl Wtf8Buf {
/// This does **not** include the WTF-8 concatenation check or `is_known_utf8` check.
fn push_code_point_unchecked(&mut self, code_point: CodePoint) {
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)
}

Expand Down Expand Up @@ -939,7 +939,7 @@ impl<'a> Iterator for EncodeWide<'a> {

let mut buf = [0; 2];
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 {
self.extra = buf[1];
}
Expand Down

0 comments on commit 76e216f

Please sign in to comment.