1use std::{
2 borrow::Borrow,
3 collections::HashMap,
4 fmt::Debug,
5 path::{Path, PathBuf},
6 str::FromStr,
7 sync::atomic::AtomicUsize,
8};
9
10use compact_str::CompactString;
11use eyre::{Context as _, ContextCompat as _};
12use itertools::Itertools;
13
14use crate::{args::TargetMemoryType, unique_name::UniqueNameMarker};
15
16#[allow(dead_code)]
17#[allow(dead_code)]
18#[allow(dead_code)]
19
20pub trait CaminoUtilModule {
22 fn get_file_main_name(&self) -> Option<CompactString>;
24}
25
26impl CaminoUtilModule for camino::Utf8Path {
27 fn get_file_main_name(&self) -> Option<CompactString> {
28 let binding = self.file_name().unwrap().split(".").collect::<Vec<_>>();
29 let file_name_poss = binding.iter().rev();
30 let mut file_name = None;
31 for name in file_name_poss {
32 if *name == "opt"
33 || *name == "adjusted"
34 || *name == "wasm"
35 || *name == "core"
36 || *name == "component"
37 {
38 continue;
39 }
40 file_name = Some(name);
41 break;
42 }
43 let file_name = file_name.map(ToOwned::to_owned).or_else(|| {
44 self.file_name()
45 .unwrap()
46 .split(".")
47 .next()
48 .as_ref()
49 .cloned()
50 });
51
52 file_name.map(CompactString::from)
53 }
54}
55
56impl CaminoUtilModule for PathBuf {
57 fn get_file_main_name(&self) -> Option<CompactString> {
58 camino::Utf8Path::new(self.to_str().unwrap()).get_file_main_name()
59 }
60}
61
62impl CaminoUtilModule for Path {
63 fn get_file_main_name(&self) -> Option<CompactString> {
64 camino::Utf8Path::new(self.to_str().unwrap()).get_file_main_name()
65 }
66}
67
68pub trait ResultUtil<T> {
70 fn to_eyre(self) -> eyre::Result<T>;
72}
73
74impl<T> ResultUtil<T> for anyhow::Result<T> {
76 fn to_eyre(self) -> eyre::Result<T> {
77 self.map_err(|e| {
78 eyre::eyre!(Box::<dyn std::error::Error + Send + Sync + 'static>::from(
79 e
80 ))
81 })
82 }
83}
84
85impl<T, I: Iterator> ResultUtil<T> for Result<T, itertools::ExactlyOneError<I>> {
86 fn to_eyre(self) -> eyre::Result<T> {
87 self.map_err(|e| eyre::eyre!(e.to_string()))
88 }
89}
90
91pub struct FunctionIdMarker;
97pub struct StrMarker;
99pub struct UniqueMarker;
101pub struct DoubleStrMarker;
103pub struct StrAndUniqueNameMarker;
105
106#[derive(Debug)]
132pub struct WasmNameHolder(&'static [compact_str::CompactString], &'static AtomicUsize);
133
134impl WasmNameHolder {
135 pub fn new(strings: Box<[compact_str::CompactString]>) -> Self {
137 let count = Box::leak(Box::new(AtomicUsize::new(0)));
138
139 let strings = Box::leak(strings);
140 WasmNameHolder(strings, count)
141 }
142
143 pub fn iter(&self) -> impl Iterator<Item = WasmName> {
145 self.0.iter().map(|s| WasmName::new(s.as_str(), self.1))
146 }
147}
148
149impl Drop for WasmNameHolder {
150 fn drop(&mut self) {
151 unsafe {
152 let _ = Box::from_raw(self.0 as *const _ as *mut [compact_str::CompactString]);
153 let count = self.1.load(std::sync::atomic::Ordering::SeqCst);
154 let _ = Box::from_raw(self.1 as *const _ as *mut AtomicUsize);
155 if count != 0 {
156 panic!(
157 "WasmNameHolder dropped while there are still {count} WasmName instances alive"
158 );
159 }
160 }
161 }
162}
163
164pub struct WasmName(&'static str, &'static AtomicUsize);
166impl WasmName {
167 pub fn new(s: &'static str, counter: &'static AtomicUsize) -> Self {
169 counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
170 WasmName(s, counter)
171 }
172}
173impl Drop for WasmName {
174 fn drop(&mut self) {
175 self.1.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
176 }
177}
178impl Clone for WasmName {
179 fn clone(&self) -> Self {
180 self.1.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
181 WasmName(self.0, self.1)
182 }
183}
184impl std::hash::Hash for WasmName {
185 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
186 (self.0 as *const str).hash(state);
187 }
188}
189impl PartialEq for WasmName {
190 fn eq(&self, other: &Self) -> bool {
191 std::ptr::addr_eq(self.0 as *const _, other.0 as *const _)
192 }
193}
194impl Eq for WasmName {}
195impl std::fmt::Debug for WasmName {
196 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
197 write!(f, "{:?}", self.0)
198 }
199}
200impl std::fmt::Display for WasmName {
201 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202 write!(f, "{}", self.0)
203 }
204}
205impl AsRef<str> for WasmName {
206 fn as_ref(&self) -> &str {
207 &self.0
208 }
209}
210impl Borrow<str> for WasmName {
211 fn borrow(&self) -> &str {
212 &self.0
213 }
214}
215
216pub fn gen_component_name(namespace: &str, name: &str) -> String {
218 format!("[static]{namespace}.{}-import", name.replace("_", "-"))
219}
220
221#[derive(Debug)]
223pub struct BitIterator {
224 current: FeatureCombinationIteratorInnerBits,
225 skip: FeatureCombinationIteratorInnerBits, kind: u8,
227}
228
229impl BitIterator {
230 const MAX_KIND: u8 = core::mem::size_of::<FeatureCombinationIteratorInnerBits>() as u8 * 8;
231
232 pub fn new(kind: u8) -> Self {
234 if kind >= Self::MAX_KIND {
235 panic!("Kind must be between 0 and {}", Self::MAX_KIND - 1);
236 }
237
238 BitIterator {
239 current: FeatureCombinationIteratorInnerBits::ZERO,
240 kind,
241 skip: FeatureCombinationIteratorInnerBits::ZERO,
242 }
243 }
244
245 pub fn now(&self) -> FeatureCombinationIteratorInnerBits {
247 self.current
248 }
249
250 pub fn register_skip(&mut self, bit: u8) {
252 if bit >= Self::MAX_KIND {
253 panic!("Bit must be between 0 and {}", Self::MAX_KIND - 1);
254 }
255 self.skip.set(bit as usize, true);
256 }
257
258 pub fn skip_raw(&mut self, mask: FeatureCombinationIteratorInnerBits) {
260 self.skip |= mask;
261 }
262
263 pub fn unregister_skip(&mut self, bit: u8) {
265 if bit >= Self::MAX_KIND {
266 panic!("Bit must be between 0 and {}", Self::MAX_KIND - 1);
267 }
268 self.skip.set(bit as usize, false);
269 }
270
271 pub fn unregister_skip_raw(&mut self, mask: FeatureCombinationIteratorInnerBits) {
273 self.skip &= !mask;
274 }
275
276 pub fn clear_skip(&mut self) {
278 self.skip = FeatureCombinationIteratorInnerBits::ZERO;
279 }
280}
281
282pub mod bits {
284 use bitvec::prelude::*;
285 type FeatureCombinationIteratorInnerBitsInner = BitArray<[u64; 2]>;
286
287 #[derive(Copy, Clone, Debug)]
288 pub struct FeatureCombinationIteratorInnerBits(FeatureCombinationIteratorInnerBitsInner);
290
291 impl core::ops::BitAnd for FeatureCombinationIteratorInnerBits {
292 type Output = Self;
293
294 fn bitand(self, rhs: Self) -> Self::Output {
295 FeatureCombinationIteratorInnerBits { 0: self.0 & rhs.0 }
296 }
297 }
298
299 impl core::ops::BitAndAssign for FeatureCombinationIteratorInnerBits {
300 fn bitand_assign(&mut self, rhs: Self) {
301 self.0 &= rhs.0;
302 }
303 }
304
305 impl core::ops::BitOr for FeatureCombinationIteratorInnerBits {
306 type Output = Self;
307
308 fn bitor(self, rhs: Self) -> Self::Output {
309 FeatureCombinationIteratorInnerBits { 0: self.0 | rhs.0 }
310 }
311 }
312
313 impl core::ops::BitOrAssign for FeatureCombinationIteratorInnerBits {
314 fn bitor_assign(&mut self, rhs: Self) {
315 self.0 |= rhs.0;
316 }
317 }
318
319 impl core::ops::BitXor for FeatureCombinationIteratorInnerBits {
320 type Output = Self;
321
322 fn bitxor(self, rhs: Self) -> Self::Output {
323 FeatureCombinationIteratorInnerBits { 0: self.0 ^ rhs.0 }
324 }
325 }
326
327 impl core::ops::Not for FeatureCombinationIteratorInnerBits {
328 type Output = Self;
329
330 fn not(self) -> Self::Output {
331 FeatureCombinationIteratorInnerBits { 0: !self.0 }
332 }
333 }
334
335 impl core::ops::AddAssign for FeatureCombinationIteratorInnerBits {
336 fn add_assign(&mut self, rhs: Self) {
337 let raw_lhs = &mut self.0.data;
339 let raw_rhs = &rhs.0.data;
340 let mut carry = 0u64;
341
342 for i in 0..raw_lhs.len() {
343 let (sum1, carry1) = raw_lhs[i].overflowing_add(raw_rhs[i]);
344 let (sum2, carry2) = sum1.overflowing_add(carry);
345 raw_lhs[i] = sum2;
346 carry = (carry1 as u64) + (carry2 as u64);
347 }
348 }
349 }
350
351 impl core::cmp::PartialOrd for FeatureCombinationIteratorInnerBits {
352 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
353 self.0.partial_cmp(&other.0)
354 }
355 }
356
357 impl core::cmp::Ord for FeatureCombinationIteratorInnerBits {
358 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
359 self.0.cmp(&other.0)
360 }
361 }
362
363 impl core::cmp::PartialEq for FeatureCombinationIteratorInnerBits {
364 fn eq(&self, other: &Self) -> bool {
365 self.0 == other.0
366 }
367 }
368
369 impl core::cmp::Eq for FeatureCombinationIteratorInnerBits {}
370
371 impl core::ops::Index<usize> for FeatureCombinationIteratorInnerBits {
372 type Output = bool;
373
374 fn index(&self, index: usize) -> &bool {
375 &self.0[index]
376 }
377 }
378
379 impl FeatureCombinationIteratorInnerBits {
380 pub const ZERO: Self = FeatureCombinationIteratorInnerBits {
382 0: FeatureCombinationIteratorInnerBitsInner::ZERO,
383 };
384 pub const ONE: Self = Self::from_number(1);
386
387 pub fn set(&mut self, index: usize, value: bool) {
389 self.0.set(index, value);
390 }
391
392 pub fn is_zero(&self) -> bool {
394 self.0 == FeatureCombinationIteratorInnerBitsInner::ZERO
395 }
396
397 pub fn is_full(&self) -> bool {
399 self.0.all()
400 }
401
402 pub fn leading_zeros(&self) -> usize {
404 self.0.leading_zeros()
405 }
406
407 pub fn trailing_zeros(&self) -> usize {
409 self.0.trailing_zeros()
410 }
411
412 pub fn as_raw_slice(&self) -> &[u64] {
414 self.0.as_raw_slice()
415 }
416
417 pub const fn from_number(num: u64) -> Self {
419 let mut bits: FeatureCombinationIteratorInnerBitsInner =
420 FeatureCombinationIteratorInnerBitsInner::ZERO;
421 bits.data[0] = num;
422 FeatureCombinationIteratorInnerBits { 0: bits }
423 }
424
425 pub fn from_one_pos(pos: usize) -> Self {
427 let mut bits: FeatureCombinationIteratorInnerBitsInner =
428 FeatureCombinationIteratorInnerBitsInner::ZERO;
429 bits.set(pos, true);
430 FeatureCombinationIteratorInnerBits { 0: bits }
431 }
432
433 pub fn increment(&mut self) {
435 let raw = &mut self.0.data;
437 let mut carry = 1u64;
438
439 for i in 0..raw.len() {
440 let (new_value, new_carry) = raw[i].overflowing_add(carry);
441 raw[i] = new_value;
442 carry = if new_carry { 1 } else { 0 };
443 if carry == 0 {
444 break;
445 }
446 }
447 }
448 }
449
450 #[cfg(test)]
451 mod tests {
452 use super::FeatureCombinationIteratorInnerBits;
453
454 #[test]
455 fn test_increment() {
456 let mut s = FeatureCombinationIteratorInnerBits::ZERO;
457 assert_eq!(s.leading_zeros(), 128);
458 s.set(1, true);
459 println!("{:?}", s.as_raw_slice());
460 assert_eq!(s.leading_zeros(), 1);
461
462 let mut a = FeatureCombinationIteratorInnerBits::ONE;
463 a.increment();
464 assert_eq!(a.as_raw_slice()[0], 2);
465
466 let mut b = FeatureCombinationIteratorInnerBits::from_number(u64::MAX);
467 b.increment();
468 assert_eq!(b.as_raw_slice()[0], 0);
469 assert_eq!(b.as_raw_slice()[1], 1);
470
471 let mut c = FeatureCombinationIteratorInnerBits::from_number(u64::MAX);
472 c.set(64, true);
473 c.increment();
474 assert_eq!(c.as_raw_slice()[0], 0);
475 assert_eq!(c.as_raw_slice()[1], 2);
476 }
477
478 #[test]
479 fn test_add_assign() {
480 let mut a = FeatureCombinationIteratorInnerBits::from_number(1);
481 let b = FeatureCombinationIteratorInnerBits::from_number(2);
482 a += b;
483 assert_eq!(a.as_raw_slice()[0], 3);
484
485 let mut c = FeatureCombinationIteratorInnerBits::from_number(u64::MAX);
486 let d = FeatureCombinationIteratorInnerBits::from_number(1);
487 c += d;
488 assert_eq!(c.as_raw_slice()[0], 0);
489 assert_eq!(c.as_raw_slice()[1], 1);
490
491 let mut e = FeatureCombinationIteratorInnerBits::from_number(u64::MAX);
492 e.set(64, true);
493 let f = FeatureCombinationIteratorInnerBits::from_number(1);
494 e += f;
495 assert_eq!(e.as_raw_slice()[0], 0);
496 assert_eq!(e.as_raw_slice()[1], 2);
497 }
498 }
499}
500pub use bits::FeatureCombinationIteratorInnerBits;
501
502impl Iterator for BitIterator {
503 type Item = FeatureCombinationIteratorInnerBits;
504
505 fn next(&mut self) -> Option<Self::Item> {
506 let count = core::mem::size_of::<FeatureCombinationIteratorInnerBits>() * 8
507 - self.current.trailing_zeros();
508 if count > self.kind as usize {
509 None
510 } else {
511 let result = self.current;
512 self.current.increment();
513
514 loop {
515 let flag = self.current & self.skip;
516 if flag.is_zero() {
517 break;
518 } else {
519 self.current +=
520 FeatureCombinationIteratorInnerBits::from_one_pos(flag.leading_zeros());
521 }
522 }
523 Some(result)
524 }
525 }
526}
527
528#[derive(Debug)]
529pub struct FeatureCombinationIterator<C: Borrow<T>, T: ?Sized> {
531 features: Vec<(
532 C,
533 FeatureCombinationIteratorInnerBits,
534 FeatureCombinationIteratorInnerBits,
535 )>,
536 current: BitIterator,
537 __marker: std::marker::PhantomData<T>,
538}
539
540impl<'a, T: 'a + ?Sized, B: Borrow<T>, C: Borrow<T>, I: IntoIterator<Item = B>> FromIterator<(C, I)>
541 for FeatureCombinationIterator<C, T>
542where
543 for<'c> &'c T: std::cmp::Eq + std::hash::Hash,
544{
545 fn from_iter<U: IntoIterator<Item = (C, I)>>(iter: U) -> Self {
546 let data = iter
548 .into_iter()
549 .map(|(v, includes)| (v, includes.into_iter().collect::<Vec<_>>()))
550 .collect::<Vec<_>>();
551
552 let num = {
554 let mut counts = HashMap::new();
555 for (v, _) in &data {
557 counts.insert(v.borrow(), 0isize);
558 }
559 for (_, inc) in &data {
561 for v in inc {
562 if let Some(c) = counts.get_mut(&v.borrow()) {
563 *c += 1;
564 }
565 }
566 }
567
568 data.iter()
569 .map(|(v, _)| -*counts.get(&v.borrow()).unwrap_or(&0))
570 .collect::<Vec<_>>()
571 };
572
573 let data = data.into_iter().zip(num).collect::<Vec<_>>();
574
575 let mut data: Vec<(C, Vec<B>)> = data.into_iter().map(|(v, _)| v).collect();
579
580 {
582 let index_map: std::collections::HashMap<&T, usize> = data
583 .iter()
584 .enumerate()
585 .map(|(i, (v, _))| (v.borrow(), i))
586 .collect();
587
588 let mut visited = vec![0u8; data.len()]; let mut stack = Vec::new();
590
591 for i in 0..data.len() {
592 if visited[i] != 0 {
593 continue;
594 }
595
596 stack.push((i, 0));
597 visited[i] = 1; while let Some((u, dep_idx)) = stack.last_mut() {
600 let u = *u;
601 let deps = &data[u].1;
602 if *dep_idx < deps.len() {
603 let dep = &deps[*dep_idx];
604 *dep_idx += 1;
605
606 if let Some(&v) = index_map.get(&dep.borrow()) {
607 if u == v {
608 continue;
609 }
610 if visited[v] == 1 {
611 panic!("Mutual reference detected!");
612 }
613 if visited[v] == 0 {
614 visited[v] = 1;
615 stack.push((v, 0));
616 }
617 }
618 } else {
619 visited[u] = 2; stack.pop();
622 }
623 }
624 }
625 }
626
627 let mut count = 0i32;
630 loop {
631 let mut changed = false;
632 for i in 0..data.len() {
633 let mut swap_idx = None;
634 {
635 let (ref_value, ref_includes) = &data[i];
636 if ref_includes
637 .iter()
638 .any(|v| v.borrow() == ref_value.borrow())
639 {
640 for j in (i + 1)..data.len() {
642 let (_, swap_includes) = &data[j];
643 if !swap_includes
644 .iter()
645 .any(|v| v.borrow() == ref_value.borrow())
646 {
647 swap_idx = Some(j);
648 break;
649 }
650 }
651 }
652 }
653
654 if let Some(j) = swap_idx {
655 data.swap(i, j);
656 changed = true;
657 }
658 }
659 if !changed {
660 break;
661 }
662 if count.checked_add(1).is_none() {
663 break;
664 }
665 count += 1;
666 if count as u128 > 1u128.checked_shl(data.len() as u32).unwrap_or(u128::MAX) {
667 panic!("Mutual reference detected!");
668 }
669 }
670
671 let (data, _): (Vec<_>, Vec<_>) = data.into_iter().map(|v| (v, ())).unzip();
672
673 let len = data.len();
674
675 let map = data
676 .iter()
677 .enumerate()
678 .map(|(i, (v, _))| (v.borrow(), i))
679 .collect::<HashMap<&T, usize>>();
680
681 let dependents_map = {
683 let mut dmap = data
684 .iter()
685 .map(|(v, _)| (v.borrow(), vec![]))
686 .collect::<HashMap<&T, Vec<&C>>>();
687
688 for (t, inc) in &data {
689 for v in inc {
690 if let Some(list) = dmap.get_mut(&v.borrow()) {
691 list.push(t);
692 }
693 }
694 }
695 dmap
696 };
697
698 let mut features_base = Vec::with_capacity(data.len());
699 let mut dependencies_masks = Vec::with_capacity(data.len());
700 for (v, inc) in &data {
701 let deps = dependents_map
702 .get(&v.borrow())
703 .map(|v| v.as_slice())
704 .unwrap_or(&[]);
705 let mut mask = FeatureCombinationIteratorInnerBits::ZERO;
706 let mut indices = Vec::new();
707
708 for dep in deps {
709 let idx = map[&(*dep).borrow()];
710 mask.set(idx, true);
711 indices.push(idx);
712 }
713 features_base.push((indices, mask));
714
715 let mut dep_mask = FeatureCombinationIteratorInnerBits::ZERO;
717 for d in inc {
718 if let Some(idx) = map.get(&d.borrow()) {
719 dep_mask.set(*idx, true);
720 }
721 }
722 dependencies_masks.push(dep_mask);
723 }
724
725 let mut features_masks: Vec<FeatureCombinationIteratorInnerBits> =
726 features_base.iter().map(|(_, m)| *m).collect();
727
728 for _ in 0..data.len() {
729 let mut changed = false;
730 for i in 0..data.len() {
731 let (indices, _) = &features_base[i];
732 let mut mask = features_masks[i];
733 for &dep_idx in indices {
734 mask |= features_masks[dep_idx];
735 if mask != features_masks[i] { }
739 }
740 if mask != features_masks[i] {
741 features_masks[i] = mask;
742 changed = true;
743 }
744 }
745 if !changed {
746 break;
747 }
748 }
749
750 let features = features_masks
751 .into_iter()
752 .zip(dependencies_masks)
753 .zip(data)
754 .map(|((mask, dep_mask), (v, _))| (v, mask, dep_mask))
755 .collect::<Vec<_>>();
756
757 FeatureCombinationIterator {
758 features,
759 current: BitIterator::new(len as u8),
760 __marker: std::marker::PhantomData,
761 }
762 }
763}
764
765impl<C: Borrow<T> + std::cmp::Eq + std::hash::Hash + Clone, T: ?Sized> Iterator
766 for FeatureCombinationIterator<C, T>
767{
768 type Item = std::collections::HashSet<C>;
769
770 fn next(&mut self) -> Option<Self::Item> {
771 loop {
772 let bits = self.current.now();
773
774 let count = core::mem::size_of::<FeatureCombinationIteratorInnerBits>() * 8
776 - bits.trailing_zeros();
777 if count > self.current.kind as usize {
778 return None;
779 }
780
781 let mut _mask = FeatureCombinationIteratorInnerBits::ZERO;
783 for (i, (_, feature_bits, _)) in self.features.iter().enumerate() {
784 if !bits[i] {
785 _mask |= *feature_bits; }
788 }
789
790 let _mask = FeatureCombinationIteratorInnerBits::ZERO;
793
794 let mut min_jump = None;
811
812 for (i, (_, _, dependencies)) in self.features.iter().enumerate() {
813 if bits[i] {
814 let missing = *dependencies & !bits;
818 if !missing.is_zero() {
819 if min_jump.is_none() {
935 min_jump = Some(FeatureCombinationIteratorInnerBits::ZERO);
936 }
937 if let Some(ref mut j) = min_jump {
938 j.set(i, true);
939 *j |= missing;
940 }
941 }
942 }
943 }
944
945 if let Some(jump_mask) = min_jump {
946 let bit = jump_mask.leading_zeros(); self.current.current += FeatureCombinationIteratorInnerBits::from_one_pos(bit);
961
962 } else {
964 let mut result = std::collections::HashSet::new();
967 for (i, (feature, _, _)) in self.features.iter().enumerate() {
968 if bits[i] {
969 result.insert(feature.clone());
970 }
971 }
972 self.current.current.increment();
973 return Some(result);
974 }
975 }
976 }
977}
978
979#[cfg(test)]
980mod tests {
981 use std::{collections::HashSet, sync::Arc};
982
983 use super::*;
984
985 #[test]
986 fn test_get_file_main_name() {
987 let path = camino::Utf8Path::new("name.opt.adjusted.wasm");
988 let file_name = path.get_file_main_name();
989 assert_eq!(file_name.unwrap(), "name");
990 }
991
992 #[test]
993 fn test_bit_generator() {
994 let bits = BitIterator::new(3).collect::<Vec<_>>();
995
996 assert_eq!(
997 &bits
998 .iter()
999 .map(|b| b.as_raw_slice()[0])
1000 .collect::<Vec<u64>>(),
1001 &[0b000, 0b001, 0b010, 0b011, 0b100, 0b101, 0b110, 0b111]
1002 );
1003
1004 let count = BitIterator::new(10).count();
1005 assert_eq!(count, 1024);
1006
1007 let mut generator = BitIterator::new(5);
1008 generator.register_skip(1);
1009 generator.register_skip(3);
1010 let bits = generator.collect::<Vec<_>>();
1011
1012 assert_eq!(
1013 &bits
1014 .iter()
1015 .map(|b| b.as_raw_slice()[0])
1016 .collect::<Vec<u64>>(),
1017 &[
1018 0b00000, 0b00001, 0b00100, 0b00101, 0b10000, 0b10001, 0b10100, 0b10101
1019 ]
1020 );
1021 }
1022
1023 #[test]
1024 fn test_feature_combination_iterator() {
1025 let data = vec![
1026 ("A", vec![]),
1027 ("B", vec!["A"]),
1028 ("C", vec!["A"]),
1029 ("D", vec!["B", "C"]),
1030 ];
1031
1032 let iterator = data
1033 .into_iter()
1034 .collect::<FeatureCombinationIterator<_, str>>();
1035
1036 println!("Iterator created: {:?}", iterator);
1037
1038 let combinations = iterator.collect::<Vec<_>>();
1039
1040 let expected = vec![
1041 HashSet::from([]),
1042 HashSet::from(["A"]),
1043 HashSet::from(["A", "B"]),
1044 HashSet::from(["A", "C"]),
1045 HashSet::from(["A", "B", "C"]),
1046 HashSet::from(["A", "B", "C", "D"]),
1047 ];
1048
1049 assert_eq!(combinations, expected);
1050
1051 let data = vec![
1052 (String::from("A"), vec![]),
1053 (String::from("B"), vec![String::from("A")]),
1054 (String::from("C"), vec![String::from("A")]),
1055 (
1056 String::from("D"),
1057 vec![String::from("B"), String::from("C")],
1058 ),
1059 ];
1060 let data_ref = data
1061 .iter()
1062 .map(|(v, inc)| (v, inc.iter().map(|s| s).collect::<Vec<_>>()))
1063 .collect::<Vec<_>>();
1064
1065 let iterator = data
1066 .clone()
1067 .into_iter()
1068 .collect::<FeatureCombinationIterator<_, String>>();
1069
1070 let iterator2 = data_ref
1071 .into_iter()
1072 .collect::<FeatureCombinationIterator<_, String>>();
1073
1074 println!("Iterator created: {:?}", iterator);
1075
1076 let combinations = iterator.collect::<Vec<_>>();
1077 let _combinations2 = iterator2.collect::<Vec<_>>();
1078
1079 let expected = vec![
1080 HashSet::from([]),
1081 HashSet::from([String::from("A")]),
1082 HashSet::from([String::from("A"), String::from("B")]),
1083 HashSet::from([String::from("A"), String::from("C")]),
1084 HashSet::from([String::from("A"), String::from("B"), String::from("C")]),
1085 HashSet::from([
1086 String::from("A"),
1087 String::from("B"),
1088 String::from("C"),
1089 String::from("D"),
1090 ]),
1091 ];
1092
1093 assert_eq!(combinations, expected);
1094
1095 let data = data
1096 .iter()
1097 .map(|(u, v)| (Arc::new(u.clone()), v))
1098 .collect::<Vec<_>>();
1099
1100 let iterator = data
1101 .into_iter()
1102 .collect::<FeatureCombinationIterator<_, String>>();
1103
1104 println!("Iterator created: {:?}", iterator);
1105
1106 let _combinations = iterator.collect::<Vec<_>>();
1107 }
1108
1109 #[test]
1110 #[should_panic(expected = "Mutual reference detected!")]
1111 fn test_feature_combination_iterator_mutual_ref() {
1112 let data = vec![
1116 (String::from("A"), vec![String::from("B")]),
1117 (String::from("B"), vec![String::from("A")]),
1118 ];
1119
1120 let _iterator = data
1121 .into_iter()
1122 .collect::<FeatureCombinationIterator<_, String>>();
1123 }
1124
1125 #[test]
1126 #[should_panic(expected = "Mutual reference detected!")]
1127 fn test_feature_combination_iterator_complex_cycle() {
1128 let data = vec![
1130 (String::from("A"), vec![String::from("B")]),
1131 (String::from("B"), vec![String::from("C")]),
1132 (String::from("C"), vec![String::from("A")]),
1133 ];
1134
1135 let _iterator = data
1136 .into_iter()
1137 .collect::<FeatureCombinationIterator<_, String>>();
1138 }
1139
1140 #[test]
1141 fn test_feature_combination_iterator_complex_valid() {
1142 let data = vec![
1150 (
1151 String::from("A"),
1152 vec![String::from("B"), String::from("C")],
1153 ),
1154 (String::from("B"), vec![String::from("D")]),
1155 (String::from("C"), vec![String::from("D")]),
1156 (String::from("D"), vec![]),
1157 ];
1158
1159 let iterator = data
1160 .into_iter()
1161 .collect::<FeatureCombinationIterator<_, String>>();
1162
1163 let combinations = iterator.collect::<Vec<_>>();
1164 assert!(combinations.len() > 0);
1166 }
1167
1168 #[test]
1169 fn test_feature_combination_iterator_complex_diamond() {
1170 use std::collections::{HashMap, HashSet};
1171 let data = vec![
1178 (
1179 String::from("Root"),
1180 vec![String::from("Left"), String::from("Right")],
1181 ),
1182 (String::from("Left"), vec![String::from("Base")]),
1183 (String::from("Right"), vec![String::from("Base")]),
1184 (String::from("Base"), vec![]),
1185 ];
1186
1187 let iterator = data
1188 .into_iter()
1189 .collect::<FeatureCombinationIterator<_, String>>();
1190
1191 let combinations: Vec<HashSet<String>> = iterator.collect();
1192
1193 let deps: HashMap<String, Vec<String>> = HashMap::from([
1198 (
1199 String::from("Root"),
1200 vec![String::from("Left"), String::from("Right")],
1201 ),
1202 (String::from("Left"), vec![String::from("Base")]),
1203 (String::from("Right"), vec![String::from("Base")]),
1204 (String::from("Base"), vec![]),
1205 ]);
1206
1207 for combo in &combinations {
1208 for feature in combo {
1209 if let Some(required) = deps.get(feature) {
1210 for req in required {
1211 assert!(
1212 combo.contains(req),
1213 "Combination {:?} invalid: {} requires {}",
1214 combo,
1215 feature,
1216 req
1217 );
1218 }
1219 }
1220 }
1221 }
1222
1223 assert!(combinations.contains(&HashSet::from([])));
1225 assert!(combinations.contains(&HashSet::from([String::from("Base")])));
1226 assert!(
1227 combinations.contains(&HashSet::from([String::from("Base"), String::from("Left")]))
1228 );
1229 assert!(combinations.contains(&HashSet::from([
1230 String::from("Base"),
1231 String::from("Left"),
1232 String::from("Right"),
1233 String::from("Root")
1234 ])));
1235
1236 assert!(!combinations.contains(&HashSet::from([String::from("Root")])));
1239 assert!(!combinations.contains(&HashSet::from([String::from("Left")])));
1241 }
1242}