github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/snow/json.go (about)

     1  package snow
     2  
     3  import (
     4  	"fmt"
     5  	"strconv"
     6  )
     7  
     8  // A JSONSyntaxError is returned from UnmarshalJSON if an invalid ID is provided.
     9  type JSONSyntaxError struct{ original []byte }
    10  
    11  func (j JSONSyntaxError) Error() string {
    12  	return fmt.Sprintf("invalid snowflake ID %q", string(j.original))
    13  }
    14  
    15  // MarshalJSON returns a json byte array string of the snowflake ID.
    16  func (f ID) MarshalJSON() ([]byte, error) {
    17  	buff := make([]byte, 0, 22)
    18  	buff = append(buff, '"')
    19  	buff = strconv.AppendInt(buff, int64(f), 10)
    20  	buff = append(buff, '"')
    21  
    22  	return buff, nil
    23  }
    24  
    25  // UnmarshalJSON converts a json byte array of a snowflake ID into an ID type.
    26  func (f *ID) UnmarshalJSON(b []byte) error {
    27  	if len(b) < 3 || b[0] != '"' || b[len(b)-1] != '"' {
    28  		return JSONSyntaxError{b}
    29  	}
    30  
    31  	i, err := strconv.ParseInt(string(b[1:len(b)-1]), 10, 64)
    32  	if err != nil {
    33  		return err
    34  	}
    35  
    36  	*f = ID(i)
    37  
    38  	return nil
    39  }