From ff63e410cec670ec7f5f2b1205dab34c6f1f305e Mon Sep 17 00:00:00 2001 From: neeldug <5161147+neeldug@users.noreply.github.com> Date: Thu, 10 Aug 2023 22:54:19 +0100 Subject: [PATCH] feat(Header): `Header::num_vars` implementation --- src/lib.rs | 25 +++++++++++++++++++++++++ src/scope.rs | 11 +++++++++++ 2 files changed, 36 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 5990e5b..67cad49 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -318,4 +318,29 @@ impl Header { _ => None, }) } + + /// Find the variable object at a specified path. + /// + /// ## Example + /// + /// ```rust + /// let mut parser = vcd::Parser::new(&b" + /// $scope module a $end + /// $var integer 32 y counter_b $end + /// $scope module b $end + /// $var integer 16 n0 counter $end + /// $upscope $end + /// $upscope $end + /// $enddefinitions $end + /// "[..]); + /// let header = parser.parse_header().unwrap(); + /// let var_count = header.num_vars(); + /// assert_eq!(var_count, 2); + /// ``` + pub fn num_vars(&self) -> usize { + self.items + .iter() + .filter(|item| matches!(item, ScopeItem::Var(_) | ScopeItem::Scope(_))) + .fold(0, |acc, scope_item| acc + scope_item.num_vars()) + } } diff --git a/src/scope.rs b/src/scope.rs index a7c641f..6c483ce 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -292,3 +292,14 @@ pub enum ScopeItem { /// `$comment` - Comment Comment(String), } + +impl ScopeItem { + /// Returns the number of variables in this scope item. + pub fn num_vars(&self) -> usize { + match self { + ScopeItem::Scope(s) => s.items.iter().map(ScopeItem::num_vars).sum(), + ScopeItem::Var(_) => 1, + ScopeItem::Comment(_) => 0, + } + } +}