Skip to content

Commit 8bc5a10

Browse files
dirkmuellerd-a-v
authored andcommitted
Further const correctness / String by reference passing cleanups (#6571)
There are actually several instances where we pass in read-only parameters as pass-by-value, where in the case of String() that is inefficient as it involves copy-constructor/temp string creations. We can avoid that, similarly to single character string concatenations done via string literals instead of char literals.
1 parent ba971fe commit 8bc5a10

File tree

11 files changed

+78
-75
lines changed

11 files changed

+78
-75
lines changed

libraries/ArduinoOTA/ArduinoOTA.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,7 @@ void ArduinoOTAClass::_onRx(){
231231
return;
232232
}
233233

234-
String challenge = _password + ":" + String(_nonce) + ":" + cnonce;
234+
String challenge = _password + ':' + String(_nonce) + ':' + cnonce;
235235
MD5Builder _challengemd5;
236236
_challengemd5.begin();
237237
_challengemd5.add(challenge);

libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.cpp

+29-26
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ void HTTPClient::clear()
150150
* @param https bool
151151
* @return success bool
152152
*/
153-
bool HTTPClient::begin(WiFiClient &client, String url) {
153+
bool HTTPClient::begin(WiFiClient &client, const String& url) {
154154
#if HTTPCLIENT_1_1_COMPATIBLE
155155
if(_tcpDeprecated) {
156156
DEBUG_HTTPCLIENT("[HTTP-Client][begin] mix up of new and deprecated api\n");
@@ -188,7 +188,7 @@ bool HTTPClient::begin(WiFiClient &client, String url) {
188188
* @param https bool
189189
* @return success bool
190190
*/
191-
bool HTTPClient::begin(WiFiClient &client, String host, uint16_t port, String uri, bool https)
191+
bool HTTPClient::begin(WiFiClient &client, const String& host, uint16_t port, const String& uri, bool https)
192192
{
193193
#if HTTPCLIENT_1_1_COMPATIBLE
194194
if(_tcpDeprecated) {
@@ -281,8 +281,10 @@ bool HTTPClient::begin(String url)
281281
}
282282
#endif // HTTPCLIENT_1_1_COMPATIBLE
283283

284-
bool HTTPClient::beginInternal(String url, const char* expectedProtocol)
284+
bool HTTPClient::beginInternal(const String& __url, const char* expectedProtocol)
285285
{
286+
String url(__url);
287+
286288
DEBUG_HTTPCLIENT("[HTTP-Client][begin] url: %s\n", url.c_str());
287289
clear();
288290

@@ -500,7 +502,7 @@ void HTTPClient::setAuthorization(const char * user, const char * password)
500502
{
501503
if(user && password) {
502504
String auth = user;
503-
auth += ":";
505+
auth += ':';
504506
auth += password;
505507
_base64Authorization = base64::encode(auth);
506508
}
@@ -533,7 +535,7 @@ void HTTPClient::setTimeout(uint16_t timeout)
533535
* set the URL to a new value. Handy for following redirects.
534536
* @param url
535537
*/
536-
bool HTTPClient::setURL(String url)
538+
bool HTTPClient::setURL(const String& url)
537539
{
538540
// if the new location is only a path then only update the URI
539541
if (url && url[0] == '/') {
@@ -542,7 +544,7 @@ bool HTTPClient::setURL(String url)
542544
return true;
543545
}
544546

545-
if (!url.startsWith(_protocol + ":")) {
547+
if (!url.startsWith(_protocol + ':')) {
546548
DEBUG_HTTPCLIENT("[HTTP-Client][setURL] new URL not the same protocol, expected '%s', URL: '%s'\n", _protocol.c_str(), url.c_str());
547549
return false;
548550
}
@@ -587,16 +589,16 @@ int HTTPClient::GET()
587589

588590
/**
589591
* sends a post request to the server
590-
* @param payload uint8_t *
592+
* @param payload const uint8_t *
591593
* @param size size_t
592594
* @return http code
593595
*/
594-
int HTTPClient::POST(uint8_t * payload, size_t size)
596+
int HTTPClient::POST(const uint8_t* payload, size_t size)
595597
{
596598
return sendRequest("POST", payload, size);
597599
}
598600

599-
int HTTPClient::POST(String payload)
601+
int HTTPClient::POST(const String& payload)
600602
{
601603
return POST((uint8_t *) payload.c_str(), payload.length());
602604
}
@@ -607,26 +609,26 @@ int HTTPClient::POST(String payload)
607609
* @param size size_t
608610
* @return http code
609611
*/
610-
int HTTPClient::PUT(uint8_t * payload, size_t size) {
612+
int HTTPClient::PUT(const uint8_t* payload, size_t size) {
611613
return sendRequest("PUT", payload, size);
612614
}
613615

614-
int HTTPClient::PUT(String payload) {
615-
return PUT((uint8_t *) payload.c_str(), payload.length());
616+
int HTTPClient::PUT(const String& payload) {
617+
return PUT((const uint8_t *) payload.c_str(), payload.length());
616618
}
617619

618620
/**
619621
* sends a patch request to the server
620-
* @param payload uint8_t *
622+
* @param payload const uint8_t *
621623
* @param size size_t
622624
* @return http code
623625
*/
624-
int HTTPClient::PATCH(uint8_t * payload, size_t size) {
626+
int HTTPClient::PATCH(const uint8_t * payload, size_t size) {
625627
return sendRequest("PATCH", payload, size);
626628
}
627629

628-
int HTTPClient::PATCH(String payload) {
629-
return PATCH((uint8_t *) payload.c_str(), payload.length());
630+
int HTTPClient::PATCH(const String& payload) {
631+
return PATCH((const uint8_t *) payload.c_str(), payload.length());
630632
}
631633

632634
/**
@@ -635,19 +637,19 @@ int HTTPClient::PATCH(String payload) {
635637
* @param payload String data for the message body
636638
* @return
637639
*/
638-
int HTTPClient::sendRequest(const char * type, String payload)
640+
int HTTPClient::sendRequest(const char * type, const String& payload)
639641
{
640-
return sendRequest(type, (uint8_t *) payload.c_str(), payload.length());
642+
return sendRequest(type, (const uint8_t *) payload.c_str(), payload.length());
641643
}
642644

643645
/**
644646
* sendRequest
645-
* @param type const char * "GET", "POST", ....
646-
* @param payload uint8_t * data for the message body if null not send
647-
* @param size size_t size for the message body if 0 not send
647+
* @param type const char * "GET", "POST", ....
648+
* @param payload const uint8_t * data for the message body if null not send
649+
* @param size size_t size for the message body if 0 not send
648650
* @return -1 if no info or > 0 when Content-Length is set by server
649651
*/
650-
int HTTPClient::sendRequest(const char * type, uint8_t * payload, size_t size)
652+
int HTTPClient::sendRequest(const char * type, const uint8_t * payload, size_t size)
651653
{
652654
bool redirect = false;
653655
int code = 0;
@@ -1212,12 +1214,12 @@ bool HTTPClient::sendHeader(const char * type)
12121214
return false;
12131215
}
12141216

1215-
String header = String(type) + " " + (_uri.length() ? _uri : F("/")) + F(" HTTP/1.");
1217+
String header = String(type) + ' ' + (_uri.length() ? _uri : F("/")) + F(" HTTP/1.");
12161218

12171219
if(_useHTTP10) {
1218-
header += "0";
1220+
header += '0';
12191221
} else {
1220-
header += "1";
1222+
header += '1';
12211223
}
12221224

12231225
header += String(F("\r\nHost: ")) + _host;
@@ -1316,7 +1318,8 @@ int HTTPClient::handleHeaderResponse()
13161318
if(_currentHeaders[i].key.equalsIgnoreCase(headerName)) {
13171319
if (_currentHeaders[i].value != "") {
13181320
// Existing value, append this one with a comma
1319-
_currentHeaders[i].value += "," + headerValue;
1321+
_currentHeaders[i].value += ',';
1322+
_currentHeaders[i].value += headerValue;
13201323
} else {
13211324
_currentHeaders[i].value = headerValue;
13221325
}

libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h

+13-13
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,8 @@ class HTTPClient
147147
* Since both begin() functions take a reference to client as a parameter, you need to
148148
* ensure the client object lives the entire time of the HTTPClient
149149
*/
150-
bool begin(WiFiClient &client, String url);
151-
bool begin(WiFiClient &client, String host, uint16_t port, String uri = "/", bool https = false);
150+
bool begin(WiFiClient &client, const String& url);
151+
bool begin(WiFiClient &client, const String& host, uint16_t port, const String& uri = "/", bool https = false);
152152

153153
#if HTTPCLIENT_1_1_COMPATIBLE
154154
// Plain HTTP connection, unencrypted
@@ -175,20 +175,20 @@ class HTTPClient
175175
void setTimeout(uint16_t timeout);
176176
void setFollowRedirects(bool follow);
177177
void setRedirectLimit(uint16_t limit); // max redirects to follow for a single request
178-
bool setURL(String url); // handy for handling redirects
178+
bool setURL(const String& url); // handy for handling redirects
179179
void useHTTP10(bool usehttp10 = true);
180180

181181
/// request handling
182182
int GET();
183-
int POST(uint8_t * payload, size_t size);
184-
int POST(String payload);
185-
int PUT(uint8_t * payload, size_t size);
186-
int PUT(String payload);
187-
int PATCH(uint8_t * payload, size_t size);
188-
int PATCH(String payload);
189-
int sendRequest(const char * type, String payload);
190-
int sendRequest(const char * type, uint8_t * payload = NULL, size_t size = 0);
191-
int sendRequest(const char * type, Stream * stream, size_t size = 0);
183+
int POST(const uint8_t* payload, size_t size);
184+
int POST(const String& payload);
185+
int PUT(const uint8_t* payload, size_t size);
186+
int PUT(const String& payload);
187+
int PATCH(const uint8_t* payload, size_t size);
188+
int PATCH(const String& payload);
189+
int sendRequest(const char* type, const String& payload);
190+
int sendRequest(const char* type, const uint8_t* payload = NULL, size_t size = 0);
191+
int sendRequest(const char* type, Stream * stream, size_t size = 0);
192192

193193
void addHeader(const String& name, const String& value, bool first = false, bool replace = true);
194194

@@ -216,7 +216,7 @@ class HTTPClient
216216
String value;
217217
};
218218

219-
bool beginInternal(String url, const char* expectedProtocol);
219+
bool beginInternal(const String& url, const char* expectedProtocol);
220220
void disconnect(bool preserveClient = false);
221221
void clear();
222222
int returnError(int error);

libraries/ESP8266WebServer/src/ESP8266WebServer-impl.h

+7-7
Original file line numberDiff line numberDiff line change
@@ -252,11 +252,11 @@ void ESP8266WebServerTemplate<ServerType>::requestAuthentication(HTTPAuthMethod
252252
_srealm = String(realm);
253253
}
254254
if(mode == BASIC_AUTH) {
255-
sendHeader(String(FPSTR(WWW_Authenticate)), String(F("Basic realm=\"")) + _srealm + String(F("\"")));
255+
sendHeader(String(FPSTR(WWW_Authenticate)), String(F("Basic realm=\"")) + _srealm + String('\"'));
256256
} else {
257257
_snonce=_getRandomHexString();
258258
_sopaque=_getRandomHexString();
259-
sendHeader(String(FPSTR(WWW_Authenticate)), String(F("Digest realm=\"")) +_srealm + String(F("\", qop=\"auth\", nonce=\"")) + _snonce + String(F("\", opaque=\"")) + _sopaque + String(F("\"")));
259+
sendHeader(String(FPSTR(WWW_Authenticate)), String(F("Digest realm=\"")) +_srealm + String(F("\", qop=\"auth\", nonce=\"")) + _snonce + String(F("\", opaque=\"")) + _sopaque + String('\"'));
260260
}
261261
using namespace mime;
262262
send(401, String(FPSTR(mimeTable[html].mimeType)), authFailMsg);
@@ -524,13 +524,13 @@ String ESP8266WebServerTemplate<ServerType>::credentialHash(const String& userna
524524
{
525525
MD5Builder md5;
526526
md5.begin();
527-
md5.add(username + ":" + realm + ":" + password); // md5 of the user:realm:password
527+
md5.add(username + ':' + realm + ':' + password); // md5 of the user:realm:password
528528
md5.calculate();
529529
return md5.toString();
530530
}
531531

532532
template <typename ServerType>
533-
void ESP8266WebServerTemplate<ServerType>::_streamFileCore(const size_t fileSize, const String & fileName, const String & contentType)
533+
void ESP8266WebServerTemplate<ServerType>::_streamFileCore(const size_t fileSize, const String &fileName, const String &contentType)
534534
{
535535
using namespace mime;
536536
setContentLength(fileSize);
@@ -544,7 +544,7 @@ void ESP8266WebServerTemplate<ServerType>::_streamFileCore(const size_t fileSize
544544

545545

546546
template <typename ServerType>
547-
const String& ESP8266WebServerTemplate<ServerType>::arg(String name) const {
547+
const String& ESP8266WebServerTemplate<ServerType>::arg(const String& name) const {
548548
for (int j = 0; j < _postArgsLen; ++j) {
549549
if ( _postArgs[j].key == name )
550550
return _postArgs[j].value;
@@ -590,7 +590,7 @@ bool ESP8266WebServerTemplate<ServerType>::hasArg(const String& name) const {
590590

591591

592592
template <typename ServerType>
593-
const String& ESP8266WebServerTemplate<ServerType>::header(String name) const {
593+
const String& ESP8266WebServerTemplate<ServerType>::header(const String& name) const {
594594
for (int i = 0; i < _headerKeysCount; ++i) {
595595
if (_currentHeaders[i].key.equalsIgnoreCase(name))
596596
return _currentHeaders[i].value;
@@ -630,7 +630,7 @@ int ESP8266WebServerTemplate<ServerType>::headers() const {
630630
}
631631

632632
template <typename ServerType>
633-
bool ESP8266WebServerTemplate<ServerType>::hasHeader(String name) const {
633+
bool ESP8266WebServerTemplate<ServerType>::hasHeader(const String& name) const {
634634
for (int i = 0; i < _headerKeysCount; ++i) {
635635
if ((_currentHeaders[i].key.equalsIgnoreCase(name)) && (_currentHeaders[i].value.length() > 0))
636636
return true;

libraries/ESP8266WebServer/src/ESP8266WebServer.h

+3-3
Original file line numberDiff line numberDiff line change
@@ -107,17 +107,17 @@ class ESP8266WebServerTemplate
107107
// Allows setting server options (i.e. SSL keys) by the instantiator
108108
ServerType &getServer() { return _server; }
109109

110-
const String& arg(String name) const; // get request argument value by name
110+
const String& arg(const String& name) const; // get request argument value by name
111111
const String& arg(int i) const; // get request argument value by number
112112
const String& argName(int i) const; // get request argument name by number
113113
int args() const; // get arguments count
114114
bool hasArg(const String& name) const; // check if argument exists
115115
void collectHeaders(const char* headerKeys[], const size_t headerKeysCount); // set the request headers to collect
116-
const String& header(String name) const; // get request header value by name
116+
const String& header(const String& name) const; // get request header value by name
117117
const String& header(int i) const; // get request header value by number
118118
const String& headerName(int i) const; // get request header name by number
119119
int headers() const; // get header count
120-
bool hasHeader(String name) const; // check if header exists
120+
bool hasHeader(const String& name) const; // check if header exists
121121
const String& hostHeader() const; // get request host header if available or empty String if not
122122

123123
// send response to the client

libraries/ESP8266WiFiMesh/src/ESP8266WiFiMesh.cpp

+4-4
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,7 @@ transmission_status_t ESP8266WiFiMesh::exchangeInfo(WiFiClient &currClient)
358358
{
359359
verboseModePrint("Transmitting"); // Not storing strings in flash (via F()) to avoid performance impacts when using the string.
360360

361-
currClient.print(getMessage() + "\r");
361+
currClient.print(getMessage() + '\r');
362362
yield();
363363

364364
if (!waitForClientTransmission(currClient, _stationModeTimeoutMs))
@@ -582,11 +582,11 @@ void ESP8266WiFiMesh::attemptTransmission(const String &message, bool concluding
582582

583583
if(_verboseMode) // Avoid string generation if not required
584584
{
585-
verboseModePrint(String(F("AP acquired: ")) + currentSSID + String(F(", Ch:")) + String(currentWiFiChannel) + " ", false);
585+
verboseModePrint(String(F("AP acquired: ")) + currentSSID + String(F(", Ch:")) + String(currentWiFiChannel) + ' ', false);
586586

587587
if(currentNetwork.networkIndex != NETWORK_INFO_DEFAULT_INT)
588588
{
589-
verboseModePrint("(" + String(WiFi.RSSI(currentNetwork.networkIndex)) + String(F("dBm) ")) +
589+
verboseModePrint(String('(') + String(WiFi.RSSI(currentNetwork.networkIndex)) + String(F("dBm) ")) +
590590
(WiFi.encryptionType(currentNetwork.networkIndex) == ENC_TYPE_NONE ? String(F("open")) : ""), false);
591591
}
592592

@@ -662,7 +662,7 @@ void ESP8266WiFiMesh::acceptRequest()
662662
if (_client.connected())
663663
{
664664
verboseModePrint("Responding"); // Not storing strings in flash (via F()) to avoid performance impacts when using the string.
665-
_client.print(response + "\r");
665+
_client.print(response + '\r');
666666
_client.flush();
667667
yield();
668668
}

libraries/ESP8266httpUpdate/src/ESP8266httpUpdate.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -439,7 +439,7 @@ HTTPUpdateResult ESP8266HTTPUpdate::handleUpdate(HTTPClient& http, const String&
439439
* @param md5 String
440440
* @return true if Update ok
441441
*/
442-
bool ESP8266HTTPUpdate::runUpdate(Stream& in, uint32_t size, String md5, int command)
442+
bool ESP8266HTTPUpdate::runUpdate(Stream& in, uint32_t size, const String& md5, int command)
443443
{
444444

445445
StreamString error;

libraries/ESP8266httpUpdate/src/ESP8266httpUpdate.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ class ESP8266HTTPUpdate
130130

131131
protected:
132132
t_httpUpdate_return handleUpdate(HTTPClient& http, const String& currentVersion, bool spiffs = false);
133-
bool runUpdate(Stream& in, uint32_t size, String md5, int command = U_FLASH);
133+
bool runUpdate(Stream& in, uint32_t size, const String& md5, int command = U_FLASH);
134134

135135
int _lastError;
136136
bool _rebootOnUpdate = true;

libraries/ESP8266mDNS/src/ESP8266mDNS_Legacy.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ bool MDNSResponder::addServiceTxt(char *name, char *proto, char *key, char *valu
277277
return false; //max txt record size
278278
}
279279
MDNSTxt *newtxt = new MDNSTxt;
280-
newtxt->_txt = String(key) + "=" + String(value);
280+
newtxt->_txt = String(key) + '=' + String(value);
281281
newtxt->_next = 0;
282282
if (servicePtr->_txts == 0) //no services have been added
283283
{

0 commit comments

Comments
 (0)