use crate::byte_reader::ByteReader;
use crate::error::Result;
use crate::method_access_flags::MethodAccessFlags;
use byteorder::{BigEndian, WriteBytesExt};
use std::fmt;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MethodParameter {
pub name_index: u16,
pub access_flags: MethodAccessFlags,
}
impl MethodParameter {
pub fn from_bytes(bytes: &mut ByteReader<'_>) -> Result<MethodParameter> {
let name_index = bytes.read_u16()?;
let access_flags = MethodAccessFlags::from_bytes(bytes)?;
let bootstrap_method = MethodParameter {
name_index,
access_flags,
};
Ok(bootstrap_method)
}
pub fn to_bytes(&self, bytes: &mut Vec<u8>) -> Result<()> {
bytes.write_u16::<BigEndian>(self.name_index)?;
self.access_flags.to_bytes(bytes)
}
}
impl fmt::Display for MethodParameter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"name_index: #{}, access_flags: {}",
self.name_index, self.access_flags
)
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_to_string() {
let method_parameter = MethodParameter {
name_index: 3,
access_flags: MethodAccessFlags::PUBLIC,
};
assert_eq!(
"name_index: #3, access_flags: (0x0001) ACC_PUBLIC",
method_parameter.to_string()
);
}
#[test]
fn test_serialization() -> Result<()> {
let method_parameter = MethodParameter {
name_index: 3,
access_flags: MethodAccessFlags::PUBLIC,
};
let expected_value = [0, 3, 0, 1];
let mut bytes = Vec::new();
method_parameter.clone().to_bytes(&mut bytes)?;
assert_eq!(expected_value, &bytes[..]);
let mut bytes = ByteReader::new(&expected_value);
assert_eq!(method_parameter, MethodParameter::from_bytes(&mut bytes)?);
Ok(())
}
}