Skip to content

Commit

Permalink
Fix wrong formatting table with string keys that are numbers
Browse files Browse the repository at this point in the history
  • Loading branch information
khvzak committed Nov 9, 2024
1 parent 7aad0ad commit b34b90e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 13 deletions.
21 changes: 8 additions & 13 deletions src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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, "{{}}");
}
Expand All @@ -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, " = ")?;
}
Expand Down
3 changes: 3 additions & 0 deletions tests/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}

Expand Down

0 comments on commit b34b90e

Please sign in to comment.