Documentation
¶
Overview ¶
Package size provides types and utilities for handling human-readable size representations.
This package implements the Size type which represents a size in bytes and provides convenient methods for parsing, formatting, and manipulating size values. It supports binary unit prefixes (KiB, MiB, GiB, etc.) using powers of 1024.
The Size type can be marshaled and unmarshaled to/from various formats including JSON, YAML, TOML, CBOR, and plain text. It also integrates with Viper for configuration management.
Basic Usage ¶
Parse a size string:
size, err := size.Parse("10MB")
if err != nil {
log.Fatal(err)
}
Format a size:
size := size.ParseUint64(1048576) fmt.Println(size.String()) // Output: "1.00 MB"
Arithmetic operations:
size := size.ParseUint64(1024) size.Mul(2.0) // Multiply by 2 size.Add(512) // Add 512 bytes
Units ¶
The package supports the following binary units (powers of 1024):
- B (Byte) = 1
- KB (Kilobyte) = 1024
- MB (Megabyte) = 1024²
- GB (Gigabyte) = 1024³
- TB (Terabyte) = 1024⁴
- PB (Petabyte) = 1024⁵
- EB (Exabyte) = 1024⁶
Thread Safety ¶
The Size type is a simple uint64 wrapper and is safe to copy by value. Methods that modify the Size value use pointer receivers.
See Also ¶
For handling durations in a similar manner, see:
- github.com/nabbar/golib/duration
- github.com/nabbar/golib/duration/big (for durations requiring arbitrary precision)
Index ¶
- Constants
- func SetDefaultUnit(unit rune)
- func ViperDecoderHook() libmap.DecodeHookFuncType
- type Size
- func GetSize(s string) (sizeBytes Size, success bool)
- func Parse(s string) (Size, error)
- func ParseByte(p []byte) (Size, error)
- func ParseByteAsSize(p []byte) (Size, error)
- func ParseFloat64(s float64) Size
- func ParseInt64(s int64) Size
- func ParseSize(s string) (Size, error)
- func ParseUint64(s uint64) Size
- func SizeFromFloat64(val float64) Size
- func SizeFromInt64(val int64) Size
- func (s *Size) Add(v uint64)
- func (s *Size) AddErr(v uint64) error
- func (s Size) Code(unit rune) string
- func (s *Size) Div(v float64)
- func (s *Size) DivErr(v float64) error
- func (s Size) ExaBytes() uint64
- func (s Size) Float32() float32
- func (s Size) Float64() float64
- func (s Size) Format(format string) string
- func (s Size) GigaBytes() uint64
- func (s Size) Int() int
- func (s Size) Int32() int32
- func (s Size) Int64() int64
- func (s Size) KiloBytes() uint64
- func (s Size) MarshalBinary() ([]byte, error)
- func (s Size) MarshalCBOR() ([]byte, error)
- func (s Size) MarshalJSON() ([]byte, error)
- func (s Size) MarshalTOML() ([]byte, error)
- func (s Size) MarshalText() ([]byte, error)
- func (s Size) MarshalYAML() (interface{}, error)
- func (s Size) MegaBytes() uint64
- func (s *Size) Mul(v float64)
- func (s *Size) MulErr(v float64) error
- func (s Size) PetaBytes() uint64
- func (s Size) String() string
- func (s *Size) Sub(v uint64)
- func (s *Size) SubErr(v uint64) error
- func (s Size) TeraBytes() uint64
- func (s Size) Uint() uint
- func (s Size) Uint32() uint32
- func (s Size) Uint64() uint64
- func (s Size) Unit(unit rune) string
- func (s *Size) UnmarshalBinary(p []byte) error
- func (s *Size) UnmarshalCBOR(p []byte) error
- func (s *Size) UnmarshalJSON(p []byte) error
- func (s *Size) UnmarshalTOML(i interface{}) error
- func (s *Size) UnmarshalText(p []byte) error
- func (s *Size) UnmarshalYAML(value *yaml.Node) error
Constants ¶
const ( // FormatRound0 formats size values with no decimal places (e.g., "1 MB"). FormatRound0 = "%.0f" // FormatRound1 formats size values with 1 decimal place (e.g., "1.5 MB"). FormatRound1 = "%.1f" // FormatRound2 formats size values with 2 decimal places (e.g., "1.50 MB"). // This is the default format used by the String() method. FormatRound2 = "%.2f" // FormatRound3 formats size values with 3 decimal places (e.g., "1.500 MB"). FormatRound3 = "%.3f" )
Variables ¶
This section is empty.
Functions ¶
func SetDefaultUnit ¶
func SetDefaultUnit(unit rune)
SetDefaultUnit sets the default unit character used when formatting size values.
The unit parameter should be a single character (e.g., 'B' for Byte, 'o' for octet). If unit is 0 or an empty string, it defaults to 'B'.
Example:
size.SetDefaultUnit('o') // Use 'o' (octet) instead of 'B'
size := size.ParseUint64(1024)
fmt.Println(size.Unit(0)) // Output: "Ko" instead of "KB"
func ViperDecoderHook ¶
func ViperDecoderHook() libmap.DecodeHookFuncType
ViperDecoderHook returns a mapstructure decode hook function for use with Viper.
This function allows Viper configuration files to automatically decode size values from various types (int, uint, float, string, []byte) into Size objects.
The hook supports the following source types:
- All integer types (int, int8, int16, int32, int64)
- All unsigned integer types (uint, uint8, uint16, uint32, uint64)
- Float types (float32, float64)
- String (parsed using Parse)
- []byte (parsed using ParseByte)
Example usage with Viper:
import (
"github.com/nabbar/golib/size"
"github.com/spf13/viper"
libmap "github.com/go-viper/mapstructure/v2"
)
type Config struct {
MaxFileSize size.Size `mapstructure:"max_file_size"`
}
v := viper.New()
v.SetConfigFile("config.yaml")
var cfg Config
err := v.Unmarshal(&cfg, viper.DecodeHook(
libmap.ComposeDecodeHookFunc(
size.ViperDecoderHook(),
// other hooks...
),
))
With this hook, your config file can contain:
max_file_size: "10MB" # String format max_file_size: 10485760 # Integer format
See also:
- github.com/nabbar/golib/viper for Viper configuration helpers
- github.com/nabbar/golib/config for complete configuration management
Types ¶
type Size ¶
type Size uint64
Size represents a size in bytes.
The Size type is a uint64 wrapper that provides convenient methods for parsing, formatting, and manipulating size values. All arithmetic operations protect against overflow and underflow.
Example:
size := size.ParseUint64(1048576) // 1 MB fmt.Println(size.String()) // Output: "1.00 MB" fmt.Println(size.MegaBytes()) // Output: 1
const ( // SizeNul represents zero bytes. SizeNul Size = 0 // SizeUnit represents one byte (1 B). SizeUnit Size = 1 // SizeKilo represents one kilobyte (1 KB = 1024 bytes). SizeKilo Size = 1 << 10 // SizeMega represents one megabyte (1 MB = 1024² bytes). SizeMega Size = 1 << 20 // SizeGiga represents one gigabyte (1 GB = 1024³ bytes). SizeGiga Size = 1 << 30 // SizeTera represents one terabyte (1 TB = 1024⁴ bytes). SizeTera Size = 1 << 40 // SizePeta represents one petabyte (1 PB = 1024⁵ bytes). SizePeta Size = 1 << 50 // SizeExa represents one exabyte (1 EB = 1024⁶ bytes). SizeExa Size = 1 << 60 )
func GetSize ¶
GetSize parses a size string and returns a Size value and a boolean indicating success. Deprecated: see Parse
func Parse ¶
Parse parses a size string into a Size value.
The size string is of the form "<number><unit>", where "<number>" is a decimal number and "<unit>" is one of the following:
- "B" for byte
- "K" for kilobyte
- "M" for megabyte
- "G" for gigabyte
- "T" for terabyte
- "P" for petabyte
- "E" for exabyte
Examples:
- "1B" for 1 byte
- "2K" for 2 kilobytes
- "3M" for 3 megabytes
- "4G" for 4 gigabytes
- "5T" for 5 terabytes
- "6P" for 6 petabytes
- "7E" for 7 exabytes
The function returns an error if the size string is invalid.
func ParseByte ¶ added in v1.19.0
ParseByte parses a byte slice into a Size value.
The function is a simple wrapper around ParseBytes.
Examples:
- ParseByte([]byte("1B")) for 1 byte
- ParseByte([]byte("2K")) for 2 kilobytes
- ParseByte([]byte("3M")) for 3 megabytes
- ParseByte([]byte("4G")) for 4 gigabytes
- ParseByte([]byte("5T")) for 5 terabytes
- ParseByte([]byte("6P")) for 6 petabytes
- ParseByte([]byte("7E")) for 7 exabytes
The function returns an error if the size string is invalid.
func ParseByteAsSize ¶
ParseByteAsSize parses a byte slice into a Size value. Deprecated: see ParseByte
func ParseFloat64 ¶ added in v1.19.0
ParseFloat64 converts a float64 value into a Size value. The function will always return a positive Size value.
Examples:
- ParseFloat64(-1.0)) for -1.0 bytes but will return 1 byte
- ParseFloat64(1.0)) for 1.0 bytes
- ParseFloat64(-1024.0)) for -1024.0 bytes but will return 1024 bytes
- ParseFloat64(1024.0)) for 1024.0 bytes
func ParseInt64 ¶ added in v1.19.0
ParseInt64 converts an int64 value into a Size value. The function will always return a positive Size value.
Examples:
- ParseInt64(-1)) for -1 byte but will return 1 byte
- ParseInt64(1)) for 1 byte
- ParseInt64(-1024)) for -1024 bytes but will return 1024 byte
- ParseInt64(1024)) for 1024 bytes
func ParseUint64 ¶ added in v1.19.0
ParseUint64 converts a uint64 value into a Size value.
This is the most efficient way to create a Size from a known byte count.
Example:
size := size.ParseUint64(1048576) // 1 MB fmt.Println(size.MegaBytes()) // Output: 1
func SizeFromFloat64 ¶ added in v1.13.1
SizeFromFloat64 converts a float64 value into a Size value. Deprecated: see ParseFloat64
func SizeFromInt64 ¶
SizeFromInt64 converts an int64 value into a Size value. Deprecated: see ParseInt64
func (*Size) Add ¶ added in v1.14.0
Add adds a uint64 value to a Size.
This is a convenience wrapper for AddErr which discards any potential errors. See the documentation for AddErr for more information.
func (*Size) AddErr ¶ added in v1.19.0
AddErr adds a uint64 value to a Size.
If the result overflowed (i.e. be greater than the maximum allowable size), the function will return an error and set the Size to the maximum allowable size.
Otherwise, it will set the Size to the result of the addition, rounded up to the nearest whole number.
func (Size) Code ¶
Code returns the unit code (e.g., "KB", "MB", "GB") for the given Size value.
The unit parameter specifies the unit character to append (e.g., 'B', 'o'). If unit is 0, the default unit (set by SetDefaultUnit) is used.
This method returns the appropriate prefix based on the Size value:
- SizeUnit returns "B" (or the specified unit)
- SizeKilo returns "KB" (or "K" + unit)
- SizeMega returns "MB" (or "M" + unit)
- SizeGiga returns "GB" (or "G" + unit)
- SizeTera returns "TB" (or "T" + unit)
- SizePeta returns "PB" (or "P" + unit)
- SizeExa returns "EB" (or "E" + unit)
Example:
fmt.Println(size.SizeKilo.Code('B')) // Output: "KB"
fmt.Println(size.SizeMega.Code('o')) // Output: "Mo"
fmt.Println(size.SizeGiga.Code(0)) // Output: "GB" (using default unit)
func (*Size) Div ¶ added in v1.14.0
Div divides a Size by a float64 value.
This is a convenience wrapper for DivErr which discards any potential errors. See the documentation for DivErr for more information.
func (*Size) DivErr ¶ added in v1.19.0
DivErr divides a Size by a float64 value.
If the divisor is 0 or negative, the function will return an error.
Otherwise, it will set the Size to the result of the division, rounded up to the nearest whole number.
func (Size) ExaBytes ¶
ExaBytes returns the size in exabytes (EB), floored to the nearest whole number.
Example:
size := size.ParseUint64(1729382256910270464) // 1.5 EB fmt.Println(size.ExaBytes()) // Output: 1
func (Size) Float32 ¶ added in v1.13.1
Float32 converts the Size to a float32 value representing bytes.
If the Size value is greater than what can be represented as a float32, the method returns math.MaxFloat32 to prevent overflow.
Example:
size := size.ParseUint64(1024) fmt.Println(size.Float32()) // Output: 1024.0
func (Size) Float64 ¶
Float64 converts the Size to a float64 value representing bytes.
If the Size value is greater than what can be represented as a float64, the method returns math.MaxFloat64 to prevent overflow.
Example:
size := size.ParseUint64(1048576) fmt.Println(size.Float64()) // Output: 1048576.0
func (Size) Format ¶
Format returns a formatted string representation of the Size using the specified format.
The format string should be a printf-style float format (e.g., "%.2f"). The method automatically selects the most appropriate unit and formats the value accordingly.
Example:
size := size.ParseUint64(1572864) // 1.5 MB fmt.Println(size.Format(FormatRound0)) // Output: "2" fmt.Println(size.Format(FormatRound1)) // Output: "1.5" fmt.Println(size.Format(FormatRound2)) // Output: "1.50"
Note: This method returns only the numeric part. Use String() to include the unit.
func (Size) GigaBytes ¶
GigaBytes returns the size in gigabytes (GB), floored to the nearest whole number.
Example:
size := size.ParseUint64(1610612736) // 1.5 GB fmt.Println(size.GigaBytes()) // Output: 1 size := size.ParseUint64(2147483648) // 2 GB fmt.Println(size.GigaBytes()) // Output: 2
func (Size) Int ¶ added in v1.13.1
Int converts the Size to an int value representing bytes.
If the Size value is greater than math.MaxInt, the method returns math.MaxInt to prevent overflow.
Example:
size := size.ParseUint64(1024) fmt.Println(size.Int()) // Output: 1024
func (Size) Int32 ¶ added in v1.13.1
Int32 converts the Size to an int32 value representing bytes.
If the Size value is greater than math.MaxInt32, the method returns math.MaxInt32 to prevent overflow.
Example:
size := size.ParseUint64(1024) fmt.Println(size.Int32()) // Output: 1024
func (Size) Int64 ¶
Int64 converts the Size to an int64 value representing bytes.
If the Size value is greater than math.MaxInt64, the method returns math.MaxInt64 to prevent overflow.
Example:
size := size.ParseUint64(1024) fmt.Println(size.Int64()) // Output: 1024
func (Size) KiloBytes ¶
KiloBytes returns the size in kilobytes (KB), floored to the nearest whole number.
Example:
size := size.ParseUint64(1536) // 1.5 KB fmt.Println(size.KiloBytes()) // Output: 1 size := size.ParseUint64(2048) // 2 KB fmt.Println(size.KiloBytes()) // Output: 2
func (Size) MarshalBinary ¶ added in v1.19.0
MarshalBinary implements the encoding.BinaryMarshaler interface.
This method uses CBOR encoding internally to provide compact binary serialization of Size values.
Example:
size := size.ParseUint64(1048576) // 1 MB data, _ := size.MarshalBinary() // data can be stored or transmitted in binary format
func (Size) MarshalCBOR ¶
MarshalCBOR implements CBOR marshaling using the fxamacker/cbor library.
The Size value is marshaled as a human-readable string (e.g., "1.50 MB") in CBOR format. This is useful for compact binary serialization while maintaining human readability when decoded.
See also: github.com/fxamacker/cbor
func (Size) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface.
The Size value is marshaled as a human-readable string (e.g., "1.50 MB") rather than a raw byte count. This makes JSON output more readable and easier to work with in configuration files.
Example:
size := size.ParseUint64(1572864) // 1.5 MB json, _ := json.Marshal(size) fmt.Println(string(json)) // Output: "\"1.50 MB\""
func (Size) MarshalTOML ¶
MarshalTOML implements the TOML marshaler interface.
The Size value is marshaled as a human-readable string (e.g., "1.50 MB") for better readability in TOML configuration files.
Example:
size := size.ParseUint64(1572864) // 1.5 MB // In TOML: max_size = "1.50 MB"
func (Size) MarshalText ¶
MarshalText implements the encoding.TextMarshaler interface.
The Size value is marshaled as a human-readable string (e.g., "1.50 MB"). This method is used by various encoding packages that work with text.
Example:
size := size.ParseUint64(1572864) // 1.5 MB text, _ := size.MarshalText() fmt.Println(string(text)) // Output: "1.50 MB"
func (Size) MarshalYAML ¶
MarshalYAML implements the yaml.Marshaler interface.
The Size value is marshaled as a human-readable string (e.g., "1.50 MB") for better readability in YAML configuration files.
Example:
size := size.ParseUint64(1572864) // 1.5 MB yaml, _ := yaml.Marshal(size) fmt.Println(string(yaml)) // Output: "1.50 MB\n"
func (Size) MegaBytes ¶
MegaBytes returns the size in megabytes (MB), floored to the nearest whole number.
Example:
size := size.ParseUint64(1572864) // 1.5 MB fmt.Println(size.MegaBytes()) // Output: 1 size := size.ParseUint64(2097152) // 2 MB fmt.Println(size.MegaBytes()) // Output: 2
func (*Size) Mul ¶ added in v1.14.0
Mul multiplies a Size by a float64 value.
This is a convenience wrapper for MulErr which discards any potential errors. See the documentation for MulErr for more information.
func (*Size) MulErr ¶ added in v1.19.0
MulErr multiplies a Size by a float64 value.
If the result overflowed (i.e. be greater than the maximum allowable size), the function will return an error and set the Size to the maximum allowable size.
Otherwise, it will set the Size to the result of the multiplication, rounded up to the nearest whole number.
func (Size) PetaBytes ¶
PetaBytes returns the size in petabytes (PB), floored to the nearest whole number.
Example:
size := size.ParseUint64(1688849860263936) // 1.5 PB fmt.Println(size.PetaBytes()) // Output: 1
func (Size) String ¶
String returns a human-readable string representation of the Size.
The method automatically selects the most appropriate unit (B, KB, MB, GB, TB, PB, EB) and formats the value with 2 decimal places (using FormatRound2).
Example:
size := size.ParseUint64(1572864) fmt.Println(size.String()) // Output: "1.50 MB" size := size.ParseUint64(1024) fmt.Println(size.String()) // Output: "1.00 KB"
func (*Size) Sub ¶ added in v1.14.0
Sub subtracts a uint64 value from a Size.
This is a convenience wrapper for SubErr which discards any potential errors. See the documentation for SubErr for more information.
func (*Size) SubErr ¶ added in v1.19.0
SubErr subtracts a uint64 value from a Size.
If the result underflow (i.e. be less than the minimum allowable size), the function will return an error and set the Size to the minimum allowable size.
Otherwise, it will set the Size to the result of the subtraction.
func (Size) TeraBytes ¶
TeraBytes returns the size in terabytes (TB), floored to the nearest whole number.
Example:
size := size.ParseUint64(1649267441664) // 1.5 TB fmt.Println(size.TeraBytes()) // Output: 1
func (Size) Uint ¶ added in v1.13.1
Uint converts the Size to a uint value representing bytes.
If the Size value is greater than math.MaxUint, the method returns math.MaxUint to prevent overflow.
Example:
size := size.ParseUint64(1024) fmt.Println(size.Uint()) // Output: 1024
func (Size) Uint32 ¶ added in v1.13.1
Uint32 converts the Size to a uint32 value representing bytes.
If the Size value is greater than math.MaxUint32, the method returns math.MaxUint32 to prevent overflow.
Example:
size := size.ParseUint64(1024) fmt.Println(size.Uint32()) // Output: 1024
func (Size) Uint64 ¶
Uint64 returns the Size value as a uint64 representing bytes.
This is the most direct way to get the raw byte count.
Example:
size := size.ParseUint64(1048576) fmt.Println(size.Uint64()) // Output: 1048576
func (Size) Unit ¶
Unit returns the unit string for the Size value.
The method automatically selects the most appropriate unit (B, KB, MB, GB, TB, PB, EB) based on the Size value. The unit parameter specifies the unit character to use (e.g., 'B' for Byte, 'o' for octet). If unit is 0, the default unit is used.
Example:
size := size.ParseUint64(1048576) // 1 MB
fmt.Println(size.Unit('B')) // Output: "MB"
fmt.Println(size.Unit('o')) // Output: "Mo"
See also: Code() for getting the unit code for predefined Size constants.
func (*Size) UnmarshalBinary ¶ added in v1.19.0
UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
This method uses CBOR decoding internally to deserialize binary data into a Size value.
Example:
var size size.Size size.UnmarshalBinary(data) fmt.Println(size.MegaBytes()) // Output: 1
func (*Size) UnmarshalCBOR ¶
UnmarshalCBOR implements CBOR unmarshaling using the fxamacker/cbor library.
The method decodes CBOR data containing a string representation of a size (e.g., "10MB") and parses it into a Size value.
See also: github.com/fxamacker/cbor
func (*Size) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface.
The method accepts both string representations (e.g., "10MB") and numeric values (e.g., 10485760). String values are parsed using the Parse function.
Example:
var size size.Size json.Unmarshal([]byte(`"10MB"`), &size) fmt.Println(size.MegaBytes()) // Output: 10
func (*Size) UnmarshalTOML ¶
UnmarshalTOML implements the TOML unmarshaler interface.
The method accepts both []byte and string representations (e.g., "10MB") from TOML files. Values are parsed using the Parse function.
Example:
var size size.Size // From TOML: max_size = "10MB" toml.Unmarshal(data, &config) // size will be 10MB
func (*Size) UnmarshalText ¶
UnmarshalText implements the encoding.TextUnmarshaler interface.
The method accepts text representations (e.g., "10MB") and parses them using the Parse function.
Example:
var size size.Size
size.UnmarshalText([]byte("10MB"))
fmt.Println(size.MegaBytes()) // Output: 10
func (*Size) UnmarshalYAML ¶
UnmarshalYAML implements the yaml.Unmarshaler interface.
The method accepts string representations (e.g., "10MB") from YAML files. String values are parsed using the Parse function.
Example:
var size size.Size
yaml.Unmarshal([]byte("10MB"), &size)
fmt.Println(size.MegaBytes()) // Output: 10