aboutsummaryrefslogtreecommitdiff
path: root/libk/string/integerview.cc
blob: dc4c80a5b88d67368cec528013c80a9a23cbf3cc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <string.h>

/* itoa:  convert n to characters in s */
template <typename T, int base = 10>
constexpr size_t itoa(T n, char s[]) {
  const bool is_negative = (n < 0);
  if constexpr (!is_unsigned<T>()) {
    if (n < 0)
      n = -n;
  }

  size_t i = 0;
  do {                                     /* generate digits in reverse order */
    s[i++] = "0123456789abcdef"[n % base]; /* get next digit */
  } while ((n /= base) > 0);               /* delete it */

  if (is_negative)
    s[i++] = '-';

  s[i] = '\0';

  // reverse(s, i);
  return i;
}

IntegerView::IntegerView(int32_t n) {
  length = itoa(n, buffer);
}
IntegerView::IntegerView(uint32_t n) {
  length = itoa(n, buffer);
}

IntegerView::IntegerView(HexFormat_int32 f) {
  length = itoa<int32_t, 16>(f.n, buffer);
  buffer[length++] = 'x';
  buffer[length++] = '0';
}

IntegerView::IntegerView(HexFormat_uint32 f) {
  length = itoa<uint32_t, 16>(f.n, buffer);
  buffer[length++] = 'x';
  buffer[length++] = '0';
}