From 177c42cae75d8a0d9985c26ea28cb4f1cf7077de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kat=20March=C3=A1n?= Date: Sat, 23 Apr 2022 02:15:31 -0700 Subject: [PATCH] feat(len): add APIs to calculate component lengths (#36) Fixes: https://github.com/kdl-org/kdl-rs/issues/19 --- src/document.rs | 10 ++++++++++ src/entry.rs | 10 ++++++++++ src/identifier.rs | 10 ++++++++++ src/node.rs | 10 ++++++++++ 4 files changed, 40 insertions(+) diff --git a/src/document.rs b/src/document.rs index cbb780a..3c89553 100644 --- a/src/document.rs +++ b/src/document.rs @@ -168,6 +168,16 @@ impl KdlDocument { self.trailing = Some(trailing.into()); } + /// Length of this document when rendered as a string. + pub fn len(&self) -> usize { + format!("{}", self).len() + } + + /// Returns true if this document is completely empty (including whitespace) + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + /// Clears leading and trailing text (whitespace, comments). `KdlNode`s in /// this document will be unaffected. pub fn clear_fmt(&mut self) { diff --git a/src/entry.rs b/src/entry.rs index 0cf5c04..5533266 100644 --- a/src/entry.rs +++ b/src/entry.rs @@ -98,6 +98,16 @@ impl KdlEntry { self.value_repr = Some(repr.into()); } + /// Length of this entry when rendered as a string. + pub fn len(&self) -> usize { + format!("{}", self).len() + } + + /// Returns true if this entry is completely empty (including whitespace). + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + /// Auto-formats this entry. pub fn fmt(&mut self) { self.leading = None; diff --git a/src/identifier.rs b/src/identifier.rs index ef260f1..d633eaf 100644 --- a/src/identifier.rs +++ b/src/identifier.rs @@ -31,6 +31,16 @@ impl KdlIdentifier { self.repr = Some(repr.into()); } + /// Length of this identifier when rendered as a string. + pub fn len(&self) -> usize { + format!("{}", self).len() + } + + /// Returns true if this identifier is completely empty. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + /// Resets this identifier to its default representation. It will attempt /// to make it an unquoted identifier, and fall back to a string /// representation if that would be invalid. diff --git a/src/node.rs b/src/node.rs index 93e2fce..b31d990 100644 --- a/src/node.rs +++ b/src/node.rs @@ -106,6 +106,16 @@ impl KdlNode { self.trailing = Some(trailing.into()); } + /// Length of this node when rendered as a string. + pub fn len(&self) -> usize { + format!("{}", self).len() + } + + /// Returns true if this node is completely empty (including whitespace). + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + /// Clears leading and trailing text (whitespace, comments), as well as /// the space before the children block, if any. Individual entries and /// their formatting will be preserved.