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