1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#![warn(missing_docs)]

//! `keeshond_datapack` lets you easily load resources for your game and cache them in memory,
//!  mapped via pathname and accessible by simple numeric ID lookup. Define how they load
//!  with the [DataObject] trait, by implementing a function that takes a [Read] object.
//!  Define where they load from by instantiating a [source::Source].
//!
//! Datapack is used by Keeshond but can work with any engine.
//!
//! # How to use
//!
//! - Implement the [DataObject] trait for each type of object you want to be able to load in.
//! - Instantiate a [source::SourceManager] object and give it a [source::Source] such as a
//!  [source::FilesystemSource]
//! - Create a folder for each package on disk (if using [FilesystemSource](source::FilesystemSource)).
//! - Create subfolders within each package for each data type and place files within.
//! - Instantiate a [DataStore] for each data type you want to load.
//! - Use [DataStore::load_package()] to ensure the package is loaded at start.
//! - When creating objects that need resources, use [DataStore::get_id()] or [DataStore::get_id_mut()]
//!  to get a [DataId]. Store this id somewhere it can be used later, as these functions do involve a
//!  couple hash lookups.
//! - When using a resource, use [DataStore::get()] or [DataStore::get_mut()] with your id to get
//!  a reference to it so you can use it.
//!
//! Pathnames are of the form `path/to/file.png`. They must match exactly, including the use of one
//!  forward slash as a separator, and no separators at the beginning or end. The package name and
//!  data type folders are not included (they are implied). Pathnames are also case-sensitive even on
//!  platforms with case-insensitive filesystems (Windows, macOS).

extern crate hashbrown;
#[macro_use] extern crate try_or;
extern crate failure;
#[macro_use] extern crate failure_derive;
extern crate walkdir;

#[cfg(test)] mod tests;

/// The `Source` trait and implementations.
pub mod source;

use crate::source::{PackageError, Source, SourceManager};

use hashbrown::hash_map::HashMap;
use hashbrown::hash_set::HashSet;

use std::cell::RefCell;
use std::rc::Rc;
use std::io::Read;
use std::marker::Sized;

/// A numeric ID used to refer to a [DataObject] of a specific type.
pub type DataId = usize;

/// Return type when loading information from a [DataStore]
#[derive(Debug, PartialEq)]
pub enum DataStoreOk
{
    /// The package was loaded successfully
    Loaded,
    /// The package was already loaded, so no action was taken
    AlreadyLoaded
}

/// Return type when failing to load a [DataObject] from a [DataStore]
#[derive(Debug, Fail)]
pub enum DataError
{
    /// The given package was not found in the [source::Source]
    #[fail(display = "The package was not found")]
    PackageNotFound,
    /// The package is loaded, but has no [DataObject] by the given pathname
    #[fail(display = "The data object was not found")]
    DataNotFound,
    /// An error occurred while reading the list of items of the package
    ///  from the [source::Source]
    #[fail(display = "Failed to read the package list: {}", _0)]
    PackageListError(PackageError),
    /// An error of type [std::io::Error] occurred.
    #[fail(display = "An I/O error occurred: {}", _0)]
    IoError(#[cause] std::io::Error),
    /// A logical error occurred while reading a [DataObject]
    #[fail(display = "The data object contained invalid data")]
    BadData
}

impl From<std::io::Error> for DataError
{
    fn from(error : std::io::Error) -> DataError
    {
        DataError::IoError(error)
    }
}

struct LoadedData<T : DataObject + 'static>
{
    data_object : T,
    index : DataId,
    pathname : String
}

/// Represents a data item loaded from a package. Implement this trait to allow the system
///  to load new types of data.
pub trait DataObject
{
    /// The folder name that [DataObjects](DataObject) of this type are stored in
    fn folder_name() -> &'static str where Self : Sized;
    /// Determines whether or not a given file should be loaded while iterating through a package.
    fn want_file(pathname : &str) -> bool where Self : Sized;
    /// A constructor that returns a new [DataObject] of this type given a [Read] object
    fn from_io(reader: &mut Read, full_pathname : &str, source : &mut Box<Source>) -> Result<Self, DataError> where Self : Sized;
}

/// Storage that allows lookup and access of [DataObjects](DataObject) of a given type
pub struct DataStore<T : DataObject + 'static>
{
    source_manager : Rc<RefCell<SourceManager>>,
    loaded_packages : HashSet<String>,
    data_list : Vec<Option<T>>,
    data_map : HashMap<String, HashMap<String, DataId>>,
    next_index : DataId
}

impl<T : DataObject + 'static> DataStore<T>
{
    /// Constructs a new [DataStore] that gets its [Sources](source::Source) from the given
    ///  [SourceManager]
    pub fn new(source_manager : Rc<RefCell<SourceManager>>) -> DataStore<T>
    {
        DataStore::<T>
        {
            source_manager,
            loaded_packages : HashSet::new(),
            data_list : Vec::new(),
            data_map : HashMap::new(),
            next_index : 0
        }
    }
    
    /// Loads the package by the given name if it is not already loaded.
    pub fn load_package(&mut self, package_name : &str) -> Result<DataStoreOk, DataError>
    {
        if self.package_loaded(package_name)
        {
            return Ok(DataStoreOk::AlreadyLoaded);
        }
        
        if let Some(mut source) = self.source_manager.borrow_mut().get_package_source(package_name)
        {
            if !source.has_package(package_name)
            {
                return Err(DataError::PackageNotFound);
            }
            
            let folder_name = T::folder_name();
            let iter = source.iter_entries(package_name, folder_name);
            
            let mut loaded_items : Vec<LoadedData<T>> = Vec::new();
            let mut new_index = self.next_index;
            let package_map = self.data_map.entry(package_name.to_string()).or_insert(HashMap::new());
            
            for entry in iter
            {
                let pathname = try_or_else!(entry,
                    |error| Err(DataError::PackageListError(error)));
                
                if !T::want_file(&pathname)
                {
                    continue;
                }
                
                let full_pathname = format!("{}/{}/{}", package_name, folder_name, pathname);
                
                let mut reader = try_or_else!(source.read_file(&full_pathname),
                    |error| Err(DataError::PackageListError(error)));
                
                let data_object = T::from_io(&mut reader, &full_pathname, &mut source)?;
                let index : DataId;
                
                if let Some(entry) = package_map.get(&pathname)
                {
                    index = *entry;
                }
                else
                {
                    index = new_index;
                    new_index += 1;
                }
                
                loaded_items.push(LoadedData::<T> { data_object, index, pathname });
            }
            
            self.next_index = new_index;
            
            while self.data_list.len() < self.next_index
            {
                self.data_list.push(None);
            }
            
            for item in loaded_items.drain(..)
            {
                self.data_list[item.index] = Some(item.data_object);
                package_map.insert(item.pathname, item.index);
            }
            
            self.loaded_packages.insert(package_name.to_string());
        }
        else
        {
            return Err(DataError::PackageNotFound);
        }
        
        Ok(DataStoreOk::Loaded)
    }
    
    /// Gets the numeric ID of the [DataObject] from the given package at the given pathname.
    pub fn get_id(&self, package_name : &str, pathname : &str) -> Result<DataId, DataError>
    {
        if let Some(package_map) = self.data_map.get(package_name)
        {
            if let Some(id) = package_map.get(pathname)
            {
                return Ok(*id);
            }
            else
            {
                return Err(DataError::DataNotFound);
            }
        }
        
        Err(DataError::PackageNotFound)
    }
    
    /// Gets the numeric ID of the [DataObject] from the given package at the given pathname.
    ///  If the package is not loaded, it will be loaded automatically.
    pub fn get_id_mut(&mut self, package_name : &str, pathname : &str) -> Result<DataId, DataError>
    {
        if let Some(package_map) = self.data_map.get(package_name)
        {
            if let Some(id) = package_map.get(pathname)
            {
                return Ok(*id);
            }
            else
            {
                return Err(DataError::DataNotFound);
            }
        }
        else
        {
            self.load_package(package_name)?;
            
            return self.get_id_mut(package_name, pathname);
        }
    }
    
    /// Returns a reference to the [DataObject] by the given [DataId], if one exists.
    ///  Otherwise returns [None].
    pub fn get(&self, index : DataId) -> Option<&T>
    {
        if index >= self.data_list.len()
        {
            return None;
        }
        
        match &self.data_list[index]
        {
            Some(data) => Some(data),
            None => None
        }
    }
    
    /// Returns a mutable reference to the [DataObject] by the given [DataId], if one exists.
    ///  Otherwise returns [None].
    pub fn get_mut(&mut self, index : DataId) -> Option<&mut T>
    {
        if index >= self.data_list.len()
        {
            return None;
        }
        
        match &mut self.data_list[index]
        {
            Some(data) => Some(data),
            None => None
        }
    }
    
    /// Unloads the given package from memory. Any [DataObjects](DataObject) will be dropped,
    ///  but pathname-id mappings will be retained in memory so that existing references will
    ///  not be invalidated. Returns true if the package was loaded.
    pub fn unload_package(&mut self, package_name : &str) -> bool
    {
        if !self.loaded_packages.contains(package_name)
        {
            return false;
        }
        
        if let Some(package_map) = self.data_map.get(package_name)
        {
            for id in package_map.values()
            {
                self.data_list[*id as DataId] = None;
            }
            
            self.loaded_packages.remove(package_name);
        }
        else
        {
            return false;
        }
        
        true
    }
    
    /// Unloads all packages from memory. Any [DataObjects](DataObject) will be dropped,
    ///  but pathname-id mappings will be retained in memory so that existing references will
    ///  not be invalidated. Returns true if the package was loaded.
    pub fn unload_all(&mut self)
    {
        self.loaded_packages.clear();
        self.data_list.clear();
    }
    
    /// Returns true if the given package is loaded.
    pub fn package_loaded(&self, package_name : &str) -> bool
    {
        self.loaded_packages.contains(package_name)
    }
}