8 "github.com/mitchellh/reflectwalk"
11 // Copy returns a deep copy of v.
12 func Copy(v interface{}) (interface{}, error) {
13 return Config{}.Copy(v)
16 // CopierFunc is a function that knows how to deep copy a specific type.
17 // Register these globally with the Copiers variable.
18 type CopierFunc func(interface{}) (interface{}, error)
20 // Copiers is a map of types that behave specially when they are copied.
21 // If a type is found in this map while deep copying, this function
22 // will be called to copy it instead of attempting to copy all fields.
24 // The key should be the type, obtained using: reflect.TypeOf(value with type).
26 // It is unsafe to write to this map after Copies have started. If you
27 // are writing to this map while also copying, wrap all modifications to
28 // this map as well as to Copy in a mutex.
29 var Copiers map[reflect.Type]CopierFunc = make(map[reflect.Type]CopierFunc)
31 // Must is a helper that wraps a call to a function returning
32 // (interface{}, error) and panics if the error is non-nil. It is intended
33 // for use in variable initializations and should only be used when a copy
34 // error should be a crashing case.
35 func Must(v interface{}, err error) interface{} {
37 panic("copy error: " + err.Error())
43 var errPointerRequired = errors.New("Copy argument must be a pointer when Lock is true")
46 // Lock any types that are a sync.Locker and are not a mutex while copying.
47 // If there is an RLocker method, use that to get the sync.Locker.
50 // Copiers is a map of types associated with a CopierFunc. Use the global
51 // Copiers map if this is nil.
52 Copiers map[reflect.Type]CopierFunc
55 func (c Config) Copy(v interface{}) (interface{}, error) {
56 if c.Lock && reflect.ValueOf(v).Kind() != reflect.Ptr {
57 return nil, errPointerRequired
69 err := reflectwalk.Walk(v, w)
74 // Get the result. If the result is nil, then we want to turn it
75 // into a typed nil if we can.
78 val := reflect.ValueOf(v)
79 result = reflect.Indirect(reflect.New(val.Type())).Interface()
85 // Return the key used to index interfaces types we've seen. Store the number
86 // of pointers in the upper 32bits, and the depth in the lower 32bits. This is
87 // easy to calculate, easy to match a key with our current depth, and we don't
88 // need to deal with initializing and cleaning up nested maps or slices.
89 func ifaceKey(pointers, depth int) uint64 {
90 return uint64(pointers)<<32 | uint64(depth)
101 // This stores the number of pointers we've walked over, indexed by depth.
104 // If an interface is indirected by a pointer, we need to know the type of
105 // interface to create when creating the new value. Store the interface
106 // types here, indexed by both the walk depth and the number of pointers
107 // already seen at that depth. Use ifaceKey to calculate the proper uint64
109 ifaceTypes map[uint64]reflect.Type
111 // any locks we've taken, indexed by depth
113 // take locks while walking the structure
117 func (w *walker) Enter(l reflectwalk.Location) error {
120 // ensure we have enough elements to index via w.depth
121 for w.depth >= len(w.locks) {
122 w.locks = append(w.locks, nil)
125 for len(w.ps) < w.depth+1 {
126 w.ps = append(w.ps, 0)
132 func (w *walker) Exit(l reflectwalk.Location) error {
133 locker := w.locks[w.depth]
134 w.locks[w.depth] = nil
136 defer locker.Unlock()
139 // clear out pointers and interfaces as we exit the stack
142 for k := range w.ifaceTypes {
143 mask := uint64(^uint32(0))
144 if k&mask == uint64(w.depth) {
145 delete(w.ifaceTypes, k)
150 if w.ignoreDepth > w.depth {
159 case reflectwalk.Array:
161 case reflectwalk.Map:
163 case reflectwalk.Slice:
164 w.replacePointerMaybe()
166 // Pop map off our container
167 w.cs = w.cs[:len(w.cs)-1]
168 case reflectwalk.MapValue:
169 // Pop off the key and value
172 m := w.cs[len(w.cs)-1]
174 // If mv is the zero value, SetMapIndex deletes the key form the map,
175 // or in this case never adds it. We need to create a properly typed
176 // zero value so that this key can be set.
178 mv = reflect.Zero(m.Elem().Type().Elem())
180 m.Elem().SetMapIndex(mk, mv)
181 case reflectwalk.ArrayElem:
182 // Pop off the value and the index and set it on the array
184 i := w.valPop().Interface().(int)
186 a := w.cs[len(w.cs)-1]
187 ae := a.Elem().Index(i) // storing array as pointer on stack - so need Elem() call
192 case reflectwalk.SliceElem:
193 // Pop off the value and the index and set it on the slice
195 i := w.valPop().Interface().(int)
197 s := w.cs[len(w.cs)-1]
198 se := s.Elem().Index(i)
203 case reflectwalk.Struct:
204 w.replacePointerMaybe()
206 // Remove the struct from the container stack
207 w.cs = w.cs[:len(w.cs)-1]
208 case reflectwalk.StructField:
209 // Pop off the value and the field
211 f := w.valPop().Interface().(reflect.StructField)
213 s := w.cs[len(w.cs)-1]
214 sf := reflect.Indirect(s).FieldByName(f.Name)
220 case reflectwalk.WalkLoc:
221 // Clear out the slices for GC
229 func (w *walker) Map(m reflect.Value) error {
235 // Create the map. If the map itself is nil, then just make a nil map
236 var newMap reflect.Value
238 newMap = reflect.New(m.Type())
240 newMap = wrapPtr(reflect.MakeMap(m.Type()))
243 w.cs = append(w.cs, newMap)
248 func (w *walker) MapElem(m, k, v reflect.Value) error {
252 func (w *walker) PointerEnter(v bool) error {
259 func (w *walker) PointerExit(v bool) error {
266 func (w *walker) Interface(v reflect.Value) error {
270 if w.ifaceTypes == nil {
271 w.ifaceTypes = make(map[uint64]reflect.Type)
274 w.ifaceTypes[ifaceKey(w.ps[w.depth], w.depth)] = v.Type()
278 func (w *walker) Primitive(v reflect.Value) error {
284 // IsValid verifies the v is non-zero and CanInterface verifies
285 // that we're allowed to read this value (unexported fields).
286 var newV reflect.Value
287 if v.IsValid() && v.CanInterface() {
288 newV = reflect.New(v.Type())
293 w.replacePointerMaybe()
297 func (w *walker) Slice(s reflect.Value) error {
303 var newS reflect.Value
305 newS = reflect.New(s.Type())
307 newS = wrapPtr(reflect.MakeSlice(s.Type(), s.Len(), s.Cap()))
310 w.cs = append(w.cs, newS)
315 func (w *walker) SliceElem(i int, elem reflect.Value) error {
320 // We don't write the slice here because elem might still be
321 // arbitrarily complex. Just record the index and continue on.
322 w.valPush(reflect.ValueOf(i))
327 func (w *walker) Array(a reflect.Value) error {
333 newA := reflect.New(a.Type())
335 w.cs = append(w.cs, newA)
340 func (w *walker) ArrayElem(i int, elem reflect.Value) error {
345 // We don't write the array here because elem might still be
346 // arbitrarily complex. Just record the index and continue on.
347 w.valPush(reflect.ValueOf(i))
352 func (w *walker) Struct(s reflect.Value) error {
359 if c, ok := Copiers[s.Type()]; ok {
360 // We have a Copier for this struct, so we use that copier to
361 // get the copy, and we ignore anything deeper than this.
362 w.ignoreDepth = w.depth
364 dup, err := c(s.Interface())
369 // We need to put a pointer to the value on the value stack,
370 // so allocate a new pointer and set it.
371 v = reflect.New(s.Type())
372 reflect.Indirect(v).Set(reflect.ValueOf(dup))
374 // No copier, we copy ourselves and allow reflectwalk to guide
375 // us deeper into the structure for copying.
376 v = reflect.New(s.Type())
379 // Push the value onto the value stack for setting the struct field,
380 // and add the struct itself to the containers stack in case we walk
381 // deeper so that its own fields can be modified.
383 w.cs = append(w.cs, v)
388 func (w *walker) StructField(f reflect.StructField, v reflect.Value) error {
393 // If PkgPath is non-empty, this is a private (unexported) field.
394 // We do not set this unexported since the Go runtime doesn't allow us.
396 return reflectwalk.SkipEntry
399 // Push the field onto the stack, we'll handle it when we exit
400 // the struct field in Exit...
401 w.valPush(reflect.ValueOf(f))
405 // ignore causes the walker to ignore any more values until we exit this on
406 func (w *walker) ignore() {
407 w.ignoreDepth = w.depth
410 func (w *walker) ignoring() bool {
411 return w.ignoreDepth > 0 && w.depth >= w.ignoreDepth
414 func (w *walker) pointerPeek() bool {
415 return w.ps[w.depth] > 0
418 func (w *walker) valPop() reflect.Value {
419 result := w.vals[len(w.vals)-1]
420 w.vals = w.vals[:len(w.vals)-1]
422 // If we're out of values, that means we popped everything off. In
423 // this case, we reset the result so the next pushed value becomes
425 if len(w.vals) == 0 {
432 func (w *walker) valPush(v reflect.Value) {
433 w.vals = append(w.vals, v)
435 // If we haven't set the result yet, then this is the result since
436 // it is the first (outermost) value we're seeing.
437 if w.Result == nil && v.IsValid() {
438 w.Result = v.Interface()
442 func (w *walker) replacePointerMaybe() {
443 // Determine the last pointer value. If it is NOT a pointer, then
444 // we need to push that onto the stack.
445 if !w.pointerPeek() {
446 w.valPush(reflect.Indirect(w.valPop()))
452 // If the expected type is a pointer to an interface of any depth,
453 // such as *interface{}, **interface{}, etc., then we need to convert
454 // the value "v" from *CONCRETE to *interface{} so types match for
457 // Example if v is type *Foo where Foo is a struct, v would become
458 // *interface{} instead. This only happens if we have an interface expectation
461 // For more info, see GH-16
462 if iType, ok := w.ifaceTypes[ifaceKey(w.ps[w.depth], w.depth)]; ok && iType.Kind() == reflect.Interface {
463 y := reflect.New(iType) // Create *interface{}
464 y.Elem().Set(reflect.Indirect(v)) // Assign "Foo" to interface{} (dereferenced)
465 v = y // v is now typed *interface{} (where *v = Foo)
468 for i := 1; i < w.ps[w.depth]; i++ {
469 if iType, ok := w.ifaceTypes[ifaceKey(w.ps[w.depth]-i, w.depth)]; ok {
470 iface := reflect.New(iType).Elem()
475 p := reflect.New(v.Type())
483 // if this value is a Locker, lock it and add it to the locks slice
484 func (w *walker) lock(v reflect.Value) {
489 if !v.IsValid() || !v.CanInterface() {
493 type rlocker interface {
494 RLocker() sync.Locker
497 var locker sync.Locker
499 // We can't call Interface() on a value directly, since that requires
500 // a copy. This is OK, since the pointer to a value which is a sync.Locker
501 // is also a sync.Locker.
502 if v.Kind() == reflect.Ptr {
503 switch l := v.Interface().(type) {
505 // don't lock a mutex directly
506 if _, ok := l.(*sync.RWMutex); !ok {
512 } else if v.CanAddr() {
513 switch l := v.Addr().Interface().(type) {
515 // don't lock a mutex directly
516 if _, ok := l.(*sync.RWMutex); !ok {
524 // still no callable locker
529 // don't lock a mutex directly
530 switch locker.(type) {
531 case *sync.Mutex, *sync.RWMutex:
536 w.locks[w.depth] = locker
539 // wrapPtr is a helper that takes v and always make it *v. copystructure
540 // stores things internally as pointers until the last moment before unwrapping
541 func wrapPtr(v reflect.Value) reflect.Value {
545 vPtr := reflect.New(v.Type())