• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang proto.Clone函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/golang/protobuf/proto.Clone函数的典型用法代码示例。如果您正苦于以下问题:Golang Clone函数的具体用法?Golang Clone怎么用?Golang Clone使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Clone函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Clone

// Clone returns a copy of Region.
func (r *Region) Clone() *Region {
	return &Region{
		meta:       proto.Clone(r.meta).(*metapb.Region),
		peer:       proto.Clone(r.peer).(*metapb.Peer),
		addr:       r.addr,
		curPeerIdx: r.curPeerIdx,
	}
}
开发者ID:jmptrader,项目名称:tidb,代码行数:9,代码来源:region_cache.go


示例2: GetRegionByKey

// GetRegionByKey returns the Region and its leader whose range contains the key.
func (c *Cluster) GetRegionByKey(key []byte) (*metapb.Region, *metapb.Peer) {
	c.RLock()
	defer c.RUnlock()

	for _, r := range c.regions {
		if regionContains(r.meta.StartKey, r.meta.EndKey, key) {
			return proto.Clone(r.meta).(*metapb.Region), proto.Clone(r.leaderPeer()).(*metapb.Peer)
		}
	}
	return nil, nil
}
开发者ID:XuHuaiyu,项目名称:tidb,代码行数:12,代码来源:cluster.go


示例3: MaybeExtractQ

// MaybeExtractQ extracts proto from HTTP request and returns it.
// Nil indicates failure, and appropriate status / description is written
// to response.
func MaybeExtractQ(w http.ResponseWriter, r *http.Request, defaultQ proto.Message) *proto.Message {
	q := proto.Clone(defaultQ)
	if r.Method == "POST" {
		reqBody, err := ioutil.ReadAll(r.Body)
		if err != nil {
			fmt.Fprintf(w, "Failed to read POST body %v", err)
			return nil
		}
		err = proto.Unmarshal(reqBody, q)
		if err != nil {
			fmt.Fprintf(w, "Failed to parse POST body as binary proto: %v", err)
			return nil
		}
	} else {
		err := r.ParseForm()
		if err != nil {
			http.NotFound(w, r)
			fmt.Fprintf(w, "strange query %v", err)
			return nil
		}
		pb := r.Form.Get("pb")
		if pb == "" {
			http.NotFound(w, r)
			fmt.Fprintf(w, "Non-empty jsonpb-encoded pb param required for GET")
			return nil
		}
		err = jsonpb.UnmarshalString(pb, q)
		if err != nil {
			fmt.Fprintf(w, "Failed to parse pb param %v", err)
			return nil
		}
	}
	return &q
}
开发者ID:xanxys,项目名称:bonsai,代码行数:37,代码来源:main.go


示例4: updateConfig

func (s *server) updateConfig(user string, updater func(*pb.ServiceConfig) error) error {
	s.Lock()
	clonedCfg := proto.Clone(s.cfgs).(*pb.ServiceConfig)
	currentVersion := clonedCfg.Version
	s.Unlock()

	err := updater(clonedCfg)

	if err != nil {
		return err
	}

	config.ApplyDefaults(clonedCfg)

	clonedCfg.User = user
	clonedCfg.Date = time.Now().Unix()
	clonedCfg.Version = currentVersion + 1

	r, e := config.Marshal(clonedCfg)

	if e != nil {
		return e
	}

	return s.persister.PersistAndNotify(r)
}
开发者ID:maniksurtani,项目名称:quotaservice,代码行数:26,代码来源:server.go


示例5: TestProto3SetDefaults

func TestProto3SetDefaults(t *testing.T) {
	in := &pb.Message{
		Terrain: map[string]*pb.Nested{
			"meadow": new(pb.Nested),
		},
		Proto2Field: new(tpb.SubDefaults),
		Proto2Value: map[string]*tpb.SubDefaults{
			"badlands": new(tpb.SubDefaults),
		},
	}

	got := proto.Clone(in).(*pb.Message)
	proto.SetDefaults(got)

	// There are no defaults in proto3.  Everything should be the zero value, but
	// we need to remember to set defaults for nested proto2 messages.
	want := &pb.Message{
		Terrain: map[string]*pb.Nested{
			"meadow": new(pb.Nested),
		},
		Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)},
		Proto2Value: map[string]*tpb.SubDefaults{
			"badlands": {N: proto.Int64(7)},
		},
	}

	if !proto.Equal(got, want) {
		t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want)
	}
}
开发者ID:zhangcunli,项目名称:go-demo,代码行数:30,代码来源:proto3_test.go


示例6: PrivacyFilterSnapshot

func PrivacyFilterSnapshot(snapshot pb.Snapshot) pb.Snapshot {
	result := proto.Clone(&snapshot).(*pb.Snapshot)
	for _, session := range result.Sessions {
		session.Pass = "<privacy filtered>"
	}
	return *result
}
开发者ID:aftran,项目名称:robustirc,代码行数:7,代码来源:util.go


示例7: TestClone

func TestClone(t *testing.T) {
	m := proto.Clone(cloneTestMessage).(*pb.MyMessage)
	if !proto.Equal(m, cloneTestMessage) {
		t.Errorf("Clone(%v) = %v", cloneTestMessage, m)
	}

	// Verify it was a deep copy.
	*m.Inner.Port++
	if proto.Equal(m, cloneTestMessage) {
		t.Error("Mutating clone changed the original")
	}
	// Byte fields and repeated fields should be copied.
	if &m.Pet[0] == &cloneTestMessage.Pet[0] {
		t.Error("Pet: repeated field not copied")
	}
	if &m.Others[0] == &cloneTestMessage.Others[0] {
		t.Error("Others: repeated field not copied")
	}
	if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] {
		t.Error("Others[0].Value: bytes field not copied")
	}
	if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] {
		t.Error("RepBytes: repeated field not copied")
	}
	if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] {
		t.Error("RepBytes[0]: bytes field not copied")
	}
}
开发者ID:zhangcunli,项目名称:go-demo,代码行数:28,代码来源:clone_test.go


示例8: addHealthResponse

// addHealthResponse adds a mocked health response to the buffer channel.
func (q *fakeQueryService) addHealthResponse(qps float64) {
	q.healthResponses <- &querypb.StreamHealthResponse{
		Target:  proto.Clone(&q.target).(*querypb.Target),
		Serving: true,
		RealtimeStats: &querypb.RealtimeStats{
			Qps: qps,
		},
	}
}
开发者ID:aaijazi,项目名称:vitess,代码行数:10,代码来源:wait_for_drain_test.go


示例9: AddDefaultHealthResponse

// AddDefaultHealthResponse adds a faked health response to the buffer channel.
// The response will have default values typical for a healthy tablet.
func (q *StreamHealthQueryService) AddDefaultHealthResponse() {
	q.healthResponses <- &querypb.StreamHealthResponse{
		Target:  proto.Clone(&q.target).(*querypb.Target),
		Serving: true,
		RealtimeStats: &querypb.RealtimeStats{
			SecondsBehindMaster: DefaultSecondsBehindMaster,
		},
	}
}
开发者ID:CowLeo,项目名称:vitess,代码行数:11,代码来源:stream_health_query_service.go


示例10: GetStore

// GetStore returns a Store's meta.
func (c *Cluster) GetStore(storeID uint64) *metapb.Store {
	c.mu.RLock()
	defer c.mu.RUnlock()

	if store := c.stores[storeID]; store != nil {
		return proto.Clone(store.meta).(*metapb.Store)
	}
	return nil
}
开发者ID:anywhy,项目名称:tidb,代码行数:10,代码来源:cluster.go


示例11: TestMerge

func TestMerge(t *testing.T) {
	for _, m := range mergeTests {
		got := proto.Clone(m.dst)
		proto.Merge(got, m.src)
		if !proto.Equal(got, m.want) {
			t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want)
		}
	}
}
开发者ID:zhangcunli,项目名称:go-demo,代码行数:9,代码来源:clone_test.go


示例12: ServeHTTP

// Compile all information exported through the hackerspace API and send it
// back to the requestor.
func (a *SpaceAPI) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	var msg = proto.Clone(a.conf.SpaceapiMd)
	var md *doorky.SpaceAPIMetadata
	var door *doorky.DoorSecret
	var out []byte
	var err error
	var ok bool

	md, ok = msg.(*doorky.SpaceAPIMetadata)
	if !ok {
		log.Print("Error: message is not of type SpaceAPIMetadata")
		http.Error(rw, http.StatusText(http.StatusInternalServerError),
			http.StatusInternalServerError)
	}

	for _, door = range a.conf.Secret {
		var lockInfo = new(doorky.SpaceAPIDoorLockSensor)
		var name = door.GetName()
		var ts time.Time
		var isOpen bool

		ts, isOpen, err = a.ts.LastValue(name)
		if err != nil {
			log.Print("Error fetching door status for ", name, ": ", err)
			continue
		}

		lockInfo.Value = proto.Bool(!isOpen)
		lockInfo.Location = proto.String(door.GetLocation())
		lockInfo.Name = proto.String(name)
		lockInfo.Description = proto.String("Last update: " + ts.String())

		if md.Sensors == nil {
			md.Sensors = new(doorky.SpaceAPISensors)
		}
		md.Sensors.DoorLocked = append(md.Sensors.DoorLocked, lockInfo)

		if a.conf.PrimaryDoor != nil && a.conf.GetPrimaryDoor() == name {
			md.State.Open = proto.Bool(isOpen)
			md.State.Lastchange = proto.Int64(ts.Unix())
		}
	}

	out, err = json.MarshalIndent(md, "    ", "    ")
	if err != nil {
		log.Print("Error marshalling JSON: ", err)
		http.Error(rw, http.StatusText(http.StatusInternalServerError)+": "+
			"Error marshalling response: "+err.Error(),
			http.StatusInternalServerError)
	}

	_, err = rw.Write(out)
	if err != nil {
		log.Print("Error writing response: ", err)
	}
}
开发者ID:starshipfactory,项目名称:doorky,代码行数:58,代码来源:space_api.go


示例13: TestReadDelimited

func TestReadDelimited(t *testing.T) {
	t.Parallel()
	for _, test := range []struct {
		buf []byte
		msg proto.Message
		n   int
		err error
	}{
		{
			buf: []byte{0},
			msg: &Empty{},
			n:   1,
		},
		{
			n:   3,
			buf: []byte{2, 8, 1},
			msg: &GoEnum{Foo: FOO_FOO1.Enum()},
		},
		{
			buf: []byte{141, 2, 10, 138, 2, 84, 104, 105, 115, 32, 105, 115, 32, 109,
				121, 32, 103, 105, 103, 97, 110, 116, 105, 99, 44, 32, 117, 110, 104,
				97, 112, 112, 121, 32, 115, 116, 114, 105, 110, 103, 46, 32, 32, 73,
				116, 32, 101, 120, 99, 101, 101, 100, 115, 10, 116, 104, 101, 32, 101,
				110, 99, 111, 100, 105, 110, 103, 32, 115, 105, 122, 101, 32, 111, 102,
				32, 97, 32, 115, 105, 110, 103, 108, 101, 32, 98, 121, 116, 101, 32,
				118, 97, 114, 105, 110, 116, 46, 32, 32, 87, 101, 32, 97, 114, 101, 32,
				117, 115, 105, 110, 103, 32, 105, 116, 32, 116, 111, 32, 102, 117, 122,
				122, 32, 116, 101, 115, 116, 32, 116, 104, 101, 10, 99, 111, 114, 114,
				101, 99, 116, 110, 101, 115, 115, 32, 111, 102, 32, 116, 104, 101, 32,
				104, 101, 97, 100, 101, 114, 32, 100, 101, 99, 111, 100, 105, 110, 103,
				32, 109, 101, 99, 104, 97, 110, 105, 115, 109, 115, 44, 32, 119, 104,
				105, 99, 104, 32, 109, 97, 121, 32, 112, 114, 111, 118, 101, 32, 112,
				114, 111, 98, 108, 101, 109, 97, 116, 105, 99, 46, 10, 73, 32, 101, 120,
				112, 101, 99, 116, 32, 105, 116, 32, 109, 97, 121, 46, 32, 32, 76, 101,
				116, 39, 115, 32, 104, 111, 112, 101, 32, 121, 111, 117, 32, 101, 110,
				106, 111, 121, 32, 116, 101, 115, 116, 105, 110, 103, 32, 97, 115, 32,
				109, 117, 99, 104, 32, 97, 115, 32, 119, 101, 32, 100, 111, 46},
			msg: &Strings{
				StringField: proto.String(`This is my gigantic, unhappy string.  It exceeds
the encoding size of a single byte varint.  We are using it to fuzz test the
correctness of the header decoding mechanisms, which may prove problematic.
I expect it may.  Let's hope you enjoy testing as much as we do.`),
			},
			n: 271,
		},
	} {
		msg := proto.Clone(test.msg)
		msg.Reset()
		if n, err := ReadDelimited(bytes.NewBuffer(test.buf), msg); n != test.n || err != test.err {
			t.Fatalf("ReadDelimited(%v, msg) = %v, %v; want %v, %v", test.buf, n, err, test.n, test.err)
		}
		if !proto.Equal(msg, test.msg) {
			t.Fatalf("ReadDelimited(%v, msg); msg = %v; want %v", test.buf, msg, test.msg)
		}
	}
}
开发者ID:digitalfishpond,项目名称:dashboard,代码行数:56,代码来源:all_test.go


示例14: GetRegion

// GetRegion returns a Region's meta and leader ID.
func (c *Cluster) GetRegion(regionID uint64) (*metapb.Region, uint64) {
	c.mu.RLock()
	defer c.mu.RUnlock()

	r := c.regions[regionID]
	if r == nil {
		return nil, 0
	}
	return proto.Clone(r.meta).(*metapb.Region), r.leader
}
开发者ID:anywhy,项目名称:tidb,代码行数:11,代码来源:cluster.go


示例15: VName

// VName returns a VName for obj relative to that of its package.
func (pi *PackageInfo) VName(obj types.Object) *spb.VName {
	sig := pi.Signature(obj)
	base := pi.VNames[obj.Pkg()]
	if base == nil {
		return govname.ForBuiltin(sig)
	}
	vname := proto.Clone(base).(*spb.VName)
	vname.Signature = sig
	return vname
}
开发者ID:benjyw,项目名称:kythe,代码行数:11,代码来源:indexer.go


示例16: subtractSystemBatteryLevel

// subtractSystemBatteryLevel sets start level to the current level of the first proto.
func subtractSystemBatteryLevel(p1, p2 *bspb.BatteryStats_System_BatteryLevel) *bspb.BatteryStats_System_BatteryLevel {
	if p1 == nil && p2 == nil {
		return nil
	}
	if p2 == nil {
		return proto.Clone(p1).(*bspb.BatteryStats_System_BatteryLevel)
	}
	if p1 == nil {
		return proto.Clone(p2).(*bspb.BatteryStats_System_BatteryLevel)

	}
	d := &bspb.BatteryStats_System_BatteryLevel{}

	// CurrentLevel is set as the diff between the current level of the 2 protos.
	d.CurrentLevel = proto.Float32(p1.GetCurrentLevel() - p2.GetCurrentLevel())
	// Startlevel is set to the level of the first proto which is our main proto against which we want to diff the other one
	d.StartLevel = proto.Float32(p1.GetCurrentLevel())
	return d
}
开发者ID:mike69d,项目名称:battery-historian,代码行数:20,代码来源:checkin_delta.go


示例17: subtractRepeatedMessage

// subtractRepeatedMessage subtracts protos in list2 from the corresponding protos in list1.
// The input lists should only contain protos, and the protos should have their identifiers
// be their first field.
func subtractRepeatedMessage(list1, list2 interface{}) reflect.Value {
	if list1 == nil && list2 == nil {
		return reflect.ValueOf([]proto.Message{})
	}
	l1 := genericListOrDie(list1)
	if list2 == nil {
		return l1
	}
	l2 := genericListOrDie(list2)
	if list1 == nil {
		// Need to make negatives of the elements in list2, so can't just return here.
		l1 = reflect.MakeSlice(l2.Type(), 0, 0)
	}

	t1, t2 := l1.Type(), l2.Type()
	if t1 != t2 {
		log.Fatalf("Mismatched list types: %v vs %v", t1, t2)
	}

	// All entries may not occur in both files, so use maps to keep track of everything.
	m1, m2 := make(map[string]proto.Message), make(map[string]proto.Message)
	for i := 0; i < l1.Len(); i++ {
		item := l1.Index(i)
		m1[name(item)] = item.Interface().(proto.Message)
	}
	for i := 0; i < l2.Len(); i++ {
		item := l2.Index(i)
		m2[name(item)] = item.Interface().(proto.Message)
	}

	out := reflect.MakeSlice(t1, 0, l1.Len()+l2.Len())
	for n, p1 := range m1 {
		p2, ok := m2[n]
		if !ok {
			// In list1 but not list2.
			out = reflect.Append(out, reflect.ValueOf(proto.Clone(p1)))
			continue
		}
		if diff := subtractMessage(p1, p2); diff != nil {
			out = reflect.Append(out, reflect.ValueOf(diff))
		}
	}
	for n, p2 := range m2 {
		if _, ok := m1[n]; !ok {
			// In list2 but not list1. Subtract to get negative values.
			if diff := subtractMessage(nil, p2); diff != nil {
				out = reflect.Append(out, reflect.ValueOf(diff))
			}
		}
	}
	if out.Len() == 0 {
		return reflect.Zero(l1.Type())
	}
	return out
}
开发者ID:mike69d,项目名称:battery-historian,代码行数:58,代码来源:checkin_delta.go


示例18: GetStoreByAddr

// GetStoreByAddr returns a Store's meta by an addr.
func (c *Cluster) GetStoreByAddr(addr string) *metapb.Store {
	c.mu.RLock()
	defer c.mu.RUnlock()

	for _, s := range c.stores {
		if s.meta.GetAddress() == addr {
			return proto.Clone(s.meta).(*metapb.Store)
		}
	}
	return nil
}
开发者ID:anywhy,项目名称:tidb,代码行数:12,代码来源:cluster.go


示例19: GetRegionByKey

// GetRegionByKey returns the Region whose range contains the key.
func (c *Cluster) GetRegionByKey(key []byte) *metapb.Region {
	c.mu.RLock()
	defer c.mu.RUnlock()

	for _, r := range c.regions {
		if regionContains(r.meta.StartKey, r.meta.EndKey, key) {
			return proto.Clone(r.meta).(*metapb.Region)
		}
	}
	return nil
}
开发者ID:anywhy,项目名称:tidb,代码行数:12,代码来源:cluster.go


示例20: IsHealthy

// IsHealthy returns nil if the query service is healthy (able to
// connect to the database and serving traffic) or an error explaining
// the unhealthiness otherwise.
func (tsv *TabletServer) IsHealthy() error {
	tsv.mu.Lock()
	target := proto.Clone(&tsv.target).(*querypb.Target)
	tsv.mu.Unlock()
	_, err := tsv.Execute(
		context.Background(),
		target,
		"select 1 from dual",
		nil,
		0,
	)
	return err
}
开发者ID:jmptrader,项目名称:vitess,代码行数:16,代码来源:tabletserver.go



注:本文中的github.com/golang/protobuf/proto.Clone函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang proto.CompactTextString函数代码示例发布时间:2022-05-23
下一篇:
Golang proto.Bool函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap