3 Star 4 Fork 1

kelvins-io/common

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
chunk.go 1.41 KB
一键复制 编辑 原始数据 按行查看 历史
雨化田 提交于 2021-09-17 23:53 +08:00 . stream helper
package stream
// Sender encapsulates a gRPC response stream and the current chunk
// that's being built.
//
// Reset, Append, [Append...], Send, Reset, Append, [Append...], Send, ...
type Sender interface {
// Reset should create a fresh response message.
Reset()
// Append should append the given item to the slice in the current response message
Append(ChunkData)
// Send should send the current response message
Send() error
}
type ChunkData interface {
Size() int
}
// New returns a new Chunker.
func NewChunker(s Sender) *Chunker { return &Chunker{s: s} }
// Chunker lets you spread items you want to send over multiple chunks.
// This type is not thread-safe.
type Chunker struct {
s Sender
size int
}
// maxMessageSize is maximum size per protobuf message
const maxMessageSize = 1 * 1024 * 1024
// Send will append an item to the current chunk and send the chunk if it is full.
func (c *Chunker) Send(it ChunkData) error {
if it == nil {
return nil
}
if c.size == 0 {
c.s.Reset()
}
itSize := it.Size()
if itSize+c.size >= maxMessageSize {
if err := c.sendResponseMsg(); err != nil {
return err
}
c.s.Reset()
}
c.s.Append(it)
c.size += itSize
return nil
}
func (c *Chunker) sendResponseMsg() error {
c.size = 0
return c.s.Send()
}
// Flush sends remaining items in the current chunk, if any.
func (c *Chunker) Flush() error {
if c.size == 0 {
return nil
}
return c.sendResponseMsg()
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/kelvins-io/common.git
git@gitee.com:kelvins-io/common.git
kelvins-io
common
common
v1.1.7

搜索帮助