Skip to content

Commit

Permalink
shallow copy on sets (#548)
Browse files Browse the repository at this point in the history
* shallow copy on sets

* add unit tests

* check for same pointers in shallow copy

* update

* update

* goimports
  • Loading branch information
saiskee authored Apr 19, 2024
1 parent a4c9691 commit a1fe17b
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
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

0 comments on commit a1fe17b

Please sign in to comment.