fn: add Collect+CollertErr function for iterators

In this commit, we introduce a new utility function `Collect` to the fn
package. This function drains all elements from an iterator and returns
them as a slice. This is particularly useful when transitioning from
iterator-based APIs to code that expects slices, allowing for gradual
migration to the new iterator patterns.

The fn module's go.mod is also updated to require Go 1.23, which is
necessary for the built-in iter.Seq type support.

The replace directive will be removed once the fn package changes are
merged and a new version is tagged.
This commit is contained in:
Olaoluwa Osuntokun
2025-08-04 15:54:59 -07:00
parent b09b20c699
commit 015875e455
4 changed files with 33 additions and 3 deletions

View File

@@ -1,6 +1,6 @@
module github.com/lightningnetwork/lnd/fn/v2
go 1.19
go 1.23
require (
github.com/stretchr/testify v1.8.1

29
fn/iter.go Normal file
View File

@@ -0,0 +1,29 @@
package fn
import "iter"
// Collect drains all of the elements from the passed iterator, returning a
// slice of the contents.
func Collect[T any](seq iter.Seq[T]) []T {
var ret []T
for i := range seq {
ret = append(ret, i)
}
return ret
}
// CollectErr drains all of the elements from the passed iterator with error
// handling, returning a slice of the contents and the first error encountered.
func CollectErr[T any](seq iter.Seq2[T, error]) ([]T, error) {
var ret []T
for val, err := range seq {
if err != nil {
return ret, err
}
ret = append(ret, val)
}
return ret, nil
}

3
go.mod
View File

@@ -206,6 +206,9 @@ require (
// store have been included in a tagged sqldb version.
replace github.com/lightningnetwork/lnd/sqldb => ./sqldb
// Replace fn package to use local version with iterator Collect function.
replace github.com/lightningnetwork/lnd/fn/v2 => ./fn
// This replace is for https://github.com/advisories/GHSA-25xm-hr59-7c27
replace github.com/ulikunitz/xz => github.com/ulikunitz/xz v0.5.11

2
go.sum
View File

@@ -374,8 +374,6 @@ github.com/lightningnetwork/lnd/cert v1.2.2 h1:71YK6hogeJtxSxw2teq3eGeuy4rHGKcFf
github.com/lightningnetwork/lnd/cert v1.2.2/go.mod h1:jQmFn/Ez4zhDgq2hnYSw8r35bqGVxViXhX6Cd7HXM6U=
github.com/lightningnetwork/lnd/clock v1.1.1 h1:OfR3/zcJd2RhH0RU+zX/77c0ZiOnIMsDIBjgjWdZgA0=
github.com/lightningnetwork/lnd/clock v1.1.1/go.mod h1:mGnAhPyjYZQJmebS7aevElXKTFDuO+uNFFfMXK1W8xQ=
github.com/lightningnetwork/lnd/fn/v2 v2.0.8 h1:r2SLz7gZYQPVc3IZhU82M66guz3Zk2oY+Rlj9QN5S3g=
github.com/lightningnetwork/lnd/fn/v2 v2.0.8/go.mod h1:TOzwrhjB/Azw1V7aa8t21ufcQmdsQOQMDtxVOQWNl8s=
github.com/lightningnetwork/lnd/healthcheck v1.2.6 h1:1sWhqr93GdkWy4+6U7JxBfcyZIE78MhIHTJZfPx7qqI=
github.com/lightningnetwork/lnd/healthcheck v1.2.6/go.mod h1:Mu02um4CWY/zdTOvFje7WJgJcHyX2zq/FG3MhOAiGaQ=
github.com/lightningnetwork/lnd/kvdb v1.4.16 h1:9BZgWdDfjmHRHLS97cz39bVuBAqMc4/p3HX1xtUdbDI=