1use crate::cesr::bexter::Bexter;
2use crate::cesr::number::Number;
3use crate::cesr::{bex_dex, num_dex, BaseMatter, Parsable};
4use crate::errors::MatterError;
5use crate::keri::core::serdering::SadValue;
6use crate::Matter;
7use num_rational::Rational32;
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10use std::fmt;
11use std::fmt::Debug;
12
13#[derive(Debug, Clone, PartialEq)]
15pub enum WeightSpec {
16 Simple(Rational32),
18
19 WeightedVec(Vec<WeightSpec>),
21
22 WeightedMap(Rational32, Vec<Rational32>),
24}
25
26#[derive(Debug, Clone)]
30pub struct Tholder {
31 _weighted: bool,
33
34 _size: usize,
36
37 _sith: TholderSith,
39
40 _thold: TholderThold,
42
43 _bexter: Option<Bexter>,
45
46 _number: Option<Number>,
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize)]
52#[serde(untagged)]
53pub enum TholderSith {
54 Integer(usize),
56
57 HexString(String),
59
60 Json(String),
62
63 Weights(Vec<WeightedSithElement>),
65}
66
67impl TholderSith {
68 pub fn from_sad_value(val: SadValue) -> Result<Self, MatterError> {
69 match val {
70 SadValue::Number(num) => Ok(TholderSith::Integer(num.as_u64().unwrap() as usize)),
71 SadValue::String(s) => {
72 if s.contains("[") {
73 Ok(TholderSith::Json(s))
74 } else {
75 Ok(TholderSith::HexString(s))
76 }
77 }
78 SadValue::Array(_) => serde_json::to_string(&val)
80 .map(TholderSith::Json)
81 .map_err(|e| MatterError::ValueError(format!("invalid sith value: {}", e))),
82 _ => Err(MatterError::ValueError(format!(
83 "invalid sith value: {:?}",
84 val
85 ))),
86 }
87 }
88}
89
90impl fmt::Display for TholderSith {
91 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92 match self {
93 TholderSith::Integer(n) => write!(f, "{}", n),
94 TholderSith::HexString(s) => write!(f, "{}", s),
95 TholderSith::Json(s) => write!(f, "{}", s),
96 TholderSith::Weights(w) => {
97 match serde_json::to_string(w) {
99 Ok(json) => write!(f, "{}", json),
100 Err(_) => write!(f, "<invalid weights>"),
101 }
102 }
103 }
104 }
105}
106
107impl fmt::Display for WeightedSithElement {
109 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
110 match serde_json::to_string(self) {
111 Ok(json) => write!(f, "{}", json),
112 Err(_) => write!(f, "<invalid weight element>"),
113 }
114 }
115}
116
117#[derive(Debug, Clone, Serialize, Deserialize)]
119#[serde(untagged)]
120pub enum WeightedSithElement {
121 Simple(String),
123
124 Array(Vec<WeightedSithElement>),
126
127 Complex(HashMap<String, Vec<WeightedSithElement>>),
129}
130
131#[derive(Debug, Clone, PartialEq)]
133pub enum TholderThold {
134 Integer(usize),
136
137 Weighted(Vec<Vec<WeightSpec>>),
139}
140
141impl Default for Tholder {
142 fn default() -> Self {
143 Tholder {
144 _weighted: false,
145 _size: 0,
146 _sith: TholderSith::HexString(String::new()),
147 _thold: TholderThold::Integer(0),
148 _bexter: None,
149 _number: None,
150 }
151 }
152}
153
154impl Tholder {
155 pub fn new(
167 thold: Option<TholderThold>,
168 limen: Option<Vec<u8>>,
169 sith: Option<TholderSith>,
170 ) -> Result<Self, MatterError> {
171 if let Some(t) = thold {
172 return Self::process_thold(t);
173 } else if let Some(l) = limen {
174 let mut tholder = Tholder::default();
175 tholder.process_limen(l.as_slice(), Some(false))?;
176 return Ok(tholder);
177 } else if let Some(s) = sith {
178 let mut tholder = Tholder::default();
179 tholder.process_sith(s)?;
180 return Ok(tholder);
181 }
182
183 Err(MatterError::EmptyMaterialError(
184 "Missing threshold expression.".to_string(),
185 ))
186 }
187
188 fn process_thold(thold: TholderThold) -> Result<Self, MatterError> {
190 let mut tholder = Tholder::default();
191 match thold {
192 TholderThold::Integer(num) => {
193 tholder.process_unweighted(num)?;
194 }
195 TholderThold::Weighted(clauses) => {
196 tholder.process_weighted(clauses)?;
197 }
198 }
199
200 Ok(tholder)
201 }
202
203 pub fn process_limen(&mut self, limen: &[u8], strip: Option<bool>) -> Result<(), MatterError> {
210 let matter = BaseMatter::from_qb64b(&mut limen.to_vec(), strip)?;
211
212 if num_dex::MAP.contains_key(matter.code()) {
213 let number = Number::new(Some(matter.raw()), Some(matter.code()), None, None)?;
214 self.process_unweighted(number.num() as usize)?;
215 } else if bex_dex::MAP.contains_key(matter.code()) {
216 let bexter = Bexter::new(Some(matter.raw()), Some(matter.code()), None, None)?;
218 let t = bexter.bext()?.replace('s', "/");
219
220 let clauses: Vec<&str> = t.split('a').collect();
222
223 let mut thold = Vec::new();
224 for c in clauses {
225 let c_parts: Vec<&str> = c.split('c').collect();
226 let mut clause = Vec::new();
227
228 for e in c_parts {
229 if let Some(k_pos) = e.find('k') {
230 let k = &e[..k_pos];
231 let v = &e[(k_pos + 1)..];
232
233 let v_parts: Vec<&str> = v.split('v').collect();
234 let weights: Vec<Rational32> = v_parts
235 .iter()
236 .map(|w| Self::weight(w))
237 .collect::<Result<Vec<Rational32>, _>>()?;
238
239 clause.push(WeightSpec::WeightedMap(Self::weight(k)?, weights));
240 } else {
241 clause.push(WeightSpec::Simple(Self::weight(e)?));
242 }
243 }
244
245 thold.push(clause);
246 }
247
248 self.process_weighted(thold)?;
249 } else {
250 return Err(MatterError::InvalidCode(format!(
251 "Invalid code for limen = {}",
252 matter.code()
253 )));
254 }
255
256 Ok(())
257 }
258
259 pub fn process_sith(&mut self, sith: TholderSith) -> Result<(), MatterError> {
269 match sith {
270 TholderSith::Integer(threshold) => self.process_unweighted(threshold),
271
272 TholderSith::HexString(hex_str) => {
273 match i32::from_str_radix(&hex_str, 16) {
275 Ok(threshold) => self.process_unweighted(threshold as usize),
276 Err(_) => Err(MatterError::ValueError(format!(
277 "Invalid hex string sith = {}",
278 hex_str
279 ))),
280 }
281 }
282
283 TholderSith::Json(json_val) => {
284 if let Ok(nested_clauses) =
286 serde_json::from_str::<Vec<Vec<WeightedSithElement>>>(json_val.as_str())
287 {
288 let mut thold = Vec::new();
290 for clause_elements in nested_clauses {
291 let mut clause_specs = Vec::new();
292 for element in clause_elements {
293 let mut element_specs = self.process_weight_clause(&element)?;
294 clause_specs.append(&mut element_specs);
295 }
296 thold.push(clause_specs);
297 }
298 self.process_weighted(thold)
299 } else {
300 let clauses: Vec<WeightedSithElement> =
302 serde_json::from_str(json_val.as_str()).unwrap();
303 if clauses.is_empty() {
304 return Err(MatterError::ValueError("Empty weight list".to_string()));
305 }
306
307 let mut single_clause = Vec::new();
309 for clause in clauses {
310 let mut processed_specs = self.process_weight_clause(&clause)?;
311 single_clause.append(&mut processed_specs);
312 }
313 self.process_weighted(vec![single_clause])
314 }
315 }
316
317 TholderSith::Weights(clauses) => {
318 if clauses.is_empty() {
319 return Err(MatterError::ValueError("Empty weight list".to_string()));
320 }
321
322 let mut single_clause = Vec::new();
324 for clause in clauses {
325 let mut processed_specs = self.process_weight_clause(&clause)?;
326 single_clause.append(&mut processed_specs);
327 }
328 self.process_weighted(vec![single_clause])
329 }
330 }
331 }
332
333 fn process_weight_clause(
335 &self,
336 clause: &WeightedSithElement,
337 ) -> Result<Vec<WeightSpec>, MatterError> {
338 match clause {
339 WeightedSithElement::Simple(weight_str) => {
340 let weight = Self::weight(weight_str)?;
341 Ok(vec![WeightSpec::Simple(weight)])
342 }
343
344 WeightedSithElement::Array(elements) => {
345 if elements.is_empty() {
346 return Err(MatterError::ValueError(
347 "Empty weight array not allowed".to_string(),
348 ));
349 }
350
351 let mut specs = Vec::new();
352 for element in elements {
353 let mut element_specs = self.process_weight_clause(element)?;
354 specs.append(&mut element_specs);
355 }
356 Ok(specs)
357 }
358
359 WeightedSithElement::Complex(weight_map) => {
360 if weight_map.is_empty() {
361 return Err(MatterError::ValueError(
362 "Empty weight map not allowed".to_string(),
363 ));
364 }
365
366 let mut specs = Vec::new();
367 for (key_str, value_elements) in weight_map {
368 if value_elements.is_empty() {
369 return Err(MatterError::ValueError(
370 "Empty weight values not allowed".to_string(),
371 ));
372 }
373
374 let key_weight = Self::weight(key_str)?;
375 let mut value_weights = Vec::new();
376
377 for value_element in value_elements {
378 if let WeightedSithElement::Simple(weight_str) = value_element {
379 value_weights.push(Self::weight(weight_str)?);
380 } else {
381 return Err(MatterError::ValueError(
382 "Complex weight values must be simple weights".to_string(),
383 ));
384 }
385 }
386
387 specs.push(WeightSpec::WeightedMap(key_weight, value_weights));
388 }
389 Ok(specs)
390 }
391 }
392 }
393
394 pub fn satisfy(&self, indices: &[usize]) -> bool {
404 if self._weighted {
405 self.satisfy_weighted(indices)
406 } else {
407 self.satisfy_numeric(indices)
408 }
409 }
410
411 fn satisfy_numeric(&self, indices: &[usize]) -> bool {
413 if let TholderThold::Integer(num) = self._thold {
414 indices.len() >= num
415 } else {
416 false
417 }
418 }
419
420 fn satisfy_weighted(&self, indices: &[usize]) -> bool {
422 if indices.is_empty() {
423 return false;
424 }
425
426 let mut unique_indices: Vec<usize> = indices.iter().cloned().collect();
428 unique_indices.sort_unstable();
429 unique_indices.dedup();
430
431 let mut sats = vec![false; self._size];
433 for &idx in &unique_indices {
434 if idx < self._size {
435 sats[idx] = true;
436 }
437 }
438
439 if let TholderThold::Weighted(ref clauses) = self._thold {
440 let mut wio = 0; for clause in clauses {
443 let mut cw = Rational32::new(0, 1); for element in clause {
446 match element {
447 WeightSpec::Simple(weight) => {
448 if wio < sats.len() && sats[wio] {
449 cw += *weight;
450 }
451 wio += 1;
452 }
453 WeightSpec::WeightedMap(key_weight, nested_weights) => {
454 let mut vw = Rational32::new(0, 1); for nested_weight in nested_weights {
456 if wio < sats.len() && sats[wio] {
457 vw += *nested_weight;
458 }
459 wio += 1;
460 }
461 if vw >= Rational32::new(1, 1) {
462 cw += *key_weight;
463 }
464 }
465 WeightSpec::WeightedVec(nested_specs) => {
466 let mut vw = Rational32::new(0, 1);
468 for nested_spec in nested_specs {
469 if let WeightSpec::Simple(weight) = nested_spec {
470 if wio < sats.len() && sats[wio] {
471 vw += *weight;
472 }
473 wio += 1;
474 }
475 }
476 if vw >= Rational32::new(1, 1) {
477 cw += Rational32::new(1, 1); }
479 }
480 }
481 }
482
483 if cw < Rational32::new(1, 1) {
484 return false;
485 }
486 }
487
488 true
489 } else {
490 false
491 }
492 }
493
494 pub fn weighted(&self) -> bool {
496 self._weighted
497 }
498
499 pub fn thold(&self) -> &TholderThold {
501 &self._thold
502 }
503
504 pub fn size(&self) -> usize {
506 self._size
507 }
508
509 pub fn limen(&self) -> Vec<u8> {
511 if self._weighted {
512 self._bexter.as_ref().unwrap().qb64b()
514 } else {
515 self._number.as_ref().unwrap().qb64b()
517 }
518 }
519
520 pub fn sith(&self) -> TholderSith {
522 match &self._thold {
523 TholderThold::Weighted(clauses) => {
524 let mut sith_clauses = Vec::new();
525
526 for clause in clauses {
527 let mut sith_clause = Vec::new();
528
529 for element in clause {
530 match element {
531 WeightSpec::Simple(weight) => {
532 let weight_str = if *weight > Rational32::new(0, 1)
533 && *weight < Rational32::new(1, 1)
534 {
535 format!("{}/{}", weight.numer(), weight.denom())
536 } else {
537 format!("{}", weight.numer() / weight.denom())
538 };
539 sith_clause.push(WeightedSithElement::Simple(weight_str));
540 }
541 WeightSpec::WeightedMap(key_weight, nested_weights) => {
542 let key_str = if *key_weight > Rational32::new(0, 1)
543 && *key_weight < Rational32::new(1, 1)
544 {
545 format!("{}/{}", key_weight.numer(), key_weight.denom())
546 } else {
547 format!("{}", key_weight.numer() / key_weight.denom())
548 };
549
550 let value_elements: Vec<WeightedSithElement> = nested_weights
551 .iter()
552 .map(|w| {
553 let weight_str = if *w > Rational32::new(0, 1)
554 && *w < Rational32::new(1, 1)
555 {
556 format!("{}/{}", w.numer(), w.denom())
557 } else {
558 format!("{}", w.numer() / w.denom())
559 };
560 WeightedSithElement::Simple(weight_str)
561 })
562 .collect();
563
564 let mut map = HashMap::new();
565 map.insert(key_str, value_elements);
566 sith_clause.push(WeightedSithElement::Complex(map));
567 }
568 WeightSpec::WeightedVec(_) => {
569 }
571 }
572 }
573
574 sith_clauses.push(sith_clause);
575 }
576
577 if sith_clauses.len() == 1 {
579 TholderSith::Weights(sith_clauses.into_iter().next().unwrap())
580 } else {
581 TholderSith::Json(serde_json::to_string(&sith_clauses).unwrap_or_default())
583 }
584 }
585 TholderThold::Integer(n) => TholderSith::HexString(format!("{:x}", n)),
586 }
587 }
588
589 pub fn json(&self) -> String {
591 match &self.sith() {
592 TholderSith::Json(json_str) => json_str.clone(), other => serde_json::to_string(other).unwrap_or_default(), }
595 }
596
597 pub fn num(&self) -> Option<usize> {
599 if !self._weighted {
600 if let TholderThold::Integer(n) = self._thold {
601 return Some(n);
602 }
603 }
604 None
605 }
606
607 fn process_unweighted(&mut self, thold: usize) -> Result<(), MatterError> {
609 if thold == 0 {
610 self._weighted = false;
612 self._size = thold;
613 self._sith = TholderSith::Integer(thold);
614 self._thold = TholderThold::Integer(thold);
615 self._bexter = None;
616 self._number = Some(Number::from_numh(format!("{:x}", thold).as_str())?);
617
618 Ok(())
619 } else {
620 self._weighted = false;
621 self._size = thold;
622 self._sith = TholderSith::Integer(thold);
623 self._thold = TholderThold::Integer(thold);
624 self._bexter = None;
625 self._number = Some(Number::from_numh(format!("{:x}", thold).as_str())?);
626
627 Ok(())
628 }
629 }
630
631 fn process_weighted(&mut self, thold: Vec<Vec<WeightSpec>>) -> Result<(), MatterError> {
633 for clause in &thold {
635 let mut top_weights = Vec::new();
637
638 for e in clause {
639 match e {
640 WeightSpec::Simple(weight) => {
641 top_weights.push(*weight);
642 }
643 WeightSpec::WeightedMap(key_weight, nested_weights) => {
644 top_weights.push(*key_weight);
645
646 let sum_nested: Rational32 = nested_weights.iter().sum();
648 if sum_nested < Rational32::new(1, 1) {
649 return Err(MatterError::ValueError(format!(
650 "Invalid sith clause, nested clause weight sum must be >= 1. Got: {:?}",
651 sum_nested
652 )));
653 }
654 }
655 WeightSpec::WeightedVec(nested_specs) => {
656 let mut nested_sum = Rational32::new(0, 1);
658
659 for nested_spec in nested_specs {
660 if let WeightSpec::Simple(weight) = nested_spec {
661 nested_sum = nested_sum + *weight;
662 }
663 }
665
666 if nested_sum < Rational32::new(1, 1) {
667 return Err(MatterError::ValueError(format!(
668 "Invalid sith clause, nested vec weight sum must be >= 1. Got: {:?}",
669 nested_sum
670 )));
671 }
672
673 top_weights.push(Rational32::new(1, 1));
675 }
676 }
677 }
678
679 let sum_top: Rational32 = top_weights.iter().sum();
681 if sum_top < Rational32::new(1, 1) {
682 return Err(MatterError::ValueError(format!(
683 "Invalid sith clause, top level weight sum must be >= 1. Got: {:?}",
684 sum_top
685 )));
686 }
687 }
688
689 let mut size = 0;
691 for clause in &thold {
692 for e in clause {
693 match e {
694 WeightSpec::Simple(_) => {
695 size += 1;
696 }
697 WeightSpec::WeightedMap(_, nested_weights) => {
698 size += nested_weights.len();
699 }
700 WeightSpec::WeightedVec(nested_specs) => {
701 size += nested_specs.len();
702 }
703 }
704 }
705 }
706
707 let mut ta = Vec::new(); for clause in &thold {
711 let mut bc = Vec::new(); for e in clause {
714 match e {
715 WeightSpec::Simple(weight) => {
716 let w_str =
718 if *weight > Rational32::new(0, 1) && *weight < Rational32::new(1, 1) {
719 format!("{}s{}", weight.numer(), weight.denom())
720 } else {
721 format!("{}", weight.numer() / weight.denom())
722 };
723
724 bc.push(w_str);
725 }
726 WeightSpec::WeightedMap(key_weight, nested_weights) => {
727 let k = if *key_weight > Rational32::new(0, 1)
729 && *key_weight < Rational32::new(1, 1)
730 {
731 format!("{}s{}", key_weight.numer(), key_weight.denom())
732 } else {
733 format!("{}", key_weight.numer() / key_weight.denom())
734 };
735
736 let v = nested_weights
738 .iter()
739 .map(|f| {
740 if *f > Rational32::new(0, 1) && *f < Rational32::new(1, 1) {
741 format!("{}s{}", f.numer(), f.denom())
742 } else {
743 format!("{}", f.numer() / f.denom())
744 }
745 })
746 .collect::<Vec<String>>()
747 .join("v");
748
749 let kv = format!("{}k{}", k, v);
751 bc.push(kv);
752 }
753 WeightSpec::WeightedVec(_nested_specs) => {
754 bc.push("1".to_string()); }
760 }
761 }
762
763 ta.push(bc);
764 }
765
766 let bext = ta
768 .iter()
769 .map(|bc| bc.join("c"))
770 .collect::<Vec<String>>()
771 .join("a");
772
773 let bexter = Bexter::from_bext(bext.as_bytes())?;
775
776 self._weighted = true;
778 self._size = size;
779
780 self._sith = if thold.len() == 1 {
782 let mut weight_elements = Vec::new();
784 for element in &thold[0] {
785 match element {
786 WeightSpec::Simple(weight) => {
787 let weight_str =
788 if *weight > Rational32::new(0, 1) && *weight < Rational32::new(1, 1) {
789 format!("{}/{}", weight.numer(), weight.denom())
790 } else {
791 format!("{}", weight.numer() / weight.denom())
792 };
793 weight_elements.push(WeightedSithElement::Simple(weight_str));
794 }
795 WeightSpec::WeightedMap(key_weight, nested_weights) => {
796 let key_str = if *key_weight > Rational32::new(0, 1)
797 && *key_weight < Rational32::new(1, 1)
798 {
799 format!("{}/{}", key_weight.numer(), key_weight.denom())
800 } else {
801 format!("{}", key_weight.numer() / key_weight.denom())
802 };
803
804 let value_elements: Vec<WeightedSithElement> = nested_weights
805 .iter()
806 .map(|w| {
807 let weight_str =
808 if *w > Rational32::new(0, 1) && *w < Rational32::new(1, 1) {
809 format!("{}/{}", w.numer(), w.denom())
810 } else {
811 format!("{}", w.numer() / w.denom())
812 };
813 WeightedSithElement::Simple(weight_str)
814 })
815 .collect();
816
817 let mut map = HashMap::new();
818 map.insert(key_str, value_elements);
819 weight_elements.push(WeightedSithElement::Complex(map));
820 }
821 WeightSpec::WeightedVec(_) => {
822 }
824 }
825 }
826 TholderSith::Weights(weight_elements)
827 } else {
828 let mut sith_clauses = Vec::new();
830
831 for clause in &thold {
832 let mut sith_clause = Vec::new();
833
834 for element in clause {
835 match element {
836 WeightSpec::Simple(weight) => {
837 let weight_str = if *weight > Rational32::new(0, 1)
838 && *weight < Rational32::new(1, 1)
839 {
840 format!("{}/{}", weight.numer(), weight.denom())
841 } else {
842 format!("{}", weight.numer() / weight.denom())
843 };
844 sith_clause.push(WeightedSithElement::Simple(weight_str));
845 }
846 WeightSpec::WeightedMap(key_weight, nested_weights) => {
847 let key_str = if *key_weight > Rational32::new(0, 1)
848 && *key_weight < Rational32::new(1, 1)
849 {
850 format!("{}/{}", key_weight.numer(), key_weight.denom())
851 } else {
852 format!("{}", key_weight.numer() / key_weight.denom())
853 };
854
855 let value_elements: Vec<WeightedSithElement> = nested_weights
856 .iter()
857 .map(|w| {
858 let weight_str = if *w > Rational32::new(0, 1)
859 && *w < Rational32::new(1, 1)
860 {
861 format!("{}/{}", w.numer(), w.denom())
862 } else {
863 format!("{}", w.numer() / w.denom())
864 };
865 WeightedSithElement::Simple(weight_str)
866 })
867 .collect();
868
869 let mut map = HashMap::new();
870 map.insert(key_str, value_elements);
871 sith_clause.push(WeightedSithElement::Complex(map));
872 }
873 WeightSpec::WeightedVec(_) => {
874 }
876 }
877 }
878
879 sith_clauses.push(sith_clause);
880 }
881
882 TholderSith::Json(serde_json::to_string(&sith_clauses).unwrap_or_default())
883 };
884
885 self._thold = TholderThold::Weighted(thold);
886 self._bexter = Some(bexter);
887 self._number = None;
888
889 Ok(())
890 }
891
892 #[allow(missing_docs)]
894 pub fn weight(weight_str: &str) -> Result<Rational32, MatterError> {
895 if weight_str.is_empty() {
897 return Err(MatterError::ParseError("Empty weight string".to_string()));
898 }
899
900 if let Ok(float_val) = weight_str.parse::<f64>() {
902 let int_val = float_val as i32;
903 if (float_val - int_val as f64).abs() > f64::EPSILON {
904 return Err(MatterError::WeightError(format!(
905 "Invalid weight str got float w={}.",
906 weight_str
907 )));
908 }
909 }
911
912 if let Ok(int_val) = weight_str.parse::<i32>() {
914 if int_val < 0 || int_val > 1 {
915 return Err(MatterError::WeightError(format!(
916 "Invalid weight not 0 <= {} <= 1.",
917 int_val
918 )));
919 }
920 return Ok(Rational32::new(int_val, 1));
921 }
922
923 if let Some(idx) = weight_str.find('/') {
925 let numerator_str = &weight_str[0..idx];
926 let denominator_str = &weight_str[idx + 1..];
927
928 match (numerator_str.parse::<i32>(), denominator_str.parse::<i32>()) {
929 (Ok(num), Ok(denom)) => {
930 if denom <= 0 {
931 return Err(MatterError::WeightError(format!(
932 "Denominator must be positive, got: {}",
933 denom
934 )));
935 }
936
937 let rational = Rational32::new(num, denom);
938 if rational < Rational32::new(0, 1) || rational > Rational32::new(1, 1) {
939 return Err(MatterError::WeightError(format!(
940 "Invalid weight not 0 <= {} <= 1.",
941 rational
942 )));
943 }
944 Ok(rational)
945 }
946 _ => Err(MatterError::ParseError(format!(
947 "Failed to parse rational number: {}",
948 weight_str
949 ))),
950 }
951 } else {
952 Err(MatterError::ParseError(format!(
953 "Invalid weight format: {}",
954 weight_str
955 )))
956 }
957 }
958}
959
960impl fmt::Display for Tholder {
961 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
962 write!(
963 f,
964 "Tholder(weighted={}, size={})",
965 self._weighted, self._size
966 )
967 }
968}
969
970#[cfg(test)]
971mod tests {
972 use super::*;
973
974 #[test]
975 fn test_tholder_empty_material_error() {
976 let result = Tholder::new(None, None, None);
978 assert!(result.is_err());
979 if let Err(MatterError::EmptyMaterialError(_)) = result {
980 } else {
982 panic!("Expected EmptyMaterialError, got: {:?}", result);
983 }
984 }
985
986 #[test]
987 fn test_tholder_validation_errors() {
988 let result = Tholder::new(None, None, Some(TholderSith::Integer(usize::MAX))); let json_str1 = r#"[1]"#;
994 let weights_result1: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str1);
995 if weights_result1.is_ok() {
996 let weights1 = weights_result1.unwrap();
997 let result1 = Tholder::new(None, None, Some(TholderSith::Weights(weights1)));
998 assert!(result1.is_err(), "Should fail with integer weight");
999 }
1000
1001 let json_str2 = r#"[2]"#;
1002 let weights_result2: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str2);
1003 if weights_result2.is_ok() {
1004 let weights2 = weights_result2.unwrap();
1005 let result2 = Tholder::new(None, None, Some(TholderSith::Weights(weights2)));
1006 assert!(result2.is_err(), "Should fail with integer weight");
1007 }
1008
1009 let json_str3 = r#"["2"]"#;
1011 let weights_result3: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str3);
1012 if weights_result3.is_ok() {
1013 let weights3 = weights_result3.unwrap();
1014 let result3 = Tholder::new(None, None, Some(TholderSith::Weights(weights3)));
1015 assert!(result3.is_err(), "Should fail with weight > 1");
1016 }
1017
1018 let json_str4 = r#"["0.5", "0.5"]"#;
1020 let weights_result4: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str4);
1021 if weights_result4.is_ok() {
1022 let weights4 = weights_result4.unwrap();
1023 let result4 = Tholder::new(None, None, Some(TholderSith::Weights(weights4)));
1024 assert!(result4.is_err(), "Should fail with float weights");
1025 }
1026
1027 let result5 = Tholder::new(None, None, Some(TholderSith::HexString("1.0".to_string())));
1029 assert!(
1030 result5.is_err(),
1031 "Should fail with float string for unweighted"
1032 );
1033
1034 let result6 = Tholder::new(None, None, Some(TholderSith::HexString("0.5".to_string())));
1035 assert!(
1036 result6.is_err(),
1037 "Should fail with float string for unweighted"
1038 );
1039
1040 let result7 = Tholder::new(
1042 None,
1043 None,
1044 Some(TholderSith::HexString("1.0/2.0".to_string())),
1045 );
1046 assert!(result7.is_err(), "Should fail with float ratio");
1047
1048 let empty_weights: Vec<WeightedSithElement> = vec![];
1050 let result8 = Tholder::new(None, None, Some(TholderSith::Weights(empty_weights)));
1051 assert!(result8.is_err(), "Should fail with empty weights array");
1052 }
1053
1054 #[test]
1055 fn test_tholder_weighted_validation_errors() {
1056 let json_str1 = r#"["1/3", "1/2", []]"#;
1058 let weights_result1: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str1);
1059
1060 assert!(weights_result1.is_ok(), "JSON parsing should succeed");
1062 let weights1 = weights_result1.unwrap();
1063 let result1 = Tholder::new(None, None, Some(TholderSith::Weights(weights1)));
1064 assert!(
1065 result1.is_err(),
1066 "Should fail with mixed array containing empty element"
1067 );
1068
1069 let json_str2 = r#"["1/3", "1/2"]"#;
1071 let weights_result2: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str2);
1072 if weights_result2.is_ok() {
1073 let weights2 = weights_result2.unwrap();
1074 let result2 = Tholder::new(None, None, Some(TholderSith::Weights(weights2)));
1075 }
1078
1079 let json_str3 = r#"[[], []]"#;
1081 let weights_result3: Result<Vec<Vec<WeightedSithElement>>, _> =
1082 serde_json::from_str(json_str3);
1083 if weights_result3.is_ok() {
1084 let nested_weights = weights_result3.unwrap();
1086 let flat_weights: Vec<WeightedSithElement> =
1087 nested_weights.into_iter().flatten().collect();
1088 let result3 = Tholder::new(None, None, Some(TholderSith::Weights(flat_weights)));
1089 assert!(result3.is_err(), "Should fail with empty nested arrays");
1090 }
1091
1092 let json_str4 = r#"["1/2", "1/2", "3/2"]"#;
1094 let weights_result4: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str4);
1095 if weights_result4.is_ok() {
1096 let weights4 = weights_result4.unwrap();
1097 let result4 = Tholder::new(None, None, Some(TholderSith::Weights(weights4)));
1098 assert!(result4.is_err(), "Should fail with weight > 1 (3/2)");
1099 }
1100
1101 let json_str5 = r#"["1/2", "1/2", "2/1"]"#;
1103 let weights_result5: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str5);
1104 if weights_result5.is_ok() {
1105 let weights5 = weights_result5.unwrap();
1106 let result5 = Tholder::new(None, None, Some(TholderSith::Weights(weights5)));
1107 assert!(result5.is_err(), "Should fail with weight > 1 (2/1)");
1108 }
1109
1110 let json_str6 = r#"["1/2", "1/2", "2"]"#;
1112 let weights_result6: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str6);
1113 if weights_result6.is_ok() {
1114 let weights6 = weights_result6.unwrap();
1115 let result6 = Tholder::new(None, None, Some(TholderSith::Weights(weights6)));
1116 assert!(result6.is_err(), "Should fail with integer weight > 1");
1117 }
1118 }
1119
1120 #[test]
1121 fn test_tholder_nested_validation_errors() {
1122 let json_str1 = r#"[["1/2", "1/2", "3/2"]]"#;
1124 let weights_result1: Result<Vec<Vec<WeightedSithElement>>, _> =
1125 serde_json::from_str(json_str1);
1126 if weights_result1.is_ok() {
1127 let nested_weights = weights_result1.unwrap();
1128 let flat_weights: Vec<WeightedSithElement> =
1129 nested_weights.into_iter().flatten().collect();
1130 let result1 = Tholder::new(None, None, Some(TholderSith::Weights(flat_weights)));
1131 assert!(result1.is_err(), "Should fail with nested weight > 1");
1132 }
1133
1134 let json_str2 = r#"[["1/2", "1/2"], "1"]"#;
1136 let weights_result2: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str2);
1137 if weights_result2.is_ok() {
1138 let weights2 = weights_result2.unwrap();
1139 let result2 = Tholder::new(None, None, Some(TholderSith::Weights(weights2)));
1140 }
1143
1144 let json_str3 = r#"[["1/2", "1/2"], "1.0"]"#;
1146 let weights_result3: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str3);
1147 if weights_result3.is_ok() {
1148 let weights3 = weights_result3.unwrap();
1149 let result3 = Tholder::new(None, None, Some(TholderSith::Weights(weights3)));
1150 assert!(
1151 result3.is_err(),
1152 "Should fail with float in mixed structure"
1153 );
1154 }
1155
1156 let json_str4 = r#"["1/2", "1/2", []]"#;
1158 let weights_result4: Result<Vec<WeightedSithElement>, _> = serde_json::from_str(json_str4);
1159 if weights_result4.is_ok() {
1160 let weights4 = weights_result4.unwrap();
1161 let result4 = Tholder::new(None, None, Some(TholderSith::Weights(weights4)));
1162 assert!(
1163 result4.is_err(),
1164 "Should fail with empty array in mixed structure"
1165 );
1166 }
1167 }
1168
1169 #[test]
1170 fn test_tholder_unweighted_valid_case() {
1171 let tholder = Tholder::new(None, None, Some(TholderSith::Integer(2))).unwrap();
1173 assert!(!tholder.weighted());
1174 assert_eq!(tholder.num().unwrap(), 2);
1175
1176 let TholderThold::Integer(thold) = tholder.thold() else {
1177 panic!("Expected integer threshold");
1178 };
1179 assert_eq!(*thold, 2);
1180 }
1181
1182 #[test]
1183 fn test_tholder_unweighted() {
1184 let expected_limen = b"MAAL";
1186
1187 let mut tholder = Tholder::default();
1189 tholder
1190 .process_sith(TholderSith::HexString("b".to_string()))
1191 .unwrap();
1192
1193 assert!(!tholder.weighted());
1195
1196 let TholderThold::Integer(thold) = tholder.thold() else {
1197 panic!("Invalid threshold")
1198 };
1199 assert_eq!(tholder.size(), *thold);
1200 assert_eq!(*thold, 11);
1201 assert_eq!(tholder.limen(), expected_limen);
1202
1203 let TholderSith::HexString(sith) = tholder.sith() else {
1204 panic!("Invalid sith")
1205 };
1206 assert_eq!(sith, "b");
1207 assert_eq!(tholder.json(), "\"b\"");
1208 assert_eq!(tholder.num().unwrap(), 11);
1209
1210 let insufficient_indices = vec![0, 1, 2];
1212 assert!(!tholder.satisfy(&insufficient_indices));
1213
1214 let sufficient_indices: Vec<usize> = (0..*thold).collect();
1216 assert!(tholder.satisfy(&sufficient_indices));
1217 }
1218
1219 #[test]
1220 fn test_tholder_integer_sith() {
1221 let expected_limen = b"MAAL";
1223 let tholder = Tholder::new(None, None, Some(TholderSith::Integer(11))).unwrap();
1224
1225 assert!(!tholder.weighted());
1226
1227 let TholderThold::Integer(thold) = tholder.thold() else {
1228 panic!("Invalid threshold")
1229 };
1230 assert_eq!(tholder.size(), *thold);
1231 assert_eq!(*thold, 11);
1232 assert_eq!(tholder.limen(), expected_limen);
1233
1234 let TholderSith::HexString(sith) = tholder.sith() else {
1235 panic!("Invalid sith")
1236 };
1237 assert_eq!(sith, "b");
1238 assert_eq!(tholder.json(), "\"b\"");
1239 assert_eq!(tholder.num().unwrap(), 11);
1240
1241 assert!(!tholder.satisfy(&[0, 1, 2]));
1242 assert!(tholder.satisfy(&(0..11).collect::<Vec<_>>()));
1243 }
1244
1245 #[test]
1246 fn test_tholder_from_limen() {
1247 let limen = b"MAAL";
1249 let tholder = Tholder::new(None, Some(limen.to_vec()), None).unwrap();
1250
1251 assert!(!tholder.weighted());
1252
1253 let TholderThold::Integer(thold) = tholder.thold() else {
1254 panic!("Invalid threshold")
1255 };
1256 assert_eq!(tholder.size(), *thold);
1257 assert_eq!(*thold, 11);
1258 assert_eq!(tholder.limen(), limen);
1259
1260 let TholderSith::HexString(sith) = tholder.sith() else {
1261 panic!("Invalid sith")
1262 };
1263 assert_eq!(sith, "b");
1264 assert_eq!(tholder.json(), "\"b\"");
1265 assert_eq!(tholder.num().unwrap(), 11);
1266
1267 assert!(!tholder.satisfy(&[0, 1, 2]));
1268 assert!(tholder.satisfy(&(0..11).collect::<Vec<_>>()));
1269 }
1270
1271 #[test]
1272 fn test_tholder_from_thold() {
1273 let expected_limen = b"MAAL";
1275 let tholder = Tholder::new(Some(TholderThold::Integer(11)), None, None).unwrap();
1276
1277 assert!(!tholder.weighted());
1278
1279 let TholderThold::Integer(thold) = tholder.thold() else {
1280 panic!("Invalid threshold")
1281 };
1282 assert_eq!(tholder.size(), *thold);
1283 assert_eq!(*thold, 11);
1284 assert_eq!(tholder.limen(), expected_limen);
1285
1286 let TholderSith::HexString(sith) = tholder.sith() else {
1287 panic!("Invalid sith")
1288 };
1289 assert_eq!(sith, "b");
1290 assert_eq!(tholder.json(), "\"b\"");
1291 assert_eq!(tholder.num().unwrap(), 11);
1292
1293 assert!(!tholder.satisfy(&[0, 1, 2]));
1294 assert!(tholder.satisfy(&(0..11).collect::<Vec<_>>()));
1295 }
1296
1297 #[test]
1298 fn test_tholder_hex_f() {
1299 let expected_limen = b"MAAP";
1301 let tholder =
1302 Tholder::new(None, None, Some(TholderSith::HexString("f".to_string()))).unwrap();
1303
1304 assert!(!tholder.weighted());
1305
1306 let TholderThold::Integer(thold) = tholder.thold() else {
1307 panic!("Invalid threshold")
1308 };
1309 assert_eq!(tholder.size(), *thold);
1310 assert_eq!(*thold, 15);
1311 assert_eq!(tholder.limen(), expected_limen);
1312
1313 let TholderSith::HexString(sith) = tholder.sith() else {
1314 panic!("Invalid sith")
1315 };
1316 assert_eq!(sith, "f");
1317 assert_eq!(tholder.json(), "\"f\"");
1318 assert_eq!(tholder.num().unwrap(), 15);
1319
1320 assert!(!tholder.satisfy(&[0, 1, 2]));
1321 assert!(tholder.satisfy(&(0..15).collect::<Vec<_>>()));
1322 }
1323
1324 #[test]
1325 fn test_tholder_integer_2() {
1326 let expected_limen = b"MAAC";
1328 let tholder = Tholder::new(None, None, Some(TholderSith::Integer(2))).unwrap();
1329
1330 assert!(!tholder.weighted());
1331
1332 let TholderThold::Integer(thold) = tholder.thold() else {
1333 panic!("Invalid threshold")
1334 };
1335 assert_eq!(tholder.size(), *thold);
1336 assert_eq!(*thold, 2);
1337 assert_eq!(tholder.limen(), expected_limen);
1338
1339 let TholderSith::HexString(sith) = tholder.sith() else {
1340 panic!("Invalid sith")
1341 };
1342 assert_eq!(sith, "2");
1343 assert_eq!(tholder.json(), "\"2\"");
1344 assert_eq!(tholder.num().unwrap(), 2);
1345
1346 assert!(tholder.satisfy(&[0, 1, 2])); assert!(tholder.satisfy(&(0..2).collect::<Vec<_>>())); }
1349
1350 #[test]
1351 fn test_tholder_integer_1() {
1352 let expected_limen = b"MAAB";
1354 let tholder = Tholder::new(None, None, Some(TholderSith::Integer(1))).unwrap();
1355
1356 assert!(!tholder.weighted());
1357
1358 let TholderThold::Integer(thold) = tholder.thold() else {
1359 panic!("Invalid threshold")
1360 };
1361 assert_eq!(tholder.size(), *thold);
1362 assert_eq!(*thold, 1);
1363 assert_eq!(tholder.limen(), expected_limen);
1364
1365 let TholderSith::HexString(sith) = tholder.sith() else {
1366 panic!("Invalid sith")
1367 };
1368 assert_eq!(sith, "1");
1369 assert_eq!(tholder.json(), "\"1\"");
1370 assert_eq!(tholder.num().unwrap(), 1);
1371
1372 assert!(tholder.satisfy(&[0])); assert!(tholder.satisfy(&(0..1).collect::<Vec<_>>())); }
1375
1376 #[test]
1377 fn test_deserialize_weighted_sith_elements() -> Result<(), Box<dyn std::error::Error>> {
1378 let json_str1 = r#"["1/2", "1/2", "1/4", "1/4", "1/4"]"#;
1380 let elements1: Vec<WeightedSithElement> = serde_json::from_str(json_str1)?;
1381
1382 assert_eq!(elements1.len(), 5);
1383 if let WeightedSithElement::Simple(val) = &elements1[0] {
1384 assert_eq!(val, "1/2");
1385 } else {
1386 panic!("Expected Simple element");
1387 }
1388
1389 let json_str2 = r#"[["1/2", "1/2", "1/4", "1/4", "1/4"], ["1", "1"]]"#;
1391 let elements2: Vec<Vec<WeightedSithElement>> = serde_json::from_str(json_str2)?;
1392
1393 assert_eq!(elements2.len(), 2);
1394 assert_eq!(elements2[0].len(), 5);
1395 assert_eq!(elements2[1].len(), 2);
1396
1397 if let WeightedSithElement::Simple(val) = &elements2[0][0] {
1398 assert_eq!(val, "1/2");
1399 } else {
1400 panic!("Expected Simple element");
1401 }
1402
1403 if let WeightedSithElement::Simple(val) = &elements2[1][0] {
1404 assert_eq!(val, "1");
1405 } else {
1406 panic!("Expected Simple element");
1407 }
1408
1409 let json_str3 = r#"[{"1/3":["1/2", "1/2", "1/2"]}, "1/3", "1/2", {"1/2": ["1", "1"]}]"#;
1411 let elements3: Vec<WeightedSithElement> = serde_json::from_str(json_str3)?;
1412
1413 assert_eq!(elements3.len(), 4);
1414
1415 match &elements3[0] {
1417 WeightedSithElement::Complex(map) => {
1418 assert_eq!(map.len(), 1);
1419 let values = map.get("1/3").expect("Key 1/3 should exist");
1420 assert_eq!(values.len(), 3);
1421
1422 if let WeightedSithElement::Simple(val) = &values[0] {
1423 assert_eq!(val, "1/2");
1424 } else {
1425 panic!("Expected Simple element in complex map");
1426 }
1427 }
1428 _ => panic!("Expected Complex element"),
1429 }
1430
1431 if let WeightedSithElement::Simple(val) = &elements3[1] {
1433 assert_eq!(val, "1/3");
1434 } else {
1435 panic!("Expected Simple element");
1436 }
1437
1438 if let WeightedSithElement::Simple(val) = &elements3[2] {
1440 assert_eq!(val, "1/2");
1441 } else {
1442 panic!("Expected Simple element");
1443 }
1444
1445 match &elements3[3] {
1447 WeightedSithElement::Complex(map) => {
1448 assert_eq!(map.len(), 1);
1449 let values = map.get("1/2").expect("Key 1/2 should exist");
1450 assert_eq!(values.len(), 2);
1451
1452 if let WeightedSithElement::Simple(val) = &values[0] {
1453 assert_eq!(val, "1");
1454 } else {
1455 panic!("Expected Simple element in complex map");
1456 }
1457 }
1458 _ => panic!("Expected Complex element"),
1459 }
1460
1461 let json_str4 = r#"[[{"1/3":["1/2", "1/2", "1/2"]}, "1/2", {"1/2": ["1", "1"]}], ["1/2", {"1/2": ["1", "1"]}]]"#;
1463 let elements4: Vec<Vec<WeightedSithElement>> = serde_json::from_str(json_str4)?;
1464
1465 assert_eq!(elements4.len(), 2);
1466 assert_eq!(elements4[0].len(), 3);
1467 assert_eq!(elements4[1].len(), 2);
1468
1469 match &elements4[0][0] {
1471 WeightedSithElement::Complex(map) => {
1472 assert_eq!(map.len(), 1);
1473 let values = map.get("1/3").expect("Key 1/3 should exist");
1474 assert_eq!(values.len(), 3);
1475
1476 if let WeightedSithElement::Simple(val) = &values[0] {
1477 assert_eq!(val, "1/2");
1478 } else {
1479 panic!("Expected Simple element in complex map");
1480 }
1481 }
1482 _ => panic!("Expected Complex element"),
1483 }
1484
1485 if let WeightedSithElement::Simple(val) = &elements4[0][1] {
1487 assert_eq!(val, "1/2");
1488 } else {
1489 panic!("Expected Simple element");
1490 }
1491
1492 match &elements4[1][1] {
1494 WeightedSithElement::Complex(map) => {
1495 assert_eq!(map.len(), 1);
1496 let values = map.get("1/2").expect("Key 1/2 should exist");
1497 assert_eq!(values.len(), 2);
1498
1499 if let WeightedSithElement::Simple(val) = &values[0] {
1500 assert_eq!(val, "1");
1501 } else {
1502 panic!("Expected Simple element in complex map");
1503 }
1504 }
1505 _ => panic!("Expected Complex element"),
1506 }
1507
1508 let json_str5 = r#"["1/2", ["1/3", "1/3", "1/3"], "1/4"]"#;
1510 let elements5: Vec<WeightedSithElement> = serde_json::from_str(json_str5)?;
1511
1512 assert_eq!(elements5.len(), 3);
1513
1514 match &elements5[1] {
1516 WeightedSithElement::Array(arr) => {
1517 assert_eq!(arr.len(), 3);
1518 if let WeightedSithElement::Simple(val) = &arr[0] {
1519 assert_eq!(val, "1/3");
1520 } else {
1521 panic!("Expected Simple element in array");
1522 }
1523 }
1524 _ => panic!("Expected Array element"),
1525 }
1526
1527 if let WeightedSithElement::Simple(val) = &elements1[0] {
1529 let weight = Tholder::weight(val)?;
1530 assert_eq!(weight, Rational32::new(1, 2));
1531 }
1532
1533 Ok(())
1534 }
1535
1536 #[test]
1537 fn test_deserialize_json_bytes() -> Result<(), Box<dyn std::error::Error>> {
1538 let json_bytes = br#"["1/2", "1/2", "1/4", "1/4", "1/4"]"#;
1540 let elements: Vec<WeightedSithElement> = serde_json::from_slice(json_bytes)?;
1541
1542 assert_eq!(elements.len(), 5);
1543 if let WeightedSithElement::Simple(val) = &elements[0] {
1544 assert_eq!(val, "1/2");
1545 let weight = Tholder::weight(val)?;
1546 assert_eq!(weight, Rational32::new(1, 2));
1547 } else {
1548 panic!("Expected Simple element");
1549 }
1550
1551 let complex_json_bytes =
1553 br#"[{"1/3":["1/2", "1/2", "1/2"]}, "1/3", "1/2", {"1/2": ["1", "1"]}]"#;
1554 let complex_elements: Vec<WeightedSithElement> =
1555 serde_json::from_slice(complex_json_bytes)?;
1556
1557 assert_eq!(complex_elements.len(), 4);
1558
1559 match &complex_elements[0] {
1561 WeightedSithElement::Complex(map) => {
1562 assert!(map.contains_key("1/3"));
1563 let values = map.get("1/3").unwrap();
1564 assert_eq!(values.len(), 3);
1565 }
1566 _ => panic!("Expected Complex element"),
1567 }
1568
1569 Ok(())
1570 }
1571
1572 #[test]
1574 fn test_process_weighted_sith() -> Result<(), Box<dyn std::error::Error>> {
1575 let json_str = r#"["1/2", "1/2", "1/4", "1/4", "1/4"]"#;
1578 let elements: Vec<WeightedSithElement> = serde_json::from_str(json_str)?;
1579
1580 let mut total_weight = Rational32::new(0, 1);
1582
1583 for element in &elements {
1584 if let WeightedSithElement::Simple(val) = element {
1585 total_weight = total_weight + Tholder::weight(val)?;
1586 }
1587 }
1588
1589 assert!(total_weight > Rational32::new(1, 1));
1591 assert_eq!(total_weight, Rational32::new(7, 4)); Ok(())
1594 }
1595
1596 fn test_tholder_weighted() -> Result<(), Box<dyn std::error::Error>> {
1599 let json_str = r#"["1/2", "1/2", "1/4", "1/4", "1/4"]"#;
1601 let weights: Vec<WeightedSithElement> = serde_json::from_str(json_str)?;
1602
1603 let tholder = Tholder::new(None, None, Some(TholderSith::Weights(weights)))?;
1605
1606 assert!(tholder.weighted());
1608 assert_eq!(tholder.size(), 5);
1609
1610 if let TholderThold::Weighted(clauses) = tholder.thold() {
1612 assert_eq!(clauses.len(), 1);
1614 assert_eq!(clauses[0].len(), 5);
1615
1616 if let WeightSpec::Simple(fraction) = clauses[0][0] {
1618 assert_eq!(fraction, Rational32::new(1, 2));
1619 } else {
1620 panic!("Expected Simple weight spec for first element");
1621 }
1622
1623 if let WeightSpec::Simple(fraction) = clauses[0][1] {
1624 assert_eq!(fraction, Rational32::new(1, 2));
1625 } else {
1626 panic!("Expected Simple weight spec for second element");
1627 }
1628
1629 if let WeightSpec::Simple(fraction) = clauses[0][2] {
1630 assert_eq!(fraction, Rational32::new(1, 4));
1631 } else {
1632 panic!("Expected Simple weight spec for third element");
1633 }
1634 } else {
1635 panic!("Expected Weighted threshold type");
1636 }
1637
1638 assert_eq!(tholder.limen(), b"4AAFA1s2c1s2c1s4c1s4c1s4");
1640
1641 if let TholderSith::Weights(weights) = tholder.sith() {
1644 assert_eq!(weights.len(), 5);
1645 if let WeightedSithElement::Simple(s) = &weights[0] {
1646 assert_eq!(s, "1/2");
1647 } else {
1648 panic!("Expected Simple weight element");
1649 }
1650 } else {
1651 panic!("Expected Weights sith type");
1652 }
1653
1654 let expected_json = r#"["1/2","1/2","1/4","1/4","1/4"]"#;
1657 assert_eq!(tholder.json(), expected_json);
1658
1659 assert_eq!(tholder.num(), None);
1661
1662 assert!(tholder.satisfy(&[0, 2, 4])); assert!(tholder.satisfy(&[0, 1])); assert!(tholder.satisfy(&[1, 3, 4])); assert!(tholder.satisfy(&[0, 1, 2, 3, 4])); assert!(tholder.satisfy(&[3, 2, 0])); assert!(tholder.satisfy(&[0, 0, 1, 2, 1])); assert!(!tholder.satisfy(&[0, 2])); assert!(!tholder.satisfy(&[2, 3, 4])); Ok(())
1678 }
1679 #[test]
1680 fn test_tholder_weighted_simple() -> Result<(), Box<dyn std::error::Error>> {
1681 let json_str = r#"["1/2", "1/2", "1/4", "1/4", "1/4"]"#;
1683 let weights: Vec<WeightedSithElement> = serde_json::from_str(json_str)?;
1684 let tholder = Tholder::new(None, None, Some(TholderSith::Weights(weights)))?;
1685
1686 assert!(tholder.weighted());
1688 assert_eq!(tholder.size(), 5);
1689
1690 if let TholderThold::Weighted(clauses) = tholder.thold() {
1692 assert_eq!(clauses.len(), 1); assert_eq!(clauses[0].len(), 5); if let WeightSpec::Simple(fraction) = clauses[0][0] {
1697 assert_eq!(fraction, Rational32::new(1, 2));
1698 } else {
1699 panic!("Expected Simple weight spec for first element");
1700 }
1701
1702 if let WeightSpec::Simple(fraction) = clauses[0][1] {
1703 assert_eq!(fraction, Rational32::new(1, 2));
1704 } else {
1705 panic!("Expected Simple weight spec for second element");
1706 }
1707
1708 if let WeightSpec::Simple(fraction) = clauses[0][2] {
1709 assert_eq!(fraction, Rational32::new(1, 4));
1710 } else {
1711 panic!("Expected Simple weight spec for third element");
1712 }
1713
1714 if let WeightSpec::Simple(fraction) = clauses[0][3] {
1715 assert_eq!(fraction, Rational32::new(1, 4));
1716 } else {
1717 panic!("Expected Simple weight spec for fourth element");
1718 }
1719
1720 if let WeightSpec::Simple(fraction) = clauses[0][4] {
1721 assert_eq!(fraction, Rational32::new(1, 4));
1722 } else {
1723 panic!("Expected Simple weight spec for fifth element");
1724 }
1725 } else {
1726 panic!("Expected Weighted threshold type");
1727 }
1728
1729 assert_eq!(tholder.limen(), b"4AAFA1s2c1s2c1s4c1s4c1s4");
1731
1732 if let TholderSith::Weights(weights) = tholder.sith() {
1734 assert_eq!(weights.len(), 5);
1735 if let WeightedSithElement::Simple(s) = &weights[0] {
1736 assert_eq!(s, "1/2");
1737 } else {
1738 panic!("Expected Simple weight element");
1739 }
1740 if let WeightedSithElement::Simple(s) = &weights[4] {
1741 assert_eq!(s, "1/4");
1742 } else {
1743 panic!("Expected Simple weight element");
1744 }
1745 } else {
1746 panic!("Expected Weights sith type");
1747 }
1748
1749 let expected_json = r#"["1/2","1/2","1/4","1/4","1/4"]"#;
1751 assert_eq!(tholder.json(), expected_json);
1752
1753 assert_eq!(tholder.num(), None);
1755
1756 assert!(tholder.satisfy(&[0, 2, 4])); assert!(tholder.satisfy(&[0, 1])); assert!(tholder.satisfy(&[1, 3, 4])); assert!(tholder.satisfy(&[0, 1, 2, 3, 4])); assert!(tholder.satisfy(&[3, 2, 0])); assert!(tholder.satisfy(&[0, 0, 1, 2, 1])); assert!(!tholder.satisfy(&[0, 2])); assert!(!tholder.satisfy(&[2, 3, 4])); Ok(())
1769 }
1770
1771 #[test]
1772 fn test_tholder_weighted_with_zero() -> Result<(), Box<dyn std::error::Error>> {
1773 let json_str = r#"["1/2", "1/2", "1/4", "1/4", "1/4", "0"]"#;
1775 let weights: Vec<WeightedSithElement> = serde_json::from_str(json_str)?;
1776 let tholder = Tholder::new(None, None, Some(TholderSith::Weights(weights)))?;
1777
1778 assert!(tholder.weighted());
1780 assert_eq!(tholder.size(), 6);
1781
1782 if let TholderThold::Weighted(clauses) = tholder.thold() {
1784 assert_eq!(clauses.len(), 1); assert_eq!(clauses[0].len(), 6); if let WeightSpec::Simple(fraction) = clauses[0][5] {
1789 assert_eq!(fraction, Rational32::new(0, 1));
1790 } else {
1791 panic!("Expected Simple weight spec for last element");
1792 }
1793 } else {
1794 panic!("Expected Weighted threshold type");
1795 }
1796
1797 assert_eq!(tholder.limen(), b"6AAGAAA1s2c1s2c1s4c1s4c1s4c0");
1799
1800 if let TholderSith::Weights(weights) = tholder.sith() {
1802 assert_eq!(weights.len(), 6);
1803 if let WeightedSithElement::Simple(s) = &weights[5] {
1804 assert_eq!(s, "0");
1805 } else {
1806 panic!("Expected Simple weight element");
1807 }
1808 } else {
1809 panic!("Expected Weights sith type");
1810 }
1811
1812 let expected_json = r#"["1/2","1/2","1/4","1/4","1/4","0"]"#;
1814 assert_eq!(tholder.json(), expected_json);
1815
1816 assert_eq!(tholder.num(), None);
1818
1819 assert!(tholder.satisfy(&[0, 2, 4])); assert!(tholder.satisfy(&[0, 1])); assert!(tholder.satisfy(&[1, 3, 4])); assert!(tholder.satisfy(&[0, 1, 2, 3, 4])); assert!(tholder.satisfy(&[3, 2, 0])); assert!(tholder.satisfy(&[0, 0, 1, 2, 1])); assert!(!tholder.satisfy(&[0, 2, 5])); assert!(!tholder.satisfy(&[2, 3, 4, 5])); Ok(())
1832 }
1833
1834 #[test]
1835 fn test_tholder_weighted_nested_single_clause() -> Result<(), Box<dyn std::error::Error>> {
1836 let json_str = r#"[["1/2", "1/2", "1/4", "1/4", "1/4"]]"#;
1838 let nested_weights: Vec<Vec<WeightedSithElement>> = serde_json::from_str(json_str)?;
1839
1840 let tholder = Tholder::new(None, None, Some(TholderSith::Json(json_str.to_string())))?;
1842
1843 assert!(tholder.weighted());
1845 assert_eq!(tholder.size(), 5);
1846
1847 if let TholderThold::Weighted(clauses) = tholder.thold() {
1849 assert_eq!(clauses.len(), 1); assert_eq!(clauses[0].len(), 5); if let WeightSpec::Simple(fraction) = clauses[0][0] {
1854 assert_eq!(fraction, Rational32::new(1, 2));
1855 } else {
1856 panic!("Expected Simple weight spec for first element");
1857 }
1858
1859 if let WeightSpec::Simple(fraction) = clauses[0][1] {
1860 assert_eq!(fraction, Rational32::new(1, 2));
1861 } else {
1862 panic!("Expected Simple weight spec for second element");
1863 }
1864
1865 if let WeightSpec::Simple(fraction) = clauses[0][2] {
1866 assert_eq!(fraction, Rational32::new(1, 4));
1867 } else {
1868 panic!("Expected Simple weight spec for third element");
1869 }
1870
1871 if let WeightSpec::Simple(fraction) = clauses[0][3] {
1872 assert_eq!(fraction, Rational32::new(1, 4));
1873 } else {
1874 panic!("Expected Simple weight spec for fourth element");
1875 }
1876
1877 if let WeightSpec::Simple(fraction) = clauses[0][4] {
1878 assert_eq!(fraction, Rational32::new(1, 4));
1879 } else {
1880 panic!("Expected Simple weight spec for fifth element");
1881 }
1882 } else {
1883 panic!("Expected Weighted threshold type");
1884 }
1885
1886 assert_eq!(tholder.limen(), b"4AAFA1s2c1s2c1s4c1s4c1s4");
1888
1889 if let TholderSith::Weights(weights) = tholder.sith() {
1891 assert_eq!(weights.len(), 5);
1892 if let WeightedSithElement::Simple(s) = &weights[0] {
1893 assert_eq!(s, "1/2");
1894 } else {
1895 panic!("Expected Simple weight element");
1896 }
1897 } else {
1898 panic!("Expected Weights sith type");
1899 }
1900
1901 let expected_json = r#"["1/2","1/2","1/4","1/4","1/4"]"#;
1903 assert_eq!(tholder.json(), expected_json);
1904
1905 assert_eq!(tholder.num(), None);
1907
1908 assert!(tholder.satisfy(&[1, 2, 3])); assert!(tholder.satisfy(&[0, 1, 2])); assert!(tholder.satisfy(&[1, 3, 4])); assert!(tholder.satisfy(&[0, 1, 2, 3, 4])); assert!(tholder.satisfy(&[3, 2, 0])); assert!(tholder.satisfy(&[0, 0, 1, 2, 1, 4, 4])); assert!(!tholder.satisfy(&[0, 2])); assert!(!tholder.satisfy(&[2, 3, 4])); Ok(())
1921 }
1922
1923 #[test]
1924 fn test_tholder_weighted_multi_clause() -> Result<(), Box<dyn std::error::Error>> {
1925 let json_str = r#"[["1/2", "1/2", "1/4", "1/4", "1/4"], ["1", "1"]]"#;
1927 let nested_weights: Vec<Vec<WeightedSithElement>> = serde_json::from_str(json_str)?;
1928
1929 let mut all_clauses = Vec::new();
1932
1933 for clause_weights in nested_weights {
1934 let mut clause_specs = Vec::new();
1935 for weight_element in clause_weights {
1936 if let WeightedSithElement::Simple(weight_str) = weight_element {
1937 let weight = Tholder::weight(&weight_str)?;
1938 clause_specs.push(WeightSpec::Simple(weight));
1939 }
1940 }
1941 all_clauses.push(clause_specs);
1942 }
1943
1944 let tholder = Tholder::new(Some(TholderThold::Weighted(all_clauses)), None, None)?;
1945
1946 assert!(tholder.weighted());
1948 assert_eq!(tholder.size(), 7); if let TholderThold::Weighted(clauses) = tholder.thold() {
1952 assert_eq!(clauses.len(), 2); assert_eq!(clauses[0].len(), 5); assert_eq!(clauses[1].len(), 2); if let WeightSpec::Simple(fraction) = clauses[0][0] {
1958 assert_eq!(fraction, Rational32::new(1, 2));
1959 } else {
1960 panic!("Expected Simple weight spec");
1961 }
1962
1963 if let WeightSpec::Simple(fraction) = clauses[1][0] {
1965 assert_eq!(fraction, Rational32::new(1, 1));
1966 } else {
1967 panic!("Expected Simple weight spec");
1968 }
1969
1970 if let WeightSpec::Simple(fraction) = clauses[1][1] {
1971 assert_eq!(fraction, Rational32::new(1, 1));
1972 } else {
1973 panic!("Expected Simple weight spec");
1974 }
1975 } else {
1976 panic!("Expected Weighted threshold type");
1977 }
1978
1979 assert_eq!(tholder.limen(), b"4AAGA1s2c1s2c1s4c1s4c1s4a1c1");
1981
1982 if let TholderSith::Json(json_str) = tholder.sith() {
1984 let expected_nested = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
1985 assert_eq!(json_str, expected_nested);
1986 } else {
1987 panic!("Expected Json sith type for multi-clause");
1988 }
1989
1990 let expected_json = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
1992 assert_eq!(tholder.json(), expected_json);
1993
1994 assert_eq!(tholder.num(), None);
1996
1997 assert!(tholder.satisfy(&[1, 2, 3, 5])); assert!(tholder.satisfy(&[0, 1, 6])); assert!(!tholder.satisfy(&[0, 1])); assert!(!tholder.satisfy(&[5, 6])); assert!(!tholder.satisfy(&[2, 3, 4])); assert!(!tholder.satisfy(&[])); Ok(())
2009 }
2010
2011 #[test]
2012 fn test_tholder_json_string_multi_clause() -> Result<(), Box<dyn std::error::Error>> {
2013 let json_str = r#"[["1/2", "1/2", "1/4", "1/4", "1/4"], ["1", "1"]]"#;
2015 let tholder = Tholder::new(None, None, Some(TholderSith::Json(json_str.to_string())))?;
2016
2017 assert!(tholder.weighted());
2019 assert_eq!(tholder.size(), 7); if let TholderThold::Weighted(clauses) = tholder.thold() {
2023 assert_eq!(clauses.len(), 2); assert_eq!(clauses[0].len(), 5); assert_eq!(clauses[1].len(), 2); if let WeightSpec::Simple(fraction) = clauses[0][0] {
2029 assert_eq!(fraction, Rational32::new(1, 2));
2030 } else {
2031 panic!("Expected Simple weight spec");
2032 }
2033
2034 if let WeightSpec::Simple(fraction) = clauses[0][1] {
2035 assert_eq!(fraction, Rational32::new(1, 2));
2036 } else {
2037 panic!("Expected Simple weight spec");
2038 }
2039
2040 if let WeightSpec::Simple(fraction) = clauses[0][2] {
2041 assert_eq!(fraction, Rational32::new(1, 4));
2042 } else {
2043 panic!("Expected Simple weight spec");
2044 }
2045
2046 if let WeightSpec::Simple(fraction) = clauses[1][0] {
2048 assert_eq!(fraction, Rational32::new(1, 1));
2049 } else {
2050 panic!("Expected Simple weight spec");
2051 }
2052
2053 if let WeightSpec::Simple(fraction) = clauses[1][1] {
2054 assert_eq!(fraction, Rational32::new(1, 1));
2055 } else {
2056 panic!("Expected Simple weight spec");
2057 }
2058 } else {
2059 panic!("Expected Weighted threshold type");
2060 }
2061
2062 assert_eq!(tholder.limen(), b"4AAGA1s2c1s2c1s4c1s4c1s4a1c1");
2064
2065 if let TholderSith::Json(json_str) = tholder.sith() {
2067 let expected_nested = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
2068 assert_eq!(json_str, expected_nested);
2069 } else {
2070 panic!("Expected Json sith type for multi-clause");
2071 }
2072
2073 let expected_json = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
2075 assert_eq!(tholder.json(), expected_json);
2076
2077 assert_eq!(tholder.num(), None);
2079
2080 assert!(tholder.satisfy(&[1, 2, 3, 5])); assert!(tholder.satisfy(&[0, 1, 6])); assert!(!tholder.satisfy(&[0, 1])); assert!(!tholder.satisfy(&[5, 6])); assert!(!tholder.satisfy(&[2, 3, 4])); assert!(!tholder.satisfy(&[])); Ok(())
2092 }
2093
2094 #[test]
2095 fn test_tholder_json_string_single_clause_nested() -> Result<(), Box<dyn std::error::Error>> {
2096 let json_str = r#"[["1/2", "1/2", "1/4", "1/4", "1/4"]]"#;
2098 let tholder = Tholder::new(None, None, Some(TholderSith::Json(json_str.to_string())))?;
2099
2100 assert!(tholder.weighted());
2102 assert_eq!(tholder.size(), 5);
2103
2104 if let TholderThold::Weighted(clauses) = tholder.thold() {
2106 assert_eq!(clauses.len(), 1); assert_eq!(clauses[0].len(), 5); if let WeightSpec::Simple(fraction) = clauses[0][0] {
2111 assert_eq!(fraction, Rational32::new(1, 2));
2112 } else {
2113 panic!("Expected Simple weight spec for first element");
2114 }
2115
2116 if let WeightSpec::Simple(fraction) = clauses[0][1] {
2117 assert_eq!(fraction, Rational32::new(1, 2));
2118 } else {
2119 panic!("Expected Simple weight spec for second element");
2120 }
2121
2122 if let WeightSpec::Simple(fraction) = clauses[0][2] {
2123 assert_eq!(fraction, Rational32::new(1, 4));
2124 } else {
2125 panic!("Expected Simple weight spec for third element");
2126 }
2127
2128 if let WeightSpec::Simple(fraction) = clauses[0][3] {
2129 assert_eq!(fraction, Rational32::new(1, 4));
2130 } else {
2131 panic!("Expected Simple weight spec for fourth element");
2132 }
2133
2134 if let WeightSpec::Simple(fraction) = clauses[0][4] {
2135 assert_eq!(fraction, Rational32::new(1, 4));
2136 } else {
2137 panic!("Expected Simple weight spec for fifth element");
2138 }
2139 } else {
2140 panic!("Expected Weighted threshold type");
2141 }
2142
2143 assert_eq!(tholder.limen(), b"4AAFA1s2c1s2c1s4c1s4c1s4");
2145
2146 if let TholderSith::Weights(weights) = tholder.sith() {
2148 assert_eq!(weights.len(), 5);
2149 if let WeightedSithElement::Simple(s) = &weights[0] {
2150 assert_eq!(s, "1/2");
2151 } else {
2152 panic!("Expected Simple weight element");
2153 }
2154 } else {
2155 panic!("Expected Weights sith type");
2156 }
2157
2158 let expected_json = r#"["1/2","1/2","1/4","1/4","1/4"]"#;
2160 assert_eq!(tholder.json(), expected_json);
2161
2162 assert_eq!(tholder.num(), None);
2164
2165 assert!(tholder.satisfy(&[1, 2, 3])); assert!(tholder.satisfy(&[0, 1, 2])); assert!(tholder.satisfy(&[1, 3, 4])); assert!(tholder.satisfy(&[0, 1, 2, 3, 4])); assert!(tholder.satisfy(&[3, 2, 0])); assert!(tholder.satisfy(&[0, 0, 1, 2, 1, 4, 4])); assert!(!tholder.satisfy(&[0, 2])); assert!(!tholder.satisfy(&[2, 3, 4])); Ok(())
2178 }
2179
2180 #[test]
2181 fn test_tholder_json_string_simple_array() -> Result<(), Box<dyn std::error::Error>> {
2182 let json_str = r#"["1/2", "1/2", "1/4", "1/4", "1/4", "0"]"#;
2184 let tholder = Tholder::new(None, None, Some(TholderSith::Json(json_str.to_string())))?;
2185
2186 assert!(tholder.weighted());
2188 assert_eq!(tholder.size(), 6);
2189
2190 if let TholderThold::Weighted(clauses) = tholder.thold() {
2192 assert_eq!(clauses.len(), 1); assert_eq!(clauses[0].len(), 6); if let WeightSpec::Simple(fraction) = clauses[0][0] {
2197 assert_eq!(fraction, Rational32::new(1, 2));
2198 } else {
2199 panic!("Expected Simple weight spec for first element");
2200 }
2201
2202 if let WeightSpec::Simple(fraction) = clauses[0][1] {
2203 assert_eq!(fraction, Rational32::new(1, 2));
2204 } else {
2205 panic!("Expected Simple weight spec for second element");
2206 }
2207
2208 if let WeightSpec::Simple(fraction) = clauses[0][2] {
2209 assert_eq!(fraction, Rational32::new(1, 4));
2210 } else {
2211 panic!("Expected Simple weight spec for third element");
2212 }
2213
2214 if let WeightSpec::Simple(fraction) = clauses[0][3] {
2215 assert_eq!(fraction, Rational32::new(1, 4));
2216 } else {
2217 panic!("Expected Simple weight spec for fourth element");
2218 }
2219
2220 if let WeightSpec::Simple(fraction) = clauses[0][4] {
2221 assert_eq!(fraction, Rational32::new(1, 4));
2222 } else {
2223 panic!("Expected Simple weight spec for fifth element");
2224 }
2225
2226 if let WeightSpec::Simple(fraction) = clauses[0][5] {
2228 assert_eq!(fraction, Rational32::new(0, 1));
2229 } else {
2230 panic!("Expected Simple weight spec for last element");
2231 }
2232 } else {
2233 panic!("Expected Weighted threshold type");
2234 }
2235
2236 assert_eq!(tholder.limen(), b"6AAGAAA1s2c1s2c1s4c1s4c1s4c0");
2238
2239 if let TholderSith::Weights(weights) = tholder.sith() {
2241 assert_eq!(weights.len(), 6);
2242 if let WeightedSithElement::Simple(s) = &weights[0] {
2243 assert_eq!(s, "1/2");
2244 } else {
2245 panic!("Expected Simple weight element");
2246 }
2247 if let WeightedSithElement::Simple(s) = &weights[5] {
2248 assert_eq!(s, "0");
2249 } else {
2250 panic!("Expected Simple weight element");
2251 }
2252 } else {
2253 panic!("Expected Weights sith type");
2254 }
2255
2256 let expected_json = r#"["1/2","1/2","1/4","1/4","1/4","0"]"#;
2258 assert_eq!(tholder.json(), expected_json);
2259
2260 assert_eq!(tholder.num(), None);
2262
2263 assert!(tholder.satisfy(&[0, 2, 4])); assert!(tholder.satisfy(&[0, 1])); assert!(tholder.satisfy(&[1, 3, 4])); assert!(tholder.satisfy(&[0, 1, 2, 3, 4])); assert!(tholder.satisfy(&[3, 2, 0])); assert!(tholder.satisfy(&[0, 0, 1, 2, 1])); assert!(!tholder.satisfy(&[0, 2, 5])); assert!(!tholder.satisfy(&[2, 3, 4, 5])); Ok(())
2276 }
2277
2278 #[test]
2279 fn test_tholder_from_limen_multi_clause() -> Result<(), Box<dyn std::error::Error>> {
2280 let limen = b"4AAGA1s2c1s2c1s4c1s4c1s4a1c1".to_vec();
2282 let tholder = Tholder::new(None, Some(limen), None)?;
2283
2284 assert!(tholder.weighted());
2286 assert_eq!(tholder.size(), 7); if let TholderThold::Weighted(clauses) = tholder.thold() {
2290 assert_eq!(clauses.len(), 2); assert_eq!(clauses[0].len(), 5); assert_eq!(clauses[1].len(), 2); if let WeightSpec::Simple(fraction) = clauses[0][0] {
2296 assert_eq!(fraction, Rational32::new(1, 2));
2297 } else {
2298 panic!("Expected Simple weight spec");
2299 }
2300
2301 if let WeightSpec::Simple(fraction) = clauses[0][1] {
2302 assert_eq!(fraction, Rational32::new(1, 2));
2303 } else {
2304 panic!("Expected Simple weight spec");
2305 }
2306
2307 if let WeightSpec::Simple(fraction) = clauses[0][2] {
2308 assert_eq!(fraction, Rational32::new(1, 4));
2309 } else {
2310 panic!("Expected Simple weight spec");
2311 }
2312
2313 if let WeightSpec::Simple(fraction) = clauses[0][3] {
2314 assert_eq!(fraction, Rational32::new(1, 4));
2315 } else {
2316 panic!("Expected Simple weight spec");
2317 }
2318
2319 if let WeightSpec::Simple(fraction) = clauses[0][4] {
2320 assert_eq!(fraction, Rational32::new(1, 4));
2321 } else {
2322 panic!("Expected Simple weight spec");
2323 }
2324
2325 if let WeightSpec::Simple(fraction) = clauses[1][0] {
2327 assert_eq!(fraction, Rational32::new(1, 1));
2328 } else {
2329 panic!("Expected Simple weight spec");
2330 }
2331
2332 if let WeightSpec::Simple(fraction) = clauses[1][1] {
2333 assert_eq!(fraction, Rational32::new(1, 1));
2334 } else {
2335 panic!("Expected Simple weight spec");
2336 }
2337 } else {
2338 panic!("Expected Weighted threshold type");
2339 }
2340
2341 assert_eq!(tholder.limen(), b"4AAGA1s2c1s2c1s4c1s4c1s4a1c1");
2343
2344 if let TholderSith::Json(json_str) = tholder.sith() {
2346 let expected_nested = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
2347 assert_eq!(json_str, expected_nested);
2348 } else {
2349 panic!("Expected Json sith type for multi-clause");
2350 }
2351
2352 let expected_json = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
2354 assert_eq!(tholder.json(), expected_json);
2355
2356 assert_eq!(tholder.num(), None);
2358
2359 assert!(tholder.satisfy(&[1, 2, 3, 5])); assert!(tholder.satisfy(&[0, 1, 6])); assert!(!tholder.satisfy(&[0, 1])); assert!(!tholder.satisfy(&[5, 6])); assert!(!tholder.satisfy(&[2, 3, 4])); assert!(!tholder.satisfy(&[])); Ok(())
2371 }
2372
2373 #[test]
2374 fn test_tholder_from_thold_multi_clause() -> Result<(), Box<dyn std::error::Error>> {
2375 let thold = TholderThold::Weighted(vec![
2378 vec![
2379 WeightSpec::Simple(Rational32::new(1, 2)),
2380 WeightSpec::Simple(Rational32::new(1, 2)),
2381 WeightSpec::Simple(Rational32::new(1, 4)),
2382 WeightSpec::Simple(Rational32::new(1, 4)),
2383 WeightSpec::Simple(Rational32::new(1, 4)),
2384 ],
2385 vec![
2386 WeightSpec::Simple(Rational32::new(1, 1)),
2387 WeightSpec::Simple(Rational32::new(1, 1)),
2388 ],
2389 ]);
2390
2391 let tholder = Tholder::new(Some(thold), None, None)?;
2392
2393 assert!(tholder.weighted());
2395 assert_eq!(tholder.size(), 7); if let TholderThold::Weighted(clauses) = tholder.thold() {
2399 assert_eq!(clauses.len(), 2); assert_eq!(clauses[0].len(), 5); assert_eq!(clauses[1].len(), 2); if let WeightSpec::Simple(fraction) = clauses[0][0] {
2405 assert_eq!(fraction, Rational32::new(1, 2));
2406 } else {
2407 panic!("Expected Simple weight spec");
2408 }
2409
2410 if let WeightSpec::Simple(fraction) = clauses[0][1] {
2411 assert_eq!(fraction, Rational32::new(1, 2));
2412 } else {
2413 panic!("Expected Simple weight spec");
2414 }
2415
2416 if let WeightSpec::Simple(fraction) = clauses[0][2] {
2417 assert_eq!(fraction, Rational32::new(1, 4));
2418 } else {
2419 panic!("Expected Simple weight spec");
2420 }
2421
2422 if let WeightSpec::Simple(fraction) = clauses[0][3] {
2423 assert_eq!(fraction, Rational32::new(1, 4));
2424 } else {
2425 panic!("Expected Simple weight spec");
2426 }
2427
2428 if let WeightSpec::Simple(fraction) = clauses[0][4] {
2429 assert_eq!(fraction, Rational32::new(1, 4));
2430 } else {
2431 panic!("Expected Simple weight spec");
2432 }
2433
2434 if let WeightSpec::Simple(fraction) = clauses[1][0] {
2436 assert_eq!(fraction, Rational32::new(1, 1));
2437 } else {
2438 panic!("Expected Simple weight spec");
2439 }
2440
2441 if let WeightSpec::Simple(fraction) = clauses[1][1] {
2442 assert_eq!(fraction, Rational32::new(1, 1));
2443 } else {
2444 panic!("Expected Simple weight spec");
2445 }
2446 } else {
2447 panic!("Expected Weighted threshold type");
2448 }
2449
2450 assert_eq!(tholder.limen(), b"4AAGA1s2c1s2c1s4c1s4c1s4a1c1");
2452
2453 if let TholderSith::Json(json_str) = tholder.sith() {
2455 let expected_nested = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
2456 assert_eq!(json_str, expected_nested);
2457 } else {
2458 panic!("Expected Json sith type for multi-clause");
2459 }
2460
2461 let expected_json = r#"[["1/2","1/2","1/4","1/4","1/4"],["1","1"]]"#;
2463 assert_eq!(tholder.json(), expected_json);
2464
2465 assert_eq!(tholder.num(), None);
2467
2468 assert!(tholder.satisfy(&[1, 2, 3, 5])); assert!(tholder.satisfy(&[0, 1, 6])); assert!(!tholder.satisfy(&[0, 1])); assert!(!tholder.satisfy(&[5, 6])); assert!(!tholder.satisfy(&[2, 3, 4])); assert!(!tholder.satisfy(&[])); Ok(())
2480 }
2481
2482 #[test]
2483 fn test_tholder_nested_weighted_single_clause() -> Result<(), Box<dyn std::error::Error>> {
2484 let json_str = r#"[{"1/3":["1/2", "1/2", "1/2"]}, "1/3", "1/2", {"1/2": ["1", "1"]}]"#;
2487 let tholder = Tholder::new(None, None, Some(TholderSith::Json(json_str.to_string())))?;
2488
2489 assert!(tholder.weighted());
2491 assert_eq!(tholder.size(), 7); if let TholderThold::Weighted(clauses) = tholder.thold() {
2495 assert_eq!(clauses.len(), 1); assert_eq!(clauses[0].len(), 4); if let WeightSpec::WeightedMap(key_weight, nested_weights) = &clauses[0][0] {
2500 assert_eq!(*key_weight, Rational32::new(1, 3));
2501 assert_eq!(nested_weights.len(), 3);
2502 assert_eq!(nested_weights[0], Rational32::new(1, 2));
2503 assert_eq!(nested_weights[1], Rational32::new(1, 2));
2504 assert_eq!(nested_weights[2], Rational32::new(1, 2));
2505 } else {
2506 panic!("Expected WeightedMap for first element");
2507 }
2508
2509 if let WeightSpec::Simple(weight) = clauses[0][1] {
2511 assert_eq!(weight, Rational32::new(1, 3));
2512 } else {
2513 panic!("Expected Simple weight for second element");
2514 }
2515
2516 if let WeightSpec::Simple(weight) = clauses[0][2] {
2518 assert_eq!(weight, Rational32::new(1, 2));
2519 } else {
2520 panic!("Expected Simple weight for third element");
2521 }
2522
2523 if let WeightSpec::WeightedMap(key_weight, nested_weights) = &clauses[0][3] {
2525 assert_eq!(*key_weight, Rational32::new(1, 2));
2526 assert_eq!(nested_weights.len(), 2);
2527 assert_eq!(nested_weights[0], Rational32::new(1, 1));
2528 assert_eq!(nested_weights[1], Rational32::new(1, 1));
2529 } else {
2530 panic!("Expected WeightedMap for fourth element");
2531 }
2532 } else {
2533 panic!("Expected Weighted threshold type");
2534 }
2535
2536 assert_eq!(tholder.limen(), b"4AAIA1s3k1s2v1s2v1s2c1s3c1s2c1s2k1v1");
2538
2539 if let TholderSith::Weights(weights) = tholder.sith() {
2541 assert_eq!(weights.len(), 4);
2542
2543 if let WeightedSithElement::Complex(map) = &weights[0] {
2545 assert!(map.contains_key("1/3"));
2546 let values = map.get("1/3").unwrap();
2547 assert_eq!(values.len(), 3);
2548 } else {
2549 panic!("Expected Complex element for first weight");
2550 }
2551
2552 if let WeightedSithElement::Simple(s) = &weights[1] {
2554 assert_eq!(s, "1/3");
2555 } else {
2556 panic!("Expected Simple element for second weight");
2557 }
2558
2559 if let WeightedSithElement::Simple(s) = &weights[2] {
2561 assert_eq!(s, "1/2");
2562 } else {
2563 panic!("Expected Simple element for third weight");
2564 }
2565
2566 if let WeightedSithElement::Complex(map) = &weights[3] {
2568 assert!(map.contains_key("1/2"));
2569 let values = map.get("1/2").unwrap();
2570 assert_eq!(values.len(), 2);
2571 } else {
2572 panic!("Expected Complex element for fourth weight");
2573 }
2574 } else {
2575 panic!("Expected Weights sith type");
2576 }
2577
2578 let expected_json = r#"[{"1/3":["1/2","1/2","1/2"]},"1/3","1/2",{"1/2":["1","1"]}]"#;
2580 assert_eq!(tholder.json(), expected_json);
2581
2582 assert_eq!(tholder.num(), None);
2584
2585 assert!(tholder.satisfy(&[0, 2, 3, 6])); assert!(tholder.satisfy(&[3, 4, 5])); assert!(tholder.satisfy(&[1, 2, 3, 4])); assert!(tholder.satisfy(&[4, 6])); assert!(tholder.satisfy(&[4, 2, 0, 3])); assert!(tholder.satisfy(&[0, 0, 1, 2, 1, 5, 6, 3])); assert!(!tholder.satisfy(&[0, 2, 5])); assert!(!tholder.satisfy(&[2, 3, 4])); Ok(())
2600 }
2601
2602 #[test]
2603 fn test_tholder_nested_weighted_from_limen() -> Result<(), Box<dyn std::error::Error>> {
2604 let limen = b"4AAIA1s3k1s2v1s2v1s2c1s3c1s2c1s2k1v1".to_vec();
2606 let tholder = Tholder::new(None, Some(limen), None)?;
2607
2608 assert!(tholder.weighted());
2610 assert_eq!(tholder.size(), 7);
2611
2612 if let TholderThold::Weighted(clauses) = tholder.thold() {
2614 assert_eq!(clauses.len(), 1);
2615 assert_eq!(clauses[0].len(), 4);
2616
2617 if let WeightSpec::WeightedMap(key_weight, nested_weights) = &clauses[0][0] {
2619 assert_eq!(*key_weight, Rational32::new(1, 3));
2620 assert_eq!(nested_weights.len(), 3);
2621 } else {
2622 panic!("Expected WeightedMap for first element");
2623 }
2624 } else {
2625 panic!("Expected Weighted threshold type");
2626 }
2627
2628 assert_eq!(tholder.limen(), b"4AAIA1s3k1s2v1s2v1s2c1s3c1s2c1s2k1v1");
2630
2631 let expected_json = r#"[{"1/3":["1/2","1/2","1/2"]},"1/3","1/2",{"1/2":["1","1"]}]"#;
2633 assert_eq!(tholder.json(), expected_json);
2634
2635 assert_eq!(tholder.num(), None);
2636
2637 Ok(())
2638 }
2639
2640 #[test]
2641 fn test_tholder_nested_weighted_from_thold() -> Result<(), Box<dyn std::error::Error>> {
2642 let thold = TholderThold::Weighted(vec![vec![
2644 WeightSpec::WeightedMap(
2645 Rational32::new(1, 3),
2646 vec![
2647 Rational32::new(1, 2),
2648 Rational32::new(1, 2),
2649 Rational32::new(1, 2),
2650 ],
2651 ),
2652 WeightSpec::Simple(Rational32::new(1, 3)),
2653 WeightSpec::Simple(Rational32::new(1, 2)),
2654 WeightSpec::WeightedMap(
2655 Rational32::new(1, 2),
2656 vec![Rational32::new(1, 1), Rational32::new(1, 1)],
2657 ),
2658 ]]);
2659
2660 let tholder = Tholder::new(Some(thold), None, None)?;
2661
2662 assert!(tholder.weighted());
2664 assert_eq!(tholder.size(), 7);
2665
2666 assert_eq!(tholder.limen(), b"4AAIA1s3k1s2v1s2v1s2c1s3c1s2c1s2k1v1");
2668
2669 let expected_json = r#"[{"1/3":["1/2","1/2","1/2"]},"1/3","1/2",{"1/2":["1","1"]}]"#;
2671 assert_eq!(tholder.json(), expected_json);
2672
2673 assert_eq!(tholder.num(), None);
2674
2675 Ok(())
2676 }
2677
2678 #[test]
2679 fn test_tholder_nested_weighted_multi_clause() -> Result<(), Box<dyn std::error::Error>> {
2680 let json_str = r#"[[{"1/3":["1/2", "1/2", "1/2"]}, "1/2", {"1/2": ["1", "1"]}], ["1/2", {"1/2": ["1", "1"]}]]"#;
2682 let tholder = Tholder::new(None, None, Some(TholderSith::Json(json_str.to_string())))?;
2683
2684 assert!(tholder.weighted());
2686 assert_eq!(tholder.size(), 9); if let TholderThold::Weighted(clauses) = tholder.thold() {
2690 assert_eq!(clauses.len(), 2); assert_eq!(clauses[0].len(), 3); assert_eq!(clauses[1].len(), 2); if let WeightSpec::WeightedMap(key_weight, nested_weights) = &clauses[0][0] {
2696 assert_eq!(*key_weight, Rational32::new(1, 3));
2697 assert_eq!(nested_weights.len(), 3);
2698 } else {
2699 panic!("Expected WeightedMap for first clause first element");
2700 }
2701
2702 if let WeightSpec::WeightedMap(key_weight, nested_weights) = &clauses[1][1] {
2704 assert_eq!(*key_weight, Rational32::new(1, 2));
2705 assert_eq!(nested_weights.len(), 2);
2706 } else {
2707 panic!("Expected WeightedMap for second clause second element");
2708 }
2709 } else {
2710 panic!("Expected Weighted threshold type");
2711 }
2712
2713 assert_eq!(
2715 tholder.limen(),
2716 b"4AAKA1s3k1s2v1s2v1s2c1s2c1s2k1v1a1s2c1s2k1v1"
2717 );
2718
2719 if let TholderSith::Json(json_str) = tholder.sith() {
2721 let expected_nested = r#"[[{"1/3":["1/2","1/2","1/2"]},"1/2",{"1/2":["1","1"]}],["1/2",{"1/2":["1","1"]}]]"#;
2722 assert_eq!(json_str, expected_nested);
2723 } else {
2724 panic!("Expected Json sith type for multi-clause");
2725 }
2726
2727 let expected_json =
2729 r#"[[{"1/3":["1/2","1/2","1/2"]},"1/2",{"1/2":["1","1"]}],["1/2",{"1/2":["1","1"]}]]"#;
2730 assert_eq!(tholder.json(), expected_json);
2731
2732 assert_eq!(tholder.num(), None);
2733
2734 assert!(tholder.satisfy(&[0, 2, 3, 5, 6, 7])); assert!(tholder.satisfy(&[3, 4, 5, 6, 8])); assert!(tholder.satisfy(&[1, 2, 3, 4, 6, 7])); assert!(tholder.satisfy(&[4, 2, 0, 3, 8, 6])); assert!(tholder.satisfy(&[0, 0, 1, 2, 1, 8, 3, 5, 6, 3])); assert!(!tholder.satisfy(&[0, 2, 5])); assert!(!tholder.satisfy(&[6, 7, 8])); Ok(())
2747 }
2748
2749 #[test]
2750 fn test_tholder_nested_weighted_multi_clause_from_limen(
2751 ) -> Result<(), Box<dyn std::error::Error>> {
2752 let limen = b"4AAKA1s3k1s2v1s2v1s2c1s2c1s2k1v1a1s2c1s2k1v1".to_vec();
2754 let tholder = Tholder::new(None, Some(limen), None)?;
2755
2756 assert!(tholder.weighted());
2757 assert_eq!(tholder.size(), 9);
2758 assert_eq!(
2759 tholder.limen(),
2760 b"4AAKA1s3k1s2v1s2v1s2c1s2c1s2k1v1a1s2c1s2k1v1"
2761 );
2762
2763 let expected_json =
2764 r#"[[{"1/3":["1/2","1/2","1/2"]},"1/2",{"1/2":["1","1"]}],["1/2",{"1/2":["1","1"]}]]"#;
2765 assert_eq!(tholder.json(), expected_json);
2766
2767 assert_eq!(tholder.num(), None);
2768
2769 Ok(())
2770 }
2771
2772 #[test]
2773 fn test_tholder_nested_weighted_multi_clause_from_thold(
2774 ) -> Result<(), Box<dyn std::error::Error>> {
2775 let thold = TholderThold::Weighted(vec![
2777 vec![
2778 WeightSpec::WeightedMap(
2779 Rational32::new(1, 3),
2780 vec![
2781 Rational32::new(1, 2),
2782 Rational32::new(1, 2),
2783 Rational32::new(1, 2),
2784 ],
2785 ),
2786 WeightSpec::Simple(Rational32::new(1, 2)),
2787 WeightSpec::WeightedMap(
2788 Rational32::new(1, 2),
2789 vec![Rational32::new(1, 1), Rational32::new(1, 1)],
2790 ),
2791 ],
2792 vec![
2793 WeightSpec::Simple(Rational32::new(1, 2)),
2794 WeightSpec::WeightedMap(
2795 Rational32::new(1, 2),
2796 vec![Rational32::new(1, 1), Rational32::new(1, 1)],
2797 ),
2798 ],
2799 ]);
2800
2801 let tholder = Tholder::new(Some(thold), None, None)?;
2802
2803 assert!(tholder.weighted());
2804 assert_eq!(tholder.size(), 9);
2805 assert_eq!(
2806 tholder.limen(),
2807 b"4AAKA1s3k1s2v1s2v1s2c1s2c1s2k1v1a1s2c1s2k1v1"
2808 );
2809
2810 let expected_json =
2811 r#"[[{"1/3":["1/2","1/2","1/2"]},"1/2",{"1/2":["1","1"]}],["1/2",{"1/2":["1","1"]}]]"#;
2812 assert_eq!(tholder.json(), expected_json);
2813
2814 assert_eq!(tholder.num(), None);
2815
2816 Ok(())
2817 }
2818
2819 #[test]
2820 fn test_tholder_nested_weighted_validation_errors() -> Result<(), Box<dyn std::error::Error>> {
2821 let json_str1 = r#"[{"1/3":["1/3", "1/3", "1/4"]}, "1/3", "1/2", {"1/2": ["1", "1"]}]"#;
2823 let result1 = Tholder::new(None, None, Some(TholderSith::Json(json_str1.to_string())));
2824 assert!(result1.is_err());
2825
2826 let json_str2 = r#"[{"1/3":["1/2", "1/2", "1/2"]}, "1/3", "1/2", {"1/2": ["2/3", "1/4"]}]"#;
2828 let result2 = Tholder::new(None, None, Some(TholderSith::Json(json_str2.to_string())));
2829 assert!(result2.is_err());
2830
2831 let json_str3 = r#"[{"1/5":["1/2", "1/2", "1/2"]}, "1/4", "1/5", {"1/5": ["1", "1"]}]"#;
2833 let result3 = Tholder::new(None, None, Some(TholderSith::Json(json_str3.to_string())));
2834 assert!(result3.is_err());
2835
2836 let json_str4 = r#"[[{"1/3":["1/2", "1/2", "1/2"]}, "1/2", {"1/2": ["1", "1"]}], ["1/2", {"1/3": ["1", "1"]}]]"#;
2838 let result4 = Tholder::new(None, None, Some(TholderSith::Json(json_str4.to_string())));
2839 assert!(result4.is_err());
2840
2841 let json_str5 = r#"[[{"1/3":["1/3", "1/4", "1/3"]}, "1/2", {"1/2": ["1", "1"]}], ["1/2", {"1/2": ["1/2", "1/2"]}]]"#;
2843 let result5 = Tholder::new(None, None, Some(TholderSith::Json(json_str5.to_string())));
2844 assert!(result5.is_err());
2845
2846 Ok(())
2847 }
2848}