Simplify invocation of snprintf (#4815)

This commit is contained in:
David Neto 2022-06-10 17:55:45 -04:00 committed by GitHub
parent fad68a7551
commit 8f7f5024f8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 6 deletions

View File

@ -15,6 +15,7 @@
#ifndef SOURCE_OPT_SCALAR_REPLACEMENT_PASS_H_ #ifndef SOURCE_OPT_SCALAR_REPLACEMENT_PASS_H_
#define SOURCE_OPT_SCALAR_REPLACEMENT_PASS_H_ #define SOURCE_OPT_SCALAR_REPLACEMENT_PASS_H_
#include <cassert>
#include <cstdio> #include <cstdio>
#include <memory> #include <memory>
#include <queue> #include <queue>
@ -37,11 +38,10 @@ class ScalarReplacementPass : public MemPass {
public: public:
ScalarReplacementPass(uint32_t limit = kDefaultLimit) ScalarReplacementPass(uint32_t limit = kDefaultLimit)
: max_num_elements_(limit) { : max_num_elements_(limit) {
name_[0] = '\0'; const auto num_to_write = snprintf(
strcat(name_, "scalar-replacement="); name_, sizeof(name_), "scalar-replacement=%u", max_num_elements_);
const size_t name_len = strlen(name_); assert(size_t(num_to_write) < sizeof(name_));
snprintf(&name_[name_len], sizeof(name_) - name_len, "%d", (void)num_to_write; // Mark as unused
max_num_elements_);
} }
const char* name() const override { return name_; } const char* name() const override { return name_; }
@ -255,7 +255,10 @@ class ScalarReplacementPass : public MemPass {
// Limit on the number of members in an object that will be replaced. // Limit on the number of members in an object that will be replaced.
// 0 means there is no limit. // 0 means there is no limit.
uint32_t max_num_elements_; uint32_t max_num_elements_;
char name_[55]; // This has to be big enough to fit "scalar-replacement=" followed by a
// uint32_t number written in decimal (so 10 digits), and then a
// terminating nul.
char name_[30];
}; };
} // namespace opt } // namespace opt

View File

@ -12,6 +12,8 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
#include "source/opt/scalar_replacement_pass.h"
#include <string> #include <string>
#include "gmock/gmock.h" #include "gmock/gmock.h"
@ -23,6 +25,18 @@ namespace spvtools {
namespace opt { namespace opt {
namespace { namespace {
using ScalarReplacementPassName = ::testing::Test;
TEST_F(ScalarReplacementPassName, Default) {
auto srp = ScalarReplacementPass();
EXPECT_STREQ(srp.name(), "scalar-replacement=100");
}
TEST_F(ScalarReplacementPassName, Large) {
auto srp = ScalarReplacementPass(0xffffffffu);
EXPECT_STREQ(srp.name(), "scalar-replacement=4294967295");
}
using ScalarReplacementTest = PassTest<::testing::Test>; using ScalarReplacementTest = PassTest<::testing::Test>;
TEST_F(ScalarReplacementTest, SimpleStruct) { TEST_F(ScalarReplacementTest, SimpleStruct) {