perf: Avoid creating strings for file extension checks (#1303)
## Summary **What is the goal of this PR?** This change avoids the pattern of creating a `std::string` using `.substr` in order to compare against a file extension literal. ```c++ std::string path; if (path.length() >= 4 && path.substr(path.length() - 4) == ".ext") ``` The `checkFileExtension` utility has moved from StringUtils to FsHelpers, to be available to code in lib/. The signature now accepts a `std::string_view` instead of `std::string`, which makes the single implementation reusable for Arduino `String`. Added utility functions for commonly repeated extensions. These changes **save about 2 KB of flash (5,999,427 to 5,997,343)**. --- ### AI Usage While CrossPoint doesn't have restrictions on AI tools in contributing, please be transparent about their usage as it helps set the right context for reviewers. Did you use AI tools to help write this code? _**NO**_
This commit is contained in:
@@ -2,8 +2,6 @@
|
||||
|
||||
#include <Utf8.h>
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace StringUtils {
|
||||
|
||||
std::string sanitizeFilename(const std::string& name, size_t maxBytes) {
|
||||
@@ -45,30 +43,4 @@ std::string sanitizeFilename(const std::string& name, size_t maxBytes) {
|
||||
return result.empty() ? "book" : result;
|
||||
}
|
||||
|
||||
bool checkFileExtension(const std::string& fileName, const char* extension) {
|
||||
if (fileName.length() < strlen(extension)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const std::string fileExt = fileName.substr(fileName.length() - strlen(extension));
|
||||
for (size_t i = 0; i < fileExt.length(); i++) {
|
||||
if (tolower(fileExt[i]) != tolower(extension[i])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool checkFileExtension(const String& fileName, const char* extension) {
|
||||
if (fileName.length() < strlen(extension)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String localFile(fileName);
|
||||
String localExtension(extension);
|
||||
localFile.toLowerCase();
|
||||
localExtension.toLowerCase();
|
||||
return localFile.endsWith(localExtension);
|
||||
}
|
||||
|
||||
} // namespace StringUtils
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include <WString.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace StringUtils {
|
||||
@@ -13,10 +11,4 @@ namespace StringUtils {
|
||||
*/
|
||||
std::string sanitizeFilename(const std::string& name, size_t maxBytes = 100);
|
||||
|
||||
/**
|
||||
* Check if the given filename ends with the specified extension (case-insensitive).
|
||||
*/
|
||||
bool checkFileExtension(const std::string& fileName, const char* extension);
|
||||
bool checkFileExtension(const String& fileName, const char* extension);
|
||||
|
||||
} // namespace StringUtils
|
||||
|
||||
Reference in New Issue
Block a user