From 5190c3e6cb3cdbf0e62f43a628f32a5d0cbdb4cb Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Sat, 2 Dec 2023 08:05:47 -0700 Subject: [PATCH] ValuePrinter: improve array style table detection before: ``` > { a = {'a'}, 1, {2} } [ 1, [ 2, ], ] ``` after: ``` > { a = {'a'}, 1, {2} } { "a": [ "a", ], 1: 1, 2: [ 2, ], } ``` refs: https://github.com/wez/wezterm/pull/4336 --- luahelper/src/lib.rs | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/luahelper/src/lib.rs b/luahelper/src/lib.rs index 546e10069..80e78432c 100644 --- a/luahelper/src/lib.rs +++ b/luahelper/src/lib.rs @@ -3,7 +3,7 @@ pub use mlua; use mlua::{IntoLua, Value as LuaValue}; use std::cell::RefCell; -use std::collections::{BTreeMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashSet}; use std::rc::Rc; use wezterm_dynamic::{FromDynamic, ToDynamic, Value as DynValue}; @@ -306,6 +306,33 @@ impl<'lua> ValuePrinterHelper<'lua> { } } +fn is_array_style_table(t: &mlua::Table) -> bool { + let mut keys = BTreeSet::new(); + for pair in t.clone().pairs::() { + match pair { + Ok((key, _)) => match key { + LuaValue::Integer(i) if i >= 1 => { + keys.insert(i); + } + _ => return false, + }, + Err(_) => return false, + } + } + + // Now see if we have contiguous keys. + // The BTreeSet will iterate the keys in ascending order. + let mut expect = 1; + for key in keys { + if key != expect { + return false; + } + expect += 1; + } + + true +} + impl<'lua> std::fmt::Debug for ValuePrinterHelper<'lua> { fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::result::Result<(), std::fmt::Error> { match &self.value { @@ -316,7 +343,7 @@ impl<'lua> std::fmt::Debug for ValuePrinterHelper<'lua> { self.visited .borrow_mut() .insert(self.value.to_pointer() as usize); - if let Ok(true) = t.contains_key(1) { + if is_array_style_table(&t) { // Treat as list let mut list = fmt.debug_list(); for value in t.clone().sequence_values() {