Skip to main content

lua_types/
table.rs

1//! Lua table implementation (array + hash hybrid).
2//!
3//! Canonical port of `reference/lua-5.4.7/src/ltable.c`. Lives in
4//! `lua-types` because `LuaValue::Table(GcRef<LuaTable>)` is defined here
5//! and the table storage must be reachable without depending on
6//! `lua-vm`. The crate `lua_unsafe = "forbid"` lint is preserved.
7//!
8//! # Interior mutability
9//!
10//! `GcRef<T>` only yields `&T` on deref, so the mutable algorithms in
11//! C-Lua's `ltable.c` (which write through `Table *`) must operate
12//! through a `RefCell`. The split is:
13//!
14//! * `LuaTable` — outer handle. All public methods take `&self`.
15//! * `TableInner` — storage + algorithms. All mutating methods are
16//!   `&mut TableInner` and are reached via `inner.borrow_mut()`.
17//!
18//! The hash part uses Brent's variation of chained scatter tables.
19//! The key invariant: if an element is not in its *main position*
20//! (the slot its hash maps to), the colliding element *is* in its
21//! own main position.
22
23use std::cell::{Cell, RefCell};
24
25use crate::closure::LuaClosure;
26use crate::error::LuaError;
27use crate::gc::GcRef;
28use crate::string::LuaString;
29use crate::value::LuaValue;
30
31// ── Constants ─────────────────────────────────────────────────────────────────
32
33/// Largest `k` such that `2^k` fits in a signed `i32`.
34const MAXABITS: u32 = (std::mem::size_of::<i32>() as u32) * 8 - 1;
35
36/// Maximum size of the array part.
37pub const MAXASIZE: u32 = 1u32 << MAXABITS;
38
39/// Largest `k` such that `2^k` fits in a signed `i32` minus one (hash part).
40pub const MAXHBITS: u32 = MAXABITS - 1;
41
42/// Maximum size of the hash part (power-of-2 count of nodes).
43const MAXHSIZE: u32 = 1u32 << MAXHBITS;
44
45/// Minimum hash node count when lazily materializing a brand-new dummy table
46/// on first non-array key insertion.
47///
48/// In workloads that create many tiny record-like tables (`binarytrees`),
49/// a dummy→rehash path on every first insert adds avoidable overhead.
50const DUMMY_TABLE_INIT_HASH_NODES: u32 = 4;
51
52/// Bit 7 of `TableFlags`: when set, `alimit` is NOT the real array size.
53const BIT_RAS: u8 = 1 << 7;
54
55/// Soft cap on array growth in a single `raw_set` call.
56///
57/// Prevents pathological inserts of a far-away integer key (e.g.
58/// `t[1<<30] = 1`) from allocating gigabytes when an array slot would
59/// be the wrong choice; falls back to the hash part for keys above the
60/// cap. Matches C-Lua's behavioural bound, which is governed by
61/// `MAXASIZE` and the rehash density heuristic.
62pub const ARRAY_GROW_CAP: u32 = 1u32 << 20;
63
64/// Cap on total entries (array + hash). Growing a table past this with a
65/// fresh key raises `LuaError::Memory` (pcall reports `"not enough memory"`),
66/// emulating C-Lua's `malloc`-NULL termination of an unbounded
67/// `for i = 1, math.huge do a[i] = ... end` loop.
68///
69/// Ideally this would be a byte budget rather than an entry count, but the
70/// GC's byte counter does not track a table's internal `Vec` capacity, so a
71/// byte budget cannot see table growth. Until table memory is GC-accounted,
72/// this stays an entry cap, sized to comfortably hold realistic large tables
73/// (a 10M-element array, issue #37) while keeping the unbounded-loop stress
74/// tests terminating within the harness time and memory limits.
75pub const TOTAL_GROW_CAP: usize = 1usize << 24;
76
77const WEAK_KEYS: u8 = 1 << 0;
78const WEAK_VALUES: u8 = 1 << 1;
79
80// ── TableFlags ─────────────────────────────────────────────────────────────────
81
82/// Bitfield for a [`LuaTable`]: lower bits record absent fast-access
83/// metamethods; bit 7 encodes whether `alimit` is the real array size.
84#[derive(Clone, Copy, Debug, Default)]
85pub struct TableFlags(pub u8);
86
87impl TableFlags {
88    /// `isrealasize(t)` — bit 7 clear means alimit IS the real array size.
89    #[inline]
90    pub fn is_real_asize(self) -> bool {
91        (self.0 & BIT_RAS) == 0
92    }
93
94    /// `setrealasize(t)` — clear bit 7 so alimit becomes the canonical size.
95    #[inline]
96    pub fn set_real_asize(&mut self) {
97        self.0 &= !BIT_RAS;
98    }
99
100    /// `setnorealasize(t)` — set bit 7 so alimit is only a hint.
101    #[inline]
102    pub fn set_no_real_asize(&mut self) {
103        self.0 |= BIT_RAS;
104    }
105
106    /// `invalidateTMcache(t)` — clear all fast-access metamethod bits.
107    #[inline]
108    pub fn invalidate_tm_cache(&mut self) {
109        const MASK_FLAGS: u8 = 0x7F;
110        self.0 &= !MASK_FLAGS;
111    }
112}
113
114// ── TableNode ──────────────────────────────────────────────────────────────────
115
116/// One node in a table's hash part.
117///
118/// signed offset into the same node vector.
119pub struct TableNode {
120    /// Value stored at this key.  C: `gval(n)`.
121    pub value: LuaValue,
122    /// Key stored in this node.  C: `n->u.key_val` + `n->u.key_tt`.
123    pub key: LuaValue,
124    /// Collision-chain offset (positive or negative; zero means end of chain).
125    pub next: i32,
126}
127
128impl TableNode {
129    fn empty() -> Self {
130        TableNode { value: LuaValue::Nil, key: LuaValue::Nil, next: 0 }
131    }
132
133    fn key_is_nil(&self) -> bool { matches!(self.key, LuaValue::Nil) }
134    fn key_is_int(&self) -> bool { matches!(self.key, LuaValue::Int(_)) }
135    fn key_int(&self) -> i64 {
136        if let LuaValue::Int(i) = self.key { i }
137        else { panic!("TableNode::key_int: key is not int") }
138    }
139    fn key_is_short_str(&self) -> bool {
140        if let LuaValue::Str(s) = &self.key { s.is_short() }
141        else { false }
142    }
143    fn key_string(&self) -> &GcRef<LuaString> {
144        if let LuaValue::Str(s) = &self.key { s }
145        else { panic!("TableNode::key_string: key is not a string") }
146    }
147    fn key_value(&self) -> LuaValue { self.key.clone() }
148    fn set_key(&mut self, k: &LuaValue) { self.key = k.clone(); }
149}
150
151// ── TableSlotRef ───────────────────────────────────────────────────────────────
152
153/// Internal slot reference returned by the "get" family of functions.
154///
155/// Replaces C's `const TValue *` pattern, which may point into either
156/// the array part, the hash part, or the static `absentkey` sentinel.
157#[derive(Debug, Clone, Copy)]
158pub enum TableSlotRef {
159    /// Key lives in the array part at this 0-based index.
160    Array(usize),
161    /// Key lives in the hash part at this 0-based node index.
162    Hash(usize),
163    /// Key is absent from the table (C: `&absentkey`).
164    Absent,
165}
166
167// ── ceil_log2 ─────────────────────────────────────────────────────────────────
168
169/// Computes `ceil(log2(x))`; returns the minimum `k` such that `2^k >= x`.
170fn ceil_log2(x: u32) -> i32 {
171    static LOG_2: [u8; 256] = [
172        0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
173        6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
174        7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
175        7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
176        8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
177        8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
178        8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
179        8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
180    ];
181    let mut l: i32 = 0;
182    let mut x = x.wrapping_sub(1);
183    while x >= 256 { l += 8; x >>= 8; }
184    l + LOG_2[x as usize] as i32
185}
186
187// ── float hash (frexp-based) ──────────────────────────────────────────────────
188
189/// Hash a `f64` to an `i32` bucket index.
190///
191/// Uses `frexp` decomposition to produce a well-distributed integer hash.
192/// Handles inf/NaN by returning 0.
193///
194fn hash_float(n: f64) -> i32 {
195    if n.is_nan() || n.is_infinite() {
196        return 0;
197    }
198    let (mantissa, exp) = frexp(n);
199    let scaled = mantissa * -(i32::MIN as f64);
200    let ni = scaled as i64;
201    if ni as f64 != scaled {
202        return 0;
203    }
204    let u = (exp as u32).wrapping_add(ni as u32);
205    if u <= i32::MAX as u32 { u as i32 } else { !(u as i32) }
206}
207
208/// Decompose `x` into mantissa ∈ `[0.5, 1)` and integer exponent.
209fn frexp(x: f64) -> (f64, i32) {
210    if x == 0.0 || x.is_nan() || x.is_infinite() {
211        return (x, 0);
212    }
213    let bits = x.to_bits();
214    let exp_bits = ((bits >> 52) & 0x7FFu64) as i32;
215    if exp_bits == 0 {
216        let scaled = x * (2.0f64.powi(64));
217        let (m, e) = frexp(scaled);
218        return (m, e - 64);
219    }
220    let exp = exp_bits - 1022;
221    let mantissa_bits = (bits & !(0x7FFu64 << 52)) | (0x3FEu64 << 52);
222    (f64::from_bits(mantissa_bits), exp)
223}
224
225// ── TableInner ─────────────────────────────────────────────────────────────────
226
227/// Hybrid array + hash storage backing a [`LuaTable`].
228///
229/// All mutating algorithms live as `&mut TableInner` methods so they
230/// can be called from the outer `&self` API via `RefCell::borrow_mut`.
231pub struct TableInner {
232    pub flags: TableFlags,
233    pub lsizenode: u8,
234    pub alimit: u32,
235    pub array: Vec<LuaValue>,
236    pub node: Vec<TableNode>,
237    pub lastfree: Option<usize>,
238}
239
240impl TableInner {
241    fn new() -> Self {
242        TableInner {
243            flags: TableFlags(0x7F),
244            lsizenode: 0,
245            alimit: 0,
246            array: Vec::new(),
247            node: Vec::new(),
248            lastfree: None,
249        }
250    }
251
252    /// `isdummy(t)` — true when the table has no allocated hash part.
253    #[inline]
254    fn is_dummy(&self) -> bool { self.lastfree.is_none() }
255
256    /// `sizenode(t)` — nominal hash-part capacity (`1 << lsizenode`).
257    #[inline]
258    fn sizenode(&self) -> u32 { 1u32 << self.lsizenode }
259
260    /// `allocsizenode(t)` — 0 when dummy, else `1 << lsizenode`.
261    #[inline]
262    fn alloc_sizenode(&self) -> u32 {
263        if self.is_dummy() { 0 } else { self.sizenode() }
264    }
265
266    /// `isrealasize(t)` accessor.
267    #[inline]
268    fn is_real_asize(&self) -> bool { self.flags.is_real_asize() }
269
270    /// `ispow2(x)` — C treats 0 as a power of two.
271    #[inline]
272    fn is_pow2(x: u32) -> bool { x == 0 || x.is_power_of_two() }
273
274    /// Returns the real size of the array part. C: `luaH_realasize`.
275    fn real_asize(&self) -> u32 {
276        if self.limit_equals_asize() {
277            return self.alimit;
278        }
279        let mut size = self.alimit;
280        size |= size >> 1;
281        size |= size >> 2;
282        size |= size >> 4;
283        size |= size >> 8;
284        size |= size >> 16;
285        size = size.wrapping_add(1);
286        debug_assert!(
287            Self::is_pow2(size) && size / 2 < self.alimit && self.alimit < size
288        );
289        size
290    }
291
292    #[inline]
293    fn limit_equals_asize(&self) -> bool {
294        self.is_real_asize() || Self::is_pow2(self.alimit)
295    }
296
297    fn is_pow2_real_asize(&self) -> bool {
298        !self.is_real_asize() || Self::is_pow2(self.alimit)
299    }
300
301    fn set_limit_to_size(&mut self) -> u32 {
302        self.alimit = self.real_asize();
303        self.flags.set_real_asize();
304        self.alimit
305    }
306
307    // ── Hash helper functions ──────────────────────────────────────────────
308
309    fn hash_idx_for_int(&self, i: i64) -> usize {
310        let ui = i as u64;
311        let sn = self.sizenode() as usize;
312        let modulo = (sn - 1) | 1;
313        if ui <= i32::MAX as u64 {
314            (ui as usize) % modulo
315        } else {
316            (ui as usize) % modulo
317        }
318    }
319
320    #[inline]
321    fn hashpow2_idx(&self, h: u32) -> usize {
322        (h & (self.sizenode() - 1)) as usize
323    }
324
325    #[inline]
326    fn hashmod_idx(&self, h: usize) -> usize {
327        let sn = self.sizenode() as usize;
328        let modulo = (sn - 1) | 1;
329        h % modulo
330    }
331
332    fn main_position(&self, key: &LuaValue) -> usize {
333        match key {
334            LuaValue::Int(i) => self.hash_idx_for_int(*i),
335            LuaValue::Float(f) => {
336                let h = hash_float(*f);
337                self.hashmod_idx(h as usize)
338            }
339            LuaValue::Str(s) if s.is_short() => self.hashpow2_idx(s.hash()),
340            LuaValue::Str(s) => self.hashpow2_idx(s.hash()),
341            LuaValue::Bool(false) => self.hashpow2_idx(0),
342            LuaValue::Bool(true) => self.hashpow2_idx(1),
343            LuaValue::LightUserData(p) => {
344                let h = (*p as usize as u32) as usize;
345                self.hashmod_idx(h)
346            }
347            LuaValue::Function(LuaClosure::LightC(f)) => {
348                let h = (*f as u32) as usize;
349                self.hashmod_idx(h)
350            }
351            LuaValue::Table(t) => {
352                let h = (GcRef::identity(t) as u32) as usize;
353                self.hashmod_idx(h)
354            }
355            LuaValue::Function(LuaClosure::Lua(cl)) => {
356                let h = (GcRef::identity(cl) as u32) as usize;
357                self.hashmod_idx(h)
358            }
359            LuaValue::Function(LuaClosure::C(cl)) => {
360                let h = (GcRef::identity(cl) as u32) as usize;
361                self.hashmod_idx(h)
362            }
363            LuaValue::UserData(u) => {
364                let h = (GcRef::identity(u) as u32) as usize;
365                self.hashmod_idx(h)
366            }
367            LuaValue::Thread(th) => {
368                let h = (GcRef::identity(th) as u32) as usize;
369                self.hashmod_idx(h)
370            }
371            LuaValue::Nil => 0,
372        }
373    }
374
375    fn main_position_from_node(&self, nd: usize) -> usize {
376        let key = self.node[nd].key_value();
377        self.main_position(&key)
378    }
379
380    // ── Key equality ───────────────────────────────────────────────────────
381
382    fn equal_key(k1: &LuaValue, n2: &TableNode) -> bool {
383        let types_match = std::mem::discriminant(k1) == std::mem::discriminant(&n2.key);
384        if !types_match {
385            return false;
386        }
387        match &n2.key {
388            LuaValue::Nil => true,
389            LuaValue::Bool(b) => matches!(k1, LuaValue::Bool(b2) if b == b2),
390            LuaValue::Int(ni) => matches!(k1, LuaValue::Int(ki) if ki == ni),
391            LuaValue::Float(nf) => matches!(k1, LuaValue::Float(kf) if kf == nf),
392            LuaValue::LightUserData(np) => matches!(k1, LuaValue::LightUserData(kp) if kp == np),
393            LuaValue::Function(LuaClosure::LightC(nf)) => {
394                matches!(k1, LuaValue::Function(LuaClosure::LightC(kf)) if kf == nf)
395            }
396            LuaValue::Str(ns) if ns.is_long() => {
397                if let LuaValue::Str(ks) = k1 {
398                    ks.as_bytes() == ns.as_bytes()
399                } else { false }
400            }
401            _ => Self::gc_ptr_eq(k1, &n2.key),
402        }
403    }
404
405    fn gc_ptr_eq(a: &LuaValue, b: &LuaValue) -> bool {
406        match (a, b) {
407            (LuaValue::Str(sa), LuaValue::Str(sb)) => GcRef::ptr_eq(sa, sb),
408            (LuaValue::Table(ta), LuaValue::Table(tb)) => GcRef::ptr_eq(ta, tb),
409            (LuaValue::Function(LuaClosure::Lua(fa)), LuaValue::Function(LuaClosure::Lua(fb))) => {
410                GcRef::ptr_eq(fa, fb)
411            }
412            (LuaValue::Function(LuaClosure::C(fa)), LuaValue::Function(LuaClosure::C(fb))) => {
413                GcRef::ptr_eq(fa, fb)
414            }
415            (LuaValue::UserData(ua), LuaValue::UserData(ub)) => GcRef::ptr_eq(ua, ub),
416            (LuaValue::Thread(ta), LuaValue::Thread(tb)) => GcRef::ptr_eq(ta, tb),
417            _ => false,
418        }
419    }
420
421    // ── Generic hash-part lookup ───────────────────────────────────────────
422
423    fn get_generic_slot(&self, key: &LuaValue) -> TableSlotRef {
424        if self.is_dummy() { return TableSlotRef::Absent; }
425        let mut n = self.main_position(key);
426        loop {
427            if Self::equal_key(key, &self.node[n]) {
428                return TableSlotRef::Hash(n);
429            }
430            let nx = self.node[n].next;
431            if nx == 0 { return TableSlotRef::Absent; }
432            n = (n as isize + nx as isize) as usize;
433        }
434    }
435
436    // ── arrayindex / findindex ─────────────────────────────────────────────
437
438    fn array_index(k: i64) -> u32 {
439        let uk = k as u64;
440        if uk.wrapping_sub(1) < MAXASIZE as u64 { k as u32 } else { 0 }
441    }
442
443    /// Find the linear traversal position of `key`. Returns 0 for `Nil`
444    /// (first iteration). Errors with `"invalid key to 'next'"` when
445    /// the key is non-nil and not present in the table.
446    fn find_index(&self, key: &LuaValue, asize: u32) -> Result<u32, LuaError> {
447        if matches!(key, LuaValue::Nil) { return Ok(0); }
448        let i = if let LuaValue::Int(k) = key { Self::array_index(*k) } else { 0 };
449        if i.wrapping_sub(1) < asize { return Ok(i); }
450        let slot = self.get_generic_slot(key);
451        match slot {
452            TableSlotRef::Absent => {
453                Err(LuaError::runtime(format_args!("invalid key to 'next'")))
454            }
455            TableSlotRef::Hash(node_idx) => Ok((node_idx as u32 + 1) + asize),
456            TableSlotRef::Array(_) => unreachable!("getgeneric returned Array slot"),
457        }
458    }
459
460    /// Iteration step: given a key (`Nil` for first call), return the
461    /// next `(key, value)` pair in C-Lua's array-then-hash order.
462    fn next_pair(&self, key: &LuaValue) -> Result<Option<(LuaValue, LuaValue)>, LuaError> {
463        let asize = self.real_asize();
464        let i = self.find_index(key, asize)?;
465        let mut i = i as usize;
466        while i < asize as usize {
467            if !matches!(self.array[i], LuaValue::Nil) {
468                return Ok(Some((LuaValue::Int((i + 1) as i64), self.array[i].clone())));
469            }
470            i += 1;
471        }
472        let mut hi = i.saturating_sub(asize as usize);
473        while hi < self.node.len() {
474            if !matches!(self.node[hi].value, LuaValue::Nil) {
475                return Ok(Some((self.node[hi].key_value(), self.node[hi].value.clone())));
476            }
477            hi += 1;
478        }
479        Ok(None)
480    }
481
482    // ── Rehash helpers ─────────────────────────────────────────────────────
483
484    fn compute_sizes(nums: &[u32], pna: &mut u32) -> u32 {
485        let mut twotoi: u32 = 1;
486        let mut a: u32 = 0;
487        let mut na: u32 = 0;
488        let mut optimal: u32 = 0;
489        for i in 0..nums.len() {
490            if twotoi == 0 || *pna <= twotoi / 2 { break; }
491            a += nums[i];
492            if a > twotoi / 2 {
493                optimal = twotoi;
494                na = a;
495            }
496            twotoi = twotoi.wrapping_mul(2);
497        }
498        debug_assert!(optimal == 0 || optimal / 2 < na && na <= optimal);
499        *pna = na;
500        optimal
501    }
502
503    fn count_int(key: i64, nums: &mut [u32]) -> bool {
504        let k = Self::array_index(key);
505        if k != 0 {
506            nums[ceil_log2(k) as usize] += 1;
507            true
508        } else { false }
509    }
510
511    fn num_use_array(&self, nums: &mut [u32]) -> u32 {
512        debug_assert!(self.is_real_asize(), "numusearray: alimit must be real size");
513        let asize = self.alimit as usize;
514        let mut ause: u32 = 0;
515        let mut i: usize = 1;
516        let mut ttlg: usize = 1;
517        for lg in 0..=(MAXABITS as usize) {
518            let mut lc: u32 = 0;
519            let lim = if ttlg > asize { asize } else { ttlg };
520            if i > lim { break; }
521            while i <= lim {
522                if !matches!(self.array[i - 1], LuaValue::Nil) { lc += 1; }
523                i += 1;
524            }
525            nums[lg] += lc;
526            ause += lc;
527            ttlg = ttlg.saturating_mul(2);
528        }
529        ause
530    }
531
532    fn num_use_hash(&self, nums: &mut [u32], pna: &mut u32) -> i32 {
533        let mut totaluse: i32 = 0;
534        let mut ause: u32 = 0;
535        let mut i = self.node.len();
536        while i > 0 {
537            i -= 1;
538            let n = &self.node[i];
539            if !matches!(n.value, LuaValue::Nil) {
540                if n.key_is_int() {
541                    if Self::count_int(n.key_int(), nums) { ause += 1; }
542                }
543                totaluse += 1;
544            }
545        }
546        *pna += ause;
547        totaluse
548    }
549
550    fn set_node_vector(&mut self, size: u32) -> Result<(), LuaError> {
551        if size == 0 {
552            self.node = Vec::new();
553            self.lsizenode = 0;
554            self.lastfree = None;
555        } else {
556            let lsize = ceil_log2(size);
557            if lsize as u32 > MAXHBITS || (1u32 << lsize) > MAXHSIZE {
558                return Err(LuaError::runtime(format_args!("table overflow")));
559            }
560            let actual_size = 1u32 << lsize;
561            let mut nodes = Vec::with_capacity(actual_size as usize);
562            for _ in 0..actual_size { nodes.push(TableNode::empty()); }
563            self.node = nodes;
564            self.lsizenode = lsize as u8;
565            self.lastfree = Some(actual_size as usize);
566        }
567        Ok(())
568    }
569
570    fn reinsert(&mut self, old_nodes: Vec<(LuaValue, LuaValue)>) -> Result<(), LuaError> {
571        for (k, v) in old_nodes {
572            self.set(&k, v)?;
573        }
574        Ok(())
575    }
576
577    /// Resize the table to new array and hash sizes.
578    fn resize(&mut self, new_asize: u32, nhsize: u32) -> Result<(), LuaError> {
579        let old_asize = self.set_limit_to_size();
580
581        let (mut new_hash_node, mut new_hash_lsize, mut new_hash_lastfree) = {
582            let mut tmp = TableInner::new();
583            tmp.set_node_vector(nhsize)?;
584            (tmp.node, tmp.lsizenode, tmp.lastfree)
585        };
586
587        if new_asize < old_asize {
588            self.alimit = new_asize;
589            std::mem::swap(&mut self.node, &mut new_hash_node);
590            std::mem::swap(&mut self.lsizenode, &mut new_hash_lsize);
591            std::mem::swap(&mut self.lastfree, &mut new_hash_lastfree);
592
593            for i in (new_asize as usize)..(old_asize as usize) {
594                if !matches!(self.array[i], LuaValue::Nil) {
595                    let v = self.array[i].clone();
596                    self.set_int((i + 1) as i64, v)?;
597                }
598            }
599
600            self.alimit = old_asize;
601            std::mem::swap(&mut self.node, &mut new_hash_node);
602            std::mem::swap(&mut self.lsizenode, &mut new_hash_lsize);
603            std::mem::swap(&mut self.lastfree, &mut new_hash_lastfree);
604        }
605
606        self.array.resize_with(new_asize as usize, || LuaValue::Nil);
607
608        std::mem::swap(&mut self.node, &mut new_hash_node);
609        std::mem::swap(&mut self.lsizenode, &mut new_hash_lsize);
610        std::mem::swap(&mut self.lastfree, &mut new_hash_lastfree);
611        self.alimit = new_asize;
612
613        let old_hash_entries: Vec<(LuaValue, LuaValue)> = new_hash_node
614            .iter()
615            .filter(|n| !matches!(n.value, LuaValue::Nil))
616            .map(|n| (n.key_value(), n.value.clone()))
617            .collect();
618        drop(new_hash_node);
619        self.reinsert(old_hash_entries)?;
620
621        Ok(())
622    }
623
624    fn rehash(&mut self, extra_key: &LuaValue) -> Result<(), LuaError> {
625        let mut nums = [0u32; MAXABITS as usize + 1];
626        self.set_limit_to_size();
627
628        let na = self.num_use_array(&mut nums);
629        let mut na = na;
630        let mut totaluse = na as i32;
631
632        totaluse += self.num_use_hash(&mut nums, &mut na);
633
634        if let LuaValue::Int(ek) = extra_key {
635            if Self::count_int(*ek, &mut nums) { na += 1; }
636        }
637        totaluse += 1;
638
639        let asize = Self::compute_sizes(&nums, &mut na);
640
641        let nh = (totaluse - na as i32).max(0) as u32;
642        self.resize(asize, nh)
643    }
644
645    fn get_free_pos(&mut self) -> Option<usize> {
646        if self.is_dummy() { return None; }
647        loop {
648            let lf = self.lastfree?;
649            if lf == 0 {
650                self.lastfree = None;
651                return None;
652            }
653            let idx = lf - 1;
654            self.lastfree = Some(idx);
655            if self.node[idx].key_is_nil() {
656                return Some(idx);
657            }
658        }
659    }
660
661    fn find_chain_predecessor(&self, idx: usize) -> Option<usize> {
662        self.node.iter().enumerate().find(|(prev, node)| {
663            node.next != 0 && (*prev as isize + node.next as isize) == idx as isize
664        }).map(|(prev, _)| prev)
665    }
666
667    fn clear_node(&mut self, idx: usize) {
668        self.node[idx].key = LuaValue::Nil;
669        self.node[idx].value = LuaValue::Nil;
670        self.node[idx].next = 0;
671    }
672
673    fn remove_hash_node(&mut self, idx: usize) {
674        if let Some(prev) = self.find_chain_predecessor(idx) {
675            let next = self.node[idx].next;
676            self.node[prev].next = if next == 0 {
677                0
678            } else {
679                let target = idx as isize + next as isize;
680                (target - prev as isize) as i32
681            };
682            self.clear_node(idx);
683            return;
684        }
685
686        let next = self.node[idx].next;
687        if next == 0 {
688            self.clear_node(idx);
689            return;
690        }
691
692        let next_idx = (idx as isize + next as isize) as usize;
693        let moved_next = self.node[next_idx].next;
694        let moved_key = self.node[next_idx].key_value();
695        let moved_value = self.node[next_idx].value.clone();
696        self.node[idx].key = moved_key;
697        self.node[idx].value = moved_value;
698        self.node[idx].next = if moved_next == 0 {
699            0
700        } else {
701            let target = next_idx as isize + moved_next as isize;
702            (target - idx as isize) as i32
703        };
704        self.clear_node(next_idx);
705    }
706
707    fn clear_dead_hash_node(&mut self, idx: usize) {
708        self.remove_hash_node(idx);
709    }
710
711    fn new_key(&mut self, key: &LuaValue, value: LuaValue) -> Result<(), LuaError> {
712        if matches!(key, LuaValue::Nil) {
713            return Err(LuaError::runtime(format_args!("table index is nil")));
714        }
715        let normalised_key;
716        let key = if let LuaValue::Float(f) = key {
717            let f = *f;
718            if f.is_nan() {
719                return Err(LuaError::runtime(format_args!("table index is NaN")));
720            }
721            let k = f as i64;
722            if k as f64 == f {
723                normalised_key = LuaValue::Int(k);
724                &normalised_key
725            } else { key }
726        } else { key };
727
728        if matches!(value, LuaValue::Nil) { return Ok(()); }
729
730        if self.is_dummy() && !matches!(key, LuaValue::Int(_)) {
731            self.set_node_vector(DUMMY_TABLE_INIT_HASH_NODES)?;
732            let mp = self.main_position(key);
733            self.node[mp].set_key(key);
734            self.node[mp].value = value;
735            return Ok(());
736        }
737
738        let mp = self.main_position(key);
739        let mp_occupied = self.is_dummy() || !matches!(self.node[mp].value, LuaValue::Nil);
740        if mp_occupied {
741            let f = self.get_free_pos();
742            let f = match f {
743                None => {
744                    self.rehash(key)?;
745                    return self.set(key, value);
746                }
747                Some(idx) => idx,
748            };
749
750            debug_assert!(!self.is_dummy());
751            let othern = self.main_position_from_node(mp);
752
753            if othern != mp {
754                let mut prev = othern;
755                while (prev as isize + self.node[prev].next as isize) as usize != mp {
756                    prev = (prev as isize + self.node[prev].next as isize) as usize;
757                }
758                self.node[prev].next = (f as isize - prev as isize) as i32;
759                let mp_key = self.node[mp].key_value();
760                let mp_val = self.node[mp].value.clone();
761                let mp_next = self.node[mp].next;
762                self.node[f].key = mp_key;
763                self.node[f].value = mp_val;
764                if mp_next != 0 {
765                    self.node[f].next = mp_next + (mp as isize - f as isize) as i32;
766                    self.node[mp].next = 0;
767                } else {
768                    self.node[f].next = 0;
769                }
770                self.node[mp].value = LuaValue::Nil;
771            } else {
772                if self.node[mp].next != 0 {
773                    let target = (mp as isize + self.node[mp].next as isize) as usize;
774                    self.node[f].next = (target as isize - f as isize) as i32;
775                } else {
776                    debug_assert!(self.node[f].next == 0);
777                }
778                self.node[mp].next = (f as isize - mp as isize) as i32;
779                self.node[f].set_key(key);
780                debug_assert!(matches!(self.node[f].value, LuaValue::Nil));
781                self.node[f].value = value;
782                return Ok(());
783            }
784        }
785        self.node[mp].set_key(key);
786        debug_assert!(matches!(self.node[mp].value, LuaValue::Nil));
787        self.node[mp].value = value;
788        Ok(())
789    }
790
791    fn get_int_slot(&self, key: i64) -> TableSlotRef {
792        let alimit = self.alimit as u64;
793        let uk = key as u64;
794        if uk.wrapping_sub(1) < alimit {
795            return TableSlotRef::Array((key - 1) as usize);
796        }
797        if !self.is_real_asize() && alimit > 0 {
798            let masked = (uk.wrapping_sub(1)) & !(alimit.wrapping_sub(1));
799            if masked < alimit {
800                return TableSlotRef::Array((key - 1) as usize);
801            }
802        }
803        if self.is_dummy() { return TableSlotRef::Absent; }
804        let mut n = self.hash_idx_for_int(key);
805        loop {
806            if self.node[n].key_is_int() && self.node[n].key_int() == key {
807                return TableSlotRef::Hash(n);
808            }
809            let nx = self.node[n].next;
810            if nx == 0 { break; }
811            n = (n as isize + nx as isize) as usize;
812        }
813        TableSlotRef::Absent
814    }
815
816    /// Read an integer key directly to a [`LuaValue`], mirroring C's
817    /// `luaH_getint`. The array-part fast path returns the slot in a
818    /// single bounds-checked load without constructing an intermediate
819    /// [`TableSlotRef`] enum; only when the key falls through to the
820    /// hash part do we walk the chain. Equivalent in observable
821    /// behaviour to `slot_value(get_int_slot(key))`.
822    #[inline]
823    fn get_int_value(&self, key: i64) -> LuaValue {
824        let alimit = self.alimit as u64;
825        let uk = key as u64;
826        if uk.wrapping_sub(1) < alimit {
827            return self.array[(key - 1) as usize].clone();
828        }
829        self.get_int_value_cold(key)
830    }
831
832    #[cold]
833    #[inline(never)]
834    fn get_int_value_cold(&self, key: i64) -> LuaValue {
835        let alimit = self.alimit as u64;
836        let uk = key as u64;
837        if !self.is_real_asize() && alimit > 0 {
838            let masked = (uk.wrapping_sub(1)) & !(alimit.wrapping_sub(1));
839            if masked < alimit {
840                return self.array[(key - 1) as usize].clone();
841            }
842        }
843        if self.is_dummy() { return LuaValue::Nil; }
844        let mut n = self.hash_idx_for_int(key);
845        loop {
846            if self.node[n].key_is_int() && self.node[n].key_int() == key {
847                return self.node[n].value.clone();
848            }
849            let nx = self.node[n].next;
850            if nx == 0 { break; }
851            n = (n as isize + nx as isize) as usize;
852        }
853        LuaValue::Nil
854    }
855
856    fn get_short_str_slot(&self, key: &GcRef<LuaString>) -> TableSlotRef {
857        debug_assert!(key.is_short());
858        if self.is_dummy() { return TableSlotRef::Absent; }
859        let mut n = self.hashpow2_idx(key.hash());
860        loop {
861            if self.node[n].key_is_short_str() {
862                let ks = self.node[n].key_string();
863                if GcRef::ptr_eq(ks, key) || ks.as_bytes() == key.as_bytes() {
864                    return TableSlotRef::Hash(n);
865                }
866            }
867            let nx = self.node[n].next;
868            if nx == 0 { return TableSlotRef::Absent; }
869            n = (n as isize + nx as isize) as usize;
870        }
871    }
872
873    /// Read a short-string key directly to a [`LuaValue`], mirroring the
874    /// shape of [`Self::get_int_value`]: a single hash-chain walk that
875    /// produces the slot's value without constructing an intermediate
876    /// [`TableSlotRef`] enum. Short strings are interned, so pointer
877    /// equality wins almost every comparison; the byte-equality fallback
878    /// handles the rare cross-interning-table path. Callers must ensure
879    /// `key.is_short()` before dispatching here.
880    #[inline]
881    fn get_str_value(&self, key: &GcRef<LuaString>) -> LuaValue {
882        debug_assert!(key.is_short());
883        if self.is_dummy() { return LuaValue::Nil; }
884        let mut n = self.hashpow2_idx(key.hash());
885        loop {
886            if self.node[n].key_is_short_str() {
887                let ks = self.node[n].key_string();
888                if GcRef::ptr_eq(ks, key) || ks.as_bytes() == key.as_bytes() {
889                    return self.node[n].value.clone();
890                }
891            }
892            let nx = self.node[n].next;
893            if nx == 0 { return LuaValue::Nil; }
894            n = (n as isize + nx as isize) as usize;
895        }
896    }
897
898    /// Cold fallback for keys that miss the integer- and short-string
899    /// fast paths in [`LuaTable::get`] (long strings, booleans,
900    /// non-integer floats, table / function keys, light userdata, …).
901    /// Routes through the existing `get_slot` + `slot_value` pair.
902    #[cold]
903    #[inline(never)]
904    fn get_generic_value(&self, key: &LuaValue) -> LuaValue {
905        let slot = self.get_slot(key);
906        self.slot_value(slot)
907    }
908
909    fn get_str_slot(&self, key: &GcRef<LuaString>) -> TableSlotRef {
910        if key.is_short() {
911            self.get_short_str_slot(key)
912        } else {
913            let ko = LuaValue::Str(key.clone());
914            self.get_generic_slot(&ko)
915        }
916    }
917
918    fn get_slot(&self, key: &LuaValue) -> TableSlotRef {
919        match key {
920            LuaValue::Str(s) if s.is_short() => self.get_short_str_slot(s),
921            LuaValue::Int(i) => self.get_int_slot(*i),
922            LuaValue::Nil => TableSlotRef::Absent,
923            LuaValue::Float(f) => {
924                let f = *f;
925                let k = f as i64;
926                if k as f64 == f { self.get_int_slot(k) }
927                else { self.get_generic_slot(key) }
928            }
929            _ => self.get_generic_slot(key),
930        }
931    }
932
933    fn slot_value(&self, slot: TableSlotRef) -> LuaValue {
934        match slot {
935            TableSlotRef::Array(i) => self.array[i].clone(),
936            TableSlotRef::Hash(i) => self.node[i].value.clone(),
937            TableSlotRef::Absent => LuaValue::Nil,
938        }
939    }
940
941    fn finish_set(&mut self, key: &LuaValue, slot: TableSlotRef, value: LuaValue) -> Result<(), LuaError> {
942        match slot {
943            TableSlotRef::Absent => self.new_key(key, value),
944            TableSlotRef::Array(i) => { self.array[i] = value; Ok(()) }
945            TableSlotRef::Hash(i) => { self.node[i].value = value; Ok(()) }
946        }
947    }
948
949    fn set(&mut self, key: &LuaValue, value: LuaValue) -> Result<(), LuaError> {
950        let slot = self.get_slot(key);
951        self.finish_set(key, slot, value)
952    }
953
954    /// Set by integer key. May grow the array part up to
955    /// [`ARRAY_GROW_CAP`] for keys just past `alimit` to amortise the
956    /// common `t[#t+1] = v` pattern.
957    fn set_int(&mut self, key: i64, value: LuaValue) -> Result<(), LuaError> {
958        let slot = self.get_int_slot(key);
959        if matches!(slot, TableSlotRef::Absent) {
960            if key > 0 && (key as u64) <= ARRAY_GROW_CAP as u64 {
961                let cur = self.alimit as i64;
962                if key == cur + 1 && !matches!(value, LuaValue::Nil) {
963                    let new_size = (key as u32).next_power_of_two().max(4);
964                    let capped = new_size.min(ARRAY_GROW_CAP);
965                    if capped > self.alimit {
966                        let nsize = self.alloc_sizenode();
967                        self.resize(capped, nsize)?;
968                        let new_slot = self.get_int_slot(key);
969                        return self.finish_set(&LuaValue::Int(key), new_slot, value);
970                    }
971                }
972            }
973        }
974        match slot {
975            TableSlotRef::Absent => {
976                let k = LuaValue::Int(key);
977                self.new_key(&k, value)
978            }
979            TableSlotRef::Array(i) => { self.array[i] = value; Ok(()) }
980            TableSlotRef::Hash(i) => { self.node[i].value = value; Ok(()) }
981        }
982    }
983
984    /// Integer-key entry used by [`LuaTable::try_raw_set`] /
985    /// [`LuaTable::try_raw_set_int`]. The array fast path writes
986    /// directly into a slot that is by definition already allocated
987    /// (it lives inside the `Vec` at offset `key-1 < alimit`), so the
988    /// `TOTAL_GROW_CAP` guard cannot apply. Only the cold path can
989    /// allocate; the guard runs there.
990    #[inline]
991    fn try_raw_set_int_fast(&mut self, key: i64, value: LuaValue) -> Result<(), LuaError> {
992        let alimit = self.alimit as u64;
993        let uk = key as u64;
994        if uk.wrapping_sub(1) < alimit {
995            self.array[(key - 1) as usize] = value;
996            return Ok(());
997        }
998        self.try_raw_set_int_cold(key, value)
999    }
1000
1001    #[cold]
1002    #[inline(never)]
1003    fn try_raw_set_int_cold(&mut self, key: i64, value: LuaValue) -> Result<(), LuaError> {
1004        if self.array.len() + self.node.len() >= TOTAL_GROW_CAP
1005            && matches!(self.get_int_slot(key), TableSlotRef::Absent)
1006        {
1007            return Err(LuaError::Memory);
1008        }
1009        self.set_int_value_cold(key, value)
1010    }
1011
1012    /// Cold fallback for [`Self::set_int_value`]: handles the
1013    /// alimit-aliased slot (non-real-`asize` tables), hash-part lookup
1014    /// + in-place store, the array-grow-on-`#t+1` heuristic, and
1015    /// `new_key` insertion. Split into a `#[cold] #[inline(never)]`
1016    /// helper so LLVM lays out the array fast path as straight-line
1017    /// code in the inlined caller.
1018    #[cold]
1019    #[inline(never)]
1020    fn set_int_value_cold(&mut self, key: i64, value: LuaValue) -> Result<(), LuaError> {
1021        let alimit = self.alimit as u64;
1022        let uk = key as u64;
1023        if !self.is_real_asize() && alimit > 0 {
1024            let masked = (uk.wrapping_sub(1)) & !(alimit.wrapping_sub(1));
1025            if masked < alimit {
1026                self.array[(key - 1) as usize] = value;
1027                return Ok(());
1028            }
1029        }
1030        if !self.is_dummy() {
1031            let mut n = self.hash_idx_for_int(key);
1032            loop {
1033                if self.node[n].key_is_int() && self.node[n].key_int() == key {
1034                    self.node[n].value = value;
1035                    return Ok(());
1036                }
1037                let nx = self.node[n].next;
1038                if nx == 0 { break; }
1039                n = (n as isize + nx as isize) as usize;
1040            }
1041        }
1042        if key > 0 && (key as u64) <= ARRAY_GROW_CAP as u64 {
1043            let cur = self.alimit as i64;
1044            if key == cur + 1 && !matches!(value, LuaValue::Nil) {
1045                let new_size = (key as u32).next_power_of_two().max(4);
1046                let capped = new_size.min(ARRAY_GROW_CAP);
1047                if capped > self.alimit {
1048                    let nsize = self.alloc_sizenode();
1049                    self.resize(capped, nsize)?;
1050                    let new_slot = self.get_int_slot(key);
1051                    return self.finish_set(&LuaValue::Int(key), new_slot, value);
1052                }
1053            }
1054        }
1055        let k = LuaValue::Int(key);
1056        self.new_key(&k, value)
1057    }
1058
1059    // ── boundary search ────────────────────────────────────────────────────
1060
1061    fn hash_search(&self, mut j: u64) -> u64 {
1062        let mut i: u64;
1063        if j == 0 { j = 1; }
1064        loop {
1065            i = j;
1066            if j <= (i64::MAX as u64) / 2 {
1067                j *= 2;
1068            } else {
1069                j = i64::MAX as u64;
1070                let s = self.get_int_slot(j as i64);
1071                if matches!(s, TableSlotRef::Absent)
1072                    || matches!(self.slot_value(s), LuaValue::Nil)
1073                {
1074                    break;
1075                } else { return j; }
1076            }
1077            let s = self.get_int_slot(j as i64);
1078            if matches!(s, TableSlotRef::Absent) { break; }
1079            if matches!(self.slot_value(s), LuaValue::Nil) { break; }
1080        }
1081        while j - i > 1 {
1082            let m = i / 2 + j / 2;
1083            let s = self.get_int_slot(m as i64);
1084            let empty = matches!(s, TableSlotRef::Absent)
1085                || matches!(self.slot_value(s), LuaValue::Nil);
1086            if empty { j = m; } else { i = m; }
1087        }
1088        i
1089    }
1090
1091    fn bin_search(array: &[LuaValue], mut i: u32, mut j: u32) -> u32 {
1092        while j - i > 1 {
1093            let m = (i + j) / 2;
1094            if matches!(array[(m - 1) as usize], LuaValue::Nil) { j = m; }
1095            else { i = m; }
1096        }
1097        i
1098    }
1099
1100    /// Find a boundary `i` such that `t[i]` is present and `t[i+1]` is absent,
1101    /// or 0 if `t[1]` is absent. C: `luaH_getn`.
1102    fn getn(&mut self) -> u64 {
1103        let limit = self.alimit;
1104        if limit > 0 && matches!(self.array[(limit - 1) as usize], LuaValue::Nil) {
1105            if limit >= 2 && !matches!(self.array[(limit - 2) as usize], LuaValue::Nil) {
1106                if self.is_pow2_real_asize() && !Self::is_pow2(limit - 1) {
1107                    self.alimit = limit - 1;
1108                    self.flags.set_no_real_asize();
1109                }
1110                return (limit - 1) as u64;
1111            } else {
1112                let boundary = Self::bin_search(&self.array, 0, limit);
1113                if self.is_pow2_real_asize() && boundary > self.real_asize() / 2 {
1114                    self.alimit = boundary;
1115                    self.flags.set_no_real_asize();
1116                }
1117                return boundary as u64;
1118            }
1119        }
1120        if !self.limit_equals_asize() {
1121            if matches!(self.array[limit as usize], LuaValue::Nil) {
1122                return limit as u64;
1123            }
1124            let real = self.real_asize();
1125            if matches!(self.array[(real - 1) as usize], LuaValue::Nil) {
1126                let old_alimit = self.alimit;
1127                let boundary = Self::bin_search(&self.array, old_alimit, real);
1128                self.alimit = boundary;
1129                return boundary as u64;
1130            }
1131        }
1132        let limit = self.real_asize();
1133        debug_assert!(
1134            limit == self.real_asize()
1135                && (limit == 0 || !matches!(self.array[(limit - 1) as usize], LuaValue::Nil))
1136        );
1137        let next_key = (limit as i64).saturating_add(1);
1138        let next_slot = self.get_int_slot(next_key);
1139        let next_empty = matches!(next_slot, TableSlotRef::Absent)
1140            || matches!(self.slot_value(next_slot), LuaValue::Nil);
1141        if self.is_dummy() || next_empty {
1142            return limit as u64;
1143        }
1144        self.hash_search(limit as u64)
1145    }
1146}
1147
1148// ── LuaTable (outer handle) ────────────────────────────────────────────────────
1149
1150/// A Lua table: hybrid array + hash map.
1151///
1152/// All public methods take `&self` so the type works through
1153/// `GcRef<LuaTable>` (which only dereferences to a shared borrow).
1154/// Mutations are routed through an internal [`RefCell`].
1155#[derive(Debug)]
1156pub struct LuaTable {
1157    inner: RefCell<TableInner>,
1158    metatable: RefCell<Option<GcRef<LuaTable>>>,
1159    weak_mode: Cell<u8>,
1160}
1161
1162impl std::fmt::Debug for TableInner {
1163    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1164        f.debug_struct("TableInner")
1165            .field("alimit", &self.alimit)
1166            .field("array_len", &self.array.len())
1167            .field("node_len", &self.node.len())
1168            .finish()
1169    }
1170}
1171
1172impl Default for LuaTable {
1173    fn default() -> Self {
1174        LuaTable {
1175            inner: RefCell::new(TableInner::new()),
1176            metatable: RefCell::new(None),
1177            weak_mode: Cell::new(0),
1178        }
1179    }
1180}
1181
1182impl LuaTable {
1183    /// Construct an empty table. Used as a placeholder by callers that
1184    /// will populate it via the normal API.
1185    pub fn placeholder() -> Self { Self::default() }
1186
1187    /// Borrow inner storage for read access. Intended for advanced
1188    /// callers (e.g. the GC trace impl); prefer the typed methods.
1189    pub fn with_inner<R>(&self, f: impl FnOnce(&TableInner) -> R) -> R {
1190        f(&self.inner.borrow())
1191    }
1192
1193    /// Read a key. Returns `LuaValue::Nil` if absent or if `k` is nil.
1194    /// Integer keys take the direct array-part fast path used by
1195    /// [`LuaTable::get_int`]; short-string keys take the analogous
1196    /// hash-chain fast path used by [`LuaTable::get_short_str`]; every
1197    /// other key shape falls through to the cold generic slot lookup.
1198    /// Marked `#[inline(always)]` so the dispatch folds into the
1199    /// caller (the hot `state::fast_get` / `state::table_get_with_tm`
1200    /// frames in the VM); profiling at #[inline] showed LLVM was still
1201    /// emitting a cross-crate function call here.
1202    #[inline(always)]
1203    pub fn get(&self, k: &LuaValue) -> LuaValue {
1204        let inner = self.inner.borrow();
1205        match k {
1206            LuaValue::Nil => LuaValue::Nil,
1207            LuaValue::Int(i) => inner.get_int_value(*i),
1208            LuaValue::Str(s) if s.is_short() => inner.get_str_value(s),
1209            _ => inner.get_generic_value(k),
1210        }
1211    }
1212
1213    /// Read by integer key. Hot path: callers like `state.fast_get_int`
1214    /// and `state.table_get_with_tm` dispatch here on every integer-key
1215    /// access in user code (`t[1]`, `OP_GETI`, ipairs loops, etc.). The
1216    /// array-part lookup folds into a single bounds-checked load,
1217    /// matching C's `luaH_getint`.
1218    #[inline(always)]
1219    pub fn get_int(&self, key: i64) -> LuaValue {
1220        let inner = self.inner.borrow();
1221        inner.get_int_value(key)
1222    }
1223
1224    /// Read by string key. Despite the name (kept for compatibility
1225    /// with the old API), this dispatches internally to either the
1226    /// short- or long-string path; passing a long string is safe. The
1227    /// short-string branch (the common case — all interned identifiers
1228    /// and most table-field keys are short) takes the folded hash-walk
1229    /// in [`TableInner::get_str_value`]; long strings still go through
1230    /// the slot indirection.
1231    #[inline(always)]
1232    pub fn get_short_str(&self, k: &GcRef<LuaString>) -> LuaValue {
1233        let inner = self.inner.borrow();
1234        if k.is_short() {
1235            inner.get_str_value(k)
1236        } else {
1237            let slot = inner.get_str_slot(k);
1238            inner.slot_value(slot)
1239        }
1240    }
1241
1242    /// Read by raw byte-string key. Linear scan over the hash part —
1243    /// rarely-used helper for callers that don't have a `GcRef<LuaString>`
1244    /// handle.
1245    pub fn get_str_bytes(&self, key_bytes: &[u8]) -> LuaValue {
1246        let mut found = LuaValue::Nil;
1247        self.for_each_entry(|k, v| {
1248            if !matches!(found, LuaValue::Nil) { return; }
1249            if let LuaValue::Str(s) = k {
1250                if s.as_bytes() == key_bytes {
1251                    found = v.clone();
1252                }
1253            }
1254        });
1255        found
1256    }
1257
1258    /// Raw set without metamethod dispatch. Nil keys are an error;
1259    /// NaN-float keys are an error. Setting `v == Nil` clears the slot.
1260    pub fn raw_set(&self, k: LuaValue, v: LuaValue) {
1261        if matches!(k, LuaValue::Nil) { return; }
1262        if let LuaValue::Float(f) = &k {
1263            if f.is_nan() { return; }
1264        }
1265        let mut inner = self.inner.borrow_mut();
1266        let _ = inner.set(&k, v);
1267    }
1268
1269    /// Raw set with explicit error returns; preferred path used by
1270    /// `LuaTableRefExt::raw_set` in `lua-vm`. Integer keys (and floats
1271    /// that are exact integers) take the same direct array-part fast
1272    /// path used by [`LuaTable::try_raw_set_int`]; other key shapes
1273    /// fall through to the generic slot lookup.
1274    #[inline]
1275    pub fn try_raw_set(&self, k: LuaValue, v: LuaValue) -> Result<(), LuaError> {
1276        match &k {
1277            LuaValue::Nil => {
1278                Err(LuaError::runtime(format_args!("table index is nil")))
1279            }
1280            LuaValue::Float(f) if f.is_nan() => {
1281                Err(LuaError::runtime(format_args!("table index is NaN")))
1282            }
1283            LuaValue::Int(i) => {
1284                let key = *i;
1285                let mut inner = self.inner.borrow_mut();
1286                inner.try_raw_set_int_fast(key, v)
1287            }
1288            LuaValue::Float(f) => {
1289                let f = *f;
1290                let k_int = f as i64;
1291                if k_int as f64 == f {
1292                    let mut inner = self.inner.borrow_mut();
1293                    inner.try_raw_set_int_fast(k_int, v)
1294                } else {
1295                    self.try_raw_set_generic(k, v)
1296                }
1297            }
1298            _ => self.try_raw_set_generic(k, v),
1299        }
1300    }
1301
1302    /// Generic-key path for [`Self::try_raw_set`]. Split out so the
1303    /// integer fast path stays branch-light and inlineable.
1304    #[cold]
1305    #[inline(never)]
1306    fn try_raw_set_generic(&self, k: LuaValue, v: LuaValue) -> Result<(), LuaError> {
1307        let mut inner = self.inner.borrow_mut();
1308        if inner.array.len() + inner.node.len() >= TOTAL_GROW_CAP
1309            && matches!(inner.get_slot(&k), TableSlotRef::Absent)
1310        {
1311            return Err(LuaError::Memory);
1312        }
1313        inner.set(&k, v)
1314    }
1315
1316    /// Raw set by integer key with explicit error returns. Routes the
1317    /// array-part fast path through [`TableInner::set_int_value`] — a
1318    /// single bounds-checked store with no intermediate
1319    /// [`TableSlotRef`] indirection — and only consults the
1320    /// `TOTAL_GROW_CAP` allocation guard when the key would create a
1321    /// new slot.
1322    #[inline]
1323    pub fn try_raw_set_int(&self, k: i64, v: LuaValue) -> Result<(), LuaError> {
1324        let mut inner = self.inner.borrow_mut();
1325        inner.try_raw_set_int_fast(k, v)
1326    }
1327
1328    /// Resize the table to new array and hash sizes (sizing hint from
1329    /// the bytecode's `OP_NEWTABLE`).
1330    pub fn resize(&self, new_asize: u32, new_hsize: u32) -> Result<(), LuaError> {
1331        let mut inner = self.inner.borrow_mut();
1332        inner.resize(new_asize, new_hsize)
1333    }
1334
1335    /// Number of array-part slots currently allocated. Cheap counter
1336    /// for sizing decisions; NOT the Lua `#t` length operator.
1337    pub fn array_len(&self) -> usize { self.inner.borrow().array.len() }
1338
1339    /// Total occupied slots (array + hash) — used for legacy
1340    /// `len()` callers; prefer `getn` for the Lua `#` operator.
1341    pub fn len(&self) -> usize {
1342        let inner = self.inner.borrow();
1343        let mut n = 0usize;
1344        for v in inner.array.iter() {
1345            if !matches!(v, LuaValue::Nil) { n += 1; }
1346        }
1347        for node in inner.node.iter() {
1348            if !matches!(node.value, LuaValue::Nil) { n += 1; }
1349        }
1350        n
1351    }
1352    pub fn is_empty(&self) -> bool { self.len() == 0 }
1353
1354    /// `#t` boundary (C: `luaH_getn`). Mutates internal caching state.
1355    pub fn getn(&self) -> u64 {
1356        let mut inner = self.inner.borrow_mut();
1357        inner.getn()
1358    }
1359
1360    /// Returns true iff `k` resolves to a slot in this table (array or
1361    /// hash). Used by `next` to validate the resumption key.
1362    pub fn contains_key(&self, k: &LuaValue) -> bool {
1363        if matches!(k, LuaValue::Nil) { return false; }
1364        let inner = self.inner.borrow();
1365        let slot = inner.get_slot(k);
1366        !matches!(slot, TableSlotRef::Absent)
1367    }
1368
1369    pub fn metatable(&self) -> Option<GcRef<LuaTable>> {
1370        self.metatable.borrow().clone()
1371    }
1372
1373    /// Install a metatable. Inspects its `__mode` field eagerly so the
1374    /// GC trace impl can read [`weak_mode`] without re-entering the
1375    /// metatable RefCell.
1376    pub fn set_metatable(&self, mt: Option<GcRef<LuaTable>>) {
1377        let mode = mt.as_ref().map(|t| extract_weak_mode(t)).unwrap_or(0);
1378        self.weak_mode.set(mode);
1379        *self.metatable.borrow_mut() = mt;
1380    }
1381
1382    pub fn weak_mode(&self) -> u8 { self.weak_mode.get() }
1383
1384    /// Implements Lua's `next(t, k)`.
1385    pub fn next_pair(&self, k: &LuaValue) -> Option<(LuaValue, LuaValue)> {
1386        let inner = self.inner.borrow();
1387        inner.next_pair(k).ok().flatten()
1388    }
1389
1390    /// Like [`next_pair`] but reports the `"invalid key to 'next'"`
1391    /// error when `k` is non-nil and not present.
1392    pub fn try_next_pair(&self, k: &LuaValue) -> Result<Option<(LuaValue, LuaValue)>, LuaError> {
1393        let inner = self.inner.borrow();
1394        inner.next_pair(k)
1395    }
1396
1397    /// Walk every live (key, value) pair via the given closure.
1398    /// Used by the GC trace impl to avoid the overhead of repeatedly
1399    /// re-entering `find_index` from `next_pair`.
1400    pub fn for_each_entry(&self, mut f: impl FnMut(&LuaValue, &LuaValue)) {
1401        let inner = self.inner.borrow();
1402        for (i, v) in inner.array.iter().enumerate() {
1403            if !matches!(v, LuaValue::Nil) {
1404                let k = LuaValue::Int((i + 1) as i64);
1405                f(&k, v);
1406            }
1407        }
1408        for node in inner.node.iter() {
1409            if !matches!(node.value, LuaValue::Nil) {
1410                f(&node.key, &node.value);
1411            }
1412        }
1413    }
1414
1415    /// Drop weak entries whose weakly-tracked target is unreachable,
1416    /// and return the list of values whose strings must still be
1417    /// marked by the caller.
1418    pub fn prune_weak_dead(&self, is_reachable: &dyn Fn(usize) -> bool) -> Vec<LuaValue> {
1419        let mode = self.weak_mode.get();
1420        if mode == 0 { return Vec::new(); }
1421        let weak_k = (mode & WEAK_KEYS) != 0;
1422        let weak_v = (mode & WEAK_VALUES) != 0;
1423        let mut to_mark: Vec<LuaValue> = Vec::new();
1424        let mut inner = self.inner.borrow_mut();
1425        for i in 0..inner.array.len() {
1426            let v = inner.array[i].clone();
1427            if matches!(v, LuaValue::Nil) { continue; }
1428            if weak_v && value_is_dead_collectable(&v, is_reachable) {
1429                inner.array[i] = LuaValue::Nil;
1430                continue;
1431            }
1432            if weak_v {
1433                if matches!(v, LuaValue::Str(_)) { to_mark.push(v); }
1434            }
1435        }
1436        let mut i = 0;
1437        while i < inner.node.len() {
1438            let v = inner.node[i].value.clone();
1439            if matches!(v, LuaValue::Nil) {
1440                i += 1;
1441                continue;
1442            }
1443            let k = inner.node[i].key.clone();
1444            if weak_v && value_is_dead_collectable(&v, is_reachable) {
1445                inner.clear_dead_hash_node(i);
1446                continue;
1447            }
1448            if weak_k && value_is_dead_collectable(&k, is_reachable) {
1449                inner.clear_dead_hash_node(i);
1450                continue;
1451            }
1452            if weak_k {
1453                if matches!(k, LuaValue::Str(_)) { to_mark.push(k); }
1454            }
1455            if weak_v {
1456                if matches!(v, LuaValue::Str(_)) { to_mark.push(v); }
1457            }
1458            i += 1;
1459        }
1460        to_mark
1461    }
1462
1463    /// Ephemeron-convergence helper for pure `__mode = "k"` tables.
1464    pub fn ephemeron_values_to_mark(&self, is_reachable: &dyn Fn(usize) -> bool) -> Vec<LuaValue> {
1465        let mode = self.weak_mode.get();
1466        if (mode & WEAK_KEYS) == 0 || (mode & WEAK_VALUES) != 0 {
1467            return Vec::new();
1468        }
1469        let inner = self.inner.borrow();
1470        let mut out = Vec::new();
1471        for node in inner.node.iter() {
1472            if matches!(node.value, LuaValue::Nil) { continue; }
1473            if !value_is_dead_collectable(&node.key, is_reachable) {
1474                out.push(node.value.clone());
1475            }
1476        }
1477        for (i, v) in inner.array.iter().enumerate() {
1478            if matches!(v, LuaValue::Nil) { continue; }
1479            let k = LuaValue::Int((i + 1) as i64);
1480            if !value_is_dead_collectable(&k, is_reachable) {
1481                out.push(v.clone());
1482            }
1483        }
1484        out
1485    }
1486}
1487
1488// ── Free helpers ──────────────────────────────────────────────────────────────
1489
1490/// True iff `v` is a collectable non-string LuaValue whose target was
1491/// unreached during the mark phase. Strings are explicitly excluded.
1492fn value_is_dead_collectable(v: &LuaValue, is_reachable: &dyn Fn(usize) -> bool) -> bool {
1493    match v {
1494        LuaValue::Table(t) => !is_reachable(t.identity()),
1495        LuaValue::UserData(u) => !is_reachable(u.identity()),
1496        LuaValue::Thread(th) => !is_reachable(th.identity()),
1497        LuaValue::Function(c) => match c {
1498            LuaClosure::Lua(x) => !is_reachable(x.identity()),
1499            LuaClosure::C(x) => !is_reachable(x.identity()),
1500            LuaClosure::LightC(_) => false,
1501        },
1502        LuaValue::Str(_)
1503        | LuaValue::Nil
1504        | LuaValue::Bool(_)
1505        | LuaValue::Int(_)
1506        | LuaValue::Float(_)
1507        | LuaValue::LightUserData(_) => false,
1508    }
1509}
1510
1511/// Inspect a metatable's `__mode` field and produce the corresponding
1512/// `WEAK_KEYS | WEAK_VALUES` bitmask. Returns 0 when no `__mode` is
1513/// set or it is not a string.
1514fn extract_weak_mode(mt: &LuaTable) -> u8 {
1515    let inner = mt.inner.borrow();
1516    for node in inner.node.iter() {
1517        if let LuaValue::Str(ks) = &node.key {
1518            if ks.as_bytes() == b"__mode" {
1519                if let LuaValue::Str(vs) = &node.value {
1520                    let bytes = vs.as_bytes();
1521                    let mut mode = 0u8;
1522                    if bytes.iter().any(|b| *b == b'k') { mode |= WEAK_KEYS; }
1523                    if bytes.iter().any(|b| *b == b'v') { mode |= WEAK_VALUES; }
1524                    return mode;
1525                }
1526                return 0;
1527            }
1528        }
1529    }
1530    0
1531}
1532
1533// ──────────────────────────────────────────────────────────────────────────────
1534// PORT STATUS
1535//   source:        src/ltable.c (~995 lines, 28 functions), src/ltable.h
1536//   target_crate:  lua-types
1537//   confidence:    high
1538//   todos:         0
1539//   port_notes:    0
1540//   unsafe_blocks: 0
1541//   notes:         Canonical LuaTable: hybrid array + hash. Mirrors C's Table
1542//                  struct (flags, lsizenode, alimit, array, node, lastfree) with
1543//                  Vec<LuaValue> + Vec<TableNode> in place of raw C pointers, and
1544//                  Option<usize> indexing in place of Node*. The luaH_getn
1545//                  boundary search + alimit-aware integer-key fast path are
1546//                  ported faithfully (see getn() and get_int_slot()). The
1547//                  integer-key read path also exposes get_int_value, which
1548//                  mirrors C's luaH_getint by returning the array slot directly
1549//                  in one bounds-checked load (no TableSlotRef indirection) and
1550//                  splitting the rare alimit-aliased / hash-part path into a
1551//                  cold helper. The short-string read path mirrors that shape
1552//                  via get_str_value (single hash-chain walk, no TableSlotRef
1553//                  round-trip); LuaTable::get dispatches on integer/short-string
1554//                  keys inline and routes everything else through a #[cold]
1555//                  get_generic_value, matching C's luaH_get fast-path structure.
1556//                  LuaTable::get / get_int / get_short_str are #[inline(always)]
1557//                  so the dispatch folds into the cross-crate VM hot frames
1558//                  (state::fast_get / state::table_get_with_tm). Weak-table mode
1559//                  flags + the prune_weak_dead / ephemeron_values_to_mark
1560//                  helpers integrate with the lua-gc Trace impl.
1561// ──────────────────────────────────────────────────────────────────────────────