qubit-fs 0.3.3

Provider-neutral synchronous and asynchronous filesystem abstraction for Rust
Documentation
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Concrete asynchronous directory stream handle.

use std::fmt::Debug;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use std::time::Instant;

use crate::directory::DirectoryStreamState;
use crate::directory::ListOptions;
use crate::directory::ListScope;
use crate::directory::ListStreamPolicy;
use crate::directory::internal::ListNextCancellationGuard;
use crate::error::FsResult;
use crate::metadata::DirEntry;
use crate::metadata::FileSystemLimits;
use crate::path::PathConstraints;
use crate::spi::AsyncDirectoryStreamSession;
use crate::spi::SpiFuture;

/// Type-erased asynchronous directory enumeration handle.
///
/// The stream validates each provider entry before yielding it and preserves
/// terminal state across asynchronous calls.
/// Dropping a pending `next_entry_async` future makes the stream failed;
/// reopen the stream to continue enumeration.
///
/// # Examples
///
/// ```
/// # use qubit_fs::{AsyncFileSystem, FsResult, Path};
///
/// # use qubit_fs::directory::ListOptions;
///
/// # async fn visit(filesystem: &AsyncFileSystem, root: &Path) -> FsResult<()> {
/// let mut stream = filesystem.list(&qubit_fs::directory::ListScope::Path(root.clone()), ListOptions::default()).await?;
/// while let Some(entry) = stream.next_entry_async().await? {
///     println!("{}", entry.path);
/// }
///
/// # Ok(())
///
/// # }
/// ```
pub struct AsyncDirectoryStream {
    /// Provider enumeration session.
    session: Box<dyn AsyncDirectoryStreamSession>,
    /// Shared validation, deadline, and terminal-state policy.
    policy: ListStreamPolicy,
}

impl AsyncDirectoryStream {
    /// Wraps an already-open asynchronous provider enumeration session.
    ///
    /// # Parameters
    /// - `scope`: Validated root that constrains returned entries.
    /// - `session`: Provider asynchronous enumeration session.
    /// - `options`: Listing filters and caller-side resource limits.
    /// - `provider`: Provider identifier attached to facade-generated errors.
    /// - `path_semantics`: Path rules used to validate provider entries.
    /// - `limits`: Filesystem limits applied to returned entries.
    /// - `constraints`: Filesystem path-form constraints applied to returned
    ///   entries.
    ///
    /// # Returns
    /// A concrete type-erased asynchronous directory stream whose deadline
    /// starts when this constructor is called.
    ///
    /// # Errors
    /// Returns an invalid-options error if the configured deadline cannot be
    /// represented by the platform monotonic clock.
    #[inline]
    pub(crate) fn new(
        scope: ListScope,
        session: Box<dyn AsyncDirectoryStreamSession>,
        options: ListOptions,
        provider: &str,
        path_semantics: crate::path::PathSemantics,
        limits: FileSystemLimits,
        constraints: PathConstraints,
    ) -> FsResult<Self> {
        let policy = ListStreamPolicy::new(
            scope,
            options,
            provider,
            path_semantics,
            limits,
            constraints,
            Instant::now(),
        )?;
        Ok(Self { session, policy })
    }

    /// Returns the current lifecycle state of this stream.
    #[inline]
    #[must_use = "inspect the stream lifecycle state"]
    pub const fn state(&self) -> DirectoryStreamState {
        self.policy.state()
    }

    /// Asynchronously reads the next directory entry.
    ///
    /// # Returns
    /// A future resolving to `Some(entry)` for the next validated entry, or
    /// `None` after the provider reports that enumeration is exhausted.
    ///
    /// # Errors
    /// Returns a provider error, a validation or resource-limit error, or an
    /// invalid-state error if enumeration has already reached a terminal
    /// state. Any such error makes the stream terminal. Dropping this future
    /// after polling it makes the stream failed because the provider may have
    /// advanced before cancellation; reopen the stream to enumerate again.
    pub fn next_entry_async(&mut self) -> SpiFuture<'_, FsResult<Option<DirEntry>>> {
        Box::pin(async move {
            self.policy.before_next(Instant::now())?;
            let Self { session, policy } = self;
            let guard = ListNextCancellationGuard::new(policy);
            let result = session.next_entry_async().await;
            guard.finish(result, Instant::now())
        })
    }
}

impl Debug for AsyncDirectoryStream {
    /// Formats the stream without exposing provider state.
    ///
    /// # Parameters
    ///
    /// - `formatter`: Formatter receiving the stream's debug representation.
    #[inline]
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        formatter.debug_struct("AsyncDirectoryStream").finish_non_exhaustive()
    }
}