use std::convert::TryInto;
use super::cand::Cand;
use super::cor::Cor;
use super::SigmaBoolean;
use super::SigmaConjecture;
use super::SigmaConjectureItems;
use crate::has_opcode::HasStaticOpCode;
use crate::serialization::op_code::OpCode;
use crate::serialization::sigma_byte_reader::SigmaByteRead;
use crate::serialization::sigma_byte_writer::SigmaByteWrite;
use crate::serialization::SigmaSerializeResult;
use crate::serialization::{SigmaParsingError, SigmaSerializable};
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct Cthreshold {
pub k: u8,
pub children: SigmaConjectureItems<SigmaBoolean>,
}
impl Cthreshold {
pub fn reduce(k: u8, children: SigmaConjectureItems<SigmaBoolean>) -> SigmaBoolean {
if k == 0 {
return true.into();
}
if k as usize > children.len() {
return false.into();
}
let mut curr_k = k;
let mut children_left = children.len();
let mut res: Vec<SigmaBoolean> = Vec::new();
for (i, ch) in children.iter().enumerate() {
if curr_k == 1 {
res.append(&mut children.as_vec()[i..children.len()].to_vec());
#[allow(clippy::unwrap_used)]
return Cor::normalized(res.try_into().unwrap());
}
if curr_k as usize == children_left {
res.append(&mut children.as_vec()[i..children.len()].to_vec());
#[allow(clippy::unwrap_used)]
return Cand::normalized(res.try_into().unwrap());
}
match ch {
&SigmaBoolean::TrivialProp(true) => {
children_left -= 1;
curr_k -= 1;
}
&SigmaBoolean::TrivialProp(false) => {
children_left -= 1;
}
sigma => {
res.push(sigma.clone());
}
}
}
#[allow(clippy::unwrap_used)]
let sigmas: SigmaConjectureItems<SigmaBoolean> = res.try_into().unwrap();
match curr_k as usize {
1 => Cor::normalized(sigmas),
ch if ch == children_left => Cand::normalized(sigmas),
_ => SigmaBoolean::SigmaConjecture(SigmaConjecture::Cthreshold(Cthreshold {
k: curr_k,
children: sigmas,
})),
}
}
}
impl std::fmt::Display for Cthreshold {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("atLeast(")?;
f.write_str(self.k.to_string().as_str())?;
f.write_str(", (")?;
for (i, item) in self.children.iter().enumerate() {
if i > 0 {
f.write_str(", ")?;
}
item.fmt(f)?;
}
f.write_str(")")
}
}
impl HasStaticOpCode for Cthreshold {
const OP_CODE: OpCode = OpCode::ATLEAST;
}
impl SigmaSerializable for Cthreshold {
fn sigma_serialize<W: SigmaByteWrite>(&self, w: &mut W) -> SigmaSerializeResult {
w.put_u16(self.k as u16)?;
w.put_u16(self.children.len() as u16)?;
self.children.iter().try_for_each(|i| i.sigma_serialize(w))
}
fn sigma_parse<R: SigmaByteRead>(r: &mut R) -> Result<Self, SigmaParsingError> {
let k = r.get_u16()? as u8; let items_count = r.get_u16()?;
let mut items = Vec::with_capacity(items_count as usize);
for _ in 0..items_count {
items.push(SigmaBoolean::sigma_parse(r)?);
}
Ok(Cthreshold {
k,
children: items.try_into()?,
})
}
}