1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
//! The implementation of `UnsizedVec<T>` for `T: ?Sized + ?Aligned`.
use ::alloc::{alloc, collections::TryReserveErrorKind};
use core::{
alloc::{Allocator, Layout},
cmp,
iter::FusedIterator,
marker::{PhantomData, Unsize},
mem::{self, ManuallyDrop},
ptr::{self, addr_of, NonNull},
};
use emplacable::{Emplacable, EmplacableFn, Emplacer};
use crate::{
helper::{
decompose, valid_align::ValidAlign, valid_size::ValidSizeUnaligned, MetadataRemainder,
SplitMetadata,
},
marker::Aligned,
unwrap_try_reserve_result,
};
use super::{TryReserveError, UnsizedVecImpl, UnsizedVecProvider};
struct ElementInfo<T: ?Sized> {
/// The pointer metadata of the element.
metadata: <T as SplitMetadata>::Remainder,
/// The offset that the element following this one would be stored at,
/// but disregarding padding due to over-alignment.
/// We use this encoding to store the sizes of `Vec` elements
/// because it allows for *O(1)* random access while only storing
/// a single `usize`.
///
/// To get the actual offset of the next element, use
/// `unchecked_pad_to(end_offset, align)`.
end_offset: ValidSizeUnaligned,
}
impl<T: ?Sized> Clone for ElementInfo<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T: ?Sized> Copy for ElementInfo<T> {}
pub(in super::super) struct UnalignedVecInner<T: ?Sized> {
ptr: NonNull<()>,
/// # Safety
///
/// For simplicity, must be a multiple of `self.align`.
byte_capacity: ValidSizeUnaligned,
elems_info: ManuallyDrop<::alloc::vec::Vec<ElementInfo<T>>>,
align: ValidAlign,
_marker: PhantomData<T>,
}
impl<T: ?Sized> UnalignedVecInner<T> {
/// The number of bytes this vec is curretly using,
/// discounting padding following the last element.
#[inline]
fn unaligned_byte_len(&self) -> ValidSizeUnaligned {
self.elems_info
.last()
.map_or(ValidSizeUnaligned::ZERO, |last| last.end_offset)
}
/// The number of bytes this vec is curretly using,
/// including padding following the last element.
#[inline]
fn aligned_byte_len(&self) -> ValidSizeUnaligned {
// SAFETY: it's an invariant of the capacity field that this be legal
unsafe { self.unaligned_byte_len().unchecked_pad_to(self.align) }
}
/// Returns the offset of the start of this element in the vec.
///
/// # Safety
///
/// Does not bounds checks
#[inline]
unsafe fn start_offset_of_unchecked(&self, index: usize) -> ValidSizeUnaligned {
index
.checked_sub(1)
.map_or(ValidSizeUnaligned::ZERO, |index_m_1|
// SAFETY: precondition of function
unsafe {
self.elems_info
.get_unchecked(index_m_1)
.end_offset
.unchecked_pad_to(self.align)
})
}
/// Returns the maximum alignment among all the elements in the vec.
/// Used by `shrink`.
#[inline]
fn max_align_of_elems(&self) -> ValidAlign {
self.iter()
.map(ValidAlign::of_val)
.max()
.unwrap_or(ValidAlign::ONE)
}
/// Used in `try_reserve_exact_bytes_align_unchecked`.
///
/// # Safety
///
/// `old_align <= new_align` must hold.
unsafe fn len_after_realign_up(
&mut self,
old_align: ValidAlign,
new_align: ValidAlign,
) -> Option<ValidSizeUnaligned> {
debug_assert!(old_align <= new_align);
let mut new_pad_to_new: ValidSizeUnaligned = ValidSizeUnaligned::ZERO;
self.elems_info.iter().try_fold(
ValidSizeUnaligned::ZERO,
|shift,
ElementInfo {
end_offset: old_end_offset,
..
}| {
let new_end_offset = old_end_offset.checked_add(shift)?;
new_pad_to_new = new_end_offset.checked_pad_to(new_align)?;
// SAFETY: `old_align <= new_align`, so if above call returned `Some`, this must be legal.
let new_pad_to_old = unsafe { new_end_offset.unchecked_pad_to(old_align) };
// SAFETY: `old_align <= new_align`, so can't underflow
let padding_difference = unsafe { new_pad_to_new.unchecked_sub(new_pad_to_old) };
shift.checked_add(padding_difference)
},
)?;
Some(new_pad_to_new)
}
/// Realigns all elements in the vec to the given `new_align`,
/// if the current align is less.
///
/// # Safety
///
/// `new_align > self.align` must hold.
/// `self.len() > 1` must hold.
///
/// Realigning must not lead to overflow.
///
/// `new_align` must be equal to the actual alignment of the allocation,
/// Also, this function does not allocate memory,
/// nor does it check that enough memory has been allocated.
///
/// Finally, this function doesn't update `self.align`, do that yourself.
unsafe fn realign_up(&mut self, new_align: ValidAlign) {
let old_align = self.align;
debug_assert!(self.len() > 1 && new_align > old_align);
// We compute the new offset of each element, along with the difference from the old offset.
// Then, we copy everything over.
// Doing this without allocating requires some complicated code.
//
// First we calculate how much we need to shift the very last element,
// then we perform the copies while reversing our calculations.
//
// The first element is already in the right place, its offset is 0.
// Starting here, our offsets are invalid, so unwinding is UB !!!
// To make this explicit, we use unckecked ops for arithmetic.
// This loop is basically `len_after_realign_up`, excpet with 0 checks and modifying metadata.
let final_offset_shift: ValidSizeUnaligned = self.elems_info.iter_mut().fold(
ValidSizeUnaligned::ZERO,
|shift, ElementInfo { end_offset, .. }| {
// SAFETY: precondition of function
unsafe {
let new_end_offset = end_offset.unchecked_add(shift);
*end_offset = new_end_offset;
let new_pad_to_new = new_end_offset.unchecked_pad_to(new_align);
let new_pad_to_old = new_end_offset.unchecked_pad_to(old_align);
let padding_difference = new_pad_to_new.unchecked_sub(new_pad_to_old);
shift.unchecked_add(padding_difference)
}
},
);
// Now we go in reverse, and copy.
self.elems_info.array_windows::<2>().rev().fold(
final_offset_shift,
|shift_end,
&[ElementInfo {
end_offset: prev_end_offset,
..
}, ElementInfo {
end_offset: new_end_offset,
..
}]| {
// SAFETY:: See comments inside block
unsafe {
// SAFETY: Reversing computation in the last loop.
let new_pad_to_new = new_end_offset.unchecked_pad_to(new_align);
let new_pad_to_old = new_end_offset.unchecked_pad_to(old_align);
let padding_difference = new_pad_to_new.unchecked_sub(new_pad_to_old);
let shift_start = shift_end.unchecked_sub(padding_difference);
let new_start_offset = prev_end_offset.unchecked_pad_to(new_align);
let old_start_offset = new_start_offset.unchecked_sub(shift_start);
// SAFETY: End offset >= start offset
let size_of_val = new_end_offset.unchecked_sub(new_start_offset);
// SAFETY: moving element to new correct position, as computed above
ptr::copy(
self.ptr.as_ptr().cast::<u8>().add(old_start_offset.get()),
self.ptr.as_ptr().cast::<u8>().add(new_start_offset.get()),
size_of_val.get(),
);
shift_start
}
},
);
}
/// Realigns all elements in the vec to the given `new_align`,
/// if the current align is greater.
///
/// Opposite of `realign_up`.
///
/// # Safety
///
/// `new_align < self.align` must hold.
/// `new_align >= self.max_align_of_elems()` must hold.
/// `self.len() > 1` must hold.
///
/// This function does not shrink the allocation,
/// you will need to do that yourself,
/// *even if you don't change the allocated size*,
/// to ensure that the allocation is later deallocated
/// with the correct alignment.
///
/// Finally, this function doesn't update `self.align`, do that yourself.
unsafe fn realign_down(&mut self, new_align: ValidAlign) {
let old_align = self.align;
debug_assert!(self.len() > 1 && new_align < old_align);
// We compute the new offset of each element, along with the difference from the old offset.
// Then, we copy the eement over.
//
// This is a lot simpler than `realign_up`, we can do everyting in a single pass.
let mut shift_back = ValidSizeUnaligned::ZERO;
for &[ElementInfo {
end_offset: prev_new_end_offset,
..
}, ElementInfo {
end_offset: old_end_offset,
..
}] in self.elems_info.array_windows::<2>()
{
// SAFETY: shift must be smaller than size of allocation up to this point
let new_end_offset = unsafe { old_end_offset.unchecked_sub(shift_back) };
// SAFETY: can't overflow, or else unshifted allocation would have overflowed
let new_start_offset = unsafe { prev_new_end_offset.unchecked_pad_to(new_align) };
// SAFETY: shift must be smaller than size of allocation up to this point
let old_start_offset = unsafe { new_start_offset.unchecked_sub(shift_back) };
// SAFETY: End offset >= start offset
let size_of_val = unsafe { new_end_offset.unchecked_sub(new_start_offset) };
// SAFETY: moving element to new correct position, as computed above
unsafe {
ptr::copy(
self.ptr.as_ptr().cast::<u8>().add(old_start_offset.get()),
self.ptr.as_ptr().cast::<u8>().add(new_start_offset.get()),
size_of_val.get(),
);
}
// SAFETY: pads can't overfolow as otherwise old offsets would be invalid.
// Sub can't overflow as new_align < old_align.
// Add can't overflow as we can't shift more than the entire size of the allocation.
shift_back = unsafe {
shift_back.unchecked_add(
new_end_offset
.unchecked_pad_to(old_align)
.unchecked_sub(new_end_offset.unchecked_pad_to(new_align)),
)
};
}
}
}
impl<T: ?Sized> Drop for UnalignedVecInner<T> {
fn drop(&mut self) {
let mut start_offset: ValidSizeUnaligned = ValidSizeUnaligned::ZERO;
// SAFETY: we are in `drop`, nobody will access the `ManuallyDrop` after us
let elems_info = unsafe { ManuallyDrop::take(&mut self.elems_info) };
// Drop remaining elements
for ElementInfo {
metadata,
end_offset,
} in elems_info
{
// SAFETY: end of element can't be smaller than start
let size_of_val = unsafe { end_offset.unchecked_sub(start_offset) };
let metadata = metadata.as_metadata(size_of_val);
let start_of_alloc = self.ptr.as_ptr().cast::<u8>();
// SAFETY: offset is within allocation
let thin_ptr_to_elem = unsafe { start_of_alloc.add(start_offset.get()) };
let wide_ptr_to_elem: *mut T =
ptr::from_raw_parts_mut(thin_ptr_to_elem.cast(), metadata);
// SAFETY: align comes from the vec
start_offset = unsafe { end_offset.unchecked_pad_to(self.align) };
// SAFETY: nobody will access this after us
unsafe { wide_ptr_to_elem.drop_in_place() }
}
// Drop allocation
//
// SAFETY: capacity and align come from the vec.
unsafe {
let alloc_layout = self
.byte_capacity
.as_layout_with_align_unchecked(self.align);
alloc::Global.deallocate(self.ptr.cast(), alloc_layout);
}
}
}
impl<T: ?Sized> UnsizedVecProvider<T> for UnalignedVecInner<T> {
type Align = ValidAlign;
type Size = ValidSizeUnaligned;
type Iter<'a> = UnalignedIter<'a, T> where T: 'a;
type IterMut<'a> = UnalignedIterMut<'a, T> where T: 'a;
const NEW_ALIGN_1: UnalignedVecInner<T> = UnalignedVecInner {
ptr: <() as Aligned>::DANGLING_THIN,
byte_capacity: ValidSizeUnaligned::ZERO,
elems_info: ManuallyDrop::new(::alloc::vec::Vec::new()),
align: <()>::ALIGN,
_marker: PhantomData,
};
const NEW_ALIGN_PTR: UnalignedVecInner<T> = UnalignedVecInner {
ptr: <usize as Aligned>::DANGLING_THIN,
byte_capacity: ValidSizeUnaligned::ZERO,
elems_info: ManuallyDrop::new(::alloc::vec::Vec::new()),
align: <usize>::ALIGN,
_marker: PhantomData,
};
#[inline]
fn capacity(&self) -> usize {
self.elems_info.capacity()
}
#[inline]
fn byte_capacity(&self) -> usize {
self.byte_capacity.get()
}
#[inline]
fn align(&self) -> usize {
self.align.into()
}
fn try_reserve_exact_capacity_bytes_align(
&mut self,
additional: usize,
additional_bytes: usize,
align: ValidAlign,
) -> Result<(), TryReserveError> {
self.elems_info.try_reserve_exact(additional)?;
let old_align = self.align;
let new_align = cmp::max(old_align, align);
let old_cap = self.byte_capacity;
let (new_align, old_cap_realigned, size_of_existing_elems_realigned): (
ValidAlign,
ValidSizeUnaligned,
ValidSizeUnaligned,
) = if old_align < new_align {
(
new_align,
old_cap.checked_pad_to(new_align).ok_or(TryReserveError {
kind: TryReserveErrorKind::CapacityOverflow,
})?,
// SAFETY: just checked `old_align < new_align`
unsafe { self.len_after_realign_up(old_align, new_align) }
// Return early if existing elems overflow `isize`
// when realigned.
.ok_or(TryReserveError {
kind: TryReserveErrorKind::CapacityOverflow,
})?,
)
} else {
if additional_bytes == 0 {
return Ok(());
}
(old_align, old_cap, self.aligned_byte_len())
};
// Now we add on the additional size requested.
let new_size = size_of_existing_elems_realigned
.checked_add_pad(additional_bytes, align)
.ok_or(TryReserveError {
kind: TryReserveErrorKind::CapacityOverflow,
})?;
let old_cap = self.byte_capacity;
let new_cap = cmp::max(old_cap_realigned, new_size);
if old_align < new_align || old_cap < new_cap {
if new_cap > ValidSizeUnaligned::ZERO {
// SAFETY: `new_cap` checked to be legal for following call in all branches above
let new_layout = unsafe { new_cap.as_layout_with_align_unchecked(new_align) };
let new_ptr: NonNull<[u8]> = (if old_cap == ValidSizeUnaligned::ZERO {
alloc::Global.allocate(new_layout)
} else {
// SAFETY: `old_cap` and `old_align` come from the vec
unsafe {
let old_layout = old_cap.as_layout_with_align_unchecked(old_align);
alloc::Global.grow(self.ptr.cast(), old_layout, new_layout)
}
})
.map_err(|_| TryReserveError {
kind: TryReserveErrorKind::AllocError {
layout: new_layout,
non_exhaustive: (),
},
})?;
self.byte_capacity = ValidSizeUnaligned::new_squished_to(new_ptr.len(), new_align);
self.ptr = new_ptr.cast();
if old_align < new_align {
if self.len() > 1 {
// SAFETY: Just performed necessary allocation, if guard.
// Overflow covered by earlier checks.
unsafe { self.realign_up(new_align) };
}
self.align = new_align;
}
} else {
self.ptr = new_align.dangling_thin();
}
}
Ok(())
}
fn shrink_capacity_bytes_align_to(
&mut self,
min_capacity: usize,
min_byte_capacity: usize,
min_align: ValidAlign,
) {
self.elems_info.shrink_to(min_capacity);
let old_align = self.align;
let new_align = cmp::max(cmp::min(min_align, old_align), self.max_align_of_elems());
debug_assert!(new_align <= old_align);
let need_to_realign_elems = new_align < old_align && self.len() > 1;
if need_to_realign_elems {
// SAFETY: checked len, new vs old, max_align_of_elems above
unsafe { self.realign_down(new_align) }
}
// SAFETY: Can't overflow, otherwise old offsets would be invalids
let new_aligned_byte_len = unsafe { self.unaligned_byte_len().unchecked_pad_to(new_align) };
let old_byte_capacity = self.byte_capacity;
let new_byte_capacity = cmp::max(
// SAFETY: `old_byte_capacity` is a valid
// `ValidSizeUnaligned`, and result of `cmp::min`
// can't be bigger than it
unsafe {
ValidSizeUnaligned::new_unchecked(cmp::min(
min_byte_capacity,
old_byte_capacity.get(),
))
},
new_aligned_byte_len,
);
debug_assert!(new_byte_capacity <= old_byte_capacity);
if new_byte_capacity < old_byte_capacity || new_align < old_align {
// SAFETY: cap and align are valid as they come from the vec
let old_layout = unsafe { old_byte_capacity.as_layout_with_align_unchecked(old_align) };
if new_byte_capacity > ValidSizeUnaligned::ZERO {
let new_layout =
// SAFETY: cap and align are <= old (valid) cap and align
unsafe { new_byte_capacity.as_layout_with_align_unchecked(new_align) };
// `shrink` can unwind, in which case we need to make sure
// we realign everything back to how it was.
struct Realigner<'a, T: ?Sized> {
vec: &'a mut UnalignedVecInner<T>,
new_align: ValidAlign,
}
impl<'a, T: ?Sized> Drop for Realigner<'a, T> {
#[inline]
fn drop(&mut self) {
let old_align = self.vec.align;
self.vec.align = self.new_align;
// SAFETY: old_align > new_align, checked self.len(),
// adjusted `self.align`
unsafe { self.vec.realign_up(old_align) }
self.vec.align = old_align;
}
}
let alloc_ptr = self.ptr.cast();
// https://github.com/rust-lang/rust-clippy/issues/9427
#[allow(clippy::unnecessary_lazy_evaluations)]
let realigner = need_to_realign_elems.then(|| Realigner {
vec: self,
new_align,
});
let shrink_result =
// SAFETY: cap and align are <= old (valid) cap and align.
// old layout and ptr come from the vec.
unsafe { alloc::Global.shrink(alloc_ptr, old_layout, new_layout) };
let Ok(new_ptr) = shrink_result else {
// `realigner` will be dropped, restoring offsets
return;
};
mem::forget(realigner);
self.byte_capacity = ValidSizeUnaligned::new_squished_to(new_ptr.len(), new_align);
self.ptr = new_ptr.cast();
} else {
if old_byte_capacity > ValidSizeUnaligned::ZERO {
// SAFETY: `old_layout` components come from the vec
unsafe { alloc::Global.deallocate(self.ptr.cast(), old_layout) }
self.byte_capacity = ValidSizeUnaligned::ZERO;
}
self.ptr = new_align.dangling_thin();
}
self.align = new_align;
}
}
unsafe fn insert_unchecked(
&mut self,
index: usize,
element: T,
unaligned_size_of_val: ValidSizeUnaligned,
) {
debug_assert!(index <= self.len());
debug_assert!(self.capacity() > self.len());
// SAFETY: preconditions of function
let aligned_size_of_val = unsafe { unaligned_size_of_val.unchecked_pad_to(self.align) };
debug_assert!(
self.byte_capacity() >= (self.aligned_byte_len().get() + aligned_size_of_val.get())
);
debug_assert!(self.align() >= mem::align_of_val(&element));
let metadata =
<T as SplitMetadata>::Remainder::from_metadata(core::ptr::metadata(&element));
// SAFETY: preconditions of function
unsafe {
let start_offset = self.start_offset_of_unchecked(index);
let how_much_to_move = self.unaligned_byte_len().unchecked_sub(start_offset);
let start_ptr = self.ptr.cast::<u8>().as_ptr().add(index);
ptr::copy(
start_ptr,
start_ptr.add(aligned_size_of_val.get()),
how_much_to_move.get(),
);
ptr::copy_nonoverlapping(
addr_of!(element).cast(),
start_ptr,
unaligned_size_of_val.get(),
);
for ElementInfo { end_offset, .. } in self.elems_info.get_unchecked_mut(index..) {
*end_offset = end_offset.unchecked_add(aligned_size_of_val);
}
self.elems_info.insert_unchecked(
index,
ElementInfo {
metadata,
end_offset: start_offset.unchecked_add(unaligned_size_of_val),
},
(),
);
}
mem::forget_unsized(element);
}
unsafe fn insert_with_unchecked(
&mut self,
index: usize,
value: Emplacable<T, impl EmplacableFn<T>>,
) {
/// Helper to ensure elements are moved back
/// where they belong in case `inner_closure`
/// panics.
struct ElementShifterBacker {
ptr_to_index: *mut u8,
num_bytes_to_shift: ValidSizeUnaligned,
shift_by_bytes: ValidSizeUnaligned,
}
impl Drop for ElementShifterBacker {
#[inline]
fn drop(&mut self) {
// SAFETY: shifting elements back in case of drop
unsafe {
ptr::copy(
self.ptr_to_index.add(self.shift_by_bytes.get()),
self.ptr_to_index,
self.num_bytes_to_shift.get(),
);
}
}
}
debug_assert!(index <= self.len());
let emplacable_closure = value.into_fn();
let emplacer_closure =
&mut |layout, metadata, inner_closure: &mut dyn FnMut(*mut PhantomData<T>)| {
let (unaligned_size_of_val, align_of_val) = decompose(layout);
let reserve_result = self.try_reserve_exact_capacity_bytes_align(
1,
unaligned_size_of_val.get(),
align_of_val,
);
unwrap_try_reserve_result(reserve_result);
let aligned_size_of_val =
// SAFETY: `try_reserve` would have failed if this could fail
unsafe { unaligned_size_of_val.unchecked_pad_to(self.align) };
// SAFETY: precondition of function
let start_offset = unsafe { self.start_offset_of_unchecked(index) };
// SAFETY: getting pointer to element
let ptr_to_elem = unsafe { self.ptr.cast::<u8>().as_ptr().add(start_offset.get()) };
let unaligned_len = self.unaligned_byte_len();
// SAFETY: by precondition of function
let num_bytes_to_shift = unsafe { unaligned_len.unchecked_sub(start_offset) };
let shifter_backer = ElementShifterBacker {
ptr_to_index: ptr_to_elem,
num_bytes_to_shift,
shift_by_bytes: aligned_size_of_val,
};
// SAFETY: copying elements right to make room
unsafe {
ptr::copy(
ptr_to_elem,
ptr_to_elem.add(aligned_size_of_val.get()),
num_bytes_to_shift.get(),
);
}
// If this unwinds, `shifter_backer` will be dropped
// and the elements will be moved back where they belong.
inner_closure(ptr_to_elem.cast());
// `inner_closure` succeeded, so don't want to move elements back now!
mem::forget(shifter_backer);
// SAFETY: by precondition of function
let elems_to_move_back = unsafe { self.elems_info.get_unchecked_mut(index..) };
for ElementInfo { end_offset, .. } in elems_to_move_back {
// SAFETY: make the offsets correct again
*end_offset = unsafe { end_offset.unchecked_add(aligned_size_of_val) };
}
// SAFETY: reserved memory earlier
unsafe {
self.elems_info.insert_unchecked(
index,
ElementInfo {
metadata: <T as SplitMetadata>::Remainder::from_metadata(metadata),
end_offset: start_offset.unchecked_add(unaligned_size_of_val),
},
(),
);
}
};
// SAFETY: `emplacer_closure` runs the closure with a valid pointer to `index`
let emplacer = unsafe { Emplacer::from_fn(emplacer_closure) };
emplacable_closure(emplacer);
}
unsafe fn remove_into_unchecked(&mut self, index: usize, emplacer: &mut Emplacer<'_, T>) {
debug_assert!(index < self.len());
// We can't remove the metadata yet, as `emplacer_closure` might unwind,
// so we can't leave vec metadata in an invalid state.
// SAFETY: by precondition of function
let removed_elem_metadata = unsafe { self.elems_info.get_unchecked(index) };
let ElementInfo {
metadata,
end_offset,
} = removed_elem_metadata;
// SAFETY: precondition of function
let start_offset = unsafe { self.start_offset_of_unchecked(index) };
// SAFETY: start_offset < end_offset
let unaligned_size_of_val = unsafe { end_offset.unchecked_sub(start_offset) };
// SAFETY: `val` comes from the vec so must be paddable
let aligned_size_of_val = unsafe { unaligned_size_of_val.unchecked_pad_to(self.align) };
let metadata = metadata.as_metadata(unaligned_size_of_val);
// Get pointer to the element we are popping out of the vec
// SAFETY: offset comes from vec
let ptr_to_elem = unsafe {
self.ptr
.as_ptr()
.cast_const()
.cast::<u8>()
.add(start_offset.get())
};
let wide_ptr_to_elem: *const T = ptr::from_raw_parts(ptr_to_elem.cast(), metadata);
// SAFETY: the element is still initialized at this point
let align_of_val = ValidAlign::of_val(unsafe { &*wide_ptr_to_elem });
// Copy element into the place
// SAFETY: we call the closure right after we unwrap it
let emplacer_closure = unsafe { emplacer.into_fn() };
emplacer_closure(
// SAFETY: `size_of_val` comes from the vec
unsafe { unaligned_size_of_val.as_layout_with_align_unchecked(align_of_val) },
metadata,
&mut |out_ptr| {
if !out_ptr.is_null() {
// SAFETY: we are allowed to copy `size_of_val` bytes into `out_ptr`,
// by the preconditions of `Emplacer::new`
unsafe {
ptr::copy_nonoverlapping(
ptr_to_elem,
out_ptr.cast::<u8>(),
unaligned_size_of_val.get(),
);
}
} else {
// SAFETY: we adjust vec metadata right after, so this won't be double-dropped
unsafe { wide_ptr_to_elem.cast_mut().drop_in_place() }
}
},
);
// Now that `emplacer_closure` has run successfuly, we don't need to worry
// about exception safety anymore.
// FIXME elide bounds check
self.elems_info.remove(index);
for ElementInfo { end_offset, .. } in
// SAFETY: `index` in range by preconditions of function.
unsafe { self.elems_info.get_unchecked_mut(index..) }
{
// SAFETY: `end_fooset >= size_of_val` for elements following something
// of size `size_of_val`
unsafe {
*end_offset = end_offset.unchecked_sub(aligned_size_of_val);
}
}
let unaligned_len = self.unaligned_byte_len();
// SAFETY: new end of vec can't be to the left of old start of elem at `index`
let how_much_to_move = unsafe { unaligned_len.unchecked_sub(start_offset) };
// SAFETY: copying elements back where they belong
unsafe {
ptr::copy(
ptr_to_elem.add(aligned_size_of_val.get()),
ptr_to_elem.cast_mut(),
how_much_to_move.get(),
);
}
}
#[inline]
unsafe fn push_unchecked(&mut self, value: T, size_of_val: ValidSizeUnaligned) {
debug_assert!(self.capacity() - self.len() > 0);
debug_assert!(self.byte_capacity() >= (self.aligned_byte_len().get() + size_of_val.get()));
debug_assert!(self.align() >= mem::align_of_val(&value));
let metadata = <T as SplitMetadata>::Remainder::from_metadata(core::ptr::metadata(&value));
let start_offset = self.aligned_byte_len();
// SAFETY: preconditions of function
unsafe {
ptr::copy_nonoverlapping(
addr_of!(value).cast(),
self.ptr.as_ptr().cast::<u8>().add(start_offset.get()),
size_of_val.get(),
);
self.elems_info.push_unchecked(
ElementInfo {
metadata,
end_offset: start_offset.unchecked_add(size_of_val),
},
(),
);
}
mem::forget_unsized(value);
}
fn push_with(&mut self, value: Emplacable<T, impl EmplacableFn<T>>) {
let emplacable_closure = value.into_fn();
let emplacer_closure =
&mut |layout: Layout, metadata, inner_closure: &mut dyn FnMut(*mut PhantomData<T>)| {
let (size_of_val, align_of_val) = decompose(layout);
let reserve_result =
self.try_reserve_exact_capacity_bytes_align(1, layout.size(), align_of_val);
unwrap_try_reserve_result(reserve_result);
let start_offset = self.aligned_byte_len();
// SAFETY: getting pointer to end of allocation
let ptr_to_elem = unsafe { self.ptr.cast::<u8>().as_ptr().add(start_offset.get()) };
inner_closure(ptr_to_elem.cast());
let elem_info: ElementInfo<T> = ElementInfo {
metadata: <T as SplitMetadata>::Remainder::from_metadata(metadata),
// SAFETY: neither operand can overflow `isize`, so sum
// can't overflow `usize`
end_offset: unsafe { start_offset.unchecked_add(size_of_val) },
};
// SAFETY: `emplacable` wrote new element at end of vec,
// and we have reserved the needed space
unsafe { self.elems_info.push_unchecked(elem_info, ()) };
};
// SAFETY: `emplacer_closure` runs the closure with a valid pointer to the end of the vec
let emplacer = unsafe { Emplacer::from_fn(emplacer_closure) };
emplacable_closure(emplacer);
}
#[inline]
unsafe fn pop_into_unchecked(&mut self, emplacer: &mut Emplacer<'_, T>) {
debug_assert!(!self.elems_info.is_empty());
// SAFETY: precondition of function
let last_elem_metadata = unsafe { self.elems_info.pop().unwrap_unchecked() };
let ElementInfo {
metadata,
end_offset,
} = last_elem_metadata;
let start_offset = self.aligned_byte_len();
// SAFETY: start_offset < end_offset
let size_of_val = unsafe { end_offset.unchecked_sub(start_offset) };
let metadata = metadata.as_metadata(size_of_val);
// Get pointer to the element we are popping out of the vec
// SAFETY: offset comes from vec
let ptr_to_elem = unsafe {
self.ptr
.as_ptr()
.cast_const()
.cast::<u8>()
.add(start_offset.get())
};
let wide_ptr_to_elem: *const T = ptr::from_raw_parts(ptr_to_elem.cast(), metadata);
// SAFETY: the element is still initialized at this point
let align_of_val = ValidAlign::of_val(unsafe { &*wide_ptr_to_elem });
// Copy element into the place
// SAFETY: we call the closure right after we unwrap it
let emplace_closure = unsafe { emplacer.into_fn() };
emplace_closure(
// SAFETY: `size_of_val` comes from the vec
unsafe { size_of_val.as_layout_with_align_unchecked(align_of_val) },
metadata,
&mut |out_ptr| {
if !out_ptr.is_null() {
// SAFETY: we are allowed to copy `size_of_val` bytes into `out_ptr`,
// by the preconditions of `Emplacer::new`
unsafe {
ptr::copy_nonoverlapping(
ptr_to_elem,
out_ptr.cast::<u8>(),
size_of_val.get(),
);
}
} else {
// SAFETY: we adjusted vec metadata earlier, so this won't be double-dropped
unsafe { wide_ptr_to_elem.cast_mut().drop_in_place() }
}
},
);
}
#[inline]
fn len(&self) -> usize {
self.elems_info.len()
}
#[inline]
unsafe fn get_unchecked_raw(&self, index: usize) -> NonNull<T> {
debug_assert!(index < self.len());
// SAFETY: see individual comments inside block
unsafe {
// SAFETY: precondition of method
let start_offset = self.start_offset_of_unchecked(index);
let &ElementInfo {
end_offset,
metadata,
} = self.elems_info.get_unchecked(index);
// SAFETY: end >= start
let size_of_val = end_offset.unchecked_sub(start_offset);
let metadata = metadata.as_metadata(size_of_val);
// SAFETY: `start_offset` in range of allocation
NonNull::from_raw_parts(
NonNull::new_unchecked(self.ptr.as_ptr().cast::<u8>().add(start_offset.get()))
.cast(),
metadata,
)
}
}
#[inline]
fn iter(&self) -> Self::Iter<'_> {
UnalignedIter {
elems_info: self.elems_info.iter(),
ptr: self.ptr,
start_offset: ValidSizeUnaligned::ZERO,
align: self.align,
}
}
#[inline]
fn iter_mut(&mut self) -> Self::IterMut<'_> {
UnalignedIterMut {
elems_info: self.elems_info.iter(),
ptr: self.ptr,
start_offset: ValidSizeUnaligned::ZERO,
align: self.align,
}
}
#[inline]
fn from_sized<S>(vec: ::alloc::vec::Vec<S>) -> Self
where
S: Unsize<T>,
{
let mut vec = ManuallyDrop::new(vec);
let len_elems = vec.len();
let cap_elems = vec.capacity();
let heap_ptr = vec.as_mut_ptr();
let heap_ptr_unsized: *mut T = heap_ptr;
let metadata =
<T as SplitMetadata>::Remainder::from_metadata(ptr::metadata(heap_ptr_unsized));
// SAFETY: ptr comes from vec, can't be null
let heap_ptr_thin: NonNull<()> = unsafe { NonNull::new_unchecked(heap_ptr_unsized.cast()) };
// SAFETY: can't overflow, as otherwise allocation would be overflowing
let byte_capacity = unsafe { cap_elems.unchecked_mul(mem::size_of::<S>()) };
// SAFETY: same as above
let byte_capacity = unsafe { ValidSizeUnaligned::new_unchecked(byte_capacity) };
let elems_info = (0..len_elems)
.map(|index| ElementInfo {
metadata,
// SAFETY: can't overflow, as otherwise allocation would be overflowing
end_offset: unsafe {
ValidSizeUnaligned::new_unchecked(index.unchecked_mul(mem::size_of::<S>()))
},
})
.collect();
let elems_info = ManuallyDrop::new(elems_info);
Self {
ptr: heap_ptr_thin,
byte_capacity,
elems_info,
align: S::ALIGN,
_marker: PhantomData,
}
}
}
impl<T: ?Sized> UnsizedVecImpl for T {
default type Impl = UnalignedVecInner<T>;
}
macro_rules! iter_ref {
($iter_ty:ident, $from_raw_parts:ident $($muta:ident)?) => {
pub(in super::super) struct $iter_ty<'a, T: ?Sized> {
elems_info: core::slice::Iter<'a, ElementInfo<T>>,
ptr: NonNull<()>,
start_offset: ValidSizeUnaligned,
align: ValidAlign,
}
impl<'a, T: ?Sized + 'a> Iterator for $iter_ty<'a, T> {
type Item = &'a $($muta)? T;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
let ElementInfo {
metadata,
end_offset,
} = *self.elems_info.next()?;
// SAFETY: end of element can't be smaller than start
let size_of_val = unsafe { end_offset.unchecked_sub(self.start_offset) };
let metadata = metadata.as_metadata(size_of_val);
let start_of_alloc = self.ptr.as_ptr().cast::<u8>();
// SAFETY: offset is within allocation
let thin_ptr_to_elem = unsafe { start_of_alloc.add(self.start_offset.get()) };
let wide_ptr = ptr::$from_raw_parts(thin_ptr_to_elem.cast(), metadata);
// SAFETY: pointer to element of vec
let wide_ref = unsafe { & $($muta)? *wide_ptr };
// SAFETY: align comes from the vec
self.start_offset = unsafe { end_offset.unchecked_pad_to(self.align) };
Some(wide_ref)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.elems_info.size_hint()
}
#[inline]
fn count(self) -> usize
where
Self: Sized,
{
self.elems_info.count()
}
#[inline]
fn nth(&mut self, n: usize) -> Option<Self::Item> {
let start_offset = n
.checked_sub(1)
.and_then(|n| self.elems_info.nth(n))
.copied()
// SAFETY: offset comes from the vec
.map_or(ValidSizeUnaligned::ZERO, |e_i| unsafe {
e_i.end_offset.unchecked_pad_to(self.align)
});
let ElementInfo {
metadata,
end_offset,
} = *self.elems_info.next()?;
// SAFETY: end of element can't be smaller than start`
let size_of_val = unsafe { end_offset.unchecked_sub(start_offset) };
let metadata = metadata.as_metadata(size_of_val);
let start_of_alloc = self.ptr.as_ptr().cast::<u8>();
// SAFETY: offset is within allocation
let thin_ptr_to_elem = unsafe { start_of_alloc.add(start_offset.get()) };
let wide_ptr = ptr::$from_raw_parts(thin_ptr_to_elem.cast(), metadata);
// SAFETY: pointer to element of vec
let wide_ref = unsafe { & $($muta)? *wide_ptr };
// SAFETY: offset comes from the vec
self.start_offset = unsafe { end_offset.unchecked_pad_to(self.align) };
Some(wide_ref)
}
#[inline]
fn last(mut self) -> Option<Self::Item>
where
Self: Sized,
{
self.nth(self.elems_info.len().checked_sub(1)?)
}
}
impl<'a, T: ?Sized + 'a> DoubleEndedIterator for $iter_ty<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<Self::Item> {
let ElementInfo {
metadata,
end_offset,
} = *self.elems_info.next_back()?;
let start_offset = self
.elems_info
.as_slice()
.last()
// SAFETY: offset comes from the vec
.map_or(ValidSizeUnaligned::ZERO, |e_i| unsafe {
e_i.end_offset.unchecked_pad_to(self.align)
});
// SAFETY: end of element can't be smaller than start
let size_of_val = unsafe { end_offset.unchecked_sub(start_offset) };
let metadata = metadata.as_metadata(size_of_val);
let start_of_alloc = self.ptr.as_ptr().cast::<u8>();
// SAFETY: offset is within allocation
let thin_ptr_to_elem = unsafe { start_of_alloc.add(start_offset.get()) };
let wide_ptr = ptr::$from_raw_parts(thin_ptr_to_elem.cast(), metadata);
// SAFETY: pointer to element of vec
let wide_ref = unsafe { & $($muta)? *wide_ptr };
Some(wide_ref)
}
}
impl<'a, T: ?Sized + 'a> ExactSizeIterator for $iter_ty<'a, T> {
#[inline]
fn len(&self) -> usize {
self.elems_info.len()
}
}
impl<'a, T: ?Sized + 'a> FusedIterator for $iter_ty<'a, T> {}
};
}
iter_ref!(UnalignedIter, from_raw_parts);
iter_ref!(UnalignedIterMut, from_raw_parts_mut mut);