Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

shallow copy on sets #548

Merged
merged 6 commits into from
Apr 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions changelog/v0.38.4/sets-shallowcopy.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
changelog:
- type: NON_USER_FACING
issueLink:
description: >
""
skipCI: "false"
10 changes: 10 additions & 0 deletions contrib/pkg/sets/v2/sets.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ type ResourceSet[T client.Object] interface {
Generic() sk_sets.ResourceSet
// Clone returns a deep copy of the set
Clone() ResourceSet[T]
// ShallowCopy returns a shallow copy of the set
ShallowCopy() ResourceSet[T]
}

// ResourceDelta represents the set of changes between two ResourceSets.
Expand Down Expand Up @@ -335,6 +337,14 @@ func (oldSet *resourceSet[T]) Clone() ResourceSet[T] {
return new
}

func (oldSet *resourceSet[T]) ShallowCopy() ResourceSet[T] {
newSet := make([]T, len(oldSet.set))
copy(newSet, oldSet.set)
return &resourceSet[T]{
set: newSet,
}
}

func (s *resourceSet[T]) Generic() sk_sets.ResourceSet {
set := sk_sets.NewResourceSet(nil)
s.Iter(func(_ int, v T) bool {
Expand Down
23 changes: 23 additions & 0 deletions contrib/tests/set_v2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,29 @@ var _ = Describe("PaintSetV2", func() {
})
})

It("should shallow copy", func() {
newPaint := &v1.Paint{
ObjectMeta: metav1.ObjectMeta{Name: "newPaint", Namespace: "newPaint"},
}
setA.Insert(paintA, paintBCluster2, paintC, newPaint)
Expect(setA.Has(newPaint)).To(BeTrue())
Expect(setA.Len()).To(Equal(4))

setB = setA.ShallowCopy()
Expect(setB.Has(newPaint)).To(BeTrue())
// want to make sure that the pointers are the same in both sets
// without having to construct a new list, so we just iterate
setB.Iter(func(i int, p *v1.Paint) bool {
setA.Iter(func(j int, p2 *v1.Paint) bool {
if i == j {
Expect(p == p2).To(BeTrue())
}
return true
})
return true
})
})

It("should double filter List", func() {
setA.Insert(paintA, paintBCluster2, paintC)
Expect(setA.Has(paintA)).To(BeTrue())
Expand Down
Loading