bytefmt

repository·main·Indexed 42 days ago

https://github.com/cloudfoundry/bytefmt

A 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.

Tokens
760
Snippets
5
Records
6
Agent score
3%

What's inside bytefmt

  1. Convert bytes to a human-readable string with ByteSize

    main

    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: Exabyte
    • P: Petabyte
    • T: Terabyte
    • G: Gigabyte
    • M: Megabyte
    • K: Kilobyte
    • B: Byte
    import "github.com/cloudfoundry/cloudfoundry/bytefmt"
    
    // Returns "100.5M"
    str := bytefmt.ByteSize(uint64(100.5 * bytefmt.MEGABYTE))
    
    // Returns "1K"
    str2 := bytefmt.ByteSize(1024)
  2. Parse human-readable byte strings with ToBytes

    main

    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 * 1024
  3. Convert human-readable strings to megabytes with ToMegabytes

    main

    Use 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 1024
  4. Byte unit constants

    main

    The 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
    )