Inkscape
Vector Graphics Editor
Loading...
Searching...
No Matches
format_size.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: GPL-2.0-or-later
2
3#include "format_size.h"
4#include <glibmm/ustring.h>
5#include <sstream>
6
7namespace Inkscape {
8namespace Util {
9
10Glib::ustring format_size(std::size_t value) {
11 if (!value) {
12 return Glib::ustring("0");
13 }
14
15 typedef std::vector<char> Digits;
16 typedef std::vector<Digits *> Groups;
17
18 Groups groups;
19
20 Digits *digits;
21
22 while (value) {
23 unsigned places=3;
24 digits = new Digits();
25 digits->reserve(places);
26
27 while ( value && places ) {
28 digits->push_back('0' + (char)( value % 10 ));
29 value /= 10;
30 --places;
31 }
32
33 groups.push_back(digits);
34 }
35
36 Glib::ustring temp;
37
38 while (true) {
39 digits = groups.back();
40 while (!digits->empty()) {
41 temp.append(1, digits->back());
42 digits->pop_back();
43 }
44 delete digits;
45
46 groups.pop_back();
47 if (groups.empty()) {
48 break;
49 }
50
51 temp.append(",");
52 }
53
54 return temp;
55}
56
57Glib::ustring format_file_size(std::size_t value) {
58 std::ostringstream ost;
59 if (value < 1024) {
60 ost << value << " B";
61 }
62 else {
63 double size = value;
64 int index = 0;
65 do {
66 size /= 1024;
67 ++index;
68 } while (size > 1024);
69
70 static const char* unit[] = {"", "k", "M", "G", "T", "P", "E", "Z", "Y"};
71 ost.precision(1);
72 ost << std::fixed << size << ' ' << unit[index] << 'B';
73 }
74 return ost.str();
75}
76
77}} // namespace
Miscellaneous supporting code.
Definition document.h:93
Glib::ustring format_size(std::size_t value)
Glib::ustring format_file_size(std::size_t value)
Helper class to stream background task notifications as a series of messages.
int index