diff --git a/src/machine/buffer.go b/src/machine/buffer.go index 87031959..73ab3328 100644 --- a/src/machine/buffer.go +++ b/src/machine/buffer.go @@ -1,9 +1,10 @@ package machine -const bufferSize = 128 +import ( + "runtime/volatile" +) -//go:volatile -type volatileByte byte +const bufferSize = 128 // RingBuffer is ring buffer implementation inspired by post at // https://www.embeddedrelated.com/showthread/comp.arch.embedded/77084-1.php @@ -12,9 +13,9 @@ type volatileByte byte // members of a struct are not compiled correctly by TinyGo. // See https://github.com/tinygo-org/tinygo/issues/151 for details. type RingBuffer struct { - rxbuffer [bufferSize]volatileByte - head volatileByte - tail volatileByte + rxbuffer [bufferSize]volatile.Register8 + head volatile.Register8 + tail volatile.Register8 } // NewRingBuffer returns a new ring buffer. @@ -24,15 +25,15 @@ func NewRingBuffer() *RingBuffer { // Used returns how many bytes in buffer have been used. func (rb *RingBuffer) Used() uint8 { - return uint8(rb.head - rb.tail) + return uint8(rb.head.Get() - rb.tail.Get()) } // Put stores a byte in the buffer. If the buffer is already // full, the method will return false. func (rb *RingBuffer) Put(val byte) bool { if rb.Used() != bufferSize { - rb.head++ - rb.rxbuffer[rb.head%bufferSize] = volatileByte(val) + rb.head.Set(rb.head.Get() + 1) + rb.rxbuffer[rb.head.Get()%bufferSize].Set(val) return true } return false @@ -42,8 +43,8 @@ func (rb *RingBuffer) Put(val byte) bool { // the method will return a false as the second value. func (rb *RingBuffer) Get() (byte, bool) { if rb.Used() != 0 { - rb.tail++ - return byte(rb.rxbuffer[rb.tail%bufferSize]), true + rb.tail.Set(rb.tail.Get() + 1) + return rb.rxbuffer[rb.tail.Get()%bufferSize].Get(), true } return 0, false }