checkpointkit 0.1.4

Crash-resume checkpoint persistence with atomic writes and progress tracking
Documentation
//! Error types for `checkpointkit`.

use std::path::PathBuf;
use thiserror::Error;

/// Errors returned by checkpoint operations.
///
/// # Examples
///
/// ```rust
/// use checkpointkit::{save, CheckpointError};
///
/// let path = std::path::Path::new("/tmp/../test.json");
/// let state = 42;
/// let result = save(&path, &state);
/// assert!(matches!(result, Err(CheckpointError::PathTraversal(_))));
/// ```
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum CheckpointError {
    /// Serialization or deserialization failed.
    #[error(
        "failed to serialize or deserialize checkpoint state: {0}. Fix: ensure the state type is serializable and the file contains valid JSON."
    )]
    Serialize(#[from] serde_json::Error),
    /// Filesystem I/O failed.
    #[error("checkpoint I/O failed at `{path}`: {source}. Fix: ensure the parent directory exists and is writable.")]
    Io {
        /// Affected path.
        path: PathBuf,
        /// Underlying I/O error.
        source: std::io::Error,
    },
    /// Disk is full - special handling for this critical error.
    #[error("disk full at `{path}`: {source}. Fix: free up disk space before saving checkpoint.")]
    DiskFull {
        /// Affected path.
        path: PathBuf,
        /// Underlying I/O error.
        source: std::io::Error,
    },
    /// Path traversal detected.
    #[error("path traversal detected in `{0}`. Fix: ensure path does not contain `..` parent directory traversal.")]
    PathTraversal(PathBuf),
    /// An existing checkpoint file is empty or truncated (0 bytes).
    ///
    /// A valid checkpoint is never empty - even `null` serializes to 4 bytes -
    /// so an existing 0-byte file indicates a truncated/corrupt checkpoint, not
    /// absence (absence surfaces as a `NotFound` I/O error on open). Returned by
    /// [`crate::load`] instead of silently treating it as "no checkpoint".
    #[error("checkpoint at `{0}` is empty or truncated (0 bytes). Fix: delete it to restart from scratch, or restore it from a backup - an empty checkpoint is never valid.")]
    CorruptCheckpoint(PathBuf),
}

impl CheckpointError {
    /// Returns true if this error indicates the disk is full.
    #[must_use]
    pub const fn is_disk_full(&self) -> bool {
        matches!(self, Self::DiskFull { .. })
    }

    /// Creates a `CheckpointError` from an I/O error, detecting disk full conditions.
    #[must_use]
    pub fn from_io_error(path: PathBuf, source: std::io::Error) -> Self {
        use std::io::ErrorKind;
        let mut disk_full = source.kind() == ErrorKind::StorageFull;
        #[cfg(unix)]
        if !disk_full {
            disk_full = source.raw_os_error() == Some(libc::ENOSPC);
        }
        if disk_full {
            Self::DiskFull { path, source }
        } else {
            Self::Io { path, source }
        }
    }
}