mercredi 29 avril 2020

How to print an array that some values must be printed with a specific behaviour?

I'm trying to make a JVM. First, I have a vector with opcodes and the strings that represent them. It's initialised like this:

Opcodes::Opcodes():
opcodes(0xff + 1, "Not implemented")
{
    opcodes[0x2A] = "aload_0";
    opcodes[0x2B] = "aload_1";
    opcodes[0x2C] = "aload_2";
    opcodes[0x2D] = "aload_3";
    opcodes[0xB7] = "invokespecial";
}

Given an opcode, I want to print it, this is the code till now:

std::string Opcodes::getString(u1 opcode)
{
    try
    {
        return Opcodes::getInstance().opcodes.at(opcode);
    }
    catch (const std::out_of_range &e)
    {
        return "Opcode too large";
    }
}

void Opcodes::printCode(std::ostream& out, u1 code[], u4 codeLength)
{
    for (u4 i = 0; i < codeLength; i++)
    {
        out << Opcodes::getString(code[i]) << std::endl;
    }
}

There will be a lot more of opcodes. For a lot of opcodes I just have to get the opcode and print it. But for the others I have to take a different approach, for example, in the method printCode() if I read the invokespecial opcode I have to print the two next opcodes in the code array (code[]) in another way than just take it from the opcodes vector, or just ignore them (don't print).

How can I do it in a good way? Which could be a good approach for that?

I could just use if or switch but it'll be really a lot of if's, I don't think that's good, sounds messy. I thought of using lambda someway. I've heard about a pattern called command, maybe it could be helpful. What do you think?

Aucun commentaire:

Enregistrer un commentaire