Overview of bytefmt
mainbytefmt is a Go library designed to provide human-readable byte formatting. It is used to convert raw byte counts into more digestible strings (e.g., converting 1024 to 1 KiB).repository·main·Indexed 42 days ago
https://github.com/cloudfoundry/bytefmtA Go library for formatting byte counts into human-readable strings and parsing them back into uint64 values. It provides utilities such as ByteSize for compact formatting, ToBytes for parsing strings with binary or SI prefixes, and ToMegabytes for specific megabyte conversion, along with base-2 byte unit constants from BYTE to EXABYTE.
bytefmt is a Go library designed to provide human-readable byte formatting. It is used to convert raw byte counts into more digestible strings (e.g., converting 1024 to 1 KiB).To use bytefmt in your Go application, import it using the following path:
code.cloudfoundry.org/bytefmt
import "code.cloudfoundry.org/bytefmt"Use ByteSize(bytes uint64) to convert a raw byte count into a compact, human-readable string (e.g., "10M", "12.5K"). The function automatically selects the unit that results in the smallest number greater than or equal to 1.
Available units in the output:
E: ExabyteP: PetabyteT: TerabyteG: GigabyteM: MegabyteK: KilobyteB: Byteimport "github.com/cloudfoundry/cloudfoundry/bytefmt"
// Returns "100.5M"
str := bytefmt.ByteSize(uint64(100.5 * bytefmt.MEGABYTE))
// Returns "1K"
str2 := bytefmt.ByteSize(1024)Use ToBytes(s string) to convert a human-readable string back into a uint64 byte count.
This function supports both binary-prefixed and SI-prefixed units, treating them all as base-2 (1024-based) units. Supported suffixes include:
E, EB, EIB (Exabyte)P, PB, PIB (Petabyte)T, TB, TIB (Terabyte)G, GB, GIB (Gigabyte)M, MB, MIB (Megabyte)K, KB, KIB (Kilobyte)B (Byte)If the string is invalid or the quantity is negative, it returns an error.
import "github.com/cloudfoundry/cloudfoundry/bytefmt"
bytes, err := bytefmt.ToBytes("10MB")
if err != nil {
// handle error
}
// bytes is 10 * 1024 * 1024Use ToMegabytes(s string) to parse a human-readable byte string and return the value specifically in megabytes as a uint64. This is a convenience wrapper around ToBytes that performs integer division by MEGABYTE.
import "github.com/cloudfoundry/cloudfoundry/bytefmt"
mb, err := bytefmt.ToMegabytes("1GB")
if err != nil {
// handle error
}
// mb is 1024The package provides constants representing base-2 (1024-based) byte increments. These can be used for calculations or to define specific byte quantities.
BYTE (1)KILOBYTE (1024)MEGABYTE (1024^2)GIGABYTE (1024^3)TERABYTE (1024^4)PETABYTE (1024^5)EXABYTE (1024^6)const (
BYTE = 1 << (10 * iota)
KILOBYTE
MEGABYTE
GIGABYTE
TERABYTE
PETABYTE
EXABYTE
)