/*
 * This file is part of DesktopBSD, see the README file.
 *
 * Author: Peter Hofer <ph@desktopbsd.net>
 *			(C) 2004, 2005
 *
 * Copyright: BSD, see the COPYING file included in this distribution
 *
 */

#include "size.h"

#include <qstring.h>

static const
daddr_t factor[] = {
	1,
	512,
	1024,
	1024 * 1024,
	1024 * 1024 * 1024,
	1024 * 1024 * 1024 * 1024
};

static const
QString name[] = {
	"Byte",
	"Blocks",
	"KB",
	"MB",
	"GB",
	"TB"
};


/** Constructor. If a size unit is specified,
  * it gets the default unit, otherwise
  * Size::Byte is the default unit.
  */
Size::Size(daddr_t size, Unit u) {
	defaultUnit = u;
	set(size, u);
}


bool  Size::operator== (const Size& size)  const {
	return value == size.value;
}


bool  Size::operator<  (const Size& size)  const {
	return value < size.value;
}


bool  Size::operator<= (const Size& size)  const {
	return value <= size.value;
}

bool  Size::operator>  (const Size& size)  const {
	return value > size.value;
}

bool  Size::operator>= (const Size& size)  const {
	return value >= size.value;
}

Size&  Size::operator=  (daddr_t size) {
	set(size, defaultUnit);
	return *this;
}


Size&  Size::operator=  (const Size& size) {
	value = size.value;
	return *this;
}


Size&  Size::operator+=  (daddr_t size) {
	value += size * factor[defaultUnit];
	return *this;
}


Size&  Size::operator+=  (const Size& size) {
	value += size.value;
	return *this;
}


void  Size::set(daddr_t size) {
	set(size, defaultUnit);
}


void  Size::set(daddr_t size, Unit u) {
	value = factor[u] * size;
}


daddr_t  Size::get()  const {
	return get(defaultUnit);
}


daddr_t  Size::get(Unit u)  const {
	return value / factor[u];
}


QString  Size::toString()  const {
	return toString(defaultUnit);
}


/** Returns a QString containing the size
  * and the unit, e.g. "1024 MB", "92917 Blocks"
  */
QString  Size::toString(Unit u)  const {
	return QString::number(get(u)) + " " + name[u];
}

/** Changes the default unit. */
void  Size::setDefaultUnit(Unit u) {
	defaultUnit = u;
}


Size::operator daddr_t ()  const {
	return get();
}

