Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 33.94 KB | None | 0 0
  1. #![allow(incomplete_features)]
  2. #![feature(doc_cfg)]
  3. #![feature(untagged_unions)]
  4. #![feature(transparent_unions)]
  5. #![feature(const_fn_union)]
  6. #![feature(core_intrinsics)]
  7. #![feature(const_fn)]
  8. #![feature(const_generics)]
  9. #![feature(maybe_uninit_ref)]
  10. #![feature(maybe_uninit_extra)]
  11. #![feature(exact_size_is_empty)]
  12.  
  13. //Literally just for stable-sort.
  14. #[cfg(feature = "std")]
  15. extern crate alloc;
  16.  
  17. use std::cmp::{Ord, PartialEq};
  18. use std::iter::{FromIterator, FusedIterator};
  19. use std::marker::PhantomData;
  20. use std::mem::ManuallyDrop;
  21. use std::ops::{Bound::Excluded, Bound::Included, Bound::Unbounded, Index, IndexMut, RangeBounds};
  22. use std::ptr;
  23.  
  24. #[derive(Copy)]
  25. #[repr(transparent)]
  26. pub union MaybeUninit<T> {
  27. uninit: (),
  28. value: ManuallyDrop<T>,
  29. }
  30.  
  31. impl<T: Copy> Clone for MaybeUninit<T> {
  32. #[inline(always)]
  33. fn clone(&self) -> Self {
  34. *self
  35. }
  36. }
  37.  
  38. impl<T> MaybeUninit<T> {
  39. #[inline(always)]
  40. pub const fn uninit() -> MaybeUninit<T> {
  41. MaybeUninit { uninit: () }
  42. }
  43.  
  44. #[inline(always)]
  45. pub fn write(&mut self, val: T) {
  46. unsafe {
  47. self.value = ManuallyDrop::new(val);
  48. }
  49. }
  50.  
  51. #[inline(always)]
  52. pub const unsafe fn assume_init(self) -> T {
  53. ManuallyDrop::into_inner(self.value)
  54. }
  55.  
  56. #[inline(always)]
  57. pub unsafe fn read(&self) -> T {
  58. (&*self.value as *const T).read()
  59. }
  60.  
  61. #[inline(always)]
  62. pub unsafe fn get_ref(&self) -> &T {
  63. &self.value
  64. }
  65.  
  66. #[inline(always)]
  67. pub unsafe fn get_mut(&mut self) -> &mut T {
  68. &mut self.value
  69. }
  70. }
  71.  
  72. ///Similar to [Iter](std::slice::IterMut), but specifically implemented with StaticVecs in mind.
  73. pub struct StaticVecIterConst<'a, T: 'a> {
  74. pub(crate) start: *const T,
  75. pub(crate) end: *const T,
  76. pub(crate) marker: PhantomData<&'a T>,
  77. }
  78.  
  79. ///Similar to [IterMut](std::slice::IterMut), but specifically implemented with StaticVecs in mind.
  80. pub struct StaticVecIterMut<'a, T: 'a> {
  81. pub(crate) start: *mut T,
  82. pub(crate) end: *mut T,
  83. pub(crate) marker: PhantomData<&'a mut T>,
  84. }
  85.  
  86. impl<'a, T: 'a> Iterator for StaticVecIterConst<'a, T> {
  87. type Item = &'a T;
  88. #[inline(always)]
  89. fn next(&mut self) -> Option<Self::Item> {
  90. if self.start < self.end {
  91. unsafe {
  92. let res = Some(&*self.start);
  93. self.start = self.start.offset(1);
  94. res
  95. }
  96. } else {
  97. None
  98. }
  99. }
  100.  
  101. #[inline(always)]
  102. fn size_hint(&self) -> (usize, Option<usize>) {
  103. let len = distance_between(self.end, self.start);
  104. (len, Some(len))
  105. }
  106. }
  107.  
  108. impl<'a, T: 'a> DoubleEndedIterator for StaticVecIterConst<'a, T> {
  109. #[inline(always)]
  110. fn next_back(&mut self) -> Option<Self::Item> {
  111. if self.end > self.start {
  112. unsafe {
  113. self.end = self.end.offset(-1);
  114. Some(&*self.end)
  115. }
  116. } else {
  117. None
  118. }
  119. }
  120. }
  121.  
  122. impl<'a, T: 'a> ExactSizeIterator for StaticVecIterConst<'a, T> {
  123. #[inline(always)]
  124. fn len(&self) -> usize {
  125. distance_between(self.end, self.start)
  126. }
  127.  
  128. #[inline(always)]
  129. fn is_empty(&self) -> bool {
  130. distance_between(self.end, self.start) == 0
  131. }
  132. }
  133.  
  134. impl<'a, T: 'a> FusedIterator for StaticVecIterConst<'a, T> {}
  135.  
  136. impl<'a, T: 'a> Iterator for StaticVecIterMut<'a, T> {
  137. type Item = &'a mut T;
  138. #[inline(always)]
  139. fn next(&mut self) -> Option<Self::Item> {
  140. if self.start < self.end {
  141. unsafe {
  142. let res = Some(&mut *self.start);
  143. self.start = self.start.offset(1);
  144. res
  145. }
  146. } else {
  147. None
  148. }
  149. }
  150.  
  151. #[inline(always)]
  152. fn size_hint(&self) -> (usize, Option<usize>) {
  153. let len = distance_between(self.end, self.start);
  154. (len, Some(len))
  155. }
  156. }
  157.  
  158. impl<'a, T: 'a> DoubleEndedIterator for StaticVecIterMut<'a, T> {
  159. #[inline(always)]
  160. fn next_back(&mut self) -> Option<Self::Item> {
  161. if self.end > self.start {
  162. unsafe {
  163. self.end = self.end.offset(-1);
  164. Some(&mut *self.end)
  165. }
  166. } else {
  167. None
  168. }
  169. }
  170. }
  171.  
  172. impl<'a, T: 'a> ExactSizeIterator for StaticVecIterMut<'a, T> {
  173. #[inline(always)]
  174. fn len(&self) -> usize {
  175. distance_between(self.end, self.start)
  176. }
  177.  
  178. #[inline(always)]
  179. fn is_empty(&self) -> bool {
  180. distance_between(self.end, self.start) == 0
  181. }
  182. }
  183.  
  184. impl<'a, T: 'a> FusedIterator for StaticVecIterMut<'a, T> {}
  185.  
  186. ///A [Vec](alloc::vec::Vec)-like struct (mostly directly API-compatible where it can be)
  187. ///implemented with const generics around a static array of fixed `N` capacity.
  188. pub struct StaticVec<T, const N: usize> {
  189. data: [MaybeUninit<T>; N],
  190. length: usize,
  191. }
  192.  
  193. impl<T, const N: usize> StaticVec<T, { N }> {
  194. ///Returns a new StaticVec instance.
  195. #[inline(always)]
  196. pub const fn new() -> Self {
  197. unsafe {
  198. Self {
  199. //Sound because data is an array of MaybeUninit<T>, not an array of T.
  200. data: MaybeUninit::uninit().assume_init(),
  201. length: 0,
  202. }
  203. }
  204. }
  205.  
  206. ///Returns a new StaticVec instance filled with the contents, if any, of a slice.
  207. ///If the slice has a length greater than the StaticVec's declared capacity,
  208. ///any contents after that point are ignored.
  209. ///Locally requires that `T` implements [Copy](std::marker::Copy) to avoid soundness issues.
  210. #[inline]
  211. pub fn new_from_slice(values: &[T]) -> Self
  212. where
  213. T: Copy,
  214. {
  215. unsafe {
  216. let mut data_: [MaybeUninit<T>; N] = MaybeUninit::uninit().assume_init();
  217. let fill_length = values.len().min(N);
  218. values
  219. .as_ptr()
  220. .copy_to_nonoverlapping(data_.as_mut_ptr() as *mut T, fill_length);
  221. Self {
  222. data: data_,
  223. length: fill_length,
  224. }
  225. }
  226. }
  227.  
  228. ///Returns a new StaticVec instance filled with the return value of an initializer function.
  229. ///The length field of the newly created StaticVec will be equal to its capacity.
  230. ///
  231. ///Example usage:
  232. ///```
  233. ///use staticvec::*;
  234. ///
  235. ///fn main() {
  236. /// let mut i = 0;
  237. /// let v = StaticVec::<i32, 64>::filled_with(|| { i += 1; i });
  238. /// assert_eq!(v.len(), 64);
  239. /// assert_eq!(v[0], 1);
  240. /// assert_eq!(v[1], 2);
  241. /// assert_eq!(v[2], 3);
  242. /// assert_eq!(v[3], 4);
  243. ///}
  244. /// ```
  245. #[inline]
  246. pub fn filled_with<F>(mut initializer: F) -> Self
  247. where
  248. F: FnMut() -> T,
  249. {
  250. let mut res = Self::new();
  251. for i in 0..N {
  252. unsafe {
  253. res.data.get_unchecked_mut(i).write(initializer());
  254. res.length += 1;
  255. }
  256. }
  257. res
  258. }
  259.  
  260. ///Returns the current length of the StaticVec.
  261. ///Just as for a normal [Vec](alloc::vec::Vec), this means the number of elements that
  262. ///have been added to it with `push`, `insert`, etc. except in the case
  263. ///that it has been set directly with the unsafe `set_len` function.
  264. #[inline(always)]
  265. pub fn len(&self) -> usize {
  266. self.length
  267. }
  268.  
  269. ///Returns the total capacity of the StaticVec.
  270. ///This is always equivalent to the generic `N` parameter it was declared with,
  271. ///which determines the fixed size of the backing array.
  272. #[inline(always)]
  273. pub const fn capacity(&self) -> usize {
  274. N
  275. }
  276.  
  277. ///Directly sets the `length` field of the StaticVec to `new_len`. Useful if you intend
  278. ///to write to it solely element-wise, but marked unsafe due to how it creates the potential for reading
  279. ///from unitialized memory later on.
  280. #[inline(always)]
  281. pub unsafe fn set_len(&mut self, new_len: usize) {
  282. self.length = new_len;
  283. }
  284.  
  285. ///Returns true if the current length of the StaticVec is 0.
  286. #[inline(always)]
  287. pub fn is_empty(&self) -> bool {
  288. self.length == 0
  289. }
  290.  
  291. ///Returns true if the current length of the StaticVec is greater than 0.
  292. #[inline(always)]
  293. pub fn is_not_empty(&self) -> bool {
  294. self.length > 0
  295. }
  296.  
  297. ///Returns true if the current length of the StaticVec is equal to its capacity.
  298. #[inline(always)]
  299. pub fn is_full(&self) -> bool {
  300. self.length == N
  301. }
  302.  
  303. ///Returns true if the current length of the StaticVec is less than its capacity.
  304. #[inline(always)]
  305. pub fn is_not_full(&self) -> bool {
  306. self.length < N
  307. }
  308.  
  309. ///Returns a constant pointer to the first element of the StaticVec's internal array.
  310. #[inline(always)]
  311. pub fn as_ptr(&self) -> *const T {
  312. self.data.as_ptr() as *const T
  313. }
  314.  
  315. ///Returns a mutable pointer to the first element of the StaticVec's internal array.
  316. #[inline(always)]
  317. pub fn as_mut_ptr(&mut self) -> *mut T {
  318. self.data.as_mut_ptr() as *mut T
  319. }
  320.  
  321. ///Returns a constant reference to a slice of the StaticVec's inhabited area.
  322. #[inline(always)]
  323. pub fn as_slice(&self) -> &[T] {
  324. unsafe {
  325. &*(self.data.get_unchecked(0..self.length) as *const [MaybeUninit<T>] as *const [T])
  326. }
  327. }
  328.  
  329. ///Returns a mutable reference to a slice of the StaticVec's inhabited area.
  330. #[inline(always)]
  331. pub fn as_mut_slice(&mut self) -> &mut [T] {
  332. unsafe {
  333. &mut *(self.data.get_unchecked_mut(0..self.length) as *mut [MaybeUninit<T>]
  334. as *mut [T])
  335. }
  336. }
  337.  
  338. ///Appends a value to the end of the StaticVec without asserting that
  339. ///its current length is less than `N`.
  340. #[inline(always)]
  341. pub unsafe fn push_unchecked(&mut self, value: T) {
  342. self.data.get_unchecked_mut(self.length).write(value);
  343. self.length += 1;
  344. }
  345.  
  346. ///Pops a value from the end of the StaticVec and returns it directly without asserting that
  347. ///the StaticVec's current length is greater than 0.
  348. #[inline(always)]
  349. pub unsafe fn pop_unchecked(&mut self) -> T {
  350. self.length -= 1;
  351. self.data.get_unchecked(self.length).read()
  352. }
  353.  
  354. ///Asserts that the current length of the StaticVec is less than `N`,
  355. ///and if so appends a value to the end of it.
  356. #[inline(always)]
  357. pub fn push(&mut self, value: T) {
  358. assert!(self.length < N);
  359. unsafe {
  360. self.push_unchecked(value);
  361. }
  362. }
  363.  
  364. ///Removes the value at the last position of the StaticVec and returns it in `Some` if
  365. ///the StaticVec has a current length greater than 0, and returns `None` otherwise.
  366. #[inline(always)]
  367. pub fn pop(&mut self) -> Option<T> {
  368. if self.length == 0 {
  369. None
  370. } else {
  371. Some(unsafe { self.pop_unchecked() })
  372. }
  373. }
  374.  
  375. ///Asserts that `index` is less than the current length of the StaticVec,
  376. ///and if so removes the value at that position and returns it. Any values
  377. ///that exist in later positions are shifted to the left.
  378. #[inline]
  379. pub fn remove(&mut self, index: usize) -> T {
  380. assert!(index < self.length);
  381. unsafe {
  382. let p = self.as_mut_ptr().add(index);
  383. let res = p.read();
  384. p.offset(1).copy_to(p, self.length - index - 1);
  385. self.length -= 1;
  386. res
  387. }
  388. }
  389.  
  390. ///Removes the first instance of `item` from the StaticVec if the item exists.
  391. #[inline(always)]
  392. pub fn remove_item(&mut self, item: &T) -> Option<T>
  393. where
  394. T: PartialEq,
  395. {
  396. //Adapted this from normal Vec's implementation.
  397. if let Some(pos) = self.iter().position(|x| *x == *item) {
  398. Some(self.remove(pos))
  399. } else {
  400. None
  401. }
  402. }
  403.  
  404. ///Asserts that `index` is less than the current length of the StaticVec,
  405. ///and if so removes the value at that position and returns it, and then
  406. ///moves the last value in the StaticVec into the empty slot.
  407. #[inline(always)]
  408. pub fn swap_remove(&mut self, index: usize) -> T {
  409. assert!(index < self.length);
  410. unsafe {
  411. let last_value = self.data.get_unchecked(self.length - 1).read();
  412. self.length -= 1;
  413. self.as_mut_ptr().add(index).replace(last_value)
  414. }
  415. }
  416.  
  417. ///Asserts that the current length of the StaticVec is less than `N` and that
  418. ///`index` is less than the length, and if so inserts `value` at that position.
  419. ///Any values that exist in later positions are shifted to the right.
  420. #[inline]
  421. pub fn insert(&mut self, index: usize, value: T) {
  422. assert!(self.length < N && index <= self.length);
  423. unsafe {
  424. let p = self.as_mut_ptr().add(index);
  425. p.copy_to(p.offset(1), self.length - index);
  426. p.write(value);
  427. self.length += 1;
  428. }
  429. }
  430.  
  431. ///Removes all contents from the StaticVec and sets its length back to 0.
  432. #[inline(always)]
  433. pub fn clear(&mut self) {
  434. unsafe {
  435. ptr::drop_in_place(self.as_mut_slice());
  436. }
  437. self.length = 0;
  438. }
  439.  
  440. ///Performs an stable in-place sort of the StaticVec's inhabited area.
  441. ///Locally requires that `T` implements [Ord](std::cmp::Ord) to make the sorting possible.
  442. #[cfg(feature = "std")]
  443. #[inline(always)]
  444. pub fn sort(&mut self)
  445. where
  446. T: Ord,
  447. {
  448. self.as_mut_slice().sort();
  449. }
  450.  
  451. ///Performs an unstable in-place sort of the StaticVec's inhabited area.
  452. ///Locally requires that `T` implements [Ord](std::cmp::Ord) to make the sorting possible.
  453. #[inline(always)]
  454. pub fn sort_unstable(&mut self)
  455. where
  456. T: Ord,
  457. {
  458. self.as_mut_slice().sort_unstable();
  459. }
  460.  
  461. ///Reverses the contents of the StaticVec's inhabited area in-place.
  462. #[inline(always)]
  463. pub fn reverse(&mut self) {
  464. self.as_mut_slice().reverse();
  465. }
  466.  
  467. ///Returns a separate, stable-sorted StaticVec of the contents of the
  468. ///StaticVec's inhabited area without modifying the original data.
  469. ///Locally requires that `T` implements [Copy](std::marker::Copy) to avoid soundness issues,
  470. ///and [Ord](std::cmp::Ord) to make the sorting possible.
  471. #[cfg(feature = "std")]
  472. #[inline]
  473. pub fn sorted(&self) -> Self
  474. where
  475. T: Copy + Ord,
  476. {
  477. unsafe {
  478. let mut res = Self::new();
  479. res.length = self.length;
  480. self.as_ptr()
  481. .copy_to_nonoverlapping(res.as_mut_ptr(), self.length);
  482. res.sort();
  483. res
  484. }
  485. }
  486.  
  487. ///Returns a separate, unstable-sorted StaticVec of the contents of the
  488. ///StaticVec's inhabited area without modifying the original data.
  489. ///Locally requires that `T` implements [Copy](std::marker::Copy) to avoid soundness issues,
  490. ///and [Ord](std::cmp::Ord) to make the sorting possible.
  491. #[inline]
  492. pub fn sorted_unstable(&self) -> Self
  493. where
  494. T: Copy + Ord,
  495. {
  496. unsafe {
  497. let mut res = Self::new();
  498. res.length = self.length;
  499. self.as_ptr()
  500. .copy_to_nonoverlapping(res.as_mut_ptr(), self.length);
  501. res.sort_unstable();
  502. res
  503. }
  504. }
  505.  
  506. ///Returns a separate, reversed StaticVec of the contents of the StaticVec's
  507. ///inhabited area without modifying the original data.
  508. ///Locally requires that `T` implements [Copy](std::marker::Copy) to avoid soundness issues.
  509. #[inline]
  510. pub fn reversed(&self) -> Self
  511. where
  512. T: Copy,
  513. {
  514. let mut res = Self::new();
  515. res.length = self.length;
  516. unsafe {
  517. reverse_copy(
  518. self.as_ptr(),
  519. self.as_ptr().add(self.length),
  520. res.as_mut_ptr(),
  521. );
  522. }
  523. res
  524. }
  525.  
  526. ///Copies and appends all elements, if any, of a slice to the StaticVec.
  527. ///If the slice has a length greater than the StaticVec's declared capacity,
  528. ///any contents after that point are ignored.
  529. ///Unlike the implementation of this function for [Vec](alloc::vec::Vec), no iterator is used,
  530. ///just a single pointer-copy call.
  531. ///Locally requires that `T` implements [Copy](std::marker::Copy) to avoid soundness issues.
  532. #[inline]
  533. pub fn extend_from_slice(&mut self, other: &[T])
  534. where
  535. T: Copy,
  536. {
  537. let mut added_length = other.len();
  538. if self.length + added_length > N {
  539. added_length = N - self.length;
  540. }
  541. unsafe {
  542. other
  543. .as_ptr()
  544. .copy_to_nonoverlapping(self.as_mut_ptr().add(self.length), added_length);
  545. }
  546. self.length += added_length;
  547. }
  548.  
  549. ///Removes the specified range of elements from the StaticVec and returns them in a new one.
  550. #[inline]
  551. pub fn drain<R>(&mut self, range: R) -> Self
  552. //No Copy bounds here because the original StaticVec gives up all access to the values in question.
  553. where
  554. R: RangeBounds<usize>,
  555. {
  556. //Borrowed this part from normal Vec's implementation.
  557. let start = match range.start_bound() {
  558. Included(&idx) => idx,
  559. Excluded(&idx) => idx + 1,
  560. Unbounded => 0,
  561. };
  562. let end = match range.end_bound() {
  563. Included(&idx) => idx + 1,
  564. Excluded(&idx) => idx,
  565. Unbounded => self.length,
  566. };
  567. assert!(start <= end && end <= self.length);
  568. let mut res = Self::new();
  569. res.length = end - start;
  570. unsafe {
  571. self.as_ptr()
  572. .add(start)
  573. .copy_to_nonoverlapping(res.as_mut_ptr(), res.length);
  574. self.as_ptr()
  575. .add(end)
  576. .copy_to(self.as_mut_ptr().add(start), self.length - end);
  577. }
  578. self.length -= res.length;
  579. res
  580. }
  581.  
  582. ///Removes all elements in the StaticVec for which `filter` returns true and
  583. ///returns them in a new one.
  584. #[inline]
  585. pub fn drain_filter<F>(&mut self, mut filter: F) -> Self
  586. where
  587. F: FnMut(&mut T) -> bool,
  588. {
  589. let mut res = Self::new();
  590. let old_length = self.length;
  591. self.length = 0;
  592. unsafe {
  593. for i in 0..old_length {
  594. let val = self.as_mut_ptr().add(i);
  595. if filter(&mut *val) {
  596. res.data.get_unchecked_mut(res.length).write(val.read());
  597. res.length += 1;
  598. } else if res.length > 0 {
  599. self.as_ptr()
  600. .add(i)
  601. .copy_to_nonoverlapping(self.as_mut_ptr().add(i - res.length), 1);
  602. }
  603. }
  604. }
  605. self.length = old_length - res.length;
  606. res
  607. }
  608.  
  609. ///Removes all elements in the StaticVec for which `filter` returns false.
  610. #[inline(always)]
  611. pub fn retain<F>(&mut self, mut filter: F)
  612. where
  613. F: FnMut(&T) -> bool,
  614. {
  615. self.drain_filter(|val| !filter(val));
  616. }
  617.  
  618. ///Shortens the StaticVec, keeping the first `length` elements and dropping the rest.
  619. #[inline(always)]
  620. pub fn truncate(&mut self, length: usize) {
  621. let old_length = self.length;
  622. self.length = length;
  623. unsafe {
  624. ptr::drop_in_place(
  625. &mut *(self.data.get_unchecked_mut(length..old_length) as *mut [MaybeUninit<T>]
  626. as *mut [T]),
  627. );
  628. }
  629. }
  630.  
  631. #[inline]
  632. pub fn split_off(&mut self, at: usize) -> Self {
  633. assert!(at <= self.length);
  634. let split_length = self.length - at;
  635. let mut split = Self::new();
  636. self.length = at;
  637. split.length = split_length;
  638. unsafe {
  639. self.as_ptr()
  640. .add(at)
  641. .copy_to_nonoverlapping(split.as_mut_ptr(), split_length);
  642. }
  643. split
  644. }
  645.  
  646. ///Returns a `StaticVecIterConst` over the StaticVec's inhabited area.
  647. #[inline(always)]
  648. pub fn iter<'a>(&'a self) -> StaticVecIterConst<'a, T> {
  649. unsafe {
  650. StaticVecIterConst::<'a, T> {
  651. start: self.as_ptr(),
  652. end: self.as_ptr().add(self.length),
  653. marker: PhantomData,
  654. }
  655. }
  656. }
  657.  
  658. ///Returns a `StaticVecIterMut` over the StaticVec's inhabited area.
  659. #[inline(always)]
  660. pub fn iter_mut<'a>(&'a mut self) -> StaticVecIterMut<'a, T> {
  661. unsafe {
  662. StaticVecIterMut::<'a, T> {
  663. start: self.as_mut_ptr(),
  664. end: self.as_mut_ptr().add(self.length),
  665. marker: PhantomData,
  666. }
  667. }
  668. }
  669. }
  670.  
  671. impl<T, const N: usize> Default for StaticVec<T, { N }> {
  672. ///Calls `new`.
  673. #[inline(always)]
  674. fn default() -> Self {
  675. Self::new()
  676. }
  677. }
  678.  
  679. impl<T, const N: usize> Drop for StaticVec<T, { N }> {
  680. ///Calls `clear` through the StaticVec before dropping it.
  681. #[inline(always)]
  682. fn drop(&mut self) {
  683. self.clear();
  684. }
  685. }
  686.  
  687. impl<T, const N: usize> Index<usize> for StaticVec<T, { N }> {
  688. type Output = T;
  689. ///Asserts that `index` is less than the current length of the StaticVec,
  690. ///and if so returns the value at that position as a constant reference.
  691. #[inline(always)]
  692. fn index(&self, index: usize) -> &Self::Output {
  693. assert!(index < self.length);
  694. unsafe { self.data.get_unchecked(index).get_ref() }
  695. }
  696. }
  697.  
  698. impl<T, const N: usize> IndexMut<usize> for StaticVec<T, { N }> {
  699. ///Asserts that `index` is less than the current length of the StaticVec,
  700. ///and if so returns the value at that position as a mutable reference.
  701. #[inline(always)]
  702. fn index_mut(&mut self, index: usize) -> &mut Self::Output {
  703. assert!(index < self.length);
  704. unsafe { self.data.get_unchecked_mut(index).get_mut() }
  705. }
  706. }
  707.  
  708. impl<T: Copy, const N: usize> From<&[T]> for StaticVec<T, { N }> {
  709. ///Creates a new StaticVec instance from the contents of `values`, using
  710. ///[new_from_slice](crate::StaticVec::new_from_slice) internally.
  711. #[inline(always)]
  712. fn from(values: &[T]) -> Self {
  713. Self::new_from_slice(values)
  714. }
  715. }
  716.  
  717. impl<'a, T: 'a, const N: usize> IntoIterator for &'a StaticVec<T, { N }> {
  718. type IntoIter = StaticVecIterConst<'a, T>;
  719. type Item = <Self::IntoIter as Iterator>::Item;
  720. ///Returns a `StaticVecIterConst` over the StaticVec's inhabited area.
  721. #[inline(always)]
  722. fn into_iter(self) -> Self::IntoIter {
  723. self.iter()
  724. }
  725. }
  726.  
  727. impl<'a, T: 'a, const N: usize> IntoIterator for &'a mut StaticVec<T, { N }> {
  728. type IntoIter = StaticVecIterMut<'a, T>;
  729. type Item = <Self::IntoIter as Iterator>::Item;
  730. ///Returns a `StaticVecIterMut` over the StaticVec's inhabited area.
  731. #[inline(always)]
  732. fn into_iter(self) -> Self::IntoIter {
  733. self.iter_mut()
  734. }
  735. }
  736.  
  737. impl<T, const N: usize> Extend<T> for StaticVec<T, { N }> {
  738. ///Appends all elements, if any, from `iter` to the StaticVec. If `iter` has a size greater than
  739. ///the StaticVec's capacity, any items after that point are ignored.
  740. #[inline]
  741. fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
  742. let spots_left = N - self.length;
  743. unsafe {
  744. let mut p = self.as_mut_ptr().add(self.length);
  745. for val in iter.into_iter().take(spots_left) {
  746. p.write(val);
  747. p = p.offset(1);
  748. self.length += 1;
  749. }
  750. }
  751. }
  752. }
  753.  
  754. impl<'a, T: Copy + 'a, const N: usize> Extend<&'a T> for StaticVec<T, { N }> {
  755. ///Appends all elements, if any, from `iter` to the StaticVec. If `iter` has a size greater than
  756. ///the StaticVec's capacity, any items after that point are ignored.
  757. #[inline]
  758. fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
  759. let spots_left = N - self.length;
  760. unsafe {
  761. let mut p = self.as_mut_ptr().add(self.length);
  762. for val in iter.into_iter().take(spots_left) {
  763. p.write(*val);
  764. p = p.offset(1);
  765. self.length += 1;
  766. }
  767. }
  768. }
  769. }
  770.  
  771. impl<'a, T: Copy + 'a, const N: usize> Extend<&'a mut T> for StaticVec<T, { N }> {
  772. ///Appends all elements, if any, from `iter` to the StaticVec. If `iter` has a size greater than
  773. ///the StaticVec's capacity, any items after that point are ignored.
  774. #[inline]
  775. fn extend<I: IntoIterator<Item = &'a mut T>>(&mut self, iter: I) {
  776. let spots_left = N - self.length;
  777. unsafe {
  778. let mut p = self.as_mut_ptr().add(self.length);
  779. for val in iter.into_iter().take(spots_left) {
  780. p.write(*val);
  781. p = p.offset(1);
  782. self.length += 1;
  783. }
  784. }
  785. }
  786. }
  787.  
  788. impl<T, const N: usize> FromIterator<T> for StaticVec<T, { N }> {
  789. ///Creates a new StaticVec instance from the elements, if any, of `iter`.
  790. ///If `iter` has a size greater than the StaticVec's capacity, any items after
  791. ///that point are ignored.
  792. #[inline]
  793. fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
  794. let mut res = Self::new();
  795. res.extend(iter);
  796. res
  797. }
  798. }
  799.  
  800. #[inline(always)]
  801. pub(crate) fn distance_between<T>(self_: *const T, origin: *const T) -> usize {
  802. unsafe {
  803. std::intrinsics::exact_div(
  804. (self_ as usize).wrapping_sub(origin as usize),
  805. std::intrinsics::size_of::<T>(),
  806. )
  807. }
  808. }
  809.  
  810. #[inline(always)]
  811. pub(crate) fn reverse_copy<T>(first: *const T, mut last: *const T, mut result: *mut T)
  812. where
  813. T: Copy,
  814. {
  815. while first != last {
  816. unsafe {
  817. last = last.offset(-1);
  818. *result = *last;
  819. result = result.offset(1);
  820. }
  821. }
  822. }
  823.  
  824. #[inline(always)]
  825. pub fn new_from_value<T, const COUNT: usize>(value: T) -> StaticVec<T, { COUNT }>
  826. where
  827. T: Copy,
  828. {
  829. let mut res = StaticVec::<T, { COUNT }>::new();
  830. res.length = COUNT;
  831. for i in 0..COUNT {
  832. unsafe {
  833. res.data.get_unchecked_mut(i).write(value);
  834. }
  835. }
  836. res
  837. }
  838.  
  839. ///Creates a new StaticVec from a `vec!`-style pseudo-slice.
  840. ///The newly created StaticVec will have a `capacity` and `length` exactly equal to the
  841. ///number of elements, if any, in the slice.
  842. #[macro_export]
  843. macro_rules! staticvec {
  844. (@put_one $val:expr) => (1);
  845. ($val:expr; $n:expr) => (
  846. new_from_value::<_, $n>($val)
  847. );
  848. ($($val:expr),*$(,)*) => ({
  849. let mut res = StaticVec::<_, {0$(+staticvec!(@put_one $val))*}>::new();
  850. {
  851. #[allow(unused_unsafe)]
  852. unsafe {
  853. ($({
  854. res.push_unchecked($val);
  855. }),*)
  856. }
  857. };
  858. res
  859. });
  860. }
  861.  
  862. #[derive(Copy, Clone)]
  863. struct MyStruct {
  864. s: &'static str,
  865. }
  866.  
  867. struct MyOtherStruct {
  868. s: &'static str,
  869. }
  870.  
  871. impl Drop for MyOtherStruct {
  872. fn drop(&mut self) {
  873. println!("Dropping MyOtherStruct with value: {}", self.s)
  874. }
  875. }
  876.  
  877. pub fn main() {
  878. let mut v = StaticVec::<f32, 24>::new();
  879. for i in 0..v.capacity() {
  880. v.push(i as f32);
  881. }
  882. for f in &v {
  883. println!("{}", f);
  884. }
  885. v.clear();
  886. v.insert(0, 47.6);
  887. v.insert(1, 48.6);
  888. v.insert(2, 49.6);
  889. v.insert(v.len() - 1, 50.6);
  890. v.insert(v.len() - 2, 51.6);
  891. v.insert(v.len() - 3, 52.6);
  892. for f in &v {
  893. println!("{}", f);
  894. }
  895. for f in 0..v.len() {
  896. println!("{}", v[f]);
  897. }
  898. v.remove(1);
  899. v.remove(2);
  900. for f in &v {
  901. println!("{}", f);
  902. }
  903. let mut va = StaticVec::<usize, 1024>::new();
  904. for i in 0..va.capacity() {
  905. va.push(i);
  906. }
  907. let ia = va.remove_item(&512).unwrap();
  908. let ib = va.remove_item(&511).unwrap();
  909. println!("{}", ia);
  910. println!("{}", ib);
  911. va.remove(10);
  912. va.remove(11);
  913. va.remove(12);
  914. va.remove(13);
  915. va.remove(14);
  916. va.remove(15);
  917. va.insert(10, 99);
  918. va.insert(11, 99);
  919. va.insert(12, 99);
  920. va.insert(13, 99);
  921. va.insert(14, 99);
  922. va.insert(15, 99);
  923. for i in 0..va.len() {
  924. println!("{}", va[i])
  925. }
  926. for i in &va {
  927. println!("{}", i)
  928. }
  929. while va.is_not_empty() {
  930. println!("{}", va.pop().unwrap());
  931. }
  932. let mut vb = StaticVec::<char, 26>::new();
  933. vb.push('a');
  934. vb.push('b');
  935. vb.push('c');
  936. vb.push('d');
  937. vb.push('e');
  938. vb.push('f');
  939. vb.push('g');
  940. vb.push('h');
  941. vb.push('i');
  942. vb.push('j');
  943. vb.push('k');
  944. vb.push('l');
  945. vb.push('m');
  946. vb.push('n');
  947. vb.push('o');
  948. vb.push('p');
  949. vb.push('q');
  950. vb.push('r');
  951. vb.push('s');
  952. vb.push('t');
  953. vb.push('u');
  954. vb.push('v');
  955. vb.push('w');
  956. vb.push('x');
  957. vb.push('y');
  958. vb.push('z');
  959. vb.remove(2);
  960. vb.remove(1);
  961. vb.remove(vb.len() - 1);
  962. for i in 0..vb.len() {
  963. println!("{}", vb[i]);
  964. }
  965. for s in &vb {
  966. println!("{}", s);
  967. }
  968. let pb = vb.as_mut_ptr();
  969. unsafe {
  970. println!("{}", *pb);
  971. println!("{}", *pb.add(1).add(1));
  972. }
  973. let pbc = vb.as_ptr();
  974. unsafe {
  975. println!("{}", *pbc);
  976. println!("{}", *pbc.add(1).add(1));
  977. }
  978. vb.clear();
  979. for _i in 0..vb.capacity() {
  980. vb.push('h');
  981. }
  982. while vb.is_not_empty() {
  983. println!("{}", vb.remove(0));
  984. }
  985. vb.push('g');
  986. vb.push('f');
  987. vb.push('e');
  988. vb.push('d');
  989. vb.push('c');
  990. vb.push('b');
  991. vb.push('a');
  992. let vbm = vb.as_mut_slice();
  993. vbm.sort_unstable();
  994. for s in vbm {
  995. println!("{}", s);
  996. }
  997. let vbmb = vb.as_mut_slice();
  998. vbmb.reverse();
  999. for s in vbmb {
  1000. println!("{}", s);
  1001. }
  1002. for s in &vb.sorted_unstable() {
  1003. println!("{}", s);
  1004. }
  1005. for s in &vb.reversed() {
  1006. println!("{}", s);
  1007. }
  1008. vb.reverse();
  1009. vb.reverse();
  1010. for s in &vb {
  1011. println!("{}", s);
  1012. }
  1013. vb.clear();
  1014. let mut vu = StaticVec::<usize, 8>::new();
  1015. vu.extend_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]);
  1016. println!("{}", vu.drain(2..5).iter().find(|&&i| i == 4).unwrap());
  1017. let vvu: StaticVec<usize, 4> = vu.iter().copied().collect();
  1018. for i in &vvu {
  1019. println!("{}", i);
  1020. }
  1021. let mut x = StaticVec::<i32, 4>::new();
  1022. x.push(1);
  1023. x.push(2);
  1024. x.push(3);
  1025. x.push(4);
  1026. let mut y = StaticVec::<i32, 4>::new();
  1027. y.push(4);
  1028. y.push(3);
  1029. y.push(2);
  1030. y.push(1);
  1031. let mut z = StaticVec::<i32, 4>::new();
  1032. z.push(1);
  1033. z.push(2);
  1034. z.push(3);
  1035. z.push(4);
  1036. let mut w = StaticVec::<i32, 4>::new();
  1037. w.push(4);
  1038. w.push(3);
  1039. w.push(2);
  1040. w.push(1);
  1041. let mut ww = StaticVec::<&StaticVec<i32, 4>, 4>::new();
  1042. ww.push(&x);
  1043. ww.push(&y);
  1044. ww.push(&z);
  1045. ww.push(&w);
  1046. for v in &ww {
  1047. for i in *v {
  1048. println!("{}", i);
  1049. }
  1050. }
  1051. let mut empty = StaticVec::<&'static str, 0>::new();
  1052. empty.sort_unstable();
  1053. empty.reverse();
  1054. for s in empty.as_slice() {
  1055. println!("{}", s);
  1056. }
  1057. for s in empty.as_mut_slice() {
  1058. println!("{}", s);
  1059. }
  1060. for s in &empty {
  1061. println!("{}", s);
  1062. }
  1063. for s in &mut empty {
  1064. println!("{}", s);
  1065. }
  1066. for s in &empty.reversed() {
  1067. println!("{}", s);
  1068. }
  1069. for s in &empty.sorted_unstable() {
  1070. println!("{}", s);
  1071. }
  1072. let mut msv = StaticVec::<MyStruct, 4>::new();
  1073. msv.push(MyStruct { s: "a" });
  1074. msv.push(MyStruct { s: "b" });
  1075. msv.push(MyStruct { s: "c" });
  1076. msv.push(MyStruct { s: "d" });
  1077. for ms in &msv.reversed() {
  1078. println!("{}", ms.s);
  1079. }
  1080. while msv.is_not_empty() {
  1081. println!("{}", msv.remove(msv.len() - 1).s)
  1082. }
  1083. let v2 = StaticVec::<i32, 8>::new_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]);
  1084. let mut it2 = v2.iter();
  1085. println!("{:?}", it2.size_hint());
  1086. while let Some(_i) = it2.next() {
  1087. println!("{:?}", it2.size_hint());
  1088. println!("{:?}", it2.len());
  1089. }
  1090. if let Some(i) = v2.iter().rfind(|&&x| x == 2) {
  1091. println!("{}", i);
  1092. }
  1093. for v in &staticvec![
  1094. staticvec![12.0, 14.0],
  1095. staticvec![16.0, 18.0],
  1096. staticvec![20.0, 22.0],
  1097. staticvec![24.0, 26.0],
  1098. staticvec![28.0, 30.0],
  1099. staticvec![32.0, 34.0],
  1100. staticvec![36.0, 38.0],
  1101. staticvec![40.0, 42.0]
  1102. ] {
  1103. for f in v.iter().skip(1) {
  1104. println!("{}", f);
  1105. }
  1106. }
  1107. let numbers = staticvec![1, 2, 3, 4, 5];
  1108. let zero = "0".to_string();
  1109. let result = numbers
  1110. .iter()
  1111. .rfold(zero, |acc, &x| format!("({} + {})", x, acc));
  1112. println!("{}", result);
  1113. let mut strings = staticvec!["foo", "bar", "baz", "qux"];
  1114. println!("{}", strings.swap_remove(1));
  1115. for s in &strings {
  1116. println!("{}", s);
  1117. }
  1118. println!("{}", strings.swap_remove(0));
  1119. for s in &strings {
  1120. println!("{}", s);
  1121. }
  1122. let mut structs = staticvec![
  1123. MyOtherStruct { s: "a" },
  1124. MyOtherStruct { s: "b" },
  1125. MyOtherStruct { s: "c" },
  1126. MyOtherStruct { s: "d" },
  1127. MyOtherStruct { s: "e" },
  1128. MyOtherStruct { s: "f" },
  1129. ];
  1130. let mut newstructs = structs.drain_filter(|s| s.s < "d");
  1131. for s in &structs {
  1132. println!("{}", s.s);
  1133. }
  1134. for s in &newstructs {
  1135. println!("{}", s.s);
  1136. }
  1137. newstructs.retain(|s| s.s == "a");
  1138. for s in &newstructs {
  1139. println!("{}", s.s);
  1140. }
  1141. let mut morestructs = staticvec![
  1142. MyOtherStruct { s: "a" },
  1143. MyOtherStruct { s: "b" },
  1144. MyOtherStruct { s: "c" },
  1145. MyOtherStruct { s: "d" },
  1146. MyOtherStruct { s: "e" },
  1147. MyOtherStruct { s: "f" },
  1148. ];
  1149. morestructs.truncate(3);
  1150. for s in &morestructs {
  1151. println!("{}", s.s);
  1152. }
  1153. let mut twelve = StaticVec::<f32, 12>::new();
  1154. twelve.extend_from_slice(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
  1155. for f in &twelve {
  1156. println!("{}", f);
  1157. }
  1158. twelve.extend([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0].iter());
  1159. for f in &twelve {
  1160. println!("{}", f);
  1161. }
  1162. println!("{}", twelve.capacity());
  1163. println!("{}", twelve.len());
  1164. let single_element_macro_test = staticvec!["ABCD"; 26];
  1165. for s in &single_element_macro_test {
  1166. println!("{}", s);
  1167. }
  1168. let mut eight_from = StaticVec::<usize, 8>::from(staticvec![1, 2, 3, 4, 5, 6, 7, 8].as_slice());
  1169. for i in &eight_from {
  1170. println!("{}", i);
  1171. }
  1172. for i in &eight_from.split_off(4) {
  1173. println!("{}", i);
  1174. }
  1175. let v = staticvec![MyStruct{s: "hey"}; 26].split_off(13);
  1176. for ms in &v {
  1177. println!("{}", ms.s);
  1178. }
  1179. static mut YYYY: StaticVec<f32, 12> = StaticVec::<f32, 12>::new();
  1180. unsafe {
  1181. for i in 0..12 {
  1182. YYYY.push_unchecked(i as f32);
  1183. }
  1184. for f in &YYYY {
  1185. println!("{}", f);
  1186. }
  1187. }
  1188. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement