Improve behaviour of tree creation and Tree::root_id().

`Tree` is now non-empty by default, and `Tree::root_id()` will no longer modify the tree when it is empty. To create an empty tree now it is necessary to use the capacity constructor with a capacity of zero:
  ```c++
  // default-constructed tree is now non-empty
  Tree tree;
  assert(!tree.empty()); // MODIFIED! was empty on previous version
  id_type root = tree.root_id(); // OK. default-constructed tree is now non-empty

  // to create an empty tree:
  Tree tree(0); // pass capacity of zero
  assert(tree.empty()); // as expected
  // but watchout, this is no longer possible:
  //id_type root = tree.root_id(); // ERROR: cannot get root of empty tree.
  ```
This changeset also enables the python library to call `root_id()` on a default-constructed tree

re #556
This commit is contained in:
Joao Paulo Magalhaes
2025-12-02 21:03:48 +00:00
parent f110282769
commit 0febd0fa65
12 changed files with 105 additions and 54 deletions

View File

@@ -0,0 +1,13 @@
import ryml
def test_create_empty_tree():
tree = ryml.Tree(0)
assert tree.empty()
def test_create_tree():
tree = ryml.Tree()
assert not tree.empty()
root = tree.root_id()
tree.to_seq(root)

View File

@@ -597,10 +597,11 @@ using id_type = RYML_ID_TYPE;
struct Tree
{
Tree();
Tree(id_type node_type, size_t arena_capacity=RYML_DEFAULT_TREE_ARENA_CAPACITY);
~Tree();
void reserve(id_type node_capacity);
void reserve_arena(size_t arena_capacity);
void reserve(id_type node_capacity=RYML_DEFAULT_TREE_CAPACITY);
void reserve_arena(size_t arena_capacity=RYML_DEFAULT_TREE_ARENA_CAPACITY);
void clear();
void clear_arena();