xref: /openbmc/linux/rust/alloc/lib.rs (revision 72afe05d)
1 // SPDX-License-Identifier: Apache-2.0 OR MIT
2 
3 //! # The Rust core allocation and collections library
4 //!
5 //! This library provides smart pointers and collections for managing
6 //! heap-allocated values.
7 //!
8 //! This library, like core, normally doesn’t need to be used directly
9 //! since its contents are re-exported in the [`std` crate](../std/index.html).
10 //! Crates that use the `#![no_std]` attribute however will typically
11 //! not depend on `std`, so they’d use this crate instead.
12 //!
13 //! ## Boxed values
14 //!
15 //! The [`Box`] type is a smart pointer type. There can only be one owner of a
16 //! [`Box`], and the owner can decide to mutate the contents, which live on the
17 //! heap.
18 //!
19 //! This type can be sent among threads efficiently as the size of a `Box` value
20 //! is the same as that of a pointer. Tree-like data structures are often built
21 //! with boxes because each node often has only one owner, the parent.
22 //!
23 //! ## Reference counted pointers
24 //!
25 //! The [`Rc`] type is a non-threadsafe reference-counted pointer type intended
26 //! for sharing memory within a thread. An [`Rc`] pointer wraps a type, `T`, and
27 //! only allows access to `&T`, a shared reference.
28 //!
29 //! This type is useful when inherited mutability (such as using [`Box`]) is too
30 //! constraining for an application, and is often paired with the [`Cell`] or
31 //! [`RefCell`] types in order to allow mutation.
32 //!
33 //! ## Atomically reference counted pointers
34 //!
35 //! The [`Arc`] type is the threadsafe equivalent of the [`Rc`] type. It
36 //! provides all the same functionality of [`Rc`], except it requires that the
37 //! contained type `T` is shareable. Additionally, [`Arc<T>`][`Arc`] is itself
38 //! sendable while [`Rc<T>`][`Rc`] is not.
39 //!
40 //! This type allows for shared access to the contained data, and is often
41 //! paired with synchronization primitives such as mutexes to allow mutation of
42 //! shared resources.
43 //!
44 //! ## Collections
45 //!
46 //! Implementations of the most common general purpose data structures are
47 //! defined in this library. They are re-exported through the
48 //! [standard collections library](../std/collections/index.html).
49 //!
50 //! ## Heap interfaces
51 //!
52 //! The [`alloc`](alloc/index.html) module defines the low-level interface to the
53 //! default global allocator. It is not compatible with the libc allocator API.
54 //!
55 //! [`Arc`]: sync
56 //! [`Box`]: boxed
57 //! [`Cell`]: core::cell
58 //! [`Rc`]: rc
59 //! [`RefCell`]: core::cell
60 
61 // To run alloc tests without x.py without ending up with two copies of alloc, Miri needs to be
62 // able to "empty" this crate. See <https://github.com/rust-lang/miri-test-libstd/issues/4>.
63 // rustc itself never sets the feature, so this line has no effect there.
64 #![cfg(any(not(feature = "miri-test-libstd"), test, doctest))]
65 //
66 #![allow(unused_attributes)]
67 #![stable(feature = "alloc", since = "1.36.0")]
68 #![doc(
69     html_playground_url = "https://play.rust-lang.org/",
70     issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
71     test(no_crate_inject, attr(allow(unused_variables), deny(warnings)))
72 )]
73 #![doc(cfg_hide(
74     not(test),
75     not(any(test, bootstrap)),
76     any(not(feature = "miri-test-libstd"), test, doctest),
77     no_global_oom_handling,
78     not(no_global_oom_handling),
79     not(no_rc),
80     not(no_sync),
81     target_has_atomic = "ptr"
82 ))]
83 #![no_std]
84 #![needs_allocator]
85 // Lints:
86 #![deny(unsafe_op_in_unsafe_fn)]
87 #![deny(fuzzy_provenance_casts)]
88 #![warn(deprecated_in_future)]
89 #![warn(missing_debug_implementations)]
90 #![warn(missing_docs)]
91 #![allow(explicit_outlives_requirements)]
92 #![warn(multiple_supertrait_upcastable)]
93 #![cfg_attr(not(bootstrap), allow(internal_features))]
94 #![cfg_attr(not(bootstrap), allow(rustdoc::redundant_explicit_links))]
95 //
96 // Library features:
97 // tidy-alphabetical-start
98 #![cfg_attr(not(no_global_oom_handling), feature(const_alloc_error))]
99 #![cfg_attr(not(no_global_oom_handling), feature(const_btree_len))]
100 #![cfg_attr(test, feature(is_sorted))]
101 #![cfg_attr(test, feature(new_uninit))]
102 #![feature(alloc_layout_extra)]
103 #![feature(allocator_api)]
104 #![feature(array_chunks)]
105 #![feature(array_into_iter_constructors)]
106 #![feature(array_methods)]
107 #![feature(array_windows)]
108 #![feature(ascii_char)]
109 #![feature(assert_matches)]
110 #![feature(async_iterator)]
111 #![feature(coerce_unsized)]
112 #![feature(const_align_of_val)]
113 #![feature(const_box)]
114 #![cfg_attr(not(no_borrow), feature(const_cow_is_borrowed))]
115 #![feature(const_eval_select)]
116 #![feature(const_maybe_uninit_as_mut_ptr)]
117 #![feature(const_maybe_uninit_write)]
118 #![feature(const_maybe_uninit_zeroed)]
119 #![feature(const_pin)]
120 #![feature(const_refs_to_cell)]
121 #![feature(const_size_of_val)]
122 #![feature(const_waker)]
123 #![feature(core_intrinsics)]
124 #![feature(core_panic)]
125 #![feature(dispatch_from_dyn)]
126 #![feature(error_generic_member_access)]
127 #![feature(error_in_core)]
128 #![feature(exact_size_is_empty)]
129 #![feature(extend_one)]
130 #![feature(fmt_internals)]
131 #![feature(fn_traits)]
132 #![feature(hasher_prefixfree_extras)]
133 #![feature(inline_const)]
134 #![feature(inplace_iteration)]
135 #![feature(iter_advance_by)]
136 #![feature(iter_next_chunk)]
137 #![feature(iter_repeat_n)]
138 #![feature(layout_for_ptr)]
139 #![feature(maybe_uninit_slice)]
140 #![feature(maybe_uninit_uninit_array)]
141 #![feature(maybe_uninit_uninit_array_transpose)]
142 #![feature(pattern)]
143 #![feature(pointer_byte_offsets)]
144 #![feature(ptr_internals)]
145 #![feature(ptr_metadata)]
146 #![feature(ptr_sub_ptr)]
147 #![feature(receiver_trait)]
148 #![feature(saturating_int_impl)]
149 #![feature(set_ptr_value)]
150 #![feature(sized_type_properties)]
151 #![feature(slice_from_ptr_range)]
152 #![feature(slice_group_by)]
153 #![feature(slice_ptr_get)]
154 #![feature(slice_ptr_len)]
155 #![feature(slice_range)]
156 #![feature(std_internals)]
157 #![feature(str_internals)]
158 #![feature(strict_provenance)]
159 #![feature(trusted_len)]
160 #![feature(trusted_random_access)]
161 #![feature(try_trait_v2)]
162 #![feature(tuple_trait)]
163 #![feature(unchecked_math)]
164 #![feature(unicode_internals)]
165 #![feature(unsize)]
166 #![feature(utf8_chunks)]
167 // tidy-alphabetical-end
168 //
169 // Language features:
170 // tidy-alphabetical-start
171 #![cfg_attr(not(test), feature(generator_trait))]
172 #![cfg_attr(test, feature(panic_update_hook))]
173 #![cfg_attr(test, feature(test))]
174 #![feature(allocator_internals)]
175 #![feature(allow_internal_unstable)]
176 #![feature(associated_type_bounds)]
177 #![feature(c_unwind)]
178 #![feature(cfg_sanitize)]
179 #![feature(const_mut_refs)]
180 #![feature(const_precise_live_drops)]
181 #![feature(const_ptr_write)]
182 #![feature(const_trait_impl)]
183 #![feature(const_try)]
184 #![feature(dropck_eyepatch)]
185 #![feature(exclusive_range_pattern)]
186 #![feature(fundamental)]
187 #![feature(hashmap_internals)]
188 #![feature(lang_items)]
189 #![feature(min_specialization)]
190 #![feature(multiple_supertrait_upcastable)]
191 #![feature(negative_impls)]
192 #![feature(never_type)]
193 #![feature(pointer_is_aligned)]
194 #![feature(rustc_allow_const_fn_unstable)]
195 #![feature(rustc_attrs)]
196 #![feature(slice_internals)]
197 #![feature(staged_api)]
198 #![feature(stmt_expr_attributes)]
199 #![feature(unboxed_closures)]
200 #![feature(unsized_fn_params)]
201 #![feature(with_negative_coherence)]
202 // tidy-alphabetical-end
203 //
204 // Rustdoc features:
205 #![feature(doc_cfg)]
206 #![feature(doc_cfg_hide)]
207 // Technically, this is a bug in rustdoc: rustdoc sees the documentation on `#[lang = slice_alloc]`
208 // blocks is for `&[T]`, which also has documentation using this feature in `core`, and gets mad
209 // that the feature-gate isn't enabled. Ideally, it wouldn't check for the feature gate for docs
210 // from other crates, but since this can only appear for lang items, it doesn't seem worth fixing.
211 #![feature(intra_doc_pointers)]
212 
213 // Allow testing this library
214 #[cfg(test)]
215 #[macro_use]
216 extern crate std;
217 #[cfg(test)]
218 extern crate test;
219 #[cfg(test)]
220 mod testing;
221 
222 // Module with internal macros used by other modules (needs to be included before other modules).
223 #[cfg(not(no_macros))]
224 #[macro_use]
225 mod macros;
226 
227 mod raw_vec;
228 
229 // Heaps provided for low-level allocation strategies
230 
231 pub mod alloc;
232 
233 // Primitive types using the heaps above
234 
235 // Need to conditionally define the mod from `boxed.rs` to avoid
236 // duplicating the lang-items when building in test cfg; but also need
237 // to allow code to have `use boxed::Box;` declarations.
238 #[cfg(not(test))]
239 pub mod boxed;
240 #[cfg(test)]
241 mod boxed {
242     pub use std::boxed::Box;
243 }
244 #[cfg(not(no_borrow))]
245 pub mod borrow;
246 pub mod collections;
247 #[cfg(all(not(no_rc), not(no_sync), not(no_global_oom_handling)))]
248 pub mod ffi;
249 #[cfg(not(no_fmt))]
250 pub mod fmt;
251 #[cfg(not(no_rc))]
252 pub mod rc;
253 pub mod slice;
254 #[cfg(not(no_str))]
255 pub mod str;
256 #[cfg(not(no_string))]
257 pub mod string;
258 #[cfg(all(not(no_rc), not(no_sync), target_has_atomic = "ptr"))]
259 pub mod sync;
260 #[cfg(all(not(no_global_oom_handling), not(no_rc), not(no_sync), target_has_atomic = "ptr"))]
261 pub mod task;
262 #[cfg(test)]
263 mod tests;
264 pub mod vec;
265 
266 #[doc(hidden)]
267 #[unstable(feature = "liballoc_internals", issue = "none", reason = "implementation detail")]
268 pub mod __export {
269     pub use core::format_args;
270 }
271 
272 #[cfg(test)]
273 #[allow(dead_code)] // Not used in all configurations
274 pub(crate) mod test_helpers {
275     /// Copied from `std::test_helpers::test_rng`, since these tests rely on the
276     /// seed not being the same for every RNG invocation too.
277     pub(crate) fn test_rng() -> rand_xorshift::XorShiftRng {
278         use std::hash::{BuildHasher, Hash, Hasher};
279         let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
280         std::panic::Location::caller().hash(&mut hasher);
281         let hc64 = hasher.finish();
282         let seed_vec =
283             hc64.to_le_bytes().into_iter().chain(0u8..8).collect::<crate::vec::Vec<u8>>();
284         let seed: [u8; 16] = seed_vec.as_slice().try_into().unwrap();
285         rand::SeedableRng::from_seed(seed)
286     }
287 }
288