# -*- cperl -*-
# -----------------------------------------------------------------------------
# $Id: Kibibyte.pm,v 1.2 2004/09/29 03:14:34 admin Exp $
# -----------------------------------------------------------------------------
package Kibibyte;
use strict;
use warnings;
use Carp;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT_OK = qw(kibibyte_format);

*kibibyte_format = \&format;
sub format ($$) {
    # $amount: bytes
    # $format: "%.1f %s"
    # both format($amount, $format) and format($format, $amount) are valid.
    my ($format, $amount) = do {
	my $re = qr/%.*?f.*?%s/;
	if ($_[0] =~ m/$re/) {
	    ($_[0], $_[1]);
	}
	elsif ($_[1] =~ m/$re/) {
	    ($_[1], $_[0]);
	}
	else {
	    croak "Format error: neither `$_[0]' nor `$_[1]' is not a valid format";
	}
    };

    if ($amount >= 1024 ** 5) {
	sprintf $format, $amount / (1024 ** 5), 'Pib';
    }
    elsif ($amount >= 1024 ** 4) {
	sprintf $format, $amount / (1024 ** 4), 'Tib';
    }
    elsif ($amount >= 1024 ** 3) {
	sprintf $format, $amount / (1024 ** 3), 'Gib';
    }
    elsif ($amount >= 1024 ** 2) {
	sprintf $format, $amount / (1024 ** 2), 'Mib';
    }
    elsif ($amount >= 1024) {
	sprintf $format, $amount / 1024, 'Kib';
    }
    else {
	sprintf $format, $amount, 'Bytes';
    }
}

1;
