From ffeff5570692c019c734e3ca28db85bc48430f7f Mon Sep 17 00:00:00 2001 From: Takeshi Yoneda Date: Sat, 24 Oct 2020 05:04:32 +0900 Subject: [PATCH] wasm: use the fixed length buffer for putchar Signed-off-by: mathetake --- src/runtime/runtime_wasm.go | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/src/runtime/runtime_wasm.go b/src/runtime/runtime_wasm.go index e37d432e..fdea0950 100644 --- a/src/runtime/runtime_wasm.go +++ b/src/runtime/runtime_wasm.go @@ -18,21 +18,30 @@ func fd_write(id uint32, iovs *__wasi_iovec_t, iovs_len uint, nwritten *uint) (e func postinit() {} +const ( + putcharBufferSize = 120 + stdout = 1 +) + // Using global variables to avoid heap allocation. var ( - putcharBuf = byte(0) - putcharIOVec = __wasi_iovec_t{ - buf: unsafe.Pointer(&putcharBuf), - bufLen: 1, + putcharBuffer = [putcharBufferSize]byte{} + putcharPosition uint = 0 + putcharIOVec = __wasi_iovec_t{ + buf: unsafe.Pointer(&putcharBuffer[0]), } + putcharNWritten uint ) func putchar(c byte) { - // write to stdout - const stdout = 1 - var nwritten uint - putcharBuf = c - fd_write(stdout, &putcharIOVec, 1, &nwritten) + putcharBuffer[putcharPosition] = c + putcharPosition++ + + if c == '\n' || putcharPosition >= putcharBufferSize { + putcharIOVec.bufLen = putcharPosition + fd_write(stdout, &putcharIOVec, 1, &putcharNWritten) + putcharPosition = 0 + } } // Abort executes the wasm 'unreachable' instruction.