Skip to content

Commit 59d5b79

Browse files
committed
perf: Awards::parse use as_i64() and Vec::with_capacity to avoid allocs
1 parent 5ad661c commit 59d5b79

1 file changed

Lines changed: 9 additions & 16 deletions

File tree

src/utils.rs

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ use serde_json_path::{JsonPath, JsonPathExt};
2020
use std::collections::{HashMap, HashSet};
2121
use std::env;
2222
use std::io::{Read, Write};
23-
use std::str::FromStr;
2423
use std::string::ToString;
2524
use std::sync::LazyLock;
2625
use time::{macros::format_description, Duration, OffsetDateTime};
@@ -525,22 +524,16 @@ impl std::fmt::Display for Awards {
525524
impl Awards {
526525
/// Convert Reddit awards JSON to Awards struct
527526
pub fn parse(items: &Value) -> Self {
528-
let parsed = items.as_array().unwrap_or(&Vec::new()).iter().fold(Vec::new(), |mut awards, item| {
529-
let name = item["name"].as_str().unwrap_or_default().to_string();
530-
let icon_url = format_url(item["resized_icons"][0]["url"].as_str().unwrap_or_default());
531-
let description = item["description"].as_str().unwrap_or_default().to_string();
532-
let count: i64 = i64::from_str(&item["count"].to_string()).unwrap_or(1);
533-
534-
awards.push(Award {
535-
name,
536-
icon_url,
537-
description,
538-
count,
527+
let arr = items.as_array().map(|v| v.as_slice()).unwrap_or_default();
528+
let mut parsed = Vec::with_capacity(arr.len());
529+
for item in arr {
530+
parsed.push(Award {
531+
name: item["name"].as_str().unwrap_or_default().to_string(),
532+
icon_url: format_url(item["resized_icons"][0]["url"].as_str().unwrap_or_default()),
533+
description: item["description"].as_str().unwrap_or_default().to_string(),
534+
count: item["count"].as_i64().unwrap_or(1),
539535
});
540-
541-
awards
542-
});
543-
536+
}
544537
Self(parsed)
545538
}
546539
}

0 commit comments

Comments
 (0)