io

package
v0.3.7 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2023 License: MIT Imports: 12 Imported by: 1

Documentation

Overview

Package io implements IO tools similar to what is available in Scala cats library (and Haskell IO).

Index

Constants

This section is empty.

Variables

View Source
var ErrorNPE = errors.New("nil pointer")
View Source
var ErrorTimeout = errors.New("timeout")

ErrorTimeout is an error that will be returned in case of timeout.

View Source
var IOUnit1 = Lift(fun.Unit1)

IOUnit1 is a IO[Unit] that will always return Unit1.

View Source
var MaxContinuationDepth = 1000000000

MaxContinuationDepth is equal to 1000000000. It's the maximum depth we run continuation before giving up.

Functions

func IOFuncToGoResult added in v0.3.7

func IOFuncToGoResult[A any, B any](f func(a A) IO[B]) func(A) GoResult[B]

IOFuncToGoResult converts a function that returns IO to a function that will return GoResult.

func LiftFunc added in v0.3.6

func LiftFunc[A any, B any](f func(A) B) func(A) IO[B]

LiftFunc wraps the result of function into IO.

func Memoize added in v0.3.7

func Memoize[A comparable, B any](f func(a A) IO[B]) func(A) IO[B]

Memoize returns a function that will remember the original function in a map. It's thread safe, however, not super performant.

func ObtainResult added in v0.2.0

func ObtainResult[A any](c Continuation[A]) (res A, err error)

ObtainResult executes continuation until final result is obtained.

func ParallelInExecutionContext added in v0.1.8

func ParallelInExecutionContext[A any](ec ExecutionContext) func(ios []IO[A]) IO[[]A]

ParallelInExecutionContext starts the given IOs in the provided `ExecutionContext` and waits for all results.

func RetryStrategyMaxCount added in v0.3.2

func RetryStrategyMaxCount(substring string) func(s int, err error) IO[option.Option[int]]

RetryStrategyMaxCount is a strategy that retries n times immediately.

func StartInExecutionContext added in v0.1.8

func StartInExecutionContext[A any](ec ExecutionContext) func(io IO[A]) IO[Fiber[A]]

StartInExecutionContext executes the given task in the provided ExecutionContext It'll establish a channel with callbacks, so that any number of listeners could join the returned fiber. (Simultaneously not more than MaxCallbackCount though.) When completed it'll start sending the results to the callbacks. The same value will be delivered to all listeners.

func ToChannel added in v0.0.10

func ToChannel[A any](ch chan<- A) func(A) IO[fun.Unit]

ToChannel saves the value to the channel

func ToChannelAndClose added in v0.0.10

func ToChannelAndClose[A any](ch chan<- A) func(A) IO[fun.Unit]

ToChannelAndClose sends the value to the channel and then closes the channel.

func UnsafeRunSync

func UnsafeRunSync[A any](io IO[A]) (res A, err error)

UnsafeRunSync runs the given IO[A] synchronously and returns the result.

func WithTimeout added in v0.0.10

func WithTimeout[A any](d time.Duration) func(ioa IO[A]) IO[A]

WithTimeout waits IO for completion for no longer than the provided duration. If there are no results, the IO will fail with timeout error.

Types

type Callback added in v0.0.10

type Callback[A any] func(A, error)

Callback[A] is a function that takes A and error. A is only valid if error is nil.

type Consumer added in v0.3.1

type Consumer[A any] func(A) IOUnit

Consumer can receive an instance of A and perform some operation on it.

func CoMap added in v0.3.1

func CoMap[A any, B any](ca Consumer[A], f func(b B) A) Consumer[B]

CoMap changes the input argument of the consumer.

type Continuation added in v0.2.0

type Continuation[A any] func() ResultOrContinuation[A]

Continuation represents some multistep computation. It is being used to avoid stack overflow. It's a universal way to do "trampolining".

type ExecutionContext added in v0.1.8

type ExecutionContext interface {
	// Start returns an IO which will return immediately when executed.
	// It'll place the runnable into this execution context.
	Start(neverFailingTask Runnable) IOUnit
	// Close stops receiving new tasks. Subsequent start invocations will fail.
	Close() IOUnit
}

ExecutionContext is a resource capable of running tasks in parallel. NB! This is not a safe resource and it is not intended to be used directly.

func BoundedExecutionContext added in v0.1.8

func BoundedExecutionContext(size int, queueLimit int) ExecutionContext

BoundedExecutionContext creates an execution context that will execute tasks concurrently. Simultaneously there could be as many as size executions. If there are more tasks than could be started immediately they will be placed in a queue. If the queue is exhausted, Start will block until some tasks are run. Recommended queue size is 0.

func UnboundedExecutionContext added in v0.1.8

func UnboundedExecutionContext() ExecutionContext

UnboundedExecutionContext runs each task in a new go routine.

type Fiber added in v0.0.10

type Fiber[A any] interface {
	// Join waits for results of the fiber.
	// When fiber completes, this IO will complete and return the result.
	// After this fiber is closed, all join IOs fail immediately.
	Join() IO[A]
	// Closes the fiber and stops sending callbacks.
	// After closing, the respective go routine may complete
	// This is not Cancel, it does not send any signals to the fiber.
	// The work will still be done.
	Close() IO[fun.Unit]
}

Fiber[A] is a type safe representation of Go routine. One might Join() and receive the result of the go routine. After Close() subsequent joins will fail.

func FailedFiber added in v0.2.5

func FailedFiber[A any](err error) Fiber[A]

FailedFiber creates a fiber that will fail on Join or Close with the given error.

type GoResult added in v0.0.3

type GoResult[A any] struct {
	Value A
	Error error
}

GoResult[A] is a data structure that represents the Go-style result of a function that could fail.

func JoinFiberAsGoResult added in v0.2.7

func JoinFiberAsGoResult[A any](f Fiber[A]) GoResult[A]

JoinFiberAsGoResult joins the fiber synchronously and returns GoResult.

func NewFailedGoResult added in v0.2.7

func NewFailedGoResult[A any](err error) GoResult[A]

NewFailedGoResult constructs a GoResult with an error.

func NewGoResult added in v0.2.7

func NewGoResult[A any](value A) GoResult[A]

NewGoResult constructs a GoResult.

func RunSync added in v0.1.4

func RunSync[A any](io IO[A]) GoResult[A]

RunSync is the same as UnsafeRunSync but returns GoResult[A].

type IO

type IO[A any] Continuation[A]

IO[A] represents a calculation that will yield a value of type A once executed. The calculation might as well fail. It is designed to not panic ever.

func AfterTimeout added in v0.3.5

func AfterTimeout[A any](duration time.Duration, ioa IO[A]) IO[A]

AfterTimeout sleeps the given time and then starts the other IO.

func AndThen added in v0.0.10

func AndThen[A any, B any](ioa IO[A], iob IO[B]) IO[B]

AndThen runs the first IO, ignores it's result and then runs the second one.

func Async added in v0.0.10

func Async[A any](k func(Callback[A])) IO[A]

Async[A] constructs an IO given a function that will eventually call a callback. Internally this function creates a channel and blocks on it until the function calls it.

func CloseChannel added in v0.1.0

func CloseChannel[A any](ch chan<- A) IO[fun.Unit]

CloseChannel is an IO that closes the given channel.

func ConcurrentlyFirst added in v0.0.10

func ConcurrentlyFirst[A any](ios []IO[A]) IO[A]

ConcurrentlyFirst - runs all IOs in parallel. returns the very first result. TODO: after obtaining result - cancel the other IOs.

func Delay added in v0.0.3

func Delay[A any](f func() IO[A]) IO[A]

Delay[A] wraps a function that will then return an IO.

func Eval

func Eval[A any](f func() (A, error)) IO[A]

Eval[A] constructs an IO[A] from a simple function that might fail. If there is panic in the function, it's recovered from and represented as an error.

func Fail

func Fail[A any](err error) IO[A]

Fail[A] constructs an IO[A] that fails with the given error.

func Finally added in v0.1.3

func Finally[A any](io IO[A], finalizer IO[fun.Unit]) IO[A]

Finally runs the finalizer regardless of the success of the IO. In case finalizer fails as well, the second error is printed to log.

func FireAndForget added in v0.0.10

func FireAndForget[A any](ioa IO[A]) IO[fun.Unit]

FireAndForget runs the given IO in a go routine and ignores the result It uses Fiber underneath.

func FlatMap

func FlatMap[A any, B any](ioA IO[A], f func(a A) IO[B]) IO[B]

FlatMap converts the result of IO[A] using a function that itself returns an IO[B]. It'll fail if any of IO[A] or IO[B] fail.

func FlatMapErr added in v0.0.3

func FlatMapErr[A any, B any](ioA IO[A], f func(a A) (B, error)) IO[B]

FlatMapErr converts IO[A] result using a function that might fail. It seems to be identical to MapErr.

func Fold added in v0.0.3

func Fold[A any, B any](ioA IO[A], f func(a A) IO[B], recover func(error) IO[B]) IO[B]

Fold performs different calculations based on whether IO[A] failed or succeeded.

func FoldErr added in v0.0.3

func FoldErr[A any, B any](ioA IO[A], f func(a A) (B, error), recover func(error) (B, error)) IO[B]

FoldErr folds IO using simple Go-style functions that might fail.

func FoldToGoResult added in v0.0.10

func FoldToGoResult[A any](io IO[A]) IO[GoResult[A]]

FoldToGoResult converts either value or error to go result typically it should never fail.

func ForEach added in v0.0.10

func ForEach[A any](io IO[A], cb func(a A)) IO[fun.Unit]

ForEach calls the provided callback after IO is completed.

func FromChannel added in v0.0.10

func FromChannel[A any](ch chan A) IO[A]

FromChannel reads a single value from the channel

func FromConstantGoResult added in v0.1.4

func FromConstantGoResult[A any](gr GoResult[A]) IO[A]

FromConstantGoResult converts an existing GoResult value into a fake IO. NB! This is not for normal delayed IO execution!

func FromPureEffect added in v0.1.3

func FromPureEffect(f func()) IO[fun.Unit]

FromPureEffect constructs IO from the simplest function signature.

func FromUnit added in v0.0.3

func FromUnit(f func() error) IO[fun.Unit]

FromUnit consturcts IO[fun.Unit] from a simple function that might fail.

func JoinWithTimeout added in v0.3.5

func JoinWithTimeout[A any](f Fiber[A], d time.Duration) IO[A]

JoinWithTimeout joins the given fiber and waits no more than the given duration.

func Lift

func Lift[A any](a A) IO[A]

Lift[A] constructs an IO[A] from a constant value.

func LiftPair added in v0.0.3

func LiftPair[A any](a A, err error) IO[A]

LiftPair[A] constructs an IO from constant values.

func MakeUnbufferedChannel added in v0.1.0

func MakeUnbufferedChannel[A any]() IO[chan A]

MakeUnbufferedChannel allocates a new unbufered channel.

func Map

func Map[A any, B any](ioA IO[A], f func(a A) B) IO[B]

Map converts the IO[A] result using the provided function that cannot fail.

func MapConst added in v0.3.2

func MapConst[A any, B any](ioA IO[A], b B) IO[B]

MapConst ignores the result and replaces it with the given constant.

func MapErr added in v0.0.2

func MapErr[A any, B any](ioA IO[A], f func(a A) (B, error)) IO[B]

MapErr maps the result of IO[A] using a function that might fail.

func MapSlice added in v0.3.6

func MapSlice[A any, B any](ioas IO[[]A], f func(a A) B) IO[[]B]

MapSlice converts each element of the slice inside IO[[]A] using the provided function that cannot fail.

func MeasureDuration added in v0.2.8

func MeasureDuration[A any](ioa IO[A]) IO[fun.Pair[A, time.Duration]]

MeasureDuration captures the wall time that was needed to evaluate the given IO.

func Never added in v0.0.10

func Never[A any]() IO[A]

Never is a simple IO that never returns.

func Notify added in v0.0.10

func Notify[A any](d time.Duration, value A, cb Callback[A]) IO[fun.Unit]

Notify starts a separate thread that will call the given callback after the specified time.

func NotifyToChannel added in v0.1.0

func NotifyToChannel[A any](d time.Duration, value A, ch chan A) IO[fun.Unit]

NotifyToChannel sends message to channel after specified duration.

func OnError added in v0.3.1

func OnError[A any](io IO[A], onError func(err error) IO[fun.Unit]) IO[A]

OnError executes a side effect when there is an error.

func PairParallel added in v0.2.8

func PairParallel[A any, B any](ioa IO[A], iob IO[B]) IO[fun.Pair[A, B]]

PairParallel runs two IOs in parallel and returns both results.

func PairSequentially added in v0.2.8

func PairSequentially[A any, B any](ioa IO[A], iob IO[B]) IO[fun.Pair[A, B]]

PairSequentially runs two IOs sequentially and returns both results.

func Parallel added in v0.0.10

func Parallel[A any](ios ...IO[A]) IO[[]A]

Parallel starts the given IOs in Go routines and waits for all results.

func Pure added in v0.0.3

func Pure[A any](f func() A) IO[A]

Pure[A] constructs an IO[A] from a function that cannot fail.

func Recover added in v0.0.3

func Recover[A any](io IO[A], recover func(err error) IO[A]) IO[A]

Recover handles a potential error from IO. It does not fail itself.

func Retry added in v0.3.2

func Retry[A any, S any](ioa IO[A], strategy func(s S, err error) IO[option.Option[S]], zero S) IO[A]

Retry performs the same operation a few times based on the retry strategy.

func RetryS added in v0.3.2

func RetryS[A any, S any](ioa IO[A], strategy func(s S, err error) IO[option.Option[S]], zero S) IO[fun.Pair[A, S]]

RetryS performs the same operation a few times based on the retry strategy. Also returns the last state of the error-handling strategy.

func RunAlso added in v0.3.0

func RunAlso[A any](ioa IO[A], other IOUnit) IO[A]

RunAlso runs the other IO in parallel, but returns only the result of the first IO.

func Sequence added in v0.0.5

func Sequence[A any](ioas []IO[A]) (res IO[[]A])

Sequence takes a slice of IOs and returns an IO that will contain a slice of results. It'll fail if any of the internal computations fail.

func Sleep added in v0.0.10

func Sleep(d time.Duration) IO[fun.Unit]

Sleep makes the IO sleep the specified time.

func SleepA added in v0.0.10

func SleepA[A any](d time.Duration, value A) IO[A]

SleepA sleeps and then returns the constant value.

func Start added in v0.0.10

func Start[A any](io IO[A]) IO[Fiber[A]]

Start will start the IO in a separate go-routine (actually in the global unbounded execution context). It'll establish a channel with callbacks, so that any number of listeners could join the returned fiber. When completed it'll start sending the results to the callbacks. The same value will be delivered to all listeners.

func StartInGoRoutineAndWaitForResult added in v0.0.10

func StartInGoRoutineAndWaitForResult[A any](io IO[A]) IO[A]

StartInGoRoutineAndWaitForResult - not very useful function. While it executes the IO in the go routine, the current thread is blocked.

func UnfoldGoResult added in v0.0.10

func UnfoldGoResult[A any](iogr IO[GoResult[A]]) IO[A]

UnfoldGoResult represents GoResult back to ordinary IO.

func Unptr added in v0.0.8

func Unptr[A any](ptra *A) IO[A]

Unptr retrieves the value at pointer. Fails if nil

func Wrapf added in v0.0.8

func Wrapf[A any](io IO[A], format string, args ...interface{}) IO[A]

Wrapf wraps an error with additional context information

type IOUnit added in v0.0.3

type IOUnit = IO[fun.Unit]

IOUnit is IO[Unit]

func Ignore added in v0.2.6

func Ignore[A any](ioa IO[A]) IOUnit

Ignore throws away the result of IO.

func SequenceUnit added in v0.0.5

func SequenceUnit(ious []IOUnit) (res IOUnit)

SequenceUnit takes a slice of IO units and returns IO that executes all of them. It'll fail if any of the internal computations fail.

type ResultOrContinuation added in v0.2.0

type ResultOrContinuation[A any] struct {
	Value        A
	Error        error
	Continuation *Continuation[A]
}

ResultOrContinuation is either a final result (value or error) or another continuation.

type Runnable added in v0.1.8

type Runnable func()

Runnable is a computation that performs some side effect and takes care of errors and panics. It task should never fail. In case it fails, application might run os.Exit(1).

Jump to

Keyboard shortcuts

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