1use super::ShardId;
4use crate::hash_map::{Entry, HashMap};
5use crate::prelude::*;
6use crate::runtime::vm::CompiledModuleId;
7use std::mem;
8use std::sync::Mutex;
9use wasmtime_environ::DefinedMemoryIndex;
10
11#[derive(Hash, Clone, Copy, Debug, PartialEq, Eq)]
13pub struct SlotId(pub u32);
14
15impl SlotId {
16 pub fn index(self) -> usize {
18 self.0 as usize
19 }
20}
21
22#[derive(Debug)]
28pub struct SimpleIndexAllocator(ModuleAffinityIndexAllocator);
29
30impl SimpleIndexAllocator {
31 pub fn new(capacity: u32) -> Result<Self, OutOfMemory> {
32 Ok(SimpleIndexAllocator(ModuleAffinityIndexAllocator::new(
33 capacity, 0,
34 )?))
35 }
36
37 pub fn is_empty(&self) -> bool {
38 self.0.is_empty()
39 }
40
41 pub fn alloc(&self) -> Option<SlotId> {
42 self.0.alloc(None)
43 }
44
45 pub(crate) fn free(&self, index: SlotId, bytes_resident: usize) {
51 self.0.free(index, bytes_resident);
52 }
53
54 pub(crate) fn free_many(&self, items: impl IntoIterator<Item = (SlotId, usize)>) {
57 self.0.free_many(items);
58 }
59
60 pub fn unused_warm_slots(&self) -> u32 {
66 self.0.unused_warm_slots()
67 }
68
69 pub fn unused_bytes_resident(&self) -> usize {
75 self.0.unused_bytes_resident()
76 }
77
78 #[cfg(test)]
79 pub(crate) fn testing_freelist(&self) -> Vec<SlotId> {
80 self.0.testing_freelist()
81 }
82}
83
84#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
86pub struct MemoryInModule(pub CompiledModuleId, pub DefinedMemoryIndex);
87
88#[derive(Debug)]
91pub struct ModuleAffinityIndexAllocator {
92 shards: Box<[super::CachePadded<Mutex<Inner>>]>,
106 slots_per_shard: u32,
107}
108
109#[derive(Debug)]
110struct Inner {
111 max_unused_warm_slots: u32,
118
119 unused_warm_slots: u32,
124
125 warm: List,
128
129 last_cold: u32,
134
135 slot_state: Vec<SlotState>,
140
141 module_affine: HashMap<MemoryInModule, List>,
147
148 unused_bytes_resident: usize,
150}
151
152#[derive(Default, Debug)]
154struct List {
155 head: Option<SlotId>,
156 tail: Option<SlotId>,
157}
158
159#[derive(Default, Debug, Copy, Clone)]
162struct Link {
163 prev: Option<SlotId>,
164 next: Option<SlotId>,
165}
166
167#[derive(Clone, Debug)]
168enum SlotState {
169 Used(Option<MemoryInModule>),
171
172 UnusedCold,
174
175 UnusedWarm(Unused),
180}
181
182impl SlotState {
183 fn unwrap_unused(&mut self) -> &mut Unused {
184 match self {
185 SlotState::UnusedWarm(u) => u,
186 _ => unreachable!(),
187 }
188 }
189}
190
191#[derive(Default, Copy, Clone, Debug)]
192struct Unused {
193 affinity: Option<MemoryInModule>,
195
196 bytes_resident: usize,
199
200 affine_list_link: Link,
202
203 unused_list_link: Link,
205}
206
207enum AllocMode {
208 ForceAffineAndClear,
209 AnySlot,
210 AnyWarm,
211}
212
213#[derive(Debug, PartialEq, Eq)]
216struct ShardLayout {
217 slots_per_shard: u32,
220 shards: Box<[(u32, u32)]>,
222}
223
224impl ShardLayout {
225 fn new(
226 capacity: u32,
227 max_unused_warm_slots: u32,
228 requested_shards: u32,
229 ) -> Result<ShardLayout, OutOfMemory> {
230 let nshards = if capacity >= 128 {
247 requested_shards.max(1)
248 } else {
249 1
250 };
251 let slots_per_shard = capacity.div_ceil(nshards).max(1);
252 let nshards = capacity.div_ceil(slots_per_shard).max(1);
253
254 let shards = (0..nshards)
255 .map(|i| {
256 let base = i * slots_per_shard;
257 let shard_capacity = capacity.saturating_sub(base).min(slots_per_shard);
258 let shard_warm = max_unused_warm_slots / nshards
261 + u32::from(i < max_unused_warm_slots % nshards);
262 (shard_capacity, shard_warm)
263 })
264 .try_collect()?;
265
266 Ok(ShardLayout {
267 slots_per_shard,
268 shards,
269 })
270 }
271}
272
273impl ModuleAffinityIndexAllocator {
274 pub fn new(capacity: u32, max_unused_warm_slots: u32) -> Result<Self, OutOfMemory> {
276 Self::new_with_shard_count(
277 capacity,
278 max_unused_warm_slots,
279 super::default_shard_count(),
280 )
281 }
282
283 fn new_with_shard_count(
286 capacity: u32,
287 max_unused_warm_slots: u32,
288 requested_shards: u32,
289 ) -> Result<Self, OutOfMemory> {
290 let layout = ShardLayout::new(capacity, max_unused_warm_slots, requested_shards)?;
291 let shards = layout
292 .shards
293 .iter()
294 .map(|&(shard_capacity, shard_warm)| {
295 super::CachePadded(Mutex::new(Inner {
296 last_cold: 0,
297 max_unused_warm_slots: shard_warm,
298 unused_warm_slots: 0,
299 module_affine: HashMap::new(),
300 slot_state: (0..shard_capacity).map(|_| SlotState::UnusedCold).collect(),
301 warm: List::default(),
302 unused_bytes_resident: 0,
303 }))
304 })
305 .try_collect()?;
306
307 Ok(ModuleAffinityIndexAllocator {
308 shards,
309 slots_per_shard: layout.slots_per_shard,
310 })
311 }
312
313 fn global_id(&self, shard: ShardId, local: SlotId) -> SlotId {
315 SlotId(u32::try_from(shard.index()).unwrap() * self.slots_per_shard + local.0)
316 }
317
318 fn shard_of(&self, global: SlotId) -> (ShardId, SlotId) {
320 let shard = ShardId::from_index((global.0 / self.slots_per_shard) as usize);
321 (shard, SlotId(global.0 % self.slots_per_shard))
322 }
323
324 fn shard(&self, shard: ShardId) -> &Mutex<Inner> {
326 &self.shards[shard.index()].0
327 }
328
329 fn shard_ids(&self) -> impl Iterator<Item = ShardId> + use<> {
331 (0..self.shards.len()).map(ShardId::from_index)
332 }
333
334 pub fn len(&self) -> usize {
336 self.shards
337 .iter()
338 .map(|s| s.0.lock().unwrap().slot_state.len())
339 .sum()
340 }
341
342 pub fn is_empty(&self) -> bool {
344 self.shards.iter().all(|s| {
345 !s.0.lock()
346 .unwrap()
347 .slot_state
348 .iter()
349 .any(|state| matches!(state, SlotState::Used(_)))
350 })
351 }
352
353 pub fn alloc(&self, for_memory: Option<MemoryInModule>) -> Option<SlotId> {
358 for shard in super::shard_ids_from_home(self.shards.len()) {
362 let mut inner = self.shard(shard).lock().unwrap();
363 if let Some((local, _)) = Self::alloc_within(&mut inner, for_memory, AllocMode::AnySlot)
364 {
365 return Some(self.global_id(shard, local));
366 }
367 }
368 None
369 }
370
371 pub fn alloc_affine_and_clear_affinity(
379 &self,
380 module_id: CompiledModuleId,
381 memory_index: DefinedMemoryIndex,
382 ) -> Option<SlotId> {
383 for shard in self.shard_ids() {
386 let mut inner = self.shard(shard).lock().unwrap();
387 if let Some((local, _)) = Self::alloc_within(
388 &mut inner,
389 Some(MemoryInModule(module_id, memory_index)),
390 AllocMode::ForceAffineAndClear,
391 ) {
392 return Some(self.global_id(shard, local));
393 }
394 }
395 None
396 }
397
398 fn alloc_within(
401 inner: &mut Inner,
402 for_memory: Option<MemoryInModule>,
403 mode: AllocMode,
404 ) -> Option<(SlotId, usize)> {
405 let slot_id = inner.pick_affine(for_memory).or_else(|| {
409 match mode {
410 AllocMode::AnySlot => {
431 if inner.unused_warm_slots < inner.max_unused_warm_slots {
432 inner.pick_cold().or_else(|| inner.pick_warm())
433 } else {
434 inner.pick_warm().or_else(|| {
435 debug_assert!(inner.max_unused_warm_slots == 0);
436 inner.pick_cold()
437 })
438 }
439 }
440
441 AllocMode::ForceAffineAndClear => None,
446
447 AllocMode::AnyWarm => inner.pick_warm(),
449 }
450 })?;
451
452 let slot = &mut inner.slot_state[slot_id.index()];
453 let (affinity, bytes_resident) = match slot {
454 SlotState::UnusedWarm(u) => (u.affinity, u.bytes_resident),
455 _ => (None, 0),
456 };
457 inner.unused_bytes_resident -= bytes_resident;
458 *slot = SlotState::Used(match mode {
459 AllocMode::ForceAffineAndClear => None,
460 AllocMode::AnySlot => for_memory,
461 AllocMode::AnyWarm => {
462 debug_assert!(for_memory.is_none());
463 affinity
464 }
465 });
466
467 Some((slot_id, bytes_resident))
468 }
469
470 pub(crate) fn free(&self, index: SlotId, bytes_resident: usize) {
471 let (shard, local) = self.shard_of(index);
472 let mut inner = self.shard(shard).lock().unwrap();
473 Self::free_locked(&mut inner, local, bytes_resident);
474 }
475
476 pub(crate) fn free_many(&self, items: impl IntoIterator<Item = (SlotId, usize)>) {
480 let mut per_shard: smallvec::SmallVec<[smallvec::SmallVec<[(SlotId, usize); 8]>; 16]> =
481 (0..self.shards.len()).map(|_| Default::default()).collect();
482 for (index, bytes_resident) in items {
483 let (shard, local) = self.shard_of(index);
484 per_shard[shard.index()].push((local, bytes_resident));
485 }
486 for (shard, items) in per_shard.into_iter().enumerate() {
487 if items.is_empty() {
488 continue;
489 }
490 let mut inner = self.shard(ShardId::from_index(shard)).lock().unwrap();
491 for (local, bytes_resident) in items {
492 Self::free_locked(&mut inner, local, bytes_resident);
493 }
494 }
495 }
496
497 fn free_locked(inner: &mut Inner, index: SlotId, bytes_resident: usize) {
498 let module_memory = match inner.slot_state[index.index()] {
499 SlotState::Used(module_memory) => module_memory,
500 _ => unreachable!(),
501 };
502
503 inner.unused_warm_slots += 1;
507 let unused_list_link = inner
508 .warm
509 .append(index, &mut inner.slot_state, |s| &mut s.unused_list_link);
510
511 let affine_list_link = match module_memory {
512 Some(module) => match inner.module_affine.entry(module) {
516 Entry::Occupied(mut e) => e
517 .get_mut()
518 .append(index, &mut inner.slot_state, |s| &mut s.affine_list_link),
519 Entry::Vacant(v) => {
520 v.insert(List::new(index));
521 Link::default()
522 }
523 },
524
525 None => Link::default(),
527 };
528
529 inner.unused_bytes_resident += bytes_resident;
530 inner.slot_state[index.index()] = SlotState::UnusedWarm(Unused {
531 affinity: module_memory,
532 bytes_resident,
533 affine_list_link,
534 unused_list_link,
535 });
536 }
537
538 #[cfg(test)]
540 pub fn num_empty_slots(&self) -> usize {
541 self.shards
542 .iter()
543 .map(|s| {
544 let inner = s.0.lock().unwrap();
545 let total_slots = inner.slot_state.len();
546 (total_slots - inner.last_cold as usize) + inner.unused_warm_slots as usize
547 })
548 .sum()
549 }
550
551 #[cfg(test)]
554 pub(crate) fn testing_freelist(&self) -> Vec<SlotId> {
555 self.shard_ids()
556 .flat_map(|shard| {
557 let inner = self.shard(shard).lock().unwrap();
558 inner
559 .warm
560 .iter(&inner.slot_state, |s| &s.unused_list_link)
561 .map(|local| self.global_id(shard, local))
562 .collect::<Vec<_>>()
563 })
564 .collect()
565 }
566
567 #[cfg(test)]
570 pub(crate) fn testing_module_affinity_list(&self) -> Vec<MemoryInModule> {
571 let mut ret = Vec::new();
572 for s in self.shards.iter() {
573 let inner = s.0.lock().unwrap();
574 for key in inner.module_affine.keys() {
575 if !ret.contains(key) {
576 ret.push(*key);
577 }
578 }
579 }
580 ret
581 }
582
583 pub fn unused_warm_slots(&self) -> u32 {
589 self.shards
590 .iter()
591 .map(|s| s.0.lock().unwrap().unused_warm_slots)
592 .sum()
593 }
594
595 pub(crate) fn take_resident_warm_slots(&self) -> Vec<(SlotId, usize)> {
605 let mut taken = Vec::new();
606 for (shard_index, shard) in self.shards.iter().enumerate() {
607 let mut inner = shard.0.lock().unwrap();
608 while let Some((slot, bytes_resident)) =
609 Self::alloc_within(&mut inner, None, AllocMode::AnyWarm)
610 {
611 taken.push((
612 self.global_id(ShardId::from_index(shard_index), slot),
613 bytes_resident,
614 ));
615 }
616 }
617 taken
618 }
619
620 pub fn unused_bytes_resident(&self) -> usize {
626 self.shards
627 .iter()
628 .map(|s| s.0.lock().unwrap().unused_bytes_resident)
629 .sum()
630 }
631}
632
633impl Inner {
634 fn pick_affine(&mut self, for_memory: Option<MemoryInModule>) -> Option<SlotId> {
637 let ret = self.module_affine.get(&for_memory?)?.tail?;
641 self.remove(ret);
642 Some(ret)
643 }
644
645 fn pick_warm(&mut self) -> Option<SlotId> {
646 let head = self.warm.head?;
651 self.remove(head);
652 Some(head)
653 }
654
655 fn remove(&mut self, slot: SlotId) {
656 self.unused_warm_slots -= 1;
659 self.warm
660 .remove(slot, &mut self.slot_state, |u| &mut u.unused_list_link);
661
662 let module = self.slot_state[slot.index()].unwrap_unused().affinity;
667 if let Some(module) = module {
668 let mut list = match self.module_affine.entry(module) {
669 Entry::Occupied(e) => e,
670 Entry::Vacant(_) => unreachable!(),
671 };
672 list.get_mut()
673 .remove(slot, &mut self.slot_state, |u| &mut u.affine_list_link);
674
675 if list.get_mut().head.is_none() {
676 list.remove();
677 }
678 }
679 }
680
681 fn pick_cold(&mut self) -> Option<SlotId> {
682 if (self.last_cold as usize) == self.slot_state.len() {
683 None
684 } else {
685 let ret = Some(SlotId(self.last_cold));
686 self.last_cold += 1;
687 ret
688 }
689 }
690}
691
692impl List {
693 fn new(id: SlotId) -> List {
695 List {
696 head: Some(id),
697 tail: Some(id),
698 }
699 }
700
701 fn append(
703 &mut self,
704 id: SlotId,
705 states: &mut [SlotState],
706 link: fn(&mut Unused) -> &mut Link,
707 ) -> Link {
708 let tail = mem::replace(&mut self.tail, Some(id));
710
711 match tail {
715 Some(tail) => link(states[tail.index()].unwrap_unused()).next = Some(id),
716 None => self.head = Some(id),
717 }
718 Link {
719 prev: tail,
720 next: None,
721 }
722 }
723
724 fn remove(
726 &mut self,
727 id: SlotId,
728 slot_state: &mut [SlotState],
729 link: fn(&mut Unused) -> &mut Link,
730 ) -> Unused {
731 let mut state = *slot_state[id.index()].unwrap_unused();
732 let next = link(&mut state).next;
733 let prev = link(&mut state).prev;
734
735 match next {
739 Some(next) => link(slot_state[next.index()].unwrap_unused()).prev = prev,
740 None => self.tail = prev,
741 }
742
743 match prev {
745 Some(prev) => link(slot_state[prev.index()].unwrap_unused()).next = next,
746 None => self.head = next,
747 }
748 state
749 }
750
751 #[cfg(test)]
752 fn iter<'a>(
753 &'a self,
754 states: &'a [SlotState],
755 link: fn(&Unused) -> &Link,
756 ) -> impl Iterator<Item = SlotId> + 'a {
757 let mut cur = self.head;
758 let mut prev = None;
759 std::iter::from_fn(move || {
760 if cur.is_none() {
761 assert_eq!(prev, self.tail);
762 }
763 let ret = cur?;
764 match &states[ret.index()] {
765 SlotState::UnusedWarm(u) => {
766 assert_eq!(link(u).prev, prev);
767 prev = Some(ret);
768 cur = link(u).next
769 }
770 _ => unreachable!(),
771 }
772 Some(ret)
773 })
774 }
775}
776
777#[cfg(test)]
778mod test {
779 use super::*;
780 use rand::RngExt;
781 use wasmtime_environ::EntityRef;
782
783 #[test]
784 fn test_next_available_allocation_strategy() {
785 for size in 0..20 {
786 let state = ModuleAffinityIndexAllocator::new(size, 0).unwrap();
787 assert_eq!(state.num_empty_slots(), usize::try_from(size).unwrap());
788 for i in 0..size {
789 assert_eq!(state.num_empty_slots(), usize::try_from(size - i).unwrap());
790 assert_eq!(state.alloc(None).unwrap().index(), i as usize);
791 }
792 assert!(state.alloc(None).is_none());
793 }
794 }
795
796 #[test]
800 fn take_resident_warm_slots_keeps_affinity() {
801 let id = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));
802 let state = ModuleAffinityIndexAllocator::new(4, 4).unwrap();
803
804 let index = state.alloc(Some(id)).unwrap();
805 state.free(index, 4096);
806 assert_eq!(state.unused_bytes_resident(), 4096);
807
808 let taken = state.take_resident_warm_slots();
809 assert_eq!(taken, vec![(index, 4096)]);
810 assert_eq!(state.unused_bytes_resident(), 0);
812 assert_eq!(state.unused_warm_slots(), 0);
813
814 state.free(index, 0);
815 assert_eq!(state.unused_bytes_resident(), 0);
816 assert_eq!(state.unused_warm_slots(), 1);
817 assert!(state.testing_module_affinity_list().contains(&id));
818 assert_eq!(state.alloc(Some(id)).unwrap(), index);
820 }
821
822 #[test]
823 fn test_affinity_allocation_strategy() {
824 let id1 = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));
825 let id2 = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));
826 let state = ModuleAffinityIndexAllocator::new(100, 100).unwrap();
827
828 let index1 = state.alloc(Some(id1)).unwrap();
829 assert_eq!(index1.index(), 0);
830 let index2 = state.alloc(Some(id2)).unwrap();
831 assert_eq!(index2.index(), 1);
832 assert_ne!(index1, index2);
833
834 state.free(index1, 0);
835 assert_eq!(state.num_empty_slots(), 99);
836
837 let index3 = state.alloc(Some(id1)).unwrap();
839 assert_eq!(index3, index1);
840 state.free(index3, 0);
841
842 state.free(index2, 0);
843
844 let affinity_modules = state.testing_module_affinity_list();
846 assert_eq!(2, affinity_modules.len());
847 assert!(affinity_modules.contains(&id1));
848 assert!(affinity_modules.contains(&id2));
849
850 assert_eq!(state.num_empty_slots(), 100);
855 let mut indices = vec![];
856 for _ in 0..100 {
857 indices.push(state.alloc(Some(id2)).unwrap());
858 }
859 assert!(state.alloc(None).is_none());
860 assert_eq!(indices[0], index2);
861 assert_eq!(state.num_empty_slots(), 0);
862
863 for i in indices {
864 state.free(i, 0);
865 }
866
867 let affinity_modules = state.testing_module_affinity_list();
869 assert_eq!(1, affinity_modules.len());
870 assert!(affinity_modules.contains(&id2));
871
872 let index = state.alloc(Some(id1)).unwrap();
875 state.free(index, 0);
876 }
877
878 #[test]
879 fn clear_affine() {
880 let id = CompiledModuleId::new();
881 let memory_index = DefinedMemoryIndex::new(0);
882
883 for max_unused_warm_slots in [0, 1, 2] {
884 let state = ModuleAffinityIndexAllocator::new(100, max_unused_warm_slots).unwrap();
885
886 let index1 = state.alloc(Some(MemoryInModule(id, memory_index))).unwrap();
887 let index2 = state.alloc(Some(MemoryInModule(id, memory_index))).unwrap();
888 state.free(index2, 0);
889 state.free(index1, 0);
890 assert!(
891 state
892 .alloc_affine_and_clear_affinity(id, memory_index)
893 .is_some()
894 );
895 assert!(
896 state
897 .alloc_affine_and_clear_affinity(id, memory_index)
898 .is_some()
899 );
900 assert_eq!(
901 state.alloc_affine_and_clear_affinity(id, memory_index),
902 None
903 );
904 }
905 }
906
907 #[test]
908 fn test_affinity_allocation_strategy_random() {
909 let mut rng = rand::rng();
910
911 let ids = std::iter::repeat_with(|| {
912 MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0))
913 })
914 .take(10)
915 .collect::<Vec<_>>();
916 let state = ModuleAffinityIndexAllocator::new_with_shard_count(1000, 1000, 1).unwrap();
923 let mut allocated: Vec<SlotId> = vec![];
924 let mut last_id = vec![None; 1000];
925
926 let mut hits = 0;
927 let amt = if cfg!(miri) { 100 } else { 100_000 };
928 for _ in 0..amt {
929 loop {
930 if !allocated.is_empty() && rng.random_bool(0.5) {
931 let i = rng.random_range(0..allocated.len());
932 let to_free_idx = allocated.swap_remove(i);
933 state.free(to_free_idx, 0);
934 } else {
935 let id = ids[rng.random_range(0..ids.len())];
936 let index = match state.alloc(Some(id)) {
937 Some(id) => id,
938 None => continue,
939 };
940 if last_id[index.index()] == Some(id) {
941 hits += 1;
942 }
943 last_id[index.index()] = Some(id);
944 allocated.push(index);
945 }
946 break;
947 }
948 }
949
950 assert!(
954 hits > (amt / 5),
955 "expected at least 20000 (20%) ID-reuses but got {hits}"
956 );
957 }
958
959 #[test]
960 fn test_affinity_threshold() {
961 let id1 = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));
962 let id2 = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));
963 let id3 = MemoryInModule(CompiledModuleId::new(), DefinedMemoryIndex::new(0));
964 let state = ModuleAffinityIndexAllocator::new(10, 2).unwrap();
965
966 assert_eq!(state.alloc(Some(id1)), Some(SlotId(0)));
968 state.free(SlotId(0), 0);
969 assert_eq!(state.alloc(Some(id2)), Some(SlotId(1)));
970 state.free(SlotId(1), 0);
971
972 assert_eq!(state.alloc(Some(id3)), Some(SlotId(0)));
975 state.free(SlotId(0), 0);
976
977 assert_eq!(state.alloc(Some(id2)), Some(SlotId(1)));
979
980 assert_eq!(state.alloc(Some(id1)), Some(SlotId(2)));
983
984 state.free(SlotId(1), 0);
985 state.free(SlotId(2), 0);
986
987 assert_eq!(state.alloc(Some(id1)), Some(SlotId(2)));
989 assert_eq!(state.alloc(Some(id2)), Some(SlotId(1)));
990 assert_eq!(state.alloc(Some(id3)), Some(SlotId(0)));
991
992 state.free(SlotId(1), 0);
993 state.free(SlotId(2), 0);
994 state.free(SlotId(0), 0);
995
996 assert_eq!(
998 state.alloc(Some(MemoryInModule(
999 CompiledModuleId::new(),
1000 DefinedMemoryIndex::new(0)
1001 ))),
1002 Some(SlotId(1))
1003 );
1004
1005 assert_eq!(
1007 state.alloc(Some(MemoryInModule(
1008 CompiledModuleId::new(),
1009 DefinedMemoryIndex::new(0)
1010 ))),
1011 Some(SlotId(2))
1012 );
1013
1014 assert_eq!(
1016 state.alloc(Some(MemoryInModule(
1017 CompiledModuleId::new(),
1018 DefinedMemoryIndex::new(0)
1019 ))),
1020 Some(SlotId(3))
1021 );
1022
1023 state.free(SlotId(1), 0);
1024 state.free(SlotId(2), 0);
1025 state.free(SlotId(3), 0);
1026
1027 assert_eq!(state.alloc(Some(id3)), Some(SlotId(0)));
1029 }
1030
1031 #[test]
1032 fn test_freelist() {
1033 let allocator = SimpleIndexAllocator::new(10).unwrap();
1034 assert_eq!(allocator.testing_freelist(), []);
1035 let a = allocator.alloc().unwrap();
1036 assert_eq!(allocator.testing_freelist(), []);
1037 allocator.free(a, 0);
1038 assert_eq!(allocator.testing_freelist(), [a]);
1039 assert_eq!(allocator.alloc(), Some(a));
1040 assert_eq!(allocator.testing_freelist(), []);
1041 let b = allocator.alloc().unwrap();
1042 assert_eq!(allocator.testing_freelist(), []);
1043 allocator.free(b, 0);
1044 assert_eq!(allocator.testing_freelist(), [b]);
1045 allocator.free(a, 0);
1046 assert_eq!(allocator.testing_freelist(), [b, a]);
1047 }
1048
1049 #[test]
1050 #[cfg_attr(miri, ignore)]
1053 fn shard_layout_is_exhaustive_and_exact() {
1054 use proptest::prelude::*;
1055
1056 proptest!(|(
1057 capacity in 0u32..100_000,
1058 max_unused_warm_slots in 0u32..10_000,
1059 requested_shards in 1u32..64,
1060 )| {
1061 let layout = ShardLayout::new(capacity, max_unused_warm_slots, requested_shards)
1062 .unwrap();
1063
1064 prop_assert_eq!(
1068 layout.shards.iter().map(|(c, _)| *c).sum::<u32>(),
1069 capacity
1070 );
1071 prop_assert_eq!(
1072 layout.shards.iter().map(|(_, w)| *w).sum::<u32>(),
1073 max_unused_warm_slots
1074 );
1075
1076 let (last, rest) = layout.shards.split_last().unwrap();
1080 for (c, _) in rest {
1081 prop_assert_eq!(*c, layout.slots_per_shard);
1082 }
1083 prop_assert!(last.0 <= layout.slots_per_shard);
1084
1085 prop_assert!(layout.shards.len() <= requested_shards as usize);
1088 if capacity < 128 {
1089 prop_assert_eq!(layout.shards.len(), 1);
1090 }
1091 });
1092 }
1093
1094 #[test]
1095 #[cfg_attr(miri, ignore)]
1098 fn sharded_alloc_is_exhaustive_and_unique() {
1099 use proptest::prelude::*;
1100
1101 proptest!(|(
1102 capacity in 0u32..2048,
1103 max_unused_warm_slots in 0u32..100,
1104 requested_shards in 1u32..64,
1105 )| {
1106 let allocator = ModuleAffinityIndexAllocator::new_with_shard_count(
1107 capacity,
1108 max_unused_warm_slots,
1109 requested_shards,
1110 )
1111 .unwrap();
1112
1113 let mut ids = Vec::new();
1116 let mut seen = std::collections::HashSet::new();
1117 for _ in 0..capacity {
1118 let id = allocator.alloc(None).unwrap();
1119 prop_assert!(id.0 < capacity);
1120 prop_assert!(seen.insert(id.0));
1121 ids.push(id);
1122 }
1123 prop_assert!(allocator.alloc(None).is_none());
1125
1126 allocator.free_many(ids.into_iter().map(|id| (id, 0)));
1128 for _ in 0..capacity {
1129 prop_assert!(allocator.alloc(None).is_some());
1130 }
1131 prop_assert!(allocator.alloc(None).is_none());
1132 });
1133 }
1134}