pub const FALSE: AigerLiteral = AigerLiteral::new(0);
pub const TRUE: AigerLiteral = FALSE.negated();
#[repr(transparent)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AigerLiteral(usize);
impl std::fmt::Display for AigerLiteral {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl AigerLiteral {
pub const fn new(index: usize) -> Self {
Self(index << 1)
}
pub const fn is_const(&self) -> bool {
self.0 >> 1 == 0
}
pub const fn negated(self) -> Self {
Self(self.0 ^ 0b1)
}
pub const fn index(&self) -> usize {
self.0 >> 1
}
pub const fn is_negated(&self) -> bool {
(self.0 & 0b1) == 0b1
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct AigerGate {
lhs: AigerLiteral,
rhs: (AigerLiteral, AigerLiteral),
}
impl AigerGate {
pub fn new(lhs: AigerLiteral, rhs: (AigerLiteral, AigerLiteral)) -> Self {
if rhs.0 > rhs.1 {
Self { lhs, rhs }
} else {
Self {
lhs,
rhs: (rhs.1, rhs.0),
}
}
}
pub fn gate_literal(&self) -> AigerLiteral {
self.lhs
}
pub fn input_lhs(&self) -> AigerLiteral {
self.rhs.0
}
pub fn input_rhs(&self) -> AigerLiteral {
self.rhs.1
}
pub fn serialize_binary(&self) -> Vec<u8> {
let deltas = (self.lhs.0 - self.rhs.0.0, self.rhs.0.0 - self.rhs.1.0);
let mut encodings = ([0u8; Self::max_leb_size()], [0u8; Self::max_leb_size()]);
let lens = (
Self::leb128_encode(deltas.0, &mut encodings.0),
Self::leb128_encode(deltas.1, &mut encodings.1),
);
encodings
.0
.into_iter()
.take(lens.0)
.chain(encodings.1.into_iter().take(lens.1))
.collect()
}
fn leb128_encode(mut value: usize, output: &mut [u8; Self::max_leb_size()]) -> usize {
const MAX_WORD_VALUE: usize = 0x7F;
let mut i = 0;
loop {
if value <= MAX_WORD_VALUE {
unsafe {
*output.get_unchecked_mut(i) = value as u8;
}
break;
} else {
unsafe {
*output.get_unchecked_mut(i) = (value & 0x7F) as u8 | 0x80;
}
value >>= 7;
i += 1;
}
}
i + 1
}
const fn max_leb_size() -> usize {
let num_bits = 8 * std::mem::size_of::<usize>();
num_bits.div_ceil(7)
}
}