pub struct Decor { /* private fields */ }
Expand description
A prefix and suffix,
Including comments, whitespaces and newlines.
Implementations§
source§impl Decor
impl Decor
sourcepub fn new(
prefix: impl Into<InternalString>,
suffix: impl Into<InternalString>
) -> Self
pub fn new(
prefix: impl Into<InternalString>,
suffix: impl Into<InternalString>
) -> Self
Creates a new decor from the given prefix and suffix.
Examples found in repository?
More examples
src/parser/state.rs (line 222)
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
pub(crate) fn on_std_header(
&mut self,
path: Vec<Key>,
trailing: &str,
) -> Result<(), CustomError> {
debug_assert!(!path.is_empty());
self.finalize_table()?;
let leading = std::mem::take(&mut self.trailing);
self.start_table(path, Decor::new(leading, trailing))?;
Ok(())
}
pub(crate) fn on_array_header(
&mut self,
path: Vec<Key>,
trailing: &str,
) -> Result<(), CustomError> {
debug_assert!(!path.is_empty());
self.finalize_table()?;
let leading = std::mem::take(&mut self.trailing);
self.start_aray_table(path, Decor::new(leading, trailing))?;
Ok(())
}
src/parser/key.rs (line 23)
17 18 19 20 21 22 23 24 25 26 27 28
pub(crate) fn key(input: Input<'_>) -> IResult<Input<'_>, Vec<Key>, ParserError<'_>> {
separated_list1(
DOT_SEP,
(ws, simple_key, ws).map(|(pre, (raw, key), suffix)| {
Key::new(key)
.with_repr_unchecked(Repr::new_unchecked(raw))
.with_decor(Decor::new(pre, suffix))
}),
)
.context(Context::Expression("key"))
.parse(input)
}
sourcepub fn clear(&mut self)
pub fn clear(&mut self)
Go back to default decor
Examples found in repository?
More examples
src/ser/pretty.rs (line 15)
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
fn visit_table_mut(&mut self, node: &mut crate::Table) {
node.decor_mut().clear();
// Empty tables could be semantically meaningful, so make sure they are not implicit
if !node.is_empty() {
node.set_implicit(true);
}
crate::visit_mut::visit_table_mut(self, node);
}
fn visit_value_mut(&mut self, node: &mut crate::Value) {
node.decor_mut().clear();
crate::visit_mut::visit_value_mut(self, node);
}
src/value.rs (line 221)
213 214 215 216 217 218 219 220 221 222 223 224 225 226
fn from_str(s: &str) -> Result<Self, Self::Err> {
use nom8::prelude::*;
let b = s.as_bytes();
let parsed = parser::value::value.parse(b).finish();
match parsed {
Ok(mut value) => {
// Only take the repr and not decor, as its probably not intended
value.decor_mut().clear();
Ok(value)
}
Err(e) => Err(Self::Err::new(e, b)),
}
}
sourcepub fn prefix(&self) -> Option<&str>
pub fn prefix(&self) -> Option<&str>
Get the prefix.
Examples found in repository?
src/encode.rs (line 25)
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
fn encode(&self, buf: &mut dyn Write, default_decor: (&str, &str)) -> Result {
let repr = self.to_repr();
write!(
buf,
"{}{}{}",
self.decor().prefix().unwrap_or(default_decor.0),
repr,
self.decor().suffix().unwrap_or(default_decor.1)
)
}
}
impl<'k> Encode for &'k [&'k Key] {
fn encode(&self, buf: &mut dyn Write, default_decor: (&str, &str)) -> Result {
for (i, key) in self.iter().enumerate() {
let first = i == 0;
let last = i + 1 == self.len();
let prefix = if first {
default_decor.0
} else {
DEFAULT_KEY_PATH_DECOR.0
};
let suffix = if last {
default_decor.1
} else {
DEFAULT_KEY_PATH_DECOR.1
};
if !first {
write!(buf, ".")?;
}
key.encode(buf, (prefix, suffix))?;
}
Ok(())
}
}
impl<T> Encode for Formatted<T>
where
T: ValueRepr,
{
fn encode(&self, buf: &mut dyn Write, default_decor: (&str, &str)) -> Result {
let repr = self.to_repr();
write!(
buf,
"{}{}{}",
self.decor().prefix().unwrap_or(default_decor.0),
repr,
self.decor().suffix().unwrap_or(default_decor.1)
)
}
}
impl Encode for Array {
fn encode(&self, buf: &mut dyn Write, default_decor: (&str, &str)) -> Result {
write!(buf, "{}[", self.decor().prefix().unwrap_or(default_decor.0))?;
for (i, elem) in self.iter().enumerate() {
let inner_decor;
if i == 0 {
inner_decor = DEFAULT_LEADING_VALUE_DECOR;
} else {
inner_decor = DEFAULT_VALUE_DECOR;
write!(buf, ",")?;
}
elem.encode(buf, inner_decor)?;
}
if self.trailing_comma() && !self.is_empty() {
write!(buf, ",")?;
}
write!(buf, "{}", self.trailing())?;
write!(buf, "]{}", self.decor().suffix().unwrap_or(default_decor.1))
}
}
impl Encode for InlineTable {
fn encode(&self, buf: &mut dyn Write, default_decor: (&str, &str)) -> Result {
write!(
buf,
"{}{{",
self.decor().prefix().unwrap_or(default_decor.0)
)?;
write!(buf, "{}", self.preamble)?;
let children = self.get_values();
let len = children.len();
for (i, (key_path, value)) in children.into_iter().enumerate() {
if i != 0 {
write!(buf, ",")?;
}
let inner_decor = if i == len - 1 {
DEFAULT_TRAILING_VALUE_DECOR
} else {
DEFAULT_VALUE_DECOR
};
key_path.as_slice().encode(buf, DEFAULT_INLINE_KEY_DECOR)?;
write!(buf, "=")?;
value.encode(buf, inner_decor)?;
}
write!(
buf,
"}}{}",
self.decor().suffix().unwrap_or(default_decor.1)
)
}
}
impl Encode for Value {
fn encode(&self, buf: &mut dyn Write, default_decor: (&str, &str)) -> Result {
match self {
Value::String(repr) => repr.encode(buf, default_decor),
Value::Integer(repr) => repr.encode(buf, default_decor),
Value::Float(repr) => repr.encode(buf, default_decor),
Value::Boolean(repr) => repr.encode(buf, default_decor),
Value::Datetime(repr) => repr.encode(buf, default_decor),
Value::Array(array) => array.encode(buf, default_decor),
Value::InlineTable(table) => table.encode(buf, default_decor),
}
}
}
impl Display for Document {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let mut path = Vec::new();
let mut last_position = 0;
let mut tables = Vec::new();
visit_nested_tables(self.as_table(), &mut path, false, &mut |t, p, is_array| {
if let Some(pos) = t.position() {
last_position = pos;
}
tables.push((last_position, t, p.clone(), is_array));
Ok(())
})
.unwrap();
tables.sort_by_key(|&(id, _, _, _)| id);
let mut first_table = true;
for (_, table, path, is_array) in tables {
visit_table(f, table, &path, is_array, &mut first_table)?;
}
self.trailing.fmt(f)
}
}
fn visit_nested_tables<'t, F>(
table: &'t Table,
path: &mut Vec<&'t Key>,
is_array_of_tables: bool,
callback: &mut F,
) -> Result
where
F: FnMut(&'t Table, &Vec<&'t Key>, bool) -> Result,
{
callback(table, path, is_array_of_tables)?;
for kv in table.items.values() {
match kv.value {
Item::Table(ref t) if !t.is_dotted() => {
path.push(&kv.key);
visit_nested_tables(t, path, false, callback)?;
path.pop();
}
Item::ArrayOfTables(ref a) => {
for t in a.iter() {
path.push(&kv.key);
visit_nested_tables(t, path, true, callback)?;
path.pop();
}
}
_ => {}
}
}
Ok(())
}
fn visit_table(
buf: &mut dyn Write,
table: &Table,
path: &[&Key],
is_array_of_tables: bool,
first_table: &mut bool,
) -> Result {
let children = table.get_values();
// We are intentionally hiding implicit tables without any tables nested under them (ie
// `table.is_empty()` which is in contrast to `table.get_values().is_empty()`). We are
// trusting the user that an empty implicit table is not semantically meaningful
//
// This allows a user to delete all tables under this implicit table and the implicit table
// will disappear.
//
// However, this means that users need to take care in deciding what tables get marked as
// implicit.
let is_visible_std_table = !(table.implicit && children.is_empty());
if path.is_empty() {
// don't print header for the root node
if !children.is_empty() {
*first_table = false;
}
} else if is_array_of_tables {
let default_decor = if *first_table {
*first_table = false;
("", DEFAULT_TABLE_DECOR.1)
} else {
DEFAULT_TABLE_DECOR
};
write!(buf, "{}[[", table.decor.prefix().unwrap_or(default_decor.0))?;
path.encode(buf, DEFAULT_KEY_PATH_DECOR)?;
writeln!(buf, "]]{}", table.decor.suffix().unwrap_or(default_decor.1))?;
} else if is_visible_std_table {
let default_decor = if *first_table {
*first_table = false;
("", DEFAULT_TABLE_DECOR.1)
} else {
DEFAULT_TABLE_DECOR
};
write!(buf, "{}[", table.decor.prefix().unwrap_or(default_decor.0))?;
path.encode(buf, DEFAULT_KEY_PATH_DECOR)?;
writeln!(buf, "]{}", table.decor.suffix().unwrap_or(default_decor.1))?;
}
// print table body
for (key_path, value) in children {
key_path.as_slice().encode(buf, DEFAULT_KEY_DECOR)?;
write!(buf, "=")?;
value.encode(buf, DEFAULT_VALUE_DECOR)?;
writeln!(buf)?;
}
Ok(())
}
More examples
src/parser/state.rs (line 46)
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
pub(crate) fn on_keyval(
&mut self,
mut path: Vec<Key>,
mut kv: TableKeyValue,
) -> Result<(), CustomError> {
{
let prefix = std::mem::take(&mut self.trailing);
let first_key = if path.is_empty() {
&mut kv.key
} else {
&mut path[0]
};
first_key
.decor
.set_prefix(prefix + first_key.decor.prefix().unwrap_or_default());
}
let table = &mut self.current_table;
let table = Self::descend_path(table, &path, true)?;
// "Likewise, using dotted keys to redefine tables already defined in [table] form is not allowed"
let mixed_table_types = table.is_dotted() == path.is_empty();
if mixed_table_types {
return Err(CustomError::DuplicateKey {
key: kv.key.get().into(),
table: None,
});
}
let key: InternalString = kv.key.get_internal().into();
match table.items.entry(key) {
indexmap::map::Entry::Vacant(o) => {
o.insert(kv);
}
indexmap::map::Entry::Occupied(o) => {
// "Since tables cannot be defined more than once, redefining such tables using a [table] header is not allowed"
return Err(CustomError::DuplicateKey {
key: o.key().as_str().into(),
table: Some(self.current_table_path.clone()),
});
}
}
Ok(())
}
sourcepub fn set_prefix(&mut self, prefix: impl Into<InternalString>)
pub fn set_prefix(&mut self, prefix: impl Into<InternalString>)
Set the prefix.
Examples found in repository?
src/ser/pretty.rs (line 39)
31 32 33 34 35 36 37 38 39 40 41 42 43 44
fn visit_array_mut(&mut self, node: &mut crate::Array) {
crate::visit_mut::visit_array_mut(self, node);
if (0..=1).contains(&node.len()) {
node.set_trailing("");
node.set_trailing_comma(false);
} else {
for item in node.iter_mut() {
item.decor_mut().set_prefix("\n ");
}
node.set_trailing("\n");
node.set_trailing_comma(true);
}
}
More examples
src/parser/state.rs (line 46)
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
pub(crate) fn on_keyval(
&mut self,
mut path: Vec<Key>,
mut kv: TableKeyValue,
) -> Result<(), CustomError> {
{
let prefix = std::mem::take(&mut self.trailing);
let first_key = if path.is_empty() {
&mut kv.key
} else {
&mut path[0]
};
first_key
.decor
.set_prefix(prefix + first_key.decor.prefix().unwrap_or_default());
}
let table = &mut self.current_table;
let table = Self::descend_path(table, &path, true)?;
// "Likewise, using dotted keys to redefine tables already defined in [table] form is not allowed"
let mixed_table_types = table.is_dotted() == path.is_empty();
if mixed_table_types {
return Err(CustomError::DuplicateKey {
key: kv.key.get().into(),
table: None,
});
}
let key: InternalString = kv.key.get_internal().into();
match table.items.entry(key) {
indexmap::map::Entry::Vacant(o) => {
o.insert(kv);
}
indexmap::map::Entry::Occupied(o) => {
// "Since tables cannot be defined more than once, redefining such tables using a [table] header is not allowed"
return Err(CustomError::DuplicateKey {
key: o.key().as_str().into(),
table: Some(self.current_table_path.clone()),
});
}
}
Ok(())
}
sourcepub fn suffix(&self) -> Option<&str>
pub fn suffix(&self) -> Option<&str>
Get the suffix.
Examples found in repository?
src/encode.rs (line 27)
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
fn encode(&self, buf: &mut dyn Write, default_decor: (&str, &str)) -> Result {
let repr = self.to_repr();
write!(
buf,
"{}{}{}",
self.decor().prefix().unwrap_or(default_decor.0),
repr,
self.decor().suffix().unwrap_or(default_decor.1)
)
}
}
impl<'k> Encode for &'k [&'k Key] {
fn encode(&self, buf: &mut dyn Write, default_decor: (&str, &str)) -> Result {
for (i, key) in self.iter().enumerate() {
let first = i == 0;
let last = i + 1 == self.len();
let prefix = if first {
default_decor.0
} else {
DEFAULT_KEY_PATH_DECOR.0
};
let suffix = if last {
default_decor.1
} else {
DEFAULT_KEY_PATH_DECOR.1
};
if !first {
write!(buf, ".")?;
}
key.encode(buf, (prefix, suffix))?;
}
Ok(())
}
}
impl<T> Encode for Formatted<T>
where
T: ValueRepr,
{
fn encode(&self, buf: &mut dyn Write, default_decor: (&str, &str)) -> Result {
let repr = self.to_repr();
write!(
buf,
"{}{}{}",
self.decor().prefix().unwrap_or(default_decor.0),
repr,
self.decor().suffix().unwrap_or(default_decor.1)
)
}
}
impl Encode for Array {
fn encode(&self, buf: &mut dyn Write, default_decor: (&str, &str)) -> Result {
write!(buf, "{}[", self.decor().prefix().unwrap_or(default_decor.0))?;
for (i, elem) in self.iter().enumerate() {
let inner_decor;
if i == 0 {
inner_decor = DEFAULT_LEADING_VALUE_DECOR;
} else {
inner_decor = DEFAULT_VALUE_DECOR;
write!(buf, ",")?;
}
elem.encode(buf, inner_decor)?;
}
if self.trailing_comma() && !self.is_empty() {
write!(buf, ",")?;
}
write!(buf, "{}", self.trailing())?;
write!(buf, "]{}", self.decor().suffix().unwrap_or(default_decor.1))
}
}
impl Encode for InlineTable {
fn encode(&self, buf: &mut dyn Write, default_decor: (&str, &str)) -> Result {
write!(
buf,
"{}{{",
self.decor().prefix().unwrap_or(default_decor.0)
)?;
write!(buf, "{}", self.preamble)?;
let children = self.get_values();
let len = children.len();
for (i, (key_path, value)) in children.into_iter().enumerate() {
if i != 0 {
write!(buf, ",")?;
}
let inner_decor = if i == len - 1 {
DEFAULT_TRAILING_VALUE_DECOR
} else {
DEFAULT_VALUE_DECOR
};
key_path.as_slice().encode(buf, DEFAULT_INLINE_KEY_DECOR)?;
write!(buf, "=")?;
value.encode(buf, inner_decor)?;
}
write!(
buf,
"}}{}",
self.decor().suffix().unwrap_or(default_decor.1)
)
}
}
impl Encode for Value {
fn encode(&self, buf: &mut dyn Write, default_decor: (&str, &str)) -> Result {
match self {
Value::String(repr) => repr.encode(buf, default_decor),
Value::Integer(repr) => repr.encode(buf, default_decor),
Value::Float(repr) => repr.encode(buf, default_decor),
Value::Boolean(repr) => repr.encode(buf, default_decor),
Value::Datetime(repr) => repr.encode(buf, default_decor),
Value::Array(array) => array.encode(buf, default_decor),
Value::InlineTable(table) => table.encode(buf, default_decor),
}
}
}
impl Display for Document {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let mut path = Vec::new();
let mut last_position = 0;
let mut tables = Vec::new();
visit_nested_tables(self.as_table(), &mut path, false, &mut |t, p, is_array| {
if let Some(pos) = t.position() {
last_position = pos;
}
tables.push((last_position, t, p.clone(), is_array));
Ok(())
})
.unwrap();
tables.sort_by_key(|&(id, _, _, _)| id);
let mut first_table = true;
for (_, table, path, is_array) in tables {
visit_table(f, table, &path, is_array, &mut first_table)?;
}
self.trailing.fmt(f)
}
}
fn visit_nested_tables<'t, F>(
table: &'t Table,
path: &mut Vec<&'t Key>,
is_array_of_tables: bool,
callback: &mut F,
) -> Result
where
F: FnMut(&'t Table, &Vec<&'t Key>, bool) -> Result,
{
callback(table, path, is_array_of_tables)?;
for kv in table.items.values() {
match kv.value {
Item::Table(ref t) if !t.is_dotted() => {
path.push(&kv.key);
visit_nested_tables(t, path, false, callback)?;
path.pop();
}
Item::ArrayOfTables(ref a) => {
for t in a.iter() {
path.push(&kv.key);
visit_nested_tables(t, path, true, callback)?;
path.pop();
}
}
_ => {}
}
}
Ok(())
}
fn visit_table(
buf: &mut dyn Write,
table: &Table,
path: &[&Key],
is_array_of_tables: bool,
first_table: &mut bool,
) -> Result {
let children = table.get_values();
// We are intentionally hiding implicit tables without any tables nested under them (ie
// `table.is_empty()` which is in contrast to `table.get_values().is_empty()`). We are
// trusting the user that an empty implicit table is not semantically meaningful
//
// This allows a user to delete all tables under this implicit table and the implicit table
// will disappear.
//
// However, this means that users need to take care in deciding what tables get marked as
// implicit.
let is_visible_std_table = !(table.implicit && children.is_empty());
if path.is_empty() {
// don't print header for the root node
if !children.is_empty() {
*first_table = false;
}
} else if is_array_of_tables {
let default_decor = if *first_table {
*first_table = false;
("", DEFAULT_TABLE_DECOR.1)
} else {
DEFAULT_TABLE_DECOR
};
write!(buf, "{}[[", table.decor.prefix().unwrap_or(default_decor.0))?;
path.encode(buf, DEFAULT_KEY_PATH_DECOR)?;
writeln!(buf, "]]{}", table.decor.suffix().unwrap_or(default_decor.1))?;
} else if is_visible_std_table {
let default_decor = if *first_table {
*first_table = false;
("", DEFAULT_TABLE_DECOR.1)
} else {
DEFAULT_TABLE_DECOR
};
write!(buf, "{}[", table.decor.prefix().unwrap_or(default_decor.0))?;
path.encode(buf, DEFAULT_KEY_PATH_DECOR)?;
writeln!(buf, "]{}", table.decor.suffix().unwrap_or(default_decor.1))?;
}
// print table body
for (key_path, value) in children {
key_path.as_slice().encode(buf, DEFAULT_KEY_DECOR)?;
write!(buf, "=")?;
value.encode(buf, DEFAULT_VALUE_DECOR)?;
writeln!(buf)?;
}
Ok(())
}
sourcepub fn set_suffix(&mut self, suffix: impl Into<InternalString>)
pub fn set_suffix(&mut self, suffix: impl Into<InternalString>)
Set the suffix.
Trait Implementations§
source§impl Ord for Decor
impl Ord for Decor
source§impl PartialEq<Decor> for Decor
impl PartialEq<Decor> for Decor
source§impl PartialOrd<Decor> for Decor
impl PartialOrd<Decor> for Decor
1.0.0 · source§fn le(&self, other: &Rhs) -> bool
fn le(&self, other: &Rhs) -> bool
This method tests less than or equal to (for
self
and other
) and is used by the <=
operator. Read moreimpl Eq for Decor
impl StructuralEq for Decor
impl StructuralPartialEq for Decor
Auto Trait Implementations§
impl RefUnwindSafe for Decor
impl Send for Decor
impl Sync for Decor
impl Unpin for Decor
impl UnwindSafe for Decor
Blanket Implementations§
source§impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
impl<Q, K> Equivalent<K> for Qwhere
Q: Eq + ?Sized,
K: Borrow<Q> + ?Sized,
source§fn equivalent(&self, key: &K) -> bool
fn equivalent(&self, key: &K) -> bool
Compare self to
key
and return true
if they are equal.