Skip to content

Commit 600f729

Browse files
committed
refactor(clippy): prefer core and alloc imports
1 parent bdc0a62 commit 600f729

53 files changed

Lines changed: 246 additions & 200 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,8 @@ todo = "warn"
136136
unimplemented = "warn"
137137
unreachable = "warn"
138138
panic_in_result_fn = "warn"
139+
std_instead_of_alloc = "warn"
140+
std_instead_of_core = "warn"
139141
# TODO: Re-enable once every crate defines package keywords and categories.
140142
cargo_common_metadata = "allow"
141143
# TODO: Re-enable once the workspace dependency graph is deduplicated.

libdd-common-ffi/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,7 @@ serde = "1.0"
3232
bolero = "0.13"
3333
assert_no_alloc = "1.1.2"
3434
function_name = "0.3.0"
35+
36+
[lints.clippy]
37+
std_instead_of_alloc = "warn"
38+
std_instead_of_core = "warn"

libdd-common-ffi/src/array_queue.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
use crate::Error;
55
use anyhow::Context;
6-
use std::{ffi::c_void, ptr::NonNull};
6+
use core::{ffi::c_void, ptr::NonNull};
77

88
#[derive(Debug)]
99
#[repr(C)]
@@ -300,11 +300,11 @@ pub unsafe extern "C" fn ddog_ArrayQueue_capacity(queue_ptr: &ArrayQueue) -> Arr
300300
mod tests {
301301
use super::*;
302302
use bolero::TypeGenerator;
303-
use std::sync::atomic::{AtomicUsize, Ordering};
303+
use core::sync::atomic::{AtomicUsize, Ordering};
304304

305305
unsafe extern "C" fn drop_item(item: *mut c_void) -> c_void {
306306
_ = Box::from_raw(item as *mut i32);
307-
std::mem::zeroed()
307+
core::mem::zeroed()
308308
}
309309

310310
#[test]
@@ -313,7 +313,7 @@ mod tests {
313313
assert!(matches!(queue_new_result, ArrayQueueNewResult::Ok(_)));
314314
let queue_ptr = match queue_new_result {
315315
ArrayQueueNewResult::Ok(ptr) => ptr.as_ptr(),
316-
_ => std::ptr::null_mut(),
316+
_ => core::ptr::null_mut(),
317317
};
318318
let item = Box::new(1i32);
319319
let item_ptr = Box::into_raw(item);
@@ -335,7 +335,7 @@ mod tests {
335335
);
336336
let item_ptr = match result {
337337
ArrayQueuePopResult::Ok(ptr) => ptr,
338-
_ => std::ptr::null_mut(),
338+
_ => core::ptr::null_mut(),
339339
};
340340
drop(Box::from_raw(item_ptr as *mut i32));
341341
let result = ddog_ArrayQueue_push(queue, item3_ptr as *mut c_void);
@@ -438,7 +438,7 @@ mod tests {
438438
assert!(matches!(queue_new_result, ArrayQueueNewResult::Ok(_)));
439439
let queue_ptr = match queue_new_result {
440440
ArrayQueueNewResult::Ok(ptr) => ptr.as_ptr(),
441-
_ => std::ptr::null_mut(),
441+
_ => core::ptr::null_mut(),
442442
};
443443
let queue = unsafe { &*queue_ptr };
444444

libdd-common-ffi/src/cstr.rs

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/
22
// SPDX-License-Identifier: Apache-2.0
33

4+
use alloc::ffi::{CString as AllocCString, NulError};
5+
use alloc::vec::Vec;
6+
use core::ffi::CStr as CoreCStr;
47
use core::fmt;
5-
use std::{
8+
use core::{
69
ffi::c_char,
710
marker::PhantomData,
811
mem::{self, ManuallyDrop},
@@ -17,21 +20,21 @@ pub struct CStr<'a> {
1720
ptr: ptr::NonNull<c_char>,
1821
/// Length of the array, not counting the null-terminator
1922
length: usize,
20-
_lifetime_marker: std::marker::PhantomData<&'a c_char>,
23+
_lifetime_marker: core::marker::PhantomData<&'a c_char>,
2124
}
2225

2326
impl<'a> CStr<'a> {
24-
pub fn from_std(s: &'a std::ffi::CStr) -> Self {
27+
pub fn from_std(s: &'a CoreCStr) -> Self {
2528
Self {
2629
ptr: unsafe { ptr::NonNull::new_unchecked(s.as_ptr().cast_mut()) },
2730
length: s.to_bytes().len(),
28-
_lifetime_marker: std::marker::PhantomData,
31+
_lifetime_marker: core::marker::PhantomData,
2932
}
3033
}
3134

32-
pub fn into_std(&self) -> &'a std::ffi::CStr {
35+
pub fn into_std(&self) -> &'a CoreCStr {
3336
unsafe {
34-
std::ffi::CStr::from_bytes_with_nul_unchecked(std::slice::from_raw_parts(
37+
CoreCStr::from_bytes_with_nul_unchecked(core::slice::from_raw_parts(
3538
self.ptr.as_ptr().cast_const().cast(),
3639
self.length + 1,
3740
))
@@ -56,8 +59,8 @@ impl fmt::Debug for CString {
5659
}
5760

5861
impl CString {
59-
pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<Self, std::ffi::NulError> {
60-
Ok(Self::from_std(std::ffi::CString::new(t)?))
62+
pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<Self, NulError> {
63+
Ok(Self::from_std(AllocCString::new(t)?))
6164
}
6265

6366
/// Creates a new `CString` from the given input, or returns an empty `CString`
@@ -99,18 +102,18 @@ impl CString {
99102
}
100103
}
101104

102-
pub fn from_std(s: std::ffi::CString) -> Self {
105+
pub fn from_std(s: AllocCString) -> Self {
103106
let length = s.to_bytes().len();
104107
Self {
105108
ptr: unsafe { ptr::NonNull::new_unchecked(s.into_raw()) },
106109
length,
107110
}
108111
}
109112

110-
pub fn into_std(self) -> std::ffi::CString {
113+
pub fn into_std(self) -> AllocCString {
111114
let s = ManuallyDrop::new(self);
112115
unsafe {
113-
std::ffi::CString::from_vec_with_nul_unchecked(Vec::from_raw_parts(
116+
AllocCString::from_vec_with_nul_unchecked(Vec::from_raw_parts(
114117
s.ptr.as_ptr().cast(),
115118
s.length + 1, // +1 for the null terminator
116119
s.length + 1, // +1 for the null terminator
@@ -123,7 +126,7 @@ impl Drop for CString {
123126
fn drop(&mut self) {
124127
let ptr = mem::replace(&mut self.ptr, NonNull::dangling());
125128
drop(unsafe {
126-
std::ffi::CString::from_vec_with_nul_unchecked(Vec::from_raw_parts(
129+
AllocCString::from_vec_with_nul_unchecked(Vec::from_raw_parts(
127130
ptr.as_ptr().cast(),
128131
self.length + 1,
129132
self.length + 1,
@@ -138,7 +141,7 @@ mod tests {
138141

139142
#[test]
140143
fn test_cstr() {
141-
let s = std::ffi::CString::new("hello").unwrap();
144+
let s = AllocCString::new("hello").unwrap();
142145
let cstr = CStr::from_std(&s);
143146
assert_eq!(cstr.into_std().to_str().unwrap(), "hello");
144147
}

libdd-common-ffi/src/endpoint.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33

44
use crate::slice::AsBytes;
55
use crate::Error;
6+
use alloc::borrow::Cow;
7+
use core::str::FromStr;
68
use hyper::http::uri::{Authority, Parts};
79
use libdd_common::{parse_uri, Endpoint};
8-
use std::borrow::Cow;
9-
use std::str::FromStr;
1010

1111
#[no_mangle]
1212
#[must_use]

libdd-common-ffi/src/error.rs

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
use crate::slice::{AsBytes, CharSlice};
55
use crate::vec::Vec;
6-
use std::fmt::{Debug, Display, Formatter};
6+
use core::fmt::{Debug, Display, Formatter};
77

88
/// You probably don't want to use this directly. This constant is used by `handle_panic_error` to
99
/// signal that something went wrong, but avoid needing any allocations to represent it.
@@ -15,7 +15,7 @@ pub(crate) const CANNOT_ALLOCATE_ERROR: Error = Error {
1515

1616
// This error message is used as a placeholder for errors without message -- corresponding to an
1717
// error where we couldn't even _allocate_ the message (or some other even weirder error).
18-
const CANNOT_ALLOCATE: &std::ffi::CStr =
18+
const CANNOT_ALLOCATE: &core::ffi::CStr =
1919
c"libdatadog failed: (panic) Cannot allocate error message";
2020
const CANNOT_ALLOCATE_CHAR_SLICE: CharSlice = unsafe {
2121
crate::Slice::from_raw_parts(CANNOT_ALLOCATE.as_ptr(), CANNOT_ALLOCATE.to_bytes().len())
@@ -40,18 +40,18 @@ impl AsRef<str> for Error {
4040
}
4141

4242
impl Display for Error {
43-
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
43+
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
4444
f.write_str(self.as_ref())
4545
}
4646
}
4747

4848
impl Debug for Error {
49-
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
49+
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
5050
f.write_fmt(format_args!("Error(\"{}\")", self.as_ref()))
5151
}
5252
}
5353

54-
impl std::error::Error for Error {}
54+
impl core::error::Error for Error {}
5555

5656
impl From<String> for Error {
5757
fn from(value: String) -> Self {
@@ -63,7 +63,7 @@ impl From<String> for Error {
6363
impl From<Error> for String {
6464
fn from(mut value: Error) -> String {
6565
let mut vec = Vec::default();
66-
std::mem::swap(&mut vec, &mut value.message);
66+
core::mem::swap(&mut vec, &mut value.message);
6767
// Safety: .message is a String (just FFI safe).
6868
unsafe { String::from_utf8_unchecked(vec.into()) }
6969
}
@@ -83,8 +83,8 @@ impl From<anyhow::Error> for Error {
8383
}
8484
}
8585

86-
impl From<Box<&dyn std::error::Error>> for Error {
87-
fn from(value: Box<&dyn std::error::Error>) -> Self {
86+
impl From<Box<&dyn core::error::Error>> for Error {
87+
fn from(value: Box<&dyn core::error::Error>) -> Self {
8888
Self::from(value.to_string())
8989
}
9090
}

libdd-common-ffi/src/handle.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Copyright 2024-Present Datadog, Inc. https://www.datadoghq.com/
22
// SPDX-License-Identifier: Apache-2.0
33

4-
use std::ptr::null_mut;
4+
use core::ptr::null_mut;
55

66
use anyhow::Context;
77

@@ -48,7 +48,7 @@ impl<T> ToInner<T> for Handle<T> {
4848
unsafe fn take(&mut self) -> anyhow::Result<Box<T>> {
4949
// Leaving a null will help with double-free issues that can arise in C.
5050
// Of course, it's best to never get there in the first place!
51-
let raw = std::mem::replace(&mut self.inner, std::ptr::null_mut());
51+
let raw = core::mem::replace(&mut self.inner, core::ptr::null_mut());
5252
anyhow::ensure!(
5353
!raw.is_null(),
5454
"inner pointer was null, indicates use after free"

libdd-common-ffi/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
#![cfg_attr(not(test), deny(clippy::todo))]
77
#![cfg_attr(not(test), deny(clippy::unimplemented))]
88

9+
extern crate alloc;
10+
911
mod error;
1012

1113
pub mod array_queue;

libdd-common-ffi/src/option.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/
22
// SPDX-License-Identifier: Apache-2.0
33

4-
use std::fmt::Debug;
4+
use core::fmt::Debug;
55

66
#[repr(C)]
77
#[derive(Debug, PartialEq, Eq)]
@@ -12,11 +12,11 @@ pub enum Option<T> {
1212
}
1313

1414
impl<T> Option<T> {
15-
pub fn to_std(self) -> std::option::Option<T> {
15+
pub fn to_std(self) -> core::option::Option<T> {
1616
self.into()
1717
}
1818

19-
pub fn to_std_ref(&self) -> std::option::Option<&T> {
19+
pub fn to_std_ref(&self) -> core::option::Option<&T> {
2020
match self {
2121
Option::Some(ref s) => Some(s),
2222
Option::None => None,
@@ -43,7 +43,7 @@ impl<T> Option<T> {
4343
}
4444
}
4545

46-
impl<T> From<Option<T>> for std::option::Option<T> {
46+
impl<T> From<Option<T>> for core::option::Option<T> {
4747
fn from(o: Option<T>) -> Self {
4848
match o {
4949
Option::Some(s) => Some(s),
@@ -52,16 +52,16 @@ impl<T> From<Option<T>> for std::option::Option<T> {
5252
}
5353
}
5454

55-
impl<T> From<std::option::Option<T>> for Option<T> {
56-
fn from(o: std::option::Option<T>) -> Self {
55+
impl<T> From<core::option::Option<T>> for Option<T> {
56+
fn from(o: core::option::Option<T>) -> Self {
5757
match o {
5858
Some(s) => Option::Some(s),
5959
None => Option::None,
6060
}
6161
}
6262
}
6363

64-
impl<T: Copy> From<&Option<T>> for std::option::Option<T> {
64+
impl<T: Copy> From<&Option<T>> for core::option::Option<T> {
6565
fn from(o: &Option<T>) -> Self {
6666
match o {
6767
Option::Some(s) => Some(*s),

libdd-common-ffi/src/slice.rs

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
// Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/
22
// SPDX-License-Identifier: Apache-2.0
33

4+
use alloc::borrow::Cow;
5+
use core::ffi::c_char;
6+
use core::fmt::{Debug, Display, Formatter};
7+
use core::hash::{Hash, Hasher};
8+
use core::marker::PhantomData;
49
use core::slice;
10+
use core::str::Utf8Error;
511
use libdd_common::error::FfiSafeErrorMessage;
612
use serde::ser::Error;
713
use serde::Serializer;
8-
use std::borrow::Cow;
9-
use std::fmt::{Debug, Display, Formatter};
10-
use std::hash::{Hash, Hasher};
11-
use std::marker::PhantomData;
12-
use std::os::raw::c_char;
13-
use std::str::Utf8Error;
1414

1515
#[repr(C)]
1616
#[derive(Clone, Copy, Debug)]
@@ -37,7 +37,7 @@ pub struct Slice<'a, T: 'a> {
3737
/// # Safety
3838
/// All strings are valid UTF-8 (enforced by using c-str literals in Rust).
3939
unsafe impl FfiSafeErrorMessage for SliceConversionError {
40-
fn as_ffi_str(&self) -> &'static std::ffi::CStr {
40+
fn as_ffi_str(&self) -> &'static core::ffi::CStr {
4141
match self {
4242
SliceConversionError::LargeLength => c"length was too large",
4343
SliceConversionError::NullPointer => c"null pointer with non-zero length",
@@ -46,7 +46,7 @@ unsafe impl FfiSafeErrorMessage for SliceConversionError {
4646
}
4747
}
4848
impl Display for SliceConversionError {
49-
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
49+
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
5050
Display::fmt(self.as_rust_str(), f)
5151
}
5252
}
@@ -62,7 +62,7 @@ impl<'a, T: 'a> core::ops::Deref for Slice<'a, T> {
6262
}
6363

6464
impl<T: Debug> Debug for Slice<'_, T> {
65-
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
65+
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
6666
self.as_slice().fmt(f)
6767
}
6868
}
@@ -106,7 +106,7 @@ pub trait AsBytes<'a> {
106106

107107
#[inline]
108108
fn try_to_utf8(&self) -> Result<&'a str, Utf8Error> {
109-
std::str::from_utf8(self.as_bytes())
109+
core::str::from_utf8(self.as_bytes())
110110
}
111111

112112
fn try_to_string(&self) -> Result<String, Utf8Error> {
@@ -127,7 +127,7 @@ pub trait AsBytes<'a> {
127127
/// # Safety
128128
/// Must only be used when the underlying data was already confirmed to be utf8.
129129
unsafe fn assume_utf8(&self) -> &'a str {
130-
std::str::from_utf8_unchecked(self.as_bytes())
130+
core::str::from_utf8_unchecked(self.as_bytes())
131131
}
132132
}
133133

@@ -276,8 +276,8 @@ impl<'a, T> Display for Slice<'a, T>
276276
where
277277
Slice<'a, T>: AsBytes<'a>,
278278
{
279-
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
280-
write!(f, "{}", self.try_to_utf8().map_err(|_| std::fmt::Error)?)
279+
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
280+
write!(f, "{}", self.try_to_utf8().map_err(|_| core::fmt::Error)?)
281281
}
282282
}
283283

@@ -322,8 +322,8 @@ impl<'a> CharSlice<'a> {
322322
#[cfg(test)]
323323
mod tests {
324324
use super::*;
325+
use core::ptr;
325326
use std::os::raw::c_char;
326-
use std::ptr;
327327

328328
#[test]
329329
fn slice_from_into_slice() {

0 commit comments

Comments
 (0)