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