Skip to content

Consider changing the name of the Document::len #133

@nik-rev

Description

@nik-rev

KdlDocument is internally a Vec<KdlNode>. I wanted to find out how many KdlNodes there are so I did kdl_document.len()

And then, I actually looked at the definition of the .len() method:

/// 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
}

I would expect a .len() method to be O(1) and delegate to the inner Vec. But it actually stringifies the entire document and returns how many characters there are in it. It even returns usize as I would expect of a regular .len() method, so there is possibility for extra confusion there

Since commonly methods like .len() and .is_empty() are O(1) and do not perform extra work, I propose to rename the .len() method and keep is_empty() as-is. The new definition of .len() should be like this:

pub fn len(&self) -> usize {
    self.nodes.len()
}

This also applies to other .is_empty() and .len() methods in the crate, like on KdlEntry

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions