From 5ca796a668934b8add531f3f5cc209315577f2db Mon Sep 17 00:00:00 2001 From: Rosen Penev Date: Wed, 12 Jul 2023 17:52:48 -0700 Subject: [PATCH 1/2] optimize other toAscii function with early exit GCC is able to see that the branch is useless as it can be done at compile time. Produces shorter assembly with both -O2 and -O3. Assign the pointer to the std::string directly and use proper iterators with std::transform. Also produces shorter assembly. Signed-off-by: Rosen Penev (cherry picked from commit 22a4b7175294b500eb112efcd0ea5b2a844ac29d) --- src/bmffimage.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/bmffimage.cpp b/src/bmffimage.cpp index ee42d9350a..d59bb59436 100644 --- a/src/bmffimage.cpp +++ b/src/bmffimage.cpp @@ -85,16 +85,16 @@ BmffImage::BmffImage(BasicIo::UniquePtr io, bool /* create */, size_t max_box_de std::string BmffImage::toAscii(uint32_t n) { const auto p = reinterpret_cast(&n); - std::string result(4, '.'); - std::transform(p, p + 4, result.begin(), [](char c) { + std::string result(p, p + 4); + if (!isBigEndianPlatform()) + std::reverse(result.begin(), result.end()); + std::transform(result.begin(), result.end(), result.begin(), [](char c) { if (32 <= c && c < 127) return c; // only allow 7-bit printable ascii if (c == 0) return '_'; // show 0 as _ return '.'; // others . }); - if (!isBigEndianPlatform()) - std::reverse(result.begin(), result.end()); return result; } From 4d436e3ce9b4406c50236a2f820155dd9fccdb51 Mon Sep 17 00:00:00 2001 From: Rosen Penev Date: Fri, 14 Jul 2023 14:56:17 -0700 Subject: [PATCH 2/2] fix toAscii function c == 0 was a dead branch because of the way printable ascii was calculated. Move it up instead. While at it, replace std::transform with std::replace. Easier to read. Signed-off-by: Rosen Penev (cherry picked from commit e1b3dfa2788bad83ce941aafcff286d3b2e4b55e) --- src/bmffimage.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/bmffimage.cpp b/src/bmffimage.cpp index d59bb59436..5e59336f7c 100644 --- a/src/bmffimage.cpp +++ b/src/bmffimage.cpp @@ -88,13 +88,11 @@ std::string BmffImage::toAscii(uint32_t n) { std::string result(p, p + 4); if (!isBigEndianPlatform()) std::reverse(result.begin(), result.end()); - std::transform(result.begin(), result.end(), result.begin(), [](char c) { - if (32 <= c && c < 127) - return c; // only allow 7-bit printable ascii - if (c == 0) - return '_'; // show 0 as _ - return '.'; // others . - }); + // show 0 as _ + std::replace(result.begin(), result.end(), '\0', '_'); + // show non 7-bit printable ascii as . + std::replace_if( + result.begin(), result.end(), [](char c) { return c < 32 || c > 126; }, '.'); return result; }