qubit-json 0.13.0

Resource-aware infrastructure for lenient and strict JSON processing
Documentation
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Defines borrowed child iterators for mutable JSON traversal.

use std::slice;

use serde_json::Value;
use serde_json::map;

use super::super::JsonTreeLocation;

/// Lazily yields disjoint children and locations borrowed from one container.
pub(in crate::value::traverse) enum MutChildCursor<'tree> {
    /// Cursor over mutable array values and their original indices.
    Array(
        /// The remaining disjoint array elements in source order.
        std::iter::Enumerate<slice::IterMut<'tree, Value>>,
    ),
    /// Cursor over mutable object values in the map's native iteration order.
    Object(
        /// The remaining disjoint object values paired with borrowed keys.
        map::IterMut<'tree>,
    ),
}

impl<'tree> MutChildCursor<'tree> {
    /// Borrows a container's children, returning no cursor for scalar values.
    ///
    /// The returned iterator holds the exclusive borrow of the container.
    /// Each yielded child may be replaced, while the container structure stays
    /// borrowed and stable until its cursor is exhausted or dropped.
    ///
    /// # Parameters
    ///
    /// - `value`: Container whose children should be traversed; scalar values
    ///   produce no cursor.
    ///
    /// # Returns
    ///
    /// A cursor for arrays and objects, or `None` for scalar values.
    #[must_use]
    pub(in crate::value::traverse) fn new(value: &'tree mut Value) -> Option<Self> {
        match value {
            Value::Array(values) => Some(Self::Array(values.iter_mut().enumerate())),
            Value::Object(entries) => Some(Self::Object(entries.iter_mut())),
            Value::Null | Value::Bool(_) | Value::Number(_) | Value::String(_) => None,
        }
    }

    /// Returns the next child and a location borrowing its parent key if
    /// needed.
    ///
    /// The caller tracks root-inclusive depth independently of this location.
    ///
    /// # Returns
    ///
    /// The next mutable child and its location, or `None` after the container
    /// has no remaining children.
    pub(in crate::value::traverse) fn next(&mut self) -> Option<(&'tree mut Value, JsonTreeLocation<'tree>)> {
        match self {
            Self::Array(children) => children
                .next()
                .map(|(index, value)| (value, JsonTreeLocation::ArrayElement { index })),
            Self::Object(children) => children
                .next()
                .map(|(key, value)| (value, JsonTreeLocation::ObjectValue { key })),
        }
    }
}