github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/golang/protobuf/proto/clone.go (about)

     1  // Go support for Protocol Buffers - Google's data interchange format
     2  //
     3  // Copyright 2011 The Go Authors.  All rights reserved.
     4  // https://yougam/libraries/golang/protobuf
     5  //
     6  // Redistribution and use in source and binary forms, with or without
     7  // modification, are permitted provided that the following conditions are
     8  // met:
     9  //
    10  //     * Redistributions of source code must retain the above copyright
    11  // notice, this list of conditions and the following disclaimer.
    12  //     * Redistributions in binary form must reproduce the above
    13  // copyright notice, this list of conditions and the following disclaimer
    14  // in the documentation and/or other materials provided with the
    15  // distribution.
    16  //     * Neither the name of Google Inc. nor the names of its
    17  // contributors may be used to endorse or promote products derived from
    18  // this software without specific prior written permission.
    19  //
    20  // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    21  // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    22  // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    23  // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
    24  // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    25  // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    26  // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    27  // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
    28  // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
    29  // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    30  // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    31  
    32  // Protocol buffer deep copy and merge.
    33  // TODO: RawMessage.
    34  
    35  package proto
    36  
    37  import (
    38  	"log"
    39  	"reflect"
    40  	"strings"
    41  )
    42  
    43  // Clone returns a deep copy of a protocol buffer.
    44  func Clone(pb Message) Message {
    45  	in := reflect.ValueOf(pb)
    46  	if in.IsNil() {
    47  		return pb
    48  	}
    49  
    50  	out := reflect.New(in.Type().Elem())
    51  	// out is empty so a merge is a deep copy.
    52  	mergeStruct(out.Elem(), in.Elem())
    53  	return out.Interface().(Message)
    54  }
    55  
    56  // Merge merges src into dst.
    57  // Required and optional fields that are set in src will be set to that value in dst.
    58  // Elements of repeated fields will be appended.
    59  // Merge panics if src and dst are not the same type, or if dst is nil.
    60  func Merge(dst, src Message) {
    61  	in := reflect.ValueOf(src)
    62  	out := reflect.ValueOf(dst)
    63  	if out.IsNil() {
    64  		panic("proto: nil destination")
    65  	}
    66  	if in.Type() != out.Type() {
    67  		// Explicit test prior to mergeStruct so that mistyped nils will fail
    68  		panic("proto: type mismatch")
    69  	}
    70  	if in.IsNil() {
    71  		// Merging nil into non-nil is a quiet no-op
    72  		return
    73  	}
    74  	mergeStruct(out.Elem(), in.Elem())
    75  }
    76  
    77  func mergeStruct(out, in reflect.Value) {
    78  	sprop := GetProperties(in.Type())
    79  	for i := 0; i < in.NumField(); i++ {
    80  		f := in.Type().Field(i)
    81  		if strings.HasPrefix(f.Name, "XXX_") {
    82  			continue
    83  		}
    84  		mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
    85  	}
    86  
    87  	if emIn, ok := in.Addr().Interface().(extendableProto); ok {
    88  		emOut := out.Addr().Interface().(extendableProto)
    89  		mergeExtension(emOut.ExtensionMap(), emIn.ExtensionMap())
    90  	}
    91  
    92  	uf := in.FieldByName("XXX_unrecognized")
    93  	if !uf.IsValid() {
    94  		return
    95  	}
    96  	uin := uf.Bytes()
    97  	if len(uin) > 0 {
    98  		out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
    99  	}
   100  }
   101  
   102  // mergeAny performs a merge between two values of the same type.
   103  // viaPtr indicates whether the values were indirected through a pointer (implying proto2).
   104  // prop is set if this is a struct field (it may be nil).
   105  func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
   106  	if in.Type() == protoMessageType {
   107  		if !in.IsNil() {
   108  			if out.IsNil() {
   109  				out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
   110  			} else {
   111  				Merge(out.Interface().(Message), in.Interface().(Message))
   112  			}
   113  		}
   114  		return
   115  	}
   116  	switch in.Kind() {
   117  	case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
   118  		reflect.String, reflect.Uint32, reflect.Uint64:
   119  		if !viaPtr && isProto3Zero(in) {
   120  			return
   121  		}
   122  		out.Set(in)
   123  	case reflect.Interface:
   124  		// Probably a oneof field; copy non-nil values.
   125  		if in.IsNil() {
   126  			return
   127  		}
   128  		// Allocate destination if it is not set, or set to a different type.
   129  		// Otherwise we will merge as normal.
   130  		if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
   131  			out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
   132  		}
   133  		mergeAny(out.Elem(), in.Elem(), false, nil)
   134  	case reflect.Map:
   135  		if in.Len() == 0 {
   136  			return
   137  		}
   138  		if out.IsNil() {
   139  			out.Set(reflect.MakeMap(in.Type()))
   140  		}
   141  		// For maps with value types of *T or []byte we need to deep copy each value.
   142  		elemKind := in.Type().Elem().Kind()
   143  		for _, key := range in.MapKeys() {
   144  			var val reflect.Value
   145  			switch elemKind {
   146  			case reflect.Ptr:
   147  				val = reflect.New(in.Type().Elem().Elem())
   148  				mergeAny(val, in.MapIndex(key), false, nil)
   149  			case reflect.Slice:
   150  				val = in.MapIndex(key)
   151  				val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
   152  			default:
   153  				val = in.MapIndex(key)
   154  			}
   155  			out.SetMapIndex(key, val)
   156  		}
   157  	case reflect.Ptr:
   158  		if in.IsNil() {
   159  			return
   160  		}
   161  		if out.IsNil() {
   162  			out.Set(reflect.New(in.Elem().Type()))
   163  		}
   164  		mergeAny(out.Elem(), in.Elem(), true, nil)
   165  	case reflect.Slice:
   166  		if in.IsNil() {
   167  			return
   168  		}
   169  		if in.Type().Elem().Kind() == reflect.Uint8 {
   170  			// []byte is a scalar bytes field, not a repeated field.
   171  
   172  			// Edge case: if this is in a proto3 message, a zero length
   173  			// bytes field is considered the zero value, and should not
   174  			// be merged.
   175  			if prop != nil && prop.proto3 && in.Len() == 0 {
   176  				return
   177  			}
   178  
   179  			// Make a deep copy.
   180  			// Append to []byte{} instead of []byte(nil) so that we never end up
   181  			// with a nil result.
   182  			out.SetBytes(append([]byte{}, in.Bytes()...))
   183  			return
   184  		}
   185  		n := in.Len()
   186  		if out.IsNil() {
   187  			out.Set(reflect.MakeSlice(in.Type(), 0, n))
   188  		}
   189  		switch in.Type().Elem().Kind() {
   190  		case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
   191  			reflect.String, reflect.Uint32, reflect.Uint64:
   192  			out.Set(reflect.AppendSlice(out, in))
   193  		default:
   194  			for i := 0; i < n; i++ {
   195  				x := reflect.Indirect(reflect.New(in.Type().Elem()))
   196  				mergeAny(x, in.Index(i), false, nil)
   197  				out.Set(reflect.Append(out, x))
   198  			}
   199  		}
   200  	case reflect.Struct:
   201  		mergeStruct(out, in)
   202  	default:
   203  		// unknown type, so not a protocol buffer
   204  		log.Printf("proto: don't know how to copy %v", in)
   205  	}
   206  }
   207  
   208  func mergeExtension(out, in map[int32]Extension) {
   209  	for extNum, eIn := range in {
   210  		eOut := Extension{desc: eIn.desc}
   211  		if eIn.value != nil {
   212  			v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
   213  			mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
   214  			eOut.value = v.Interface()
   215  		}
   216  		if eIn.enc != nil {
   217  			eOut.enc = make([]byte, len(eIn.enc))
   218  			copy(eOut.enc, eIn.enc)
   219  		}
   220  
   221  		out[extNum] = eOut
   222  	}
   223  }