docsrs 0.1.6

Easily retrieve docs for any crate on crates.io
Documentation
use super::{Doc, parsed::Parsed};
use crate::Error;
use std::{fs, path::Path};

/// Represents raw JSON documentation data in bytes.
///
/// This struct holds uncompressed JSON documentation data as bytes, typically
/// obtained from decompressing a zstd file or reading directly from a JSON file.
/// The data is ready to be parsed into a structured AST.
pub struct RawJson(Vec<u8>);

impl Doc<RawJson> {
    pub(super) fn new(data: Vec<u8>) -> Self {
        Self(RawJson(data))
    }

    /// Loads raw JSON documentation data from a file.
    ///
    /// Reads a JSON documentation file from disk, typically generated by rustdoc
    /// with the `--output-format json` flag. The file should contain the complete
    /// documentation AST in JSON format.
    ///
    /// # Arguments
    ///
    /// - `path` - Path to the JSON documentation file
    ///
    /// # Returns
    ///
    /// `Result<Doc<RawJson>, Error>` - Raw JSON documentation or file I/O error.
    ///
    /// # Example
    ///
    /// ```rust
    /// let raw_doc = Doc::from_json("docs/serde.json")?;
    /// let raw_doc = Doc::from_json("/path/to/std.json")?;
    /// ```
    pub fn from_json<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
        let json = fs::read(path)?;
        Ok(Doc(RawJson(json)))
    }

    /// Parses the raw JSON data into a structured documentation AST.
    ///
    /// Deserializes the JSON bytes into a rustdoc AST structure, making the
    /// documentation data accessible for indexing and searching. This step
    /// validates the JSON format and creates typed representations of all
    /// documentation items.
    ///
    /// # Returns
    ///
    /// `Result<Doc<Parsed>, Error>` - Parsed documentation AST or JSON parsing error.
    ///
    /// # Example
    ///
    /// ```rust
    /// let raw_doc = Doc::from_json("docs/serde.json")?;
    /// let parsed_doc = raw_doc.parse()?;
    /// ```
    pub fn parse(self) -> Result<Doc<Parsed>, Error> {
        let ast = serde_json::from_slice(&self.0.0)?;

        Ok(<Doc<Parsed>>::new(ast))
    }
}