Skip to content

Provides a unified interface for wrapping io objects in a mutex

License

Notifications You must be signed in to change notification settings

hashicorp/go-gatedio

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Golang GatedIO

Build Status Go Documentation

The gatedio package provides tiny wrappers around the io.ReadWriter, io.Writer, and io.Reader interfaces to support concurrent usage and access across multiple goroutines.

This library is especially useful in tests where a bytes.Buffer may be used. Go's native bytes.Buffer is not safe across multiple goroutes and therefore must be wrapped in some kind of mutex.

Usage & Examples

API Package documentation can be found on GoDoc.

The gatedio.* functions can replace any io.Reader, io.Writer, or io.ReadWriter. This is especially useful in tests:

func TestSomething(t *testing.T) {
  buf := gatedio.NewBuffer(make(bytes.Buffer))

  go func() { buf.Write([]byte("a")) }()
  go func() { buf.Write([]byte("b")) }()
}

Please note, accessing the underlying data structure is still not safe across multiple goroutines without locking:

// This is not safe!
var b bytes.Buffer
buf := gatedio.NewBuffer(&b)

go func() { buf.Write([]byte("a")) }()

// This is still a race condition:
b.Len() // or b.Anything()

For these cases, it is better to use the GatedBytesBuffer:

buf := gatedio.BytesBuffer()

This implements all functions of a bytes.Buffer, but wraps all calls in a mutex for safe concurrent access.

Developing

To install, clone from GitHub:

$ git clone https://github.com/hashicorp/go-gatedio

Then install dependencies:

$ make updatedeps

Then test;

$ make test testrace

About

Provides a unified interface for wrapping io objects in a mutex

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published