diff options
author | David A. Mellis <d.mellis@arduino.cc> | 2011-11-19 16:23:19 -0500 |
---|---|---|
committer | David A. Mellis <d.mellis@arduino.cc> | 2011-11-19 16:23:19 -0500 |
commit | b86a613d99961e9d35da685fefce39647bafa9de (patch) | |
tree | aa009ff8c4a51d8410bd507837b212965e0dfd98 /cores/arduino/Stream.cpp | |
parent | ee6ea5c26cfe7abe12dcf1dcbb3b49763d97cc31 (diff) |
readBytes() and readBytesUntil() handle zero bytes and return # of bytes read.
http://code.google.com/p/arduino/issues/detail?id=586
Diffstat (limited to 'cores/arduino/Stream.cpp')
-rw-r--r-- | cores/arduino/Stream.cpp | 45 |
1 files changed, 23 insertions, 22 deletions
diff --git a/cores/arduino/Stream.cpp b/cores/arduino/Stream.cpp index a7d9d38..5fad8dd 100644 --- a/cores/arduino/Stream.cpp +++ b/cores/arduino/Stream.cpp @@ -208,11 +208,20 @@ float Stream::parseFloat(char skipChar){ } // read characters from stream into buffer -// terminates if length characters have been read, null is detected or timeout (see setTimeout) -// returns the number of characters placed in the buffer (0 means no valid data found) -int Stream::readBytes( char *buffer, size_t length) +// terminates if length characters have been read, or timeout (see setTimeout) +// returns the number of characters placed in the buffer +// the buffer is NOT null terminated. +// +size_t Stream::readBytes(char *buffer, size_t length) { - return readBytesUntil( 0, buffer, length); + size_t count = 0; + while (count < length) { + int c = timedRead(); + if (c < 0) break; + *buffer++ = (char)c; + count++; + } + return count; } @@ -220,24 +229,16 @@ int Stream::readBytes( char *buffer, size_t length) // terminates if length characters have been read, timeout, or if the terminator character detected // returns the number of characters placed in the buffer (0 means no valid data found) -int Stream::readBytesUntil( char terminator, char *buffer, size_t length) +size_t Stream::readBytesUntil(char terminator, char *buffer, size_t length) { - unsigned int index = 0; - *buffer = 0; - while(index < length-1 ){ - int c = timedRead(); - if( c <= 0 ){ - return 0; // timeout returns 0 ! - } - else if( c == terminator){ - buffer[index] = 0; // terminate the string - return index; // data got successfully - } - else{ - buffer[index++] = (char)c; - } - } - buffer[index] = 0; - return index; // here if buffer is full before detecting the terminator + if (length < 1) return 0; + size_t index = 0; + while (index < length) { + int c = timedRead(); + if (c < 0 || c == terminator) break; + *buffer++ = (char)c; + index++; + } + return index; // return number of characters, not including null terminator } |