ringchan package - github.com/floatdrop/ringchan - Go Packages

README

RingChan

CI Go Report Card Go Reference

RingChan is a thread-safe, fixed-capacity ring buffer implemented as a channel in Go. It mimics Go's channel behavior while providing ring-buffer semantics — meaning new items overwrite the oldest when full.

Features

  • Fixed-size buffer with overwrite behavior
  • Range-friendly: can be iterated using for ... range
  • Safe for concurrent producers and consumers

Installation

go get github.com/floatdrop/ringchan

Usage

package main

import (
	"fmt"
	"time"

	"github.com/floatdrop/ringchan"
)

func main() {
	input := make(chan string, 5)
	ring := ringchan.New(input, 3)

	go func() {
		inputs := []string{"A", "B", "C", "D", "E"}
		for _, v := range inputs {
			input <- v
		}
		close(input)
	}()

	time.Sleep(50 * time.Millisecond)

	for v := range ring.C {
		fmt.Println("Got:", v)
	}

	// Output:
	// Got: C
	// Got: D
	// Got: E
}

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

This section is empty.

This section is empty.

This section is empty.

type Ring[T any] struct {
	
	C <-chan T

	
	Dropped int
}
func New[T any](in <-chan T, size int) *Ring[T]

New creates a ring-buffered channel with fixed capacity from incoming channel. When full, new inserts will drop the oldest items to make space.

package main

import (
	"fmt"
	"time"

	"github.com/floatdrop/ringchan"
)

func main() {
	input := make(chan string, 5)
	ring := ringchan.New(input, 3)

	go func() {
		inputs := []string{"A", "B", "C", "D", "E"}
		for _, v := range inputs {
			input <- v
		}
		close(input)
	}()

	time.Sleep(50 * time.Millisecond)

	for v := range ring.C {
		fmt.Println("Got:", v)
	}

}
Output:

Got: C
Got: D
Got: E