Add opt::Operand::AsCString and AsString (#3240)

It only works when the operand is a literal string.
This commit is contained in:
David Neto 2020-03-19 09:44:28 -07:00 committed by GitHub
parent da52d0875c
commit 60104cd974
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 0 deletions

View File

@ -80,6 +80,15 @@ struct Operand {
spv_operand_type_t type; // Type of this logical operand.
OperandData words; // Binary segments of this logical operand.
// Returns a string operand as a C-style string.
const char* AsCString() const {
assert(type == SPV_OPERAND_TYPE_LITERAL_STRING);
return reinterpret_cast<const char*>(words.data());
}
// Returns a string operand as a std::string.
std::string AsString() const { return AsCString(); }
friend bool operator==(const Operand& o1, const Operand& o2) {
return o1.type == o2.type && o1.words == o2.words;
}

View File

@ -14,6 +14,7 @@
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
@ -60,6 +61,18 @@ TEST(InstructionTest, CreateWithOpcodeAndNoOperands) {
EXPECT_EQ(inst.end(), inst.begin());
}
TEST(InstructionTest, OperandAsCString) {
Operand::OperandData abcde{0x64636261, 0x65};
Operand operand(SPV_OPERAND_TYPE_LITERAL_STRING, std::move(abcde));
EXPECT_STREQ("abcde", operand.AsCString());
}
TEST(InstructionTest, OperandAsString) {
Operand::OperandData abcde{0x64636261, 0x65};
Operand operand(SPV_OPERAND_TYPE_LITERAL_STRING, std::move(abcde));
EXPECT_EQ("abcde", operand.AsString());
}
// The words for an OpTypeInt for 32-bit signed integer resulting in Id 44.
uint32_t kSampleInstructionWords[] = {(4 << 16) | uint32_t(SpvOpTypeInt), 44,
32, 1};