Skip to content

threatfender/byte_count

Repository files navigation

ByteCount

✓ 100% test coverage✓ IEC/SI FormattingHexDocs

ByteCount is a tiny, dependency-free Elixir library for working with byte counts across multiple unit systems:

  • SI: kB -> kilobytes, MB -> megabytes, GB, etc.
  • IEC KiB -> kibibytes, MiB -> mebibytes, GiB, etc.

Features

Installation

Update your dependencies in mix.exs:

def deps do
  [
    {:byte_count, "~> 1.0"}
  ]
end

Reference

Area Function Example
C parse/1 ByteCount.parse("10kb")
parse!/1
C b/1, kb/1, mb/1, gb/1, tb/1, pb/1 ByteCount.kb(1).bytes == 1000
eb/1, zb/1, yb/1, rb/1, qb/1
C kib/1, mib/1, gib/1, tib/1, pib/1 ByteCount.kib(1).bytes == 1024
eib/1, zib/1, yib/1, rib/1, qib/1
F format/1, format/2, to_integer/1 ByteCount.format(byte_count)
A add/2, subtract/2, multiply/2, divide/2 ByteCount.add(bc1, bc2)

C = Construction, F = Formatting, A = Arithmethic.

Examples

  1. Construction - Construct byte count structs using the SI and IEC helpers:
# International System of Units (SI) -> powers of 10 (decimal).

iex> ByteCount.kb(4)
%ByteCount{bytes: 4000}

iex> ByteCount.parse!("4kb")
%ByteCount{bytes: 4000}
# International Electrotechnical Commission (IEC) -> power of 2 (binary).

iex> ByteCount.kib(4)
%ByteCount{bytes: 4096}

iex> ByteCount.mib(4)
%ByteCount{bytes: 1048576}

iex> ByteCount.parse!("4kib")
%ByteCount{bytes: 4096}
  1. Formatting - Display human-friendly byte counts:
iex(1)> ByteCount.kb(4) |> ByteCount.format()
"3.9 KiB"

iex(1)> ByteCount.kb(4) |> ByteCount.format(short: true)
"3.9K"

iex> ByteCount.kb(4) |> ByteCount.format(style: :si, short: true, precision: 2)
"4.0k"
  1. Arithmetic - Perform arithmetic operations:
iex> ByteCount.add(ByteCount.kb(4), ByteCount.kb(6))
%ByteCount{bytes: 10000}

License

ByteCount is open source software licensed under the Apache 2.0 License.

About

Parse and format byte counts using SI & IEC units

Resources

License

Stars

Watchers

Forks

Packages

No packages published