From fc0aa6cd5abdf2fd053b623c86c39b787bf51155 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 19 Nov 2024 16:41:35 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=87=AA=E5=AE=9A=E4=B9=89Bi?= =?UTF-8?q?gInt=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bigint.go | 118 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 bigint.go diff --git a/bigint.go b/bigint.go new file mode 100644 index 0000000..0aa4100 --- /dev/null +++ b/bigint.go @@ -0,0 +1,118 @@ +// Package wrapper ... +// +// Description : wrapper ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2024-11-19 16:33 +package wrapper + +import ( + "database/sql/driver" + "fmt" + "reflect" + "strconv" +) + +// BigInt 是一个自定义类型,用于在JSON编码时将int64转换为字符串。 +// 建议只在Output中使用它,Input时直接使用int64。 +type BigInt string + +var EmptyBigInt BigInt = "0" + +func (f *BigInt) IsNil() bool { + if nil == f { + return true + } + return reflect.ValueOf(*f).IsNil() +} + +// MarshalJSON 自定义的JSON编码逻辑。 +// @implements json.Marshaler +func (f *BigInt) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf(`"%d"`, f.Int64())), nil +} + +// ToString 返回BigId的字符串表示。 +func (f *BigInt) String() string { + if f.IsNil() { + return string(EmptyBigInt) + } + return string(*f) +} + +// Value 在orm写入数据库时会调用它进行格式转换. +// @implements database/sql/driver.Valuer +func (f *BigInt) Value() (driver.Value, error) { + if f.IsNil() { + return 0, nil + } + return f.Uint64(), nil +} + +// Int64 返回BigId的int64表示。 +// @implements github.com/gogf/gf/v2/util/gconv.iInt64 +func (f *BigInt) Int64() int64 { + if f.IsNil() { + return 0 + } + i, err := strconv.ParseInt(string(*f), 10, 64) + if err != nil || i <= 0 { + return 0 + } + return i +} + +// Uint64 返回BigId的uint64表示。 +// @implements github.com/gogf/gf/v2/util/gconv.iUint64 +func (f *BigInt) Uint64() uint64 { + if f.IsNil() { + return 0 + } + return uint64(f.Int64()) +} + +// IsEmpty 判断BigId是否为空 +func (f *BigInt) IsEmpty() bool { + if f.IsNil() { + return true + } + return *f == "" || *f == EmptyBigInt || f.Int64() == 0 +} + +// UnmarshalJSON converts a json byte array of a big ID into an BigInt type. +// @implements json.Unmarshaler +func (f *BigInt) UnmarshalJSON(b []byte) error { + var ( + s = string(b) + ) + // 如果是null,设置为0 + if s == "null" || s == "" || s == "0" { + *f = EmptyBigInt + return nil + } + // 如果是字符串,去掉引号 + if len(b) >= 3 && b[0] == '"' && b[len(b)-1] == '"' { + s = string(b[1 : len(b)-1]) + } + + *f = StrToBigInt(s) + return nil +} + +// ToBigInt 将int转换为BigInt +func ToBigInt(id int64) BigInt { + if id <= 0 { + return EmptyBigInt + } + return BigInt(fmt.Sprintf("%d", id)) +} + +// StrToBigInt 将str转换为BigInt类型 +func StrToBigInt(id string) BigInt { + i, err := strconv.ParseInt(id, 10, 64) + if err != nil || i <= 0 { + return EmptyBigInt + } + return BigInt(id) +} -- 2.36.6