arduino / arduino/ArduinoCore-API

Add (nonblocking) read(buf, len) to Stream class

Open
#54 9 comments 0 reactions 1 assignee Claimed by @cmaglie View on GitHub
enhancement
Dominant language
C++
Stars
306
Forks
150
PR merge metrics
No merged PRs in 30d

Description

Currently, the Stream class only has a (virtual) `read()` method to read one character at a time. It does have a `readBytes()` method to read multiple bytes at a time, but hat one blocks (with a timeout) and is not virtual, so it resorts to single-character reads.

It would be good to have a virtual multiple-byte reading method, which allows:
- Callers to easily read multiple bytes into a buffer
- Stream implementations to do efficient multiple-byte reads (e.g. prevent one SPI transfer per byte)

The Client class already has exactly this method, probably for the above reasons. Adding a virtual version of it to Stream means that Client implementations will support it out of the box.

We can also add a default implementation to the Stream class (using the existing `read()` method), that should keep all existing Stream implementations working. The default implementation would be something like:

Something like this (untested):

```
int read(uint8_t *buf, size_t size) {
if (!available())
return -1;
int res = 0;
while((int c = read()) >= 0 && size--)
buf[res] = c;
return res;
}
```

Note that this has a slightly peculiar return value: it returns -1 when
there is no data, to match the (Ethernet)Client implementation (which
returns 0 when the connection is closed). I guess it would make sense
swapping these, but that would break backward compatibility for the
Ethernet and (to a lesser degree, see arduino/Arduino#2251) the Wifi library.

How does all this sound?

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.