qubit-fs 0.3.2

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.
// =============================================================================
//! Failure returned by the convenience whole-file write operation.

use std::error::Error;
use std::fmt::Debug;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;

use crate::error::FsError;
use crate::write::WriteFailureState;
use crate::write::WriterRecovery;

/// A whole-file write failure retaining the recoverable writer when available.
///
/// This value is returned by `FileSystem::write_all` and is not constructed
/// directly by callers.
///
/// # Examples
///
/// ```rust
/// use qubit_fs::write::WriteAllFailure;
///
/// fn inspect_failure(failure: WriteAllFailure) {
///     let (error, state, confirmed_bytes, recovery) = failure.into_parts();
///     eprintln!("write failed after {confirmed_bytes} confirmed bytes: {error}");
///     if recovery.is_some() {
///         eprintln!("a writer is available for explicit recovery");
///     }
///     eprintln!("publication state: {state:?}");
/// }
/// ```
#[must_use]
pub struct WriteAllFailure {
    /// Contextual filesystem error that interrupted the whole-file write.
    error: Box<FsError>,
    /// Immutable publication certainty captured at failure.
    state: WriteFailureState,
    /// Bytes acknowledged before the failure, independent of later recovery.
    written_bytes: u64,
    /// Opened writer retained for explicit recovery when available.
    writer: Option<WriterRecovery>,
}

impl WriteAllFailure {
    /// Builds a failure within the facade after a write or commit error.
    /// # Parameters
    /// - `error`: Failure whose trusted filesystem context is being restored.
    /// - `state`: Publication state used to classify or retain this outcome.
    /// - `written_bytes`: Value used by `new` to preserve the writer operation
    ///   contract.
    /// - `writer`: Retained writer slot updated by cancellation tracking.
    pub(crate) fn new(
        error: FsError,
        state: WriteFailureState,
        written_bytes: u64,
        writer: Option<WriterRecovery>,
    ) -> Self {
        Self {
            error: Box::new(error),
            state,
            written_bytes,
            writer,
        }
    }

    /// Returns the causal filesystem error.
    ///
    /// # Returns
    /// The filesystem error with its original operation and provider context.
    #[must_use = "inspect the filesystem error instead of silently discarding it"]
    #[inline]
    pub const fn error(&self) -> &FsError {
        &self.error
    }
    /// Returns publication certainty at the original failure, even after
    /// recovery.
    ///
    /// # Returns
    /// The immutable publication state captured when the write failed.
    pub const fn state(&self) -> WriteFailureState {
        self.state
    }
    /// Returns the original acknowledged byte count, excluding uncertain
    /// writes.
    ///
    /// # Returns
    /// The number of bytes acknowledged before the failure.
    #[must_use]
    pub const fn written_bytes(&self) -> u64 {
        self.written_bytes
    }
    /// Transfers the retained session without changing the failure snapshot.
    ///
    /// # Returns
    /// The retained writer, or `None` if no writer remains available.
    pub fn take_recovery(&mut self) -> Option<WriterRecovery> {
        self.writer.take()
    }
    /// Returns the retained writer, if opening had completed.
    ///
    /// # Returns
    /// A shared reference to the retained writer, or `None` if unavailable.
    #[inline]
    #[must_use = "inspect the recovery state before abandoning the retained writer"]
    pub fn recovery(&self) -> Option<&WriterRecovery> {
        self.writer.as_ref()
    }
    /// Returns a mutable retained writer for explicit recovery.
    ///
    /// # Returns
    /// A mutable reference to the retained writer, or `None` if unavailable.
    #[inline]
    #[must_use = "inspect the recovery state before abandoning the retained writer"]
    pub fn recovery_mut(&mut self) -> Option<&mut WriterRecovery> {
        self.writer.as_mut()
    }
    /// Returns the causal error and optional writer.
    ///
    /// # Returns
    /// The original error, publication state, confirmed byte count, and
    /// optional retained writer.
    #[must_use = "retain the failure details or recover the retained writer"]
    #[inline]
    pub fn into_parts(self) -> (FsError, WriteFailureState, u64, Option<WriterRecovery>) {
        (*self.error, self.state, self.written_bytes, self.writer)
    }
}

impl Display for WriteAllFailure {
    /// Formats the causal failure without exposing writer internals.
    /// # Parameters
    /// - `formatter`: Formatter receiving the diagnostic representation.
    #[inline]
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        Display::fmt(&self.error, formatter)
    }
}

impl Debug for WriteAllFailure {
    /// Formats the causal error and whether recovery is available.
    /// # Parameters
    /// - `formatter`: Formatter receiving the diagnostic representation.
    #[inline]
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        formatter
            .debug_struct("WriteAllFailure")
            .field("error", &self.error)
            .field("state", &self.state)
            .field("written_bytes", &self.written_bytes)
            .field("has_recovery", &self.writer.is_some())
            .finish()
    }
}

impl Error for WriteAllFailure {
    /// Returns the underlying filesystem error.
    #[inline]
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        Some(self.error.as_ref())
    }
}