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

     1  package clone
     2  
     3  import (
     4  	"time"
     5  
     6  	"github.com/shopspring/decimal"
     7  	"gorm.io/gorm"
     8  )
     9  
    10  func ComparablePtr[T comparable](s *T) (d *T) {
    11  	if s == nil {
    12  		return
    13  	}
    14  	d = new(T)
    15  	*d = *s
    16  	return
    17  }
    18  
    19  func SliceComparable[T comparable, TS ~[]T](s TS) (d TS) {
    20  	if s == nil {
    21  		return
    22  	}
    23  	d = make(TS, len(s), cap(s))
    24  	copy(d, s)
    25  	return
    26  }
    27  
    28  func SliceComparablePtr[T comparable, TS ~[]*T](s TS) (d TS) {
    29  	if s == nil {
    30  		return
    31  	}
    32  	d = make(TS, len(s), cap(s))
    33  	copy(d, s)
    34  	return
    35  }
    36  
    37  func TimePtr(s *time.Time) (d *time.Time) {
    38  	if s == nil {
    39  		return
    40  	}
    41  	d = new(time.Time)
    42  	*d = time.Date(s.Year(), s.Month(), s.Day(), s.Hour(), s.Minute(), s.Second(), s.Nanosecond(),
    43  		TimeLocationPtr(s.Location()))
    44  	return
    45  }
    46  
    47  func TimeLocationPtr(s *time.Location) (d *time.Location) {
    48  	if s == nil {
    49  		return
    50  	}
    51  	d, _ = time.LoadLocation(s.String())
    52  	return
    53  }
    54  
    55  func DecimalPtr(s *decimal.Decimal) (d *decimal.Decimal) {
    56  	if s == nil {
    57  		return
    58  	}
    59  	d = new(decimal.Decimal)
    60  	*d = s.Copy()
    61  	return
    62  }
    63  
    64  func GormModelPtr(s *gorm.Model) (d *gorm.Model) {
    65  	if s == nil {
    66  		return
    67  	}
    68  	return &gorm.Model{
    69  		ID:        s.ID,
    70  		CreatedAt: *TimePtr(&s.CreatedAt),
    71  		UpdatedAt: *TimePtr(&s.UpdatedAt),
    72  		DeletedAt: gorm.DeletedAt{
    73  			Time:  *TimePtr(&s.DeletedAt.Time),
    74  			Valid: s.DeletedAt.Valid,
    75  		},
    76  	}
    77  }
    78  
    79  type Clonable[T any] interface {
    80  	Clone() T
    81  }
    82  
    83  func Slice[T Clonable[T], TS ~[]T](s TS) (d TS) {
    84  	if s == nil {
    85  		return
    86  	}
    87  	d = make(TS, 0, len(s))
    88  	for _, item := range s {
    89  		d = append(d, item.Clone())
    90  	}
    91  	return
    92  }
    93  
    94  func Map[T Clonable[T], K comparable](s map[K]T) (d map[K]T) {
    95  	if s == nil {
    96  		return
    97  	}
    98  	d = make(map[K]T, len(s))
    99  	for k, v := range s {
   100  		d[k] = v.Clone()
   101  	}
   102  	return
   103  }