network/frame_stream.go

44 lines
970 B
Go
Raw Normal View History

2022-10-11 17:36:09 +08:00
package network
import (
"errors"
"io"
"sync"
"git.hpds.cc/Component/network/frame"
)
2023-04-05 16:15:59 +08:00
// ErrStreamNil be returned if FrameStream underlying stream is nil.
var ErrStreamNil = errors.New("hpdsMq: frame stream underlying is nil")
2022-10-11 17:36:09 +08:00
// 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.
2023-04-05 16:15:59 +08:00
func NewFrameStream(s io.ReadWriter) frame.ReadWriter {
return &FrameStream{stream: s}
2022-10-11 17:36:09 +08:00
}
// ReadFrame reads next frame from QUIC stream.
func (fs *FrameStream) ReadFrame() (frame.Frame, error) {
if fs.stream == nil {
2023-04-05 16:15:59 +08:00
return nil, ErrStreamNil
2022-10-11 17:36:09 +08:00
}
return ParseFrame(fs.stream)
}
// WriteFrame writes a frame into QUIC stream.
2023-04-05 16:15:59 +08:00
func (fs *FrameStream) WriteFrame(frm frame.Frame) error {
2022-10-11 17:36:09 +08:00
if fs.stream == nil {
2023-04-05 16:15:59 +08:00
return ErrStreamNil
2022-10-11 17:36:09 +08:00
}
fs.mu.Lock()
defer fs.mu.Unlock()
2023-04-05 16:15:59 +08:00
_, err := fs.stream.Write(frm.Encode())
return err
2022-10-11 17:36:09 +08:00
}