diff --git a/gio-qt/include/dglibutils.h b/gio-qt/include/dglibutils.h index 4f5ce8e..367ab5c 100644 --- a/gio-qt/include/dglibutils.h +++ b/gio-qt/include/dglibutils.h @@ -37,6 +37,15 @@ enum DGlibUserDirectory }; Q_ENUMS(DGlibUserDirectory); +enum DGlibFormatSizeFlag +{ + FORMAT_SIZE_DEFAULT = 0x0, + FORMAT_SIZE_LONG_FORMAT = 1 << 0, + FORMAT_SIZE_IEC_UNITS = 1 << 1, + FORMAT_SIZE_BITS = 1 << 2 +}; +Q_DECLARE_FLAGS(DGlibFormatSizeFlags, DGlibFormatSizeFlag) + class DGlibUtils { public: @@ -44,6 +53,7 @@ public: static QStringList systemDataDirs(); static QString userDataDir(); static QString tmpDir(); + static QString formatSize(quint64 size, DGlibFormatSizeFlags flags = FORMAT_SIZE_DEFAULT); }; #endif // DGLIBUTILS_H diff --git a/gio-qt/source/dglibutils.cpp b/gio-qt/source/dglibutils.cpp index 00cf716..6daf4b2 100644 --- a/gio-qt/source/dglibutils.cpp +++ b/gio-qt/source/dglibutils.cpp @@ -93,3 +93,21 @@ QString DGlibUtils::tmpDir() { return QString::fromStdString(Glib::get_tmp_dir()); } + +/*! + * \brief Formats a size (for example the size of a file) into a human readable string. + * + * Sizes are rounded to the nearest size prefix (kB, MB, GB) and are displayed rounded to the nearest tenth. E.g. the file + * size 3292528 bytes will be converted into the string "3.2 MB". + * + * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes), unless the DGlibFormatSizeFlags::FORMAT_SIZE_IEC_UNITS flag is set. + * + * \param size A size in bytes. + * \param flags Flags to modify the output. + * \return A formatted string containing a human readable file size. + */ +QString DGlibUtils::formatSize(quint64 size, DGlibFormatSizeFlags flags) +{ + unsigned int flagValue = flags; + return QString::fromStdString(Glib::format_size(size, static_cast(flagValue))); +} diff --git a/test/tst_matchgioenum.cpp b/test/tst_matchgioenum.cpp index 3b2fef2..bf98a68 100644 --- a/test/tst_matchgioenum.cpp +++ b/test/tst_matchgioenum.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include @@ -15,6 +16,7 @@ public: DGioMatchGioEnumTest(); private Q_SLOTS: + void testCase_DGlibUtilsClass(); void testCase_DGioFileClass(); void testCase_DGioFileInfoClass(); void testCase_DGioMountOperationClass(); @@ -25,6 +27,14 @@ DGioMatchGioEnumTest::DGioMatchGioEnumTest() // } +void DGioMatchGioEnumTest::testCase_DGlibUtilsClass() +{ + QCOMPARE(DGlibFormatSizeFlag::FORMAT_SIZE_DEFAULT, Glib::FORMAT_SIZE_DEFAULT); + QCOMPARE(DGlibFormatSizeFlag::FORMAT_SIZE_LONG_FORMAT, Glib::FORMAT_SIZE_LONG_FORMAT); + QCOMPARE(DGlibFormatSizeFlag::FORMAT_SIZE_IEC_UNITS, Glib::FORMAT_SIZE_IEC_UNITS); + QCOMPARE(DGlibFormatSizeFlag::FORMAT_SIZE_BITS, Glib::FORMAT_SIZE_BITS); +} + void DGioMatchGioEnumTest::testCase_DGioFileClass() { QCOMPARE(DGioFileQueryInfoFlag::FILE_QUERY_INFO_NONE, Gio::FILE_QUERY_INFO_NONE);