chan.go 2.46 KB
Newer Older
1 2 3 4
package msgio

import (
	"io"
5 6

	mpool "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-msgio/mpool"
7 8
)

9 10
// Chan is a msgio duplex channel. It is used to have a channel interface
// around a msgio.Reader or Writer.
11 12 13 14 15 16
type Chan struct {
	MsgChan   chan []byte
	ErrChan   chan error
	CloseChan chan bool
}

17
// NewChan constructs a Chan with a given buffer size.
Jeromy's avatar
Jeromy committed
18 19 20 21 22 23 24 25
func NewChan(chanSize int) *Chan {
	return &Chan{
		MsgChan:   make(chan []byte, chanSize),
		ErrChan:   make(chan error, 1),
		CloseChan: make(chan bool, 2),
	}
}

26 27 28 29
// ReadFrom wraps the given io.Reader with a msgio.Reader, reads all
// messages, ands sends them down the channel.
func (s *Chan) ReadFrom(r io.Reader) {
	s.readFrom(NewReader(r))
30 31
}

32 33 34 35
// ReadFromWithPool wraps the given io.Reader with a msgio.Reader, reads all
// messages, ands sends them down the channel. Uses given Pool
func (s *Chan) ReadFromWithPool(r io.Reader, p *mpool.Pool) {
	s.readFrom(NewReaderWithPool(r, p))
Jeromy's avatar
Jeromy committed
36 37
}

38 39 40 41 42 43
// ReadFrom wraps the given io.Reader with a msgio.Reader, reads all
// messages, ands sends them down the channel.
func (s *Chan) readFrom(mr Reader) {
	// single reader, no need for Mutex
	mr.(*reader).lock = new(nullLocker)

44 45
Loop:
	for {
46
		buf, err := mr.ReadMsg()
47 48 49 50 51 52 53 54 55 56 57 58 59
		if err != nil {
			if err == io.EOF {
				break Loop // done
			}

			// unexpected error. tell the client.
			s.ErrChan <- err
			break Loop
		}

		select {
		case <-s.CloseChan:
			break Loop // told we're done
60
		case s.MsgChan <- buf:
61 62 63 64 65 66 67 68 69
			// ok seems fine. send it away
		}
	}

	close(s.MsgChan)
	// signal we're done
	s.CloseChan <- true
}

70 71
// WriteTo wraps the given io.Writer with a msgio.Writer, listens on the
// channel and writes all messages to the writer.
72 73 74 75
func (s *Chan) WriteTo(w io.Writer) {
	// new buffer per message
	// if bottleneck, cycle around a set of buffers
	mw := NewWriter(w)
76 77 78

	// single writer, no need for Mutex
	mw.(*writer).lock = new(nullLocker)
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
Loop:
	for {
		select {
		case <-s.CloseChan:
			break Loop // told we're done

		case msg, ok := <-s.MsgChan:
			if !ok { // chan closed
				break Loop
			}

			if err := mw.WriteMsg(msg); err != nil {
				if err != io.EOF {
					// unexpected error. tell the client.
					s.ErrChan <- err
				}

				break Loop
			}
		}
	}

	// signal we're done
	s.CloseChan <- true
}

105
// Close the Chan
106 107 108
func (s *Chan) Close() {
	s.CloseChan <- true
}
109 110 111 112 113 114

// nullLocker conforms to the sync.Locker interface but does nothing.
type nullLocker struct{}

func (l *nullLocker) Lock()   {}
func (l *nullLocker) Unlock() {}