summaryrefslogtreecommitdiff
path: root/src/table.rs
diff options
context:
space:
mode:
authorAlex Orlenko <zxteam@protonmail.com>2023-04-11 20:36:32 +0100
committerAlex Orlenko <zxteam@protonmail.com>2023-04-11 20:36:41 +0100
commitcdbf04f50cd400cde1d5474b6aa0c6fdde999deb (patch)
tree5ae32d0f85dbb30c51133d20a2adf23983287dc1 /src/table.rs
parentba324b4f5497065f80d18ed42e0cf31d2ee1e3da (diff)
downloadmlua-cdbf04f50cd400cde1d5474b6aa0c6fdde999deb.zip
Add pretty-print to the Debug formatting to Value to Table.
This would allow dumping any Lua variable in human readable form.
Diffstat (limited to 'src/table.rs')
-rw-r--r--src/table.rs40
1 files changed, 39 insertions, 1 deletions
diff --git a/src/table.rs b/src/table.rs
index 5231a06..fd24ed9 100644
--- a/src/table.rs
+++ b/src/table.rs
@@ -1,3 +1,5 @@
+use std::collections::HashSet;
+use std::fmt;
use std::marker::PhantomData;
use std::os::raw::c_void;
@@ -20,7 +22,7 @@ use crate::value::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti, Nil, Value};
use {futures_core::future::LocalBoxFuture, futures_util::future};
/// Handle to an internal Lua table.
-#[derive(Clone, Debug)]
+#[derive(Clone)]
pub struct Table<'lua>(pub(crate) LuaRef<'lua>);
/// Owned handle to an internal Lua table.
@@ -738,6 +740,42 @@ impl<'lua> Table<'lua> {
}
Ok(())
}
+
+ pub(crate) fn fmt_pretty(
+ &self,
+ fmt: &mut fmt::Formatter,
+ ident: usize,
+ visited: &mut HashSet<*const c_void>,
+ ) -> fmt::Result {
+ visited.insert(self.to_pointer());
+
+ let t = self.clone();
+ // Collect key/value pairs into a vector so we can sort them
+ let mut pairs = t.pairs::<Value, Value>().flatten().collect::<Vec<_>>();
+ // Sort keys
+ pairs.sort_by(|(a, _), (b, _)| a.cmp(b));
+ if pairs.is_empty() {
+ return write!(fmt, "{{}}");
+ }
+ writeln!(fmt, "{{")?;
+ for (key, value) in pairs {
+ write!(fmt, "{}[", " ".repeat(ident + 2))?;
+ key.fmt_pretty(fmt, false, ident + 2, visited)?;
+ write!(fmt, "] = ")?;
+ value.fmt_pretty(fmt, true, ident + 2, visited)?;
+ writeln!(fmt, ",")?;
+ }
+ write!(fmt, "{}}}", " ".repeat(ident))
+ }
+}
+
+impl fmt::Debug for Table<'_> {
+ fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
+ if fmt.alternate() {
+ return self.fmt_pretty(fmt, 0, &mut HashSet::new());
+ }
+ fmt.write_fmt(format_args!("Table({:?})", self.0))
+ }
}
impl<'lua> PartialEq for Table<'lua> {