textfsm-core 0.3.1

Core parsing library for TextFSM template-based state machine
Documentation
//! Template parsing and representation.
//!
//! A Template is an immutable, compiled representation of a TextFSM template file.
//! It can be shared across threads and reused to create multiple Parser instances.

mod parse;
mod value;
mod rule;

pub use value::ValueDef;
pub use rule::{Rule, State};

use std::collections::HashMap;
use std::io::BufRead;

use crate::error::TemplateError;
use crate::parser::Parser;

/// Compiled template - immutable, can be shared across threads.
#[derive(Debug, Clone)]
pub struct Template {
    /// Value definitions in order.
    values: Vec<ValueDef>,

    /// Map of value name to index for fast lookup.
    #[allow(dead_code)]
    value_index: HashMap<String, usize>,

    /// Map of value name to template pattern for rule substitution.
    #[allow(dead_code)]
    value_templates: HashMap<String, String>,

    /// States by name.
    states: HashMap<String, State>,

    /// State names in definition order.
    state_order: Vec<String>,
}

impl Template {
    /// Parse a template from a reader.
    pub fn parse<R: BufRead>(reader: R) -> Result<Self, TemplateError> {
        parse::parse_template(reader)
    }

    /// Parse a template from a string.
    pub fn parse_str(s: &str) -> Result<Self, TemplateError> {
        Self::parse(s.as_bytes())
    }

    /// Create a new parser instance for this template.
    pub fn parser(&self) -> Parser<'_> {
        Parser::new(self)
    }

    /// Get the value definitions.
    pub fn values(&self) -> &[ValueDef] {
        &self.values
    }

    /// Get the header (value names in order).
    pub fn header(&self) -> Vec<&str> {
        self.values.iter().map(|v| v.name.as_str()).collect()
    }

    /// Get a state by name.
    pub fn get_state(&self, name: &str) -> Option<&State> {
        self.states.get(name)
    }

    /// Get state names in definition order.
    pub fn state_order(&self) -> &[String] {
        &self.state_order
    }

    /// Get the value template patterns (for internal use).
    #[allow(dead_code)]
    pub(crate) fn value_templates(&self) -> &HashMap<String, String> {
        &self.value_templates
    }

    /// Get value index by name.
    #[allow(dead_code)]
    pub(crate) fn value_index(&self, name: &str) -> Option<usize> {
        self.value_index.get(name).copied()
    }
}