• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

PeterCDMcLean / BitLib / 16781103655

06 Aug 2025 03:17PM UTC coverage: 74.757%. Remained the same
16781103655

push

github

web-flow
Use upload / download action instead of cache (#28)

* Use upload / download action instead of cache

* Try without single quotes

* Rerun base_ref build if possible

3451 of 5352 branches covered (64.48%)

Branch coverage included in aggregate %.

2555 of 2682 relevant lines covered (95.26%)

29850565.99 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

64.31
/include/bitlib/bit-algorithms/to_from_string.hpp
1
// ================================= array_REF =================================== //
2
// Project:     The Experimental Bit Algorithms Library
3
// \file        to_string.hpp
4
// Description: Implementation of array_ref
5
// Creator:     Vincent Reverdy
6
// Contributor: Peter McLean [2025]
7
// License:     BSD 3-Clause License
8
// ========================================================================== //
9

10
#ifndef _BIT_TO_STRING_HPP_INCLUDED
11
#define _BIT_TO_STRING_HPP_INCLUDED
12

13
#include <array>
14
#include <bit>
15
#include <iomanip>
16
#include <sstream>
17
#include <string>
18

19
#include "bitlib/bit-algorithms/accumulate.hpp"
20
#include "bitlib/bit-algorithms/count.hpp"
21
#include "bitlib/bit-algorithms/division.hpp"
22
#include "bitlib/bit-algorithms/multiplication.hpp"
23
#include "bitlib/bit-containers/bit_policy.hpp"
24
#include "bitlib/bit_concepts.hpp"
25

26
namespace bit {
27

28
namespace string {
29

30
template <std::size_t Base>
31
constexpr auto make_digit_map() {
32
  static_assert((Base >= 2) && ((Base & (Base - 1)) == 0), "Base must be power of 2 >= 2");
33
  static_assert(Base <= 64, "Base too large for simple char mapping");
34

35
  ::std::array<char, Base> map{};
36
  for (std::size_t i = 0; i < Base; ++i) {
37
    map[i] = (i < 10) ? ('0' + i) : ('A' + (i - 10));
38
  }
39
  return map;
40
}
41

42
constexpr std::span<const char> make_digit_map(std::size_t Base) {
8✔
43
  switch (Base) {
8✔
44
    case 2: {
×
45
      static constexpr auto map = make_digit_map<2>();
46
      return std::span<const char>(static_cast<const char*>(map.data()), map.size());
×
47
    }
48
    case 4: {
×
49
      static constexpr auto map = make_digit_map<4>();
50
      return std::span<const char>(static_cast<const char*>(map.data()), map.size());
×
51
    }
52
    case 8: {
×
53
      static constexpr auto map = make_digit_map<8>();
54
      return std::span<const char>(static_cast<const char*>(map.data()), map.size());
×
55
    }
56
    case 16: {
8!
57
      static constexpr auto map = make_digit_map<16>();
4✔
58
      return std::span<const char>(static_cast<const char*>(map.data()), map.size());
12✔
59
    }
60
    case 32: {
×
61
      static constexpr auto map = make_digit_map<32>();
62
      return std::span<const char>(static_cast<const char*>(map.data()), map.size());
×
63
    }
64
    case 64: {
×
65
      static constexpr auto map = make_digit_map<64>();
66
      return std::span<const char>(static_cast<const char*>(map.data()), map.size());
×
67
    }
68
    default:
×
69
      return {};  // or throw, or abort
×
70
  }
4✔
71
}
4✔
72

73
template <std::size_t Base>
74
constexpr auto make_from_digit_map() {
75
  static_assert((Base >= 2) && ((Base & (Base - 1)) == 0), "Base must be power of 2 >= 2");
76
  static_assert(Base <= 64, "Base too large for simple char mapping");
77

78
  ::std::array<char, 128> map{};
79
  for (std::size_t i = 0; i < 128; ++i) {
80
    map[i] = ~0;
81
    if (i >= '0' && i <= '9') {
82
      map[i] = i - '0';
83
    }
84
    if (i >= 'a' && i <= 'z') {
85
      map[i] = (i - 'a') + 10;
86
    }
87
    if (i >= 'A' && i <= 'Z') {
88
      map[i] = (i - 'A') + 10;
89
    }
90
  }
91
  return map;
92
}
93

94
constexpr auto make_from_digit_map(std::size_t Base) {
4✔
95
  switch (Base) {
4✔
96
    case 2: {
×
97
      static constexpr auto map2 = make_from_digit_map<2>();
98
      return map2;
×
99
    }
100
    case 4: {
×
101
      static constexpr auto map4 = make_from_digit_map<4>();
102
      return map4;
×
103
    }
104
    case 8: {
×
105
      static constexpr auto map8 = make_from_digit_map<8>();
106
      return map8;
×
107
    }
108
    case 16: {
4!
109
      static constexpr auto map16 = make_from_digit_map<16>();
2✔
110
      return map16;
4✔
111
    }
112
    case 32: {
×
113
      static constexpr auto map32 = make_from_digit_map<32>();
114
      return map32;
×
115
    }
116
    case 64: {
×
117
      static constexpr auto map64 = make_from_digit_map<64>();
118
      return map64;
×
119
    }
120
    default:
×
121
      throw std::runtime_error("Base not implemented");
×
122
  }
2✔
123
}
2✔
124

125
struct metadata_t {
126
  size_t base;
127
  bool is_signed;
128
  std::endian endian;
129
  bool str_sign_extend_zeros;
130
  char fill;
131
};
132

133
constexpr metadata_t typical(size_t base = 10, bool str_sign_extend_zeros = false) {
2✔
134
  return {
1✔
135
      .base = base,
1✔
136
      .is_signed = false,
1✔
137
      .endian = std::endian::big,
1✔
138
      .str_sign_extend_zeros = str_sign_extend_zeros,
1✔
139
      .fill = '\0'};
2✔
140
}
1✔
141

142
}  // namespace string
143

144
template <typename RandomAccessIt, typename CharIt>
145
constexpr CharIt to_string(
6✔
146
    const bit_iterator<RandomAccessIt>& bit_first,
147
    const bit_iterator<RandomAccessIt>& bit_last,
148
    const CharIt str_first,
149
    const CharIt str_last,
150
    string::metadata_t meta = string::typical()) {
6✔
151
  if (std::has_single_bit(meta.base)) {
12!
152
    const auto base_bits = std::bit_width(meta.base - 1);
8✔
153
    const auto base_digits = string::make_digit_map(meta.base);
8✔
154

155
    CharIt cursor = accumulate_while(
8✔
156
        policy::AccumulateNoInitialSubword{},
4✔
157
        bit_first, bit_last, str_last,
4✔
158
        [meta, base_bits, base_digits, str_first](CharIt cursor, auto word, const size_t bits = bitsof<decltype(word)>()) {
8✔
159
          const int characters = ((bits + base_bits - 1) / base_bits);
8✔
160
          for (int i = characters - 1; i >= 0; i--) {
72!
161
            if (cursor == str_first) {
66!
162
              return std::make_pair(false, cursor);
2✔
163
            }
1✔
164
            *(--cursor) = base_digits[word & (meta.base - 1)];
64✔
165
            word >>= base_bits;
64✔
166
          }
32✔
167
          return std::make_pair(cursor != str_first, cursor);
6✔
168
        });
4✔
169
    if (cursor != str_first) {
8!
170
      return std::copy(cursor, str_last, str_first);
×
171
    } else {
4✔
172
      return str_last;
8✔
173
    }
4✔
174
  } else {
4✔
175
    using word_type = typename bit_iterator<RandomAccessIt>::word_type;
2✔
176
    size_t store_bits = distance(bit_first, bit_last);
4✔
177
    std::vector<word_type> vec((store_bits + bitsof<word_type>() - 1) / bitsof<word_type>());
8✔
178
    vec.back() = 0;  // Ensure last word is zeroed
4✔
179
    bit_iterator<word_type*> bit_it(vec.data());
4✔
180

181
    const unsigned char base = static_cast<unsigned char>(meta.base);
4✔
182
    auto remainder = ::bit::division(bit_first, bit_last, bit_it, base);
4✔
183
    CharIt cursor = str_last;
4✔
184
    *(--cursor) = static_cast<char>(remainder + '0');
4✔
185

186
    while ((cursor != str_first) && (store_bits -= ::bit::count_msb(bit_it, bit_it + store_bits, bit0))) {
12!
187
      remainder = ::bit::division(bit_it, bit_it + store_bits, bit_it, base);
8✔
188
      *(--cursor) = static_cast<char>(remainder + '0');
8✔
189
    }
4✔
190
    if (cursor != str_first) {
4!
191
      return std::copy(cursor, str_last, str_first);
×
192
    }
193
    return str_last;
4✔
194
  }
4✔
195
}
6✔
196

197
template <typename RandomAccessIt>
198
constexpr size_t estimate_length(
6✔
199
    const bit_iterator<RandomAccessIt>& first,
200
    const bit_iterator<RandomAccessIt>& last,
201
    const size_t base,
202
    const bool str_sign_extend_zeros) {
6✔
203
  if (std::has_single_bit(base)) {
12!
204
    const auto base_bits = std::bit_width(base - 1);
8✔
205

206
    int skip_leading_bits = str_sign_extend_zeros ? 0 : count_msb(first, last, bit0);
8!
207

208
    int str_len = (distance(first, last) - skip_leading_bits);
8✔
209
    str_len = (str_len + base_bits - 1) / base_bits;  // Round up to nearest base digit
8✔
210
    return static_cast<size_t>(std::max(1, str_len));
8✔
211
  } else {
4✔
212
    const uint32_t LOG2BASE = std::ceil(1 / std::logbf(base) * (1 << 16));
4✔
213
    int skip_leading_bits = str_sign_extend_zeros ? 0 : count_msb(first, last, bit0);
4!
214
    const auto bits = distance(first, last) - skip_leading_bits;
4✔
215
    const auto fixed_point = (bits * LOG2BASE);
4✔
216
    const auto max_len = (fixed_point >> 16) + ((fixed_point & ((1 << 16) - 1)) != 0);
4✔
217
    return static_cast<size_t>(std::max(max_len, static_cast<decltype(max_len)>(1)));
4✔
218
  }
2✔
219
}
6✔
220

221
template <typename RandomAccessIt>
222
constexpr std::string to_string(
6✔
223
    const bit_iterator<RandomAccessIt>& first,
224
    const bit_iterator<RandomAccessIt>& last,
225
    string::metadata_t meta = string::typical()) {
6✔
226
  std::string buffer(estimate_length(first, last, meta.base, meta.str_sign_extend_zeros), meta.fill);
24✔
227
  if (meta.fill) {
12!
228
    std::fill(to_string(first, last, buffer.begin(), buffer.end(), meta), buffer.end(), meta.fill);
×
229
  } else {
6✔
230
    buffer.resize(to_string(first, last, buffer.begin(), buffer.end(), meta) - buffer.begin());
12✔
231
  }
6✔
232
  return buffer;
18✔
233
}
6✔
234

235
template <string::metadata_t meta = string::typical(), typename RandomAccessIt>
236
constexpr std::string to_string(
237
    const bit_iterator<RandomAccessIt>& first,
238
    const bit_iterator<RandomAccessIt>& last) {
239
  static_assert(meta.endian == std::endian::big, "Only bit big endian support (MSB on the left)");
240
  return to_string(first, last, meta);
241
}
242

243
constexpr std::string to_string(const bit_sized_range auto& bits, string::metadata_t meta = string::typical()) {
12✔
244
  return to_string(bits.begin(), bits.end(), meta);
18✔
245
}
6✔
246

247
template <string::metadata_t meta = string::typical()>
248
constexpr std::string to_string(const bit_sized_range auto& bits) {
10✔
249
  return to_string(bits, meta);
15✔
250
}
5✔
251

252
template <string::metadata_t meta = string::typical(), typename RandomAccessIt, typename CharIt>
253
constexpr CharIt to_string(
254
    const bit_iterator<RandomAccessIt>& first,
255
    const bit_iterator<RandomAccessIt>& last,
256
    const CharIt str_first,
257
    const CharIt str_last) {
258
  static_assert(meta.endian == std::endian::big, "Only bit big endian support (MSB on the left)");
259
  return to_string(first, last, str_first, str_last, meta);
260
}
261

262
template <typename CharIt>
263
constexpr CharIt to_string(
264
    const bit_sized_range auto& bits,
265
    const CharIt str_first,
266
    const CharIt str_last,
267
    string::metadata_t meta = string::typical()) {
268
  return to_string(str_first, str_last, bits.begin(), bits.end(), meta);
269
}
270

271
template <string::metadata_t meta = string::typical(), typename CharIt>
272
constexpr CharIt to_string(
273
    const bit_sized_range auto& bits,
274
    const CharIt str_first,
275
    const CharIt str_last) {
276
  return to_string(bits, str_first, str_last, meta);
277
}
278

279
template <typename CharIt, typename RandomAccessIt, typename Policy = policy::typical<typename RandomAccessIt::value_type>>
280
constexpr void from_string(
3✔
281
    const CharIt str_first, const CharIt str_last,
282
    const bit_iterator<RandomAccessIt>& bit_first, const bit_iterator<RandomAccessIt>& bit_last,
283
    string::metadata_t meta = string::typical()) {
3✔
284
  // TODO: This should be a policy
285
  if (str_first == str_last) {
6!
286
    return;  // Nothing to do
×
287
  }
288
  if (std::has_single_bit(meta.base)) {
6!
289
    const auto base_bits = std::bit_width(meta.base - 1);
4✔
290
    const auto base_from_digits = string::make_from_digit_map(meta.base);
4✔
291
    using word_type = uint64_t;
2✔
292
    std::vector<word_type> vec;
4✔
293
    size_t store_bits = distance(bit_first, bit_last);
4✔
294

295
    bit_iterator<RandomAccessIt> bit_it = bit_first;
4✔
296
    auto cursor = std::distance(str_first, str_last) - 1;
4✔
297
    while ((cursor >= 0) && store_bits) {
6!
298
      word_type work = 0;
4✔
299
      size_t bits = 0;
4✔
300
      for (; (bits < bitsof<word_type>()) && (cursor >= 0); cursor--) {
28!
301
        char c = str_first[cursor];
24✔
302
        // TODO: This should be a policy
303
        if (c >= base_from_digits.size()) {
36!
304
          continue;
×
305
        }
306
        auto digit = base_from_digits[c];
24✔
307
        // TODO: This should be a policy
308
        if (~0 == digit) {
24!
309
          continue;
×
310
        }
311
        work |= (digit << bits);
24✔
312
        bits += base_bits;
24✔
313
      }
12✔
314
      if (store_bits < bits) {
4!
315
        Policy::truncation::template from_integral<word_type, std::dynamic_extent, RandomAccessIt>(
2✔
316
            bit_it, bit_last, work);
1✔
317
        return;
2✔
318
      } else if ((store_bits > bits) && (cursor < 0)) {
2!
319
        const bit_iterator<word_type*> p_integral(&work);
2✔
320
        bit_it = ::bit::copy(p_integral, p_integral + bits, bit_it);
2✔
321
        Policy::extension::template from_integral<word_type, std::dynamic_extent, RandomAccessIt>(
2✔
322
            bit_it, bit_last, work);
1✔
323
      } else if (store_bits >= bits) {
1!
324
        const bit_iterator<word_type*> p_integral(&work);
×
325
        bit_it = ::bit::copy(p_integral, p_integral + bits, bit_it);
×
326
      }
327
    }
2✔
328
  } else {
4✔
329
    if (meta.base != 10) {
2!
330
      throw std::runtime_error("Base not implemented");
×
331
    }
332
    using word_type = typename bit_iterator<RandomAccessIt>::word_type;
1✔
333
    std::vector<word_type> vec;
2✔
334
    size_t store_bits = distance(bit_first, bit_last);
2✔
335

336
    // TODO: template with uninitialized_t
337
    ::bit::fill(bit_first, bit_last, bit0);  // Clear the bits first
2✔
338

339
    CharIt cursor = str_first;
2✔
340
    while (cursor != str_last) {
8!
341
      unsigned char c = (*cursor - '0');
6✔
342
      if (c <= 9) {
6!
343
        auto overflow_mult = ::bit::multiplication(bit_first, bit_last, word_type{10});
6✔
344
        auto overflow_add = ::bit::addition(bit_first, bit_last, c);
6✔
345
        if (overflow_mult || overflow_add) {
6!
346
          //Policy::truncation::template overflow(bit_first, bit_last);
347
          return;
×
348
        }
349
      }
3✔
350
      cursor++;
6✔
351
    }
3✔
352
    //Policy::extension::template extend(bit_first, bit_last);
353
  }
2✔
354
}
3✔
355

356
template <string::metadata_t meta = string::typical(),
357
          typename CharIt,
358
          typename RandomAccessIt,
359
          typename Policy = policy::typical<typename RandomAccessIt::value_type>>
360
constexpr void from_string(
3✔
361
    const CharIt str_first, const CharIt str_last,
362
    const bit_iterator<RandomAccessIt>& bit_first, const bit_iterator<RandomAccessIt>& bit_last) {
3✔
363
  static_assert(meta.endian == std::endian::big, "Only bit big endian support (MSB on the left)");
3✔
364
  from_string<CharIt, RandomAccessIt, Policy>(str_first, str_last, bit_first, bit_last, meta);
6✔
365
}
6✔
366

367
template <typename CharIt>
368
constexpr std::vector<uintptr_t> from_string(
369
    const CharIt first, const CharIt last, string::metadata_t meta = string::typical()) {
370
  if (std::has_single_bit(meta.base)) {
371
    const auto base_bits = std::bit_width(meta.base - 1);
372
    const auto base_from_digits = string::make_from_digit_map(meta.base);
373

374
    std::vector<uintptr_t> vec;
375

376
    last--;
377
    while (last >= first) {
378
      uintptr_t work = 0;
379
      size_t bits = 0;
380
      for (; (bits < bitsof<uintptr_t>()) && (last >= first); last--) {
381
        char c = *last;
382
        // TODO: This should be a policy
383
        if (c >= base_from_digits.size()) {
384
          continue;
385
        }
386
        auto digit = base_from_digits[c];
387
        // TODO: This should be a policy
388
        if (~0 == digit) {
389
          continue;
390
        }
391
        work |= (digit << bits);
392
        bits += base_bits;
393
      }
394
      if (bits) {
395
        vec.push_back(work);
396
      }
397
    }
398
    return vec;
399
  } else {
400
    //from_string base 10 not implemented yet;
401
    return {};
402
  }
403
}
404

405
template <string::metadata_t meta = string::typical(),
406
          typename CharIt>
407
constexpr std::vector<uintptr_t> from_string(
408
    const CharIt first, const CharIt last) {
409
  static_assert(meta.endian == std::endian::big, "Only bit big endian support (MSB on the left)");
410
  return from_string(first, last, meta);
411
}
412

413
template <string::metadata_t meta = string::typical(), typename RandomAccessIt, typename Policy = policy::typical<typename RandomAccessIt::value_type>>
414
constexpr void from_string(
415
    const std::string& str,
416
    const bit_iterator<RandomAccessIt>& bit_first, const bit_iterator<RandomAccessIt>& bit_last) {
417
  static_assert(meta.endian == std::endian::big, "Only bit big endian support (MSB on the left)");
418
  from_string<meta, RandomAccessIt, Policy>(str.c_str(), str.c_str() + str.length(), bit_first, bit_last);
419
}
420

421
template <string::metadata_t meta = string::typical(), bit_range RangeT, typename Policy = policy::typical<typename std::ranges::iterator_t<RangeT>::value_type>>
422
constexpr void from_string(
3✔
423
    const std::string& str,
424
    RangeT& bits) {
3✔
425
  using range_iterator_t = std::ranges::iterator_t<RangeT>;
3✔
426
  using RandomAccessIt = typename range_iterator_t::iterator_type;
3✔
427
  from_string<meta, std::string::const_iterator, RandomAccessIt, Policy>(str.begin(), str.end(), bits.begin(), bits.end());
6✔
428
}
6✔
429

430
template <typename RandomAccessIt, typename Policy = policy::typical<typename RandomAccessIt::value_type>>
431
constexpr void from_string(
432
    const std::string& str,
433
    const bit_iterator<RandomAccessIt>& bit_first, const bit_iterator<RandomAccessIt>& bit_last,
434
    string::metadata_t meta = string::typical()) {
435
  from_string<std::string::const_iterator, RandomAccessIt, Policy>(
436
      str.begin(), str.end(),
437
      bit_first, bit_last,
438
      meta);
439
}
440

441
template <bit_range RangeT, typename Policy = policy::typical<typename std::ranges::iterator_t<RangeT>::value_type>>
442
constexpr void from_string(
443
    const std::string& str,
444
    RangeT& bits,
445
    string::metadata_t meta = string::typical()) {
446
  using range_iterator_t = std::ranges::iterator_t<RangeT>;
447
  using RandomAccessIt = typename range_iterator_t::iterator_type;
448
  from_string<std::string::const_iterator, RandomAccessIt, Policy>(
449
      str.begin(), str.end(),
450
      bits.begin(), bits.end(),
451
      meta);
452
}
453

454
}  // namespace bit
455

456
#endif // _BIT_TO_STRING_HPP_INCLUDED
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc