@@ -23,40 +23,35 @@ void MD5Builder::addHexString(const char * data){
2323 free (tmp);
2424}
2525
26- bool MD5Builder::addStream (Stream & stream, const size_t total_len ) {
26+ bool MD5Builder::addStream (Stream & stream, const size_t maxLen ) {
2727 const int buf_size = 512 ;
28- int bytesleft = total_len ;
28+ int maxLengthLeft = maxLen ;
2929 uint8_t * buf = (uint8_t *) malloc (buf_size);
30+
3031 if (buf) {
31- while ((stream.available () > -1 ) && (bytesleft > 0 )) {
32- // get available data size
33- int sizeAvailable = stream.available ();
34- if (sizeAvailable) {
35- int readBytes = sizeAvailable;
32+ int bytesAvailable = stream.available ();
33+ while ((bytesAvailable > 0 ) && (maxLengthLeft > 0 )) {
34+
35+ // determine number of bytes to read
36+ int readBytes = bytesAvailable;
37+ if (readBytes > maxLengthLeft) readBytes = maxLengthLeft ; // read only until max_len
38+ if (readBytes > buf_size) readBytes = buf_size; // not read more the buffer can handle
39+
40+ // read data and check if we got something
41+ int numBytesRead = stream.readBytes (buf, readBytes);
42+ if (numBytesRead< 1 ) return false ;
3643
37- // read only the asked bytes
38- if (readBytes > bytesleft) {
39- readBytes = bytesleft ;
40- }
44+ // Update MD5 with buffer payload
45+ MD5Update (&_ctx, buf, numBytesRead);
4146
42- // not read more the buffer can handle
43- if (readBytes > buf_size) {
44- readBytes = buf_size;
45- }
47+ delay (0 ); // time for network streams
4648
47- // read data
48- int bytesread = stream.readBytes (buf, readBytes);
49- bytesleft -= bytesread;
50- if (bytesread > 0 ) {
51- MD5Update (&_ctx, buf, bytesread);
52- }
53- }
54- // time for network streams
55- delay (0 );
49+ // update available number of bytes
50+ maxLengthLeft -= numBytesRead;
51+ bytesAvailable = stream.available ();
5652 }
57- // guaranteed not null
5853 free (buf);
59- return (bytesleft == 0 ) ;
54+ return true ;
6055 } else {
6156 return false ;
6257 }
0 commit comments