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

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