file_data.rs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. pub trait HasFileData: std::any::Any {
  2. fn files(&self) -> Option<std::sync::Arc<dyn FileEngine>> {
  3. None
  4. }
  5. }
  6. #[cfg(feature = "serialize")]
  7. /// A file engine that serializes files to bytes
  8. #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)]
  9. pub struct SerializedFileEngine {
  10. pub files: std::collections::HashMap<String, Vec<u8>>,
  11. }
  12. #[cfg(feature = "serialize")]
  13. #[async_trait::async_trait(?Send)]
  14. impl FileEngine for SerializedFileEngine {
  15. fn files(&self) -> Vec<String> {
  16. self.files.keys().cloned().collect()
  17. }
  18. async fn file_size(&self, file: &str) -> Option<u64> {
  19. let file = self.files.get(file)?;
  20. Some(file.len() as u64)
  21. }
  22. async fn read_file(&self, file: &str) -> Option<Vec<u8>> {
  23. self.files.get(file).cloned()
  24. }
  25. async fn read_file_to_string(&self, file: &str) -> Option<String> {
  26. self.read_file(file)
  27. .await
  28. .map(|bytes| String::from_utf8_lossy(&bytes).to_string())
  29. }
  30. async fn get_native_file(&self, file: &str) -> Option<Box<dyn std::any::Any>> {
  31. self.read_file(file)
  32. .await
  33. .map(|val| Box::new(val) as Box<dyn std::any::Any>)
  34. }
  35. }
  36. #[async_trait::async_trait(?Send)]
  37. pub trait FileEngine {
  38. // get a list of file names
  39. fn files(&self) -> Vec<String>;
  40. // get the size of a file
  41. async fn file_size(&self, file: &str) -> Option<u64>;
  42. // read a file to bytes
  43. async fn read_file(&self, file: &str) -> Option<Vec<u8>>;
  44. // read a file to string
  45. async fn read_file_to_string(&self, file: &str) -> Option<String>;
  46. // returns a file in platform's native representation
  47. async fn get_native_file(&self, file: &str) -> Option<Box<dyn std::any::Any>>;
  48. }