Function Serial.availableForWrite() return 63 instead of 64.

Hello Readers,

I have read that the Serial transmit buffer has a capability of holding 64 bytes. The function Serial.availableForWrite() should return that number, but instead it returns 63. Can anyone help me clarify?

Thank you in advance!

Kind regards,

Niek

The function Serial.availableForWrite() should return that number,

Where did you see that?

The availableForWrite() method tells you how many characters you can write before blocking happens.

With a 64 byte buffer, you can write 63 characters with no blocking. When you write the 64th character, the write() method is going to block until a byte has shifted out.

the implementation in HardwareSerial.cpp is

 if (head >= tail) return SERIAL_TX_BUFFER_SIZE - 1 - head + tail;
 return tail - head - 1;

empty buffer is tested as head == tail

so I think the implementation of availableForWrite is wrong
EDIT: they choose a not-ideal way to implement a ring buffer

Juraj:
the implementation in HardwareSerial.cpp is

 if (head >= tail) return SERIAL_TX_BUFFER_SIZE - 1 - head + tail;

return tail - head - 1;




empty buffer is tested as head == tail

so I think the implementation of availableForWrite is wrong

If the buffer were allowed to contain 64 bytes of data, then head would equal tail, which is the same condition as an empty buffer, so this case is not allowed. The circular buffer implemented in HardwareSerial.cpp doesn't allow its full capacity to be used (it's one byte less). (See also I've been writing ring buffers wrong all these years for a good explanation of this issue.)

christop:
If the buffer were allowed to contain 64 bytes of data, then head would equal tail, which is the same condition as an empty buffer, so this case is not allowed. The circular buffer implemented in HardwareSerial.cpp doesn't allow its full capacity to be used (it's one byte less). (See also I've been writing ring buffers wrong all these years for a good explanation of this issue.)

yes. I agree