Size

Size is a Elixir library that helps you working with file sizes.

Installation

Add size to your list of dependencies in mix.exs:

def deps do
[{:size, "~> 0.1.0"}]
end

And run:

$ mix deps.get

What can you do with Size?

Specify sizes

Size defines a set of macros to improve specification of sizes.

Instead of define a magic number that nobody understand like:

disk_space = 12884901888

You can better do the following:

import Size, only: :macros
disk_space = gigabytes(12)

A lot better, right?.

You can also work using bits instead of bytes:

import Size, only: :macros
network_speed = megabits(3)

The list of macros available are:

For bytes (output always in bytes):

bytes(bytes)
kilobytes(kilobytes)
megabytes(megabytes)
gigabytes(gigabytes)
terabytes(terabytes)
petabytes(petabytes)
exabytes(exabytes)
zettabytes(zettabytes)
yottabytes(yottabytes)

For bits (output always in bits):

bits(bits)
kilobits(kilobits)
megabits(megabits)
gigabits(gigabits)
terabits(terabits)
petabits(petabits)
exabits(exabits)
zettabits(zettabits)
yottabits(yottabits)

Examples

bytes(2.1) # Input in bytes, output in bytes
3
kilobytes(1) # Input in kilobytes, output in bytes
1024
megabytes(1) # Input in megabytes, output in bytes
1048576
megabytes(2) # Input in megabytes, output in bytes
2097152
megabytes(2.1) # Input in megabytes, output in bytes
2202010
gigabytes(12) # Input in gigabytes, output in bytes
12884901888
bits(2.1) # Input in bits, output in bits
3
kilobits(1) # Input in kilobits, output in bits
1000
megabits(100) # Input in megabits, output in bits
100000000
gigabits(12.5) # Input in gigabits, output in bits
12500000000

Humanize file sizes

Size provide humanize(size, options) and humanize!(size, options) functions to generate human-readable file sizes.

Size.humanize(1024)
{:ok, "1 KB"}
Size.humanize!(1024)
"1 KB"

humanize returns {:ok, string}, where string is the humanized version of the size parameter or {:error, reason} if an error occurs.

humanize! returns a string with the humanized version of the size parameter or an exception is raised if an error occurs.

size input parameter should always be a integer quantity of bytes. Not floats or strings are supported.

Options

humanize allows a set of options to customize the formatting/output of the given size.

Author