xref: /haiku/src/kits/shared/StringForSize.cpp (revision 922e7ba1f3228e6f28db69b0ded8f86eb32dea17)
1 /*
2  * Copyright 2010 Haiku Inc. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 #include "StringForSize.h"
7 
8 #include <stdio.h>
9 
10 #include <Catalog.h>
11 #include <LocaleBackend.h>
12 using BPrivate::gLocaleBackend;
13 using BPrivate::LocaleBackend;
14 
15 
16 #undef B_TRANSLATE_CONTEXT
17 #define B_TRANSLATE_CONTEXT "StringForSize"
18 
19 
20 namespace BPrivate {
21 
22 
23 const char*
24 string_for_size(double size, char* string, size_t stringSize)
25 {
26 	// we need to translate some strings, and in order to do so, we need
27 	// to use the LocaleBackend to reache liblocale.so
28 	if (gLocaleBackend == NULL)
29 		LocaleBackend::LoadBackend();
30 	double kib = size / 1024.0;
31 	if (kib < 1.0) {
32 		const char* trKey = B_TRANSLATE_MARK("%d bytes");
33 		snprintf(string, stringSize, gLocaleBackend->GetString(trKey,
34 			B_TRANSLATE_CONTEXT), (int)size);
35 		return string;
36 	}
37 	double mib = kib / 1024.0;
38 	if (mib < 1.0) {
39 		const char* trKey = B_TRANSLATE_MARK("%3.2f KiB");
40 		snprintf(string, stringSize, gLocaleBackend->GetString(trKey,
41 			B_TRANSLATE_CONTEXT), kib);
42 		return string;
43 	}
44 	double gib = mib / 1024.0;
45 	if (gib < 1.0) {
46 		const char* trKey = B_TRANSLATE_MARK("%3.2f MiB");
47 		snprintf(string, stringSize, gLocaleBackend->GetString(trKey,
48 			B_TRANSLATE_CONTEXT), mib);
49 		return string;
50 	}
51 	double tib = gib / 1024.0;
52 	if (tib < 1.0) {
53 		const char* trKey = B_TRANSLATE_MARK("%3.2f GiB");
54 		snprintf(string, stringSize, gLocaleBackend->GetString(trKey,
55 			B_TRANSLATE_CONTEXT), gib);
56 		return string;
57 	}
58 	const char* trKey = B_TRANSLATE_MARK("%.2f TiB");
59 	snprintf(string, stringSize, gLocaleBackend->GetString(trKey,
60 		B_TRANSLATE_CONTEXT), tib);
61 	return string;
62 }
63 
64 
65 }	// namespace BPrivate
66 
67