lnwire: add MergedCopy method to CustomRecords

This commit is contained in:
Oliver Gugger 2024-09-12 17:45:26 +02:00
parent 0c6a1558d5
commit 83923c7f33
No known key found for this signature in database
GPG Key ID: 8E4256593F177720
2 changed files with 68 additions and 0 deletions

View File

@ -89,6 +89,22 @@ func (c CustomRecords) Copy() CustomRecords {
return customRecords
}
// MergedCopy creates a copy of the records and merges them with the given
// records. If the same key is present in both sets, the value from the other
// records will be used.
func (c CustomRecords) MergedCopy(other CustomRecords) CustomRecords {
copiedRecords := make(CustomRecords, len(c))
for k, v := range c {
copiedRecords[k] = v
}
for k, v := range other {
copiedRecords[k] = v
}
return copiedRecords
}
// ExtendRecordProducers extends the given records slice with the custom
// records. The resultant records slice will be sorted if the given records
// slice contains TLV types greater than or equal to MinCustomRecordsTlvType.

View File

@ -6,6 +6,7 @@ import (
"github.com/lightningnetwork/lnd/fn"
"github.com/lightningnetwork/lnd/tlv"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@ -194,3 +195,54 @@ func serializeRecordProducers(t *testing.T,
return b.Bytes()
}
func TestCustomRecordsMergedCopy(t *testing.T) {
tests := []struct {
name string
c CustomRecords
other CustomRecords
want CustomRecords
}{
{
name: "nil records",
want: make(CustomRecords),
},
{
name: "empty records",
c: make(CustomRecords),
other: make(CustomRecords),
want: make(CustomRecords),
},
{
name: "distinct records",
c: CustomRecords{
1: {1, 2, 3},
},
other: CustomRecords{
2: {4, 5, 6},
},
want: CustomRecords{
1: {1, 2, 3},
2: {4, 5, 6},
},
},
{
name: "same records, different values",
c: CustomRecords{
1: {1, 2, 3},
},
other: CustomRecords{
1: {4, 5, 6},
},
want: CustomRecords{
1: {4, 5, 6},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := tt.c.MergedCopy(tt.other)
assert.Equal(t, tt.want, result)
})
}
}