github.com/matrixorigin/matrixone@v1.2.0/pkg/common/morpc/examples/message/message.go (about) 1 // Copyright 2021 - 2022 Matrix Origin 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package message 16 17 import ( 18 "github.com/fagongzi/goetty/v2/buf" 19 ) 20 21 // ExampleMessage example message 22 type ExampleMessage struct { 23 MsgID uint64 24 Content string 25 } 26 27 func (tm *ExampleMessage) GetID() uint64 { 28 return tm.MsgID 29 } 30 31 func (tm *ExampleMessage) SetID(id uint64) { 32 tm.MsgID = id 33 } 34 35 func (tm *ExampleMessage) DebugString() string { 36 return "" 37 } 38 39 func (tm *ExampleMessage) Size() int { 40 return 4 + 8 + len(tm.Content) 41 } 42 43 func (tm *ExampleMessage) MarshalTo(data []byte) (int, error) { 44 offset := 0 45 46 buf.Uint64ToBytesTo(tm.MsgID, data[offset:]) 47 offset += 8 48 49 buf.Int2BytesTo(len(tm.Content), data[offset:]) 50 offset += 4 51 52 if len(tm.Content) > 0 { 53 copy(data[offset:], []byte(tm.Content)) 54 } 55 56 return len(data), nil 57 } 58 59 func (tm *ExampleMessage) Unmarshal(data []byte) error { 60 offset := 0 61 62 tm.MsgID = buf.Byte2Uint64(data) 63 offset += 8 64 65 n := buf.Byte2Int(data[offset:]) 66 offset += 4 67 68 content := make([]byte, n) 69 if n > 0 { 70 copy(content, data[offset:offset+n]) 71 } 72 tm.Content = string(content) 73 74 return nil 75 }