openapi_nexus_go/ast/ty/
go_struct.rs1use pretty::RcDoc;
4use serde::{Deserialize, Serialize};
5
6use crate::ast::common::{GoDocComment, GoField};
7use openapi_nexus_core::traits::ToRcDoc;
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct GoStruct {
12 pub name: String,
13 pub fields: Vec<GoField>,
14 pub doc: Option<GoDocComment>,
15}
16
17impl GoStruct {
18 pub fn new(name: String) -> Self {
19 Self {
20 name,
21 fields: Vec::new(),
22 doc: None,
23 }
24 }
25
26 pub fn with_field(mut self, field: GoField) -> Self {
27 self.fields.push(field);
28 self
29 }
30
31 pub fn with_fields(mut self, fields: Vec<GoField>) -> Self {
32 self.fields = fields;
33 self
34 }
35
36 pub fn with_doc(mut self, doc: GoDocComment) -> Self {
37 self.doc = Some(doc);
38 self
39 }
40}
41
42impl ToRcDoc for GoStruct {
43 fn to_rcdoc(&self) -> RcDoc<'static, ()> {
44 let mut doc = RcDoc::nil();
45
46 if let Some(comment) = &self.doc {
47 doc = doc.append(comment.to_rcdoc()).append(RcDoc::hardline());
48 }
49
50 doc = doc
51 .append(RcDoc::text("type"))
52 .append(RcDoc::space())
53 .append(RcDoc::text(self.name.clone()))
54 .append(RcDoc::space())
55 .append(RcDoc::text("struct"))
56 .append(RcDoc::space())
57 .append(RcDoc::text("{"));
58
59 if !self.fields.is_empty() {
60 doc = doc.append(RcDoc::hardline());
61 for field in &self.fields {
62 if let Some(comment) = &field.doc {
63 doc = doc
64 .append(RcDoc::text("\t"))
65 .append(comment.to_rcdoc())
66 .append(RcDoc::hardline());
67 }
68 doc = doc
69 .append(RcDoc::text("\t"))
70 .append(field.to_rcdoc())
71 .append(RcDoc::hardline());
72 }
73 }
74
75 doc.append(RcDoc::text("}"))
76 }
77}