refactor: 数据块已经在内存中,直接使用 write_all

This commit is contained in:
amtoaer
2025-01-22 01:52:32 +08:00
parent 6ae87364b4
commit b888db6a61
+3 -6
View File
@@ -5,7 +5,7 @@ use anyhow::{bail, ensure, Result};
use futures::StreamExt; use futures::StreamExt;
use reqwest::Method; use reqwest::Method;
use tokio::fs::{self, File}; use tokio::fs::{self, File};
use tokio::io::{self, AsyncWriteExt}; use tokio::io::AsyncWriteExt;
use crate::bilibili::Client; use crate::bilibili::Client;
pub struct Downloader { pub struct Downloader {
@@ -26,16 +26,13 @@ impl Downloader {
} }
let mut file = File::create(path).await?; let mut file = File::create(path).await?;
let resp = self.client.request(Method::GET, url, None).send().await?; let resp = self.client.request(Method::GET, url, None).send().await?;
let expected = resp.content_length().unwrap_or_else(|| { let expected = resp.content_length().unwrap_or_default();
warn!("content length is missing, fallback to 0");
0
});
let mut received = 0u64; let mut received = 0u64;
let mut stream = resp.bytes_stream(); let mut stream = resp.bytes_stream();
while let Some(bytes) = stream.next().await { while let Some(bytes) = stream.next().await {
let bytes = bytes?; let bytes = bytes?;
received += bytes.len() as u64; received += bytes.len() as u64;
io::copy(&mut bytes.as_ref(), &mut file).await?; file.write_all(&bytes).await?;
} }
file.flush().await?; file.flush().await?;
ensure!( ensure!(