network/frame_stream.go

44 lines
970 B
Go

package network
import (
"errors"
"io"
"sync"
"git.hpds.cc/Component/network/frame"
)
// ErrStreamNil be returned if FrameStream underlying stream is nil.
var ErrStreamNil = errors.New("hpdsMq: frame stream underlying is nil")
// FrameStream is the QUIC Stream with the minimum unit Frame.
type FrameStream struct {
// Stream is a QUIC stream.
stream io.ReadWriter
mu sync.Mutex
}
// NewFrameStream creates a new FrameStream.
func NewFrameStream(s io.ReadWriter) frame.ReadWriter {
return &FrameStream{stream: s}
}
// ReadFrame reads next frame from QUIC stream.
func (fs *FrameStream) ReadFrame() (frame.Frame, error) {
if fs.stream == nil {
return nil, ErrStreamNil
}
return ParseFrame(fs.stream)
}
// WriteFrame writes a frame into QUIC stream.
func (fs *FrameStream) WriteFrame(frm frame.Frame) error {
if fs.stream == nil {
return ErrStreamNil
}
fs.mu.Lock()
defer fs.mu.Unlock()
_, err := fs.stream.Write(frm.Encode())
return err
}