github.com/vmware/govmomi@v0.51.0/vim25/types/deep_copy.go (about)

     1  // © Broadcom. All Rights Reserved.
     2  // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries.
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package types
     6  
     7  import (
     8  	"bytes"
     9  )
    10  
    11  // DeepCopyInto creates a deep-copy of src by encoding it to JSON and then
    12  // decoding that into dst.
    13  // Please note, empty slices or maps in src that are set to omitempty will be
    14  // nil in the copied object.
    15  func DeepCopyInto[T AnyType](dst *T, src T) error {
    16  	var w bytes.Buffer
    17  	e := NewJSONEncoder(&w)
    18  	if err := e.Encode(src); err != nil {
    19  		return err
    20  	}
    21  	d := NewJSONDecoder(&w)
    22  	if err := d.Decode(dst); err != nil {
    23  		return err
    24  	}
    25  	return nil
    26  }
    27  
    28  // MustDeepCopyInto panics if DeepCopyInto returns an error.
    29  func MustDeepCopyInto[T AnyType](dst *T, src T) error {
    30  	if err := DeepCopyInto(dst, src); err != nil {
    31  		panic(err)
    32  	}
    33  	return nil
    34  }
    35  
    36  // DeepCopy creates a deep-copy of src by encoding it to JSON and then decoding
    37  // that into a new instance of T.
    38  // Please note, empty slices or maps in src that are set to omitempty will be
    39  // nil in the copied object.
    40  func DeepCopy[T AnyType](src T) (T, error) {
    41  	var dst T
    42  	err := DeepCopyInto(&dst, src)
    43  	return dst, err
    44  }
    45  
    46  // MustDeepCopy panics if DeepCopy returns an error.
    47  func MustDeepCopy[T AnyType](src T) T {
    48  	dst, err := DeepCopy(src)
    49  	if err != nil {
    50  		panic(err)
    51  	}
    52  	return dst
    53  }