OILS / mycpp / gc_mops.cc View on Github | oilshell.org

58 lines, 35 significant
1#include "mycpp/gc_mops.h"
2
3#include <errno.h>
4#include <inttypes.h> // PRIo64, PRIx64
5#include <stdio.h>
6
7#include "mycpp/gc_alloc.h"
8#include "mycpp/gc_builtins.h" // StringToInt64
9#include "mycpp/gc_str.h"
10
11namespace mops {
12
13const BigInt ZERO = BigInt{0};
14const BigInt ONE = BigInt{1};
15const BigInt MINUS_ONE = BigInt{-1};
16const BigInt MINUS_TWO = BigInt{-2}; // for printf
17
18static const int kInt64BufSize = 32; // more than twice as big as kIntBufSize
19
20// Note: Could also use OverAllocatedStr, but most strings are small?
21
22// Similar to str(int i) in gc_builtins.cc
23
24BigStr* ToStr(BigInt b) {
25 char buf[kInt64BufSize];
26 int len = snprintf(buf, kInt64BufSize, "%" PRId64, b);
27 return ::StrFromC(buf, len);
28}
29
30BigStr* ToOctal(BigInt b) {
31 char buf[kInt64BufSize];
32 int len = snprintf(buf, kInt64BufSize, "%" PRIo64, b);
33 return ::StrFromC(buf, len);
34}
35
36BigStr* ToHexUpper(BigInt b) {
37 char buf[kInt64BufSize];
38 int len = snprintf(buf, kInt64BufSize, "%" PRIX64, b);
39 return ::StrFromC(buf, len);
40}
41
42BigStr* ToHexLower(BigInt b) {
43 char buf[kInt64BufSize];
44 int len = snprintf(buf, kInt64BufSize, "%" PRIx64, b);
45 return ::StrFromC(buf, len);
46}
47
48// Copied from gc_builtins - to_int()
49BigInt FromStr(BigStr* s, int base) {
50 int64_t i;
51 if (StringToInt64(s->data_, len(s), base, &i)) {
52 return i;
53 } else {
54 throw Alloc<ValueError>();
55 }
56}
57
58} // namespace mops