Skip to content

Commit

Permalink
chore: fixes mutability of the Repeat output (#2140)
Browse files Browse the repository at this point in the history
## Overview
Closes #2139 

## Checklist

- [ ] New and updated code has appropriate documentation
- [ ] New and updated code has new and/or updated testing
- [ ] Required CI checks are passing
- [ ] Visual proof for any user facing features like CLI or
documentation updates
- [ ] Linked issues closed with keywords
  • Loading branch information
staheri14 authored Jul 24, 2023
1 parent ffefa9b commit ad2ee18
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
17 changes: 16 additions & 1 deletion pkg/namespace/namespace.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ func (n Namespace) IsPayForBlob() bool {
func (n Namespace) Repeat(times int) []Namespace {
ns := make([]Namespace, times)
for i := 0; i < times; i++ {
ns[i] = n
ns[i] = n.deepCopy()
}
return ns
}
Expand Down Expand Up @@ -180,3 +180,18 @@ func leftPad(b []byte, size int) []byte {
pad := make([]byte, size-len(b))
return append(pad, b...)
}

// deepCopy returns a deep copy of the Namespace object.
func (n Namespace) deepCopy() Namespace {
// Create a deep copy of the ID slice
copyID := make([]byte, len(n.ID))
copy(copyID, n.ID)

// Create a new Namespace object with the copied fields
copyNamespace := Namespace{
Version: n.Version,
ID: copyID,
}

return copyNamespace
}
13 changes: 13 additions & 0 deletions pkg/namespace/namespace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,19 @@ func TestNew(t *testing.T) {
}
}

// TestRepeatNonMutability ensures that the output of Repeat method is not mutated when the original namespace is mutated.
func TestRepeatNonMutability(t *testing.T) {
n := 10
namespace := Namespace{Version: NamespaceVersionMax, ID: []byte{1, 2, 3, 4}}
repeated := namespace.Repeat(n)
// mutate the original namespace
namespace.ID[0] = 5
// ensure the repeated namespaces are not mutated
for i := 0; i < n; i++ {
assert.NotEqual(t, repeated[i], namespace)
}
}

func TestNewV0(t *testing.T) {
type testCase struct {
name string
Expand Down

0 comments on commit ad2ee18

Please sign in to comment.