zlink_core/idl/
custom_object.rs1use core::fmt;
4
5use alloc::vec::Vec;
6
7use super::{Field, List};
8
9#[derive(Debug, Clone, Eq)]
11pub struct CustomObject<'a> {
12 name: &'a str,
14 fields: List<'a, Field<'a>>,
16 comments: List<'a, super::Comment<'a>>,
18}
19
20impl<'a> CustomObject<'a> {
21 pub const fn new(
23 name: &'a str,
24 fields: &'a [&'a Field<'a>],
25 comments: &'a [&'a super::Comment<'a>],
26 ) -> Self {
27 Self {
28 name,
29 fields: List::Borrowed(fields),
30 comments: List::Borrowed(comments),
31 }
32 }
33
34 pub fn new_owned(
36 name: &'a str,
37 fields: Vec<Field<'a>>,
38 comments: Vec<super::Comment<'a>>,
39 ) -> Self {
40 Self {
41 name,
42 fields: List::from(fields),
43 comments: List::from(comments),
44 }
45 }
46
47 pub fn name(&self) -> &'a str {
49 self.name
50 }
51
52 pub fn fields(&self) -> impl Iterator<Item = &Field<'a>> {
54 self.fields.iter()
55 }
56
57 pub fn comments(&self) -> impl Iterator<Item = &super::Comment<'a>> {
59 self.comments.iter()
60 }
61}
62
63impl<'a> fmt::Display for CustomObject<'a> {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 for comment in self.comments.iter() {
67 writeln!(f, "{comment}")?;
68 }
69 write!(f, "type {} (", self.name)?;
70 let mut first = true;
71 for field in self.fields.iter() {
72 if !first {
73 write!(f, ", ")?;
74 }
75 first = false;
76 write!(f, "{field}")?;
77 }
78 write!(f, ")")
79 }
80}
81
82impl<'a> PartialEq for CustomObject<'a> {
83 fn eq(&self, other: &Self) -> bool {
84 self.name == other.name && self.fields == other.fields
85 }
86}
87
88#[cfg(test)]
89mod tests {
90 use super::*;
91 use crate::idl::{Comment, Field, Type};
92 use core::fmt::Write;
93
94 #[test]
95 fn display_with_comments() {
96 let comment1 = Comment::new("User data structure");
97 let comment2 = Comment::new("Contains basic user information");
98 let comments = [&comment1, &comment2];
99
100 let name_field = Field::new("name", &Type::String, &[]);
101 let age_field = Field::new("age", &Type::Int, &[]);
102 let fields = [&name_field, &age_field];
103
104 let custom_object = CustomObject::new("User", &fields, &comments);
105 let mut displayed = String::new();
106 write!(&mut displayed, "{}", custom_object).unwrap();
107 assert_eq!(
108 displayed,
109 "# User data structure\n# Contains basic user information\ntype User (name: string, age: int)"
110 );
111 }
112}