@@ -188,6 +188,52 @@ impl Cache {
188
188
Ok ( ( ) )
189
189
}
190
190
191
+ /// Removes an entry from the cache, returning its [`Metadata`].
192
+ ///
193
+ /// This will remove the entry from both the main cache database and the metadata database.
194
+ /// Please note that this will return `Error::NotFound` if either the main database *or* the
195
+ /// meta database didn't find the entry.
196
+ ///
197
+ /// # Examples
198
+ ///
199
+ /// ```rust
200
+ /// # #[tokio::main(flavor = "current_thread")]
201
+ /// # async fn main() {
202
+ /// use forceps::CacheBuilder;
203
+ ///
204
+ /// let cache = CacheBuilder::new("./cache")
205
+ /// .build()
206
+ /// .await
207
+ /// .unwrap();
208
+ ///
209
+ /// # cache.write(b"MY_KEY", b"Hello World").await.unwrap();
210
+ /// let metadata = cache.remove(b"MY_KEY").await.unwrap();
211
+ /// assert_eq!(metadata.get_size(), b"Hello World".len() as u64);
212
+ /// # }
213
+ /// ```
214
+ pub async fn remove < K : AsRef < [ u8 ] > > ( & self , key : K ) -> Result < Metadata > {
215
+ let key = key. as_ref ( ) ;
216
+
217
+ let cur_path = self . path_from_key ( key) ;
218
+ let tmp_path = crate :: tmp:: tmppath_in ( & self . path ) ;
219
+
220
+ // move then delete the file
221
+ //
222
+ // the purpose of moving then deleting is that file moves are much faster than file
223
+ // deletes. if we were to delete in place, and another thread starts reading, it could
224
+ // spell bad news.
225
+ afs:: rename ( & cur_path, & tmp_path)
226
+ . await
227
+ . map_err ( |e| match e. kind ( ) {
228
+ io:: ErrorKind :: NotFound => ForcepError :: NotFound ,
229
+ _ => ForcepError :: Io ( e) ,
230
+ } ) ?;
231
+ afs:: remove_file ( & tmp_path) . await . map_err ( ForcepError :: Io ) ?;
232
+
233
+ // remove the metadata for the entry
234
+ self . meta . remove_metadata_for ( key)
235
+ }
236
+
191
237
/// Queries the index database for metadata on the entry with the corresponding key.
192
238
///
193
239
/// This will return the metadata for the associated key. For information about what metadata
@@ -337,12 +383,13 @@ mod test {
337
383
}
338
384
339
385
#[ tokio:: test]
340
- async fn basic_write_read ( ) {
386
+ async fn write_read_remove ( ) {
341
387
let cache = default_cache ( ) . await ;
342
388
343
389
cache. write ( & b"CACHE_KEY" , & b"Hello World" ) . await . unwrap ( ) ;
344
390
let data = cache. read ( & b"CACHE_KEY" ) . await . unwrap ( ) ;
345
391
assert_eq ! ( & data, & b"Hello World" ) ;
392
+ cache. remove ( & b"CACHE_KEY" ) . await . unwrap ( ) ;
346
393
}
347
394
348
395
#[ tokio:: test]
0 commit comments