khora_lanes/asset_lane/
pack_loader.rs

1// Copyright 2025 eraflo
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use anyhow::{bail, Context, Result};
16use khora_core::asset::AssetSource;
17use std::{
18    fs::File,
19    io::{Read, Seek, SeekFrom},
20};
21
22/// A "Lane" responsible for the I/O task of reading raw asset data from a `data.pack` file.
23///
24/// This struct encapsulates the low-level logic of seeking to a specific
25/// location in the pack file and reading the correct number of bytes.
26pub struct PackLoadingLane {
27    /// An open file handle to the `data.pack` file.
28    pack_file: File,
29}
30
31impl PackLoadingLane {
32    /// Creates a new lane with a handle to the pack file.
33    pub fn new(pack_file: File) -> Self {
34        Self { pack_file }
35    }
36
37    /// Reads the raw bytes of an asset from the pack file based on its location.
38    pub fn load_asset_bytes(&mut self, source: &AssetSource) -> Result<Vec<u8>> {
39        match source {
40            AssetSource::Packed { offset, size } => {
41                let mut buffer = vec![0; *size as usize];
42                self.pack_file
43                    .seek(SeekFrom::Start(*offset))
44                    .context("Failed to seek to asset location in pack file")?;
45                self.pack_file
46                    .read_exact(&mut buffer)
47                    .context("Failed to read asset bytes from pack file")?;
48                Ok(buffer)
49            }
50            AssetSource::Path(_) => {
51                bail!("PackLoadingLane cannot load assets from a Path source.")
52            }
53        }
54    }
55}