dbc_rs/nodes/serialize.rs
1use super::Nodes;
2use crate::BU_;
3use std::fmt::{Display, Formatter, Result};
4
5impl Display for Nodes {
6 fn fmt(&self, f: &mut Formatter<'_>) -> Result {
7 if self.nodes.is_empty() {
8 return Ok(());
9 }
10 for (i, node) in self.iter().enumerate() {
11 if i > 0 {
12 write!(f, " ")?;
13 }
14 write!(f, "{}", node)?;
15 }
16 Ok(())
17 }
18}
19
20impl Nodes {
21 /// Converts the nodes to their DBC file representation.
22 ///
23 /// Returns a string in the format: `BU_: Node1 Node2 Node3 ...`
24 ///
25 /// # Examples
26 ///
27 /// ```rust,no_run
28 /// use dbc_rs::Dbc;
29 ///
30 /// let dbc = Dbc::parse(r#"VERSION "1.0"
31 ///
32 /// BU_: ECM TCM BCM
33 /// "#)?;
34 ///
35 /// let dbc_string = dbc.nodes().to_dbc_string();
36 /// assert_eq!(dbc_string, "BU_: ECM TCM BCM");
37 /// # Ok::<(), dbc_rs::Error>(())
38 /// ```
39 ///
40 /// # Empty Nodes
41 ///
42 /// Empty node lists are represented as `BU_:`:
43 ///
44 /// ```rust,no_run
45 /// use dbc_rs::Dbc;
46 ///
47 /// let dbc = Dbc::parse(r#"VERSION "1.0"
48 ///
49 /// BU_:
50 /// "#)?;
51 ///
52 /// assert_eq!(dbc.nodes().to_dbc_string(), "BU_:");
53 /// # Ok::<(), dbc_rs::Error>(())
54 /// ```
55 ///
56 /// # Feature Requirements
57 ///
58 /// This method requires the `std` feature to be enabled.
59 #[must_use = "return value should be used"]
60 pub fn to_dbc_string(&self) -> std::string::String {
61 let mut result = format!("{}:", BU_);
62 let nodes_str = format!("{}", self);
63 if !nodes_str.is_empty() {
64 result.push(' ');
65 result.push_str(&nodes_str);
66 }
67 result
68 }
69}