SILICON
Loading...
Searching...
No Matches
num_formatting.cpp
Go to the documentation of this file.
1/*
2 Copyright (c) 2026. Giulio Cocconi
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18#include "num_formatting.hpp"
19
20#include <boost/multiprecision/cpp_int/import_export.hpp>
21
22#include <algorithm>
23#include <cctype>
24#include <format>
25#include <ios>
26#include <iterator>
27#include <map>
28#include <ranges>
29#include <stdexcept>
30#include <utility>
31#include <vector>
32
33#include <core/wireUtils.hpp>
34
35namespace SILICON::core {
36namespace {
37
38 const std::map<BusValueFormat, std::string> formatPrefix{
40 {BusValueFormat::Hex, "0x"},
41 {BusValueFormat::Oct, "0o"},
42 {BusValueFormat::Bin, "0b"},
43 };
44
45 const std::map<BusValueFormat, std::string> formatAlphabet{
47 std::format("{}{}{}{}", static_cast<char>(std::to_underlying(State::LOW)),
48 static_cast<char>(std::to_underlying(State::HIGH)),
49 static_cast<char>(std::to_underlying(State::UNKNOWN)),
50 static_cast<char>(std::to_underlying(State::ERROR)))},
51 {BusValueFormat::Signed, "0123456789"},
52 {BusValueFormat::Unsigned, "0123456789"},
53 {BusValueFormat::Oct, "01234567"},
54 {BusValueFormat::Hex, "0123456789ABCDEF"},
55 {BusValueFormat::Bin, "01"},
56 };
57
58 bool satisfiesAlphabet(const std::string_view DIGITS, const BusValueFormat format)
59 {
60 const auto alphabet = formatAlphabet.at(format);
61
62 return !DIGITS.empty() && std::ranges::all_of(DIGITS, [alphabet](const char digit) {
63 return alphabet.contains(toupper(digit));
64 });
65 };
66
67 char upper(const char value)
68 {
69 return static_cast<char>(std::toupper(static_cast<unsigned char>(value)));
70 }
71
72 std::string_view trim(std::string_view text)
73 {
74 while (!text.empty() && std::isspace(static_cast<unsigned char>(text.front())) != 0)
75 text.remove_prefix(1);
76 while (!text.empty() && std::isspace(static_cast<unsigned char>(text.back())) != 0)
77 text.remove_suffix(1);
78 return text;
79 }
80
81 bool startsWithIgnoreCase(const std::string_view value, const std::string_view prefix)
82 {
83 return value.size() >= prefix.size()
84 && std::ranges::equal(
85 value.substr(0, prefix.size()), prefix,
86 [](const char lhs, const char rhs) { return upper(lhs) == upper(rhs); });
87 }
88
89 [[nodiscard]] std::pair<BusValueFormat, std::string_view>
90 getFormat(std::string_view value)
91 {
92 value = trim(value);
93 if (value.empty())
94 return {BusValueFormat::Unknown, {}};
95
96 // Explicit prefixes take precedence over the raw alphabet (notably for 0xE).
97 for (const auto& [format, prefix] : formatPrefix) {
98 if (!startsWithIgnoreCase(value, prefix))
99 continue;
100
101 const auto DIGITS = value.substr(prefix.size());
102 if (satisfiesAlphabet(DIGITS, format))
103 return {format, DIGITS};
104 }
105
106 for (const auto& [format, _] : formatAlphabet) {
107 if (formatPrefix.contains(format))
108 continue;
109
110 auto DIGITS = value;
111 if (satisfiesAlphabet(DIGITS, format))
112 return {format, DIGITS};
113 }
114 return {BusValueFormat::Unknown, {}};
115 }
116
117 BigInt parseMagnitude(const std::string_view DIGITS, const BusValueFormat format)
118 {
119 if (format == BusValueFormat::Bin) {
120 std::vector<unsigned char> bits;
121 bits.reserve(DIGITS.size());
122 std::ranges::transform(DIGITS, std::back_inserter(bits),
123 [](const char bit) { return bit == '1'; });
124
125 BigInt result;
126 boost::multiprecision::import_bits(result, bits.begin(), bits.end(), 1, true);
127 return result;
128 }
129
130 auto firstNonZero = DIGITS.find_first_not_of('0');
131 if (firstNonZero == std::string_view::npos)
132 return 0;
133
134 std::string encoded(DIGITS.substr(firstNonZero));
135 switch (format) {
136 case BusValueFormat::Hex: encoded.insert(0, "0x"); break;
137 case BusValueFormat::Oct: encoded.insert(0, "0"); break;
139 case BusValueFormat::Unsigned: break;
140 default: throw std::invalid_argument("Invalid integer input format");
141 }
142
143 return BigInt(encoded);
144 }
145
146 std::size_t magnitudeWidth(const BigInt& value)
147 {
148 return value == 0 ? 1
149 : static_cast<std::size_t>(boost::multiprecision::msb(value)) + 1;
150 }
151
152 std::string formatBigInt(const BigInt& value, const BusValueFormat format)
153 {
154 switch (format) {
156 case BusValueFormat::Unsigned: return value.str();
158 return value.str(0, std::ios_base::hex | std::ios_base::uppercase);
159 case BusValueFormat::Oct: return value.str(0, std::ios_base::oct);
160 default: throw std::invalid_argument("Invalid integer output format");
161 }
162 }
163
164} // namespace
165
166std::string formatInteger(const BigInt& value, const BusValueFormat format,
167 const std::size_t bitWidth)
168{
169 if (bitWidth == 0)
170 throw std::invalid_argument("Integer bit width must be positive");
171
172 const BigInt modulus = BigInt{1} << bitWidth;
173 BigInt number = value & (modulus - 1);
174
175 switch (format) {
177 if ((number & (BigInt{1} << (bitWidth - 1))) != 0)
178 number -= modulus;
179 return formatBigInt(number, format);
180 }
181 case BusValueFormat::Unsigned: return formatBigInt(number, format);
182 case BusValueFormat::Bin: {
183 const auto bits = busValueFromInteger(number, bitWidth);
184 return bits | std::views::reverse | std::views::transform([](const State state) {
185 return static_cast<char>(std::to_underlying(state));
186 })
187 | std::ranges::to<std::string>();
188 }
190 case BusValueFormat::Hex: return formatBigInt(number, format);
193 throw std::invalid_argument("Invalid integer output format");
194 }
195 throw std::invalid_argument("Invalid integer output format");
196}
197
198std::optional<BigInt> parseInteger(std::string_view text, const BusValueFormat format,
199 const std::size_t bitWidth)
200{
201 if (bitWidth == 0)
202 return std::nullopt;
203 text = trim(text);
204 if (text.empty())
205 return std::nullopt;
206
207 const BigInt modulus = BigInt{1} << bitWidth;
208 if (format == BusValueFormat::Signed) {
209 bool negative = false;
210 if (text.front() == '+' || text.front() == '-') {
211 negative = text.front() == '-';
212 text.remove_prefix(1);
213 }
214 if (!satisfiesAlphabet(text, format))
215 return std::nullopt;
216
217 BigInt value = parseMagnitude(text, format);
218 if (negative)
219 value = -value;
220
221 const BigInt minimum = -(BigInt{1} << (bitWidth - 1));
222 const BigInt maximum = (BigInt{1} << (bitWidth - 1)) - 1;
223 if (value < minimum || value > maximum)
224 return std::nullopt;
225 if (value < 0)
226 value += modulus;
227 return value;
228 }
229
230 if (format == BusValueFormat::Unsigned && text.front() == '+')
231 text.remove_prefix(1);
232
233 if (format != BusValueFormat::Unsigned && format != BusValueFormat::Bin
234 && format != BusValueFormat::Oct && format != BusValueFormat::Hex)
235 return std::nullopt;
236
237 if (format == BusValueFormat::Bin && startsWithIgnoreCase(text, "0b"))
238 text.remove_prefix(2);
239 else if (format == BusValueFormat::Oct && startsWithIgnoreCase(text, "0o"))
240 text.remove_prefix(2);
241 else if (format == BusValueFormat::Hex && startsWithIgnoreCase(text, "0x"))
242 text.remove_prefix(2);
243
244 if (!satisfiesAlphabet(text, format))
245 return std::nullopt;
246 const BigInt value = parseMagnitude(text, format);
247 if (value >= modulus)
248 return std::nullopt;
249 return value;
250}
251
252BusValue maxValueForBusWidth(const std::size_t width)
253{
254 return BusValue(width, State::HIGH);
255}
256
257BusValue busValueFromInteger(const BigInt& value, const std::size_t width)
258{
259 BusValue result(width, State::LOW);
260 if (width == 0)
261 return result;
262
263 const BigInt bitPattern = value & ((BigInt{1} << width) - 1);
264 std::vector<unsigned char> bits;
265 boost::multiprecision::export_bits(bitPattern, std::back_inserter(bits), 1, false);
266 std::ranges::transform(
267 bits | std::views::take(width), result.begin(),
268 [](const unsigned char bit) { return bit == 0 ? State::LOW : State::HIGH; });
269 return result;
270}
271
272BigInt integerFromBusValue(const BusValue& value, const Signedness signedness)
273{
274 if (value.empty())
275 return 0;
276
277 if (!std::ranges::all_of(value, wireUtils::isKnownBinary))
278 throw std::invalid_argument("Bus values must contain only 0 or 1 to form an integer");
279
280 std::vector<unsigned char> bits;
281 bits.reserve(value.size());
282 std::ranges::transform(value, std::back_inserter(bits),
283 [](const State state) { return state == State::HIGH; });
284
285 BigInt result;
286
287 boost::multiprecision::import_bits(result, bits.begin(), bits.end(), 1, false);
288
289 if (signedness == Signedness::SIGNED && value.back() == State::HIGH)
290 result -= BigInt{1} << value.size();
291
292 return result;
293}
294
295BusValue busValueFromBits(const std::string_view bits)
296{
297 if (bits.empty())
298 return {};
299
300 const auto [format, DIGITS] = getFormat(bits);
301 // Only valid formats are those which satisfy the raw alphabet
302 if (format != BusValueFormat::Raw && !satisfiesAlphabet(DIGITS, BusValueFormat::Raw))
303 throw std::invalid_argument("Raw bus values may contain only 0, 1, X, or E");
304
305 return DIGITS | std::views::reverse | std::views::transform([](const char digit) {
306 return static_cast<State>(upper(digit));
307 })
308 | std::ranges::to<BusValue>();
309}
310
311std::string formatValue(const BusValue& value, const BusValueFormat format,
312 const std::size_t fixedWidth)
313{
314 if (value.empty())
315 return {};
316
317 const bool mustBeRaw = std::ranges::any_of(value, [](const State state) {
318 return state == State::UNKNOWN || state == State::ERROR;
319 });
320
321 const auto rawStr = value | std::views::reverse
322 | std::views::transform([](const State state) {
323 return static_cast<char>(std::to_underlying(state));
324 })
325 | std::ranges::to<std::string>();
326
327 if (format == BusValueFormat::Raw || mustBeRaw)
328 return rawStr;
329
330 const BigInt unsignedNumber = integerFromBusValue(value);
331 std::string res;
332 switch (format) {
334 case BusValueFormat::Oct: res = formatBigInt(unsignedNumber, format); break;
335 case BusValueFormat::Bin: res = rawStr; break;
336 case BusValueFormat::Unsigned: res = formatBigInt(unsignedNumber, format); break;
338 const BigInt signedNumber = value.back() == State::HIGH
339 ? unsignedNumber - (BigInt{1} << value.size())
340 : unsignedNumber;
341 res = formatBigInt(signedNumber, format);
342 break;
343 }
345 case BusValueFormat::Unknown: throw std::invalid_argument("Invalid output format");
346 }
347
348 const bool needsPrefix =
349 format != BusValueFormat::Signed && formatPrefix.contains(format);
350 const std::size_t padding = fixedWidth > res.size() ? fixedWidth - res.size() : 0;
351 return std::format("{}{}{}", needsPrefix ? formatPrefix.at(format) : "",
352 std::string(padding, '0'), res);
353}
354
355ParsedBusValue valueFromStr(const std::string_view value)
356{
357 const auto [format, DIGITS] = getFormat(value);
358 BusValue result;
359
360 switch (format) {
362 result = DIGITS | std::views::reverse | std::views::transform([](const char digit) {
363 return static_cast<State>(upper(digit));
364 })
365 | std::ranges::to<BusValue>();
366 break;
368 result = busValueFromInteger(parseMagnitude(DIGITS, format), DIGITS.size());
369 break;
371 result = busValueFromInteger(parseMagnitude(DIGITS, format), DIGITS.size() * 4);
372 break;
374 result = busValueFromInteger(parseMagnitude(DIGITS, format), DIGITS.size() * 3);
375 break;
378 const BigInt magnitude = parseMagnitude(DIGITS, format);
379 result = busValueFromInteger(magnitude, magnitudeWidth(magnitude));
380
381 if (format == BusValueFormat::Signed) {
382 result.push_back(State::LOW);
383 if (trim(value).front() == '-')
384 result = twosComplement(result);
385 }
386 break;
387 }
389 }
390
391 return {std::move(result), format};
392}
393
394std::optional<BusValue> resizeParsedValue(const ParsedBusValue& parsed,
395 const std::size_t width)
396{
397 if (parsed.format == BusValueFormat::Unknown || parsed.value.empty())
398 return std::nullopt;
399
400 if (parsed.format == BusValueFormat::Signed) {
401 if (!SILICON::wireUtils::fitsSigned(parsed.value, width))
402 return std::nullopt;
403 return SILICON::wireUtils::normalizeBusValue(parsed.value, width,
404 parsed.value.back());
405 }
406
407 if (!SILICON::wireUtils::fitsUnsigned(parsed.value, width))
408 return std::nullopt;
409
410 const State extension = parsed.format == BusValueFormat::Raw && parsed.value.size() == 1
411 && parsed.value.front() == State::UNKNOWN
413 : State::LOW;
414 return SILICON::wireUtils::normalizeBusValue(parsed.value, width, extension);
415}
416
417} // namespace SILICON::core
ParsedBusValue valueFromStr(const std::string_view value)
Parse user-facing decimal, hexadecimal, octal, binary, or four-state text.
boost::multiprecision::cpp_int BigInt
std::optional< BigInt > parseInteger(std::string_view text, const BusValueFormat format, const std::size_t bitWidth)
std::optional< BusValue > resizeParsedValue(const ParsedBusValue &parsed, const std::size_t width)
Adapts a parsed textual value to an exact destination width.
BigInt integerFromBusValue(const BusValue &value, const Signedness signedness)
Decodes an LSB-first BusValue as an unsigned arbitrary-precision integer. Empty values yield zero....
BusValue maxValueForBusWidth(const std::size_t width)
BusValue twosComplement(const BusValue &n)
Definition wire.cpp:272
BusValue busValueFromBits(const std::string_view bits)
Strictly decodes an MSB-first raw string containing 0, 1, X, or E.
std::string formatInteger(const BigInt &value, const BusValueFormat format, const std::size_t bitWidth)
BusValue busValueFromInteger(const BigInt &value, const std::size_t width)
Builds an LSB-first BusValue from the low width bits of an integer. Negative values use two's complem...
std::string formatValue(const BusValue &value, const BusValueFormat format, const std::size_t fixedWidth)
Format an LSB-first BusValue for display.
std::vector< State > BusValue
Definition wire.hpp:120
QVariant value(const QSettings &settings, const Definition &setting)
Reads a setting value, falling back to its declared default when unset.
BusValue normalizeBusValue(const BusValue &value, const std::size_t width, const State extension)
Resize an LSB-first value to an exact bus width.
Definition wire.cpp:121
bool fitsUnsigned(const BusValue &value, const std::size_t width)
Tests whether an LSB-first value is representable as an unsigned value.
Definition wire.cpp:97
bool fitsSigned(const BusValue &value, const std::size_t width)
Tests whether an LSB-first two's-complement value fits a signed width.
Definition wire.cpp:105
bool isKnownBinary(const State state)
Tests whether a state is a concrete binary logic value.
Definition wire.cpp:136
A bit-vector together with the textual interpretation that produced it.