Skip to content

Instantly share code, notes, and snippets.

@ehfeng
Created October 15, 2022 21:40
Show Gist options
  • Save ehfeng/97cf0d7e91d7c9351bcb477fa06850bc to your computer and use it in GitHub Desktop.
Save ehfeng/97cf0d7e91d7c9351bcb477fa06850bc to your computer and use it in GitHub Desktop.
BigInt
package bigint
import (
"encoding/json"
"errors"
"strconv"
"gopkg.in/guregu/null.v4"
)
var ErrInvalidBigInt = errors.New("Invalid BigInt")
var NullBytes = []byte("null")
// in lieu of support for json struct tag option `json:",string"`
// https://github.com/kyleconroy/sqlc/discussions/1087
type BigInt int64
func (i BigInt) Bytes() []byte {
ib := []byte(strconv.FormatInt(int64(i), 10))
b := make([]byte, 1, len(ib)+2)
b[0] = '"'
return append(append(b, ib...), '"')
}
func (i BigInt) String() string {
return string(i.Bytes())
}
func (i BigInt) MarshalJSON() ([]byte, error) {
return i.Bytes(), nil
}
func (i *BigInt) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
p, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return ErrInvalidBigInt
}
*i = BigInt(p)
return nil
}
func NewBigIntFromStr(s string) (BigInt, error) {
i, err := strconv.ParseInt(s, 10, 64)
return BigInt(i), err
}
type NullBigInt null.Int
func (i NullBigInt) Bytes() []byte {
if i.Valid {
ib := []byte(strconv.FormatInt(i.Int64, 10))
b := make([]byte, 1, len(ib)+2)
b[0] = '"'
return append(append(b, ib...), '"')
} else {
return NullBytes
}
}
func (i NullBigInt) String() string {
return string(i.Bytes())
}
func (i NullBigInt) MarshalJSON() ([]byte, error) {
return i.Bytes(), nil
}
func (i *NullBigInt) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
p, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return ErrInvalidBigInt
}
*i = NullBigInt(null.IntFrom(p))
return nil
}
func NewNullBigIntFromStr(s string) (BigInt, error) {
i, err := strconv.ParseInt(s, 10, 64)
return BigInt(i), err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment