woodpecker/stream/stream_impl.go

73 lines
1.4 KiB
Go
Raw Normal View History

2016-04-13 00:27:24 +00:00
package stream
import (
2016-04-23 00:35:32 +00:00
"fmt"
2016-04-13 00:27:24 +00:00
"io"
"sync"
)
2016-04-23 00:35:32 +00:00
type stream struct {
sync.Mutex
writers map[string]*writer
2016-04-13 00:27:24 +00:00
}
2016-04-23 00:35:32 +00:00
// New returns a new in-memory implementation of Stream.
func New() Stream {
return &stream{
writers: map[string]*writer{},
2016-04-13 00:27:24 +00:00
}
}
2016-04-23 00:35:32 +00:00
// Reader returns an io.Reader for reading from to the stream.
func (s *stream) Reader(name string) (io.ReadCloser, error) {
2016-04-23 00:35:32 +00:00
s.Lock()
defer s.Unlock()
2016-04-13 00:27:24 +00:00
2016-04-23 00:35:32 +00:00
if !s.exists(name) {
return nil, fmt.Errorf("stream: cannot read stream %s, not found", name)
2016-04-13 00:27:24 +00:00
}
2016-04-23 00:35:32 +00:00
return s.writers[name].Reader()
2016-04-13 00:27:24 +00:00
}
2016-04-23 00:35:32 +00:00
// Writer returns an io.WriteCloser for writing to the stream.
func (s *stream) Writer(name string) (io.WriteCloser, error) {
s.Lock()
defer s.Unlock()
2016-04-13 00:27:24 +00:00
2016-04-23 00:35:32 +00:00
if !s.exists(name) {
return nil, fmt.Errorf("stream: cannot write stream %s, not found", name)
}
return s.writers[name], nil
2016-04-13 00:27:24 +00:00
}
2016-04-23 00:35:32 +00:00
// Create creates a new stream.
func (s *stream) Create(name string) error {
s.Lock()
defer s.Unlock()
if s.exists(name) {
return fmt.Errorf("stream: cannot create stream %s, already exists", name)
}
2016-04-13 00:27:24 +00:00
2016-04-23 00:35:32 +00:00
s.writers[name] = newWriter()
2016-04-13 00:27:24 +00:00
return nil
}
2016-04-23 00:35:32 +00:00
// Delete deletes the stream by key.
func (s *stream) Delete(name string) error {
s.Lock()
defer s.Unlock()
if !s.exists(name) {
return fmt.Errorf("stream: cannot delete stream %s, not found", name)
}
2016-04-23 00:50:28 +00:00
w := s.writers[name]
2016-04-23 00:35:32 +00:00
delete(s.writers, name)
2016-04-23 00:50:28 +00:00
return w.Close()
2016-04-13 00:27:24 +00:00
}
2016-04-23 00:35:32 +00:00
func (s *stream) exists(name string) bool {
_, exists := s.writers[name]
return exists
2016-04-13 00:27:24 +00:00
}