-
Notifications
You must be signed in to change notification settings - Fork 33
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #482 from projectdiscovery/introduce_safewriter
introduce safewriter
- Loading branch information
Showing
2 changed files
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
package ioutil | ||
|
||
import ( | ||
"errors" | ||
"io" | ||
"sync" | ||
) | ||
|
||
// SafeWriter is a thread-safe wrapper for io.Writer | ||
type SafeWriter struct { | ||
writer io.Writer // The underlying writer | ||
mutex *sync.Mutex // Mutex for ensuring thread-safety | ||
} | ||
|
||
// NewSafeWriter creates and returns a new SafeWriter | ||
func NewSafeWriter(writer io.Writer) (*SafeWriter, error) { | ||
// Check if the provided writer is nil | ||
if writer == nil { | ||
return nil, errors.New("writer is nil") | ||
} | ||
|
||
safeWriter := &SafeWriter{ | ||
writer: writer, | ||
mutex: &sync.Mutex{}, | ||
} | ||
return safeWriter, nil | ||
} | ||
|
||
// Write implements the io.Writer interface in a thread-safe manner | ||
func (sw *SafeWriter) Write(p []byte) (n int, err error) { | ||
sw.mutex.Lock() | ||
defer sw.mutex.Unlock() | ||
|
||
if sw.writer == nil { | ||
return 0, io.ErrClosedPipe | ||
} | ||
return sw.writer.Write(p) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
package ioutil | ||
|
||
import ( | ||
"strings" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
func TestSafeWriter(t *testing.T) { | ||
t.Run("success", func(t *testing.T) { | ||
var sb strings.Builder | ||
sw, err := NewSafeWriter(&sb) | ||
require.Nil(t, err) | ||
_, err = sw.Write([]byte("test")) | ||
require.Nil(t, err) | ||
require.Equal(t, "test", sb.String()) | ||
}) | ||
|
||
t.Run("failure", func(t *testing.T) { | ||
sw, err := NewSafeWriter(nil) | ||
require.NotNil(t, err) | ||
require.Nil(t, sw) | ||
}) | ||
} |