use alloc::{rc::Rc, string::String, vec::Vec};
use core::{
cell::RefCell,
hash::{BuildHasher, Hasher},
};
use ahash::RandomState;
use libafl_bolts::{Error, HasLen};
use serde::{Deserialize, Serialize};
use crate::inputs::Input;
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct Terminal {
pub state: usize,
pub trigger_idx: usize,
pub symbol: String,
}
impl Terminal {
#[must_use]
pub fn new(state: usize, trigger_idx: usize, symbol: String) -> Self {
Self {
state,
trigger_idx,
symbol,
}
}
}
#[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct GramatronInput {
terms: Vec<Terminal>,
}
impl Input for GramatronInput {
#[must_use]
fn generate_name(&self, _idx: usize) -> String {
let mut hasher = RandomState::with_seeds(0, 0, 0, 0).build_hasher();
for term in &self.terms {
hasher.write(term.symbol.as_bytes());
}
format!("{:016x}", hasher.finish())
}
}
impl From<GramatronInput> for Rc<RefCell<GramatronInput>> {
fn from(input: GramatronInput) -> Self {
Rc::new(RefCell::new(input))
}
}
impl HasLen for GramatronInput {
#[inline]
fn len(&self) -> usize {
self.terms.len()
}
}
impl GramatronInput {
#[must_use]
pub fn new(terms: Vec<Terminal>) -> Self {
Self { terms }
}
#[must_use]
pub fn terminals(&self) -> &[Terminal] {
&self.terms
}
#[must_use]
pub fn terminals_mut(&mut self) -> &mut Vec<Terminal> {
&mut self.terms
}
pub fn unparse(&self, bytes: &mut Vec<u8>) {
bytes.clear();
for term in &self.terms {
bytes.extend_from_slice(term.symbol.as_bytes());
}
}
pub fn crop(&self, from: usize, to: usize) -> Result<Self, Error> {
if from < to && to <= self.terms.len() {
let mut terms = vec![];
terms.clone_from_slice(&self.terms[from..to]);
Ok(Self { terms })
} else {
Err(Error::illegal_argument("Invalid from or to argument"))
}
}
}