Generic batches for go

Go Report Card GitHub Actions Go Reference

batch

import "github.com/ninedraft/batch"

Package batch contains a generic batch buffer, which accumulates multiple items into one slice and pass it into user defined callback.

Known issues

- goreport card does not support generics (yet);
- gomarkdoc does not support generics (yet);
- doc.go.dev does not support generics (yet);

Code quality politics

- no external non-test dependencies;
- code coverage >= 90% (~100% currently);

Index

Constants

DefaultSize is a default batch size.

const DefaultSize uint = 64

type Batcher

Batcher implements buffering (similar to bufio.Writer). Pushed values are accumulated in an internal buffer until Size number of values is reached. Then accumulated values are passed into the provided callback. If callback returns an error, then all subsequent calls of Push and Flush will return the same error until the Bather is reset with Reset.

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

package main

import (
	"context"
	"fmt"
	"github.com/ninedraft/batch"
	"strconv"
)

func main() {
	var ctx = context.Background()

	var fn = func(_ context.Context, values []string) error {
		fmt.Println(values)
		return nil
	}
	var b = batch.New(4, fn)

	for i := 0; i < 15; i++ {
		if err := b.Push(ctx, strconv.Itoa(i)); err != nil {
			panic(err)
		}
	}
	if err := b.Flush(ctx); err != nil {
		panic(err)
	}
}

Output

[0 1 2 3]
[4 5 6 7]
[8 9 10 11]
[12 13 14]

func New

func New[T any](size uint, fn Callback[T]) *Batcher[T]

New creates a new batcher with defined size and callback. If size is 0, then DefaultSize is used. If fn callback is nil, then Batcher may panic with future methods calls.

func (*BADRECV) Flush

func (b *Batcher[T]) Flush(ctx context.Context) error

Flush passes internal buffer into the callback function and resets buffer. It returns resulting error, if got one.

func (*BADRECV) Push

func (b *Batcher[T]) Push(ctx context.Context, v T) error

Push puts message into internal buffer. It will call the callback with provided context and filled buffer if len(buffer) > size. If callback is called, then Push returns resulting error. If callback is nil, then Push will panic.

func (*BADRECV) Reset

func (b *Batcher[T]) Reset(fn Callback[T])

Reset drops internal buffer and error.

func (*BADRECV) Size

func (b *Batcher[T]) Size() uint

Size returns internal buffer size.

type Callback

Callback describes a value consuming function. Values slice must be used only while function execution and must not be shared between calls.

type Callback[T any] func(ctx context.Context, values []T) error

Generated by gomarkdoc

Similar Resources

A better Generic Pool (sync.Pool)

A better Generic Pool (sync.Pool)

This package is a thin wrapper over the Pool provided by the sync package. The Pool is an essential package to obtain maximum performance by reducing the number of memory allocations.

Dec 1, 2022

Package ethtool allows control of the Linux ethtool generic netlink interface.

ethtool Package ethtool allows control of the Linux ethtool generic netlink interface.

Dec 14, 2022

rconn is a multiplatform program for creating generic reverse connections. Lets you consume services that are behind firewall or NAT without opening ports or port-forwarding.

rconn is a multiplatform program for creating generic reverse connections. Lets you consume services that are behind firewall or NAT without opening ports or port-forwarding.

rconn (r[everse] conn[ection]) is a multiplatform program for creating reverse connections. It lets you consume services that are behind NAT and/or fi

Jan 1, 2023

Go library for decoding generic map values into native Go structures and vice versa.

mapstructure mapstructure is a Go library for decoding generic map values to structures and vice versa, while providing helpful error handling. This l

Dec 28, 2022

Generic Prometheus ⟷ MQTT Bridge

Promqtt: Prometheus ⟷ MQTT Bridge Promqtt makes Prometheus MQTT capable in a truly generic way. It has no assumptions on message payloads or topic lay

Sep 18, 2022

The k8s-generic-webhook is a library to simplify the implementation of webhooks for arbitrary customer resources (CR) in the operator-sdk or controller-runtime.

k8s-generic-webhook The k8s-generic-webhook is a library to simplify the implementation of webhooks for arbitrary customer resources (CR) in the opera

Nov 24, 2022

The first generic linked list in go :dancer:

linkedlist.go The first generic linked list in go 💃 gotip first of all you need to install the master version of golang. go install golang.org/dl/got

Dec 7, 2022

Optimistic rollup tech, minimal and generic.

Opti Optimistic rollup tech, minimal and generic. VERY experimental, just exploratory code, question is: 1:1 EVM rollup with interactive fraud proof p

Aug 30, 2022

Generic error handling with panic, recover, and defer.

Generic error handling with panic, recover, and defer.

Aug 25, 2022

conditiond is a generic constraint and policy evaluator.

conditiond conditiond is a generic constraint and policy evaluator. This tool lets you define constraints in data and evaluate them at run time. It's

Dec 5, 2022

Go datastructures for a generic world

Generic data structures for Go With the upcoming release of 1.18, it's now possible to build a library of generic data structures in Go. The purpose o

Nov 9, 2021

Generic impersonation and privilege escalation with Golang. Like GenericPotato both named pipes and HTTP are supported.

This is very similar to GenericPotato - I referenced it heavily while researching. Gotato starts a named pipe or web server and waits for input. Once

Nov 9, 2022

Generic mapStringInterface tool for extracting of data for CSV output

Generic mapStringInterface tool for extracting of data for CSV output

Nov 2, 2021

An experimental generic functional utility library inspired by Lodash

go-godash An experimental generic functional utility library inspired by Lodash Implemented functions Map Reduce Sum Filter Take TakeWhile Drop DropWh

May 31, 2022

Generic templating tool with support of JSON, YAML and TOML data

gotempl Small binary used to generate files from Go Templates and data files. The following formats are supported: JSON YAML TOML Usage usage: gotempl

Jun 15, 2022

generic sort for slices in golang

slices generic sort for slices in golang basic API func BinarySearch[E constraints.Ordered](list []E, x E) int func IsSorted[E constraints.Ordered](li

Nov 3, 2022

Generic slices for Go 1.8+

Slice A simple package that makes working with slices a little bit easier with the help of generics. Install go get github.com/twharmon/slice Example

Nov 1, 2022

This package provides a generic way of deep copying Go objects

Package for copying Go values This package provides a generic way of deep copying Go objects. It is designed with performance in mind and is suitable

Nov 9, 2022

A slice backed binary heap with support for generic type parameters.

go-binaryheap A slice backed binary heap where the order can be customized by a comparison function. The main branch now requires go 1.18 because the

Jun 13, 2022
Provider-generic-workflows - A generic provider which uses argo workflows to define the backend actions.

provider-generic-workflows provider-generic-workflows is a generic provider which uses argo workflows for managing the external resource. This will re

Jan 1, 2022
Go-generic-unboxing - A quick ready to ship demo for go generic using the official example

Go generic This repo contain basic demo for installing and running go1.18beta1 v

Feb 1, 2022
Generic - Golang generic example

泛型 场景 假设需要写一个列表总数计算的函数,根据不同数据类型,我们可能分别要写 SumInts(data []int),SumFloats(data []fl

Jan 27, 2022
This library implements the pub/sub pattern in a generic way. It uses Go's generic types to declare the type of the event.

observer This library implements the pub/sub pattern in a generic way. It uses Go's generic types to declare the type of the event. Usage go get githu

Nov 16, 2022
gpool - a generic context-aware resizable goroutines pool to bound concurrency based on semaphore.

gpool - a generic context-aware resizable goroutines pool to bound concurrency. Installation $ go get github.com/sherifabdlnaby/gpool import "github.c

Oct 31, 2022
A generic oplog/replication system for microservices
A generic oplog/replication system for microservices

REST Operation Log OpLog is used as a real-time data synchronization layer between a producer and consumers. Basically, it's a generic database replic

Oct 23, 2022
a generic object pool for golang

Go Commons Pool The Go Commons Pool is a generic object pool for Golang, direct rewrite from Apache Commons Pool. Features Support custom PooledObject

Jan 5, 2023
Go library for decoding generic map values into native Go structures and vice versa.

mapstructure mapstructure is a Go library for decoding generic map values to structures and vice versa, while providing helpful error handling. This l

Jan 1, 2023
A generic fuzzing and delta-debugging framework
A generic fuzzing and delta-debugging framework

Tavor Tavor (Sindarin for woodpecker) is a framework for easily implementing and using fuzzing and delta-debugging. Its EBNF-like notation allows you

Dec 18, 2022
MongoDB generic REST server in Go
MongoDB generic REST server in Go

Mora - Mongo Rest API REST server for accessing MongoDB documents and meta data Documents When querying on collections those parameters are available:

Dec 17, 2022