github.com/andersfylling/snowflake/v5@v5.0.1/utils.go (about)

     1  package snowflake
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"strconv"
     7  )
     8  
     9  // ParseSnowflakeString interprets a string with a decimal number.
    10  //         Note that in contrast to ParseUint, this function assumes the given string is
    11  //         always valid and thus will panic rather than return an error.
    12  //         This should only be used on checks that can be done at compile time,
    13  //         unless you want to trust other modules to returns valid data.
    14  func ParseSnowflakeString(v string) Snowflake {
    15  	id, err := ParseSnowflakeUint(v, 10)
    16  	if err != nil {
    17  		panic(fmt.Errorf("unable to parse %s into snowflake", v)) // TODO
    18  	}
    19  	return id
    20  }
    21  
    22  // ParseUint converts a string and given base to a Snowflake
    23  func ParseSnowflakeUint(v string, base int) (Snowflake, error) {
    24  	if v == "" {
    25  		return Snowflake(0), nil
    26  	}
    27  
    28  	id, err := strconv.ParseUint(v, base, 64)
    29  	return Snowflake(id), err
    30  }
    31  
    32  func GetSnowflake(v interface{}) (s Snowflake, err error) {
    33  	switch x := v.(type) {
    34  	case int:
    35  		s = NewSnowflake(uint64(x))
    36  	case int8:
    37  		s = NewSnowflake(uint64(x))
    38  	case int16:
    39  		s = NewSnowflake(uint64(x))
    40  	case int32:
    41  		s = NewSnowflake(uint64(x))
    42  	case int64:
    43  		s = NewSnowflake(uint64(x))
    44  
    45  	case uint:
    46  		s = NewSnowflake(uint64(x))
    47  	case uint8:
    48  		s = NewSnowflake(uint64(x))
    49  	case uint16:
    50  		s = NewSnowflake(uint64(x))
    51  	case uint32:
    52  		s = NewSnowflake(uint64(x))
    53  	case uint64:
    54  		s = NewSnowflake(x)
    55  
    56  	case string:
    57  		i, err := strconv.ParseUint(x, 10, 64)
    58  		if err != nil {
    59  			s = NewSnowflake(0)
    60  		} else {
    61  			s = NewSnowflake(i)
    62  		}
    63  
    64  	case Snowflake:
    65  		s = x
    66  
    67  	default:
    68  		s = NewSnowflake(0)
    69  		err = errors.New("not supported type for snowflake")
    70  	}
    71  
    72  	return
    73  }