From 3028ee4cdde1514a607c7801f37d04abfc0192b8 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Thu, 17 Mar 2022 09:41:29 -0700 Subject: [PATCH] more robust cycle detection when debug printing lua values printing _G would still sometimes overflow for me. The code a0b8d2196a260726eca28b32fecaeb87420851ec wasn't sufficient so beef it up both with a hash set to remember all visited refs as well as a depth limit of 128, which should be deep enough for most practical purposes. --- luahelper/src/serde_lua/mod.rs | 39 ++++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/luahelper/src/serde_lua/mod.rs b/luahelper/src/serde_lua/mod.rs index 271a4ab0f..6b5348ee5 100644 --- a/luahelper/src/serde_lua/mod.rs +++ b/luahelper/src/serde_lua/mod.rs @@ -6,7 +6,7 @@ use serde::de::{ }; use serde::{serde_if_integer128, Deserialize}; use std::cmp::Ordering; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, HashSet}; use std::convert::TryInto; use thiserror::*; @@ -127,18 +127,39 @@ impl<'lua> Ord for ValueWrapper<'lua> { fn table_has_cycle(top: &Table, value: &Value) -> bool { if let Value::Table(table) = value { - for pair in table.clone().pairs::() { - if let Ok(pair) = pair { - if let Value::Table(child) = pair.1 { - if child == *top || child == *table { - return true; - } - if table_has_cycle(top, &Value::Table(child)) { - return true; + let mut seen = HashSet::new(); + + /// Capture the lua reference number. There's no direct accessor, + /// but the debug struct includes that number. + fn lref(t: &Table) -> String { + format!("{:?}", t) + } + + seen.insert(lref(top)); + + fn check_cycle(seen: &mut HashSet, table: &Table, depth: usize) -> bool { + let cref = lref(table); + if seen.contains(&cref) { + return true; + } + if depth > 128 { + // Seems suspicious + return true; + } + seen.insert(cref); + for pair in table.clone().pairs::() { + if let Ok(pair) = pair { + if let Value::Table(child) = pair.1 { + if check_cycle(seen, &child, depth + 1) { + return true; + } } } } + false } + + return check_cycle(&mut seen, table, 0); } false }