File: memoize.go

package info (click to toggle)
golang-github-cilium-ebpf 0.11.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,776 kB
  • sloc: ansic: 1,046; makefile: 103; sh: 100
file content (26 lines) | stat: -rw-r--r-- 480 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package internal

import (
	"sync"
)

type memoizedFunc[T any] struct {
	once   sync.Once
	fn     func() (T, error)
	result T
	err    error
}

func (mf *memoizedFunc[T]) do() (T, error) {
	mf.once.Do(func() {
		mf.result, mf.err = mf.fn()
	})
	return mf.result, mf.err
}

// Memoize the result of a function call.
//
// fn is only ever called once, even if it returns an error.
func Memoize[T any](fn func() (T, error)) func() (T, error) {
	return (&memoizedFunc[T]{fn: fn}).do
}