1/**
2 * Copyright (c) 2006-2023 LOVE Development Team
3 *
4 * This software is provided 'as-is', without any express or implied
5 * warranty. In no event will the authors be held liable for any damages
6 * arising from the use of this software.
7 *
8 * Permission is granted to anyone to use this software for any purpose,
9 * including commercial applications, and to alter it and redistribute it
10 * freely, subject to the following restrictions:
11 *
12 * 1. The origin of this software must not be misrepresented; you must not
13 * claim that you wrote the original software. If you use this software
14 * in a product, an acknowledgment in the product documentation would be
15 * appreciated but is not required.
16 * 2. Altered source versions must be plainly marked as such, and must not be
17 * misrepresented as being the original software.
18 * 3. This notice may not be removed or altered from any source distribution.
19 **/
20
21#ifndef LOVE_VARIANT_H
22#define LOVE_VARIANT_H
23
24#include "common/runtime.h"
25#include "common/Object.h"
26#include "common/int.h"
27
28#include <cstring>
29#include <string>
30#include <vector>
31#include <set>
32
33namespace love
34{
35
36class Variant
37{
38public:
39
40 static const int MAX_SMALL_STRING_LENGTH = 15;
41
42 enum Type
43 {
44 UNKNOWN = 0,
45 BOOLEAN,
46 NUMBER,
47 STRING,
48 SMALLSTRING,
49 LUSERDATA,
50 LOVEOBJECT,
51 NIL,
52 TABLE
53 };
54
55 class SharedString : public love::Object
56 {
57 public:
58
59 SharedString(const char *string, size_t len)
60 : len(len)
61 {
62 str = new char[len+1];
63 str[len] = '\0';
64 memcpy(str, string, len);
65 }
66 virtual ~SharedString() { delete[] str; }
67
68 char *str;
69 size_t len;
70 };
71
72 class SharedTable : public love::Object
73 {
74 public:
75
76 SharedTable(std::vector<std::pair<Variant, Variant>> *table)
77 : table(table)
78 {
79 }
80
81 virtual ~SharedTable() { delete table; }
82
83 std::vector<std::pair<Variant, Variant>> *table;
84 };
85
86 union Data
87 {
88 bool boolean;
89 double number;
90 SharedString *string;
91 void *userdata;
92 Proxy objectproxy;
93 SharedTable *table;
94 struct
95 {
96 char str[MAX_SMALL_STRING_LENGTH];
97 uint8 len;
98 } smallstring;
99 };
100
101 Variant();
102 Variant(bool boolean);
103 Variant(double number);
104 Variant(const char *str, size_t len);
105 Variant(const std::string &str);
106 Variant(void *lightuserdata);
107 Variant(love::Type *type, love::Object *object);
108 Variant(std::vector<std::pair<Variant, Variant>> *table);
109 Variant(const Variant &v);
110 Variant(Variant &&v);
111 ~Variant();
112
113 Variant &operator = (const Variant &v);
114
115 Type getType() const { return type; }
116 const Data &getData() const { return data; }
117
118 static Variant fromLua(lua_State *L, int n, std::set<const void*> *tableSet = nullptr);
119 void toLua(lua_State *L) const;
120
121private:
122
123 Type type;
124 Data data;
125
126}; // Variant
127} // love
128
129#endif // LOVE_VARIANT_H
130