Skip to main content

cheap_clone/
lib.rs

1// `CheapClone` trait is inspired by https://github.com/graphprotocol/graph-node/blob/master/graph/src/cheap_clone.rs
2
3//! A trait which indicates that such type can be cloned cheaply.
4#![cfg_attr(not(any(feature = "std", test)), no_std)]
5#![cfg_attr(docsrs, feature(doc_cfg))]
6#![cfg_attr(docsrs, allow(unused_attributes))]
7#![deny(missing_docs)]
8#![forbid(unsafe_code)]
9
10#[cfg(any(feature = "std", test))]
11extern crate std;
12
13#[cfg(all(not(feature = "std"), feature = "alloc"))]
14extern crate alloc as std;
15
16macro_rules! impl_cheap_clone_for_copy {
17  ($($ty: ty), +$(,)?) => {
18    $(
19      impl crate::CheapClone for $ty {
20        fn cheap_clone(&self) -> Self {
21          *self
22        }
23      }
24    )*
25  };
26}
27
28/// Things that are fast to clone in the context of an application.
29///
30/// The purpose of this API is to reduce the number of calls to .clone() which need to
31/// be audited for performance.
32///
33/// As a rule of thumb, only constant-time `Clone` impls should also implement CheapClone.
34/// Eg:
35/// - ✔ [`Arc<T>`](std::sync::Arc)
36/// - ✔ [`Rc<T>`](std::rc::Rc)
37/// - ✔ [`Bytes`](bytes_1::Bytes)
38/// - ✗ [`Vec<T>`](std::vec::Vec)
39/// - ✔ [`SmolStr`](smol_str03::SmolStr)
40/// - ✔ [`FastStr`](faststr02::FastStr)
41/// - ✗ [`String`]
42pub trait CheapClone: Clone {
43  /// Returns a copy of the value.
44  fn cheap_clone(&self) -> Self {
45    self.clone()
46  }
47}
48
49#[cfg(feature = "bytes_1")]
50#[cfg_attr(docsrs, doc(cfg(feature = "bytes_1")))]
51impl CheapClone for bytes_1::Bytes {}
52
53#[cfg(feature = "smol_str_0_3")]
54#[cfg_attr(docsrs, doc(cfg(feature = "smol_str_0_3")))]
55impl CheapClone for smol_str_0_3::SmolStr {}
56
57#[cfg(feature = "smol_str_0_2")]
58#[cfg_attr(docsrs, doc(cfg(feature = "smol_str_0_2")))]
59impl CheapClone for smol_str_0_2::SmolStr {}
60
61#[cfg(feature = "faststr_0_2")]
62#[cfg_attr(docsrs, doc(cfg(feature = "faststr_0_2")))]
63impl CheapClone for faststr_0_2::FastStr {}
64
65#[cfg(feature = "triomphe_0_1")]
66#[cfg_attr(docsrs, doc(cfg(feature = "triomphe_0_1")))]
67impl<T> CheapClone for triomphe_0_1::Arc<T> {}
68
69#[cfg(any(feature = "alloc", feature = "std"))]
70mod a {
71  use super::CheapClone;
72
73  impl<T: ?Sized> CheapClone for std::rc::Rc<T> {}
74  impl<T: ?Sized> CheapClone for std::sync::Arc<T> {}
75}
76
77impl<T: CheapClone> CheapClone for core::pin::Pin<T> {}
78
79// `core::net` types are `Copy` and live in `core` (since Rust 1.77), so these
80// impls are available on `no_std` targets, not just `std`.
81impl_cheap_clone_for_copy!(
82  core::net::IpAddr,
83  core::net::Ipv4Addr,
84  core::net::Ipv6Addr,
85  core::net::SocketAddr,
86  core::net::SocketAddrV4,
87  core::net::SocketAddrV6,
88);
89
90impl<T: CheapClone> CheapClone for core::cmp::Reverse<T> {
91  #[inline]
92  fn cheap_clone(&self) -> Self {
93    core::cmp::Reverse(self.0.cheap_clone())
94  }
95}
96impl<T: CheapClone> CheapClone for Option<T> {
97  #[inline]
98  fn cheap_clone(&self) -> Self {
99    self.as_ref().map(CheapClone::cheap_clone)
100  }
101}
102impl<T: CheapClone, E: CheapClone> CheapClone for Result<T, E> {
103  #[inline]
104  fn cheap_clone(&self) -> Self {
105    match self {
106      Ok(ok) => Ok(ok.cheap_clone()),
107      Err(err) => Err(err.cheap_clone()),
108    }
109  }
110}
111#[cfg(feature = "either")]
112impl<L: CheapClone, R: CheapClone> CheapClone for either::Either<L, R> {
113  #[inline]
114  fn cheap_clone(&self) -> Self {
115    match self {
116      either::Either::Left(left) => either::Either::Left(left.cheap_clone()),
117      either::Either::Right(right) => either::Either::Right(right.cheap_clone()),
118    }
119  }
120}
121#[cfg(feature = "among")]
122impl<L: CheapClone, M: CheapClone, R: CheapClone> CheapClone for among::Among<L, M, R> {
123  #[inline]
124  fn cheap_clone(&self) -> Self {
125    match self {
126      among::Among::Left(left) => among::Among::Left(left.cheap_clone()),
127      among::Among::Middle(middle) => among::Among::Middle(middle.cheap_clone()),
128      among::Among::Right(right) => among::Among::Right(right.cheap_clone()),
129    }
130  }
131}
132
133impl_cheap_clone_for_copy! {
134  (),
135  bool, char, f32, f64, i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize,
136  core::num::NonZeroI8,
137  core::num::NonZeroI16,
138  core::num::NonZeroI32,
139  core::num::NonZeroI64,
140  core::num::NonZeroI128,
141  core::num::NonZeroIsize,
142  core::num::NonZeroU8,
143  core::num::NonZeroU16,
144  core::num::NonZeroU32,
145  core::num::NonZeroU64,
146  core::num::NonZeroU128,
147  core::num::NonZeroUsize,
148  &str
149}
150
151impl<T: Copy, const N: usize> CheapClone for [T; N] {
152  fn cheap_clone(&self) -> Self {
153    *self
154  }
155}
156
157impl<T> CheapClone for &T {
158  fn cheap_clone(&self) -> Self {
159    self
160  }
161}
162
163macro_rules! impl_cheap_clone_for_tuple {
164  (@output $($param:literal),+ $(,)?) => {
165    ::paste::paste! {
166      impl<$([< T $param >]: CheapClone),+> CheapClone for ($([< T $param >],)+) {
167        fn cheap_clone(&self) -> Self {
168          ($(self.$param.cheap_clone(),)+)
169        }
170      }
171    }
172  };
173  (@mid $($end:literal),+$(,)?) => {
174    $(
175      seq_macro::seq!(
176        N in 0..=$end {
177          impl_cheap_clone_for_tuple!(@output #(N,)*);
178        }
179      );
180    )*
181  };
182  ($end:literal) => {
183    seq_macro::seq!(N in 1..=$end {
184      impl_cheap_clone_for_tuple!(@mid N);
185    });
186  };
187}
188
189impl_cheap_clone_for_tuple!(@output 0);
190impl_cheap_clone_for_tuple!(96);