size

package
v1.19.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 9 Imported by: 0

README

Size Package

Go Version

Type-safe, human-readable size representation library for Go with parsing, formatting, arithmetic operations, and comprehensive marshaling support.


Table of Contents


Overview

This library provides production-ready size value handling for Go applications. It emphasizes type safety, overflow protection, and flexibility while supporting multiple serialization formats and integration with popular configuration systems.

Design Philosophy
  1. Type-Safe: Size wraps uint64 to prevent accidental misuse as plain integers
  2. Overflow-Protected: All arithmetic operations detect and handle overflow/underflow
  3. Human-Readable: Automatic formatting with appropriate units (KB, MB, GB, etc.)
  4. Format-Agnostic: Marshaling/unmarshaling for JSON, YAML, TOML, CBOR, and plain text
  5. Configuration-Ready: Native integration with Viper through decode hooks

Key Features

  • Flexible Parsing: Parse size strings like "10MB", "1.5GB", "1GB500MB" with automatic unit detection
  • Safe Arithmetic: Multiply, divide, add, subtract with overflow/underflow protection
  • Multiple Units: Support for B, KB, MB, GB, TB, PB, EB (binary powers of 1024)
  • Rich Formatting: Convert to various numeric types with overflow detection
  • Universal Marshaling: JSON, YAML, TOML, CBOR, binary, and text encoding
  • Viper Integration: Seamless configuration file parsing with ViperDecoderHook()
  • Zero Dependencies: Only relies on standard library (except Viper hook)

Installation

go get github.com/nabbar/golib/size

Architecture

Type Structure
Size (uint64)
│
├── Parsing      → Parse(), ParseByte(), ParseInt64(), ParseFloat64()
├── Formatting   → String(), Format(), Unit()
├── Arithmetic   → Mul(), Div(), Add(), Sub() (with overflow protection)
├── Conversion   → Int64(), Uint64(), Float64(), KiloBytes(), etc.
└── Marshaling   → JSON, YAML, TOML, CBOR, Text, Binary
Component Overview
┌─────────────────────────────────────────────────────┐
│                   Size Package                      │
│  Parse, Format, Arithmetic, Marshal/Unmarshal       │
└───────┬──────────┬───────────┬──────────┬───────────┘
        │          │           │          │
   ┌────▼───┐ ┌────▼───┐ ┌─────▼────┐ ┌───▼─────────┐
   │ Parser │ │ Format │ │Arithmetic│ │  Encoding   │
   │        │ │        │ │          │ │             │
   │ String │ │ Human  │ │ Overflow │ │ JSON, YAML  │
   │ Numeric│ │ Machine│ │  Safety  │ │ TOML, CBOR  │
   └────────┘ └────────┘ └──────────┘ └─────────────┘
Component Purpose Safety Example
Parser Convert strings/numbers to Size Overflow checks Parse("10MB")
Formatter Convert Size to strings/numbers Overflow detection size.String()
Arithmetic Math operations on Size values Error on overflow size.MulErr(2.0)
Encoding Serialize/deserialize Type-safe json.Marshal(size)
Unit System

The package uses binary prefixes (powers of 1024):

B   = 1
KB  = 1024¹  = 1,024
MB  = 1024²  = 1,048,576
GB  = 1024³  = 1,073,741,824
TB  = 1024⁴  = 1,099,511,627,776
PB  = 1024⁵  = 1,125,899,906,842,624
EB  = 1024⁶  = 1,152,921,504,606,846,976

Note: This follows the traditional computing convention (1 KB = 1024 bytes), not the SI decimal system (1 kB = 1000 bytes).


Performance

Memory Efficiency
  • Size Type: 8 bytes (underlying uint64)
  • Zero Allocation: Parsing and formatting operations minimize heap allocations
  • Value Semantics: Pass by value is efficient; methods use pointer receivers only when modifying
Parsing Performance
BenchmarkParse          5000000    250 ns/op     32 B/op    2 allocs/op
BenchmarkParseComplex   2000000    650 ns/op     96 B/op    4 allocs/op
BenchmarkFormat         10000000   120 ns/op     48 B/op    2 allocs/op

Benchmarks on AMD64, Go 1.21

Thread Safety
  • Value Type: Size is a simple value type and safe to copy
  • Concurrent Reads: Safe across goroutines
  • Concurrent Writes: Use explicit synchronization for pointer receivers (Mul, Add, etc.)

Use Cases

This library is designed for scenarios requiring type-safe size handling:

Configuration Files

  • Parse size limits from YAML/TOML/JSON configurations
  • Human-readable format (e.g., max_upload: "100MB")
  • Type-safe validation with Viper integration

Resource Management

  • Memory allocation limits
  • File size restrictions
  • Quota enforcement with overflow protection

CLI Applications

  • Parse user input for size flags (e.g., --max-size 1.5GB)
  • Display progress with formatted output
  • Validate size constraints

Storage Systems

  • Calculate disk usage with safe arithmetic
  • Compare file sizes with type safety
  • Aggregate storage metrics

Logging & Monitoring

  • Format byte counts in human-readable form
  • Track memory usage over time
  • Alert on size thresholds

Quick Start

Basic Parsing

Parse size strings with automatic unit detection:

package main

import (
    "fmt"
    "github.com/nabbar/golib/size"
)

func main() {
    // Parse from string
    s, err := size.Parse("10MB")
    if err != nil {
        panic(err)
    }
    fmt.Println(s.String())        // Output: "10.00 MB"
    fmt.Println(s.Uint64())        // Output: 10485760
    fmt.Println(s.MegaBytes())     // Output: 10
}
Arithmetic Operations

Perform safe arithmetic with overflow detection:

package main

import (
    "fmt"
    "github.com/nabbar/golib/size"
)

func main() {
    s := size.ParseUint64(1024 * 1024) // 1 MB
    
    // Multiply (with error checking)
    err := s.MulErr(2.5)
    if err != nil {
        fmt.Println("Overflow detected!")
    }
    fmt.Println(s.String()) // Output: "2.50 MB"
    
    // Add
    s.Add(512 * 1024) // Add 512 KB
    fmt.Println(s.String()) // Output: "3.00 MB"
    
    // Subtract
    s.Sub(1024 * 1024) // Subtract 1 MB
    fmt.Println(s.String()) // Output: "2.00 MB"
}
JSON Marshaling

Automatic serialization to human-readable format:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/nabbar/golib/size"
)

type Config struct {
    MaxUpload size.Size `json:"max_upload"`
    MaxFile   size.Size `json:"max_file"`
}

func main() {
    cfg := Config{
        MaxUpload: size.ParseUint64(100 * 1024 * 1024), // 100 MB
        MaxFile:   size.ParseUint64(10 * 1024 * 1024),  // 10 MB
    }
    
    // Marshal to JSON
    data, _ := json.MarshalIndent(cfg, "", "  ")
    fmt.Println(string(data))
    // Output:
    // {
    //   "max_upload": "100.00 MB",
    //   "max_file": "10.00 MB"
    // }
    
    // Unmarshal from JSON
    input := `{"max_upload": "200MB", "max_file": "20MB"}`
    var newCfg Config
    json.Unmarshal([]byte(input), &newCfg)
    fmt.Println(newCfg.MaxUpload.MegaBytes()) // Output: 200
}
Viper Integration

Seamless configuration parsing with Viper:

package main

import (
    "github.com/nabbar/golib/size"
    "github.com/spf13/viper"
    libmap "github.com/go-viper/mapstructure/v2"
)

type ServerConfig struct {
    MaxRequestSize  size.Size `mapstructure:"max_request_size"`
    MaxUploadSize   size.Size `mapstructure:"max_upload_size"`
    CacheSize       size.Size `mapstructure:"cache_size"`
}

func main() {
    v := viper.New()
    v.SetConfigFile("config.yaml")
    v.ReadInConfig()
    
    var cfg ServerConfig
    err := v.Unmarshal(&cfg, viper.DecodeHook(
        libmap.ComposeDecodeHookFunc(
            size.ViperDecoderHook(),
            libmap.StringToTimeDurationHookFunc(),
        ),
    ))
    
    if err != nil {
        panic(err)
    }
    
    // Now cfg.MaxRequestSize is properly parsed
    fmt.Println(cfg.MaxRequestSize.MegaBytes())
}

config.yaml:

max_request_size: "10MB"
max_upload_size: "100MB"
cache_size: 1073741824  # Can use numeric values too
Complex Parsing

Parse complex size expressions:

package main

import (
    "fmt"
    "github.com/nabbar/golib/size"
)

func main() {
    // Multiple units in one string
    s, _ := size.Parse("1GB500MB")
    fmt.Println(s.String()) // Output: "1.49 GB"
    
    // Fractional values
    s, _ = size.Parse("2.5TB")
    fmt.Println(s.TeraBytes()) // Output: 2
    
    // Different unit variations
    examples := []string{
        "10MB", "10Mb", "10mb", "10M",  // All parse to 10 megabytes
        "1.5GB", "1GB500MB",             // Same value
    }
    
    for _, ex := range examples {
        s, _ := size.Parse(ex)
        fmt.Printf("%-12s = %d bytes\n", ex, s.Uint64())
    }
}

API Reference

Parsing Functions
// Parse from string (most common)
size, err := size.Parse("10MB")

// Parse from byte slice
size, err := size.ParseByte([]byte("10MB"))

// Convert from numeric types
size := size.ParseUint64(1048576)
size := size.ParseInt64(-1048576)   // Converts to absolute value
size := size.ParseFloat64(1048576.5)
Arithmetic Operations

All arithmetic operations have two variants:

  • Non-error: Ignores overflow (e.g., Mul())
  • Error-returning: Returns error on overflow (e.g., MulErr())
size := size.ParseUint64(1024)

// Multiplication
size.Mul(2.0)              // size *= 2
err := size.MulErr(2.0)    // Returns error on overflow

// Division
size.Div(2.0)              // size /= 2
err := size.DivErr(2.0)    // Returns error if divisor ≤ 0

// Addition
size.Add(512)              // size += 512
err := size.AddErr(512)    // Returns error on overflow

// Subtraction
size.Sub(256)              // size -= 256
err := size.SubErr(256)    // Returns error on underflow
Formatting
size := size.ParseUint64(1572864) // 1.5 MB

// Human-readable string
size.String()                   // "1.50 MB"
size.Format(size.FormatRound0)  // "2"
size.Format(size.FormatRound1)  // "1.5"
size.Format(size.FormatRound2)  // "1.50"
size.Format(size.FormatRound3)  // "1.500"

// Get unit only
size.Unit('B')  // "MB"
size.Unit('o')  // "Mo" (useful for French/other locales)
Type Conversion
size := size.ParseUint64(1048576)

// Integer types (with overflow protection)
size.Int64()   // 1048576
size.Int32()   // 1048576 (or MaxInt32 if too large)
size.Int()     // 1048576
size.Uint64()  // 1048576
size.Uint32()  // 1048576 (or MaxUint32 if too large)
size.Uint()    // 1048576

// Float types (with overflow protection)
size.Float64() // 1048576.0
size.Float32() // 1048576.0

// Unit-specific conversions
size.KiloBytes() // 1024
size.MegaBytes() // 1
size.GigaBytes() // 0
Constants
size.SizeNul   // 0
size.SizeUnit  // 1 B
size.SizeKilo  // 1024 B
size.SizeMega  // 1048576 B
size.SizeGiga  // 1073741824 B
size.SizeTera  // 1099511627776 B
size.SizePeta  // 1125899906842624 B
size.SizeExa   // 1152921504606846976 B
Format Constants
size.FormatRound0 // "%.0f" - no decimal places
size.FormatRound1 // "%.1f" - 1 decimal place
size.FormatRound2 // "%.2f" - 2 decimal places (default)
size.FormatRound3 // "%.3f" - 3 decimal places
Marshaling

The Size type implements multiple encoding interfaces:

// JSON
json.Marshal(size)     // Outputs: "1.50 MB"
json.Unmarshal(data, &size)

// YAML
yaml.Marshal(size)     // Outputs: 1.50 MB
yaml.Unmarshal(data, &size)

// TOML
toml.Marshal(size)
toml.Unmarshal(data, &size)

// Text encoding
size.MarshalText()
size.UnmarshalText([]byte("10MB"))

// Binary (CBOR)
size.MarshalBinary()
size.UnmarshalBinary(data)

Best Practices

Use Parse() for String Input

// ✅ Good: Parse and handle errors
func setLimit(input string) error {
    limit, err := size.Parse(input)
    if err != nil {
        return fmt.Errorf("invalid size: %w", err)
    }
    server.SetLimit(limit)
    return nil
}

// ❌ Bad: No validation
func setLimitBad(input string) {
    limit, _ := size.Parse(input)
    server.SetLimit(limit)
}

Check Arithmetic Errors

// ✅ Good: Check for overflow
func calculateTotal(sizes []size.Size) (size.Size, error) {
    total := size.SizeNul
    for _, s := range sizes {
        if err := total.AddErr(s.Uint64()); err != nil {
            return 0, fmt.Errorf("size overflow: %w", err)
        }
    }
    return total, nil
}

// ❌ Bad: Silent overflow
func calculateTotalBad(sizes []size.Size) size.Size {
    total := size.SizeNul
    for _, s := range sizes {
        total.Add(s.Uint64())
    }
    return total
}

Use Type Conversion Safely

// ✅ Good: Check for overflow potential
func toInt32(s size.Size) (int32, error) {
    if s.Uint64() > math.MaxInt32 {
        return 0, errors.New("size too large for int32")
    }
    return s.Int32(), nil
}

// ❌ Bad: Assume no overflow
func toInt32Bad(s size.Size) int32 {
    return s.Int32() // May return MaxInt32 silently
}

Consistent Units in Configuration

// ✅ Good: Human-readable config
type Config struct {
    MaxFileSize   size.Size `json:"max_file_size"`   // User can write "100MB"
    MaxUploadSize size.Size `json:"max_upload_size"` // User can write "1GB"
}

// ❌ Bad: Raw byte counts
type ConfigBad struct {
    MaxFileSize   uint64 `json:"max_file_size"`   // User must calculate 104857600
    MaxUploadSize uint64 `json:"max_upload_size"` // User must calculate 1073741824
}

Marshal to Human-Readable Format

// ✅ Good: Easy to read
type APIResponse struct {
    TotalSize     size.Size `json:"total_size"`
    AvailableSize size.Size `json:"available_size"`
}
// JSON output: {"total_size": "10.50 GB", "available_size": "5.25 GB"}

// ❌ Bad: Requires client-side formatting
type APIResponseBad struct {
    TotalSize     uint64 `json:"total_size"`
    AvailableSize uint64 `json:"available_size"`
}
// JSON output: {"total_size": 11274289152, "available_size": 5637144576}

Testing

Test Suite: 352 specs using Ginkgo v2 and Gomega (95.4% coverage)

# Run tests
go test ./...

# With coverage
go test -cover ./...

# With race detection (recommended)
CGO_ENABLED=1 go test -race ./...

Coverage Areas

  • Parsing (strings, numbers, complex expressions)
  • Arithmetic operations (overflow/underflow handling)
  • Type conversions (all numeric types)
  • Formatting (various precision levels)
  • Marshaling (JSON, YAML, TOML, CBOR, Text, Binary)
  • Viper integration (decode hook with multiple types)
  • Edge cases (maximum values, zero, negative inputs)

Quality Assurance

  • ✅ Zero data races (verified with -race)
  • ✅ 95.4% code coverage
  • ✅ All overflow/underflow scenarios tested
  • ✅ Cross-format marshaling verified

See TESTING.md for detailed testing documentation.


Contributing

Contributions are welcome! Please follow these guidelines:

Code Contributions

  • Do not use AI to generate package implementation code
  • AI may assist with tests, documentation, and bug fixing
  • All contributions must pass go test -race
  • Maintain or improve test coverage (≥95%)
  • Follow existing code style and patterns

Documentation

  • Update README.md for new features
  • Add examples for common use cases
  • Keep TESTING.md synchronized with test changes

Testing

  • Write tests for all new features
  • Test edge cases and error conditions
  • Verify overflow/underflow protection
  • Add comments explaining complex scenarios

Pull Requests

  • Provide clear description of changes
  • Reference related issues
  • Include test results
  • Update documentation

See CONTRIBUTING.md for detailed guidelines.


Future Enhancements

Potential improvements for future versions:

Unit Systems

  • SI decimal prefixes (kB, MB, GB = powers of 1000)
  • IEC binary prefixes (KiB, MiB, GiB = powers of 1024) with explicit notation
  • User-selectable unit system

Parsing Features

  • Negative size values with explicit semantics
  • Unit aliases (e.g., "megabytes", "megs")
  • Localized unit names
  • Scientific notation support (e.g., "1e6")

Formatting Options

  • Custom format strings
  • Locale-aware number formatting
  • Compact notation (e.g., "10M" instead of "10.00 MB")
  • Adaptive precision based on magnitude

Arithmetic

  • Checked arithmetic mode (panic on overflow)
  • Saturation arithmetic mode (clamp to max/min)
  • Fixed-point arithmetic for precise fractional operations

Performance

  • Zero-allocation parsing for common patterns
  • String interning for frequently used values
  • SIMD-accelerated parsing

Suggestions and contributions are welcome via GitHub issues.


AI Transparency Notice

In accordance with Article 50.4 of the EU AI Act, AI assistance has been used for testing, documentation, and bug fixing under human supervision.


License

MIT License - See LICENSE file for details.


Resources

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

View Source
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

func GetSize(s string) (sizeBytes Size, success bool)

GetSize parses a size string and returns a Size value and a boolean indicating success. Deprecated: see Parse

func Parse

func Parse(s string) (Size, error)

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

func ParseByte(p []byte) (Size, error)

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

func ParseByteAsSize(p []byte) (Size, error)

ParseByteAsSize parses a byte slice into a Size value. Deprecated: see ParseByte

func ParseFloat64 added in v1.19.0

func ParseFloat64(s float64) Size

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

func ParseInt64(s int64) Size

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 ParseSize

func ParseSize(s string) (Size, error)

ParseSize parses a size string into a Size value. Deprecated: see Parse

func ParseUint64 added in v1.19.0

func ParseUint64(s uint64) Size

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

func SizeFromFloat64(val float64) Size

SizeFromFloat64 converts a float64 value into a Size value. Deprecated: see ParseFloat64

func SizeFromInt64

func SizeFromInt64(val int64) Size

SizeFromInt64 converts an int64 value into a Size value. Deprecated: see ParseInt64

func (*Size) Add added in v1.14.0

func (s *Size) Add(v uint64)

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

func (s *Size) AddErr(v uint64) error

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

func (s Size) Code(unit rune) string

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

func (s *Size) Div(v float64)

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

func (s *Size) DivErr(v float64) error

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

func (s Size) ExaBytes() uint64

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

func (s Size) Float32() float32

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

func (s Size) Float64() 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

func (s Size) Format(format string) string

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

func (s Size) GigaBytes() uint64

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

func (s Size) Int() int

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

func (s Size) Int32() int32

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

func (s Size) Int64() 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

func (s Size) KiloBytes() uint64

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

func (s Size) MarshalBinary() ([]byte, error)

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

func (s Size) MarshalCBOR() ([]byte, error)

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

func (s Size) MarshalJSON() ([]byte, error)

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

func (s Size) MarshalTOML() ([]byte, error)

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

func (s Size) MarshalText() ([]byte, error)

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

func (s Size) MarshalYAML() (interface{}, error)

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

func (s Size) MegaBytes() uint64

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

func (s *Size) Mul(v float64)

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

func (s *Size) MulErr(v float64) error

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

func (s Size) PetaBytes() uint64

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

func (s Size) String() 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

func (s *Size) Sub(v uint64)

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

func (s *Size) SubErr(v uint64) error

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

func (s Size) TeraBytes() uint64

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

func (s Size) Uint() uint

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

func (s Size) Uint32() uint32

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

func (s Size) Uint64() 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

func (s Size) Unit(unit rune) string

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

func (s *Size) UnmarshalBinary(p []byte) error

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

func (s *Size) UnmarshalCBOR(p []byte) error

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

func (s *Size) UnmarshalJSON(p []byte) error

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

func (s *Size) UnmarshalTOML(i interface{}) error

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

func (s *Size) UnmarshalText(p []byte) error

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

func (s *Size) UnmarshalYAML(value *yaml.Node) error

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL