boxed.rs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028
  1. // SPDX-License-Identifier: Apache-2.0 OR MIT
  2. //! A pointer type for heap allocation.
  3. //!
  4. //! [`Box<T>`], casually referred to as a 'box', provides the simplest form of
  5. //! heap allocation in Rust. Boxes provide ownership for this allocation, and
  6. //! drop their contents when they go out of scope. Boxes also ensure that they
  7. //! never allocate more than `isize::MAX` bytes.
  8. //!
  9. //! # Examples
  10. //!
  11. //! Move a value from the stack to the heap by creating a [`Box`]:
  12. //!
  13. //! ```
  14. //! let val: u8 = 5;
  15. //! let boxed: Box<u8> = Box::new(val);
  16. //! ```
  17. //!
  18. //! Move a value from a [`Box`] back to the stack by [dereferencing]:
  19. //!
  20. //! ```
  21. //! let boxed: Box<u8> = Box::new(5);
  22. //! let val: u8 = *boxed;
  23. //! ```
  24. //!
  25. //! Creating a recursive data structure:
  26. //!
  27. //! ```
  28. //! #[derive(Debug)]
  29. //! enum List<T> {
  30. //! Cons(T, Box<List<T>>),
  31. //! Nil,
  32. //! }
  33. //!
  34. //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
  35. //! println!("{list:?}");
  36. //! ```
  37. //!
  38. //! This will print `Cons(1, Cons(2, Nil))`.
  39. //!
  40. //! Recursive structures must be boxed, because if the definition of `Cons`
  41. //! looked like this:
  42. //!
  43. //! ```compile_fail,E0072
  44. //! # enum List<T> {
  45. //! Cons(T, List<T>),
  46. //! # }
  47. //! ```
  48. //!
  49. //! It wouldn't work. This is because the size of a `List` depends on how many
  50. //! elements are in the list, and so we don't know how much memory to allocate
  51. //! for a `Cons`. By introducing a [`Box<T>`], which has a defined size, we know how
  52. //! big `Cons` needs to be.
  53. //!
  54. //! # Memory layout
  55. //!
  56. //! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
  57. //! its allocation. It is valid to convert both ways between a [`Box`] and a
  58. //! raw pointer allocated with the [`Global`] allocator, given that the
  59. //! [`Layout`] used with the allocator is correct for the type. More precisely,
  60. //! a `value: *mut T` that has been allocated with the [`Global`] allocator
  61. //! with `Layout::for_value(&*value)` may be converted into a box using
  62. //! [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut
  63. //! T` obtained from [`Box::<T>::into_raw`] may be deallocated using the
  64. //! [`Global`] allocator with [`Layout::for_value(&*value)`].
  65. //!
  66. //! For zero-sized values, the `Box` pointer still has to be [valid] for reads
  67. //! and writes and sufficiently aligned. In particular, casting any aligned
  68. //! non-zero integer literal to a raw pointer produces a valid pointer, but a
  69. //! pointer pointing into previously allocated memory that since got freed is
  70. //! not valid. The recommended way to build a Box to a ZST if `Box::new` cannot
  71. //! be used is to use [`ptr::NonNull::dangling`].
  72. //!
  73. //! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
  74. //! as a single pointer and is also ABI-compatible with C pointers
  75. //! (i.e. the C type `T*`). This means that if you have extern "C"
  76. //! Rust functions that will be called from C, you can define those
  77. //! Rust functions using `Box<T>` types, and use `T*` as corresponding
  78. //! type on the C side. As an example, consider this C header which
  79. //! declares functions that create and destroy some kind of `Foo`
  80. //! value:
  81. //!
  82. //! ```c
  83. //! /* C header */
  84. //!
  85. //! /* Returns ownership to the caller */
  86. //! struct Foo* foo_new(void);
  87. //!
  88. //! /* Takes ownership from the caller; no-op when invoked with null */
  89. //! void foo_delete(struct Foo*);
  90. //! ```
  91. //!
  92. //! These two functions might be implemented in Rust as follows. Here, the
  93. //! `struct Foo*` type from C is translated to `Box<Foo>`, which captures
  94. //! the ownership constraints. Note also that the nullable argument to
  95. //! `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>`
  96. //! cannot be null.
  97. //!
  98. //! ```
  99. //! #[repr(C)]
  100. //! pub struct Foo;
  101. //!
  102. //! #[no_mangle]
  103. //! pub extern "C" fn foo_new() -> Box<Foo> {
  104. //! Box::new(Foo)
  105. //! }
  106. //!
  107. //! #[no_mangle]
  108. //! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
  109. //! ```
  110. //!
  111. //! Even though `Box<T>` has the same representation and C ABI as a C pointer,
  112. //! this does not mean that you can convert an arbitrary `T*` into a `Box<T>`
  113. //! and expect things to work. `Box<T>` values will always be fully aligned,
  114. //! non-null pointers. Moreover, the destructor for `Box<T>` will attempt to
  115. //! free the value with the global allocator. In general, the best practice
  116. //! is to only use `Box<T>` for pointers that originated from the global
  117. //! allocator.
  118. //!
  119. //! **Important.** At least at present, you should avoid using
  120. //! `Box<T>` types for functions that are defined in C but invoked
  121. //! from Rust. In those cases, you should directly mirror the C types
  122. //! as closely as possible. Using types like `Box<T>` where the C
  123. //! definition is just using `T*` can lead to undefined behavior, as
  124. //! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
  125. //!
  126. //! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
  127. //! [dereferencing]: core::ops::Deref
  128. //! [`Box::<T>::from_raw(value)`]: Box::from_raw
  129. //! [`Global`]: crate::alloc::Global
  130. //! [`Layout`]: crate::alloc::Layout
  131. //! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value
  132. //! [valid]: ptr#safety
  133. #![stable(feature = "rust1", since = "1.0.0")]
  134. use core::any::Any;
  135. use core::async_iter::AsyncIterator;
  136. use core::borrow;
  137. use core::cmp::Ordering;
  138. use core::convert::{From, TryFrom};
  139. use core::fmt;
  140. use core::future::Future;
  141. use core::hash::{Hash, Hasher};
  142. #[cfg(not(no_global_oom_handling))]
  143. use core::iter::FromIterator;
  144. use core::iter::{FusedIterator, Iterator};
  145. use core::marker::{Destruct, Unpin, Unsize};
  146. use core::mem;
  147. use core::ops::{
  148. CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
  149. };
  150. use core::pin::Pin;
  151. use core::ptr::{self, Unique};
  152. use core::task::{Context, Poll};
  153. #[cfg(not(no_global_oom_handling))]
  154. use crate::alloc::{handle_alloc_error, WriteCloneIntoRaw};
  155. use crate::alloc::{AllocError, Allocator, Global, Layout};
  156. #[cfg(not(no_global_oom_handling))]
  157. use crate::borrow::Cow;
  158. use crate::raw_vec::RawVec;
  159. #[cfg(not(no_global_oom_handling))]
  160. use crate::str::from_boxed_utf8_unchecked;
  161. #[cfg(not(no_global_oom_handling))]
  162. use crate::vec::Vec;
  163. #[cfg(not(no_thin))]
  164. #[unstable(feature = "thin_box", issue = "92791")]
  165. pub use thin::ThinBox;
  166. #[cfg(not(no_thin))]
  167. mod thin;
  168. /// A pointer type for heap allocation.
  169. ///
  170. /// See the [module-level documentation](../../std/boxed/index.html) for more.
  171. #[lang = "owned_box"]
  172. #[fundamental]
  173. #[stable(feature = "rust1", since = "1.0.0")]
  174. // The declaration of the `Box` struct must be kept in sync with the
  175. // `alloc::alloc::box_free` function or ICEs will happen. See the comment
  176. // on `box_free` for more details.
  177. pub struct Box<
  178. T: ?Sized,
  179. #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
  180. >(Unique<T>, A);
  181. impl<T> Box<T> {
  182. /// Allocates memory on the heap and then places `x` into it.
  183. ///
  184. /// This doesn't actually allocate if `T` is zero-sized.
  185. ///
  186. /// # Examples
  187. ///
  188. /// ```
  189. /// let five = Box::new(5);
  190. /// ```
  191. #[cfg(not(no_global_oom_handling))]
  192. #[inline(always)]
  193. #[stable(feature = "rust1", since = "1.0.0")]
  194. #[must_use]
  195. pub fn new(x: T) -> Self {
  196. box x
  197. }
  198. /// Constructs a new box with uninitialized contents.
  199. ///
  200. /// # Examples
  201. ///
  202. /// ```
  203. /// #![feature(new_uninit)]
  204. ///
  205. /// let mut five = Box::<u32>::new_uninit();
  206. ///
  207. /// let five = unsafe {
  208. /// // Deferred initialization:
  209. /// five.as_mut_ptr().write(5);
  210. ///
  211. /// five.assume_init()
  212. /// };
  213. ///
  214. /// assert_eq!(*five, 5)
  215. /// ```
  216. #[cfg(not(no_global_oom_handling))]
  217. #[unstable(feature = "new_uninit", issue = "63291")]
  218. #[must_use]
  219. #[inline]
  220. pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
  221. Self::new_uninit_in(Global)
  222. }
  223. /// Constructs a new `Box` with uninitialized contents, with the memory
  224. /// being filled with `0` bytes.
  225. ///
  226. /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
  227. /// of this method.
  228. ///
  229. /// # Examples
  230. ///
  231. /// ```
  232. /// #![feature(new_uninit)]
  233. ///
  234. /// let zero = Box::<u32>::new_zeroed();
  235. /// let zero = unsafe { zero.assume_init() };
  236. ///
  237. /// assert_eq!(*zero, 0)
  238. /// ```
  239. ///
  240. /// [zeroed]: mem::MaybeUninit::zeroed
  241. #[cfg(not(no_global_oom_handling))]
  242. #[inline]
  243. #[unstable(feature = "new_uninit", issue = "63291")]
  244. #[must_use]
  245. pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
  246. Self::new_zeroed_in(Global)
  247. }
  248. /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
  249. /// `x` will be pinned in memory and unable to be moved.
  250. #[cfg(not(no_global_oom_handling))]
  251. #[stable(feature = "pin", since = "1.33.0")]
  252. #[must_use]
  253. #[inline(always)]
  254. pub fn pin(x: T) -> Pin<Box<T>> {
  255. (box x).into()
  256. }
  257. /// Allocates memory on the heap then places `x` into it,
  258. /// returning an error if the allocation fails
  259. ///
  260. /// This doesn't actually allocate if `T` is zero-sized.
  261. ///
  262. /// # Examples
  263. ///
  264. /// ```
  265. /// #![feature(allocator_api)]
  266. ///
  267. /// let five = Box::try_new(5)?;
  268. /// # Ok::<(), std::alloc::AllocError>(())
  269. /// ```
  270. #[unstable(feature = "allocator_api", issue = "32838")]
  271. #[inline]
  272. pub fn try_new(x: T) -> Result<Self, AllocError> {
  273. Self::try_new_in(x, Global)
  274. }
  275. /// Constructs a new box with uninitialized contents on the heap,
  276. /// returning an error if the allocation fails
  277. ///
  278. /// # Examples
  279. ///
  280. /// ```
  281. /// #![feature(allocator_api, new_uninit)]
  282. ///
  283. /// let mut five = Box::<u32>::try_new_uninit()?;
  284. ///
  285. /// let five = unsafe {
  286. /// // Deferred initialization:
  287. /// five.as_mut_ptr().write(5);
  288. ///
  289. /// five.assume_init()
  290. /// };
  291. ///
  292. /// assert_eq!(*five, 5);
  293. /// # Ok::<(), std::alloc::AllocError>(())
  294. /// ```
  295. #[unstable(feature = "allocator_api", issue = "32838")]
  296. // #[unstable(feature = "new_uninit", issue = "63291")]
  297. #[inline]
  298. pub fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
  299. Box::try_new_uninit_in(Global)
  300. }
  301. /// Constructs a new `Box` with uninitialized contents, with the memory
  302. /// being filled with `0` bytes on the heap
  303. ///
  304. /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
  305. /// of this method.
  306. ///
  307. /// # Examples
  308. ///
  309. /// ```
  310. /// #![feature(allocator_api, new_uninit)]
  311. ///
  312. /// let zero = Box::<u32>::try_new_zeroed()?;
  313. /// let zero = unsafe { zero.assume_init() };
  314. ///
  315. /// assert_eq!(*zero, 0);
  316. /// # Ok::<(), std::alloc::AllocError>(())
  317. /// ```
  318. ///
  319. /// [zeroed]: mem::MaybeUninit::zeroed
  320. #[unstable(feature = "allocator_api", issue = "32838")]
  321. // #[unstable(feature = "new_uninit", issue = "63291")]
  322. #[inline]
  323. pub fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
  324. Box::try_new_zeroed_in(Global)
  325. }
  326. }
  327. impl<T, A: Allocator> Box<T, A> {
  328. /// Allocates memory in the given allocator then places `x` into it.
  329. ///
  330. /// This doesn't actually allocate if `T` is zero-sized.
  331. ///
  332. /// # Examples
  333. ///
  334. /// ```
  335. /// #![feature(allocator_api)]
  336. ///
  337. /// use std::alloc::System;
  338. ///
  339. /// let five = Box::new_in(5, System);
  340. /// ```
  341. #[cfg(not(no_global_oom_handling))]
  342. #[unstable(feature = "allocator_api", issue = "32838")]
  343. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  344. #[must_use]
  345. #[inline]
  346. pub const fn new_in(x: T, alloc: A) -> Self
  347. where
  348. A: ~const Allocator + ~const Destruct,
  349. {
  350. let mut boxed = Self::new_uninit_in(alloc);
  351. unsafe {
  352. boxed.as_mut_ptr().write(x);
  353. boxed.assume_init()
  354. }
  355. }
  356. /// Allocates memory in the given allocator then places `x` into it,
  357. /// returning an error if the allocation fails
  358. ///
  359. /// This doesn't actually allocate if `T` is zero-sized.
  360. ///
  361. /// # Examples
  362. ///
  363. /// ```
  364. /// #![feature(allocator_api)]
  365. ///
  366. /// use std::alloc::System;
  367. ///
  368. /// let five = Box::try_new_in(5, System)?;
  369. /// # Ok::<(), std::alloc::AllocError>(())
  370. /// ```
  371. #[unstable(feature = "allocator_api", issue = "32838")]
  372. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  373. #[inline]
  374. pub const fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError>
  375. where
  376. T: ~const Destruct,
  377. A: ~const Allocator + ~const Destruct,
  378. {
  379. let mut boxed = Self::try_new_uninit_in(alloc)?;
  380. unsafe {
  381. boxed.as_mut_ptr().write(x);
  382. Ok(boxed.assume_init())
  383. }
  384. }
  385. /// Constructs a new box with uninitialized contents in the provided allocator.
  386. ///
  387. /// # Examples
  388. ///
  389. /// ```
  390. /// #![feature(allocator_api, new_uninit)]
  391. ///
  392. /// use std::alloc::System;
  393. ///
  394. /// let mut five = Box::<u32, _>::new_uninit_in(System);
  395. ///
  396. /// let five = unsafe {
  397. /// // Deferred initialization:
  398. /// five.as_mut_ptr().write(5);
  399. ///
  400. /// five.assume_init()
  401. /// };
  402. ///
  403. /// assert_eq!(*five, 5)
  404. /// ```
  405. #[unstable(feature = "allocator_api", issue = "32838")]
  406. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  407. #[cfg(not(no_global_oom_handling))]
  408. #[must_use]
  409. // #[unstable(feature = "new_uninit", issue = "63291")]
  410. pub const fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
  411. where
  412. A: ~const Allocator + ~const Destruct,
  413. {
  414. let layout = Layout::new::<mem::MaybeUninit<T>>();
  415. // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
  416. // That would make code size bigger.
  417. match Box::try_new_uninit_in(alloc) {
  418. Ok(m) => m,
  419. Err(_) => handle_alloc_error(layout),
  420. }
  421. }
  422. /// Constructs a new box with uninitialized contents in the provided allocator,
  423. /// returning an error if the allocation fails
  424. ///
  425. /// # Examples
  426. ///
  427. /// ```
  428. /// #![feature(allocator_api, new_uninit)]
  429. ///
  430. /// use std::alloc::System;
  431. ///
  432. /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
  433. ///
  434. /// let five = unsafe {
  435. /// // Deferred initialization:
  436. /// five.as_mut_ptr().write(5);
  437. ///
  438. /// five.assume_init()
  439. /// };
  440. ///
  441. /// assert_eq!(*five, 5);
  442. /// # Ok::<(), std::alloc::AllocError>(())
  443. /// ```
  444. #[unstable(feature = "allocator_api", issue = "32838")]
  445. // #[unstable(feature = "new_uninit", issue = "63291")]
  446. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  447. pub const fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
  448. where
  449. A: ~const Allocator + ~const Destruct,
  450. {
  451. let layout = Layout::new::<mem::MaybeUninit<T>>();
  452. let ptr = alloc.allocate(layout)?.cast();
  453. unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
  454. }
  455. /// Constructs a new `Box` with uninitialized contents, with the memory
  456. /// being filled with `0` bytes in the provided allocator.
  457. ///
  458. /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
  459. /// of this method.
  460. ///
  461. /// # Examples
  462. ///
  463. /// ```
  464. /// #![feature(allocator_api, new_uninit)]
  465. ///
  466. /// use std::alloc::System;
  467. ///
  468. /// let zero = Box::<u32, _>::new_zeroed_in(System);
  469. /// let zero = unsafe { zero.assume_init() };
  470. ///
  471. /// assert_eq!(*zero, 0)
  472. /// ```
  473. ///
  474. /// [zeroed]: mem::MaybeUninit::zeroed
  475. #[unstable(feature = "allocator_api", issue = "32838")]
  476. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  477. #[cfg(not(no_global_oom_handling))]
  478. // #[unstable(feature = "new_uninit", issue = "63291")]
  479. #[must_use]
  480. pub const fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
  481. where
  482. A: ~const Allocator + ~const Destruct,
  483. {
  484. let layout = Layout::new::<mem::MaybeUninit<T>>();
  485. // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
  486. // That would make code size bigger.
  487. match Box::try_new_zeroed_in(alloc) {
  488. Ok(m) => m,
  489. Err(_) => handle_alloc_error(layout),
  490. }
  491. }
  492. /// Constructs a new `Box` with uninitialized contents, with the memory
  493. /// being filled with `0` bytes in the provided allocator,
  494. /// returning an error if the allocation fails,
  495. ///
  496. /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
  497. /// of this method.
  498. ///
  499. /// # Examples
  500. ///
  501. /// ```
  502. /// #![feature(allocator_api, new_uninit)]
  503. ///
  504. /// use std::alloc::System;
  505. ///
  506. /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
  507. /// let zero = unsafe { zero.assume_init() };
  508. ///
  509. /// assert_eq!(*zero, 0);
  510. /// # Ok::<(), std::alloc::AllocError>(())
  511. /// ```
  512. ///
  513. /// [zeroed]: mem::MaybeUninit::zeroed
  514. #[unstable(feature = "allocator_api", issue = "32838")]
  515. // #[unstable(feature = "new_uninit", issue = "63291")]
  516. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  517. pub const fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
  518. where
  519. A: ~const Allocator + ~const Destruct,
  520. {
  521. let layout = Layout::new::<mem::MaybeUninit<T>>();
  522. let ptr = alloc.allocate_zeroed(layout)?.cast();
  523. unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
  524. }
  525. /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement `Unpin`, then
  526. /// `x` will be pinned in memory and unable to be moved.
  527. #[cfg(not(no_global_oom_handling))]
  528. #[unstable(feature = "allocator_api", issue = "32838")]
  529. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  530. #[must_use]
  531. #[inline(always)]
  532. pub const fn pin_in(x: T, alloc: A) -> Pin<Self>
  533. where
  534. A: 'static + ~const Allocator + ~const Destruct,
  535. {
  536. Self::into_pin(Self::new_in(x, alloc))
  537. }
  538. /// Converts a `Box<T>` into a `Box<[T]>`
  539. ///
  540. /// This conversion does not allocate on the heap and happens in place.
  541. #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
  542. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  543. pub const fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
  544. let (raw, alloc) = Box::into_raw_with_allocator(boxed);
  545. unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
  546. }
  547. /// Consumes the `Box`, returning the wrapped value.
  548. ///
  549. /// # Examples
  550. ///
  551. /// ```
  552. /// #![feature(box_into_inner)]
  553. ///
  554. /// let c = Box::new(5);
  555. ///
  556. /// assert_eq!(Box::into_inner(c), 5);
  557. /// ```
  558. #[unstable(feature = "box_into_inner", issue = "80437")]
  559. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  560. #[inline]
  561. pub const fn into_inner(boxed: Self) -> T
  562. where
  563. Self: ~const Destruct,
  564. {
  565. *boxed
  566. }
  567. }
  568. impl<T> Box<[T]> {
  569. /// Constructs a new boxed slice with uninitialized contents.
  570. ///
  571. /// # Examples
  572. ///
  573. /// ```
  574. /// #![feature(new_uninit)]
  575. ///
  576. /// let mut values = Box::<[u32]>::new_uninit_slice(3);
  577. ///
  578. /// let values = unsafe {
  579. /// // Deferred initialization:
  580. /// values[0].as_mut_ptr().write(1);
  581. /// values[1].as_mut_ptr().write(2);
  582. /// values[2].as_mut_ptr().write(3);
  583. ///
  584. /// values.assume_init()
  585. /// };
  586. ///
  587. /// assert_eq!(*values, [1, 2, 3])
  588. /// ```
  589. #[cfg(not(no_global_oom_handling))]
  590. #[unstable(feature = "new_uninit", issue = "63291")]
  591. #[must_use]
  592. pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
  593. unsafe { RawVec::with_capacity(len).into_box(len) }
  594. }
  595. /// Constructs a new boxed slice with uninitialized contents, with the memory
  596. /// being filled with `0` bytes.
  597. ///
  598. /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
  599. /// of this method.
  600. ///
  601. /// # Examples
  602. ///
  603. /// ```
  604. /// #![feature(new_uninit)]
  605. ///
  606. /// let values = Box::<[u32]>::new_zeroed_slice(3);
  607. /// let values = unsafe { values.assume_init() };
  608. ///
  609. /// assert_eq!(*values, [0, 0, 0])
  610. /// ```
  611. ///
  612. /// [zeroed]: mem::MaybeUninit::zeroed
  613. #[cfg(not(no_global_oom_handling))]
  614. #[unstable(feature = "new_uninit", issue = "63291")]
  615. #[must_use]
  616. pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
  617. unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
  618. }
  619. /// Constructs a new boxed slice with uninitialized contents. Returns an error if
  620. /// the allocation fails
  621. ///
  622. /// # Examples
  623. ///
  624. /// ```
  625. /// #![feature(allocator_api, new_uninit)]
  626. ///
  627. /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
  628. /// let values = unsafe {
  629. /// // Deferred initialization:
  630. /// values[0].as_mut_ptr().write(1);
  631. /// values[1].as_mut_ptr().write(2);
  632. /// values[2].as_mut_ptr().write(3);
  633. /// values.assume_init()
  634. /// };
  635. ///
  636. /// assert_eq!(*values, [1, 2, 3]);
  637. /// # Ok::<(), std::alloc::AllocError>(())
  638. /// ```
  639. #[unstable(feature = "allocator_api", issue = "32838")]
  640. #[inline]
  641. pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
  642. unsafe {
  643. let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
  644. Ok(l) => l,
  645. Err(_) => return Err(AllocError),
  646. };
  647. let ptr = Global.allocate(layout)?;
  648. Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
  649. }
  650. }
  651. /// Constructs a new boxed slice with uninitialized contents, with the memory
  652. /// being filled with `0` bytes. Returns an error if the allocation fails
  653. ///
  654. /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
  655. /// of this method.
  656. ///
  657. /// # Examples
  658. ///
  659. /// ```
  660. /// #![feature(allocator_api, new_uninit)]
  661. ///
  662. /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
  663. /// let values = unsafe { values.assume_init() };
  664. ///
  665. /// assert_eq!(*values, [0, 0, 0]);
  666. /// # Ok::<(), std::alloc::AllocError>(())
  667. /// ```
  668. ///
  669. /// [zeroed]: mem::MaybeUninit::zeroed
  670. #[unstable(feature = "allocator_api", issue = "32838")]
  671. #[inline]
  672. pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
  673. unsafe {
  674. let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
  675. Ok(l) => l,
  676. Err(_) => return Err(AllocError),
  677. };
  678. let ptr = Global.allocate_zeroed(layout)?;
  679. Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
  680. }
  681. }
  682. }
  683. impl<T, A: Allocator> Box<[T], A> {
  684. /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
  685. ///
  686. /// # Examples
  687. ///
  688. /// ```
  689. /// #![feature(allocator_api, new_uninit)]
  690. ///
  691. /// use std::alloc::System;
  692. ///
  693. /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
  694. ///
  695. /// let values = unsafe {
  696. /// // Deferred initialization:
  697. /// values[0].as_mut_ptr().write(1);
  698. /// values[1].as_mut_ptr().write(2);
  699. /// values[2].as_mut_ptr().write(3);
  700. ///
  701. /// values.assume_init()
  702. /// };
  703. ///
  704. /// assert_eq!(*values, [1, 2, 3])
  705. /// ```
  706. #[cfg(not(no_global_oom_handling))]
  707. #[unstable(feature = "allocator_api", issue = "32838")]
  708. // #[unstable(feature = "new_uninit", issue = "63291")]
  709. #[must_use]
  710. pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
  711. unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
  712. }
  713. /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
  714. /// with the memory being filled with `0` bytes.
  715. ///
  716. /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
  717. /// of this method.
  718. ///
  719. /// # Examples
  720. ///
  721. /// ```
  722. /// #![feature(allocator_api, new_uninit)]
  723. ///
  724. /// use std::alloc::System;
  725. ///
  726. /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
  727. /// let values = unsafe { values.assume_init() };
  728. ///
  729. /// assert_eq!(*values, [0, 0, 0])
  730. /// ```
  731. ///
  732. /// [zeroed]: mem::MaybeUninit::zeroed
  733. #[cfg(not(no_global_oom_handling))]
  734. #[unstable(feature = "allocator_api", issue = "32838")]
  735. // #[unstable(feature = "new_uninit", issue = "63291")]
  736. #[must_use]
  737. pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
  738. unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
  739. }
  740. }
  741. impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
  742. /// Converts to `Box<T, A>`.
  743. ///
  744. /// # Safety
  745. ///
  746. /// As with [`MaybeUninit::assume_init`],
  747. /// it is up to the caller to guarantee that the value
  748. /// really is in an initialized state.
  749. /// Calling this when the content is not yet fully initialized
  750. /// causes immediate undefined behavior.
  751. ///
  752. /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
  753. ///
  754. /// # Examples
  755. ///
  756. /// ```
  757. /// #![feature(new_uninit)]
  758. ///
  759. /// let mut five = Box::<u32>::new_uninit();
  760. ///
  761. /// let five: Box<u32> = unsafe {
  762. /// // Deferred initialization:
  763. /// five.as_mut_ptr().write(5);
  764. ///
  765. /// five.assume_init()
  766. /// };
  767. ///
  768. /// assert_eq!(*five, 5)
  769. /// ```
  770. #[unstable(feature = "new_uninit", issue = "63291")]
  771. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  772. #[inline]
  773. pub const unsafe fn assume_init(self) -> Box<T, A> {
  774. let (raw, alloc) = Box::into_raw_with_allocator(self);
  775. unsafe { Box::from_raw_in(raw as *mut T, alloc) }
  776. }
  777. /// Writes the value and converts to `Box<T, A>`.
  778. ///
  779. /// This method converts the box similarly to [`Box::assume_init`] but
  780. /// writes `value` into it before conversion thus guaranteeing safety.
  781. /// In some scenarios use of this method may improve performance because
  782. /// the compiler may be able to optimize copying from stack.
  783. ///
  784. /// # Examples
  785. ///
  786. /// ```
  787. /// #![feature(new_uninit)]
  788. ///
  789. /// let big_box = Box::<[usize; 1024]>::new_uninit();
  790. ///
  791. /// let mut array = [0; 1024];
  792. /// for (i, place) in array.iter_mut().enumerate() {
  793. /// *place = i;
  794. /// }
  795. ///
  796. /// // The optimizer may be able to elide this copy, so previous code writes
  797. /// // to heap directly.
  798. /// let big_box = Box::write(big_box, array);
  799. ///
  800. /// for (i, x) in big_box.iter().enumerate() {
  801. /// assert_eq!(*x, i);
  802. /// }
  803. /// ```
  804. #[unstable(feature = "new_uninit", issue = "63291")]
  805. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  806. #[inline]
  807. pub const fn write(mut boxed: Self, value: T) -> Box<T, A> {
  808. unsafe {
  809. (*boxed).write(value);
  810. boxed.assume_init()
  811. }
  812. }
  813. }
  814. impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
  815. /// Converts to `Box<[T], A>`.
  816. ///
  817. /// # Safety
  818. ///
  819. /// As with [`MaybeUninit::assume_init`],
  820. /// it is up to the caller to guarantee that the values
  821. /// really are in an initialized state.
  822. /// Calling this when the content is not yet fully initialized
  823. /// causes immediate undefined behavior.
  824. ///
  825. /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
  826. ///
  827. /// # Examples
  828. ///
  829. /// ```
  830. /// #![feature(new_uninit)]
  831. ///
  832. /// let mut values = Box::<[u32]>::new_uninit_slice(3);
  833. ///
  834. /// let values = unsafe {
  835. /// // Deferred initialization:
  836. /// values[0].as_mut_ptr().write(1);
  837. /// values[1].as_mut_ptr().write(2);
  838. /// values[2].as_mut_ptr().write(3);
  839. ///
  840. /// values.assume_init()
  841. /// };
  842. ///
  843. /// assert_eq!(*values, [1, 2, 3])
  844. /// ```
  845. #[unstable(feature = "new_uninit", issue = "63291")]
  846. #[inline]
  847. pub unsafe fn assume_init(self) -> Box<[T], A> {
  848. let (raw, alloc) = Box::into_raw_with_allocator(self);
  849. unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
  850. }
  851. }
  852. impl<T: ?Sized> Box<T> {
  853. /// Constructs a box from a raw pointer.
  854. ///
  855. /// After calling this function, the raw pointer is owned by the
  856. /// resulting `Box`. Specifically, the `Box` destructor will call
  857. /// the destructor of `T` and free the allocated memory. For this
  858. /// to be safe, the memory must have been allocated in accordance
  859. /// with the [memory layout] used by `Box` .
  860. ///
  861. /// # Safety
  862. ///
  863. /// This function is unsafe because improper use may lead to
  864. /// memory problems. For example, a double-free may occur if the
  865. /// function is called twice on the same raw pointer.
  866. ///
  867. /// The safety conditions are described in the [memory layout] section.
  868. ///
  869. /// # Examples
  870. ///
  871. /// Recreate a `Box` which was previously converted to a raw pointer
  872. /// using [`Box::into_raw`]:
  873. /// ```
  874. /// let x = Box::new(5);
  875. /// let ptr = Box::into_raw(x);
  876. /// let x = unsafe { Box::from_raw(ptr) };
  877. /// ```
  878. /// Manually create a `Box` from scratch by using the global allocator:
  879. /// ```
  880. /// use std::alloc::{alloc, Layout};
  881. ///
  882. /// unsafe {
  883. /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
  884. /// // In general .write is required to avoid attempting to destruct
  885. /// // the (uninitialized) previous contents of `ptr`, though for this
  886. /// // simple example `*ptr = 5` would have worked as well.
  887. /// ptr.write(5);
  888. /// let x = Box::from_raw(ptr);
  889. /// }
  890. /// ```
  891. ///
  892. /// [memory layout]: self#memory-layout
  893. /// [`Layout`]: crate::Layout
  894. #[stable(feature = "box_raw", since = "1.4.0")]
  895. #[inline]
  896. pub unsafe fn from_raw(raw: *mut T) -> Self {
  897. unsafe { Self::from_raw_in(raw, Global) }
  898. }
  899. }
  900. impl<T: ?Sized, A: Allocator> Box<T, A> {
  901. /// Constructs a box from a raw pointer in the given allocator.
  902. ///
  903. /// After calling this function, the raw pointer is owned by the
  904. /// resulting `Box`. Specifically, the `Box` destructor will call
  905. /// the destructor of `T` and free the allocated memory. For this
  906. /// to be safe, the memory must have been allocated in accordance
  907. /// with the [memory layout] used by `Box` .
  908. ///
  909. /// # Safety
  910. ///
  911. /// This function is unsafe because improper use may lead to
  912. /// memory problems. For example, a double-free may occur if the
  913. /// function is called twice on the same raw pointer.
  914. ///
  915. ///
  916. /// # Examples
  917. ///
  918. /// Recreate a `Box` which was previously converted to a raw pointer
  919. /// using [`Box::into_raw_with_allocator`]:
  920. /// ```
  921. /// #![feature(allocator_api)]
  922. ///
  923. /// use std::alloc::System;
  924. ///
  925. /// let x = Box::new_in(5, System);
  926. /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
  927. /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
  928. /// ```
  929. /// Manually create a `Box` from scratch by using the system allocator:
  930. /// ```
  931. /// #![feature(allocator_api, slice_ptr_get)]
  932. ///
  933. /// use std::alloc::{Allocator, Layout, System};
  934. ///
  935. /// unsafe {
  936. /// let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
  937. /// // In general .write is required to avoid attempting to destruct
  938. /// // the (uninitialized) previous contents of `ptr`, though for this
  939. /// // simple example `*ptr = 5` would have worked as well.
  940. /// ptr.write(5);
  941. /// let x = Box::from_raw_in(ptr, System);
  942. /// }
  943. /// # Ok::<(), std::alloc::AllocError>(())
  944. /// ```
  945. ///
  946. /// [memory layout]: self#memory-layout
  947. /// [`Layout`]: crate::Layout
  948. #[unstable(feature = "allocator_api", issue = "32838")]
  949. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  950. #[inline]
  951. pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
  952. Box(unsafe { Unique::new_unchecked(raw) }, alloc)
  953. }
  954. /// Consumes the `Box`, returning a wrapped raw pointer.
  955. ///
  956. /// The pointer will be properly aligned and non-null.
  957. ///
  958. /// After calling this function, the caller is responsible for the
  959. /// memory previously managed by the `Box`. In particular, the
  960. /// caller should properly destroy `T` and release the memory, taking
  961. /// into account the [memory layout] used by `Box`. The easiest way to
  962. /// do this is to convert the raw pointer back into a `Box` with the
  963. /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
  964. /// the cleanup.
  965. ///
  966. /// Note: this is an associated function, which means that you have
  967. /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
  968. /// is so that there is no conflict with a method on the inner type.
  969. ///
  970. /// # Examples
  971. /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
  972. /// for automatic cleanup:
  973. /// ```
  974. /// let x = Box::new(String::from("Hello"));
  975. /// let ptr = Box::into_raw(x);
  976. /// let x = unsafe { Box::from_raw(ptr) };
  977. /// ```
  978. /// Manual cleanup by explicitly running the destructor and deallocating
  979. /// the memory:
  980. /// ```
  981. /// use std::alloc::{dealloc, Layout};
  982. /// use std::ptr;
  983. ///
  984. /// let x = Box::new(String::from("Hello"));
  985. /// let p = Box::into_raw(x);
  986. /// unsafe {
  987. /// ptr::drop_in_place(p);
  988. /// dealloc(p as *mut u8, Layout::new::<String>());
  989. /// }
  990. /// ```
  991. ///
  992. /// [memory layout]: self#memory-layout
  993. #[stable(feature = "box_raw", since = "1.4.0")]
  994. #[inline]
  995. pub fn into_raw(b: Self) -> *mut T {
  996. Self::into_raw_with_allocator(b).0
  997. }
  998. /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
  999. ///
  1000. /// The pointer will be properly aligned and non-null.
  1001. ///
  1002. /// After calling this function, the caller is responsible for the
  1003. /// memory previously managed by the `Box`. In particular, the
  1004. /// caller should properly destroy `T` and release the memory, taking
  1005. /// into account the [memory layout] used by `Box`. The easiest way to
  1006. /// do this is to convert the raw pointer back into a `Box` with the
  1007. /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
  1008. /// the cleanup.
  1009. ///
  1010. /// Note: this is an associated function, which means that you have
  1011. /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
  1012. /// is so that there is no conflict with a method on the inner type.
  1013. ///
  1014. /// # Examples
  1015. /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
  1016. /// for automatic cleanup:
  1017. /// ```
  1018. /// #![feature(allocator_api)]
  1019. ///
  1020. /// use std::alloc::System;
  1021. ///
  1022. /// let x = Box::new_in(String::from("Hello"), System);
  1023. /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
  1024. /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
  1025. /// ```
  1026. /// Manual cleanup by explicitly running the destructor and deallocating
  1027. /// the memory:
  1028. /// ```
  1029. /// #![feature(allocator_api)]
  1030. ///
  1031. /// use std::alloc::{Allocator, Layout, System};
  1032. /// use std::ptr::{self, NonNull};
  1033. ///
  1034. /// let x = Box::new_in(String::from("Hello"), System);
  1035. /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
  1036. /// unsafe {
  1037. /// ptr::drop_in_place(ptr);
  1038. /// let non_null = NonNull::new_unchecked(ptr);
  1039. /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
  1040. /// }
  1041. /// ```
  1042. ///
  1043. /// [memory layout]: self#memory-layout
  1044. #[unstable(feature = "allocator_api", issue = "32838")]
  1045. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  1046. #[inline]
  1047. pub const fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
  1048. let (leaked, alloc) = Box::into_unique(b);
  1049. (leaked.as_ptr(), alloc)
  1050. }
  1051. #[unstable(
  1052. feature = "ptr_internals",
  1053. issue = "none",
  1054. reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
  1055. )]
  1056. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  1057. #[inline]
  1058. #[doc(hidden)]
  1059. pub const fn into_unique(b: Self) -> (Unique<T>, A) {
  1060. // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
  1061. // raw pointer for the type system. Turning it directly into a raw pointer would not be
  1062. // recognized as "releasing" the unique pointer to permit aliased raw accesses,
  1063. // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
  1064. // behaves correctly.
  1065. let alloc = unsafe { ptr::read(&b.1) };
  1066. (Unique::from(Box::leak(b)), alloc)
  1067. }
  1068. /// Returns a reference to the underlying allocator.
  1069. ///
  1070. /// Note: this is an associated function, which means that you have
  1071. /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
  1072. /// is so that there is no conflict with a method on the inner type.
  1073. #[unstable(feature = "allocator_api", issue = "32838")]
  1074. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  1075. #[inline]
  1076. pub const fn allocator(b: &Self) -> &A {
  1077. &b.1
  1078. }
  1079. /// Consumes and leaks the `Box`, returning a mutable reference,
  1080. /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
  1081. /// `'a`. If the type has only static references, or none at all, then this
  1082. /// may be chosen to be `'static`.
  1083. ///
  1084. /// This function is mainly useful for data that lives for the remainder of
  1085. /// the program's life. Dropping the returned reference will cause a memory
  1086. /// leak. If this is not acceptable, the reference should first be wrapped
  1087. /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
  1088. /// then be dropped which will properly destroy `T` and release the
  1089. /// allocated memory.
  1090. ///
  1091. /// Note: this is an associated function, which means that you have
  1092. /// to call it as `Box::leak(b)` instead of `b.leak()`. This
  1093. /// is so that there is no conflict with a method on the inner type.
  1094. ///
  1095. /// # Examples
  1096. ///
  1097. /// Simple usage:
  1098. ///
  1099. /// ```
  1100. /// let x = Box::new(41);
  1101. /// let static_ref: &'static mut usize = Box::leak(x);
  1102. /// *static_ref += 1;
  1103. /// assert_eq!(*static_ref, 42);
  1104. /// ```
  1105. ///
  1106. /// Unsized data:
  1107. ///
  1108. /// ```
  1109. /// let x = vec![1, 2, 3].into_boxed_slice();
  1110. /// let static_ref = Box::leak(x);
  1111. /// static_ref[0] = 4;
  1112. /// assert_eq!(*static_ref, [4, 2, 3]);
  1113. /// ```
  1114. #[stable(feature = "box_leak", since = "1.26.0")]
  1115. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  1116. #[inline]
  1117. pub const fn leak<'a>(b: Self) -> &'a mut T
  1118. where
  1119. A: 'a,
  1120. {
  1121. unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
  1122. }
  1123. /// Converts a `Box<T>` into a `Pin<Box<T>>`
  1124. ///
  1125. /// This conversion does not allocate on the heap and happens in place.
  1126. ///
  1127. /// This is also available via [`From`].
  1128. #[unstable(feature = "box_into_pin", issue = "62370")]
  1129. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  1130. pub const fn into_pin(boxed: Self) -> Pin<Self>
  1131. where
  1132. A: 'static,
  1133. {
  1134. // It's not possible to move or replace the insides of a `Pin<Box<T>>`
  1135. // when `T: !Unpin`, so it's safe to pin it directly without any
  1136. // additional requirements.
  1137. unsafe { Pin::new_unchecked(boxed) }
  1138. }
  1139. }
  1140. #[stable(feature = "rust1", since = "1.0.0")]
  1141. unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
  1142. fn drop(&mut self) {
  1143. // FIXME: Do nothing, drop is currently performed by compiler.
  1144. }
  1145. }
  1146. #[cfg(not(no_global_oom_handling))]
  1147. #[stable(feature = "rust1", since = "1.0.0")]
  1148. impl<T: Default> Default for Box<T> {
  1149. /// Creates a `Box<T>`, with the `Default` value for T.
  1150. fn default() -> Self {
  1151. box T::default()
  1152. }
  1153. }
  1154. #[cfg(not(no_global_oom_handling))]
  1155. #[stable(feature = "rust1", since = "1.0.0")]
  1156. #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
  1157. impl<T> const Default for Box<[T]> {
  1158. fn default() -> Self {
  1159. let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
  1160. Box(ptr, Global)
  1161. }
  1162. }
  1163. #[cfg(not(no_global_oom_handling))]
  1164. #[stable(feature = "default_box_extra", since = "1.17.0")]
  1165. #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
  1166. impl const Default for Box<str> {
  1167. fn default() -> Self {
  1168. // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
  1169. let ptr: Unique<str> = unsafe {
  1170. let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
  1171. Unique::new_unchecked(bytes.as_ptr() as *mut str)
  1172. };
  1173. Box(ptr, Global)
  1174. }
  1175. }
  1176. #[cfg(not(no_global_oom_handling))]
  1177. #[stable(feature = "rust1", since = "1.0.0")]
  1178. impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
  1179. /// Returns a new box with a `clone()` of this box's contents.
  1180. ///
  1181. /// # Examples
  1182. ///
  1183. /// ```
  1184. /// let x = Box::new(5);
  1185. /// let y = x.clone();
  1186. ///
  1187. /// // The value is the same
  1188. /// assert_eq!(x, y);
  1189. ///
  1190. /// // But they are unique objects
  1191. /// assert_ne!(&*x as *const i32, &*y as *const i32);
  1192. /// ```
  1193. #[inline]
  1194. fn clone(&self) -> Self {
  1195. // Pre-allocate memory to allow writing the cloned value directly.
  1196. let mut boxed = Self::new_uninit_in(self.1.clone());
  1197. unsafe {
  1198. (**self).write_clone_into_raw(boxed.as_mut_ptr());
  1199. boxed.assume_init()
  1200. }
  1201. }
  1202. /// Copies `source`'s contents into `self` without creating a new allocation.
  1203. ///
  1204. /// # Examples
  1205. ///
  1206. /// ```
  1207. /// let x = Box::new(5);
  1208. /// let mut y = Box::new(10);
  1209. /// let yp: *const i32 = &*y;
  1210. ///
  1211. /// y.clone_from(&x);
  1212. ///
  1213. /// // The value is the same
  1214. /// assert_eq!(x, y);
  1215. ///
  1216. /// // And no allocation occurred
  1217. /// assert_eq!(yp, &*y);
  1218. /// ```
  1219. #[inline]
  1220. fn clone_from(&mut self, source: &Self) {
  1221. (**self).clone_from(&(**source));
  1222. }
  1223. }
  1224. #[cfg(not(no_global_oom_handling))]
  1225. #[stable(feature = "box_slice_clone", since = "1.3.0")]
  1226. impl Clone for Box<str> {
  1227. fn clone(&self) -> Self {
  1228. // this makes a copy of the data
  1229. let buf: Box<[u8]> = self.as_bytes().into();
  1230. unsafe { from_boxed_utf8_unchecked(buf) }
  1231. }
  1232. }
  1233. #[stable(feature = "rust1", since = "1.0.0")]
  1234. impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
  1235. #[inline]
  1236. fn eq(&self, other: &Self) -> bool {
  1237. PartialEq::eq(&**self, &**other)
  1238. }
  1239. #[inline]
  1240. fn ne(&self, other: &Self) -> bool {
  1241. PartialEq::ne(&**self, &**other)
  1242. }
  1243. }
  1244. #[stable(feature = "rust1", since = "1.0.0")]
  1245. impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
  1246. #[inline]
  1247. fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
  1248. PartialOrd::partial_cmp(&**self, &**other)
  1249. }
  1250. #[inline]
  1251. fn lt(&self, other: &Self) -> bool {
  1252. PartialOrd::lt(&**self, &**other)
  1253. }
  1254. #[inline]
  1255. fn le(&self, other: &Self) -> bool {
  1256. PartialOrd::le(&**self, &**other)
  1257. }
  1258. #[inline]
  1259. fn ge(&self, other: &Self) -> bool {
  1260. PartialOrd::ge(&**self, &**other)
  1261. }
  1262. #[inline]
  1263. fn gt(&self, other: &Self) -> bool {
  1264. PartialOrd::gt(&**self, &**other)
  1265. }
  1266. }
  1267. #[stable(feature = "rust1", since = "1.0.0")]
  1268. impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
  1269. #[inline]
  1270. fn cmp(&self, other: &Self) -> Ordering {
  1271. Ord::cmp(&**self, &**other)
  1272. }
  1273. }
  1274. #[stable(feature = "rust1", since = "1.0.0")]
  1275. impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
  1276. #[stable(feature = "rust1", since = "1.0.0")]
  1277. impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
  1278. fn hash<H: Hasher>(&self, state: &mut H) {
  1279. (**self).hash(state);
  1280. }
  1281. }
  1282. #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
  1283. impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
  1284. fn finish(&self) -> u64 {
  1285. (**self).finish()
  1286. }
  1287. fn write(&mut self, bytes: &[u8]) {
  1288. (**self).write(bytes)
  1289. }
  1290. fn write_u8(&mut self, i: u8) {
  1291. (**self).write_u8(i)
  1292. }
  1293. fn write_u16(&mut self, i: u16) {
  1294. (**self).write_u16(i)
  1295. }
  1296. fn write_u32(&mut self, i: u32) {
  1297. (**self).write_u32(i)
  1298. }
  1299. fn write_u64(&mut self, i: u64) {
  1300. (**self).write_u64(i)
  1301. }
  1302. fn write_u128(&mut self, i: u128) {
  1303. (**self).write_u128(i)
  1304. }
  1305. fn write_usize(&mut self, i: usize) {
  1306. (**self).write_usize(i)
  1307. }
  1308. fn write_i8(&mut self, i: i8) {
  1309. (**self).write_i8(i)
  1310. }
  1311. fn write_i16(&mut self, i: i16) {
  1312. (**self).write_i16(i)
  1313. }
  1314. fn write_i32(&mut self, i: i32) {
  1315. (**self).write_i32(i)
  1316. }
  1317. fn write_i64(&mut self, i: i64) {
  1318. (**self).write_i64(i)
  1319. }
  1320. fn write_i128(&mut self, i: i128) {
  1321. (**self).write_i128(i)
  1322. }
  1323. fn write_isize(&mut self, i: isize) {
  1324. (**self).write_isize(i)
  1325. }
  1326. fn write_length_prefix(&mut self, len: usize) {
  1327. (**self).write_length_prefix(len)
  1328. }
  1329. fn write_str(&mut self, s: &str) {
  1330. (**self).write_str(s)
  1331. }
  1332. }
  1333. #[cfg(not(no_global_oom_handling))]
  1334. #[stable(feature = "from_for_ptrs", since = "1.6.0")]
  1335. impl<T> From<T> for Box<T> {
  1336. /// Converts a `T` into a `Box<T>`
  1337. ///
  1338. /// The conversion allocates on the heap and moves `t`
  1339. /// from the stack into it.
  1340. ///
  1341. /// # Examples
  1342. ///
  1343. /// ```rust
  1344. /// let x = 5;
  1345. /// let boxed = Box::new(5);
  1346. ///
  1347. /// assert_eq!(Box::from(x), boxed);
  1348. /// ```
  1349. fn from(t: T) -> Self {
  1350. Box::new(t)
  1351. }
  1352. }
  1353. #[stable(feature = "pin", since = "1.33.0")]
  1354. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  1355. impl<T: ?Sized, A: Allocator> const From<Box<T, A>> for Pin<Box<T, A>>
  1356. where
  1357. A: 'static,
  1358. {
  1359. /// Converts a `Box<T>` into a `Pin<Box<T>>`
  1360. ///
  1361. /// This conversion does not allocate on the heap and happens in place.
  1362. fn from(boxed: Box<T, A>) -> Self {
  1363. Box::into_pin(boxed)
  1364. }
  1365. }
  1366. #[cfg(not(no_global_oom_handling))]
  1367. #[stable(feature = "box_from_slice", since = "1.17.0")]
  1368. impl<T: Copy> From<&[T]> for Box<[T]> {
  1369. /// Converts a `&[T]` into a `Box<[T]>`
  1370. ///
  1371. /// This conversion allocates on the heap
  1372. /// and performs a copy of `slice`.
  1373. ///
  1374. /// # Examples
  1375. /// ```rust
  1376. /// // create a &[u8] which will be used to create a Box<[u8]>
  1377. /// let slice: &[u8] = &[104, 101, 108, 108, 111];
  1378. /// let boxed_slice: Box<[u8]> = Box::from(slice);
  1379. ///
  1380. /// println!("{boxed_slice:?}");
  1381. /// ```
  1382. fn from(slice: &[T]) -> Box<[T]> {
  1383. let len = slice.len();
  1384. let buf = RawVec::with_capacity(len);
  1385. unsafe {
  1386. ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
  1387. buf.into_box(slice.len()).assume_init()
  1388. }
  1389. }
  1390. }
  1391. #[cfg(not(no_global_oom_handling))]
  1392. #[stable(feature = "box_from_cow", since = "1.45.0")]
  1393. impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
  1394. /// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
  1395. ///
  1396. /// When `cow` is the `Cow::Borrowed` variant, this
  1397. /// conversion allocates on the heap and copies the
  1398. /// underlying slice. Otherwise, it will try to reuse the owned
  1399. /// `Vec`'s allocation.
  1400. #[inline]
  1401. fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
  1402. match cow {
  1403. Cow::Borrowed(slice) => Box::from(slice),
  1404. Cow::Owned(slice) => Box::from(slice),
  1405. }
  1406. }
  1407. }
  1408. #[cfg(not(no_global_oom_handling))]
  1409. #[stable(feature = "box_from_slice", since = "1.17.0")]
  1410. impl From<&str> for Box<str> {
  1411. /// Converts a `&str` into a `Box<str>`
  1412. ///
  1413. /// This conversion allocates on the heap
  1414. /// and performs a copy of `s`.
  1415. ///
  1416. /// # Examples
  1417. ///
  1418. /// ```rust
  1419. /// let boxed: Box<str> = Box::from("hello");
  1420. /// println!("{boxed}");
  1421. /// ```
  1422. #[inline]
  1423. fn from(s: &str) -> Box<str> {
  1424. unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
  1425. }
  1426. }
  1427. #[cfg(not(no_global_oom_handling))]
  1428. #[stable(feature = "box_from_cow", since = "1.45.0")]
  1429. impl From<Cow<'_, str>> for Box<str> {
  1430. /// Converts a `Cow<'_, str>` into a `Box<str>`
  1431. ///
  1432. /// When `cow` is the `Cow::Borrowed` variant, this
  1433. /// conversion allocates on the heap and copies the
  1434. /// underlying `str`. Otherwise, it will try to reuse the owned
  1435. /// `String`'s allocation.
  1436. ///
  1437. /// # Examples
  1438. ///
  1439. /// ```rust
  1440. /// use std::borrow::Cow;
  1441. ///
  1442. /// let unboxed = Cow::Borrowed("hello");
  1443. /// let boxed: Box<str> = Box::from(unboxed);
  1444. /// println!("{boxed}");
  1445. /// ```
  1446. ///
  1447. /// ```rust
  1448. /// # use std::borrow::Cow;
  1449. /// let unboxed = Cow::Owned("hello".to_string());
  1450. /// let boxed: Box<str> = Box::from(unboxed);
  1451. /// println!("{boxed}");
  1452. /// ```
  1453. #[inline]
  1454. fn from(cow: Cow<'_, str>) -> Box<str> {
  1455. match cow {
  1456. Cow::Borrowed(s) => Box::from(s),
  1457. Cow::Owned(s) => Box::from(s),
  1458. }
  1459. }
  1460. }
  1461. #[stable(feature = "boxed_str_conv", since = "1.19.0")]
  1462. impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
  1463. /// Converts a `Box<str>` into a `Box<[u8]>`
  1464. ///
  1465. /// This conversion does not allocate on the heap and happens in place.
  1466. ///
  1467. /// # Examples
  1468. /// ```rust
  1469. /// // create a Box<str> which will be used to create a Box<[u8]>
  1470. /// let boxed: Box<str> = Box::from("hello");
  1471. /// let boxed_str: Box<[u8]> = Box::from(boxed);
  1472. ///
  1473. /// // create a &[u8] which will be used to create a Box<[u8]>
  1474. /// let slice: &[u8] = &[104, 101, 108, 108, 111];
  1475. /// let boxed_slice = Box::from(slice);
  1476. ///
  1477. /// assert_eq!(boxed_slice, boxed_str);
  1478. /// ```
  1479. #[inline]
  1480. fn from(s: Box<str, A>) -> Self {
  1481. let (raw, alloc) = Box::into_raw_with_allocator(s);
  1482. unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
  1483. }
  1484. }
  1485. #[cfg(not(no_global_oom_handling))]
  1486. #[stable(feature = "box_from_array", since = "1.45.0")]
  1487. impl<T, const N: usize> From<[T; N]> for Box<[T]> {
  1488. /// Converts a `[T; N]` into a `Box<[T]>`
  1489. ///
  1490. /// This conversion moves the array to newly heap-allocated memory.
  1491. ///
  1492. /// # Examples
  1493. ///
  1494. /// ```rust
  1495. /// let boxed: Box<[u8]> = Box::from([4, 2]);
  1496. /// println!("{boxed:?}");
  1497. /// ```
  1498. fn from(array: [T; N]) -> Box<[T]> {
  1499. box array
  1500. }
  1501. }
  1502. #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
  1503. impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
  1504. type Error = Box<[T]>;
  1505. /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
  1506. ///
  1507. /// The conversion occurs in-place and does not require a
  1508. /// new memory allocation.
  1509. ///
  1510. /// # Errors
  1511. ///
  1512. /// Returns the old `Box<[T]>` in the `Err` variant if
  1513. /// `boxed_slice.len()` does not equal `N`.
  1514. fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
  1515. if boxed_slice.len() == N {
  1516. Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
  1517. } else {
  1518. Err(boxed_slice)
  1519. }
  1520. }
  1521. }
  1522. impl<A: Allocator> Box<dyn Any, A> {
  1523. /// Attempt to downcast the box to a concrete type.
  1524. ///
  1525. /// # Examples
  1526. ///
  1527. /// ```
  1528. /// use std::any::Any;
  1529. ///
  1530. /// fn print_if_string(value: Box<dyn Any>) {
  1531. /// if let Ok(string) = value.downcast::<String>() {
  1532. /// println!("String ({}): {}", string.len(), string);
  1533. /// }
  1534. /// }
  1535. ///
  1536. /// let my_string = "Hello World".to_string();
  1537. /// print_if_string(Box::new(my_string));
  1538. /// print_if_string(Box::new(0i8));
  1539. /// ```
  1540. #[inline]
  1541. #[stable(feature = "rust1", since = "1.0.0")]
  1542. pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
  1543. if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
  1544. }
  1545. /// Downcasts the box to a concrete type.
  1546. ///
  1547. /// For a safe alternative see [`downcast`].
  1548. ///
  1549. /// # Examples
  1550. ///
  1551. /// ```
  1552. /// #![feature(downcast_unchecked)]
  1553. ///
  1554. /// use std::any::Any;
  1555. ///
  1556. /// let x: Box<dyn Any> = Box::new(1_usize);
  1557. ///
  1558. /// unsafe {
  1559. /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
  1560. /// }
  1561. /// ```
  1562. ///
  1563. /// # Safety
  1564. ///
  1565. /// The contained value must be of type `T`. Calling this method
  1566. /// with the incorrect type is *undefined behavior*.
  1567. ///
  1568. /// [`downcast`]: Self::downcast
  1569. #[inline]
  1570. #[unstable(feature = "downcast_unchecked", issue = "90850")]
  1571. pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
  1572. debug_assert!(self.is::<T>());
  1573. unsafe {
  1574. let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
  1575. Box::from_raw_in(raw as *mut T, alloc)
  1576. }
  1577. }
  1578. }
  1579. impl<A: Allocator> Box<dyn Any + Send, A> {
  1580. /// Attempt to downcast the box to a concrete type.
  1581. ///
  1582. /// # Examples
  1583. ///
  1584. /// ```
  1585. /// use std::any::Any;
  1586. ///
  1587. /// fn print_if_string(value: Box<dyn Any + Send>) {
  1588. /// if let Ok(string) = value.downcast::<String>() {
  1589. /// println!("String ({}): {}", string.len(), string);
  1590. /// }
  1591. /// }
  1592. ///
  1593. /// let my_string = "Hello World".to_string();
  1594. /// print_if_string(Box::new(my_string));
  1595. /// print_if_string(Box::new(0i8));
  1596. /// ```
  1597. #[inline]
  1598. #[stable(feature = "rust1", since = "1.0.0")]
  1599. pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
  1600. if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
  1601. }
  1602. /// Downcasts the box to a concrete type.
  1603. ///
  1604. /// For a safe alternative see [`downcast`].
  1605. ///
  1606. /// # Examples
  1607. ///
  1608. /// ```
  1609. /// #![feature(downcast_unchecked)]
  1610. ///
  1611. /// use std::any::Any;
  1612. ///
  1613. /// let x: Box<dyn Any + Send> = Box::new(1_usize);
  1614. ///
  1615. /// unsafe {
  1616. /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
  1617. /// }
  1618. /// ```
  1619. ///
  1620. /// # Safety
  1621. ///
  1622. /// The contained value must be of type `T`. Calling this method
  1623. /// with the incorrect type is *undefined behavior*.
  1624. ///
  1625. /// [`downcast`]: Self::downcast
  1626. #[inline]
  1627. #[unstable(feature = "downcast_unchecked", issue = "90850")]
  1628. pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
  1629. debug_assert!(self.is::<T>());
  1630. unsafe {
  1631. let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
  1632. Box::from_raw_in(raw as *mut T, alloc)
  1633. }
  1634. }
  1635. }
  1636. impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
  1637. /// Attempt to downcast the box to a concrete type.
  1638. ///
  1639. /// # Examples
  1640. ///
  1641. /// ```
  1642. /// use std::any::Any;
  1643. ///
  1644. /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
  1645. /// if let Ok(string) = value.downcast::<String>() {
  1646. /// println!("String ({}): {}", string.len(), string);
  1647. /// }
  1648. /// }
  1649. ///
  1650. /// let my_string = "Hello World".to_string();
  1651. /// print_if_string(Box::new(my_string));
  1652. /// print_if_string(Box::new(0i8));
  1653. /// ```
  1654. #[inline]
  1655. #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
  1656. pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
  1657. if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
  1658. }
  1659. /// Downcasts the box to a concrete type.
  1660. ///
  1661. /// For a safe alternative see [`downcast`].
  1662. ///
  1663. /// # Examples
  1664. ///
  1665. /// ```
  1666. /// #![feature(downcast_unchecked)]
  1667. ///
  1668. /// use std::any::Any;
  1669. ///
  1670. /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
  1671. ///
  1672. /// unsafe {
  1673. /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
  1674. /// }
  1675. /// ```
  1676. ///
  1677. /// # Safety
  1678. ///
  1679. /// The contained value must be of type `T`. Calling this method
  1680. /// with the incorrect type is *undefined behavior*.
  1681. ///
  1682. /// [`downcast`]: Self::downcast
  1683. #[inline]
  1684. #[unstable(feature = "downcast_unchecked", issue = "90850")]
  1685. pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
  1686. debug_assert!(self.is::<T>());
  1687. unsafe {
  1688. let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
  1689. Box::into_raw_with_allocator(self);
  1690. Box::from_raw_in(raw as *mut T, alloc)
  1691. }
  1692. }
  1693. }
  1694. #[stable(feature = "rust1", since = "1.0.0")]
  1695. impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
  1696. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  1697. fmt::Display::fmt(&**self, f)
  1698. }
  1699. }
  1700. #[stable(feature = "rust1", since = "1.0.0")]
  1701. impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
  1702. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  1703. fmt::Debug::fmt(&**self, f)
  1704. }
  1705. }
  1706. #[stable(feature = "rust1", since = "1.0.0")]
  1707. impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
  1708. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  1709. // It's not possible to extract the inner Uniq directly from the Box,
  1710. // instead we cast it to a *const which aliases the Unique
  1711. let ptr: *const T = &**self;
  1712. fmt::Pointer::fmt(&ptr, f)
  1713. }
  1714. }
  1715. #[stable(feature = "rust1", since = "1.0.0")]
  1716. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  1717. impl<T: ?Sized, A: Allocator> const Deref for Box<T, A> {
  1718. type Target = T;
  1719. fn deref(&self) -> &T {
  1720. &**self
  1721. }
  1722. }
  1723. #[stable(feature = "rust1", since = "1.0.0")]
  1724. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  1725. impl<T: ?Sized, A: Allocator> const DerefMut for Box<T, A> {
  1726. fn deref_mut(&mut self) -> &mut T {
  1727. &mut **self
  1728. }
  1729. }
  1730. #[unstable(feature = "receiver_trait", issue = "none")]
  1731. impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
  1732. #[stable(feature = "rust1", since = "1.0.0")]
  1733. impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
  1734. type Item = I::Item;
  1735. fn next(&mut self) -> Option<I::Item> {
  1736. (**self).next()
  1737. }
  1738. fn size_hint(&self) -> (usize, Option<usize>) {
  1739. (**self).size_hint()
  1740. }
  1741. fn nth(&mut self, n: usize) -> Option<I::Item> {
  1742. (**self).nth(n)
  1743. }
  1744. fn last(self) -> Option<I::Item> {
  1745. BoxIter::last(self)
  1746. }
  1747. }
  1748. trait BoxIter {
  1749. type Item;
  1750. fn last(self) -> Option<Self::Item>;
  1751. }
  1752. impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
  1753. type Item = I::Item;
  1754. default fn last(self) -> Option<I::Item> {
  1755. #[inline]
  1756. fn some<T>(_: Option<T>, x: T) -> Option<T> {
  1757. Some(x)
  1758. }
  1759. self.fold(None, some)
  1760. }
  1761. }
  1762. /// Specialization for sized `I`s that uses `I`s implementation of `last()`
  1763. /// instead of the default.
  1764. #[stable(feature = "rust1", since = "1.0.0")]
  1765. impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
  1766. fn last(self) -> Option<I::Item> {
  1767. (*self).last()
  1768. }
  1769. }
  1770. #[stable(feature = "rust1", since = "1.0.0")]
  1771. impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
  1772. fn next_back(&mut self) -> Option<I::Item> {
  1773. (**self).next_back()
  1774. }
  1775. fn nth_back(&mut self, n: usize) -> Option<I::Item> {
  1776. (**self).nth_back(n)
  1777. }
  1778. }
  1779. #[stable(feature = "rust1", since = "1.0.0")]
  1780. impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
  1781. fn len(&self) -> usize {
  1782. (**self).len()
  1783. }
  1784. fn is_empty(&self) -> bool {
  1785. (**self).is_empty()
  1786. }
  1787. }
  1788. #[stable(feature = "fused", since = "1.26.0")]
  1789. impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
  1790. #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
  1791. impl<Args, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
  1792. type Output = <F as FnOnce<Args>>::Output;
  1793. extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
  1794. <F as FnOnce<Args>>::call_once(*self, args)
  1795. }
  1796. }
  1797. #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
  1798. impl<Args, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
  1799. extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
  1800. <F as FnMut<Args>>::call_mut(self, args)
  1801. }
  1802. }
  1803. #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
  1804. impl<Args, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
  1805. extern "rust-call" fn call(&self, args: Args) -> Self::Output {
  1806. <F as Fn<Args>>::call(self, args)
  1807. }
  1808. }
  1809. #[unstable(feature = "coerce_unsized", issue = "27732")]
  1810. impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
  1811. #[unstable(feature = "dispatch_from_dyn", issue = "none")]
  1812. impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
  1813. #[cfg(not(no_global_oom_handling))]
  1814. #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
  1815. impl<I> FromIterator<I> for Box<[I]> {
  1816. fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
  1817. iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
  1818. }
  1819. }
  1820. #[cfg(not(no_global_oom_handling))]
  1821. #[stable(feature = "box_slice_clone", since = "1.3.0")]
  1822. impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
  1823. fn clone(&self) -> Self {
  1824. let alloc = Box::allocator(self).clone();
  1825. self.to_vec_in(alloc).into_boxed_slice()
  1826. }
  1827. fn clone_from(&mut self, other: &Self) {
  1828. if self.len() == other.len() {
  1829. self.clone_from_slice(&other);
  1830. } else {
  1831. *self = other.clone();
  1832. }
  1833. }
  1834. }
  1835. #[stable(feature = "box_borrow", since = "1.1.0")]
  1836. impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
  1837. fn borrow(&self) -> &T {
  1838. &**self
  1839. }
  1840. }
  1841. #[stable(feature = "box_borrow", since = "1.1.0")]
  1842. impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
  1843. fn borrow_mut(&mut self) -> &mut T {
  1844. &mut **self
  1845. }
  1846. }
  1847. #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
  1848. impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
  1849. fn as_ref(&self) -> &T {
  1850. &**self
  1851. }
  1852. }
  1853. #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
  1854. impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
  1855. fn as_mut(&mut self) -> &mut T {
  1856. &mut **self
  1857. }
  1858. }
  1859. /* Nota bene
  1860. *
  1861. * We could have chosen not to add this impl, and instead have written a
  1862. * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
  1863. * because Box<T> implements Unpin even when T does not, as a result of
  1864. * this impl.
  1865. *
  1866. * We chose this API instead of the alternative for a few reasons:
  1867. * - Logically, it is helpful to understand pinning in regard to the
  1868. * memory region being pointed to. For this reason none of the
  1869. * standard library pointer types support projecting through a pin
  1870. * (Box<T> is the only pointer type in std for which this would be
  1871. * safe.)
  1872. * - It is in practice very useful to have Box<T> be unconditionally
  1873. * Unpin because of trait objects, for which the structural auto
  1874. * trait functionality does not apply (e.g., Box<dyn Foo> would
  1875. * otherwise not be Unpin).
  1876. *
  1877. * Another type with the same semantics as Box but only a conditional
  1878. * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
  1879. * could have a method to project a Pin<T> from it.
  1880. */
  1881. #[stable(feature = "pin", since = "1.33.0")]
  1882. #[rustc_const_unstable(feature = "const_box", issue = "92521")]
  1883. impl<T: ?Sized, A: Allocator> const Unpin for Box<T, A> where A: 'static {}
  1884. #[unstable(feature = "generator_trait", issue = "43122")]
  1885. impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
  1886. where
  1887. A: 'static,
  1888. {
  1889. type Yield = G::Yield;
  1890. type Return = G::Return;
  1891. fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
  1892. G::resume(Pin::new(&mut *self), arg)
  1893. }
  1894. }
  1895. #[unstable(feature = "generator_trait", issue = "43122")]
  1896. impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
  1897. where
  1898. A: 'static,
  1899. {
  1900. type Yield = G::Yield;
  1901. type Return = G::Return;
  1902. fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
  1903. G::resume((*self).as_mut(), arg)
  1904. }
  1905. }
  1906. #[stable(feature = "futures_api", since = "1.36.0")]
  1907. impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
  1908. where
  1909. A: 'static,
  1910. {
  1911. type Output = F::Output;
  1912. fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
  1913. F::poll(Pin::new(&mut *self), cx)
  1914. }
  1915. }
  1916. #[unstable(feature = "async_iterator", issue = "79024")]
  1917. impl<S: ?Sized + AsyncIterator + Unpin> AsyncIterator for Box<S> {
  1918. type Item = S::Item;
  1919. fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
  1920. Pin::new(&mut **self).poll_next(cx)
  1921. }
  1922. fn size_hint(&self) -> (usize, Option<usize>) {
  1923. (**self).size_hint()
  1924. }
  1925. }