1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use ahash::AHasher;
use core::hash::Hasher;
use alloc::{rc::Rc, string::String, vec::Vec};
use core::{cell::RefCell, convert::From};
use serde::{Deserialize, Serialize};
use crate::{bolts::HasLen, inputs::Input, Error};
#[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 = AHasher::new_with_keys(0, 0);
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"))
}
}
}