Skip to content

Commit

Permalink
Filter.Clone()
Browse files Browse the repository at this point in the history
  • Loading branch information
fiatjaf committed Nov 6, 2023
1 parent d6baa2f commit f5cd0c1
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 2 deletions.
33 changes: 31 additions & 2 deletions filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,11 +101,11 @@ func FilterEqual(a Filter, b Filter) bool {
}
}

if a.Since != b.Since {
if !arePointerValuesEqual(a.Since, b.Since) {
return false
}

if a.Until != b.Until {
if !arePointerValuesEqual(a.Until, b.Until) {
return false
}

Expand All @@ -115,3 +115,32 @@ func FilterEqual(a Filter, b Filter) bool {

return true
}

func (ef Filter) Clone() Filter {
clone := Filter{
IDs: slices.Clone(ef.IDs),
Authors: slices.Clone(ef.Authors),
Kinds: slices.Clone(ef.Kinds),
Limit: ef.Limit,
Search: ef.Search,
}

if ef.Tags != nil {
clone.Tags = make(TagMap, len(ef.Tags))
for k, v := range ef.Tags {
clone.Tags[k] = slices.Clone(v)
}
}

if ef.Since != nil {
since := *ef.Since
clone.Since = &since
}

if ef.Until != nil {
until := *ef.Until
clone.Until = &until
}

return clone
}
38 changes: 38 additions & 0 deletions filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,3 +91,41 @@ func TestFilterEquality(t *testing.T) {
t.Error("kinds filters shouldn't be equal")
}
}

func TestFilterClone(t *testing.T) {
ts := Now() - 60*60
flt := Filter{
Kinds: []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9},
Tags: TagMap{"letter": {"a", "b"}, "fruit": {"banana"}},
Since: &ts,
IDs: []string{"9894b4b5cb5166d23ee8899a4151cf0c66aec00bde101982a13b8e8ceb972df9"},
}
clone := flt.Clone()
if !FilterEqual(flt, clone) {
t.Errorf("clone is not equal:\n %v !=\n %v", flt, clone)
}

clone1 := flt.Clone()
clone1.IDs = append(clone1.IDs, "88f0c63fcb93463407af97a5e5ee64fa883d107ef9e558472c4eb9aaaefa459d")
if FilterEqual(flt, clone1) {
t.Error("modifying the clone ids should cause it to not be equal anymore")
}

clone2 := flt.Clone()
clone2.Tags["letter"] = append(clone2.Tags["letter"], "c")
if FilterEqual(flt, clone2) {
t.Error("modifying the clone tag items should cause it to not be equal anymore")
}

clone3 := flt.Clone()
clone3.Tags["g"] = []string{"drt"}
if FilterEqual(flt, clone3) {
t.Error("modifying the clone tag map should cause it to not be equal anymore")
}

clone4 := flt.Clone()
*clone4.Since++
if FilterEqual(flt, clone4) {
t.Error("modifying the clone since should cause it to not be equal anymore")
}
}
10 changes: 10 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,13 @@ func IsValidRelayURL(u string) bool {
}
return true
}

func arePointerValuesEqual[V comparable](a *V, b *V) bool {
if a == nil && b == nil {
return true
}
if a != nil && b != nil {
return *a == *b
}
return false
}

0 comments on commit f5cd0c1

Please sign in to comment.