github.com/kaleido-io/firefly@v0.0.0-20210622132723-8b4b6aacb971/pkg/fftypes/byteable.go (about) 1 // Copyright © 2021 Kaleido, Inc. 2 // 3 // SPDX-License-Identifier: Apache-2.0 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 17 package fftypes 18 19 import ( 20 "context" 21 "crypto/sha256" 22 "encoding/json" 23 24 "github.com/kaleido-io/firefly/internal/log" 25 ) 26 27 // Byteable uses raw encode/decode to preserve field order, and can handle any types of field. 28 // It validates the JSON can be unmarshalled, but does not change the order. 29 // It does however trim out whitespace 30 type Byteable []byte 31 32 func (h *Byteable) UnmarshalJSON(b []byte) error { 33 var flattener json.RawMessage 34 err := json.Unmarshal(b, &flattener) 35 if err != nil { 36 return err 37 } 38 *h, err = json.Marshal(flattener) 39 return err 40 } 41 42 func (h Byteable) MarshalJSON() ([]byte, error) { 43 if h == nil { 44 return []byte("null"), nil 45 } 46 return h, nil 47 } 48 49 func (h Byteable) Hash() *Bytes32 { 50 var b32 Bytes32 = sha256.Sum256([]byte(h)) 51 return &b32 52 } 53 54 func (h Byteable) String() string { 55 b, _ := h.MarshalJSON() 56 return string(b) 57 } 58 59 func (h Byteable) JSONObjectOk() (*JSONObject, bool) { 60 var jo *JSONObject 61 err := json.Unmarshal(h, &jo) 62 if err != nil { 63 log.L(context.Background()).Warnf("Unable to deserialize as JSON object: %s", string(h)) 64 jo = &JSONObject{} 65 } 66 return jo, err == nil 67 } 68 69 // JSONObject attempts to de-serailize the contained structure as a JSON Object (map) 70 // Will fail if the type is array, string, bool, number etc. 71 func (h Byteable) JSONObject() *JSONObject { 72 jo, _ := h.JSONObjectOk() 73 return jo 74 }