code.vegaprotocol.io/vega@v0.79.0/datanode/entities/id.go (about) 1 // Copyright (C) 2023 Gobalsky Labs Limited 2 // 3 // This program is free software: you can redistribute it and/or modify 4 // it under the terms of the GNU Affero General Public License as 5 // published by the Free Software Foundation, either version 3 of the 6 // License, or (at your option) any later version. 7 // 8 // This program is distributed in the hope that it will be useful, 9 // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 // GNU Affero General Public License for more details. 12 // 13 // You should have received a copy of the GNU Affero General Public License 14 // along with this program. If not, see <http://www.gnu.org/licenses/>. 15 16 package entities 17 18 import ( 19 "encoding/hex" 20 "errors" 21 "fmt" 22 23 "github.com/jackc/pgtype" 24 ) 25 26 var ( 27 ErrInvalidID = errors.New("not a valid hex id (or well known exception)") 28 ErrNotFound = errors.New("no resource corresponding to this id") 29 ) 30 31 type ID[T any] string 32 33 var wellKnownIds = map[string]string{ 34 "VOTE": "00", 35 "network": "03", 36 "XYZalpha": "04", 37 "XYZbeta": "05", 38 "XYZdelta": "06", 39 "XYZepsilon": "07", 40 "XYZgamma": "08", 41 "fBTC": "09", 42 "fDAI": "0a", 43 "fEURO": "0b", 44 "fUSDC": "0c", 45 } 46 47 var wellKnownIdsReversed = map[string]string{ 48 "00": "VOTE", 49 "03": "network", 50 "04": "XYZalpha", 51 "05": "XYZbeta", 52 "06": "XYZdelta", 53 "07": "XYZepsilon", 54 "08": "XYZgamma", 55 "09": "fBTC", 56 "0a": "fDAI", 57 "0b": "fEURO", 58 "0c": "fUSDC", 59 } 60 61 func (id *ID[T]) Bytes() ([]byte, error) { 62 strID := id.String() 63 sub, ok := wellKnownIds[strID] 64 if ok { 65 strID = sub 66 } 67 68 bytes, err := hex.DecodeString(strID) 69 if err != nil { 70 return nil, fmt.Errorf("decoding '%v': %w", id.String(), ErrInvalidID) 71 } 72 return bytes, nil 73 } 74 75 func (id *ID[T]) SetBytes(src []byte) error { 76 strID := hex.EncodeToString(src) 77 78 sub, ok := wellKnownIdsReversed[strID] 79 if ok { 80 strID = sub 81 } 82 *id = ID[T](strID) 83 return nil 84 } 85 86 func (id *ID[T]) Error() error { 87 _, err := id.Bytes() 88 return err 89 } 90 91 func (id *ID[T]) String() string { 92 if id == nil { 93 return "" 94 } 95 96 return string(*id) 97 } 98 99 func (id ID[T]) EncodeBinary(ci *pgtype.ConnInfo, buf []byte) ([]byte, error) { 100 bytes, err := id.Bytes() 101 if err != nil { 102 return buf, err 103 } 104 return append(buf, bytes...), nil 105 } 106 107 func (id *ID[T]) DecodeBinary(ci *pgtype.ConnInfo, src []byte) error { 108 return id.SetBytes(src) 109 } 110 111 func (id *ID[T]) Where(fieldName *string, nextBindVar func(args *[]any, arg any) string, args ...any) (string, []any) { 112 if fieldName == nil { 113 return fmt.Sprintf("id = %s", nextBindVar(&args, id)), args 114 } 115 return fmt.Sprintf("%s = %s", *fieldName, nextBindVar(&args, id)), args 116 }