github.com/jmigpin/editor@v1.6.0/util/chanutil/nbchan.go (about)

     1  package chanutil
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"time"
     7  )
     8  
     9  // Non-blocking channel. Note: consider using syncutil.* instead.
    10  type NBChan struct {
    11  	ch        chan interface{}
    12  	LogString string
    13  }
    14  
    15  func NewNBChan() *NBChan {
    16  	return NewNBChan2(0, "nbchan")
    17  }
    18  func NewNBChan2(n int, logS string) *NBChan {
    19  	ch := &NBChan{
    20  		ch:        make(chan interface{}, n),
    21  		LogString: logS,
    22  	}
    23  	return ch
    24  }
    25  
    26  //----------
    27  
    28  // Send now if a receiver is watching, or fails (non-blocking) with error.
    29  func (ch *NBChan) Send(v interface{}) error {
    30  	select {
    31  	case ch.ch <- v:
    32  		return nil
    33  	default:
    34  		return errors.New("failed to send")
    35  	}
    36  }
    37  
    38  // Receives or fails after timeout.
    39  func (ch *NBChan) Receive(timeout time.Duration) (interface{}, error) {
    40  	timer := time.NewTimer(timeout)
    41  	defer timer.Stop()
    42  
    43  	select {
    44  	case <-timer.C:
    45  		return nil, fmt.Errorf("%v: receive timeout", ch.LogString)
    46  	case v := <-ch.ch:
    47  		return v, nil
    48  	}
    49  }
    50  
    51  //----------
    52  
    53  func (ch *NBChan) NewBufChan(n int) {
    54  	ch.ch = make(chan interface{}, n)
    55  }
    56  
    57  // Setting the channel to zero allows a send to fail immediatly if there is no receiver waiting.
    58  func (ch *NBChan) SetBufChanToZero() {
    59  	ch.NewBufChan(0)
    60  }