infinity

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 15, 2023 License: MIT Imports: 1 Imported by: 3

README

go-infinity-channel

.github/workflows/test.yml codecov Go Reference

go-infinity-channel is a Go package that provides an infinitely queueing channel. This package offers a Channel struct, which uses generics to hold data of any type in a queue between an input channel and an output channel. The buffer between the input and output channels queues the incoming data without any limit, making it available for the output channel. This package is useful when there's no need for buffer size constraints or when avoiding blocking during data transfers.

Synopsis

Try this on go playground!

package main

import (
	"fmt"
	"time"

	infinity "github.com/Code-Hex/go-infinity-channel"
)

func main() {
	ch := infinity.NewChannel[int]()

	go func() {
		for i := 0; i < 10; i++ {
			ch.In() <- i
			time.Sleep(100 * time.Millisecond)
		}
		ch.Close()
	}()

	for i := range ch.Out() {
		fmt.Println("Received:", i)
	}
}

Requirements

Go 1.18 or later.

Install

$ go get github.com/Code-Hex/go-infinity-channel

Caution

When reading values from the output channel, it is important to use the for range loop to avoid panics caused by receiving from a closed channel. Do not use an incremental for loop to read a fixed number of items from the output channel, as it may lead to panics if you try to read more items than were sent to the input channel.

Recommended:

for item := range ch.Out() {
	fmt.Println(item)
}

Not recommended:

// Assuming `count` is the number of items you expect to read from the channel
for i := 0; i < count; i++ {
	fmt.Println(<-ch.Out())
}

Author

Documentation

Overview

Package infinity provides an unbounded buffered channel implementation.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Channel

type Channel[T any] struct {
	// contains filtered or unexported fields
}

Channel represents an unbounded buffered channel for values of type T.

func NewChannel

func NewChannel[T any]() *Channel[T]

NewChannel creates a new unbounded buffered channel for values of type T.

func (*Channel[T]) Close

func (ch *Channel[T]) Close()

Close safely closes the input channel, ensuring that it is closed only once. It uses the sync.Once field in the Channel struct to guarantee a single execution.

func (*Channel[T]) In

func (ch *Channel[T]) In() chan<- T

In returns a send-only channel for writing values to the Channel.

func (*Channel[T]) Len

func (ch *Channel[T]) Len() int

Len returns the current number of elements in the Channel buffer.

func (*Channel[T]) Out

func (ch *Channel[T]) Out() <-chan T

Out returns a receive-only channel for reading values from the Channel.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL