OSDN Git Service

feat: add fed orm (#136)
[bytom/vapor.git] / protocol / bc / asset.go
1 package bc
2
3 import (
4         "encoding/binary"
5         "errors"
6         "io"
7
8         "github.com/vapor/encoding/blockchain"
9 )
10
11 // NewAssetID convert byte array to aseet id
12 func NewAssetID(b [32]byte) (a AssetID) {
13         return AssetID{
14                 V0: binary.BigEndian.Uint64(b[0:8]),
15                 V1: binary.BigEndian.Uint64(b[8:16]),
16                 V2: binary.BigEndian.Uint64(b[16:24]),
17                 V3: binary.BigEndian.Uint64(b[24:32]),
18         }
19 }
20
21 // Byte32 return the byte array representation
22 func (a AssetID) Byte32() (b32 [32]byte) { return Hash(a).Byte32() }
23
24 // MarshalText satisfies the TextMarshaler interface.
25 func (a AssetID) MarshalText() ([]byte, error) { return Hash(a).MarshalText() }
26
27 // UnmarshalText satisfies the TextUnmarshaler interface.
28 func (a *AssetID) UnmarshalText(b []byte) error { return (*Hash)(a).UnmarshalText(b) }
29
30 // UnmarshalJSON satisfies the json.Unmarshaler interface.
31 func (a *AssetID) UnmarshalJSON(b []byte) error { return (*Hash)(a).UnmarshalJSON(b) }
32
33 // Bytes returns the byte representation.
34 func (a AssetID) Bytes() []byte { return Hash(a).Bytes() }
35
36 // WriteTo satisfies the io.WriterTo interface.
37 func (a AssetID) WriteTo(w io.Writer) (int64, error) { return Hash(a).WriteTo(w) }
38
39 // ReadFrom satisfies the io.ReaderFrom interface.
40 func (a *AssetID) ReadFrom(r io.Reader) (int64, error) { return (*Hash)(a).ReadFrom(r) }
41
42 // IsZero tells whether a Asset pointer is nil or points to an all-zero hash.
43 func (a *AssetID) IsZero() bool { return (*Hash)(a).IsZero() }
44
45 // ReadFrom read the AssetAmount from the bytes
46 func (a *AssetAmount) ReadFrom(r *blockchain.Reader) (err error) {
47         var assetID AssetID
48         if _, err = assetID.ReadFrom(r); err != nil {
49                 return err
50         }
51         a.AssetId = &assetID
52         a.Amount, err = blockchain.ReadVarint63(r)
53         return err
54 }
55
56 // WriteTo convert struct to byte and write to io
57 func (a AssetAmount) WriteTo(w io.Writer) (int64, error) {
58         n, err := a.AssetId.WriteTo(w)
59         if err != nil {
60                 return n, err
61         }
62         n2, err := blockchain.WriteVarint63(w, a.Amount)
63         return n + int64(n2), err
64 }
65
66 // Equal check does two AssetAmount have same assetID and amount
67 func (a *AssetAmount) Equal(other *AssetAmount) (eq bool, err error) {
68         if a == nil || other == nil {
69                 return false, errors.New("empty asset amount")
70         }
71         if a.AssetId == nil || other.AssetId == nil {
72                 return false, errors.New("empty asset id")
73         }
74         return a.Amount == other.Amount && *a.AssetId == *other.AssetId, nil
75 }