constructor: allow nil options

This can make it significantly easier to configure libp2p with optional options.
This commit is contained in:
Steven Allen
2019-04-17 16:20:02 -07:00
parent 213863abbc
commit cff9cb577c
4 changed files with 54 additions and 0 deletions

View File

@@ -242,6 +242,9 @@ type Option func(cfg *Config) error
// encountered (if any).
func (cfg *Config) Apply(opts ...Option) error {
for _, opt := range opts {
if opt == nil {
continue
}
if err := opt(cfg); err != nil {
return err
}

23
config/config_test.go Normal file
View File

@@ -0,0 +1,23 @@
package config
import (
"testing"
)
func TestNilOption(t *testing.T) {
var cfg Config
optsRun := 0
opt := func(c *Config) error {
optsRun++
return nil
}
if err := cfg.Apply(nil); err != nil {
t.Fatal(err)
}
if err := cfg.Apply(opt, nil, nil, opt, opt, nil); err != nil {
t.Fatal(err)
}
if optsRun != 3 {
t.Fatalf("expected to have handled 3 options, handled %d", optsRun)
}
}

View File

@@ -19,6 +19,9 @@ type Option = config.Option
func ChainOptions(opts ...Option) Option {
return func(cfg *Config) error {
for _, opt := range opts {
if opt == nil {
continue
}
if err := opt(cfg); err != nil {
return err
}

View File

@@ -133,3 +133,28 @@ func makeRandomHost(t *testing.T, port int) (host.Host, error) {
return New(ctx, opts...)
}
func TestChainOptions(t *testing.T) {
var cfg Config
var optsRun []int
optcount := 0
newOpt := func() Option {
index := optcount
optcount++
return func(c *Config) error {
optsRun = append(optsRun, index)
return nil
}
}
if err := cfg.Apply(newOpt(), nil, ChainOptions(newOpt(), newOpt(), ChainOptions(), ChainOptions(nil, newOpt()))); err != nil {
t.Fatal(err)
}
if optcount != len(optsRun) {
t.Errorf("expected to have handled %d options, handled %d", optcount, len(optsRun))
}
for i, x := range optsRun {
if i != x {
t.Errorf("expected opt %d, got opt %d", i, x)
}
}
}