xref: /openbmc/linux/rust/alloc/lib.rs (revision 0c6dfa75)
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 #![allow(unused_attributes)]
62 #![stable(feature = "alloc", since = "1.36.0")]
63 #![doc(
64     html_playground_url = "https://play.rust-lang.org/",
65     issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
66     test(no_crate_inject, attr(allow(unused_variables), deny(warnings)))
67 )]
68 #![doc(cfg_hide(
69     not(test),
70     not(any(test, bootstrap)),
71     any(not(feature = "miri-test-libstd"), test, doctest),
72     no_global_oom_handling,
73     not(no_global_oom_handling),
74     not(no_rc),
75     not(no_sync),
76     target_has_atomic = "ptr"
77 ))]
78 #![no_std]
79 #![needs_allocator]
80 // To run alloc tests without x.py without ending up with two copies of alloc, Miri needs to be
81 // able to "empty" this crate. See <https://github.com/rust-lang/miri-test-libstd/issues/4>.
82 // rustc itself never sets the feature, so this line has no affect there.
83 #![cfg(any(not(feature = "miri-test-libstd"), test, doctest))]
84 //
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 //
94 // Library features:
95 // tidy-alphabetical-start
96 #![cfg_attr(not(no_global_oom_handling), feature(const_alloc_error))]
97 #![cfg_attr(not(no_global_oom_handling), feature(const_btree_len))]
98 #![cfg_attr(test, feature(is_sorted))]
99 #![cfg_attr(test, feature(new_uninit))]
100 #![feature(alloc_layout_extra)]
101 #![feature(allocator_api)]
102 #![feature(array_chunks)]
103 #![feature(array_into_iter_constructors)]
104 #![feature(array_methods)]
105 #![feature(array_windows)]
106 #![feature(ascii_char)]
107 #![feature(assert_matches)]
108 #![feature(async_iterator)]
109 #![feature(coerce_unsized)]
110 #![feature(const_align_of_val)]
111 #![feature(const_box)]
112 #![cfg_attr(not(no_borrow), feature(const_cow_is_borrowed))]
113 #![feature(const_eval_select)]
114 #![feature(const_maybe_uninit_as_mut_ptr)]
115 #![feature(const_maybe_uninit_write)]
116 #![feature(const_maybe_uninit_zeroed)]
117 #![feature(const_pin)]
118 #![feature(const_refs_to_cell)]
119 #![feature(const_size_of_val)]
120 #![feature(const_waker)]
121 #![feature(core_intrinsics)]
122 #![feature(core_panic)]
123 #![feature(dispatch_from_dyn)]
124 #![feature(error_generic_member_access)]
125 #![feature(error_in_core)]
126 #![feature(exact_size_is_empty)]
127 #![feature(extend_one)]
128 #![feature(fmt_internals)]
129 #![feature(fn_traits)]
130 #![feature(hasher_prefixfree_extras)]
131 #![feature(inline_const)]
132 #![feature(inplace_iteration)]
133 #![feature(iter_advance_by)]
134 #![feature(iter_next_chunk)]
135 #![feature(iter_repeat_n)]
136 #![feature(layout_for_ptr)]
137 #![feature(maybe_uninit_slice)]
138 #![feature(maybe_uninit_uninit_array)]
139 #![feature(maybe_uninit_uninit_array_transpose)]
140 #![feature(pattern)]
141 #![feature(pointer_byte_offsets)]
142 #![feature(provide_any)]
143 #![feature(ptr_internals)]
144 #![feature(ptr_metadata)]
145 #![feature(ptr_sub_ptr)]
146 #![feature(receiver_trait)]
147 #![feature(saturating_int_impl)]
148 #![feature(set_ptr_value)]
149 #![feature(sized_type_properties)]
150 #![feature(slice_from_ptr_range)]
151 #![feature(slice_group_by)]
152 #![feature(slice_ptr_get)]
153 #![feature(slice_ptr_len)]
154 #![feature(slice_range)]
155 #![feature(std_internals)]
156 #![feature(str_internals)]
157 #![feature(strict_provenance)]
158 #![feature(trusted_len)]
159 #![feature(trusted_random_access)]
160 #![feature(try_trait_v2)]
161 #![feature(tuple_trait)]
162 #![feature(unchecked_math)]
163 #![feature(unicode_internals)]
164 #![feature(unsize)]
165 #![feature(utf8_chunks)]
166 // tidy-alphabetical-end
167 //
168 // Language features:
169 // tidy-alphabetical-start
170 #![cfg_attr(not(test), feature(generator_trait))]
171 #![cfg_attr(test, feature(panic_update_hook))]
172 #![cfg_attr(test, feature(test))]
173 #![feature(allocator_internals)]
174 #![feature(allow_internal_unstable)]
175 #![feature(associated_type_bounds)]
176 #![feature(c_unwind)]
177 #![feature(cfg_sanitize)]
178 #![feature(const_mut_refs)]
179 #![feature(const_precise_live_drops)]
180 #![feature(const_ptr_write)]
181 #![feature(const_trait_impl)]
182 #![feature(const_try)]
183 #![feature(dropck_eyepatch)]
184 #![feature(exclusive_range_pattern)]
185 #![feature(fundamental)]
186 #![feature(hashmap_internals)]
187 #![feature(lang_items)]
188 #![feature(min_specialization)]
189 #![feature(multiple_supertrait_upcastable)]
190 #![feature(negative_impls)]
191 #![feature(never_type)]
192 #![feature(pointer_is_aligned)]
193 #![feature(rustc_allow_const_fn_unstable)]
194 #![feature(rustc_attrs)]
195 #![feature(slice_internals)]
196 #![feature(staged_api)]
197 #![feature(stmt_expr_attributes)]
198 #![feature(unboxed_closures)]
199 #![feature(unsized_fn_params)]
200 #![feature(with_negative_coherence)]
201 // tidy-alphabetical-end
202 //
203 // Rustdoc features:
204 #![feature(doc_cfg)]
205 #![feature(doc_cfg_hide)]
206 // Technically, this is a bug in rustdoc: rustdoc sees the documentation on `#[lang = slice_alloc]`
207 // blocks is for `&[T]`, which also has documentation using this feature in `core`, and gets mad
208 // that the feature-gate isn't enabled. Ideally, it wouldn't check for the feature gate for docs
209 // from other crates, but since this can only appear for lang items, it doesn't seem worth fixing.
210 #![feature(intra_doc_pointers)]
211 
212 // Allow testing this library
213 #[cfg(test)]
214 #[macro_use]
215 extern crate std;
216 #[cfg(test)]
217 extern crate test;
218 #[cfg(test)]
219 mod testing;
220 
221 // Module with internal macros used by other modules (needs to be included before other modules).
222 #[cfg(not(no_macros))]
223 #[macro_use]
224 mod macros;
225 
226 mod raw_vec;
227 
228 // Heaps provided for low-level allocation strategies
229 
230 pub mod alloc;
231 
232 // Primitive types using the heaps above
233 
234 // Need to conditionally define the mod from `boxed.rs` to avoid
235 // duplicating the lang-items when building in test cfg; but also need
236 // to allow code to have `use boxed::Box;` declarations.
237 #[cfg(not(test))]
238 pub mod boxed;
239 #[cfg(test)]
240 mod boxed {
241     pub use std::boxed::Box;
242 }
243 #[cfg(not(no_borrow))]
244 pub mod borrow;
245 pub mod collections;
246 #[cfg(all(not(no_rc), not(no_sync), not(no_global_oom_handling)))]
247 pub mod ffi;
248 #[cfg(not(no_fmt))]
249 pub mod fmt;
250 #[cfg(not(no_rc))]
251 pub mod rc;
252 pub mod slice;
253 #[cfg(not(no_str))]
254 pub mod str;
255 #[cfg(not(no_string))]
256 pub mod string;
257 #[cfg(all(not(no_rc), not(no_sync), target_has_atomic = "ptr"))]
258 pub mod sync;
259 #[cfg(all(not(no_global_oom_handling), not(no_rc), not(no_sync), target_has_atomic = "ptr"))]
260 pub mod task;
261 #[cfg(test)]
262 mod tests;
263 pub mod vec;
264 
265 #[doc(hidden)]
266 #[unstable(feature = "liballoc_internals", issue = "none", reason = "implementation detail")]
267 pub mod __export {
268     pub use core::format_args;
269 }
270 
271 #[cfg(test)]
272 #[allow(dead_code)] // Not used in all configurations
273 pub(crate) mod test_helpers {
274     /// Copied from `std::test_helpers::test_rng`, since these tests rely on the
275     /// seed not being the same for every RNG invocation too.
276     pub(crate) fn test_rng() -> rand_xorshift::XorShiftRng {
277         use std::hash::{BuildHasher, Hash, Hasher};
278         let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
279         std::panic::Location::caller().hash(&mut hasher);
280         let hc64 = hasher.finish();
281         let seed_vec =
282             hc64.to_le_bytes().into_iter().chain(0u8..8).collect::<crate::vec::Vec<u8>>();
283         let seed: [u8; 16] = seed_vec.as_slice().try_into().unwrap();
284         rand::SeedableRng::from_seed(seed)
285     }
286 }
287