use std::fmt::{self, Display, Write};
use crate::{Doc, Formatter, Type};
#[derive(Debug, Clone)]
pub struct Field {
name: String,
ty: Type,
width: Option<u8>,
doc: Option<Doc>,
}
impl Field {
pub fn new(name: &str, ty: Type) -> Self {
Field::with_string(String::from(name), ty)
}
pub fn with_string(name: String, ty: Type) -> Self {
Field {
name,
ty,
width: None,
doc: None,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub fn to_type(&self) -> Type {
self.ty.clone()
}
pub fn as_type(&self) -> &Type {
&self.ty
}
pub fn push_doc_str(&mut self, doc: &str) -> &mut Self {
if let Some(d) = &mut self.doc {
d.add_text(doc);
} else {
self.doc = Some(Doc::with_str(doc));
}
self
}
pub fn set_doc(&mut self, doc: Doc) -> &mut Self {
self.doc = Some(doc);
self
}
pub fn set_bitfield_width(&mut self, width: u8) -> &mut Self {
if self.ty.is_integer() {
self.width = Some(width);
}
self
}
pub fn is_bitfield(&self) -> bool {
self.width.is_some()
}
pub fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
if let Some(ref docs) = self.doc {
docs.fmt(fmt)?;
}
self.ty.fmt(fmt)?;
write!(fmt, " {}", self.name)?;
if let Some(w) = self.width {
write!(fmt, " : {w}")?;
}
if self.ty.is_array() {
write!(fmt, "[{}]", self.ty.get_array_size())?;
}
writeln!(fmt, ";")
}
}
impl Display for Field {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut ret = String::new();
self.fmt(&mut Formatter::new(&mut ret)).unwrap();
write!(f, "{ret}")
}
}