github.com/status-im/status-go@v1.1.0/services/wallet/bigint/sql_big_int.go (about)

     1  package bigint
     2  
     3  import (
     4  	"database/sql/driver"
     5  	"errors"
     6  	"math/big"
     7  )
     8  
     9  // SQLBigInt type for storing uint256 in the databse.
    10  // FIXME(dshulyak) SQL big int is max 64 bits. Maybe store as bytes in big endian and hope
    11  // that lexographical sorting will work.
    12  type SQLBigInt big.Int
    13  
    14  // Scan implements interface.
    15  func (i *SQLBigInt) Scan(value interface{}) error {
    16  	if value == nil {
    17  		return nil
    18  	}
    19  	val, ok := value.(int64)
    20  	if !ok {
    21  		return errors.New("not an integer")
    22  	}
    23  	(*big.Int)(i).SetInt64(val)
    24  	return nil
    25  }
    26  
    27  // Value implements interface.
    28  func (i *SQLBigInt) Value() (driver.Value, error) {
    29  	val := (*big.Int)(i)
    30  	if val == nil {
    31  		return nil, nil
    32  	}
    33  	if !val.IsInt64() {
    34  		return nil, errors.New("not an int64")
    35  	}
    36  	return (*big.Int)(i).Int64(), nil
    37  }
    38  
    39  // SQLBigIntBytes type for storing big.Int as BLOB in the databse.
    40  type SQLBigIntBytes big.Int
    41  
    42  func (i *SQLBigIntBytes) Scan(value interface{}) error {
    43  	if value == nil {
    44  		return nil
    45  	}
    46  	val, ok := value.([]byte)
    47  	if !ok {
    48  		return errors.New("not an integer")
    49  	}
    50  	(*big.Int)(i).SetBytes(val)
    51  	return nil
    52  }
    53  
    54  func (i *SQLBigIntBytes) Value() (driver.Value, error) {
    55  	val := (*big.Int)(i)
    56  	if val == nil {
    57  		return nil, nil
    58  	}
    59  	return (*big.Int)(i).Bytes(), nil
    60  }
    61  
    62  type NilableSQLBigInt struct {
    63  	big.Int
    64  	isNil bool
    65  }
    66  
    67  func (i *NilableSQLBigInt) IsNil() bool {
    68  	return i.isNil
    69  }
    70  
    71  func (i *NilableSQLBigInt) SetNil() {
    72  	i.isNil = true
    73  }
    74  
    75  // Scan implements interface.
    76  func (i *NilableSQLBigInt) Scan(value interface{}) error {
    77  	if value == nil {
    78  		i.SetNil()
    79  		return nil
    80  	}
    81  	val, ok := value.(int64)
    82  	if !ok {
    83  		return errors.New("not an integer")
    84  	}
    85  
    86  	i.SetInt64(val)
    87  	return nil
    88  }
    89  
    90  // Not implemented, used only for scanning
    91  func (i *NilableSQLBigInt) Value() (driver.Value, error) {
    92  	return nil, errors.New("NilableSQLBigInt.Value is not implemented")
    93  }