Skip to content

Commit

Permalink
Merge pull request #1490 from 0chain/hotfix/encrypt-buf
Browse files Browse the repository at this point in the history
fix buf size for write
  • Loading branch information
dabasov authored May 14, 2024
2 parents aa36617 + d7721f8 commit 358c397
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions wasmsdk/jsbridge/file_writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,21 @@ type FileWriter struct {
bufLen int
buf []byte
bufWriteOffset int
writeError bool
}

const writeBufferSize = 4 * 1024 * 1024 //4MB
const writeBlocks = 60

// len(p) will always be <= 64KB
func (w *FileWriter) Write(p []byte) (int, error) {
//init buffer if not initialized
if len(w.buf) == 0 {
w.buf = make([]byte, len(p)*writeBlocks)
}

//copy bytes to buf
if w.bufWriteOffset+len(p) > len(w.buf) {
w.writeError = true
return 0, io.ErrShortWrite
}
n := copy(w.buf[w.bufWriteOffset:], p)
Expand All @@ -38,6 +45,7 @@ func (w *FileWriter) Write(p []byte) (int, error) {
js.CopyBytesToJS(w.uint8Array, w.buf)
_, err := Await(w.writableStream.Call("write", w.uint8Array))
if len(err) > 0 && !err[0].IsNull() {
w.writeError = true
return 0, errors.New("file_writer: " + err[0].String())
}
//reset buffer
Expand All @@ -63,7 +71,7 @@ func (w *FileWriter) Write(p []byte) (int, error) {

func (w *FileWriter) Close() error {

if w.bufWriteOffset > 0 {
if w.bufWriteOffset > 0 && !w.writeError {
w.buf = w.buf[:w.bufWriteOffset]
uint8Array := js.Global().Get("Uint8Array").New(len(w.buf))
js.CopyBytesToJS(uint8Array, w.buf)
Expand Down Expand Up @@ -120,6 +128,5 @@ func NewFileWriter(filename string) (*FileWriter, error) {
return &FileWriter{
writableStream: writableStream[0],
fileHandle: fileHandle[0],
buf: make([]byte, writeBufferSize),
}, nil
}

0 comments on commit 358c397

Please sign in to comment.