From b1a33a494f7a9510f600cb18e771b35905597be6 Mon Sep 17 00:00:00 2001 From: rubidium Date: Fri, 16 Jan 2009 12:59:47 +0000 Subject: (svn r15104) -Codechange: unify the resolving of the xyz kbytes/megabytes strings. --- src/strings.cpp | 46 +++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 41 insertions(+), 5 deletions(-) (limited to 'src/strings.cpp') diff --git a/src/strings.cpp b/src/strings.cpp index c4daa6753..aee7c8eb7 100644 --- a/src/strings.cpp +++ b/src/strings.cpp @@ -264,6 +264,43 @@ static char *FormatHexNumber(char *buff, int64 number, const char *last) return buff + seprintf(buff, last, "0x%x", (uint32)number); } +/** + * Format a given number as a number of bytes with the SI prefix. + * @param buff the buffer to write to + * @param number the number of bytes to write down + * @param last the last element in the buffer + * @return till where we wrote + */ +static char *FormatBytes(char *buff, int64 number, const char *last) +{ + assert(number >= 0); + + /* 0 2^10 2^20 2^30 2^40 2^50 2^60 */ + const char *siUnits[] = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB" }; + int id = 1; + while (number >= 1024 * 1024) { + number /= 1024; + id++; + } + + if (number < 1024) { + id = 0; + buff += seprintf(buff, last, "%i", (int)number); + } else if (number < 1024 * 10) { + buff += seprintf(buff, last, "%i.%02i", (int)number / 1024, (int)(number % 1024) * 100 / 1024); + } else if (number < 1024 * 100) { + buff += seprintf(buff, last, "%i.%01i", (int)number / 1024, (int)(number % 1024) * 10 / 1024); + } else { + assert(number < 1024 * 1024); + buff += seprintf(buff, last, "%i", (int)number / 1024); + } + + assert(id < lengthof(siUnits)); + buff += seprintf(buff, last, " %s", siUnits[id]); + + return buff; +} + static char *FormatYmdString(char *buff, Date date, const char *last) { YearMonthDay ymd; @@ -820,6 +857,10 @@ static char *FormatString(char *buff, const char *str, const int64 *argv, uint c buff = FormatHexNumber(buff, GetInt64(&argv), last); break; + case SCC_BYTES: // {BYTES} + buff = FormatBytes(buff, GetInt64(&argv), last); + break; + case SCC_CURRENCY: // {CURRENCY} buff = FormatGenericCurrency(buff, _currency, GetInt64(&argv), false, last); break; @@ -1585,9 +1626,4 @@ void CheckForMissingGlyphsInLoadedLanguagePack() ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0); } #endif - } - - -/* --- Handling of saving/loading string IDs from old savegames --- */ - -- cgit v1.2.3-70-g09d2