Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created October 20, 2020 10:06
Show Gist options
  • Save rust-play/c92c52a577d9d3c974a1b24d28750348 to your computer and use it in GitHub Desktop.
Save rust-play/c92c52a577d9d3c974a1b24d28750348 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
fn main() -> anyhow::Result<()> {
println!("{}", get_name(include_bytes!("../Class.class"))?);
Ok(())
}
fn get_name(cf: &'static [u8]) -> anyhow::Result<String> {
use anyhow::Context;
use classfile_parser::constant_info::ConstantInfo::{NameAndType, Utf8};
use classfile_parser::constant_info::NameAndTypeConstant;
let (_, cf) = classfile_parser::class_parser(cf).context("Parse classfile")?;
let ci = cf
.const_pool
.get(cf.this_class as usize)
.context(format!("this_class index {} out of bounds", cf.this_class))?;
let name_index = if let NameAndType(NameAndTypeConstant { name_index, .. }) = ci {
*name_index
} else {
anyhow::bail!(
"Expected a NameAndTypeConstant for this_class, found {:?}",
ci
);
};
let ci = cf.const_pool.get(name_index as usize).context(format!(
"name_index for this_class {} out of bounds",
name_index
))?;
let s = if let Utf8(s) = ci {
&s.utf8_string
} else {
anyhow::bail!(
"Expected a Utf8 constant for this_class' name, found {:?}",
ci
);
};
anyhow::ensure!(
s.starts_with("L") && s.ends_with(";"),
"Expected class name to be of the form \"Lclass/Path.class;\", found \"{}\"",
s
);
Ok(s[1..s.len() - 1].to_owned())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment