From a12f505886287e133b03e36e4acda6e4966663b9 Mon Sep 17 00:00:00 2001 From: Tim Wu Date: Thu, 17 Jun 2021 10:43:10 -0400 Subject: [PATCH] add usage example for Result --- pkg/scale/README.md | 49 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/pkg/scale/README.md b/pkg/scale/README.md index 55f382fe00..029c022abc 100644 --- a/pkg/scale/README.md +++ b/pkg/scale/README.md @@ -159,6 +159,55 @@ result := scale.NewResult(int32(0), int32(0) result.Set(scale.Ok, 10) ``` +``` +import ( + "fmt" + "github.com/ChainSafe/gossamer/pkg/scale" +) + +func resultExample() { + // pass in zero or non-zero values of the types for Ok and Err cases + res := scale.NewResult(bool(false), string("")) + + // set the OK case with a value of true, any values for OK that are not bool will return an error + err := res.Set(scale.OK, true) + if err != nil { + panic(err) + } + + bytes, err := scale.Marshal(res) + if err != nil { + panic(err) + } + + // [0x00, 0x01] + fmt.Printf("%v\n", bytes) + + res1 := scale.NewResult(bool(false), string("")) + + err = scale.Unmarshal(bytes, &res1) + if err != nil { + panic(err) + } + + // res1 should be Set with OK mode and value of true + ok, err := res1.Unwrap() + if err != nil { + panic(err) + } + + switch ok := ok.(type) { + case bool: + if !ok { + panic(fmt.Errorf("unexpected ok value: %v", ok)) + } + default: + panic(fmt.Errorf("unexpected type: %T", ok)) + } +} + +``` + ### Varying Data Type A `VaryingDataType` is analogous to a Rust enum. A `VaryingDataType` needs to be registered using the `RegisterVaryingDataType` function with its associated `VaryingDataTypeValue` types. `VaryingDataTypeValue` is an