remedy_lua/value.rs
1//! Values: what a register, a table slot or an upvalue holds.
2
3use crate::number;
4
5macro_rules! gc_ref {
6 ($(#[$doc:meta])* $name:ident) => {
7 $(#[$doc])*
8 ///
9 /// A reference into the collector's heap: valid while what it names is reachable from
10 /// the script, from a running call's arguments, or from a [`Root`](crate::Root).
11 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
12 pub struct $name {
13 pub(crate) idx: u32,
14 pub(crate) generation: u32,
15 }
16 };
17}
18
19gc_ref!(
20 /// A string.
21 StrRef
22);
23gc_ref!(
24 /// A table.
25 TableRef
26);
27gc_ref!(
28 /// A function: a Lua closure or a native (Rust) function.
29 FuncRef
30);
31gc_ref!(
32 /// A full userdata: a host value with an optional metatable.
33 UdRef
34);
35gc_ref!(
36 /// A thread (coroutine).
37 ThreadRef
38);
39
40/// A RemedyLua value. Strings, tables, functions, userdata and threads are references
41/// into the collector's heap ([`StrRef`] and friends); the rest are plain data. Values are
42/// `Copy`: holding one does not keep what it names alive (see [`Root`](crate::Root)).
43// Every payload at offset 8 (the tag, then one 8-byte slot): a value copies as two
44// words, never byte by byte through the stack. The tag is a whole word: with a one-byte
45// tag the seven bytes after it were part of the enum's payload as the code generator sees
46// it, so a value read for a test (`is_nil`) and then stored was copied as 1 + 8 + 4 + 2 + 1
47// bytes, through the stack frame, and the stores stalled the loads after them (fannkuch,
48// whose every step reads or writes an array slot, ran 28% slower).
49#[repr(C, u64)]
50#[derive(Clone, Copy, Debug, Default)]
51pub enum Value {
52 /// `nil`.
53 #[default]
54 Nil,
55 /// `true` or `false`.
56 Bool(bool),
57 /// An integer (64-bit, wrapping).
58 Int(i64),
59 /// A float (64-bit).
60 Num(f64),
61 /// A string (bytes, not necessarily UTF-8).
62 Str(StrRef),
63 /// A table.
64 Table(TableRef),
65 /// A function.
66 Func(FuncRef),
67 /// A full userdata.
68 UserData(UdRef),
69 /// A coroutine.
70 Thread(ThreadRef),
71}
72
73// Two words, with or without `Option` (its `None` is a tag no value has): table slots
74// and stacks are charged `SLOT_SIZE` (16) bytes a value.
75const _: () = assert!(std::mem::size_of::<Value>() == 16 && std::mem::size_of::<Option<Value>>() == 16);
76
77impl Value {
78 /// The value, copied as its two words (tag, then payload) rather than one 16-byte
79 /// move. A register just written by an instruction is two 8-byte stores (tag and
80 /// payload), and a 16-byte load over two stores cannot be forwarded from them: the
81 /// copy waits for both to reach the cache, about a dozen cycles per Lua `MOVE` after
82 /// an arithmetic result. Use it where a value is copied right after being made.
83 #[inline(always)]
84 pub(crate) fn copied(&self) -> Value {
85 match *self {
86 Value::Nil => Value::Nil,
87 Value::Bool(x) => Value::Bool(x),
88 Value::Int(x) => Value::Int(x),
89 Value::Num(x) => Value::Num(x),
90 Value::Str(x) => Value::Str(x),
91 Value::Table(x) => Value::Table(x),
92 Value::Func(x) => Value::Func(x),
93 Value::UserData(x) => Value::UserData(x),
94 Value::Thread(x) => Value::Thread(x),
95 }
96 }
97
98 /// Whether it counts as true in a condition (everything but `nil` and `false`).
99 #[inline]
100 pub fn truthy(self) -> bool {
101 !matches!(self, Value::Nil | Value::Bool(false))
102 }
103
104 /// Whether it is `nil`.
105 #[inline]
106 pub fn is_nil(self) -> bool {
107 matches!(self, Value::Nil)
108 }
109
110 /// Lua's name for its type, as `type` returns it.
111 pub fn type_name(self) -> &'static str {
112 match self {
113 Value::Nil => "nil",
114 Value::Bool(_) => "boolean",
115 Value::Int(_) | Value::Num(_) => "number",
116 Value::Str(_) => "string",
117 Value::Table(_) => "table",
118 Value::Func(_) => "function",
119 Value::UserData(_) => "userdata",
120 Value::Thread(_) => "thread",
121 }
122 }
123
124 /// Whether it lives in the collector's heap.
125 #[inline]
126 pub(crate) fn is_collectable(self) -> bool {
127 matches!(self, Value::Str(_) | Value::Table(_) | Value::Func(_) | Value::UserData(_) | Value::Thread(_))
128 }
129
130 /// Equality without metamethods, by identity for strings: short strings (up to 40
131 /// bytes) are interned, so this is `rawequal` for them, but two equal long strings may be
132 /// different objects. Hosts compare values with [`Lua::raw_equal`](crate::Lua::raw_equal).
133 #[inline]
134 pub fn raw_eq(self, other: Value) -> bool {
135 match (self, other) {
136 (Value::Nil, Value::Nil) => true,
137 (Value::Bool(a), Value::Bool(b)) => a == b,
138 (Value::Int(a), Value::Int(b)) => a == b,
139 (Value::Num(a), Value::Num(b)) => a == b,
140 (Value::Int(i), Value::Num(f)) | (Value::Num(f), Value::Int(i)) => number::int_eq_float(i, f),
141 (Value::Str(a), Value::Str(b)) => a == b,
142 (Value::Table(a), Value::Table(b)) => a == b,
143 (Value::Func(a), Value::Func(b)) => a == b,
144 (Value::UserData(a), Value::UserData(b)) => a == b,
145 (Value::Thread(a), Value::Thread(b)) => a == b,
146 _ => false,
147 }
148 }
149
150 /// The integer it is, or converts to exactly (a float with an integral value).
151 pub fn as_int(self) -> Option<i64> {
152 match self {
153 Value::Int(i) => Some(i),
154 Value::Num(f) => number::float_to_int(f),
155 _ => None,
156 }
157 }
158
159 /// The number it is, as a float.
160 pub fn as_num(self) -> Option<f64> {
161 match self {
162 Value::Int(i) => Some(i as f64),
163 Value::Num(f) => Some(f),
164 _ => None,
165 }
166 }
167
168 /// The boolean it is.
169 pub fn as_bool(self) -> Option<bool> {
170 match self {
171 Value::Bool(b) => Some(b),
172 _ => None,
173 }
174 }
175
176 /// The table it is.
177 pub fn as_table(self) -> Option<TableRef> {
178 match self {
179 Value::Table(t) => Some(t),
180 _ => None,
181 }
182 }
183
184 /// The function it is.
185 pub fn as_func(self) -> Option<FuncRef> {
186 match self {
187 Value::Func(f) => Some(f),
188 _ => None,
189 }
190 }
191}
192
193/// A table key: a value normalized so equal keys are equal Rust values (floats with
194/// integral values become integers).
195#[inline]
196pub(crate) fn normalize_key(v: Value) -> Value {
197 match v {
198 Value::Num(f) => match number::float_to_int(f) {
199 Some(i) => Value::Int(i),
200 None => v,
201 },
202 other => other,
203 }
204}
205
206/// A hash for a normalized key: seeded (each table carries its state's seed, so keys a
207/// script chooses cannot be aimed at one slot), then mixed (murmur3's finalizer).
208#[inline]
209pub(crate) fn hash_key(v: Value, seed: u64) -> u64 {
210 let raw = match v {
211 Value::Nil => 0,
212 Value::Bool(b) => u64::from(b) + 1,
213 Value::Int(i) => i as u64,
214 Value::Num(f) => f.to_bits() ^ 0x5555,
215 Value::Str(r) => u64::from(r.idx) ^ (1 << 40),
216 Value::Table(r) => u64::from(r.idx) ^ (2 << 40),
217 Value::Func(r) => u64::from(r.idx) ^ (3 << 40),
218 Value::UserData(r) => u64::from(r.idx) ^ (4 << 40),
219 Value::Thread(r) => u64::from(r.idx) ^ (5 << 40),
220 };
221 let mut h = raw ^ seed;
222 h ^= h >> 33;
223 h = h.wrapping_mul(0xff51_afd7_ed55_8ccd);
224 h ^= h >> 33;
225 h = h.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
226 h ^ (h >> 33)
227}
228
229impl PartialEq for Value {
230 /// Raw equality without the heap: `1 == 1.0`, objects by identity, strings by identity
231 /// (equal to by content for short strings only). Compare script values with
232 /// [`Lua::raw_equal`](crate::Lua::raw_equal), which compares strings by content.
233 fn eq(&self, other: &Value) -> bool {
234 self.raw_eq(*other)
235 }
236}