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

     1  package snow
     2  
     3  import "errors"
     4  
     5  const (
     6  	encodeBase58Map = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
     7  )
     8  
     9  // nolint gochecknoglobals
    10  var (
    11  	decodeBase58Map [256]byte
    12  
    13  	// ErrInvalidBase58 is returned by ParseBase58 when given an invalid []byte
    14  	ErrInvalidBase58 = errors.New("invalid base58")
    15  )
    16  
    17  // Create maps for decoding Base58/Base32.
    18  // This speeds up the process tremendously.
    19  // nolint gochecknoinits
    20  func init() {
    21  	for i := 0; i < len(encodeBase58Map); i++ {
    22  		decodeBase58Map[i] = 0xFF
    23  	}
    24  
    25  	for i := 0; i < len(encodeBase58Map); i++ {
    26  		decodeBase58Map[encodeBase58Map[i]] = byte(i)
    27  	}
    28  }
    29  
    30  // Base58 returns a base58 string of the snowflake ID
    31  // nolint gomnd
    32  func (f ID) Base58() string {
    33  	if f < 58 {
    34  		return string(encodeBase58Map[f])
    35  	}
    36  
    37  	b := make([]byte, 0, 11)
    38  	for f >= 58 {
    39  		b = append(b, encodeBase58Map[f%58])
    40  		f /= 58
    41  	}
    42  
    43  	b = append(b, encodeBase58Map[f])
    44  
    45  	for x, y := 0, len(b)-1; x < y; x, y = x+1, y-1 {
    46  		b[x], b[y] = b[y], b[x]
    47  	}
    48  
    49  	return string(b)
    50  }
    51  
    52  // ParseBase58 parses a base58 []byte into a snowflake ID
    53  func ParseBase58(b []byte) (ID, error) {
    54  	var id int64
    55  
    56  	for i := range b {
    57  		if decodeBase58Map[b[i]] == 0xFF { // nolint gomnd
    58  			return -1, ErrInvalidBase58
    59  		}
    60  
    61  		id = id*58 + int64(decodeBase58Map[b[i]]) // nolint gomnd
    62  	}
    63  
    64  	return ID(id), nil
    65  }