bytesizer
is a Go package that provides a simple and intuitive way to work with byte counts. It allows you to easily convert between different units of byte sizes, such as bytes, kilobytes, megabytes, gigabytes, terabytes, and petabytes. Similar to how time.Duration
works in Go, bytesizer
helps in representing byte sizes with appropriate types and methods.
- Conversion between byte units and bytes
- Formatting of byte sizes into human-readable strings
- Parsing of strings into byte sizes with support for different units
- Fetching byte sizes as integer or floating-point numbers for precision work
To install bytesizer
, you can use the following Go command:
go get github.com/iamlongalong/bytesizer
Replace iamlongalong
with your actual GitHub username where the package is hosted.
Below you'll find the methods provided by the bytesizer
package and some examples of how to use them.
bytesizer
defines the following byte size units:
const (
Byte ByteSize = 1 << (10 * iota)
KB
MB
GB
TB
PB
)
Calculate the length of a byte slice and return it as a ByteSize
:
size := bytesizer.Calc([]byte("Hello World!"))
Format a ByteSize
value to a string according to a specified unit:
formattedSize := size.Format(bytesizer.KB) // returns string like "1KB"
Convert a ByteSize
to a string with an automatic unit:
sizeString := size.String() // returns string like "11B"
Get the byte size as different units (returns float64
):
bytes := size.Byte()
kilobytes := size.KB()
// ... and so on for MB, GB, TB, PB
Get the byte size as different units (returns int
):
bytesInt := size.ByteInt()
kilobytesInt := size.KBInt()
// ... and so on for MBInt, GBInt, TBInt, PBInt
Parse a string representation of a byte size into a ByteSize
object:
size, err := bytesizer.Parse("10KB")
if err != nil {
log.Fatal(err)
}
fmt.Println(size) // Output: 10240 (Bytes equivalent of 10KB)
Contributions to bytesizer
are welcome! Feel free to report issues or submit pull requests on our GitHub repository.
This package is licensed under the MIT License - see the LICENSE.md file for details.