Skip to content

Commit

Permalink
fix: Sort dotted tables (#164)
Browse files Browse the repository at this point in the history
  • Loading branch information
epage authored Sep 3, 2021
1 parent e00fc9e commit 37b55b7
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 16 deletions.
22 changes: 19 additions & 3 deletions src/inline_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::iter::FromIterator;

use crate::key::Key;
use crate::repr::{Decor, InternalString};
use crate::table::{sort_key_value_pairs, Iter, KeyValuePairs, TableKeyValue, TableLike};
use crate::table::{Iter, KeyValuePairs, TableKeyValue, TableLike};
use crate::value::{DEFAULT_TRAILING_VALUE_DECOR, DEFAULT_VALUE_DECOR};
use crate::{Item, Value};

Expand Down Expand Up @@ -212,8 +212,24 @@ impl InlineTable {
}

/// Sorts the key/value pairs by key.
pub fn sort(&mut self) {
sort_key_value_pairs(&mut self.items);
pub fn sort_values(&mut self) {
let mut keys: Vec<InternalString> = self
.items
.iter_mut()
.filter_map(|(key, kv)| match &mut kv.value {
Item::Value(Value::InlineTable(table)) if table.is_dotted() => {
table.sort_values();
Some(key)
}
Item::Value(_) => Some(key),
_ => None,
})
.cloned()
.collect();
keys.sort();
for key in keys {
self.items.get_refresh(&key);
}
}

/// Auto formats the table.
Expand Down
30 changes: 17 additions & 13 deletions src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,23 @@ impl Table {
///
/// Doesn't affect subtables or subarrays.
pub fn sort_values(&mut self) {
sort_key_value_pairs(&mut self.items);
let mut keys: Vec<InternalString> = self
.items
.iter_mut()
.filter_map(|(key, kv)| match &mut kv.value {
Item::Table(table) if table.is_dotted() => {
table.sort_values();
Some(key)
}
Item::Value(_) => Some(key),
_ => None,
})
.cloned()
.collect();
keys.sort();
for key in keys {
self.items.get_refresh(&key);
}
}

/// Auto formats the table.
Expand Down Expand Up @@ -323,18 +339,6 @@ impl<'s> IntoIterator for &'s Table {

pub(crate) type KeyValuePairs = LinkedHashMap<InternalString, TableKeyValue>;

pub(crate) fn sort_key_value_pairs(items: &mut LinkedHashMap<InternalString, TableKeyValue>) {
let mut keys: Vec<InternalString> = items
.iter()
.filter_map(|i| (i.1).value.as_value().map(|_| i.0))
.cloned()
.collect();
keys.sort();
for key in keys {
items.get_refresh(&key);
}
}

fn decorate_table(table: &mut Table) {
for (key_decor, value) in table
.items
Expand Down

0 comments on commit 37b55b7

Please sign in to comment.