Skip to main content

cache_lite/
object.rs

1/*
2 * @filename: object.rs
3 * @description: Cache object implementation for cache-lite library
4 * @author: TaimWay <taimway@gmail.com>
5 * 
6 * Copyright (C) 2026 TaimWay
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in all
16 * copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 * SOFTWARE.
25 */
26
27use std::path::{Path, PathBuf};
28use std::time::SystemTime;
29use crate::{CacheError, CacheResult};
30
31/// Represents an individual cache object with file operations
32#[derive(Debug)]
33pub struct CacheObject {
34    name: String,
35    path: PathBuf,
36    id: u32,
37    created_at: SystemTime
38}
39
40impl CacheObject {
41    /// Creates a new CacheObject
42    pub fn new(
43        name: String, 
44        path: PathBuf, 
45        id: u32
46    ) -> Self {
47        let obj = CacheObject {
48            name,
49            path,
50            id,
51            created_at: SystemTime::now()
52        };
53        
54        obj
55    }
56
57    /// Returns the cache object name
58    /// 
59    /// # Returns
60    /// `&str` - Cache object identifier
61    pub fn name(&self) -> &str {
62        &self.name
63    }
64
65    /// Returns the filesystem path of the cache object
66    /// 
67    /// # Returns
68    /// `&Path` - Path to cache file
69    pub fn path(&self) -> &Path {
70        &self.path
71    }
72
73    /// Returns the creation time of the cache object
74    /// 
75    /// # Returns
76    /// `SystemTime` - Creation timestamp
77    pub fn created_at(&self) -> SystemTime {
78        self.created_at
79    }
80
81    /// Returns the cache object ID
82    /// 
83    /// # Returns
84    /// `u32` - Unique identifier
85    pub fn id(&self) -> u32 {
86        self.id
87    }
88
89    /// Opens the cache file for reading/writing
90    /// 
91    /// # Returns
92    /// `CacheResult<std::fs::File>` - File handle or error
93    pub fn get_file(&self) -> CacheResult<std::fs::File> {
94        std::fs::OpenOptions::new()
95            .read(true)
96            .write(true)
97            .create(true)
98            .open(&self.path)
99            .map_err(|e| CacheError::Io(e))
100    }
101
102    /// Reads and returns the entire cache content as string
103    /// 
104    /// # Returns
105    /// `CacheResult<String>` - Cache content or error
106    pub fn get_string(&self) -> CacheResult<String> {
107        std::fs::read_to_string(&self.path)
108            .map_err(|e| CacheError::Io(e))
109    }
110
111    /// Writes string content to the cache file
112    /// 
113    /// # Parameters
114    /// - `content: &str` - Content to write
115    /// 
116    /// # Returns
117    /// `CacheResult<()>` - Success or error
118    pub fn write_string(&self, content: &str) -> CacheResult<()> {
119        std::fs::write(&self.path, content)
120            .map_err(|e| CacheError::Io(e))
121    }
122
123    /// Writes binary content to the cache file
124    /// 
125    /// # Parameters
126    /// - `content: &[u8]` - Binary content to write
127    /// 
128    /// # Returns
129    /// `CacheResult<()>` - Success or error
130    pub fn write_bytes(&self, content: &[u8]) -> CacheResult<()> {
131        std::fs::write(&self.path, content)
132            .map_err(|e| CacheError::Io(e))
133    }
134
135    /// Reads and returns the entire cache content as bytes
136    /// 
137    /// # Returns
138    /// `CacheResult<Vec<u8>>` - Cache content or error
139    pub fn get_bytes(&self) -> CacheResult<Vec<u8>> {
140        std::fs::read(&self.path)
141            .map_err(|e| CacheError::Io(e))
142    }
143
144    /// Deletes the cache object and its file
145    /// 
146    /// # Returns
147    /// `CacheResult<()>` - Success or error
148    pub fn delete(&self) -> CacheResult<()> {
149        if self.path.exists() {
150            std::fs::remove_file(&self.path)
151                .map_err(|e| CacheError::Io(e))?;
152        }
153        Ok(())
154    }
155
156    /// Checks if the cache file exists
157    /// 
158    /// # Returns
159    /// `bool` - True if the cache file exists
160    pub fn exists(&self) -> bool {
161        self.path.exists()
162    }
163
164    /// Gets the file size in bytes
165    /// 
166    /// # Returns
167    /// `CacheResult<u64>` - File size in bytes or error
168    pub fn size(&self) -> CacheResult<u64> {
169        std::fs::metadata(&self.path)
170            .map(|metadata| metadata.len())
171            .map_err(|e| CacheError::Io(e))
172    }
173
174    /// Checks if the cache has expired based on its lifecycle policy
175    /// 
176    /// # Returns
177    /// `bool` - True if expired, false otherwise
178    #[deprecated(note="This enumeration has been deprecated due to issues, and it now only returns false")]
179    pub fn is_expired(&self) -> bool {
180        false
181    }
182}
183
184impl Clone for CacheObject {
185    fn clone(&self) -> Self {
186        CacheObject {
187            name: self.name.clone(),
188            path: self.path.clone(),
189            id: self.id,
190            created_at: self.created_at
191        }
192    }
193}