Move files around a bit

This commit is contained in:
Igor Katson 2024-04-30 09:39:38 +01:00
parent f2ae2f67f4
commit cd33f99352
3 changed files with 5 additions and 2 deletions

View file

@ -1,3 +1,5 @@
mod opened_file;
use std::{
fs::OpenOptions,
io::{Read, Seek, SeekFrom, Write},
@ -6,7 +8,9 @@ use std::{
use anyhow::Context;
use crate::{opened_file::OpenedFile, torrent_state::ManagedTorrentInfo};
use crate::torrent_state::ManagedTorrentInfo;
use self::opened_file::OpenedFile;
use super::{StorageFactory, TorrentStorage};

View file

@ -0,0 +1,43 @@
use std::fs::File;
use anyhow::Context;
use parking_lot::Mutex;
#[derive(Debug)]
pub(crate) struct OpenedFile {
pub file: Mutex<File>,
}
pub(crate) fn dummy_file() -> anyhow::Result<std::fs::File> {
#[cfg(target_os = "windows")]
const DEVNULL: &str = "NUL";
#[cfg(not(target_os = "windows"))]
const DEVNULL: &str = "/dev/null";
std::fs::OpenOptions::new()
.read(true)
.open(DEVNULL)
.with_context(|| format!("error opening {}", DEVNULL))
}
impl OpenedFile {
pub fn new(f: File) -> Self {
Self {
file: Mutex::new(f),
}
}
pub fn take(&self) -> anyhow::Result<File> {
let mut f = self.file.lock();
let dummy = dummy_file()?;
let f = std::mem::replace(&mut *f, dummy);
Ok(f)
}
pub fn take_clone(&self) -> anyhow::Result<Self> {
let f = self.take()?;
Ok(Self {
file: Mutex::new(f),
})
}
}