random_image_server/
state.rs1use std::fmt::Debug;
2
3use crate::{cache::CacheBackend, config::CacheBackendType};
4
5#[derive(Debug)]
7pub struct ServerState {
8 pub cache: Box<dyn CacheBackend>,
10
11 pub current_index: usize,
13}
14
15impl Default for ServerState {
16 fn default() -> Self {
17 Self {
18 cache: Box::new(crate::cache::InMemoryCache::new()),
19 current_index: 0,
20 }
21 }
22}
23
24impl CacheBackendType {
25 #[must_use]
27 pub fn create_backend(&self) -> Box<dyn CacheBackend> {
28 match self {
29 Self::InMemory => Box::new(crate::cache::InMemoryCache::new()),
30 Self::FileSystem => Box::new(crate::cache::FileSystemCache::new()),
31 }
32 }
33}
34
35impl ServerState {
36 #[must_use]
38 pub fn with_config(config: &crate::config::Config) -> Self {
39 Self {
40 cache: config.cache.backend.create_backend(),
41 current_index: 0,
42 }
43 }
44}
45
46#[cfg(test)]
47mod tests {
48 use super::*;
49 use crate::config::{CacheBackendType, CacheConfig, Config};
50 use pretty_assertions::assert_eq;
51
52 #[test]
53 fn test_server_state_default() {
54 let state = ServerState::default();
55 assert_eq!(state.current_index, 0);
56 assert!(state.cache.is_empty());
57 }
58
59 #[test]
60 fn test_server_state_with_config_in_memory() {
61 let config = Config {
62 cache: CacheConfig {
63 backend: CacheBackendType::InMemory,
64 },
65 ..Config::default()
66 };
67 let state = ServerState::with_config(&config);
68 assert_eq!(state.cache.backend_type(), "InMemory");
69 assert_eq!(state.current_index, 0);
70 assert!(state.cache.is_empty());
71 }
72
73 #[test]
74 fn test_server_state_with_config_file_system() {
75 let config = Config {
76 cache: CacheConfig {
77 backend: CacheBackendType::FileSystem,
78 },
79 ..Config::default()
80 };
81 let state = ServerState::with_config(&config);
82 assert_eq!(state.cache.backend_type(), "FileSystem");
83 assert_eq!(state.current_index, 0);
84 assert!(state.cache.is_empty());
85 }
86
87 #[test]
88 fn test_cache_backend_type_create_backend_in_memory() {
89 let backend = CacheBackendType::InMemory.create_backend();
90 assert_eq!(backend.size(), 0);
91 assert!(backend.is_empty());
92 }
93
94 #[test]
95 fn test_cache_backend_type_create_backend_file_system() {
96 let backend = CacheBackendType::FileSystem.create_backend();
97 assert_eq!(backend.size(), 0);
98 assert!(backend.is_empty());
99 }
100}