1
0
mirror of https://github.com/esp8266/Arduino.git synced 2025-04-25 20:02:37 +03:00

Various String handling cleanups (#6945)

Use the proper api (::clear(), isEmpty()) instead of doing
comparisons/assignments of empty strings. Also fix mixture
of tabs and spaces in the source code.
This commit is contained in:
Dirk Mueller 2019-12-26 21:03:18 +01:00 committed by Develo
parent 6c2ab25087
commit 698ffc3498
11 changed files with 108 additions and 108 deletions

View File

@ -156,9 +156,9 @@ unsigned char String::changeBuffer(unsigned int maxStrLen) {
if (maxStrLen < sizeof(sso.buff) - 1) {
if (isSSO() || !buffer()) {
// Already using SSO, nothing to do
uint16_t oldLen = len();
uint16_t oldLen = len();
setSSO(true);
setLen(oldLen);
setLen(oldLen);
return 1;
} else { // if bufptr && !isSSO()
// Using bufptr, need to shrink into sso.buff
@ -167,7 +167,7 @@ unsigned char String::changeBuffer(unsigned int maxStrLen) {
free(wbuffer());
uint16_t oldLen = len();
setSSO(true);
setLen(oldLen);
setLen(oldLen);
memcpy(wbuffer(), temp, maxStrLen);
return 1;
}
@ -204,7 +204,7 @@ unsigned char String::changeBuffer(unsigned int maxStrLen) {
// /*********************************************/
String & String::copy(const char *cstr, unsigned int length) {
if(!reserve(length)) {
if (!reserve(length)) {
invalidate();
return *this;
}
@ -225,11 +225,11 @@ String & String::copy(const __FlashStringHelper *pstr, unsigned int length) {
#ifdef __GXX_EXPERIMENTAL_CXX0X__
void String::move(String &rhs) {
if(buffer()) {
if(capacity() >= rhs.len()) {
if (buffer()) {
if (capacity() >= rhs.len()) {
memmove_P(wbuffer(), rhs.buffer(), rhs.length() + 1);
setLen(rhs.len());
rhs.invalidate();
rhs.invalidate();
return;
} else {
if (!isSSO()) {
@ -255,10 +255,10 @@ void String::move(String &rhs) {
#endif
String & String::operator =(const String &rhs) {
if(this == &rhs)
if (this == &rhs)
return *this;
if(rhs.buffer())
if (rhs.buffer())
copy(rhs.buffer(), rhs.len());
else
invalidate();
@ -268,20 +268,20 @@ String & String::operator =(const String &rhs) {
#ifdef __GXX_EXPERIMENTAL_CXX0X__
String & String::operator =(String &&rval) {
if(this != &rval)
if (this != &rval)
move(rval);
return *this;
}
String & String::operator =(StringSumHelper &&rval) {
if(this != &rval)
if (this != &rval)
move(rval);
return *this;
}
#endif
String & String::operator =(const char *cstr) {
if(cstr)
if (cstr)
copy(cstr, strlen(cstr));
else
invalidate();
@ -323,11 +323,11 @@ unsigned char String::concat(const String &s) {
unsigned char String::concat(const char *cstr, unsigned int length) {
unsigned int newlen = len() + length;
if(!cstr)
if (!cstr)
return 0;
if(length == 0)
if (length == 0)
return 1;
if(!reserve(newlen))
if (!reserve(newlen))
return 0;
memmove_P(wbuffer() + len(), cstr, length + 1);
setLen(newlen);
@ -336,7 +336,7 @@ unsigned char String::concat(const char *cstr, unsigned int length) {
}
unsigned char String::concat(const char *cstr) {
if(!cstr)
if (!cstr)
return 0;
return concat(cstr, strlen(cstr));
}
@ -407,70 +407,70 @@ unsigned char String::concat(const __FlashStringHelper * str) {
StringSumHelper & operator +(const StringSumHelper &lhs, const String &rhs) {
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(rhs.buffer(), rhs.len()))
if (!a.concat(rhs.buffer(), rhs.len()))
a.invalidate();
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, const char *cstr) {
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!cstr || !a.concat(cstr, strlen(cstr)))
if (!cstr || !a.concat(cstr, strlen(cstr)))
a.invalidate();
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, char c) {
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(c))
if (!a.concat(c))
a.invalidate();
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, unsigned char num) {
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(num))
if (!a.concat(num))
a.invalidate();
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, int num) {
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(num))
if (!a.concat(num))
a.invalidate();
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, unsigned int num) {
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(num))
if (!a.concat(num))
a.invalidate();
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, long num) {
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(num))
if (!a.concat(num))
a.invalidate();
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, unsigned long num) {
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(num))
if (!a.concat(num))
a.invalidate();
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, float num) {
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(num))
if (!a.concat(num))
a.invalidate();
return a;
}
StringSumHelper & operator +(const StringSumHelper &lhs, double num) {
StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
if(!a.concat(num))
if (!a.concat(num))
a.invalidate();
return a;
}
@ -503,9 +503,9 @@ unsigned char String::equals(const String &s2) const {
}
unsigned char String::equals(const char *cstr) const {
if(len() == 0)
if (len() == 0)
return (cstr == NULL || *cstr == 0);
if(cstr == NULL)
if (cstr == NULL)
return buffer()[0] == 0;
return strcmp(buffer(), cstr) == 0;
}
@ -527,16 +527,16 @@ unsigned char String::operator>=(const String &rhs) const {
}
unsigned char String::equalsIgnoreCase(const String &s2) const {
if(this == &s2)
if (this == &s2)
return 1;
if(len() != s2.len())
if (len() != s2.len())
return 0;
if(len() == 0)
if (len() == 0)
return 1;
const char *p1 = buffer();
const char *p2 = s2.buffer();
while(*p1) {
if(tolower(*p1++) != tolower(*p2++))
while (*p1) {
if (tolower(*p1++) != tolower(*p2++))
return 0;
}
return 1;
@ -545,18 +545,18 @@ unsigned char String::equalsIgnoreCase(const String &s2) const {
unsigned char String::equalsConstantTime(const String &s2) const {
// To avoid possible time-based attacks present function
// compares given strings in a constant time.
if(len() != s2.len())
if (len() != s2.len())
return 0;
//at this point lengths are the same
if(len() == 0)
if (len() == 0)
return 1;
//at this point lenghts are the same and non-zero
const char *p1 = buffer();
const char *p2 = s2.buffer();
unsigned int equalchars = 0;
unsigned int diffchars = 0;
while(*p1) {
if(*p1 == *p2)
while (*p1) {
if (*p1 == *p2)
++equalchars;
else
++diffchars;
@ -596,13 +596,13 @@ char String::charAt(unsigned int loc) const {
}
void String::setCharAt(unsigned int loc, char c) {
if(loc < len())
if (loc < len())
wbuffer()[loc] = c;
}
char & String::operator[](unsigned int index) {
static char dummy_writable_char;
if(index >= len() || !buffer()) {
if (index >= len() || !buffer()) {
dummy_writable_char = 0;
return dummy_writable_char;
}
@ -610,20 +610,20 @@ char & String::operator[](unsigned int index) {
}
char String::operator[](unsigned int index) const {
if(index >= len() || !buffer())
if (index >= len() || !buffer())
return 0;
return buffer()[index];
}
void String::getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index) const {
if(!bufsize || !buf)
if (!bufsize || !buf)
return;
if(index >= len()) {
if (index >= len()) {
buf[0] = 0;
return;
}
unsigned int n = bufsize - 1;
if(n > len() - index)
if (n > len() - index)
n = len() - index;
strncpy((char *) buf, buffer() + index, n);
buf[n] = 0;
@ -638,10 +638,10 @@ int String::indexOf(char c) const {
}
int String::indexOf(char ch, unsigned int fromIndex) const {
if(fromIndex >= len())
if (fromIndex >= len())
return -1;
const char* temp = strchr(buffer() + fromIndex, ch);
if(temp == NULL)
if (temp == NULL)
return -1;
return temp - buffer();
}
@ -651,10 +651,10 @@ int String::indexOf(const String &s2) const {
}
int String::indexOf(const String &s2, unsigned int fromIndex) const {
if(fromIndex >= len())
if (fromIndex >= len())
return -1;
const char *found = strstr(buffer() + fromIndex, s2.buffer());
if(found == NULL)
if (found == NULL)
return -1;
return found - buffer();
}
@ -664,13 +664,13 @@ int String::lastIndexOf(char theChar) const {
}
int String::lastIndexOf(char ch, unsigned int fromIndex) const {
if(fromIndex >= len())
if (fromIndex >= len())
return -1;
char tempchar = buffer()[fromIndex + 1];
wbuffer()[fromIndex + 1] = '\0';
char* temp = strrchr(wbuffer(), ch);
wbuffer()[fromIndex + 1] = tempchar;
if(temp == NULL)
if (temp == NULL)
return -1;
return temp - buffer();
}
@ -680,31 +680,31 @@ int String::lastIndexOf(const String &s2) const {
}
int String::lastIndexOf(const String &s2, unsigned int fromIndex) const {
if(s2.len() == 0 || len() == 0 || s2.len() > len())
if (s2.len() == 0 || len() == 0 || s2.len() > len())
return -1;
if(fromIndex >= len())
if (fromIndex >= len())
fromIndex = len() - 1;
int found = -1;
for(char *p = wbuffer(); p <= wbuffer() + fromIndex; p++) {
for (char *p = wbuffer(); p <= wbuffer() + fromIndex; p++) {
p = strstr(p, s2.buffer());
if(!p)
if (!p)
break;
if((unsigned int) (p - wbuffer()) <= fromIndex)
if ((unsigned int) (p - wbuffer()) <= fromIndex)
found = p - buffer();
}
return found;
}
String String::substring(unsigned int left, unsigned int right) const {
if(left > right) {
if (left > right) {
unsigned int temp = right;
right = left;
left = temp;
}
String out;
if(left >= len())
if (left >= len())
return out;
if(right > len())
if (right > len())
right = len();
char temp = buffer()[right]; // save the replaced character
wbuffer()[right] = '\0';
@ -718,28 +718,28 @@ String String::substring(unsigned int left, unsigned int right) const {
// /*********************************************/
void String::replace(char find, char replace) {
if(!buffer())
if (!buffer())
return;
for(char *p = wbuffer(); *p; p++) {
if(*p == find)
for (char *p = wbuffer(); *p; p++) {
if (*p == find)
*p = replace;
}
}
void String::replace(const String& find, const String& replace) {
if(len() == 0 || find.len() == 0)
if (len() == 0 || find.len() == 0)
return;
int diff = replace.len() - find.len();
char *readFrom = wbuffer();
char *foundAt;
if(diff == 0) {
while((foundAt = strstr(readFrom, find.buffer())) != NULL) {
if (diff == 0) {
while ((foundAt = strstr(readFrom, find.buffer())) != NULL) {
memmove_P(foundAt, replace.buffer(), replace.len());
readFrom = foundAt + replace.len();
}
} else if(diff < 0) {
} else if (diff < 0) {
char *writeTo = wbuffer();
while((foundAt = strstr(readFrom, find.buffer())) != NULL) {
while ((foundAt = strstr(readFrom, find.buffer())) != NULL) {
unsigned int n = foundAt - readFrom;
memmove_P(writeTo, readFrom, n);
writeTo += n;
@ -751,19 +751,19 @@ void String::replace(const String& find, const String& replace) {
memmove_P(writeTo, readFrom, strlen(readFrom)+1);
} else {
unsigned int size = len(); // compute size needed for result
while((foundAt = strstr(readFrom, find.buffer())) != NULL) {
while ((foundAt = strstr(readFrom, find.buffer())) != NULL) {
readFrom = foundAt + find.len();
size += diff;
}
if(size == len())
if (size == len())
return;
if(size > capacity() && !changeBuffer(size))
if (size > capacity() && !changeBuffer(size))
return; // XXX: tell user!
int index = len() - 1;
while(index >= 0 && (index = lastIndexOf(find, index)) >= 0) {
while (index >= 0 && (index = lastIndexOf(find, index)) >= 0) {
readFrom = wbuffer() + index + find.len();
memmove_P(readFrom + diff, readFrom, len() - (readFrom - buffer()));
int newLen = len() + diff;
int newLen = len() + diff;
memmove_P(wbuffer() + index, replace.buffer(), replace.len());
setLen(newLen);
wbuffer()[newLen] = 0;
@ -780,13 +780,13 @@ void String::remove(unsigned int index) {
}
void String::remove(unsigned int index, unsigned int count) {
if(index >= len()) {
if (index >= len()) {
return;
}
if(count <= 0) {
if (count <= 0) {
return;
}
if(count > len() - index) {
if (count > len() - index) {
count = len() - index;
}
char *writeTo = wbuffer() + index;
@ -797,33 +797,33 @@ void String::remove(unsigned int index, unsigned int count) {
}
void String::toLowerCase(void) {
if(!buffer())
if (!buffer())
return;
for(char *p = wbuffer(); *p; p++) {
for (char *p = wbuffer(); *p; p++) {
*p = tolower(*p);
}
}
void String::toUpperCase(void) {
if(!buffer())
if (!buffer())
return;
for(char *p = wbuffer(); *p; p++) {
for (char *p = wbuffer(); *p; p++) {
*p = toupper(*p);
}
}
void String::trim(void) {
if(!buffer() || len() == 0)
if (!buffer() || len() == 0)
return;
char *begin = wbuffer();
while(isspace(*begin))
while (isspace(*begin))
begin++;
char *end = wbuffer() + len() - 1;
while(isspace(*end) && end >= begin)
while (isspace(*end) && end >= begin)
end--;
unsigned int newlen = end + 1 - begin;
setLen(newlen);
if(begin > buffer())
if (begin > buffer())
memmove_P(wbuffer(), begin, newlen);
wbuffer()[newlen] = 0;
}

View File

@ -145,7 +145,7 @@ constructor:
.. code:: cpp
String(const char *cstr = ""); // constructor from const char *
String(const char *cstr = nullptr); // constructor from const char *
String(const String &str); // copy constructor
String(const __FlashStringHelper *str); // constructor for flash strings

View File

@ -168,7 +168,7 @@ int ArduinoOTAClass::parseInt(){
}
String ArduinoOTAClass::readStringUntil(char end){
String res = "";
String res;
int value;
while(true){
value = _udp_ota->read();

View File

@ -119,7 +119,7 @@ void DNSServer::respondToRequest(uint8_t *buffer, size_t length)
query, queryLength);
// If we have no domain name configured, just return an error
if (_domainName == "")
if (_domainName.isEmpty())
return replyWithError(dnsHeader, _errorReplyCode,
query, queryLength);

View File

@ -137,9 +137,9 @@ void HTTPClient::clear()
{
_returnCode = 0;
_size = -1;
_headers = "";
_headers.clear();
_location.clear();
_payload.reset();
_location = "";
}
@ -657,7 +657,7 @@ int HTTPClient::sendRequest(const char * type, const uint8_t * payload, size_t s
// wipe out any existing headers from previous request
for(size_t i = 0; i < _headerKeysCount; i++) {
if (_currentHeaders[i].value.length() > 0) {
_currentHeaders[i].value = "";
_currentHeaders[i].value.clear();
}
}

View File

@ -77,7 +77,7 @@ void ESP8266HTTPUpdateServerTemplate<ServerType>::setup(ESP8266WebServerTemplate
HTTPUpload& upload = _server->upload();
if(upload.status == UPLOAD_FILE_START){
_updaterError = String();
_updaterError.clear();
if (_serial_output)
Serial.setDebugOutput(true);

View File

@ -122,7 +122,7 @@ void handleFileUpload() {
}
DBG_OUTPUT_PORT.print("handleFileUpload Name: "); DBG_OUTPUT_PORT.println(filename);
fsUploadFile = filesystem->open(filename, "w");
filename = String();
filename.clear();
} else if (upload.status == UPLOAD_FILE_WRITE) {
//DBG_OUTPUT_PORT.print("handleFileUpload Data: "); DBG_OUTPUT_PORT.println(upload.currentSize);
if (fsUploadFile) {
@ -150,7 +150,7 @@ void handleFileDelete() {
}
filesystem->remove(path);
server.send(200, "text/plain", "");
path = String();
path.clear();
}
void handleFileCreate() {
@ -172,7 +172,7 @@ void handleFileCreate() {
return server.send(500, "text/plain", "CREATE FAILED");
}
server.send(200, "text/plain", "");
path = String();
path.clear();
}
void handleFileList() {
@ -184,7 +184,7 @@ void handleFileList() {
String path = server.arg("dir");
DBG_OUTPUT_PORT.println("handleFileList: " + path);
Dir dir = filesystem->openDir(path);
path = String();
path.clear();
String output = "[";
while (dir.next()) {
@ -275,13 +275,13 @@ void setup(void) {
//get heap status, analog input value and all GPIO statuses in one json call
server.on("/all", HTTP_GET, []() {
String json = "{";
String json('{');
json += "\"heap\":" + String(ESP.getFreeHeap());
json += ", \"analog\":" + String(analogRead(A0));
json += ", \"gpio\":" + String((uint32_t)(((GPI | GPO) & 0xFFFF) | ((GP16I & 0x01) << 16)));
json += "}";
server.send(200, "text/json", json);
json = String();
json.clear();
});
server.begin();
DBG_OUTPUT_PORT.println("HTTP server started");

View File

@ -209,7 +209,7 @@ void printDirectory() {
return returnFail("BAD PATH");
}
File dir = SD.open((char *)path.c_str());
path = String();
path.clear();
if (!dir.isDirectory()) {
dir.close();
return returnFail("NOT DIR");

View File

@ -89,7 +89,7 @@ bool ESP8266WebServerTemplate<ServerType>::_parseRequest(ClientType& client) {
String url = req.substring(addr_start + 1, addr_end);
String versionEnd = req.substring(addr_end + 8);
_currentVersion = atoi(versionEnd.c_str());
String searchStr = "";
String searchStr;
int hasSearch = url.indexOf('?');
if (hasSearch != -1){
searchStr = url.substring(hasSearch + 1);
@ -144,7 +144,7 @@ bool ESP8266WebServerTemplate<ServerType>::_parseRequest(ClientType& client) {
while(1){
req = client.readStringUntil('\r');
client.readStringUntil('\n');
if (req == "") break;//no moar headers
if (req.isEmpty()) break;//no moar headers
int headerDiv = req.indexOf(':');
if (headerDiv == -1){
break;
@ -222,7 +222,7 @@ bool ESP8266WebServerTemplate<ServerType>::_parseRequest(ClientType& client) {
while(1){
req = client.readStringUntil('\r');
client.readStringUntil('\n');
if (req == "") break;//no moar headers
if (req.isEmpty()) break;//no moar headers
int headerDiv = req.indexOf(':');
if (headerDiv == -1){
break;
@ -452,7 +452,7 @@ bool ESP8266WebServerTemplate<ServerType>::_parseForm(ClientType& client, const
line = client.readStringUntil('\r');
client.readStringUntil('\n');
if (line.startsWith("--"+boundary)) break;
if (argValue.length() > 0) argValue += "\n";
if (argValue.length() > 0) argValue += '\n';
argValue += line;
}
#ifdef DEBUG_ESP_HTTP_SERVER
@ -600,7 +600,7 @@ readfile:
template <typename ServerType>
String ESP8266WebServerTemplate<ServerType>::urlDecode(const String& text)
{
String decoded = "";
String decoded;
char temp[] = "0x00";
unsigned int len = text.length();
unsigned int i = 0;

View File

@ -31,7 +31,7 @@
const IPAddress ESP8266WiFiMesh::emptyIP = IPAddress();
const uint32_t ESP8266WiFiMesh::lwipVersion203Signature[3] {2,0,3};
String ESP8266WiFiMesh::lastSSID = "";
String ESP8266WiFiMesh::lastSSID;
bool ESP8266WiFiMesh::staticIPActivated = false;
// IP needs to be at the same subnet as server gateway (192.168.4 in this case). Station gateway ip must match ip for server.
@ -55,7 +55,7 @@ ESP8266WiFiMesh::ESP8266WiFiMesh(ESP8266WiFiMesh::requestHandlerType requestHand
{
storeLwipVersion();
updateNetworkNames(meshName, (nodeID != "" ? nodeID : uint64ToString(ESP.getChipId())));
updateNetworkNames(meshName, (!nodeID.isEmpty() ? nodeID : uint64ToString(ESP.getChipId())));
_requestHandler = requestHandler;
_responseHandler = responseHandler;
setWiFiChannel(meshWiFiChannel);
@ -67,9 +67,9 @@ ESP8266WiFiMesh::ESP8266WiFiMesh(ESP8266WiFiMesh::requestHandlerType requestHand
void ESP8266WiFiMesh::updateNetworkNames(const String &newMeshName, const String &newNodeID)
{
if(newMeshName != "")
if(!newMeshName.isEmpty())
_meshName = newMeshName;
if(newNodeID != "")
if(!newNodeID.isEmpty())
_nodeID = newNodeID;
String newSSID = _meshName + _nodeID;
@ -453,7 +453,7 @@ void ESP8266WiFiMesh::initiateConnectionToAP(const String &targetSSID, int targe
*/
transmission_status_t ESP8266WiFiMesh::connectToNode(const String &targetSSID, int targetChannel, uint8_t *targetBSSID)
{
if(staticIPActivated && lastSSID != "" && lastSSID != targetSSID) // So we only do this once per connection, in case there is a performance impact.
if(staticIPActivated && !lastSSID.isEmpty() && lastSSID != targetSSID) // So we only do this once per connection, in case there is a performance impact.
{
#ifdef ENABLE_STATIC_IP_OPTIMIZATION
if(atLeastLwipVersion(lwipVersion203Signature))
@ -562,12 +562,12 @@ void ESP8266WiFiMesh::attemptTransmission(const String &message, bool concluding
WiFi.disconnect();
yield();
String currentSSID = "";
String currentSSID;
int currentWiFiChannel = NETWORK_INFO_DEFAULT_INT;
uint8_t *currentBSSID = NULL;
// If an SSID has been assigned, it is prioritized over an assigned networkIndex since the networkIndex is more likely to change.
if(currentNetwork.SSID != "")
if(!currentNetwork.SSID.isEmpty())
{
currentSSID = currentNetwork.SSID;
currentWiFiChannel = currentNetwork.wifiChannel;

View File

@ -95,7 +95,7 @@ TEST_CASE("STA mode events are called both when using DHCP and static config", "
delay(100);
REQUIRE(events == "connected,got_ip,disconnected,");
events = String();
events.clear();
// now run the same with static IP config saved above