From 841fef387a555a1173524b9394eefca2256d8fa1 Mon Sep 17 00:00:00 2001 From: wdvxdr Date: Sat, 11 Feb 2023 18:01:19 +0800 Subject: [PATCH] internal/proto: re-use map[uint64]any use slice will cause some panic. --- client/guild.go | 4 ++-- internal/proto/dynamic.go | 23 +++++++++++++++++++---- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/client/guild.go b/client/guild.go index be3ed4bc..e2634665 100644 --- a/client/guild.go +++ b/client/guild.go @@ -175,7 +175,7 @@ func (g *GuildInfo) removeChannel(id uint64) { } func (s *GuildService) GetUserProfile(tinyId uint64) (*GuildUserProfile, error) { - flags := make(proto.DynamicMessage, 101) + flags := proto.DynamicMessage{} for i := 3; i <= 29; i++ { flags[uint64(i)] = 1 } @@ -275,7 +275,7 @@ func (s *GuildService) FetchGuildMemberListWithRole(guildId, channelId uint64, s // FetchGuildMemberProfileInfo 获取单个频道成员资料 func (s *GuildService) FetchGuildMemberProfileInfo(guildId, tinyId uint64) (*GuildUserProfile, error) { seq := s.c.nextSeq() - flags := make(proto.DynamicMessage, 101) + flags := proto.DynamicMessage{} for i := 3; i <= 29; i++ { flags[uint64(i)] = 1 } diff --git a/internal/proto/dynamic.go b/internal/proto/dynamic.go index 466ee2ad..883fcddf 100644 --- a/internal/proto/dynamic.go +++ b/internal/proto/dynamic.go @@ -3,9 +3,10 @@ package proto import ( "encoding/binary" "math" + "sort" ) -type DynamicMessage []any +type DynamicMessage map[uint64]any // zigzag encoding types type ( @@ -20,10 +21,24 @@ type encoder struct { func (msg DynamicMessage) Encode() []byte { en := encoder{} + + // sort all items + type pair struct { + key uint64 + value any + } + var all []pair + for k, v := range msg { + all = append(all, pair{key: k, value: v}) + } + sort.Slice(all, func(i, j int) bool { + return all[i].key < all[j].key + }) + //nolint:staticcheck - for id, value := range msg { - key := uint64(id << 3) - switch v := value.(type) { + for _, item := range all { + key := item.key << 3 + switch v := item.value.(type) { case bool: en.uvarint(key | 0) vi := uint64(0)