feat(assets): implement AssetDir directory iterator with rewind support
This commit is contained in:
parent
f07b5e7d6a
commit
f6e7bbd7a5
3 changed files with 54 additions and 0 deletions
31
crates/molotov-core/src/assets/dir.rs
Normal file
31
crates/molotov-core/src/assets/dir.rs
Normal file
|
|
@ -0,0 +1,31 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
use std::ffi::CString;
|
||||||
|
|
||||||
|
pub struct AssetDir {
|
||||||
|
entries: Vec<CString>,
|
||||||
|
cursor: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AssetDir {
|
||||||
|
pub fn new(filenames: Vec<String>) -> Self {
|
||||||
|
let entries = filenames
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|s| CString::new(s).ok())
|
||||||
|
.collect();
|
||||||
|
Self { entries, cursor: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_next_filename(&mut self) -> *const libc::c_char {
|
||||||
|
if self.cursor < self.entries.len() {
|
||||||
|
let ptr = self.entries[self.cursor].as_ptr();
|
||||||
|
self.cursor += 1;
|
||||||
|
ptr
|
||||||
|
} else {
|
||||||
|
std::ptr::null()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn rewind(&mut self) {
|
||||||
|
self.cursor = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
pub mod asset;
|
pub mod asset;
|
||||||
|
pub mod dir;
|
||||||
pub mod types;
|
pub mod types;
|
||||||
|
|
|
||||||
22
crates/molotov-core/tests/asset_dir_test.rs
Normal file
22
crates/molotov-core/tests/asset_dir_test.rs
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||||
|
use molotov_core::assets::dir::AssetDir;
|
||||||
|
use std::ffi::CStr;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_asset_dir_iteration_and_rewind() {
|
||||||
|
let files = vec!["font.ttf".to_string(), "cursor.png".to_string(), "sound.ogg".to_string()];
|
||||||
|
let mut dir = AssetDir::new(files);
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
let f1 = dir.get_next_filename();
|
||||||
|
assert!(!f1.is_null());
|
||||||
|
assert_eq!(CStr::from_ptr(f1).to_str().unwrap(), "font.ttf");
|
||||||
|
|
||||||
|
let f2 = dir.get_next_filename();
|
||||||
|
assert_eq!(CStr::from_ptr(f2).to_str().unwrap(), "cursor.png");
|
||||||
|
|
||||||
|
dir.rewind();
|
||||||
|
let f1_again = dir.get_next_filename();
|
||||||
|
assert_eq!(CStr::from_ptr(f1_again).to_str().unwrap(), "font.ttf");
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in a new issue