├── .github └── workflows │ └── go.yml ├── LICENSE ├── README.md ├── copy.go ├── copy_test.go ├── disable_ro.go ├── go.mod └── go.sum /.github/workflows/go.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a golang project 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go 3 | 4 | name: Go 5 | 6 | on: 7 | push: 8 | branches: [ "main" ] 9 | pull_request: 10 | branches: [ "main" ] 11 | 12 | jobs: 13 | 14 | build: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v3 18 | 19 | - name: Set up Go 20 | uses: actions/setup-go@v4 21 | with: 22 | go-version: '1.22.1' 23 | 24 | - name: Build 25 | run: go build -v ./... 26 | 27 | - name: Test 28 | run: go test -v ./... 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # deep 2 | Support for doing deep copies of (almost all) Go types. 3 | 4 | This is a from scratch implementation of the ideas from https://github.com/barkimedes/go-deepcopy (which, unfortunatelly appears to be dead) but it is faster, simpler to use for callers and supports copying unexported fields. 5 | 6 | It should support most Go types. Specificaly, it does not support functions, channels and unsafe.Pointers unless they are nil. Also it might have weird interactions with structs that include any synchronization primitives (mutexes, for example. They should still be copied but if they are usable after that is left as an exercise to the reader). 7 | 8 | One possible usage scenario would be, for example, to negate the use of the deepcopy-gen tool described in [Kubernetes code generation](https://www.redhat.com/en/blog/kubernetes-deep-dive-code-generation-customresources). For any type T, the DeepCopy method can be implemented more or less like this: 9 | 10 | ``` 11 | func (t* T) DeepCopy() *T { 12 | return deep.MustCopy(t) // This would panic on errors. 13 | } 14 | ``` 15 | 16 | ## Benchmarks 17 | 18 | | Benchmark | Iterations | Time | Bytes Allocated | Allocations | 19 | |------------------------------------|------------|----------------|-----------------|------------------| 20 | | **BenchmarkCopy_Deep-16** | **830553** | **1273 ns/op** | **1264 B/op** | **21 allocs/op** | 21 | | BenchmarkCopy_DeepCopy-16 (1) | 458072 | 2466 ns/op | 1912 B/op | 50 allocs/op | 22 | | BenchmarkCopy_CopyStructure-16 (2) | 149685 | 7836 ns/op | 6392 B/op | 168 allocs/op | 23 | | BenchmarkCopy_Clone-16 (3) | 510760 | 2188 ns/op | 1656 B/op | 22 allocs/op | 24 | 25 | (1) https://github.com/barkimedes/go-deepcopy (does not support unexported fields) 26 | 27 | (2) https://github.com/mitchellh/copystructure (does not support cycles) 28 | 29 | (3) https://github.com/huandu/go-clone 30 | -------------------------------------------------------------------------------- /copy.go: -------------------------------------------------------------------------------- 1 | package deep 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | ) 7 | 8 | // Copier is an interface that types can implement to provide their own 9 | // custom deep copy logic. The type T in Copy() (T, error) must be the 10 | // same concrete type as the receiver that implements this interface. 11 | type Copier[T any] interface { 12 | Copy() (T, error) 13 | } 14 | 15 | // Copy creates a deep copy of src. It returns the copy and a nil error in case 16 | // of success and the zero value for the type and a non-nil error on failure. 17 | func Copy[T any](src T) (T, error) { 18 | return copyInternal(src, false) 19 | } 20 | 21 | // CopySkipUnsupported creates a deep copy of src. It returns the copy and a nil 22 | // error in case of success and the zero value for the type and a non-nil error 23 | // on failure. Unsupported types are skipped (the copy will have the zero value 24 | // for the type) instead of returning an error. 25 | func CopySkipUnsupported[T any](src T) (T, error) { 26 | return copyInternal(src, true) 27 | } 28 | 29 | // MustCopy creates a deep copy of src. It returns the copy on success or panics 30 | // in case of any failure. 31 | func MustCopy[T any](src T) T { 32 | dst, err := copyInternal(src, false) 33 | if err != nil { 34 | panic(err) 35 | } 36 | 37 | return dst 38 | } 39 | 40 | type pointersMapKey struct { 41 | ptr uintptr 42 | typ reflect.Type 43 | } 44 | type pointersMap map[pointersMapKey]reflect.Value 45 | 46 | func copyInternal[T any](src T, skipUnsupported bool) (T, error) { 47 | v := reflect.ValueOf(src) 48 | 49 | // If src is the zero value for its type (e.g. an uninitialized interface, 50 | // or if T is 'any' and src is its zero value), v will be invalid. 51 | if !v.IsValid() { 52 | // This amounts to returning the zero value for T. 53 | var t T 54 | return t, nil 55 | } 56 | 57 | // Attempt to use Copier interface if src is suitable: 58 | // - A value type (struct, int, etc.) 59 | // - A non-nil pointer type 60 | // - A non-nil interface type 61 | // This logic avoids trying to call Copy() on a nil receiver if T itself 62 | // is a pointer or interface type that is nil. 63 | attemptCopier := false 64 | srcKind := v.Kind() 65 | if srcKind != reflect.Interface && srcKind != reflect.Ptr { 66 | attemptCopier = true 67 | } else { 68 | // Pointers or interface types are candidates only if they are not nil 69 | if !v.IsNil() { 70 | attemptCopier = true 71 | } 72 | } 73 | 74 | if attemptCopier { 75 | srcType := v.Type() 76 | 77 | // If T is an interface or pointer type, converting src to 'any' is generally 78 | // non-allocating for src's underlying data. 79 | if srcKind == reflect.Interface || srcKind == reflect.Ptr { 80 | if copier, ok := any(src).(Copier[T]); ok { 81 | return copier.Copy() 82 | } 83 | } else { 84 | // T is a value type (e.g. struct, array, basic type). 85 | // The any(src) conversion might allocate. 86 | // Check Implements first to avoid this allocation if T doesn't implement Copier[T]. 87 | copierInterfaceType := reflect.TypeOf((*Copier[T])(nil)).Elem() 88 | if srcType.Implements(copierInterfaceType) { 89 | // T implements Copier[T]. Now the type assertion (and potential allocation) 90 | // is justified as we expect to call the custom method. 91 | if copier, ok := any(src).(Copier[T]); ok { 92 | return copier.Copy() 93 | } 94 | } 95 | } 96 | } 97 | 98 | dst, err := recursiveCopy(v, make(pointersMap), 99 | skipUnsupported) 100 | if err != nil { 101 | var t T 102 | return t, err 103 | } 104 | 105 | return dst.Interface().(T), nil 106 | } 107 | 108 | func recursiveCopy(v reflect.Value, pointers pointersMap, 109 | skipUnsupported bool) (reflect.Value, error) { 110 | switch v.Kind() { 111 | case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, 112 | reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, 113 | reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, 114 | reflect.Complex64, reflect.Complex128, reflect.String: 115 | // Direct type, just copy it. 116 | return v, nil 117 | case reflect.Array: 118 | return recursiveCopyArray(v, pointers, skipUnsupported) 119 | case reflect.Interface: 120 | return recursiveCopyInterface(v, pointers, skipUnsupported) 121 | case reflect.Map: 122 | return recursiveCopyMap(v, pointers, skipUnsupported) 123 | case reflect.Ptr: 124 | return recursiveCopyPtr(v, pointers, skipUnsupported) 125 | case reflect.Slice: 126 | return recursiveCopySlice(v, pointers, skipUnsupported) 127 | case reflect.Struct: 128 | return recursiveCopyStruct(v, pointers, skipUnsupported) 129 | case reflect.Func, reflect.Chan, reflect.UnsafePointer: 130 | if v.IsNil() { 131 | // If we have a nil function, unsafe pointer or channel, then we 132 | // can copy it. 133 | return v, nil 134 | } else { 135 | if skipUnsupported { 136 | return reflect.Zero(v.Type()), nil 137 | } else { 138 | return reflect.Value{}, fmt.Errorf("unsuported non-nil value for type: %s", v.Type()) 139 | } 140 | } 141 | default: 142 | if skipUnsupported { 143 | return reflect.Zero(v.Type()), nil 144 | } else { 145 | return reflect.Value{}, fmt.Errorf("unsuported type: %s", v.Type()) 146 | } 147 | } 148 | } 149 | 150 | func recursiveCopyArray(v reflect.Value, pointers pointersMap, 151 | skipUnsupported bool) (reflect.Value, error) { 152 | dst := reflect.New(v.Type()).Elem() 153 | 154 | for i := 0; i < v.Len(); i++ { 155 | elem := v.Index(i) 156 | elemDst, err := recursiveCopy(elem, pointers, skipUnsupported) 157 | if err != nil { 158 | return reflect.Value{}, err 159 | } 160 | 161 | dst.Index(i).Set(elemDst) 162 | } 163 | 164 | return dst, nil 165 | } 166 | 167 | func recursiveCopyInterface(v reflect.Value, pointers pointersMap, 168 | skipUnsupported bool) (reflect.Value, error) { 169 | if v.IsNil() { 170 | // If the interface is nil, just return it. 171 | return v, nil 172 | } 173 | 174 | return recursiveCopy(v.Elem(), pointers, skipUnsupported) 175 | } 176 | 177 | func recursiveCopyMap(v reflect.Value, pointers pointersMap, 178 | skipUnsupported bool) (reflect.Value, error) { 179 | if v.IsNil() { 180 | // If the slice is nil, just return it. 181 | return v, nil 182 | } 183 | 184 | dst := reflect.MakeMap(v.Type()) 185 | 186 | for _, key := range v.MapKeys() { 187 | elem := v.MapIndex(key) 188 | elemDst, err := recursiveCopy(elem, pointers, 189 | skipUnsupported) 190 | if err != nil { 191 | return reflect.Value{}, err 192 | } 193 | 194 | dst.SetMapIndex(key, elemDst) 195 | } 196 | 197 | return dst, nil 198 | } 199 | 200 | func recursiveCopyPtr(v reflect.Value, pointers pointersMap, 201 | skipUnsupported bool) (reflect.Value, error) { 202 | // If the pointer is nil, just return it. 203 | if v.IsNil() { 204 | return v, nil 205 | } 206 | 207 | ptr := v.Pointer() 208 | typ := v.Type() 209 | key := pointersMapKey{ptr, typ} 210 | 211 | // If the pointer is already in the pointers map, return it. 212 | if dst, ok := pointers[key]; ok { 213 | return dst, nil 214 | } 215 | 216 | // Otherwise, create a new pointer and add it to the pointers map. 217 | dst := reflect.New(v.Type().Elem()) 218 | 219 | pointers[key] = dst 220 | 221 | // Proceed with the copy. 222 | elem := v.Elem() 223 | elemDst, err := recursiveCopy(elem, pointers, skipUnsupported) 224 | if err != nil { 225 | return reflect.Value{}, err 226 | } 227 | 228 | dst.Elem().Set(elemDst) 229 | 230 | return dst, nil 231 | } 232 | 233 | func recursiveCopySlice(v reflect.Value, pointers pointersMap, 234 | skipUnsupported bool) (reflect.Value, error) { 235 | if v.IsNil() { 236 | // If the slice is nil, just return it. 237 | return v, nil 238 | } 239 | 240 | dst := reflect.MakeSlice(v.Type(), v.Len(), v.Cap()) 241 | 242 | for i := 0; i < v.Len(); i++ { 243 | elem := v.Index(i) 244 | elemDst, err := recursiveCopy(elem, pointers, 245 | skipUnsupported) 246 | if err != nil { 247 | return reflect.Value{}, err 248 | } 249 | 250 | dst.Index(i).Set(elemDst) 251 | } 252 | 253 | return dst, nil 254 | } 255 | 256 | func recursiveCopyStruct(v reflect.Value, pointers pointersMap, 257 | skipUnsupported bool) (reflect.Value, error) { 258 | dst := reflect.New(v.Type()).Elem() 259 | 260 | for i := 0; i < v.NumField(); i++ { 261 | elem := v.Field(i) 262 | 263 | // If the field is unexported, we need to disable read-only mode. If it 264 | // is exported, doing this changes nothing so we just do it. We need to 265 | // do this here not because we are writting to the field (this is the 266 | // source), but because Interface() does not work if the read-only bits 267 | // are set. 268 | disableRO(&elem) 269 | 270 | elemDst, err := recursiveCopy(elem, pointers, 271 | skipUnsupported) 272 | if err != nil { 273 | return reflect.Value{}, err 274 | } 275 | 276 | dstField := dst.Field(i) 277 | 278 | // If the field is unexported, we need to disable read-only mode so we 279 | // can actually write to it. 280 | disableRO(&dstField) 281 | 282 | dstField.Set(elemDst) 283 | } 284 | 285 | return dst, nil 286 | } 287 | -------------------------------------------------------------------------------- /copy_test.go: -------------------------------------------------------------------------------- 1 | package deep 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | "testing" 7 | "unsafe" 8 | ) 9 | 10 | func TestCopy_Bool(t *testing.T) { 11 | doCopyAndCheck(t, true, false) 12 | } 13 | 14 | func TestCopy_Int(t *testing.T) { 15 | doCopyAndCheck(t, 42, false) 16 | } 17 | 18 | func TestCopy_Int8(t *testing.T) { 19 | doCopyAndCheck(t, int8(42), false) 20 | } 21 | 22 | func TestCopy_Int16(t *testing.T) { 23 | doCopyAndCheck(t, int16(42), false) 24 | } 25 | 26 | func TestCopy_Int32(t *testing.T) { 27 | doCopyAndCheck(t, int32(42), false) 28 | } 29 | 30 | func TestCopy_Int64(t *testing.T) { 31 | doCopyAndCheck(t, int64(42), false) 32 | } 33 | 34 | func TestCopy_Uint(t *testing.T) { 35 | doCopyAndCheck(t, uint(42), false) 36 | } 37 | 38 | func TestCopy_Uint8(t *testing.T) { 39 | doCopyAndCheck(t, uint8(42), false) 40 | } 41 | 42 | func TestCopy_Uint16(t *testing.T) { 43 | doCopyAndCheck(t, uint16(42), false) 44 | } 45 | 46 | func TestCopy_Uint32(t *testing.T) { 47 | doCopyAndCheck(t, uint32(42), false) 48 | } 49 | 50 | func TestCopy_Uint64(t *testing.T) { 51 | doCopyAndCheck(t, uint64(42), false) 52 | } 53 | 54 | func TestCopy_Uintptr(t *testing.T) { 55 | doCopyAndCheck(t, uintptr(42), false) 56 | } 57 | 58 | func TestCopy_Float32(t *testing.T) { 59 | doCopyAndCheck(t, float32(42), false) 60 | } 61 | 62 | func TestCopy_Float64(t *testing.T) { 63 | doCopyAndCheck(t, float64(42), false) 64 | } 65 | 66 | func TestCopy_Complex64(t *testing.T) { 67 | doCopyAndCheck(t, complex64(42), false) 68 | } 69 | 70 | func TestCopy_Complex128(t *testing.T) { 71 | doCopyAndCheck(t, complex128(42), false) 72 | } 73 | 74 | func TestCopy_String(t *testing.T) { 75 | doCopyAndCheck(t, "42", false) 76 | } 77 | 78 | func TestCopy_Array(t *testing.T) { 79 | doCopyAndCheck(t, [4]int{42, 43, 44, 45}, false) 80 | } 81 | 82 | func TestCopy_Array_Error(t *testing.T) { 83 | doCopyAndCheck(t, [1]func(){func() {}}, true) 84 | } 85 | 86 | func TestCopy_Map(t *testing.T) { 87 | doCopyAndCheck(t, map[int]string{42: "42", 43: "43", 44: "44", 45: "45"}, false) 88 | } 89 | 90 | func TestCopy_Map_Error(t *testing.T) { 91 | doCopyAndCheck(t, map[int]func(){0: func() {}}, true) 92 | } 93 | 94 | func TestCopy_Map_Nil(t *testing.T) { 95 | var m map[int]int 96 | doCopyAndCheck(t, m, false) 97 | } 98 | 99 | func TestCopy_Ptr(t *testing.T) { 100 | value := 42 101 | doCopyAndCheck(t, &value, false) 102 | } 103 | 104 | func TestCopyPtr_Error(t *testing.T) { 105 | value := func() {} 106 | doCopyAndCheck(t, &value, true) 107 | } 108 | 109 | func TestCopy_Ptr_Nil(t *testing.T) { 110 | value := (*int)(nil) 111 | doCopyAndCheck(t, value, false) 112 | } 113 | 114 | func TestCopy_Slice(t *testing.T) { 115 | doCopyAndCheck(t, []int{42, 43, 44, 45}, false) 116 | } 117 | 118 | func TestCopy_Slice_Nil(t *testing.T) { 119 | var S []int 120 | doCopyAndCheck(t, S, false) 121 | } 122 | 123 | func TestCopy_Slice_Error(t *testing.T) { 124 | doCopyAndCheck(t, []func(){func() {}}, true) 125 | } 126 | 127 | func TestCopy_Any_MapStringAny(t *testing.T) { 128 | doCopyAndCheck(t, any(map[string]any{"key": 123}), false) 129 | } 130 | 131 | func TestCopy_Struct(t *testing.T) { 132 | type S struct { 133 | A int 134 | B string 135 | } 136 | doCopyAndCheck(t, S{42, "42"}, false) 137 | } 138 | 139 | func TestCopy_Struct_Loop(t *testing.T) { 140 | type S struct { 141 | A int 142 | B *S 143 | } 144 | 145 | // Create a loop. 146 | src := S{A: 1} 147 | src.B = &src 148 | 149 | doCopyAndCheck(t, src, false) 150 | } 151 | 152 | func TestCopy_Struct_Unexported(t *testing.T) { 153 | type S struct { 154 | a int 155 | b string 156 | } 157 | 158 | doCopyAndCheck(t, S{42, "42"}, false) 159 | } 160 | 161 | func TestCopy_Struct_Error(t *testing.T) { 162 | type S struct { 163 | A func() 164 | } 165 | 166 | doCopyAndCheck(t, S{A: func() {}}, true) 167 | } 168 | 169 | func TestCopy_Func_Nil(t *testing.T) { 170 | var f func() 171 | doCopyAndCheck(t, f, false) 172 | } 173 | 174 | func TestCopy_Func_Error(t *testing.T) { 175 | doCopyAndCheck(t, func() {}, true) 176 | } 177 | 178 | func TestCopy_Chan_Nil(t *testing.T) { 179 | var c chan struct{} 180 | doCopyAndCheck(t, c, false) 181 | } 182 | 183 | func TestCopy_Chan_Error(t *testing.T) { 184 | doCopyAndCheck(t, make(chan struct{}), true) 185 | } 186 | 187 | func TestCopy_UnsafePointer_Nil(t *testing.T) { 188 | var p unsafe.Pointer 189 | doCopyAndCheck(t, p, false) 190 | } 191 | 192 | func TestCopy_UnsafePointer_Error(t *testing.T) { 193 | doCopyAndCheck(t, unsafe.Pointer(t), true) 194 | } 195 | 196 | func TestCopy_Interface_Nil(t *testing.T) { 197 | var value any 198 | doCopyAndCheck(t, value, false) 199 | } 200 | 201 | func TestCopy_Interface_Struct_Recursive_Nil(t *testing.T) { 202 | var s struct { 203 | A any 204 | } 205 | doCopyAndCheck(t, s, false) 206 | } 207 | 208 | func TestCopy_Interface_Slice_Recursive_Nil(t *testing.T) { 209 | value := []any{nil} 210 | doCopyAndCheck(t, value, false) 211 | } 212 | 213 | func TestCopy_Interface_Map_Recursive_Nil(t *testing.T) { 214 | value := map[string]any{"test": nil} 215 | doCopyAndCheck(t, value, false) 216 | } 217 | 218 | func TestCopy_DerivedType(t *testing.T) { 219 | type S int 220 | doCopyAndCheck(t, S(42), false) 221 | } 222 | 223 | func TestCopy_Struct_With_Any_Field(t *testing.T) { 224 | type S struct { 225 | A any 226 | } 227 | 228 | src := S{A: map[string]interface{}{"key1": "value1", "key2": 12345}} 229 | doCopyAndCheck(t, src, false) 230 | } 231 | 232 | func TestCopySkipUnsupported(t *testing.T) { 233 | type S struct { 234 | A int 235 | B func() 236 | C int 237 | } 238 | 239 | src := S{A: 42, B: func() {}, C: 43} 240 | dst, err := CopySkipUnsupported(src) 241 | if err != nil { 242 | t.Errorf("CopySkipUnsupported failed: %v", err) 243 | } 244 | 245 | if src.A != dst.A { 246 | t.Errorf("CopySkipUnsupported failed: expected %v, got %v", src.A, dst.A) 247 | } 248 | 249 | if src.C != dst.C { 250 | t.Errorf("CopySkipUnsupported failed: expected %v, got %v", src.C, dst.C) 251 | } 252 | 253 | if dst.B != nil { 254 | t.Errorf("CopySkipUnsupported failed: expected nil, got non-nil") 255 | } 256 | } 257 | 258 | func TestMustCopy(t *testing.T) { 259 | src := 42 260 | dst := MustCopy(src) 261 | if src != dst { 262 | t.Errorf("MustCopy failed: expected %v, got %v", src, dst) 263 | } 264 | } 265 | 266 | func TestMustCopy_Error(t *testing.T) { 267 | defer func() { 268 | if r := recover(); r == nil { 269 | t.Error("MustCopy did not panic") 270 | } 271 | }() 272 | 273 | MustCopy(func() {}) 274 | } 275 | 276 | func doCopyAndCheck[T any](t *testing.T, src T, expectError bool) { 277 | t.Helper() 278 | 279 | dst, err := Copy(src) 280 | if err != nil { 281 | if !expectError { 282 | t.Errorf("Copy failed: %v", err) 283 | } 284 | return 285 | } 286 | if !reflect.DeepEqual(dst, src) { 287 | t.Errorf("Copy failed: expected %v, got %v", src, dst) 288 | } 289 | } 290 | 291 | func BenchmarkCopy_Deep(b *testing.B) { 292 | type InnerStruct struct { 293 | Description string 294 | ID int 295 | Points *InnerStruct 296 | } 297 | 298 | type NestedStruct struct { 299 | Title string 300 | InnerData InnerStruct 301 | MoreData *NestedStruct 302 | } 303 | 304 | type ComplexStruct struct { 305 | Name string 306 | Age int 307 | Data map[string]interface{} 308 | Nested NestedStruct 309 | Pointers []*InnerStruct 310 | IsAvailable bool 311 | // Both below can be copied if they are nil. 312 | F func() 313 | C chan struct{} 314 | } 315 | 316 | src := ComplexStruct{ 317 | Name: "Complex Example", 318 | Age: 42, 319 | Data: map[string]interface{}{"key1": "value1", "key2": 12345}, 320 | IsAvailable: true, 321 | } 322 | 323 | innerInstance := InnerStruct{ 324 | Description: "Inner struct instance", 325 | ID: 1, 326 | } 327 | 328 | innerInstance.Points = &innerInstance // Cyclic reference 329 | 330 | nestedInstance := NestedStruct{ 331 | Title: "Nested Instance", 332 | InnerData: innerInstance, 333 | } 334 | 335 | nestedInstance.MoreData = &nestedInstance // Cyclic reference 336 | 337 | src.Nested = nestedInstance 338 | src.Pointers = append(src.Pointers, &innerInstance) 339 | 340 | for i := 0; i < b.N; i++ { 341 | MustCopy(src) 342 | } 343 | } 344 | 345 | func TestTrickyMemberPointer(t *testing.T) { 346 | type Foo struct { 347 | N int 348 | } 349 | type Bar struct { 350 | F *Foo 351 | P *int 352 | } 353 | 354 | foo := Foo{N: 1} 355 | bar := Bar{F: &foo, P: &foo.N} 356 | 357 | doCopyAndCheck(t, bar, false) 358 | } 359 | 360 | type CustomTypeForCopier struct { 361 | Value int 362 | F func() // Normally unsupported if non-nil. 363 | } 364 | 365 | var ( 366 | customTypeCopyCalled bool 367 | customTypeCopyErrored bool 368 | customPtrTypeCopyCalled bool 369 | ) 370 | 371 | func (ct CustomTypeForCopier) Copy() (CustomTypeForCopier, error) { 372 | customTypeCopyCalled = true 373 | if ct.F != nil && ct.Value == -1 { // Special case to return error 374 | customTypeCopyErrored = true 375 | return CustomTypeForCopier{}, fmt.Errorf("custom copy error for F") 376 | } 377 | // Example custom logic: double value, share function pointer 378 | return CustomTypeForCopier{Value: ct.Value * 2, F: ct.F}, nil 379 | } 380 | 381 | func TestCopy_CustomCopier_ValueReceiver(t *testing.T) { 382 | customTypeCopyCalled = false 383 | customTypeCopyErrored = false 384 | src := CustomTypeForCopier{Value: 10, F: func() {}} 385 | 386 | dst, err := Copy(src) 387 | 388 | if err != nil { 389 | t.Fatalf("Copy failed for CustomCopier: %v", err) 390 | } 391 | if !customTypeCopyCalled { 392 | t.Errorf("Custom Copier method was not called") 393 | } 394 | if customTypeCopyErrored { 395 | t.Errorf("Custom Copier method unexpectedly errored") 396 | } 397 | if dst.Value != 20 { // As per custom logic 398 | t.Errorf("Expected dst.Value to be 20, got %d", dst.Value) 399 | } 400 | if reflect.ValueOf(dst.F).Pointer() != reflect.ValueOf(src.F).Pointer() { 401 | t.Errorf("Expected func to be shallow copied (shared) by custom copier") 402 | } 403 | } 404 | 405 | func TestCopy_CustomCopier_ErrorCase(t *testing.T) { 406 | customTypeCopyCalled = false 407 | customTypeCopyErrored = false 408 | // Trigger error condition in custom copier 409 | src := CustomTypeForCopier{Value: -1, F: func() {}} 410 | 411 | _, err := Copy(src) 412 | 413 | if err == nil { 414 | t.Fatalf("Expected error from custom copier, got nil") 415 | } 416 | if !customTypeCopyCalled { 417 | t.Errorf("Custom Copier method was not called (for error case)") 418 | } 419 | if !customTypeCopyErrored { 420 | t.Errorf("Custom Copier method did not flag error internally") 421 | } 422 | expectedErrorMsg := "custom copy error for F" 423 | if err.Error() != expectedErrorMsg { 424 | t.Errorf("Expected error message '%s', got '%s'", expectedErrorMsg, err.Error()) 425 | } 426 | } 427 | 428 | type CustomPtrTypeForCopier struct { 429 | Value int 430 | } 431 | 432 | func (cpt *CustomPtrTypeForCopier) Copy() (*CustomPtrTypeForCopier, error) { 433 | customPtrTypeCopyCalled = true 434 | if cpt == nil { 435 | // This case should ideally not be hit if the main Copy function guards against it. 436 | return nil, fmt.Errorf("custom Copy() called on nil CustomPtrTypeForCopier receiver") 437 | } 438 | return &CustomPtrTypeForCopier{Value: cpt.Value * 3}, nil 439 | } 440 | 441 | func TestCopy_CustomCopier_PointerReceiver(t *testing.T) { 442 | customPtrTypeCopyCalled = false 443 | src := &CustomPtrTypeForCopier{Value: 5} // T is *CustomPtrTypeForCopier 444 | 445 | dst, err := Copy(src) 446 | 447 | if err != nil { 448 | t.Fatalf("Copy failed for CustomCopier with pointer receiver: %v", err) 449 | } 450 | if !customPtrTypeCopyCalled { 451 | t.Errorf("Custom Copier method (ptr receiver) was not called") 452 | } 453 | if dst.Value != 15 { 454 | t.Errorf("Expected dst.Value to be 15, got %d", dst.Value) 455 | } 456 | if dst == src { 457 | t.Errorf("Expected a new pointer from custom copier, got the same pointer") 458 | } 459 | 460 | // Test that a nil pointer of a type that implements Copier still results in a nil copy 461 | // and does not call the custom Copy method. 462 | customPtrTypeCopyCalled = false 463 | var nilSrc *CustomPtrTypeForCopier 464 | dstNil, errNil := Copy(nilSrc) 465 | if errNil != nil { 466 | t.Fatalf("Copy failed for nil CustomPtrTypeForCopier: %v", errNil) 467 | } 468 | if customPtrTypeCopyCalled { 469 | t.Errorf("Custom Copier method (ptr receiver) was called for nil input, but should not have been") 470 | } 471 | if dstNil != nil { 472 | t.Errorf("Expected nil for copied nil pointer of custom type, got %v", dstNil) 473 | } 474 | } 475 | -------------------------------------------------------------------------------- /disable_ro.go: -------------------------------------------------------------------------------- 1 | package deep 2 | 3 | import ( 4 | "reflect" 5 | "unsafe" 6 | ) 7 | 8 | func init() { 9 | // Try to make sure we can use the trick in this file. It is still possible 10 | // that things will break but we should be able to detect most of them. 11 | t := reflect.TypeOf(reflect.Value{}) 12 | if t.Kind() != reflect.Struct { 13 | panic("deep: reflect.Value is not a struct") 14 | } 15 | 16 | for i := 0; i < t.NumField(); i++ { 17 | f := t.Field(i) 18 | if f.Name == "flag" { 19 | // Check that the field is a uintptr. 20 | if f.Type.Kind() != reflect.Uintptr { 21 | panic("deep: reflect.Value.flag is not a uintptr") 22 | } 23 | 24 | flagOffset = f.Offset 25 | 26 | return 27 | } 28 | } 29 | 30 | panic("deep: reflect.Value has no flag field") 31 | } 32 | 33 | var flagOffset uintptr 34 | 35 | const ( 36 | // Lifted from go/src/reflect/value.go. 37 | flagStickyRO uintptr = 1 << 5 38 | flagEmbedRO uintptr = 1 << 6 39 | flagRO uintptr = flagStickyRO | flagEmbedRO 40 | ) 41 | 42 | // disableRO disables the read-only flag of a reflect.Value object. We use this 43 | // to allow the reflect package to access the value of an unexported field as 44 | // if it was exported (so we can copy it). 45 | // 46 | // DANGER! HERE BE DRAGONS! This is brittle and depends on internal state of a 47 | // reflect.Value object. It is not guaranteed to work in future (or previous) 48 | // versions of Go although we try to detect changes and panic immediatelly 49 | // during initialization. 50 | func disableRO(v *reflect.Value) { 51 | // Get pointer to flags. 52 | flags := (*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(v)) + flagOffset)) 53 | 54 | // Clear the read-only flags. 55 | *flags &^= flagRO 56 | } 57 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/brunoga/deep 2 | 3 | go 1.20.0 4 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/brunoga/deep/fd732f6edadce8957a5ab882038f0abbfc129b39/go.sum --------------------------------------------------------------------------------