mod.rs 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140
  1. // SPDX-License-Identifier: Apache-2.0 OR MIT
  2. //! A contiguous growable array type with heap-allocated contents, written
  3. //! `Vec<T>`.
  4. //!
  5. //! Vectors have *O*(1) indexing, amortized *O*(1) push (to the end) and
  6. //! *O*(1) pop (from the end).
  7. //!
  8. //! Vectors ensure they never allocate more than `isize::MAX` bytes.
  9. //!
  10. //! # Examples
  11. //!
  12. //! You can explicitly create a [`Vec`] with [`Vec::new`]:
  13. //!
  14. //! ```
  15. //! let v: Vec<i32> = Vec::new();
  16. //! ```
  17. //!
  18. //! ...or by using the [`vec!`] macro:
  19. //!
  20. //! ```
  21. //! let v: Vec<i32> = vec![];
  22. //!
  23. //! let v = vec![1, 2, 3, 4, 5];
  24. //!
  25. //! let v = vec![0; 10]; // ten zeroes
  26. //! ```
  27. //!
  28. //! You can [`push`] values onto the end of a vector (which will grow the vector
  29. //! as needed):
  30. //!
  31. //! ```
  32. //! let mut v = vec![1, 2];
  33. //!
  34. //! v.push(3);
  35. //! ```
  36. //!
  37. //! Popping values works in much the same way:
  38. //!
  39. //! ```
  40. //! let mut v = vec![1, 2];
  41. //!
  42. //! let two = v.pop();
  43. //! ```
  44. //!
  45. //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
  46. //!
  47. //! ```
  48. //! let mut v = vec![1, 2, 3];
  49. //! let three = v[2];
  50. //! v[1] = v[1] + 5;
  51. //! ```
  52. //!
  53. //! [`push`]: Vec::push
  54. #![stable(feature = "rust1", since = "1.0.0")]
  55. #[cfg(not(no_global_oom_handling))]
  56. use core::cmp;
  57. use core::cmp::Ordering;
  58. use core::convert::TryFrom;
  59. use core::fmt;
  60. use core::hash::{Hash, Hasher};
  61. use core::intrinsics::{arith_offset, assume};
  62. use core::iter;
  63. #[cfg(not(no_global_oom_handling))]
  64. use core::iter::FromIterator;
  65. use core::marker::PhantomData;
  66. use core::mem::{self, ManuallyDrop, MaybeUninit};
  67. use core::ops::{self, Index, IndexMut, Range, RangeBounds};
  68. use core::ptr::{self, NonNull};
  69. use core::slice::{self, SliceIndex};
  70. use crate::alloc::{Allocator, Global};
  71. use crate::borrow::{Cow, ToOwned};
  72. use crate::boxed::Box;
  73. use crate::collections::TryReserveError;
  74. use crate::raw_vec::RawVec;
  75. #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
  76. pub use self::drain_filter::DrainFilter;
  77. mod drain_filter;
  78. #[cfg(not(no_global_oom_handling))]
  79. #[stable(feature = "vec_splice", since = "1.21.0")]
  80. pub use self::splice::Splice;
  81. #[cfg(not(no_global_oom_handling))]
  82. mod splice;
  83. #[stable(feature = "drain", since = "1.6.0")]
  84. pub use self::drain::Drain;
  85. mod drain;
  86. #[cfg(not(no_global_oom_handling))]
  87. mod cow;
  88. #[cfg(not(no_global_oom_handling))]
  89. pub(crate) use self::in_place_collect::AsVecIntoIter;
  90. #[stable(feature = "rust1", since = "1.0.0")]
  91. pub use self::into_iter::IntoIter;
  92. mod into_iter;
  93. #[cfg(not(no_global_oom_handling))]
  94. use self::is_zero::IsZero;
  95. mod is_zero;
  96. #[cfg(not(no_global_oom_handling))]
  97. mod in_place_collect;
  98. mod partial_eq;
  99. #[cfg(not(no_global_oom_handling))]
  100. use self::spec_from_elem::SpecFromElem;
  101. #[cfg(not(no_global_oom_handling))]
  102. mod spec_from_elem;
  103. #[cfg(not(no_global_oom_handling))]
  104. use self::set_len_on_drop::SetLenOnDrop;
  105. #[cfg(not(no_global_oom_handling))]
  106. mod set_len_on_drop;
  107. #[cfg(not(no_global_oom_handling))]
  108. use self::in_place_drop::InPlaceDrop;
  109. #[cfg(not(no_global_oom_handling))]
  110. mod in_place_drop;
  111. #[cfg(not(no_global_oom_handling))]
  112. use self::spec_from_iter_nested::SpecFromIterNested;
  113. #[cfg(not(no_global_oom_handling))]
  114. mod spec_from_iter_nested;
  115. #[cfg(not(no_global_oom_handling))]
  116. use self::spec_from_iter::SpecFromIter;
  117. #[cfg(not(no_global_oom_handling))]
  118. mod spec_from_iter;
  119. #[cfg(not(no_global_oom_handling))]
  120. use self::spec_extend::SpecExtend;
  121. #[cfg(not(no_global_oom_handling))]
  122. mod spec_extend;
  123. /// A contiguous growable array type, written as `Vec<T>`, short for 'vector'.
  124. ///
  125. /// # Examples
  126. ///
  127. /// ```
  128. /// let mut vec = Vec::new();
  129. /// vec.push(1);
  130. /// vec.push(2);
  131. ///
  132. /// assert_eq!(vec.len(), 2);
  133. /// assert_eq!(vec[0], 1);
  134. ///
  135. /// assert_eq!(vec.pop(), Some(2));
  136. /// assert_eq!(vec.len(), 1);
  137. ///
  138. /// vec[0] = 7;
  139. /// assert_eq!(vec[0], 7);
  140. ///
  141. /// vec.extend([1, 2, 3].iter().copied());
  142. ///
  143. /// for x in &vec {
  144. /// println!("{x}");
  145. /// }
  146. /// assert_eq!(vec, [7, 1, 2, 3]);
  147. /// ```
  148. ///
  149. /// The [`vec!`] macro is provided for convenient initialization:
  150. ///
  151. /// ```
  152. /// let mut vec1 = vec![1, 2, 3];
  153. /// vec1.push(4);
  154. /// let vec2 = Vec::from([1, 2, 3, 4]);
  155. /// assert_eq!(vec1, vec2);
  156. /// ```
  157. ///
  158. /// It can also initialize each element of a `Vec<T>` with a given value.
  159. /// This may be more efficient than performing allocation and initialization
  160. /// in separate steps, especially when initializing a vector of zeros:
  161. ///
  162. /// ```
  163. /// let vec = vec![0; 5];
  164. /// assert_eq!(vec, [0, 0, 0, 0, 0]);
  165. ///
  166. /// // The following is equivalent, but potentially slower:
  167. /// let mut vec = Vec::with_capacity(5);
  168. /// vec.resize(5, 0);
  169. /// assert_eq!(vec, [0, 0, 0, 0, 0]);
  170. /// ```
  171. ///
  172. /// For more information, see
  173. /// [Capacity and Reallocation](#capacity-and-reallocation).
  174. ///
  175. /// Use a `Vec<T>` as an efficient stack:
  176. ///
  177. /// ```
  178. /// let mut stack = Vec::new();
  179. ///
  180. /// stack.push(1);
  181. /// stack.push(2);
  182. /// stack.push(3);
  183. ///
  184. /// while let Some(top) = stack.pop() {
  185. /// // Prints 3, 2, 1
  186. /// println!("{top}");
  187. /// }
  188. /// ```
  189. ///
  190. /// # Indexing
  191. ///
  192. /// The `Vec` type allows to access values by index, because it implements the
  193. /// [`Index`] trait. An example will be more explicit:
  194. ///
  195. /// ```
  196. /// let v = vec![0, 2, 4, 6];
  197. /// println!("{}", v[1]); // it will display '2'
  198. /// ```
  199. ///
  200. /// However be careful: if you try to access an index which isn't in the `Vec`,
  201. /// your software will panic! You cannot do this:
  202. ///
  203. /// ```should_panic
  204. /// let v = vec![0, 2, 4, 6];
  205. /// println!("{}", v[6]); // it will panic!
  206. /// ```
  207. ///
  208. /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
  209. /// the `Vec`.
  210. ///
  211. /// # Slicing
  212. ///
  213. /// A `Vec` can be mutable. On the other hand, slices are read-only objects.
  214. /// To get a [slice][prim@slice], use [`&`]. Example:
  215. ///
  216. /// ```
  217. /// fn read_slice(slice: &[usize]) {
  218. /// // ...
  219. /// }
  220. ///
  221. /// let v = vec![0, 1];
  222. /// read_slice(&v);
  223. ///
  224. /// // ... and that's all!
  225. /// // you can also do it like this:
  226. /// let u: &[usize] = &v;
  227. /// // or like this:
  228. /// let u: &[_] = &v;
  229. /// ```
  230. ///
  231. /// In Rust, it's more common to pass slices as arguments rather than vectors
  232. /// when you just want to provide read access. The same goes for [`String`] and
  233. /// [`&str`].
  234. ///
  235. /// # Capacity and reallocation
  236. ///
  237. /// The capacity of a vector is the amount of space allocated for any future
  238. /// elements that will be added onto the vector. This is not to be confused with
  239. /// the *length* of a vector, which specifies the number of actual elements
  240. /// within the vector. If a vector's length exceeds its capacity, its capacity
  241. /// will automatically be increased, but its elements will have to be
  242. /// reallocated.
  243. ///
  244. /// For example, a vector with capacity 10 and length 0 would be an empty vector
  245. /// with space for 10 more elements. Pushing 10 or fewer elements onto the
  246. /// vector will not change its capacity or cause reallocation to occur. However,
  247. /// if the vector's length is increased to 11, it will have to reallocate, which
  248. /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
  249. /// whenever possible to specify how big the vector is expected to get.
  250. ///
  251. /// # Guarantees
  252. ///
  253. /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
  254. /// about its design. This ensures that it's as low-overhead as possible in
  255. /// the general case, and can be correctly manipulated in primitive ways
  256. /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
  257. /// If additional type parameters are added (e.g., to support custom allocators),
  258. /// overriding their defaults may change the behavior.
  259. ///
  260. /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
  261. /// triplet. No more, no less. The order of these fields is completely
  262. /// unspecified, and you should use the appropriate methods to modify these.
  263. /// The pointer will never be null, so this type is null-pointer-optimized.
  264. ///
  265. /// However, the pointer might not actually point to allocated memory. In particular,
  266. /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
  267. /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
  268. /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
  269. /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
  270. /// the `Vec` might not report a [`capacity`] of 0*. `Vec` will allocate if and only
  271. /// if <code>[mem::size_of::\<T>]\() * [capacity]\() > 0</code>. In general, `Vec`'s allocation
  272. /// details are very subtle --- if you intend to allocate memory using a `Vec`
  273. /// and use it for something else (either to pass to unsafe code, or to build your
  274. /// own memory-backed collection), be sure to deallocate this memory by using
  275. /// `from_raw_parts` to recover the `Vec` and then dropping it.
  276. ///
  277. /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
  278. /// (as defined by the allocator Rust is configured to use by default), and its
  279. /// pointer points to [`len`] initialized, contiguous elements in order (what
  280. /// you would see if you coerced it to a slice), followed by <code>[capacity] - [len]</code>
  281. /// logically uninitialized, contiguous elements.
  282. ///
  283. /// A vector containing the elements `'a'` and `'b'` with capacity 4 can be
  284. /// visualized as below. The top part is the `Vec` struct, it contains a
  285. /// pointer to the head of the allocation in the heap, length and capacity.
  286. /// The bottom part is the allocation on the heap, a contiguous memory block.
  287. ///
  288. /// ```text
  289. /// ptr len capacity
  290. /// +--------+--------+--------+
  291. /// | 0x0123 | 2 | 4 |
  292. /// +--------+--------+--------+
  293. /// |
  294. /// v
  295. /// Heap +--------+--------+--------+--------+
  296. /// | 'a' | 'b' | uninit | uninit |
  297. /// +--------+--------+--------+--------+
  298. /// ```
  299. ///
  300. /// - **uninit** represents memory that is not initialized, see [`MaybeUninit`].
  301. /// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory
  302. /// layout (including the order of fields).
  303. ///
  304. /// `Vec` will never perform a "small optimization" where elements are actually
  305. /// stored on the stack for two reasons:
  306. ///
  307. /// * It would make it more difficult for unsafe code to correctly manipulate
  308. /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
  309. /// only moved, and it would be more difficult to determine if a `Vec` had
  310. /// actually allocated memory.
  311. ///
  312. /// * It would penalize the general case, incurring an additional branch
  313. /// on every access.
  314. ///
  315. /// `Vec` will never automatically shrink itself, even if completely empty. This
  316. /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
  317. /// and then filling it back up to the same [`len`] should incur no calls to
  318. /// the allocator. If you wish to free up unused memory, use
  319. /// [`shrink_to_fit`] or [`shrink_to`].
  320. ///
  321. /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
  322. /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
  323. /// <code>[len] == [capacity]</code>. That is, the reported capacity is completely
  324. /// accurate, and can be relied on. It can even be used to manually free the memory
  325. /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
  326. /// when not necessary.
  327. ///
  328. /// `Vec` does not guarantee any particular growth strategy when reallocating
  329. /// when full, nor when [`reserve`] is called. The current strategy is basic
  330. /// and it may prove desirable to use a non-constant growth factor. Whatever
  331. /// strategy is used will of course guarantee *O*(1) amortized [`push`].
  332. ///
  333. /// `vec![x; n]`, `vec![a, b, c, d]`, and
  334. /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
  335. /// with exactly the requested capacity. If <code>[len] == [capacity]</code>,
  336. /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
  337. /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
  338. ///
  339. /// `Vec` will not specifically overwrite any data that is removed from it,
  340. /// but also won't specifically preserve it. Its uninitialized memory is
  341. /// scratch space that it may use however it wants. It will generally just do
  342. /// whatever is most efficient or otherwise easy to implement. Do not rely on
  343. /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
  344. /// buffer may simply be reused by another allocation. Even if you zero a `Vec`'s memory
  345. /// first, that might not actually happen because the optimizer does not consider
  346. /// this a side-effect that must be preserved. There is one case which we will
  347. /// not break, however: using `unsafe` code to write to the excess capacity,
  348. /// and then increasing the length to match, is always valid.
  349. ///
  350. /// Currently, `Vec` does not guarantee the order in which elements are dropped.
  351. /// The order has changed in the past and may change again.
  352. ///
  353. /// [`get`]: ../../std/vec/struct.Vec.html#method.get
  354. /// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
  355. /// [`String`]: crate::string::String
  356. /// [`&str`]: type@str
  357. /// [`shrink_to_fit`]: Vec::shrink_to_fit
  358. /// [`shrink_to`]: Vec::shrink_to
  359. /// [capacity]: Vec::capacity
  360. /// [`capacity`]: Vec::capacity
  361. /// [mem::size_of::\<T>]: core::mem::size_of
  362. /// [len]: Vec::len
  363. /// [`len`]: Vec::len
  364. /// [`push`]: Vec::push
  365. /// [`insert`]: Vec::insert
  366. /// [`reserve`]: Vec::reserve
  367. /// [`MaybeUninit`]: core::mem::MaybeUninit
  368. /// [owned slice]: Box
  369. #[stable(feature = "rust1", since = "1.0.0")]
  370. #[cfg_attr(not(test), rustc_diagnostic_item = "Vec")]
  371. #[rustc_insignificant_dtor]
  372. pub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> {
  373. buf: RawVec<T, A>,
  374. len: usize,
  375. }
  376. ////////////////////////////////////////////////////////////////////////////////
  377. // Inherent methods
  378. ////////////////////////////////////////////////////////////////////////////////
  379. impl<T> Vec<T> {
  380. /// Constructs a new, empty `Vec<T>`.
  381. ///
  382. /// The vector will not allocate until elements are pushed onto it.
  383. ///
  384. /// # Examples
  385. ///
  386. /// ```
  387. /// # #![allow(unused_mut)]
  388. /// let mut vec: Vec<i32> = Vec::new();
  389. /// ```
  390. #[inline]
  391. #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
  392. #[stable(feature = "rust1", since = "1.0.0")]
  393. #[must_use]
  394. pub const fn new() -> Self {
  395. Vec { buf: RawVec::NEW, len: 0 }
  396. }
  397. /// Constructs a new, empty `Vec<T>` with the specified capacity.
  398. ///
  399. /// The vector will be able to hold exactly `capacity` elements without
  400. /// reallocating. If `capacity` is 0, the vector will not allocate.
  401. ///
  402. /// It is important to note that although the returned vector has the
  403. /// *capacity* specified, the vector will have a zero *length*. For an
  404. /// explanation of the difference between length and capacity, see
  405. /// *[Capacity and reallocation]*.
  406. ///
  407. /// [Capacity and reallocation]: #capacity-and-reallocation
  408. ///
  409. /// # Panics
  410. ///
  411. /// Panics if the new capacity exceeds `isize::MAX` bytes.
  412. ///
  413. /// # Examples
  414. ///
  415. /// ```
  416. /// let mut vec = Vec::with_capacity(10);
  417. ///
  418. /// // The vector contains no items, even though it has capacity for more
  419. /// assert_eq!(vec.len(), 0);
  420. /// assert_eq!(vec.capacity(), 10);
  421. ///
  422. /// // These are all done without reallocating...
  423. /// for i in 0..10 {
  424. /// vec.push(i);
  425. /// }
  426. /// assert_eq!(vec.len(), 10);
  427. /// assert_eq!(vec.capacity(), 10);
  428. ///
  429. /// // ...but this may make the vector reallocate
  430. /// vec.push(11);
  431. /// assert_eq!(vec.len(), 11);
  432. /// assert!(vec.capacity() >= 11);
  433. /// ```
  434. #[cfg(not(no_global_oom_handling))]
  435. #[inline]
  436. #[stable(feature = "rust1", since = "1.0.0")]
  437. #[must_use]
  438. pub fn with_capacity(capacity: usize) -> Self {
  439. Self::with_capacity_in(capacity, Global)
  440. }
  441. /// Creates a `Vec<T>` directly from the raw components of another vector.
  442. ///
  443. /// # Safety
  444. ///
  445. /// This is highly unsafe, due to the number of invariants that aren't
  446. /// checked:
  447. ///
  448. /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
  449. /// (at least, it's highly likely to be incorrect if it wasn't).
  450. /// * `T` needs to have the same alignment as what `ptr` was allocated with.
  451. /// (`T` having a less strict alignment is not sufficient, the alignment really
  452. /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
  453. /// allocated and deallocated with the same layout.)
  454. /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs
  455. /// to be the same size as the pointer was allocated with. (Because similar to
  456. /// alignment, [`dealloc`] must be called with the same layout `size`.)
  457. /// * `length` needs to be less than or equal to `capacity`.
  458. ///
  459. /// Violating these may cause problems like corrupting the allocator's
  460. /// internal data structures. For example it is normally **not** safe
  461. /// to build a `Vec<u8>` from a pointer to a C `char` array with length
  462. /// `size_t`, doing so is only safe if the array was initially allocated by
  463. /// a `Vec` or `String`.
  464. /// It's also not safe to build one from a `Vec<u16>` and its length, because
  465. /// the allocator cares about the alignment, and these two types have different
  466. /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
  467. /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. To avoid
  468. /// these issues, it is often preferable to do casting/transmuting using
  469. /// [`slice::from_raw_parts`] instead.
  470. ///
  471. /// The ownership of `ptr` is effectively transferred to the
  472. /// `Vec<T>` which may then deallocate, reallocate or change the
  473. /// contents of memory pointed to by the pointer at will. Ensure
  474. /// that nothing else uses the pointer after calling this
  475. /// function.
  476. ///
  477. /// [`String`]: crate::string::String
  478. /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
  479. ///
  480. /// # Examples
  481. ///
  482. /// ```
  483. /// use std::ptr;
  484. /// use std::mem;
  485. ///
  486. /// let v = vec![1, 2, 3];
  487. ///
  488. // FIXME Update this when vec_into_raw_parts is stabilized
  489. /// // Prevent running `v`'s destructor so we are in complete control
  490. /// // of the allocation.
  491. /// let mut v = mem::ManuallyDrop::new(v);
  492. ///
  493. /// // Pull out the various important pieces of information about `v`
  494. /// let p = v.as_mut_ptr();
  495. /// let len = v.len();
  496. /// let cap = v.capacity();
  497. ///
  498. /// unsafe {
  499. /// // Overwrite memory with 4, 5, 6
  500. /// for i in 0..len as isize {
  501. /// ptr::write(p.offset(i), 4 + i);
  502. /// }
  503. ///
  504. /// // Put everything back together into a Vec
  505. /// let rebuilt = Vec::from_raw_parts(p, len, cap);
  506. /// assert_eq!(rebuilt, [4, 5, 6]);
  507. /// }
  508. /// ```
  509. #[inline]
  510. #[stable(feature = "rust1", since = "1.0.0")]
  511. pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
  512. unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) }
  513. }
  514. }
  515. impl<T, A: Allocator> Vec<T, A> {
  516. /// Constructs a new, empty `Vec<T, A>`.
  517. ///
  518. /// The vector will not allocate until elements are pushed onto it.
  519. ///
  520. /// # Examples
  521. ///
  522. /// ```
  523. /// #![feature(allocator_api)]
  524. ///
  525. /// use std::alloc::System;
  526. ///
  527. /// # #[allow(unused_mut)]
  528. /// let mut vec: Vec<i32, _> = Vec::new_in(System);
  529. /// ```
  530. #[inline]
  531. #[unstable(feature = "allocator_api", issue = "32838")]
  532. pub const fn new_in(alloc: A) -> Self {
  533. Vec { buf: RawVec::new_in(alloc), len: 0 }
  534. }
  535. /// Constructs a new, empty `Vec<T, A>` with the specified capacity with the provided
  536. /// allocator.
  537. ///
  538. /// The vector will be able to hold exactly `capacity` elements without
  539. /// reallocating. If `capacity` is 0, the vector will not allocate.
  540. ///
  541. /// It is important to note that although the returned vector has the
  542. /// *capacity* specified, the vector will have a zero *length*. For an
  543. /// explanation of the difference between length and capacity, see
  544. /// *[Capacity and reallocation]*.
  545. ///
  546. /// [Capacity and reallocation]: #capacity-and-reallocation
  547. ///
  548. /// # Panics
  549. ///
  550. /// Panics if the new capacity exceeds `isize::MAX` bytes.
  551. ///
  552. /// # Examples
  553. ///
  554. /// ```
  555. /// #![feature(allocator_api)]
  556. ///
  557. /// use std::alloc::System;
  558. ///
  559. /// let mut vec = Vec::with_capacity_in(10, System);
  560. ///
  561. /// // The vector contains no items, even though it has capacity for more
  562. /// assert_eq!(vec.len(), 0);
  563. /// assert_eq!(vec.capacity(), 10);
  564. ///
  565. /// // These are all done without reallocating...
  566. /// for i in 0..10 {
  567. /// vec.push(i);
  568. /// }
  569. /// assert_eq!(vec.len(), 10);
  570. /// assert_eq!(vec.capacity(), 10);
  571. ///
  572. /// // ...but this may make the vector reallocate
  573. /// vec.push(11);
  574. /// assert_eq!(vec.len(), 11);
  575. /// assert!(vec.capacity() >= 11);
  576. /// ```
  577. #[cfg(not(no_global_oom_handling))]
  578. #[inline]
  579. #[unstable(feature = "allocator_api", issue = "32838")]
  580. pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
  581. Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 }
  582. }
  583. /// Creates a `Vec<T, A>` directly from the raw components of another vector.
  584. ///
  585. /// # Safety
  586. ///
  587. /// This is highly unsafe, due to the number of invariants that aren't
  588. /// checked:
  589. ///
  590. /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
  591. /// (at least, it's highly likely to be incorrect if it wasn't).
  592. /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
  593. /// (`T` having a less strict alignment is not sufficient, the alignment really
  594. /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
  595. /// allocated and deallocated with the same layout.)
  596. /// * `length` needs to be less than or equal to `capacity`.
  597. /// * `capacity` needs to be the capacity that the pointer was allocated with.
  598. ///
  599. /// Violating these may cause problems like corrupting the allocator's
  600. /// internal data structures. For example it is **not** safe
  601. /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
  602. /// It's also not safe to build one from a `Vec<u16>` and its length, because
  603. /// the allocator cares about the alignment, and these two types have different
  604. /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
  605. /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
  606. ///
  607. /// The ownership of `ptr` is effectively transferred to the
  608. /// `Vec<T>` which may then deallocate, reallocate or change the
  609. /// contents of memory pointed to by the pointer at will. Ensure
  610. /// that nothing else uses the pointer after calling this
  611. /// function.
  612. ///
  613. /// [`String`]: crate::string::String
  614. /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
  615. ///
  616. /// # Examples
  617. ///
  618. /// ```
  619. /// #![feature(allocator_api)]
  620. ///
  621. /// use std::alloc::System;
  622. ///
  623. /// use std::ptr;
  624. /// use std::mem;
  625. ///
  626. /// let mut v = Vec::with_capacity_in(3, System);
  627. /// v.push(1);
  628. /// v.push(2);
  629. /// v.push(3);
  630. ///
  631. // FIXME Update this when vec_into_raw_parts is stabilized
  632. /// // Prevent running `v`'s destructor so we are in complete control
  633. /// // of the allocation.
  634. /// let mut v = mem::ManuallyDrop::new(v);
  635. ///
  636. /// // Pull out the various important pieces of information about `v`
  637. /// let p = v.as_mut_ptr();
  638. /// let len = v.len();
  639. /// let cap = v.capacity();
  640. /// let alloc = v.allocator();
  641. ///
  642. /// unsafe {
  643. /// // Overwrite memory with 4, 5, 6
  644. /// for i in 0..len as isize {
  645. /// ptr::write(p.offset(i), 4 + i);
  646. /// }
  647. ///
  648. /// // Put everything back together into a Vec
  649. /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
  650. /// assert_eq!(rebuilt, [4, 5, 6]);
  651. /// }
  652. /// ```
  653. #[inline]
  654. #[unstable(feature = "allocator_api", issue = "32838")]
  655. pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {
  656. unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } }
  657. }
  658. /// Decomposes a `Vec<T>` into its raw components.
  659. ///
  660. /// Returns the raw pointer to the underlying data, the length of
  661. /// the vector (in elements), and the allocated capacity of the
  662. /// data (in elements). These are the same arguments in the same
  663. /// order as the arguments to [`from_raw_parts`].
  664. ///
  665. /// After calling this function, the caller is responsible for the
  666. /// memory previously managed by the `Vec`. The only way to do
  667. /// this is to convert the raw pointer, length, and capacity back
  668. /// into a `Vec` with the [`from_raw_parts`] function, allowing
  669. /// the destructor to perform the cleanup.
  670. ///
  671. /// [`from_raw_parts`]: Vec::from_raw_parts
  672. ///
  673. /// # Examples
  674. ///
  675. /// ```
  676. /// #![feature(vec_into_raw_parts)]
  677. /// let v: Vec<i32> = vec![-1, 0, 1];
  678. ///
  679. /// let (ptr, len, cap) = v.into_raw_parts();
  680. ///
  681. /// let rebuilt = unsafe {
  682. /// // We can now make changes to the components, such as
  683. /// // transmuting the raw pointer to a compatible type.
  684. /// let ptr = ptr as *mut u32;
  685. ///
  686. /// Vec::from_raw_parts(ptr, len, cap)
  687. /// };
  688. /// assert_eq!(rebuilt, [4294967295, 0, 1]);
  689. /// ```
  690. #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
  691. pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
  692. let mut me = ManuallyDrop::new(self);
  693. (me.as_mut_ptr(), me.len(), me.capacity())
  694. }
  695. /// Decomposes a `Vec<T>` into its raw components.
  696. ///
  697. /// Returns the raw pointer to the underlying data, the length of the vector (in elements),
  698. /// the allocated capacity of the data (in elements), and the allocator. These are the same
  699. /// arguments in the same order as the arguments to [`from_raw_parts_in`].
  700. ///
  701. /// After calling this function, the caller is responsible for the
  702. /// memory previously managed by the `Vec`. The only way to do
  703. /// this is to convert the raw pointer, length, and capacity back
  704. /// into a `Vec` with the [`from_raw_parts_in`] function, allowing
  705. /// the destructor to perform the cleanup.
  706. ///
  707. /// [`from_raw_parts_in`]: Vec::from_raw_parts_in
  708. ///
  709. /// # Examples
  710. ///
  711. /// ```
  712. /// #![feature(allocator_api, vec_into_raw_parts)]
  713. ///
  714. /// use std::alloc::System;
  715. ///
  716. /// let mut v: Vec<i32, System> = Vec::new_in(System);
  717. /// v.push(-1);
  718. /// v.push(0);
  719. /// v.push(1);
  720. ///
  721. /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();
  722. ///
  723. /// let rebuilt = unsafe {
  724. /// // We can now make changes to the components, such as
  725. /// // transmuting the raw pointer to a compatible type.
  726. /// let ptr = ptr as *mut u32;
  727. ///
  728. /// Vec::from_raw_parts_in(ptr, len, cap, alloc)
  729. /// };
  730. /// assert_eq!(rebuilt, [4294967295, 0, 1]);
  731. /// ```
  732. #[unstable(feature = "allocator_api", issue = "32838")]
  733. // #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
  734. pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) {
  735. let mut me = ManuallyDrop::new(self);
  736. let len = me.len();
  737. let capacity = me.capacity();
  738. let ptr = me.as_mut_ptr();
  739. let alloc = unsafe { ptr::read(me.allocator()) };
  740. (ptr, len, capacity, alloc)
  741. }
  742. /// Returns the number of elements the vector can hold without
  743. /// reallocating.
  744. ///
  745. /// # Examples
  746. ///
  747. /// ```
  748. /// let vec: Vec<i32> = Vec::with_capacity(10);
  749. /// assert_eq!(vec.capacity(), 10);
  750. /// ```
  751. #[inline]
  752. #[stable(feature = "rust1", since = "1.0.0")]
  753. pub fn capacity(&self) -> usize {
  754. self.buf.capacity()
  755. }
  756. /// Reserves capacity for at least `additional` more elements to be inserted
  757. /// in the given `Vec<T>`. The collection may reserve more space to avoid
  758. /// frequent reallocations. After calling `reserve`, capacity will be
  759. /// greater than or equal to `self.len() + additional`. Does nothing if
  760. /// capacity is already sufficient.
  761. ///
  762. /// # Panics
  763. ///
  764. /// Panics if the new capacity exceeds `isize::MAX` bytes.
  765. ///
  766. /// # Examples
  767. ///
  768. /// ```
  769. /// let mut vec = vec![1];
  770. /// vec.reserve(10);
  771. /// assert!(vec.capacity() >= 11);
  772. /// ```
  773. #[cfg(not(no_global_oom_handling))]
  774. #[stable(feature = "rust1", since = "1.0.0")]
  775. pub fn reserve(&mut self, additional: usize) {
  776. self.buf.reserve(self.len, additional);
  777. }
  778. /// Reserves the minimum capacity for exactly `additional` more elements to
  779. /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
  780. /// capacity will be greater than or equal to `self.len() + additional`.
  781. /// Does nothing if the capacity is already sufficient.
  782. ///
  783. /// Note that the allocator may give the collection more space than it
  784. /// requests. Therefore, capacity can not be relied upon to be precisely
  785. /// minimal. Prefer [`reserve`] if future insertions are expected.
  786. ///
  787. /// [`reserve`]: Vec::reserve
  788. ///
  789. /// # Panics
  790. ///
  791. /// Panics if the new capacity exceeds `isize::MAX` bytes.
  792. ///
  793. /// # Examples
  794. ///
  795. /// ```
  796. /// let mut vec = vec![1];
  797. /// vec.reserve_exact(10);
  798. /// assert!(vec.capacity() >= 11);
  799. /// ```
  800. #[cfg(not(no_global_oom_handling))]
  801. #[stable(feature = "rust1", since = "1.0.0")]
  802. pub fn reserve_exact(&mut self, additional: usize) {
  803. self.buf.reserve_exact(self.len, additional);
  804. }
  805. /// Tries to reserve capacity for at least `additional` more elements to be inserted
  806. /// in the given `Vec<T>`. The collection may reserve more space to avoid
  807. /// frequent reallocations. After calling `try_reserve`, capacity will be
  808. /// greater than or equal to `self.len() + additional`. Does nothing if
  809. /// capacity is already sufficient.
  810. ///
  811. /// # Errors
  812. ///
  813. /// If the capacity overflows, or the allocator reports a failure, then an error
  814. /// is returned.
  815. ///
  816. /// # Examples
  817. ///
  818. /// ```
  819. /// use std::collections::TryReserveError;
  820. ///
  821. /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
  822. /// let mut output = Vec::new();
  823. ///
  824. /// // Pre-reserve the memory, exiting if we can't
  825. /// output.try_reserve(data.len())?;
  826. ///
  827. /// // Now we know this can't OOM in the middle of our complex work
  828. /// output.extend(data.iter().map(|&val| {
  829. /// val * 2 + 5 // very complicated
  830. /// }));
  831. ///
  832. /// Ok(output)
  833. /// }
  834. /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
  835. /// ```
  836. #[stable(feature = "try_reserve", since = "1.57.0")]
  837. pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
  838. self.buf.try_reserve(self.len, additional)
  839. }
  840. /// Tries to reserve the minimum capacity for exactly `additional`
  841. /// elements to be inserted in the given `Vec<T>`. After calling
  842. /// `try_reserve_exact`, capacity will be greater than or equal to
  843. /// `self.len() + additional` if it returns `Ok(())`.
  844. /// Does nothing if the capacity is already sufficient.
  845. ///
  846. /// Note that the allocator may give the collection more space than it
  847. /// requests. Therefore, capacity can not be relied upon to be precisely
  848. /// minimal. Prefer [`try_reserve`] if future insertions are expected.
  849. ///
  850. /// [`try_reserve`]: Vec::try_reserve
  851. ///
  852. /// # Errors
  853. ///
  854. /// If the capacity overflows, or the allocator reports a failure, then an error
  855. /// is returned.
  856. ///
  857. /// # Examples
  858. ///
  859. /// ```
  860. /// use std::collections::TryReserveError;
  861. ///
  862. /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
  863. /// let mut output = Vec::new();
  864. ///
  865. /// // Pre-reserve the memory, exiting if we can't
  866. /// output.try_reserve_exact(data.len())?;
  867. ///
  868. /// // Now we know this can't OOM in the middle of our complex work
  869. /// output.extend(data.iter().map(|&val| {
  870. /// val * 2 + 5 // very complicated
  871. /// }));
  872. ///
  873. /// Ok(output)
  874. /// }
  875. /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
  876. /// ```
  877. #[stable(feature = "try_reserve", since = "1.57.0")]
  878. pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
  879. self.buf.try_reserve_exact(self.len, additional)
  880. }
  881. /// Shrinks the capacity of the vector as much as possible.
  882. ///
  883. /// It will drop down as close as possible to the length but the allocator
  884. /// may still inform the vector that there is space for a few more elements.
  885. ///
  886. /// # Examples
  887. ///
  888. /// ```
  889. /// let mut vec = Vec::with_capacity(10);
  890. /// vec.extend([1, 2, 3]);
  891. /// assert_eq!(vec.capacity(), 10);
  892. /// vec.shrink_to_fit();
  893. /// assert!(vec.capacity() >= 3);
  894. /// ```
  895. #[cfg(not(no_global_oom_handling))]
  896. #[stable(feature = "rust1", since = "1.0.0")]
  897. pub fn shrink_to_fit(&mut self) {
  898. // The capacity is never less than the length, and there's nothing to do when
  899. // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
  900. // by only calling it with a greater capacity.
  901. if self.capacity() > self.len {
  902. self.buf.shrink_to_fit(self.len);
  903. }
  904. }
  905. /// Shrinks the capacity of the vector with a lower bound.
  906. ///
  907. /// The capacity will remain at least as large as both the length
  908. /// and the supplied value.
  909. ///
  910. /// If the current capacity is less than the lower limit, this is a no-op.
  911. ///
  912. /// # Examples
  913. ///
  914. /// ```
  915. /// let mut vec = Vec::with_capacity(10);
  916. /// vec.extend([1, 2, 3]);
  917. /// assert_eq!(vec.capacity(), 10);
  918. /// vec.shrink_to(4);
  919. /// assert!(vec.capacity() >= 4);
  920. /// vec.shrink_to(0);
  921. /// assert!(vec.capacity() >= 3);
  922. /// ```
  923. #[cfg(not(no_global_oom_handling))]
  924. #[stable(feature = "shrink_to", since = "1.56.0")]
  925. pub fn shrink_to(&mut self, min_capacity: usize) {
  926. if self.capacity() > min_capacity {
  927. self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
  928. }
  929. }
  930. /// Converts the vector into [`Box<[T]>`][owned slice].
  931. ///
  932. /// Note that this will drop any excess capacity.
  933. ///
  934. /// [owned slice]: Box
  935. ///
  936. /// # Examples
  937. ///
  938. /// ```
  939. /// let v = vec![1, 2, 3];
  940. ///
  941. /// let slice = v.into_boxed_slice();
  942. /// ```
  943. ///
  944. /// Any excess capacity is removed:
  945. ///
  946. /// ```
  947. /// let mut vec = Vec::with_capacity(10);
  948. /// vec.extend([1, 2, 3]);
  949. ///
  950. /// assert_eq!(vec.capacity(), 10);
  951. /// let slice = vec.into_boxed_slice();
  952. /// assert_eq!(slice.into_vec().capacity(), 3);
  953. /// ```
  954. #[cfg(not(no_global_oom_handling))]
  955. #[stable(feature = "rust1", since = "1.0.0")]
  956. pub fn into_boxed_slice(mut self) -> Box<[T], A> {
  957. unsafe {
  958. self.shrink_to_fit();
  959. let me = ManuallyDrop::new(self);
  960. let buf = ptr::read(&me.buf);
  961. let len = me.len();
  962. buf.into_box(len).assume_init()
  963. }
  964. }
  965. /// Shortens the vector, keeping the first `len` elements and dropping
  966. /// the rest.
  967. ///
  968. /// If `len` is greater than the vector's current length, this has no
  969. /// effect.
  970. ///
  971. /// The [`drain`] method can emulate `truncate`, but causes the excess
  972. /// elements to be returned instead of dropped.
  973. ///
  974. /// Note that this method has no effect on the allocated capacity
  975. /// of the vector.
  976. ///
  977. /// # Examples
  978. ///
  979. /// Truncating a five element vector to two elements:
  980. ///
  981. /// ```
  982. /// let mut vec = vec![1, 2, 3, 4, 5];
  983. /// vec.truncate(2);
  984. /// assert_eq!(vec, [1, 2]);
  985. /// ```
  986. ///
  987. /// No truncation occurs when `len` is greater than the vector's current
  988. /// length:
  989. ///
  990. /// ```
  991. /// let mut vec = vec![1, 2, 3];
  992. /// vec.truncate(8);
  993. /// assert_eq!(vec, [1, 2, 3]);
  994. /// ```
  995. ///
  996. /// Truncating when `len == 0` is equivalent to calling the [`clear`]
  997. /// method.
  998. ///
  999. /// ```
  1000. /// let mut vec = vec![1, 2, 3];
  1001. /// vec.truncate(0);
  1002. /// assert_eq!(vec, []);
  1003. /// ```
  1004. ///
  1005. /// [`clear`]: Vec::clear
  1006. /// [`drain`]: Vec::drain
  1007. #[stable(feature = "rust1", since = "1.0.0")]
  1008. pub fn truncate(&mut self, len: usize) {
  1009. // This is safe because:
  1010. //
  1011. // * the slice passed to `drop_in_place` is valid; the `len > self.len`
  1012. // case avoids creating an invalid slice, and
  1013. // * the `len` of the vector is shrunk before calling `drop_in_place`,
  1014. // such that no value will be dropped twice in case `drop_in_place`
  1015. // were to panic once (if it panics twice, the program aborts).
  1016. unsafe {
  1017. // Note: It's intentional that this is `>` and not `>=`.
  1018. // Changing it to `>=` has negative performance
  1019. // implications in some cases. See #78884 for more.
  1020. if len > self.len {
  1021. return;
  1022. }
  1023. let remaining_len = self.len - len;
  1024. let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
  1025. self.len = len;
  1026. ptr::drop_in_place(s);
  1027. }
  1028. }
  1029. /// Extracts a slice containing the entire vector.
  1030. ///
  1031. /// Equivalent to `&s[..]`.
  1032. ///
  1033. /// # Examples
  1034. ///
  1035. /// ```
  1036. /// use std::io::{self, Write};
  1037. /// let buffer = vec![1, 2, 3, 5, 8];
  1038. /// io::sink().write(buffer.as_slice()).unwrap();
  1039. /// ```
  1040. #[inline]
  1041. #[stable(feature = "vec_as_slice", since = "1.7.0")]
  1042. pub fn as_slice(&self) -> &[T] {
  1043. self
  1044. }
  1045. /// Extracts a mutable slice of the entire vector.
  1046. ///
  1047. /// Equivalent to `&mut s[..]`.
  1048. ///
  1049. /// # Examples
  1050. ///
  1051. /// ```
  1052. /// use std::io::{self, Read};
  1053. /// let mut buffer = vec![0; 3];
  1054. /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
  1055. /// ```
  1056. #[inline]
  1057. #[stable(feature = "vec_as_slice", since = "1.7.0")]
  1058. pub fn as_mut_slice(&mut self) -> &mut [T] {
  1059. self
  1060. }
  1061. /// Returns a raw pointer to the vector's buffer.
  1062. ///
  1063. /// The caller must ensure that the vector outlives the pointer this
  1064. /// function returns, or else it will end up pointing to garbage.
  1065. /// Modifying the vector may cause its buffer to be reallocated,
  1066. /// which would also make any pointers to it invalid.
  1067. ///
  1068. /// The caller must also ensure that the memory the pointer (non-transitively) points to
  1069. /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
  1070. /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
  1071. ///
  1072. /// # Examples
  1073. ///
  1074. /// ```
  1075. /// let x = vec![1, 2, 4];
  1076. /// let x_ptr = x.as_ptr();
  1077. ///
  1078. /// unsafe {
  1079. /// for i in 0..x.len() {
  1080. /// assert_eq!(*x_ptr.add(i), 1 << i);
  1081. /// }
  1082. /// }
  1083. /// ```
  1084. ///
  1085. /// [`as_mut_ptr`]: Vec::as_mut_ptr
  1086. #[stable(feature = "vec_as_ptr", since = "1.37.0")]
  1087. #[inline]
  1088. pub fn as_ptr(&self) -> *const T {
  1089. // We shadow the slice method of the same name to avoid going through
  1090. // `deref`, which creates an intermediate reference.
  1091. let ptr = self.buf.ptr();
  1092. unsafe {
  1093. assume(!ptr.is_null());
  1094. }
  1095. ptr
  1096. }
  1097. /// Returns an unsafe mutable pointer to the vector's buffer.
  1098. ///
  1099. /// The caller must ensure that the vector outlives the pointer this
  1100. /// function returns, or else it will end up pointing to garbage.
  1101. /// Modifying the vector may cause its buffer to be reallocated,
  1102. /// which would also make any pointers to it invalid.
  1103. ///
  1104. /// # Examples
  1105. ///
  1106. /// ```
  1107. /// // Allocate vector big enough for 4 elements.
  1108. /// let size = 4;
  1109. /// let mut x: Vec<i32> = Vec::with_capacity(size);
  1110. /// let x_ptr = x.as_mut_ptr();
  1111. ///
  1112. /// // Initialize elements via raw pointer writes, then set length.
  1113. /// unsafe {
  1114. /// for i in 0..size {
  1115. /// *x_ptr.add(i) = i as i32;
  1116. /// }
  1117. /// x.set_len(size);
  1118. /// }
  1119. /// assert_eq!(&*x, &[0, 1, 2, 3]);
  1120. /// ```
  1121. #[stable(feature = "vec_as_ptr", since = "1.37.0")]
  1122. #[inline]
  1123. pub fn as_mut_ptr(&mut self) -> *mut T {
  1124. // We shadow the slice method of the same name to avoid going through
  1125. // `deref_mut`, which creates an intermediate reference.
  1126. let ptr = self.buf.ptr();
  1127. unsafe {
  1128. assume(!ptr.is_null());
  1129. }
  1130. ptr
  1131. }
  1132. /// Returns a reference to the underlying allocator.
  1133. #[unstable(feature = "allocator_api", issue = "32838")]
  1134. #[inline]
  1135. pub fn allocator(&self) -> &A {
  1136. self.buf.allocator()
  1137. }
  1138. /// Forces the length of the vector to `new_len`.
  1139. ///
  1140. /// This is a low-level operation that maintains none of the normal
  1141. /// invariants of the type. Normally changing the length of a vector
  1142. /// is done using one of the safe operations instead, such as
  1143. /// [`truncate`], [`resize`], [`extend`], or [`clear`].
  1144. ///
  1145. /// [`truncate`]: Vec::truncate
  1146. /// [`resize`]: Vec::resize
  1147. /// [`extend`]: Extend::extend
  1148. /// [`clear`]: Vec::clear
  1149. ///
  1150. /// # Safety
  1151. ///
  1152. /// - `new_len` must be less than or equal to [`capacity()`].
  1153. /// - The elements at `old_len..new_len` must be initialized.
  1154. ///
  1155. /// [`capacity()`]: Vec::capacity
  1156. ///
  1157. /// # Examples
  1158. ///
  1159. /// This method can be useful for situations in which the vector
  1160. /// is serving as a buffer for other code, particularly over FFI:
  1161. ///
  1162. /// ```no_run
  1163. /// # #![allow(dead_code)]
  1164. /// # // This is just a minimal skeleton for the doc example;
  1165. /// # // don't use this as a starting point for a real library.
  1166. /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
  1167. /// # const Z_OK: i32 = 0;
  1168. /// # extern "C" {
  1169. /// # fn deflateGetDictionary(
  1170. /// # strm: *mut std::ffi::c_void,
  1171. /// # dictionary: *mut u8,
  1172. /// # dictLength: *mut usize,
  1173. /// # ) -> i32;
  1174. /// # }
  1175. /// # impl StreamWrapper {
  1176. /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
  1177. /// // Per the FFI method's docs, "32768 bytes is always enough".
  1178. /// let mut dict = Vec::with_capacity(32_768);
  1179. /// let mut dict_length = 0;
  1180. /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
  1181. /// // 1. `dict_length` elements were initialized.
  1182. /// // 2. `dict_length` <= the capacity (32_768)
  1183. /// // which makes `set_len` safe to call.
  1184. /// unsafe {
  1185. /// // Make the FFI call...
  1186. /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
  1187. /// if r == Z_OK {
  1188. /// // ...and update the length to what was initialized.
  1189. /// dict.set_len(dict_length);
  1190. /// Some(dict)
  1191. /// } else {
  1192. /// None
  1193. /// }
  1194. /// }
  1195. /// }
  1196. /// # }
  1197. /// ```
  1198. ///
  1199. /// While the following example is sound, there is a memory leak since
  1200. /// the inner vectors were not freed prior to the `set_len` call:
  1201. ///
  1202. /// ```
  1203. /// let mut vec = vec![vec![1, 0, 0],
  1204. /// vec![0, 1, 0],
  1205. /// vec![0, 0, 1]];
  1206. /// // SAFETY:
  1207. /// // 1. `old_len..0` is empty so no elements need to be initialized.
  1208. /// // 2. `0 <= capacity` always holds whatever `capacity` is.
  1209. /// unsafe {
  1210. /// vec.set_len(0);
  1211. /// }
  1212. /// ```
  1213. ///
  1214. /// Normally, here, one would use [`clear`] instead to correctly drop
  1215. /// the contents and thus not leak memory.
  1216. #[inline]
  1217. #[stable(feature = "rust1", since = "1.0.0")]
  1218. pub unsafe fn set_len(&mut self, new_len: usize) {
  1219. debug_assert!(new_len <= self.capacity());
  1220. self.len = new_len;
  1221. }
  1222. /// Removes an element from the vector and returns it.
  1223. ///
  1224. /// The removed element is replaced by the last element of the vector.
  1225. ///
  1226. /// This does not preserve ordering, but is *O*(1).
  1227. /// If you need to preserve the element order, use [`remove`] instead.
  1228. ///
  1229. /// [`remove`]: Vec::remove
  1230. ///
  1231. /// # Panics
  1232. ///
  1233. /// Panics if `index` is out of bounds.
  1234. ///
  1235. /// # Examples
  1236. ///
  1237. /// ```
  1238. /// let mut v = vec!["foo", "bar", "baz", "qux"];
  1239. ///
  1240. /// assert_eq!(v.swap_remove(1), "bar");
  1241. /// assert_eq!(v, ["foo", "qux", "baz"]);
  1242. ///
  1243. /// assert_eq!(v.swap_remove(0), "foo");
  1244. /// assert_eq!(v, ["baz", "qux"]);
  1245. /// ```
  1246. #[inline]
  1247. #[stable(feature = "rust1", since = "1.0.0")]
  1248. pub fn swap_remove(&mut self, index: usize) -> T {
  1249. #[cold]
  1250. #[inline(never)]
  1251. fn assert_failed(index: usize, len: usize) -> ! {
  1252. panic!("swap_remove index (is {index}) should be < len (is {len})");
  1253. }
  1254. let len = self.len();
  1255. if index >= len {
  1256. assert_failed(index, len);
  1257. }
  1258. unsafe {
  1259. // We replace self[index] with the last element. Note that if the
  1260. // bounds check above succeeds there must be a last element (which
  1261. // can be self[index] itself).
  1262. let value = ptr::read(self.as_ptr().add(index));
  1263. let base_ptr = self.as_mut_ptr();
  1264. ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1);
  1265. self.set_len(len - 1);
  1266. value
  1267. }
  1268. }
  1269. /// Inserts an element at position `index` within the vector, shifting all
  1270. /// elements after it to the right.
  1271. ///
  1272. /// # Panics
  1273. ///
  1274. /// Panics if `index > len`.
  1275. ///
  1276. /// # Examples
  1277. ///
  1278. /// ```
  1279. /// let mut vec = vec![1, 2, 3];
  1280. /// vec.insert(1, 4);
  1281. /// assert_eq!(vec, [1, 4, 2, 3]);
  1282. /// vec.insert(4, 5);
  1283. /// assert_eq!(vec, [1, 4, 2, 3, 5]);
  1284. /// ```
  1285. #[cfg(not(no_global_oom_handling))]
  1286. #[stable(feature = "rust1", since = "1.0.0")]
  1287. pub fn insert(&mut self, index: usize, element: T) {
  1288. #[cold]
  1289. #[inline(never)]
  1290. fn assert_failed(index: usize, len: usize) -> ! {
  1291. panic!("insertion index (is {index}) should be <= len (is {len})");
  1292. }
  1293. let len = self.len();
  1294. if index > len {
  1295. assert_failed(index, len);
  1296. }
  1297. // space for the new element
  1298. if len == self.buf.capacity() {
  1299. self.reserve(1);
  1300. }
  1301. unsafe {
  1302. // infallible
  1303. // The spot to put the new value
  1304. {
  1305. let p = self.as_mut_ptr().add(index);
  1306. // Shift everything over to make space. (Duplicating the
  1307. // `index`th element into two consecutive places.)
  1308. ptr::copy(p, p.offset(1), len - index);
  1309. // Write it in, overwriting the first copy of the `index`th
  1310. // element.
  1311. ptr::write(p, element);
  1312. }
  1313. self.set_len(len + 1);
  1314. }
  1315. }
  1316. /// Removes and returns the element at position `index` within the vector,
  1317. /// shifting all elements after it to the left.
  1318. ///
  1319. /// Note: Because this shifts over the remaining elements, it has a
  1320. /// worst-case performance of *O*(*n*). If you don't need the order of elements
  1321. /// to be preserved, use [`swap_remove`] instead. If you'd like to remove
  1322. /// elements from the beginning of the `Vec`, consider using
  1323. /// [`VecDeque::pop_front`] instead.
  1324. ///
  1325. /// [`swap_remove`]: Vec::swap_remove
  1326. /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
  1327. ///
  1328. /// # Panics
  1329. ///
  1330. /// Panics if `index` is out of bounds.
  1331. ///
  1332. /// # Examples
  1333. ///
  1334. /// ```
  1335. /// let mut v = vec![1, 2, 3];
  1336. /// assert_eq!(v.remove(1), 2);
  1337. /// assert_eq!(v, [1, 3]);
  1338. /// ```
  1339. #[stable(feature = "rust1", since = "1.0.0")]
  1340. #[track_caller]
  1341. pub fn remove(&mut self, index: usize) -> T {
  1342. #[cold]
  1343. #[inline(never)]
  1344. #[track_caller]
  1345. fn assert_failed(index: usize, len: usize) -> ! {
  1346. panic!("removal index (is {index}) should be < len (is {len})");
  1347. }
  1348. let len = self.len();
  1349. if index >= len {
  1350. assert_failed(index, len);
  1351. }
  1352. unsafe {
  1353. // infallible
  1354. let ret;
  1355. {
  1356. // the place we are taking from.
  1357. let ptr = self.as_mut_ptr().add(index);
  1358. // copy it out, unsafely having a copy of the value on
  1359. // the stack and in the vector at the same time.
  1360. ret = ptr::read(ptr);
  1361. // Shift everything down to fill in that spot.
  1362. ptr::copy(ptr.offset(1), ptr, len - index - 1);
  1363. }
  1364. self.set_len(len - 1);
  1365. ret
  1366. }
  1367. }
  1368. /// Retains only the elements specified by the predicate.
  1369. ///
  1370. /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
  1371. /// This method operates in place, visiting each element exactly once in the
  1372. /// original order, and preserves the order of the retained elements.
  1373. ///
  1374. /// # Examples
  1375. ///
  1376. /// ```
  1377. /// let mut vec = vec![1, 2, 3, 4];
  1378. /// vec.retain(|&x| x % 2 == 0);
  1379. /// assert_eq!(vec, [2, 4]);
  1380. /// ```
  1381. ///
  1382. /// Because the elements are visited exactly once in the original order,
  1383. /// external state may be used to decide which elements to keep.
  1384. ///
  1385. /// ```
  1386. /// let mut vec = vec![1, 2, 3, 4, 5];
  1387. /// let keep = [false, true, true, false, true];
  1388. /// let mut iter = keep.iter();
  1389. /// vec.retain(|_| *iter.next().unwrap());
  1390. /// assert_eq!(vec, [2, 3, 5]);
  1391. /// ```
  1392. #[stable(feature = "rust1", since = "1.0.0")]
  1393. pub fn retain<F>(&mut self, mut f: F)
  1394. where
  1395. F: FnMut(&T) -> bool,
  1396. {
  1397. self.retain_mut(|elem| f(elem));
  1398. }
  1399. /// Retains only the elements specified by the predicate, passing a mutable reference to it.
  1400. ///
  1401. /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
  1402. /// This method operates in place, visiting each element exactly once in the
  1403. /// original order, and preserves the order of the retained elements.
  1404. ///
  1405. /// # Examples
  1406. ///
  1407. /// ```
  1408. /// let mut vec = vec![1, 2, 3, 4];
  1409. /// vec.retain_mut(|x| if *x > 3 {
  1410. /// false
  1411. /// } else {
  1412. /// *x += 1;
  1413. /// true
  1414. /// });
  1415. /// assert_eq!(vec, [2, 3, 4]);
  1416. /// ```
  1417. #[stable(feature = "vec_retain_mut", since = "1.61.0")]
  1418. pub fn retain_mut<F>(&mut self, mut f: F)
  1419. where
  1420. F: FnMut(&mut T) -> bool,
  1421. {
  1422. let original_len = self.len();
  1423. // Avoid double drop if the drop guard is not executed,
  1424. // since we may make some holes during the process.
  1425. unsafe { self.set_len(0) };
  1426. // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
  1427. // |<- processed len ->| ^- next to check
  1428. // |<- deleted cnt ->|
  1429. // |<- original_len ->|
  1430. // Kept: Elements which predicate returns true on.
  1431. // Hole: Moved or dropped element slot.
  1432. // Unchecked: Unchecked valid elements.
  1433. //
  1434. // This drop guard will be invoked when predicate or `drop` of element panicked.
  1435. // It shifts unchecked elements to cover holes and `set_len` to the correct length.
  1436. // In cases when predicate and `drop` never panick, it will be optimized out.
  1437. struct BackshiftOnDrop<'a, T, A: Allocator> {
  1438. v: &'a mut Vec<T, A>,
  1439. processed_len: usize,
  1440. deleted_cnt: usize,
  1441. original_len: usize,
  1442. }
  1443. impl<T, A: Allocator> Drop for BackshiftOnDrop<'_, T, A> {
  1444. fn drop(&mut self) {
  1445. if self.deleted_cnt > 0 {
  1446. // SAFETY: Trailing unchecked items must be valid since we never touch them.
  1447. unsafe {
  1448. ptr::copy(
  1449. self.v.as_ptr().add(self.processed_len),
  1450. self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt),
  1451. self.original_len - self.processed_len,
  1452. );
  1453. }
  1454. }
  1455. // SAFETY: After filling holes, all items are in contiguous memory.
  1456. unsafe {
  1457. self.v.set_len(self.original_len - self.deleted_cnt);
  1458. }
  1459. }
  1460. }
  1461. let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len };
  1462. fn process_loop<F, T, A: Allocator, const DELETED: bool>(
  1463. original_len: usize,
  1464. f: &mut F,
  1465. g: &mut BackshiftOnDrop<'_, T, A>,
  1466. ) where
  1467. F: FnMut(&mut T) -> bool,
  1468. {
  1469. while g.processed_len != original_len {
  1470. // SAFETY: Unchecked element must be valid.
  1471. let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) };
  1472. if !f(cur) {
  1473. // Advance early to avoid double drop if `drop_in_place` panicked.
  1474. g.processed_len += 1;
  1475. g.deleted_cnt += 1;
  1476. // SAFETY: We never touch this element again after dropped.
  1477. unsafe { ptr::drop_in_place(cur) };
  1478. // We already advanced the counter.
  1479. if DELETED {
  1480. continue;
  1481. } else {
  1482. break;
  1483. }
  1484. }
  1485. if DELETED {
  1486. // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element.
  1487. // We use copy for move, and never touch this element again.
  1488. unsafe {
  1489. let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt);
  1490. ptr::copy_nonoverlapping(cur, hole_slot, 1);
  1491. }
  1492. }
  1493. g.processed_len += 1;
  1494. }
  1495. }
  1496. // Stage 1: Nothing was deleted.
  1497. process_loop::<F, T, A, false>(original_len, &mut f, &mut g);
  1498. // Stage 2: Some elements were deleted.
  1499. process_loop::<F, T, A, true>(original_len, &mut f, &mut g);
  1500. // All item are processed. This can be optimized to `set_len` by LLVM.
  1501. drop(g);
  1502. }
  1503. /// Removes all but the first of consecutive elements in the vector that resolve to the same
  1504. /// key.
  1505. ///
  1506. /// If the vector is sorted, this removes all duplicates.
  1507. ///
  1508. /// # Examples
  1509. ///
  1510. /// ```
  1511. /// let mut vec = vec![10, 20, 21, 30, 20];
  1512. ///
  1513. /// vec.dedup_by_key(|i| *i / 10);
  1514. ///
  1515. /// assert_eq!(vec, [10, 20, 30, 20]);
  1516. /// ```
  1517. #[stable(feature = "dedup_by", since = "1.16.0")]
  1518. #[inline]
  1519. pub fn dedup_by_key<F, K>(&mut self, mut key: F)
  1520. where
  1521. F: FnMut(&mut T) -> K,
  1522. K: PartialEq,
  1523. {
  1524. self.dedup_by(|a, b| key(a) == key(b))
  1525. }
  1526. /// Removes all but the first of consecutive elements in the vector satisfying a given equality
  1527. /// relation.
  1528. ///
  1529. /// The `same_bucket` function is passed references to two elements from the vector and
  1530. /// must determine if the elements compare equal. The elements are passed in opposite order
  1531. /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
  1532. ///
  1533. /// If the vector is sorted, this removes all duplicates.
  1534. ///
  1535. /// # Examples
  1536. ///
  1537. /// ```
  1538. /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
  1539. ///
  1540. /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
  1541. ///
  1542. /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
  1543. /// ```
  1544. #[stable(feature = "dedup_by", since = "1.16.0")]
  1545. pub fn dedup_by<F>(&mut self, mut same_bucket: F)
  1546. where
  1547. F: FnMut(&mut T, &mut T) -> bool,
  1548. {
  1549. let len = self.len();
  1550. if len <= 1 {
  1551. return;
  1552. }
  1553. /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */
  1554. struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> {
  1555. /* Offset of the element we want to check if it is duplicate */
  1556. read: usize,
  1557. /* Offset of the place where we want to place the non-duplicate
  1558. * when we find it. */
  1559. write: usize,
  1560. /* The Vec that would need correction if `same_bucket` panicked */
  1561. vec: &'a mut Vec<T, A>,
  1562. }
  1563. impl<'a, T, A: core::alloc::Allocator> Drop for FillGapOnDrop<'a, T, A> {
  1564. fn drop(&mut self) {
  1565. /* This code gets executed when `same_bucket` panics */
  1566. /* SAFETY: invariant guarantees that `read - write`
  1567. * and `len - read` never overflow and that the copy is always
  1568. * in-bounds. */
  1569. unsafe {
  1570. let ptr = self.vec.as_mut_ptr();
  1571. let len = self.vec.len();
  1572. /* How many items were left when `same_bucket` panicked.
  1573. * Basically vec[read..].len() */
  1574. let items_left = len.wrapping_sub(self.read);
  1575. /* Pointer to first item in vec[write..write+items_left] slice */
  1576. let dropped_ptr = ptr.add(self.write);
  1577. /* Pointer to first item in vec[read..] slice */
  1578. let valid_ptr = ptr.add(self.read);
  1579. /* Copy `vec[read..]` to `vec[write..write+items_left]`.
  1580. * The slices can overlap, so `copy_nonoverlapping` cannot be used */
  1581. ptr::copy(valid_ptr, dropped_ptr, items_left);
  1582. /* How many items have been already dropped
  1583. * Basically vec[read..write].len() */
  1584. let dropped = self.read.wrapping_sub(self.write);
  1585. self.vec.set_len(len - dropped);
  1586. }
  1587. }
  1588. }
  1589. let mut gap = FillGapOnDrop { read: 1, write: 1, vec: self };
  1590. let ptr = gap.vec.as_mut_ptr();
  1591. /* Drop items while going through Vec, it should be more efficient than
  1592. * doing slice partition_dedup + truncate */
  1593. /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr
  1594. * are always in-bounds and read_ptr never aliases prev_ptr */
  1595. unsafe {
  1596. while gap.read < len {
  1597. let read_ptr = ptr.add(gap.read);
  1598. let prev_ptr = ptr.add(gap.write.wrapping_sub(1));
  1599. if same_bucket(&mut *read_ptr, &mut *prev_ptr) {
  1600. // Increase `gap.read` now since the drop may panic.
  1601. gap.read += 1;
  1602. /* We have found duplicate, drop it in-place */
  1603. ptr::drop_in_place(read_ptr);
  1604. } else {
  1605. let write_ptr = ptr.add(gap.write);
  1606. /* Because `read_ptr` can be equal to `write_ptr`, we either
  1607. * have to use `copy` or conditional `copy_nonoverlapping`.
  1608. * Looks like the first option is faster. */
  1609. ptr::copy(read_ptr, write_ptr, 1);
  1610. /* We have filled that place, so go further */
  1611. gap.write += 1;
  1612. gap.read += 1;
  1613. }
  1614. }
  1615. /* Technically we could let `gap` clean up with its Drop, but
  1616. * when `same_bucket` is guaranteed to not panic, this bloats a little
  1617. * the codegen, so we just do it manually */
  1618. gap.vec.set_len(gap.write);
  1619. mem::forget(gap);
  1620. }
  1621. }
  1622. /// Appends an element to the back of a collection.
  1623. ///
  1624. /// # Panics
  1625. ///
  1626. /// Panics if the new capacity exceeds `isize::MAX` bytes.
  1627. ///
  1628. /// # Examples
  1629. ///
  1630. /// ```
  1631. /// let mut vec = vec![1, 2];
  1632. /// vec.push(3);
  1633. /// assert_eq!(vec, [1, 2, 3]);
  1634. /// ```
  1635. #[cfg(not(no_global_oom_handling))]
  1636. #[inline]
  1637. #[stable(feature = "rust1", since = "1.0.0")]
  1638. pub fn push(&mut self, value: T) {
  1639. // This will panic or abort if we would allocate > isize::MAX bytes
  1640. // or if the length increment would overflow for zero-sized types.
  1641. if self.len == self.buf.capacity() {
  1642. self.buf.reserve_for_push(self.len);
  1643. }
  1644. unsafe {
  1645. let end = self.as_mut_ptr().add(self.len);
  1646. ptr::write(end, value);
  1647. self.len += 1;
  1648. }
  1649. }
  1650. /// Tries to append an element to the back of a collection.
  1651. ///
  1652. /// # Examples
  1653. ///
  1654. /// ```
  1655. /// let mut vec = vec![1, 2];
  1656. /// vec.try_push(3).unwrap();
  1657. /// assert_eq!(vec, [1, 2, 3]);
  1658. /// ```
  1659. #[inline]
  1660. #[stable(feature = "kernel", since = "1.0.0")]
  1661. pub fn try_push(&mut self, value: T) -> Result<(), TryReserveError> {
  1662. if self.len == self.buf.capacity() {
  1663. self.buf.try_reserve_for_push(self.len)?;
  1664. }
  1665. unsafe {
  1666. let end = self.as_mut_ptr().add(self.len);
  1667. ptr::write(end, value);
  1668. self.len += 1;
  1669. }
  1670. Ok(())
  1671. }
  1672. /// Removes the last element from a vector and returns it, or [`None`] if it
  1673. /// is empty.
  1674. ///
  1675. /// If you'd like to pop the first element, consider using
  1676. /// [`VecDeque::pop_front`] instead.
  1677. ///
  1678. /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
  1679. ///
  1680. /// # Examples
  1681. ///
  1682. /// ```
  1683. /// let mut vec = vec![1, 2, 3];
  1684. /// assert_eq!(vec.pop(), Some(3));
  1685. /// assert_eq!(vec, [1, 2]);
  1686. /// ```
  1687. #[inline]
  1688. #[stable(feature = "rust1", since = "1.0.0")]
  1689. pub fn pop(&mut self) -> Option<T> {
  1690. if self.len == 0 {
  1691. None
  1692. } else {
  1693. unsafe {
  1694. self.len -= 1;
  1695. Some(ptr::read(self.as_ptr().add(self.len())))
  1696. }
  1697. }
  1698. }
  1699. /// Moves all the elements of `other` into `self`, leaving `other` empty.
  1700. ///
  1701. /// # Panics
  1702. ///
  1703. /// Panics if the number of elements in the vector overflows a `usize`.
  1704. ///
  1705. /// # Examples
  1706. ///
  1707. /// ```
  1708. /// let mut vec = vec![1, 2, 3];
  1709. /// let mut vec2 = vec![4, 5, 6];
  1710. /// vec.append(&mut vec2);
  1711. /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
  1712. /// assert_eq!(vec2, []);
  1713. /// ```
  1714. #[cfg(not(no_global_oom_handling))]
  1715. #[inline]
  1716. #[stable(feature = "append", since = "1.4.0")]
  1717. pub fn append(&mut self, other: &mut Self) {
  1718. unsafe {
  1719. self.append_elements(other.as_slice() as _);
  1720. other.set_len(0);
  1721. }
  1722. }
  1723. /// Appends elements to `self` from other buffer.
  1724. #[cfg(not(no_global_oom_handling))]
  1725. #[inline]
  1726. unsafe fn append_elements(&mut self, other: *const [T]) {
  1727. let count = unsafe { (*other).len() };
  1728. self.reserve(count);
  1729. let len = self.len();
  1730. unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
  1731. self.len += count;
  1732. }
  1733. /// Removes the specified range from the vector in bulk, returning all
  1734. /// removed elements as an iterator. If the iterator is dropped before
  1735. /// being fully consumed, it drops the remaining removed elements.
  1736. ///
  1737. /// The returned iterator keeps a mutable borrow on the vector to optimize
  1738. /// its implementation.
  1739. ///
  1740. /// # Panics
  1741. ///
  1742. /// Panics if the starting point is greater than the end point or if
  1743. /// the end point is greater than the length of the vector.
  1744. ///
  1745. /// # Leaking
  1746. ///
  1747. /// If the returned iterator goes out of scope without being dropped (due to
  1748. /// [`mem::forget`], for example), the vector may have lost and leaked
  1749. /// elements arbitrarily, including elements outside the range.
  1750. ///
  1751. /// # Examples
  1752. ///
  1753. /// ```
  1754. /// let mut v = vec![1, 2, 3];
  1755. /// let u: Vec<_> = v.drain(1..).collect();
  1756. /// assert_eq!(v, &[1]);
  1757. /// assert_eq!(u, &[2, 3]);
  1758. ///
  1759. /// // A full range clears the vector, like `clear()` does
  1760. /// v.drain(..);
  1761. /// assert_eq!(v, &[]);
  1762. /// ```
  1763. #[stable(feature = "drain", since = "1.6.0")]
  1764. pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
  1765. where
  1766. R: RangeBounds<usize>,
  1767. {
  1768. // Memory safety
  1769. //
  1770. // When the Drain is first created, it shortens the length of
  1771. // the source vector to make sure no uninitialized or moved-from elements
  1772. // are accessible at all if the Drain's destructor never gets to run.
  1773. //
  1774. // Drain will ptr::read out the values to remove.
  1775. // When finished, remaining tail of the vec is copied back to cover
  1776. // the hole, and the vector length is restored to the new length.
  1777. //
  1778. let len = self.len();
  1779. let Range { start, end } = slice::range(range, ..len);
  1780. unsafe {
  1781. // set self.vec length's to start, to be safe in case Drain is leaked
  1782. self.set_len(start);
  1783. // Use the borrow in the IterMut to indicate borrowing behavior of the
  1784. // whole Drain iterator (like &mut T).
  1785. let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
  1786. Drain {
  1787. tail_start: end,
  1788. tail_len: len - end,
  1789. iter: range_slice.iter(),
  1790. vec: NonNull::from(self),
  1791. }
  1792. }
  1793. }
  1794. /// Clears the vector, removing all values.
  1795. ///
  1796. /// Note that this method has no effect on the allocated capacity
  1797. /// of the vector.
  1798. ///
  1799. /// # Examples
  1800. ///
  1801. /// ```
  1802. /// let mut v = vec![1, 2, 3];
  1803. ///
  1804. /// v.clear();
  1805. ///
  1806. /// assert!(v.is_empty());
  1807. /// ```
  1808. #[inline]
  1809. #[stable(feature = "rust1", since = "1.0.0")]
  1810. pub fn clear(&mut self) {
  1811. let elems: *mut [T] = self.as_mut_slice();
  1812. // SAFETY:
  1813. // - `elems` comes directly from `as_mut_slice` and is therefore valid.
  1814. // - Setting `self.len` before calling `drop_in_place` means that,
  1815. // if an element's `Drop` impl panics, the vector's `Drop` impl will
  1816. // do nothing (leaking the rest of the elements) instead of dropping
  1817. // some twice.
  1818. unsafe {
  1819. self.len = 0;
  1820. ptr::drop_in_place(elems);
  1821. }
  1822. }
  1823. /// Returns the number of elements in the vector, also referred to
  1824. /// as its 'length'.
  1825. ///
  1826. /// # Examples
  1827. ///
  1828. /// ```
  1829. /// let a = vec![1, 2, 3];
  1830. /// assert_eq!(a.len(), 3);
  1831. /// ```
  1832. #[inline]
  1833. #[stable(feature = "rust1", since = "1.0.0")]
  1834. pub fn len(&self) -> usize {
  1835. self.len
  1836. }
  1837. /// Returns `true` if the vector contains no elements.
  1838. ///
  1839. /// # Examples
  1840. ///
  1841. /// ```
  1842. /// let mut v = Vec::new();
  1843. /// assert!(v.is_empty());
  1844. ///
  1845. /// v.push(1);
  1846. /// assert!(!v.is_empty());
  1847. /// ```
  1848. #[stable(feature = "rust1", since = "1.0.0")]
  1849. pub fn is_empty(&self) -> bool {
  1850. self.len() == 0
  1851. }
  1852. /// Splits the collection into two at the given index.
  1853. ///
  1854. /// Returns a newly allocated vector containing the elements in the range
  1855. /// `[at, len)`. After the call, the original vector will be left containing
  1856. /// the elements `[0, at)` with its previous capacity unchanged.
  1857. ///
  1858. /// # Panics
  1859. ///
  1860. /// Panics if `at > len`.
  1861. ///
  1862. /// # Examples
  1863. ///
  1864. /// ```
  1865. /// let mut vec = vec![1, 2, 3];
  1866. /// let vec2 = vec.split_off(1);
  1867. /// assert_eq!(vec, [1]);
  1868. /// assert_eq!(vec2, [2, 3]);
  1869. /// ```
  1870. #[cfg(not(no_global_oom_handling))]
  1871. #[inline]
  1872. #[must_use = "use `.truncate()` if you don't need the other half"]
  1873. #[stable(feature = "split_off", since = "1.4.0")]
  1874. pub fn split_off(&mut self, at: usize) -> Self
  1875. where
  1876. A: Clone,
  1877. {
  1878. #[cold]
  1879. #[inline(never)]
  1880. fn assert_failed(at: usize, len: usize) -> ! {
  1881. panic!("`at` split index (is {at}) should be <= len (is {len})");
  1882. }
  1883. if at > self.len() {
  1884. assert_failed(at, self.len());
  1885. }
  1886. if at == 0 {
  1887. // the new vector can take over the original buffer and avoid the copy
  1888. return mem::replace(
  1889. self,
  1890. Vec::with_capacity_in(self.capacity(), self.allocator().clone()),
  1891. );
  1892. }
  1893. let other_len = self.len - at;
  1894. let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());
  1895. // Unsafely `set_len` and copy items to `other`.
  1896. unsafe {
  1897. self.set_len(at);
  1898. other.set_len(other_len);
  1899. ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
  1900. }
  1901. other
  1902. }
  1903. /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
  1904. ///
  1905. /// If `new_len` is greater than `len`, the `Vec` is extended by the
  1906. /// difference, with each additional slot filled with the result of
  1907. /// calling the closure `f`. The return values from `f` will end up
  1908. /// in the `Vec` in the order they have been generated.
  1909. ///
  1910. /// If `new_len` is less than `len`, the `Vec` is simply truncated.
  1911. ///
  1912. /// This method uses a closure to create new values on every push. If
  1913. /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
  1914. /// want to use the [`Default`] trait to generate values, you can
  1915. /// pass [`Default::default`] as the second argument.
  1916. ///
  1917. /// # Examples
  1918. ///
  1919. /// ```
  1920. /// let mut vec = vec![1, 2, 3];
  1921. /// vec.resize_with(5, Default::default);
  1922. /// assert_eq!(vec, [1, 2, 3, 0, 0]);
  1923. ///
  1924. /// let mut vec = vec![];
  1925. /// let mut p = 1;
  1926. /// vec.resize_with(4, || { p *= 2; p });
  1927. /// assert_eq!(vec, [2, 4, 8, 16]);
  1928. /// ```
  1929. #[cfg(not(no_global_oom_handling))]
  1930. #[stable(feature = "vec_resize_with", since = "1.33.0")]
  1931. pub fn resize_with<F>(&mut self, new_len: usize, f: F)
  1932. where
  1933. F: FnMut() -> T,
  1934. {
  1935. let len = self.len();
  1936. if new_len > len {
  1937. self.extend_with(new_len - len, ExtendFunc(f));
  1938. } else {
  1939. self.truncate(new_len);
  1940. }
  1941. }
  1942. /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
  1943. /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
  1944. /// `'a`. If the type has only static references, or none at all, then this
  1945. /// may be chosen to be `'static`.
  1946. ///
  1947. /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`,
  1948. /// so the leaked allocation may include unused capacity that is not part
  1949. /// of the returned slice.
  1950. ///
  1951. /// This function is mainly useful for data that lives for the remainder of
  1952. /// the program's life. Dropping the returned reference will cause a memory
  1953. /// leak.
  1954. ///
  1955. /// # Examples
  1956. ///
  1957. /// Simple usage:
  1958. ///
  1959. /// ```
  1960. /// let x = vec![1, 2, 3];
  1961. /// let static_ref: &'static mut [usize] = x.leak();
  1962. /// static_ref[0] += 1;
  1963. /// assert_eq!(static_ref, &[2, 2, 3]);
  1964. /// ```
  1965. #[cfg(not(no_global_oom_handling))]
  1966. #[stable(feature = "vec_leak", since = "1.47.0")]
  1967. #[inline]
  1968. pub fn leak<'a>(self) -> &'a mut [T]
  1969. where
  1970. A: 'a,
  1971. {
  1972. let mut me = ManuallyDrop::new(self);
  1973. unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) }
  1974. }
  1975. /// Returns the remaining spare capacity of the vector as a slice of
  1976. /// `MaybeUninit<T>`.
  1977. ///
  1978. /// The returned slice can be used to fill the vector with data (e.g. by
  1979. /// reading from a file) before marking the data as initialized using the
  1980. /// [`set_len`] method.
  1981. ///
  1982. /// [`set_len`]: Vec::set_len
  1983. ///
  1984. /// # Examples
  1985. ///
  1986. /// ```
  1987. /// // Allocate vector big enough for 10 elements.
  1988. /// let mut v = Vec::with_capacity(10);
  1989. ///
  1990. /// // Fill in the first 3 elements.
  1991. /// let uninit = v.spare_capacity_mut();
  1992. /// uninit[0].write(0);
  1993. /// uninit[1].write(1);
  1994. /// uninit[2].write(2);
  1995. ///
  1996. /// // Mark the first 3 elements of the vector as being initialized.
  1997. /// unsafe {
  1998. /// v.set_len(3);
  1999. /// }
  2000. ///
  2001. /// assert_eq!(&v, &[0, 1, 2]);
  2002. /// ```
  2003. #[stable(feature = "vec_spare_capacity", since = "1.60.0")]
  2004. #[inline]
  2005. pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
  2006. // Note:
  2007. // This method is not implemented in terms of `split_at_spare_mut`,
  2008. // to prevent invalidation of pointers to the buffer.
  2009. unsafe {
  2010. slice::from_raw_parts_mut(
  2011. self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
  2012. self.buf.capacity() - self.len,
  2013. )
  2014. }
  2015. }
  2016. /// Returns vector content as a slice of `T`, along with the remaining spare
  2017. /// capacity of the vector as a slice of `MaybeUninit<T>`.
  2018. ///
  2019. /// The returned spare capacity slice can be used to fill the vector with data
  2020. /// (e.g. by reading from a file) before marking the data as initialized using
  2021. /// the [`set_len`] method.
  2022. ///
  2023. /// [`set_len`]: Vec::set_len
  2024. ///
  2025. /// Note that this is a low-level API, which should be used with care for
  2026. /// optimization purposes. If you need to append data to a `Vec`
  2027. /// you can use [`push`], [`extend`], [`extend_from_slice`],
  2028. /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or
  2029. /// [`resize_with`], depending on your exact needs.
  2030. ///
  2031. /// [`push`]: Vec::push
  2032. /// [`extend`]: Vec::extend
  2033. /// [`extend_from_slice`]: Vec::extend_from_slice
  2034. /// [`extend_from_within`]: Vec::extend_from_within
  2035. /// [`insert`]: Vec::insert
  2036. /// [`append`]: Vec::append
  2037. /// [`resize`]: Vec::resize
  2038. /// [`resize_with`]: Vec::resize_with
  2039. ///
  2040. /// # Examples
  2041. ///
  2042. /// ```
  2043. /// #![feature(vec_split_at_spare)]
  2044. ///
  2045. /// let mut v = vec![1, 1, 2];
  2046. ///
  2047. /// // Reserve additional space big enough for 10 elements.
  2048. /// v.reserve(10);
  2049. ///
  2050. /// let (init, uninit) = v.split_at_spare_mut();
  2051. /// let sum = init.iter().copied().sum::<u32>();
  2052. ///
  2053. /// // Fill in the next 4 elements.
  2054. /// uninit[0].write(sum);
  2055. /// uninit[1].write(sum * 2);
  2056. /// uninit[2].write(sum * 3);
  2057. /// uninit[3].write(sum * 4);
  2058. ///
  2059. /// // Mark the 4 elements of the vector as being initialized.
  2060. /// unsafe {
  2061. /// let len = v.len();
  2062. /// v.set_len(len + 4);
  2063. /// }
  2064. ///
  2065. /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
  2066. /// ```
  2067. #[unstable(feature = "vec_split_at_spare", issue = "81944")]
  2068. #[inline]
  2069. pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
  2070. // SAFETY:
  2071. // - len is ignored and so never changed
  2072. let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() };
  2073. (init, spare)
  2074. }
  2075. /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`.
  2076. ///
  2077. /// This method provides unique access to all vec parts at once in `extend_from_within`.
  2078. unsafe fn split_at_spare_mut_with_len(
  2079. &mut self,
  2080. ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) {
  2081. let ptr = self.as_mut_ptr();
  2082. // SAFETY:
  2083. // - `ptr` is guaranteed to be valid for `self.len` elements
  2084. // - but the allocation extends out to `self.buf.capacity()` elements, possibly
  2085. // uninitialized
  2086. let spare_ptr = unsafe { ptr.add(self.len) };
  2087. let spare_ptr = spare_ptr.cast::<MaybeUninit<T>>();
  2088. let spare_len = self.buf.capacity() - self.len;
  2089. // SAFETY:
  2090. // - `ptr` is guaranteed to be valid for `self.len` elements
  2091. // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized`
  2092. unsafe {
  2093. let initialized = slice::from_raw_parts_mut(ptr, self.len);
  2094. let spare = slice::from_raw_parts_mut(spare_ptr, spare_len);
  2095. (initialized, spare, &mut self.len)
  2096. }
  2097. }
  2098. }
  2099. impl<T: Clone, A: Allocator> Vec<T, A> {
  2100. /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
  2101. ///
  2102. /// If `new_len` is greater than `len`, the `Vec` is extended by the
  2103. /// difference, with each additional slot filled with `value`.
  2104. /// If `new_len` is less than `len`, the `Vec` is simply truncated.
  2105. ///
  2106. /// This method requires `T` to implement [`Clone`],
  2107. /// in order to be able to clone the passed value.
  2108. /// If you need more flexibility (or want to rely on [`Default`] instead of
  2109. /// [`Clone`]), use [`Vec::resize_with`].
  2110. /// If you only need to resize to a smaller size, use [`Vec::truncate`].
  2111. ///
  2112. /// # Examples
  2113. ///
  2114. /// ```
  2115. /// let mut vec = vec!["hello"];
  2116. /// vec.resize(3, "world");
  2117. /// assert_eq!(vec, ["hello", "world", "world"]);
  2118. ///
  2119. /// let mut vec = vec![1, 2, 3, 4];
  2120. /// vec.resize(2, 0);
  2121. /// assert_eq!(vec, [1, 2]);
  2122. /// ```
  2123. #[cfg(not(no_global_oom_handling))]
  2124. #[stable(feature = "vec_resize", since = "1.5.0")]
  2125. pub fn resize(&mut self, new_len: usize, value: T) {
  2126. let len = self.len();
  2127. if new_len > len {
  2128. self.extend_with(new_len - len, ExtendElement(value))
  2129. } else {
  2130. self.truncate(new_len);
  2131. }
  2132. }
  2133. /// Clones and appends all elements in a slice to the `Vec`.
  2134. ///
  2135. /// Iterates over the slice `other`, clones each element, and then appends
  2136. /// it to this `Vec`. The `other` slice is traversed in-order.
  2137. ///
  2138. /// Note that this function is same as [`extend`] except that it is
  2139. /// specialized to work with slices instead. If and when Rust gets
  2140. /// specialization this function will likely be deprecated (but still
  2141. /// available).
  2142. ///
  2143. /// # Examples
  2144. ///
  2145. /// ```
  2146. /// let mut vec = vec![1];
  2147. /// vec.extend_from_slice(&[2, 3, 4]);
  2148. /// assert_eq!(vec, [1, 2, 3, 4]);
  2149. /// ```
  2150. ///
  2151. /// [`extend`]: Vec::extend
  2152. #[cfg(not(no_global_oom_handling))]
  2153. #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
  2154. pub fn extend_from_slice(&mut self, other: &[T]) {
  2155. self.spec_extend(other.iter())
  2156. }
  2157. /// Copies elements from `src` range to the end of the vector.
  2158. ///
  2159. /// # Panics
  2160. ///
  2161. /// Panics if the starting point is greater than the end point or if
  2162. /// the end point is greater than the length of the vector.
  2163. ///
  2164. /// # Examples
  2165. ///
  2166. /// ```
  2167. /// let mut vec = vec![0, 1, 2, 3, 4];
  2168. ///
  2169. /// vec.extend_from_within(2..);
  2170. /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);
  2171. ///
  2172. /// vec.extend_from_within(..2);
  2173. /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);
  2174. ///
  2175. /// vec.extend_from_within(4..8);
  2176. /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
  2177. /// ```
  2178. #[cfg(not(no_global_oom_handling))]
  2179. #[stable(feature = "vec_extend_from_within", since = "1.53.0")]
  2180. pub fn extend_from_within<R>(&mut self, src: R)
  2181. where
  2182. R: RangeBounds<usize>,
  2183. {
  2184. let range = slice::range(src, ..self.len());
  2185. self.reserve(range.len());
  2186. // SAFETY:
  2187. // - `slice::range` guarantees that the given range is valid for indexing self
  2188. unsafe {
  2189. self.spec_extend_from_within(range);
  2190. }
  2191. }
  2192. }
  2193. impl<T, A: Allocator, const N: usize> Vec<[T; N], A> {
  2194. /// Takes a `Vec<[T; N]>` and flattens it into a `Vec<T>`.
  2195. ///
  2196. /// # Panics
  2197. ///
  2198. /// Panics if the length of the resulting vector would overflow a `usize`.
  2199. ///
  2200. /// This is only possible when flattening a vector of arrays of zero-sized
  2201. /// types, and thus tends to be irrelevant in practice. If
  2202. /// `size_of::<T>() > 0`, this will never panic.
  2203. ///
  2204. /// # Examples
  2205. ///
  2206. /// ```
  2207. /// #![feature(slice_flatten)]
  2208. ///
  2209. /// let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
  2210. /// assert_eq!(vec.pop(), Some([7, 8, 9]));
  2211. ///
  2212. /// let mut flattened = vec.into_flattened();
  2213. /// assert_eq!(flattened.pop(), Some(6));
  2214. /// ```
  2215. #[unstable(feature = "slice_flatten", issue = "95629")]
  2216. pub fn into_flattened(self) -> Vec<T, A> {
  2217. let (ptr, len, cap, alloc) = self.into_raw_parts_with_alloc();
  2218. let (new_len, new_cap) = if mem::size_of::<T>() == 0 {
  2219. (len.checked_mul(N).expect("vec len overflow"), usize::MAX)
  2220. } else {
  2221. // SAFETY:
  2222. // - `cap * N` cannot overflow because the allocation is already in
  2223. // the address space.
  2224. // - Each `[T; N]` has `N` valid elements, so there are `len * N`
  2225. // valid elements in the allocation.
  2226. unsafe { (len.unchecked_mul(N), cap.unchecked_mul(N)) }
  2227. };
  2228. // SAFETY:
  2229. // - `ptr` was allocated by `self`
  2230. // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`.
  2231. // - `new_cap` refers to the same sized allocation as `cap` because
  2232. // `new_cap * size_of::<T>()` == `cap * size_of::<[T; N]>()`
  2233. // - `len` <= `cap`, so `len * N` <= `cap * N`.
  2234. unsafe { Vec::<T, A>::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) }
  2235. }
  2236. }
  2237. // This code generalizes `extend_with_{element,default}`.
  2238. trait ExtendWith<T> {
  2239. fn next(&mut self) -> T;
  2240. fn last(self) -> T;
  2241. }
  2242. struct ExtendElement<T>(T);
  2243. impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
  2244. fn next(&mut self) -> T {
  2245. self.0.clone()
  2246. }
  2247. fn last(self) -> T {
  2248. self.0
  2249. }
  2250. }
  2251. struct ExtendFunc<F>(F);
  2252. impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
  2253. fn next(&mut self) -> T {
  2254. (self.0)()
  2255. }
  2256. fn last(mut self) -> T {
  2257. (self.0)()
  2258. }
  2259. }
  2260. impl<T, A: Allocator> Vec<T, A> {
  2261. #[cfg(not(no_global_oom_handling))]
  2262. /// Extend the vector by `n` values, using the given generator.
  2263. fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
  2264. self.reserve(n);
  2265. unsafe {
  2266. let mut ptr = self.as_mut_ptr().add(self.len());
  2267. // Use SetLenOnDrop to work around bug where compiler
  2268. // might not realize the store through `ptr` through self.set_len()
  2269. // don't alias.
  2270. let mut local_len = SetLenOnDrop::new(&mut self.len);
  2271. // Write all elements except the last one
  2272. for _ in 1..n {
  2273. ptr::write(ptr, value.next());
  2274. ptr = ptr.offset(1);
  2275. // Increment the length in every step in case next() panics
  2276. local_len.increment_len(1);
  2277. }
  2278. if n > 0 {
  2279. // We can write the last element directly without cloning needlessly
  2280. ptr::write(ptr, value.last());
  2281. local_len.increment_len(1);
  2282. }
  2283. // len set by scope guard
  2284. }
  2285. }
  2286. }
  2287. impl<T: PartialEq, A: Allocator> Vec<T, A> {
  2288. /// Removes consecutive repeated elements in the vector according to the
  2289. /// [`PartialEq`] trait implementation.
  2290. ///
  2291. /// If the vector is sorted, this removes all duplicates.
  2292. ///
  2293. /// # Examples
  2294. ///
  2295. /// ```
  2296. /// let mut vec = vec![1, 2, 2, 3, 2];
  2297. ///
  2298. /// vec.dedup();
  2299. ///
  2300. /// assert_eq!(vec, [1, 2, 3, 2]);
  2301. /// ```
  2302. #[stable(feature = "rust1", since = "1.0.0")]
  2303. #[inline]
  2304. pub fn dedup(&mut self) {
  2305. self.dedup_by(|a, b| a == b)
  2306. }
  2307. }
  2308. ////////////////////////////////////////////////////////////////////////////////
  2309. // Internal methods and functions
  2310. ////////////////////////////////////////////////////////////////////////////////
  2311. #[doc(hidden)]
  2312. #[cfg(not(no_global_oom_handling))]
  2313. #[stable(feature = "rust1", since = "1.0.0")]
  2314. pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
  2315. <T as SpecFromElem>::from_elem(elem, n, Global)
  2316. }
  2317. #[doc(hidden)]
  2318. #[cfg(not(no_global_oom_handling))]
  2319. #[unstable(feature = "allocator_api", issue = "32838")]
  2320. pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
  2321. <T as SpecFromElem>::from_elem(elem, n, alloc)
  2322. }
  2323. trait ExtendFromWithinSpec {
  2324. /// # Safety
  2325. ///
  2326. /// - `src` needs to be valid index
  2327. /// - `self.capacity() - self.len()` must be `>= src.len()`
  2328. unsafe fn spec_extend_from_within(&mut self, src: Range<usize>);
  2329. }
  2330. impl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
  2331. default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
  2332. // SAFETY:
  2333. // - len is increased only after initializing elements
  2334. let (this, spare, len) = unsafe { self.split_at_spare_mut_with_len() };
  2335. // SAFETY:
  2336. // - caller guaratees that src is a valid index
  2337. let to_clone = unsafe { this.get_unchecked(src) };
  2338. iter::zip(to_clone, spare)
  2339. .map(|(src, dst)| dst.write(src.clone()))
  2340. // Note:
  2341. // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len
  2342. // - len is increased after each element to prevent leaks (see issue #82533)
  2343. .for_each(|_| *len += 1);
  2344. }
  2345. }
  2346. impl<T: Copy, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
  2347. unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
  2348. let count = src.len();
  2349. {
  2350. let (init, spare) = self.split_at_spare_mut();
  2351. // SAFETY:
  2352. // - caller guaratees that `src` is a valid index
  2353. let source = unsafe { init.get_unchecked(src) };
  2354. // SAFETY:
  2355. // - Both pointers are created from unique slice references (`&mut [_]`)
  2356. // so they are valid and do not overlap.
  2357. // - Elements are :Copy so it's OK to to copy them, without doing
  2358. // anything with the original values
  2359. // - `count` is equal to the len of `source`, so source is valid for
  2360. // `count` reads
  2361. // - `.reserve(count)` guarantees that `spare.len() >= count` so spare
  2362. // is valid for `count` writes
  2363. unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) };
  2364. }
  2365. // SAFETY:
  2366. // - The elements were just initialized by `copy_nonoverlapping`
  2367. self.len += count;
  2368. }
  2369. }
  2370. ////////////////////////////////////////////////////////////////////////////////
  2371. // Common trait implementations for Vec
  2372. ////////////////////////////////////////////////////////////////////////////////
  2373. #[stable(feature = "rust1", since = "1.0.0")]
  2374. impl<T, A: Allocator> ops::Deref for Vec<T, A> {
  2375. type Target = [T];
  2376. fn deref(&self) -> &[T] {
  2377. unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
  2378. }
  2379. }
  2380. #[stable(feature = "rust1", since = "1.0.0")]
  2381. impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
  2382. fn deref_mut(&mut self) -> &mut [T] {
  2383. unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
  2384. }
  2385. }
  2386. #[cfg(not(no_global_oom_handling))]
  2387. trait SpecCloneFrom {
  2388. fn clone_from(this: &mut Self, other: &Self);
  2389. }
  2390. #[cfg(not(no_global_oom_handling))]
  2391. impl<T: Clone, A: Allocator> SpecCloneFrom for Vec<T, A> {
  2392. default fn clone_from(this: &mut Self, other: &Self) {
  2393. // drop anything that will not be overwritten
  2394. this.truncate(other.len());
  2395. // self.len <= other.len due to the truncate above, so the
  2396. // slices here are always in-bounds.
  2397. let (init, tail) = other.split_at(this.len());
  2398. // reuse the contained values' allocations/resources.
  2399. this.clone_from_slice(init);
  2400. this.extend_from_slice(tail);
  2401. }
  2402. }
  2403. #[cfg(not(no_global_oom_handling))]
  2404. impl<T: Copy, A: Allocator> SpecCloneFrom for Vec<T, A> {
  2405. fn clone_from(this: &mut Self, other: &Self) {
  2406. this.clear();
  2407. this.extend_from_slice(other);
  2408. }
  2409. }
  2410. #[cfg(not(no_global_oom_handling))]
  2411. #[stable(feature = "rust1", since = "1.0.0")]
  2412. impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
  2413. #[cfg(not(test))]
  2414. fn clone(&self) -> Self {
  2415. let alloc = self.allocator().clone();
  2416. <[T]>::to_vec_in(&**self, alloc)
  2417. }
  2418. // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
  2419. // required for this method definition, is not available. Instead use the
  2420. // `slice::to_vec` function which is only available with cfg(test)
  2421. // NB see the slice::hack module in slice.rs for more information
  2422. #[cfg(test)]
  2423. fn clone(&self) -> Self {
  2424. let alloc = self.allocator().clone();
  2425. crate::slice::to_vec(&**self, alloc)
  2426. }
  2427. fn clone_from(&mut self, other: &Self) {
  2428. SpecCloneFrom::clone_from(self, other)
  2429. }
  2430. }
  2431. /// The hash of a vector is the same as that of the corresponding slice,
  2432. /// as required by the `core::borrow::Borrow` implementation.
  2433. ///
  2434. /// ```
  2435. /// #![feature(build_hasher_simple_hash_one)]
  2436. /// use std::hash::BuildHasher;
  2437. ///
  2438. /// let b = std::collections::hash_map::RandomState::new();
  2439. /// let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
  2440. /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
  2441. /// assert_eq!(b.hash_one(v), b.hash_one(s));
  2442. /// ```
  2443. #[stable(feature = "rust1", since = "1.0.0")]
  2444. impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
  2445. #[inline]
  2446. fn hash<H: Hasher>(&self, state: &mut H) {
  2447. Hash::hash(&**self, state)
  2448. }
  2449. }
  2450. #[stable(feature = "rust1", since = "1.0.0")]
  2451. #[rustc_on_unimplemented(
  2452. message = "vector indices are of type `usize` or ranges of `usize`",
  2453. label = "vector indices are of type `usize` or ranges of `usize`"
  2454. )]
  2455. impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
  2456. type Output = I::Output;
  2457. #[inline]
  2458. fn index(&self, index: I) -> &Self::Output {
  2459. Index::index(&**self, index)
  2460. }
  2461. }
  2462. #[stable(feature = "rust1", since = "1.0.0")]
  2463. #[rustc_on_unimplemented(
  2464. message = "vector indices are of type `usize` or ranges of `usize`",
  2465. label = "vector indices are of type `usize` or ranges of `usize`"
  2466. )]
  2467. impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
  2468. #[inline]
  2469. fn index_mut(&mut self, index: I) -> &mut Self::Output {
  2470. IndexMut::index_mut(&mut **self, index)
  2471. }
  2472. }
  2473. #[cfg(not(no_global_oom_handling))]
  2474. #[stable(feature = "rust1", since = "1.0.0")]
  2475. impl<T> FromIterator<T> for Vec<T> {
  2476. #[inline]
  2477. fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
  2478. <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter())
  2479. }
  2480. }
  2481. #[stable(feature = "rust1", since = "1.0.0")]
  2482. impl<T, A: Allocator> IntoIterator for Vec<T, A> {
  2483. type Item = T;
  2484. type IntoIter = IntoIter<T, A>;
  2485. /// Creates a consuming iterator, that is, one that moves each value out of
  2486. /// the vector (from start to end). The vector cannot be used after calling
  2487. /// this.
  2488. ///
  2489. /// # Examples
  2490. ///
  2491. /// ```
  2492. /// let v = vec!["a".to_string(), "b".to_string()];
  2493. /// for s in v.into_iter() {
  2494. /// // s has type String, not &String
  2495. /// println!("{s}");
  2496. /// }
  2497. /// ```
  2498. #[inline]
  2499. fn into_iter(self) -> IntoIter<T, A> {
  2500. unsafe {
  2501. let mut me = ManuallyDrop::new(self);
  2502. let alloc = ManuallyDrop::new(ptr::read(me.allocator()));
  2503. let begin = me.as_mut_ptr();
  2504. let end = if mem::size_of::<T>() == 0 {
  2505. arith_offset(begin as *const i8, me.len() as isize) as *const T
  2506. } else {
  2507. begin.add(me.len()) as *const T
  2508. };
  2509. let cap = me.buf.capacity();
  2510. IntoIter {
  2511. buf: NonNull::new_unchecked(begin),
  2512. phantom: PhantomData,
  2513. cap,
  2514. alloc,
  2515. ptr: begin,
  2516. end,
  2517. }
  2518. }
  2519. }
  2520. }
  2521. #[stable(feature = "rust1", since = "1.0.0")]
  2522. impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
  2523. type Item = &'a T;
  2524. type IntoIter = slice::Iter<'a, T>;
  2525. fn into_iter(self) -> slice::Iter<'a, T> {
  2526. self.iter()
  2527. }
  2528. }
  2529. #[stable(feature = "rust1", since = "1.0.0")]
  2530. impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
  2531. type Item = &'a mut T;
  2532. type IntoIter = slice::IterMut<'a, T>;
  2533. fn into_iter(self) -> slice::IterMut<'a, T> {
  2534. self.iter_mut()
  2535. }
  2536. }
  2537. #[cfg(not(no_global_oom_handling))]
  2538. #[stable(feature = "rust1", since = "1.0.0")]
  2539. impl<T, A: Allocator> Extend<T> for Vec<T, A> {
  2540. #[inline]
  2541. fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
  2542. <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
  2543. }
  2544. #[inline]
  2545. fn extend_one(&mut self, item: T) {
  2546. self.push(item);
  2547. }
  2548. #[inline]
  2549. fn extend_reserve(&mut self, additional: usize) {
  2550. self.reserve(additional);
  2551. }
  2552. }
  2553. impl<T, A: Allocator> Vec<T, A> {
  2554. // leaf method to which various SpecFrom/SpecExtend implementations delegate when
  2555. // they have no further optimizations to apply
  2556. #[cfg(not(no_global_oom_handling))]
  2557. fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
  2558. // This is the case for a general iterator.
  2559. //
  2560. // This function should be the moral equivalent of:
  2561. //
  2562. // for item in iterator {
  2563. // self.push(item);
  2564. // }
  2565. while let Some(element) = iterator.next() {
  2566. let len = self.len();
  2567. if len == self.capacity() {
  2568. let (lower, _) = iterator.size_hint();
  2569. self.reserve(lower.saturating_add(1));
  2570. }
  2571. unsafe {
  2572. ptr::write(self.as_mut_ptr().add(len), element);
  2573. // Since next() executes user code which can panic we have to bump the length
  2574. // after each step.
  2575. // NB can't overflow since we would have had to alloc the address space
  2576. self.set_len(len + 1);
  2577. }
  2578. }
  2579. }
  2580. /// Creates a splicing iterator that replaces the specified range in the vector
  2581. /// with the given `replace_with` iterator and yields the removed items.
  2582. /// `replace_with` does not need to be the same length as `range`.
  2583. ///
  2584. /// `range` is removed even if the iterator is not consumed until the end.
  2585. ///
  2586. /// It is unspecified how many elements are removed from the vector
  2587. /// if the `Splice` value is leaked.
  2588. ///
  2589. /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
  2590. ///
  2591. /// This is optimal if:
  2592. ///
  2593. /// * The tail (elements in the vector after `range`) is empty,
  2594. /// * or `replace_with` yields fewer or equal elements than `range`’s length
  2595. /// * or the lower bound of its `size_hint()` is exact.
  2596. ///
  2597. /// Otherwise, a temporary vector is allocated and the tail is moved twice.
  2598. ///
  2599. /// # Panics
  2600. ///
  2601. /// Panics if the starting point is greater than the end point or if
  2602. /// the end point is greater than the length of the vector.
  2603. ///
  2604. /// # Examples
  2605. ///
  2606. /// ```
  2607. /// let mut v = vec![1, 2, 3, 4];
  2608. /// let new = [7, 8, 9];
  2609. /// let u: Vec<_> = v.splice(1..3, new).collect();
  2610. /// assert_eq!(v, &[1, 7, 8, 9, 4]);
  2611. /// assert_eq!(u, &[2, 3]);
  2612. /// ```
  2613. #[cfg(not(no_global_oom_handling))]
  2614. #[inline]
  2615. #[stable(feature = "vec_splice", since = "1.21.0")]
  2616. pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
  2617. where
  2618. R: RangeBounds<usize>,
  2619. I: IntoIterator<Item = T>,
  2620. {
  2621. Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
  2622. }
  2623. /// Creates an iterator which uses a closure to determine if an element should be removed.
  2624. ///
  2625. /// If the closure returns true, then the element is removed and yielded.
  2626. /// If the closure returns false, the element will remain in the vector and will not be yielded
  2627. /// by the iterator.
  2628. ///
  2629. /// Using this method is equivalent to the following code:
  2630. ///
  2631. /// ```
  2632. /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
  2633. /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
  2634. /// let mut i = 0;
  2635. /// while i < vec.len() {
  2636. /// if some_predicate(&mut vec[i]) {
  2637. /// let val = vec.remove(i);
  2638. /// // your code here
  2639. /// } else {
  2640. /// i += 1;
  2641. /// }
  2642. /// }
  2643. ///
  2644. /// # assert_eq!(vec, vec![1, 4, 5]);
  2645. /// ```
  2646. ///
  2647. /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
  2648. /// because it can backshift the elements of the array in bulk.
  2649. ///
  2650. /// Note that `drain_filter` also lets you mutate every element in the filter closure,
  2651. /// regardless of whether you choose to keep or remove it.
  2652. ///
  2653. /// # Examples
  2654. ///
  2655. /// Splitting an array into evens and odds, reusing the original allocation:
  2656. ///
  2657. /// ```
  2658. /// #![feature(drain_filter)]
  2659. /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
  2660. ///
  2661. /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
  2662. /// let odds = numbers;
  2663. ///
  2664. /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
  2665. /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
  2666. /// ```
  2667. #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
  2668. pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F, A>
  2669. where
  2670. F: FnMut(&mut T) -> bool,
  2671. {
  2672. let old_len = self.len();
  2673. // Guard against us getting leaked (leak amplification)
  2674. unsafe {
  2675. self.set_len(0);
  2676. }
  2677. DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
  2678. }
  2679. }
  2680. /// Extend implementation that copies elements out of references before pushing them onto the Vec.
  2681. ///
  2682. /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
  2683. /// append the entire slice at once.
  2684. ///
  2685. /// [`copy_from_slice`]: slice::copy_from_slice
  2686. #[cfg(not(no_global_oom_handling))]
  2687. #[stable(feature = "extend_ref", since = "1.2.0")]
  2688. impl<'a, T: Copy + 'a, A: Allocator + 'a> Extend<&'a T> for Vec<T, A> {
  2689. fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
  2690. self.spec_extend(iter.into_iter())
  2691. }
  2692. #[inline]
  2693. fn extend_one(&mut self, &item: &'a T) {
  2694. self.push(item);
  2695. }
  2696. #[inline]
  2697. fn extend_reserve(&mut self, additional: usize) {
  2698. self.reserve(additional);
  2699. }
  2700. }
  2701. /// Implements comparison of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
  2702. #[stable(feature = "rust1", since = "1.0.0")]
  2703. impl<T: PartialOrd, A: Allocator> PartialOrd for Vec<T, A> {
  2704. #[inline]
  2705. fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
  2706. PartialOrd::partial_cmp(&**self, &**other)
  2707. }
  2708. }
  2709. #[stable(feature = "rust1", since = "1.0.0")]
  2710. impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
  2711. /// Implements ordering of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
  2712. #[stable(feature = "rust1", since = "1.0.0")]
  2713. impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
  2714. #[inline]
  2715. fn cmp(&self, other: &Self) -> Ordering {
  2716. Ord::cmp(&**self, &**other)
  2717. }
  2718. }
  2719. #[stable(feature = "rust1", since = "1.0.0")]
  2720. unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec<T, A> {
  2721. fn drop(&mut self) {
  2722. unsafe {
  2723. // use drop for [T]
  2724. // use a raw slice to refer to the elements of the vector as weakest necessary type;
  2725. // could avoid questions of validity in certain cases
  2726. ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
  2727. }
  2728. // RawVec handles deallocation
  2729. }
  2730. }
  2731. #[stable(feature = "rust1", since = "1.0.0")]
  2732. #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
  2733. impl<T> const Default for Vec<T> {
  2734. /// Creates an empty `Vec<T>`.
  2735. fn default() -> Vec<T> {
  2736. Vec::new()
  2737. }
  2738. }
  2739. #[stable(feature = "rust1", since = "1.0.0")]
  2740. impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
  2741. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  2742. fmt::Debug::fmt(&**self, f)
  2743. }
  2744. }
  2745. #[stable(feature = "rust1", since = "1.0.0")]
  2746. impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
  2747. fn as_ref(&self) -> &Vec<T, A> {
  2748. self
  2749. }
  2750. }
  2751. #[stable(feature = "vec_as_mut", since = "1.5.0")]
  2752. impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
  2753. fn as_mut(&mut self) -> &mut Vec<T, A> {
  2754. self
  2755. }
  2756. }
  2757. #[stable(feature = "rust1", since = "1.0.0")]
  2758. impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
  2759. fn as_ref(&self) -> &[T] {
  2760. self
  2761. }
  2762. }
  2763. #[stable(feature = "vec_as_mut", since = "1.5.0")]
  2764. impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
  2765. fn as_mut(&mut self) -> &mut [T] {
  2766. self
  2767. }
  2768. }
  2769. #[cfg(not(no_global_oom_handling))]
  2770. #[stable(feature = "rust1", since = "1.0.0")]
  2771. impl<T: Clone> From<&[T]> for Vec<T> {
  2772. /// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
  2773. ///
  2774. /// # Examples
  2775. ///
  2776. /// ```
  2777. /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);
  2778. /// ```
  2779. #[cfg(not(test))]
  2780. fn from(s: &[T]) -> Vec<T> {
  2781. s.to_vec()
  2782. }
  2783. #[cfg(test)]
  2784. fn from(s: &[T]) -> Vec<T> {
  2785. crate::slice::to_vec(s, Global)
  2786. }
  2787. }
  2788. #[cfg(not(no_global_oom_handling))]
  2789. #[stable(feature = "vec_from_mut", since = "1.19.0")]
  2790. impl<T: Clone> From<&mut [T]> for Vec<T> {
  2791. /// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
  2792. ///
  2793. /// # Examples
  2794. ///
  2795. /// ```
  2796. /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);
  2797. /// ```
  2798. #[cfg(not(test))]
  2799. fn from(s: &mut [T]) -> Vec<T> {
  2800. s.to_vec()
  2801. }
  2802. #[cfg(test)]
  2803. fn from(s: &mut [T]) -> Vec<T> {
  2804. crate::slice::to_vec(s, Global)
  2805. }
  2806. }
  2807. #[cfg(not(no_global_oom_handling))]
  2808. #[stable(feature = "vec_from_array", since = "1.44.0")]
  2809. impl<T, const N: usize> From<[T; N]> for Vec<T> {
  2810. /// Allocate a `Vec<T>` and move `s`'s items into it.
  2811. ///
  2812. /// # Examples
  2813. ///
  2814. /// ```
  2815. /// assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]);
  2816. /// ```
  2817. #[cfg(not(test))]
  2818. fn from(s: [T; N]) -> Vec<T> {
  2819. <[T]>::into_vec(box s)
  2820. }
  2821. #[cfg(test)]
  2822. fn from(s: [T; N]) -> Vec<T> {
  2823. crate::slice::into_vec(box s)
  2824. }
  2825. }
  2826. #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
  2827. impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
  2828. where
  2829. [T]: ToOwned<Owned = Vec<T>>,
  2830. {
  2831. /// Convert a clone-on-write slice into a vector.
  2832. ///
  2833. /// If `s` already owns a `Vec<T>`, it will be returned directly.
  2834. /// If `s` is borrowing a slice, a new `Vec<T>` will be allocated and
  2835. /// filled by cloning `s`'s items into it.
  2836. ///
  2837. /// # Examples
  2838. ///
  2839. /// ```
  2840. /// # use std::borrow::Cow;
  2841. /// let o: Cow<[i32]> = Cow::Owned(vec![1, 2, 3]);
  2842. /// let b: Cow<[i32]> = Cow::Borrowed(&[1, 2, 3]);
  2843. /// assert_eq!(Vec::from(o), Vec::from(b));
  2844. /// ```
  2845. fn from(s: Cow<'a, [T]>) -> Vec<T> {
  2846. s.into_owned()
  2847. }
  2848. }
  2849. // note: test pulls in libstd, which causes errors here
  2850. #[cfg(not(test))]
  2851. #[stable(feature = "vec_from_box", since = "1.18.0")]
  2852. impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
  2853. /// Convert a boxed slice into a vector by transferring ownership of
  2854. /// the existing heap allocation.
  2855. ///
  2856. /// # Examples
  2857. ///
  2858. /// ```
  2859. /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
  2860. /// assert_eq!(Vec::from(b), vec![1, 2, 3]);
  2861. /// ```
  2862. fn from(s: Box<[T], A>) -> Self {
  2863. s.into_vec()
  2864. }
  2865. }
  2866. // note: test pulls in libstd, which causes errors here
  2867. #[cfg(not(no_global_oom_handling))]
  2868. #[cfg(not(test))]
  2869. #[stable(feature = "box_from_vec", since = "1.20.0")]
  2870. impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> {
  2871. /// Convert a vector into a boxed slice.
  2872. ///
  2873. /// If `v` has excess capacity, its items will be moved into a
  2874. /// newly-allocated buffer with exactly the right capacity.
  2875. ///
  2876. /// # Examples
  2877. ///
  2878. /// ```
  2879. /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice());
  2880. /// ```
  2881. fn from(v: Vec<T, A>) -> Self {
  2882. v.into_boxed_slice()
  2883. }
  2884. }
  2885. #[cfg(not(no_global_oom_handling))]
  2886. #[stable(feature = "rust1", since = "1.0.0")]
  2887. impl From<&str> for Vec<u8> {
  2888. /// Allocate a `Vec<u8>` and fill it with a UTF-8 string.
  2889. ///
  2890. /// # Examples
  2891. ///
  2892. /// ```
  2893. /// assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']);
  2894. /// ```
  2895. fn from(s: &str) -> Vec<u8> {
  2896. From::from(s.as_bytes())
  2897. }
  2898. }
  2899. #[stable(feature = "array_try_from_vec", since = "1.48.0")]
  2900. impl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] {
  2901. type Error = Vec<T, A>;
  2902. /// Gets the entire contents of the `Vec<T>` as an array,
  2903. /// if its size exactly matches that of the requested array.
  2904. ///
  2905. /// # Examples
  2906. ///
  2907. /// ```
  2908. /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
  2909. /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
  2910. /// ```
  2911. ///
  2912. /// If the length doesn't match, the input comes back in `Err`:
  2913. /// ```
  2914. /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
  2915. /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
  2916. /// ```
  2917. ///
  2918. /// If you're fine with just getting a prefix of the `Vec<T>`,
  2919. /// you can call [`.truncate(N)`](Vec::truncate) first.
  2920. /// ```
  2921. /// let mut v = String::from("hello world").into_bytes();
  2922. /// v.sort();
  2923. /// v.truncate(2);
  2924. /// let [a, b]: [_; 2] = v.try_into().unwrap();
  2925. /// assert_eq!(a, b' ');
  2926. /// assert_eq!(b, b'd');
  2927. /// ```
  2928. fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
  2929. if vec.len() != N {
  2930. return Err(vec);
  2931. }
  2932. // SAFETY: `.set_len(0)` is always sound.
  2933. unsafe { vec.set_len(0) };
  2934. // SAFETY: A `Vec`'s pointer is always aligned properly, and
  2935. // the alignment the array needs is the same as the items.
  2936. // We checked earlier that we have sufficient items.
  2937. // The items will not double-drop as the `set_len`
  2938. // tells the `Vec` not to also drop them.
  2939. let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
  2940. Ok(array)
  2941. }
  2942. }