Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 57 additions & 1 deletion src/descriptors.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use std::borrow::Cow;
use std::{
borrow::Cow,
fmt::{self, Write},
};

use crate::ParseError;

Expand Down Expand Up @@ -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<Cow<'a, str>> = 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.
Expand Down Expand Up @@ -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,
Expand All @@ -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>(
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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
Expand Down