github.com/matm/etcd@v0.3.1-0.20140328024009-5b4a473f1453/third_party/code.google.com/p/gogoprotobuf/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  // http://code.google.com/p/goprotobuf/
     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.
    33  // TODO: MessageSet and 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  	for i := 0; i < in.NumField(); i++ {
    79  		f := in.Type().Field(i)
    80  		if strings.HasPrefix(f.Name, "XXX_") {
    81  			continue
    82  		}
    83  		mergeAny(out.Field(i), in.Field(i))
    84  	}
    85  
    86  	if emIn, ok := in.Addr().Interface().(extendableProto); ok {
    87  		emOut := out.Addr().Interface().(extendableProto)
    88  		mergeExtension(emOut.ExtensionMap(), emIn.ExtensionMap())
    89  	}
    90  
    91  	uf := in.FieldByName("XXX_unrecognized")
    92  	if !uf.IsValid() {
    93  		return
    94  	}
    95  	uin := uf.Bytes()
    96  	if len(uin) > 0 {
    97  		out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
    98  	}
    99  }
   100  
   101  func mergeAny(out, in reflect.Value) {
   102  	if in.Type() == protoMessageType {
   103  		if !in.IsNil() {
   104  			if out.IsNil() {
   105  				out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
   106  			} else {
   107  				Merge(out.Interface().(Message), in.Interface().(Message))
   108  			}
   109  		}
   110  		return
   111  	}
   112  	switch in.Kind() {
   113  	case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
   114  		reflect.String, reflect.Uint32, reflect.Uint64:
   115  		out.Set(in)
   116  	case reflect.Ptr:
   117  		if in.IsNil() {
   118  			return
   119  		}
   120  		if out.IsNil() {
   121  			out.Set(reflect.New(in.Elem().Type()))
   122  		}
   123  		mergeAny(out.Elem(), in.Elem())
   124  	case reflect.Slice:
   125  		if in.IsNil() {
   126  			return
   127  		}
   128  		n := in.Len()
   129  		if out.IsNil() {
   130  			out.Set(reflect.MakeSlice(in.Type(), 0, n))
   131  		}
   132  		switch in.Type().Elem().Kind() {
   133  		case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
   134  			reflect.String, reflect.Uint32, reflect.Uint64, reflect.Uint8:
   135  			out.Set(reflect.AppendSlice(out, in))
   136  		default:
   137  			for i := 0; i < n; i++ {
   138  				x := reflect.Indirect(reflect.New(in.Type().Elem()))
   139  				mergeAny(x, in.Index(i))
   140  				out.Set(reflect.Append(out, x))
   141  			}
   142  		}
   143  	case reflect.Struct:
   144  		mergeStruct(out, in)
   145  	default:
   146  		// unknown type, so not a protocol buffer
   147  		log.Printf("proto: don't know how to copy %v", in)
   148  	}
   149  }
   150  
   151  func mergeExtension(out, in map[int32]Extension) {
   152  	for extNum, eIn := range in {
   153  		eOut := Extension{desc: eIn.desc}
   154  		if eIn.value != nil {
   155  			v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
   156  			mergeAny(v, reflect.ValueOf(eIn.value))
   157  			eOut.value = v.Interface()
   158  		}
   159  		if eIn.enc != nil {
   160  			eOut.enc = make([]byte, len(eIn.enc))
   161  			copy(eOut.enc, eIn.enc)
   162  		}
   163  
   164  		out[extNum] = eOut
   165  	}
   166  }