Skip to content

library: Move CStr to libcore, and CString to liballoc #94079

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 15, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Cargo.lock
Original file line number Diff line number Diff line change
@@ -731,9 +731,9 @@ dependencies = [

[[package]]
name = "compiler_builtins"
version = "0.1.70"
version = "0.1.71"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80873f979f0a344a4ade87c2f70d9ccf5720b83b10c97ec7cd745895d021e85a"
checksum = "163437f05ca8f29d7e9128ea728dedf5eb620e445fbca273641d3a3050305f23"
dependencies = [
"cc",
"rustc-std-workspace-core",
2 changes: 2 additions & 0 deletions compiler/rustc_hir/src/lang_items.rs
Original file line number Diff line number Diff line change
@@ -326,6 +326,8 @@ language_item_table! {
Range, sym::Range, range_struct, Target::Struct, GenericRequirement::None;
RangeToInclusive, sym::RangeToInclusive, range_to_inclusive_struct, Target::Struct, GenericRequirement::None;
RangeTo, sym::RangeTo, range_to_struct, Target::Struct, GenericRequirement::None;

CStr, sym::CStr, c_str, Target::Struct, GenericRequirement::None;
}

pub enum GenericRequirement {
1 change: 1 addition & 0 deletions compiler/rustc_metadata/src/creader.rs
Original file line number Diff line number Diff line change
@@ -417,6 +417,7 @@ impl<'a> CrateLoader<'a> {

let crate_metadata = CrateMetadata::new(
self.sess,
&self.cstore,
metadata,
crate_root,
raw_proc_macros,
24 changes: 15 additions & 9 deletions compiler/rustc_metadata/src/rmeta/decoder.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Decoding metadata from a single crate's metadata

use crate::creader::CrateMetadataRef;
use crate::creader::{CStore, CrateMetadataRef};
use crate::rmeta::table::{FixedSizeEncoding, Table};
use crate::rmeta::*;

@@ -1737,6 +1737,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
impl CrateMetadata {
crate fn new(
sess: &Session,
cstore: &CStore,
blob: MetadataBlob,
root: CrateRoot<'static>,
raw_proc_macros: Option<&'static [ProcMacro]>,
@@ -1752,11 +1753,6 @@ impl CrateMetadata {
.decode((&blob, sess))
.map(|trait_impls| (trait_impls.trait_id, trait_impls.impls))
.collect();
let incoherent_impls = root
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this change related? It doesn't seem to be documented in the PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a bugfix for #94963 to account for incoherent impl types having DefIds, without it this PR ICEs.

.incoherent_impls
.decode((&blob, sess))
.map(|incoherent_impls| (incoherent_impls.self_ty, incoherent_impls.impls))
.collect();
let alloc_decoding_state =
AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect());
let dependencies = Lock::new(cnum_map.iter().cloned().collect());
@@ -1765,11 +1761,11 @@ impl CrateMetadata {
// that does not copy any data. It just does some data verification.
let def_path_hash_map = root.def_path_hash_map.decode(&blob);

CrateMetadata {
let mut cdata = CrateMetadata {
blob,
root,
trait_impls,
incoherent_impls,
incoherent_impls: Default::default(),
raw_proc_macros,
source_map_import_info: OnceCell::new(),
def_path_hash_map,
@@ -1786,7 +1782,17 @@ impl CrateMetadata {
hygiene_context: Default::default(),
def_key_cache: Default::default(),
def_path_hash_cache: Default::default(),
}
};

// Need `CrateMetadataRef` to decode `DefId`s in simplified types.
cdata.incoherent_impls = cdata
.root
.incoherent_impls
.decode(CrateMetadataRef { cdata: &cdata, cstore })
.map(|incoherent_impls| (incoherent_impls.self_ty, incoherent_impls.impls))
.collect();

cdata
}

crate fn dependencies(&self) -> LockGuard<'_, Vec<CrateNum>> {
6 changes: 5 additions & 1 deletion compiler/rustc_typeck/src/check/method/probe.rs
Original file line number Diff line number Diff line change
@@ -644,7 +644,11 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> {
self.assemble_inherent_impl_candidates_for_type(p.def_id());
}
ty::Adt(def, _) => {
self.assemble_inherent_impl_candidates_for_type(def.did());
let def_id = def.did();
self.assemble_inherent_impl_candidates_for_type(def_id);
if Some(def_id) == self.tcx.lang_items().c_str() {
self.assemble_inherent_candidates_for_incoherent_ty(raw_self_ty);
}
}
ty::Foreign(did) => {
self.assemble_inherent_impl_candidates_for_type(did);
7 changes: 6 additions & 1 deletion compiler/rustc_typeck/src/coherence/inherent_impls.rs
Original file line number Diff line number Diff line change
@@ -55,7 +55,12 @@ impl<'tcx> ItemLikeVisitor<'_> for InherentCollect<'tcx> {
let self_ty = self.tcx.type_of(item.def_id);
match *self_ty.kind() {
ty::Adt(def, _) => {
self.check_def_id(item, def.did());
let def_id = def.did();
if !def_id.is_local() && Some(def_id) == self.tcx.lang_items().c_str() {
self.check_primitive_impl(item.def_id, self_ty, items, ty.span)
} else {
self.check_def_id(item, def_id);
}
}
ty::Foreign(did) => {
self.check_def_id(item, did);
743 changes: 132 additions & 611 deletions library/std/src/ffi/c_str.rs → library/alloc/src/ffi/c_str.rs

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
use super::*;
use crate::borrow::Cow::{Borrowed, Owned};
use crate::collections::hash_map::DefaultHasher;
use crate::hash::{Hash, Hasher};
use crate::os::raw::c_char;
use crate::rc::Rc;
use crate::sync::Arc;
use core::assert_matches::assert_matches;
use core::ffi::FromBytesUntilNulError;
use core::hash::{Hash, Hasher};

#[allow(deprecated)]
use core::hash::SipHasher13 as DefaultHasher;

#[test]
fn c_to_rust() {
@@ -47,22 +49,6 @@ fn borrowed() {
}
}

#[test]
fn to_str() {
let data = b"123\xE2\x80\xA6\0";
let ptr = data.as_ptr() as *const c_char;
unsafe {
assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
}
let data = b"123\xE2\0";
let ptr = data.as_ptr() as *const c_char;
unsafe {
assert!(CStr::from_ptr(ptr).to_str().is_err());
assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
}
}

#[test]
fn to_owned() {
let data = b"123\0";
@@ -78,9 +64,11 @@ fn equal_hash() {
let ptr = data.as_ptr() as *const c_char;
let cstr: &'static CStr = unsafe { CStr::from_ptr(ptr) };

#[allow(deprecated)]
let mut s = DefaultHasher::new();
cstr.hash(&mut s);
let cstr_hash = s.finish();
#[allow(deprecated)]
let mut s = DefaultHasher::new();
CString::new(&data[..data.len() - 1]).unwrap().hash(&mut s);
let cstring_hash = s.finish();
@@ -122,11 +110,11 @@ fn cstr_from_bytes_until_nul() {
// Test an empty slice. This should fail because it
// does not contain a nul byte.
let b = b"";
assert_eq!(CStr::from_bytes_until_nul(&b[..]), Err(FromBytesUntilNulError(())));
assert_matches!(CStr::from_bytes_until_nul(&b[..]), Err(FromBytesUntilNulError { .. }));

// Test a non-empty slice, that does not contain a nul byte.
let b = b"hello";
assert_eq!(CStr::from_bytes_until_nul(&b[..]), Err(FromBytesUntilNulError(())));
assert_matches!(CStr::from_bytes_until_nul(&b[..]), Err(FromBytesUntilNulError { .. }));

// Test an empty nul-terminated string
let b = b"\0";
91 changes: 91 additions & 0 deletions library/alloc/src/ffi/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
//! Utilities related to FFI bindings.
//!
//! This module provides utilities to handle data across non-Rust
//! interfaces, like other programming languages and the underlying
//! operating system. It is mainly of use for FFI (Foreign Function
//! Interface) bindings and code that needs to exchange C-like strings
//! with other languages.
//!
//! # Overview
//!
//! Rust represents owned strings with the [`String`] type, and
//! borrowed slices of strings with the [`str`] primitive. Both are
//! always in UTF-8 encoding, and may contain nul bytes in the middle,
//! i.e., if you look at the bytes that make up the string, there may
//! be a `\0` among them. Both `String` and `str` store their length
//! explicitly; there are no nul terminators at the end of strings
//! like in C.
//!
//! C strings are different from Rust strings:
//!
//! * **Encodings** - Rust strings are UTF-8, but C strings may use
//! other encodings. If you are using a string from C, you should
//! check its encoding explicitly, rather than just assuming that it
//! is UTF-8 like you can do in Rust.
//!
//! * **Character size** - C strings may use `char` or `wchar_t`-sized
//! characters; please **note** that C's `char` is different from Rust's.
//! The C standard leaves the actual sizes of those types open to
//! interpretation, but defines different APIs for strings made up of
//! each character type. Rust strings are always UTF-8, so different
//! Unicode characters will be encoded in a variable number of bytes
//! each. The Rust type [`char`] represents a '[Unicode scalar
//! value]', which is similar to, but not the same as, a '[Unicode
//! code point]'.
//!
//! * **Nul terminators and implicit string lengths** - Often, C
//! strings are nul-terminated, i.e., they have a `\0` character at the
//! end. The length of a string buffer is not stored, but has to be
//! calculated; to compute the length of a string, C code must
//! manually call a function like `strlen()` for `char`-based strings,
//! or `wcslen()` for `wchar_t`-based ones. Those functions return
//! the number of characters in the string excluding the nul
//! terminator, so the buffer length is really `len+1` characters.
//! Rust strings don't have a nul terminator; their length is always
//! stored and does not need to be calculated. While in Rust
//! accessing a string's length is an *O*(1) operation (because the
//! length is stored); in C it is an *O*(*n*) operation because the
//! length needs to be computed by scanning the string for the nul
//! terminator.
//!
//! * **Internal nul characters** - When C strings have a nul
//! terminator character, this usually means that they cannot have nul
//! characters in the middle — a nul character would essentially
//! truncate the string. Rust strings *can* have nul characters in
//! the middle, because nul does not have to mark the end of the
//! string in Rust.
//!
//! # Representations of non-Rust strings
//!
//! [`CString`] and [`CStr`] are useful when you need to transfer
//! UTF-8 strings to and from languages with a C ABI, like Python.
//!
//! * **From Rust to C:** [`CString`] represents an owned, C-friendly
//! string: it is nul-terminated, and has no internal nul characters.
//! Rust code can create a [`CString`] out of a normal string (provided
//! that the string doesn't have nul characters in the middle), and
//! then use a variety of methods to obtain a raw <code>\*mut [u8]</code> that can
//! then be passed as an argument to functions which use the C
//! conventions for strings.
//!
//! * **From C to Rust:** [`CStr`] represents a borrowed C string; it
//! is what you would use to wrap a raw <code>\*const [u8]</code> that you got from
//! a C function. A [`CStr`] is guaranteed to be a nul-terminated array
//! of bytes. Once you have a [`CStr`], you can convert it to a Rust
//! <code>&[str]</code> if it's valid UTF-8, or lossily convert it by adding
//! replacement characters.
//!
//! [`String`]: crate::string::String
//! [`CStr`]: core::ffi::CStr
#![unstable(feature = "alloc_ffi", issue = "94079")]

#[cfg(bootstrap)]
#[unstable(feature = "cstr_internals", issue = "none")]
pub use self::c_str::CStrExt;
#[unstable(feature = "alloc_c_string", issue = "94079")]
pub use self::c_str::FromVecWithNulError;
#[unstable(feature = "alloc_c_string", issue = "94079")]
pub use self::c_str::{CString, IntoStringError, NulError};

mod c_str;
9 changes: 9 additions & 0 deletions library/alloc/src/lib.rs
Original file line number Diff line number Diff line change
@@ -86,11 +86,13 @@
#![allow(explicit_outlives_requirements)]
//
// Library features:
#![cfg_attr(not(no_global_oom_handling), feature(alloc_c_string))]
#![feature(alloc_layout_extra)]
#![feature(allocator_api)]
#![feature(array_chunks)]
#![feature(array_methods)]
#![feature(array_windows)]
#![feature(assert_matches)]
#![feature(async_iterator)]
#![feature(coerce_unsized)]
#![cfg_attr(not(no_global_oom_handling), feature(const_alloc_error))]
@@ -104,9 +106,12 @@
#![feature(const_maybe_uninit_write)]
#![feature(const_maybe_uninit_as_mut_ptr)]
#![feature(const_refs_to_cell)]
#![feature(core_c_str)]
#![feature(core_intrinsics)]
#![feature(core_ffi_c)]
#![feature(const_eval_select)]
#![feature(const_pin)]
#![feature(cstr_from_bytes_until_nul)]
#![feature(dispatch_from_dyn)]
#![feature(exact_size_is_empty)]
#![feature(extend_one)]
@@ -152,6 +157,7 @@
#![feature(exclusive_range_pattern)]
#![feature(fundamental)]
#![cfg_attr(not(test), feature(generator_trait))]
#![feature(hashmap_internals)]
#![feature(lang_items)]
#![feature(let_else)]
#![feature(min_specialization)]
@@ -160,6 +166,7 @@
#![feature(nll)] // Not necessary, but here to test the `nll` feature.
#![feature(rustc_allow_const_fn_unstable)]
#![feature(rustc_attrs)]
#![feature(slice_internals)]
#![feature(staged_api)]
#![cfg_attr(test, feature(test))]
#![feature(unboxed_closures)]
@@ -205,6 +212,8 @@ mod boxed {
}
pub mod borrow;
pub mod collections;
#[cfg(not(no_global_oom_handling))]
pub mod ffi;
pub mod fmt;
pub mod rc;
pub mod slice;
2 changes: 1 addition & 1 deletion library/alloc/src/slice.rs
Original file line number Diff line number Diff line change
@@ -153,7 +153,7 @@ pub use hack::to_vec;
// functions are actually methods that are in `impl [T]` but not in
// `core::slice::SliceExt` - we need to supply these functions for the
// `test_permutations` test
mod hack {
pub(crate) mod hack {
use core::alloc::Allocator;

use crate::boxed::Box;
18 changes: 18 additions & 0 deletions library/alloc/tests/c_str.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
use std::borrow::Cow::{Borrowed, Owned};
use std::ffi::{c_char, CStr};

#[test]
fn to_str() {
let data = b"123\xE2\x80\xA6\0";
let ptr = data.as_ptr() as *const c_char;
unsafe {
assert_eq!(CStr::from_ptr(ptr).to_str(), Ok("123…"));
assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Borrowed("123…"));
}
let data = b"123\xE2\0";
let ptr = data.as_ptr() as *const c_char;
unsafe {
assert!(CStr::from_ptr(ptr).to_str().is_err());
assert_eq!(CStr::from_ptr(ptr).to_string_lossy(), Owned::<str>(format!("123\u{FFFD}")));
}
}
3 changes: 3 additions & 0 deletions library/alloc/tests/lib.rs
Original file line number Diff line number Diff line change
@@ -12,6 +12,8 @@
#![feature(const_nonnull_slice_from_raw_parts)]
#![feature(const_ptr_write)]
#![feature(const_try)]
#![feature(core_c_str)]
#![feature(core_ffi_c)]
#![feature(core_intrinsics)]
#![feature(drain_filter)]
#![feature(exact_size_is_empty)]
@@ -49,6 +51,7 @@ mod binary_heap;
mod borrow;
mod boxed;
mod btree_set_hash;
mod c_str;
mod const_fns;
mod cow_str;
mod fmt;
570 changes: 570 additions & 0 deletions library/core/src/ffi/c_str.rs

Large diffs are not rendered by default.

5 changes: 5 additions & 0 deletions library/core/src/ffi/mod.rs
Original file line number Diff line number Diff line change
@@ -14,6 +14,11 @@ use crate::marker::PhantomData;
use crate::num::*;
use crate::ops::{Deref, DerefMut};

#[unstable(feature = "core_c_str", issue = "94079")]
pub use self::c_str::{CStr, FromBytesUntilNulError, FromBytesWithNulError};

mod c_str;

macro_rules! type_alias_no_nz {
{
$Docfile:tt, $Alias:ident = $Real:ty;
2 changes: 1 addition & 1 deletion library/core/src/lib.rs
Original file line number Diff line number Diff line change
@@ -20,7 +20,7 @@
// FIXME: Fill me in with more detail when the interface settles
//! This library is built on the assumption of a few existing symbols:
//!
//! * `memcpy`, `memcmp`, `memset` - These are core memory routines which are
//! * `memcpy`, `memcmp`, `memset`, `strlen` - These are core memory routines which are
//! often generated by LLVM. Additionally, this library can make explicit
//! calls to these functions. Their signatures are the same as found in C.
//! These functions are often provided by the system libc, but can also be
2 changes: 1 addition & 1 deletion library/std/Cargo.toml
Original file line number Diff line number Diff line change
@@ -16,7 +16,7 @@ panic_unwind = { path = "../panic_unwind", optional = true }
panic_abort = { path = "../panic_abort" }
core = { path = "../core" }
libc = { version = "0.2.116", default-features = false, features = ['rustc-dep-of-std'] }
compiler_builtins = { version = "0.1.69" }
compiler_builtins = { version = "0.1.71" }
profiler_builtins = { path = "../profiler_builtins", optional = true }
unwind = { path = "../unwind" }
hashbrown = { version = "0.12", default-features = false, features = ['rustc-dep-of-std'] }
43 changes: 43 additions & 0 deletions library/std/src/error.rs
Original file line number Diff line number Diff line change
@@ -26,6 +26,7 @@ use crate::borrow::Cow;
use crate::cell;
use crate::char;
use crate::fmt::{self, Debug, Display, Write};
use crate::io;
use crate::mem::transmute;
use crate::num;
use crate::str;
@@ -612,6 +613,48 @@ impl Error for alloc::collections::TryReserveError {}
#[unstable(feature = "duration_checked_float", issue = "83400")]
impl Error for time::FromFloatSecsError {}

#[stable(feature = "rust1", since = "1.0.0")]
impl Error for alloc::ffi::NulError {
#[allow(deprecated)]
fn description(&self) -> &str {
"nul byte found in data"
}
}

#[stable(feature = "rust1", since = "1.0.0")]
impl From<alloc::ffi::NulError> for io::Error {
/// Converts a [`alloc::ffi::NulError`] into a [`io::Error`].
fn from(_: alloc::ffi::NulError) -> io::Error {
io::const_io_error!(io::ErrorKind::InvalidInput, "data provided contains a nul byte")
}
}

#[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
impl Error for core::ffi::FromBytesWithNulError {
#[allow(deprecated)]
fn description(&self) -> &str {
self.__description()
}
}

#[unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")]
impl Error for core::ffi::FromBytesUntilNulError {}

#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
impl Error for alloc::ffi::FromVecWithNulError {}

#[stable(feature = "cstring_into", since = "1.7.0")]
impl Error for alloc::ffi::IntoStringError {
#[allow(deprecated)]
fn description(&self) -> &str {
"C string contained non-utf8 bytes"
}

fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(self.__source())
}
}

// Copied from `any.rs`.
impl dyn Error + 'static {
/// Returns `true` if the inner type is the same as `T`.
21 changes: 16 additions & 5 deletions library/std/src/ffi/mod.rs
Original file line number Diff line number Diff line change
@@ -146,12 +146,24 @@
#![stable(feature = "rust1", since = "1.0.0")]

#[stable(feature = "cstr_from_bytes", since = "1.10.0")]
pub use self::c_str::FromBytesWithNulError;
/// See [alloc::ffi::FromVecWithNulError].
#[stable(feature = "cstring_from_vec_with_nul", since = "1.58.0")]
pub use self::c_str::FromVecWithNulError;
pub type FromVecWithNulError = alloc::ffi::FromVecWithNulError;
/// See [alloc::ffi::CString].
#[stable(feature = "rust1", since = "1.0.0")]
pub type CString = alloc::ffi::CString;
/// See [alloc::ffi::IntoStringError].
#[stable(feature = "rust1", since = "1.0.0")]
pub type IntoStringError = alloc::ffi::IntoStringError;
/// See [alloc::ffi::NulError].
#[stable(feature = "rust1", since = "1.0.0")]
pub use self::c_str::{CStr, CString, IntoStringError, NulError};
pub type NulError = alloc::ffi::NulError;
/// See [core::ffi::CStr].
#[stable(feature = "rust1", since = "1.0.0")]
pub type CStr = core::ffi::CStr;
/// See [core::ffi::FromBytesWithNulError].
#[stable(feature = "cstr_from_bytes", since = "1.10.0")]
pub type FromBytesWithNulError = core::ffi::FromBytesWithNulError;

#[stable(feature = "rust1", since = "1.0.0")]
pub use self::os_str::{OsStr, OsString};
@@ -176,5 +188,4 @@ pub use core::ffi::{c_ptrdiff_t, c_size_t, c_ssize_t};
)]
pub use core::ffi::{VaList, VaListImpl};

mod c_str;
mod os_str;
4 changes: 4 additions & 0 deletions library/std/src/lib.rs
Original file line number Diff line number Diff line change
@@ -260,7 +260,10 @@
#![feature(atomic_mut_ptr)]
#![feature(char_error_internals)]
#![feature(char_internals)]
#![feature(core_c_str)]
#![feature(core_intrinsics)]
#![feature(cstr_from_bytes_until_nul)]
#![feature(cstr_internals)]
#![feature(duration_checked_float)]
#![feature(duration_constants)]
#![feature(exact_size_is_empty)]
@@ -286,6 +289,7 @@
//
// Library features (alloc):
#![feature(alloc_layout_extra)]
#![feature(alloc_c_string)]
#![feature(allocator_api)]
#![feature(get_mut_unchecked)]
#![feature(map_try_insert)]
4 changes: 4 additions & 0 deletions library/std/src/prelude/v1.rs
Original file line number Diff line number Diff line change
@@ -95,3 +95,7 @@ pub use crate::string::{String, ToString};
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)]
pub use crate::vec::Vec;

#[cfg(bootstrap)]
#[unstable(feature = "cstr_internals", issue = "none")]
pub use alloc::ffi::CStrExt;
10 changes: 0 additions & 10 deletions library/std/src/sys/hermit/mod.rs
Original file line number Diff line number Diff line change
@@ -71,16 +71,6 @@ pub fn unsupported_err() -> crate::io::Error {
)
}

pub unsafe fn strlen(start: *const c_char) -> usize {
let mut str = start;

while *str != 0 {
str = str.offset(1);
}

(str as usize) - (start as usize)
}

#[no_mangle]
pub extern "C" fn floor(x: f64) -> f64 {
unsafe { intrinsics::floorf64(x) }
10 changes: 0 additions & 10 deletions library/std/src/sys/sgx/mod.rs
Original file line number Diff line number Diff line change
@@ -5,7 +5,6 @@
#![deny(unsafe_op_in_unsafe_fn)]

use crate::io::ErrorKind;
use crate::os::raw::c_char;
use crate::sync::atomic::{AtomicBool, Ordering};

pub mod abi;
@@ -130,15 +129,6 @@ pub fn decode_error_kind(code: i32) -> ErrorKind {
}
}

pub unsafe fn strlen(mut s: *const c_char) -> usize {
let mut n = 0;
while unsafe { *s } != 0 {
n += 1;
s = unsafe { s.offset(1) };
}
return n;
}

pub fn abort_internal() -> ! {
abi::usercalls::exit(true)
}
2 changes: 0 additions & 2 deletions library/std/src/sys/solid/mod.rs
Original file line number Diff line number Diff line change
@@ -99,5 +99,3 @@ pub fn hashmap_random_keys() -> (u64, u64) {
(x1, x2)
}
}

pub use libc::strlen;
1 change: 0 additions & 1 deletion library/std/src/sys/unix/mod.rs
Original file line number Diff line number Diff line change
@@ -3,7 +3,6 @@
use crate::io::ErrorKind;

pub use self::rand::hashmap_random_keys;
pub use libc::strlen;

#[cfg(not(target_os = "espidf"))]
#[macro_use]
16 changes: 0 additions & 16 deletions library/std/src/sys/unsupported/common.rs
Original file line number Diff line number Diff line change
@@ -4,10 +4,6 @@ pub mod memchr {
pub use core::slice::memchr::{memchr, memrchr};
}

// This is not necessarily correct. May want to consider making it part of the
// spec definition?
use crate::os::raw::c_char;

// SAFETY: must be called only once during runtime initialization.
// NOTE: this is not guaranteed to run, for example when Rust code is called externally.
pub unsafe fn init(_argc: isize, _argv: *const *const u8) {}
@@ -38,15 +34,3 @@ pub fn abort_internal() -> ! {
pub fn hashmap_random_keys() -> (u64, u64) {
(1, 2)
}

pub unsafe fn strlen(mut s: *const c_char) -> usize {
// SAFETY: The caller must guarantee `s` points to a valid 0-terminated string.
unsafe {
let mut n = 0;
while *s != 0 {
n += 1;
s = s.offset(1);
}
n
}
}
1 change: 0 additions & 1 deletion library/std/src/sys/windows/mod.rs
Original file line number Diff line number Diff line change
@@ -7,7 +7,6 @@ use crate::path::PathBuf;
use crate::time::Duration;

pub use self::rand::hashmap_random_keys;
pub use libc::strlen;

#[macro_use]
pub mod compat;
2 changes: 1 addition & 1 deletion src/tools/clippy/clippy_utils/src/paths.rs
Original file line number Diff line number Diff line change
@@ -23,7 +23,7 @@ pub const BTREEMAP_ENTRY: [&str; 6] = ["alloc", "collections", "btree", "map", "
pub const BTREEMAP_INSERT: [&str; 6] = ["alloc", "collections", "btree", "map", "BTreeMap", "insert"];
pub const CLONE_TRAIT_METHOD: [&str; 4] = ["core", "clone", "Clone", "clone"];
pub const COW: [&str; 3] = ["alloc", "borrow", "Cow"];
pub const CSTRING_AS_C_STR: [&str; 5] = ["std", "ffi", "c_str", "CString", "as_c_str"];
pub const CSTRING_AS_C_STR: [&str; 5] = ["alloc", "ffi", "c_str", "CString", "as_c_str"];
pub const DEFAULT_TRAIT_METHOD: [&str; 4] = ["core", "default", "Default", "default"];
pub const DEREF_MUT_TRAIT_METHOD: [&str; 5] = ["core", "ops", "deref", "DerefMut", "deref_mut"];
/// Preferably use the diagnostic item `sym::deref_method` where possible