xref: /haiku/src/kits/shared/StringForRate.cpp (revision 13581b3d2a71545960b98fefebc5225b5bf29072)
1 /*
2  * Copyright 2012-2024, Haiku Inc. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 #include "StringForRate.h"
7 
8 #include <stdio.h>
9 
10 #include <Catalog.h>
11 #include <NumberFormat.h>
12 #include <StringFormat.h>
13 #include <SystemCatalog.h>
14 
15 
16 using BPrivate::gSystemCatalog;
17 
18 
19 #undef B_TRANSLATION_CONTEXT
20 #define B_TRANSLATION_CONTEXT "StringForRate"
21 
22 
23 namespace BPrivate {
24 
25 
26 const char*
27 string_for_rate(double rate, char* string, size_t stringSize)
28 {
29 	const char* kFormats[] = {
30 		B_TRANSLATE_MARK_COMMENT("{0, plural, one{%s byte/s} other{%s bytes/s}}",
31 			"units per second"),
32 		B_TRANSLATE_MARK_COMMENT("%s KiB/s", "units per second"),
33 		B_TRANSLATE_MARK_COMMENT("%s MiB/s", "units per second"),
34 		B_TRANSLATE_MARK_COMMENT("%s GiB/s", "units per second"),
35 		B_TRANSLATE_MARK_COMMENT("%s TiB/s", "units per second")
36 	};
37 
38 	size_t index = 0;
39 	while (index < B_COUNT_OF(kFormats) - 1 && rate >= 1024.0) {
40 		rate /= 1024.0;
41 		index++;
42 	}
43 
44 	BString format;
45 	BStringFormat formatter(
46 		gSystemCatalog.GetString(kFormats[index], B_TRANSLATION_CONTEXT, "units per second"));
47 	formatter.Format(format, rate);
48 
49 	BString printedRate;
50 	BNumberFormat numberFormat;
51 	numberFormat.SetPrecision(index == 0 ? 0 : 2);
52 	numberFormat.Format(printedRate, rate);
53 
54 	snprintf(string, stringSize, format.String(), printedRate.String());
55 
56 	return string;
57 }
58 
59 
60 }	// namespace BPrivate
61 
62