copy.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package deepcopy
  2. import (
  3. "fmt"
  4. "time"
  5. "github.com/gogo/protobuf/types"
  6. )
  7. // CopierFrom can be implemented if an object knows how to copy another into itself.
  8. type CopierFrom interface {
  9. // Copy takes the fields from src and copies them into the target object.
  10. //
  11. // Calling this method with a nil receiver or a nil src may panic.
  12. CopyFrom(src interface{})
  13. }
  14. // Copy copies src into dst. dst and src must have the same type.
  15. //
  16. // If the type has a copy function defined, it will be used.
  17. //
  18. // Default implementations for builtin types and well known protobuf types may
  19. // be provided.
  20. //
  21. // If the copy cannot be performed, this function will panic. Make sure to test
  22. // types that use this function.
  23. func Copy(dst, src interface{}) {
  24. switch dst := dst.(type) {
  25. case *types.Any:
  26. src := src.(*types.Any)
  27. dst.TypeUrl = src.TypeUrl
  28. if src.Value != nil {
  29. dst.Value = make([]byte, len(src.Value))
  30. copy(dst.Value, src.Value)
  31. } else {
  32. dst.Value = nil
  33. }
  34. case *types.Duration:
  35. src := src.(*types.Duration)
  36. *dst = *src
  37. case *time.Duration:
  38. src := src.(*time.Duration)
  39. *dst = *src
  40. case *types.Timestamp:
  41. src := src.(*types.Timestamp)
  42. *dst = *src
  43. case CopierFrom:
  44. dst.CopyFrom(src)
  45. default:
  46. panic(fmt.Sprintf("Copy for %T not implemented", dst))
  47. }
  48. }