diff --git a/cores/esp8266/MD5Builder.cpp b/cores/esp8266/MD5Builder.cpp index dd3d9dd333..b0507fefc7 100644 --- a/cores/esp8266/MD5Builder.cpp +++ b/cores/esp8266/MD5Builder.cpp @@ -23,40 +23,35 @@ void MD5Builder::addHexString(const char * data){ free(tmp); } -bool MD5Builder::addStream(Stream & stream, const size_t total_len) { +bool MD5Builder::addStream(Stream & stream, const size_t maxLen) { const int buf_size = 512; - int bytesleft = total_len; + int maxLengthLeft = maxLen; uint8_t * buf = (uint8_t*) malloc(buf_size); + if(buf) { - while((stream.available() > -1) && (bytesleft > 0)) { - // get available data size - int sizeAvailable = stream.available(); - if(sizeAvailable) { - int readBytes = sizeAvailable; + int bytesAvailable = stream.available(); + while((bytesAvailable > 0) && (maxLengthLeft > 0)) { + + // determine number of bytes to read + int readBytes = bytesAvailable; + if(readBytes > maxLengthLeft) readBytes = maxLengthLeft ; // read only until max_len + if(readBytes > buf_size) readBytes = buf_size; // not read more the buffer can handle + + // read data and check if we got something + int numBytesRead = stream.readBytes(buf, readBytes); + if(numBytesRead< 1) return false; - // read only the asked bytes - if(readBytes > bytesleft) { - readBytes = bytesleft ; - } + // Update MD5 with buffer payload + MD5Update(&_ctx, buf, numBytesRead); - // not read more the buffer can handle - if(readBytes > buf_size) { - readBytes = buf_size; - } + delay(0); // time for network streams - // read data - int bytesread = stream.readBytes(buf, readBytes); - bytesleft -= bytesread; - if(bytesread > 0) { - MD5Update(&_ctx, buf, bytesread); - } - } - // time for network streams - delay(0); + // update available number of bytes + maxLengthLeft -= numBytesRead; + bytesAvailable = stream.available(); } - // guaranteed not null free(buf); - return (bytesleft == 0); + return true; } else { return false; } diff --git a/cores/esp8266/MD5Builder.h b/cores/esp8266/MD5Builder.h index ec1ac83114..e2ca4a1a79 100644 --- a/cores/esp8266/MD5Builder.h +++ b/cores/esp8266/MD5Builder.h @@ -37,7 +37,7 @@ class MD5Builder { void addHexString(const char * data); void addHexString(char * data){ addHexString((const char*)data); } void addHexString(String data){ addHexString(data.c_str()); } - bool addStream(Stream & stream, const size_t total_len); + bool addStream(Stream & stream, const size_t maxLen); void calculate(void); void getBytes(uint8_t * output); void getChars(char * output);