From 365c657ea86aeffe4796fc795c42f54363eb1170 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Chojnacki?= Date: Sat, 13 Jun 2026 00:05:39 +0200 Subject: [PATCH] refactor(clippy): prefer core and alloc imports --- Cargo.toml | 2 ++ libdd-common-ffi/Cargo.toml | 4 +++ libdd-common-ffi/src/array_queue.rs | 12 ++++---- libdd-common-ffi/src/cstr.rs | 8 ++--- libdd-common-ffi/src/endpoint.rs | 4 +-- libdd-common-ffi/src/error.rs | 14 ++++----- libdd-common-ffi/src/handle.rs | 4 +-- libdd-common-ffi/src/lib.rs | 2 ++ libdd-common-ffi/src/option.rs | 14 ++++----- libdd-common-ffi/src/slice.rs | 24 +++++++-------- libdd-common-ffi/src/slice_mut.rs | 16 +++++----- libdd-common-ffi/src/string.rs | 2 +- libdd-common-ffi/src/timespec.rs | 2 +- libdd-common-ffi/src/utils.rs | 11 ++++--- libdd-common-ffi/src/vec.rs | 8 ++--- libdd-common/Cargo.toml | 4 +++ libdd-common/src/bench_utils.rs | 30 +++++++++---------- libdd-common/src/config.rs | 3 +- libdd-common/src/connector/conn_stream.rs | 4 +-- libdd-common/src/connector/errors.rs | 2 +- libdd-common/src/connector/mod.rs | 6 ++-- libdd-common/src/dump_server.rs | 6 ++-- libdd-common/src/entity_id/unix/mod.rs | 4 +-- libdd-common/src/error.rs | 2 +- libdd-common/src/http_common.rs | 22 +++++++------- libdd-common/src/lib.rs | 8 +++-- libdd-common/src/rate_limiter.rs | 4 +-- libdd-common/src/tag.rs | 8 ++--- libdd-common/src/test_utils.rs | 7 +++-- libdd-common/src/timeout.rs | 7 +++-- libdd-common/src/unix_utils/execve.rs | 20 ++++++------- libdd-common/src/unix_utils/process.rs | 2 +- libdd-library-config-ffi/Cargo.toml | 4 +++ libdd-library-config-ffi/src/lib.rs | 18 ++++++----- .../src/tracer_metadata.rs | 2 +- libdd-library-config/Cargo.toml | 4 +++ libdd-library-config/src/lib.rs | 17 ++++++----- libdd-library-config/src/tracer_metadata.rs | 4 +-- .../benches/benchmarks/credit_cards_bench.rs | 4 +-- .../benches/benchmarks/ip_address_bench.rs | 2 +- .../benches/trace_obfuscation.rs | 2 ++ libdd-trace-obfuscation/src/http.rs | 2 +- libdd-trace-obfuscation/src/ip_address.rs | 4 ++- libdd-trace-obfuscation/src/json/mod.rs | 6 ++-- libdd-trace-obfuscation/src/lib.rs | 2 ++ .../src/obfuscation_config.rs | 2 +- libdd-trace-obfuscation/src/replacer.rs | 2 +- libdd-trace-obfuscation/src/sql.rs | 2 +- .../tests/test_span_obfuscation.rs | 11 +++---- 49 files changed, 197 insertions(+), 157 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index dc3e374492..e8854028ae 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -136,6 +136,8 @@ todo = "warn" unimplemented = "warn" unreachable = "warn" panic_in_result_fn = "warn" +std_instead_of_alloc = "warn" +std_instead_of_core = "warn" # TODO: Re-enable once every crate defines package keywords and categories. cargo_common_metadata = "allow" # TODO: Re-enable once the workspace dependency graph is deduplicated. diff --git a/libdd-common-ffi/Cargo.toml b/libdd-common-ffi/Cargo.toml index b7900a339d..0de874f611 100644 --- a/libdd-common-ffi/Cargo.toml +++ b/libdd-common-ffi/Cargo.toml @@ -32,3 +32,7 @@ serde = "1.0" bolero = "0.13" assert_no_alloc = "1.1.2" function_name = "0.3.0" + +[lints.clippy] +std_instead_of_alloc = "warn" +std_instead_of_core = "warn" diff --git a/libdd-common-ffi/src/array_queue.rs b/libdd-common-ffi/src/array_queue.rs index 17f3334430..3427d42c50 100644 --- a/libdd-common-ffi/src/array_queue.rs +++ b/libdd-common-ffi/src/array_queue.rs @@ -3,7 +3,7 @@ use crate::Error; use anyhow::Context; -use std::{ffi::c_void, ptr::NonNull}; +use core::{ffi::c_void, ptr::NonNull}; #[derive(Debug)] #[repr(C)] @@ -300,11 +300,11 @@ pub unsafe extern "C" fn ddog_ArrayQueue_capacity(queue_ptr: &ArrayQueue) -> Arr mod tests { use super::*; use bolero::TypeGenerator; - use std::sync::atomic::{AtomicUsize, Ordering}; + use core::sync::atomic::{AtomicUsize, Ordering}; unsafe extern "C" fn drop_item(item: *mut c_void) -> c_void { _ = Box::from_raw(item as *mut i32); - std::mem::zeroed() + core::mem::zeroed() } #[test] @@ -313,7 +313,7 @@ mod tests { assert!(matches!(queue_new_result, ArrayQueueNewResult::Ok(_))); let queue_ptr = match queue_new_result { ArrayQueueNewResult::Ok(ptr) => ptr.as_ptr(), - _ => std::ptr::null_mut(), + _ => core::ptr::null_mut(), }; let item = Box::new(1i32); let item_ptr = Box::into_raw(item); @@ -335,7 +335,7 @@ mod tests { ); let item_ptr = match result { ArrayQueuePopResult::Ok(ptr) => ptr, - _ => std::ptr::null_mut(), + _ => core::ptr::null_mut(), }; drop(Box::from_raw(item_ptr as *mut i32)); let result = ddog_ArrayQueue_push(queue, item3_ptr as *mut c_void); @@ -438,7 +438,7 @@ mod tests { assert!(matches!(queue_new_result, ArrayQueueNewResult::Ok(_))); let queue_ptr = match queue_new_result { ArrayQueueNewResult::Ok(ptr) => ptr.as_ptr(), - _ => std::ptr::null_mut(), + _ => core::ptr::null_mut(), }; let queue = unsafe { &*queue_ptr }; diff --git a/libdd-common-ffi/src/cstr.rs b/libdd-common-ffi/src/cstr.rs index 0e09516f9e..9d8e94ce56 100644 --- a/libdd-common-ffi/src/cstr.rs +++ b/libdd-common-ffi/src/cstr.rs @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 use core::fmt; -use std::{ +use core::{ ffi::c_char, marker::PhantomData, mem::{self, ManuallyDrop}, @@ -17,7 +17,7 @@ pub struct CStr<'a> { ptr: ptr::NonNull, /// Length of the array, not counting the null-terminator length: usize, - _lifetime_marker: std::marker::PhantomData<&'a c_char>, + _lifetime_marker: core::marker::PhantomData<&'a c_char>, } impl<'a> CStr<'a> { @@ -25,13 +25,13 @@ impl<'a> CStr<'a> { Self { ptr: unsafe { ptr::NonNull::new_unchecked(s.as_ptr().cast_mut()) }, length: s.to_bytes().len(), - _lifetime_marker: std::marker::PhantomData, + _lifetime_marker: core::marker::PhantomData, } } pub fn into_std(&self) -> &'a std::ffi::CStr { unsafe { - std::ffi::CStr::from_bytes_with_nul_unchecked(std::slice::from_raw_parts( + std::ffi::CStr::from_bytes_with_nul_unchecked(core::slice::from_raw_parts( self.ptr.as_ptr().cast_const().cast(), self.length + 1, )) diff --git a/libdd-common-ffi/src/endpoint.rs b/libdd-common-ffi/src/endpoint.rs index d79fdce4f3..4e2f1fdbc4 100644 --- a/libdd-common-ffi/src/endpoint.rs +++ b/libdd-common-ffi/src/endpoint.rs @@ -3,10 +3,10 @@ use crate::slice::AsBytes; use crate::Error; +use alloc::borrow::Cow; +use core::str::FromStr; use hyper::http::uri::{Authority, Parts}; use libdd_common::{parse_uri, Endpoint}; -use std::borrow::Cow; -use std::str::FromStr; #[no_mangle] #[must_use] diff --git a/libdd-common-ffi/src/error.rs b/libdd-common-ffi/src/error.rs index ab5f1cc212..5bb23354a2 100644 --- a/libdd-common-ffi/src/error.rs +++ b/libdd-common-ffi/src/error.rs @@ -3,7 +3,7 @@ use crate::slice::{AsBytes, CharSlice}; use crate::vec::Vec; -use std::fmt::{Debug, Display, Formatter}; +use core::fmt::{Debug, Display, Formatter}; /// You probably don't want to use this directly. This constant is used by `handle_panic_error` to /// signal that something went wrong, but avoid needing any allocations to represent it. @@ -40,18 +40,18 @@ impl AsRef for Error { } impl Display for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { f.write_str(self.as_ref()) } } impl Debug for Error { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { f.write_fmt(format_args!("Error(\"{}\")", self.as_ref())) } } -impl std::error::Error for Error {} +impl core::error::Error for Error {} impl From for Error { fn from(value: String) -> Self { @@ -63,7 +63,7 @@ impl From for Error { impl From for String { fn from(mut value: Error) -> String { let mut vec = Vec::default(); - std::mem::swap(&mut vec, &mut value.message); + core::mem::swap(&mut vec, &mut value.message); // Safety: .message is a String (just FFI safe). unsafe { String::from_utf8_unchecked(vec.into()) } } @@ -83,8 +83,8 @@ impl From for Error { } } -impl From> for Error { - fn from(value: Box<&dyn std::error::Error>) -> Self { +impl From> for Error { + fn from(value: Box<&dyn core::error::Error>) -> Self { Self::from(value.to_string()) } } diff --git a/libdd-common-ffi/src/handle.rs b/libdd-common-ffi/src/handle.rs index 25a19b59b0..7716ab7253 100644 --- a/libdd-common-ffi/src/handle.rs +++ b/libdd-common-ffi/src/handle.rs @@ -1,7 +1,7 @@ // Copyright 2024-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 -use std::ptr::null_mut; +use core::ptr::null_mut; use anyhow::Context; @@ -48,7 +48,7 @@ impl ToInner for Handle { unsafe fn take(&mut self) -> anyhow::Result> { // Leaving a null will help with double-free issues that can arise in C. // Of course, it's best to never get there in the first place! - let raw = std::mem::replace(&mut self.inner, std::ptr::null_mut()); + let raw = core::mem::replace(&mut self.inner, core::ptr::null_mut()); anyhow::ensure!( !raw.is_null(), "inner pointer was null, indicates use after free" diff --git a/libdd-common-ffi/src/lib.rs b/libdd-common-ffi/src/lib.rs index 0fdb04b4be..c5ec15142c 100644 --- a/libdd-common-ffi/src/lib.rs +++ b/libdd-common-ffi/src/lib.rs @@ -6,6 +6,8 @@ #![cfg_attr(not(test), deny(clippy::todo))] #![cfg_attr(not(test), deny(clippy::unimplemented))] +extern crate alloc; + mod error; pub mod array_queue; diff --git a/libdd-common-ffi/src/option.rs b/libdd-common-ffi/src/option.rs index 9c3eb9fb5f..29cb572969 100644 --- a/libdd-common-ffi/src/option.rs +++ b/libdd-common-ffi/src/option.rs @@ -1,7 +1,7 @@ // Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 -use std::fmt::Debug; +use core::fmt::Debug; #[repr(C)] #[derive(Debug, PartialEq, Eq)] @@ -12,11 +12,11 @@ pub enum Option { } impl Option { - pub fn to_std(self) -> std::option::Option { + pub fn to_std(self) -> core::option::Option { self.into() } - pub fn to_std_ref(&self) -> std::option::Option<&T> { + pub fn to_std_ref(&self) -> core::option::Option<&T> { match self { Option::Some(ref s) => Some(s), Option::None => None, @@ -43,7 +43,7 @@ impl Option { } } -impl From> for std::option::Option { +impl From> for core::option::Option { fn from(o: Option) -> Self { match o { Option::Some(s) => Some(s), @@ -52,8 +52,8 @@ impl From> for std::option::Option { } } -impl From> for Option { - fn from(o: std::option::Option) -> Self { +impl From> for Option { + fn from(o: core::option::Option) -> Self { match o { Some(s) => Option::Some(s), None => Option::None, @@ -61,7 +61,7 @@ impl From> for Option { } } -impl From<&Option> for std::option::Option { +impl From<&Option> for core::option::Option { fn from(o: &Option) -> Self { match o { Option::Some(s) => Some(*s), diff --git a/libdd-common-ffi/src/slice.rs b/libdd-common-ffi/src/slice.rs index a703188e1b..fb4a9e2c0e 100644 --- a/libdd-common-ffi/src/slice.rs +++ b/libdd-common-ffi/src/slice.rs @@ -1,16 +1,16 @@ // Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +use alloc::borrow::Cow; +use core::fmt::{Debug, Display, Formatter}; +use core::hash::{Hash, Hasher}; +use core::marker::PhantomData; use core::slice; +use core::str::Utf8Error; use libdd_common::error::FfiSafeErrorMessage; use serde::ser::Error; use serde::Serializer; -use std::borrow::Cow; -use std::fmt::{Debug, Display, Formatter}; -use std::hash::{Hash, Hasher}; -use std::marker::PhantomData; use std::os::raw::c_char; -use std::str::Utf8Error; #[repr(C)] #[derive(Clone, Copy, Debug)] @@ -46,7 +46,7 @@ unsafe impl FfiSafeErrorMessage for SliceConversionError { } } impl Display for SliceConversionError { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { Display::fmt(self.as_rust_str(), f) } } @@ -62,7 +62,7 @@ impl<'a, T: 'a> core::ops::Deref for Slice<'a, T> { } impl Debug for Slice<'_, T> { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.as_slice().fmt(f) } } @@ -106,7 +106,7 @@ pub trait AsBytes<'a> { #[inline] fn try_to_utf8(&self) -> Result<&'a str, Utf8Error> { - std::str::from_utf8(self.as_bytes()) + core::str::from_utf8(self.as_bytes()) } fn try_to_string(&self) -> Result { @@ -127,7 +127,7 @@ pub trait AsBytes<'a> { /// # Safety /// Must only be used when the underlying data was already confirmed to be utf8. unsafe fn assume_utf8(&self) -> &'a str { - std::str::from_utf8_unchecked(self.as_bytes()) + core::str::from_utf8_unchecked(self.as_bytes()) } } @@ -276,8 +276,8 @@ impl<'a, T> Display for Slice<'a, T> where Slice<'a, T>: AsBytes<'a>, { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.try_to_utf8().map_err(|_| std::fmt::Error)?) + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { + write!(f, "{}", self.try_to_utf8().map_err(|_| core::fmt::Error)?) } } @@ -322,8 +322,8 @@ impl<'a> CharSlice<'a> { #[cfg(test)] mod tests { use super::*; + use core::ptr; use std::os::raw::c_char; - use std::ptr; #[test] fn slice_from_into_slice() { diff --git a/libdd-common-ffi/src/slice_mut.rs b/libdd-common-ffi/src/slice_mut.rs index 60bea136f2..d87df1795b 100644 --- a/libdd-common-ffi/src/slice_mut.rs +++ b/libdd-common-ffi/src/slice_mut.rs @@ -2,14 +2,14 @@ // SPDX-License-Identifier: Apache-2.0 use crate::slice::{AsBytes, SliceConversionError}; +use core::fmt::{Debug, Display, Formatter}; +use core::hash::{Hash, Hasher}; +use core::marker::PhantomData; +use core::ptr::NonNull; use core::slice; use serde::ser::Error; use serde::Serializer; -use std::fmt::{Debug, Display, Formatter}; -use std::hash::{Hash, Hasher}; -use std::marker::PhantomData; use std::os::raw::c_char; -use std::ptr::NonNull; #[repr(C)] #[derive(Copy, Clone)] @@ -34,7 +34,7 @@ impl<'a, T: 'a> core::ops::Deref for MutSlice<'a, T> { } impl Debug for MutSlice<'_, T> { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { self.as_slice().fmt(f) } } @@ -175,8 +175,8 @@ impl<'a, T> Display for MutSlice<'a, T> where MutSlice<'a, T>: AsBytes<'a>, { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "{}", self.try_to_utf8().map_err(|_| std::fmt::Error)?) + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { + write!(f, "{}", self.try_to_utf8().map_err(|_| core::fmt::Error)?) } } @@ -202,7 +202,7 @@ impl<'a> From<&'a mut str> for MutSlice<'a, c_char> { #[cfg(test)] mod tests { use super::*; - use std::ptr; + use core::ptr; #[derive(Debug, Eq, PartialEq)] struct Foo(i64); diff --git a/libdd-common-ffi/src/string.rs b/libdd-common-ffi/src/string.rs index 21090f45bf..53762a63cb 100644 --- a/libdd-common-ffi/src/string.rs +++ b/libdd-common-ffi/src/string.rs @@ -29,7 +29,7 @@ impl From for StringWrapper { impl From for String { fn from(mut value: StringWrapper) -> Self { - let msg = std::mem::take(&mut value.message); + let msg = core::mem::take(&mut value.message); #[allow(clippy::unwrap_used)] String::from_utf8(msg.into()).unwrap() } diff --git a/libdd-common-ffi/src/timespec.rs b/libdd-common-ffi/src/timespec.rs index a490845c31..a86ba0ad06 100644 --- a/libdd-common-ffi/src/timespec.rs +++ b/libdd-common-ffi/src/timespec.rs @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 use chrono::{DateTime, TimeZone, Utc}; -use std::fmt::Debug; +use core::fmt::Debug; use std::time::SystemTime; /// Represents time since the Unix Epoch in seconds plus nanoseconds. diff --git a/libdd-common-ffi/src/utils.rs b/libdd-common-ffi/src/utils.rs index ee3f6f61ca..23d657855b 100644 --- a/libdd-common-ffi/src/utils.rs +++ b/libdd-common-ffi/src/utils.rs @@ -1,7 +1,8 @@ // Copyright 2024-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 -use std::panic::{catch_unwind, AssertUnwindSafe}; +use core::panic::AssertUnwindSafe; +use std::panic::catch_unwind; /// Wraps a C-FFI function in standard form /// Expects the function to return a result type that implements into and to be decorated with @@ -9,7 +10,8 @@ use std::panic::{catch_unwind, AssertUnwindSafe}; #[macro_export] macro_rules! wrap_with_ffi_result { ($body:block) => {{ - use std::panic::{catch_unwind, AssertUnwindSafe}; + use core::panic::AssertUnwindSafe; + use std::panic::catch_unwind; catch_unwind(AssertUnwindSafe(|| { $crate::wrap_with_ffi_result_no_catch!({ $body }) @@ -38,7 +40,8 @@ macro_rules! wrap_with_ffi_result_no_catch { #[macro_export] macro_rules! wrap_with_void_ffi_result { ($body:block) => {{ - use std::panic::{catch_unwind, AssertUnwindSafe}; + use core::panic::AssertUnwindSafe; + use std::panic::catch_unwind; catch_unwind(AssertUnwindSafe(|| { $crate::wrap_with_void_ffi_result_no_catch!({ $body }) @@ -80,7 +83,7 @@ impl ToHexStr for usize { /// being unable to allocate, this helper handles failures to allocate as well, turning them into a /// fallback error. pub fn handle_panic_error( - error: Box, + error: Box, function_name: &str, ) -> crate::Error { catch_unwind(AssertUnwindSafe(|| { diff --git a/libdd-common-ffi/src/vec.rs b/libdd-common-ffi/src/vec.rs index 1635b0c7b3..e67107ad6f 100644 --- a/libdd-common-ffi/src/vec.rs +++ b/libdd-common-ffi/src/vec.rs @@ -4,10 +4,10 @@ extern crate alloc; use crate::slice::Slice; +use core::marker::PhantomData; +use core::mem::ManuallyDrop; use core::ops::Deref; -use std::marker::PhantomData; -use std::mem::ManuallyDrop; -use std::ptr::NonNull; +use core::ptr::NonNull; /// Holds the raw parts of a Rust Vec; it should only be created from Rust, /// never from C. @@ -97,7 +97,7 @@ impl<'a, T> IntoIterator for &'a Vec { } impl Vec { - fn replace(&mut self, mut vec: ManuallyDrop>) { + fn replace(&mut self, mut vec: ManuallyDrop>) { self.ptr = vec.as_mut_ptr(); self.len = vec.len(); self.capacity = vec.capacity(); diff --git a/libdd-common/Cargo.toml b/libdd-common/Cargo.toml index b4bca918d6..dd0131b6f1 100644 --- a/libdd-common/Cargo.toml +++ b/libdd-common/Cargo.toml @@ -123,3 +123,7 @@ bench-utils = ["dep:criterion"] # normal environments, so we need to let the rust linter know that it is in # fact a real thing, though one that shows up only in some situations. unexpected_cfgs = { level = "warn", check-cfg = ['cfg(coverage)'] } + +[lints.clippy] +std_instead_of_alloc = "warn" +std_instead_of_core = "warn" diff --git a/libdd-common/src/bench_utils.rs b/libdd-common/src/bench_utils.rs index 17337f6cd9..fc1e9ee413 100644 --- a/libdd-common/src/bench_utils.rs +++ b/libdd-common/src/bench_utils.rs @@ -7,11 +7,8 @@ #![allow(missing_docs)] -use std::{ - alloc::{GlobalAlloc, System}, - cell::Cell, - time::Duration, -}; +use core::{alloc::GlobalAlloc, cell::Cell, time::Duration}; +use std::alloc::System; use criterion::{Criterion, Throughput}; @@ -46,16 +43,16 @@ struct AllocStats { pub struct ReportingAllocator { alloc: T, - allocated_bytes: std::sync::atomic::AtomicUsize, - allocations: std::sync::atomic::AtomicUsize, + allocated_bytes: core::sync::atomic::AtomicUsize, + allocations: core::sync::atomic::AtomicUsize, } impl ReportingAllocator { pub const fn new(alloc: T) -> Self { Self { alloc, - allocated_bytes: std::sync::atomic::AtomicUsize::new(0), - allocations: std::sync::atomic::AtomicUsize::new(0), + allocated_bytes: core::sync::atomic::AtomicUsize::new(0), + allocations: core::sync::atomic::AtomicUsize::new(0), } } @@ -63,22 +60,22 @@ impl ReportingAllocator { AllocStats { allocated_bytes: self .allocated_bytes - .load(std::sync::atomic::Ordering::Relaxed), - allocations: self.allocations.load(std::sync::atomic::Ordering::Relaxed), + .load(core::sync::atomic::Ordering::Relaxed), + allocations: self.allocations.load(core::sync::atomic::Ordering::Relaxed), } } } unsafe impl GlobalAlloc for ReportingAllocator { - unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 { + unsafe fn alloc(&self, layout: core::alloc::Layout) -> *mut u8 { self.allocated_bytes - .fetch_add(layout.size(), std::sync::atomic::Ordering::Relaxed); + .fetch_add(layout.size(), core::sync::atomic::Ordering::Relaxed); self.allocations - .fetch_add(1, std::sync::atomic::Ordering::Relaxed); + .fetch_add(1, core::sync::atomic::Ordering::Relaxed); self.alloc.alloc(layout) } - unsafe fn dealloc(&self, ptr: *mut u8, layout: std::alloc::Layout) { + unsafe fn dealloc(&self, ptr: *mut u8, layout: core::alloc::Layout) { self.alloc.dealloc(ptr, layout); } } @@ -169,8 +166,9 @@ impl criterion::measurement::ValueFormatter for AllocationFormatter { #[cfg(test)] mod tests { use super::*; + use core::alloc::{GlobalAlloc, Layout}; use criterion::measurement::{Measurement, ValueFormatter}; - use std::alloc::{GlobalAlloc, Layout, System}; + use std::alloc::System; static SHARED: ReportingAllocator = ReportingAllocator::new(System); diff --git a/libdd-common/src/config.rs b/libdd-common/src/config.rs index 0019fd6b46..fe88c0f248 100644 --- a/libdd-common/src/config.rs +++ b/libdd-common/src/config.rs @@ -2,8 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 pub mod parse_env { + use core::{str::FromStr, time::Duration}; use http::Uri; - use std::{env, str::FromStr, time::Duration}; + use std::env; use crate::parse_uri; diff --git a/libdd-common/src/connector/conn_stream.rs b/libdd-common/src/connector/conn_stream.rs index 6fdedfdd56..23331a8028 100644 --- a/libdd-common/src/connector/conn_stream.rs +++ b/libdd-common/src/connector/conn_stream.rs @@ -1,7 +1,7 @@ // Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 -use std::{ +use core::{ pin::Pin, task::{Context, Poll}, }; @@ -35,7 +35,7 @@ pub enum ConnStream { }, } -pub type ConnStreamError = Box; +pub type ConnStreamError = Box; use hyper_util::client::legacy::connect::{self, HttpConnector}; use hyper_util::rt::TokioIo; diff --git a/libdd-common/src/connector/errors.rs b/libdd-common/src/connector/errors.rs index a4e2c8a062..e46f42e830 100644 --- a/libdd-common/src/connector/errors.rs +++ b/libdd-common/src/connector/errors.rs @@ -1,8 +1,8 @@ // Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +use alloc::fmt; use std::error; -use std::fmt; #[derive(Clone, Debug, PartialEq, Eq)] pub enum Error { diff --git a/libdd-common/src/connector/mod.rs b/libdd-common/src/connector/mod.rs index 8e93359dbc..d9e0d1c7eb 100644 --- a/libdd-common/src/connector/mod.rs +++ b/libdd-common/src/connector/mod.rs @@ -5,10 +5,10 @@ use futures::future::BoxFuture; use futures::{future, FutureExt}; use hyper_util::client::legacy::connect; -use std::future::Future; -use std::pin::Pin; +use core::future::Future; +use core::pin::Pin; +use core::task::{Context, Poll}; use std::sync::LazyLock; -use std::task::{Context, Poll}; #[cfg(unix)] pub mod uds; diff --git a/libdd-common/src/dump_server.rs b/libdd-common/src/dump_server.rs index 66dd352e3c..396fb5789a 100644 --- a/libdd-common/src/dump_server.rs +++ b/libdd-common/src/dump_server.rs @@ -178,7 +178,7 @@ fn is_chunked_encoding(headers: &[httparse::Header]) -> bool { headers.iter().any(|h| { h.name .eq_ignore_ascii_case(http::header::TRANSFER_ENCODING.as_str()) - && std::str::from_utf8(h.value).is_ok_and(|v| v.to_lowercase().contains("chunked")) + && core::str::from_utf8(h.value).is_ok_and(|v| v.to_lowercase().contains("chunked")) }) } @@ -190,7 +190,7 @@ fn get_content_length(headers: &[httparse::Header]) -> Option { h.name .eq_ignore_ascii_case(http::header::CONTENT_LENGTH.as_str()) }) - .and_then(|h| std::str::from_utf8(h.value).ok()) + .and_then(|h| core::str::from_utf8(h.value).ok()) .and_then(|v| v.trim().parse().ok()) } @@ -294,7 +294,7 @@ fn decode_chunked_body(chunked_data: &[u8]) -> anyhow::Result> { .with_context(|| format!("Missing CRLF after chunk size at position {}", pos))?; // Parse the chunk size (hex) - let size_str = std::str::from_utf8(&chunked_data[pos..pos + line_end]) + let size_str = core::str::from_utf8(&chunked_data[pos..pos + line_end]) .context("Invalid UTF-8 in chunk size")?; let chunk_size = usize::from_str_radix(size_str.trim(), 16) diff --git a/libdd-common/src/entity_id/unix/mod.rs b/libdd-common/src/entity_id/unix/mod.rs index 826f2e9604..91ec121ee8 100644 --- a/libdd-common/src/entity_id/unix/mod.rs +++ b/libdd-common/src/entity_id/unix/mod.rs @@ -1,8 +1,8 @@ // Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +use alloc::fmt; use std::error; -use std::fmt; use std::path::Path; use std::sync::LazyLock; @@ -66,7 +66,7 @@ fn get_cgroup_path() -> &'static str { #[cfg(feature = "cgroup_testing")] return TESTING_CGROUP_PATH .get() - .map(std::ops::Deref::deref) + .map(core::ops::Deref::deref) .unwrap_or(DEFAULT_CGROUP_PATH); #[cfg(not(feature = "cgroup_testing"))] return DEFAULT_CGROUP_PATH; diff --git a/libdd-common/src/error.rs b/libdd-common/src/error.rs index b91ea2ed2e..6a4dadd97c 100644 --- a/libdd-common/src/error.rs +++ b/libdd-common/src/error.rs @@ -29,6 +29,6 @@ pub unsafe trait FfiSafeErrorMessage { fn as_rust_str(&self) -> &'static str { // Bytes will not contain the null terminator. let bytes = self.as_ffi_str().to_bytes(); - unsafe { std::str::from_utf8_unchecked(bytes) } + unsafe { core::str::from_utf8_unchecked(bytes) } } } diff --git a/libdd-common/src/http_common.rs b/libdd-common/src/http_common.rs index 1ffd3246fe..cc8ca19171 100644 --- a/libdd-common/src/http_common.rs +++ b/libdd-common/src/http_common.rs @@ -1,8 +1,8 @@ // Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +use core::convert::Infallible; use core::fmt; -use std::convert::Infallible; use thiserror::Error; @@ -26,8 +26,8 @@ pub struct ClientError { kind: ErrorKind, } -impl std::fmt::Display for ClientError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Display for ClientError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.source.fmt(f) } } @@ -46,7 +46,7 @@ pub enum Error { } impl fmt::Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Error::Client(e) => write!(f, "client error: {e}"), Error::Infallible(e) => match *e {}, @@ -67,15 +67,15 @@ impl From for Error { } } -impl std::error::Error for Error {} +impl core::error::Error for Error {} // --- Native-only code (hyper, Body, client builders, etc.) --- #[cfg(not(target_arch = "wasm32"))] mod native { use super::*; - use std::error::Error as _; - use std::task::Poll; + use core::error::Error as _; + use core::task::Poll; use crate::connector::Connector; use http_body_util::BodyExt; @@ -205,7 +205,7 @@ mod native { } pub fn boxed< - E: std::error::Error + Sync + Send + 'static, + E: core::error::Error + Sync + Send + 'static, T: hyper::body::Body + Sync + Send + 'static, >( body: T, @@ -253,9 +253,9 @@ mod native { type Error = Error; fn poll_frame( - self: std::pin::Pin<&mut Self>, - cx: &mut std::task::Context<'_>, - ) -> std::task::Poll, Self::Error>>> { + self: core::pin::Pin<&mut Self>, + cx: &mut core::task::Context<'_>, + ) -> core::task::Poll, Self::Error>>> { match self.project() { BodyProj::Single(pin) => pin.poll_frame(cx).map_err(Error::Infallible), BodyProj::Empty(pin) => pin.poll_frame(cx).map_err(Error::Infallible), diff --git a/libdd-common/src/lib.rs b/libdd-common/src/lib.rs index dbd2e4a090..c0d830c71a 100644 --- a/libdd-common/src/lib.rs +++ b/libdd-common/src/lib.rs @@ -6,12 +6,16 @@ #![cfg_attr(not(test), deny(clippy::todo))] #![cfg_attr(not(test), deny(clippy::unimplemented))] +extern crate alloc; + +use alloc::borrow::Cow; use anyhow::Context; +use core::{ops::Deref, str::FromStr}; use http::uri; use serde::de::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use std::path::PathBuf; use std::sync::{Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard}; -use std::{borrow::Cow, ops::Deref, path::PathBuf, str::FromStr}; pub mod azure_app_services; #[cfg(not(target_arch = "wasm32"))] @@ -460,7 +464,7 @@ impl Endpoint { // configuration will mutate the system environment (it doesn't pass // it as part of the SAPI env, it changes the actual system env). let mut builder = reqwest::Client::builder() - .timeout(std::time::Duration::from_millis(self.timeout_ms)) + .timeout(core::time::Duration::from_millis(self.timeout_ms)) .hickory_dns(!self.use_system_resolver) .no_proxy(); diff --git a/libdd-common/src/rate_limiter.rs b/libdd-common/src/rate_limiter.rs index 9d686b08d1..de2f9c1029 100644 --- a/libdd-common/src/rate_limiter.rs +++ b/libdd-common/src/rate_limiter.rs @@ -1,7 +1,7 @@ // Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 -use std::sync::atomic::{AtomicI64, AtomicU32, AtomicU64, Ordering}; +use core::sync::atomic::{AtomicI64, AtomicU32, AtomicU64, Ordering}; pub trait Limiter { /// Takes the limit per interval. @@ -158,7 +158,7 @@ impl Limiter for LocalLimiter { #[cfg(test)] mod tests { use crate::rate_limiter::{now, Limiter, LocalLimiter, MOCK_NOW, TIME_PER_SECOND}; - use std::sync::atomic::Ordering; + use core::sync::atomic::Ordering; fn set_mock_time(nanos: u64) { MOCK_NOW.store(nanos, Ordering::Relaxed); diff --git a/libdd-common/src/tag.rs b/libdd-common/src/tag.rs index 4f06abe182..7adad82511 100644 --- a/libdd-common/src/tag.rs +++ b/libdd-common/src/tag.rs @@ -1,9 +1,9 @@ // Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +use alloc::borrow::Cow; +use core::fmt::{Debug, Display, Formatter}; use serde::{Deserialize, Serialize}; -use std::borrow::Cow; -use std::fmt::{Debug, Display, Formatter}; pub use static_assertions::{const_assert, const_assert_ne}; @@ -71,7 +71,7 @@ macro_rules! tag { } impl Debug for Tag { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { f.debug_struct("Tag").field("value", &self.value).finish() } } @@ -84,7 +84,7 @@ impl AsRef for Tag { // Any type which implements Display automatically has to_string. impl Display for Tag { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { write!(f, "{}", self.value) } } diff --git a/libdd-common/src/test_utils.rs b/libdd-common/src/test_utils.rs index e3cf75e695..0c99083ebe 100644 --- a/libdd-common/src/test_utils.rs +++ b/libdd-common/src/test_utils.rs @@ -36,7 +36,7 @@ impl Drop for TempFileGuard { } } -impl std::ops::Deref for TempFileGuard { +impl core::ops::Deref for TempFileGuard { type Target = PathBuf; fn deref(&self) -> &Self::Target { @@ -529,7 +529,8 @@ mod tests { ); // Spawn some threads and verify the count increases - use std::sync::{Arc, Barrier}; + use alloc::sync::Arc; + use std::sync::Barrier; let barrier = Arc::new(Barrier::new(6)); // 5 spawned threads + main thread let handles: Vec<_> = (0..5) @@ -537,7 +538,7 @@ mod tests { let barrier = Arc::clone(&barrier); std::thread::spawn(move || { barrier.wait(); - std::thread::sleep(std::time::Duration::from_millis(50)); + std::thread::sleep(core::time::Duration::from_millis(50)); }) }) .collect(); diff --git a/libdd-common/src/timeout.rs b/libdd-common/src/timeout.rs index 3d17827370..592fe07826 100644 --- a/libdd-common/src/timeout.rs +++ b/libdd-common/src/timeout.rs @@ -1,7 +1,8 @@ // Copyright 2025-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 -use std::time::{Duration, Instant}; +use core::time::Duration; +use std::time::Instant; pub struct TimeoutManager { start_time: Instant, @@ -38,8 +39,8 @@ impl TimeoutManager { } } -impl std::fmt::Debug for TimeoutManager { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +impl core::fmt::Debug for TimeoutManager { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("TimeoutManager") .field("start_time", &self.start_time) .field("elapsed", &self.elapsed()) diff --git a/libdd-common/src/unix_utils/execve.rs b/libdd-common/src/unix_utils/execve.rs index 4a0ea02be0..00a58cd9dc 100644 --- a/libdd-common/src/unix_utils/execve.rs +++ b/libdd-common/src/unix_utils/execve.rs @@ -52,7 +52,7 @@ impl PreparedExecve { let args_ptrs: Vec<*const libc::c_char> = args_cstrings .iter() .map(|arg| arg.as_ptr()) - .chain(std::iter::once(std::ptr::null())) // Adds a null pointer to the end of the list + .chain(core::iter::once(core::ptr::null())) // Adds a null pointer to the end of the list .collect(); // Allocate and store environment variables @@ -67,7 +67,7 @@ impl PreparedExecve { let env_vars_ptrs: Vec<*const libc::c_char> = env_vars_cstrings .iter() .map(|env| env.as_ptr()) - .chain(std::iter::once(std::ptr::null())) // Adds a null pointer to the end of the list + .chain(core::iter::once(core::ptr::null())) // Adds a null pointer to the end of the list .collect(); Ok(Self { @@ -119,7 +119,7 @@ mod tests { // Verify the struct was created successfully // We can't directly access private fields, but we can verify the struct exists - assert!(std::mem::size_of_val(&prepared) > 0); + assert!(core::mem::size_of_val(&prepared) > 0); } #[test] @@ -131,7 +131,7 @@ mod tests { let prepared = PreparedExecve::new(binary_path, &args, &env).unwrap(); // Should still create successfully with empty args and env - assert!(std::mem::size_of_val(&prepared) > 0); + assert!(core::mem::size_of_val(&prepared) > 0); } #[test] @@ -152,7 +152,7 @@ mod tests { let prepared = PreparedExecve::new(binary_path, &args, &env).unwrap(); // Should handle complex arguments and environment variables - assert!(std::mem::size_of_val(&prepared) > 0); + assert!(core::mem::size_of_val(&prepared) > 0); } #[test] @@ -228,7 +228,7 @@ mod tests { let prepared = PreparedExecve::new(binary_path, &args, &env).unwrap(); // Should handle Unicode characters - assert!(std::mem::size_of_val(&prepared) > 0); + assert!(core::mem::size_of_val(&prepared) > 0); } #[test] @@ -240,7 +240,7 @@ mod tests { let prepared = PreparedExecve::new(binary_path, &args, &env).unwrap(); // Should handle large numbers of arguments - assert!(std::mem::size_of_val(&prepared) > 0); + assert!(core::mem::size_of_val(&prepared) > 0); } #[test] @@ -254,7 +254,7 @@ mod tests { let prepared = PreparedExecve::new(binary_path, &args, &env).unwrap(); // Should handle large numbers of environment variables - assert!(std::mem::size_of_val(&prepared) > 0); + assert!(core::mem::size_of_val(&prepared) > 0); } #[test] @@ -266,7 +266,7 @@ mod tests { let prepared = PreparedExecve::new(binary_path, &args, &env).unwrap(); // Should handle empty binary path (though this might not be valid for execve) - assert!(std::mem::size_of_val(&prepared) > 0); + assert!(core::mem::size_of_val(&prepared) > 0); } #[test] @@ -281,7 +281,7 @@ mod tests { let prepared = PreparedExecve::new(binary_path, &args, &env).unwrap(); // Should handle empty keys and values - assert!(std::mem::size_of_val(&prepared) > 0); + assert!(core::mem::size_of_val(&prepared) > 0); } #[test] diff --git a/libdd-common/src/unix_utils/process.rs b/libdd-common/src/unix_utils/process.rs index c7704622b0..26763f1e59 100644 --- a/libdd-common/src/unix_utils/process.rs +++ b/libdd-common/src/unix_utils/process.rs @@ -103,7 +103,7 @@ pub fn wait_for_pollhup( #[cfg(test)] mod tests { use super::*; - use std::time::Duration; + use core::time::Duration; #[cfg_attr(miri, ignore)] // miri doesn't support waitpid #[test] diff --git a/libdd-library-config-ffi/Cargo.toml b/libdd-library-config-ffi/Cargo.toml index a8b7bd26e0..a751035173 100644 --- a/libdd-library-config-ffi/Cargo.toml +++ b/libdd-library-config-ffi/Cargo.toml @@ -29,3 +29,7 @@ build_common = { path = "../build-common" } [dev-dependencies] tempfile = { version = "3.3" } + +[lints.clippy] +std_instead_of_alloc = "warn" +std_instead_of_core = "warn" diff --git a/libdd-library-config-ffi/src/lib.rs b/libdd-library-config-ffi/src/lib.rs index 9e53349f9d..a22ad4a99e 100644 --- a/libdd-library-config-ffi/src/lib.rs +++ b/libdd-library-config-ffi/src/lib.rs @@ -1,13 +1,17 @@ // Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +extern crate alloc; + pub mod tracer_metadata; use libdd_common_ffi::{self as ffi, slice::AsBytes, CString, CharSlice, Error}; use libdd_library_config::{self as lib_config, LibraryConfigSource}; #[cfg(all(feature = "catch_panic", panic = "unwind"))] -use std::panic::{catch_unwind, AssertUnwindSafe}; +use core::panic::AssertUnwindSafe; +#[cfg(all(feature = "catch_panic", panic = "unwind"))] +use std::panic::catch_unwind; #[cfg(all(feature = "catch_panic", panic = "unwind"))] macro_rules! catch_panic { @@ -87,15 +91,15 @@ impl LibraryConfig { .into_iter() .map(|c| { Ok(LibraryConfig { - name: ffi::CString::from_std(std::ffi::CString::new(c.name)?), - value: ffi::CString::from_std(std::ffi::CString::new(c.value)?), + name: ffi::CString::from_std(alloc::ffi::CString::new(c.name)?), + value: ffi::CString::from_std(alloc::ffi::CString::new(c.value)?), source: c.source, - config_id: ffi::CString::from_std(std::ffi::CString::new( + config_id: ffi::CString::from_std(alloc::ffi::CString::new( c.config_id.unwrap_or_default(), )?), }) }) - .collect::, std::ffi::NulError>>()?; + .collect::, alloc::ffi::NulError>>()?; Ok(ffi::Vec::from_std(cfg)) } @@ -238,7 +242,7 @@ pub extern "C" fn ddog_library_config_fleet_stable_config_path() -> ffi::CStr<'s lib_config::Configurator::FLEET_STABLE_CONFIGURATION_PATH, "\0" ); - std::ffi::CStr::from_bytes_with_nul_unchecked(path.as_bytes()) + core::ffi::CStr::from_bytes_with_nul_unchecked(path.as_bytes()) }) } @@ -251,7 +255,7 @@ pub extern "C" fn ddog_library_config_local_stable_config_path() -> ffi::CStr<'s lib_config::Configurator::LOCAL_STABLE_CONFIGURATION_PATH, "\0" ); - std::ffi::CStr::from_bytes_with_nul_unchecked(path.as_bytes()) + core::ffi::CStr::from_bytes_with_nul_unchecked(path.as_bytes()) }) } diff --git a/libdd-library-config-ffi/src/tracer_metadata.rs b/libdd-library-config-ffi/src/tracer_metadata.rs index f4d3f6530f..6fbb22ad75 100644 --- a/libdd-library-config-ffi/src/tracer_metadata.rs +++ b/libdd-library-config-ffi/src/tracer_metadata.rs @@ -1,11 +1,11 @@ // Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +use core::ffi::CStr; use libdd_common_ffi::Result; #[cfg(target_os = "linux")] use libdd_library_config::tracer_metadata::AnonymousFileHandle; use libdd_library_config::tracer_metadata::{self, TracerMetadata}; -use std::ffi::CStr; use std::os::raw::{c_char, c_int}; /// C-compatible representation of an anonymous file handle diff --git a/libdd-library-config/Cargo.toml b/libdd-library-config/Cargo.toml index 909a3a25c5..2c150735fb 100644 --- a/libdd-library-config/Cargo.toml +++ b/libdd-library-config/Cargo.toml @@ -36,3 +36,7 @@ serial_test = "3.2" [target.'cfg(unix)'.dependencies] memfd = { version = "0.6" } libc = "0.2" + +[lints.clippy] +std_instead_of_alloc = "warn" +std_instead_of_core = "warn" diff --git a/libdd-library-config/src/lib.rs b/libdd-library-config/src/lib.rs index f243678c09..6d473f1d84 100644 --- a/libdd-library-config/src/lib.rs +++ b/libdd-library-config/src/lib.rs @@ -1,14 +1,15 @@ // Copyright 2021-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +extern crate alloc; + pub mod otel_process_ctx; pub mod tracer_metadata; -use std::borrow::Cow; -use std::cell::OnceCell; +use alloc::borrow::Cow; +use core::{cell::OnceCell, mem, ops::Deref}; use std::collections::HashMap; -use std::ops::Deref; use std::path::Path; -use std::{env, fs, io, mem}; +use std::{env, fs, io}; /// This struct holds maps used to match and template configurations. /// @@ -30,7 +31,7 @@ impl<'a> MatchMaps<'a> { self.env_map.get_or_init(|| { let mut map = HashMap::new(); for e in &process_info.envp { - let Ok(s) = std::str::from_utf8(e.deref()) else { + let Ok(s) = core::str::from_utf8(e.deref()) else { continue; }; let (k, v) = match s.split_once('=') { @@ -47,7 +48,7 @@ impl<'a> MatchMaps<'a> { self.args_map.get_or_init(|| { let mut map = HashMap::new(); for arg in &process_info.args { - let Ok(arg) = std::str::from_utf8(arg.deref()) else { + let Ok(arg) = core::str::from_utf8(arg.deref()) else { continue; }; // Split args between key and value on '=' @@ -145,7 +146,7 @@ impl<'a> Matcher<'a> { template_map_key(index, self.match_maps.args(self.process_info)) } "tags" => template_map_key(index, self.match_maps.tags), - _ => std::borrow::Cow::Borrowed("UNDEFINED"), + _ => alloc::borrow::Cow::Borrowed("UNDEFINED"), }; templated.push_str(&val); rest = tail; @@ -257,7 +258,7 @@ impl<'de> serde::Deserialize<'de> for ConfigMap { impl<'de> serde::de::Visitor<'de> for ConfigMapVisitor { type Value = ConfigMap; - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result { formatter.write_str("struct ConfigMap(HashMap)") } diff --git a/libdd-library-config/src/tracer_metadata.rs b/libdd-library-config/src/tracer_metadata.rs index 03d0ae9b4c..c0ff76dc62 100644 --- a/libdd-library-config/src/tracer_metadata.rs +++ b/libdd-library-config/src/tracer_metadata.rs @@ -1,7 +1,7 @@ // Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +use core::default::Default; use libdd_trace_protobuf::opentelemetry::proto as otel_proto; -use std::default::Default; /// This struct MUST be backward compatible. #[derive(serde::Serialize, Debug, PartialEq, Eq, Hash)] @@ -139,7 +139,7 @@ impl TracerMetadata { key: "threadlocal.attribute_key_map".to_owned(), value: Some(AnyValue { value: Some(any_value::Value::ArrayValue(ArrayValue { - values: std::iter::once(AnyValue { + values: core::iter::once(AnyValue { value: Some(any_value::Value::StringValue( "datadog.local_root_span_id".to_owned(), )), diff --git a/libdd-trace-obfuscation/benches/benchmarks/credit_cards_bench.rs b/libdd-trace-obfuscation/benches/benchmarks/credit_cards_bench.rs index 02520efdfd..ce0967dd57 100644 --- a/libdd-trace-obfuscation/benches/benchmarks/credit_cards_bench.rs +++ b/libdd-trace-obfuscation/benches/benchmarks/credit_cards_bench.rs @@ -1,8 +1,8 @@ // Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 -use std::hint::black_box; -use std::time::Duration; +use core::hint::black_box; +use core::time::Duration; use criterion::Throughput::Elements; use criterion::{criterion_group, BatchSize, BenchmarkId, Criterion}; diff --git a/libdd-trace-obfuscation/benches/benchmarks/ip_address_bench.rs b/libdd-trace-obfuscation/benches/benchmarks/ip_address_bench.rs index 5da38048cf..b5c0a1d4f3 100644 --- a/libdd-trace-obfuscation/benches/benchmarks/ip_address_bench.rs +++ b/libdd-trace-obfuscation/benches/benchmarks/ip_address_bench.rs @@ -1,9 +1,9 @@ // Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +use alloc::borrow::Cow; use criterion::{black_box, criterion_group, Criterion}; use libdd_trace_obfuscation::ip_address; -use std::borrow::Cow; fn quantize_peer_ip_address_benchmark(c: &mut Criterion) { let mut group = c.benchmark_group("ip_address"); diff --git a/libdd-trace-obfuscation/benches/trace_obfuscation.rs b/libdd-trace-obfuscation/benches/trace_obfuscation.rs index f18ba5f9e1..100bb1bbfa 100644 --- a/libdd-trace-obfuscation/benches/trace_obfuscation.rs +++ b/libdd-trace-obfuscation/benches/trace_obfuscation.rs @@ -1,6 +1,8 @@ // Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +extern crate alloc; + use criterion::criterion_main; mod benchmarks; diff --git a/libdd-trace-obfuscation/src/http.rs b/libdd-trace-obfuscation/src/http.rs index bfedd3234f..c3cc86a707 100644 --- a/libdd-trace-obfuscation/src/http.rs +++ b/libdd-trace-obfuscation/src/http.rs @@ -5,9 +5,9 @@ // restrictive on the accepted forms of urls so that this module can be greatly simplified. // One idea for now is to match the url to a regex on both side to validate it +use core::fmt::Write; use fluent_uri::UriRef; use percent_encoding::percent_decode_str; -use std::fmt::Write; /// Returns true for Go net/url's "category 1" characters: /// ASCII bytes that always trigger escaping in URLs (plus space and quote). diff --git a/libdd-trace-obfuscation/src/ip_address.rs b/libdd-trace-obfuscation/src/ip_address.rs index 2395e5b414..d734a28867 100644 --- a/libdd-trace-obfuscation/src/ip_address.rs +++ b/libdd-trace-obfuscation/src/ip_address.rs @@ -1,8 +1,10 @@ // Copyright 2024-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +use alloc::borrow::Cow; +use core::net::Ipv6Addr; use libdd_common::regex_engine::Regex; -use std::{borrow::Cow, collections::HashSet, net::Ipv6Addr, sync::LazyLock}; +use std::{collections::HashSet, sync::LazyLock}; const ALLOWED_IP_ADDRESSES: [&str; 5] = [ // localhost diff --git a/libdd-trace-obfuscation/src/json/mod.rs b/libdd-trace-obfuscation/src/json/mod.rs index 9187926623..6618057f1e 100644 --- a/libdd-trace-obfuscation/src/json/mod.rs +++ b/libdd-trace-obfuscation/src/json/mod.rs @@ -181,7 +181,7 @@ mod tests { enabled: true, keep_keys: keep_keys .iter() - .map(std::string::ToString::to_string) + .map(alloc::string::ToString::to_string) .collect(), ..Default::default() }) @@ -192,11 +192,11 @@ mod tests { enabled: true, keep_keys: keep_keys .iter() - .map(std::string::ToString::to_string) + .map(alloc::string::ToString::to_string) .collect(), transform_keys: transform_keys .iter() - .map(std::string::ToString::to_string) + .map(alloc::string::ToString::to_string) .collect(), transformer: Some(obfuscate_sql_string), }) diff --git a/libdd-trace-obfuscation/src/lib.rs b/libdd-trace-obfuscation/src/lib.rs index d09afe6cd8..5da50c7a15 100644 --- a/libdd-trace-obfuscation/src/lib.rs +++ b/libdd-trace-obfuscation/src/lib.rs @@ -1,5 +1,7 @@ // Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +extern crate alloc; + pub mod credit_cards; pub mod http; pub mod ip_address; diff --git a/libdd-trace-obfuscation/src/obfuscation_config.rs b/libdd-trace-obfuscation/src/obfuscation_config.rs index 093df204f3..67f5526274 100644 --- a/libdd-trace-obfuscation/src/obfuscation_config.rs +++ b/libdd-trace-obfuscation/src/obfuscation_config.rs @@ -106,7 +106,7 @@ impl ObfuscationConfig { /// # Errors /// /// Returns an error if one of the regular expressions used by the config cannot be compiled. - pub fn new() -> Result> { + pub fn new() -> Result> { let tag_replace_rules: Option> = match env::var("DD_APM_REPLACE_TAGS") { Ok(replace_rules_str) => match replacer::parse_rules_from_string(&replace_rules_str) { Ok(res) => { diff --git a/libdd-trace-obfuscation/src/replacer.rs b/libdd-trace-obfuscation/src/replacer.rs index 17d1d93cf1..cda9bc71c8 100644 --- a/libdd-trace-obfuscation/src/replacer.rs +++ b/libdd-trace-obfuscation/src/replacer.rs @@ -192,7 +192,7 @@ fn replace_all( } scratch_space.push_str(&haystack[last_match..]); } - std::mem::swap(scratch_space, haystack); + core::mem::swap(scratch_space, haystack); scratch_space.truncate(0); } diff --git a/libdd-trace-obfuscation/src/sql.rs b/libdd-trace-obfuscation/src/sql.rs index 1678b9cc74..f703cf6969 100644 --- a/libdd-trace-obfuscation/src/sql.rs +++ b/libdd-trace-obfuscation/src/sql.rs @@ -2276,7 +2276,7 @@ fn normalize_plan_sql(s: &str) -> String { #[cfg(test)] mod tests { use super::{DbmsKind, SqlObfuscateConfig, SqlObfuscationMode}; - use std::fmt::Write; + use core::fmt::Write; #[test] fn test_sql_obfuscation() { diff --git a/libdd-trace-obfuscation/tests/test_span_obfuscation.rs b/libdd-trace-obfuscation/tests/test_span_obfuscation.rs index 933c184242..83709e69f1 100644 --- a/libdd-trace-obfuscation/tests/test_span_obfuscation.rs +++ b/libdd-trace-obfuscation/tests/test_span_obfuscation.rs @@ -9,10 +9,11 @@ clippy::format_push_string )] -use std::{ - collections::{BTreeSet, HashSet}, - fmt::{self, Display}, -}; +extern crate alloc; + +use alloc::{collections::BTreeSet, fmt}; +use core::fmt::Display; +use std::collections::HashSet; use libdd_trace_obfuscation::{obfuscate::obfuscate_span, obfuscation_config::ObfuscationConfig}; use libdd_trace_protobuf::pb::{ @@ -152,7 +153,7 @@ impl<'a> SpanComparison<'a> { } } impl Display for SpanComparison<'_> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { fn cmp_field(left: &T, right: &T) -> String { if left == right { format!("{left:?}")