Skip to content

Commit

Permalink
fix: write called without restricting size (#4)
Browse files Browse the repository at this point in the history
This commit reverts the change by switching back to real-time allocated buffer and fixed a bug caused by writing `dupBuf` instead of `dupBuf[:len(b)]`.

Signed-off-by: Gaukas Wang <i@gaukas.wang>
  • Loading branch information
gaukas committed Mar 18, 2024
1 parent 11a16e6 commit a4098d9
Showing 1 changed file with 7 additions and 13 deletions.
20 changes: 7 additions & 13 deletions tinygo/v0/examples/reverse/wrapper_transport.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
package main

import (
"io"

v0 "github.com/refraction-networking/watm/tinygo/v0"
v0net "github.com/refraction-networking/watm/tinygo/v0/net"
)

var dupBuf []byte = make([]byte, 16384) // 16k buffer for reversing

// type guard: ReverseWrappingTransport must implement [v0.WrappingTransport].
var _ v0.WrappingTransport = (*ReverseWrappingTransport)(nil)

Expand All @@ -24,29 +20,27 @@ type ReverseConn struct {
}

func (rc *ReverseConn) Read(b []byte) (n int, err error) {
n, err = rc.Conn.Read(dupBuf)
tmpBuf := make([]byte, len(b))
n, err = rc.Conn.Read(tmpBuf)
if err != nil {
return 0, err
}

if n > len(b) {
err = io.ErrShortBuffer
n = len(b)
}

// reverse all bytes read successfully so far
for i := 0; i < n; i++ {
b[i] = dupBuf[n-i-1]
b[i] = tmpBuf[n-i-1]
}

return n, err
}

func (rc *ReverseConn) Write(b []byte) (n int, err error) {
tmpBuf := make([]byte, len(b))

// reverse the bytes to be written
for i := 0; i < len(b); i++ {
dupBuf[i] = b[len(b)-i-1]
tmpBuf[i] = b[len(b)-i-1]
}

return rc.Conn.Write(dupBuf)
return rc.Conn.Write(tmpBuf[:len(b)])
}

0 comments on commit a4098d9

Please sign in to comment.