Skip to main content

pleiades_data/data/
mod.rs

1use std::fmt;
2use std::path::PathBuf;
3use std::sync::OnceLock;
4
5#[cfg(feature = "packaged-artifact-path")]
6use std::path::Path;
7
8use pleiades_compression::CompressedArtifact;
9
10pub(crate) const PACKAGED_ARTIFACT_FIXTURE: &[u8] =
11    include_bytes!("../../tests/fixtures/packaged-artifact.bin");
12
13/// Returns the checked-in packaged artifact bytes.
14pub fn packaged_artifact_bytes() -> &'static [u8] {
15    PACKAGED_ARTIFACT_FIXTURE
16}
17
18/// Returns the bundled packed artifact.
19pub fn packaged_artifact() -> &'static CompressedArtifact {
20    static ARTIFACT: OnceLock<CompressedArtifact> = OnceLock::new();
21    ARTIFACT.get_or_init(crate::regenerate::build_packaged_artifact)
22}
23
24/// Decodes a packaged artifact from raw bytes.
25pub fn packaged_artifact_from_bytes(
26    bytes: &[u8],
27) -> Result<CompressedArtifact, pleiades_compression::CompressionError> {
28    let artifact = CompressedArtifact::decode(bytes)?;
29    artifact.validate()?;
30    Ok(artifact)
31}
32
33/// Errors that can occur while loading an external packaged artifact.
34#[derive(Debug)]
35pub enum PackagedArtifactLoadError {
36    /// The artifact could not be read from disk.
37    Io {
38        /// Path that was attempted.
39        path: PathBuf,
40        /// The underlying I/O error.
41        error: std::io::Error,
42    },
43    /// The artifact decoded but failed validation.
44    Decode(pleiades_compression::CompressionError),
45}
46
47impl fmt::Display for PackagedArtifactLoadError {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        match self {
50            Self::Io { path, error } => write!(
51                f,
52                "failed to read packaged artifact at {}: {}",
53                path.display(),
54                error
55            ),
56            Self::Decode(error) => write!(f, "failed to decode packaged artifact: {}", error),
57        }
58    }
59}
60
61impl std::error::Error for PackagedArtifactLoadError {}
62
63#[cfg(feature = "packaged-artifact-path")]
64/// Loads a packaged artifact from a file path.
65pub fn packaged_artifact_from_path(
66    path: impl AsRef<Path>,
67) -> Result<CompressedArtifact, PackagedArtifactLoadError> {
68    let path = path.as_ref();
69    let bytes = std::fs::read(path).map_err(|error| PackagedArtifactLoadError::Io {
70        path: path.to_path_buf(),
71        error,
72    })?;
73    packaged_artifact_from_bytes(&bytes).map_err(PackagedArtifactLoadError::Decode)
74}