grammpars 0.1.0

Offline conversion between Telegram Desktop tdata, Telethon, and grammers sessions
Documentation
/// General hashing utility functions.
pub struct Utils;

impl Utils {
    /// Calculates an MD5 digest.
    pub fn md5(data: &[u8]) -> Vec<u8> {
        use md5::{Digest, Md5};
        let mut hasher = Md5::new();
        hasher.update(data);
        hasher.finalize().to_vec()
    }

    /// Calculates a SHA-1 digest.
    pub fn sha1(data: &[u8]) -> Vec<u8> {
        use sha1::{Digest, Sha1};
        let mut hasher = Sha1::new();
        hasher.update(data);
        hasher.finalize().to_vec()
    }
}

/// Selects an unused temporary path next to a destination file.
pub(crate) fn temporary_sibling(
    destination: &std::path::Path,
) -> Result<std::path::PathBuf, crate::error::OpenteleError> {
    use std::ffi::OsString;

    let parent = destination
        .parent()
        .unwrap_or_else(|| std::path::Path::new("."));
    std::fs::create_dir_all(parent)?;
    let file_name = destination.file_name().ok_or_else(|| {
        crate::error::OpenteleError::InvalidArgument("output path has no file name".into())
    })?;
    loop {
        let mut temporary_name = OsString::from(".");
        temporary_name.push(file_name);
        temporary_name.push(format!(".{:016x}.tmp", rand::random::<u64>()));
        let candidate = parent.join(temporary_name);
        if !candidate.exists() {
            return Ok(candidate);
        }
    }
}

/// Replaces a destination with a temporary file while preserving recoverability.
pub(crate) fn replace_file(
    temporary: &std::path::Path,
    destination: &std::path::Path,
) -> Result<(), crate::error::OpenteleError> {
    if !destination.exists() {
        std::fs::rename(temporary, destination)?;
        return Ok(());
    }
    let backup = temporary_sibling(destination)?.with_extension("backup");
    std::fs::rename(destination, &backup)?;
    match std::fs::rename(temporary, destination) {
        Ok(()) => {
            std::fs::remove_file(backup)?;
            Ok(())
        }
        Err(error) => {
            let _ = std::fs::rename(backup, destination);
            Err(error.into())
        }
    }
}