Skip to content

Commit

Permalink
api: A generic copy function for vim25/types
Browse files Browse the repository at this point in the history
This patch provides a helper function, `Copy[T any](src T) T` for
creating exact copies of Go objects, specifically those from
vim25/types. The copy function encodes the Go object to JSON using
the vim JSON encoder. Then the copy function decodes the data to
a new instance of the same type. The function is implemented using
Go generics, so it does not depend directly on reflection (though
Go's JSON encoder does).

Signed-off-by: akutz <akutz@vmware.com>
  • Loading branch information
akutz committed Dec 10, 2024
1 parent 8b2a311 commit 5bb9901
Show file tree
Hide file tree
Showing 3 changed files with 242 additions and 0 deletions.
65 changes: 65 additions & 0 deletions vim25/types/deep_copy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
Copyright (c) 2024-2024 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package types

import (
"bytes"
)

// DeepCopyInto creates a deep-copy of src by encoding it to JSON and then
// decoding that into dst.
// Please note, empty slices or maps in src that are set to omitempty will be
// nil in the copied object.
func DeepCopyInto[T AnyType](dst *T, src T) error {
var w bytes.Buffer
e := NewJSONEncoder(&w)
if err := e.Encode(src); err != nil {
return err
}
d := NewJSONDecoder(&w)
if err := d.Decode(dst); err != nil {
return err
}
return nil
}

// MustDeepCopyInto panics if DeepCopyInto returns an error.
func MustDeepCopyInto[T AnyType](dst *T, src T) error {
if err := DeepCopyInto(dst, src); err != nil {
panic(err)
}
return nil
}

// DeepCopy creates a deep-copy of src by encoding it to JSON and then decoding
// that into a new instance of T.
// Please note, empty slices or maps in src that are set to omitempty will be
// nil in the copied object.
func DeepCopy[T AnyType](src T) (T, error) {
var dst T
err := DeepCopyInto(&dst, src)
return dst, err
}

// MustDeepCopy panics if DeepCopy returns an error.
func MustDeepCopy[T AnyType](src T) T {
dst, err := DeepCopy(src)
if err != nil {
panic(err)
}
return dst
}
173 changes: 173 additions & 0 deletions vim25/types/deep_copy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
/*
Copyright (c) 2024-2024 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package types

import (
"testing"

"github.com/google/go-cmp/cmp"
"github.com/stretchr/testify/assert"
)

func TestMustDeepCopy(t *testing.T) {
newConfigSpec := func() VirtualMachineConfigSpec {
return VirtualMachineConfigSpec{
Name: "vm-001",
GuestId: "otherGuest",
Files: &VirtualMachineFileInfo{VmPathName: "[datastore1]"},
NumCPUs: 1,
MemoryMB: 128,
DeviceChange: []BaseVirtualDeviceConfigSpec{
&VirtualDeviceConfigSpec{
Operation: VirtualDeviceConfigSpecOperationAdd,
Device: &VirtualLsiLogicController{VirtualSCSIController{
SharedBus: VirtualSCSISharingNoSharing,
VirtualController: VirtualController{
BusNumber: 0,
VirtualDevice: VirtualDevice{
Key: 1000,
},
},
}},
},
&VirtualDeviceConfigSpec{
Operation: VirtualDeviceConfigSpecOperationAdd,
FileOperation: VirtualDeviceConfigSpecFileOperationCreate,
Device: &VirtualDisk{
VirtualDevice: VirtualDevice{
Key: 0,
ControllerKey: 1000,
UnitNumber: NewInt32(10),
Backing: &VirtualDiskFlatVer2BackingInfo{
DiskMode: string(VirtualDiskModePersistent),
ThinProvisioned: NewBool(true),
VirtualDeviceFileBackingInfo: VirtualDeviceFileBackingInfo{
FileName: "[datastore1]",
},
},
},
CapacityInKB: 4000000,
},
},
&VirtualDeviceConfigSpec{
Operation: VirtualDeviceConfigSpecOperationAdd,
Device: &VirtualE1000{VirtualEthernetCard{
VirtualDevice: VirtualDevice{
Key: 0,
DeviceInfo: &Description{
Label: "Network Adapter 1",
Summary: "VM Network",
},
Backing: &VirtualEthernetCardNetworkBackingInfo{
VirtualDeviceDeviceBackingInfo: VirtualDeviceDeviceBackingInfo{
DeviceName: "VM Network",
},
},
},
AddressType: string(VirtualEthernetCardMacTypeGenerated),
}},
},
},
ExtraConfig: []BaseOptionValue{
&OptionValue{Key: "bios.bootOrder", Value: "ethernet0"},
},
}
}

t.Run("a string", func(t *testing.T) {
t.Parallel()
var dst AnyType
assert.NotPanics(t, func() {
dst = MustDeepCopy("hello")
})
assert.Equal(t, "hello", dst)
})

t.Run("a *uint8", func(t *testing.T) {
t.Parallel()
var dst AnyType
assert.NotPanics(t, func() {
dst = MustDeepCopy(New(uint8(42)))
})
assert.Equal(t, &[]uint8{42}[0], dst)
})

t.Run("a VirtualMachineConfigSpec", func(t *testing.T) {
t.Parallel()
var dst AnyType
assert.NotPanics(t, func() {
dst = MustDeepCopy(newConfigSpec())
})
assert.Equal(t, newConfigSpec(), dst)
})

t.Run("a *VirtualMachineConfigSpec", func(t *testing.T) {
t.Parallel()
var dst AnyType
assert.NotPanics(t, func() {
dst = MustDeepCopy(New(newConfigSpec()))
})
assert.Equal(t, New(newConfigSpec()), dst)
})

t.Run("a **VirtualMachineConfigSpec", func(t *testing.T) {
t.Parallel()

var dst AnyType
exp := newConfigSpec()
ptrExp := &exp
ptrPtrExp := &ptrExp

assert.NotPanics(t, func() {
dst = MustDeepCopy(New(New(newConfigSpec())))
})

assert.Equal(t, ptrPtrExp, dst)

exp.Name += "-not-equal"
assert.NotEqual(t, ptrPtrExp, dst)
})

t.Run("a VirtualMachineConfigSpec with nil DeviceChange vs empty", func(t *testing.T) {
t.Parallel()

t.Run("src is nil, exp is nil", func(t *testing.T) {
t.Parallel()
var dst AnyType
exp, src := newConfigSpec(), newConfigSpec()
exp.DeviceChange = nil
src.DeviceChange = nil
assert.NotPanics(t, func() {
dst = MustDeepCopy(src)
})
assert.Equal(t, exp, dst, cmp.Diff(exp, dst))
})

t.Run("src is empty, exp is nil", func(t *testing.T) {
t.Parallel()
var dst AnyType
exp, src := newConfigSpec(), newConfigSpec()
exp.DeviceChange = nil
src.DeviceChange = []BaseVirtualDeviceConfigSpec{}
assert.NotPanics(t, func() {
dst = MustDeepCopy(src)
})
assert.Equal(t, exp, dst, cmp.Diff(exp, dst))
})

})
}
4 changes: 4 additions & 0 deletions vim25/types/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ func EnumValuesAsStrings[T ~string](enumValues []T) []string {
return stringValues
}

func New[T any](t T) *T {
return &t
}

func NewBool(v bool) *bool {
return &v
}
Expand Down

0 comments on commit 5bb9901

Please sign in to comment.