mem_str.cpp
Go to the documentation of this file.
1 // Conversions of memory amounts and strings
2 // Author: Max Schwarz <max.schwarz@ais.uni-bonn.de>
3 
4 #include "mem_str.h"
5 
6 #include <fmt/format.h>
7 
8 #include <regex>
9 
10 namespace rosbag_fancy
11 {
12 namespace mem_str
13 {
14 
15 std::string memoryToString(uint64_t memory)
16 {
17  if(memory < static_cast<uint64_t>(1<<10))
18  return fmt::format("{}.0 B", memory);
19  else if(memory < static_cast<uint64_t>(1<<20))
20  return fmt::format("{:.1f} KiB", static_cast<double>(memory) / static_cast<uint64_t>(1<<10));
21  else if(memory < static_cast<uint64_t>(1<<30))
22  return fmt::format("{:.1f} MiB", static_cast<double>(memory) / static_cast<uint64_t>(1<<20));
23  else if(memory < static_cast<uint64_t>(1ull<<40))
24  return fmt::format("{:.1f} GiB", static_cast<double>(memory) / static_cast<uint64_t>(1ull<<30));
25  else
26  return fmt::format("{:.1f} TiB", static_cast<double>(memory) / static_cast<uint64_t>(1ull<<40));
27 }
28 
29 uint64_t stringToMemory(std::string humanSize)
30 {
31  // format should be "10MB" or "3 GB" or "10 B" or "10GiB"
32  static std::regex memoryRegex{R"EOS((\d+)\s*(K|M|G|T|E|)i?B?)EOS"};
33 
34  std::smatch match;
35  if(!std::regex_match(humanSize, match, memoryRegex))
36  {
37  fmt::print(stderr, "Could not parse memory string '{}' - it should be something like '120B' or '10GB'\n",
38  humanSize
39  );
40  std::exit(1);
41  }
42 
43  std::string number = match[1].str();
44  std::string unit = match[2].str();
45 
46  std::uint64_t multiplier = [&]() -> std::uint64_t {
47  if(unit.empty())
48  return 1;
49 
50  switch(unit[0])
51  {
52  case 'K': return 1ULL << 10;
53  case 'M': return 1ULL << 20;
54  case 'G': return 1ULL << 30;
55  case 'T': return 1ULL << 40;
56  case 'E': return 1ULL << 50;
57  }
58 
59  throw std::logic_error{"I got regexes wrong :("};
60  }();
61 
62  return std::stoull(humanSize) * multiplier;
63 }
64 
65 }
66 }
rosbag_fancy
Definition: bag_reader.cpp:240
rosbag_fancy::mem_str::stringToMemory
uint64_t stringToMemory(std::string humanSize)
Definition: mem_str.cpp:29
rosbag_fancy::mem_str::memoryToString
std::string memoryToString(uint64_t memory)
Definition: mem_str.cpp:15
format
std::string format
Definition: ui.cpp:76
mem_str.h


rosbag_fancy
Author(s):
autogenerated on Tue Feb 20 2024 03:20:59