-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalue.cpp
More file actions
74 lines (69 loc) · 2.69 KB
/
Copy pathvalue.cpp
File metadata and controls
74 lines (69 loc) · 2.69 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "value.h"
#include <sstream>
#include <stdexcept>
#include <cstdlib>
Value::Value() : type(ValueType::NIL), i(0), f(0.0), b(false), c('\0'), s("") {}
Value Value::Int(long long v){ Value x; x.type=ValueType::INT; x.i=v; return x; }
Value Value::Float(double v){ Value x; x.type=ValueType::FLOAT; x.f=v; return x; }
Value Value::Bool(bool v){ Value x; x.type=ValueType::BOOL; x.b=v; return x; }
Value Value::String(const std::string& v){ Value x; x.type=ValueType::STRING; x.s=v; return x; }
Value Value::Char(char v){ Value x; x.type=ValueType::CHAR; x.c=v; return x; }
std::string Value::toString() const {
switch (type) {
case ValueType::INT: return std::to_string(i);
case ValueType::FLOAT: { std::ostringstream oss; oss << f; return oss.str(); }
case ValueType::BOOL: return b ? "true" : "false";
case ValueType::STRING: return s;
case ValueType::CHAR: return std::string(1, c);
case ValueType::NIL: return "nil";
}
return "nil";
}
static long long asInt(const Value& v) {
switch (v.type) {
case ValueType::INT: return v.i;
case ValueType::FLOAT: return (long long)v.f;
case ValueType::BOOL: return v.b ? 1 : 0;
case ValueType::CHAR: return (long long)v.c;
case ValueType::STRING: return std::stoll(v.s);
case ValueType::NIL: return 0;
}
return 0;
}
static double asFloat(const Value& v) {
switch (v.type) {
case ValueType::FLOAT: return v.f;
case ValueType::INT: return (double)v.i;
case ValueType::BOOL: return v.b ? 1.0 : 0.0;
case ValueType::CHAR: return (double)v.c;
case ValueType::STRING: return std::stod(v.s);
case ValueType::NIL: return 0.0;
}
return 0.0;
}
static bool asBool(const Value& v) {
switch (v.type) {
case ValueType::BOOL: return v.b;
case ValueType::INT: return v.i != 0;
case ValueType::FLOAT: return v.f != 0.0;
case ValueType::CHAR: return v.c != '\0';
case ValueType::STRING: return !v.s.empty();
case ValueType::NIL: return false;
}
return false;
}
Value castTo(const Value& v, ValueType t) {
switch (t) {
case ValueType::INT: return Value::Int(asInt(v));
case ValueType::FLOAT: return Value::Float(asFloat(v));
case ValueType::BOOL: return Value::Bool(asBool(v));
case ValueType::STRING: return Value::String(v.toString());
case ValueType::CHAR: {
if (v.type == ValueType::CHAR) return v;
if (v.type == ValueType::STRING) return Value::Char(v.s.empty() ? '\0' : v.s[0]);
return Value::Char((char)asInt(v));
}
case ValueType::NIL: return Value();
}
return Value();
}