Add opt::Operand::AsCString and AsString (#3240)
It only works when the operand is a literal string.
diff --git a/source/opt/instruction.h b/source/opt/instruction.h
index 322e0aa..63dfa87 100644
--- a/source/opt/instruction.h
+++ b/source/opt/instruction.h
@@ -80,6 +80,15 @@
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;
}
diff --git a/test/opt/instruction_test.cpp b/test/opt/instruction_test.cpp
index a697201..d219f3e 100644
--- a/test/opt/instruction_test.cpp
+++ b/test/opt/instruction_test.cpp
@@ -14,6 +14,7 @@
#include <memory>
#include <string>
+#include <utility>
#include <vector>
#include "gmock/gmock.h"
@@ -60,6 +61,18 @@
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};