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

chore: fixes mutability of the Repeat output #2140

Merged
merged 3 commits into from
Jul 24, 2023
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
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
Loading