From 60104cd97446877dad8ed1010a635218937a2f18 Mon Sep 17 00:00:00 2001 From: David Neto Date: Thu, 19 Mar 2020 09:44:28 -0700 Subject: [PATCH] Add opt::Operand::AsCString and AsString (#3240) It only works when the operand is a literal string. --- source/opt/instruction.h | 9 +++++++++ test/opt/instruction_test.cpp | 13 +++++++++++++ 2 files changed, 22 insertions(+) diff --git a/source/opt/instruction.h b/source/opt/instruction.h index 322e0aac..63dfa877 100644 --- a/source/opt/instruction.h +++ b/source/opt/instruction.h @@ -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(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 a6972011..d219f3e6 100644 --- a/test/opt/instruction_test.cpp +++ b/test/opt/instruction_test.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #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};