use fs_err as FileSystemError;
use rustdoc_types::Crate;
use tracing::instrument;
use crate::error::Error;
pub struct Parser;
impl Parser {
#[instrument(skip(json), fields(json_len = json.len()))]
pub fn parse_json(json: &str) -> Result<Crate, Error> {
tracing::info!("Starting JSON parsing");
#[cfg(feature = "simd-json")]
let result = {
tracing::debug!("Using simd-json parser");
let mut json_bytes = json.as_bytes().to_vec();
simd_json::from_slice::<Crate>(&mut json_bytes).map_err(Error::SimdJsonParse)
};
#[cfg(not(feature = "simd-json"))]
let result: Result<Crate, Error> = {
tracing::debug!("Using serde_json parser");
serde_json::from_str(json).map_err(Error::JsonParse)
};
match &result {
Ok(krate) => {
tracing::info!(
crate_name = ?krate.index.get(&krate.root).and_then(|i| i.name.as_ref()),
item_count = krate.index.len(),
"Successfully parsed crate"
);
},
Err(e) => {
tracing::warn!(error = %e, "Failed to parse JSON");
},
}
result
}
#[instrument(skip_all, fields(path = %path.as_ref().display()))]
pub fn parse_file(path: impl AsRef<std::path::Path>) -> Result<Crate, Error> {
let path = path.as_ref();
tracing::debug!("Reading file");
let json = FileSystemError::read_to_string(path).map_err(Error::FileRead)?;
tracing::debug!(bytes = json.len(), "File read successfully");
Self::parse_json(&json)
}
#[inline]
pub fn parse_json_string(content: &str) -> Result<Crate, Error> {
Self::parse_json(content)
}
}