Once I make the buffer size big enough to hold for the first write, the right output is produced, but it seems that the first write is lost if the buffer is too small.
The std.Io.Writer.write function is simply allowed to only write a portion of the provided bytes for whatever reason the underlying implementation sees fit, as long as it reports the number of bytes actually written, even if that number is zero. It is the callerâs responsibility to make sure the output stream is not corrupted by this.
If you want to make sure that the whole slice is written before the function returns, you need to use std.Io.Writer.writeAll (whichâwhen you look at the implementationâactually only calls std.Io.Writer.write in a while loop until all bytes are written).
@spiffyk explained that the contract of the interface allows this behaviour.
But the reason std.File.Writer does this is that by default File.Reader/Writer are in a mode that does positional read/writes with an internally tracked position. However, stdio are fifo files, meaning they do not allow positional reads/writes which the reader/writer detects via an error from the syscall and changes modes, but it does not reattempt the read/write and instead aborts.
With that it should still print âfirst\nâ, the reason it doesnât is that the buffer is too small, text is 6 bytes because of â\nâ, but the buffer is only 5, so it skips putting it into the buffer and goes straight to the implementation, but that doesnât do anything for reasons already explained, and itâs not in the buffer because itâs too large so it is lost.
you can create a File.Reader/Writer in streaming mode with File.[reader/writer]Streaming(buffer) which will solve this issue.