Skip to content

Commit

Permalink
feat(Header): Header::num_vars implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
neeldug committed Aug 10, 2023
1 parent 5e7cdef commit ff63e41
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}
11 changes: 11 additions & 0 deletions src/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}
}

0 comments on commit ff63e41

Please sign in to comment.