Made the close functions actually idempotent

This commit is contained in:
Tracker-Friendly 2024-10-25 20:28:25 +01:00
parent 76f95f834c
commit 18bd0a477a
1 changed files with 9 additions and 8 deletions

17
main.go
View File

@ -4,6 +4,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"strings"
"sync" "sync"
"syscall/js" "syscall/js"
@ -61,13 +62,12 @@ func (r *ReadableStream) Read(p []byte) (n int, err error) {
} }
// Close closes the ReadableStream. If the stream is already closed, Close does nothing. // Close closes the ReadableStream. If the stream is already closed, Close does nothing.
// If the stream is not yet closed, it is canceled. The reader is closed and the underlying source or pipeline is terminated.
// This method is idempotent, meaning that it can be called multiple times without causing an error.
func (r *ReadableStream) Close() (err error) { func (r *ReadableStream) Close() (err error) {
defer func() { defer func() {
recovered := recover() // We don't want any errors to be thrown if the stream is already closed.
if recovered != nil { recovery := recover()
err = fmt.Errorf("panic: %v", recovered) if !strings.Contains(recovery.(string), "Can not close stream after closing or error") {
err = fmt.Errorf("panic: %v", recovery)
} }
}() }()
@ -138,9 +138,10 @@ func (w *WritableStream) Write(p []byte) (n int, err error) {
// Close closes the WritableStream. If the stream is already closed, Close does nothing. // Close closes the WritableStream. If the stream is already closed, Close does nothing.
func (w *WritableStream) Close() (err error) { func (w *WritableStream) Close() (err error) {
defer func() { defer func() {
recovered := recover() // We don't want any errors to be thrown if the stream is already closed.
if recovered != nil { recovery := recover()
err = fmt.Errorf("panic: %v", recovered) if !strings.Contains(recovery.(string), "Can not close stream after closing or error") {
err = fmt.Errorf("panic: %v", recovery)
} }
}() }()