Skip to content

Commit cb27777

Browse files
committed
Move size hint check to method
1 parent 733b43a commit cb27777

File tree

1 file changed

+19
-17
lines changed

1 file changed

+19
-17
lines changed

mullvad-update/src/client/fetch.rs

+19-17
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,24 @@ pub enum SizeHint {
3535
Maximum(usize),
3636
}
3737

38+
impl SizeHint {
39+
/// This function succeeds if `actual` is allowed according to the [SizeHint]. Otherwise, it
40+
/// returns an error.
41+
fn check_size(&self, actual: usize) -> anyhow::Result<()> {
42+
match *self {
43+
SizeHint::Exact(expected) if actual != expected => {
44+
anyhow::bail!("File size mismatch: expected {expected} bytes, served {actual}")
45+
}
46+
SizeHint::Maximum(limit) if actual > limit => {
47+
anyhow::bail!(
48+
"File size exceeds limit: expected at most {limit} bytes, served {actual}"
49+
)
50+
}
51+
_ => Ok(()),
52+
}
53+
}
54+
}
55+
3856
/// Download `url` to `file`. If the file already exists, this appends to it, as long
3957
/// as the file pointed to by `url` is larger than it.
4058
///
@@ -84,7 +102,7 @@ pub async fn get_to_writer(
84102
.get(CONTENT_LENGTH)
85103
.context("Missing file size")?;
86104
let total_size: usize = total_size.to_str()?.parse().context("invalid size")?;
87-
check_size_hint(size_hint, total_size)?;
105+
size_hint.check_size(total_size)?;
88106

89107
let already_fetched_bytes = writer
90108
.stream_position()
@@ -145,22 +163,6 @@ pub async fn get_to_writer(
145163
Ok(())
146164
}
147165

148-
/// This function succeeds if `actual` is allowed according to the [SizeHint]. Otherwise, it
149-
/// returns an error.
150-
fn check_size_hint(hint: SizeHint, actual: usize) -> anyhow::Result<()> {
151-
match hint {
152-
SizeHint::Exact(expected) if actual != expected => {
153-
anyhow::bail!("File size mismatch: expected {expected} bytes, served {actual}")
154-
}
155-
SizeHint::Maximum(limit) if actual > limit => {
156-
anyhow::bail!(
157-
"File size exceeds limit: expected at most {limit} bytes, served {actual}"
158-
)
159-
}
160-
_ => Ok(()),
161-
}
162-
}
163-
164166
/// If a file exists, append to it. Otherwise, create a new file
165167
async fn create_or_append(path: impl AsRef<Path>) -> io::Result<File> {
166168
match fs::File::create_new(&path).await {

0 commit comments

Comments
 (0)