diff --git a/src/descriptors.rs b/src/descriptors.rs index c49547e..512e933 100644 --- a/src/descriptors.rs +++ b/src/descriptors.rs @@ -1,4 +1,7 @@ -use std::borrow::Cow; +use std::{ + borrow::Cow, + fmt::{self, Write}, +}; use crate::ParseError; @@ -49,6 +52,12 @@ impl ClassName<'_> { .fold(0, |sum, segment| sum + segment.name.len() + 1) } } +impl<'a> fmt::Display for ClassName<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + let segments: Vec> = self.segments.iter().map(|s| s.name.clone()).collect(); + write!(f, "{};", segments.join("/")) + } +} // Returns the classname descriptor at the start of the given data, and ignores anything following. // Returns an error if there was no such classname. @@ -96,6 +105,22 @@ impl FieldType<'_> { } } +impl fmt::Display for FieldType<'_> { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match self { + Self::Byte => write!(f, "B"), + Self::Char => write!(f, "C"), + Self::Double => write!(f, "D"), + Self::Float => write!(f, "F"), + Self::Integer => write!(f, "I"), + Self::Long => write!(f, "J"), + Self::Short => write!(f, "S"), + Self::Boolean => write!(f, "Z"), + Self::Object(obj) => write!(f, "L{};", obj), + } + } +} + #[derive(Clone, Debug, Hash, PartialEq, Eq)] pub struct FieldDescriptor<'a> { pub dimensions: u8, @@ -108,6 +133,17 @@ impl FieldDescriptor<'_> { } } +impl fmt::Display for FieldDescriptor<'_> { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + write!( + f, + "{}{}", + "[".repeat(self.dimensions as usize), + self.field_type + ) + } +} + // Parse the field descriptor at the start of the given data, and ignores anything // following. Returns an error if the data don't start with a field descriptor. pub(crate) fn parse_field_descriptor<'a>( @@ -148,6 +184,14 @@ pub enum ReturnDescriptor<'a> { Return(FieldDescriptor<'a>), Void, } +impl fmt::Display for ReturnDescriptor<'_> { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + match self { + Self::Void => f.write_char('V'), + Self::Return(field) => write!(f, "{}", field), + } + } +} impl ReturnDescriptor<'_> { fn byte_len(&self) -> usize { @@ -177,6 +221,18 @@ pub struct MethodDescriptor<'a> { pub return_type: ReturnDescriptor<'a>, } +impl fmt::Display for MethodDescriptor<'_> { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + f.write_char('(')?; + + for param in &self.parameters { + write!(f, "{}", param)?; + } + + write!(f, "){}", self.return_type) + } +} + impl MethodDescriptor<'_> { fn byte_len(&self) -> usize { 1 + self