laravel-nestedset 0.1.0

Nested set trees for Laravel Rust models: fast subtree and ancestor queries, safe under concurrent writes.
Documentation
//! Turning a list of nodes into a tree: `into_tree` and `into_flat_tree`.

use std::collections::HashMap;

use laravel::model::{CreateBuilder, Model};
use serde::Serialize;

use crate::node::NestedSet;

/// A node with its children, built by [`IntoTree::into_tree`]. It serializes as the model's own
/// fields plus `depth` and `children`, ready for a JSON API or a template:
///
/// ```json
/// { "id": 1, "name": "Shop", "depth": 0, "children": [{ "id": 2, "name": "Phones", ... }] }
/// ```
#[derive(Debug, Clone, Serialize)]
pub struct TreeNode<M> {
    /// The node.
    #[serde(flatten)]
    pub node: M,
    /// The node's depth in the built tree: `0` for the nodes at its top.
    pub depth: usize,
    /// The node's children, in the order the list had them.
    pub children: Vec<TreeNode<M>>,
}

/// Builds trees from a list of nodes, such as the result of a query.
///
/// ```ignore
/// use laravel_nestedset::IntoTree;
///
/// let menu = Category::query()
///     .scope(Category::default_order)
///     .get()
///     .await?
///     .into_tree();
/// ```
pub trait IntoTree<M> {
    /// Nests each node under its parent, when the parent is in the list. Nodes whose parent isn't
    /// in the list are at the top. Siblings keep the list's order, so order the query with
    /// [`NestedSet::default_order`] for tree order.
    fn into_tree(self) -> Vec<TreeNode<M>>;

    /// Lists every node right before its children, without nesting them. Handy for a `<select>` of categories indented by depth.
    fn into_flat_tree(self) -> Vec<M>;
}

impl<M: NestedSet> IntoTree<M> for Vec<M> {
    fn into_tree(self) -> Vec<TreeNode<M>> {
        let (mut slots, tops, children) = link(self);
        tops.into_iter()
            .map(|index| build(index, 0, &mut slots, &children))
            .collect()
    }

    fn into_flat_tree(self) -> Vec<M> {
        let (mut slots, tops, children) = link(self);
        let mut flat = Vec::with_capacity(slots.len());
        let mut stack: Vec<usize> = tops.into_iter().rev().collect();
        while let Some(index) = stack.pop() {
            if let Some(node) = slots[index].take() {
                flat.push(node);
            }
            if let Some(below) = children.get(&index) {
                stack.extend(below.iter().rev());
            }
        }
        flat
    }
}

/// The nodes in slots, the indexes of the top nodes, and each node's child indexes.
type Linked<M> = (Vec<Option<M>>, Vec<usize>, HashMap<usize, Vec<usize>>);

fn link<M: NestedSet>(nodes: Vec<M>) -> Linked<M> {
    let positions: HashMap<&M::Key, usize> = nodes
        .iter()
        .enumerate()
        .map(|(index, node)| (node.node_key(), index))
        .collect();
    let mut tops = Vec::new();
    let mut children: HashMap<usize, Vec<usize>> = HashMap::new();
    for (index, node) in nodes.iter().enumerate() {
        match node.parent_key().and_then(|parent| positions.get(parent)) {
            Some(&parent) if parent != index => children.entry(parent).or_default().push(index),
            _ => tops.push(index),
        }
    }
    (nodes.into_iter().map(Some).collect(), tops, children)
}

fn build<M>(
    index: usize,
    depth: usize,
    slots: &mut Vec<Option<M>>,
    children: &HashMap<usize, Vec<usize>>,
) -> TreeNode<M> {
    let node = slots[index].take().expect("each node is built once");
    let children = children
        .get(&index)
        .map(|below| {
            below
                .iter()
                .map(|&child| build(child, depth + 1, slots, children))
                .collect()
        })
        .unwrap_or_default();
    TreeNode { node, depth, children }
}

/// A node to create with its children, for
/// [`NestedSet::create_tree`] and [`NestedSet::create_child_tree`].
///
/// ```ignore
/// use laravel_nestedset::NewNode;
///
/// let shop = Category::create_tree(
///     NewNode::new(Category::create().name("Shop")).children([
///         NewNode::new(Category::create().name("Phones")),
///         NewNode::new(Category::create().name("Laptops")),
///     ]),
/// )
/// .await?;
/// ```
pub struct NewNode<M: Model> {
    pub(crate) create: CreateBuilder<M>,
    pub(crate) children: Vec<NewNode<M>>,
}

impl<M: Model> NewNode<M> {
    /// A node that `create` makes, without children yet.
    pub fn new(create: impl Into<CreateBuilder<M>>) -> Self {
        Self {
            create: create.into(),
            children: Vec::new(),
        }
    }

    /// Adds `children` after the node's other children.
    #[must_use]
    pub fn children(mut self, children: impl IntoIterator<Item = NewNode<M>>) -> Self {
        self.children.extend(children);
        self
    }
}