1
0
mirror of https://github.com/duke-git/lancet.git synced 2026-02-08 22:52:29 +08:00

feat: add ToBigInt

This commit is contained in:
dudaodong
2024-12-02 11:25:16 +08:00
parent 8f3ea60636
commit 7fb49515ce
7 changed files with 217 additions and 61 deletions

View File

@@ -14,11 +14,13 @@ import (
"fmt"
"io"
"math"
"math/big"
"reflect"
"strconv"
"strings"
"github.com/duke-git/lancet/v2/structs"
"golang.org/x/exp/constraints"
"golang.org/x/text/encoding/simplifiedchinese"
"golang.org/x/text/transform"
)
@@ -483,3 +485,36 @@ func ToRawUrlBase64(value any) string {
return base64.RawURLEncoding.EncodeToString(marshal)
}
}
// ToBigInt converts an integer of any supported type (int, int64, uint64, etc.) to *big.Int
// Play: todo
func ToBigInt[T constraints.Integer](v T) (*big.Int, error) {
result := new(big.Int)
switch v := any(v).(type) {
case int:
result.SetInt64(int64(v)) // Convert to int64 for big.Int
case int8:
result.SetInt64(int64(v))
case int16:
result.SetInt64(int64(v))
case int32:
result.SetInt64(int64(v))
case int64:
result.SetInt64(v)
case uint:
result.SetUint64(uint64(v)) // Convert to uint64 for big.Int
case uint8:
result.SetUint64(uint64(v))
case uint16:
result.SetUint64(uint64(v))
case uint32:
result.SetUint64(uint64(v))
case uint64:
result.SetUint64(v)
default:
return nil, fmt.Errorf("unsupported type: %T", v)
}
return result, nil
}

View File

@@ -571,3 +571,12 @@ func ExampleToRawUrlBase64() {
// dHJ1ZQ
// ZXJy
}
func ExampleToBigInt() {
n := 9876543210
bigInt, _ := ToBigInt(n)
fmt.Println(bigInt)
// Output:
// 9876543210
}

View File

@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"io"
"math/big"
"reflect"
"strconv"
"testing"
@@ -741,3 +742,52 @@ func TestToRawUrlBase64(t *testing.T) {
d15, _ := base64.RawURLEncoding.DecodeString(r15)
assert.Equal("4+3/4?=", string(d15))
}
func TestToBigInt(t *testing.T) {
t.Parallel()
assert := internal.NewAssert(t, "TestToBigInt")
tests := []struct {
name string
input int64
want *big.Int
}{
{
name: "int",
input: 42,
want: big.NewInt(42),
},
{
name: "int8",
input: int64(int8(127)),
want: big.NewInt(127),
},
{
name: "int16",
input: int64(int16(32000)),
want: big.NewInt(32000),
},
{
name: "int32",
input: int64(int32(123456)),
want: big.NewInt(123456),
},
{
name: "int64",
input: int64(987654321),
want: big.NewInt(987654321),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := ToBigInt(tt.input)
if err != nil {
t.Errorf("ToBigInt() error = %v", err)
return
}
assert.Equal(tt.want, got)
})
}
}