basic/
basic.rs

1use keeshond_datapack::{DataObject, DataError, DataStore, TrustPolicy};
2use keeshond_datapack::source::{FilesystemSource, Source, SourceManager, TrustLevel};
3
4use std::io::Read;
5use std::cell::RefCell;
6use std::rc::Rc;
7
8struct TextData
9{
10    text : String
11}
12
13impl DataObject for TextData
14{
15    fn folder_name() -> &'static str where Self : Sized
16    {
17        "text"
18    }
19    fn trust_policy() -> TrustPolicy { TrustPolicy::UntrustedOk }
20    fn want_file(_pathname : &str) -> bool where Self : Sized
21    {
22        true
23    }
24    fn from_package_source(source : &mut Box<dyn Source>, package_name : &str, pathname : &str) -> Result<Self, DataError> where Self : Sized
25    {
26        let mut reader = source.read_file(package_name, pathname)?;
27        let mut text = String::new();
28        
29        let result = reader.read_to_string(&mut text);
30        
31        if result.is_err()
32        {
33            return Err(DataError::BadData("Couldn't read string".to_string()));
34        }
35        
36        Ok(TextData{ text })
37    }
38}
39
40fn main()
41{
42    println!("Listing items in mypackage/text:");
43    
44    let mut source = FilesystemSource::new("examples", TrustLevel::TrustedSource);
45    let iter = source.iter_entries("mypackage", "text");
46    
47    for entry in iter
48    {
49        match entry
50        {
51            Ok(pathname) => println!("{}", pathname),
52            Err(error) => println!("Error: {}", error)
53        }
54    }
55    
56    println!("Loading files from mypackage/text...");
57    
58    let source_manager = Rc::new(RefCell::new(SourceManager::new()));
59    source_manager.borrow_mut().add_source(Box::new(source));
60    
61    let mut store = DataStore::<TextData>::new(source_manager);
62    
63    store.load_package("mypackage").expect("Failed to load package.");
64    
65    for name in &["emoji.txt", "missingfile.txt", "loremipsum.txt"]
66    {
67        match store.get_id("mypackage", name)
68        {
69            Ok(id) =>
70            {
71                println!("Contents of {}:", name);
72                match store.get(id)
73                {
74                    Some(data) => println!("{}", data.text),
75                    None => println!("(not found)"),
76                }
77            }
78            Err(error) =>
79            {
80                println!("Error for {}:\n{}", name, error);
81            }
82        }
83        
84        println!("");
85    }
86}