Skip to content

Commit 6a18cef

Browse files
committed
Document Bytecode methods and functions
1 parent 6ca1de2 commit 6a18cef

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

src/bytecode.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,13 @@ const NEW: u8 = 187;
2121
const ATHROW: u8 = 191;
2222
const CHECKCAST: u8 = 192;
2323

24+
/// A JVM bytecode instruction.
25+
///
26+
/// For more detailed information on the different types of bytecode
27+
/// instructions, see the following section of the Java Virtual Machine
28+
/// Specification.
29+
///
30+
/// https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-6.html
2431
#[derive(Debug)]
2532
#[derive(PartialEq)]
2633
pub enum Bytecode {
@@ -49,6 +56,27 @@ pub enum Bytecode {
4956
}
5057

5158
impl Bytecode {
59+
/// Converts the given slice of bytes into the bytecode instructions that
60+
/// they represent.
61+
///
62+
/// ```
63+
/// # use jvm_class_file_parser::Bytecode;
64+
/// # use jvm_class_file_parser::Bytecode::*;
65+
/// #
66+
/// let bytes = vec![
67+
/// 42,
68+
/// 183, 0, 1,
69+
/// 177,
70+
/// ];
71+
///
72+
/// let bytecodes = vec![
73+
/// (0, Aload_0),
74+
/// (1, Invokespecial(1)),
75+
/// (4, Return),
76+
/// ];
77+
///
78+
/// assert_eq!(bytecodes, Bytecode::from_bytes(&bytes));
79+
/// ```
5280
pub fn from_bytes(bytes: &[u8]) -> Vec<(usize, Bytecode)> {
5381
use Bytecode::*;
5482

@@ -222,6 +250,17 @@ impl Bytecode {
222250
bytecode
223251
}
224252

253+
/// Converts the bytecode into a String representation.
254+
///
255+
/// Takes in the index of the instruction so that it can be used to display
256+
/// bytecode instructions that contain an instruction offset.
257+
///
258+
/// ```
259+
/// # use jvm_class_file_parser::Bytecode::*;
260+
/// #
261+
/// assert_eq!("aconst_null", Aconst_null.to_string(2));
262+
/// assert_eq!("ifeq 15", Ifeq(5).to_string(10));
263+
/// ```
225264
pub fn to_string(&self, index: u16) -> String {
226265
use Bytecode::*;
227266

tests/parse_classes.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,6 @@ fn parse_class_intbox() {
6868
let get_value = &class_file.methods[1];
6969
let get_value_code = get_value.get_code(&class_file);
7070

71-
use Bytecode::*;
7271
assert_eq!(
7372
Some(Code {
7473
max_stack: 1,

0 commit comments

Comments
 (0)