tenho seguinte código tauri v2 rust use serde::{Deserialize, Serialize}; use…
- User
tenho seguinte código tauri v2 rust
use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf};
use tauri::{AppHandle, Emitter}; use reqwest::Client; use tokio::fs as tokio_fs; use tokio::io::AsyncWriteExt; use std::time::Instant;
#[derive(Debug, Deserialize)] struct PatchEntry { file_name: String, }
#[derive(Debug, Serialize, Clone)] struct DownloadMessage { message: String, }
#[derive(Debug, Serialize, Clone)] struct DownloadInfo { current_file: usize, total_files: usize, file_name: String, downloaded_bytes: u64, total_bytes: u64, }
fn get_exe_dir() -> PathBuf { std::env::current_exe() .unwrap() .parent() .unwrap() .to_path_buf() }
// Função de leitura de patches assíncrona async fn read_patch_file(path: &Path) -> Result<Vec, Box> { let content = tokio_fs::read_to_string(path).await?; let patches: Vec = serde_json::from_str(&content)?; Ok(patches) }
async fn download_file( app_handle: &AppHandle, client: &Client, entry: PatchEntry, download_dir: &Path, current_file: usize, total_files: usize, ) -> Result<(), Box> { let url = format!("https://hil-speed.hetzner.com/{}", entry.file_name); let file_path = download_dir.join(&entry.file_name);
codelet mut response = client.get(&url).send().await?; let total_bytes = response.content_length().unwrap_or(0); let mut file = tokio_fs::OpenOptions::new() .write(true) .create(true) .open(file_path) .await?; let mut downloaded_bytes = 0; let start_time = Instant::now(); app_handle.emit("download_message", DownloadMessage { message: "Baixando".to_string() })?; while let Some(chunk) = response.chunk().await? { file.write_all(&chunk).await?; downloaded_bytes += chunk.len() as u64; let elapsed_time = Instant::now().duration_since(start_time).as_secs_f64(); let speed = if elapsed_time > 0.0 { downloaded_bytes as f64 / elapsed_time } else { 0.0 }; app_handle.emit("download_info", DownloadInfo { current_file, total_files, file_name: entry.file_name.clone(), downloaded_bytes, total_bytes, })?; app_handle.emit("download_speed", speed)?; } app_handle.emit("download_message", DownloadMessage { message: "Download concluído".to_string() })?; Ok(()) - Assistant
Sim, faz sentido usar
asyncmesmo que você esteja baixando os arquivos um por vez. A programação assíncrona é benéfica para várias razões, mesmo em um contexto de downloads sequenciais. Aqui estão algumas razões pelas quais você deve considerar manter a abordagem assíncrona: - User
altere o código para usar apenas sync em vez de async
- Assistant
- User
warning: unused import:
Duration--> src\download.rs:8:17 | 8 | use std::time::{Duration, Instant}; | ^^^^^^^^ | = note:#[warn(unused_imports)]on by defaulterror[E0599]: no method named
readfound for structreqwest::blocking::Responsein the current scope --> src\download.rs:65:41 | 65 | while let Ok(bytes_read) = response.read(&mut buffer) { | ^^^^ | ::: C:\Users\jonatas.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\std\src\io\mod.rs:756:8 | 756 | fn read(&mut self, buf: &mut [u8]) -> Result; | ---- the method is available forreqwest::blocking::Responsehere | = help: items from traits can only be used if the trait is in scope help: there is a methodread_i8with a similar name, but with different arguments --> C:\Users\jonatas.cargo\registry\src\index.crates.io-6f17d22bba15001f\byteorder-1.5.0\src\io.rs:85:5 | 85 | fn read_i8(&mut self) -> Result { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: traitReadwhich providesreadis implemented but not in scope; perhaps you want to import it | 1 + use std::io::Read; | - Assistant
- User
warning: unused import:
self--> src\download.rs:3:15 | 3 | use std::io::{self, Write}; | ^^^^ | = note:#[warn(unused_imports)]on by defaulterror[E0282]: type annotations needed for
Vec<_>--> src\download.rs:65:9 | 65 | let mut buffer = Vec::new(); | ^^^^^^^^^^ ---------- type must be known at this point | help: consider givingbufferan explicit type, where the type for type parameterTis specified | 65 | let mut buffer: Vec = Vec::new(); | ++++++++For more information about this error, try
rustc --explain E0282. warning:RagnaTales(lib) generated 1 warning error: could not compileRagnaTales(lib) due to 1 previous error; 1 warning emitted - Assistant