github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/amino/example_test.go (about) 1 // Copyright 2017 Tendermint. All Rights Reserved. 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 amino_test 16 17 import ( 18 "fmt" 19 "reflect" 20 21 amino "github.com/gnolang/gno/tm2/pkg/amino" 22 ) 23 24 func Example() { 25 type Message interface{} 26 27 type bcMessage struct { 28 Message string 29 Height int 30 } 31 32 type bcResponse struct { 33 Status int 34 Message string 35 } 36 37 type bcStatus struct { 38 Peers int 39 } 40 41 // amino.RegisterPackage registers globally. 42 amino.RegisterPackage( 43 amino.NewPackage( 44 reflect.TypeOf(bcMessage{}).PkgPath(), 45 "amino_test", 46 amino.GetCallersDirname(), 47 ). 48 WithTypes(&bcMessage{}, &bcResponse{}, &bcStatus{}), 49 ) 50 51 bm := &bcMessage{Message: "ABC", Height: 100} 52 msg := bm 53 54 var bz []byte // the marshalled bytes. 55 var err error 56 bz, err = amino.MarshalAnySized(msg) 57 fmt.Printf("Encoded: %X (err: %v)\n", bz, err) 58 59 var msg2 Message 60 err = amino.UnmarshalSized(bz, &msg2) 61 fmt.Printf("Decoded: %v (err: %v)\n", msg2, err) 62 bm2 := msg2.(*bcMessage) 63 fmt.Printf("Decoded successfully: %v\n", *bm == *bm2) 64 65 // Output: 66 // Encoded: 210A152F616D696E6F5F746573742E62634D65737361676512080A0341424310C801 (err: <nil>) 67 // Decoded: &{ABC 100} (err: <nil>) 68 // Decoded successfully: true 69 }