github.com/wfusion/gofusion@v1.1.14/common/utils/clone/register.go (about)

     1  // Copyright 2022 Huan Du. All rights reserved.
     2  // Licensed under the MIT license that can be found in the LICENSE file.
     3  
     4  //go:build go1.19
     5  // +build go1.19
     6  
     7  package clone
     8  
     9  import (
    10  	"reflect"
    11  	"sync/atomic"
    12  )
    13  
    14  // Record the count of cloning atomic.Pointer[T] for test purpose only.
    15  var registerAtomicPointerCalled int32
    16  
    17  // RegisterAtomicPointer registers a custom clone function for atomic.Pointer[T].
    18  func RegisterAtomicPointer[T any]() {
    19  	SetCustomFunc(reflect.TypeOf(atomic.Pointer[T]{}), func(allocator *Allocator, old, new reflect.Value) {
    20  		if !old.CanAddr() {
    21  			return
    22  		}
    23  
    24  		// Clone value inside atomic.Pointer[T].
    25  		oldValue := old.Addr().Interface().(*atomic.Pointer[T])
    26  		newValue := new.Addr().Interface().(*atomic.Pointer[T])
    27  		v := oldValue.Load()
    28  		newValue.Store(v)
    29  
    30  		atomic.AddInt32(&registerAtomicPointerCalled, 1)
    31  	})
    32  }