summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlex Orlenko <zxteam@protonmail.com>2024-11-09 13:51:55 +0000
committerAlex Orlenko <zxteam@protonmail.com>2024-11-09 13:51:55 +0000
commitb34b90eca31a305c4a4bd900cbb9cb6bb4eb6da8 (patch)
tree7436c7c3a98957f55f055e1ac0dba84c1073d0aa
parent7aad0adcb4beacc8fb778b84fa6a2f088767acb7 (diff)
downloadmlua-b34b90eca31a305c4a4bd900cbb9cb6bb4eb6da8.zip
Fix wrong formatting table with string keys that are numbers
-rw-r--r--src/table.rs21
-rw-r--r--tests/table.rs3
2 files changed, 11 insertions, 13 deletions
diff --git a/src/table.rs b/src/table.rs
index d09b662..ddf3ff3 100644
--- a/src/table.rs
+++ b/src/table.rs
@@ -778,13 +778,8 @@ impl Table {
let mut pairs = self.pairs::<Value, Value>().flatten().collect::<Vec<_>>();
// Sort keys
pairs.sort_by(|(a, _), (b, _)| a.sort_cmp(b));
- let is_sequence = pairs.iter().enumerate().all(|(i, (k, _))| {
- if let Value::Integer(n) = k {
- *n == (i + 1) as Integer
- } else {
- false
- }
- });
+ let is_sequence = (pairs.iter().enumerate())
+ .all(|(i, (k, _))| matches!(k, Value::Integer(n) if *n == (i + 1) as Integer));
if pairs.is_empty() {
return write!(fmt, "{{}}");
}
@@ -797,14 +792,14 @@ impl Table {
writeln!(fmt, ",")?;
}
} else {
+ fn is_simple_key(key: &[u8]) -> bool {
+ key.iter().take(1).all(|c| c.is_ascii_alphabetic() || *c == b'_')
+ && key.iter().all(|c| c.is_ascii_alphanumeric() || *c == b'_')
+ }
+
for (key, value) in pairs {
match key {
- Value::String(key)
- if key
- .to_string_lossy()
- .chars()
- .all(|c| matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '_')) =>
- {
+ Value::String(key) if is_simple_key(&key.as_bytes()) => {
write!(fmt, "{}{}", " ".repeat(ident + 2), key.to_string_lossy())?;
write!(fmt, " = ")?;
}
diff --git a/tests/table.rs b/tests/table.rs
index d6cc90f..d2e4936 100644
--- a/tests/table.rs
+++ b/tests/table.rs
@@ -414,6 +414,9 @@ fn test_table_fmt() -> Result<()> {
"{\n [false] = false,\n [true] = true,\n [1] = 1,\n [1.99] = 1.99,\n [2] = 2,\n [3] = 3,\n [9.2] = 9.2,\n a = 5,\n b = {\n 6,\n },\n [\"special-<chars>\"] = 10,\n}"
);
+ let table2 = lua.create_table_from([("1", "first"), ("2", "second")])?;
+ assert_eq!(format!("{table2:#?}"), "{\n [\"1\"] = \"first\",\n [\"2\"] = \"second\",\n}");
+
Ok(())
}