Skip to main content

textfsm_core/template/
mod.rs

1//! Template parsing and representation.
2//!
3//! A Template is an immutable, compiled representation of a TextFSM template file.
4//! It can be shared across threads and reused to create multiple Parser instances.
5
6mod parse;
7mod value;
8mod rule;
9
10pub use value::ValueDef;
11pub use rule::{Rule, State};
12
13use std::collections::HashMap;
14use std::io::BufRead;
15
16use crate::error::TemplateError;
17use crate::parser::Parser;
18
19/// Compiled template - immutable, can be shared across threads.
20#[derive(Debug, Clone)]
21pub struct Template {
22    /// Value definitions in order.
23    values: Vec<ValueDef>,
24
25    /// Map of value name to index for fast lookup.
26    #[allow(dead_code)]
27    value_index: HashMap<String, usize>,
28
29    /// Map of value name to template pattern for rule substitution.
30    #[allow(dead_code)]
31    value_templates: HashMap<String, String>,
32
33    /// States by name.
34    states: HashMap<String, State>,
35
36    /// State names in definition order.
37    state_order: Vec<String>,
38}
39
40impl Template {
41    /// Parse a template from a reader.
42    pub fn parse<R: BufRead>(reader: R) -> Result<Self, TemplateError> {
43        parse::parse_template(reader)
44    }
45
46    /// Parse a template from a string.
47    pub fn parse_str(s: &str) -> Result<Self, TemplateError> {
48        Self::parse(s.as_bytes())
49    }
50
51    /// Create a new parser instance for this template.
52    pub fn parser(&self) -> Parser<'_> {
53        Parser::new(self)
54    }
55
56    /// Get the value definitions.
57    pub fn values(&self) -> &[ValueDef] {
58        &self.values
59    }
60
61    /// Get the header (value names in order).
62    pub fn header(&self) -> Vec<&str> {
63        self.values.iter().map(|v| v.name.as_str()).collect()
64    }
65
66    /// Get a state by name.
67    pub fn get_state(&self, name: &str) -> Option<&State> {
68        self.states.get(name)
69    }
70
71    /// Get state names in definition order.
72    pub fn state_order(&self) -> &[String] {
73        &self.state_order
74    }
75
76    /// Get the value template patterns (for internal use).
77    #[allow(dead_code)]
78    pub(crate) fn value_templates(&self) -> &HashMap<String, String> {
79        &self.value_templates
80    }
81
82    /// Get value index by name.
83    #[allow(dead_code)]
84    pub(crate) fn value_index(&self, name: &str) -> Option<usize> {
85        self.value_index.get(name).copied()
86    }
87}