gf/g/container/gchan/gchan.go

71 lines
1.5 KiB
Go
Raw Normal View History

// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
2019-06-09 10:33:16 +08:00
// Package gchan provides graceful channel for no panic operations.
2019-01-16 13:35:16 +08:00
//
// It's safe to call Chan.Push/Close functions repeatedly.
package gchan
import (
2019-06-12 11:21:10 +08:00
"errors"
"github.com/gogf/gf/g/container/gtype"
)
2019-06-09 10:33:16 +08:00
// Graceful channel.
type Chan struct {
2019-06-12 11:21:10 +08:00
channel chan interface{}
closed *gtype.Bool
}
2019-06-09 10:33:16 +08:00
// New creates a graceful channel with given <limit>.
func New(limit int) *Chan {
2019-06-12 11:21:10 +08:00
return &Chan{
channel: make(chan interface{}, limit),
closed: gtype.NewBool(),
}
}
// Push pushes <value> to channel.
// It is safe to be called repeatedly.
func (c *Chan) Push(value interface{}) error {
2019-06-12 11:21:10 +08:00
if c.closed.Val() {
return errors.New("channel is closed")
}
c.channel <- value
return nil
}
// Pop pops value from channel.
// If there's no value in channel, it would block to wait.
2019-06-09 10:33:16 +08:00
// If the channel is closed, it will return a nil value immediately.
func (c *Chan) Pop() interface{} {
2019-06-12 11:21:10 +08:00
return <-c.channel
}
// Close closes the channel.
// It is safe to be called repeatedly.
func (c *Chan) Close() {
2019-06-12 11:21:10 +08:00
if !c.closed.Set(true) {
close(c.channel)
}
}
// See Len.
func (c *Chan) Size() int {
2019-06-12 11:21:10 +08:00
return c.Len()
}
// Len returns the length of the channel.
func (c *Chan) Len() int {
return len(c.channel)
2019-06-12 11:21:10 +08:00
}
// Cap returns the capacity of the channel.
func (c *Chan) Cap() int {
return cap(c.channel)
}