1 Star 0 Fork 0

Eriloan / goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
bytes.go 1.77 KB
一键复制 编辑 原始数据 按行查看 历史
Eriloan 提交于 2022-03-23 18:05 . 修改依赖库引用
package bytes
import (
"bytes"
"reflect"
"strconv"
"strings"
"unsafe"
)
//Join Bytes join
func Join(pBytes ...[]byte) []byte {
return bytes.Join(pBytes, []byte(""))
}
//UnsafeString GetString returns a string pointer without allocation
func UnsafeString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
//UnsafeBytes GetBytes returns a byte pointer without allocation
func UnsafeBytes(s string) (bs []byte) {
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
bh := (*reflect.SliceHeader)(unsafe.Pointer(&bs))
bh.Data = sh.Data
bh.Len = sh.Len
bh.Cap = sh.Len
return
}
// CopyString copies a string to make it immutable
func CopyString(s string) string {
return string(UnsafeBytes(s))
}
// CopyBytes copies a slice to make it immutable
func CopyBytes(b []byte) []byte {
tmp := make([]byte, len(b))
copy(tmp, b)
return tmp
}
const (
uByte = 1 << (10 * iota)
uKilobyte
uMegabyte
uGigabyte
uTerabyte
uPetabyte
uExabyte
)
// ByteSize returns a human-readable byte string of the form 10M, 12.5K, and so forth.
// The unit that results in the smallest number greater than or equal to 1 is always chosen.
func ByteSize(bytes uint64) string {
unit := ""
value := float64(bytes)
switch {
case bytes >= uExabyte:
unit = "EB"
value = value / uExabyte
case bytes >= uPetabyte:
unit = "PB"
value = value / uPetabyte
case bytes >= uTerabyte:
unit = "TB"
value = value / uTerabyte
case bytes >= uGigabyte:
unit = "GB"
value = value / uGigabyte
case bytes >= uMegabyte:
unit = "MB"
value = value / uMegabyte
case bytes >= uKilobyte:
unit = "KB"
value = value / uKilobyte
case bytes >= uByte:
unit = "B"
default:
return "0B"
}
result := strconv.FormatFloat(value, 'f', 1, 64)
result = strings.TrimSuffix(result, ".0")
return result + unit
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/shibingli/goutils.git
git@gitee.com:shibingli/goutils.git
shibingli
goutils
goutils
v1.2.2

搜索帮助

344bd9b3 5694891 D2dac590 5694891