micropython / micropython/micropython
RFC: Ways to enable allocation-free buffer operations
Nobody has claimed this yet.
- Dominant language
- C
- Stars
- 22.1k
- Forks
- 9k
- Avg merge
- 6d 4h
- Merged PRs (30d)
- 16
Description
It is difficult to perform I2C reads of variable length data in an interrupt context. I tried pre-allocating a buffer, creating a memoryview, and issuing
i2c.readfrom_into(addr, mv[0 : num_bytes]) # mv is the memoryview instance
Alas mv[x:y] instantiates a new memoryview causing an allocation. Consequently with a preallocated buffer you are forced to fill the entire buffer if allocation is to be avoided. Depending on the remote hardware this may be impossible.
In practice you might want to read into a buffer which has already accumulated some data (eg a circular buffer). The length of data to be read may also change at runtime. An option would be for readfrom_into to take two additional parameters: offset and size. Reading would start at offset and end when size bytes were received or the buffer became full. Defaults (0 and -1) could be used to provide existing behaviour.
This seems rather widespread. Code which reads into, and writes from, preallocated buffers appears to offer the promise of allocation-free operation but falls at the last hurdle of actually delivering it.
Or is there any way to ensure memoryview objects don't have this side-effect? The following fails:
from pyb import Timer
a = bytearray(10)
m = memoryview(a)
b = bytearray((1,2))
def cb(_):
m[3:5] = b # bang
t = Timer(1, freq=1, callback=cb)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the memoryview slicing and assignment behavior and the readfrom_into entry point described in the issue, then compare the proposed offset and size semantics with the Timer callback example. Done would require an agreed allocation-free buffer API, but the RFC names no file or test to update.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- embedded-iot
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100